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(Attr.BranchProtection,
5567                                                    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         (void)CGM.getTarget().validateBranchProtection(Attr.BranchProtection,
6381                                                        BPI, DiagMsg);
6382 
6383         static const char *SignReturnAddrStr[] = {"none", "non-leaf", "all"};
6384         assert(static_cast<unsigned>(BPI.SignReturnAddr) <= 2 &&
6385                "Unexpected SignReturnAddressScopeKind");
6386         Fn->addFnAttr("sign-return-address",
6387                       SignReturnAddrStr[static_cast<int>(BPI.SignReturnAddr)]);
6388 
6389         Fn->addFnAttr("branch-target-enforcement",
6390                       BPI.BranchTargetEnforcement ? "true" : "false");
6391       }
6392     }
6393 
6394     const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
6395     if (!Attr)
6396       return;
6397 
6398     const char *Kind;
6399     switch (Attr->getInterrupt()) {
6400     case ARMInterruptAttr::Generic: Kind = ""; break;
6401     case ARMInterruptAttr::IRQ:     Kind = "IRQ"; break;
6402     case ARMInterruptAttr::FIQ:     Kind = "FIQ"; break;
6403     case ARMInterruptAttr::SWI:     Kind = "SWI"; break;
6404     case ARMInterruptAttr::ABORT:   Kind = "ABORT"; break;
6405     case ARMInterruptAttr::UNDEF:   Kind = "UNDEF"; break;
6406     }
6407 
6408     Fn->addFnAttr("interrupt", Kind);
6409 
6410     ARMABIInfo::ABIKind ABI = cast<ARMABIInfo>(getABIInfo()).getABIKind();
6411     if (ABI == ARMABIInfo::APCS)
6412       return;
6413 
6414     // AAPCS guarantees that sp will be 8-byte aligned on any public interface,
6415     // however this is not necessarily true on taking any interrupt. Instruct
6416     // the backend to perform a realignment as part of the function prologue.
6417     llvm::AttrBuilder B(Fn->getContext());
6418     B.addStackAlignmentAttr(8);
6419     Fn->addFnAttrs(B);
6420   }
6421 };
6422 
6423 class WindowsARMTargetCodeGenInfo : public ARMTargetCodeGenInfo {
6424 public:
6425   WindowsARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
6426       : ARMTargetCodeGenInfo(CGT, K) {}
6427 
6428   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
6429                            CodeGen::CodeGenModule &CGM) const override;
6430 
6431   void getDependentLibraryOption(llvm::StringRef Lib,
6432                                  llvm::SmallString<24> &Opt) const override {
6433     Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib);
6434   }
6435 
6436   void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value,
6437                                llvm::SmallString<32> &Opt) const override {
6438     Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
6439   }
6440 };
6441 
6442 void WindowsARMTargetCodeGenInfo::setTargetAttributes(
6443     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
6444   ARMTargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
6445   if (GV->isDeclaration())
6446     return;
6447   addStackProbeTargetAttributes(D, GV, CGM);
6448 }
6449 }
6450 
6451 void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
6452   if (!::classifyReturnType(getCXXABI(), FI, *this))
6453     FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), FI.isVariadic(),
6454                                             FI.getCallingConvention());
6455 
6456   for (auto &I : FI.arguments())
6457     I.info = classifyArgumentType(I.type, FI.isVariadic(),
6458                                   FI.getCallingConvention());
6459 
6460 
6461   // Always honor user-specified calling convention.
6462   if (FI.getCallingConvention() != llvm::CallingConv::C)
6463     return;
6464 
6465   llvm::CallingConv::ID cc = getRuntimeCC();
6466   if (cc != llvm::CallingConv::C)
6467     FI.setEffectiveCallingConvention(cc);
6468 }
6469 
6470 /// Return the default calling convention that LLVM will use.
6471 llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
6472   // The default calling convention that LLVM will infer.
6473   if (isEABIHF() || getTarget().getTriple().isWatchABI())
6474     return llvm::CallingConv::ARM_AAPCS_VFP;
6475   else if (isEABI())
6476     return llvm::CallingConv::ARM_AAPCS;
6477   else
6478     return llvm::CallingConv::ARM_APCS;
6479 }
6480 
6481 /// Return the calling convention that our ABI would like us to use
6482 /// as the C calling convention.
6483 llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
6484   switch (getABIKind()) {
6485   case APCS: return llvm::CallingConv::ARM_APCS;
6486   case AAPCS: return llvm::CallingConv::ARM_AAPCS;
6487   case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
6488   case AAPCS16_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
6489   }
6490   llvm_unreachable("bad ABI kind");
6491 }
6492 
6493 void ARMABIInfo::setCCs() {
6494   assert(getRuntimeCC() == llvm::CallingConv::C);
6495 
6496   // Don't muddy up the IR with a ton of explicit annotations if
6497   // they'd just match what LLVM will infer from the triple.
6498   llvm::CallingConv::ID abiCC = getABIDefaultCC();
6499   if (abiCC != getLLVMDefaultCC())
6500     RuntimeCC = abiCC;
6501 }
6502 
6503 ABIArgInfo ARMABIInfo::coerceIllegalVector(QualType Ty) const {
6504   uint64_t Size = getContext().getTypeSize(Ty);
6505   if (Size <= 32) {
6506     llvm::Type *ResType =
6507         llvm::Type::getInt32Ty(getVMContext());
6508     return ABIArgInfo::getDirect(ResType);
6509   }
6510   if (Size == 64 || Size == 128) {
6511     auto *ResType = llvm::FixedVectorType::get(
6512         llvm::Type::getInt32Ty(getVMContext()), Size / 32);
6513     return ABIArgInfo::getDirect(ResType);
6514   }
6515   return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
6516 }
6517 
6518 ABIArgInfo ARMABIInfo::classifyHomogeneousAggregate(QualType Ty,
6519                                                     const Type *Base,
6520                                                     uint64_t Members) const {
6521   assert(Base && "Base class should be set for homogeneous aggregate");
6522   // Base can be a floating-point or a vector.
6523   if (const VectorType *VT = Base->getAs<VectorType>()) {
6524     // FP16 vectors should be converted to integer vectors
6525     if (!getTarget().hasLegalHalfType() && containsAnyFP16Vectors(Ty)) {
6526       uint64_t Size = getContext().getTypeSize(VT);
6527       auto *NewVecTy = llvm::FixedVectorType::get(
6528           llvm::Type::getInt32Ty(getVMContext()), Size / 32);
6529       llvm::Type *Ty = llvm::ArrayType::get(NewVecTy, Members);
6530       return ABIArgInfo::getDirect(Ty, 0, nullptr, false);
6531     }
6532   }
6533   unsigned Align = 0;
6534   if (getABIKind() == ARMABIInfo::AAPCS ||
6535       getABIKind() == ARMABIInfo::AAPCS_VFP) {
6536     // For alignment adjusted HFAs, cap the argument alignment to 8, leave it
6537     // default otherwise.
6538     Align = getContext().getTypeUnadjustedAlignInChars(Ty).getQuantity();
6539     unsigned BaseAlign = getContext().getTypeAlignInChars(Base).getQuantity();
6540     Align = (Align > BaseAlign && Align >= 8) ? 8 : 0;
6541   }
6542   return ABIArgInfo::getDirect(nullptr, 0, nullptr, false, Align);
6543 }
6544 
6545 ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty, bool isVariadic,
6546                                             unsigned functionCallConv) const {
6547   // 6.1.2.1 The following argument types are VFP CPRCs:
6548   //   A single-precision floating-point type (including promoted
6549   //   half-precision types); A double-precision floating-point type;
6550   //   A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
6551   //   with a Base Type of a single- or double-precision floating-point type,
6552   //   64-bit containerized vectors or 128-bit containerized vectors with one
6553   //   to four Elements.
6554   // Variadic functions should always marshal to the base standard.
6555   bool IsAAPCS_VFP =
6556       !isVariadic && isEffectivelyAAPCS_VFP(functionCallConv, /* AAPCS16 */ false);
6557 
6558   Ty = useFirstFieldIfTransparentUnion(Ty);
6559 
6560   // Handle illegal vector types here.
6561   if (isIllegalVectorType(Ty))
6562     return coerceIllegalVector(Ty);
6563 
6564   if (!isAggregateTypeForABI(Ty)) {
6565     // Treat an enum type as its underlying type.
6566     if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
6567       Ty = EnumTy->getDecl()->getIntegerType();
6568     }
6569 
6570     if (const auto *EIT = Ty->getAs<BitIntType>())
6571       if (EIT->getNumBits() > 64)
6572         return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
6573 
6574     return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
6575                                               : ABIArgInfo::getDirect());
6576   }
6577 
6578   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
6579     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
6580   }
6581 
6582   // Ignore empty records.
6583   if (isEmptyRecord(getContext(), Ty, true))
6584     return ABIArgInfo::getIgnore();
6585 
6586   if (IsAAPCS_VFP) {
6587     // Homogeneous Aggregates need to be expanded when we can fit the aggregate
6588     // into VFP registers.
6589     const Type *Base = nullptr;
6590     uint64_t Members = 0;
6591     if (isHomogeneousAggregate(Ty, Base, Members))
6592       return classifyHomogeneousAggregate(Ty, Base, Members);
6593   } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
6594     // WatchOS does have homogeneous aggregates. Note that we intentionally use
6595     // this convention even for a variadic function: the backend will use GPRs
6596     // if needed.
6597     const Type *Base = nullptr;
6598     uint64_t Members = 0;
6599     if (isHomogeneousAggregate(Ty, Base, Members)) {
6600       assert(Base && Members <= 4 && "unexpected homogeneous aggregate");
6601       llvm::Type *Ty =
6602         llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members);
6603       return ABIArgInfo::getDirect(Ty, 0, nullptr, false);
6604     }
6605   }
6606 
6607   if (getABIKind() == ARMABIInfo::AAPCS16_VFP &&
6608       getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(16)) {
6609     // WatchOS is adopting the 64-bit AAPCS rule on composite types: if they're
6610     // bigger than 128-bits, they get placed in space allocated by the caller,
6611     // and a pointer is passed.
6612     return ABIArgInfo::getIndirect(
6613         CharUnits::fromQuantity(getContext().getTypeAlign(Ty) / 8), false);
6614   }
6615 
6616   // Support byval for ARM.
6617   // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
6618   // most 8-byte. We realign the indirect argument if type alignment is bigger
6619   // than ABI alignment.
6620   uint64_t ABIAlign = 4;
6621   uint64_t TyAlign;
6622   if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
6623       getABIKind() == ARMABIInfo::AAPCS) {
6624     TyAlign = getContext().getTypeUnadjustedAlignInChars(Ty).getQuantity();
6625     ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
6626   } else {
6627     TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity();
6628   }
6629   if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
6630     assert(getABIKind() != ARMABIInfo::AAPCS16_VFP && "unexpected byval");
6631     return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
6632                                    /*ByVal=*/true,
6633                                    /*Realign=*/TyAlign > ABIAlign);
6634   }
6635 
6636   // On RenderScript, coerce Aggregates <= 64 bytes to an integer array of
6637   // same size and alignment.
6638   if (getTarget().isRenderScriptTarget()) {
6639     return coerceToIntArray(Ty, getContext(), getVMContext());
6640   }
6641 
6642   // Otherwise, pass by coercing to a structure of the appropriate size.
6643   llvm::Type* ElemTy;
6644   unsigned SizeRegs;
6645   // FIXME: Try to match the types of the arguments more accurately where
6646   // we can.
6647   if (TyAlign <= 4) {
6648     ElemTy = llvm::Type::getInt32Ty(getVMContext());
6649     SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
6650   } else {
6651     ElemTy = llvm::Type::getInt64Ty(getVMContext());
6652     SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
6653   }
6654 
6655   return ABIArgInfo::getDirect(llvm::ArrayType::get(ElemTy, SizeRegs));
6656 }
6657 
6658 static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
6659                               llvm::LLVMContext &VMContext) {
6660   // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
6661   // is called integer-like if its size is less than or equal to one word, and
6662   // the offset of each of its addressable sub-fields is zero.
6663 
6664   uint64_t Size = Context.getTypeSize(Ty);
6665 
6666   // Check that the type fits in a word.
6667   if (Size > 32)
6668     return false;
6669 
6670   // FIXME: Handle vector types!
6671   if (Ty->isVectorType())
6672     return false;
6673 
6674   // Float types are never treated as "integer like".
6675   if (Ty->isRealFloatingType())
6676     return false;
6677 
6678   // If this is a builtin or pointer type then it is ok.
6679   if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
6680     return true;
6681 
6682   // Small complex integer types are "integer like".
6683   if (const ComplexType *CT = Ty->getAs<ComplexType>())
6684     return isIntegerLikeType(CT->getElementType(), Context, VMContext);
6685 
6686   // Single element and zero sized arrays should be allowed, by the definition
6687   // above, but they are not.
6688 
6689   // Otherwise, it must be a record type.
6690   const RecordType *RT = Ty->getAs<RecordType>();
6691   if (!RT) return false;
6692 
6693   // Ignore records with flexible arrays.
6694   const RecordDecl *RD = RT->getDecl();
6695   if (RD->hasFlexibleArrayMember())
6696     return false;
6697 
6698   // Check that all sub-fields are at offset 0, and are themselves "integer
6699   // like".
6700   const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
6701 
6702   bool HadField = false;
6703   unsigned idx = 0;
6704   for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
6705        i != e; ++i, ++idx) {
6706     const FieldDecl *FD = *i;
6707 
6708     // Bit-fields are not addressable, we only need to verify they are "integer
6709     // like". We still have to disallow a subsequent non-bitfield, for example:
6710     //   struct { int : 0; int x }
6711     // is non-integer like according to gcc.
6712     if (FD->isBitField()) {
6713       if (!RD->isUnion())
6714         HadField = true;
6715 
6716       if (!isIntegerLikeType(FD->getType(), Context, VMContext))
6717         return false;
6718 
6719       continue;
6720     }
6721 
6722     // Check if this field is at offset 0.
6723     if (Layout.getFieldOffset(idx) != 0)
6724       return false;
6725 
6726     if (!isIntegerLikeType(FD->getType(), Context, VMContext))
6727       return false;
6728 
6729     // Only allow at most one field in a structure. This doesn't match the
6730     // wording above, but follows gcc in situations with a field following an
6731     // empty structure.
6732     if (!RD->isUnion()) {
6733       if (HadField)
6734         return false;
6735 
6736       HadField = true;
6737     }
6738   }
6739 
6740   return true;
6741 }
6742 
6743 ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy, bool isVariadic,
6744                                           unsigned functionCallConv) const {
6745 
6746   // Variadic functions should always marshal to the base standard.
6747   bool IsAAPCS_VFP =
6748       !isVariadic && isEffectivelyAAPCS_VFP(functionCallConv, /* AAPCS16 */ true);
6749 
6750   if (RetTy->isVoidType())
6751     return ABIArgInfo::getIgnore();
6752 
6753   if (const VectorType *VT = RetTy->getAs<VectorType>()) {
6754     // Large vector types should be returned via memory.
6755     if (getContext().getTypeSize(RetTy) > 128)
6756       return getNaturalAlignIndirect(RetTy);
6757     // TODO: FP16/BF16 vectors should be converted to integer vectors
6758     // This check is similar  to isIllegalVectorType - refactor?
6759     if ((!getTarget().hasLegalHalfType() &&
6760         (VT->getElementType()->isFloat16Type() ||
6761          VT->getElementType()->isHalfType())) ||
6762         (IsFloatABISoftFP &&
6763          VT->getElementType()->isBFloat16Type()))
6764       return coerceIllegalVector(RetTy);
6765   }
6766 
6767   if (!isAggregateTypeForABI(RetTy)) {
6768     // Treat an enum type as its underlying type.
6769     if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6770       RetTy = EnumTy->getDecl()->getIntegerType();
6771 
6772     if (const auto *EIT = RetTy->getAs<BitIntType>())
6773       if (EIT->getNumBits() > 64)
6774         return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
6775 
6776     return isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
6777                                                 : ABIArgInfo::getDirect();
6778   }
6779 
6780   // Are we following APCS?
6781   if (getABIKind() == APCS) {
6782     if (isEmptyRecord(getContext(), RetTy, false))
6783       return ABIArgInfo::getIgnore();
6784 
6785     // Complex types are all returned as packed integers.
6786     //
6787     // FIXME: Consider using 2 x vector types if the back end handles them
6788     // correctly.
6789     if (RetTy->isAnyComplexType())
6790       return ABIArgInfo::getDirect(llvm::IntegerType::get(
6791           getVMContext(), getContext().getTypeSize(RetTy)));
6792 
6793     // Integer like structures are returned in r0.
6794     if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
6795       // Return in the smallest viable integer type.
6796       uint64_t Size = getContext().getTypeSize(RetTy);
6797       if (Size <= 8)
6798         return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6799       if (Size <= 16)
6800         return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6801       return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6802     }
6803 
6804     // Otherwise return in memory.
6805     return getNaturalAlignIndirect(RetTy);
6806   }
6807 
6808   // Otherwise this is an AAPCS variant.
6809 
6810   if (isEmptyRecord(getContext(), RetTy, true))
6811     return ABIArgInfo::getIgnore();
6812 
6813   // Check for homogeneous aggregates with AAPCS-VFP.
6814   if (IsAAPCS_VFP) {
6815     const Type *Base = nullptr;
6816     uint64_t Members = 0;
6817     if (isHomogeneousAggregate(RetTy, Base, Members))
6818       return classifyHomogeneousAggregate(RetTy, Base, Members);
6819   }
6820 
6821   // Aggregates <= 4 bytes are returned in r0; other aggregates
6822   // are returned indirectly.
6823   uint64_t Size = getContext().getTypeSize(RetTy);
6824   if (Size <= 32) {
6825     // On RenderScript, coerce Aggregates <= 4 bytes to an integer array of
6826     // same size and alignment.
6827     if (getTarget().isRenderScriptTarget()) {
6828       return coerceToIntArray(RetTy, getContext(), getVMContext());
6829     }
6830     if (getDataLayout().isBigEndian())
6831       // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4)
6832       return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6833 
6834     // Return in the smallest viable integer type.
6835     if (Size <= 8)
6836       return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6837     if (Size <= 16)
6838       return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6839     return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6840   } else if (Size <= 128 && getABIKind() == AAPCS16_VFP) {
6841     llvm::Type *Int32Ty = llvm::Type::getInt32Ty(getVMContext());
6842     llvm::Type *CoerceTy =
6843         llvm::ArrayType::get(Int32Ty, llvm::alignTo(Size, 32) / 32);
6844     return ABIArgInfo::getDirect(CoerceTy);
6845   }
6846 
6847   return getNaturalAlignIndirect(RetTy);
6848 }
6849 
6850 /// isIllegalVector - check whether Ty is an illegal vector type.
6851 bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
6852   if (const VectorType *VT = Ty->getAs<VectorType> ()) {
6853     // On targets that don't support half, fp16 or bfloat, they are expanded
6854     // into float, and we don't want the ABI to depend on whether or not they
6855     // are supported in hardware. Thus return false to coerce vectors of these
6856     // types into integer vectors.
6857     // We do not depend on hasLegalHalfType for bfloat as it is a
6858     // separate IR type.
6859     if ((!getTarget().hasLegalHalfType() &&
6860         (VT->getElementType()->isFloat16Type() ||
6861          VT->getElementType()->isHalfType())) ||
6862         (IsFloatABISoftFP &&
6863          VT->getElementType()->isBFloat16Type()))
6864       return true;
6865     if (isAndroid()) {
6866       // Android shipped using Clang 3.1, which supported a slightly different
6867       // vector ABI. The primary differences were that 3-element vector types
6868       // were legal, and so were sub 32-bit vectors (i.e. <2 x i8>). This path
6869       // accepts that legacy behavior for Android only.
6870       // Check whether VT is legal.
6871       unsigned NumElements = VT->getNumElements();
6872       // NumElements should be power of 2 or equal to 3.
6873       if (!llvm::isPowerOf2_32(NumElements) && NumElements != 3)
6874         return true;
6875     } else {
6876       // Check whether VT is legal.
6877       unsigned NumElements = VT->getNumElements();
6878       uint64_t Size = getContext().getTypeSize(VT);
6879       // NumElements should be power of 2.
6880       if (!llvm::isPowerOf2_32(NumElements))
6881         return true;
6882       // Size should be greater than 32 bits.
6883       return Size <= 32;
6884     }
6885   }
6886   return false;
6887 }
6888 
6889 /// Return true if a type contains any 16-bit floating point vectors
6890 bool ARMABIInfo::containsAnyFP16Vectors(QualType Ty) const {
6891   if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
6892     uint64_t NElements = AT->getSize().getZExtValue();
6893     if (NElements == 0)
6894       return false;
6895     return containsAnyFP16Vectors(AT->getElementType());
6896   } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
6897     const RecordDecl *RD = RT->getDecl();
6898 
6899     // If this is a C++ record, check the bases first.
6900     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
6901       if (llvm::any_of(CXXRD->bases(), [this](const CXXBaseSpecifier &B) {
6902             return containsAnyFP16Vectors(B.getType());
6903           }))
6904         return true;
6905 
6906     if (llvm::any_of(RD->fields(), [this](FieldDecl *FD) {
6907           return FD && containsAnyFP16Vectors(FD->getType());
6908         }))
6909       return true;
6910 
6911     return false;
6912   } else {
6913     if (const VectorType *VT = Ty->getAs<VectorType>())
6914       return (VT->getElementType()->isFloat16Type() ||
6915               VT->getElementType()->isBFloat16Type() ||
6916               VT->getElementType()->isHalfType());
6917     return false;
6918   }
6919 }
6920 
6921 bool ARMABIInfo::isLegalVectorTypeForSwift(CharUnits vectorSize,
6922                                            llvm::Type *eltTy,
6923                                            unsigned numElts) const {
6924   if (!llvm::isPowerOf2_32(numElts))
6925     return false;
6926   unsigned size = getDataLayout().getTypeStoreSizeInBits(eltTy);
6927   if (size > 64)
6928     return false;
6929   if (vectorSize.getQuantity() != 8 &&
6930       (vectorSize.getQuantity() != 16 || numElts == 1))
6931     return false;
6932   return true;
6933 }
6934 
6935 bool ARMABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
6936   // Homogeneous aggregates for AAPCS-VFP must have base types of float,
6937   // double, or 64-bit or 128-bit vectors.
6938   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
6939     if (BT->getKind() == BuiltinType::Float ||
6940         BT->getKind() == BuiltinType::Double ||
6941         BT->getKind() == BuiltinType::LongDouble)
6942       return true;
6943   } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
6944     unsigned VecSize = getContext().getTypeSize(VT);
6945     if (VecSize == 64 || VecSize == 128)
6946       return true;
6947   }
6948   return false;
6949 }
6950 
6951 bool ARMABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
6952                                                    uint64_t Members) const {
6953   return Members <= 4;
6954 }
6955 
6956 bool ARMABIInfo::isEffectivelyAAPCS_VFP(unsigned callConvention,
6957                                         bool acceptHalf) const {
6958   // Give precedence to user-specified calling conventions.
6959   if (callConvention != llvm::CallingConv::C)
6960     return (callConvention == llvm::CallingConv::ARM_AAPCS_VFP);
6961   else
6962     return (getABIKind() == AAPCS_VFP) ||
6963            (acceptHalf && (getABIKind() == AAPCS16_VFP));
6964 }
6965 
6966 Address ARMABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6967                               QualType Ty) const {
6968   CharUnits SlotSize = CharUnits::fromQuantity(4);
6969 
6970   // Empty records are ignored for parameter passing purposes.
6971   if (isEmptyRecord(getContext(), Ty, true)) {
6972     Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize);
6973     Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
6974     return Addr;
6975   }
6976 
6977   CharUnits TySize = getContext().getTypeSizeInChars(Ty);
6978   CharUnits TyAlignForABI = getContext().getTypeUnadjustedAlignInChars(Ty);
6979 
6980   // Use indirect if size of the illegal vector is bigger than 16 bytes.
6981   bool IsIndirect = false;
6982   const Type *Base = nullptr;
6983   uint64_t Members = 0;
6984   if (TySize > CharUnits::fromQuantity(16) && isIllegalVectorType(Ty)) {
6985     IsIndirect = true;
6986 
6987   // ARMv7k passes structs bigger than 16 bytes indirectly, in space
6988   // allocated by the caller.
6989   } else if (TySize > CharUnits::fromQuantity(16) &&
6990              getABIKind() == ARMABIInfo::AAPCS16_VFP &&
6991              !isHomogeneousAggregate(Ty, Base, Members)) {
6992     IsIndirect = true;
6993 
6994   // Otherwise, bound the type's ABI alignment.
6995   // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
6996   // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
6997   // Our callers should be prepared to handle an under-aligned address.
6998   } else if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
6999              getABIKind() == ARMABIInfo::AAPCS) {
7000     TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
7001     TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(8));
7002   } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
7003     // ARMv7k allows type alignment up to 16 bytes.
7004     TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
7005     TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(16));
7006   } else {
7007     TyAlignForABI = CharUnits::fromQuantity(4);
7008   }
7009 
7010   TypeInfoChars TyInfo(TySize, TyAlignForABI, AlignRequirementKind::None);
7011   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TyInfo,
7012                           SlotSize, /*AllowHigherAlign*/ true);
7013 }
7014 
7015 //===----------------------------------------------------------------------===//
7016 // NVPTX ABI Implementation
7017 //===----------------------------------------------------------------------===//
7018 
7019 namespace {
7020 
7021 class NVPTXTargetCodeGenInfo;
7022 
7023 class NVPTXABIInfo : public ABIInfo {
7024   NVPTXTargetCodeGenInfo &CGInfo;
7025 
7026 public:
7027   NVPTXABIInfo(CodeGenTypes &CGT, NVPTXTargetCodeGenInfo &Info)
7028       : ABIInfo(CGT), CGInfo(Info) {}
7029 
7030   ABIArgInfo classifyReturnType(QualType RetTy) const;
7031   ABIArgInfo classifyArgumentType(QualType Ty) const;
7032 
7033   void computeInfo(CGFunctionInfo &FI) const override;
7034   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7035                     QualType Ty) const override;
7036   bool isUnsupportedType(QualType T) const;
7037   ABIArgInfo coerceToIntArrayWithLimit(QualType Ty, unsigned MaxSize) const;
7038 };
7039 
7040 class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
7041 public:
7042   NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
7043       : TargetCodeGenInfo(std::make_unique<NVPTXABIInfo>(CGT, *this)) {}
7044 
7045   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
7046                            CodeGen::CodeGenModule &M) const override;
7047   bool shouldEmitStaticExternCAliases() const override;
7048 
7049   llvm::Type *getCUDADeviceBuiltinSurfaceDeviceType() const override {
7050     // On the device side, surface reference is represented as an object handle
7051     // in 64-bit integer.
7052     return llvm::Type::getInt64Ty(getABIInfo().getVMContext());
7053   }
7054 
7055   llvm::Type *getCUDADeviceBuiltinTextureDeviceType() const override {
7056     // On the device side, texture reference is represented as an object handle
7057     // in 64-bit integer.
7058     return llvm::Type::getInt64Ty(getABIInfo().getVMContext());
7059   }
7060 
7061   bool emitCUDADeviceBuiltinSurfaceDeviceCopy(CodeGenFunction &CGF, LValue Dst,
7062                                               LValue Src) const override {
7063     emitBuiltinSurfTexDeviceCopy(CGF, Dst, Src);
7064     return true;
7065   }
7066 
7067   bool emitCUDADeviceBuiltinTextureDeviceCopy(CodeGenFunction &CGF, LValue Dst,
7068                                               LValue Src) const override {
7069     emitBuiltinSurfTexDeviceCopy(CGF, Dst, Src);
7070     return true;
7071   }
7072 
7073 private:
7074   // Adds a NamedMDNode with GV, Name, and Operand as operands, and adds the
7075   // resulting MDNode to the nvvm.annotations MDNode.
7076   static void addNVVMMetadata(llvm::GlobalValue *GV, StringRef Name,
7077                               int Operand);
7078 
7079   static void emitBuiltinSurfTexDeviceCopy(CodeGenFunction &CGF, LValue Dst,
7080                                            LValue Src) {
7081     llvm::Value *Handle = nullptr;
7082     llvm::Constant *C =
7083         llvm::dyn_cast<llvm::Constant>(Src.getAddress(CGF).getPointer());
7084     // Lookup `addrspacecast` through the constant pointer if any.
7085     if (auto *ASC = llvm::dyn_cast_or_null<llvm::AddrSpaceCastOperator>(C))
7086       C = llvm::cast<llvm::Constant>(ASC->getPointerOperand());
7087     if (auto *GV = llvm::dyn_cast_or_null<llvm::GlobalVariable>(C)) {
7088       // Load the handle from the specific global variable using
7089       // `nvvm.texsurf.handle.internal` intrinsic.
7090       Handle = CGF.EmitRuntimeCall(
7091           CGF.CGM.getIntrinsic(llvm::Intrinsic::nvvm_texsurf_handle_internal,
7092                                {GV->getType()}),
7093           {GV}, "texsurf_handle");
7094     } else
7095       Handle = CGF.EmitLoadOfScalar(Src, SourceLocation());
7096     CGF.EmitStoreOfScalar(Handle, Dst);
7097   }
7098 };
7099 
7100 /// Checks if the type is unsupported directly by the current target.
7101 bool NVPTXABIInfo::isUnsupportedType(QualType T) const {
7102   ASTContext &Context = getContext();
7103   if (!Context.getTargetInfo().hasFloat16Type() && T->isFloat16Type())
7104     return true;
7105   if (!Context.getTargetInfo().hasFloat128Type() &&
7106       (T->isFloat128Type() ||
7107        (T->isRealFloatingType() && Context.getTypeSize(T) == 128)))
7108     return true;
7109   if (const auto *EIT = T->getAs<BitIntType>())
7110     return EIT->getNumBits() >
7111            (Context.getTargetInfo().hasInt128Type() ? 128U : 64U);
7112   if (!Context.getTargetInfo().hasInt128Type() && T->isIntegerType() &&
7113       Context.getTypeSize(T) > 64U)
7114     return true;
7115   if (const auto *AT = T->getAsArrayTypeUnsafe())
7116     return isUnsupportedType(AT->getElementType());
7117   const auto *RT = T->getAs<RecordType>();
7118   if (!RT)
7119     return false;
7120   const RecordDecl *RD = RT->getDecl();
7121 
7122   // If this is a C++ record, check the bases first.
7123   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
7124     for (const CXXBaseSpecifier &I : CXXRD->bases())
7125       if (isUnsupportedType(I.getType()))
7126         return true;
7127 
7128   for (const FieldDecl *I : RD->fields())
7129     if (isUnsupportedType(I->getType()))
7130       return true;
7131   return false;
7132 }
7133 
7134 /// Coerce the given type into an array with maximum allowed size of elements.
7135 ABIArgInfo NVPTXABIInfo::coerceToIntArrayWithLimit(QualType Ty,
7136                                                    unsigned MaxSize) const {
7137   // Alignment and Size are measured in bits.
7138   const uint64_t Size = getContext().getTypeSize(Ty);
7139   const uint64_t Alignment = getContext().getTypeAlign(Ty);
7140   const unsigned Div = std::min<unsigned>(MaxSize, Alignment);
7141   llvm::Type *IntType = llvm::Type::getIntNTy(getVMContext(), Div);
7142   const uint64_t NumElements = (Size + Div - 1) / Div;
7143   return ABIArgInfo::getDirect(llvm::ArrayType::get(IntType, NumElements));
7144 }
7145 
7146 ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
7147   if (RetTy->isVoidType())
7148     return ABIArgInfo::getIgnore();
7149 
7150   if (getContext().getLangOpts().OpenMP &&
7151       getContext().getLangOpts().OpenMPIsDevice && isUnsupportedType(RetTy))
7152     return coerceToIntArrayWithLimit(RetTy, 64);
7153 
7154   // note: this is different from default ABI
7155   if (!RetTy->isScalarType())
7156     return ABIArgInfo::getDirect();
7157 
7158   // Treat an enum type as its underlying type.
7159   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
7160     RetTy = EnumTy->getDecl()->getIntegerType();
7161 
7162   return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
7163                                                : ABIArgInfo::getDirect());
7164 }
7165 
7166 ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
7167   // Treat an enum type as its underlying type.
7168   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7169     Ty = EnumTy->getDecl()->getIntegerType();
7170 
7171   // Return aggregates type as indirect by value
7172   if (isAggregateTypeForABI(Ty)) {
7173     // Under CUDA device compilation, tex/surf builtin types are replaced with
7174     // object types and passed directly.
7175     if (getContext().getLangOpts().CUDAIsDevice) {
7176       if (Ty->isCUDADeviceBuiltinSurfaceType())
7177         return ABIArgInfo::getDirect(
7178             CGInfo.getCUDADeviceBuiltinSurfaceDeviceType());
7179       if (Ty->isCUDADeviceBuiltinTextureType())
7180         return ABIArgInfo::getDirect(
7181             CGInfo.getCUDADeviceBuiltinTextureDeviceType());
7182     }
7183     return getNaturalAlignIndirect(Ty, /* byval */ true);
7184   }
7185 
7186   if (const auto *EIT = Ty->getAs<BitIntType>()) {
7187     if ((EIT->getNumBits() > 128) ||
7188         (!getContext().getTargetInfo().hasInt128Type() &&
7189          EIT->getNumBits() > 64))
7190       return getNaturalAlignIndirect(Ty, /* byval */ true);
7191   }
7192 
7193   return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
7194                                             : ABIArgInfo::getDirect());
7195 }
7196 
7197 void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
7198   if (!getCXXABI().classifyReturnType(FI))
7199     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7200   for (auto &I : FI.arguments())
7201     I.info = classifyArgumentType(I.type);
7202 
7203   // Always honor user-specified calling convention.
7204   if (FI.getCallingConvention() != llvm::CallingConv::C)
7205     return;
7206 
7207   FI.setEffectiveCallingConvention(getRuntimeCC());
7208 }
7209 
7210 Address NVPTXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7211                                 QualType Ty) const {
7212   llvm_unreachable("NVPTX does not support varargs");
7213 }
7214 
7215 void NVPTXTargetCodeGenInfo::setTargetAttributes(
7216     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
7217   if (GV->isDeclaration())
7218     return;
7219   const VarDecl *VD = dyn_cast_or_null<VarDecl>(D);
7220   if (VD) {
7221     if (M.getLangOpts().CUDA) {
7222       if (VD->getType()->isCUDADeviceBuiltinSurfaceType())
7223         addNVVMMetadata(GV, "surface", 1);
7224       else if (VD->getType()->isCUDADeviceBuiltinTextureType())
7225         addNVVMMetadata(GV, "texture", 1);
7226       return;
7227     }
7228   }
7229 
7230   const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
7231   if (!FD) return;
7232 
7233   llvm::Function *F = cast<llvm::Function>(GV);
7234 
7235   // Perform special handling in OpenCL mode
7236   if (M.getLangOpts().OpenCL) {
7237     // Use OpenCL function attributes to check for kernel functions
7238     // By default, all functions are device functions
7239     if (FD->hasAttr<OpenCLKernelAttr>()) {
7240       // OpenCL __kernel functions get kernel metadata
7241       // Create !{<func-ref>, metadata !"kernel", i32 1} node
7242       addNVVMMetadata(F, "kernel", 1);
7243       // And kernel functions are not subject to inlining
7244       F->addFnAttr(llvm::Attribute::NoInline);
7245     }
7246   }
7247 
7248   // Perform special handling in CUDA mode.
7249   if (M.getLangOpts().CUDA) {
7250     // CUDA __global__ functions get a kernel metadata entry.  Since
7251     // __global__ functions cannot be called from the device, we do not
7252     // need to set the noinline attribute.
7253     if (FD->hasAttr<CUDAGlobalAttr>()) {
7254       // Create !{<func-ref>, metadata !"kernel", i32 1} node
7255       addNVVMMetadata(F, "kernel", 1);
7256     }
7257     if (CUDALaunchBoundsAttr *Attr = FD->getAttr<CUDALaunchBoundsAttr>()) {
7258       // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node
7259       llvm::APSInt MaxThreads(32);
7260       MaxThreads = Attr->getMaxThreads()->EvaluateKnownConstInt(M.getContext());
7261       if (MaxThreads > 0)
7262         addNVVMMetadata(F, "maxntidx", MaxThreads.getExtValue());
7263 
7264       // min blocks is an optional argument for CUDALaunchBoundsAttr. If it was
7265       // not specified in __launch_bounds__ or if the user specified a 0 value,
7266       // we don't have to add a PTX directive.
7267       if (Attr->getMinBlocks()) {
7268         llvm::APSInt MinBlocks(32);
7269         MinBlocks = Attr->getMinBlocks()->EvaluateKnownConstInt(M.getContext());
7270         if (MinBlocks > 0)
7271           // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node
7272           addNVVMMetadata(F, "minctasm", MinBlocks.getExtValue());
7273       }
7274     }
7275   }
7276 }
7277 
7278 void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::GlobalValue *GV,
7279                                              StringRef Name, int Operand) {
7280   llvm::Module *M = GV->getParent();
7281   llvm::LLVMContext &Ctx = M->getContext();
7282 
7283   // Get "nvvm.annotations" metadata node
7284   llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
7285 
7286   llvm::Metadata *MDVals[] = {
7287       llvm::ConstantAsMetadata::get(GV), llvm::MDString::get(Ctx, Name),
7288       llvm::ConstantAsMetadata::get(
7289           llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand))};
7290   // Append metadata to nvvm.annotations
7291   MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
7292 }
7293 
7294 bool NVPTXTargetCodeGenInfo::shouldEmitStaticExternCAliases() const {
7295   return false;
7296 }
7297 }
7298 
7299 //===----------------------------------------------------------------------===//
7300 // SystemZ ABI Implementation
7301 //===----------------------------------------------------------------------===//
7302 
7303 namespace {
7304 
7305 class SystemZABIInfo : public SwiftABIInfo {
7306   bool HasVector;
7307   bool IsSoftFloatABI;
7308 
7309 public:
7310   SystemZABIInfo(CodeGenTypes &CGT, bool HV, bool SF)
7311     : SwiftABIInfo(CGT), HasVector(HV), IsSoftFloatABI(SF) {}
7312 
7313   bool isPromotableIntegerTypeForABI(QualType Ty) const;
7314   bool isCompoundType(QualType Ty) const;
7315   bool isVectorArgumentType(QualType Ty) const;
7316   bool isFPArgumentType(QualType Ty) const;
7317   QualType GetSingleElementType(QualType Ty) const;
7318 
7319   ABIArgInfo classifyReturnType(QualType RetTy) const;
7320   ABIArgInfo classifyArgumentType(QualType ArgTy) const;
7321 
7322   void computeInfo(CGFunctionInfo &FI) const override {
7323     if (!getCXXABI().classifyReturnType(FI))
7324       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7325     for (auto &I : FI.arguments())
7326       I.info = classifyArgumentType(I.type);
7327   }
7328 
7329   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7330                     QualType Ty) const override;
7331 
7332   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
7333                                     bool asReturnValue) const override {
7334     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
7335   }
7336   bool isSwiftErrorInRegister() const override {
7337     return false;
7338   }
7339 };
7340 
7341 class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
7342 public:
7343   SystemZTargetCodeGenInfo(CodeGenTypes &CGT, bool HasVector, bool SoftFloatABI)
7344       : TargetCodeGenInfo(
7345             std::make_unique<SystemZABIInfo>(CGT, HasVector, SoftFloatABI)) {}
7346 
7347   llvm::Value *testFPKind(llvm::Value *V, unsigned BuiltinID,
7348                           CGBuilderTy &Builder,
7349                           CodeGenModule &CGM) const override {
7350     assert(V->getType()->isFloatingPointTy() && "V should have an FP type.");
7351     // Only use TDC in constrained FP mode.
7352     if (!Builder.getIsFPConstrained())
7353       return nullptr;
7354 
7355     llvm::Type *Ty = V->getType();
7356     if (Ty->isFloatTy() || Ty->isDoubleTy() || Ty->isFP128Ty()) {
7357       llvm::Module &M = CGM.getModule();
7358       auto &Ctx = M.getContext();
7359       llvm::Function *TDCFunc =
7360           llvm::Intrinsic::getDeclaration(&M, llvm::Intrinsic::s390_tdc, Ty);
7361       unsigned TDCBits = 0;
7362       switch (BuiltinID) {
7363       case Builtin::BI__builtin_isnan:
7364         TDCBits = 0xf;
7365         break;
7366       case Builtin::BIfinite:
7367       case Builtin::BI__finite:
7368       case Builtin::BIfinitef:
7369       case Builtin::BI__finitef:
7370       case Builtin::BIfinitel:
7371       case Builtin::BI__finitel:
7372       case Builtin::BI__builtin_isfinite:
7373         TDCBits = 0xfc0;
7374         break;
7375       case Builtin::BI__builtin_isinf:
7376         TDCBits = 0x30;
7377         break;
7378       default:
7379         break;
7380       }
7381       if (TDCBits)
7382         return Builder.CreateCall(
7383             TDCFunc,
7384             {V, llvm::ConstantInt::get(llvm::Type::getInt64Ty(Ctx), TDCBits)});
7385     }
7386     return nullptr;
7387   }
7388 };
7389 }
7390 
7391 bool SystemZABIInfo::isPromotableIntegerTypeForABI(QualType Ty) const {
7392   // Treat an enum type as its underlying type.
7393   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7394     Ty = EnumTy->getDecl()->getIntegerType();
7395 
7396   // Promotable integer types are required to be promoted by the ABI.
7397   if (ABIInfo::isPromotableIntegerTypeForABI(Ty))
7398     return true;
7399 
7400   if (const auto *EIT = Ty->getAs<BitIntType>())
7401     if (EIT->getNumBits() < 64)
7402       return true;
7403 
7404   // 32-bit values must also be promoted.
7405   if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
7406     switch (BT->getKind()) {
7407     case BuiltinType::Int:
7408     case BuiltinType::UInt:
7409       return true;
7410     default:
7411       return false;
7412     }
7413   return false;
7414 }
7415 
7416 bool SystemZABIInfo::isCompoundType(QualType Ty) const {
7417   return (Ty->isAnyComplexType() ||
7418           Ty->isVectorType() ||
7419           isAggregateTypeForABI(Ty));
7420 }
7421 
7422 bool SystemZABIInfo::isVectorArgumentType(QualType Ty) const {
7423   return (HasVector &&
7424           Ty->isVectorType() &&
7425           getContext().getTypeSize(Ty) <= 128);
7426 }
7427 
7428 bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
7429   if (IsSoftFloatABI)
7430     return false;
7431 
7432   if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
7433     switch (BT->getKind()) {
7434     case BuiltinType::Float:
7435     case BuiltinType::Double:
7436       return true;
7437     default:
7438       return false;
7439     }
7440 
7441   return false;
7442 }
7443 
7444 QualType SystemZABIInfo::GetSingleElementType(QualType Ty) const {
7445   const RecordType *RT = Ty->getAs<RecordType>();
7446 
7447   if (RT && RT->isStructureOrClassType()) {
7448     const RecordDecl *RD = RT->getDecl();
7449     QualType Found;
7450 
7451     // If this is a C++ record, check the bases first.
7452     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
7453       for (const auto &I : CXXRD->bases()) {
7454         QualType Base = I.getType();
7455 
7456         // Empty bases don't affect things either way.
7457         if (isEmptyRecord(getContext(), Base, true))
7458           continue;
7459 
7460         if (!Found.isNull())
7461           return Ty;
7462         Found = GetSingleElementType(Base);
7463       }
7464 
7465     // Check the fields.
7466     for (const auto *FD : RD->fields()) {
7467       // For compatibility with GCC, ignore empty bitfields in C++ mode.
7468       // Unlike isSingleElementStruct(), empty structure and array fields
7469       // do count.  So do anonymous bitfields that aren't zero-sized.
7470       if (getContext().getLangOpts().CPlusPlus &&
7471           FD->isZeroLengthBitField(getContext()))
7472         continue;
7473       // Like isSingleElementStruct(), ignore C++20 empty data members.
7474       if (FD->hasAttr<NoUniqueAddressAttr>() &&
7475           isEmptyRecord(getContext(), FD->getType(), true))
7476         continue;
7477 
7478       // Unlike isSingleElementStruct(), arrays do not count.
7479       // Nested structures still do though.
7480       if (!Found.isNull())
7481         return Ty;
7482       Found = GetSingleElementType(FD->getType());
7483     }
7484 
7485     // Unlike isSingleElementStruct(), trailing padding is allowed.
7486     // An 8-byte aligned struct s { float f; } is passed as a double.
7487     if (!Found.isNull())
7488       return Found;
7489   }
7490 
7491   return Ty;
7492 }
7493 
7494 Address SystemZABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7495                                   QualType Ty) const {
7496   // Assume that va_list type is correct; should be pointer to LLVM type:
7497   // struct {
7498   //   i64 __gpr;
7499   //   i64 __fpr;
7500   //   i8 *__overflow_arg_area;
7501   //   i8 *__reg_save_area;
7502   // };
7503 
7504   // Every non-vector argument occupies 8 bytes and is passed by preference
7505   // in either GPRs or FPRs.  Vector arguments occupy 8 or 16 bytes and are
7506   // always passed on the stack.
7507   Ty = getContext().getCanonicalType(Ty);
7508   auto TyInfo = getContext().getTypeInfoInChars(Ty);
7509   llvm::Type *ArgTy = CGF.ConvertTypeForMem(Ty);
7510   llvm::Type *DirectTy = ArgTy;
7511   ABIArgInfo AI = classifyArgumentType(Ty);
7512   bool IsIndirect = AI.isIndirect();
7513   bool InFPRs = false;
7514   bool IsVector = false;
7515   CharUnits UnpaddedSize;
7516   CharUnits DirectAlign;
7517   if (IsIndirect) {
7518     DirectTy = llvm::PointerType::getUnqual(DirectTy);
7519     UnpaddedSize = DirectAlign = CharUnits::fromQuantity(8);
7520   } else {
7521     if (AI.getCoerceToType())
7522       ArgTy = AI.getCoerceToType();
7523     InFPRs = (!IsSoftFloatABI && (ArgTy->isFloatTy() || ArgTy->isDoubleTy()));
7524     IsVector = ArgTy->isVectorTy();
7525     UnpaddedSize = TyInfo.Width;
7526     DirectAlign = TyInfo.Align;
7527   }
7528   CharUnits PaddedSize = CharUnits::fromQuantity(8);
7529   if (IsVector && UnpaddedSize > PaddedSize)
7530     PaddedSize = CharUnits::fromQuantity(16);
7531   assert((UnpaddedSize <= PaddedSize) && "Invalid argument size.");
7532 
7533   CharUnits Padding = (PaddedSize - UnpaddedSize);
7534 
7535   llvm::Type *IndexTy = CGF.Int64Ty;
7536   llvm::Value *PaddedSizeV =
7537     llvm::ConstantInt::get(IndexTy, PaddedSize.getQuantity());
7538 
7539   if (IsVector) {
7540     // Work out the address of a vector argument on the stack.
7541     // Vector arguments are always passed in the high bits of a
7542     // single (8 byte) or double (16 byte) stack slot.
7543     Address OverflowArgAreaPtr =
7544         CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr");
7545     Address OverflowArgArea =
7546       Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
7547               TyInfo.Align);
7548     Address MemAddr =
7549       CGF.Builder.CreateElementBitCast(OverflowArgArea, DirectTy, "mem_addr");
7550 
7551     // Update overflow_arg_area_ptr pointer
7552     llvm::Value *NewOverflowArgArea =
7553       CGF.Builder.CreateGEP(OverflowArgArea.getElementType(),
7554                             OverflowArgArea.getPointer(), PaddedSizeV,
7555                             "overflow_arg_area");
7556     CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
7557 
7558     return MemAddr;
7559   }
7560 
7561   assert(PaddedSize.getQuantity() == 8);
7562 
7563   unsigned MaxRegs, RegCountField, RegSaveIndex;
7564   CharUnits RegPadding;
7565   if (InFPRs) {
7566     MaxRegs = 4; // Maximum of 4 FPR arguments
7567     RegCountField = 1; // __fpr
7568     RegSaveIndex = 16; // save offset for f0
7569     RegPadding = CharUnits(); // floats are passed in the high bits of an FPR
7570   } else {
7571     MaxRegs = 5; // Maximum of 5 GPR arguments
7572     RegCountField = 0; // __gpr
7573     RegSaveIndex = 2; // save offset for r2
7574     RegPadding = Padding; // values are passed in the low bits of a GPR
7575   }
7576 
7577   Address RegCountPtr =
7578       CGF.Builder.CreateStructGEP(VAListAddr, RegCountField, "reg_count_ptr");
7579   llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
7580   llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
7581   llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
7582                                                  "fits_in_regs");
7583 
7584   llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
7585   llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
7586   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
7587   CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
7588 
7589   // Emit code to load the value if it was passed in registers.
7590   CGF.EmitBlock(InRegBlock);
7591 
7592   // Work out the address of an argument register.
7593   llvm::Value *ScaledRegCount =
7594     CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
7595   llvm::Value *RegBase =
7596     llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize.getQuantity()
7597                                       + RegPadding.getQuantity());
7598   llvm::Value *RegOffset =
7599     CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
7600   Address RegSaveAreaPtr =
7601       CGF.Builder.CreateStructGEP(VAListAddr, 3, "reg_save_area_ptr");
7602   llvm::Value *RegSaveArea =
7603     CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
7604   Address RawRegAddr(CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, RegOffset,
7605                                            "raw_reg_addr"),
7606                      PaddedSize);
7607   Address RegAddr =
7608     CGF.Builder.CreateElementBitCast(RawRegAddr, DirectTy, "reg_addr");
7609 
7610   // Update the register count
7611   llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
7612   llvm::Value *NewRegCount =
7613     CGF.Builder.CreateAdd(RegCount, One, "reg_count");
7614   CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
7615   CGF.EmitBranch(ContBlock);
7616 
7617   // Emit code to load the value if it was passed in memory.
7618   CGF.EmitBlock(InMemBlock);
7619 
7620   // Work out the address of a stack argument.
7621   Address OverflowArgAreaPtr =
7622       CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr");
7623   Address OverflowArgArea =
7624     Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
7625             PaddedSize);
7626   Address RawMemAddr =
7627     CGF.Builder.CreateConstByteGEP(OverflowArgArea, Padding, "raw_mem_addr");
7628   Address MemAddr =
7629     CGF.Builder.CreateElementBitCast(RawMemAddr, DirectTy, "mem_addr");
7630 
7631   // Update overflow_arg_area_ptr pointer
7632   llvm::Value *NewOverflowArgArea =
7633     CGF.Builder.CreateGEP(OverflowArgArea.getElementType(),
7634                           OverflowArgArea.getPointer(), PaddedSizeV,
7635                           "overflow_arg_area");
7636   CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
7637   CGF.EmitBranch(ContBlock);
7638 
7639   // Return the appropriate result.
7640   CGF.EmitBlock(ContBlock);
7641   Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
7642                                  MemAddr, InMemBlock, "va_arg.addr");
7643 
7644   if (IsIndirect)
7645     ResAddr = Address(CGF.Builder.CreateLoad(ResAddr, "indirect_arg"),
7646                       TyInfo.Align);
7647 
7648   return ResAddr;
7649 }
7650 
7651 ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
7652   if (RetTy->isVoidType())
7653     return ABIArgInfo::getIgnore();
7654   if (isVectorArgumentType(RetTy))
7655     return ABIArgInfo::getDirect();
7656   if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
7657     return getNaturalAlignIndirect(RetTy);
7658   return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
7659                                                : ABIArgInfo::getDirect());
7660 }
7661 
7662 ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
7663   // Handle the generic C++ ABI.
7664   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
7665     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
7666 
7667   // Integers and enums are extended to full register width.
7668   if (isPromotableIntegerTypeForABI(Ty))
7669     return ABIArgInfo::getExtend(Ty);
7670 
7671   // Handle vector types and vector-like structure types.  Note that
7672   // as opposed to float-like structure types, we do not allow any
7673   // padding for vector-like structures, so verify the sizes match.
7674   uint64_t Size = getContext().getTypeSize(Ty);
7675   QualType SingleElementTy = GetSingleElementType(Ty);
7676   if (isVectorArgumentType(SingleElementTy) &&
7677       getContext().getTypeSize(SingleElementTy) == Size)
7678     return ABIArgInfo::getDirect(CGT.ConvertType(SingleElementTy));
7679 
7680   // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
7681   if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
7682     return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
7683 
7684   // Handle small structures.
7685   if (const RecordType *RT = Ty->getAs<RecordType>()) {
7686     // Structures with flexible arrays have variable length, so really
7687     // fail the size test above.
7688     const RecordDecl *RD = RT->getDecl();
7689     if (RD->hasFlexibleArrayMember())
7690       return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
7691 
7692     // The structure is passed as an unextended integer, a float, or a double.
7693     llvm::Type *PassTy;
7694     if (isFPArgumentType(SingleElementTy)) {
7695       assert(Size == 32 || Size == 64);
7696       if (Size == 32)
7697         PassTy = llvm::Type::getFloatTy(getVMContext());
7698       else
7699         PassTy = llvm::Type::getDoubleTy(getVMContext());
7700     } else
7701       PassTy = llvm::IntegerType::get(getVMContext(), Size);
7702     return ABIArgInfo::getDirect(PassTy);
7703   }
7704 
7705   // Non-structure compounds are passed indirectly.
7706   if (isCompoundType(Ty))
7707     return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
7708 
7709   return ABIArgInfo::getDirect(nullptr);
7710 }
7711 
7712 //===----------------------------------------------------------------------===//
7713 // MSP430 ABI Implementation
7714 //===----------------------------------------------------------------------===//
7715 
7716 namespace {
7717 
7718 class MSP430ABIInfo : public DefaultABIInfo {
7719   static ABIArgInfo complexArgInfo() {
7720     ABIArgInfo Info = ABIArgInfo::getDirect();
7721     Info.setCanBeFlattened(false);
7722     return Info;
7723   }
7724 
7725 public:
7726   MSP430ABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
7727 
7728   ABIArgInfo classifyReturnType(QualType RetTy) const {
7729     if (RetTy->isAnyComplexType())
7730       return complexArgInfo();
7731 
7732     return DefaultABIInfo::classifyReturnType(RetTy);
7733   }
7734 
7735   ABIArgInfo classifyArgumentType(QualType RetTy) const {
7736     if (RetTy->isAnyComplexType())
7737       return complexArgInfo();
7738 
7739     return DefaultABIInfo::classifyArgumentType(RetTy);
7740   }
7741 
7742   // Just copy the original implementations because
7743   // DefaultABIInfo::classify{Return,Argument}Type() are not virtual
7744   void computeInfo(CGFunctionInfo &FI) const override {
7745     if (!getCXXABI().classifyReturnType(FI))
7746       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7747     for (auto &I : FI.arguments())
7748       I.info = classifyArgumentType(I.type);
7749   }
7750 
7751   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7752                     QualType Ty) const override {
7753     return EmitVAArgInstr(CGF, VAListAddr, Ty, classifyArgumentType(Ty));
7754   }
7755 };
7756 
7757 class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
7758 public:
7759   MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
7760       : TargetCodeGenInfo(std::make_unique<MSP430ABIInfo>(CGT)) {}
7761   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
7762                            CodeGen::CodeGenModule &M) const override;
7763 };
7764 
7765 }
7766 
7767 void MSP430TargetCodeGenInfo::setTargetAttributes(
7768     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
7769   if (GV->isDeclaration())
7770     return;
7771   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
7772     const auto *InterruptAttr = FD->getAttr<MSP430InterruptAttr>();
7773     if (!InterruptAttr)
7774       return;
7775 
7776     // Handle 'interrupt' attribute:
7777     llvm::Function *F = cast<llvm::Function>(GV);
7778 
7779     // Step 1: Set ISR calling convention.
7780     F->setCallingConv(llvm::CallingConv::MSP430_INTR);
7781 
7782     // Step 2: Add attributes goodness.
7783     F->addFnAttr(llvm::Attribute::NoInline);
7784     F->addFnAttr("interrupt", llvm::utostr(InterruptAttr->getNumber()));
7785   }
7786 }
7787 
7788 //===----------------------------------------------------------------------===//
7789 // MIPS ABI Implementation.  This works for both little-endian and
7790 // big-endian variants.
7791 //===----------------------------------------------------------------------===//
7792 
7793 namespace {
7794 class MipsABIInfo : public ABIInfo {
7795   bool IsO32;
7796   unsigned MinABIStackAlignInBytes, StackAlignInBytes;
7797   void CoerceToIntArgs(uint64_t TySize,
7798                        SmallVectorImpl<llvm::Type *> &ArgList) const;
7799   llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
7800   llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
7801   llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
7802 public:
7803   MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
7804     ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
7805     StackAlignInBytes(IsO32 ? 8 : 16) {}
7806 
7807   ABIArgInfo classifyReturnType(QualType RetTy) const;
7808   ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
7809   void computeInfo(CGFunctionInfo &FI) const override;
7810   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7811                     QualType Ty) const override;
7812   ABIArgInfo extendType(QualType Ty) const;
7813 };
7814 
7815 class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
7816   unsigned SizeOfUnwindException;
7817 public:
7818   MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
7819       : TargetCodeGenInfo(std::make_unique<MipsABIInfo>(CGT, IsO32)),
7820         SizeOfUnwindException(IsO32 ? 24 : 32) {}
7821 
7822   int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
7823     return 29;
7824   }
7825 
7826   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
7827                            CodeGen::CodeGenModule &CGM) const override {
7828     const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
7829     if (!FD) return;
7830     llvm::Function *Fn = cast<llvm::Function>(GV);
7831 
7832     if (FD->hasAttr<MipsLongCallAttr>())
7833       Fn->addFnAttr("long-call");
7834     else if (FD->hasAttr<MipsShortCallAttr>())
7835       Fn->addFnAttr("short-call");
7836 
7837     // Other attributes do not have a meaning for declarations.
7838     if (GV->isDeclaration())
7839       return;
7840 
7841     if (FD->hasAttr<Mips16Attr>()) {
7842       Fn->addFnAttr("mips16");
7843     }
7844     else if (FD->hasAttr<NoMips16Attr>()) {
7845       Fn->addFnAttr("nomips16");
7846     }
7847 
7848     if (FD->hasAttr<MicroMipsAttr>())
7849       Fn->addFnAttr("micromips");
7850     else if (FD->hasAttr<NoMicroMipsAttr>())
7851       Fn->addFnAttr("nomicromips");
7852 
7853     const MipsInterruptAttr *Attr = FD->getAttr<MipsInterruptAttr>();
7854     if (!Attr)
7855       return;
7856 
7857     const char *Kind;
7858     switch (Attr->getInterrupt()) {
7859     case MipsInterruptAttr::eic:     Kind = "eic"; break;
7860     case MipsInterruptAttr::sw0:     Kind = "sw0"; break;
7861     case MipsInterruptAttr::sw1:     Kind = "sw1"; break;
7862     case MipsInterruptAttr::hw0:     Kind = "hw0"; break;
7863     case MipsInterruptAttr::hw1:     Kind = "hw1"; break;
7864     case MipsInterruptAttr::hw2:     Kind = "hw2"; break;
7865     case MipsInterruptAttr::hw3:     Kind = "hw3"; break;
7866     case MipsInterruptAttr::hw4:     Kind = "hw4"; break;
7867     case MipsInterruptAttr::hw5:     Kind = "hw5"; break;
7868     }
7869 
7870     Fn->addFnAttr("interrupt", Kind);
7871 
7872   }
7873 
7874   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
7875                                llvm::Value *Address) const override;
7876 
7877   unsigned getSizeOfUnwindException() const override {
7878     return SizeOfUnwindException;
7879   }
7880 };
7881 }
7882 
7883 void MipsABIInfo::CoerceToIntArgs(
7884     uint64_t TySize, SmallVectorImpl<llvm::Type *> &ArgList) const {
7885   llvm::IntegerType *IntTy =
7886     llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
7887 
7888   // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
7889   for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
7890     ArgList.push_back(IntTy);
7891 
7892   // If necessary, add one more integer type to ArgList.
7893   unsigned R = TySize % (MinABIStackAlignInBytes * 8);
7894 
7895   if (R)
7896     ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
7897 }
7898 
7899 // In N32/64, an aligned double precision floating point field is passed in
7900 // a register.
7901 llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
7902   SmallVector<llvm::Type*, 8> ArgList, IntArgList;
7903 
7904   if (IsO32) {
7905     CoerceToIntArgs(TySize, ArgList);
7906     return llvm::StructType::get(getVMContext(), ArgList);
7907   }
7908 
7909   if (Ty->isComplexType())
7910     return CGT.ConvertType(Ty);
7911 
7912   const RecordType *RT = Ty->getAs<RecordType>();
7913 
7914   // Unions/vectors are passed in integer registers.
7915   if (!RT || !RT->isStructureOrClassType()) {
7916     CoerceToIntArgs(TySize, ArgList);
7917     return llvm::StructType::get(getVMContext(), ArgList);
7918   }
7919 
7920   const RecordDecl *RD = RT->getDecl();
7921   const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
7922   assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
7923 
7924   uint64_t LastOffset = 0;
7925   unsigned idx = 0;
7926   llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
7927 
7928   // Iterate over fields in the struct/class and check if there are any aligned
7929   // double fields.
7930   for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
7931        i != e; ++i, ++idx) {
7932     const QualType Ty = i->getType();
7933     const BuiltinType *BT = Ty->getAs<BuiltinType>();
7934 
7935     if (!BT || BT->getKind() != BuiltinType::Double)
7936       continue;
7937 
7938     uint64_t Offset = Layout.getFieldOffset(idx);
7939     if (Offset % 64) // Ignore doubles that are not aligned.
7940       continue;
7941 
7942     // Add ((Offset - LastOffset) / 64) args of type i64.
7943     for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
7944       ArgList.push_back(I64);
7945 
7946     // Add double type.
7947     ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
7948     LastOffset = Offset + 64;
7949   }
7950 
7951   CoerceToIntArgs(TySize - LastOffset, IntArgList);
7952   ArgList.append(IntArgList.begin(), IntArgList.end());
7953 
7954   return llvm::StructType::get(getVMContext(), ArgList);
7955 }
7956 
7957 llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
7958                                         uint64_t Offset) const {
7959   if (OrigOffset + MinABIStackAlignInBytes > Offset)
7960     return nullptr;
7961 
7962   return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
7963 }
7964 
7965 ABIArgInfo
7966 MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
7967   Ty = useFirstFieldIfTransparentUnion(Ty);
7968 
7969   uint64_t OrigOffset = Offset;
7970   uint64_t TySize = getContext().getTypeSize(Ty);
7971   uint64_t Align = getContext().getTypeAlign(Ty) / 8;
7972 
7973   Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
7974                    (uint64_t)StackAlignInBytes);
7975   unsigned CurrOffset = llvm::alignTo(Offset, Align);
7976   Offset = CurrOffset + llvm::alignTo(TySize, Align * 8) / 8;
7977 
7978   if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
7979     // Ignore empty aggregates.
7980     if (TySize == 0)
7981       return ABIArgInfo::getIgnore();
7982 
7983     if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
7984       Offset = OrigOffset + MinABIStackAlignInBytes;
7985       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
7986     }
7987 
7988     // If we have reached here, aggregates are passed directly by coercing to
7989     // another structure type. Padding is inserted if the offset of the
7990     // aggregate is unaligned.
7991     ABIArgInfo ArgInfo =
7992         ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
7993                               getPaddingType(OrigOffset, CurrOffset));
7994     ArgInfo.setInReg(true);
7995     return ArgInfo;
7996   }
7997 
7998   // Treat an enum type as its underlying type.
7999   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
8000     Ty = EnumTy->getDecl()->getIntegerType();
8001 
8002   // Make sure we pass indirectly things that are too large.
8003   if (const auto *EIT = Ty->getAs<BitIntType>())
8004     if (EIT->getNumBits() > 128 ||
8005         (EIT->getNumBits() > 64 &&
8006          !getContext().getTargetInfo().hasInt128Type()))
8007       return getNaturalAlignIndirect(Ty);
8008 
8009   // All integral types are promoted to the GPR width.
8010   if (Ty->isIntegralOrEnumerationType())
8011     return extendType(Ty);
8012 
8013   return ABIArgInfo::getDirect(
8014       nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset));
8015 }
8016 
8017 llvm::Type*
8018 MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
8019   const RecordType *RT = RetTy->getAs<RecordType>();
8020   SmallVector<llvm::Type*, 8> RTList;
8021 
8022   if (RT && RT->isStructureOrClassType()) {
8023     const RecordDecl *RD = RT->getDecl();
8024     const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
8025     unsigned FieldCnt = Layout.getFieldCount();
8026 
8027     // N32/64 returns struct/classes in floating point registers if the
8028     // following conditions are met:
8029     // 1. The size of the struct/class is no larger than 128-bit.
8030     // 2. The struct/class has one or two fields all of which are floating
8031     //    point types.
8032     // 3. The offset of the first field is zero (this follows what gcc does).
8033     //
8034     // Any other composite results are returned in integer registers.
8035     //
8036     if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
8037       RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
8038       for (; b != e; ++b) {
8039         const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
8040 
8041         if (!BT || !BT->isFloatingPoint())
8042           break;
8043 
8044         RTList.push_back(CGT.ConvertType(b->getType()));
8045       }
8046 
8047       if (b == e)
8048         return llvm::StructType::get(getVMContext(), RTList,
8049                                      RD->hasAttr<PackedAttr>());
8050 
8051       RTList.clear();
8052     }
8053   }
8054 
8055   CoerceToIntArgs(Size, RTList);
8056   return llvm::StructType::get(getVMContext(), RTList);
8057 }
8058 
8059 ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
8060   uint64_t Size = getContext().getTypeSize(RetTy);
8061 
8062   if (RetTy->isVoidType())
8063     return ABIArgInfo::getIgnore();
8064 
8065   // O32 doesn't treat zero-sized structs differently from other structs.
8066   // However, N32/N64 ignores zero sized return values.
8067   if (!IsO32 && Size == 0)
8068     return ABIArgInfo::getIgnore();
8069 
8070   if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
8071     if (Size <= 128) {
8072       if (RetTy->isAnyComplexType())
8073         return ABIArgInfo::getDirect();
8074 
8075       // O32 returns integer vectors in registers and N32/N64 returns all small
8076       // aggregates in registers.
8077       if (!IsO32 ||
8078           (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) {
8079         ABIArgInfo ArgInfo =
8080             ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
8081         ArgInfo.setInReg(true);
8082         return ArgInfo;
8083       }
8084     }
8085 
8086     return getNaturalAlignIndirect(RetTy);
8087   }
8088 
8089   // Treat an enum type as its underlying type.
8090   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
8091     RetTy = EnumTy->getDecl()->getIntegerType();
8092 
8093   // Make sure we pass indirectly things that are too large.
8094   if (const auto *EIT = RetTy->getAs<BitIntType>())
8095     if (EIT->getNumBits() > 128 ||
8096         (EIT->getNumBits() > 64 &&
8097          !getContext().getTargetInfo().hasInt128Type()))
8098       return getNaturalAlignIndirect(RetTy);
8099 
8100   if (isPromotableIntegerTypeForABI(RetTy))
8101     return ABIArgInfo::getExtend(RetTy);
8102 
8103   if ((RetTy->isUnsignedIntegerOrEnumerationType() ||
8104       RetTy->isSignedIntegerOrEnumerationType()) && Size == 32 && !IsO32)
8105     return ABIArgInfo::getSignExtend(RetTy);
8106 
8107   return ABIArgInfo::getDirect();
8108 }
8109 
8110 void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
8111   ABIArgInfo &RetInfo = FI.getReturnInfo();
8112   if (!getCXXABI().classifyReturnType(FI))
8113     RetInfo = classifyReturnType(FI.getReturnType());
8114 
8115   // Check if a pointer to an aggregate is passed as a hidden argument.
8116   uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
8117 
8118   for (auto &I : FI.arguments())
8119     I.info = classifyArgumentType(I.type, Offset);
8120 }
8121 
8122 Address MipsABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8123                                QualType OrigTy) const {
8124   QualType Ty = OrigTy;
8125 
8126   // Integer arguments are promoted to 32-bit on O32 and 64-bit on N32/N64.
8127   // Pointers are also promoted in the same way but this only matters for N32.
8128   unsigned SlotSizeInBits = IsO32 ? 32 : 64;
8129   unsigned PtrWidth = getTarget().getPointerWidth(0);
8130   bool DidPromote = false;
8131   if ((Ty->isIntegerType() &&
8132           getContext().getIntWidth(Ty) < SlotSizeInBits) ||
8133       (Ty->isPointerType() && PtrWidth < SlotSizeInBits)) {
8134     DidPromote = true;
8135     Ty = getContext().getIntTypeForBitwidth(SlotSizeInBits,
8136                                             Ty->isSignedIntegerType());
8137   }
8138 
8139   auto TyInfo = getContext().getTypeInfoInChars(Ty);
8140 
8141   // The alignment of things in the argument area is never larger than
8142   // StackAlignInBytes.
8143   TyInfo.Align =
8144     std::min(TyInfo.Align, CharUnits::fromQuantity(StackAlignInBytes));
8145 
8146   // MinABIStackAlignInBytes is the size of argument slots on the stack.
8147   CharUnits ArgSlotSize = CharUnits::fromQuantity(MinABIStackAlignInBytes);
8148 
8149   Address Addr = emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
8150                           TyInfo, ArgSlotSize, /*AllowHigherAlign*/ true);
8151 
8152 
8153   // If there was a promotion, "unpromote" into a temporary.
8154   // TODO: can we just use a pointer into a subset of the original slot?
8155   if (DidPromote) {
8156     Address Temp = CGF.CreateMemTemp(OrigTy, "vaarg.promotion-temp");
8157     llvm::Value *Promoted = CGF.Builder.CreateLoad(Addr);
8158 
8159     // Truncate down to the right width.
8160     llvm::Type *IntTy = (OrigTy->isIntegerType() ? Temp.getElementType()
8161                                                  : CGF.IntPtrTy);
8162     llvm::Value *V = CGF.Builder.CreateTrunc(Promoted, IntTy);
8163     if (OrigTy->isPointerType())
8164       V = CGF.Builder.CreateIntToPtr(V, Temp.getElementType());
8165 
8166     CGF.Builder.CreateStore(V, Temp);
8167     Addr = Temp;
8168   }
8169 
8170   return Addr;
8171 }
8172 
8173 ABIArgInfo MipsABIInfo::extendType(QualType Ty) const {
8174   int TySize = getContext().getTypeSize(Ty);
8175 
8176   // MIPS64 ABI requires unsigned 32 bit integers to be sign extended.
8177   if (Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
8178     return ABIArgInfo::getSignExtend(Ty);
8179 
8180   return ABIArgInfo::getExtend(Ty);
8181 }
8182 
8183 bool
8184 MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
8185                                                llvm::Value *Address) const {
8186   // This information comes from gcc's implementation, which seems to
8187   // as canonical as it gets.
8188 
8189   // Everything on MIPS is 4 bytes.  Double-precision FP registers
8190   // are aliased to pairs of single-precision FP registers.
8191   llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
8192 
8193   // 0-31 are the general purpose registers, $0 - $31.
8194   // 32-63 are the floating-point registers, $f0 - $f31.
8195   // 64 and 65 are the multiply/divide registers, $hi and $lo.
8196   // 66 is the (notional, I think) register for signal-handler return.
8197   AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
8198 
8199   // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
8200   // They are one bit wide and ignored here.
8201 
8202   // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
8203   // (coprocessor 1 is the FP unit)
8204   // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
8205   // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
8206   // 176-181 are the DSP accumulator registers.
8207   AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
8208   return false;
8209 }
8210 
8211 //===----------------------------------------------------------------------===//
8212 // M68k ABI Implementation
8213 //===----------------------------------------------------------------------===//
8214 
8215 namespace {
8216 
8217 class M68kTargetCodeGenInfo : public TargetCodeGenInfo {
8218 public:
8219   M68kTargetCodeGenInfo(CodeGenTypes &CGT)
8220       : TargetCodeGenInfo(std::make_unique<DefaultABIInfo>(CGT)) {}
8221   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
8222                            CodeGen::CodeGenModule &M) const override;
8223 };
8224 
8225 } // namespace
8226 
8227 void M68kTargetCodeGenInfo::setTargetAttributes(
8228     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
8229   if (const auto *FD = dyn_cast_or_null<FunctionDecl>(D)) {
8230     if (const auto *attr = FD->getAttr<M68kInterruptAttr>()) {
8231       // Handle 'interrupt' attribute:
8232       llvm::Function *F = cast<llvm::Function>(GV);
8233 
8234       // Step 1: Set ISR calling convention.
8235       F->setCallingConv(llvm::CallingConv::M68k_INTR);
8236 
8237       // Step 2: Add attributes goodness.
8238       F->addFnAttr(llvm::Attribute::NoInline);
8239 
8240       // Step 3: Emit ISR vector alias.
8241       unsigned Num = attr->getNumber() / 2;
8242       llvm::GlobalAlias::create(llvm::Function::ExternalLinkage,
8243                                 "__isr_" + Twine(Num), F);
8244     }
8245   }
8246 }
8247 
8248 //===----------------------------------------------------------------------===//
8249 // AVR ABI Implementation. Documented at
8250 // https://gcc.gnu.org/wiki/avr-gcc#Calling_Convention
8251 // https://gcc.gnu.org/wiki/avr-gcc#Reduced_Tiny
8252 //===----------------------------------------------------------------------===//
8253 
8254 namespace {
8255 class AVRABIInfo : public DefaultABIInfo {
8256 public:
8257   AVRABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
8258 
8259   ABIArgInfo classifyReturnType(QualType Ty) const {
8260     // A return struct with size less than or equal to 8 bytes is returned
8261     // directly via registers R18-R25.
8262     if (isAggregateTypeForABI(Ty) && getContext().getTypeSize(Ty) <= 64)
8263       return ABIArgInfo::getDirect();
8264     else
8265       return DefaultABIInfo::classifyReturnType(Ty);
8266   }
8267 
8268   // Just copy the original implementation of DefaultABIInfo::computeInfo(),
8269   // since DefaultABIInfo::classify{Return,Argument}Type() are not virtual.
8270   void computeInfo(CGFunctionInfo &FI) const override {
8271     if (!getCXXABI().classifyReturnType(FI))
8272       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
8273     for (auto &I : FI.arguments())
8274       I.info = classifyArgumentType(I.type);
8275   }
8276 };
8277 
8278 class AVRTargetCodeGenInfo : public TargetCodeGenInfo {
8279 public:
8280   AVRTargetCodeGenInfo(CodeGenTypes &CGT)
8281       : TargetCodeGenInfo(std::make_unique<AVRABIInfo>(CGT)) {}
8282 
8283   LangAS getGlobalVarAddressSpace(CodeGenModule &CGM,
8284                                   const VarDecl *D) const override {
8285     // Check if global/static variable is defined in address space
8286     // 1~6 (__flash, __flash1, __flash2, __flash3, __flash4, __flash5)
8287     // but not constant.
8288     LangAS AS = D->getType().getAddressSpace();
8289     if (isTargetAddressSpace(AS) && 1 <= toTargetAddressSpace(AS) &&
8290         toTargetAddressSpace(AS) <= 6 && !D->getType().isConstQualified())
8291       CGM.getDiags().Report(D->getLocation(),
8292                             diag::err_verify_nonconst_addrspace)
8293           << "__flash*";
8294     return TargetCodeGenInfo::getGlobalVarAddressSpace(CGM, D);
8295   }
8296 
8297   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
8298                            CodeGen::CodeGenModule &CGM) const override {
8299     if (GV->isDeclaration())
8300       return;
8301     const auto *FD = dyn_cast_or_null<FunctionDecl>(D);
8302     if (!FD) return;
8303     auto *Fn = cast<llvm::Function>(GV);
8304 
8305     if (FD->getAttr<AVRInterruptAttr>())
8306       Fn->addFnAttr("interrupt");
8307 
8308     if (FD->getAttr<AVRSignalAttr>())
8309       Fn->addFnAttr("signal");
8310   }
8311 };
8312 }
8313 
8314 //===----------------------------------------------------------------------===//
8315 // TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
8316 // Currently subclassed only to implement custom OpenCL C function attribute
8317 // handling.
8318 //===----------------------------------------------------------------------===//
8319 
8320 namespace {
8321 
8322 class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
8323 public:
8324   TCETargetCodeGenInfo(CodeGenTypes &CGT)
8325     : DefaultTargetCodeGenInfo(CGT) {}
8326 
8327   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
8328                            CodeGen::CodeGenModule &M) const override;
8329 };
8330 
8331 void TCETargetCodeGenInfo::setTargetAttributes(
8332     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
8333   if (GV->isDeclaration())
8334     return;
8335   const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
8336   if (!FD) return;
8337 
8338   llvm::Function *F = cast<llvm::Function>(GV);
8339 
8340   if (M.getLangOpts().OpenCL) {
8341     if (FD->hasAttr<OpenCLKernelAttr>()) {
8342       // OpenCL C Kernel functions are not subject to inlining
8343       F->addFnAttr(llvm::Attribute::NoInline);
8344       const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
8345       if (Attr) {
8346         // Convert the reqd_work_group_size() attributes to metadata.
8347         llvm::LLVMContext &Context = F->getContext();
8348         llvm::NamedMDNode *OpenCLMetadata =
8349             M.getModule().getOrInsertNamedMetadata(
8350                 "opencl.kernel_wg_size_info");
8351 
8352         SmallVector<llvm::Metadata *, 5> Operands;
8353         Operands.push_back(llvm::ConstantAsMetadata::get(F));
8354 
8355         Operands.push_back(
8356             llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
8357                 M.Int32Ty, llvm::APInt(32, Attr->getXDim()))));
8358         Operands.push_back(
8359             llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
8360                 M.Int32Ty, llvm::APInt(32, Attr->getYDim()))));
8361         Operands.push_back(
8362             llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
8363                 M.Int32Ty, llvm::APInt(32, Attr->getZDim()))));
8364 
8365         // Add a boolean constant operand for "required" (true) or "hint"
8366         // (false) for implementing the work_group_size_hint attr later.
8367         // Currently always true as the hint is not yet implemented.
8368         Operands.push_back(
8369             llvm::ConstantAsMetadata::get(llvm::ConstantInt::getTrue(Context)));
8370         OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
8371       }
8372     }
8373   }
8374 }
8375 
8376 }
8377 
8378 //===----------------------------------------------------------------------===//
8379 // Hexagon ABI Implementation
8380 //===----------------------------------------------------------------------===//
8381 
8382 namespace {
8383 
8384 class HexagonABIInfo : public DefaultABIInfo {
8385 public:
8386   HexagonABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
8387 
8388 private:
8389   ABIArgInfo classifyReturnType(QualType RetTy) const;
8390   ABIArgInfo classifyArgumentType(QualType RetTy) const;
8391   ABIArgInfo classifyArgumentType(QualType RetTy, unsigned *RegsLeft) const;
8392 
8393   void computeInfo(CGFunctionInfo &FI) const override;
8394 
8395   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8396                     QualType Ty) const override;
8397   Address EmitVAArgFromMemory(CodeGenFunction &CFG, Address VAListAddr,
8398                               QualType Ty) const;
8399   Address EmitVAArgForHexagon(CodeGenFunction &CFG, Address VAListAddr,
8400                               QualType Ty) const;
8401   Address EmitVAArgForHexagonLinux(CodeGenFunction &CFG, Address VAListAddr,
8402                                    QualType Ty) const;
8403 };
8404 
8405 class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
8406 public:
8407   HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
8408       : TargetCodeGenInfo(std::make_unique<HexagonABIInfo>(CGT)) {}
8409 
8410   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
8411     return 29;
8412   }
8413 
8414   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
8415                            CodeGen::CodeGenModule &GCM) const override {
8416     if (GV->isDeclaration())
8417       return;
8418     const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
8419     if (!FD)
8420       return;
8421   }
8422 };
8423 
8424 } // namespace
8425 
8426 void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
8427   unsigned RegsLeft = 6;
8428   if (!getCXXABI().classifyReturnType(FI))
8429     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
8430   for (auto &I : FI.arguments())
8431     I.info = classifyArgumentType(I.type, &RegsLeft);
8432 }
8433 
8434 static bool HexagonAdjustRegsLeft(uint64_t Size, unsigned *RegsLeft) {
8435   assert(Size <= 64 && "Not expecting to pass arguments larger than 64 bits"
8436                        " through registers");
8437 
8438   if (*RegsLeft == 0)
8439     return false;
8440 
8441   if (Size <= 32) {
8442     (*RegsLeft)--;
8443     return true;
8444   }
8445 
8446   if (2 <= (*RegsLeft & (~1U))) {
8447     *RegsLeft = (*RegsLeft & (~1U)) - 2;
8448     return true;
8449   }
8450 
8451   // Next available register was r5 but candidate was greater than 32-bits so it
8452   // has to go on the stack. However we still consume r5
8453   if (*RegsLeft == 1)
8454     *RegsLeft = 0;
8455 
8456   return false;
8457 }
8458 
8459 ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty,
8460                                                 unsigned *RegsLeft) const {
8461   if (!isAggregateTypeForABI(Ty)) {
8462     // Treat an enum type as its underlying type.
8463     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
8464       Ty = EnumTy->getDecl()->getIntegerType();
8465 
8466     uint64_t Size = getContext().getTypeSize(Ty);
8467     if (Size <= 64)
8468       HexagonAdjustRegsLeft(Size, RegsLeft);
8469 
8470     if (Size > 64 && Ty->isBitIntType())
8471       return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
8472 
8473     return isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
8474                                              : ABIArgInfo::getDirect();
8475   }
8476 
8477   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
8478     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
8479 
8480   // Ignore empty records.
8481   if (isEmptyRecord(getContext(), Ty, true))
8482     return ABIArgInfo::getIgnore();
8483 
8484   uint64_t Size = getContext().getTypeSize(Ty);
8485   unsigned Align = getContext().getTypeAlign(Ty);
8486 
8487   if (Size > 64)
8488     return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
8489 
8490   if (HexagonAdjustRegsLeft(Size, RegsLeft))
8491     Align = Size <= 32 ? 32 : 64;
8492   if (Size <= Align) {
8493     // Pass in the smallest viable integer type.
8494     if (!llvm::isPowerOf2_64(Size))
8495       Size = llvm::NextPowerOf2(Size);
8496     return ABIArgInfo::getDirect(llvm::Type::getIntNTy(getVMContext(), Size));
8497   }
8498   return DefaultABIInfo::classifyArgumentType(Ty);
8499 }
8500 
8501 ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
8502   if (RetTy->isVoidType())
8503     return ABIArgInfo::getIgnore();
8504 
8505   const TargetInfo &T = CGT.getTarget();
8506   uint64_t Size = getContext().getTypeSize(RetTy);
8507 
8508   if (RetTy->getAs<VectorType>()) {
8509     // HVX vectors are returned in vector registers or register pairs.
8510     if (T.hasFeature("hvx")) {
8511       assert(T.hasFeature("hvx-length64b") || T.hasFeature("hvx-length128b"));
8512       uint64_t VecSize = T.hasFeature("hvx-length64b") ? 64*8 : 128*8;
8513       if (Size == VecSize || Size == 2*VecSize)
8514         return ABIArgInfo::getDirectInReg();
8515     }
8516     // Large vector types should be returned via memory.
8517     if (Size > 64)
8518       return getNaturalAlignIndirect(RetTy);
8519   }
8520 
8521   if (!isAggregateTypeForABI(RetTy)) {
8522     // Treat an enum type as its underlying type.
8523     if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
8524       RetTy = EnumTy->getDecl()->getIntegerType();
8525 
8526     if (Size > 64 && RetTy->isBitIntType())
8527       return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
8528 
8529     return isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
8530                                                 : ABIArgInfo::getDirect();
8531   }
8532 
8533   if (isEmptyRecord(getContext(), RetTy, true))
8534     return ABIArgInfo::getIgnore();
8535 
8536   // Aggregates <= 8 bytes are returned in registers, other aggregates
8537   // are returned indirectly.
8538   if (Size <= 64) {
8539     // Return in the smallest viable integer type.
8540     if (!llvm::isPowerOf2_64(Size))
8541       Size = llvm::NextPowerOf2(Size);
8542     return ABIArgInfo::getDirect(llvm::Type::getIntNTy(getVMContext(), Size));
8543   }
8544   return getNaturalAlignIndirect(RetTy, /*ByVal=*/true);
8545 }
8546 
8547 Address HexagonABIInfo::EmitVAArgFromMemory(CodeGenFunction &CGF,
8548                                             Address VAListAddr,
8549                                             QualType Ty) const {
8550   // Load the overflow area pointer.
8551   Address __overflow_area_pointer_p =
8552       CGF.Builder.CreateStructGEP(VAListAddr, 2, "__overflow_area_pointer_p");
8553   llvm::Value *__overflow_area_pointer = CGF.Builder.CreateLoad(
8554       __overflow_area_pointer_p, "__overflow_area_pointer");
8555 
8556   uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8;
8557   if (Align > 4) {
8558     // Alignment should be a power of 2.
8559     assert((Align & (Align - 1)) == 0 && "Alignment is not power of 2!");
8560 
8561     // overflow_arg_area = (overflow_arg_area + align - 1) & -align;
8562     llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int64Ty, Align - 1);
8563 
8564     // Add offset to the current pointer to access the argument.
8565     __overflow_area_pointer =
8566         CGF.Builder.CreateGEP(CGF.Int8Ty, __overflow_area_pointer, Offset);
8567     llvm::Value *AsInt =
8568         CGF.Builder.CreatePtrToInt(__overflow_area_pointer, CGF.Int32Ty);
8569 
8570     // Create a mask which should be "AND"ed
8571     // with (overflow_arg_area + align - 1)
8572     llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int32Ty, -(int)Align);
8573     __overflow_area_pointer = CGF.Builder.CreateIntToPtr(
8574         CGF.Builder.CreateAnd(AsInt, Mask), __overflow_area_pointer->getType(),
8575         "__overflow_area_pointer.align");
8576   }
8577 
8578   // Get the type of the argument from memory and bitcast
8579   // overflow area pointer to the argument type.
8580   llvm::Type *PTy = CGF.ConvertTypeForMem(Ty);
8581   Address AddrTyped = CGF.Builder.CreateBitCast(
8582       Address(__overflow_area_pointer, CharUnits::fromQuantity(Align)),
8583       llvm::PointerType::getUnqual(PTy));
8584 
8585   // Round up to the minimum stack alignment for varargs which is 4 bytes.
8586   uint64_t Offset = llvm::alignTo(CGF.getContext().getTypeSize(Ty) / 8, 4);
8587 
8588   __overflow_area_pointer = CGF.Builder.CreateGEP(
8589       CGF.Int8Ty, __overflow_area_pointer,
8590       llvm::ConstantInt::get(CGF.Int32Ty, Offset),
8591       "__overflow_area_pointer.next");
8592   CGF.Builder.CreateStore(__overflow_area_pointer, __overflow_area_pointer_p);
8593 
8594   return AddrTyped;
8595 }
8596 
8597 Address HexagonABIInfo::EmitVAArgForHexagon(CodeGenFunction &CGF,
8598                                             Address VAListAddr,
8599                                             QualType Ty) const {
8600   // FIXME: Need to handle alignment
8601   llvm::Type *BP = CGF.Int8PtrTy;
8602   llvm::Type *BPP = CGF.Int8PtrPtrTy;
8603   CGBuilderTy &Builder = CGF.Builder;
8604   Address VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
8605   llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
8606   // Handle address alignment for type alignment > 32 bits
8607   uint64_t TyAlign = CGF.getContext().getTypeAlign(Ty) / 8;
8608   if (TyAlign > 4) {
8609     assert((TyAlign & (TyAlign - 1)) == 0 && "Alignment is not power of 2!");
8610     llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int32Ty);
8611     AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt32(TyAlign - 1));
8612     AddrAsInt = Builder.CreateAnd(AddrAsInt, Builder.getInt32(~(TyAlign - 1)));
8613     Addr = Builder.CreateIntToPtr(AddrAsInt, BP);
8614   }
8615   llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
8616   Address AddrTyped = Builder.CreateBitCast(
8617       Address(Addr, CharUnits::fromQuantity(TyAlign)), PTy);
8618 
8619   uint64_t Offset = llvm::alignTo(CGF.getContext().getTypeSize(Ty) / 8, 4);
8620   llvm::Value *NextAddr = Builder.CreateGEP(
8621       CGF.Int8Ty, Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset), "ap.next");
8622   Builder.CreateStore(NextAddr, VAListAddrAsBPP);
8623 
8624   return AddrTyped;
8625 }
8626 
8627 Address HexagonABIInfo::EmitVAArgForHexagonLinux(CodeGenFunction &CGF,
8628                                                  Address VAListAddr,
8629                                                  QualType Ty) const {
8630   int ArgSize = CGF.getContext().getTypeSize(Ty) / 8;
8631 
8632   if (ArgSize > 8)
8633     return EmitVAArgFromMemory(CGF, VAListAddr, Ty);
8634 
8635   // Here we have check if the argument is in register area or
8636   // in overflow area.
8637   // If the saved register area pointer + argsize rounded up to alignment >
8638   // saved register area end pointer, argument is in overflow area.
8639   unsigned RegsLeft = 6;
8640   Ty = CGF.getContext().getCanonicalType(Ty);
8641   (void)classifyArgumentType(Ty, &RegsLeft);
8642 
8643   llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
8644   llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
8645   llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
8646   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
8647 
8648   // Get rounded size of the argument.GCC does not allow vararg of
8649   // size < 4 bytes. We follow the same logic here.
8650   ArgSize = (CGF.getContext().getTypeSize(Ty) <= 32) ? 4 : 8;
8651   int ArgAlign = (CGF.getContext().getTypeSize(Ty) <= 32) ? 4 : 8;
8652 
8653   // Argument may be in saved register area
8654   CGF.EmitBlock(MaybeRegBlock);
8655 
8656   // Load the current saved register area pointer.
8657   Address __current_saved_reg_area_pointer_p = CGF.Builder.CreateStructGEP(
8658       VAListAddr, 0, "__current_saved_reg_area_pointer_p");
8659   llvm::Value *__current_saved_reg_area_pointer = CGF.Builder.CreateLoad(
8660       __current_saved_reg_area_pointer_p, "__current_saved_reg_area_pointer");
8661 
8662   // Load the saved register area end pointer.
8663   Address __saved_reg_area_end_pointer_p = CGF.Builder.CreateStructGEP(
8664       VAListAddr, 1, "__saved_reg_area_end_pointer_p");
8665   llvm::Value *__saved_reg_area_end_pointer = CGF.Builder.CreateLoad(
8666       __saved_reg_area_end_pointer_p, "__saved_reg_area_end_pointer");
8667 
8668   // If the size of argument is > 4 bytes, check if the stack
8669   // location is aligned to 8 bytes
8670   if (ArgAlign > 4) {
8671 
8672     llvm::Value *__current_saved_reg_area_pointer_int =
8673         CGF.Builder.CreatePtrToInt(__current_saved_reg_area_pointer,
8674                                    CGF.Int32Ty);
8675 
8676     __current_saved_reg_area_pointer_int = CGF.Builder.CreateAdd(
8677         __current_saved_reg_area_pointer_int,
8678         llvm::ConstantInt::get(CGF.Int32Ty, (ArgAlign - 1)),
8679         "align_current_saved_reg_area_pointer");
8680 
8681     __current_saved_reg_area_pointer_int =
8682         CGF.Builder.CreateAnd(__current_saved_reg_area_pointer_int,
8683                               llvm::ConstantInt::get(CGF.Int32Ty, -ArgAlign),
8684                               "align_current_saved_reg_area_pointer");
8685 
8686     __current_saved_reg_area_pointer =
8687         CGF.Builder.CreateIntToPtr(__current_saved_reg_area_pointer_int,
8688                                    __current_saved_reg_area_pointer->getType(),
8689                                    "align_current_saved_reg_area_pointer");
8690   }
8691 
8692   llvm::Value *__new_saved_reg_area_pointer =
8693       CGF.Builder.CreateGEP(CGF.Int8Ty, __current_saved_reg_area_pointer,
8694                             llvm::ConstantInt::get(CGF.Int32Ty, ArgSize),
8695                             "__new_saved_reg_area_pointer");
8696 
8697   llvm::Value *UsingStack = nullptr;
8698   UsingStack = CGF.Builder.CreateICmpSGT(__new_saved_reg_area_pointer,
8699                                          __saved_reg_area_end_pointer);
8700 
8701   CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, InRegBlock);
8702 
8703   // Argument in saved register area
8704   // Implement the block where argument is in register saved area
8705   CGF.EmitBlock(InRegBlock);
8706 
8707   llvm::Type *PTy = CGF.ConvertType(Ty);
8708   llvm::Value *__saved_reg_area_p = CGF.Builder.CreateBitCast(
8709       __current_saved_reg_area_pointer, llvm::PointerType::getUnqual(PTy));
8710 
8711   CGF.Builder.CreateStore(__new_saved_reg_area_pointer,
8712                           __current_saved_reg_area_pointer_p);
8713 
8714   CGF.EmitBranch(ContBlock);
8715 
8716   // Argument in overflow area
8717   // Implement the block where the argument is in overflow area.
8718   CGF.EmitBlock(OnStackBlock);
8719 
8720   // Load the overflow area pointer
8721   Address __overflow_area_pointer_p =
8722       CGF.Builder.CreateStructGEP(VAListAddr, 2, "__overflow_area_pointer_p");
8723   llvm::Value *__overflow_area_pointer = CGF.Builder.CreateLoad(
8724       __overflow_area_pointer_p, "__overflow_area_pointer");
8725 
8726   // Align the overflow area pointer according to the alignment of the argument
8727   if (ArgAlign > 4) {
8728     llvm::Value *__overflow_area_pointer_int =
8729         CGF.Builder.CreatePtrToInt(__overflow_area_pointer, CGF.Int32Ty);
8730 
8731     __overflow_area_pointer_int =
8732         CGF.Builder.CreateAdd(__overflow_area_pointer_int,
8733                               llvm::ConstantInt::get(CGF.Int32Ty, ArgAlign - 1),
8734                               "align_overflow_area_pointer");
8735 
8736     __overflow_area_pointer_int =
8737         CGF.Builder.CreateAnd(__overflow_area_pointer_int,
8738                               llvm::ConstantInt::get(CGF.Int32Ty, -ArgAlign),
8739                               "align_overflow_area_pointer");
8740 
8741     __overflow_area_pointer = CGF.Builder.CreateIntToPtr(
8742         __overflow_area_pointer_int, __overflow_area_pointer->getType(),
8743         "align_overflow_area_pointer");
8744   }
8745 
8746   // Get the pointer for next argument in overflow area and store it
8747   // to overflow area pointer.
8748   llvm::Value *__new_overflow_area_pointer = CGF.Builder.CreateGEP(
8749       CGF.Int8Ty, __overflow_area_pointer,
8750       llvm::ConstantInt::get(CGF.Int32Ty, ArgSize),
8751       "__overflow_area_pointer.next");
8752 
8753   CGF.Builder.CreateStore(__new_overflow_area_pointer,
8754                           __overflow_area_pointer_p);
8755 
8756   CGF.Builder.CreateStore(__new_overflow_area_pointer,
8757                           __current_saved_reg_area_pointer_p);
8758 
8759   // Bitcast the overflow area pointer to the type of argument.
8760   llvm::Type *OverflowPTy = CGF.ConvertTypeForMem(Ty);
8761   llvm::Value *__overflow_area_p = CGF.Builder.CreateBitCast(
8762       __overflow_area_pointer, llvm::PointerType::getUnqual(OverflowPTy));
8763 
8764   CGF.EmitBranch(ContBlock);
8765 
8766   // Get the correct pointer to load the variable argument
8767   // Implement the ContBlock
8768   CGF.EmitBlock(ContBlock);
8769 
8770   llvm::Type *MemPTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
8771   llvm::PHINode *ArgAddr = CGF.Builder.CreatePHI(MemPTy, 2, "vaarg.addr");
8772   ArgAddr->addIncoming(__saved_reg_area_p, InRegBlock);
8773   ArgAddr->addIncoming(__overflow_area_p, OnStackBlock);
8774 
8775   return Address(ArgAddr, CharUnits::fromQuantity(ArgAlign));
8776 }
8777 
8778 Address HexagonABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8779                                   QualType Ty) const {
8780 
8781   if (getTarget().getTriple().isMusl())
8782     return EmitVAArgForHexagonLinux(CGF, VAListAddr, Ty);
8783 
8784   return EmitVAArgForHexagon(CGF, VAListAddr, Ty);
8785 }
8786 
8787 //===----------------------------------------------------------------------===//
8788 // Lanai ABI Implementation
8789 //===----------------------------------------------------------------------===//
8790 
8791 namespace {
8792 class LanaiABIInfo : public DefaultABIInfo {
8793 public:
8794   LanaiABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
8795 
8796   bool shouldUseInReg(QualType Ty, CCState &State) const;
8797 
8798   void computeInfo(CGFunctionInfo &FI) const override {
8799     CCState State(FI);
8800     // Lanai uses 4 registers to pass arguments unless the function has the
8801     // regparm attribute set.
8802     if (FI.getHasRegParm()) {
8803       State.FreeRegs = FI.getRegParm();
8804     } else {
8805       State.FreeRegs = 4;
8806     }
8807 
8808     if (!getCXXABI().classifyReturnType(FI))
8809       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
8810     for (auto &I : FI.arguments())
8811       I.info = classifyArgumentType(I.type, State);
8812   }
8813 
8814   ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
8815   ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
8816 };
8817 } // end anonymous namespace
8818 
8819 bool LanaiABIInfo::shouldUseInReg(QualType Ty, CCState &State) const {
8820   unsigned Size = getContext().getTypeSize(Ty);
8821   unsigned SizeInRegs = llvm::alignTo(Size, 32U) / 32U;
8822 
8823   if (SizeInRegs == 0)
8824     return false;
8825 
8826   if (SizeInRegs > State.FreeRegs) {
8827     State.FreeRegs = 0;
8828     return false;
8829   }
8830 
8831   State.FreeRegs -= SizeInRegs;
8832 
8833   return true;
8834 }
8835 
8836 ABIArgInfo LanaiABIInfo::getIndirectResult(QualType Ty, bool ByVal,
8837                                            CCState &State) const {
8838   if (!ByVal) {
8839     if (State.FreeRegs) {
8840       --State.FreeRegs; // Non-byval indirects just use one pointer.
8841       return getNaturalAlignIndirectInReg(Ty);
8842     }
8843     return getNaturalAlignIndirect(Ty, false);
8844   }
8845 
8846   // Compute the byval alignment.
8847   const unsigned MinABIStackAlignInBytes = 4;
8848   unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
8849   return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true,
8850                                  /*Realign=*/TypeAlign >
8851                                      MinABIStackAlignInBytes);
8852 }
8853 
8854 ABIArgInfo LanaiABIInfo::classifyArgumentType(QualType Ty,
8855                                               CCState &State) const {
8856   // Check with the C++ ABI first.
8857   const RecordType *RT = Ty->getAs<RecordType>();
8858   if (RT) {
8859     CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
8860     if (RAA == CGCXXABI::RAA_Indirect) {
8861       return getIndirectResult(Ty, /*ByVal=*/false, State);
8862     } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
8863       return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
8864     }
8865   }
8866 
8867   if (isAggregateTypeForABI(Ty)) {
8868     // Structures with flexible arrays are always indirect.
8869     if (RT && RT->getDecl()->hasFlexibleArrayMember())
8870       return getIndirectResult(Ty, /*ByVal=*/true, State);
8871 
8872     // Ignore empty structs/unions.
8873     if (isEmptyRecord(getContext(), Ty, true))
8874       return ABIArgInfo::getIgnore();
8875 
8876     llvm::LLVMContext &LLVMContext = getVMContext();
8877     unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
8878     if (SizeInRegs <= State.FreeRegs) {
8879       llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
8880       SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32);
8881       llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
8882       State.FreeRegs -= SizeInRegs;
8883       return ABIArgInfo::getDirectInReg(Result);
8884     } else {
8885       State.FreeRegs = 0;
8886     }
8887     return getIndirectResult(Ty, true, State);
8888   }
8889 
8890   // Treat an enum type as its underlying type.
8891   if (const auto *EnumTy = Ty->getAs<EnumType>())
8892     Ty = EnumTy->getDecl()->getIntegerType();
8893 
8894   bool InReg = shouldUseInReg(Ty, State);
8895 
8896   // Don't pass >64 bit integers in registers.
8897   if (const auto *EIT = Ty->getAs<BitIntType>())
8898     if (EIT->getNumBits() > 64)
8899       return getIndirectResult(Ty, /*ByVal=*/true, State);
8900 
8901   if (isPromotableIntegerTypeForABI(Ty)) {
8902     if (InReg)
8903       return ABIArgInfo::getDirectInReg();
8904     return ABIArgInfo::getExtend(Ty);
8905   }
8906   if (InReg)
8907     return ABIArgInfo::getDirectInReg();
8908   return ABIArgInfo::getDirect();
8909 }
8910 
8911 namespace {
8912 class LanaiTargetCodeGenInfo : public TargetCodeGenInfo {
8913 public:
8914   LanaiTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
8915       : TargetCodeGenInfo(std::make_unique<LanaiABIInfo>(CGT)) {}
8916 };
8917 }
8918 
8919 //===----------------------------------------------------------------------===//
8920 // AMDGPU ABI Implementation
8921 //===----------------------------------------------------------------------===//
8922 
8923 namespace {
8924 
8925 class AMDGPUABIInfo final : public DefaultABIInfo {
8926 private:
8927   static const unsigned MaxNumRegsForArgsRet = 16;
8928 
8929   unsigned numRegsForType(QualType Ty) const;
8930 
8931   bool isHomogeneousAggregateBaseType(QualType Ty) const override;
8932   bool isHomogeneousAggregateSmallEnough(const Type *Base,
8933                                          uint64_t Members) const override;
8934 
8935   // Coerce HIP scalar pointer arguments from generic pointers to global ones.
8936   llvm::Type *coerceKernelArgumentType(llvm::Type *Ty, unsigned FromAS,
8937                                        unsigned ToAS) const {
8938     // Single value types.
8939     auto *PtrTy = llvm::dyn_cast<llvm::PointerType>(Ty);
8940     if (PtrTy && PtrTy->getAddressSpace() == FromAS)
8941       return llvm::PointerType::getWithSamePointeeType(PtrTy, ToAS);
8942     return Ty;
8943   }
8944 
8945 public:
8946   explicit AMDGPUABIInfo(CodeGen::CodeGenTypes &CGT) :
8947     DefaultABIInfo(CGT) {}
8948 
8949   ABIArgInfo classifyReturnType(QualType RetTy) const;
8950   ABIArgInfo classifyKernelArgumentType(QualType Ty) const;
8951   ABIArgInfo classifyArgumentType(QualType Ty, unsigned &NumRegsLeft) const;
8952 
8953   void computeInfo(CGFunctionInfo &FI) const override;
8954   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8955                     QualType Ty) const override;
8956 };
8957 
8958 bool AMDGPUABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
8959   return true;
8960 }
8961 
8962 bool AMDGPUABIInfo::isHomogeneousAggregateSmallEnough(
8963   const Type *Base, uint64_t Members) const {
8964   uint32_t NumRegs = (getContext().getTypeSize(Base) + 31) / 32;
8965 
8966   // Homogeneous Aggregates may occupy at most 16 registers.
8967   return Members * NumRegs <= MaxNumRegsForArgsRet;
8968 }
8969 
8970 /// Estimate number of registers the type will use when passed in registers.
8971 unsigned AMDGPUABIInfo::numRegsForType(QualType Ty) const {
8972   unsigned NumRegs = 0;
8973 
8974   if (const VectorType *VT = Ty->getAs<VectorType>()) {
8975     // Compute from the number of elements. The reported size is based on the
8976     // in-memory size, which includes the padding 4th element for 3-vectors.
8977     QualType EltTy = VT->getElementType();
8978     unsigned EltSize = getContext().getTypeSize(EltTy);
8979 
8980     // 16-bit element vectors should be passed as packed.
8981     if (EltSize == 16)
8982       return (VT->getNumElements() + 1) / 2;
8983 
8984     unsigned EltNumRegs = (EltSize + 31) / 32;
8985     return EltNumRegs * VT->getNumElements();
8986   }
8987 
8988   if (const RecordType *RT = Ty->getAs<RecordType>()) {
8989     const RecordDecl *RD = RT->getDecl();
8990     assert(!RD->hasFlexibleArrayMember());
8991 
8992     for (const FieldDecl *Field : RD->fields()) {
8993       QualType FieldTy = Field->getType();
8994       NumRegs += numRegsForType(FieldTy);
8995     }
8996 
8997     return NumRegs;
8998   }
8999 
9000   return (getContext().getTypeSize(Ty) + 31) / 32;
9001 }
9002 
9003 void AMDGPUABIInfo::computeInfo(CGFunctionInfo &FI) const {
9004   llvm::CallingConv::ID CC = FI.getCallingConvention();
9005 
9006   if (!getCXXABI().classifyReturnType(FI))
9007     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
9008 
9009   unsigned NumRegsLeft = MaxNumRegsForArgsRet;
9010   for (auto &Arg : FI.arguments()) {
9011     if (CC == llvm::CallingConv::AMDGPU_KERNEL) {
9012       Arg.info = classifyKernelArgumentType(Arg.type);
9013     } else {
9014       Arg.info = classifyArgumentType(Arg.type, NumRegsLeft);
9015     }
9016   }
9017 }
9018 
9019 Address AMDGPUABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9020                                  QualType Ty) const {
9021   llvm_unreachable("AMDGPU does not support varargs");
9022 }
9023 
9024 ABIArgInfo AMDGPUABIInfo::classifyReturnType(QualType RetTy) const {
9025   if (isAggregateTypeForABI(RetTy)) {
9026     // Records with non-trivial destructors/copy-constructors should not be
9027     // returned by value.
9028     if (!getRecordArgABI(RetTy, getCXXABI())) {
9029       // Ignore empty structs/unions.
9030       if (isEmptyRecord(getContext(), RetTy, true))
9031         return ABIArgInfo::getIgnore();
9032 
9033       // Lower single-element structs to just return a regular value.
9034       if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
9035         return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
9036 
9037       if (const RecordType *RT = RetTy->getAs<RecordType>()) {
9038         const RecordDecl *RD = RT->getDecl();
9039         if (RD->hasFlexibleArrayMember())
9040           return DefaultABIInfo::classifyReturnType(RetTy);
9041       }
9042 
9043       // Pack aggregates <= 4 bytes into single VGPR or pair.
9044       uint64_t Size = getContext().getTypeSize(RetTy);
9045       if (Size <= 16)
9046         return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
9047 
9048       if (Size <= 32)
9049         return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
9050 
9051       if (Size <= 64) {
9052         llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext());
9053         return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2));
9054       }
9055 
9056       if (numRegsForType(RetTy) <= MaxNumRegsForArgsRet)
9057         return ABIArgInfo::getDirect();
9058     }
9059   }
9060 
9061   // Otherwise just do the default thing.
9062   return DefaultABIInfo::classifyReturnType(RetTy);
9063 }
9064 
9065 /// For kernels all parameters are really passed in a special buffer. It doesn't
9066 /// make sense to pass anything byval, so everything must be direct.
9067 ABIArgInfo AMDGPUABIInfo::classifyKernelArgumentType(QualType Ty) const {
9068   Ty = useFirstFieldIfTransparentUnion(Ty);
9069 
9070   // TODO: Can we omit empty structs?
9071 
9072   if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
9073     Ty = QualType(SeltTy, 0);
9074 
9075   llvm::Type *OrigLTy = CGT.ConvertType(Ty);
9076   llvm::Type *LTy = OrigLTy;
9077   if (getContext().getLangOpts().HIP) {
9078     LTy = coerceKernelArgumentType(
9079         OrigLTy, /*FromAS=*/getContext().getTargetAddressSpace(LangAS::Default),
9080         /*ToAS=*/getContext().getTargetAddressSpace(LangAS::cuda_device));
9081   }
9082 
9083   // FIXME: Should also use this for OpenCL, but it requires addressing the
9084   // problem of kernels being called.
9085   //
9086   // FIXME: This doesn't apply the optimization of coercing pointers in structs
9087   // to global address space when using byref. This would require implementing a
9088   // new kind of coercion of the in-memory type when for indirect arguments.
9089   if (!getContext().getLangOpts().OpenCL && LTy == OrigLTy &&
9090       isAggregateTypeForABI(Ty)) {
9091     return ABIArgInfo::getIndirectAliased(
9092         getContext().getTypeAlignInChars(Ty),
9093         getContext().getTargetAddressSpace(LangAS::opencl_constant),
9094         false /*Realign*/, nullptr /*Padding*/);
9095   }
9096 
9097   // If we set CanBeFlattened to true, CodeGen will expand the struct to its
9098   // individual elements, which confuses the Clover OpenCL backend; therefore we
9099   // have to set it to false here. Other args of getDirect() are just defaults.
9100   return ABIArgInfo::getDirect(LTy, 0, nullptr, false);
9101 }
9102 
9103 ABIArgInfo AMDGPUABIInfo::classifyArgumentType(QualType Ty,
9104                                                unsigned &NumRegsLeft) const {
9105   assert(NumRegsLeft <= MaxNumRegsForArgsRet && "register estimate underflow");
9106 
9107   Ty = useFirstFieldIfTransparentUnion(Ty);
9108 
9109   if (isAggregateTypeForABI(Ty)) {
9110     // Records with non-trivial destructors/copy-constructors should not be
9111     // passed by value.
9112     if (auto RAA = getRecordArgABI(Ty, getCXXABI()))
9113       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
9114 
9115     // Ignore empty structs/unions.
9116     if (isEmptyRecord(getContext(), Ty, true))
9117       return ABIArgInfo::getIgnore();
9118 
9119     // Lower single-element structs to just pass a regular value. TODO: We
9120     // could do reasonable-size multiple-element structs too, using getExpand(),
9121     // though watch out for things like bitfields.
9122     if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
9123       return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
9124 
9125     if (const RecordType *RT = Ty->getAs<RecordType>()) {
9126       const RecordDecl *RD = RT->getDecl();
9127       if (RD->hasFlexibleArrayMember())
9128         return DefaultABIInfo::classifyArgumentType(Ty);
9129     }
9130 
9131     // Pack aggregates <= 8 bytes into single VGPR or pair.
9132     uint64_t Size = getContext().getTypeSize(Ty);
9133     if (Size <= 64) {
9134       unsigned NumRegs = (Size + 31) / 32;
9135       NumRegsLeft -= std::min(NumRegsLeft, NumRegs);
9136 
9137       if (Size <= 16)
9138         return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
9139 
9140       if (Size <= 32)
9141         return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
9142 
9143       // XXX: Should this be i64 instead, and should the limit increase?
9144       llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext());
9145       return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2));
9146     }
9147 
9148     if (NumRegsLeft > 0) {
9149       unsigned NumRegs = numRegsForType(Ty);
9150       if (NumRegsLeft >= NumRegs) {
9151         NumRegsLeft -= NumRegs;
9152         return ABIArgInfo::getDirect();
9153       }
9154     }
9155   }
9156 
9157   // Otherwise just do the default thing.
9158   ABIArgInfo ArgInfo = DefaultABIInfo::classifyArgumentType(Ty);
9159   if (!ArgInfo.isIndirect()) {
9160     unsigned NumRegs = numRegsForType(Ty);
9161     NumRegsLeft -= std::min(NumRegs, NumRegsLeft);
9162   }
9163 
9164   return ArgInfo;
9165 }
9166 
9167 class AMDGPUTargetCodeGenInfo : public TargetCodeGenInfo {
9168 public:
9169   AMDGPUTargetCodeGenInfo(CodeGenTypes &CGT)
9170       : TargetCodeGenInfo(std::make_unique<AMDGPUABIInfo>(CGT)) {}
9171 
9172   void setFunctionDeclAttributes(const FunctionDecl *FD, llvm::Function *F,
9173                                  CodeGenModule &CGM) const;
9174 
9175   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
9176                            CodeGen::CodeGenModule &M) const override;
9177   unsigned getOpenCLKernelCallingConv() const override;
9178 
9179   llvm::Constant *getNullPointer(const CodeGen::CodeGenModule &CGM,
9180       llvm::PointerType *T, QualType QT) const override;
9181 
9182   LangAS getASTAllocaAddressSpace() const override {
9183     return getLangASFromTargetAS(
9184         getABIInfo().getDataLayout().getAllocaAddrSpace());
9185   }
9186   LangAS getGlobalVarAddressSpace(CodeGenModule &CGM,
9187                                   const VarDecl *D) const override;
9188   llvm::SyncScope::ID getLLVMSyncScopeID(const LangOptions &LangOpts,
9189                                          SyncScope Scope,
9190                                          llvm::AtomicOrdering Ordering,
9191                                          llvm::LLVMContext &Ctx) const override;
9192   llvm::Function *
9193   createEnqueuedBlockKernel(CodeGenFunction &CGF,
9194                             llvm::Function *BlockInvokeFunc,
9195                             llvm::Value *BlockLiteral) const override;
9196   bool shouldEmitStaticExternCAliases() const override;
9197   void setCUDAKernelCallingConvention(const FunctionType *&FT) const override;
9198 };
9199 }
9200 
9201 static bool requiresAMDGPUProtectedVisibility(const Decl *D,
9202                                               llvm::GlobalValue *GV) {
9203   if (GV->getVisibility() != llvm::GlobalValue::HiddenVisibility)
9204     return false;
9205 
9206   return D->hasAttr<OpenCLKernelAttr>() ||
9207          (isa<FunctionDecl>(D) && D->hasAttr<CUDAGlobalAttr>()) ||
9208          (isa<VarDecl>(D) &&
9209           (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>() ||
9210            cast<VarDecl>(D)->getType()->isCUDADeviceBuiltinSurfaceType() ||
9211            cast<VarDecl>(D)->getType()->isCUDADeviceBuiltinTextureType()));
9212 }
9213 
9214 void AMDGPUTargetCodeGenInfo::setFunctionDeclAttributes(
9215     const FunctionDecl *FD, llvm::Function *F, CodeGenModule &M) const {
9216   const auto *ReqdWGS =
9217       M.getLangOpts().OpenCL ? FD->getAttr<ReqdWorkGroupSizeAttr>() : nullptr;
9218   const bool IsOpenCLKernel =
9219       M.getLangOpts().OpenCL && FD->hasAttr<OpenCLKernelAttr>();
9220   const bool IsHIPKernel = M.getLangOpts().HIP && FD->hasAttr<CUDAGlobalAttr>();
9221 
9222   const auto *FlatWGS = FD->getAttr<AMDGPUFlatWorkGroupSizeAttr>();
9223   if (ReqdWGS || FlatWGS) {
9224     unsigned Min = 0;
9225     unsigned Max = 0;
9226     if (FlatWGS) {
9227       Min = FlatWGS->getMin()
9228                 ->EvaluateKnownConstInt(M.getContext())
9229                 .getExtValue();
9230       Max = FlatWGS->getMax()
9231                 ->EvaluateKnownConstInt(M.getContext())
9232                 .getExtValue();
9233     }
9234     if (ReqdWGS && Min == 0 && Max == 0)
9235       Min = Max = ReqdWGS->getXDim() * ReqdWGS->getYDim() * ReqdWGS->getZDim();
9236 
9237     if (Min != 0) {
9238       assert(Min <= Max && "Min must be less than or equal Max");
9239 
9240       std::string AttrVal = llvm::utostr(Min) + "," + llvm::utostr(Max);
9241       F->addFnAttr("amdgpu-flat-work-group-size", AttrVal);
9242     } else
9243       assert(Max == 0 && "Max must be zero");
9244   } else if (IsOpenCLKernel || IsHIPKernel) {
9245     // By default, restrict the maximum size to a value specified by
9246     // --gpu-max-threads-per-block=n or its default value for HIP.
9247     const unsigned OpenCLDefaultMaxWorkGroupSize = 256;
9248     const unsigned DefaultMaxWorkGroupSize =
9249         IsOpenCLKernel ? OpenCLDefaultMaxWorkGroupSize
9250                        : M.getLangOpts().GPUMaxThreadsPerBlock;
9251     std::string AttrVal =
9252         std::string("1,") + llvm::utostr(DefaultMaxWorkGroupSize);
9253     F->addFnAttr("amdgpu-flat-work-group-size", AttrVal);
9254   }
9255 
9256   if (const auto *Attr = FD->getAttr<AMDGPUWavesPerEUAttr>()) {
9257     unsigned Min =
9258         Attr->getMin()->EvaluateKnownConstInt(M.getContext()).getExtValue();
9259     unsigned Max = Attr->getMax() ? Attr->getMax()
9260                                         ->EvaluateKnownConstInt(M.getContext())
9261                                         .getExtValue()
9262                                   : 0;
9263 
9264     if (Min != 0) {
9265       assert((Max == 0 || Min <= Max) && "Min must be less than or equal Max");
9266 
9267       std::string AttrVal = llvm::utostr(Min);
9268       if (Max != 0)
9269         AttrVal = AttrVal + "," + llvm::utostr(Max);
9270       F->addFnAttr("amdgpu-waves-per-eu", AttrVal);
9271     } else
9272       assert(Max == 0 && "Max must be zero");
9273   }
9274 
9275   if (const auto *Attr = FD->getAttr<AMDGPUNumSGPRAttr>()) {
9276     unsigned NumSGPR = Attr->getNumSGPR();
9277 
9278     if (NumSGPR != 0)
9279       F->addFnAttr("amdgpu-num-sgpr", llvm::utostr(NumSGPR));
9280   }
9281 
9282   if (const auto *Attr = FD->getAttr<AMDGPUNumVGPRAttr>()) {
9283     uint32_t NumVGPR = Attr->getNumVGPR();
9284 
9285     if (NumVGPR != 0)
9286       F->addFnAttr("amdgpu-num-vgpr", llvm::utostr(NumVGPR));
9287   }
9288 }
9289 
9290 void AMDGPUTargetCodeGenInfo::setTargetAttributes(
9291     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
9292   if (requiresAMDGPUProtectedVisibility(D, GV)) {
9293     GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
9294     GV->setDSOLocal(true);
9295   }
9296 
9297   if (GV->isDeclaration())
9298     return;
9299 
9300   llvm::Function *F = dyn_cast<llvm::Function>(GV);
9301   if (!F)
9302     return;
9303 
9304   const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
9305   if (FD)
9306     setFunctionDeclAttributes(FD, F, M);
9307 
9308   const bool IsHIPKernel =
9309       M.getLangOpts().HIP && FD && FD->hasAttr<CUDAGlobalAttr>();
9310 
9311   if (IsHIPKernel)
9312     F->addFnAttr("uniform-work-group-size", "true");
9313 
9314   if (M.getContext().getTargetInfo().allowAMDGPUUnsafeFPAtomics())
9315     F->addFnAttr("amdgpu-unsafe-fp-atomics", "true");
9316 
9317   if (!getABIInfo().getCodeGenOpts().EmitIEEENaNCompliantInsts)
9318     F->addFnAttr("amdgpu-ieee", "false");
9319 }
9320 
9321 unsigned AMDGPUTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
9322   return llvm::CallingConv::AMDGPU_KERNEL;
9323 }
9324 
9325 // Currently LLVM assumes null pointers always have value 0,
9326 // which results in incorrectly transformed IR. Therefore, instead of
9327 // emitting null pointers in private and local address spaces, a null
9328 // pointer in generic address space is emitted which is casted to a
9329 // pointer in local or private address space.
9330 llvm::Constant *AMDGPUTargetCodeGenInfo::getNullPointer(
9331     const CodeGen::CodeGenModule &CGM, llvm::PointerType *PT,
9332     QualType QT) const {
9333   if (CGM.getContext().getTargetNullPointerValue(QT) == 0)
9334     return llvm::ConstantPointerNull::get(PT);
9335 
9336   auto &Ctx = CGM.getContext();
9337   auto NPT = llvm::PointerType::getWithSamePointeeType(
9338       PT, Ctx.getTargetAddressSpace(LangAS::opencl_generic));
9339   return llvm::ConstantExpr::getAddrSpaceCast(
9340       llvm::ConstantPointerNull::get(NPT), PT);
9341 }
9342 
9343 LangAS
9344 AMDGPUTargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM,
9345                                                   const VarDecl *D) const {
9346   assert(!CGM.getLangOpts().OpenCL &&
9347          !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) &&
9348          "Address space agnostic languages only");
9349   LangAS DefaultGlobalAS = getLangASFromTargetAS(
9350       CGM.getContext().getTargetAddressSpace(LangAS::opencl_global));
9351   if (!D)
9352     return DefaultGlobalAS;
9353 
9354   LangAS AddrSpace = D->getType().getAddressSpace();
9355   assert(AddrSpace == LangAS::Default || isTargetAddressSpace(AddrSpace));
9356   if (AddrSpace != LangAS::Default)
9357     return AddrSpace;
9358 
9359   // Only promote to address space 4 if VarDecl has constant initialization.
9360   if (CGM.isTypeConstant(D->getType(), false) &&
9361       D->hasConstantInitialization()) {
9362     if (auto ConstAS = CGM.getTarget().getConstantAddressSpace())
9363       return ConstAS.getValue();
9364   }
9365   return DefaultGlobalAS;
9366 }
9367 
9368 llvm::SyncScope::ID
9369 AMDGPUTargetCodeGenInfo::getLLVMSyncScopeID(const LangOptions &LangOpts,
9370                                             SyncScope Scope,
9371                                             llvm::AtomicOrdering Ordering,
9372                                             llvm::LLVMContext &Ctx) const {
9373   std::string Name;
9374   switch (Scope) {
9375   case SyncScope::HIPSingleThread:
9376     Name = "singlethread";
9377     break;
9378   case SyncScope::HIPWavefront:
9379   case SyncScope::OpenCLSubGroup:
9380     Name = "wavefront";
9381     break;
9382   case SyncScope::HIPWorkgroup:
9383   case SyncScope::OpenCLWorkGroup:
9384     Name = "workgroup";
9385     break;
9386   case SyncScope::HIPAgent:
9387   case SyncScope::OpenCLDevice:
9388     Name = "agent";
9389     break;
9390   case SyncScope::HIPSystem:
9391   case SyncScope::OpenCLAllSVMDevices:
9392     Name = "";
9393     break;
9394   }
9395 
9396   if (Ordering != llvm::AtomicOrdering::SequentiallyConsistent) {
9397     if (!Name.empty())
9398       Name = Twine(Twine(Name) + Twine("-")).str();
9399 
9400     Name = Twine(Twine(Name) + Twine("one-as")).str();
9401   }
9402 
9403   return Ctx.getOrInsertSyncScopeID(Name);
9404 }
9405 
9406 bool AMDGPUTargetCodeGenInfo::shouldEmitStaticExternCAliases() const {
9407   return false;
9408 }
9409 
9410 void AMDGPUTargetCodeGenInfo::setCUDAKernelCallingConvention(
9411     const FunctionType *&FT) const {
9412   FT = getABIInfo().getContext().adjustFunctionType(
9413       FT, FT->getExtInfo().withCallingConv(CC_OpenCLKernel));
9414 }
9415 
9416 //===----------------------------------------------------------------------===//
9417 // SPARC v8 ABI Implementation.
9418 // Based on the SPARC Compliance Definition version 2.4.1.
9419 //
9420 // Ensures that complex values are passed in registers.
9421 //
9422 namespace {
9423 class SparcV8ABIInfo : public DefaultABIInfo {
9424 public:
9425   SparcV8ABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
9426 
9427 private:
9428   ABIArgInfo classifyReturnType(QualType RetTy) const;
9429   void computeInfo(CGFunctionInfo &FI) const override;
9430 };
9431 } // end anonymous namespace
9432 
9433 
9434 ABIArgInfo
9435 SparcV8ABIInfo::classifyReturnType(QualType Ty) const {
9436   if (Ty->isAnyComplexType()) {
9437     return ABIArgInfo::getDirect();
9438   }
9439   else {
9440     return DefaultABIInfo::classifyReturnType(Ty);
9441   }
9442 }
9443 
9444 void SparcV8ABIInfo::computeInfo(CGFunctionInfo &FI) const {
9445 
9446   FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
9447   for (auto &Arg : FI.arguments())
9448     Arg.info = classifyArgumentType(Arg.type);
9449 }
9450 
9451 namespace {
9452 class SparcV8TargetCodeGenInfo : public TargetCodeGenInfo {
9453 public:
9454   SparcV8TargetCodeGenInfo(CodeGenTypes &CGT)
9455       : TargetCodeGenInfo(std::make_unique<SparcV8ABIInfo>(CGT)) {}
9456 };
9457 } // end anonymous namespace
9458 
9459 //===----------------------------------------------------------------------===//
9460 // SPARC v9 ABI Implementation.
9461 // Based on the SPARC Compliance Definition version 2.4.1.
9462 //
9463 // Function arguments a mapped to a nominal "parameter array" and promoted to
9464 // registers depending on their type. Each argument occupies 8 or 16 bytes in
9465 // the array, structs larger than 16 bytes are passed indirectly.
9466 //
9467 // One case requires special care:
9468 //
9469 //   struct mixed {
9470 //     int i;
9471 //     float f;
9472 //   };
9473 //
9474 // When a struct mixed is passed by value, it only occupies 8 bytes in the
9475 // parameter array, but the int is passed in an integer register, and the float
9476 // is passed in a floating point register. This is represented as two arguments
9477 // with the LLVM IR inreg attribute:
9478 //
9479 //   declare void f(i32 inreg %i, float inreg %f)
9480 //
9481 // The code generator will only allocate 4 bytes from the parameter array for
9482 // the inreg arguments. All other arguments are allocated a multiple of 8
9483 // bytes.
9484 //
9485 namespace {
9486 class SparcV9ABIInfo : public ABIInfo {
9487 public:
9488   SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
9489 
9490 private:
9491   ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
9492   void computeInfo(CGFunctionInfo &FI) const override;
9493   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9494                     QualType Ty) const override;
9495 
9496   // Coercion type builder for structs passed in registers. The coercion type
9497   // serves two purposes:
9498   //
9499   // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
9500   //    in registers.
9501   // 2. Expose aligned floating point elements as first-level elements, so the
9502   //    code generator knows to pass them in floating point registers.
9503   //
9504   // We also compute the InReg flag which indicates that the struct contains
9505   // aligned 32-bit floats.
9506   //
9507   struct CoerceBuilder {
9508     llvm::LLVMContext &Context;
9509     const llvm::DataLayout &DL;
9510     SmallVector<llvm::Type*, 8> Elems;
9511     uint64_t Size;
9512     bool InReg;
9513 
9514     CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
9515       : Context(c), DL(dl), Size(0), InReg(false) {}
9516 
9517     // Pad Elems with integers until Size is ToSize.
9518     void pad(uint64_t ToSize) {
9519       assert(ToSize >= Size && "Cannot remove elements");
9520       if (ToSize == Size)
9521         return;
9522 
9523       // Finish the current 64-bit word.
9524       uint64_t Aligned = llvm::alignTo(Size, 64);
9525       if (Aligned > Size && Aligned <= ToSize) {
9526         Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
9527         Size = Aligned;
9528       }
9529 
9530       // Add whole 64-bit words.
9531       while (Size + 64 <= ToSize) {
9532         Elems.push_back(llvm::Type::getInt64Ty(Context));
9533         Size += 64;
9534       }
9535 
9536       // Final in-word padding.
9537       if (Size < ToSize) {
9538         Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
9539         Size = ToSize;
9540       }
9541     }
9542 
9543     // Add a floating point element at Offset.
9544     void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
9545       // Unaligned floats are treated as integers.
9546       if (Offset % Bits)
9547         return;
9548       // The InReg flag is only required if there are any floats < 64 bits.
9549       if (Bits < 64)
9550         InReg = true;
9551       pad(Offset);
9552       Elems.push_back(Ty);
9553       Size = Offset + Bits;
9554     }
9555 
9556     // Add a struct type to the coercion type, starting at Offset (in bits).
9557     void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
9558       const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
9559       for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
9560         llvm::Type *ElemTy = StrTy->getElementType(i);
9561         uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
9562         switch (ElemTy->getTypeID()) {
9563         case llvm::Type::StructTyID:
9564           addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
9565           break;
9566         case llvm::Type::FloatTyID:
9567           addFloat(ElemOffset, ElemTy, 32);
9568           break;
9569         case llvm::Type::DoubleTyID:
9570           addFloat(ElemOffset, ElemTy, 64);
9571           break;
9572         case llvm::Type::FP128TyID:
9573           addFloat(ElemOffset, ElemTy, 128);
9574           break;
9575         case llvm::Type::PointerTyID:
9576           if (ElemOffset % 64 == 0) {
9577             pad(ElemOffset);
9578             Elems.push_back(ElemTy);
9579             Size += 64;
9580           }
9581           break;
9582         default:
9583           break;
9584         }
9585       }
9586     }
9587 
9588     // Check if Ty is a usable substitute for the coercion type.
9589     bool isUsableType(llvm::StructType *Ty) const {
9590       return llvm::makeArrayRef(Elems) == Ty->elements();
9591     }
9592 
9593     // Get the coercion type as a literal struct type.
9594     llvm::Type *getType() const {
9595       if (Elems.size() == 1)
9596         return Elems.front();
9597       else
9598         return llvm::StructType::get(Context, Elems);
9599     }
9600   };
9601 };
9602 } // end anonymous namespace
9603 
9604 ABIArgInfo
9605 SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
9606   if (Ty->isVoidType())
9607     return ABIArgInfo::getIgnore();
9608 
9609   uint64_t Size = getContext().getTypeSize(Ty);
9610 
9611   // Anything too big to fit in registers is passed with an explicit indirect
9612   // pointer / sret pointer.
9613   if (Size > SizeLimit)
9614     return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
9615 
9616   // Treat an enum type as its underlying type.
9617   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
9618     Ty = EnumTy->getDecl()->getIntegerType();
9619 
9620   // Integer types smaller than a register are extended.
9621   if (Size < 64 && Ty->isIntegerType())
9622     return ABIArgInfo::getExtend(Ty);
9623 
9624   if (const auto *EIT = Ty->getAs<BitIntType>())
9625     if (EIT->getNumBits() < 64)
9626       return ABIArgInfo::getExtend(Ty);
9627 
9628   // Other non-aggregates go in registers.
9629   if (!isAggregateTypeForABI(Ty))
9630     return ABIArgInfo::getDirect();
9631 
9632   // If a C++ object has either a non-trivial copy constructor or a non-trivial
9633   // destructor, it is passed with an explicit indirect pointer / sret pointer.
9634   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
9635     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
9636 
9637   // This is a small aggregate type that should be passed in registers.
9638   // Build a coercion type from the LLVM struct type.
9639   llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
9640   if (!StrTy)
9641     return ABIArgInfo::getDirect();
9642 
9643   CoerceBuilder CB(getVMContext(), getDataLayout());
9644   CB.addStruct(0, StrTy);
9645   CB.pad(llvm::alignTo(CB.DL.getTypeSizeInBits(StrTy), 64));
9646 
9647   // Try to use the original type for coercion.
9648   llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
9649 
9650   if (CB.InReg)
9651     return ABIArgInfo::getDirectInReg(CoerceTy);
9652   else
9653     return ABIArgInfo::getDirect(CoerceTy);
9654 }
9655 
9656 Address SparcV9ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9657                                   QualType Ty) const {
9658   ABIArgInfo AI = classifyType(Ty, 16 * 8);
9659   llvm::Type *ArgTy = CGT.ConvertType(Ty);
9660   if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
9661     AI.setCoerceToType(ArgTy);
9662 
9663   CharUnits SlotSize = CharUnits::fromQuantity(8);
9664 
9665   CGBuilderTy &Builder = CGF.Builder;
9666   Address Addr(Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
9667   llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
9668 
9669   auto TypeInfo = getContext().getTypeInfoInChars(Ty);
9670 
9671   Address ArgAddr = Address::invalid();
9672   CharUnits Stride;
9673   switch (AI.getKind()) {
9674   case ABIArgInfo::Expand:
9675   case ABIArgInfo::CoerceAndExpand:
9676   case ABIArgInfo::InAlloca:
9677     llvm_unreachable("Unsupported ABI kind for va_arg");
9678 
9679   case ABIArgInfo::Extend: {
9680     Stride = SlotSize;
9681     CharUnits Offset = SlotSize - TypeInfo.Width;
9682     ArgAddr = Builder.CreateConstInBoundsByteGEP(Addr, Offset, "extend");
9683     break;
9684   }
9685 
9686   case ABIArgInfo::Direct: {
9687     auto AllocSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
9688     Stride = CharUnits::fromQuantity(AllocSize).alignTo(SlotSize);
9689     ArgAddr = Addr;
9690     break;
9691   }
9692 
9693   case ABIArgInfo::Indirect:
9694   case ABIArgInfo::IndirectAliased:
9695     Stride = SlotSize;
9696     ArgAddr = Builder.CreateElementBitCast(Addr, ArgPtrTy, "indirect");
9697     ArgAddr = Address(Builder.CreateLoad(ArgAddr, "indirect.arg"),
9698                       TypeInfo.Align);
9699     break;
9700 
9701   case ABIArgInfo::Ignore:
9702     return Address(llvm::UndefValue::get(ArgPtrTy), TypeInfo.Align);
9703   }
9704 
9705   // Update VAList.
9706   Address NextPtr = Builder.CreateConstInBoundsByteGEP(Addr, Stride, "ap.next");
9707   Builder.CreateStore(NextPtr.getPointer(), VAListAddr);
9708 
9709   return Builder.CreateBitCast(ArgAddr, ArgPtrTy, "arg.addr");
9710 }
9711 
9712 void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
9713   FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
9714   for (auto &I : FI.arguments())
9715     I.info = classifyType(I.type, 16 * 8);
9716 }
9717 
9718 namespace {
9719 class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
9720 public:
9721   SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
9722       : TargetCodeGenInfo(std::make_unique<SparcV9ABIInfo>(CGT)) {}
9723 
9724   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
9725     return 14;
9726   }
9727 
9728   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
9729                                llvm::Value *Address) const override;
9730 };
9731 } // end anonymous namespace
9732 
9733 bool
9734 SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
9735                                                 llvm::Value *Address) const {
9736   // This is calculated from the LLVM and GCC tables and verified
9737   // against gcc output.  AFAIK all ABIs use the same encoding.
9738 
9739   CodeGen::CGBuilderTy &Builder = CGF.Builder;
9740 
9741   llvm::IntegerType *i8 = CGF.Int8Ty;
9742   llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
9743   llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
9744 
9745   // 0-31: the 8-byte general-purpose registers
9746   AssignToArrayRange(Builder, Address, Eight8, 0, 31);
9747 
9748   // 32-63: f0-31, the 4-byte floating-point registers
9749   AssignToArrayRange(Builder, Address, Four8, 32, 63);
9750 
9751   //   Y   = 64
9752   //   PSR = 65
9753   //   WIM = 66
9754   //   TBR = 67
9755   //   PC  = 68
9756   //   NPC = 69
9757   //   FSR = 70
9758   //   CSR = 71
9759   AssignToArrayRange(Builder, Address, Eight8, 64, 71);
9760 
9761   // 72-87: d0-15, the 8-byte floating-point registers
9762   AssignToArrayRange(Builder, Address, Eight8, 72, 87);
9763 
9764   return false;
9765 }
9766 
9767 // ARC ABI implementation.
9768 namespace {
9769 
9770 class ARCABIInfo : public DefaultABIInfo {
9771 public:
9772   using DefaultABIInfo::DefaultABIInfo;
9773 
9774 private:
9775   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9776                     QualType Ty) const override;
9777 
9778   void updateState(const ABIArgInfo &Info, QualType Ty, CCState &State) const {
9779     if (!State.FreeRegs)
9780       return;
9781     if (Info.isIndirect() && Info.getInReg())
9782       State.FreeRegs--;
9783     else if (Info.isDirect() && Info.getInReg()) {
9784       unsigned sz = (getContext().getTypeSize(Ty) + 31) / 32;
9785       if (sz < State.FreeRegs)
9786         State.FreeRegs -= sz;
9787       else
9788         State.FreeRegs = 0;
9789     }
9790   }
9791 
9792   void computeInfo(CGFunctionInfo &FI) const override {
9793     CCState State(FI);
9794     // ARC uses 8 registers to pass arguments.
9795     State.FreeRegs = 8;
9796 
9797     if (!getCXXABI().classifyReturnType(FI))
9798       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
9799     updateState(FI.getReturnInfo(), FI.getReturnType(), State);
9800     for (auto &I : FI.arguments()) {
9801       I.info = classifyArgumentType(I.type, State.FreeRegs);
9802       updateState(I.info, I.type, State);
9803     }
9804   }
9805 
9806   ABIArgInfo getIndirectByRef(QualType Ty, bool HasFreeRegs) const;
9807   ABIArgInfo getIndirectByValue(QualType Ty) const;
9808   ABIArgInfo classifyArgumentType(QualType Ty, uint8_t FreeRegs) const;
9809   ABIArgInfo classifyReturnType(QualType RetTy) const;
9810 };
9811 
9812 class ARCTargetCodeGenInfo : public TargetCodeGenInfo {
9813 public:
9814   ARCTargetCodeGenInfo(CodeGenTypes &CGT)
9815       : TargetCodeGenInfo(std::make_unique<ARCABIInfo>(CGT)) {}
9816 };
9817 
9818 
9819 ABIArgInfo ARCABIInfo::getIndirectByRef(QualType Ty, bool HasFreeRegs) const {
9820   return HasFreeRegs ? getNaturalAlignIndirectInReg(Ty) :
9821                        getNaturalAlignIndirect(Ty, false);
9822 }
9823 
9824 ABIArgInfo ARCABIInfo::getIndirectByValue(QualType Ty) const {
9825   // Compute the byval alignment.
9826   const unsigned MinABIStackAlignInBytes = 4;
9827   unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
9828   return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true,
9829                                  TypeAlign > MinABIStackAlignInBytes);
9830 }
9831 
9832 Address ARCABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9833                               QualType Ty) const {
9834   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
9835                           getContext().getTypeInfoInChars(Ty),
9836                           CharUnits::fromQuantity(4), true);
9837 }
9838 
9839 ABIArgInfo ARCABIInfo::classifyArgumentType(QualType Ty,
9840                                             uint8_t FreeRegs) const {
9841   // Handle the generic C++ ABI.
9842   const RecordType *RT = Ty->getAs<RecordType>();
9843   if (RT) {
9844     CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
9845     if (RAA == CGCXXABI::RAA_Indirect)
9846       return getIndirectByRef(Ty, FreeRegs > 0);
9847 
9848     if (RAA == CGCXXABI::RAA_DirectInMemory)
9849       return getIndirectByValue(Ty);
9850   }
9851 
9852   // Treat an enum type as its underlying type.
9853   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
9854     Ty = EnumTy->getDecl()->getIntegerType();
9855 
9856   auto SizeInRegs = llvm::alignTo(getContext().getTypeSize(Ty), 32) / 32;
9857 
9858   if (isAggregateTypeForABI(Ty)) {
9859     // Structures with flexible arrays are always indirect.
9860     if (RT && RT->getDecl()->hasFlexibleArrayMember())
9861       return getIndirectByValue(Ty);
9862 
9863     // Ignore empty structs/unions.
9864     if (isEmptyRecord(getContext(), Ty, true))
9865       return ABIArgInfo::getIgnore();
9866 
9867     llvm::LLVMContext &LLVMContext = getVMContext();
9868 
9869     llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
9870     SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32);
9871     llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
9872 
9873     return FreeRegs >= SizeInRegs ?
9874         ABIArgInfo::getDirectInReg(Result) :
9875         ABIArgInfo::getDirect(Result, 0, nullptr, false);
9876   }
9877 
9878   if (const auto *EIT = Ty->getAs<BitIntType>())
9879     if (EIT->getNumBits() > 64)
9880       return getIndirectByValue(Ty);
9881 
9882   return isPromotableIntegerTypeForABI(Ty)
9883              ? (FreeRegs >= SizeInRegs ? ABIArgInfo::getExtendInReg(Ty)
9884                                        : ABIArgInfo::getExtend(Ty))
9885              : (FreeRegs >= SizeInRegs ? ABIArgInfo::getDirectInReg()
9886                                        : ABIArgInfo::getDirect());
9887 }
9888 
9889 ABIArgInfo ARCABIInfo::classifyReturnType(QualType RetTy) const {
9890   if (RetTy->isAnyComplexType())
9891     return ABIArgInfo::getDirectInReg();
9892 
9893   // Arguments of size > 4 registers are indirect.
9894   auto RetSize = llvm::alignTo(getContext().getTypeSize(RetTy), 32) / 32;
9895   if (RetSize > 4)
9896     return getIndirectByRef(RetTy, /*HasFreeRegs*/ true);
9897 
9898   return DefaultABIInfo::classifyReturnType(RetTy);
9899 }
9900 
9901 } // End anonymous namespace.
9902 
9903 //===----------------------------------------------------------------------===//
9904 // XCore ABI Implementation
9905 //===----------------------------------------------------------------------===//
9906 
9907 namespace {
9908 
9909 /// A SmallStringEnc instance is used to build up the TypeString by passing
9910 /// it by reference between functions that append to it.
9911 typedef llvm::SmallString<128> SmallStringEnc;
9912 
9913 /// TypeStringCache caches the meta encodings of Types.
9914 ///
9915 /// The reason for caching TypeStrings is two fold:
9916 ///   1. To cache a type's encoding for later uses;
9917 ///   2. As a means to break recursive member type inclusion.
9918 ///
9919 /// A cache Entry can have a Status of:
9920 ///   NonRecursive:   The type encoding is not recursive;
9921 ///   Recursive:      The type encoding is recursive;
9922 ///   Incomplete:     An incomplete TypeString;
9923 ///   IncompleteUsed: An incomplete TypeString that has been used in a
9924 ///                   Recursive type encoding.
9925 ///
9926 /// A NonRecursive entry will have all of its sub-members expanded as fully
9927 /// as possible. Whilst it may contain types which are recursive, the type
9928 /// itself is not recursive and thus its encoding may be safely used whenever
9929 /// the type is encountered.
9930 ///
9931 /// A Recursive entry will have all of its sub-members expanded as fully as
9932 /// possible. The type itself is recursive and it may contain other types which
9933 /// are recursive. The Recursive encoding must not be used during the expansion
9934 /// of a recursive type's recursive branch. For simplicity the code uses
9935 /// IncompleteCount to reject all usage of Recursive encodings for member types.
9936 ///
9937 /// An Incomplete entry is always a RecordType and only encodes its
9938 /// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and
9939 /// are placed into the cache during type expansion as a means to identify and
9940 /// handle recursive inclusion of types as sub-members. If there is recursion
9941 /// the entry becomes IncompleteUsed.
9942 ///
9943 /// During the expansion of a RecordType's members:
9944 ///
9945 ///   If the cache contains a NonRecursive encoding for the member type, the
9946 ///   cached encoding is used;
9947 ///
9948 ///   If the cache contains a Recursive encoding for the member type, the
9949 ///   cached encoding is 'Swapped' out, as it may be incorrect, and...
9950 ///
9951 ///   If the member is a RecordType, an Incomplete encoding is placed into the
9952 ///   cache to break potential recursive inclusion of itself as a sub-member;
9953 ///
9954 ///   Once a member RecordType has been expanded, its temporary incomplete
9955 ///   entry is removed from the cache. If a Recursive encoding was swapped out
9956 ///   it is swapped back in;
9957 ///
9958 ///   If an incomplete entry is used to expand a sub-member, the incomplete
9959 ///   entry is marked as IncompleteUsed. The cache keeps count of how many
9960 ///   IncompleteUsed entries it currently contains in IncompleteUsedCount;
9961 ///
9962 ///   If a member's encoding is found to be a NonRecursive or Recursive viz:
9963 ///   IncompleteUsedCount==0, the member's encoding is added to the cache.
9964 ///   Else the member is part of a recursive type and thus the recursion has
9965 ///   been exited too soon for the encoding to be correct for the member.
9966 ///
9967 class TypeStringCache {
9968   enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed};
9969   struct Entry {
9970     std::string Str;     // The encoded TypeString for the type.
9971     enum Status State;   // Information about the encoding in 'Str'.
9972     std::string Swapped; // A temporary place holder for a Recursive encoding
9973                          // during the expansion of RecordType's members.
9974   };
9975   std::map<const IdentifierInfo *, struct Entry> Map;
9976   unsigned IncompleteCount;     // Number of Incomplete entries in the Map.
9977   unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map.
9978 public:
9979   TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {}
9980   void addIncomplete(const IdentifierInfo *ID, std::string StubEnc);
9981   bool removeIncomplete(const IdentifierInfo *ID);
9982   void addIfComplete(const IdentifierInfo *ID, StringRef Str,
9983                      bool IsRecursive);
9984   StringRef lookupStr(const IdentifierInfo *ID);
9985 };
9986 
9987 /// TypeString encodings for enum & union fields must be order.
9988 /// FieldEncoding is a helper for this ordering process.
9989 class FieldEncoding {
9990   bool HasName;
9991   std::string Enc;
9992 public:
9993   FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {}
9994   StringRef str() { return Enc; }
9995   bool operator<(const FieldEncoding &rhs) const {
9996     if (HasName != rhs.HasName) return HasName;
9997     return Enc < rhs.Enc;
9998   }
9999 };
10000 
10001 class XCoreABIInfo : public DefaultABIInfo {
10002 public:
10003   XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
10004   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
10005                     QualType Ty) const override;
10006 };
10007 
10008 class XCoreTargetCodeGenInfo : public TargetCodeGenInfo {
10009   mutable TypeStringCache TSC;
10010   void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
10011                     const CodeGen::CodeGenModule &M) const;
10012 
10013 public:
10014   XCoreTargetCodeGenInfo(CodeGenTypes &CGT)
10015       : TargetCodeGenInfo(std::make_unique<XCoreABIInfo>(CGT)) {}
10016   void emitTargetMetadata(CodeGen::CodeGenModule &CGM,
10017                           const llvm::MapVector<GlobalDecl, StringRef>
10018                               &MangledDeclNames) const override;
10019 };
10020 
10021 } // End anonymous namespace.
10022 
10023 // TODO: this implementation is likely now redundant with the default
10024 // EmitVAArg.
10025 Address XCoreABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
10026                                 QualType Ty) const {
10027   CGBuilderTy &Builder = CGF.Builder;
10028 
10029   // Get the VAList.
10030   CharUnits SlotSize = CharUnits::fromQuantity(4);
10031   Address AP(Builder.CreateLoad(VAListAddr), SlotSize);
10032 
10033   // Handle the argument.
10034   ABIArgInfo AI = classifyArgumentType(Ty);
10035   CharUnits TypeAlign = getContext().getTypeAlignInChars(Ty);
10036   llvm::Type *ArgTy = CGT.ConvertType(Ty);
10037   if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
10038     AI.setCoerceToType(ArgTy);
10039   llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
10040 
10041   Address Val = Address::invalid();
10042   CharUnits ArgSize = CharUnits::Zero();
10043   switch (AI.getKind()) {
10044   case ABIArgInfo::Expand:
10045   case ABIArgInfo::CoerceAndExpand:
10046   case ABIArgInfo::InAlloca:
10047     llvm_unreachable("Unsupported ABI kind for va_arg");
10048   case ABIArgInfo::Ignore:
10049     Val = Address(llvm::UndefValue::get(ArgPtrTy), TypeAlign);
10050     ArgSize = CharUnits::Zero();
10051     break;
10052   case ABIArgInfo::Extend:
10053   case ABIArgInfo::Direct:
10054     Val = Builder.CreateBitCast(AP, ArgPtrTy);
10055     ArgSize = CharUnits::fromQuantity(
10056                        getDataLayout().getTypeAllocSize(AI.getCoerceToType()));
10057     ArgSize = ArgSize.alignTo(SlotSize);
10058     break;
10059   case ABIArgInfo::Indirect:
10060   case ABIArgInfo::IndirectAliased:
10061     Val = Builder.CreateElementBitCast(AP, ArgPtrTy);
10062     Val = Address(Builder.CreateLoad(Val), TypeAlign);
10063     ArgSize = SlotSize;
10064     break;
10065   }
10066 
10067   // Increment the VAList.
10068   if (!ArgSize.isZero()) {
10069     Address APN = Builder.CreateConstInBoundsByteGEP(AP, ArgSize);
10070     Builder.CreateStore(APN.getPointer(), VAListAddr);
10071   }
10072 
10073   return Val;
10074 }
10075 
10076 /// During the expansion of a RecordType, an incomplete TypeString is placed
10077 /// into the cache as a means to identify and break recursion.
10078 /// If there is a Recursive encoding in the cache, it is swapped out and will
10079 /// be reinserted by removeIncomplete().
10080 /// All other types of encoding should have been used rather than arriving here.
10081 void TypeStringCache::addIncomplete(const IdentifierInfo *ID,
10082                                     std::string StubEnc) {
10083   if (!ID)
10084     return;
10085   Entry &E = Map[ID];
10086   assert( (E.Str.empty() || E.State == Recursive) &&
10087          "Incorrectly use of addIncomplete");
10088   assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()");
10089   E.Swapped.swap(E.Str); // swap out the Recursive
10090   E.Str.swap(StubEnc);
10091   E.State = Incomplete;
10092   ++IncompleteCount;
10093 }
10094 
10095 /// Once the RecordType has been expanded, the temporary incomplete TypeString
10096 /// must be removed from the cache.
10097 /// If a Recursive was swapped out by addIncomplete(), it will be replaced.
10098 /// Returns true if the RecordType was defined recursively.
10099 bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) {
10100   if (!ID)
10101     return false;
10102   auto I = Map.find(ID);
10103   assert(I != Map.end() && "Entry not present");
10104   Entry &E = I->second;
10105   assert( (E.State == Incomplete ||
10106            E.State == IncompleteUsed) &&
10107          "Entry must be an incomplete type");
10108   bool IsRecursive = false;
10109   if (E.State == IncompleteUsed) {
10110     // We made use of our Incomplete encoding, thus we are recursive.
10111     IsRecursive = true;
10112     --IncompleteUsedCount;
10113   }
10114   if (E.Swapped.empty())
10115     Map.erase(I);
10116   else {
10117     // Swap the Recursive back.
10118     E.Swapped.swap(E.Str);
10119     E.Swapped.clear();
10120     E.State = Recursive;
10121   }
10122   --IncompleteCount;
10123   return IsRecursive;
10124 }
10125 
10126 /// Add the encoded TypeString to the cache only if it is NonRecursive or
10127 /// Recursive (viz: all sub-members were expanded as fully as possible).
10128 void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str,
10129                                     bool IsRecursive) {
10130   if (!ID || IncompleteUsedCount)
10131     return; // No key or it is is an incomplete sub-type so don't add.
10132   Entry &E = Map[ID];
10133   if (IsRecursive && !E.Str.empty()) {
10134     assert(E.State==Recursive && E.Str.size() == Str.size() &&
10135            "This is not the same Recursive entry");
10136     // The parent container was not recursive after all, so we could have used
10137     // this Recursive sub-member entry after all, but we assumed the worse when
10138     // we started viz: IncompleteCount!=0.
10139     return;
10140   }
10141   assert(E.Str.empty() && "Entry already present");
10142   E.Str = Str.str();
10143   E.State = IsRecursive? Recursive : NonRecursive;
10144 }
10145 
10146 /// Return a cached TypeString encoding for the ID. If there isn't one, or we
10147 /// are recursively expanding a type (IncompleteCount != 0) and the cached
10148 /// encoding is Recursive, return an empty StringRef.
10149 StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) {
10150   if (!ID)
10151     return StringRef();   // We have no key.
10152   auto I = Map.find(ID);
10153   if (I == Map.end())
10154     return StringRef();   // We have no encoding.
10155   Entry &E = I->second;
10156   if (E.State == Recursive && IncompleteCount)
10157     return StringRef();   // We don't use Recursive encodings for member types.
10158 
10159   if (E.State == Incomplete) {
10160     // The incomplete type is being used to break out of recursion.
10161     E.State = IncompleteUsed;
10162     ++IncompleteUsedCount;
10163   }
10164   return E.Str;
10165 }
10166 
10167 /// The XCore ABI includes a type information section that communicates symbol
10168 /// type information to the linker. The linker uses this information to verify
10169 /// safety/correctness of things such as array bound and pointers et al.
10170 /// The ABI only requires C (and XC) language modules to emit TypeStrings.
10171 /// This type information (TypeString) is emitted into meta data for all global
10172 /// symbols: definitions, declarations, functions & variables.
10173 ///
10174 /// The TypeString carries type, qualifier, name, size & value details.
10175 /// Please see 'Tools Development Guide' section 2.16.2 for format details:
10176 /// https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf
10177 /// The output is tested by test/CodeGen/xcore-stringtype.c.
10178 ///
10179 static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
10180                           const CodeGen::CodeGenModule &CGM,
10181                           TypeStringCache &TSC);
10182 
10183 /// XCore uses emitTargetMD to emit TypeString metadata for global symbols.
10184 void XCoreTargetCodeGenInfo::emitTargetMD(
10185     const Decl *D, llvm::GlobalValue *GV,
10186     const CodeGen::CodeGenModule &CGM) const {
10187   SmallStringEnc Enc;
10188   if (getTypeString(Enc, D, CGM, TSC)) {
10189     llvm::LLVMContext &Ctx = CGM.getModule().getContext();
10190     llvm::Metadata *MDVals[] = {llvm::ConstantAsMetadata::get(GV),
10191                                 llvm::MDString::get(Ctx, Enc.str())};
10192     llvm::NamedMDNode *MD =
10193       CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings");
10194     MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
10195   }
10196 }
10197 
10198 void XCoreTargetCodeGenInfo::emitTargetMetadata(
10199     CodeGen::CodeGenModule &CGM,
10200     const llvm::MapVector<GlobalDecl, StringRef> &MangledDeclNames) const {
10201   // Warning, new MangledDeclNames may be appended within this loop.
10202   // We rely on MapVector insertions adding new elements to the end
10203   // of the container.
10204   for (unsigned I = 0; I != MangledDeclNames.size(); ++I) {
10205     auto Val = *(MangledDeclNames.begin() + I);
10206     llvm::GlobalValue *GV = CGM.GetGlobalValue(Val.second);
10207     if (GV) {
10208       const Decl *D = Val.first.getDecl()->getMostRecentDecl();
10209       emitTargetMD(D, GV, CGM);
10210     }
10211   }
10212 }
10213 
10214 //===----------------------------------------------------------------------===//
10215 // Base ABI and target codegen info implementation common between SPIR and
10216 // SPIR-V.
10217 //===----------------------------------------------------------------------===//
10218 
10219 namespace {
10220 class CommonSPIRABIInfo : public DefaultABIInfo {
10221 public:
10222   CommonSPIRABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) { setCCs(); }
10223 
10224 private:
10225   void setCCs();
10226 };
10227 
10228 class SPIRVABIInfo : public CommonSPIRABIInfo {
10229 public:
10230   SPIRVABIInfo(CodeGenTypes &CGT) : CommonSPIRABIInfo(CGT) {}
10231   void computeInfo(CGFunctionInfo &FI) const override;
10232 
10233 private:
10234   ABIArgInfo classifyKernelArgumentType(QualType Ty) const;
10235 };
10236 } // end anonymous namespace
10237 namespace {
10238 class CommonSPIRTargetCodeGenInfo : public TargetCodeGenInfo {
10239 public:
10240   CommonSPIRTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
10241       : TargetCodeGenInfo(std::make_unique<CommonSPIRABIInfo>(CGT)) {}
10242   CommonSPIRTargetCodeGenInfo(std::unique_ptr<ABIInfo> ABIInfo)
10243       : TargetCodeGenInfo(std::move(ABIInfo)) {}
10244 
10245   LangAS getASTAllocaAddressSpace() const override {
10246     return getLangASFromTargetAS(
10247         getABIInfo().getDataLayout().getAllocaAddrSpace());
10248   }
10249 
10250   unsigned getOpenCLKernelCallingConv() const override;
10251 };
10252 class SPIRVTargetCodeGenInfo : public CommonSPIRTargetCodeGenInfo {
10253 public:
10254   SPIRVTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
10255       : CommonSPIRTargetCodeGenInfo(std::make_unique<SPIRVABIInfo>(CGT)) {}
10256   void setCUDAKernelCallingConvention(const FunctionType *&FT) const override;
10257 };
10258 } // End anonymous namespace.
10259 
10260 void CommonSPIRABIInfo::setCCs() {
10261   assert(getRuntimeCC() == llvm::CallingConv::C);
10262   RuntimeCC = llvm::CallingConv::SPIR_FUNC;
10263 }
10264 
10265 ABIArgInfo SPIRVABIInfo::classifyKernelArgumentType(QualType Ty) const {
10266   if (getContext().getLangOpts().HIP) {
10267     // Coerce pointer arguments with default address space to CrossWorkGroup
10268     // pointers for HIPSPV. When the language mode is HIP, the SPIRTargetInfo
10269     // maps cuda_device to SPIR-V's CrossWorkGroup address space.
10270     llvm::Type *LTy = CGT.ConvertType(Ty);
10271     auto DefaultAS = getContext().getTargetAddressSpace(LangAS::Default);
10272     auto GlobalAS = getContext().getTargetAddressSpace(LangAS::cuda_device);
10273     auto *PtrTy = llvm::dyn_cast<llvm::PointerType>(LTy);
10274     if (PtrTy && PtrTy->getAddressSpace() == DefaultAS) {
10275       LTy = llvm::PointerType::getWithSamePointeeType(PtrTy, GlobalAS);
10276       return ABIArgInfo::getDirect(LTy, 0, nullptr, false);
10277     }
10278   }
10279   return classifyArgumentType(Ty);
10280 }
10281 
10282 void SPIRVABIInfo::computeInfo(CGFunctionInfo &FI) const {
10283   // The logic is same as in DefaultABIInfo with an exception on the kernel
10284   // arguments handling.
10285   llvm::CallingConv::ID CC = FI.getCallingConvention();
10286 
10287   if (!getCXXABI().classifyReturnType(FI))
10288     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
10289 
10290   for (auto &I : FI.arguments()) {
10291     if (CC == llvm::CallingConv::SPIR_KERNEL) {
10292       I.info = classifyKernelArgumentType(I.type);
10293     } else {
10294       I.info = classifyArgumentType(I.type);
10295     }
10296   }
10297 }
10298 
10299 namespace clang {
10300 namespace CodeGen {
10301 void computeSPIRKernelABIInfo(CodeGenModule &CGM, CGFunctionInfo &FI) {
10302   if (CGM.getTarget().getTriple().isSPIRV())
10303     SPIRVABIInfo(CGM.getTypes()).computeInfo(FI);
10304   else
10305     CommonSPIRABIInfo(CGM.getTypes()).computeInfo(FI);
10306 }
10307 }
10308 }
10309 
10310 unsigned CommonSPIRTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
10311   return llvm::CallingConv::SPIR_KERNEL;
10312 }
10313 
10314 void SPIRVTargetCodeGenInfo::setCUDAKernelCallingConvention(
10315     const FunctionType *&FT) const {
10316   // Convert HIP kernels to SPIR-V kernels.
10317   if (getABIInfo().getContext().getLangOpts().HIP) {
10318     FT = getABIInfo().getContext().adjustFunctionType(
10319         FT, FT->getExtInfo().withCallingConv(CC_OpenCLKernel));
10320     return;
10321   }
10322 }
10323 
10324 static bool appendType(SmallStringEnc &Enc, QualType QType,
10325                        const CodeGen::CodeGenModule &CGM,
10326                        TypeStringCache &TSC);
10327 
10328 /// Helper function for appendRecordType().
10329 /// Builds a SmallVector containing the encoded field types in declaration
10330 /// order.
10331 static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE,
10332                              const RecordDecl *RD,
10333                              const CodeGen::CodeGenModule &CGM,
10334                              TypeStringCache &TSC) {
10335   for (const auto *Field : RD->fields()) {
10336     SmallStringEnc Enc;
10337     Enc += "m(";
10338     Enc += Field->getName();
10339     Enc += "){";
10340     if (Field->isBitField()) {
10341       Enc += "b(";
10342       llvm::raw_svector_ostream OS(Enc);
10343       OS << Field->getBitWidthValue(CGM.getContext());
10344       Enc += ':';
10345     }
10346     if (!appendType(Enc, Field->getType(), CGM, TSC))
10347       return false;
10348     if (Field->isBitField())
10349       Enc += ')';
10350     Enc += '}';
10351     FE.emplace_back(!Field->getName().empty(), Enc);
10352   }
10353   return true;
10354 }
10355 
10356 /// Appends structure and union types to Enc and adds encoding to cache.
10357 /// Recursively calls appendType (via extractFieldType) for each field.
10358 /// Union types have their fields ordered according to the ABI.
10359 static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT,
10360                              const CodeGen::CodeGenModule &CGM,
10361                              TypeStringCache &TSC, const IdentifierInfo *ID) {
10362   // Append the cached TypeString if we have one.
10363   StringRef TypeString = TSC.lookupStr(ID);
10364   if (!TypeString.empty()) {
10365     Enc += TypeString;
10366     return true;
10367   }
10368 
10369   // Start to emit an incomplete TypeString.
10370   size_t Start = Enc.size();
10371   Enc += (RT->isUnionType()? 'u' : 's');
10372   Enc += '(';
10373   if (ID)
10374     Enc += ID->getName();
10375   Enc += "){";
10376 
10377   // We collect all encoded fields and order as necessary.
10378   bool IsRecursive = false;
10379   const RecordDecl *RD = RT->getDecl()->getDefinition();
10380   if (RD && !RD->field_empty()) {
10381     // An incomplete TypeString stub is placed in the cache for this RecordType
10382     // so that recursive calls to this RecordType will use it whilst building a
10383     // complete TypeString for this RecordType.
10384     SmallVector<FieldEncoding, 16> FE;
10385     std::string StubEnc(Enc.substr(Start).str());
10386     StubEnc += '}';  // StubEnc now holds a valid incomplete TypeString.
10387     TSC.addIncomplete(ID, std::move(StubEnc));
10388     if (!extractFieldType(FE, RD, CGM, TSC)) {
10389       (void) TSC.removeIncomplete(ID);
10390       return false;
10391     }
10392     IsRecursive = TSC.removeIncomplete(ID);
10393     // The ABI requires unions to be sorted but not structures.
10394     // See FieldEncoding::operator< for sort algorithm.
10395     if (RT->isUnionType())
10396       llvm::sort(FE);
10397     // We can now complete the TypeString.
10398     unsigned E = FE.size();
10399     for (unsigned I = 0; I != E; ++I) {
10400       if (I)
10401         Enc += ',';
10402       Enc += FE[I].str();
10403     }
10404   }
10405   Enc += '}';
10406   TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive);
10407   return true;
10408 }
10409 
10410 /// Appends enum types to Enc and adds the encoding to the cache.
10411 static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET,
10412                            TypeStringCache &TSC,
10413                            const IdentifierInfo *ID) {
10414   // Append the cached TypeString if we have one.
10415   StringRef TypeString = TSC.lookupStr(ID);
10416   if (!TypeString.empty()) {
10417     Enc += TypeString;
10418     return true;
10419   }
10420 
10421   size_t Start = Enc.size();
10422   Enc += "e(";
10423   if (ID)
10424     Enc += ID->getName();
10425   Enc += "){";
10426 
10427   // We collect all encoded enumerations and order them alphanumerically.
10428   if (const EnumDecl *ED = ET->getDecl()->getDefinition()) {
10429     SmallVector<FieldEncoding, 16> FE;
10430     for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E;
10431          ++I) {
10432       SmallStringEnc EnumEnc;
10433       EnumEnc += "m(";
10434       EnumEnc += I->getName();
10435       EnumEnc += "){";
10436       I->getInitVal().toString(EnumEnc);
10437       EnumEnc += '}';
10438       FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc));
10439     }
10440     llvm::sort(FE);
10441     unsigned E = FE.size();
10442     for (unsigned I = 0; I != E; ++I) {
10443       if (I)
10444         Enc += ',';
10445       Enc += FE[I].str();
10446     }
10447   }
10448   Enc += '}';
10449   TSC.addIfComplete(ID, Enc.substr(Start), false);
10450   return true;
10451 }
10452 
10453 /// Appends type's qualifier to Enc.
10454 /// This is done prior to appending the type's encoding.
10455 static void appendQualifier(SmallStringEnc &Enc, QualType QT) {
10456   // Qualifiers are emitted in alphabetical order.
10457   static const char *const Table[]={"","c:","r:","cr:","v:","cv:","rv:","crv:"};
10458   int Lookup = 0;
10459   if (QT.isConstQualified())
10460     Lookup += 1<<0;
10461   if (QT.isRestrictQualified())
10462     Lookup += 1<<1;
10463   if (QT.isVolatileQualified())
10464     Lookup += 1<<2;
10465   Enc += Table[Lookup];
10466 }
10467 
10468 /// Appends built-in types to Enc.
10469 static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) {
10470   const char *EncType;
10471   switch (BT->getKind()) {
10472     case BuiltinType::Void:
10473       EncType = "0";
10474       break;
10475     case BuiltinType::Bool:
10476       EncType = "b";
10477       break;
10478     case BuiltinType::Char_U:
10479       EncType = "uc";
10480       break;
10481     case BuiltinType::UChar:
10482       EncType = "uc";
10483       break;
10484     case BuiltinType::SChar:
10485       EncType = "sc";
10486       break;
10487     case BuiltinType::UShort:
10488       EncType = "us";
10489       break;
10490     case BuiltinType::Short:
10491       EncType = "ss";
10492       break;
10493     case BuiltinType::UInt:
10494       EncType = "ui";
10495       break;
10496     case BuiltinType::Int:
10497       EncType = "si";
10498       break;
10499     case BuiltinType::ULong:
10500       EncType = "ul";
10501       break;
10502     case BuiltinType::Long:
10503       EncType = "sl";
10504       break;
10505     case BuiltinType::ULongLong:
10506       EncType = "ull";
10507       break;
10508     case BuiltinType::LongLong:
10509       EncType = "sll";
10510       break;
10511     case BuiltinType::Float:
10512       EncType = "ft";
10513       break;
10514     case BuiltinType::Double:
10515       EncType = "d";
10516       break;
10517     case BuiltinType::LongDouble:
10518       EncType = "ld";
10519       break;
10520     default:
10521       return false;
10522   }
10523   Enc += EncType;
10524   return true;
10525 }
10526 
10527 /// Appends a pointer encoding to Enc before calling appendType for the pointee.
10528 static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT,
10529                               const CodeGen::CodeGenModule &CGM,
10530                               TypeStringCache &TSC) {
10531   Enc += "p(";
10532   if (!appendType(Enc, PT->getPointeeType(), CGM, TSC))
10533     return false;
10534   Enc += ')';
10535   return true;
10536 }
10537 
10538 /// Appends array encoding to Enc before calling appendType for the element.
10539 static bool appendArrayType(SmallStringEnc &Enc, QualType QT,
10540                             const ArrayType *AT,
10541                             const CodeGen::CodeGenModule &CGM,
10542                             TypeStringCache &TSC, StringRef NoSizeEnc) {
10543   if (AT->getSizeModifier() != ArrayType::Normal)
10544     return false;
10545   Enc += "a(";
10546   if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
10547     CAT->getSize().toStringUnsigned(Enc);
10548   else
10549     Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "".
10550   Enc += ':';
10551   // The Qualifiers should be attached to the type rather than the array.
10552   appendQualifier(Enc, QT);
10553   if (!appendType(Enc, AT->getElementType(), CGM, TSC))
10554     return false;
10555   Enc += ')';
10556   return true;
10557 }
10558 
10559 /// Appends a function encoding to Enc, calling appendType for the return type
10560 /// and the arguments.
10561 static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT,
10562                              const CodeGen::CodeGenModule &CGM,
10563                              TypeStringCache &TSC) {
10564   Enc += "f{";
10565   if (!appendType(Enc, FT->getReturnType(), CGM, TSC))
10566     return false;
10567   Enc += "}(";
10568   if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) {
10569     // N.B. we are only interested in the adjusted param types.
10570     auto I = FPT->param_type_begin();
10571     auto E = FPT->param_type_end();
10572     if (I != E) {
10573       do {
10574         if (!appendType(Enc, *I, CGM, TSC))
10575           return false;
10576         ++I;
10577         if (I != E)
10578           Enc += ',';
10579       } while (I != E);
10580       if (FPT->isVariadic())
10581         Enc += ",va";
10582     } else {
10583       if (FPT->isVariadic())
10584         Enc += "va";
10585       else
10586         Enc += '0';
10587     }
10588   }
10589   Enc += ')';
10590   return true;
10591 }
10592 
10593 /// Handles the type's qualifier before dispatching a call to handle specific
10594 /// type encodings.
10595 static bool appendType(SmallStringEnc &Enc, QualType QType,
10596                        const CodeGen::CodeGenModule &CGM,
10597                        TypeStringCache &TSC) {
10598 
10599   QualType QT = QType.getCanonicalType();
10600 
10601   if (const ArrayType *AT = QT->getAsArrayTypeUnsafe())
10602     // The Qualifiers should be attached to the type rather than the array.
10603     // Thus we don't call appendQualifier() here.
10604     return appendArrayType(Enc, QT, AT, CGM, TSC, "");
10605 
10606   appendQualifier(Enc, QT);
10607 
10608   if (const BuiltinType *BT = QT->getAs<BuiltinType>())
10609     return appendBuiltinType(Enc, BT);
10610 
10611   if (const PointerType *PT = QT->getAs<PointerType>())
10612     return appendPointerType(Enc, PT, CGM, TSC);
10613 
10614   if (const EnumType *ET = QT->getAs<EnumType>())
10615     return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier());
10616 
10617   if (const RecordType *RT = QT->getAsStructureType())
10618     return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
10619 
10620   if (const RecordType *RT = QT->getAsUnionType())
10621     return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
10622 
10623   if (const FunctionType *FT = QT->getAs<FunctionType>())
10624     return appendFunctionType(Enc, FT, CGM, TSC);
10625 
10626   return false;
10627 }
10628 
10629 static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
10630                           const CodeGen::CodeGenModule &CGM,
10631                           TypeStringCache &TSC) {
10632   if (!D)
10633     return false;
10634 
10635   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
10636     if (FD->getLanguageLinkage() != CLanguageLinkage)
10637       return false;
10638     return appendType(Enc, FD->getType(), CGM, TSC);
10639   }
10640 
10641   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
10642     if (VD->getLanguageLinkage() != CLanguageLinkage)
10643       return false;
10644     QualType QT = VD->getType().getCanonicalType();
10645     if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) {
10646       // Global ArrayTypes are given a size of '*' if the size is unknown.
10647       // The Qualifiers should be attached to the type rather than the array.
10648       // Thus we don't call appendQualifier() here.
10649       return appendArrayType(Enc, QT, AT, CGM, TSC, "*");
10650     }
10651     return appendType(Enc, QT, CGM, TSC);
10652   }
10653   return false;
10654 }
10655 
10656 //===----------------------------------------------------------------------===//
10657 // RISCV ABI Implementation
10658 //===----------------------------------------------------------------------===//
10659 
10660 namespace {
10661 class RISCVABIInfo : public DefaultABIInfo {
10662 private:
10663   // Size of the integer ('x') registers in bits.
10664   unsigned XLen;
10665   // Size of the floating point ('f') registers in bits. Note that the target
10666   // ISA might have a wider FLen than the selected ABI (e.g. an RV32IF target
10667   // with soft float ABI has FLen==0).
10668   unsigned FLen;
10669   static const int NumArgGPRs = 8;
10670   static const int NumArgFPRs = 8;
10671   bool detectFPCCEligibleStructHelper(QualType Ty, CharUnits CurOff,
10672                                       llvm::Type *&Field1Ty,
10673                                       CharUnits &Field1Off,
10674                                       llvm::Type *&Field2Ty,
10675                                       CharUnits &Field2Off) const;
10676 
10677 public:
10678   RISCVABIInfo(CodeGen::CodeGenTypes &CGT, unsigned XLen, unsigned FLen)
10679       : DefaultABIInfo(CGT), XLen(XLen), FLen(FLen) {}
10680 
10681   // DefaultABIInfo's classifyReturnType and classifyArgumentType are
10682   // non-virtual, but computeInfo is virtual, so we overload it.
10683   void computeInfo(CGFunctionInfo &FI) const override;
10684 
10685   ABIArgInfo classifyArgumentType(QualType Ty, bool IsFixed, int &ArgGPRsLeft,
10686                                   int &ArgFPRsLeft) const;
10687   ABIArgInfo classifyReturnType(QualType RetTy) const;
10688 
10689   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
10690                     QualType Ty) const override;
10691 
10692   ABIArgInfo extendType(QualType Ty) const;
10693 
10694   bool detectFPCCEligibleStruct(QualType Ty, llvm::Type *&Field1Ty,
10695                                 CharUnits &Field1Off, llvm::Type *&Field2Ty,
10696                                 CharUnits &Field2Off, int &NeededArgGPRs,
10697                                 int &NeededArgFPRs) const;
10698   ABIArgInfo coerceAndExpandFPCCEligibleStruct(llvm::Type *Field1Ty,
10699                                                CharUnits Field1Off,
10700                                                llvm::Type *Field2Ty,
10701                                                CharUnits Field2Off) const;
10702 };
10703 } // end anonymous namespace
10704 
10705 void RISCVABIInfo::computeInfo(CGFunctionInfo &FI) const {
10706   QualType RetTy = FI.getReturnType();
10707   if (!getCXXABI().classifyReturnType(FI))
10708     FI.getReturnInfo() = classifyReturnType(RetTy);
10709 
10710   // IsRetIndirect is true if classifyArgumentType indicated the value should
10711   // be passed indirect, or if the type size is a scalar greater than 2*XLen
10712   // and not a complex type with elements <= FLen. e.g. fp128 is passed direct
10713   // in LLVM IR, relying on the backend lowering code to rewrite the argument
10714   // list and pass indirectly on RV32.
10715   bool IsRetIndirect = FI.getReturnInfo().getKind() == ABIArgInfo::Indirect;
10716   if (!IsRetIndirect && RetTy->isScalarType() &&
10717       getContext().getTypeSize(RetTy) > (2 * XLen)) {
10718     if (RetTy->isComplexType() && FLen) {
10719       QualType EltTy = RetTy->castAs<ComplexType>()->getElementType();
10720       IsRetIndirect = getContext().getTypeSize(EltTy) > FLen;
10721     } else {
10722       // This is a normal scalar > 2*XLen, such as fp128 on RV32.
10723       IsRetIndirect = true;
10724     }
10725   }
10726 
10727   // We must track the number of GPRs used in order to conform to the RISC-V
10728   // ABI, as integer scalars passed in registers should have signext/zeroext
10729   // when promoted, but are anyext if passed on the stack. As GPR usage is
10730   // different for variadic arguments, we must also track whether we are
10731   // examining a vararg or not.
10732   int ArgGPRsLeft = IsRetIndirect ? NumArgGPRs - 1 : NumArgGPRs;
10733   int ArgFPRsLeft = FLen ? NumArgFPRs : 0;
10734   int NumFixedArgs = FI.getNumRequiredArgs();
10735 
10736   int ArgNum = 0;
10737   for (auto &ArgInfo : FI.arguments()) {
10738     bool IsFixed = ArgNum < NumFixedArgs;
10739     ArgInfo.info =
10740         classifyArgumentType(ArgInfo.type, IsFixed, ArgGPRsLeft, ArgFPRsLeft);
10741     ArgNum++;
10742   }
10743 }
10744 
10745 // Returns true if the struct is a potential candidate for the floating point
10746 // calling convention. If this function returns true, the caller is
10747 // responsible for checking that if there is only a single field then that
10748 // field is a float.
10749 bool RISCVABIInfo::detectFPCCEligibleStructHelper(QualType Ty, CharUnits CurOff,
10750                                                   llvm::Type *&Field1Ty,
10751                                                   CharUnits &Field1Off,
10752                                                   llvm::Type *&Field2Ty,
10753                                                   CharUnits &Field2Off) const {
10754   bool IsInt = Ty->isIntegralOrEnumerationType();
10755   bool IsFloat = Ty->isRealFloatingType();
10756 
10757   if (IsInt || IsFloat) {
10758     uint64_t Size = getContext().getTypeSize(Ty);
10759     if (IsInt && Size > XLen)
10760       return false;
10761     // Can't be eligible if larger than the FP registers. Half precision isn't
10762     // currently supported on RISC-V and the ABI hasn't been confirmed, so
10763     // default to the integer ABI in that case.
10764     if (IsFloat && (Size > FLen || Size < 32))
10765       return false;
10766     // Can't be eligible if an integer type was already found (int+int pairs
10767     // are not eligible).
10768     if (IsInt && Field1Ty && Field1Ty->isIntegerTy())
10769       return false;
10770     if (!Field1Ty) {
10771       Field1Ty = CGT.ConvertType(Ty);
10772       Field1Off = CurOff;
10773       return true;
10774     }
10775     if (!Field2Ty) {
10776       Field2Ty = CGT.ConvertType(Ty);
10777       Field2Off = CurOff;
10778       return true;
10779     }
10780     return false;
10781   }
10782 
10783   if (auto CTy = Ty->getAs<ComplexType>()) {
10784     if (Field1Ty)
10785       return false;
10786     QualType EltTy = CTy->getElementType();
10787     if (getContext().getTypeSize(EltTy) > FLen)
10788       return false;
10789     Field1Ty = CGT.ConvertType(EltTy);
10790     Field1Off = CurOff;
10791     Field2Ty = Field1Ty;
10792     Field2Off = Field1Off + getContext().getTypeSizeInChars(EltTy);
10793     return true;
10794   }
10795 
10796   if (const ConstantArrayType *ATy = getContext().getAsConstantArrayType(Ty)) {
10797     uint64_t ArraySize = ATy->getSize().getZExtValue();
10798     QualType EltTy = ATy->getElementType();
10799     CharUnits EltSize = getContext().getTypeSizeInChars(EltTy);
10800     for (uint64_t i = 0; i < ArraySize; ++i) {
10801       bool Ret = detectFPCCEligibleStructHelper(EltTy, CurOff, Field1Ty,
10802                                                 Field1Off, Field2Ty, Field2Off);
10803       if (!Ret)
10804         return false;
10805       CurOff += EltSize;
10806     }
10807     return true;
10808   }
10809 
10810   if (const auto *RTy = Ty->getAs<RecordType>()) {
10811     // Structures with either a non-trivial destructor or a non-trivial
10812     // copy constructor are not eligible for the FP calling convention.
10813     if (getRecordArgABI(Ty, CGT.getCXXABI()))
10814       return false;
10815     if (isEmptyRecord(getContext(), Ty, true))
10816       return true;
10817     const RecordDecl *RD = RTy->getDecl();
10818     // Unions aren't eligible unless they're empty (which is caught above).
10819     if (RD->isUnion())
10820       return false;
10821     int ZeroWidthBitFieldCount = 0;
10822     for (const FieldDecl *FD : RD->fields()) {
10823       const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
10824       uint64_t FieldOffInBits = Layout.getFieldOffset(FD->getFieldIndex());
10825       QualType QTy = FD->getType();
10826       if (FD->isBitField()) {
10827         unsigned BitWidth = FD->getBitWidthValue(getContext());
10828         // Allow a bitfield with a type greater than XLen as long as the
10829         // bitwidth is XLen or less.
10830         if (getContext().getTypeSize(QTy) > XLen && BitWidth <= XLen)
10831           QTy = getContext().getIntTypeForBitwidth(XLen, false);
10832         if (BitWidth == 0) {
10833           ZeroWidthBitFieldCount++;
10834           continue;
10835         }
10836       }
10837 
10838       bool Ret = detectFPCCEligibleStructHelper(
10839           QTy, CurOff + getContext().toCharUnitsFromBits(FieldOffInBits),
10840           Field1Ty, Field1Off, Field2Ty, Field2Off);
10841       if (!Ret)
10842         return false;
10843 
10844       // As a quirk of the ABI, zero-width bitfields aren't ignored for fp+fp
10845       // or int+fp structs, but are ignored for a struct with an fp field and
10846       // any number of zero-width bitfields.
10847       if (Field2Ty && ZeroWidthBitFieldCount > 0)
10848         return false;
10849     }
10850     return Field1Ty != nullptr;
10851   }
10852 
10853   return false;
10854 }
10855 
10856 // Determine if a struct is eligible for passing according to the floating
10857 // point calling convention (i.e., when flattened it contains a single fp
10858 // value, fp+fp, or int+fp of appropriate size). If so, NeededArgFPRs and
10859 // NeededArgGPRs are incremented appropriately.
10860 bool RISCVABIInfo::detectFPCCEligibleStruct(QualType Ty, llvm::Type *&Field1Ty,
10861                                             CharUnits &Field1Off,
10862                                             llvm::Type *&Field2Ty,
10863                                             CharUnits &Field2Off,
10864                                             int &NeededArgGPRs,
10865                                             int &NeededArgFPRs) const {
10866   Field1Ty = nullptr;
10867   Field2Ty = nullptr;
10868   NeededArgGPRs = 0;
10869   NeededArgFPRs = 0;
10870   bool IsCandidate = detectFPCCEligibleStructHelper(
10871       Ty, CharUnits::Zero(), Field1Ty, Field1Off, Field2Ty, Field2Off);
10872   // Not really a candidate if we have a single int but no float.
10873   if (Field1Ty && !Field2Ty && !Field1Ty->isFloatingPointTy())
10874     return false;
10875   if (!IsCandidate)
10876     return false;
10877   if (Field1Ty && Field1Ty->isFloatingPointTy())
10878     NeededArgFPRs++;
10879   else if (Field1Ty)
10880     NeededArgGPRs++;
10881   if (Field2Ty && Field2Ty->isFloatingPointTy())
10882     NeededArgFPRs++;
10883   else if (Field2Ty)
10884     NeededArgGPRs++;
10885   return true;
10886 }
10887 
10888 // Call getCoerceAndExpand for the two-element flattened struct described by
10889 // Field1Ty, Field1Off, Field2Ty, Field2Off. This method will create an
10890 // appropriate coerceToType and unpaddedCoerceToType.
10891 ABIArgInfo RISCVABIInfo::coerceAndExpandFPCCEligibleStruct(
10892     llvm::Type *Field1Ty, CharUnits Field1Off, llvm::Type *Field2Ty,
10893     CharUnits Field2Off) const {
10894   SmallVector<llvm::Type *, 3> CoerceElts;
10895   SmallVector<llvm::Type *, 2> UnpaddedCoerceElts;
10896   if (!Field1Off.isZero())
10897     CoerceElts.push_back(llvm::ArrayType::get(
10898         llvm::Type::getInt8Ty(getVMContext()), Field1Off.getQuantity()));
10899 
10900   CoerceElts.push_back(Field1Ty);
10901   UnpaddedCoerceElts.push_back(Field1Ty);
10902 
10903   if (!Field2Ty) {
10904     return ABIArgInfo::getCoerceAndExpand(
10905         llvm::StructType::get(getVMContext(), CoerceElts, !Field1Off.isZero()),
10906         UnpaddedCoerceElts[0]);
10907   }
10908 
10909   CharUnits Field2Align =
10910       CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(Field2Ty));
10911   CharUnits Field1End = Field1Off +
10912       CharUnits::fromQuantity(getDataLayout().getTypeStoreSize(Field1Ty));
10913   CharUnits Field2OffNoPadNoPack = Field1End.alignTo(Field2Align);
10914 
10915   CharUnits Padding = CharUnits::Zero();
10916   if (Field2Off > Field2OffNoPadNoPack)
10917     Padding = Field2Off - Field2OffNoPadNoPack;
10918   else if (Field2Off != Field2Align && Field2Off > Field1End)
10919     Padding = Field2Off - Field1End;
10920 
10921   bool IsPacked = !Field2Off.isMultipleOf(Field2Align);
10922 
10923   if (!Padding.isZero())
10924     CoerceElts.push_back(llvm::ArrayType::get(
10925         llvm::Type::getInt8Ty(getVMContext()), Padding.getQuantity()));
10926 
10927   CoerceElts.push_back(Field2Ty);
10928   UnpaddedCoerceElts.push_back(Field2Ty);
10929 
10930   auto CoerceToType =
10931       llvm::StructType::get(getVMContext(), CoerceElts, IsPacked);
10932   auto UnpaddedCoerceToType =
10933       llvm::StructType::get(getVMContext(), UnpaddedCoerceElts, IsPacked);
10934 
10935   return ABIArgInfo::getCoerceAndExpand(CoerceToType, UnpaddedCoerceToType);
10936 }
10937 
10938 ABIArgInfo RISCVABIInfo::classifyArgumentType(QualType Ty, bool IsFixed,
10939                                               int &ArgGPRsLeft,
10940                                               int &ArgFPRsLeft) const {
10941   assert(ArgGPRsLeft <= NumArgGPRs && "Arg GPR tracking underflow");
10942   Ty = useFirstFieldIfTransparentUnion(Ty);
10943 
10944   // Structures with either a non-trivial destructor or a non-trivial
10945   // copy constructor are always passed indirectly.
10946   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
10947     if (ArgGPRsLeft)
10948       ArgGPRsLeft -= 1;
10949     return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA ==
10950                                            CGCXXABI::RAA_DirectInMemory);
10951   }
10952 
10953   // Ignore empty structs/unions.
10954   if (isEmptyRecord(getContext(), Ty, true))
10955     return ABIArgInfo::getIgnore();
10956 
10957   uint64_t Size = getContext().getTypeSize(Ty);
10958 
10959   // Pass floating point values via FPRs if possible.
10960   if (IsFixed && Ty->isFloatingType() && !Ty->isComplexType() &&
10961       FLen >= Size && ArgFPRsLeft) {
10962     ArgFPRsLeft--;
10963     return ABIArgInfo::getDirect();
10964   }
10965 
10966   // Complex types for the hard float ABI must be passed direct rather than
10967   // using CoerceAndExpand.
10968   if (IsFixed && Ty->isComplexType() && FLen && ArgFPRsLeft >= 2) {
10969     QualType EltTy = Ty->castAs<ComplexType>()->getElementType();
10970     if (getContext().getTypeSize(EltTy) <= FLen) {
10971       ArgFPRsLeft -= 2;
10972       return ABIArgInfo::getDirect();
10973     }
10974   }
10975 
10976   if (IsFixed && FLen && Ty->isStructureOrClassType()) {
10977     llvm::Type *Field1Ty = nullptr;
10978     llvm::Type *Field2Ty = nullptr;
10979     CharUnits Field1Off = CharUnits::Zero();
10980     CharUnits Field2Off = CharUnits::Zero();
10981     int NeededArgGPRs = 0;
10982     int NeededArgFPRs = 0;
10983     bool IsCandidate =
10984         detectFPCCEligibleStruct(Ty, Field1Ty, Field1Off, Field2Ty, Field2Off,
10985                                  NeededArgGPRs, NeededArgFPRs);
10986     if (IsCandidate && NeededArgGPRs <= ArgGPRsLeft &&
10987         NeededArgFPRs <= ArgFPRsLeft) {
10988       ArgGPRsLeft -= NeededArgGPRs;
10989       ArgFPRsLeft -= NeededArgFPRs;
10990       return coerceAndExpandFPCCEligibleStruct(Field1Ty, Field1Off, Field2Ty,
10991                                                Field2Off);
10992     }
10993   }
10994 
10995   uint64_t NeededAlign = getContext().getTypeAlign(Ty);
10996   bool MustUseStack = false;
10997   // Determine the number of GPRs needed to pass the current argument
10998   // according to the ABI. 2*XLen-aligned varargs are passed in "aligned"
10999   // register pairs, so may consume 3 registers.
11000   int NeededArgGPRs = 1;
11001   if (!IsFixed && NeededAlign == 2 * XLen)
11002     NeededArgGPRs = 2 + (ArgGPRsLeft % 2);
11003   else if (Size > XLen && Size <= 2 * XLen)
11004     NeededArgGPRs = 2;
11005 
11006   if (NeededArgGPRs > ArgGPRsLeft) {
11007     MustUseStack = true;
11008     NeededArgGPRs = ArgGPRsLeft;
11009   }
11010 
11011   ArgGPRsLeft -= NeededArgGPRs;
11012 
11013   if (!isAggregateTypeForABI(Ty) && !Ty->isVectorType()) {
11014     // Treat an enum type as its underlying type.
11015     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
11016       Ty = EnumTy->getDecl()->getIntegerType();
11017 
11018     // All integral types are promoted to XLen width, unless passed on the
11019     // stack.
11020     if (Size < XLen && Ty->isIntegralOrEnumerationType() && !MustUseStack) {
11021       return extendType(Ty);
11022     }
11023 
11024     if (const auto *EIT = Ty->getAs<BitIntType>()) {
11025       if (EIT->getNumBits() < XLen && !MustUseStack)
11026         return extendType(Ty);
11027       if (EIT->getNumBits() > 128 ||
11028           (!getContext().getTargetInfo().hasInt128Type() &&
11029            EIT->getNumBits() > 64))
11030         return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
11031     }
11032 
11033     return ABIArgInfo::getDirect();
11034   }
11035 
11036   // Aggregates which are <= 2*XLen will be passed in registers if possible,
11037   // so coerce to integers.
11038   if (Size <= 2 * XLen) {
11039     unsigned Alignment = getContext().getTypeAlign(Ty);
11040 
11041     // Use a single XLen int if possible, 2*XLen if 2*XLen alignment is
11042     // required, and a 2-element XLen array if only XLen alignment is required.
11043     if (Size <= XLen) {
11044       return ABIArgInfo::getDirect(
11045           llvm::IntegerType::get(getVMContext(), XLen));
11046     } else if (Alignment == 2 * XLen) {
11047       return ABIArgInfo::getDirect(
11048           llvm::IntegerType::get(getVMContext(), 2 * XLen));
11049     } else {
11050       return ABIArgInfo::getDirect(llvm::ArrayType::get(
11051           llvm::IntegerType::get(getVMContext(), XLen), 2));
11052     }
11053   }
11054   return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
11055 }
11056 
11057 ABIArgInfo RISCVABIInfo::classifyReturnType(QualType RetTy) const {
11058   if (RetTy->isVoidType())
11059     return ABIArgInfo::getIgnore();
11060 
11061   int ArgGPRsLeft = 2;
11062   int ArgFPRsLeft = FLen ? 2 : 0;
11063 
11064   // The rules for return and argument types are the same, so defer to
11065   // classifyArgumentType.
11066   return classifyArgumentType(RetTy, /*IsFixed=*/true, ArgGPRsLeft,
11067                               ArgFPRsLeft);
11068 }
11069 
11070 Address RISCVABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
11071                                 QualType Ty) const {
11072   CharUnits SlotSize = CharUnits::fromQuantity(XLen / 8);
11073 
11074   // Empty records are ignored for parameter passing purposes.
11075   if (isEmptyRecord(getContext(), Ty, true)) {
11076     Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize);
11077     Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
11078     return Addr;
11079   }
11080 
11081   auto TInfo = getContext().getTypeInfoInChars(Ty);
11082 
11083   // Arguments bigger than 2*Xlen bytes are passed indirectly.
11084   bool IsIndirect = TInfo.Width > 2 * SlotSize;
11085 
11086   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TInfo,
11087                           SlotSize, /*AllowHigherAlign=*/true);
11088 }
11089 
11090 ABIArgInfo RISCVABIInfo::extendType(QualType Ty) const {
11091   int TySize = getContext().getTypeSize(Ty);
11092   // RV64 ABI requires unsigned 32 bit integers to be sign extended.
11093   if (XLen == 64 && Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
11094     return ABIArgInfo::getSignExtend(Ty);
11095   return ABIArgInfo::getExtend(Ty);
11096 }
11097 
11098 namespace {
11099 class RISCVTargetCodeGenInfo : public TargetCodeGenInfo {
11100 public:
11101   RISCVTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, unsigned XLen,
11102                          unsigned FLen)
11103       : TargetCodeGenInfo(std::make_unique<RISCVABIInfo>(CGT, XLen, FLen)) {}
11104 
11105   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
11106                            CodeGen::CodeGenModule &CGM) const override {
11107     const auto *FD = dyn_cast_or_null<FunctionDecl>(D);
11108     if (!FD) return;
11109 
11110     const auto *Attr = FD->getAttr<RISCVInterruptAttr>();
11111     if (!Attr)
11112       return;
11113 
11114     const char *Kind;
11115     switch (Attr->getInterrupt()) {
11116     case RISCVInterruptAttr::user: Kind = "user"; break;
11117     case RISCVInterruptAttr::supervisor: Kind = "supervisor"; break;
11118     case RISCVInterruptAttr::machine: Kind = "machine"; break;
11119     }
11120 
11121     auto *Fn = cast<llvm::Function>(GV);
11122 
11123     Fn->addFnAttr("interrupt", Kind);
11124   }
11125 };
11126 } // namespace
11127 
11128 //===----------------------------------------------------------------------===//
11129 // VE ABI Implementation.
11130 //
11131 namespace {
11132 class VEABIInfo : public DefaultABIInfo {
11133 public:
11134   VEABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
11135 
11136 private:
11137   ABIArgInfo classifyReturnType(QualType RetTy) const;
11138   ABIArgInfo classifyArgumentType(QualType RetTy) const;
11139   void computeInfo(CGFunctionInfo &FI) const override;
11140 };
11141 } // end anonymous namespace
11142 
11143 ABIArgInfo VEABIInfo::classifyReturnType(QualType Ty) const {
11144   if (Ty->isAnyComplexType())
11145     return ABIArgInfo::getDirect();
11146   uint64_t Size = getContext().getTypeSize(Ty);
11147   if (Size < 64 && Ty->isIntegerType())
11148     return ABIArgInfo::getExtend(Ty);
11149   return DefaultABIInfo::classifyReturnType(Ty);
11150 }
11151 
11152 ABIArgInfo VEABIInfo::classifyArgumentType(QualType Ty) const {
11153   if (Ty->isAnyComplexType())
11154     return ABIArgInfo::getDirect();
11155   uint64_t Size = getContext().getTypeSize(Ty);
11156   if (Size < 64 && Ty->isIntegerType())
11157     return ABIArgInfo::getExtend(Ty);
11158   return DefaultABIInfo::classifyArgumentType(Ty);
11159 }
11160 
11161 void VEABIInfo::computeInfo(CGFunctionInfo &FI) const {
11162   FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
11163   for (auto &Arg : FI.arguments())
11164     Arg.info = classifyArgumentType(Arg.type);
11165 }
11166 
11167 namespace {
11168 class VETargetCodeGenInfo : public TargetCodeGenInfo {
11169 public:
11170   VETargetCodeGenInfo(CodeGenTypes &CGT)
11171       : TargetCodeGenInfo(std::make_unique<VEABIInfo>(CGT)) {}
11172   // VE ABI requires the arguments of variadic and prototype-less functions
11173   // are passed in both registers and memory.
11174   bool isNoProtoCallVariadic(const CallArgList &args,
11175                              const FunctionNoProtoType *fnType) const override {
11176     return true;
11177   }
11178 };
11179 } // end anonymous namespace
11180 
11181 //===----------------------------------------------------------------------===//
11182 // Driver code
11183 //===----------------------------------------------------------------------===//
11184 
11185 bool CodeGenModule::supportsCOMDAT() const {
11186   return getTriple().supportsCOMDAT();
11187 }
11188 
11189 const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
11190   if (TheTargetCodeGenInfo)
11191     return *TheTargetCodeGenInfo;
11192 
11193   // Helper to set the unique_ptr while still keeping the return value.
11194   auto SetCGInfo = [&](TargetCodeGenInfo *P) -> const TargetCodeGenInfo & {
11195     this->TheTargetCodeGenInfo.reset(P);
11196     return *P;
11197   };
11198 
11199   const llvm::Triple &Triple = getTarget().getTriple();
11200   switch (Triple.getArch()) {
11201   default:
11202     return SetCGInfo(new DefaultTargetCodeGenInfo(Types));
11203 
11204   case llvm::Triple::le32:
11205     return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
11206   case llvm::Triple::m68k:
11207     return SetCGInfo(new M68kTargetCodeGenInfo(Types));
11208   case llvm::Triple::mips:
11209   case llvm::Triple::mipsel:
11210     if (Triple.getOS() == llvm::Triple::NaCl)
11211       return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
11212     return SetCGInfo(new MIPSTargetCodeGenInfo(Types, true));
11213 
11214   case llvm::Triple::mips64:
11215   case llvm::Triple::mips64el:
11216     return SetCGInfo(new MIPSTargetCodeGenInfo(Types, false));
11217 
11218   case llvm::Triple::avr:
11219     return SetCGInfo(new AVRTargetCodeGenInfo(Types));
11220 
11221   case llvm::Triple::aarch64:
11222   case llvm::Triple::aarch64_32:
11223   case llvm::Triple::aarch64_be: {
11224     AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS;
11225     if (getTarget().getABI() == "darwinpcs")
11226       Kind = AArch64ABIInfo::DarwinPCS;
11227     else if (Triple.isOSWindows())
11228       return SetCGInfo(
11229           new WindowsAArch64TargetCodeGenInfo(Types, AArch64ABIInfo::Win64));
11230 
11231     return SetCGInfo(new AArch64TargetCodeGenInfo(Types, Kind));
11232   }
11233 
11234   case llvm::Triple::wasm32:
11235   case llvm::Triple::wasm64: {
11236     WebAssemblyABIInfo::ABIKind Kind = WebAssemblyABIInfo::MVP;
11237     if (getTarget().getABI() == "experimental-mv")
11238       Kind = WebAssemblyABIInfo::ExperimentalMV;
11239     return SetCGInfo(new WebAssemblyTargetCodeGenInfo(Types, Kind));
11240   }
11241 
11242   case llvm::Triple::arm:
11243   case llvm::Triple::armeb:
11244   case llvm::Triple::thumb:
11245   case llvm::Triple::thumbeb: {
11246     if (Triple.getOS() == llvm::Triple::Win32) {
11247       return SetCGInfo(
11248           new WindowsARMTargetCodeGenInfo(Types, ARMABIInfo::AAPCS_VFP));
11249     }
11250 
11251     ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
11252     StringRef ABIStr = getTarget().getABI();
11253     if (ABIStr == "apcs-gnu")
11254       Kind = ARMABIInfo::APCS;
11255     else if (ABIStr == "aapcs16")
11256       Kind = ARMABIInfo::AAPCS16_VFP;
11257     else if (CodeGenOpts.FloatABI == "hard" ||
11258              (CodeGenOpts.FloatABI != "soft" &&
11259               (Triple.getEnvironment() == llvm::Triple::GNUEABIHF ||
11260                Triple.getEnvironment() == llvm::Triple::MuslEABIHF ||
11261                Triple.getEnvironment() == llvm::Triple::EABIHF)))
11262       Kind = ARMABIInfo::AAPCS_VFP;
11263 
11264     return SetCGInfo(new ARMTargetCodeGenInfo(Types, Kind));
11265   }
11266 
11267   case llvm::Triple::ppc: {
11268     if (Triple.isOSAIX())
11269       return SetCGInfo(new AIXTargetCodeGenInfo(Types, /*Is64Bit*/ false));
11270 
11271     bool IsSoftFloat =
11272         CodeGenOpts.FloatABI == "soft" || getTarget().hasFeature("spe");
11273     bool RetSmallStructInRegABI =
11274         PPC32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
11275     return SetCGInfo(
11276         new PPC32TargetCodeGenInfo(Types, IsSoftFloat, RetSmallStructInRegABI));
11277   }
11278   case llvm::Triple::ppcle: {
11279     bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
11280     bool RetSmallStructInRegABI =
11281         PPC32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
11282     return SetCGInfo(
11283         new PPC32TargetCodeGenInfo(Types, IsSoftFloat, RetSmallStructInRegABI));
11284   }
11285   case llvm::Triple::ppc64:
11286     if (Triple.isOSAIX())
11287       return SetCGInfo(new AIXTargetCodeGenInfo(Types, /*Is64Bit*/ true));
11288 
11289     if (Triple.isOSBinFormatELF()) {
11290       PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1;
11291       if (getTarget().getABI() == "elfv2")
11292         Kind = PPC64_SVR4_ABIInfo::ELFv2;
11293       bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
11294 
11295       return SetCGInfo(
11296           new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, IsSoftFloat));
11297     }
11298     return SetCGInfo(new PPC64TargetCodeGenInfo(Types));
11299   case llvm::Triple::ppc64le: {
11300     assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
11301     PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2;
11302     if (getTarget().getABI() == "elfv1")
11303       Kind = PPC64_SVR4_ABIInfo::ELFv1;
11304     bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
11305 
11306     return SetCGInfo(
11307         new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, IsSoftFloat));
11308   }
11309 
11310   case llvm::Triple::nvptx:
11311   case llvm::Triple::nvptx64:
11312     return SetCGInfo(new NVPTXTargetCodeGenInfo(Types));
11313 
11314   case llvm::Triple::msp430:
11315     return SetCGInfo(new MSP430TargetCodeGenInfo(Types));
11316 
11317   case llvm::Triple::riscv32:
11318   case llvm::Triple::riscv64: {
11319     StringRef ABIStr = getTarget().getABI();
11320     unsigned XLen = getTarget().getPointerWidth(0);
11321     unsigned ABIFLen = 0;
11322     if (ABIStr.endswith("f"))
11323       ABIFLen = 32;
11324     else if (ABIStr.endswith("d"))
11325       ABIFLen = 64;
11326     return SetCGInfo(new RISCVTargetCodeGenInfo(Types, XLen, ABIFLen));
11327   }
11328 
11329   case llvm::Triple::systemz: {
11330     bool SoftFloat = CodeGenOpts.FloatABI == "soft";
11331     bool HasVector = !SoftFloat && getTarget().getABI() == "vector";
11332     return SetCGInfo(new SystemZTargetCodeGenInfo(Types, HasVector, SoftFloat));
11333   }
11334 
11335   case llvm::Triple::tce:
11336   case llvm::Triple::tcele:
11337     return SetCGInfo(new TCETargetCodeGenInfo(Types));
11338 
11339   case llvm::Triple::x86: {
11340     bool IsDarwinVectorABI = Triple.isOSDarwin();
11341     bool RetSmallStructInRegABI =
11342         X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
11343     bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
11344 
11345     if (Triple.getOS() == llvm::Triple::Win32) {
11346       return SetCGInfo(new WinX86_32TargetCodeGenInfo(
11347           Types, IsDarwinVectorABI, RetSmallStructInRegABI,
11348           IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters));
11349     } else {
11350       return SetCGInfo(new X86_32TargetCodeGenInfo(
11351           Types, IsDarwinVectorABI, RetSmallStructInRegABI,
11352           IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters,
11353           CodeGenOpts.FloatABI == "soft"));
11354     }
11355   }
11356 
11357   case llvm::Triple::x86_64: {
11358     StringRef ABI = getTarget().getABI();
11359     X86AVXABILevel AVXLevel =
11360         (ABI == "avx512"
11361              ? X86AVXABILevel::AVX512
11362              : ABI == "avx" ? X86AVXABILevel::AVX : X86AVXABILevel::None);
11363 
11364     switch (Triple.getOS()) {
11365     case llvm::Triple::Win32:
11366       return SetCGInfo(new WinX86_64TargetCodeGenInfo(Types, AVXLevel));
11367     default:
11368       return SetCGInfo(new X86_64TargetCodeGenInfo(Types, AVXLevel));
11369     }
11370   }
11371   case llvm::Triple::hexagon:
11372     return SetCGInfo(new HexagonTargetCodeGenInfo(Types));
11373   case llvm::Triple::lanai:
11374     return SetCGInfo(new LanaiTargetCodeGenInfo(Types));
11375   case llvm::Triple::r600:
11376     return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
11377   case llvm::Triple::amdgcn:
11378     return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
11379   case llvm::Triple::sparc:
11380     return SetCGInfo(new SparcV8TargetCodeGenInfo(Types));
11381   case llvm::Triple::sparcv9:
11382     return SetCGInfo(new SparcV9TargetCodeGenInfo(Types));
11383   case llvm::Triple::xcore:
11384     return SetCGInfo(new XCoreTargetCodeGenInfo(Types));
11385   case llvm::Triple::arc:
11386     return SetCGInfo(new ARCTargetCodeGenInfo(Types));
11387   case llvm::Triple::spir:
11388   case llvm::Triple::spir64:
11389     return SetCGInfo(new CommonSPIRTargetCodeGenInfo(Types));
11390   case llvm::Triple::spirv32:
11391   case llvm::Triple::spirv64:
11392     return SetCGInfo(new SPIRVTargetCodeGenInfo(Types));
11393   case llvm::Triple::ve:
11394     return SetCGInfo(new VETargetCodeGenInfo(Types));
11395   }
11396 }
11397 
11398 /// Create an OpenCL kernel for an enqueued block.
11399 ///
11400 /// The kernel has the same function type as the block invoke function. Its
11401 /// name is the name of the block invoke function postfixed with "_kernel".
11402 /// It simply calls the block invoke function then returns.
11403 llvm::Function *
11404 TargetCodeGenInfo::createEnqueuedBlockKernel(CodeGenFunction &CGF,
11405                                              llvm::Function *Invoke,
11406                                              llvm::Value *BlockLiteral) const {
11407   auto *InvokeFT = Invoke->getFunctionType();
11408   llvm::SmallVector<llvm::Type *, 2> ArgTys;
11409   for (auto &P : InvokeFT->params())
11410     ArgTys.push_back(P);
11411   auto &C = CGF.getLLVMContext();
11412   std::string Name = Invoke->getName().str() + "_kernel";
11413   auto *FT = llvm::FunctionType::get(llvm::Type::getVoidTy(C), ArgTys, false);
11414   auto *F = llvm::Function::Create(FT, llvm::GlobalValue::ExternalLinkage, Name,
11415                                    &CGF.CGM.getModule());
11416   auto IP = CGF.Builder.saveIP();
11417   auto *BB = llvm::BasicBlock::Create(C, "entry", F);
11418   auto &Builder = CGF.Builder;
11419   Builder.SetInsertPoint(BB);
11420   llvm::SmallVector<llvm::Value *, 2> Args;
11421   for (auto &A : F->args())
11422     Args.push_back(&A);
11423   llvm::CallInst *call = Builder.CreateCall(Invoke, Args);
11424   call->setCallingConv(Invoke->getCallingConv());
11425   Builder.CreateRetVoid();
11426   Builder.restoreIP(IP);
11427   return F;
11428 }
11429 
11430 /// Create an OpenCL kernel for an enqueued block.
11431 ///
11432 /// The type of the first argument (the block literal) is the struct type
11433 /// of the block literal instead of a pointer type. The first argument
11434 /// (block literal) is passed directly by value to the kernel. The kernel
11435 /// allocates the same type of struct on stack and stores the block literal
11436 /// to it and passes its pointer to the block invoke function. The kernel
11437 /// has "enqueued-block" function attribute and kernel argument metadata.
11438 llvm::Function *AMDGPUTargetCodeGenInfo::createEnqueuedBlockKernel(
11439     CodeGenFunction &CGF, llvm::Function *Invoke,
11440     llvm::Value *BlockLiteral) const {
11441   auto &Builder = CGF.Builder;
11442   auto &C = CGF.getLLVMContext();
11443 
11444   auto *BlockTy = BlockLiteral->getType()->getPointerElementType();
11445   auto *InvokeFT = Invoke->getFunctionType();
11446   llvm::SmallVector<llvm::Type *, 2> ArgTys;
11447   llvm::SmallVector<llvm::Metadata *, 8> AddressQuals;
11448   llvm::SmallVector<llvm::Metadata *, 8> AccessQuals;
11449   llvm::SmallVector<llvm::Metadata *, 8> ArgTypeNames;
11450   llvm::SmallVector<llvm::Metadata *, 8> ArgBaseTypeNames;
11451   llvm::SmallVector<llvm::Metadata *, 8> ArgTypeQuals;
11452   llvm::SmallVector<llvm::Metadata *, 8> ArgNames;
11453 
11454   ArgTys.push_back(BlockTy);
11455   ArgTypeNames.push_back(llvm::MDString::get(C, "__block_literal"));
11456   AddressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(0)));
11457   ArgBaseTypeNames.push_back(llvm::MDString::get(C, "__block_literal"));
11458   ArgTypeQuals.push_back(llvm::MDString::get(C, ""));
11459   AccessQuals.push_back(llvm::MDString::get(C, "none"));
11460   ArgNames.push_back(llvm::MDString::get(C, "block_literal"));
11461   for (unsigned I = 1, E = InvokeFT->getNumParams(); I < E; ++I) {
11462     ArgTys.push_back(InvokeFT->getParamType(I));
11463     ArgTypeNames.push_back(llvm::MDString::get(C, "void*"));
11464     AddressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(3)));
11465     AccessQuals.push_back(llvm::MDString::get(C, "none"));
11466     ArgBaseTypeNames.push_back(llvm::MDString::get(C, "void*"));
11467     ArgTypeQuals.push_back(llvm::MDString::get(C, ""));
11468     ArgNames.push_back(
11469         llvm::MDString::get(C, (Twine("local_arg") + Twine(I)).str()));
11470   }
11471   std::string Name = Invoke->getName().str() + "_kernel";
11472   auto *FT = llvm::FunctionType::get(llvm::Type::getVoidTy(C), ArgTys, false);
11473   auto *F = llvm::Function::Create(FT, llvm::GlobalValue::InternalLinkage, Name,
11474                                    &CGF.CGM.getModule());
11475   F->addFnAttr("enqueued-block");
11476   auto IP = CGF.Builder.saveIP();
11477   auto *BB = llvm::BasicBlock::Create(C, "entry", F);
11478   Builder.SetInsertPoint(BB);
11479   const auto BlockAlign = CGF.CGM.getDataLayout().getPrefTypeAlign(BlockTy);
11480   auto *BlockPtr = Builder.CreateAlloca(BlockTy, nullptr);
11481   BlockPtr->setAlignment(BlockAlign);
11482   Builder.CreateAlignedStore(F->arg_begin(), BlockPtr, BlockAlign);
11483   auto *Cast = Builder.CreatePointerCast(BlockPtr, InvokeFT->getParamType(0));
11484   llvm::SmallVector<llvm::Value *, 2> Args;
11485   Args.push_back(Cast);
11486   for (auto I = F->arg_begin() + 1, E = F->arg_end(); I != E; ++I)
11487     Args.push_back(I);
11488   llvm::CallInst *call = Builder.CreateCall(Invoke, Args);
11489   call->setCallingConv(Invoke->getCallingConv());
11490   Builder.CreateRetVoid();
11491   Builder.restoreIP(IP);
11492 
11493   F->setMetadata("kernel_arg_addr_space", llvm::MDNode::get(C, AddressQuals));
11494   F->setMetadata("kernel_arg_access_qual", llvm::MDNode::get(C, AccessQuals));
11495   F->setMetadata("kernel_arg_type", llvm::MDNode::get(C, ArgTypeNames));
11496   F->setMetadata("kernel_arg_base_type",
11497                  llvm::MDNode::get(C, ArgBaseTypeNames));
11498   F->setMetadata("kernel_arg_type_qual", llvm::MDNode::get(C, ArgTypeQuals));
11499   if (CGF.CGM.getCodeGenOpts().EmitOpenCLArgMetadata)
11500     F->setMetadata("kernel_arg_name", llvm::MDNode::get(C, ArgNames));
11501 
11502   return F;
11503 }
11504