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/Builtins.h"
23 #include "clang/Basic/CodeGenOptions.h"
24 #include "clang/Basic/DiagnosticFrontend.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/MathExtras.h"
37 #include "llvm/Support/raw_ostream.h"
38 #include <algorithm> // std::sort
39 
40 using namespace clang;
41 using namespace CodeGen;
42 
43 // Helper for coercing an aggregate argument or return value into an integer
44 // array of the same size (including padding) and alignment.  This alternate
45 // coercion happens only for the RenderScript ABI and can be removed after
46 // runtimes that rely on it are no longer supported.
47 //
48 // RenderScript assumes that the size of the argument / return value in the IR
49 // is the same as the size of the corresponding qualified type. This helper
50 // coerces the aggregate type into an array of the same size (including
51 // padding).  This coercion is used in lieu of expansion of struct members or
52 // other canonical coercions that return a coerced-type of larger size.
53 //
54 // Ty          - The argument / return value type
55 // Context     - The associated ASTContext
56 // LLVMContext - The associated LLVMContext
57 static ABIArgInfo coerceToIntArray(QualType Ty,
58                                    ASTContext &Context,
59                                    llvm::LLVMContext &LLVMContext) {
60   // Alignment and Size are measured in bits.
61   const uint64_t Size = Context.getTypeSize(Ty);
62   const uint64_t Alignment = Context.getTypeAlign(Ty);
63   llvm::Type *IntType = llvm::Type::getIntNTy(LLVMContext, Alignment);
64   const uint64_t NumElements = (Size + Alignment - 1) / Alignment;
65   return ABIArgInfo::getDirect(llvm::ArrayType::get(IntType, NumElements));
66 }
67 
68 static void AssignToArrayRange(CodeGen::CGBuilderTy &Builder,
69                                llvm::Value *Array,
70                                llvm::Value *Value,
71                                unsigned FirstIndex,
72                                unsigned LastIndex) {
73   // Alternatively, we could emit this as a loop in the source.
74   for (unsigned I = FirstIndex; I <= LastIndex; ++I) {
75     llvm::Value *Cell =
76         Builder.CreateConstInBoundsGEP1_32(Builder.getInt8Ty(), Array, I);
77     Builder.CreateAlignedStore(Value, Cell, CharUnits::One());
78   }
79 }
80 
81 static bool isAggregateTypeForABI(QualType T) {
82   return !CodeGenFunction::hasScalarEvaluationKind(T) ||
83          T->isMemberFunctionPointerType();
84 }
85 
86 ABIArgInfo ABIInfo::getNaturalAlignIndirect(QualType Ty, bool ByVal,
87                                             bool Realign,
88                                             llvm::Type *Padding) const {
89   return ABIArgInfo::getIndirect(getContext().getTypeAlignInChars(Ty), ByVal,
90                                  Realign, Padding);
91 }
92 
93 ABIArgInfo
94 ABIInfo::getNaturalAlignIndirectInReg(QualType Ty, bool Realign) const {
95   return ABIArgInfo::getIndirectInReg(getContext().getTypeAlignInChars(Ty),
96                                       /*ByVal*/ false, Realign);
97 }
98 
99 Address ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
100                              QualType Ty) const {
101   return Address::invalid();
102 }
103 
104 static llvm::Type *getVAListElementType(CodeGenFunction &CGF) {
105   return CGF.ConvertTypeForMem(
106       CGF.getContext().getBuiltinVaListType()->getPointeeType());
107 }
108 
109 bool ABIInfo::isPromotableIntegerTypeForABI(QualType Ty) const {
110   if (Ty->isPromotableIntegerType())
111     return true;
112 
113   if (const auto *EIT = Ty->getAs<BitIntType>())
114     if (EIT->getNumBits() < getContext().getTypeSize(getContext().IntTy))
115       return true;
116 
117   return false;
118 }
119 
120 ABIInfo::~ABIInfo() {}
121 
122 /// Does the given lowering require more than the given number of
123 /// registers when expanded?
124 ///
125 /// This is intended to be the basis of a reasonable basic implementation
126 /// of should{Pass,Return}IndirectlyForSwift.
127 ///
128 /// For most targets, a limit of four total registers is reasonable; this
129 /// limits the amount of code required in order to move around the value
130 /// in case it wasn't produced immediately prior to the call by the caller
131 /// (or wasn't produced in exactly the right registers) or isn't used
132 /// immediately within the callee.  But some targets may need to further
133 /// limit the register count due to an inability to support that many
134 /// return registers.
135 static bool occupiesMoreThan(CodeGenTypes &cgt,
136                              ArrayRef<llvm::Type*> scalarTypes,
137                              unsigned maxAllRegisters) {
138   unsigned intCount = 0, fpCount = 0;
139   for (llvm::Type *type : scalarTypes) {
140     if (type->isPointerTy()) {
141       intCount++;
142     } else if (auto intTy = dyn_cast<llvm::IntegerType>(type)) {
143       auto ptrWidth = cgt.getTarget().getPointerWidth(0);
144       intCount += (intTy->getBitWidth() + ptrWidth - 1) / ptrWidth;
145     } else {
146       assert(type->isVectorTy() || type->isFloatingPointTy());
147       fpCount++;
148     }
149   }
150 
151   return (intCount + fpCount > maxAllRegisters);
152 }
153 
154 bool SwiftABIInfo::isLegalVectorTypeForSwift(CharUnits vectorSize,
155                                              llvm::Type *eltTy,
156                                              unsigned numElts) const {
157   // The default implementation of this assumes that the target guarantees
158   // 128-bit SIMD support but nothing more.
159   return (vectorSize.getQuantity() > 8 && vectorSize.getQuantity() <= 16);
160 }
161 
162 static CGCXXABI::RecordArgABI getRecordArgABI(const RecordType *RT,
163                                               CGCXXABI &CXXABI) {
164   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
165   if (!RD) {
166     if (!RT->getDecl()->canPassInRegisters())
167       return CGCXXABI::RAA_Indirect;
168     return CGCXXABI::RAA_Default;
169   }
170   return CXXABI.getRecordArgABI(RD);
171 }
172 
173 static CGCXXABI::RecordArgABI getRecordArgABI(QualType T,
174                                               CGCXXABI &CXXABI) {
175   const RecordType *RT = T->getAs<RecordType>();
176   if (!RT)
177     return CGCXXABI::RAA_Default;
178   return getRecordArgABI(RT, CXXABI);
179 }
180 
181 static bool classifyReturnType(const CGCXXABI &CXXABI, CGFunctionInfo &FI,
182                                const ABIInfo &Info) {
183   QualType Ty = FI.getReturnType();
184 
185   if (const auto *RT = Ty->getAs<RecordType>())
186     if (!isa<CXXRecordDecl>(RT->getDecl()) &&
187         !RT->getDecl()->canPassInRegisters()) {
188       FI.getReturnInfo() = Info.getNaturalAlignIndirect(Ty);
189       return true;
190     }
191 
192   return CXXABI.classifyReturnType(FI);
193 }
194 
195 /// Pass transparent unions as if they were the type of the first element. Sema
196 /// should ensure that all elements of the union have the same "machine type".
197 static QualType useFirstFieldIfTransparentUnion(QualType Ty) {
198   if (const RecordType *UT = Ty->getAsUnionType()) {
199     const RecordDecl *UD = UT->getDecl();
200     if (UD->hasAttr<TransparentUnionAttr>()) {
201       assert(!UD->field_empty() && "sema created an empty transparent union");
202       return UD->field_begin()->getType();
203     }
204   }
205   return Ty;
206 }
207 
208 CGCXXABI &ABIInfo::getCXXABI() const {
209   return CGT.getCXXABI();
210 }
211 
212 ASTContext &ABIInfo::getContext() const {
213   return CGT.getContext();
214 }
215 
216 llvm::LLVMContext &ABIInfo::getVMContext() const {
217   return CGT.getLLVMContext();
218 }
219 
220 const llvm::DataLayout &ABIInfo::getDataLayout() const {
221   return CGT.getDataLayout();
222 }
223 
224 const TargetInfo &ABIInfo::getTarget() const {
225   return CGT.getTarget();
226 }
227 
228 const CodeGenOptions &ABIInfo::getCodeGenOpts() const {
229   return CGT.getCodeGenOpts();
230 }
231 
232 bool ABIInfo::isAndroid() const { return getTarget().getTriple().isAndroid(); }
233 
234 bool ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
235   return false;
236 }
237 
238 bool ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
239                                                 uint64_t Members) const {
240   return false;
241 }
242 
243 LLVM_DUMP_METHOD void ABIArgInfo::dump() const {
244   raw_ostream &OS = llvm::errs();
245   OS << "(ABIArgInfo Kind=";
246   switch (TheKind) {
247   case Direct:
248     OS << "Direct Type=";
249     if (llvm::Type *Ty = getCoerceToType())
250       Ty->print(OS);
251     else
252       OS << "null";
253     break;
254   case Extend:
255     OS << "Extend";
256     break;
257   case Ignore:
258     OS << "Ignore";
259     break;
260   case InAlloca:
261     OS << "InAlloca Offset=" << getInAllocaFieldIndex();
262     break;
263   case Indirect:
264     OS << "Indirect Align=" << getIndirectAlign().getQuantity()
265        << " ByVal=" << getIndirectByVal()
266        << " Realign=" << getIndirectRealign();
267     break;
268   case IndirectAliased:
269     OS << "Indirect Align=" << getIndirectAlign().getQuantity()
270        << " AadrSpace=" << getIndirectAddrSpace()
271        << " Realign=" << getIndirectRealign();
272     break;
273   case Expand:
274     OS << "Expand";
275     break;
276   case CoerceAndExpand:
277     OS << "CoerceAndExpand Type=";
278     getCoerceAndExpandType()->print(OS);
279     break;
280   }
281   OS << ")\n";
282 }
283 
284 // Dynamically round a pointer up to a multiple of the given alignment.
285 static llvm::Value *emitRoundPointerUpToAlignment(CodeGenFunction &CGF,
286                                                   llvm::Value *Ptr,
287                                                   CharUnits Align) {
288   llvm::Value *PtrAsInt = Ptr;
289   // OverflowArgArea = (OverflowArgArea + Align - 1) & -Align;
290   PtrAsInt = CGF.Builder.CreatePtrToInt(PtrAsInt, CGF.IntPtrTy);
291   PtrAsInt = CGF.Builder.CreateAdd(PtrAsInt,
292         llvm::ConstantInt::get(CGF.IntPtrTy, Align.getQuantity() - 1));
293   PtrAsInt = CGF.Builder.CreateAnd(PtrAsInt,
294            llvm::ConstantInt::get(CGF.IntPtrTy, -Align.getQuantity()));
295   PtrAsInt = CGF.Builder.CreateIntToPtr(PtrAsInt,
296                                         Ptr->getType(),
297                                         Ptr->getName() + ".aligned");
298   return PtrAsInt;
299 }
300 
301 /// Emit va_arg for a platform using the common void* representation,
302 /// where arguments are simply emitted in an array of slots on the stack.
303 ///
304 /// This version implements the core direct-value passing rules.
305 ///
306 /// \param SlotSize - The size and alignment of a stack slot.
307 ///   Each argument will be allocated to a multiple of this number of
308 ///   slots, and all the slots will be aligned to this value.
309 /// \param AllowHigherAlign - The slot alignment is not a cap;
310 ///   an argument type with an alignment greater than the slot size
311 ///   will be emitted on a higher-alignment address, potentially
312 ///   leaving one or more empty slots behind as padding.  If this
313 ///   is false, the returned address might be less-aligned than
314 ///   DirectAlign.
315 static Address emitVoidPtrDirectVAArg(CodeGenFunction &CGF,
316                                       Address VAListAddr,
317                                       llvm::Type *DirectTy,
318                                       CharUnits DirectSize,
319                                       CharUnits DirectAlign,
320                                       CharUnits SlotSize,
321                                       bool AllowHigherAlign) {
322   // Cast the element type to i8* if necessary.  Some platforms define
323   // va_list as a struct containing an i8* instead of just an i8*.
324   if (VAListAddr.getElementType() != CGF.Int8PtrTy)
325     VAListAddr = CGF.Builder.CreateElementBitCast(VAListAddr, CGF.Int8PtrTy);
326 
327   llvm::Value *Ptr = CGF.Builder.CreateLoad(VAListAddr, "argp.cur");
328 
329   // If the CC aligns values higher than the slot size, do so if needed.
330   Address Addr = Address::invalid();
331   if (AllowHigherAlign && DirectAlign > SlotSize) {
332     Addr = Address(emitRoundPointerUpToAlignment(CGF, Ptr, DirectAlign),
333                    CGF.Int8Ty, DirectAlign);
334   } else {
335     Addr = Address(Ptr, CGF.Int8Ty, SlotSize);
336   }
337 
338   // Advance the pointer past the argument, then store that back.
339   CharUnits FullDirectSize = DirectSize.alignTo(SlotSize);
340   Address NextPtr =
341       CGF.Builder.CreateConstInBoundsByteGEP(Addr, FullDirectSize, "argp.next");
342   CGF.Builder.CreateStore(NextPtr.getPointer(), VAListAddr);
343 
344   // If the argument is smaller than a slot, and this is a big-endian
345   // target, the argument will be right-adjusted in its slot.
346   if (DirectSize < SlotSize && CGF.CGM.getDataLayout().isBigEndian() &&
347       !DirectTy->isStructTy()) {
348     Addr = CGF.Builder.CreateConstInBoundsByteGEP(Addr, SlotSize - DirectSize);
349   }
350 
351   Addr = CGF.Builder.CreateElementBitCast(Addr, DirectTy);
352   return Addr;
353 }
354 
355 /// Emit va_arg for a platform using the common void* representation,
356 /// where arguments are simply emitted in an array of slots on the stack.
357 ///
358 /// \param IsIndirect - Values of this type are passed indirectly.
359 /// \param ValueInfo - The size and alignment of this type, generally
360 ///   computed with getContext().getTypeInfoInChars(ValueTy).
361 /// \param SlotSizeAndAlign - The size and alignment of a stack slot.
362 ///   Each argument will be allocated to a multiple of this number of
363 ///   slots, and all the slots will be aligned to this value.
364 /// \param AllowHigherAlign - The slot alignment is not a cap;
365 ///   an argument type with an alignment greater than the slot size
366 ///   will be emitted on a higher-alignment address, potentially
367 ///   leaving one or more empty slots behind as padding.
368 static Address emitVoidPtrVAArg(CodeGenFunction &CGF, Address VAListAddr,
369                                 QualType ValueTy, bool IsIndirect,
370                                 TypeInfoChars ValueInfo,
371                                 CharUnits SlotSizeAndAlign,
372                                 bool AllowHigherAlign) {
373   // The size and alignment of the value that was passed directly.
374   CharUnits DirectSize, DirectAlign;
375   if (IsIndirect) {
376     DirectSize = CGF.getPointerSize();
377     DirectAlign = CGF.getPointerAlign();
378   } else {
379     DirectSize = ValueInfo.Width;
380     DirectAlign = ValueInfo.Align;
381   }
382 
383   // Cast the address we've calculated to the right type.
384   llvm::Type *DirectTy = CGF.ConvertTypeForMem(ValueTy), *ElementTy = DirectTy;
385   if (IsIndirect)
386     DirectTy = DirectTy->getPointerTo(0);
387 
388   Address Addr =
389       emitVoidPtrDirectVAArg(CGF, VAListAddr, DirectTy, DirectSize, DirectAlign,
390                              SlotSizeAndAlign, AllowHigherAlign);
391 
392   if (IsIndirect) {
393     Addr = Address(CGF.Builder.CreateLoad(Addr), ElementTy, ValueInfo.Align);
394   }
395 
396   return Addr;
397 }
398 
399 static Address complexTempStructure(CodeGenFunction &CGF, Address VAListAddr,
400                                     QualType Ty, CharUnits SlotSize,
401                                     CharUnits EltSize, const ComplexType *CTy) {
402   Address Addr =
403       emitVoidPtrDirectVAArg(CGF, VAListAddr, CGF.Int8Ty, SlotSize * 2,
404                              SlotSize, SlotSize, /*AllowHigher*/ true);
405 
406   Address RealAddr = Addr;
407   Address ImagAddr = RealAddr;
408   if (CGF.CGM.getDataLayout().isBigEndian()) {
409     RealAddr =
410         CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, SlotSize - EltSize);
411     ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(ImagAddr,
412                                                       2 * SlotSize - EltSize);
413   } else {
414     ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, SlotSize);
415   }
416 
417   llvm::Type *EltTy = CGF.ConvertTypeForMem(CTy->getElementType());
418   RealAddr = CGF.Builder.CreateElementBitCast(RealAddr, EltTy);
419   ImagAddr = CGF.Builder.CreateElementBitCast(ImagAddr, EltTy);
420   llvm::Value *Real = CGF.Builder.CreateLoad(RealAddr, ".vareal");
421   llvm::Value *Imag = CGF.Builder.CreateLoad(ImagAddr, ".vaimag");
422 
423   Address Temp = CGF.CreateMemTemp(Ty, "vacplx");
424   CGF.EmitStoreOfComplex({Real, Imag}, CGF.MakeAddrLValue(Temp, Ty),
425                          /*init*/ true);
426   return Temp;
427 }
428 
429 static Address emitMergePHI(CodeGenFunction &CGF,
430                             Address Addr1, llvm::BasicBlock *Block1,
431                             Address Addr2, llvm::BasicBlock *Block2,
432                             const llvm::Twine &Name = "") {
433   assert(Addr1.getType() == Addr2.getType());
434   llvm::PHINode *PHI = CGF.Builder.CreatePHI(Addr1.getType(), 2, Name);
435   PHI->addIncoming(Addr1.getPointer(), Block1);
436   PHI->addIncoming(Addr2.getPointer(), Block2);
437   CharUnits Align = std::min(Addr1.getAlignment(), Addr2.getAlignment());
438   return Address(PHI, Addr1.getElementType(), Align);
439 }
440 
441 TargetCodeGenInfo::~TargetCodeGenInfo() = default;
442 
443 // If someone can figure out a general rule for this, that would be great.
444 // It's probably just doomed to be platform-dependent, though.
445 unsigned TargetCodeGenInfo::getSizeOfUnwindException() const {
446   // Verified for:
447   //   x86-64     FreeBSD, Linux, Darwin
448   //   x86-32     FreeBSD, Linux, Darwin
449   //   PowerPC    Linux, Darwin
450   //   ARM        Darwin (*not* EABI)
451   //   AArch64    Linux
452   return 32;
453 }
454 
455 bool TargetCodeGenInfo::isNoProtoCallVariadic(const CallArgList &args,
456                                      const FunctionNoProtoType *fnType) const {
457   // The following conventions are known to require this to be false:
458   //   x86_stdcall
459   //   MIPS
460   // For everything else, we just prefer false unless we opt out.
461   return false;
462 }
463 
464 void
465 TargetCodeGenInfo::getDependentLibraryOption(llvm::StringRef Lib,
466                                              llvm::SmallString<24> &Opt) const {
467   // This assumes the user is passing a library name like "rt" instead of a
468   // filename like "librt.a/so", and that they don't care whether it's static or
469   // dynamic.
470   Opt = "-l";
471   Opt += Lib;
472 }
473 
474 unsigned TargetCodeGenInfo::getOpenCLKernelCallingConv() const {
475   // OpenCL kernels are called via an explicit runtime API with arguments
476   // set with clSetKernelArg(), not as normal sub-functions.
477   // Return SPIR_KERNEL by default as the kernel calling convention to
478   // ensure the fingerprint is fixed such way that each OpenCL argument
479   // gets one matching argument in the produced kernel function argument
480   // list to enable feasible implementation of clSetKernelArg() with
481   // aggregates etc. In case we would use the default C calling conv here,
482   // clSetKernelArg() might break depending on the target-specific
483   // conventions; different targets might split structs passed as values
484   // to multiple function arguments etc.
485   return llvm::CallingConv::SPIR_KERNEL;
486 }
487 
488 llvm::Constant *TargetCodeGenInfo::getNullPointer(const CodeGen::CodeGenModule &CGM,
489     llvm::PointerType *T, QualType QT) const {
490   return llvm::ConstantPointerNull::get(T);
491 }
492 
493 LangAS TargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM,
494                                                    const VarDecl *D) const {
495   assert(!CGM.getLangOpts().OpenCL &&
496          !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) &&
497          "Address space agnostic languages only");
498   return D ? D->getType().getAddressSpace() : LangAS::Default;
499 }
500 
501 llvm::Value *TargetCodeGenInfo::performAddrSpaceCast(
502     CodeGen::CodeGenFunction &CGF, llvm::Value *Src, LangAS SrcAddr,
503     LangAS DestAddr, llvm::Type *DestTy, bool isNonNull) const {
504   // Since target may map different address spaces in AST to the same address
505   // space, an address space conversion may end up as a bitcast.
506   if (auto *C = dyn_cast<llvm::Constant>(Src))
507     return performAddrSpaceCast(CGF.CGM, C, SrcAddr, DestAddr, DestTy);
508   // Try to preserve the source's name to make IR more readable.
509   return CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
510       Src, DestTy, Src->hasName() ? Src->getName() + ".ascast" : "");
511 }
512 
513 llvm::Constant *
514 TargetCodeGenInfo::performAddrSpaceCast(CodeGenModule &CGM, llvm::Constant *Src,
515                                         LangAS SrcAddr, LangAS DestAddr,
516                                         llvm::Type *DestTy) const {
517   // Since target may map different address spaces in AST to the same address
518   // space, an address space conversion may end up as a bitcast.
519   return llvm::ConstantExpr::getPointerCast(Src, DestTy);
520 }
521 
522 llvm::SyncScope::ID
523 TargetCodeGenInfo::getLLVMSyncScopeID(const LangOptions &LangOpts,
524                                       SyncScope Scope,
525                                       llvm::AtomicOrdering Ordering,
526                                       llvm::LLVMContext &Ctx) const {
527   return Ctx.getOrInsertSyncScopeID(""); /* default sync scope */
528 }
529 
530 static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays);
531 
532 /// isEmptyField - Return true iff a the field is "empty", that is it
533 /// is an unnamed bit-field or an (array of) empty record(s).
534 static bool isEmptyField(ASTContext &Context, const FieldDecl *FD,
535                          bool AllowArrays) {
536   if (FD->isUnnamedBitfield())
537     return true;
538 
539   QualType FT = FD->getType();
540 
541   // Constant arrays of empty records count as empty, strip them off.
542   // Constant arrays of zero length always count as empty.
543   bool WasArray = false;
544   if (AllowArrays)
545     while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
546       if (AT->getSize() == 0)
547         return true;
548       FT = AT->getElementType();
549       // The [[no_unique_address]] special case below does not apply to
550       // arrays of C++ empty records, so we need to remember this fact.
551       WasArray = true;
552     }
553 
554   const RecordType *RT = FT->getAs<RecordType>();
555   if (!RT)
556     return false;
557 
558   // C++ record fields are never empty, at least in the Itanium ABI.
559   //
560   // FIXME: We should use a predicate for whether this behavior is true in the
561   // current ABI.
562   //
563   // The exception to the above rule are fields marked with the
564   // [[no_unique_address]] attribute (since C++20).  Those do count as empty
565   // according to the Itanium ABI.  The exception applies only to records,
566   // not arrays of records, so we must also check whether we stripped off an
567   // array type above.
568   if (isa<CXXRecordDecl>(RT->getDecl()) &&
569       (WasArray || !FD->hasAttr<NoUniqueAddressAttr>()))
570     return false;
571 
572   return isEmptyRecord(Context, FT, AllowArrays);
573 }
574 
575 /// isEmptyRecord - Return true iff a structure contains only empty
576 /// fields. Note that a structure with a flexible array member is not
577 /// considered empty.
578 static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) {
579   const RecordType *RT = T->getAs<RecordType>();
580   if (!RT)
581     return false;
582   const RecordDecl *RD = RT->getDecl();
583   if (RD->hasFlexibleArrayMember())
584     return false;
585 
586   // If this is a C++ record, check the bases first.
587   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
588     for (const auto &I : CXXRD->bases())
589       if (!isEmptyRecord(Context, I.getType(), true))
590         return false;
591 
592   for (const auto *I : RD->fields())
593     if (!isEmptyField(Context, I, AllowArrays))
594       return false;
595   return true;
596 }
597 
598 /// isSingleElementStruct - Determine if a structure is a "single
599 /// element struct", i.e. it has exactly one non-empty field or
600 /// exactly one field which is itself a single element
601 /// struct. Structures with flexible array members are never
602 /// considered single element structs.
603 ///
604 /// \return The field declaration for the single non-empty field, if
605 /// it exists.
606 static const Type *isSingleElementStruct(QualType T, ASTContext &Context) {
607   const RecordType *RT = T->getAs<RecordType>();
608   if (!RT)
609     return nullptr;
610 
611   const RecordDecl *RD = RT->getDecl();
612   if (RD->hasFlexibleArrayMember())
613     return nullptr;
614 
615   const Type *Found = nullptr;
616 
617   // If this is a C++ record, check the bases first.
618   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
619     for (const auto &I : CXXRD->bases()) {
620       // Ignore empty records.
621       if (isEmptyRecord(Context, I.getType(), true))
622         continue;
623 
624       // If we already found an element then this isn't a single-element struct.
625       if (Found)
626         return nullptr;
627 
628       // If this is non-empty and not a single element struct, the composite
629       // cannot be a single element struct.
630       Found = isSingleElementStruct(I.getType(), Context);
631       if (!Found)
632         return nullptr;
633     }
634   }
635 
636   // Check for single element.
637   for (const auto *FD : RD->fields()) {
638     QualType FT = FD->getType();
639 
640     // Ignore empty fields.
641     if (isEmptyField(Context, FD, true))
642       continue;
643 
644     // If we already found an element then this isn't a single-element
645     // struct.
646     if (Found)
647       return nullptr;
648 
649     // Treat single element arrays as the element.
650     while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
651       if (AT->getSize().getZExtValue() != 1)
652         break;
653       FT = AT->getElementType();
654     }
655 
656     if (!isAggregateTypeForABI(FT)) {
657       Found = FT.getTypePtr();
658     } else {
659       Found = isSingleElementStruct(FT, Context);
660       if (!Found)
661         return nullptr;
662     }
663   }
664 
665   // We don't consider a struct a single-element struct if it has
666   // padding beyond the element type.
667   if (Found && Context.getTypeSize(Found) != Context.getTypeSize(T))
668     return nullptr;
669 
670   return Found;
671 }
672 
673 namespace {
674 Address EmitVAArgInstr(CodeGenFunction &CGF, Address VAListAddr, QualType Ty,
675                        const ABIArgInfo &AI) {
676   // This default implementation defers to the llvm backend's va_arg
677   // instruction. It can handle only passing arguments directly
678   // (typically only handled in the backend for primitive types), or
679   // aggregates passed indirectly by pointer (NOTE: if the "byval"
680   // flag has ABI impact in the callee, this implementation cannot
681   // work.)
682 
683   // Only a few cases are covered here at the moment -- those needed
684   // by the default abi.
685   llvm::Value *Val;
686 
687   if (AI.isIndirect()) {
688     assert(!AI.getPaddingType() &&
689            "Unexpected PaddingType seen in arginfo in generic VAArg emitter!");
690     assert(
691         !AI.getIndirectRealign() &&
692         "Unexpected IndirectRealign seen in arginfo in generic VAArg emitter!");
693 
694     auto TyInfo = CGF.getContext().getTypeInfoInChars(Ty);
695     CharUnits TyAlignForABI = TyInfo.Align;
696 
697     llvm::Type *ElementTy = CGF.ConvertTypeForMem(Ty);
698     llvm::Type *BaseTy = llvm::PointerType::getUnqual(ElementTy);
699     llvm::Value *Addr =
700         CGF.Builder.CreateVAArg(VAListAddr.getPointer(), BaseTy);
701     return Address(Addr, ElementTy, TyAlignForABI);
702   } else {
703     assert((AI.isDirect() || AI.isExtend()) &&
704            "Unexpected ArgInfo Kind in generic VAArg emitter!");
705 
706     assert(!AI.getInReg() &&
707            "Unexpected InReg seen in arginfo in generic VAArg emitter!");
708     assert(!AI.getPaddingType() &&
709            "Unexpected PaddingType seen in arginfo in generic VAArg emitter!");
710     assert(!AI.getDirectOffset() &&
711            "Unexpected DirectOffset seen in arginfo in generic VAArg emitter!");
712     assert(!AI.getCoerceToType() &&
713            "Unexpected CoerceToType seen in arginfo in generic VAArg emitter!");
714 
715     Address Temp = CGF.CreateMemTemp(Ty, "varet");
716     Val = CGF.Builder.CreateVAArg(VAListAddr.getPointer(),
717                                   CGF.ConvertTypeForMem(Ty));
718     CGF.Builder.CreateStore(Val, Temp);
719     return Temp;
720   }
721 }
722 
723 /// DefaultABIInfo - The default implementation for ABI specific
724 /// details. This implementation provides information which results in
725 /// self-consistent and sensible LLVM IR generation, but does not
726 /// conform to any particular ABI.
727 class DefaultABIInfo : public ABIInfo {
728 public:
729   DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
730 
731   ABIArgInfo classifyReturnType(QualType RetTy) const;
732   ABIArgInfo classifyArgumentType(QualType RetTy) const;
733 
734   void computeInfo(CGFunctionInfo &FI) const override {
735     if (!getCXXABI().classifyReturnType(FI))
736       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
737     for (auto &I : FI.arguments())
738       I.info = classifyArgumentType(I.type);
739   }
740 
741   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
742                     QualType Ty) const override {
743     return EmitVAArgInstr(CGF, VAListAddr, Ty, classifyArgumentType(Ty));
744   }
745 };
746 
747 class DefaultTargetCodeGenInfo : public TargetCodeGenInfo {
748 public:
749   DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
750       : TargetCodeGenInfo(std::make_unique<DefaultABIInfo>(CGT)) {}
751 };
752 
753 ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const {
754   Ty = useFirstFieldIfTransparentUnion(Ty);
755 
756   if (isAggregateTypeForABI(Ty)) {
757     // Records with non-trivial destructors/copy-constructors should not be
758     // passed by value.
759     if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
760       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
761 
762     return getNaturalAlignIndirect(Ty);
763   }
764 
765   // Treat an enum type as its underlying type.
766   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
767     Ty = EnumTy->getDecl()->getIntegerType();
768 
769   ASTContext &Context = getContext();
770   if (const auto *EIT = Ty->getAs<BitIntType>())
771     if (EIT->getNumBits() >
772         Context.getTypeSize(Context.getTargetInfo().hasInt128Type()
773                                 ? Context.Int128Ty
774                                 : Context.LongLongTy))
775       return getNaturalAlignIndirect(Ty);
776 
777   return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
778                                             : ABIArgInfo::getDirect());
779 }
780 
781 ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const {
782   if (RetTy->isVoidType())
783     return ABIArgInfo::getIgnore();
784 
785   if (isAggregateTypeForABI(RetTy))
786     return getNaturalAlignIndirect(RetTy);
787 
788   // Treat an enum type as its underlying type.
789   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
790     RetTy = EnumTy->getDecl()->getIntegerType();
791 
792   if (const auto *EIT = RetTy->getAs<BitIntType>())
793     if (EIT->getNumBits() >
794         getContext().getTypeSize(getContext().getTargetInfo().hasInt128Type()
795                                      ? getContext().Int128Ty
796                                      : getContext().LongLongTy))
797       return getNaturalAlignIndirect(RetTy);
798 
799   return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
800                                                : ABIArgInfo::getDirect());
801 }
802 
803 //===----------------------------------------------------------------------===//
804 // WebAssembly ABI Implementation
805 //
806 // This is a very simple ABI that relies a lot on DefaultABIInfo.
807 //===----------------------------------------------------------------------===//
808 
809 class WebAssemblyABIInfo final : public SwiftABIInfo {
810 public:
811   enum ABIKind {
812     MVP = 0,
813     ExperimentalMV = 1,
814   };
815 
816 private:
817   DefaultABIInfo defaultInfo;
818   ABIKind Kind;
819 
820 public:
821   explicit WebAssemblyABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind)
822       : SwiftABIInfo(CGT), defaultInfo(CGT), Kind(Kind) {}
823 
824 private:
825   ABIArgInfo classifyReturnType(QualType RetTy) const;
826   ABIArgInfo classifyArgumentType(QualType Ty) const;
827 
828   // DefaultABIInfo's classifyReturnType and classifyArgumentType are
829   // non-virtual, but computeInfo and EmitVAArg are virtual, so we
830   // overload them.
831   void computeInfo(CGFunctionInfo &FI) const override {
832     if (!getCXXABI().classifyReturnType(FI))
833       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
834     for (auto &Arg : FI.arguments())
835       Arg.info = classifyArgumentType(Arg.type);
836   }
837 
838   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
839                     QualType Ty) const override;
840 
841   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
842                                     bool asReturnValue) const override {
843     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
844   }
845 
846   bool isSwiftErrorInRegister() const override {
847     return false;
848   }
849 };
850 
851 class WebAssemblyTargetCodeGenInfo final : public TargetCodeGenInfo {
852 public:
853   explicit WebAssemblyTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
854                                         WebAssemblyABIInfo::ABIKind K)
855       : TargetCodeGenInfo(std::make_unique<WebAssemblyABIInfo>(CGT, K)) {}
856 
857   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
858                            CodeGen::CodeGenModule &CGM) const override {
859     TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
860     if (const auto *FD = dyn_cast_or_null<FunctionDecl>(D)) {
861       if (const auto *Attr = FD->getAttr<WebAssemblyImportModuleAttr>()) {
862         llvm::Function *Fn = cast<llvm::Function>(GV);
863         llvm::AttrBuilder B(GV->getContext());
864         B.addAttribute("wasm-import-module", Attr->getImportModule());
865         Fn->addFnAttrs(B);
866       }
867       if (const auto *Attr = FD->getAttr<WebAssemblyImportNameAttr>()) {
868         llvm::Function *Fn = cast<llvm::Function>(GV);
869         llvm::AttrBuilder B(GV->getContext());
870         B.addAttribute("wasm-import-name", Attr->getImportName());
871         Fn->addFnAttrs(B);
872       }
873       if (const auto *Attr = FD->getAttr<WebAssemblyExportNameAttr>()) {
874         llvm::Function *Fn = cast<llvm::Function>(GV);
875         llvm::AttrBuilder B(GV->getContext());
876         B.addAttribute("wasm-export-name", Attr->getExportName());
877         Fn->addFnAttrs(B);
878       }
879     }
880 
881     if (auto *FD = dyn_cast_or_null<FunctionDecl>(D)) {
882       llvm::Function *Fn = cast<llvm::Function>(GV);
883       if (!FD->doesThisDeclarationHaveABody() && !FD->hasPrototype())
884         Fn->addFnAttr("no-prototype");
885     }
886   }
887 };
888 
889 /// Classify argument of given type \p Ty.
890 ABIArgInfo WebAssemblyABIInfo::classifyArgumentType(QualType Ty) const {
891   Ty = useFirstFieldIfTransparentUnion(Ty);
892 
893   if (isAggregateTypeForABI(Ty)) {
894     // Records with non-trivial destructors/copy-constructors should not be
895     // passed by value.
896     if (auto RAA = getRecordArgABI(Ty, getCXXABI()))
897       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
898     // Ignore empty structs/unions.
899     if (isEmptyRecord(getContext(), Ty, true))
900       return ABIArgInfo::getIgnore();
901     // Lower single-element structs to just pass a regular value. TODO: We
902     // could do reasonable-size multiple-element structs too, using getExpand(),
903     // though watch out for things like bitfields.
904     if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
905       return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
906     // For the experimental multivalue ABI, fully expand all other aggregates
907     if (Kind == ABIKind::ExperimentalMV) {
908       const RecordType *RT = Ty->getAs<RecordType>();
909       assert(RT);
910       bool HasBitField = false;
911       for (auto *Field : RT->getDecl()->fields()) {
912         if (Field->isBitField()) {
913           HasBitField = true;
914           break;
915         }
916       }
917       if (!HasBitField)
918         return ABIArgInfo::getExpand();
919     }
920   }
921 
922   // Otherwise just do the default thing.
923   return defaultInfo.classifyArgumentType(Ty);
924 }
925 
926 ABIArgInfo WebAssemblyABIInfo::classifyReturnType(QualType RetTy) const {
927   if (isAggregateTypeForABI(RetTy)) {
928     // Records with non-trivial destructors/copy-constructors should not be
929     // returned by value.
930     if (!getRecordArgABI(RetTy, getCXXABI())) {
931       // Ignore empty structs/unions.
932       if (isEmptyRecord(getContext(), RetTy, true))
933         return ABIArgInfo::getIgnore();
934       // Lower single-element structs to just return a regular value. TODO: We
935       // could do reasonable-size multiple-element structs too, using
936       // ABIArgInfo::getDirect().
937       if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
938         return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
939       // For the experimental multivalue ABI, return all other aggregates
940       if (Kind == ABIKind::ExperimentalMV)
941         return ABIArgInfo::getDirect();
942     }
943   }
944 
945   // Otherwise just do the default thing.
946   return defaultInfo.classifyReturnType(RetTy);
947 }
948 
949 Address WebAssemblyABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
950                                       QualType Ty) const {
951   bool IsIndirect = isAggregateTypeForABI(Ty) &&
952                     !isEmptyRecord(getContext(), Ty, true) &&
953                     !isSingleElementStruct(Ty, getContext());
954   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
955                           getContext().getTypeInfoInChars(Ty),
956                           CharUnits::fromQuantity(4),
957                           /*AllowHigherAlign=*/true);
958 }
959 
960 //===----------------------------------------------------------------------===//
961 // le32/PNaCl bitcode ABI Implementation
962 //
963 // This is a simplified version of the x86_32 ABI.  Arguments and return values
964 // are always passed on the stack.
965 //===----------------------------------------------------------------------===//
966 
967 class PNaClABIInfo : public ABIInfo {
968  public:
969   PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
970 
971   ABIArgInfo classifyReturnType(QualType RetTy) const;
972   ABIArgInfo classifyArgumentType(QualType RetTy) const;
973 
974   void computeInfo(CGFunctionInfo &FI) const override;
975   Address EmitVAArg(CodeGenFunction &CGF,
976                     Address VAListAddr, QualType Ty) const override;
977 };
978 
979 class PNaClTargetCodeGenInfo : public TargetCodeGenInfo {
980  public:
981    PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
982        : TargetCodeGenInfo(std::make_unique<PNaClABIInfo>(CGT)) {}
983 };
984 
985 void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const {
986   if (!getCXXABI().classifyReturnType(FI))
987     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
988 
989   for (auto &I : FI.arguments())
990     I.info = classifyArgumentType(I.type);
991 }
992 
993 Address PNaClABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
994                                 QualType Ty) const {
995   // The PNaCL ABI is a bit odd, in that varargs don't use normal
996   // function classification. Structs get passed directly for varargs
997   // functions, through a rewriting transform in
998   // pnacl-llvm/lib/Transforms/NaCl/ExpandVarArgs.cpp, which allows
999   // this target to actually support a va_arg instructions with an
1000   // aggregate type, unlike other targets.
1001   return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
1002 }
1003 
1004 /// Classify argument of given type \p Ty.
1005 ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const {
1006   if (isAggregateTypeForABI(Ty)) {
1007     if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
1008       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
1009     return getNaturalAlignIndirect(Ty);
1010   } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
1011     // Treat an enum type as its underlying type.
1012     Ty = EnumTy->getDecl()->getIntegerType();
1013   } else if (Ty->isFloatingType()) {
1014     // Floating-point types don't go inreg.
1015     return ABIArgInfo::getDirect();
1016   } else if (const auto *EIT = Ty->getAs<BitIntType>()) {
1017     // Treat bit-precise integers as integers if <= 64, otherwise pass
1018     // indirectly.
1019     if (EIT->getNumBits() > 64)
1020       return getNaturalAlignIndirect(Ty);
1021     return ABIArgInfo::getDirect();
1022   }
1023 
1024   return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
1025                                             : ABIArgInfo::getDirect());
1026 }
1027 
1028 ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const {
1029   if (RetTy->isVoidType())
1030     return ABIArgInfo::getIgnore();
1031 
1032   // In the PNaCl ABI we always return records/structures on the stack.
1033   if (isAggregateTypeForABI(RetTy))
1034     return getNaturalAlignIndirect(RetTy);
1035 
1036   // Treat bit-precise integers as integers if <= 64, otherwise pass indirectly.
1037   if (const auto *EIT = RetTy->getAs<BitIntType>()) {
1038     if (EIT->getNumBits() > 64)
1039       return getNaturalAlignIndirect(RetTy);
1040     return ABIArgInfo::getDirect();
1041   }
1042 
1043   // Treat an enum type as its underlying type.
1044   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
1045     RetTy = EnumTy->getDecl()->getIntegerType();
1046 
1047   return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
1048                                                : ABIArgInfo::getDirect());
1049 }
1050 
1051 /// IsX86_MMXType - Return true if this is an MMX type.
1052 bool IsX86_MMXType(llvm::Type *IRType) {
1053   // Return true if the type is an MMX type <2 x i32>, <4 x i16>, or <8 x i8>.
1054   return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 &&
1055     cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() &&
1056     IRType->getScalarSizeInBits() != 64;
1057 }
1058 
1059 static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
1060                                           StringRef Constraint,
1061                                           llvm::Type* Ty) {
1062   bool IsMMXCons = llvm::StringSwitch<bool>(Constraint)
1063                      .Cases("y", "&y", "^Ym", true)
1064                      .Default(false);
1065   if (IsMMXCons && Ty->isVectorTy()) {
1066     if (cast<llvm::VectorType>(Ty)->getPrimitiveSizeInBits().getFixedSize() !=
1067         64) {
1068       // Invalid MMX constraint
1069       return nullptr;
1070     }
1071 
1072     return llvm::Type::getX86_MMXTy(CGF.getLLVMContext());
1073   }
1074 
1075   // No operation needed
1076   return Ty;
1077 }
1078 
1079 /// Returns true if this type can be passed in SSE registers with the
1080 /// X86_VectorCall calling convention. Shared between x86_32 and x86_64.
1081 static bool isX86VectorTypeForVectorCall(ASTContext &Context, QualType Ty) {
1082   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
1083     if (BT->isFloatingPoint() && BT->getKind() != BuiltinType::Half) {
1084       if (BT->getKind() == BuiltinType::LongDouble) {
1085         if (&Context.getTargetInfo().getLongDoubleFormat() ==
1086             &llvm::APFloat::x87DoubleExtended())
1087           return false;
1088       }
1089       return true;
1090     }
1091   } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
1092     // vectorcall can pass XMM, YMM, and ZMM vectors. We don't pass SSE1 MMX
1093     // registers specially.
1094     unsigned VecSize = Context.getTypeSize(VT);
1095     if (VecSize == 128 || VecSize == 256 || VecSize == 512)
1096       return true;
1097   }
1098   return false;
1099 }
1100 
1101 /// Returns true if this aggregate is small enough to be passed in SSE registers
1102 /// in the X86_VectorCall calling convention. Shared between x86_32 and x86_64.
1103 static bool isX86VectorCallAggregateSmallEnough(uint64_t NumMembers) {
1104   return NumMembers <= 4;
1105 }
1106 
1107 /// Returns a Homogeneous Vector Aggregate ABIArgInfo, used in X86.
1108 static ABIArgInfo getDirectX86Hva(llvm::Type* T = nullptr) {
1109   auto AI = ABIArgInfo::getDirect(T);
1110   AI.setInReg(true);
1111   AI.setCanBeFlattened(false);
1112   return AI;
1113 }
1114 
1115 //===----------------------------------------------------------------------===//
1116 // X86-32 ABI Implementation
1117 //===----------------------------------------------------------------------===//
1118 
1119 /// Similar to llvm::CCState, but for Clang.
1120 struct CCState {
1121   CCState(CGFunctionInfo &FI)
1122       : IsPreassigned(FI.arg_size()), CC(FI.getCallingConvention()) {}
1123 
1124   llvm::SmallBitVector IsPreassigned;
1125   unsigned CC = CallingConv::CC_C;
1126   unsigned FreeRegs = 0;
1127   unsigned FreeSSERegs = 0;
1128 };
1129 
1130 /// X86_32ABIInfo - The X86-32 ABI information.
1131 class X86_32ABIInfo : public SwiftABIInfo {
1132   enum Class {
1133     Integer,
1134     Float
1135   };
1136 
1137   static const unsigned MinABIStackAlignInBytes = 4;
1138 
1139   bool IsDarwinVectorABI;
1140   bool IsRetSmallStructInRegABI;
1141   bool IsWin32StructABI;
1142   bool IsSoftFloatABI;
1143   bool IsMCUABI;
1144   bool IsLinuxABI;
1145   unsigned DefaultNumRegisterParameters;
1146 
1147   static bool isRegisterSize(unsigned Size) {
1148     return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
1149   }
1150 
1151   bool isHomogeneousAggregateBaseType(QualType Ty) const override {
1152     // FIXME: Assumes vectorcall is in use.
1153     return isX86VectorTypeForVectorCall(getContext(), Ty);
1154   }
1155 
1156   bool isHomogeneousAggregateSmallEnough(const Type *Ty,
1157                                          uint64_t NumMembers) const override {
1158     // FIXME: Assumes vectorcall is in use.
1159     return isX86VectorCallAggregateSmallEnough(NumMembers);
1160   }
1161 
1162   bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context) const;
1163 
1164   /// getIndirectResult - Give a source type \arg Ty, return a suitable result
1165   /// such that the argument will be passed in memory.
1166   ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
1167 
1168   ABIArgInfo getIndirectReturnResult(QualType Ty, CCState &State) const;
1169 
1170   /// Return the alignment to use for the given type on the stack.
1171   unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const;
1172 
1173   Class classify(QualType Ty) const;
1174   ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const;
1175   ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
1176 
1177   /// Updates the number of available free registers, returns
1178   /// true if any registers were allocated.
1179   bool updateFreeRegs(QualType Ty, CCState &State) const;
1180 
1181   bool shouldAggregateUseDirect(QualType Ty, CCState &State, bool &InReg,
1182                                 bool &NeedsPadding) const;
1183   bool shouldPrimitiveUseInReg(QualType Ty, CCState &State) const;
1184 
1185   bool canExpandIndirectArgument(QualType Ty) const;
1186 
1187   /// Rewrite the function info so that all memory arguments use
1188   /// inalloca.
1189   void rewriteWithInAlloca(CGFunctionInfo &FI) const;
1190 
1191   void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
1192                            CharUnits &StackOffset, ABIArgInfo &Info,
1193                            QualType Type) const;
1194   void runVectorCallFirstPass(CGFunctionInfo &FI, CCState &State) const;
1195 
1196 public:
1197 
1198   void computeInfo(CGFunctionInfo &FI) const override;
1199   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
1200                     QualType Ty) const override;
1201 
1202   X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
1203                 bool RetSmallStructInRegABI, bool Win32StructABI,
1204                 unsigned NumRegisterParameters, bool SoftFloatABI)
1205     : SwiftABIInfo(CGT), IsDarwinVectorABI(DarwinVectorABI),
1206       IsRetSmallStructInRegABI(RetSmallStructInRegABI),
1207       IsWin32StructABI(Win32StructABI), IsSoftFloatABI(SoftFloatABI),
1208       IsMCUABI(CGT.getTarget().getTriple().isOSIAMCU()),
1209       IsLinuxABI(CGT.getTarget().getTriple().isOSLinux() ||
1210                  CGT.getTarget().getTriple().isOSCygMing()),
1211       DefaultNumRegisterParameters(NumRegisterParameters) {}
1212 
1213   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
1214                                     bool asReturnValue) const override {
1215     // LLVM's x86-32 lowering currently only assigns up to three
1216     // integer registers and three fp registers.  Oddly, it'll use up to
1217     // four vector registers for vectors, but those can overlap with the
1218     // scalar registers.
1219     return occupiesMoreThan(CGT, scalars, /*total*/ 3);
1220   }
1221 
1222   bool isSwiftErrorInRegister() const override {
1223     // x86-32 lowering does not support passing swifterror in a register.
1224     return false;
1225   }
1226 };
1227 
1228 class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
1229 public:
1230   X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
1231                           bool RetSmallStructInRegABI, bool Win32StructABI,
1232                           unsigned NumRegisterParameters, bool SoftFloatABI)
1233       : TargetCodeGenInfo(std::make_unique<X86_32ABIInfo>(
1234             CGT, DarwinVectorABI, RetSmallStructInRegABI, Win32StructABI,
1235             NumRegisterParameters, SoftFloatABI)) {}
1236 
1237   static bool isStructReturnInRegABI(
1238       const llvm::Triple &Triple, const CodeGenOptions &Opts);
1239 
1240   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
1241                            CodeGen::CodeGenModule &CGM) const override;
1242 
1243   int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
1244     // Darwin uses different dwarf register numbers for EH.
1245     if (CGM.getTarget().getTriple().isOSDarwin()) return 5;
1246     return 4;
1247   }
1248 
1249   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
1250                                llvm::Value *Address) const override;
1251 
1252   llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
1253                                   StringRef Constraint,
1254                                   llvm::Type* Ty) const override {
1255     return X86AdjustInlineAsmType(CGF, Constraint, Ty);
1256   }
1257 
1258   void addReturnRegisterOutputs(CodeGenFunction &CGF, LValue ReturnValue,
1259                                 std::string &Constraints,
1260                                 std::vector<llvm::Type *> &ResultRegTypes,
1261                                 std::vector<llvm::Type *> &ResultTruncRegTypes,
1262                                 std::vector<LValue> &ResultRegDests,
1263                                 std::string &AsmString,
1264                                 unsigned NumOutputs) const override;
1265 
1266   llvm::Constant *
1267   getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
1268     unsigned Sig = (0xeb << 0) |  // jmp rel8
1269                    (0x06 << 8) |  //           .+0x08
1270                    ('v' << 16) |
1271                    ('2' << 24);
1272     return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
1273   }
1274 
1275   StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
1276     return "movl\t%ebp, %ebp"
1277            "\t\t// marker for objc_retainAutoreleaseReturnValue";
1278   }
1279 };
1280 
1281 }
1282 
1283 /// Rewrite input constraint references after adding some output constraints.
1284 /// In the case where there is one output and one input and we add one output,
1285 /// we need to replace all operand references greater than or equal to 1:
1286 ///     mov $0, $1
1287 ///     mov eax, $1
1288 /// The result will be:
1289 ///     mov $0, $2
1290 ///     mov eax, $2
1291 static void rewriteInputConstraintReferences(unsigned FirstIn,
1292                                              unsigned NumNewOuts,
1293                                              std::string &AsmString) {
1294   std::string Buf;
1295   llvm::raw_string_ostream OS(Buf);
1296   size_t Pos = 0;
1297   while (Pos < AsmString.size()) {
1298     size_t DollarStart = AsmString.find('$', Pos);
1299     if (DollarStart == std::string::npos)
1300       DollarStart = AsmString.size();
1301     size_t DollarEnd = AsmString.find_first_not_of('$', DollarStart);
1302     if (DollarEnd == std::string::npos)
1303       DollarEnd = AsmString.size();
1304     OS << StringRef(&AsmString[Pos], DollarEnd - Pos);
1305     Pos = DollarEnd;
1306     size_t NumDollars = DollarEnd - DollarStart;
1307     if (NumDollars % 2 != 0 && Pos < AsmString.size()) {
1308       // We have an operand reference.
1309       size_t DigitStart = Pos;
1310       if (AsmString[DigitStart] == '{') {
1311         OS << '{';
1312         ++DigitStart;
1313       }
1314       size_t DigitEnd = AsmString.find_first_not_of("0123456789", DigitStart);
1315       if (DigitEnd == std::string::npos)
1316         DigitEnd = AsmString.size();
1317       StringRef OperandStr(&AsmString[DigitStart], DigitEnd - DigitStart);
1318       unsigned OperandIndex;
1319       if (!OperandStr.getAsInteger(10, OperandIndex)) {
1320         if (OperandIndex >= FirstIn)
1321           OperandIndex += NumNewOuts;
1322         OS << OperandIndex;
1323       } else {
1324         OS << OperandStr;
1325       }
1326       Pos = DigitEnd;
1327     }
1328   }
1329   AsmString = std::move(OS.str());
1330 }
1331 
1332 /// Add output constraints for EAX:EDX because they are return registers.
1333 void X86_32TargetCodeGenInfo::addReturnRegisterOutputs(
1334     CodeGenFunction &CGF, LValue ReturnSlot, std::string &Constraints,
1335     std::vector<llvm::Type *> &ResultRegTypes,
1336     std::vector<llvm::Type *> &ResultTruncRegTypes,
1337     std::vector<LValue> &ResultRegDests, std::string &AsmString,
1338     unsigned NumOutputs) const {
1339   uint64_t RetWidth = CGF.getContext().getTypeSize(ReturnSlot.getType());
1340 
1341   // Use the EAX constraint if the width is 32 or smaller and EAX:EDX if it is
1342   // larger.
1343   if (!Constraints.empty())
1344     Constraints += ',';
1345   if (RetWidth <= 32) {
1346     Constraints += "={eax}";
1347     ResultRegTypes.push_back(CGF.Int32Ty);
1348   } else {
1349     // Use the 'A' constraint for EAX:EDX.
1350     Constraints += "=A";
1351     ResultRegTypes.push_back(CGF.Int64Ty);
1352   }
1353 
1354   // Truncate EAX or EAX:EDX to an integer of the appropriate size.
1355   llvm::Type *CoerceTy = llvm::IntegerType::get(CGF.getLLVMContext(), RetWidth);
1356   ResultTruncRegTypes.push_back(CoerceTy);
1357 
1358   // Coerce the integer by bitcasting the return slot pointer.
1359   ReturnSlot.setAddress(
1360       CGF.Builder.CreateElementBitCast(ReturnSlot.getAddress(CGF), CoerceTy));
1361   ResultRegDests.push_back(ReturnSlot);
1362 
1363   rewriteInputConstraintReferences(NumOutputs, 1, AsmString);
1364 }
1365 
1366 /// shouldReturnTypeInRegister - Determine if the given type should be
1367 /// returned in a register (for the Darwin and MCU ABI).
1368 bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
1369                                                ASTContext &Context) const {
1370   uint64_t Size = Context.getTypeSize(Ty);
1371 
1372   // For i386, type must be register sized.
1373   // For the MCU ABI, it only needs to be <= 8-byte
1374   if ((IsMCUABI && Size > 64) || (!IsMCUABI && !isRegisterSize(Size)))
1375    return false;
1376 
1377   if (Ty->isVectorType()) {
1378     // 64- and 128- bit vectors inside structures are not returned in
1379     // registers.
1380     if (Size == 64 || Size == 128)
1381       return false;
1382 
1383     return true;
1384   }
1385 
1386   // If this is a builtin, pointer, enum, complex type, member pointer, or
1387   // member function pointer it is ok.
1388   if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() ||
1389       Ty->isAnyComplexType() || Ty->isEnumeralType() ||
1390       Ty->isBlockPointerType() || Ty->isMemberPointerType())
1391     return true;
1392 
1393   // Arrays are treated like records.
1394   if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
1395     return shouldReturnTypeInRegister(AT->getElementType(), Context);
1396 
1397   // Otherwise, it must be a record type.
1398   const RecordType *RT = Ty->getAs<RecordType>();
1399   if (!RT) return false;
1400 
1401   // FIXME: Traverse bases here too.
1402 
1403   // Structure types are passed in register if all fields would be
1404   // passed in a register.
1405   for (const auto *FD : RT->getDecl()->fields()) {
1406     // Empty fields are ignored.
1407     if (isEmptyField(Context, FD, true))
1408       continue;
1409 
1410     // Check fields recursively.
1411     if (!shouldReturnTypeInRegister(FD->getType(), Context))
1412       return false;
1413   }
1414   return true;
1415 }
1416 
1417 static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
1418   // Treat complex types as the element type.
1419   if (const ComplexType *CTy = Ty->getAs<ComplexType>())
1420     Ty = CTy->getElementType();
1421 
1422   // Check for a type which we know has a simple scalar argument-passing
1423   // convention without any padding.  (We're specifically looking for 32
1424   // and 64-bit integer and integer-equivalents, float, and double.)
1425   if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() &&
1426       !Ty->isEnumeralType() && !Ty->isBlockPointerType())
1427     return false;
1428 
1429   uint64_t Size = Context.getTypeSize(Ty);
1430   return Size == 32 || Size == 64;
1431 }
1432 
1433 static bool addFieldSizes(ASTContext &Context, const RecordDecl *RD,
1434                           uint64_t &Size) {
1435   for (const auto *FD : RD->fields()) {
1436     // Scalar arguments on the stack get 4 byte alignment on x86. If the
1437     // argument is smaller than 32-bits, expanding the struct will create
1438     // alignment padding.
1439     if (!is32Or64BitBasicType(FD->getType(), Context))
1440       return false;
1441 
1442     // FIXME: Reject bit-fields wholesale; there are two problems, we don't know
1443     // how to expand them yet, and the predicate for telling if a bitfield still
1444     // counts as "basic" is more complicated than what we were doing previously.
1445     if (FD->isBitField())
1446       return false;
1447 
1448     Size += Context.getTypeSize(FD->getType());
1449   }
1450   return true;
1451 }
1452 
1453 static bool addBaseAndFieldSizes(ASTContext &Context, const CXXRecordDecl *RD,
1454                                  uint64_t &Size) {
1455   // Don't do this if there are any non-empty bases.
1456   for (const CXXBaseSpecifier &Base : RD->bases()) {
1457     if (!addBaseAndFieldSizes(Context, Base.getType()->getAsCXXRecordDecl(),
1458                               Size))
1459       return false;
1460   }
1461   if (!addFieldSizes(Context, RD, Size))
1462     return false;
1463   return true;
1464 }
1465 
1466 /// Test whether an argument type which is to be passed indirectly (on the
1467 /// stack) would have the equivalent layout if it was expanded into separate
1468 /// arguments. If so, we prefer to do the latter to avoid inhibiting
1469 /// optimizations.
1470 bool X86_32ABIInfo::canExpandIndirectArgument(QualType Ty) const {
1471   // We can only expand structure types.
1472   const RecordType *RT = Ty->getAs<RecordType>();
1473   if (!RT)
1474     return false;
1475   const RecordDecl *RD = RT->getDecl();
1476   uint64_t Size = 0;
1477   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
1478     if (!IsWin32StructABI) {
1479       // On non-Windows, we have to conservatively match our old bitcode
1480       // prototypes in order to be ABI-compatible at the bitcode level.
1481       if (!CXXRD->isCLike())
1482         return false;
1483     } else {
1484       // Don't do this for dynamic classes.
1485       if (CXXRD->isDynamicClass())
1486         return false;
1487     }
1488     if (!addBaseAndFieldSizes(getContext(), CXXRD, Size))
1489       return false;
1490   } else {
1491     if (!addFieldSizes(getContext(), RD, Size))
1492       return false;
1493   }
1494 
1495   // We can do this if there was no alignment padding.
1496   return Size == getContext().getTypeSize(Ty);
1497 }
1498 
1499 ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(QualType RetTy, CCState &State) const {
1500   // If the return value is indirect, then the hidden argument is consuming one
1501   // integer register.
1502   if (State.FreeRegs) {
1503     --State.FreeRegs;
1504     if (!IsMCUABI)
1505       return getNaturalAlignIndirectInReg(RetTy);
1506   }
1507   return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
1508 }
1509 
1510 ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy,
1511                                              CCState &State) const {
1512   if (RetTy->isVoidType())
1513     return ABIArgInfo::getIgnore();
1514 
1515   const Type *Base = nullptr;
1516   uint64_t NumElts = 0;
1517   if ((State.CC == llvm::CallingConv::X86_VectorCall ||
1518        State.CC == llvm::CallingConv::X86_RegCall) &&
1519       isHomogeneousAggregate(RetTy, Base, NumElts)) {
1520     // The LLVM struct type for such an aggregate should lower properly.
1521     return ABIArgInfo::getDirect();
1522   }
1523 
1524   if (const VectorType *VT = RetTy->getAs<VectorType>()) {
1525     // On Darwin, some vectors are returned in registers.
1526     if (IsDarwinVectorABI) {
1527       uint64_t Size = getContext().getTypeSize(RetTy);
1528 
1529       // 128-bit vectors are a special case; they are returned in
1530       // registers and we need to make sure to pick a type the LLVM
1531       // backend will like.
1532       if (Size == 128)
1533         return ABIArgInfo::getDirect(llvm::FixedVectorType::get(
1534             llvm::Type::getInt64Ty(getVMContext()), 2));
1535 
1536       // Always return in register if it fits in a general purpose
1537       // register, or if it is 64 bits and has a single element.
1538       if ((Size == 8 || Size == 16 || Size == 32) ||
1539           (Size == 64 && VT->getNumElements() == 1))
1540         return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
1541                                                             Size));
1542 
1543       return getIndirectReturnResult(RetTy, State);
1544     }
1545 
1546     return ABIArgInfo::getDirect();
1547   }
1548 
1549   if (isAggregateTypeForABI(RetTy)) {
1550     if (const RecordType *RT = RetTy->getAs<RecordType>()) {
1551       // Structures with flexible arrays are always indirect.
1552       if (RT->getDecl()->hasFlexibleArrayMember())
1553         return getIndirectReturnResult(RetTy, State);
1554     }
1555 
1556     // If specified, structs and unions are always indirect.
1557     if (!IsRetSmallStructInRegABI && !RetTy->isAnyComplexType())
1558       return getIndirectReturnResult(RetTy, State);
1559 
1560     // Ignore empty structs/unions.
1561     if (isEmptyRecord(getContext(), RetTy, true))
1562       return ABIArgInfo::getIgnore();
1563 
1564     // Return complex of _Float16 as <2 x half> so the backend will use xmm0.
1565     if (const ComplexType *CT = RetTy->getAs<ComplexType>()) {
1566       QualType ET = getContext().getCanonicalType(CT->getElementType());
1567       if (ET->isFloat16Type())
1568         return ABIArgInfo::getDirect(llvm::FixedVectorType::get(
1569             llvm::Type::getHalfTy(getVMContext()), 2));
1570     }
1571 
1572     // Small structures which are register sized are generally returned
1573     // in a register.
1574     if (shouldReturnTypeInRegister(RetTy, getContext())) {
1575       uint64_t Size = getContext().getTypeSize(RetTy);
1576 
1577       // As a special-case, if the struct is a "single-element" struct, and
1578       // the field is of type "float" or "double", return it in a
1579       // floating-point register. (MSVC does not apply this special case.)
1580       // We apply a similar transformation for pointer types to improve the
1581       // quality of the generated IR.
1582       if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
1583         if ((!IsWin32StructABI && SeltTy->isRealFloatingType())
1584             || SeltTy->hasPointerRepresentation())
1585           return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
1586 
1587       // FIXME: We should be able to narrow this integer in cases with dead
1588       // padding.
1589       return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
1590     }
1591 
1592     return getIndirectReturnResult(RetTy, State);
1593   }
1594 
1595   // Treat an enum type as its underlying type.
1596   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
1597     RetTy = EnumTy->getDecl()->getIntegerType();
1598 
1599   if (const auto *EIT = RetTy->getAs<BitIntType>())
1600     if (EIT->getNumBits() > 64)
1601       return getIndirectReturnResult(RetTy, State);
1602 
1603   return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
1604                                                : ABIArgInfo::getDirect());
1605 }
1606 
1607 static bool isSIMDVectorType(ASTContext &Context, QualType Ty) {
1608   return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128;
1609 }
1610 
1611 static bool isRecordWithSIMDVectorType(ASTContext &Context, QualType Ty) {
1612   const RecordType *RT = Ty->getAs<RecordType>();
1613   if (!RT)
1614     return false;
1615   const RecordDecl *RD = RT->getDecl();
1616 
1617   // If this is a C++ record, check the bases first.
1618   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
1619     for (const auto &I : CXXRD->bases())
1620       if (!isRecordWithSIMDVectorType(Context, I.getType()))
1621         return false;
1622 
1623   for (const auto *i : RD->fields()) {
1624     QualType FT = i->getType();
1625 
1626     if (isSIMDVectorType(Context, FT))
1627       return true;
1628 
1629     if (isRecordWithSIMDVectorType(Context, FT))
1630       return true;
1631   }
1632 
1633   return false;
1634 }
1635 
1636 unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
1637                                                  unsigned Align) const {
1638   // Otherwise, if the alignment is less than or equal to the minimum ABI
1639   // alignment, just use the default; the backend will handle this.
1640   if (Align <= MinABIStackAlignInBytes)
1641     return 0; // Use default alignment.
1642 
1643   if (IsLinuxABI) {
1644     // Exclude other System V OS (e.g Darwin, PS4 and FreeBSD) since we don't
1645     // want to spend any effort dealing with the ramifications of ABI breaks.
1646     //
1647     // If the vector type is __m128/__m256/__m512, return the default alignment.
1648     if (Ty->isVectorType() && (Align == 16 || Align == 32 || Align == 64))
1649       return Align;
1650   }
1651   // On non-Darwin, the stack type alignment is always 4.
1652   if (!IsDarwinVectorABI) {
1653     // Set explicit alignment, since we may need to realign the top.
1654     return MinABIStackAlignInBytes;
1655   }
1656 
1657   // Otherwise, if the type contains an SSE vector type, the alignment is 16.
1658   if (Align >= 16 && (isSIMDVectorType(getContext(), Ty) ||
1659                       isRecordWithSIMDVectorType(getContext(), Ty)))
1660     return 16;
1661 
1662   return MinABIStackAlignInBytes;
1663 }
1664 
1665 ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal,
1666                                             CCState &State) const {
1667   if (!ByVal) {
1668     if (State.FreeRegs) {
1669       --State.FreeRegs; // Non-byval indirects just use one pointer.
1670       if (!IsMCUABI)
1671         return getNaturalAlignIndirectInReg(Ty);
1672     }
1673     return getNaturalAlignIndirect(Ty, false);
1674   }
1675 
1676   // Compute the byval alignment.
1677   unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
1678   unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign);
1679   if (StackAlign == 0)
1680     return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true);
1681 
1682   // If the stack alignment is less than the type alignment, realign the
1683   // argument.
1684   bool Realign = TypeAlign > StackAlign;
1685   return ABIArgInfo::getIndirect(CharUnits::fromQuantity(StackAlign),
1686                                  /*ByVal=*/true, Realign);
1687 }
1688 
1689 X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const {
1690   const Type *T = isSingleElementStruct(Ty, getContext());
1691   if (!T)
1692     T = Ty.getTypePtr();
1693 
1694   if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
1695     BuiltinType::Kind K = BT->getKind();
1696     if (K == BuiltinType::Float || K == BuiltinType::Double)
1697       return Float;
1698   }
1699   return Integer;
1700 }
1701 
1702 bool X86_32ABIInfo::updateFreeRegs(QualType Ty, CCState &State) const {
1703   if (!IsSoftFloatABI) {
1704     Class C = classify(Ty);
1705     if (C == Float)
1706       return false;
1707   }
1708 
1709   unsigned Size = getContext().getTypeSize(Ty);
1710   unsigned SizeInRegs = (Size + 31) / 32;
1711 
1712   if (SizeInRegs == 0)
1713     return false;
1714 
1715   if (!IsMCUABI) {
1716     if (SizeInRegs > State.FreeRegs) {
1717       State.FreeRegs = 0;
1718       return false;
1719     }
1720   } else {
1721     // The MCU psABI allows passing parameters in-reg even if there are
1722     // earlier parameters that are passed on the stack. Also,
1723     // it does not allow passing >8-byte structs in-register,
1724     // even if there are 3 free registers available.
1725     if (SizeInRegs > State.FreeRegs || SizeInRegs > 2)
1726       return false;
1727   }
1728 
1729   State.FreeRegs -= SizeInRegs;
1730   return true;
1731 }
1732 
1733 bool X86_32ABIInfo::shouldAggregateUseDirect(QualType Ty, CCState &State,
1734                                              bool &InReg,
1735                                              bool &NeedsPadding) const {
1736   // On Windows, aggregates other than HFAs are never passed in registers, and
1737   // they do not consume register slots. Homogenous floating-point aggregates
1738   // (HFAs) have already been dealt with at this point.
1739   if (IsWin32StructABI && isAggregateTypeForABI(Ty))
1740     return false;
1741 
1742   NeedsPadding = false;
1743   InReg = !IsMCUABI;
1744 
1745   if (!updateFreeRegs(Ty, State))
1746     return false;
1747 
1748   if (IsMCUABI)
1749     return true;
1750 
1751   if (State.CC == llvm::CallingConv::X86_FastCall ||
1752       State.CC == llvm::CallingConv::X86_VectorCall ||
1753       State.CC == llvm::CallingConv::X86_RegCall) {
1754     if (getContext().getTypeSize(Ty) <= 32 && State.FreeRegs)
1755       NeedsPadding = true;
1756 
1757     return false;
1758   }
1759 
1760   return true;
1761 }
1762 
1763 bool X86_32ABIInfo::shouldPrimitiveUseInReg(QualType Ty, CCState &State) const {
1764   if (!updateFreeRegs(Ty, State))
1765     return false;
1766 
1767   if (IsMCUABI)
1768     return false;
1769 
1770   if (State.CC == llvm::CallingConv::X86_FastCall ||
1771       State.CC == llvm::CallingConv::X86_VectorCall ||
1772       State.CC == llvm::CallingConv::X86_RegCall) {
1773     if (getContext().getTypeSize(Ty) > 32)
1774       return false;
1775 
1776     return (Ty->isIntegralOrEnumerationType() || Ty->isPointerType() ||
1777         Ty->isReferenceType());
1778   }
1779 
1780   return true;
1781 }
1782 
1783 void X86_32ABIInfo::runVectorCallFirstPass(CGFunctionInfo &FI, CCState &State) const {
1784   // Vectorcall x86 works subtly different than in x64, so the format is
1785   // a bit different than the x64 version.  First, all vector types (not HVAs)
1786   // are assigned, with the first 6 ending up in the [XYZ]MM0-5 registers.
1787   // This differs from the x64 implementation, where the first 6 by INDEX get
1788   // registers.
1789   // In the second pass over the arguments, HVAs are passed in the remaining
1790   // vector registers if possible, or indirectly by address. The address will be
1791   // passed in ECX/EDX if available. Any other arguments are passed according to
1792   // the usual fastcall rules.
1793   MutableArrayRef<CGFunctionInfoArgInfo> Args = FI.arguments();
1794   for (int I = 0, E = Args.size(); I < E; ++I) {
1795     const Type *Base = nullptr;
1796     uint64_t NumElts = 0;
1797     const QualType &Ty = Args[I].type;
1798     if ((Ty->isVectorType() || Ty->isBuiltinType()) &&
1799         isHomogeneousAggregate(Ty, Base, NumElts)) {
1800       if (State.FreeSSERegs >= NumElts) {
1801         State.FreeSSERegs -= NumElts;
1802         Args[I].info = ABIArgInfo::getDirectInReg();
1803         State.IsPreassigned.set(I);
1804       }
1805     }
1806   }
1807 }
1808 
1809 ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
1810                                                CCState &State) const {
1811   // FIXME: Set alignment on indirect arguments.
1812   bool IsFastCall = State.CC == llvm::CallingConv::X86_FastCall;
1813   bool IsRegCall = State.CC == llvm::CallingConv::X86_RegCall;
1814   bool IsVectorCall = State.CC == llvm::CallingConv::X86_VectorCall;
1815 
1816   Ty = useFirstFieldIfTransparentUnion(Ty);
1817   TypeInfo TI = getContext().getTypeInfo(Ty);
1818 
1819   // Check with the C++ ABI first.
1820   const RecordType *RT = Ty->getAs<RecordType>();
1821   if (RT) {
1822     CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
1823     if (RAA == CGCXXABI::RAA_Indirect) {
1824       return getIndirectResult(Ty, false, State);
1825     } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
1826       // The field index doesn't matter, we'll fix it up later.
1827       return ABIArgInfo::getInAlloca(/*FieldIndex=*/0);
1828     }
1829   }
1830 
1831   // Regcall uses the concept of a homogenous vector aggregate, similar
1832   // to other targets.
1833   const Type *Base = nullptr;
1834   uint64_t NumElts = 0;
1835   if ((IsRegCall || IsVectorCall) &&
1836       isHomogeneousAggregate(Ty, Base, NumElts)) {
1837     if (State.FreeSSERegs >= NumElts) {
1838       State.FreeSSERegs -= NumElts;
1839 
1840       // Vectorcall passes HVAs directly and does not flatten them, but regcall
1841       // does.
1842       if (IsVectorCall)
1843         return getDirectX86Hva();
1844 
1845       if (Ty->isBuiltinType() || Ty->isVectorType())
1846         return ABIArgInfo::getDirect();
1847       return ABIArgInfo::getExpand();
1848     }
1849     return getIndirectResult(Ty, /*ByVal=*/false, State);
1850   }
1851 
1852   if (isAggregateTypeForABI(Ty)) {
1853     // Structures with flexible arrays are always indirect.
1854     // FIXME: This should not be byval!
1855     if (RT && RT->getDecl()->hasFlexibleArrayMember())
1856       return getIndirectResult(Ty, true, State);
1857 
1858     // Ignore empty structs/unions on non-Windows.
1859     if (!IsWin32StructABI && isEmptyRecord(getContext(), Ty, true))
1860       return ABIArgInfo::getIgnore();
1861 
1862     llvm::LLVMContext &LLVMContext = getVMContext();
1863     llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
1864     bool NeedsPadding = false;
1865     bool InReg;
1866     if (shouldAggregateUseDirect(Ty, State, InReg, NeedsPadding)) {
1867       unsigned SizeInRegs = (TI.Width + 31) / 32;
1868       SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32);
1869       llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
1870       if (InReg)
1871         return ABIArgInfo::getDirectInReg(Result);
1872       else
1873         return ABIArgInfo::getDirect(Result);
1874     }
1875     llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : nullptr;
1876 
1877     // Pass over-aligned aggregates on Windows indirectly. This behavior was
1878     // added in MSVC 2015.
1879     if (IsWin32StructABI && TI.isAlignRequired() && TI.Align > 32)
1880       return getIndirectResult(Ty, /*ByVal=*/false, State);
1881 
1882     // Expand small (<= 128-bit) record types when we know that the stack layout
1883     // of those arguments will match the struct. This is important because the
1884     // LLVM backend isn't smart enough to remove byval, which inhibits many
1885     // optimizations.
1886     // Don't do this for the MCU if there are still free integer registers
1887     // (see X86_64 ABI for full explanation).
1888     if (TI.Width <= 4 * 32 && (!IsMCUABI || State.FreeRegs == 0) &&
1889         canExpandIndirectArgument(Ty))
1890       return ABIArgInfo::getExpandWithPadding(
1891           IsFastCall || IsVectorCall || IsRegCall, PaddingType);
1892 
1893     return getIndirectResult(Ty, true, State);
1894   }
1895 
1896   if (const VectorType *VT = Ty->getAs<VectorType>()) {
1897     // On Windows, vectors are passed directly if registers are available, or
1898     // indirectly if not. This avoids the need to align argument memory. Pass
1899     // user-defined vector types larger than 512 bits indirectly for simplicity.
1900     if (IsWin32StructABI) {
1901       if (TI.Width <= 512 && State.FreeSSERegs > 0) {
1902         --State.FreeSSERegs;
1903         return ABIArgInfo::getDirectInReg();
1904       }
1905       return getIndirectResult(Ty, /*ByVal=*/false, State);
1906     }
1907 
1908     // On Darwin, some vectors are passed in memory, we handle this by passing
1909     // it as an i8/i16/i32/i64.
1910     if (IsDarwinVectorABI) {
1911       if ((TI.Width == 8 || TI.Width == 16 || TI.Width == 32) ||
1912           (TI.Width == 64 && VT->getNumElements() == 1))
1913         return ABIArgInfo::getDirect(
1914             llvm::IntegerType::get(getVMContext(), TI.Width));
1915     }
1916 
1917     if (IsX86_MMXType(CGT.ConvertType(Ty)))
1918       return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64));
1919 
1920     return ABIArgInfo::getDirect();
1921   }
1922 
1923 
1924   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1925     Ty = EnumTy->getDecl()->getIntegerType();
1926 
1927   bool InReg = shouldPrimitiveUseInReg(Ty, State);
1928 
1929   if (isPromotableIntegerTypeForABI(Ty)) {
1930     if (InReg)
1931       return ABIArgInfo::getExtendInReg(Ty);
1932     return ABIArgInfo::getExtend(Ty);
1933   }
1934 
1935   if (const auto *EIT = Ty->getAs<BitIntType>()) {
1936     if (EIT->getNumBits() <= 64) {
1937       if (InReg)
1938         return ABIArgInfo::getDirectInReg();
1939       return ABIArgInfo::getDirect();
1940     }
1941     return getIndirectResult(Ty, /*ByVal=*/false, State);
1942   }
1943 
1944   if (InReg)
1945     return ABIArgInfo::getDirectInReg();
1946   return ABIArgInfo::getDirect();
1947 }
1948 
1949 void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const {
1950   CCState State(FI);
1951   if (IsMCUABI)
1952     State.FreeRegs = 3;
1953   else if (State.CC == llvm::CallingConv::X86_FastCall) {
1954     State.FreeRegs = 2;
1955     State.FreeSSERegs = 3;
1956   } else if (State.CC == llvm::CallingConv::X86_VectorCall) {
1957     State.FreeRegs = 2;
1958     State.FreeSSERegs = 6;
1959   } else if (FI.getHasRegParm())
1960     State.FreeRegs = FI.getRegParm();
1961   else if (State.CC == llvm::CallingConv::X86_RegCall) {
1962     State.FreeRegs = 5;
1963     State.FreeSSERegs = 8;
1964   } else if (IsWin32StructABI) {
1965     // Since MSVC 2015, the first three SSE vectors have been passed in
1966     // registers. The rest are passed indirectly.
1967     State.FreeRegs = DefaultNumRegisterParameters;
1968     State.FreeSSERegs = 3;
1969   } else
1970     State.FreeRegs = DefaultNumRegisterParameters;
1971 
1972   if (!::classifyReturnType(getCXXABI(), FI, *this)) {
1973     FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), State);
1974   } else if (FI.getReturnInfo().isIndirect()) {
1975     // The C++ ABI is not aware of register usage, so we have to check if the
1976     // return value was sret and put it in a register ourselves if appropriate.
1977     if (State.FreeRegs) {
1978       --State.FreeRegs;  // The sret parameter consumes a register.
1979       if (!IsMCUABI)
1980         FI.getReturnInfo().setInReg(true);
1981     }
1982   }
1983 
1984   // The chain argument effectively gives us another free register.
1985   if (FI.isChainCall())
1986     ++State.FreeRegs;
1987 
1988   // For vectorcall, do a first pass over the arguments, assigning FP and vector
1989   // arguments to XMM registers as available.
1990   if (State.CC == llvm::CallingConv::X86_VectorCall)
1991     runVectorCallFirstPass(FI, State);
1992 
1993   bool UsedInAlloca = false;
1994   MutableArrayRef<CGFunctionInfoArgInfo> Args = FI.arguments();
1995   for (int I = 0, E = Args.size(); I < E; ++I) {
1996     // Skip arguments that have already been assigned.
1997     if (State.IsPreassigned.test(I))
1998       continue;
1999 
2000     Args[I].info = classifyArgumentType(Args[I].type, State);
2001     UsedInAlloca |= (Args[I].info.getKind() == ABIArgInfo::InAlloca);
2002   }
2003 
2004   // If we needed to use inalloca for any argument, do a second pass and rewrite
2005   // all the memory arguments to use inalloca.
2006   if (UsedInAlloca)
2007     rewriteWithInAlloca(FI);
2008 }
2009 
2010 void
2011 X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
2012                                    CharUnits &StackOffset, ABIArgInfo &Info,
2013                                    QualType Type) const {
2014   // Arguments are always 4-byte-aligned.
2015   CharUnits WordSize = CharUnits::fromQuantity(4);
2016   assert(StackOffset.isMultipleOf(WordSize) && "unaligned inalloca struct");
2017 
2018   // sret pointers and indirect things will require an extra pointer
2019   // indirection, unless they are byval. Most things are byval, and will not
2020   // require this indirection.
2021   bool IsIndirect = false;
2022   if (Info.isIndirect() && !Info.getIndirectByVal())
2023     IsIndirect = true;
2024   Info = ABIArgInfo::getInAlloca(FrameFields.size(), IsIndirect);
2025   llvm::Type *LLTy = CGT.ConvertTypeForMem(Type);
2026   if (IsIndirect)
2027     LLTy = LLTy->getPointerTo(0);
2028   FrameFields.push_back(LLTy);
2029   StackOffset += IsIndirect ? WordSize : getContext().getTypeSizeInChars(Type);
2030 
2031   // Insert padding bytes to respect alignment.
2032   CharUnits FieldEnd = StackOffset;
2033   StackOffset = FieldEnd.alignTo(WordSize);
2034   if (StackOffset != FieldEnd) {
2035     CharUnits NumBytes = StackOffset - FieldEnd;
2036     llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext());
2037     Ty = llvm::ArrayType::get(Ty, NumBytes.getQuantity());
2038     FrameFields.push_back(Ty);
2039   }
2040 }
2041 
2042 static bool isArgInAlloca(const ABIArgInfo &Info) {
2043   // Leave ignored and inreg arguments alone.
2044   switch (Info.getKind()) {
2045   case ABIArgInfo::InAlloca:
2046     return true;
2047   case ABIArgInfo::Ignore:
2048   case ABIArgInfo::IndirectAliased:
2049     return false;
2050   case ABIArgInfo::Indirect:
2051   case ABIArgInfo::Direct:
2052   case ABIArgInfo::Extend:
2053     return !Info.getInReg();
2054   case ABIArgInfo::Expand:
2055   case ABIArgInfo::CoerceAndExpand:
2056     // These are aggregate types which are never passed in registers when
2057     // inalloca is involved.
2058     return true;
2059   }
2060   llvm_unreachable("invalid enum");
2061 }
2062 
2063 void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const {
2064   assert(IsWin32StructABI && "inalloca only supported on win32");
2065 
2066   // Build a packed struct type for all of the arguments in memory.
2067   SmallVector<llvm::Type *, 6> FrameFields;
2068 
2069   // The stack alignment is always 4.
2070   CharUnits StackAlign = CharUnits::fromQuantity(4);
2071 
2072   CharUnits StackOffset;
2073   CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end();
2074 
2075   // Put 'this' into the struct before 'sret', if necessary.
2076   bool IsThisCall =
2077       FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall;
2078   ABIArgInfo &Ret = FI.getReturnInfo();
2079   if (Ret.isIndirect() && Ret.isSRetAfterThis() && !IsThisCall &&
2080       isArgInAlloca(I->info)) {
2081     addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
2082     ++I;
2083   }
2084 
2085   // Put the sret parameter into the inalloca struct if it's in memory.
2086   if (Ret.isIndirect() && !Ret.getInReg()) {
2087     addFieldToArgStruct(FrameFields, StackOffset, Ret, FI.getReturnType());
2088     // On Windows, the hidden sret parameter is always returned in eax.
2089     Ret.setInAllocaSRet(IsWin32StructABI);
2090   }
2091 
2092   // Skip the 'this' parameter in ecx.
2093   if (IsThisCall)
2094     ++I;
2095 
2096   // Put arguments passed in memory into the struct.
2097   for (; I != E; ++I) {
2098     if (isArgInAlloca(I->info))
2099       addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
2100   }
2101 
2102   FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields,
2103                                         /*isPacked=*/true),
2104                   StackAlign);
2105 }
2106 
2107 Address X86_32ABIInfo::EmitVAArg(CodeGenFunction &CGF,
2108                                  Address VAListAddr, QualType Ty) const {
2109 
2110   auto TypeInfo = getContext().getTypeInfoInChars(Ty);
2111 
2112   // x86-32 changes the alignment of certain arguments on the stack.
2113   //
2114   // Just messing with TypeInfo like this works because we never pass
2115   // anything indirectly.
2116   TypeInfo.Align = CharUnits::fromQuantity(
2117                 getTypeStackAlignInBytes(Ty, TypeInfo.Align.getQuantity()));
2118 
2119   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
2120                           TypeInfo, CharUnits::fromQuantity(4),
2121                           /*AllowHigherAlign*/ true);
2122 }
2123 
2124 bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
2125     const llvm::Triple &Triple, const CodeGenOptions &Opts) {
2126   assert(Triple.getArch() == llvm::Triple::x86);
2127 
2128   switch (Opts.getStructReturnConvention()) {
2129   case CodeGenOptions::SRCK_Default:
2130     break;
2131   case CodeGenOptions::SRCK_OnStack:  // -fpcc-struct-return
2132     return false;
2133   case CodeGenOptions::SRCK_InRegs:  // -freg-struct-return
2134     return true;
2135   }
2136 
2137   if (Triple.isOSDarwin() || Triple.isOSIAMCU())
2138     return true;
2139 
2140   switch (Triple.getOS()) {
2141   case llvm::Triple::DragonFly:
2142   case llvm::Triple::FreeBSD:
2143   case llvm::Triple::OpenBSD:
2144   case llvm::Triple::Win32:
2145     return true;
2146   default:
2147     return false;
2148   }
2149 }
2150 
2151 static void addX86InterruptAttrs(const FunctionDecl *FD, llvm::GlobalValue *GV,
2152                                  CodeGen::CodeGenModule &CGM) {
2153   if (!FD->hasAttr<AnyX86InterruptAttr>())
2154     return;
2155 
2156   llvm::Function *Fn = cast<llvm::Function>(GV);
2157   Fn->setCallingConv(llvm::CallingConv::X86_INTR);
2158   if (FD->getNumParams() == 0)
2159     return;
2160 
2161   auto PtrTy = cast<PointerType>(FD->getParamDecl(0)->getType());
2162   llvm::Type *ByValTy = CGM.getTypes().ConvertType(PtrTy->getPointeeType());
2163   llvm::Attribute NewAttr = llvm::Attribute::getWithByValType(
2164     Fn->getContext(), ByValTy);
2165   Fn->addParamAttr(0, NewAttr);
2166 }
2167 
2168 void X86_32TargetCodeGenInfo::setTargetAttributes(
2169     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
2170   if (GV->isDeclaration())
2171     return;
2172   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2173     if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
2174       llvm::Function *Fn = cast<llvm::Function>(GV);
2175       Fn->addFnAttr("stackrealign");
2176     }
2177 
2178     addX86InterruptAttrs(FD, GV, CGM);
2179   }
2180 }
2181 
2182 bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
2183                                                CodeGen::CodeGenFunction &CGF,
2184                                                llvm::Value *Address) const {
2185   CodeGen::CGBuilderTy &Builder = CGF.Builder;
2186 
2187   llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
2188 
2189   // 0-7 are the eight integer registers;  the order is different
2190   //   on Darwin (for EH), but the range is the same.
2191   // 8 is %eip.
2192   AssignToArrayRange(Builder, Address, Four8, 0, 8);
2193 
2194   if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
2195     // 12-16 are st(0..4).  Not sure why we stop at 4.
2196     // These have size 16, which is sizeof(long double) on
2197     // platforms with 8-byte alignment for that type.
2198     llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
2199     AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
2200 
2201   } else {
2202     // 9 is %eflags, which doesn't get a size on Darwin for some
2203     // reason.
2204     Builder.CreateAlignedStore(
2205         Four8, Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, Address, 9),
2206                                CharUnits::One());
2207 
2208     // 11-16 are st(0..5).  Not sure why we stop at 5.
2209     // These have size 12, which is sizeof(long double) on
2210     // platforms with 4-byte alignment for that type.
2211     llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
2212     AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
2213   }
2214 
2215   return false;
2216 }
2217 
2218 //===----------------------------------------------------------------------===//
2219 // X86-64 ABI Implementation
2220 //===----------------------------------------------------------------------===//
2221 
2222 
2223 namespace {
2224 /// The AVX ABI level for X86 targets.
2225 enum class X86AVXABILevel {
2226   None,
2227   AVX,
2228   AVX512
2229 };
2230 
2231 /// \p returns the size in bits of the largest (native) vector for \p AVXLevel.
2232 static unsigned getNativeVectorSizeForAVXABI(X86AVXABILevel AVXLevel) {
2233   switch (AVXLevel) {
2234   case X86AVXABILevel::AVX512:
2235     return 512;
2236   case X86AVXABILevel::AVX:
2237     return 256;
2238   case X86AVXABILevel::None:
2239     return 128;
2240   }
2241   llvm_unreachable("Unknown AVXLevel");
2242 }
2243 
2244 /// X86_64ABIInfo - The X86_64 ABI information.
2245 class X86_64ABIInfo : public SwiftABIInfo {
2246   enum Class {
2247     Integer = 0,
2248     SSE,
2249     SSEUp,
2250     X87,
2251     X87Up,
2252     ComplexX87,
2253     NoClass,
2254     Memory
2255   };
2256 
2257   /// merge - Implement the X86_64 ABI merging algorithm.
2258   ///
2259   /// Merge an accumulating classification \arg Accum with a field
2260   /// classification \arg Field.
2261   ///
2262   /// \param Accum - The accumulating classification. This should
2263   /// always be either NoClass or the result of a previous merge
2264   /// call. In addition, this should never be Memory (the caller
2265   /// should just return Memory for the aggregate).
2266   static Class merge(Class Accum, Class Field);
2267 
2268   /// postMerge - Implement the X86_64 ABI post merging algorithm.
2269   ///
2270   /// Post merger cleanup, reduces a malformed Hi and Lo pair to
2271   /// final MEMORY or SSE classes when necessary.
2272   ///
2273   /// \param AggregateSize - The size of the current aggregate in
2274   /// the classification process.
2275   ///
2276   /// \param Lo - The classification for the parts of the type
2277   /// residing in the low word of the containing object.
2278   ///
2279   /// \param Hi - The classification for the parts of the type
2280   /// residing in the higher words of the containing object.
2281   ///
2282   void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
2283 
2284   /// classify - Determine the x86_64 register classes in which the
2285   /// given type T should be passed.
2286   ///
2287   /// \param Lo - The classification for the parts of the type
2288   /// residing in the low word of the containing object.
2289   ///
2290   /// \param Hi - The classification for the parts of the type
2291   /// residing in the high word of the containing object.
2292   ///
2293   /// \param OffsetBase - The bit offset of this type in the
2294   /// containing object.  Some parameters are classified different
2295   /// depending on whether they straddle an eightbyte boundary.
2296   ///
2297   /// \param isNamedArg - Whether the argument in question is a "named"
2298   /// argument, as used in AMD64-ABI 3.5.7.
2299   ///
2300   /// \param IsRegCall - Whether the calling conversion is regcall.
2301   ///
2302   /// If a word is unused its result will be NoClass; if a type should
2303   /// be passed in Memory then at least the classification of \arg Lo
2304   /// will be Memory.
2305   ///
2306   /// The \arg Lo class will be NoClass iff the argument is ignored.
2307   ///
2308   /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
2309   /// also be ComplexX87.
2310   void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi,
2311                 bool isNamedArg, bool IsRegCall = false) const;
2312 
2313   llvm::Type *GetByteVectorType(QualType Ty) const;
2314   llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
2315                                  unsigned IROffset, QualType SourceTy,
2316                                  unsigned SourceOffset) const;
2317   llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
2318                                      unsigned IROffset, QualType SourceTy,
2319                                      unsigned SourceOffset) const;
2320 
2321   /// getIndirectResult - Give a source type \arg Ty, return a suitable result
2322   /// such that the argument will be returned in memory.
2323   ABIArgInfo getIndirectReturnResult(QualType Ty) const;
2324 
2325   /// getIndirectResult - Give a source type \arg Ty, return a suitable result
2326   /// such that the argument will be passed in memory.
2327   ///
2328   /// \param freeIntRegs - The number of free integer registers remaining
2329   /// available.
2330   ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
2331 
2332   ABIArgInfo classifyReturnType(QualType RetTy) const;
2333 
2334   ABIArgInfo classifyArgumentType(QualType Ty, unsigned freeIntRegs,
2335                                   unsigned &neededInt, unsigned &neededSSE,
2336                                   bool isNamedArg,
2337                                   bool IsRegCall = false) const;
2338 
2339   ABIArgInfo classifyRegCallStructType(QualType Ty, unsigned &NeededInt,
2340                                        unsigned &NeededSSE,
2341                                        unsigned &MaxVectorWidth) const;
2342 
2343   ABIArgInfo classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
2344                                            unsigned &NeededSSE,
2345                                            unsigned &MaxVectorWidth) const;
2346 
2347   bool IsIllegalVectorType(QualType Ty) const;
2348 
2349   /// The 0.98 ABI revision clarified a lot of ambiguities,
2350   /// unfortunately in ways that were not always consistent with
2351   /// certain previous compilers.  In particular, platforms which
2352   /// required strict binary compatibility with older versions of GCC
2353   /// may need to exempt themselves.
2354   bool honorsRevision0_98() const {
2355     return !getTarget().getTriple().isOSDarwin();
2356   }
2357 
2358   /// GCC classifies <1 x long long> as SSE but some platform ABIs choose to
2359   /// classify it as INTEGER (for compatibility with older clang compilers).
2360   bool classifyIntegerMMXAsSSE() const {
2361     // Clang <= 3.8 did not do this.
2362     if (getContext().getLangOpts().getClangABICompat() <=
2363         LangOptions::ClangABI::Ver3_8)
2364       return false;
2365 
2366     const llvm::Triple &Triple = getTarget().getTriple();
2367     if (Triple.isOSDarwin() || Triple.getOS() == llvm::Triple::PS4)
2368       return false;
2369     if (Triple.isOSFreeBSD() && Triple.getOSMajorVersion() >= 10)
2370       return false;
2371     return true;
2372   }
2373 
2374   // GCC classifies vectors of __int128 as memory.
2375   bool passInt128VectorsInMem() const {
2376     // Clang <= 9.0 did not do this.
2377     if (getContext().getLangOpts().getClangABICompat() <=
2378         LangOptions::ClangABI::Ver9)
2379       return false;
2380 
2381     const llvm::Triple &T = getTarget().getTriple();
2382     return T.isOSLinux() || T.isOSNetBSD();
2383   }
2384 
2385   X86AVXABILevel AVXLevel;
2386   // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
2387   // 64-bit hardware.
2388   bool Has64BitPointers;
2389 
2390 public:
2391   X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) :
2392       SwiftABIInfo(CGT), AVXLevel(AVXLevel),
2393       Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {
2394   }
2395 
2396   bool isPassedUsingAVXType(QualType type) const {
2397     unsigned neededInt, neededSSE;
2398     // The freeIntRegs argument doesn't matter here.
2399     ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE,
2400                                            /*isNamedArg*/true);
2401     if (info.isDirect()) {
2402       llvm::Type *ty = info.getCoerceToType();
2403       if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
2404         return vectorTy->getPrimitiveSizeInBits().getFixedSize() > 128;
2405     }
2406     return false;
2407   }
2408 
2409   void computeInfo(CGFunctionInfo &FI) const override;
2410 
2411   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
2412                     QualType Ty) const override;
2413   Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
2414                       QualType Ty) const override;
2415 
2416   bool has64BitPointers() const {
2417     return Has64BitPointers;
2418   }
2419 
2420   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
2421                                     bool asReturnValue) const override {
2422     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
2423   }
2424   bool isSwiftErrorInRegister() const override {
2425     return true;
2426   }
2427 };
2428 
2429 /// WinX86_64ABIInfo - The Windows X86_64 ABI information.
2430 class WinX86_64ABIInfo : public SwiftABIInfo {
2431 public:
2432   WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
2433       : SwiftABIInfo(CGT), AVXLevel(AVXLevel),
2434         IsMingw64(getTarget().getTriple().isWindowsGNUEnvironment()) {}
2435 
2436   void computeInfo(CGFunctionInfo &FI) const override;
2437 
2438   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
2439                     QualType Ty) const override;
2440 
2441   bool isHomogeneousAggregateBaseType(QualType Ty) const override {
2442     // FIXME: Assumes vectorcall is in use.
2443     return isX86VectorTypeForVectorCall(getContext(), Ty);
2444   }
2445 
2446   bool isHomogeneousAggregateSmallEnough(const Type *Ty,
2447                                          uint64_t NumMembers) const override {
2448     // FIXME: Assumes vectorcall is in use.
2449     return isX86VectorCallAggregateSmallEnough(NumMembers);
2450   }
2451 
2452   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type *> scalars,
2453                                     bool asReturnValue) const override {
2454     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
2455   }
2456 
2457   bool isSwiftErrorInRegister() const override {
2458     return true;
2459   }
2460 
2461 private:
2462   ABIArgInfo classify(QualType Ty, unsigned &FreeSSERegs, bool IsReturnType,
2463                       bool IsVectorCall, bool IsRegCall) const;
2464   ABIArgInfo reclassifyHvaArgForVectorCall(QualType Ty, unsigned &FreeSSERegs,
2465                                            const ABIArgInfo &current) const;
2466 
2467   X86AVXABILevel AVXLevel;
2468 
2469   bool IsMingw64;
2470 };
2471 
2472 class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2473 public:
2474   X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
2475       : TargetCodeGenInfo(std::make_unique<X86_64ABIInfo>(CGT, AVXLevel)) {}
2476 
2477   const X86_64ABIInfo &getABIInfo() const {
2478     return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
2479   }
2480 
2481   /// Disable tail call on x86-64. The epilogue code before the tail jump blocks
2482   /// autoreleaseRV/retainRV and autoreleaseRV/unsafeClaimRV optimizations.
2483   bool markARCOptimizedReturnCallsAsNoTail() const override { return true; }
2484 
2485   int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
2486     return 7;
2487   }
2488 
2489   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2490                                llvm::Value *Address) const override {
2491     llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
2492 
2493     // 0-15 are the 16 integer registers.
2494     // 16 is %rip.
2495     AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
2496     return false;
2497   }
2498 
2499   llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
2500                                   StringRef Constraint,
2501                                   llvm::Type* Ty) const override {
2502     return X86AdjustInlineAsmType(CGF, Constraint, Ty);
2503   }
2504 
2505   bool isNoProtoCallVariadic(const CallArgList &args,
2506                              const FunctionNoProtoType *fnType) const override {
2507     // The default CC on x86-64 sets %al to the number of SSA
2508     // registers used, and GCC sets this when calling an unprototyped
2509     // function, so we override the default behavior.  However, don't do
2510     // that when AVX types are involved: the ABI explicitly states it is
2511     // undefined, and it doesn't work in practice because of how the ABI
2512     // defines varargs anyway.
2513     if (fnType->getCallConv() == CC_C) {
2514       bool HasAVXType = false;
2515       for (CallArgList::const_iterator
2516              it = args.begin(), ie = args.end(); it != ie; ++it) {
2517         if (getABIInfo().isPassedUsingAVXType(it->Ty)) {
2518           HasAVXType = true;
2519           break;
2520         }
2521       }
2522 
2523       if (!HasAVXType)
2524         return true;
2525     }
2526 
2527     return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
2528   }
2529 
2530   llvm::Constant *
2531   getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
2532     unsigned Sig = (0xeb << 0) | // jmp rel8
2533                    (0x06 << 8) | //           .+0x08
2534                    ('v' << 16) |
2535                    ('2' << 24);
2536     return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
2537   }
2538 
2539   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2540                            CodeGen::CodeGenModule &CGM) const override {
2541     if (GV->isDeclaration())
2542       return;
2543     if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2544       if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
2545         llvm::Function *Fn = cast<llvm::Function>(GV);
2546         Fn->addFnAttr("stackrealign");
2547       }
2548 
2549       addX86InterruptAttrs(FD, GV, CGM);
2550     }
2551   }
2552 
2553   void checkFunctionCallABI(CodeGenModule &CGM, SourceLocation CallLoc,
2554                             const FunctionDecl *Caller,
2555                             const FunctionDecl *Callee,
2556                             const CallArgList &Args) const override;
2557 };
2558 
2559 static void initFeatureMaps(const ASTContext &Ctx,
2560                             llvm::StringMap<bool> &CallerMap,
2561                             const FunctionDecl *Caller,
2562                             llvm::StringMap<bool> &CalleeMap,
2563                             const FunctionDecl *Callee) {
2564   if (CalleeMap.empty() && CallerMap.empty()) {
2565     // The caller is potentially nullptr in the case where the call isn't in a
2566     // function.  In this case, the getFunctionFeatureMap ensures we just get
2567     // the TU level setting (since it cannot be modified by 'target'..
2568     Ctx.getFunctionFeatureMap(CallerMap, Caller);
2569     Ctx.getFunctionFeatureMap(CalleeMap, Callee);
2570   }
2571 }
2572 
2573 static bool checkAVXParamFeature(DiagnosticsEngine &Diag,
2574                                  SourceLocation CallLoc,
2575                                  const llvm::StringMap<bool> &CallerMap,
2576                                  const llvm::StringMap<bool> &CalleeMap,
2577                                  QualType Ty, StringRef Feature,
2578                                  bool IsArgument) {
2579   bool CallerHasFeat = CallerMap.lookup(Feature);
2580   bool CalleeHasFeat = CalleeMap.lookup(Feature);
2581   if (!CallerHasFeat && !CalleeHasFeat)
2582     return Diag.Report(CallLoc, diag::warn_avx_calling_convention)
2583            << IsArgument << Ty << Feature;
2584 
2585   // Mixing calling conventions here is very clearly an error.
2586   if (!CallerHasFeat || !CalleeHasFeat)
2587     return Diag.Report(CallLoc, diag::err_avx_calling_convention)
2588            << IsArgument << Ty << Feature;
2589 
2590   // Else, both caller and callee have the required feature, so there is no need
2591   // to diagnose.
2592   return false;
2593 }
2594 
2595 static bool checkAVXParam(DiagnosticsEngine &Diag, ASTContext &Ctx,
2596                           SourceLocation CallLoc,
2597                           const llvm::StringMap<bool> &CallerMap,
2598                           const llvm::StringMap<bool> &CalleeMap, QualType Ty,
2599                           bool IsArgument) {
2600   uint64_t Size = Ctx.getTypeSize(Ty);
2601   if (Size > 256)
2602     return checkAVXParamFeature(Diag, CallLoc, CallerMap, CalleeMap, Ty,
2603                                 "avx512f", IsArgument);
2604 
2605   if (Size > 128)
2606     return checkAVXParamFeature(Diag, CallLoc, CallerMap, CalleeMap, Ty, "avx",
2607                                 IsArgument);
2608 
2609   return false;
2610 }
2611 
2612 void X86_64TargetCodeGenInfo::checkFunctionCallABI(
2613     CodeGenModule &CGM, SourceLocation CallLoc, const FunctionDecl *Caller,
2614     const FunctionDecl *Callee, const CallArgList &Args) const {
2615   llvm::StringMap<bool> CallerMap;
2616   llvm::StringMap<bool> CalleeMap;
2617   unsigned ArgIndex = 0;
2618 
2619   // We need to loop through the actual call arguments rather than the the
2620   // function's parameters, in case this variadic.
2621   for (const CallArg &Arg : Args) {
2622     // The "avx" feature changes how vectors >128 in size are passed. "avx512f"
2623     // additionally changes how vectors >256 in size are passed. Like GCC, we
2624     // warn when a function is called with an argument where this will change.
2625     // Unlike GCC, we also error when it is an obvious ABI mismatch, that is,
2626     // the caller and callee features are mismatched.
2627     // Unfortunately, we cannot do this diagnostic in SEMA, since the callee can
2628     // change its ABI with attribute-target after this call.
2629     if (Arg.getType()->isVectorType() &&
2630         CGM.getContext().getTypeSize(Arg.getType()) > 128) {
2631       initFeatureMaps(CGM.getContext(), CallerMap, Caller, CalleeMap, Callee);
2632       QualType Ty = Arg.getType();
2633       // The CallArg seems to have desugared the type already, so for clearer
2634       // diagnostics, replace it with the type in the FunctionDecl if possible.
2635       if (ArgIndex < Callee->getNumParams())
2636         Ty = Callee->getParamDecl(ArgIndex)->getType();
2637 
2638       if (checkAVXParam(CGM.getDiags(), CGM.getContext(), CallLoc, CallerMap,
2639                         CalleeMap, Ty, /*IsArgument*/ true))
2640         return;
2641     }
2642     ++ArgIndex;
2643   }
2644 
2645   // Check return always, as we don't have a good way of knowing in codegen
2646   // whether this value is used, tail-called, etc.
2647   if (Callee->getReturnType()->isVectorType() &&
2648       CGM.getContext().getTypeSize(Callee->getReturnType()) > 128) {
2649     initFeatureMaps(CGM.getContext(), CallerMap, Caller, CalleeMap, Callee);
2650     checkAVXParam(CGM.getDiags(), CGM.getContext(), CallLoc, CallerMap,
2651                   CalleeMap, Callee->getReturnType(),
2652                   /*IsArgument*/ false);
2653   }
2654 }
2655 
2656 static std::string qualifyWindowsLibrary(llvm::StringRef Lib) {
2657   // If the argument does not end in .lib, automatically add the suffix.
2658   // If the argument contains a space, enclose it in quotes.
2659   // This matches the behavior of MSVC.
2660   bool Quote = Lib.contains(' ');
2661   std::string ArgStr = Quote ? "\"" : "";
2662   ArgStr += Lib;
2663   if (!Lib.endswith_insensitive(".lib") && !Lib.endswith_insensitive(".a"))
2664     ArgStr += ".lib";
2665   ArgStr += Quote ? "\"" : "";
2666   return ArgStr;
2667 }
2668 
2669 class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
2670 public:
2671   WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
2672         bool DarwinVectorABI, bool RetSmallStructInRegABI, bool Win32StructABI,
2673         unsigned NumRegisterParameters)
2674     : X86_32TargetCodeGenInfo(CGT, DarwinVectorABI, RetSmallStructInRegABI,
2675         Win32StructABI, NumRegisterParameters, false) {}
2676 
2677   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2678                            CodeGen::CodeGenModule &CGM) const override;
2679 
2680   void getDependentLibraryOption(llvm::StringRef Lib,
2681                                  llvm::SmallString<24> &Opt) const override {
2682     Opt = "/DEFAULTLIB:";
2683     Opt += qualifyWindowsLibrary(Lib);
2684   }
2685 
2686   void getDetectMismatchOption(llvm::StringRef Name,
2687                                llvm::StringRef Value,
2688                                llvm::SmallString<32> &Opt) const override {
2689     Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
2690   }
2691 };
2692 
2693 static void addStackProbeTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2694                                           CodeGen::CodeGenModule &CGM) {
2695   if (llvm::Function *Fn = dyn_cast_or_null<llvm::Function>(GV)) {
2696 
2697     if (CGM.getCodeGenOpts().StackProbeSize != 4096)
2698       Fn->addFnAttr("stack-probe-size",
2699                     llvm::utostr(CGM.getCodeGenOpts().StackProbeSize));
2700     if (CGM.getCodeGenOpts().NoStackArgProbe)
2701       Fn->addFnAttr("no-stack-arg-probe");
2702   }
2703 }
2704 
2705 void WinX86_32TargetCodeGenInfo::setTargetAttributes(
2706     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
2707   X86_32TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
2708   if (GV->isDeclaration())
2709     return;
2710   addStackProbeTargetAttributes(D, GV, CGM);
2711 }
2712 
2713 class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2714 public:
2715   WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
2716                              X86AVXABILevel AVXLevel)
2717       : TargetCodeGenInfo(std::make_unique<WinX86_64ABIInfo>(CGT, AVXLevel)) {}
2718 
2719   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2720                            CodeGen::CodeGenModule &CGM) const override;
2721 
2722   int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
2723     return 7;
2724   }
2725 
2726   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2727                                llvm::Value *Address) const override {
2728     llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
2729 
2730     // 0-15 are the 16 integer registers.
2731     // 16 is %rip.
2732     AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
2733     return false;
2734   }
2735 
2736   void getDependentLibraryOption(llvm::StringRef Lib,
2737                                  llvm::SmallString<24> &Opt) const override {
2738     Opt = "/DEFAULTLIB:";
2739     Opt += qualifyWindowsLibrary(Lib);
2740   }
2741 
2742   void getDetectMismatchOption(llvm::StringRef Name,
2743                                llvm::StringRef Value,
2744                                llvm::SmallString<32> &Opt) const override {
2745     Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
2746   }
2747 };
2748 
2749 void WinX86_64TargetCodeGenInfo::setTargetAttributes(
2750     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
2751   TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
2752   if (GV->isDeclaration())
2753     return;
2754   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2755     if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
2756       llvm::Function *Fn = cast<llvm::Function>(GV);
2757       Fn->addFnAttr("stackrealign");
2758     }
2759 
2760     addX86InterruptAttrs(FD, GV, CGM);
2761   }
2762 
2763   addStackProbeTargetAttributes(D, GV, CGM);
2764 }
2765 }
2766 
2767 void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
2768                               Class &Hi) const {
2769   // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
2770   //
2771   // (a) If one of the classes is Memory, the whole argument is passed in
2772   //     memory.
2773   //
2774   // (b) If X87UP is not preceded by X87, the whole argument is passed in
2775   //     memory.
2776   //
2777   // (c) If the size of the aggregate exceeds two eightbytes and the first
2778   //     eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
2779   //     argument is passed in memory. NOTE: This is necessary to keep the
2780   //     ABI working for processors that don't support the __m256 type.
2781   //
2782   // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
2783   //
2784   // Some of these are enforced by the merging logic.  Others can arise
2785   // only with unions; for example:
2786   //   union { _Complex double; unsigned; }
2787   //
2788   // Note that clauses (b) and (c) were added in 0.98.
2789   //
2790   if (Hi == Memory)
2791     Lo = Memory;
2792   if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
2793     Lo = Memory;
2794   if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
2795     Lo = Memory;
2796   if (Hi == SSEUp && Lo != SSE)
2797     Hi = SSE;
2798 }
2799 
2800 X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
2801   // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
2802   // classified recursively so that always two fields are
2803   // considered. The resulting class is calculated according to
2804   // the classes of the fields in the eightbyte:
2805   //
2806   // (a) If both classes are equal, this is the resulting class.
2807   //
2808   // (b) If one of the classes is NO_CLASS, the resulting class is
2809   // the other class.
2810   //
2811   // (c) If one of the classes is MEMORY, the result is the MEMORY
2812   // class.
2813   //
2814   // (d) If one of the classes is INTEGER, the result is the
2815   // INTEGER.
2816   //
2817   // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
2818   // MEMORY is used as class.
2819   //
2820   // (f) Otherwise class SSE is used.
2821 
2822   // Accum should never be memory (we should have returned) or
2823   // ComplexX87 (because this cannot be passed in a structure).
2824   assert((Accum != Memory && Accum != ComplexX87) &&
2825          "Invalid accumulated classification during merge.");
2826   if (Accum == Field || Field == NoClass)
2827     return Accum;
2828   if (Field == Memory)
2829     return Memory;
2830   if (Accum == NoClass)
2831     return Field;
2832   if (Accum == Integer || Field == Integer)
2833     return Integer;
2834   if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
2835       Accum == X87 || Accum == X87Up)
2836     return Memory;
2837   return SSE;
2838 }
2839 
2840 void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase, Class &Lo,
2841                              Class &Hi, bool isNamedArg, bool IsRegCall) const {
2842   // FIXME: This code can be simplified by introducing a simple value class for
2843   // Class pairs with appropriate constructor methods for the various
2844   // situations.
2845 
2846   // FIXME: Some of the split computations are wrong; unaligned vectors
2847   // shouldn't be passed in registers for example, so there is no chance they
2848   // can straddle an eightbyte. Verify & simplify.
2849 
2850   Lo = Hi = NoClass;
2851 
2852   Class &Current = OffsetBase < 64 ? Lo : Hi;
2853   Current = Memory;
2854 
2855   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
2856     BuiltinType::Kind k = BT->getKind();
2857 
2858     if (k == BuiltinType::Void) {
2859       Current = NoClass;
2860     } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
2861       Lo = Integer;
2862       Hi = Integer;
2863     } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
2864       Current = Integer;
2865     } else if (k == BuiltinType::Float || k == BuiltinType::Double ||
2866                k == BuiltinType::Float16) {
2867       Current = SSE;
2868     } else if (k == BuiltinType::LongDouble) {
2869       const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
2870       if (LDF == &llvm::APFloat::IEEEquad()) {
2871         Lo = SSE;
2872         Hi = SSEUp;
2873       } else if (LDF == &llvm::APFloat::x87DoubleExtended()) {
2874         Lo = X87;
2875         Hi = X87Up;
2876       } else if (LDF == &llvm::APFloat::IEEEdouble()) {
2877         Current = SSE;
2878       } else
2879         llvm_unreachable("unexpected long double representation!");
2880     }
2881     // FIXME: _Decimal32 and _Decimal64 are SSE.
2882     // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
2883     return;
2884   }
2885 
2886   if (const EnumType *ET = Ty->getAs<EnumType>()) {
2887     // Classify the underlying integer type.
2888     classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
2889     return;
2890   }
2891 
2892   if (Ty->hasPointerRepresentation()) {
2893     Current = Integer;
2894     return;
2895   }
2896 
2897   if (Ty->isMemberPointerType()) {
2898     if (Ty->isMemberFunctionPointerType()) {
2899       if (Has64BitPointers) {
2900         // If Has64BitPointers, this is an {i64, i64}, so classify both
2901         // Lo and Hi now.
2902         Lo = Hi = Integer;
2903       } else {
2904         // Otherwise, with 32-bit pointers, this is an {i32, i32}. If that
2905         // straddles an eightbyte boundary, Hi should be classified as well.
2906         uint64_t EB_FuncPtr = (OffsetBase) / 64;
2907         uint64_t EB_ThisAdj = (OffsetBase + 64 - 1) / 64;
2908         if (EB_FuncPtr != EB_ThisAdj) {
2909           Lo = Hi = Integer;
2910         } else {
2911           Current = Integer;
2912         }
2913       }
2914     } else {
2915       Current = Integer;
2916     }
2917     return;
2918   }
2919 
2920   if (const VectorType *VT = Ty->getAs<VectorType>()) {
2921     uint64_t Size = getContext().getTypeSize(VT);
2922     if (Size == 1 || Size == 8 || Size == 16 || Size == 32) {
2923       // gcc passes the following as integer:
2924       // 4 bytes - <4 x char>, <2 x short>, <1 x int>, <1 x float>
2925       // 2 bytes - <2 x char>, <1 x short>
2926       // 1 byte  - <1 x char>
2927       Current = Integer;
2928 
2929       // If this type crosses an eightbyte boundary, it should be
2930       // split.
2931       uint64_t EB_Lo = (OffsetBase) / 64;
2932       uint64_t EB_Hi = (OffsetBase + Size - 1) / 64;
2933       if (EB_Lo != EB_Hi)
2934         Hi = Lo;
2935     } else if (Size == 64) {
2936       QualType ElementType = VT->getElementType();
2937 
2938       // gcc passes <1 x double> in memory. :(
2939       if (ElementType->isSpecificBuiltinType(BuiltinType::Double))
2940         return;
2941 
2942       // gcc passes <1 x long long> as SSE but clang used to unconditionally
2943       // pass them as integer.  For platforms where clang is the de facto
2944       // platform compiler, we must continue to use integer.
2945       if (!classifyIntegerMMXAsSSE() &&
2946           (ElementType->isSpecificBuiltinType(BuiltinType::LongLong) ||
2947            ElementType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
2948            ElementType->isSpecificBuiltinType(BuiltinType::Long) ||
2949            ElementType->isSpecificBuiltinType(BuiltinType::ULong)))
2950         Current = Integer;
2951       else
2952         Current = SSE;
2953 
2954       // If this type crosses an eightbyte boundary, it should be
2955       // split.
2956       if (OffsetBase && OffsetBase != 64)
2957         Hi = Lo;
2958     } else if (Size == 128 ||
2959                (isNamedArg && Size <= getNativeVectorSizeForAVXABI(AVXLevel))) {
2960       QualType ElementType = VT->getElementType();
2961 
2962       // gcc passes 256 and 512 bit <X x __int128> vectors in memory. :(
2963       if (passInt128VectorsInMem() && Size != 128 &&
2964           (ElementType->isSpecificBuiltinType(BuiltinType::Int128) ||
2965            ElementType->isSpecificBuiltinType(BuiltinType::UInt128)))
2966         return;
2967 
2968       // Arguments of 256-bits are split into four eightbyte chunks. The
2969       // least significant one belongs to class SSE and all the others to class
2970       // SSEUP. The original Lo and Hi design considers that types can't be
2971       // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
2972       // This design isn't correct for 256-bits, but since there're no cases
2973       // where the upper parts would need to be inspected, avoid adding
2974       // complexity and just consider Hi to match the 64-256 part.
2975       //
2976       // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
2977       // registers if they are "named", i.e. not part of the "..." of a
2978       // variadic function.
2979       //
2980       // Similarly, per 3.2.3. of the AVX512 draft, 512-bits ("named") args are
2981       // split into eight eightbyte chunks, one SSE and seven SSEUP.
2982       Lo = SSE;
2983       Hi = SSEUp;
2984     }
2985     return;
2986   }
2987 
2988   if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
2989     QualType ET = getContext().getCanonicalType(CT->getElementType());
2990 
2991     uint64_t Size = getContext().getTypeSize(Ty);
2992     if (ET->isIntegralOrEnumerationType()) {
2993       if (Size <= 64)
2994         Current = Integer;
2995       else if (Size <= 128)
2996         Lo = Hi = Integer;
2997     } else if (ET->isFloat16Type() || ET == getContext().FloatTy) {
2998       Current = SSE;
2999     } else if (ET == getContext().DoubleTy) {
3000       Lo = Hi = SSE;
3001     } else if (ET == getContext().LongDoubleTy) {
3002       const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
3003       if (LDF == &llvm::APFloat::IEEEquad())
3004         Current = Memory;
3005       else if (LDF == &llvm::APFloat::x87DoubleExtended())
3006         Current = ComplexX87;
3007       else if (LDF == &llvm::APFloat::IEEEdouble())
3008         Lo = Hi = SSE;
3009       else
3010         llvm_unreachable("unexpected long double representation!");
3011     }
3012 
3013     // If this complex type crosses an eightbyte boundary then it
3014     // should be split.
3015     uint64_t EB_Real = (OffsetBase) / 64;
3016     uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
3017     if (Hi == NoClass && EB_Real != EB_Imag)
3018       Hi = Lo;
3019 
3020     return;
3021   }
3022 
3023   if (const auto *EITy = Ty->getAs<BitIntType>()) {
3024     if (EITy->getNumBits() <= 64)
3025       Current = Integer;
3026     else if (EITy->getNumBits() <= 128)
3027       Lo = Hi = Integer;
3028     // Larger values need to get passed in memory.
3029     return;
3030   }
3031 
3032   if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
3033     // Arrays are treated like structures.
3034 
3035     uint64_t Size = getContext().getTypeSize(Ty);
3036 
3037     // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
3038     // than eight eightbytes, ..., it has class MEMORY.
3039     // regcall ABI doesn't have limitation to an object. The only limitation
3040     // is the free registers, which will be checked in computeInfo.
3041     if (!IsRegCall && Size > 512)
3042       return;
3043 
3044     // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
3045     // fields, it has class MEMORY.
3046     //
3047     // Only need to check alignment of array base.
3048     if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
3049       return;
3050 
3051     // Otherwise implement simplified merge. We could be smarter about
3052     // this, but it isn't worth it and would be harder to verify.
3053     Current = NoClass;
3054     uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
3055     uint64_t ArraySize = AT->getSize().getZExtValue();
3056 
3057     // The only case a 256-bit wide vector could be used is when the array
3058     // contains a single 256-bit element. Since Lo and Hi logic isn't extended
3059     // to work for sizes wider than 128, early check and fallback to memory.
3060     //
3061     if (Size > 128 &&
3062         (Size != EltSize || Size > getNativeVectorSizeForAVXABI(AVXLevel)))
3063       return;
3064 
3065     for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
3066       Class FieldLo, FieldHi;
3067       classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
3068       Lo = merge(Lo, FieldLo);
3069       Hi = merge(Hi, FieldHi);
3070       if (Lo == Memory || Hi == Memory)
3071         break;
3072     }
3073 
3074     postMerge(Size, Lo, Hi);
3075     assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
3076     return;
3077   }
3078 
3079   if (const RecordType *RT = Ty->getAs<RecordType>()) {
3080     uint64_t Size = getContext().getTypeSize(Ty);
3081 
3082     // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
3083     // than eight eightbytes, ..., it has class MEMORY.
3084     if (Size > 512)
3085       return;
3086 
3087     // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
3088     // copy constructor or a non-trivial destructor, it is passed by invisible
3089     // reference.
3090     if (getRecordArgABI(RT, getCXXABI()))
3091       return;
3092 
3093     const RecordDecl *RD = RT->getDecl();
3094 
3095     // Assume variable sized types are passed in memory.
3096     if (RD->hasFlexibleArrayMember())
3097       return;
3098 
3099     const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
3100 
3101     // Reset Lo class, this will be recomputed.
3102     Current = NoClass;
3103 
3104     // If this is a C++ record, classify the bases first.
3105     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3106       for (const auto &I : CXXRD->bases()) {
3107         assert(!I.isVirtual() && !I.getType()->isDependentType() &&
3108                "Unexpected base class!");
3109         const auto *Base =
3110             cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
3111 
3112         // Classify this field.
3113         //
3114         // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
3115         // single eightbyte, each is classified separately. Each eightbyte gets
3116         // initialized to class NO_CLASS.
3117         Class FieldLo, FieldHi;
3118         uint64_t Offset =
3119           OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
3120         classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg);
3121         Lo = merge(Lo, FieldLo);
3122         Hi = merge(Hi, FieldHi);
3123         if (Lo == Memory || Hi == Memory) {
3124           postMerge(Size, Lo, Hi);
3125           return;
3126         }
3127       }
3128     }
3129 
3130     // Classify the fields one at a time, merging the results.
3131     unsigned idx = 0;
3132     bool UseClang11Compat = getContext().getLangOpts().getClangABICompat() <=
3133                                 LangOptions::ClangABI::Ver11 ||
3134                             getContext().getTargetInfo().getTriple().isPS4();
3135     bool IsUnion = RT->isUnionType() && !UseClang11Compat;
3136 
3137     for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
3138            i != e; ++i, ++idx) {
3139       uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
3140       bool BitField = i->isBitField();
3141 
3142       // Ignore padding bit-fields.
3143       if (BitField && i->isUnnamedBitfield())
3144         continue;
3145 
3146       // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
3147       // eight eightbytes, or it contains unaligned fields, it has class MEMORY.
3148       //
3149       // The only case a 256-bit or a 512-bit wide vector could be used is when
3150       // the struct contains a single 256-bit or 512-bit element. Early check
3151       // and fallback to memory.
3152       //
3153       // FIXME: Extended the Lo and Hi logic properly to work for size wider
3154       // than 128.
3155       if (Size > 128 &&
3156           ((!IsUnion && Size != getContext().getTypeSize(i->getType())) ||
3157            Size > getNativeVectorSizeForAVXABI(AVXLevel))) {
3158         Lo = Memory;
3159         postMerge(Size, Lo, Hi);
3160         return;
3161       }
3162       // Note, skip this test for bit-fields, see below.
3163       if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
3164         Lo = Memory;
3165         postMerge(Size, Lo, Hi);
3166         return;
3167       }
3168 
3169       // Classify this field.
3170       //
3171       // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
3172       // exceeds a single eightbyte, each is classified
3173       // separately. Each eightbyte gets initialized to class
3174       // NO_CLASS.
3175       Class FieldLo, FieldHi;
3176 
3177       // Bit-fields require special handling, they do not force the
3178       // structure to be passed in memory even if unaligned, and
3179       // therefore they can straddle an eightbyte.
3180       if (BitField) {
3181         assert(!i->isUnnamedBitfield());
3182         uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
3183         uint64_t Size = i->getBitWidthValue(getContext());
3184 
3185         uint64_t EB_Lo = Offset / 64;
3186         uint64_t EB_Hi = (Offset + Size - 1) / 64;
3187 
3188         if (EB_Lo) {
3189           assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
3190           FieldLo = NoClass;
3191           FieldHi = Integer;
3192         } else {
3193           FieldLo = Integer;
3194           FieldHi = EB_Hi ? Integer : NoClass;
3195         }
3196       } else
3197         classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
3198       Lo = merge(Lo, FieldLo);
3199       Hi = merge(Hi, FieldHi);
3200       if (Lo == Memory || Hi == Memory)
3201         break;
3202     }
3203 
3204     postMerge(Size, Lo, Hi);
3205   }
3206 }
3207 
3208 ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
3209   // If this is a scalar LLVM value then assume LLVM will pass it in the right
3210   // place naturally.
3211   if (!isAggregateTypeForABI(Ty)) {
3212     // Treat an enum type as its underlying type.
3213     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3214       Ty = EnumTy->getDecl()->getIntegerType();
3215 
3216     if (Ty->isBitIntType())
3217       return getNaturalAlignIndirect(Ty);
3218 
3219     return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
3220                                               : ABIArgInfo::getDirect());
3221   }
3222 
3223   return getNaturalAlignIndirect(Ty);
3224 }
3225 
3226 bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
3227   if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
3228     uint64_t Size = getContext().getTypeSize(VecTy);
3229     unsigned LargestVector = getNativeVectorSizeForAVXABI(AVXLevel);
3230     if (Size <= 64 || Size > LargestVector)
3231       return true;
3232     QualType EltTy = VecTy->getElementType();
3233     if (passInt128VectorsInMem() &&
3234         (EltTy->isSpecificBuiltinType(BuiltinType::Int128) ||
3235          EltTy->isSpecificBuiltinType(BuiltinType::UInt128)))
3236       return true;
3237   }
3238 
3239   return false;
3240 }
3241 
3242 ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
3243                                             unsigned freeIntRegs) const {
3244   // If this is a scalar LLVM value then assume LLVM will pass it in the right
3245   // place naturally.
3246   //
3247   // This assumption is optimistic, as there could be free registers available
3248   // when we need to pass this argument in memory, and LLVM could try to pass
3249   // the argument in the free register. This does not seem to happen currently,
3250   // but this code would be much safer if we could mark the argument with
3251   // 'onstack'. See PR12193.
3252   if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty) &&
3253       !Ty->isBitIntType()) {
3254     // Treat an enum type as its underlying type.
3255     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3256       Ty = EnumTy->getDecl()->getIntegerType();
3257 
3258     return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
3259                                               : ABIArgInfo::getDirect());
3260   }
3261 
3262   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
3263     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
3264 
3265   // Compute the byval alignment. We specify the alignment of the byval in all
3266   // cases so that the mid-level optimizer knows the alignment of the byval.
3267   unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
3268 
3269   // Attempt to avoid passing indirect results using byval when possible. This
3270   // is important for good codegen.
3271   //
3272   // We do this by coercing the value into a scalar type which the backend can
3273   // handle naturally (i.e., without using byval).
3274   //
3275   // For simplicity, we currently only do this when we have exhausted all of the
3276   // free integer registers. Doing this when there are free integer registers
3277   // would require more care, as we would have to ensure that the coerced value
3278   // did not claim the unused register. That would require either reording the
3279   // arguments to the function (so that any subsequent inreg values came first),
3280   // or only doing this optimization when there were no following arguments that
3281   // might be inreg.
3282   //
3283   // We currently expect it to be rare (particularly in well written code) for
3284   // arguments to be passed on the stack when there are still free integer
3285   // registers available (this would typically imply large structs being passed
3286   // by value), so this seems like a fair tradeoff for now.
3287   //
3288   // We can revisit this if the backend grows support for 'onstack' parameter
3289   // attributes. See PR12193.
3290   if (freeIntRegs == 0) {
3291     uint64_t Size = getContext().getTypeSize(Ty);
3292 
3293     // If this type fits in an eightbyte, coerce it into the matching integral
3294     // type, which will end up on the stack (with alignment 8).
3295     if (Align == 8 && Size <= 64)
3296       return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
3297                                                           Size));
3298   }
3299 
3300   return ABIArgInfo::getIndirect(CharUnits::fromQuantity(Align));
3301 }
3302 
3303 /// The ABI specifies that a value should be passed in a full vector XMM/YMM
3304 /// register. Pick an LLVM IR type that will be passed as a vector register.
3305 llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
3306   // Wrapper structs/arrays that only contain vectors are passed just like
3307   // vectors; strip them off if present.
3308   if (const Type *InnerTy = isSingleElementStruct(Ty, getContext()))
3309     Ty = QualType(InnerTy, 0);
3310 
3311   llvm::Type *IRType = CGT.ConvertType(Ty);
3312   if (isa<llvm::VectorType>(IRType)) {
3313     // Don't pass vXi128 vectors in their native type, the backend can't
3314     // legalize them.
3315     if (passInt128VectorsInMem() &&
3316         cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy(128)) {
3317       // Use a vXi64 vector.
3318       uint64_t Size = getContext().getTypeSize(Ty);
3319       return llvm::FixedVectorType::get(llvm::Type::getInt64Ty(getVMContext()),
3320                                         Size / 64);
3321     }
3322 
3323     return IRType;
3324   }
3325 
3326   if (IRType->getTypeID() == llvm::Type::FP128TyID)
3327     return IRType;
3328 
3329   // We couldn't find the preferred IR vector type for 'Ty'.
3330   uint64_t Size = getContext().getTypeSize(Ty);
3331   assert((Size == 128 || Size == 256 || Size == 512) && "Invalid type found!");
3332 
3333 
3334   // Return a LLVM IR vector type based on the size of 'Ty'.
3335   return llvm::FixedVectorType::get(llvm::Type::getDoubleTy(getVMContext()),
3336                                     Size / 64);
3337 }
3338 
3339 /// BitsContainNoUserData - Return true if the specified [start,end) bit range
3340 /// is known to either be off the end of the specified type or being in
3341 /// alignment padding.  The user type specified is known to be at most 128 bits
3342 /// in size, and have passed through X86_64ABIInfo::classify with a successful
3343 /// classification that put one of the two halves in the INTEGER class.
3344 ///
3345 /// It is conservatively correct to return false.
3346 static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
3347                                   unsigned EndBit, ASTContext &Context) {
3348   // If the bytes being queried are off the end of the type, there is no user
3349   // data hiding here.  This handles analysis of builtins, vectors and other
3350   // types that don't contain interesting padding.
3351   unsigned TySize = (unsigned)Context.getTypeSize(Ty);
3352   if (TySize <= StartBit)
3353     return true;
3354 
3355   if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
3356     unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
3357     unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
3358 
3359     // Check each element to see if the element overlaps with the queried range.
3360     for (unsigned i = 0; i != NumElts; ++i) {
3361       // If the element is after the span we care about, then we're done..
3362       unsigned EltOffset = i*EltSize;
3363       if (EltOffset >= EndBit) break;
3364 
3365       unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
3366       if (!BitsContainNoUserData(AT->getElementType(), EltStart,
3367                                  EndBit-EltOffset, Context))
3368         return false;
3369     }
3370     // If it overlaps no elements, then it is safe to process as padding.
3371     return true;
3372   }
3373 
3374   if (const RecordType *RT = Ty->getAs<RecordType>()) {
3375     const RecordDecl *RD = RT->getDecl();
3376     const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
3377 
3378     // If this is a C++ record, check the bases first.
3379     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3380       for (const auto &I : CXXRD->bases()) {
3381         assert(!I.isVirtual() && !I.getType()->isDependentType() &&
3382                "Unexpected base class!");
3383         const auto *Base =
3384             cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
3385 
3386         // If the base is after the span we care about, ignore it.
3387         unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
3388         if (BaseOffset >= EndBit) continue;
3389 
3390         unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
3391         if (!BitsContainNoUserData(I.getType(), BaseStart,
3392                                    EndBit-BaseOffset, Context))
3393           return false;
3394       }
3395     }
3396 
3397     // Verify that no field has data that overlaps the region of interest.  Yes
3398     // this could be sped up a lot by being smarter about queried fields,
3399     // however we're only looking at structs up to 16 bytes, so we don't care
3400     // much.
3401     unsigned idx = 0;
3402     for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
3403          i != e; ++i, ++idx) {
3404       unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
3405 
3406       // If we found a field after the region we care about, then we're done.
3407       if (FieldOffset >= EndBit) break;
3408 
3409       unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
3410       if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
3411                                  Context))
3412         return false;
3413     }
3414 
3415     // If nothing in this record overlapped the area of interest, then we're
3416     // clean.
3417     return true;
3418   }
3419 
3420   return false;
3421 }
3422 
3423 /// getFPTypeAtOffset - Return a floating point type at the specified offset.
3424 static llvm::Type *getFPTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
3425                                      const llvm::DataLayout &TD) {
3426   if (IROffset == 0 && IRType->isFloatingPointTy())
3427     return IRType;
3428 
3429   // If this is a struct, recurse into the field at the specified offset.
3430   if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
3431     if (!STy->getNumContainedTypes())
3432       return nullptr;
3433 
3434     const llvm::StructLayout *SL = TD.getStructLayout(STy);
3435     unsigned Elt = SL->getElementContainingOffset(IROffset);
3436     IROffset -= SL->getElementOffset(Elt);
3437     return getFPTypeAtOffset(STy->getElementType(Elt), IROffset, TD);
3438   }
3439 
3440   // If this is an array, recurse into the field at the specified offset.
3441   if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
3442     llvm::Type *EltTy = ATy->getElementType();
3443     unsigned EltSize = TD.getTypeAllocSize(EltTy);
3444     IROffset -= IROffset / EltSize * EltSize;
3445     return getFPTypeAtOffset(EltTy, IROffset, TD);
3446   }
3447 
3448   return nullptr;
3449 }
3450 
3451 /// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
3452 /// low 8 bytes of an XMM register, corresponding to the SSE class.
3453 llvm::Type *X86_64ABIInfo::
3454 GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
3455                    QualType SourceTy, unsigned SourceOffset) const {
3456   const llvm::DataLayout &TD = getDataLayout();
3457   unsigned SourceSize =
3458       (unsigned)getContext().getTypeSize(SourceTy) / 8 - SourceOffset;
3459   llvm::Type *T0 = getFPTypeAtOffset(IRType, IROffset, TD);
3460   if (!T0 || T0->isDoubleTy())
3461     return llvm::Type::getDoubleTy(getVMContext());
3462 
3463   // Get the adjacent FP type.
3464   llvm::Type *T1 = nullptr;
3465   unsigned T0Size = TD.getTypeAllocSize(T0);
3466   if (SourceSize > T0Size)
3467       T1 = getFPTypeAtOffset(IRType, IROffset + T0Size, TD);
3468   if (T1 == nullptr) {
3469     // Check if IRType is a half + float. float type will be in IROffset+4 due
3470     // to its alignment.
3471     if (T0->isHalfTy() && SourceSize > 4)
3472       T1 = getFPTypeAtOffset(IRType, IROffset + 4, TD);
3473     // If we can't get a second FP type, return a simple half or float.
3474     // avx512fp16-abi.c:pr51813_2 shows it works to return float for
3475     // {float, i8} too.
3476     if (T1 == nullptr)
3477       return T0;
3478   }
3479 
3480   if (T0->isFloatTy() && T1->isFloatTy())
3481     return llvm::FixedVectorType::get(T0, 2);
3482 
3483   if (T0->isHalfTy() && T1->isHalfTy()) {
3484     llvm::Type *T2 = nullptr;
3485     if (SourceSize > 4)
3486       T2 = getFPTypeAtOffset(IRType, IROffset + 4, TD);
3487     if (T2 == nullptr)
3488       return llvm::FixedVectorType::get(T0, 2);
3489     return llvm::FixedVectorType::get(T0, 4);
3490   }
3491 
3492   if (T0->isHalfTy() || T1->isHalfTy())
3493     return llvm::FixedVectorType::get(llvm::Type::getHalfTy(getVMContext()), 4);
3494 
3495   return llvm::Type::getDoubleTy(getVMContext());
3496 }
3497 
3498 
3499 /// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
3500 /// an 8-byte GPR.  This means that we either have a scalar or we are talking
3501 /// about the high or low part of an up-to-16-byte struct.  This routine picks
3502 /// the best LLVM IR type to represent this, which may be i64 or may be anything
3503 /// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
3504 /// etc).
3505 ///
3506 /// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
3507 /// the source type.  IROffset is an offset in bytes into the LLVM IR type that
3508 /// the 8-byte value references.  PrefType may be null.
3509 ///
3510 /// SourceTy is the source-level type for the entire argument.  SourceOffset is
3511 /// an offset into this that we're processing (which is always either 0 or 8).
3512 ///
3513 llvm::Type *X86_64ABIInfo::
3514 GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
3515                        QualType SourceTy, unsigned SourceOffset) const {
3516   // If we're dealing with an un-offset LLVM IR type, then it means that we're
3517   // returning an 8-byte unit starting with it.  See if we can safely use it.
3518   if (IROffset == 0) {
3519     // Pointers and int64's always fill the 8-byte unit.
3520     if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
3521         IRType->isIntegerTy(64))
3522       return IRType;
3523 
3524     // If we have a 1/2/4-byte integer, we can use it only if the rest of the
3525     // goodness in the source type is just tail padding.  This is allowed to
3526     // kick in for struct {double,int} on the int, but not on
3527     // struct{double,int,int} because we wouldn't return the second int.  We
3528     // have to do this analysis on the source type because we can't depend on
3529     // unions being lowered a specific way etc.
3530     if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
3531         IRType->isIntegerTy(32) ||
3532         (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
3533       unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
3534           cast<llvm::IntegerType>(IRType)->getBitWidth();
3535 
3536       if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
3537                                 SourceOffset*8+64, getContext()))
3538         return IRType;
3539     }
3540   }
3541 
3542   if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
3543     // If this is a struct, recurse into the field at the specified offset.
3544     const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
3545     if (IROffset < SL->getSizeInBytes()) {
3546       unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
3547       IROffset -= SL->getElementOffset(FieldIdx);
3548 
3549       return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
3550                                     SourceTy, SourceOffset);
3551     }
3552   }
3553 
3554   if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
3555     llvm::Type *EltTy = ATy->getElementType();
3556     unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
3557     unsigned EltOffset = IROffset/EltSize*EltSize;
3558     return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
3559                                   SourceOffset);
3560   }
3561 
3562   // Okay, we don't have any better idea of what to pass, so we pass this in an
3563   // integer register that isn't too big to fit the rest of the struct.
3564   unsigned TySizeInBytes =
3565     (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
3566 
3567   assert(TySizeInBytes != SourceOffset && "Empty field?");
3568 
3569   // It is always safe to classify this as an integer type up to i64 that
3570   // isn't larger than the structure.
3571   return llvm::IntegerType::get(getVMContext(),
3572                                 std::min(TySizeInBytes-SourceOffset, 8U)*8);
3573 }
3574 
3575 
3576 /// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
3577 /// be used as elements of a two register pair to pass or return, return a
3578 /// first class aggregate to represent them.  For example, if the low part of
3579 /// a by-value argument should be passed as i32* and the high part as float,
3580 /// return {i32*, float}.
3581 static llvm::Type *
3582 GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
3583                            const llvm::DataLayout &TD) {
3584   // In order to correctly satisfy the ABI, we need to the high part to start
3585   // at offset 8.  If the high and low parts we inferred are both 4-byte types
3586   // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
3587   // the second element at offset 8.  Check for this:
3588   unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
3589   unsigned HiAlign = TD.getABITypeAlignment(Hi);
3590   unsigned HiStart = llvm::alignTo(LoSize, HiAlign);
3591   assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
3592 
3593   // To handle this, we have to increase the size of the low part so that the
3594   // second element will start at an 8 byte offset.  We can't increase the size
3595   // of the second element because it might make us access off the end of the
3596   // struct.
3597   if (HiStart != 8) {
3598     // There are usually two sorts of types the ABI generation code can produce
3599     // for the low part of a pair that aren't 8 bytes in size: half, float or
3600     // i8/i16/i32.  This can also include pointers when they are 32-bit (X32 and
3601     // NaCl).
3602     // Promote these to a larger type.
3603     if (Lo->isHalfTy() || Lo->isFloatTy())
3604       Lo = llvm::Type::getDoubleTy(Lo->getContext());
3605     else {
3606       assert((Lo->isIntegerTy() || Lo->isPointerTy())
3607              && "Invalid/unknown lo type");
3608       Lo = llvm::Type::getInt64Ty(Lo->getContext());
3609     }
3610   }
3611 
3612   llvm::StructType *Result = llvm::StructType::get(Lo, Hi);
3613 
3614   // Verify that the second element is at an 8-byte offset.
3615   assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
3616          "Invalid x86-64 argument pair!");
3617   return Result;
3618 }
3619 
3620 ABIArgInfo X86_64ABIInfo::
3621 classifyReturnType(QualType RetTy) const {
3622   // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
3623   // classification algorithm.
3624   X86_64ABIInfo::Class Lo, Hi;
3625   classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
3626 
3627   // Check some invariants.
3628   assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
3629   assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
3630 
3631   llvm::Type *ResType = nullptr;
3632   switch (Lo) {
3633   case NoClass:
3634     if (Hi == NoClass)
3635       return ABIArgInfo::getIgnore();
3636     // If the low part is just padding, it takes no register, leave ResType
3637     // null.
3638     assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3639            "Unknown missing lo part");
3640     break;
3641 
3642   case SSEUp:
3643   case X87Up:
3644     llvm_unreachable("Invalid classification for lo word.");
3645 
3646     // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
3647     // hidden argument.
3648   case Memory:
3649     return getIndirectReturnResult(RetTy);
3650 
3651     // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
3652     // available register of the sequence %rax, %rdx is used.
3653   case Integer:
3654     ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
3655 
3656     // If we have a sign or zero extended integer, make sure to return Extend
3657     // so that the parameter gets the right LLVM IR attributes.
3658     if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3659       // Treat an enum type as its underlying type.
3660       if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
3661         RetTy = EnumTy->getDecl()->getIntegerType();
3662 
3663       if (RetTy->isIntegralOrEnumerationType() &&
3664           isPromotableIntegerTypeForABI(RetTy))
3665         return ABIArgInfo::getExtend(RetTy);
3666     }
3667     break;
3668 
3669     // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
3670     // available SSE register of the sequence %xmm0, %xmm1 is used.
3671   case SSE:
3672     ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
3673     break;
3674 
3675     // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
3676     // returned on the X87 stack in %st0 as 80-bit x87 number.
3677   case X87:
3678     ResType = llvm::Type::getX86_FP80Ty(getVMContext());
3679     break;
3680 
3681     // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
3682     // part of the value is returned in %st0 and the imaginary part in
3683     // %st1.
3684   case ComplexX87:
3685     assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
3686     ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
3687                                     llvm::Type::getX86_FP80Ty(getVMContext()));
3688     break;
3689   }
3690 
3691   llvm::Type *HighPart = nullptr;
3692   switch (Hi) {
3693     // Memory was handled previously and X87 should
3694     // never occur as a hi class.
3695   case Memory:
3696   case X87:
3697     llvm_unreachable("Invalid classification for hi word.");
3698 
3699   case ComplexX87: // Previously handled.
3700   case NoClass:
3701     break;
3702 
3703   case Integer:
3704     HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
3705     if (Lo == NoClass)  // Return HighPart at offset 8 in memory.
3706       return ABIArgInfo::getDirect(HighPart, 8);
3707     break;
3708   case SSE:
3709     HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
3710     if (Lo == NoClass)  // Return HighPart at offset 8 in memory.
3711       return ABIArgInfo::getDirect(HighPart, 8);
3712     break;
3713 
3714     // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
3715     // is passed in the next available eightbyte chunk if the last used
3716     // vector register.
3717     //
3718     // SSEUP should always be preceded by SSE, just widen.
3719   case SSEUp:
3720     assert(Lo == SSE && "Unexpected SSEUp classification.");
3721     ResType = GetByteVectorType(RetTy);
3722     break;
3723 
3724     // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
3725     // returned together with the previous X87 value in %st0.
3726   case X87Up:
3727     // If X87Up is preceded by X87, we don't need to do
3728     // anything. However, in some cases with unions it may not be
3729     // preceded by X87. In such situations we follow gcc and pass the
3730     // extra bits in an SSE reg.
3731     if (Lo != X87) {
3732       HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
3733       if (Lo == NoClass)  // Return HighPart at offset 8 in memory.
3734         return ABIArgInfo::getDirect(HighPart, 8);
3735     }
3736     break;
3737   }
3738 
3739   // If a high part was specified, merge it together with the low part.  It is
3740   // known to pass in the high eightbyte of the result.  We do this by forming a
3741   // first class struct aggregate with the high and low part: {low, high}
3742   if (HighPart)
3743     ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
3744 
3745   return ABIArgInfo::getDirect(ResType);
3746 }
3747 
3748 ABIArgInfo
3749 X86_64ABIInfo::classifyArgumentType(QualType Ty, unsigned freeIntRegs,
3750                                     unsigned &neededInt, unsigned &neededSSE,
3751                                     bool isNamedArg, bool IsRegCall) const {
3752   Ty = useFirstFieldIfTransparentUnion(Ty);
3753 
3754   X86_64ABIInfo::Class Lo, Hi;
3755   classify(Ty, 0, Lo, Hi, isNamedArg, IsRegCall);
3756 
3757   // Check some invariants.
3758   // FIXME: Enforce these by construction.
3759   assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
3760   assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
3761 
3762   neededInt = 0;
3763   neededSSE = 0;
3764   llvm::Type *ResType = nullptr;
3765   switch (Lo) {
3766   case NoClass:
3767     if (Hi == NoClass)
3768       return ABIArgInfo::getIgnore();
3769     // If the low part is just padding, it takes no register, leave ResType
3770     // null.
3771     assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3772            "Unknown missing lo part");
3773     break;
3774 
3775     // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
3776     // on the stack.
3777   case Memory:
3778 
3779     // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
3780     // COMPLEX_X87, it is passed in memory.
3781   case X87:
3782   case ComplexX87:
3783     if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect)
3784       ++neededInt;
3785     return getIndirectResult(Ty, freeIntRegs);
3786 
3787   case SSEUp:
3788   case X87Up:
3789     llvm_unreachable("Invalid classification for lo word.");
3790 
3791     // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
3792     // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
3793     // and %r9 is used.
3794   case Integer:
3795     ++neededInt;
3796 
3797     // Pick an 8-byte type based on the preferred type.
3798     ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
3799 
3800     // If we have a sign or zero extended integer, make sure to return Extend
3801     // so that the parameter gets the right LLVM IR attributes.
3802     if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3803       // Treat an enum type as its underlying type.
3804       if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3805         Ty = EnumTy->getDecl()->getIntegerType();
3806 
3807       if (Ty->isIntegralOrEnumerationType() &&
3808           isPromotableIntegerTypeForABI(Ty))
3809         return ABIArgInfo::getExtend(Ty);
3810     }
3811 
3812     break;
3813 
3814     // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
3815     // available SSE register is used, the registers are taken in the
3816     // order from %xmm0 to %xmm7.
3817   case SSE: {
3818     llvm::Type *IRType = CGT.ConvertType(Ty);
3819     ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
3820     ++neededSSE;
3821     break;
3822   }
3823   }
3824 
3825   llvm::Type *HighPart = nullptr;
3826   switch (Hi) {
3827     // Memory was handled previously, ComplexX87 and X87 should
3828     // never occur as hi classes, and X87Up must be preceded by X87,
3829     // which is passed in memory.
3830   case Memory:
3831   case X87:
3832   case ComplexX87:
3833     llvm_unreachable("Invalid classification for hi word.");
3834 
3835   case NoClass: break;
3836 
3837   case Integer:
3838     ++neededInt;
3839     // Pick an 8-byte type based on the preferred type.
3840     HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
3841 
3842     if (Lo == NoClass)  // Pass HighPart at offset 8 in memory.
3843       return ABIArgInfo::getDirect(HighPart, 8);
3844     break;
3845 
3846     // X87Up generally doesn't occur here (long double is passed in
3847     // memory), except in situations involving unions.
3848   case X87Up:
3849   case SSE:
3850     HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
3851 
3852     if (Lo == NoClass)  // Pass HighPart at offset 8 in memory.
3853       return ABIArgInfo::getDirect(HighPart, 8);
3854 
3855     ++neededSSE;
3856     break;
3857 
3858     // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
3859     // eightbyte is passed in the upper half of the last used SSE
3860     // register.  This only happens when 128-bit vectors are passed.
3861   case SSEUp:
3862     assert(Lo == SSE && "Unexpected SSEUp classification");
3863     ResType = GetByteVectorType(Ty);
3864     break;
3865   }
3866 
3867   // If a high part was specified, merge it together with the low part.  It is
3868   // known to pass in the high eightbyte of the result.  We do this by forming a
3869   // first class struct aggregate with the high and low part: {low, high}
3870   if (HighPart)
3871     ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
3872 
3873   return ABIArgInfo::getDirect(ResType);
3874 }
3875 
3876 ABIArgInfo
3877 X86_64ABIInfo::classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
3878                                              unsigned &NeededSSE,
3879                                              unsigned &MaxVectorWidth) const {
3880   auto RT = Ty->getAs<RecordType>();
3881   assert(RT && "classifyRegCallStructType only valid with struct types");
3882 
3883   if (RT->getDecl()->hasFlexibleArrayMember())
3884     return getIndirectReturnResult(Ty);
3885 
3886   // Sum up bases
3887   if (auto CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
3888     if (CXXRD->isDynamicClass()) {
3889       NeededInt = NeededSSE = 0;
3890       return getIndirectReturnResult(Ty);
3891     }
3892 
3893     for (const auto &I : CXXRD->bases())
3894       if (classifyRegCallStructTypeImpl(I.getType(), NeededInt, NeededSSE,
3895                                         MaxVectorWidth)
3896               .isIndirect()) {
3897         NeededInt = NeededSSE = 0;
3898         return getIndirectReturnResult(Ty);
3899       }
3900   }
3901 
3902   // Sum up members
3903   for (const auto *FD : RT->getDecl()->fields()) {
3904     QualType MTy = FD->getType();
3905     if (MTy->isRecordType() && !MTy->isUnionType()) {
3906       if (classifyRegCallStructTypeImpl(MTy, NeededInt, NeededSSE,
3907                                         MaxVectorWidth)
3908               .isIndirect()) {
3909         NeededInt = NeededSSE = 0;
3910         return getIndirectReturnResult(Ty);
3911       }
3912     } else {
3913       unsigned LocalNeededInt, LocalNeededSSE;
3914       if (classifyArgumentType(MTy, UINT_MAX, LocalNeededInt, LocalNeededSSE,
3915                                true, true)
3916               .isIndirect()) {
3917         NeededInt = NeededSSE = 0;
3918         return getIndirectReturnResult(Ty);
3919       }
3920       if (const auto *AT = getContext().getAsConstantArrayType(MTy))
3921         MTy = AT->getElementType();
3922       if (const auto *VT = MTy->getAs<VectorType>())
3923         if (getContext().getTypeSize(VT) > MaxVectorWidth)
3924           MaxVectorWidth = getContext().getTypeSize(VT);
3925       NeededInt += LocalNeededInt;
3926       NeededSSE += LocalNeededSSE;
3927     }
3928   }
3929 
3930   return ABIArgInfo::getDirect();
3931 }
3932 
3933 ABIArgInfo
3934 X86_64ABIInfo::classifyRegCallStructType(QualType Ty, unsigned &NeededInt,
3935                                          unsigned &NeededSSE,
3936                                          unsigned &MaxVectorWidth) const {
3937 
3938   NeededInt = 0;
3939   NeededSSE = 0;
3940   MaxVectorWidth = 0;
3941 
3942   return classifyRegCallStructTypeImpl(Ty, NeededInt, NeededSSE,
3943                                        MaxVectorWidth);
3944 }
3945 
3946 void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
3947 
3948   const unsigned CallingConv = FI.getCallingConvention();
3949   // It is possible to force Win64 calling convention on any x86_64 target by
3950   // using __attribute__((ms_abi)). In such case to correctly emit Win64
3951   // compatible code delegate this call to WinX86_64ABIInfo::computeInfo.
3952   if (CallingConv == llvm::CallingConv::Win64) {
3953     WinX86_64ABIInfo Win64ABIInfo(CGT, AVXLevel);
3954     Win64ABIInfo.computeInfo(FI);
3955     return;
3956   }
3957 
3958   bool IsRegCall = CallingConv == llvm::CallingConv::X86_RegCall;
3959 
3960   // Keep track of the number of assigned registers.
3961   unsigned FreeIntRegs = IsRegCall ? 11 : 6;
3962   unsigned FreeSSERegs = IsRegCall ? 16 : 8;
3963   unsigned NeededInt = 0, NeededSSE = 0, MaxVectorWidth = 0;
3964 
3965   if (!::classifyReturnType(getCXXABI(), FI, *this)) {
3966     if (IsRegCall && FI.getReturnType()->getTypePtr()->isRecordType() &&
3967         !FI.getReturnType()->getTypePtr()->isUnionType()) {
3968       FI.getReturnInfo() = classifyRegCallStructType(
3969           FI.getReturnType(), NeededInt, NeededSSE, MaxVectorWidth);
3970       if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
3971         FreeIntRegs -= NeededInt;
3972         FreeSSERegs -= NeededSSE;
3973       } else {
3974         FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType());
3975       }
3976     } else if (IsRegCall && FI.getReturnType()->getAs<ComplexType>() &&
3977                getContext().getCanonicalType(FI.getReturnType()
3978                                                  ->getAs<ComplexType>()
3979                                                  ->getElementType()) ==
3980                    getContext().LongDoubleTy)
3981       // Complex Long Double Type is passed in Memory when Regcall
3982       // calling convention is used.
3983       FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType());
3984     else
3985       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
3986   }
3987 
3988   // If the return value is indirect, then the hidden argument is consuming one
3989   // integer register.
3990   if (FI.getReturnInfo().isIndirect())
3991     --FreeIntRegs;
3992   else if (NeededSSE && MaxVectorWidth > 0)
3993     FI.setMaxVectorWidth(MaxVectorWidth);
3994 
3995   // The chain argument effectively gives us another free register.
3996   if (FI.isChainCall())
3997     ++FreeIntRegs;
3998 
3999   unsigned NumRequiredArgs = FI.getNumRequiredArgs();
4000   // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
4001   // get assigned (in left-to-right order) for passing as follows...
4002   unsigned ArgNo = 0;
4003   for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
4004        it != ie; ++it, ++ArgNo) {
4005     bool IsNamedArg = ArgNo < NumRequiredArgs;
4006 
4007     if (IsRegCall && it->type->isStructureOrClassType())
4008       it->info = classifyRegCallStructType(it->type, NeededInt, NeededSSE,
4009                                            MaxVectorWidth);
4010     else
4011       it->info = classifyArgumentType(it->type, FreeIntRegs, NeededInt,
4012                                       NeededSSE, IsNamedArg);
4013 
4014     // AMD64-ABI 3.2.3p3: If there are no registers available for any
4015     // eightbyte of an argument, the whole argument is passed on the
4016     // stack. If registers have already been assigned for some
4017     // eightbytes of such an argument, the assignments get reverted.
4018     if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
4019       FreeIntRegs -= NeededInt;
4020       FreeSSERegs -= NeededSSE;
4021       if (MaxVectorWidth > FI.getMaxVectorWidth())
4022         FI.setMaxVectorWidth(MaxVectorWidth);
4023     } else {
4024       it->info = getIndirectResult(it->type, FreeIntRegs);
4025     }
4026   }
4027 }
4028 
4029 static Address EmitX86_64VAArgFromMemory(CodeGenFunction &CGF,
4030                                          Address VAListAddr, QualType Ty) {
4031   Address overflow_arg_area_p =
4032       CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_p");
4033   llvm::Value *overflow_arg_area =
4034     CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
4035 
4036   // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
4037   // byte boundary if alignment needed by type exceeds 8 byte boundary.
4038   // It isn't stated explicitly in the standard, but in practice we use
4039   // alignment greater than 16 where necessary.
4040   CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
4041   if (Align > CharUnits::fromQuantity(8)) {
4042     overflow_arg_area = emitRoundPointerUpToAlignment(CGF, overflow_arg_area,
4043                                                       Align);
4044   }
4045 
4046   // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
4047   llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
4048   llvm::Value *Res =
4049     CGF.Builder.CreateBitCast(overflow_arg_area,
4050                               llvm::PointerType::getUnqual(LTy));
4051 
4052   // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
4053   // l->overflow_arg_area + sizeof(type).
4054   // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
4055   // an 8 byte boundary.
4056 
4057   uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
4058   llvm::Value *Offset =
4059       llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7)  & ~7);
4060   overflow_arg_area = CGF.Builder.CreateGEP(CGF.Int8Ty, overflow_arg_area,
4061                                             Offset, "overflow_arg_area.next");
4062   CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
4063 
4064   // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
4065   return Address(Res, LTy, Align);
4066 }
4067 
4068 Address X86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4069                                  QualType Ty) const {
4070   // Assume that va_list type is correct; should be pointer to LLVM type:
4071   // struct {
4072   //   i32 gp_offset;
4073   //   i32 fp_offset;
4074   //   i8* overflow_arg_area;
4075   //   i8* reg_save_area;
4076   // };
4077   unsigned neededInt, neededSSE;
4078 
4079   Ty = getContext().getCanonicalType(Ty);
4080   ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
4081                                        /*isNamedArg*/false);
4082 
4083   // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
4084   // in the registers. If not go to step 7.
4085   if (!neededInt && !neededSSE)
4086     return EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
4087 
4088   // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
4089   // general purpose registers needed to pass type and num_fp to hold
4090   // the number of floating point registers needed.
4091 
4092   // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
4093   // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
4094   // l->fp_offset > 304 - num_fp * 16 go to step 7.
4095   //
4096   // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
4097   // register save space).
4098 
4099   llvm::Value *InRegs = nullptr;
4100   Address gp_offset_p = Address::invalid(), fp_offset_p = Address::invalid();
4101   llvm::Value *gp_offset = nullptr, *fp_offset = nullptr;
4102   if (neededInt) {
4103     gp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "gp_offset_p");
4104     gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
4105     InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
4106     InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
4107   }
4108 
4109   if (neededSSE) {
4110     fp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 1, "fp_offset_p");
4111     fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
4112     llvm::Value *FitsInFP =
4113       llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
4114     FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
4115     InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
4116   }
4117 
4118   llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
4119   llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
4120   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
4121   CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
4122 
4123   // Emit code to load the value if it was passed in registers.
4124 
4125   CGF.EmitBlock(InRegBlock);
4126 
4127   // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
4128   // an offset of l->gp_offset and/or l->fp_offset. This may require
4129   // copying to a temporary location in case the parameter is passed
4130   // in different register classes or requires an alignment greater
4131   // than 8 for general purpose registers and 16 for XMM registers.
4132   //
4133   // FIXME: This really results in shameful code when we end up needing to
4134   // collect arguments from different places; often what should result in a
4135   // simple assembling of a structure from scattered addresses has many more
4136   // loads than necessary. Can we clean this up?
4137   llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
4138   llvm::Value *RegSaveArea = CGF.Builder.CreateLoad(
4139       CGF.Builder.CreateStructGEP(VAListAddr, 3), "reg_save_area");
4140 
4141   Address RegAddr = Address::invalid();
4142   if (neededInt && neededSSE) {
4143     // FIXME: Cleanup.
4144     assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
4145     llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
4146     Address Tmp = CGF.CreateMemTemp(Ty);
4147     Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
4148     assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
4149     llvm::Type *TyLo = ST->getElementType(0);
4150     llvm::Type *TyHi = ST->getElementType(1);
4151     assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
4152            "Unexpected ABI info for mixed regs");
4153     llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
4154     llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
4155     llvm::Value *GPAddr =
4156         CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, gp_offset);
4157     llvm::Value *FPAddr =
4158         CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, fp_offset);
4159     llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr;
4160     llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr;
4161 
4162     // Copy the first element.
4163     // FIXME: Our choice of alignment here and below is probably pessimistic.
4164     llvm::Value *V = CGF.Builder.CreateAlignedLoad(
4165         TyLo, CGF.Builder.CreateBitCast(RegLoAddr, PTyLo),
4166         CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyLo)));
4167     CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
4168 
4169     // Copy the second element.
4170     V = CGF.Builder.CreateAlignedLoad(
4171         TyHi, CGF.Builder.CreateBitCast(RegHiAddr, PTyHi),
4172         CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyHi)));
4173     CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
4174 
4175     RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
4176   } else if (neededInt) {
4177     RegAddr = Address(CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, gp_offset),
4178                       CGF.Int8Ty, CharUnits::fromQuantity(8));
4179     RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
4180 
4181     // Copy to a temporary if necessary to ensure the appropriate alignment.
4182     auto TInfo = getContext().getTypeInfoInChars(Ty);
4183     uint64_t TySize = TInfo.Width.getQuantity();
4184     CharUnits TyAlign = TInfo.Align;
4185 
4186     // Copy into a temporary if the type is more aligned than the
4187     // register save area.
4188     if (TyAlign.getQuantity() > 8) {
4189       Address Tmp = CGF.CreateMemTemp(Ty);
4190       CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, false);
4191       RegAddr = Tmp;
4192     }
4193 
4194   } else if (neededSSE == 1) {
4195     RegAddr = Address(CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, fp_offset),
4196                       CGF.Int8Ty, CharUnits::fromQuantity(16));
4197     RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
4198   } else {
4199     assert(neededSSE == 2 && "Invalid number of needed registers!");
4200     // SSE registers are spaced 16 bytes apart in the register save
4201     // area, we need to collect the two eightbytes together.
4202     // The ABI isn't explicit about this, but it seems reasonable
4203     // to assume that the slots are 16-byte aligned, since the stack is
4204     // naturally 16-byte aligned and the prologue is expected to store
4205     // all the SSE registers to the RSA.
4206     Address RegAddrLo = Address(CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea,
4207                                                       fp_offset),
4208                                 CGF.Int8Ty, CharUnits::fromQuantity(16));
4209     Address RegAddrHi =
4210       CGF.Builder.CreateConstInBoundsByteGEP(RegAddrLo,
4211                                              CharUnits::fromQuantity(16));
4212     llvm::Type *ST = AI.canHaveCoerceToType()
4213                          ? AI.getCoerceToType()
4214                          : llvm::StructType::get(CGF.DoubleTy, CGF.DoubleTy);
4215     llvm::Value *V;
4216     Address Tmp = CGF.CreateMemTemp(Ty);
4217     Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
4218     V = CGF.Builder.CreateLoad(CGF.Builder.CreateElementBitCast(
4219         RegAddrLo, ST->getStructElementType(0)));
4220     CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
4221     V = CGF.Builder.CreateLoad(CGF.Builder.CreateElementBitCast(
4222         RegAddrHi, ST->getStructElementType(1)));
4223     CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
4224 
4225     RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
4226   }
4227 
4228   // AMD64-ABI 3.5.7p5: Step 5. Set:
4229   // l->gp_offset = l->gp_offset + num_gp * 8
4230   // l->fp_offset = l->fp_offset + num_fp * 16.
4231   if (neededInt) {
4232     llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
4233     CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
4234                             gp_offset_p);
4235   }
4236   if (neededSSE) {
4237     llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
4238     CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
4239                             fp_offset_p);
4240   }
4241   CGF.EmitBranch(ContBlock);
4242 
4243   // Emit code to load the value if it was passed in memory.
4244 
4245   CGF.EmitBlock(InMemBlock);
4246   Address MemAddr = EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
4247 
4248   // Return the appropriate result.
4249 
4250   CGF.EmitBlock(ContBlock);
4251   Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, MemAddr, InMemBlock,
4252                                  "vaarg.addr");
4253   return ResAddr;
4254 }
4255 
4256 Address X86_64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
4257                                    QualType Ty) const {
4258   // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
4259   // not 1, 2, 4, or 8 bytes, must be passed by reference."
4260   uint64_t Width = getContext().getTypeSize(Ty);
4261   bool IsIndirect = Width > 64 || !llvm::isPowerOf2_64(Width);
4262 
4263   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
4264                           CGF.getContext().getTypeInfoInChars(Ty),
4265                           CharUnits::fromQuantity(8),
4266                           /*allowHigherAlign*/ false);
4267 }
4268 
4269 ABIArgInfo WinX86_64ABIInfo::reclassifyHvaArgForVectorCall(
4270     QualType Ty, unsigned &FreeSSERegs, const ABIArgInfo &current) const {
4271   const Type *Base = nullptr;
4272   uint64_t NumElts = 0;
4273 
4274   if (!Ty->isBuiltinType() && !Ty->isVectorType() &&
4275       isHomogeneousAggregate(Ty, Base, NumElts) && FreeSSERegs >= NumElts) {
4276     FreeSSERegs -= NumElts;
4277     return getDirectX86Hva();
4278   }
4279   return current;
4280 }
4281 
4282 ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, unsigned &FreeSSERegs,
4283                                       bool IsReturnType, bool IsVectorCall,
4284                                       bool IsRegCall) const {
4285 
4286   if (Ty->isVoidType())
4287     return ABIArgInfo::getIgnore();
4288 
4289   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4290     Ty = EnumTy->getDecl()->getIntegerType();
4291 
4292   TypeInfo Info = getContext().getTypeInfo(Ty);
4293   uint64_t Width = Info.Width;
4294   CharUnits Align = getContext().toCharUnitsFromBits(Info.Align);
4295 
4296   const RecordType *RT = Ty->getAs<RecordType>();
4297   if (RT) {
4298     if (!IsReturnType) {
4299       if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
4300         return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
4301     }
4302 
4303     if (RT->getDecl()->hasFlexibleArrayMember())
4304       return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
4305 
4306   }
4307 
4308   const Type *Base = nullptr;
4309   uint64_t NumElts = 0;
4310   // vectorcall adds the concept of a homogenous vector aggregate, similar to
4311   // other targets.
4312   if ((IsVectorCall || IsRegCall) &&
4313       isHomogeneousAggregate(Ty, Base, NumElts)) {
4314     if (IsRegCall) {
4315       if (FreeSSERegs >= NumElts) {
4316         FreeSSERegs -= NumElts;
4317         if (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())
4318           return ABIArgInfo::getDirect();
4319         return ABIArgInfo::getExpand();
4320       }
4321       return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
4322     } else if (IsVectorCall) {
4323       if (FreeSSERegs >= NumElts &&
4324           (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())) {
4325         FreeSSERegs -= NumElts;
4326         return ABIArgInfo::getDirect();
4327       } else if (IsReturnType) {
4328         return ABIArgInfo::getExpand();
4329       } else if (!Ty->isBuiltinType() && !Ty->isVectorType()) {
4330         // HVAs are delayed and reclassified in the 2nd step.
4331         return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
4332       }
4333     }
4334   }
4335 
4336   if (Ty->isMemberPointerType()) {
4337     // If the member pointer is represented by an LLVM int or ptr, pass it
4338     // directly.
4339     llvm::Type *LLTy = CGT.ConvertType(Ty);
4340     if (LLTy->isPointerTy() || LLTy->isIntegerTy())
4341       return ABIArgInfo::getDirect();
4342   }
4343 
4344   if (RT || Ty->isAnyComplexType() || Ty->isMemberPointerType()) {
4345     // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
4346     // not 1, 2, 4, or 8 bytes, must be passed by reference."
4347     if (Width > 64 || !llvm::isPowerOf2_64(Width))
4348       return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
4349 
4350     // Otherwise, coerce it to a small integer.
4351     return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Width));
4352   }
4353 
4354   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4355     switch (BT->getKind()) {
4356     case BuiltinType::Bool:
4357       // Bool type is always extended to the ABI, other builtin types are not
4358       // extended.
4359       return ABIArgInfo::getExtend(Ty);
4360 
4361     case BuiltinType::LongDouble:
4362       // Mingw64 GCC uses the old 80 bit extended precision floating point
4363       // unit. It passes them indirectly through memory.
4364       if (IsMingw64) {
4365         const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
4366         if (LDF == &llvm::APFloat::x87DoubleExtended())
4367           return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
4368       }
4369       break;
4370 
4371     case BuiltinType::Int128:
4372     case BuiltinType::UInt128:
4373       // If it's a parameter type, the normal ABI rule is that arguments larger
4374       // than 8 bytes are passed indirectly. GCC follows it. We follow it too,
4375       // even though it isn't particularly efficient.
4376       if (!IsReturnType)
4377         return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
4378 
4379       // Mingw64 GCC returns i128 in XMM0. Coerce to v2i64 to handle that.
4380       // Clang matches them for compatibility.
4381       return ABIArgInfo::getDirect(llvm::FixedVectorType::get(
4382           llvm::Type::getInt64Ty(getVMContext()), 2));
4383 
4384     default:
4385       break;
4386     }
4387   }
4388 
4389   if (Ty->isBitIntType()) {
4390     // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
4391     // not 1, 2, 4, or 8 bytes, must be passed by reference."
4392     // However, non-power-of-two bit-precise integers will be passed as 1, 2, 4,
4393     // or 8 bytes anyway as long is it fits in them, so we don't have to check
4394     // the power of 2.
4395     if (Width <= 64)
4396       return ABIArgInfo::getDirect();
4397     return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
4398   }
4399 
4400   return ABIArgInfo::getDirect();
4401 }
4402 
4403 void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
4404   const unsigned CC = FI.getCallingConvention();
4405   bool IsVectorCall = CC == llvm::CallingConv::X86_VectorCall;
4406   bool IsRegCall = CC == llvm::CallingConv::X86_RegCall;
4407 
4408   // If __attribute__((sysv_abi)) is in use, use the SysV argument
4409   // classification rules.
4410   if (CC == llvm::CallingConv::X86_64_SysV) {
4411     X86_64ABIInfo SysVABIInfo(CGT, AVXLevel);
4412     SysVABIInfo.computeInfo(FI);
4413     return;
4414   }
4415 
4416   unsigned FreeSSERegs = 0;
4417   if (IsVectorCall) {
4418     // We can use up to 4 SSE return registers with vectorcall.
4419     FreeSSERegs = 4;
4420   } else if (IsRegCall) {
4421     // RegCall gives us 16 SSE registers.
4422     FreeSSERegs = 16;
4423   }
4424 
4425   if (!getCXXABI().classifyReturnType(FI))
4426     FI.getReturnInfo() = classify(FI.getReturnType(), FreeSSERegs, true,
4427                                   IsVectorCall, IsRegCall);
4428 
4429   if (IsVectorCall) {
4430     // We can use up to 6 SSE register parameters with vectorcall.
4431     FreeSSERegs = 6;
4432   } else if (IsRegCall) {
4433     // RegCall gives us 16 SSE registers, we can reuse the return registers.
4434     FreeSSERegs = 16;
4435   }
4436 
4437   unsigned ArgNum = 0;
4438   unsigned ZeroSSERegs = 0;
4439   for (auto &I : FI.arguments()) {
4440     // Vectorcall in x64 only permits the first 6 arguments to be passed as
4441     // XMM/YMM registers. After the sixth argument, pretend no vector
4442     // registers are left.
4443     unsigned *MaybeFreeSSERegs =
4444         (IsVectorCall && ArgNum >= 6) ? &ZeroSSERegs : &FreeSSERegs;
4445     I.info =
4446         classify(I.type, *MaybeFreeSSERegs, false, IsVectorCall, IsRegCall);
4447     ++ArgNum;
4448   }
4449 
4450   if (IsVectorCall) {
4451     // For vectorcall, assign aggregate HVAs to any free vector registers in a
4452     // second pass.
4453     for (auto &I : FI.arguments())
4454       I.info = reclassifyHvaArgForVectorCall(I.type, FreeSSERegs, I.info);
4455   }
4456 }
4457 
4458 Address WinX86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4459                                     QualType Ty) const {
4460   // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
4461   // not 1, 2, 4, or 8 bytes, must be passed by reference."
4462   uint64_t Width = getContext().getTypeSize(Ty);
4463   bool IsIndirect = Width > 64 || !llvm::isPowerOf2_64(Width);
4464 
4465   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
4466                           CGF.getContext().getTypeInfoInChars(Ty),
4467                           CharUnits::fromQuantity(8),
4468                           /*allowHigherAlign*/ false);
4469 }
4470 
4471 static bool PPC_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4472                                         llvm::Value *Address, bool Is64Bit,
4473                                         bool IsAIX) {
4474   // This is calculated from the LLVM and GCC tables and verified
4475   // against gcc output.  AFAIK all PPC ABIs use the same encoding.
4476 
4477   CodeGen::CGBuilderTy &Builder = CGF.Builder;
4478 
4479   llvm::IntegerType *i8 = CGF.Int8Ty;
4480   llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
4481   llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
4482   llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
4483 
4484   // 0-31: r0-31, the 4-byte or 8-byte general-purpose registers
4485   AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 0, 31);
4486 
4487   // 32-63: fp0-31, the 8-byte floating-point registers
4488   AssignToArrayRange(Builder, Address, Eight8, 32, 63);
4489 
4490   // 64-67 are various 4-byte or 8-byte special-purpose registers:
4491   // 64: mq
4492   // 65: lr
4493   // 66: ctr
4494   // 67: ap
4495   AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 64, 67);
4496 
4497   // 68-76 are various 4-byte special-purpose registers:
4498   // 68-75 cr0-7
4499   // 76: xer
4500   AssignToArrayRange(Builder, Address, Four8, 68, 76);
4501 
4502   // 77-108: v0-31, the 16-byte vector registers
4503   AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
4504 
4505   // 109: vrsave
4506   // 110: vscr
4507   AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 109, 110);
4508 
4509   // AIX does not utilize the rest of the registers.
4510   if (IsAIX)
4511     return false;
4512 
4513   // 111: spe_acc
4514   // 112: spefscr
4515   // 113: sfp
4516   AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 111, 113);
4517 
4518   if (!Is64Bit)
4519     return false;
4520 
4521   // TODO: Need to verify if these registers are used on 64 bit AIX with Power8
4522   // or above CPU.
4523   // 64-bit only registers:
4524   // 114: tfhar
4525   // 115: tfiar
4526   // 116: texasr
4527   AssignToArrayRange(Builder, Address, Eight8, 114, 116);
4528 
4529   return false;
4530 }
4531 
4532 // AIX
4533 namespace {
4534 /// AIXABIInfo - The AIX XCOFF ABI information.
4535 class AIXABIInfo : public ABIInfo {
4536   const bool Is64Bit;
4537   const unsigned PtrByteSize;
4538   CharUnits getParamTypeAlignment(QualType Ty) const;
4539 
4540 public:
4541   AIXABIInfo(CodeGen::CodeGenTypes &CGT, bool Is64Bit)
4542       : ABIInfo(CGT), Is64Bit(Is64Bit), PtrByteSize(Is64Bit ? 8 : 4) {}
4543 
4544   bool isPromotableTypeForABI(QualType Ty) const;
4545 
4546   ABIArgInfo classifyReturnType(QualType RetTy) const;
4547   ABIArgInfo classifyArgumentType(QualType Ty) const;
4548 
4549   void computeInfo(CGFunctionInfo &FI) const override {
4550     if (!getCXXABI().classifyReturnType(FI))
4551       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
4552 
4553     for (auto &I : FI.arguments())
4554       I.info = classifyArgumentType(I.type);
4555   }
4556 
4557   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4558                     QualType Ty) const override;
4559 };
4560 
4561 class AIXTargetCodeGenInfo : public TargetCodeGenInfo {
4562   const bool Is64Bit;
4563 
4564 public:
4565   AIXTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool Is64Bit)
4566       : TargetCodeGenInfo(std::make_unique<AIXABIInfo>(CGT, Is64Bit)),
4567         Is64Bit(Is64Bit) {}
4568   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4569     return 1; // r1 is the dedicated stack pointer
4570   }
4571 
4572   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4573                                llvm::Value *Address) const override;
4574 };
4575 } // namespace
4576 
4577 // Return true if the ABI requires Ty to be passed sign- or zero-
4578 // extended to 32/64 bits.
4579 bool AIXABIInfo::isPromotableTypeForABI(QualType Ty) const {
4580   // Treat an enum type as its underlying type.
4581   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4582     Ty = EnumTy->getDecl()->getIntegerType();
4583 
4584   // Promotable integer types are required to be promoted by the ABI.
4585   if (Ty->isPromotableIntegerType())
4586     return true;
4587 
4588   if (!Is64Bit)
4589     return false;
4590 
4591   // For 64 bit mode, in addition to the usual promotable integer types, we also
4592   // need to extend all 32-bit types, since the ABI requires promotion to 64
4593   // bits.
4594   if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
4595     switch (BT->getKind()) {
4596     case BuiltinType::Int:
4597     case BuiltinType::UInt:
4598       return true;
4599     default:
4600       break;
4601     }
4602 
4603   return false;
4604 }
4605 
4606 ABIArgInfo AIXABIInfo::classifyReturnType(QualType RetTy) const {
4607   if (RetTy->isAnyComplexType())
4608     return ABIArgInfo::getDirect();
4609 
4610   if (RetTy->isVectorType())
4611     return ABIArgInfo::getDirect();
4612 
4613   if (RetTy->isVoidType())
4614     return ABIArgInfo::getIgnore();
4615 
4616   if (isAggregateTypeForABI(RetTy))
4617     return getNaturalAlignIndirect(RetTy);
4618 
4619   return (isPromotableTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
4620                                         : ABIArgInfo::getDirect());
4621 }
4622 
4623 ABIArgInfo AIXABIInfo::classifyArgumentType(QualType Ty) const {
4624   Ty = useFirstFieldIfTransparentUnion(Ty);
4625 
4626   if (Ty->isAnyComplexType())
4627     return ABIArgInfo::getDirect();
4628 
4629   if (Ty->isVectorType())
4630     return ABIArgInfo::getDirect();
4631 
4632   if (isAggregateTypeForABI(Ty)) {
4633     // Records with non-trivial destructors/copy-constructors should not be
4634     // passed by value.
4635     if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
4636       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
4637 
4638     CharUnits CCAlign = getParamTypeAlignment(Ty);
4639     CharUnits TyAlign = getContext().getTypeAlignInChars(Ty);
4640 
4641     return ABIArgInfo::getIndirect(CCAlign, /*ByVal*/ true,
4642                                    /*Realign*/ TyAlign > CCAlign);
4643   }
4644 
4645   return (isPromotableTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
4646                                      : ABIArgInfo::getDirect());
4647 }
4648 
4649 CharUnits AIXABIInfo::getParamTypeAlignment(QualType Ty) const {
4650   // Complex types are passed just like their elements.
4651   if (const ComplexType *CTy = Ty->getAs<ComplexType>())
4652     Ty = CTy->getElementType();
4653 
4654   if (Ty->isVectorType())
4655     return CharUnits::fromQuantity(16);
4656 
4657   // If the structure contains a vector type, the alignment is 16.
4658   if (isRecordWithSIMDVectorType(getContext(), Ty))
4659     return CharUnits::fromQuantity(16);
4660 
4661   return CharUnits::fromQuantity(PtrByteSize);
4662 }
4663 
4664 Address AIXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4665                               QualType Ty) const {
4666 
4667   auto TypeInfo = getContext().getTypeInfoInChars(Ty);
4668   TypeInfo.Align = getParamTypeAlignment(Ty);
4669 
4670   CharUnits SlotSize = CharUnits::fromQuantity(PtrByteSize);
4671 
4672   // If we have a complex type and the base type is smaller than the register
4673   // size, the ABI calls for the real and imaginary parts to be right-adjusted
4674   // in separate words in 32bit mode or doublewords in 64bit mode. However,
4675   // Clang expects us to produce a pointer to a structure with the two parts
4676   // packed tightly. So generate loads of the real and imaginary parts relative
4677   // to the va_list pointer, and store them to a temporary structure. We do the
4678   // same as the PPC64ABI here.
4679   if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
4680     CharUnits EltSize = TypeInfo.Width / 2;
4681     if (EltSize < SlotSize)
4682       return complexTempStructure(CGF, VAListAddr, Ty, SlotSize, EltSize, CTy);
4683   }
4684 
4685   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false, TypeInfo,
4686                           SlotSize, /*AllowHigher*/ true);
4687 }
4688 
4689 bool AIXTargetCodeGenInfo::initDwarfEHRegSizeTable(
4690     CodeGen::CodeGenFunction &CGF, llvm::Value *Address) const {
4691   return PPC_initDwarfEHRegSizeTable(CGF, Address, Is64Bit, /*IsAIX*/ true);
4692 }
4693 
4694 // PowerPC-32
4695 namespace {
4696 /// PPC32_SVR4_ABIInfo - The 32-bit PowerPC ELF (SVR4) ABI information.
4697 class PPC32_SVR4_ABIInfo : public DefaultABIInfo {
4698   bool IsSoftFloatABI;
4699   bool IsRetSmallStructInRegABI;
4700 
4701   CharUnits getParamTypeAlignment(QualType Ty) const;
4702 
4703 public:
4704   PPC32_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, bool SoftFloatABI,
4705                      bool RetSmallStructInRegABI)
4706       : DefaultABIInfo(CGT), IsSoftFloatABI(SoftFloatABI),
4707         IsRetSmallStructInRegABI(RetSmallStructInRegABI) {}
4708 
4709   ABIArgInfo classifyReturnType(QualType RetTy) const;
4710 
4711   void computeInfo(CGFunctionInfo &FI) const override {
4712     if (!getCXXABI().classifyReturnType(FI))
4713       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
4714     for (auto &I : FI.arguments())
4715       I.info = classifyArgumentType(I.type);
4716   }
4717 
4718   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4719                     QualType Ty) const override;
4720 };
4721 
4722 class PPC32TargetCodeGenInfo : public TargetCodeGenInfo {
4723 public:
4724   PPC32TargetCodeGenInfo(CodeGenTypes &CGT, bool SoftFloatABI,
4725                          bool RetSmallStructInRegABI)
4726       : TargetCodeGenInfo(std::make_unique<PPC32_SVR4_ABIInfo>(
4727             CGT, SoftFloatABI, RetSmallStructInRegABI)) {}
4728 
4729   static bool isStructReturnInRegABI(const llvm::Triple &Triple,
4730                                      const CodeGenOptions &Opts);
4731 
4732   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4733     // This is recovered from gcc output.
4734     return 1; // r1 is the dedicated stack pointer
4735   }
4736 
4737   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4738                                llvm::Value *Address) const override;
4739 };
4740 }
4741 
4742 CharUnits PPC32_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const {
4743   // Complex types are passed just like their elements.
4744   if (const ComplexType *CTy = Ty->getAs<ComplexType>())
4745     Ty = CTy->getElementType();
4746 
4747   if (Ty->isVectorType())
4748     return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16
4749                                                                        : 4);
4750 
4751   // For single-element float/vector structs, we consider the whole type
4752   // to have the same alignment requirements as its single element.
4753   const Type *AlignTy = nullptr;
4754   if (const Type *EltType = isSingleElementStruct(Ty, getContext())) {
4755     const BuiltinType *BT = EltType->getAs<BuiltinType>();
4756     if ((EltType->isVectorType() && getContext().getTypeSize(EltType) == 128) ||
4757         (BT && BT->isFloatingPoint()))
4758       AlignTy = EltType;
4759   }
4760 
4761   if (AlignTy)
4762     return CharUnits::fromQuantity(AlignTy->isVectorType() ? 16 : 4);
4763   return CharUnits::fromQuantity(4);
4764 }
4765 
4766 ABIArgInfo PPC32_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
4767   uint64_t Size;
4768 
4769   // -msvr4-struct-return puts small aggregates in GPR3 and GPR4.
4770   if (isAggregateTypeForABI(RetTy) && IsRetSmallStructInRegABI &&
4771       (Size = getContext().getTypeSize(RetTy)) <= 64) {
4772     // System V ABI (1995), page 3-22, specified:
4773     // > A structure or union whose size is less than or equal to 8 bytes
4774     // > shall be returned in r3 and r4, as if it were first stored in the
4775     // > 8-byte aligned memory area and then the low addressed word were
4776     // > loaded into r3 and the high-addressed word into r4.  Bits beyond
4777     // > the last member of the structure or union are not defined.
4778     //
4779     // GCC for big-endian PPC32 inserts the pad before the first member,
4780     // not "beyond the last member" of the struct.  To stay compatible
4781     // with GCC, we coerce the struct to an integer of the same size.
4782     // LLVM will extend it and return i32 in r3, or i64 in r3:r4.
4783     if (Size == 0)
4784       return ABIArgInfo::getIgnore();
4785     else {
4786       llvm::Type *CoerceTy = llvm::Type::getIntNTy(getVMContext(), Size);
4787       return ABIArgInfo::getDirect(CoerceTy);
4788     }
4789   }
4790 
4791   return DefaultABIInfo::classifyReturnType(RetTy);
4792 }
4793 
4794 // TODO: this implementation is now likely redundant with
4795 // DefaultABIInfo::EmitVAArg.
4796 Address PPC32_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAList,
4797                                       QualType Ty) const {
4798   if (getTarget().getTriple().isOSDarwin()) {
4799     auto TI = getContext().getTypeInfoInChars(Ty);
4800     TI.Align = getParamTypeAlignment(Ty);
4801 
4802     CharUnits SlotSize = CharUnits::fromQuantity(4);
4803     return emitVoidPtrVAArg(CGF, VAList, Ty,
4804                             classifyArgumentType(Ty).isIndirect(), TI, SlotSize,
4805                             /*AllowHigherAlign=*/true);
4806   }
4807 
4808   const unsigned OverflowLimit = 8;
4809   if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
4810     // TODO: Implement this. For now ignore.
4811     (void)CTy;
4812     return Address::invalid(); // FIXME?
4813   }
4814 
4815   // struct __va_list_tag {
4816   //   unsigned char gpr;
4817   //   unsigned char fpr;
4818   //   unsigned short reserved;
4819   //   void *overflow_arg_area;
4820   //   void *reg_save_area;
4821   // };
4822 
4823   bool isI64 = Ty->isIntegerType() && getContext().getTypeSize(Ty) == 64;
4824   bool isInt = !Ty->isFloatingType();
4825   bool isF64 = Ty->isFloatingType() && getContext().getTypeSize(Ty) == 64;
4826 
4827   // All aggregates are passed indirectly?  That doesn't seem consistent
4828   // with the argument-lowering code.
4829   bool isIndirect = isAggregateTypeForABI(Ty);
4830 
4831   CGBuilderTy &Builder = CGF.Builder;
4832 
4833   // The calling convention either uses 1-2 GPRs or 1 FPR.
4834   Address NumRegsAddr = Address::invalid();
4835   if (isInt || IsSoftFloatABI) {
4836     NumRegsAddr = Builder.CreateStructGEP(VAList, 0, "gpr");
4837   } else {
4838     NumRegsAddr = Builder.CreateStructGEP(VAList, 1, "fpr");
4839   }
4840 
4841   llvm::Value *NumRegs = Builder.CreateLoad(NumRegsAddr, "numUsedRegs");
4842 
4843   // "Align" the register count when TY is i64.
4844   if (isI64 || (isF64 && IsSoftFloatABI)) {
4845     NumRegs = Builder.CreateAdd(NumRegs, Builder.getInt8(1));
4846     NumRegs = Builder.CreateAnd(NumRegs, Builder.getInt8((uint8_t) ~1U));
4847   }
4848 
4849   llvm::Value *CC =
4850       Builder.CreateICmpULT(NumRegs, Builder.getInt8(OverflowLimit), "cond");
4851 
4852   llvm::BasicBlock *UsingRegs = CGF.createBasicBlock("using_regs");
4853   llvm::BasicBlock *UsingOverflow = CGF.createBasicBlock("using_overflow");
4854   llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
4855 
4856   Builder.CreateCondBr(CC, UsingRegs, UsingOverflow);
4857 
4858   llvm::Type *DirectTy = CGF.ConvertType(Ty), *ElementTy = DirectTy;
4859   if (isIndirect) DirectTy = DirectTy->getPointerTo(0);
4860 
4861   // Case 1: consume registers.
4862   Address RegAddr = Address::invalid();
4863   {
4864     CGF.EmitBlock(UsingRegs);
4865 
4866     Address RegSaveAreaPtr = Builder.CreateStructGEP(VAList, 4);
4867     RegAddr = Address(Builder.CreateLoad(RegSaveAreaPtr), CGF.Int8Ty,
4868                       CharUnits::fromQuantity(8));
4869     assert(RegAddr.getElementType() == CGF.Int8Ty);
4870 
4871     // Floating-point registers start after the general-purpose registers.
4872     if (!(isInt || IsSoftFloatABI)) {
4873       RegAddr = Builder.CreateConstInBoundsByteGEP(RegAddr,
4874                                                    CharUnits::fromQuantity(32));
4875     }
4876 
4877     // Get the address of the saved value by scaling the number of
4878     // registers we've used by the number of
4879     CharUnits RegSize = CharUnits::fromQuantity((isInt || IsSoftFloatABI) ? 4 : 8);
4880     llvm::Value *RegOffset =
4881         Builder.CreateMul(NumRegs, Builder.getInt8(RegSize.getQuantity()));
4882     RegAddr = Address(
4883         Builder.CreateInBoundsGEP(CGF.Int8Ty, RegAddr.getPointer(), RegOffset),
4884         CGF.Int8Ty, RegAddr.getAlignment().alignmentOfArrayElement(RegSize));
4885     RegAddr = Builder.CreateElementBitCast(RegAddr, DirectTy);
4886 
4887     // Increase the used-register count.
4888     NumRegs =
4889       Builder.CreateAdd(NumRegs,
4890                         Builder.getInt8((isI64 || (isF64 && IsSoftFloatABI)) ? 2 : 1));
4891     Builder.CreateStore(NumRegs, NumRegsAddr);
4892 
4893     CGF.EmitBranch(Cont);
4894   }
4895 
4896   // Case 2: consume space in the overflow area.
4897   Address MemAddr = Address::invalid();
4898   {
4899     CGF.EmitBlock(UsingOverflow);
4900 
4901     Builder.CreateStore(Builder.getInt8(OverflowLimit), NumRegsAddr);
4902 
4903     // Everything in the overflow area is rounded up to a size of at least 4.
4904     CharUnits OverflowAreaAlign = CharUnits::fromQuantity(4);
4905 
4906     CharUnits Size;
4907     if (!isIndirect) {
4908       auto TypeInfo = CGF.getContext().getTypeInfoInChars(Ty);
4909       Size = TypeInfo.Width.alignTo(OverflowAreaAlign);
4910     } else {
4911       Size = CGF.getPointerSize();
4912     }
4913 
4914     Address OverflowAreaAddr = Builder.CreateStructGEP(VAList, 3);
4915     Address OverflowArea =
4916         Address(Builder.CreateLoad(OverflowAreaAddr, "argp.cur"), CGF.Int8Ty,
4917                 OverflowAreaAlign);
4918     // Round up address of argument to alignment
4919     CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
4920     if (Align > OverflowAreaAlign) {
4921       llvm::Value *Ptr = OverflowArea.getPointer();
4922       OverflowArea = Address(emitRoundPointerUpToAlignment(CGF, Ptr, Align),
4923                              OverflowArea.getElementType(), Align);
4924     }
4925 
4926     MemAddr = Builder.CreateElementBitCast(OverflowArea, DirectTy);
4927 
4928     // Increase the overflow area.
4929     OverflowArea = Builder.CreateConstInBoundsByteGEP(OverflowArea, Size);
4930     Builder.CreateStore(OverflowArea.getPointer(), OverflowAreaAddr);
4931     CGF.EmitBranch(Cont);
4932   }
4933 
4934   CGF.EmitBlock(Cont);
4935 
4936   // Merge the cases with a phi.
4937   Address Result = emitMergePHI(CGF, RegAddr, UsingRegs, MemAddr, UsingOverflow,
4938                                 "vaarg.addr");
4939 
4940   // Load the pointer if the argument was passed indirectly.
4941   if (isIndirect) {
4942     Result = Address(Builder.CreateLoad(Result, "aggr"), ElementTy,
4943                      getContext().getTypeAlignInChars(Ty));
4944   }
4945 
4946   return Result;
4947 }
4948 
4949 bool PPC32TargetCodeGenInfo::isStructReturnInRegABI(
4950     const llvm::Triple &Triple, const CodeGenOptions &Opts) {
4951   assert(Triple.isPPC32());
4952 
4953   switch (Opts.getStructReturnConvention()) {
4954   case CodeGenOptions::SRCK_Default:
4955     break;
4956   case CodeGenOptions::SRCK_OnStack: // -maix-struct-return
4957     return false;
4958   case CodeGenOptions::SRCK_InRegs: // -msvr4-struct-return
4959     return true;
4960   }
4961 
4962   if (Triple.isOSBinFormatELF() && !Triple.isOSLinux())
4963     return true;
4964 
4965   return false;
4966 }
4967 
4968 bool
4969 PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4970                                                 llvm::Value *Address) const {
4971   return PPC_initDwarfEHRegSizeTable(CGF, Address, /*Is64Bit*/ false,
4972                                      /*IsAIX*/ false);
4973 }
4974 
4975 // PowerPC-64
4976 
4977 namespace {
4978 /// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
4979 class PPC64_SVR4_ABIInfo : public SwiftABIInfo {
4980 public:
4981   enum ABIKind {
4982     ELFv1 = 0,
4983     ELFv2
4984   };
4985 
4986 private:
4987   static const unsigned GPRBits = 64;
4988   ABIKind Kind;
4989   bool IsSoftFloatABI;
4990 
4991 public:
4992   PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind,
4993                      bool SoftFloatABI)
4994       : SwiftABIInfo(CGT), Kind(Kind), IsSoftFloatABI(SoftFloatABI) {}
4995 
4996   bool isPromotableTypeForABI(QualType Ty) const;
4997   CharUnits getParamTypeAlignment(QualType Ty) const;
4998 
4999   ABIArgInfo classifyReturnType(QualType RetTy) const;
5000   ABIArgInfo classifyArgumentType(QualType Ty) const;
5001 
5002   bool isHomogeneousAggregateBaseType(QualType Ty) const override;
5003   bool isHomogeneousAggregateSmallEnough(const Type *Ty,
5004                                          uint64_t Members) const override;
5005 
5006   // TODO: We can add more logic to computeInfo to improve performance.
5007   // Example: For aggregate arguments that fit in a register, we could
5008   // use getDirectInReg (as is done below for structs containing a single
5009   // floating-point value) to avoid pushing them to memory on function
5010   // entry.  This would require changing the logic in PPCISelLowering
5011   // when lowering the parameters in the caller and args in the callee.
5012   void computeInfo(CGFunctionInfo &FI) const override {
5013     if (!getCXXABI().classifyReturnType(FI))
5014       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
5015     for (auto &I : FI.arguments()) {
5016       // We rely on the default argument classification for the most part.
5017       // One exception:  An aggregate containing a single floating-point
5018       // or vector item must be passed in a register if one is available.
5019       const Type *T = isSingleElementStruct(I.type, getContext());
5020       if (T) {
5021         const BuiltinType *BT = T->getAs<BuiltinType>();
5022         if ((T->isVectorType() && getContext().getTypeSize(T) == 128) ||
5023             (BT && BT->isFloatingPoint())) {
5024           QualType QT(T, 0);
5025           I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
5026           continue;
5027         }
5028       }
5029       I.info = classifyArgumentType(I.type);
5030     }
5031   }
5032 
5033   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5034                     QualType Ty) const override;
5035 
5036   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
5037                                     bool asReturnValue) const override {
5038     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
5039   }
5040 
5041   bool isSwiftErrorInRegister() const override {
5042     return false;
5043   }
5044 };
5045 
5046 class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
5047 
5048 public:
5049   PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT,
5050                                PPC64_SVR4_ABIInfo::ABIKind Kind,
5051                                bool SoftFloatABI)
5052       : TargetCodeGenInfo(
5053             std::make_unique<PPC64_SVR4_ABIInfo>(CGT, Kind, SoftFloatABI)) {}
5054 
5055   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
5056     // This is recovered from gcc output.
5057     return 1; // r1 is the dedicated stack pointer
5058   }
5059 
5060   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
5061                                llvm::Value *Address) const override;
5062 };
5063 
5064 class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
5065 public:
5066   PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
5067 
5068   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
5069     // This is recovered from gcc output.
5070     return 1; // r1 is the dedicated stack pointer
5071   }
5072 
5073   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
5074                                llvm::Value *Address) const override;
5075 };
5076 
5077 }
5078 
5079 // Return true if the ABI requires Ty to be passed sign- or zero-
5080 // extended to 64 bits.
5081 bool
5082 PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
5083   // Treat an enum type as its underlying type.
5084   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5085     Ty = EnumTy->getDecl()->getIntegerType();
5086 
5087   // Promotable integer types are required to be promoted by the ABI.
5088   if (isPromotableIntegerTypeForABI(Ty))
5089     return true;
5090 
5091   // In addition to the usual promotable integer types, we also need to
5092   // extend all 32-bit types, since the ABI requires promotion to 64 bits.
5093   if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
5094     switch (BT->getKind()) {
5095     case BuiltinType::Int:
5096     case BuiltinType::UInt:
5097       return true;
5098     default:
5099       break;
5100     }
5101 
5102   if (const auto *EIT = Ty->getAs<BitIntType>())
5103     if (EIT->getNumBits() < 64)
5104       return true;
5105 
5106   return false;
5107 }
5108 
5109 /// isAlignedParamType - Determine whether a type requires 16-byte or
5110 /// higher alignment in the parameter area.  Always returns at least 8.
5111 CharUnits PPC64_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const {
5112   // Complex types are passed just like their elements.
5113   if (const ComplexType *CTy = Ty->getAs<ComplexType>())
5114     Ty = CTy->getElementType();
5115 
5116   auto FloatUsesVector = [this](QualType Ty){
5117     return Ty->isRealFloatingType() && &getContext().getFloatTypeSemantics(
5118                                            Ty) == &llvm::APFloat::IEEEquad();
5119   };
5120 
5121   // Only vector types of size 16 bytes need alignment (larger types are
5122   // passed via reference, smaller types are not aligned).
5123   if (Ty->isVectorType()) {
5124     return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16 : 8);
5125   } else if (FloatUsesVector(Ty)) {
5126     // According to ABI document section 'Optional Save Areas': If extended
5127     // precision floating-point values in IEEE BINARY 128 QUADRUPLE PRECISION
5128     // format are supported, map them to a single quadword, quadword aligned.
5129     return CharUnits::fromQuantity(16);
5130   }
5131 
5132   // For single-element float/vector structs, we consider the whole type
5133   // to have the same alignment requirements as its single element.
5134   const Type *AlignAsType = nullptr;
5135   const Type *EltType = isSingleElementStruct(Ty, getContext());
5136   if (EltType) {
5137     const BuiltinType *BT = EltType->getAs<BuiltinType>();
5138     if ((EltType->isVectorType() && getContext().getTypeSize(EltType) == 128) ||
5139         (BT && BT->isFloatingPoint()))
5140       AlignAsType = EltType;
5141   }
5142 
5143   // Likewise for ELFv2 homogeneous aggregates.
5144   const Type *Base = nullptr;
5145   uint64_t Members = 0;
5146   if (!AlignAsType && Kind == ELFv2 &&
5147       isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members))
5148     AlignAsType = Base;
5149 
5150   // With special case aggregates, only vector base types need alignment.
5151   if (AlignAsType) {
5152     bool UsesVector = AlignAsType->isVectorType() ||
5153                       FloatUsesVector(QualType(AlignAsType, 0));
5154     return CharUnits::fromQuantity(UsesVector ? 16 : 8);
5155   }
5156 
5157   // Otherwise, we only need alignment for any aggregate type that
5158   // has an alignment requirement of >= 16 bytes.
5159   if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128) {
5160     return CharUnits::fromQuantity(16);
5161   }
5162 
5163   return CharUnits::fromQuantity(8);
5164 }
5165 
5166 /// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous
5167 /// aggregate.  Base is set to the base element type, and Members is set
5168 /// to the number of base elements.
5169 bool ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base,
5170                                      uint64_t &Members) const {
5171   if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
5172     uint64_t NElements = AT->getSize().getZExtValue();
5173     if (NElements == 0)
5174       return false;
5175     if (!isHomogeneousAggregate(AT->getElementType(), Base, Members))
5176       return false;
5177     Members *= NElements;
5178   } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
5179     const RecordDecl *RD = RT->getDecl();
5180     if (RD->hasFlexibleArrayMember())
5181       return false;
5182 
5183     Members = 0;
5184 
5185     // If this is a C++ record, check the properties of the record such as
5186     // bases and ABI specific restrictions
5187     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
5188       if (!getCXXABI().isPermittedToBeHomogeneousAggregate(CXXRD))
5189         return false;
5190 
5191       for (const auto &I : CXXRD->bases()) {
5192         // Ignore empty records.
5193         if (isEmptyRecord(getContext(), I.getType(), true))
5194           continue;
5195 
5196         uint64_t FldMembers;
5197         if (!isHomogeneousAggregate(I.getType(), Base, FldMembers))
5198           return false;
5199 
5200         Members += FldMembers;
5201       }
5202     }
5203 
5204     for (const auto *FD : RD->fields()) {
5205       // Ignore (non-zero arrays of) empty records.
5206       QualType FT = FD->getType();
5207       while (const ConstantArrayType *AT =
5208              getContext().getAsConstantArrayType(FT)) {
5209         if (AT->getSize().getZExtValue() == 0)
5210           return false;
5211         FT = AT->getElementType();
5212       }
5213       if (isEmptyRecord(getContext(), FT, true))
5214         continue;
5215 
5216       // For compatibility with GCC, ignore empty bitfields in C++ mode.
5217       if (getContext().getLangOpts().CPlusPlus &&
5218           FD->isZeroLengthBitField(getContext()))
5219         continue;
5220 
5221       uint64_t FldMembers;
5222       if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers))
5223         return false;
5224 
5225       Members = (RD->isUnion() ?
5226                  std::max(Members, FldMembers) : Members + FldMembers);
5227     }
5228 
5229     if (!Base)
5230       return false;
5231 
5232     // Ensure there is no padding.
5233     if (getContext().getTypeSize(Base) * Members !=
5234         getContext().getTypeSize(Ty))
5235       return false;
5236   } else {
5237     Members = 1;
5238     if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
5239       Members = 2;
5240       Ty = CT->getElementType();
5241     }
5242 
5243     // Most ABIs only support float, double, and some vector type widths.
5244     if (!isHomogeneousAggregateBaseType(Ty))
5245       return false;
5246 
5247     // The base type must be the same for all members.  Types that
5248     // agree in both total size and mode (float vs. vector) are
5249     // treated as being equivalent here.
5250     const Type *TyPtr = Ty.getTypePtr();
5251     if (!Base) {
5252       Base = TyPtr;
5253       // If it's a non-power-of-2 vector, its size is already a power-of-2,
5254       // so make sure to widen it explicitly.
5255       if (const VectorType *VT = Base->getAs<VectorType>()) {
5256         QualType EltTy = VT->getElementType();
5257         unsigned NumElements =
5258             getContext().getTypeSize(VT) / getContext().getTypeSize(EltTy);
5259         Base = getContext()
5260                    .getVectorType(EltTy, NumElements, VT->getVectorKind())
5261                    .getTypePtr();
5262       }
5263     }
5264 
5265     if (Base->isVectorType() != TyPtr->isVectorType() ||
5266         getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr))
5267       return false;
5268   }
5269   return Members > 0 && isHomogeneousAggregateSmallEnough(Base, Members);
5270 }
5271 
5272 bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
5273   // Homogeneous aggregates for ELFv2 must have base types of float,
5274   // double, long double, or 128-bit vectors.
5275   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
5276     if (BT->getKind() == BuiltinType::Float ||
5277         BT->getKind() == BuiltinType::Double ||
5278         BT->getKind() == BuiltinType::LongDouble ||
5279         BT->getKind() == BuiltinType::Ibm128 ||
5280         (getContext().getTargetInfo().hasFloat128Type() &&
5281          (BT->getKind() == BuiltinType::Float128))) {
5282       if (IsSoftFloatABI)
5283         return false;
5284       return true;
5285     }
5286   }
5287   if (const VectorType *VT = Ty->getAs<VectorType>()) {
5288     if (getContext().getTypeSize(VT) == 128)
5289       return true;
5290   }
5291   return false;
5292 }
5293 
5294 bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateSmallEnough(
5295     const Type *Base, uint64_t Members) const {
5296   // Vector and fp128 types require one register, other floating point types
5297   // require one or two registers depending on their size.
5298   uint32_t NumRegs =
5299       ((getContext().getTargetInfo().hasFloat128Type() &&
5300           Base->isFloat128Type()) ||
5301         Base->isVectorType()) ? 1
5302                               : (getContext().getTypeSize(Base) + 63) / 64;
5303 
5304   // Homogeneous Aggregates may occupy at most 8 registers.
5305   return Members * NumRegs <= 8;
5306 }
5307 
5308 ABIArgInfo
5309 PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
5310   Ty = useFirstFieldIfTransparentUnion(Ty);
5311 
5312   if (Ty->isAnyComplexType())
5313     return ABIArgInfo::getDirect();
5314 
5315   // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes)
5316   // or via reference (larger than 16 bytes).
5317   if (Ty->isVectorType()) {
5318     uint64_t Size = getContext().getTypeSize(Ty);
5319     if (Size > 128)
5320       return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
5321     else if (Size < 128) {
5322       llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
5323       return ABIArgInfo::getDirect(CoerceTy);
5324     }
5325   }
5326 
5327   if (const auto *EIT = Ty->getAs<BitIntType>())
5328     if (EIT->getNumBits() > 128)
5329       return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
5330 
5331   if (isAggregateTypeForABI(Ty)) {
5332     if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
5333       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
5334 
5335     uint64_t ABIAlign = getParamTypeAlignment(Ty).getQuantity();
5336     uint64_t TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity();
5337 
5338     // ELFv2 homogeneous aggregates are passed as array types.
5339     const Type *Base = nullptr;
5340     uint64_t Members = 0;
5341     if (Kind == ELFv2 &&
5342         isHomogeneousAggregate(Ty, Base, Members)) {
5343       llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
5344       llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
5345       return ABIArgInfo::getDirect(CoerceTy);
5346     }
5347 
5348     // If an aggregate may end up fully in registers, we do not
5349     // use the ByVal method, but pass the aggregate as array.
5350     // This is usually beneficial since we avoid forcing the
5351     // back-end to store the argument to memory.
5352     uint64_t Bits = getContext().getTypeSize(Ty);
5353     if (Bits > 0 && Bits <= 8 * GPRBits) {
5354       llvm::Type *CoerceTy;
5355 
5356       // Types up to 8 bytes are passed as integer type (which will be
5357       // properly aligned in the argument save area doubleword).
5358       if (Bits <= GPRBits)
5359         CoerceTy =
5360             llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
5361       // Larger types are passed as arrays, with the base type selected
5362       // according to the required alignment in the save area.
5363       else {
5364         uint64_t RegBits = ABIAlign * 8;
5365         uint64_t NumRegs = llvm::alignTo(Bits, RegBits) / RegBits;
5366         llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits);
5367         CoerceTy = llvm::ArrayType::get(RegTy, NumRegs);
5368       }
5369 
5370       return ABIArgInfo::getDirect(CoerceTy);
5371     }
5372 
5373     // All other aggregates are passed ByVal.
5374     return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
5375                                    /*ByVal=*/true,
5376                                    /*Realign=*/TyAlign > ABIAlign);
5377   }
5378 
5379   return (isPromotableTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
5380                                      : ABIArgInfo::getDirect());
5381 }
5382 
5383 ABIArgInfo
5384 PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
5385   if (RetTy->isVoidType())
5386     return ABIArgInfo::getIgnore();
5387 
5388   if (RetTy->isAnyComplexType())
5389     return ABIArgInfo::getDirect();
5390 
5391   // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes)
5392   // or via reference (larger than 16 bytes).
5393   if (RetTy->isVectorType()) {
5394     uint64_t Size = getContext().getTypeSize(RetTy);
5395     if (Size > 128)
5396       return getNaturalAlignIndirect(RetTy);
5397     else if (Size < 128) {
5398       llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
5399       return ABIArgInfo::getDirect(CoerceTy);
5400     }
5401   }
5402 
5403   if (const auto *EIT = RetTy->getAs<BitIntType>())
5404     if (EIT->getNumBits() > 128)
5405       return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
5406 
5407   if (isAggregateTypeForABI(RetTy)) {
5408     // ELFv2 homogeneous aggregates are returned as array types.
5409     const Type *Base = nullptr;
5410     uint64_t Members = 0;
5411     if (Kind == ELFv2 &&
5412         isHomogeneousAggregate(RetTy, Base, Members)) {
5413       llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
5414       llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
5415       return ABIArgInfo::getDirect(CoerceTy);
5416     }
5417 
5418     // ELFv2 small aggregates are returned in up to two registers.
5419     uint64_t Bits = getContext().getTypeSize(RetTy);
5420     if (Kind == ELFv2 && Bits <= 2 * GPRBits) {
5421       if (Bits == 0)
5422         return ABIArgInfo::getIgnore();
5423 
5424       llvm::Type *CoerceTy;
5425       if (Bits > GPRBits) {
5426         CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits);
5427         CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy);
5428       } else
5429         CoerceTy =
5430             llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
5431       return ABIArgInfo::getDirect(CoerceTy);
5432     }
5433 
5434     // All other aggregates are returned indirectly.
5435     return getNaturalAlignIndirect(RetTy);
5436   }
5437 
5438   return (isPromotableTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
5439                                         : ABIArgInfo::getDirect());
5440 }
5441 
5442 // Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
5443 Address PPC64_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5444                                       QualType Ty) const {
5445   auto TypeInfo = getContext().getTypeInfoInChars(Ty);
5446   TypeInfo.Align = getParamTypeAlignment(Ty);
5447 
5448   CharUnits SlotSize = CharUnits::fromQuantity(8);
5449 
5450   // If we have a complex type and the base type is smaller than 8 bytes,
5451   // the ABI calls for the real and imaginary parts to be right-adjusted
5452   // in separate doublewords.  However, Clang expects us to produce a
5453   // pointer to a structure with the two parts packed tightly.  So generate
5454   // loads of the real and imaginary parts relative to the va_list pointer,
5455   // and store them to a temporary structure.
5456   if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
5457     CharUnits EltSize = TypeInfo.Width / 2;
5458     if (EltSize < SlotSize)
5459       return complexTempStructure(CGF, VAListAddr, Ty, SlotSize, EltSize, CTy);
5460   }
5461 
5462   // Otherwise, just use the general rule.
5463   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
5464                           TypeInfo, SlotSize, /*AllowHigher*/ true);
5465 }
5466 
5467 bool
5468 PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
5469   CodeGen::CodeGenFunction &CGF,
5470   llvm::Value *Address) const {
5471   return PPC_initDwarfEHRegSizeTable(CGF, Address, /*Is64Bit*/ true,
5472                                      /*IsAIX*/ false);
5473 }
5474 
5475 bool
5476 PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
5477                                                 llvm::Value *Address) const {
5478   return PPC_initDwarfEHRegSizeTable(CGF, Address, /*Is64Bit*/ true,
5479                                      /*IsAIX*/ false);
5480 }
5481 
5482 //===----------------------------------------------------------------------===//
5483 // AArch64 ABI Implementation
5484 //===----------------------------------------------------------------------===//
5485 
5486 namespace {
5487 
5488 class AArch64ABIInfo : public SwiftABIInfo {
5489 public:
5490   enum ABIKind {
5491     AAPCS = 0,
5492     DarwinPCS,
5493     Win64
5494   };
5495 
5496 private:
5497   ABIKind Kind;
5498 
5499 public:
5500   AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind)
5501     : SwiftABIInfo(CGT), Kind(Kind) {}
5502 
5503 private:
5504   ABIKind getABIKind() const { return Kind; }
5505   bool isDarwinPCS() const { return Kind == DarwinPCS; }
5506 
5507   ABIArgInfo classifyReturnType(QualType RetTy, bool IsVariadic) const;
5508   ABIArgInfo classifyArgumentType(QualType RetTy, bool IsVariadic,
5509                                   unsigned CallingConvention) const;
5510   ABIArgInfo coerceIllegalVector(QualType Ty) const;
5511   bool isHomogeneousAggregateBaseType(QualType Ty) const override;
5512   bool isHomogeneousAggregateSmallEnough(const Type *Ty,
5513                                          uint64_t Members) const override;
5514 
5515   bool isIllegalVectorType(QualType Ty) const;
5516 
5517   void computeInfo(CGFunctionInfo &FI) const override {
5518     if (!::classifyReturnType(getCXXABI(), FI, *this))
5519       FI.getReturnInfo() =
5520           classifyReturnType(FI.getReturnType(), FI.isVariadic());
5521 
5522     for (auto &it : FI.arguments())
5523       it.info = classifyArgumentType(it.type, FI.isVariadic(),
5524                                      FI.getCallingConvention());
5525   }
5526 
5527   Address EmitDarwinVAArg(Address VAListAddr, QualType Ty,
5528                           CodeGenFunction &CGF) const;
5529 
5530   Address EmitAAPCSVAArg(Address VAListAddr, QualType Ty,
5531                          CodeGenFunction &CGF) const;
5532 
5533   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5534                     QualType Ty) const override {
5535     llvm::Type *BaseTy = CGF.ConvertType(Ty);
5536     if (isa<llvm::ScalableVectorType>(BaseTy))
5537       llvm::report_fatal_error("Passing SVE types to variadic functions is "
5538                                "currently not supported");
5539 
5540     return Kind == Win64 ? EmitMSVAArg(CGF, VAListAddr, Ty)
5541                          : isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF)
5542                                          : EmitAAPCSVAArg(VAListAddr, Ty, CGF);
5543   }
5544 
5545   Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
5546                       QualType Ty) const override;
5547 
5548   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
5549                                     bool asReturnValue) const override {
5550     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
5551   }
5552   bool isSwiftErrorInRegister() const override {
5553     return true;
5554   }
5555 
5556   bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy,
5557                                  unsigned elts) const override;
5558 
5559   bool allowBFloatArgsAndRet() const override {
5560     return getTarget().hasBFloat16Type();
5561   }
5562 };
5563 
5564 class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
5565 public:
5566   AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind)
5567       : TargetCodeGenInfo(std::make_unique<AArch64ABIInfo>(CGT, Kind)) {}
5568 
5569   StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
5570     return "mov\tfp, fp\t\t// marker for objc_retainAutoreleaseReturnValue";
5571   }
5572 
5573   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
5574     return 31;
5575   }
5576 
5577   bool doesReturnSlotInterfereWithArgs() const override { return false; }
5578 
5579   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5580                            CodeGen::CodeGenModule &CGM) const override {
5581     const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
5582     if (!FD)
5583       return;
5584 
5585     const auto *TA = FD->getAttr<TargetAttr>();
5586     if (TA == nullptr)
5587       return;
5588 
5589     ParsedTargetAttr Attr = TA->parse();
5590     if (Attr.BranchProtection.empty())
5591       return;
5592 
5593     TargetInfo::BranchProtectionInfo BPI;
5594     StringRef Error;
5595     (void)CGM.getTarget().validateBranchProtection(
5596         Attr.BranchProtection, Attr.Architecture, BPI, Error);
5597     assert(Error.empty());
5598 
5599     auto *Fn = cast<llvm::Function>(GV);
5600     static const char *SignReturnAddrStr[] = {"none", "non-leaf", "all"};
5601     Fn->addFnAttr("sign-return-address", SignReturnAddrStr[static_cast<int>(BPI.SignReturnAddr)]);
5602 
5603     if (BPI.SignReturnAddr != LangOptions::SignReturnAddressScopeKind::None) {
5604       Fn->addFnAttr("sign-return-address-key",
5605                     BPI.SignKey == LangOptions::SignReturnAddressKeyKind::AKey
5606                         ? "a_key"
5607                         : "b_key");
5608     }
5609 
5610     Fn->addFnAttr("branch-target-enforcement",
5611                   BPI.BranchTargetEnforcement ? "true" : "false");
5612   }
5613 
5614   bool isScalarizableAsmOperand(CodeGen::CodeGenFunction &CGF,
5615                                 llvm::Type *Ty) const override {
5616     if (CGF.getTarget().hasFeature("ls64")) {
5617       auto *ST = dyn_cast<llvm::StructType>(Ty);
5618       if (ST && ST->getNumElements() == 1) {
5619         auto *AT = dyn_cast<llvm::ArrayType>(ST->getElementType(0));
5620         if (AT && AT->getNumElements() == 8 &&
5621             AT->getElementType()->isIntegerTy(64))
5622           return true;
5623       }
5624     }
5625     return TargetCodeGenInfo::isScalarizableAsmOperand(CGF, Ty);
5626   }
5627 };
5628 
5629 class WindowsAArch64TargetCodeGenInfo : public AArch64TargetCodeGenInfo {
5630 public:
5631   WindowsAArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind K)
5632       : AArch64TargetCodeGenInfo(CGT, K) {}
5633 
5634   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5635                            CodeGen::CodeGenModule &CGM) const override;
5636 
5637   void getDependentLibraryOption(llvm::StringRef Lib,
5638                                  llvm::SmallString<24> &Opt) const override {
5639     Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib);
5640   }
5641 
5642   void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value,
5643                                llvm::SmallString<32> &Opt) const override {
5644     Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
5645   }
5646 };
5647 
5648 void WindowsAArch64TargetCodeGenInfo::setTargetAttributes(
5649     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
5650   AArch64TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
5651   if (GV->isDeclaration())
5652     return;
5653   addStackProbeTargetAttributes(D, GV, CGM);
5654 }
5655 }
5656 
5657 ABIArgInfo AArch64ABIInfo::coerceIllegalVector(QualType Ty) const {
5658   assert(Ty->isVectorType() && "expected vector type!");
5659 
5660   const auto *VT = Ty->castAs<VectorType>();
5661   if (VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector) {
5662     assert(VT->getElementType()->isBuiltinType() && "expected builtin type!");
5663     assert(VT->getElementType()->castAs<BuiltinType>()->getKind() ==
5664                BuiltinType::UChar &&
5665            "unexpected builtin type for SVE predicate!");
5666     return ABIArgInfo::getDirect(llvm::ScalableVectorType::get(
5667         llvm::Type::getInt1Ty(getVMContext()), 16));
5668   }
5669 
5670   if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector) {
5671     assert(VT->getElementType()->isBuiltinType() && "expected builtin type!");
5672 
5673     const auto *BT = VT->getElementType()->castAs<BuiltinType>();
5674     llvm::ScalableVectorType *ResType = nullptr;
5675     switch (BT->getKind()) {
5676     default:
5677       llvm_unreachable("unexpected builtin type for SVE vector!");
5678     case BuiltinType::SChar:
5679     case BuiltinType::UChar:
5680       ResType = llvm::ScalableVectorType::get(
5681           llvm::Type::getInt8Ty(getVMContext()), 16);
5682       break;
5683     case BuiltinType::Short:
5684     case BuiltinType::UShort:
5685       ResType = llvm::ScalableVectorType::get(
5686           llvm::Type::getInt16Ty(getVMContext()), 8);
5687       break;
5688     case BuiltinType::Int:
5689     case BuiltinType::UInt:
5690       ResType = llvm::ScalableVectorType::get(
5691           llvm::Type::getInt32Ty(getVMContext()), 4);
5692       break;
5693     case BuiltinType::Long:
5694     case BuiltinType::ULong:
5695       ResType = llvm::ScalableVectorType::get(
5696           llvm::Type::getInt64Ty(getVMContext()), 2);
5697       break;
5698     case BuiltinType::Half:
5699       ResType = llvm::ScalableVectorType::get(
5700           llvm::Type::getHalfTy(getVMContext()), 8);
5701       break;
5702     case BuiltinType::Float:
5703       ResType = llvm::ScalableVectorType::get(
5704           llvm::Type::getFloatTy(getVMContext()), 4);
5705       break;
5706     case BuiltinType::Double:
5707       ResType = llvm::ScalableVectorType::get(
5708           llvm::Type::getDoubleTy(getVMContext()), 2);
5709       break;
5710     case BuiltinType::BFloat16:
5711       ResType = llvm::ScalableVectorType::get(
5712           llvm::Type::getBFloatTy(getVMContext()), 8);
5713       break;
5714     }
5715     return ABIArgInfo::getDirect(ResType);
5716   }
5717 
5718   uint64_t Size = getContext().getTypeSize(Ty);
5719   // Android promotes <2 x i8> to i16, not i32
5720   if (isAndroid() && (Size <= 16)) {
5721     llvm::Type *ResType = llvm::Type::getInt16Ty(getVMContext());
5722     return ABIArgInfo::getDirect(ResType);
5723   }
5724   if (Size <= 32) {
5725     llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext());
5726     return ABIArgInfo::getDirect(ResType);
5727   }
5728   if (Size == 64) {
5729     auto *ResType =
5730         llvm::FixedVectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2);
5731     return ABIArgInfo::getDirect(ResType);
5732   }
5733   if (Size == 128) {
5734     auto *ResType =
5735         llvm::FixedVectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4);
5736     return ABIArgInfo::getDirect(ResType);
5737   }
5738   return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
5739 }
5740 
5741 ABIArgInfo
5742 AArch64ABIInfo::classifyArgumentType(QualType Ty, bool IsVariadic,
5743                                      unsigned CallingConvention) const {
5744   Ty = useFirstFieldIfTransparentUnion(Ty);
5745 
5746   // Handle illegal vector types here.
5747   if (isIllegalVectorType(Ty))
5748     return coerceIllegalVector(Ty);
5749 
5750   if (!isAggregateTypeForABI(Ty)) {
5751     // Treat an enum type as its underlying type.
5752     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5753       Ty = EnumTy->getDecl()->getIntegerType();
5754 
5755     if (const auto *EIT = Ty->getAs<BitIntType>())
5756       if (EIT->getNumBits() > 128)
5757         return getNaturalAlignIndirect(Ty);
5758 
5759     return (isPromotableIntegerTypeForABI(Ty) && isDarwinPCS()
5760                 ? ABIArgInfo::getExtend(Ty)
5761                 : ABIArgInfo::getDirect());
5762   }
5763 
5764   // Structures with either a non-trivial destructor or a non-trivial
5765   // copy constructor are always indirect.
5766   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
5767     return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA ==
5768                                      CGCXXABI::RAA_DirectInMemory);
5769   }
5770 
5771   // Empty records are always ignored on Darwin, but actually passed in C++ mode
5772   // elsewhere for GNU compatibility.
5773   uint64_t Size = getContext().getTypeSize(Ty);
5774   bool IsEmpty = isEmptyRecord(getContext(), Ty, true);
5775   if (IsEmpty || Size == 0) {
5776     if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS())
5777       return ABIArgInfo::getIgnore();
5778 
5779     // GNU C mode. The only argument that gets ignored is an empty one with size
5780     // 0.
5781     if (IsEmpty && Size == 0)
5782       return ABIArgInfo::getIgnore();
5783     return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
5784   }
5785 
5786   // Homogeneous Floating-point Aggregates (HFAs) need to be expanded.
5787   const Type *Base = nullptr;
5788   uint64_t Members = 0;
5789   bool IsWin64 = Kind == Win64 || CallingConvention == llvm::CallingConv::Win64;
5790   bool IsWinVariadic = IsWin64 && IsVariadic;
5791   // In variadic functions on Windows, all composite types are treated alike,
5792   // no special handling of HFAs/HVAs.
5793   if (!IsWinVariadic && isHomogeneousAggregate(Ty, Base, Members)) {
5794     if (Kind != AArch64ABIInfo::AAPCS)
5795       return ABIArgInfo::getDirect(
5796           llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members));
5797 
5798     // For alignment adjusted HFAs, cap the argument alignment to 16, leave it
5799     // default otherwise.
5800     unsigned Align =
5801         getContext().getTypeUnadjustedAlignInChars(Ty).getQuantity();
5802     unsigned BaseAlign = getContext().getTypeAlignInChars(Base).getQuantity();
5803     Align = (Align > BaseAlign && Align >= 16) ? 16 : 0;
5804     return ABIArgInfo::getDirect(
5805         llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members), 0,
5806         nullptr, true, Align);
5807   }
5808 
5809   // Aggregates <= 16 bytes are passed directly in registers or on the stack.
5810   if (Size <= 128) {
5811     // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
5812     // same size and alignment.
5813     if (getTarget().isRenderScriptTarget()) {
5814       return coerceToIntArray(Ty, getContext(), getVMContext());
5815     }
5816     unsigned Alignment;
5817     if (Kind == AArch64ABIInfo::AAPCS) {
5818       Alignment = getContext().getTypeUnadjustedAlign(Ty);
5819       Alignment = Alignment < 128 ? 64 : 128;
5820     } else {
5821       Alignment = std::max(getContext().getTypeAlign(Ty),
5822                            (unsigned)getTarget().getPointerWidth(0));
5823     }
5824     Size = llvm::alignTo(Size, Alignment);
5825 
5826     // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
5827     // For aggregates with 16-byte alignment, we use i128.
5828     llvm::Type *BaseTy = llvm::Type::getIntNTy(getVMContext(), Alignment);
5829     return ABIArgInfo::getDirect(
5830         Size == Alignment ? BaseTy
5831                           : llvm::ArrayType::get(BaseTy, Size / Alignment));
5832   }
5833 
5834   return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
5835 }
5836 
5837 ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy,
5838                                               bool IsVariadic) const {
5839   if (RetTy->isVoidType())
5840     return ABIArgInfo::getIgnore();
5841 
5842   if (const auto *VT = RetTy->getAs<VectorType>()) {
5843     if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector ||
5844         VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector)
5845       return coerceIllegalVector(RetTy);
5846   }
5847 
5848   // Large vector types should be returned via memory.
5849   if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
5850     return getNaturalAlignIndirect(RetTy);
5851 
5852   if (!isAggregateTypeForABI(RetTy)) {
5853     // Treat an enum type as its underlying type.
5854     if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5855       RetTy = EnumTy->getDecl()->getIntegerType();
5856 
5857     if (const auto *EIT = RetTy->getAs<BitIntType>())
5858       if (EIT->getNumBits() > 128)
5859         return getNaturalAlignIndirect(RetTy);
5860 
5861     return (isPromotableIntegerTypeForABI(RetTy) && isDarwinPCS()
5862                 ? ABIArgInfo::getExtend(RetTy)
5863                 : ABIArgInfo::getDirect());
5864   }
5865 
5866   uint64_t Size = getContext().getTypeSize(RetTy);
5867   if (isEmptyRecord(getContext(), RetTy, true) || Size == 0)
5868     return ABIArgInfo::getIgnore();
5869 
5870   const Type *Base = nullptr;
5871   uint64_t Members = 0;
5872   if (isHomogeneousAggregate(RetTy, Base, Members) &&
5873       !(getTarget().getTriple().getArch() == llvm::Triple::aarch64_32 &&
5874         IsVariadic))
5875     // Homogeneous Floating-point Aggregates (HFAs) are returned directly.
5876     return ABIArgInfo::getDirect();
5877 
5878   // Aggregates <= 16 bytes are returned directly in registers or on the stack.
5879   if (Size <= 128) {
5880     // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
5881     // same size and alignment.
5882     if (getTarget().isRenderScriptTarget()) {
5883       return coerceToIntArray(RetTy, getContext(), getVMContext());
5884     }
5885 
5886     if (Size <= 64 && getDataLayout().isLittleEndian()) {
5887       // Composite types are returned in lower bits of a 64-bit register for LE,
5888       // and in higher bits for BE. However, integer types are always returned
5889       // in lower bits for both LE and BE, and they are not rounded up to
5890       // 64-bits. We can skip rounding up of composite types for LE, but not for
5891       // BE, otherwise composite types will be indistinguishable from integer
5892       // types.
5893       return ABIArgInfo::getDirect(
5894           llvm::IntegerType::get(getVMContext(), Size));
5895     }
5896 
5897     unsigned Alignment = getContext().getTypeAlign(RetTy);
5898     Size = llvm::alignTo(Size, 64); // round up to multiple of 8 bytes
5899 
5900     // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
5901     // For aggregates with 16-byte alignment, we use i128.
5902     if (Alignment < 128 && Size == 128) {
5903       llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
5904       return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
5905     }
5906     return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
5907   }
5908 
5909   return getNaturalAlignIndirect(RetTy);
5910 }
5911 
5912 /// isIllegalVectorType - check whether the vector type is legal for AArch64.
5913 bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const {
5914   if (const VectorType *VT = Ty->getAs<VectorType>()) {
5915     // Check whether VT is a fixed-length SVE vector. These types are
5916     // represented as scalable vectors in function args/return and must be
5917     // coerced from fixed vectors.
5918     if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector ||
5919         VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector)
5920       return true;
5921 
5922     // Check whether VT is legal.
5923     unsigned NumElements = VT->getNumElements();
5924     uint64_t Size = getContext().getTypeSize(VT);
5925     // NumElements should be power of 2.
5926     if (!llvm::isPowerOf2_32(NumElements))
5927       return true;
5928 
5929     // arm64_32 has to be compatible with the ARM logic here, which allows huge
5930     // vectors for some reason.
5931     llvm::Triple Triple = getTarget().getTriple();
5932     if (Triple.getArch() == llvm::Triple::aarch64_32 &&
5933         Triple.isOSBinFormatMachO())
5934       return Size <= 32;
5935 
5936     return Size != 64 && (Size != 128 || NumElements == 1);
5937   }
5938   return false;
5939 }
5940 
5941 bool AArch64ABIInfo::isLegalVectorTypeForSwift(CharUnits totalSize,
5942                                                llvm::Type *eltTy,
5943                                                unsigned elts) const {
5944   if (!llvm::isPowerOf2_32(elts))
5945     return false;
5946   if (totalSize.getQuantity() != 8 &&
5947       (totalSize.getQuantity() != 16 || elts == 1))
5948     return false;
5949   return true;
5950 }
5951 
5952 bool AArch64ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
5953   // Homogeneous aggregates for AAPCS64 must have base types of a floating
5954   // point type or a short-vector type. This is the same as the 32-bit ABI,
5955   // but with the difference that any floating-point type is allowed,
5956   // including __fp16.
5957   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
5958     if (BT->isFloatingPoint())
5959       return true;
5960   } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
5961     unsigned VecSize = getContext().getTypeSize(VT);
5962     if (VecSize == 64 || VecSize == 128)
5963       return true;
5964   }
5965   return false;
5966 }
5967 
5968 bool AArch64ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
5969                                                        uint64_t Members) const {
5970   return Members <= 4;
5971 }
5972 
5973 Address AArch64ABIInfo::EmitAAPCSVAArg(Address VAListAddr, QualType Ty,
5974                                        CodeGenFunction &CGF) const {
5975   ABIArgInfo AI = classifyArgumentType(Ty, /*IsVariadic=*/true,
5976                                        CGF.CurFnInfo->getCallingConvention());
5977   bool IsIndirect = AI.isIndirect();
5978 
5979   llvm::Type *BaseTy = CGF.ConvertType(Ty);
5980   if (IsIndirect)
5981     BaseTy = llvm::PointerType::getUnqual(BaseTy);
5982   else if (AI.getCoerceToType())
5983     BaseTy = AI.getCoerceToType();
5984 
5985   unsigned NumRegs = 1;
5986   if (llvm::ArrayType *ArrTy = dyn_cast<llvm::ArrayType>(BaseTy)) {
5987     BaseTy = ArrTy->getElementType();
5988     NumRegs = ArrTy->getNumElements();
5989   }
5990   bool IsFPR = BaseTy->isFloatingPointTy() || BaseTy->isVectorTy();
5991 
5992   // The AArch64 va_list type and handling is specified in the Procedure Call
5993   // Standard, section B.4:
5994   //
5995   // struct {
5996   //   void *__stack;
5997   //   void *__gr_top;
5998   //   void *__vr_top;
5999   //   int __gr_offs;
6000   //   int __vr_offs;
6001   // };
6002 
6003   llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
6004   llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
6005   llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
6006   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
6007 
6008   CharUnits TySize = getContext().getTypeSizeInChars(Ty);
6009   CharUnits TyAlign = getContext().getTypeUnadjustedAlignInChars(Ty);
6010 
6011   Address reg_offs_p = Address::invalid();
6012   llvm::Value *reg_offs = nullptr;
6013   int reg_top_index;
6014   int RegSize = IsIndirect ? 8 : TySize.getQuantity();
6015   if (!IsFPR) {
6016     // 3 is the field number of __gr_offs
6017     reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 3, "gr_offs_p");
6018     reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
6019     reg_top_index = 1; // field number for __gr_top
6020     RegSize = llvm::alignTo(RegSize, 8);
6021   } else {
6022     // 4 is the field number of __vr_offs.
6023     reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 4, "vr_offs_p");
6024     reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
6025     reg_top_index = 2; // field number for __vr_top
6026     RegSize = 16 * NumRegs;
6027   }
6028 
6029   //=======================================
6030   // Find out where argument was passed
6031   //=======================================
6032 
6033   // If reg_offs >= 0 we're already using the stack for this type of
6034   // argument. We don't want to keep updating reg_offs (in case it overflows,
6035   // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
6036   // whatever they get).
6037   llvm::Value *UsingStack = nullptr;
6038   UsingStack = CGF.Builder.CreateICmpSGE(
6039       reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0));
6040 
6041   CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
6042 
6043   // Otherwise, at least some kind of argument could go in these registers, the
6044   // question is whether this particular type is too big.
6045   CGF.EmitBlock(MaybeRegBlock);
6046 
6047   // Integer arguments may need to correct register alignment (for example a
6048   // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
6049   // align __gr_offs to calculate the potential address.
6050   if (!IsFPR && !IsIndirect && TyAlign.getQuantity() > 8) {
6051     int Align = TyAlign.getQuantity();
6052 
6053     reg_offs = CGF.Builder.CreateAdd(
6054         reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
6055         "align_regoffs");
6056     reg_offs = CGF.Builder.CreateAnd(
6057         reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align),
6058         "aligned_regoffs");
6059   }
6060 
6061   // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
6062   // The fact that this is done unconditionally reflects the fact that
6063   // allocating an argument to the stack also uses up all the remaining
6064   // registers of the appropriate kind.
6065   llvm::Value *NewOffset = nullptr;
6066   NewOffset = CGF.Builder.CreateAdd(
6067       reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs");
6068   CGF.Builder.CreateStore(NewOffset, reg_offs_p);
6069 
6070   // Now we're in a position to decide whether this argument really was in
6071   // registers or not.
6072   llvm::Value *InRegs = nullptr;
6073   InRegs = CGF.Builder.CreateICmpSLE(
6074       NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg");
6075 
6076   CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
6077 
6078   //=======================================
6079   // Argument was in registers
6080   //=======================================
6081 
6082   // Now we emit the code for if the argument was originally passed in
6083   // registers. First start the appropriate block:
6084   CGF.EmitBlock(InRegBlock);
6085 
6086   llvm::Value *reg_top = nullptr;
6087   Address reg_top_p =
6088       CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index, "reg_top_p");
6089   reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
6090   Address BaseAddr(CGF.Builder.CreateInBoundsGEP(CGF.Int8Ty, reg_top, reg_offs),
6091                    CGF.Int8Ty, CharUnits::fromQuantity(IsFPR ? 16 : 8));
6092   Address RegAddr = Address::invalid();
6093   llvm::Type *MemTy = CGF.ConvertTypeForMem(Ty), *ElementTy = MemTy;
6094 
6095   if (IsIndirect) {
6096     // If it's been passed indirectly (actually a struct), whatever we find from
6097     // stored registers or on the stack will actually be a struct **.
6098     MemTy = llvm::PointerType::getUnqual(MemTy);
6099   }
6100 
6101   const Type *Base = nullptr;
6102   uint64_t NumMembers = 0;
6103   bool IsHFA = isHomogeneousAggregate(Ty, Base, NumMembers);
6104   if (IsHFA && NumMembers > 1) {
6105     // Homogeneous aggregates passed in registers will have their elements split
6106     // and stored 16-bytes apart regardless of size (they're notionally in qN,
6107     // qN+1, ...). We reload and store into a temporary local variable
6108     // contiguously.
6109     assert(!IsIndirect && "Homogeneous aggregates should be passed directly");
6110     auto BaseTyInfo = getContext().getTypeInfoInChars(QualType(Base, 0));
6111     llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
6112     llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
6113     Address Tmp = CGF.CreateTempAlloca(HFATy,
6114                                        std::max(TyAlign, BaseTyInfo.Align));
6115 
6116     // On big-endian platforms, the value will be right-aligned in its slot.
6117     int Offset = 0;
6118     if (CGF.CGM.getDataLayout().isBigEndian() &&
6119         BaseTyInfo.Width.getQuantity() < 16)
6120       Offset = 16 - BaseTyInfo.Width.getQuantity();
6121 
6122     for (unsigned i = 0; i < NumMembers; ++i) {
6123       CharUnits BaseOffset = CharUnits::fromQuantity(16 * i + Offset);
6124       Address LoadAddr =
6125         CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, BaseOffset);
6126       LoadAddr = CGF.Builder.CreateElementBitCast(LoadAddr, BaseTy);
6127 
6128       Address StoreAddr = CGF.Builder.CreateConstArrayGEP(Tmp, i);
6129 
6130       llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
6131       CGF.Builder.CreateStore(Elem, StoreAddr);
6132     }
6133 
6134     RegAddr = CGF.Builder.CreateElementBitCast(Tmp, MemTy);
6135   } else {
6136     // Otherwise the object is contiguous in memory.
6137 
6138     // It might be right-aligned in its slot.
6139     CharUnits SlotSize = BaseAddr.getAlignment();
6140     if (CGF.CGM.getDataLayout().isBigEndian() && !IsIndirect &&
6141         (IsHFA || !isAggregateTypeForABI(Ty)) &&
6142         TySize < SlotSize) {
6143       CharUnits Offset = SlotSize - TySize;
6144       BaseAddr = CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, Offset);
6145     }
6146 
6147     RegAddr = CGF.Builder.CreateElementBitCast(BaseAddr, MemTy);
6148   }
6149 
6150   CGF.EmitBranch(ContBlock);
6151 
6152   //=======================================
6153   // Argument was on the stack
6154   //=======================================
6155   CGF.EmitBlock(OnStackBlock);
6156 
6157   Address stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "stack_p");
6158   llvm::Value *OnStackPtr = CGF.Builder.CreateLoad(stack_p, "stack");
6159 
6160   // Again, stack arguments may need realignment. In this case both integer and
6161   // floating-point ones might be affected.
6162   if (!IsIndirect && TyAlign.getQuantity() > 8) {
6163     int Align = TyAlign.getQuantity();
6164 
6165     OnStackPtr = CGF.Builder.CreatePtrToInt(OnStackPtr, CGF.Int64Ty);
6166 
6167     OnStackPtr = CGF.Builder.CreateAdd(
6168         OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
6169         "align_stack");
6170     OnStackPtr = CGF.Builder.CreateAnd(
6171         OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, -Align),
6172         "align_stack");
6173 
6174     OnStackPtr = CGF.Builder.CreateIntToPtr(OnStackPtr, CGF.Int8PtrTy);
6175   }
6176   Address OnStackAddr = Address(OnStackPtr, CGF.Int8Ty,
6177                                 std::max(CharUnits::fromQuantity(8), TyAlign));
6178 
6179   // All stack slots are multiples of 8 bytes.
6180   CharUnits StackSlotSize = CharUnits::fromQuantity(8);
6181   CharUnits StackSize;
6182   if (IsIndirect)
6183     StackSize = StackSlotSize;
6184   else
6185     StackSize = TySize.alignTo(StackSlotSize);
6186 
6187   llvm::Value *StackSizeC = CGF.Builder.getSize(StackSize);
6188   llvm::Value *NewStack = CGF.Builder.CreateInBoundsGEP(
6189       CGF.Int8Ty, OnStackPtr, StackSizeC, "new_stack");
6190 
6191   // Write the new value of __stack for the next call to va_arg
6192   CGF.Builder.CreateStore(NewStack, stack_p);
6193 
6194   if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) &&
6195       TySize < StackSlotSize) {
6196     CharUnits Offset = StackSlotSize - TySize;
6197     OnStackAddr = CGF.Builder.CreateConstInBoundsByteGEP(OnStackAddr, Offset);
6198   }
6199 
6200   OnStackAddr = CGF.Builder.CreateElementBitCast(OnStackAddr, MemTy);
6201 
6202   CGF.EmitBranch(ContBlock);
6203 
6204   //=======================================
6205   // Tidy up
6206   //=======================================
6207   CGF.EmitBlock(ContBlock);
6208 
6209   Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, OnStackAddr,
6210                                  OnStackBlock, "vaargs.addr");
6211 
6212   if (IsIndirect)
6213     return Address(CGF.Builder.CreateLoad(ResAddr, "vaarg.addr"), ElementTy,
6214                    TyAlign);
6215 
6216   return ResAddr;
6217 }
6218 
6219 Address AArch64ABIInfo::EmitDarwinVAArg(Address VAListAddr, QualType Ty,
6220                                         CodeGenFunction &CGF) const {
6221   // The backend's lowering doesn't support va_arg for aggregates or
6222   // illegal vector types.  Lower VAArg here for these cases and use
6223   // the LLVM va_arg instruction for everything else.
6224   if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty))
6225     return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
6226 
6227   uint64_t PointerSize = getTarget().getPointerWidth(0) / 8;
6228   CharUnits SlotSize = CharUnits::fromQuantity(PointerSize);
6229 
6230   // Empty records are ignored for parameter passing purposes.
6231   if (isEmptyRecord(getContext(), Ty, true)) {
6232     Address Addr = Address(CGF.Builder.CreateLoad(VAListAddr, "ap.cur"),
6233                            getVAListElementType(CGF), SlotSize);
6234     Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
6235     return Addr;
6236   }
6237 
6238   // The size of the actual thing passed, which might end up just
6239   // being a pointer for indirect types.
6240   auto TyInfo = getContext().getTypeInfoInChars(Ty);
6241 
6242   // Arguments bigger than 16 bytes which aren't homogeneous
6243   // aggregates should be passed indirectly.
6244   bool IsIndirect = false;
6245   if (TyInfo.Width.getQuantity() > 16) {
6246     const Type *Base = nullptr;
6247     uint64_t Members = 0;
6248     IsIndirect = !isHomogeneousAggregate(Ty, Base, Members);
6249   }
6250 
6251   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
6252                           TyInfo, SlotSize, /*AllowHigherAlign*/ true);
6253 }
6254 
6255 Address AArch64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
6256                                     QualType Ty) const {
6257   bool IsIndirect = false;
6258 
6259   // Composites larger than 16 bytes are passed by reference.
6260   if (isAggregateTypeForABI(Ty) && getContext().getTypeSize(Ty) > 128)
6261     IsIndirect = true;
6262 
6263   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
6264                           CGF.getContext().getTypeInfoInChars(Ty),
6265                           CharUnits::fromQuantity(8),
6266                           /*allowHigherAlign*/ false);
6267 }
6268 
6269 //===----------------------------------------------------------------------===//
6270 // ARM ABI Implementation
6271 //===----------------------------------------------------------------------===//
6272 
6273 namespace {
6274 
6275 class ARMABIInfo : public SwiftABIInfo {
6276 public:
6277   enum ABIKind {
6278     APCS = 0,
6279     AAPCS = 1,
6280     AAPCS_VFP = 2,
6281     AAPCS16_VFP = 3,
6282   };
6283 
6284 private:
6285   ABIKind Kind;
6286   bool IsFloatABISoftFP;
6287 
6288 public:
6289   ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind)
6290       : SwiftABIInfo(CGT), Kind(_Kind) {
6291     setCCs();
6292     IsFloatABISoftFP = CGT.getCodeGenOpts().FloatABI == "softfp" ||
6293         CGT.getCodeGenOpts().FloatABI == ""; // default
6294   }
6295 
6296   bool isEABI() const {
6297     switch (getTarget().getTriple().getEnvironment()) {
6298     case llvm::Triple::Android:
6299     case llvm::Triple::EABI:
6300     case llvm::Triple::EABIHF:
6301     case llvm::Triple::GNUEABI:
6302     case llvm::Triple::GNUEABIHF:
6303     case llvm::Triple::MuslEABI:
6304     case llvm::Triple::MuslEABIHF:
6305       return true;
6306     default:
6307       return false;
6308     }
6309   }
6310 
6311   bool isEABIHF() const {
6312     switch (getTarget().getTriple().getEnvironment()) {
6313     case llvm::Triple::EABIHF:
6314     case llvm::Triple::GNUEABIHF:
6315     case llvm::Triple::MuslEABIHF:
6316       return true;
6317     default:
6318       return false;
6319     }
6320   }
6321 
6322   ABIKind getABIKind() const { return Kind; }
6323 
6324   bool allowBFloatArgsAndRet() const override {
6325     return !IsFloatABISoftFP && getTarget().hasBFloat16Type();
6326   }
6327 
6328 private:
6329   ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic,
6330                                 unsigned functionCallConv) const;
6331   ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic,
6332                                   unsigned functionCallConv) const;
6333   ABIArgInfo classifyHomogeneousAggregate(QualType Ty, const Type *Base,
6334                                           uint64_t Members) const;
6335   ABIArgInfo coerceIllegalVector(QualType Ty) const;
6336   bool isIllegalVectorType(QualType Ty) const;
6337   bool containsAnyFP16Vectors(QualType Ty) const;
6338 
6339   bool isHomogeneousAggregateBaseType(QualType Ty) const override;
6340   bool isHomogeneousAggregateSmallEnough(const Type *Ty,
6341                                          uint64_t Members) const override;
6342 
6343   bool isEffectivelyAAPCS_VFP(unsigned callConvention, bool acceptHalf) const;
6344 
6345   void computeInfo(CGFunctionInfo &FI) const override;
6346 
6347   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6348                     QualType Ty) const override;
6349 
6350   llvm::CallingConv::ID getLLVMDefaultCC() const;
6351   llvm::CallingConv::ID getABIDefaultCC() const;
6352   void setCCs();
6353 
6354   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
6355                                     bool asReturnValue) const override {
6356     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
6357   }
6358   bool isSwiftErrorInRegister() const override {
6359     return true;
6360   }
6361   bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy,
6362                                  unsigned elts) const override;
6363 };
6364 
6365 class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
6366 public:
6367   ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
6368       : TargetCodeGenInfo(std::make_unique<ARMABIInfo>(CGT, K)) {}
6369 
6370   const ARMABIInfo &getABIInfo() const {
6371     return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
6372   }
6373 
6374   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
6375     return 13;
6376   }
6377 
6378   StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
6379     return "mov\tr7, r7\t\t// marker for objc_retainAutoreleaseReturnValue";
6380   }
6381 
6382   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
6383                                llvm::Value *Address) const override {
6384     llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
6385 
6386     // 0-15 are the 16 integer registers.
6387     AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
6388     return false;
6389   }
6390 
6391   unsigned getSizeOfUnwindException() const override {
6392     if (getABIInfo().isEABI()) return 88;
6393     return TargetCodeGenInfo::getSizeOfUnwindException();
6394   }
6395 
6396   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
6397                            CodeGen::CodeGenModule &CGM) const override {
6398     if (GV->isDeclaration())
6399       return;
6400     const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
6401     if (!FD)
6402       return;
6403     auto *Fn = cast<llvm::Function>(GV);
6404 
6405     if (const auto *TA = FD->getAttr<TargetAttr>()) {
6406       ParsedTargetAttr Attr = TA->parse();
6407       if (!Attr.BranchProtection.empty()) {
6408         TargetInfo::BranchProtectionInfo BPI;
6409         StringRef DiagMsg;
6410         StringRef Arch = Attr.Architecture.empty()
6411                              ? CGM.getTarget().getTargetOpts().CPU
6412                              : Attr.Architecture;
6413         if (!CGM.getTarget().validateBranchProtection(Attr.BranchProtection,
6414                                                       Arch, BPI, DiagMsg)) {
6415           CGM.getDiags().Report(
6416               D->getLocation(),
6417               diag::warn_target_unsupported_branch_protection_attribute)
6418               << Arch;
6419         } else {
6420           static const char *SignReturnAddrStr[] = {"none", "non-leaf", "all"};
6421           assert(static_cast<unsigned>(BPI.SignReturnAddr) <= 2 &&
6422                  "Unexpected SignReturnAddressScopeKind");
6423           Fn->addFnAttr(
6424               "sign-return-address",
6425               SignReturnAddrStr[static_cast<int>(BPI.SignReturnAddr)]);
6426 
6427           Fn->addFnAttr("branch-target-enforcement",
6428                         BPI.BranchTargetEnforcement ? "true" : "false");
6429         }
6430       } else if (CGM.getLangOpts().BranchTargetEnforcement ||
6431                  CGM.getLangOpts().hasSignReturnAddress()) {
6432         // If the Branch Protection attribute is missing, validate the target
6433         // Architecture attribute against Branch Protection command line
6434         // settings.
6435         if (!CGM.getTarget().isBranchProtectionSupportedArch(Attr.Architecture))
6436           CGM.getDiags().Report(
6437               D->getLocation(),
6438               diag::warn_target_unsupported_branch_protection_attribute)
6439               << Attr.Architecture;
6440       }
6441     }
6442 
6443     const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
6444     if (!Attr)
6445       return;
6446 
6447     const char *Kind;
6448     switch (Attr->getInterrupt()) {
6449     case ARMInterruptAttr::Generic: Kind = ""; break;
6450     case ARMInterruptAttr::IRQ:     Kind = "IRQ"; break;
6451     case ARMInterruptAttr::FIQ:     Kind = "FIQ"; break;
6452     case ARMInterruptAttr::SWI:     Kind = "SWI"; break;
6453     case ARMInterruptAttr::ABORT:   Kind = "ABORT"; break;
6454     case ARMInterruptAttr::UNDEF:   Kind = "UNDEF"; break;
6455     }
6456 
6457     Fn->addFnAttr("interrupt", Kind);
6458 
6459     ARMABIInfo::ABIKind ABI = cast<ARMABIInfo>(getABIInfo()).getABIKind();
6460     if (ABI == ARMABIInfo::APCS)
6461       return;
6462 
6463     // AAPCS guarantees that sp will be 8-byte aligned on any public interface,
6464     // however this is not necessarily true on taking any interrupt. Instruct
6465     // the backend to perform a realignment as part of the function prologue.
6466     llvm::AttrBuilder B(Fn->getContext());
6467     B.addStackAlignmentAttr(8);
6468     Fn->addFnAttrs(B);
6469   }
6470 };
6471 
6472 class WindowsARMTargetCodeGenInfo : public ARMTargetCodeGenInfo {
6473 public:
6474   WindowsARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
6475       : ARMTargetCodeGenInfo(CGT, K) {}
6476 
6477   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
6478                            CodeGen::CodeGenModule &CGM) const override;
6479 
6480   void getDependentLibraryOption(llvm::StringRef Lib,
6481                                  llvm::SmallString<24> &Opt) const override {
6482     Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib);
6483   }
6484 
6485   void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value,
6486                                llvm::SmallString<32> &Opt) const override {
6487     Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
6488   }
6489 };
6490 
6491 void WindowsARMTargetCodeGenInfo::setTargetAttributes(
6492     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
6493   ARMTargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
6494   if (GV->isDeclaration())
6495     return;
6496   addStackProbeTargetAttributes(D, GV, CGM);
6497 }
6498 }
6499 
6500 void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
6501   if (!::classifyReturnType(getCXXABI(), FI, *this))
6502     FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), FI.isVariadic(),
6503                                             FI.getCallingConvention());
6504 
6505   for (auto &I : FI.arguments())
6506     I.info = classifyArgumentType(I.type, FI.isVariadic(),
6507                                   FI.getCallingConvention());
6508 
6509 
6510   // Always honor user-specified calling convention.
6511   if (FI.getCallingConvention() != llvm::CallingConv::C)
6512     return;
6513 
6514   llvm::CallingConv::ID cc = getRuntimeCC();
6515   if (cc != llvm::CallingConv::C)
6516     FI.setEffectiveCallingConvention(cc);
6517 }
6518 
6519 /// Return the default calling convention that LLVM will use.
6520 llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
6521   // The default calling convention that LLVM will infer.
6522   if (isEABIHF() || getTarget().getTriple().isWatchABI())
6523     return llvm::CallingConv::ARM_AAPCS_VFP;
6524   else if (isEABI())
6525     return llvm::CallingConv::ARM_AAPCS;
6526   else
6527     return llvm::CallingConv::ARM_APCS;
6528 }
6529 
6530 /// Return the calling convention that our ABI would like us to use
6531 /// as the C calling convention.
6532 llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
6533   switch (getABIKind()) {
6534   case APCS: return llvm::CallingConv::ARM_APCS;
6535   case AAPCS: return llvm::CallingConv::ARM_AAPCS;
6536   case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
6537   case AAPCS16_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
6538   }
6539   llvm_unreachable("bad ABI kind");
6540 }
6541 
6542 void ARMABIInfo::setCCs() {
6543   assert(getRuntimeCC() == llvm::CallingConv::C);
6544 
6545   // Don't muddy up the IR with a ton of explicit annotations if
6546   // they'd just match what LLVM will infer from the triple.
6547   llvm::CallingConv::ID abiCC = getABIDefaultCC();
6548   if (abiCC != getLLVMDefaultCC())
6549     RuntimeCC = abiCC;
6550 }
6551 
6552 ABIArgInfo ARMABIInfo::coerceIllegalVector(QualType Ty) const {
6553   uint64_t Size = getContext().getTypeSize(Ty);
6554   if (Size <= 32) {
6555     llvm::Type *ResType =
6556         llvm::Type::getInt32Ty(getVMContext());
6557     return ABIArgInfo::getDirect(ResType);
6558   }
6559   if (Size == 64 || Size == 128) {
6560     auto *ResType = llvm::FixedVectorType::get(
6561         llvm::Type::getInt32Ty(getVMContext()), Size / 32);
6562     return ABIArgInfo::getDirect(ResType);
6563   }
6564   return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
6565 }
6566 
6567 ABIArgInfo ARMABIInfo::classifyHomogeneousAggregate(QualType Ty,
6568                                                     const Type *Base,
6569                                                     uint64_t Members) const {
6570   assert(Base && "Base class should be set for homogeneous aggregate");
6571   // Base can be a floating-point or a vector.
6572   if (const VectorType *VT = Base->getAs<VectorType>()) {
6573     // FP16 vectors should be converted to integer vectors
6574     if (!getTarget().hasLegalHalfType() && containsAnyFP16Vectors(Ty)) {
6575       uint64_t Size = getContext().getTypeSize(VT);
6576       auto *NewVecTy = llvm::FixedVectorType::get(
6577           llvm::Type::getInt32Ty(getVMContext()), Size / 32);
6578       llvm::Type *Ty = llvm::ArrayType::get(NewVecTy, Members);
6579       return ABIArgInfo::getDirect(Ty, 0, nullptr, false);
6580     }
6581   }
6582   unsigned Align = 0;
6583   if (getABIKind() == ARMABIInfo::AAPCS ||
6584       getABIKind() == ARMABIInfo::AAPCS_VFP) {
6585     // For alignment adjusted HFAs, cap the argument alignment to 8, leave it
6586     // default otherwise.
6587     Align = getContext().getTypeUnadjustedAlignInChars(Ty).getQuantity();
6588     unsigned BaseAlign = getContext().getTypeAlignInChars(Base).getQuantity();
6589     Align = (Align > BaseAlign && Align >= 8) ? 8 : 0;
6590   }
6591   return ABIArgInfo::getDirect(nullptr, 0, nullptr, false, Align);
6592 }
6593 
6594 ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty, bool isVariadic,
6595                                             unsigned functionCallConv) const {
6596   // 6.1.2.1 The following argument types are VFP CPRCs:
6597   //   A single-precision floating-point type (including promoted
6598   //   half-precision types); A double-precision floating-point type;
6599   //   A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
6600   //   with a Base Type of a single- or double-precision floating-point type,
6601   //   64-bit containerized vectors or 128-bit containerized vectors with one
6602   //   to four Elements.
6603   // Variadic functions should always marshal to the base standard.
6604   bool IsAAPCS_VFP =
6605       !isVariadic && isEffectivelyAAPCS_VFP(functionCallConv, /* AAPCS16 */ false);
6606 
6607   Ty = useFirstFieldIfTransparentUnion(Ty);
6608 
6609   // Handle illegal vector types here.
6610   if (isIllegalVectorType(Ty))
6611     return coerceIllegalVector(Ty);
6612 
6613   if (!isAggregateTypeForABI(Ty)) {
6614     // Treat an enum type as its underlying type.
6615     if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
6616       Ty = EnumTy->getDecl()->getIntegerType();
6617     }
6618 
6619     if (const auto *EIT = Ty->getAs<BitIntType>())
6620       if (EIT->getNumBits() > 64)
6621         return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
6622 
6623     return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
6624                                               : ABIArgInfo::getDirect());
6625   }
6626 
6627   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
6628     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
6629   }
6630 
6631   // Ignore empty records.
6632   if (isEmptyRecord(getContext(), Ty, true))
6633     return ABIArgInfo::getIgnore();
6634 
6635   if (IsAAPCS_VFP) {
6636     // Homogeneous Aggregates need to be expanded when we can fit the aggregate
6637     // into VFP registers.
6638     const Type *Base = nullptr;
6639     uint64_t Members = 0;
6640     if (isHomogeneousAggregate(Ty, Base, Members))
6641       return classifyHomogeneousAggregate(Ty, Base, Members);
6642   } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
6643     // WatchOS does have homogeneous aggregates. Note that we intentionally use
6644     // this convention even for a variadic function: the backend will use GPRs
6645     // if needed.
6646     const Type *Base = nullptr;
6647     uint64_t Members = 0;
6648     if (isHomogeneousAggregate(Ty, Base, Members)) {
6649       assert(Base && Members <= 4 && "unexpected homogeneous aggregate");
6650       llvm::Type *Ty =
6651         llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members);
6652       return ABIArgInfo::getDirect(Ty, 0, nullptr, false);
6653     }
6654   }
6655 
6656   if (getABIKind() == ARMABIInfo::AAPCS16_VFP &&
6657       getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(16)) {
6658     // WatchOS is adopting the 64-bit AAPCS rule on composite types: if they're
6659     // bigger than 128-bits, they get placed in space allocated by the caller,
6660     // and a pointer is passed.
6661     return ABIArgInfo::getIndirect(
6662         CharUnits::fromQuantity(getContext().getTypeAlign(Ty) / 8), false);
6663   }
6664 
6665   // Support byval for ARM.
6666   // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
6667   // most 8-byte. We realign the indirect argument if type alignment is bigger
6668   // than ABI alignment.
6669   uint64_t ABIAlign = 4;
6670   uint64_t TyAlign;
6671   if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
6672       getABIKind() == ARMABIInfo::AAPCS) {
6673     TyAlign = getContext().getTypeUnadjustedAlignInChars(Ty).getQuantity();
6674     ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
6675   } else {
6676     TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity();
6677   }
6678   if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
6679     assert(getABIKind() != ARMABIInfo::AAPCS16_VFP && "unexpected byval");
6680     return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
6681                                    /*ByVal=*/true,
6682                                    /*Realign=*/TyAlign > ABIAlign);
6683   }
6684 
6685   // On RenderScript, coerce Aggregates <= 64 bytes to an integer array of
6686   // same size and alignment.
6687   if (getTarget().isRenderScriptTarget()) {
6688     return coerceToIntArray(Ty, getContext(), getVMContext());
6689   }
6690 
6691   // Otherwise, pass by coercing to a structure of the appropriate size.
6692   llvm::Type* ElemTy;
6693   unsigned SizeRegs;
6694   // FIXME: Try to match the types of the arguments more accurately where
6695   // we can.
6696   if (TyAlign <= 4) {
6697     ElemTy = llvm::Type::getInt32Ty(getVMContext());
6698     SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
6699   } else {
6700     ElemTy = llvm::Type::getInt64Ty(getVMContext());
6701     SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
6702   }
6703 
6704   return ABIArgInfo::getDirect(llvm::ArrayType::get(ElemTy, SizeRegs));
6705 }
6706 
6707 static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
6708                               llvm::LLVMContext &VMContext) {
6709   // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
6710   // is called integer-like if its size is less than or equal to one word, and
6711   // the offset of each of its addressable sub-fields is zero.
6712 
6713   uint64_t Size = Context.getTypeSize(Ty);
6714 
6715   // Check that the type fits in a word.
6716   if (Size > 32)
6717     return false;
6718 
6719   // FIXME: Handle vector types!
6720   if (Ty->isVectorType())
6721     return false;
6722 
6723   // Float types are never treated as "integer like".
6724   if (Ty->isRealFloatingType())
6725     return false;
6726 
6727   // If this is a builtin or pointer type then it is ok.
6728   if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
6729     return true;
6730 
6731   // Small complex integer types are "integer like".
6732   if (const ComplexType *CT = Ty->getAs<ComplexType>())
6733     return isIntegerLikeType(CT->getElementType(), Context, VMContext);
6734 
6735   // Single element and zero sized arrays should be allowed, by the definition
6736   // above, but they are not.
6737 
6738   // Otherwise, it must be a record type.
6739   const RecordType *RT = Ty->getAs<RecordType>();
6740   if (!RT) return false;
6741 
6742   // Ignore records with flexible arrays.
6743   const RecordDecl *RD = RT->getDecl();
6744   if (RD->hasFlexibleArrayMember())
6745     return false;
6746 
6747   // Check that all sub-fields are at offset 0, and are themselves "integer
6748   // like".
6749   const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
6750 
6751   bool HadField = false;
6752   unsigned idx = 0;
6753   for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
6754        i != e; ++i, ++idx) {
6755     const FieldDecl *FD = *i;
6756 
6757     // Bit-fields are not addressable, we only need to verify they are "integer
6758     // like". We still have to disallow a subsequent non-bitfield, for example:
6759     //   struct { int : 0; int x }
6760     // is non-integer like according to gcc.
6761     if (FD->isBitField()) {
6762       if (!RD->isUnion())
6763         HadField = true;
6764 
6765       if (!isIntegerLikeType(FD->getType(), Context, VMContext))
6766         return false;
6767 
6768       continue;
6769     }
6770 
6771     // Check if this field is at offset 0.
6772     if (Layout.getFieldOffset(idx) != 0)
6773       return false;
6774 
6775     if (!isIntegerLikeType(FD->getType(), Context, VMContext))
6776       return false;
6777 
6778     // Only allow at most one field in a structure. This doesn't match the
6779     // wording above, but follows gcc in situations with a field following an
6780     // empty structure.
6781     if (!RD->isUnion()) {
6782       if (HadField)
6783         return false;
6784 
6785       HadField = true;
6786     }
6787   }
6788 
6789   return true;
6790 }
6791 
6792 ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy, bool isVariadic,
6793                                           unsigned functionCallConv) const {
6794 
6795   // Variadic functions should always marshal to the base standard.
6796   bool IsAAPCS_VFP =
6797       !isVariadic && isEffectivelyAAPCS_VFP(functionCallConv, /* AAPCS16 */ true);
6798 
6799   if (RetTy->isVoidType())
6800     return ABIArgInfo::getIgnore();
6801 
6802   if (const VectorType *VT = RetTy->getAs<VectorType>()) {
6803     // Large vector types should be returned via memory.
6804     if (getContext().getTypeSize(RetTy) > 128)
6805       return getNaturalAlignIndirect(RetTy);
6806     // TODO: FP16/BF16 vectors should be converted to integer vectors
6807     // This check is similar  to isIllegalVectorType - refactor?
6808     if ((!getTarget().hasLegalHalfType() &&
6809         (VT->getElementType()->isFloat16Type() ||
6810          VT->getElementType()->isHalfType())) ||
6811         (IsFloatABISoftFP &&
6812          VT->getElementType()->isBFloat16Type()))
6813       return coerceIllegalVector(RetTy);
6814   }
6815 
6816   if (!isAggregateTypeForABI(RetTy)) {
6817     // Treat an enum type as its underlying type.
6818     if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6819       RetTy = EnumTy->getDecl()->getIntegerType();
6820 
6821     if (const auto *EIT = RetTy->getAs<BitIntType>())
6822       if (EIT->getNumBits() > 64)
6823         return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
6824 
6825     return isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
6826                                                 : ABIArgInfo::getDirect();
6827   }
6828 
6829   // Are we following APCS?
6830   if (getABIKind() == APCS) {
6831     if (isEmptyRecord(getContext(), RetTy, false))
6832       return ABIArgInfo::getIgnore();
6833 
6834     // Complex types are all returned as packed integers.
6835     //
6836     // FIXME: Consider using 2 x vector types if the back end handles them
6837     // correctly.
6838     if (RetTy->isAnyComplexType())
6839       return ABIArgInfo::getDirect(llvm::IntegerType::get(
6840           getVMContext(), getContext().getTypeSize(RetTy)));
6841 
6842     // Integer like structures are returned in r0.
6843     if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
6844       // Return in the smallest viable integer type.
6845       uint64_t Size = getContext().getTypeSize(RetTy);
6846       if (Size <= 8)
6847         return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6848       if (Size <= 16)
6849         return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6850       return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6851     }
6852 
6853     // Otherwise return in memory.
6854     return getNaturalAlignIndirect(RetTy);
6855   }
6856 
6857   // Otherwise this is an AAPCS variant.
6858 
6859   if (isEmptyRecord(getContext(), RetTy, true))
6860     return ABIArgInfo::getIgnore();
6861 
6862   // Check for homogeneous aggregates with AAPCS-VFP.
6863   if (IsAAPCS_VFP) {
6864     const Type *Base = nullptr;
6865     uint64_t Members = 0;
6866     if (isHomogeneousAggregate(RetTy, Base, Members))
6867       return classifyHomogeneousAggregate(RetTy, Base, Members);
6868   }
6869 
6870   // Aggregates <= 4 bytes are returned in r0; other aggregates
6871   // are returned indirectly.
6872   uint64_t Size = getContext().getTypeSize(RetTy);
6873   if (Size <= 32) {
6874     // On RenderScript, coerce Aggregates <= 4 bytes to an integer array of
6875     // same size and alignment.
6876     if (getTarget().isRenderScriptTarget()) {
6877       return coerceToIntArray(RetTy, getContext(), getVMContext());
6878     }
6879     if (getDataLayout().isBigEndian())
6880       // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4)
6881       return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6882 
6883     // Return in the smallest viable integer type.
6884     if (Size <= 8)
6885       return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6886     if (Size <= 16)
6887       return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6888     return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6889   } else if (Size <= 128 && getABIKind() == AAPCS16_VFP) {
6890     llvm::Type *Int32Ty = llvm::Type::getInt32Ty(getVMContext());
6891     llvm::Type *CoerceTy =
6892         llvm::ArrayType::get(Int32Ty, llvm::alignTo(Size, 32) / 32);
6893     return ABIArgInfo::getDirect(CoerceTy);
6894   }
6895 
6896   return getNaturalAlignIndirect(RetTy);
6897 }
6898 
6899 /// isIllegalVector - check whether Ty is an illegal vector type.
6900 bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
6901   if (const VectorType *VT = Ty->getAs<VectorType> ()) {
6902     // On targets that don't support half, fp16 or bfloat, they are expanded
6903     // into float, and we don't want the ABI to depend on whether or not they
6904     // are supported in hardware. Thus return false to coerce vectors of these
6905     // types into integer vectors.
6906     // We do not depend on hasLegalHalfType for bfloat as it is a
6907     // separate IR type.
6908     if ((!getTarget().hasLegalHalfType() &&
6909         (VT->getElementType()->isFloat16Type() ||
6910          VT->getElementType()->isHalfType())) ||
6911         (IsFloatABISoftFP &&
6912          VT->getElementType()->isBFloat16Type()))
6913       return true;
6914     if (isAndroid()) {
6915       // Android shipped using Clang 3.1, which supported a slightly different
6916       // vector ABI. The primary differences were that 3-element vector types
6917       // were legal, and so were sub 32-bit vectors (i.e. <2 x i8>). This path
6918       // accepts that legacy behavior for Android only.
6919       // Check whether VT is legal.
6920       unsigned NumElements = VT->getNumElements();
6921       // NumElements should be power of 2 or equal to 3.
6922       if (!llvm::isPowerOf2_32(NumElements) && NumElements != 3)
6923         return true;
6924     } else {
6925       // Check whether VT is legal.
6926       unsigned NumElements = VT->getNumElements();
6927       uint64_t Size = getContext().getTypeSize(VT);
6928       // NumElements should be power of 2.
6929       if (!llvm::isPowerOf2_32(NumElements))
6930         return true;
6931       // Size should be greater than 32 bits.
6932       return Size <= 32;
6933     }
6934   }
6935   return false;
6936 }
6937 
6938 /// Return true if a type contains any 16-bit floating point vectors
6939 bool ARMABIInfo::containsAnyFP16Vectors(QualType Ty) const {
6940   if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
6941     uint64_t NElements = AT->getSize().getZExtValue();
6942     if (NElements == 0)
6943       return false;
6944     return containsAnyFP16Vectors(AT->getElementType());
6945   } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
6946     const RecordDecl *RD = RT->getDecl();
6947 
6948     // If this is a C++ record, check the bases first.
6949     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
6950       if (llvm::any_of(CXXRD->bases(), [this](const CXXBaseSpecifier &B) {
6951             return containsAnyFP16Vectors(B.getType());
6952           }))
6953         return true;
6954 
6955     if (llvm::any_of(RD->fields(), [this](FieldDecl *FD) {
6956           return FD && containsAnyFP16Vectors(FD->getType());
6957         }))
6958       return true;
6959 
6960     return false;
6961   } else {
6962     if (const VectorType *VT = Ty->getAs<VectorType>())
6963       return (VT->getElementType()->isFloat16Type() ||
6964               VT->getElementType()->isBFloat16Type() ||
6965               VT->getElementType()->isHalfType());
6966     return false;
6967   }
6968 }
6969 
6970 bool ARMABIInfo::isLegalVectorTypeForSwift(CharUnits vectorSize,
6971                                            llvm::Type *eltTy,
6972                                            unsigned numElts) const {
6973   if (!llvm::isPowerOf2_32(numElts))
6974     return false;
6975   unsigned size = getDataLayout().getTypeStoreSizeInBits(eltTy);
6976   if (size > 64)
6977     return false;
6978   if (vectorSize.getQuantity() != 8 &&
6979       (vectorSize.getQuantity() != 16 || numElts == 1))
6980     return false;
6981   return true;
6982 }
6983 
6984 bool ARMABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
6985   // Homogeneous aggregates for AAPCS-VFP must have base types of float,
6986   // double, or 64-bit or 128-bit vectors.
6987   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
6988     if (BT->getKind() == BuiltinType::Float ||
6989         BT->getKind() == BuiltinType::Double ||
6990         BT->getKind() == BuiltinType::LongDouble)
6991       return true;
6992   } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
6993     unsigned VecSize = getContext().getTypeSize(VT);
6994     if (VecSize == 64 || VecSize == 128)
6995       return true;
6996   }
6997   return false;
6998 }
6999 
7000 bool ARMABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
7001                                                    uint64_t Members) const {
7002   return Members <= 4;
7003 }
7004 
7005 bool ARMABIInfo::isEffectivelyAAPCS_VFP(unsigned callConvention,
7006                                         bool acceptHalf) const {
7007   // Give precedence to user-specified calling conventions.
7008   if (callConvention != llvm::CallingConv::C)
7009     return (callConvention == llvm::CallingConv::ARM_AAPCS_VFP);
7010   else
7011     return (getABIKind() == AAPCS_VFP) ||
7012            (acceptHalf && (getABIKind() == AAPCS16_VFP));
7013 }
7014 
7015 Address ARMABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7016                               QualType Ty) const {
7017   CharUnits SlotSize = CharUnits::fromQuantity(4);
7018 
7019   // Empty records are ignored for parameter passing purposes.
7020   if (isEmptyRecord(getContext(), Ty, true)) {
7021     Address Addr = Address(CGF.Builder.CreateLoad(VAListAddr),
7022                            getVAListElementType(CGF), SlotSize);
7023     Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
7024     return Addr;
7025   }
7026 
7027   CharUnits TySize = getContext().getTypeSizeInChars(Ty);
7028   CharUnits TyAlignForABI = getContext().getTypeUnadjustedAlignInChars(Ty);
7029 
7030   // Use indirect if size of the illegal vector is bigger than 16 bytes.
7031   bool IsIndirect = false;
7032   const Type *Base = nullptr;
7033   uint64_t Members = 0;
7034   if (TySize > CharUnits::fromQuantity(16) && isIllegalVectorType(Ty)) {
7035     IsIndirect = true;
7036 
7037   // ARMv7k passes structs bigger than 16 bytes indirectly, in space
7038   // allocated by the caller.
7039   } else if (TySize > CharUnits::fromQuantity(16) &&
7040              getABIKind() == ARMABIInfo::AAPCS16_VFP &&
7041              !isHomogeneousAggregate(Ty, Base, Members)) {
7042     IsIndirect = true;
7043 
7044   // Otherwise, bound the type's ABI alignment.
7045   // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
7046   // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
7047   // Our callers should be prepared to handle an under-aligned address.
7048   } else if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
7049              getABIKind() == ARMABIInfo::AAPCS) {
7050     TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
7051     TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(8));
7052   } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
7053     // ARMv7k allows type alignment up to 16 bytes.
7054     TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
7055     TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(16));
7056   } else {
7057     TyAlignForABI = CharUnits::fromQuantity(4);
7058   }
7059 
7060   TypeInfoChars TyInfo(TySize, TyAlignForABI, AlignRequirementKind::None);
7061   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TyInfo,
7062                           SlotSize, /*AllowHigherAlign*/ true);
7063 }
7064 
7065 //===----------------------------------------------------------------------===//
7066 // NVPTX ABI Implementation
7067 //===----------------------------------------------------------------------===//
7068 
7069 namespace {
7070 
7071 class NVPTXTargetCodeGenInfo;
7072 
7073 class NVPTXABIInfo : public ABIInfo {
7074   NVPTXTargetCodeGenInfo &CGInfo;
7075 
7076 public:
7077   NVPTXABIInfo(CodeGenTypes &CGT, NVPTXTargetCodeGenInfo &Info)
7078       : ABIInfo(CGT), CGInfo(Info) {}
7079 
7080   ABIArgInfo classifyReturnType(QualType RetTy) const;
7081   ABIArgInfo classifyArgumentType(QualType Ty) const;
7082 
7083   void computeInfo(CGFunctionInfo &FI) const override;
7084   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7085                     QualType Ty) const override;
7086   bool isUnsupportedType(QualType T) const;
7087   ABIArgInfo coerceToIntArrayWithLimit(QualType Ty, unsigned MaxSize) const;
7088 };
7089 
7090 class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
7091 public:
7092   NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
7093       : TargetCodeGenInfo(std::make_unique<NVPTXABIInfo>(CGT, *this)) {}
7094 
7095   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
7096                            CodeGen::CodeGenModule &M) const override;
7097   bool shouldEmitStaticExternCAliases() const override;
7098 
7099   llvm::Type *getCUDADeviceBuiltinSurfaceDeviceType() const override {
7100     // On the device side, surface reference is represented as an object handle
7101     // in 64-bit integer.
7102     return llvm::Type::getInt64Ty(getABIInfo().getVMContext());
7103   }
7104 
7105   llvm::Type *getCUDADeviceBuiltinTextureDeviceType() const override {
7106     // On the device side, texture reference is represented as an object handle
7107     // in 64-bit integer.
7108     return llvm::Type::getInt64Ty(getABIInfo().getVMContext());
7109   }
7110 
7111   bool emitCUDADeviceBuiltinSurfaceDeviceCopy(CodeGenFunction &CGF, LValue Dst,
7112                                               LValue Src) const override {
7113     emitBuiltinSurfTexDeviceCopy(CGF, Dst, Src);
7114     return true;
7115   }
7116 
7117   bool emitCUDADeviceBuiltinTextureDeviceCopy(CodeGenFunction &CGF, LValue Dst,
7118                                               LValue Src) const override {
7119     emitBuiltinSurfTexDeviceCopy(CGF, Dst, Src);
7120     return true;
7121   }
7122 
7123 private:
7124   // Adds a NamedMDNode with GV, Name, and Operand as operands, and adds the
7125   // resulting MDNode to the nvvm.annotations MDNode.
7126   static void addNVVMMetadata(llvm::GlobalValue *GV, StringRef Name,
7127                               int Operand);
7128 
7129   static void emitBuiltinSurfTexDeviceCopy(CodeGenFunction &CGF, LValue Dst,
7130                                            LValue Src) {
7131     llvm::Value *Handle = nullptr;
7132     llvm::Constant *C =
7133         llvm::dyn_cast<llvm::Constant>(Src.getAddress(CGF).getPointer());
7134     // Lookup `addrspacecast` through the constant pointer if any.
7135     if (auto *ASC = llvm::dyn_cast_or_null<llvm::AddrSpaceCastOperator>(C))
7136       C = llvm::cast<llvm::Constant>(ASC->getPointerOperand());
7137     if (auto *GV = llvm::dyn_cast_or_null<llvm::GlobalVariable>(C)) {
7138       // Load the handle from the specific global variable using
7139       // `nvvm.texsurf.handle.internal` intrinsic.
7140       Handle = CGF.EmitRuntimeCall(
7141           CGF.CGM.getIntrinsic(llvm::Intrinsic::nvvm_texsurf_handle_internal,
7142                                {GV->getType()}),
7143           {GV}, "texsurf_handle");
7144     } else
7145       Handle = CGF.EmitLoadOfScalar(Src, SourceLocation());
7146     CGF.EmitStoreOfScalar(Handle, Dst);
7147   }
7148 };
7149 
7150 /// Checks if the type is unsupported directly by the current target.
7151 bool NVPTXABIInfo::isUnsupportedType(QualType T) const {
7152   ASTContext &Context = getContext();
7153   if (!Context.getTargetInfo().hasFloat16Type() && T->isFloat16Type())
7154     return true;
7155   if (!Context.getTargetInfo().hasFloat128Type() &&
7156       (T->isFloat128Type() ||
7157        (T->isRealFloatingType() && Context.getTypeSize(T) == 128)))
7158     return true;
7159   if (const auto *EIT = T->getAs<BitIntType>())
7160     return EIT->getNumBits() >
7161            (Context.getTargetInfo().hasInt128Type() ? 128U : 64U);
7162   if (!Context.getTargetInfo().hasInt128Type() && T->isIntegerType() &&
7163       Context.getTypeSize(T) > 64U)
7164     return true;
7165   if (const auto *AT = T->getAsArrayTypeUnsafe())
7166     return isUnsupportedType(AT->getElementType());
7167   const auto *RT = T->getAs<RecordType>();
7168   if (!RT)
7169     return false;
7170   const RecordDecl *RD = RT->getDecl();
7171 
7172   // If this is a C++ record, check the bases first.
7173   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
7174     for (const CXXBaseSpecifier &I : CXXRD->bases())
7175       if (isUnsupportedType(I.getType()))
7176         return true;
7177 
7178   for (const FieldDecl *I : RD->fields())
7179     if (isUnsupportedType(I->getType()))
7180       return true;
7181   return false;
7182 }
7183 
7184 /// Coerce the given type into an array with maximum allowed size of elements.
7185 ABIArgInfo NVPTXABIInfo::coerceToIntArrayWithLimit(QualType Ty,
7186                                                    unsigned MaxSize) const {
7187   // Alignment and Size are measured in bits.
7188   const uint64_t Size = getContext().getTypeSize(Ty);
7189   const uint64_t Alignment = getContext().getTypeAlign(Ty);
7190   const unsigned Div = std::min<unsigned>(MaxSize, Alignment);
7191   llvm::Type *IntType = llvm::Type::getIntNTy(getVMContext(), Div);
7192   const uint64_t NumElements = (Size + Div - 1) / Div;
7193   return ABIArgInfo::getDirect(llvm::ArrayType::get(IntType, NumElements));
7194 }
7195 
7196 ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
7197   if (RetTy->isVoidType())
7198     return ABIArgInfo::getIgnore();
7199 
7200   if (getContext().getLangOpts().OpenMP &&
7201       getContext().getLangOpts().OpenMPIsDevice && isUnsupportedType(RetTy))
7202     return coerceToIntArrayWithLimit(RetTy, 64);
7203 
7204   // note: this is different from default ABI
7205   if (!RetTy->isScalarType())
7206     return ABIArgInfo::getDirect();
7207 
7208   // Treat an enum type as its underlying type.
7209   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
7210     RetTy = EnumTy->getDecl()->getIntegerType();
7211 
7212   return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
7213                                                : ABIArgInfo::getDirect());
7214 }
7215 
7216 ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
7217   // Treat an enum type as its underlying type.
7218   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7219     Ty = EnumTy->getDecl()->getIntegerType();
7220 
7221   // Return aggregates type as indirect by value
7222   if (isAggregateTypeForABI(Ty)) {
7223     // Under CUDA device compilation, tex/surf builtin types are replaced with
7224     // object types and passed directly.
7225     if (getContext().getLangOpts().CUDAIsDevice) {
7226       if (Ty->isCUDADeviceBuiltinSurfaceType())
7227         return ABIArgInfo::getDirect(
7228             CGInfo.getCUDADeviceBuiltinSurfaceDeviceType());
7229       if (Ty->isCUDADeviceBuiltinTextureType())
7230         return ABIArgInfo::getDirect(
7231             CGInfo.getCUDADeviceBuiltinTextureDeviceType());
7232     }
7233     return getNaturalAlignIndirect(Ty, /* byval */ true);
7234   }
7235 
7236   if (const auto *EIT = Ty->getAs<BitIntType>()) {
7237     if ((EIT->getNumBits() > 128) ||
7238         (!getContext().getTargetInfo().hasInt128Type() &&
7239          EIT->getNumBits() > 64))
7240       return getNaturalAlignIndirect(Ty, /* byval */ true);
7241   }
7242 
7243   return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
7244                                             : ABIArgInfo::getDirect());
7245 }
7246 
7247 void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
7248   if (!getCXXABI().classifyReturnType(FI))
7249     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7250   for (auto &I : FI.arguments())
7251     I.info = classifyArgumentType(I.type);
7252 
7253   // Always honor user-specified calling convention.
7254   if (FI.getCallingConvention() != llvm::CallingConv::C)
7255     return;
7256 
7257   FI.setEffectiveCallingConvention(getRuntimeCC());
7258 }
7259 
7260 Address NVPTXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7261                                 QualType Ty) const {
7262   llvm_unreachable("NVPTX does not support varargs");
7263 }
7264 
7265 void NVPTXTargetCodeGenInfo::setTargetAttributes(
7266     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
7267   if (GV->isDeclaration())
7268     return;
7269   const VarDecl *VD = dyn_cast_or_null<VarDecl>(D);
7270   if (VD) {
7271     if (M.getLangOpts().CUDA) {
7272       if (VD->getType()->isCUDADeviceBuiltinSurfaceType())
7273         addNVVMMetadata(GV, "surface", 1);
7274       else if (VD->getType()->isCUDADeviceBuiltinTextureType())
7275         addNVVMMetadata(GV, "texture", 1);
7276       return;
7277     }
7278   }
7279 
7280   const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
7281   if (!FD) return;
7282 
7283   llvm::Function *F = cast<llvm::Function>(GV);
7284 
7285   // Perform special handling in OpenCL mode
7286   if (M.getLangOpts().OpenCL) {
7287     // Use OpenCL function attributes to check for kernel functions
7288     // By default, all functions are device functions
7289     if (FD->hasAttr<OpenCLKernelAttr>()) {
7290       // OpenCL __kernel functions get kernel metadata
7291       // Create !{<func-ref>, metadata !"kernel", i32 1} node
7292       addNVVMMetadata(F, "kernel", 1);
7293       // And kernel functions are not subject to inlining
7294       F->addFnAttr(llvm::Attribute::NoInline);
7295     }
7296   }
7297 
7298   // Perform special handling in CUDA mode.
7299   if (M.getLangOpts().CUDA) {
7300     // CUDA __global__ functions get a kernel metadata entry.  Since
7301     // __global__ functions cannot be called from the device, we do not
7302     // need to set the noinline attribute.
7303     if (FD->hasAttr<CUDAGlobalAttr>()) {
7304       // Create !{<func-ref>, metadata !"kernel", i32 1} node
7305       addNVVMMetadata(F, "kernel", 1);
7306     }
7307     if (CUDALaunchBoundsAttr *Attr = FD->getAttr<CUDALaunchBoundsAttr>()) {
7308       // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node
7309       llvm::APSInt MaxThreads(32);
7310       MaxThreads = Attr->getMaxThreads()->EvaluateKnownConstInt(M.getContext());
7311       if (MaxThreads > 0)
7312         addNVVMMetadata(F, "maxntidx", MaxThreads.getExtValue());
7313 
7314       // min blocks is an optional argument for CUDALaunchBoundsAttr. If it was
7315       // not specified in __launch_bounds__ or if the user specified a 0 value,
7316       // we don't have to add a PTX directive.
7317       if (Attr->getMinBlocks()) {
7318         llvm::APSInt MinBlocks(32);
7319         MinBlocks = Attr->getMinBlocks()->EvaluateKnownConstInt(M.getContext());
7320         if (MinBlocks > 0)
7321           // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node
7322           addNVVMMetadata(F, "minctasm", MinBlocks.getExtValue());
7323       }
7324     }
7325   }
7326 }
7327 
7328 void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::GlobalValue *GV,
7329                                              StringRef Name, int Operand) {
7330   llvm::Module *M = GV->getParent();
7331   llvm::LLVMContext &Ctx = M->getContext();
7332 
7333   // Get "nvvm.annotations" metadata node
7334   llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
7335 
7336   llvm::Metadata *MDVals[] = {
7337       llvm::ConstantAsMetadata::get(GV), llvm::MDString::get(Ctx, Name),
7338       llvm::ConstantAsMetadata::get(
7339           llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand))};
7340   // Append metadata to nvvm.annotations
7341   MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
7342 }
7343 
7344 bool NVPTXTargetCodeGenInfo::shouldEmitStaticExternCAliases() const {
7345   return false;
7346 }
7347 }
7348 
7349 //===----------------------------------------------------------------------===//
7350 // SystemZ ABI Implementation
7351 //===----------------------------------------------------------------------===//
7352 
7353 namespace {
7354 
7355 class SystemZABIInfo : public SwiftABIInfo {
7356   bool HasVector;
7357   bool IsSoftFloatABI;
7358 
7359 public:
7360   SystemZABIInfo(CodeGenTypes &CGT, bool HV, bool SF)
7361     : SwiftABIInfo(CGT), HasVector(HV), IsSoftFloatABI(SF) {}
7362 
7363   bool isPromotableIntegerTypeForABI(QualType Ty) const;
7364   bool isCompoundType(QualType Ty) const;
7365   bool isVectorArgumentType(QualType Ty) const;
7366   bool isFPArgumentType(QualType Ty) const;
7367   QualType GetSingleElementType(QualType Ty) const;
7368 
7369   ABIArgInfo classifyReturnType(QualType RetTy) const;
7370   ABIArgInfo classifyArgumentType(QualType ArgTy) const;
7371 
7372   void computeInfo(CGFunctionInfo &FI) const override {
7373     if (!getCXXABI().classifyReturnType(FI))
7374       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7375     for (auto &I : FI.arguments())
7376       I.info = classifyArgumentType(I.type);
7377   }
7378 
7379   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7380                     QualType Ty) const override;
7381 
7382   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
7383                                     bool asReturnValue) const override {
7384     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
7385   }
7386   bool isSwiftErrorInRegister() const override {
7387     return false;
7388   }
7389 };
7390 
7391 class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
7392 public:
7393   SystemZTargetCodeGenInfo(CodeGenTypes &CGT, bool HasVector, bool SoftFloatABI)
7394       : TargetCodeGenInfo(
7395             std::make_unique<SystemZABIInfo>(CGT, HasVector, SoftFloatABI)) {}
7396 
7397   llvm::Value *testFPKind(llvm::Value *V, unsigned BuiltinID,
7398                           CGBuilderTy &Builder,
7399                           CodeGenModule &CGM) const override {
7400     assert(V->getType()->isFloatingPointTy() && "V should have an FP type.");
7401     // Only use TDC in constrained FP mode.
7402     if (!Builder.getIsFPConstrained())
7403       return nullptr;
7404 
7405     llvm::Type *Ty = V->getType();
7406     if (Ty->isFloatTy() || Ty->isDoubleTy() || Ty->isFP128Ty()) {
7407       llvm::Module &M = CGM.getModule();
7408       auto &Ctx = M.getContext();
7409       llvm::Function *TDCFunc =
7410           llvm::Intrinsic::getDeclaration(&M, llvm::Intrinsic::s390_tdc, Ty);
7411       unsigned TDCBits = 0;
7412       switch (BuiltinID) {
7413       case Builtin::BI__builtin_isnan:
7414         TDCBits = 0xf;
7415         break;
7416       case Builtin::BIfinite:
7417       case Builtin::BI__finite:
7418       case Builtin::BIfinitef:
7419       case Builtin::BI__finitef:
7420       case Builtin::BIfinitel:
7421       case Builtin::BI__finitel:
7422       case Builtin::BI__builtin_isfinite:
7423         TDCBits = 0xfc0;
7424         break;
7425       case Builtin::BI__builtin_isinf:
7426         TDCBits = 0x30;
7427         break;
7428       default:
7429         break;
7430       }
7431       if (TDCBits)
7432         return Builder.CreateCall(
7433             TDCFunc,
7434             {V, llvm::ConstantInt::get(llvm::Type::getInt64Ty(Ctx), TDCBits)});
7435     }
7436     return nullptr;
7437   }
7438 };
7439 }
7440 
7441 bool SystemZABIInfo::isPromotableIntegerTypeForABI(QualType Ty) const {
7442   // Treat an enum type as its underlying type.
7443   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7444     Ty = EnumTy->getDecl()->getIntegerType();
7445 
7446   // Promotable integer types are required to be promoted by the ABI.
7447   if (ABIInfo::isPromotableIntegerTypeForABI(Ty))
7448     return true;
7449 
7450   if (const auto *EIT = Ty->getAs<BitIntType>())
7451     if (EIT->getNumBits() < 64)
7452       return true;
7453 
7454   // 32-bit values must also be promoted.
7455   if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
7456     switch (BT->getKind()) {
7457     case BuiltinType::Int:
7458     case BuiltinType::UInt:
7459       return true;
7460     default:
7461       return false;
7462     }
7463   return false;
7464 }
7465 
7466 bool SystemZABIInfo::isCompoundType(QualType Ty) const {
7467   return (Ty->isAnyComplexType() ||
7468           Ty->isVectorType() ||
7469           isAggregateTypeForABI(Ty));
7470 }
7471 
7472 bool SystemZABIInfo::isVectorArgumentType(QualType Ty) const {
7473   return (HasVector &&
7474           Ty->isVectorType() &&
7475           getContext().getTypeSize(Ty) <= 128);
7476 }
7477 
7478 bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
7479   if (IsSoftFloatABI)
7480     return false;
7481 
7482   if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
7483     switch (BT->getKind()) {
7484     case BuiltinType::Float:
7485     case BuiltinType::Double:
7486       return true;
7487     default:
7488       return false;
7489     }
7490 
7491   return false;
7492 }
7493 
7494 QualType SystemZABIInfo::GetSingleElementType(QualType Ty) const {
7495   const RecordType *RT = Ty->getAs<RecordType>();
7496 
7497   if (RT && RT->isStructureOrClassType()) {
7498     const RecordDecl *RD = RT->getDecl();
7499     QualType Found;
7500 
7501     // If this is a C++ record, check the bases first.
7502     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
7503       for (const auto &I : CXXRD->bases()) {
7504         QualType Base = I.getType();
7505 
7506         // Empty bases don't affect things either way.
7507         if (isEmptyRecord(getContext(), Base, true))
7508           continue;
7509 
7510         if (!Found.isNull())
7511           return Ty;
7512         Found = GetSingleElementType(Base);
7513       }
7514 
7515     // Check the fields.
7516     for (const auto *FD : RD->fields()) {
7517       // For compatibility with GCC, ignore empty bitfields in C++ mode.
7518       // Unlike isSingleElementStruct(), empty structure and array fields
7519       // do count.  So do anonymous bitfields that aren't zero-sized.
7520       if (getContext().getLangOpts().CPlusPlus &&
7521           FD->isZeroLengthBitField(getContext()))
7522         continue;
7523       // Like isSingleElementStruct(), ignore C++20 empty data members.
7524       if (FD->hasAttr<NoUniqueAddressAttr>() &&
7525           isEmptyRecord(getContext(), FD->getType(), true))
7526         continue;
7527 
7528       // Unlike isSingleElementStruct(), arrays do not count.
7529       // Nested structures still do though.
7530       if (!Found.isNull())
7531         return Ty;
7532       Found = GetSingleElementType(FD->getType());
7533     }
7534 
7535     // Unlike isSingleElementStruct(), trailing padding is allowed.
7536     // An 8-byte aligned struct s { float f; } is passed as a double.
7537     if (!Found.isNull())
7538       return Found;
7539   }
7540 
7541   return Ty;
7542 }
7543 
7544 Address SystemZABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7545                                   QualType Ty) const {
7546   // Assume that va_list type is correct; should be pointer to LLVM type:
7547   // struct {
7548   //   i64 __gpr;
7549   //   i64 __fpr;
7550   //   i8 *__overflow_arg_area;
7551   //   i8 *__reg_save_area;
7552   // };
7553 
7554   // Every non-vector argument occupies 8 bytes and is passed by preference
7555   // in either GPRs or FPRs.  Vector arguments occupy 8 or 16 bytes and are
7556   // always passed on the stack.
7557   Ty = getContext().getCanonicalType(Ty);
7558   auto TyInfo = getContext().getTypeInfoInChars(Ty);
7559   llvm::Type *ArgTy = CGF.ConvertTypeForMem(Ty);
7560   llvm::Type *DirectTy = ArgTy;
7561   ABIArgInfo AI = classifyArgumentType(Ty);
7562   bool IsIndirect = AI.isIndirect();
7563   bool InFPRs = false;
7564   bool IsVector = false;
7565   CharUnits UnpaddedSize;
7566   CharUnits DirectAlign;
7567   if (IsIndirect) {
7568     DirectTy = llvm::PointerType::getUnqual(DirectTy);
7569     UnpaddedSize = DirectAlign = CharUnits::fromQuantity(8);
7570   } else {
7571     if (AI.getCoerceToType())
7572       ArgTy = AI.getCoerceToType();
7573     InFPRs = (!IsSoftFloatABI && (ArgTy->isFloatTy() || ArgTy->isDoubleTy()));
7574     IsVector = ArgTy->isVectorTy();
7575     UnpaddedSize = TyInfo.Width;
7576     DirectAlign = TyInfo.Align;
7577   }
7578   CharUnits PaddedSize = CharUnits::fromQuantity(8);
7579   if (IsVector && UnpaddedSize > PaddedSize)
7580     PaddedSize = CharUnits::fromQuantity(16);
7581   assert((UnpaddedSize <= PaddedSize) && "Invalid argument size.");
7582 
7583   CharUnits Padding = (PaddedSize - UnpaddedSize);
7584 
7585   llvm::Type *IndexTy = CGF.Int64Ty;
7586   llvm::Value *PaddedSizeV =
7587     llvm::ConstantInt::get(IndexTy, PaddedSize.getQuantity());
7588 
7589   if (IsVector) {
7590     // Work out the address of a vector argument on the stack.
7591     // Vector arguments are always passed in the high bits of a
7592     // single (8 byte) or double (16 byte) stack slot.
7593     Address OverflowArgAreaPtr =
7594         CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr");
7595     Address OverflowArgArea =
7596         Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
7597                 CGF.Int8Ty, TyInfo.Align);
7598     Address MemAddr =
7599         CGF.Builder.CreateElementBitCast(OverflowArgArea, DirectTy, "mem_addr");
7600 
7601     // Update overflow_arg_area_ptr pointer
7602     llvm::Value *NewOverflowArgArea = CGF.Builder.CreateGEP(
7603         OverflowArgArea.getElementType(), OverflowArgArea.getPointer(),
7604         PaddedSizeV, "overflow_arg_area");
7605     CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
7606 
7607     return MemAddr;
7608   }
7609 
7610   assert(PaddedSize.getQuantity() == 8);
7611 
7612   unsigned MaxRegs, RegCountField, RegSaveIndex;
7613   CharUnits RegPadding;
7614   if (InFPRs) {
7615     MaxRegs = 4; // Maximum of 4 FPR arguments
7616     RegCountField = 1; // __fpr
7617     RegSaveIndex = 16; // save offset for f0
7618     RegPadding = CharUnits(); // floats are passed in the high bits of an FPR
7619   } else {
7620     MaxRegs = 5; // Maximum of 5 GPR arguments
7621     RegCountField = 0; // __gpr
7622     RegSaveIndex = 2; // save offset for r2
7623     RegPadding = Padding; // values are passed in the low bits of a GPR
7624   }
7625 
7626   Address RegCountPtr =
7627       CGF.Builder.CreateStructGEP(VAListAddr, RegCountField, "reg_count_ptr");
7628   llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
7629   llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
7630   llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
7631                                                  "fits_in_regs");
7632 
7633   llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
7634   llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
7635   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
7636   CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
7637 
7638   // Emit code to load the value if it was passed in registers.
7639   CGF.EmitBlock(InRegBlock);
7640 
7641   // Work out the address of an argument register.
7642   llvm::Value *ScaledRegCount =
7643     CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
7644   llvm::Value *RegBase =
7645     llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize.getQuantity()
7646                                       + RegPadding.getQuantity());
7647   llvm::Value *RegOffset =
7648     CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
7649   Address RegSaveAreaPtr =
7650       CGF.Builder.CreateStructGEP(VAListAddr, 3, "reg_save_area_ptr");
7651   llvm::Value *RegSaveArea =
7652       CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
7653   Address RawRegAddr(
7654       CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, RegOffset, "raw_reg_addr"),
7655       CGF.Int8Ty, PaddedSize);
7656   Address RegAddr =
7657       CGF.Builder.CreateElementBitCast(RawRegAddr, DirectTy, "reg_addr");
7658 
7659   // Update the register count
7660   llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
7661   llvm::Value *NewRegCount =
7662     CGF.Builder.CreateAdd(RegCount, One, "reg_count");
7663   CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
7664   CGF.EmitBranch(ContBlock);
7665 
7666   // Emit code to load the value if it was passed in memory.
7667   CGF.EmitBlock(InMemBlock);
7668 
7669   // Work out the address of a stack argument.
7670   Address OverflowArgAreaPtr =
7671       CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr");
7672   Address OverflowArgArea =
7673       Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
7674               CGF.Int8Ty, PaddedSize);
7675   Address RawMemAddr =
7676       CGF.Builder.CreateConstByteGEP(OverflowArgArea, Padding, "raw_mem_addr");
7677   Address MemAddr =
7678     CGF.Builder.CreateElementBitCast(RawMemAddr, DirectTy, "mem_addr");
7679 
7680   // Update overflow_arg_area_ptr pointer
7681   llvm::Value *NewOverflowArgArea =
7682     CGF.Builder.CreateGEP(OverflowArgArea.getElementType(),
7683                           OverflowArgArea.getPointer(), PaddedSizeV,
7684                           "overflow_arg_area");
7685   CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
7686   CGF.EmitBranch(ContBlock);
7687 
7688   // Return the appropriate result.
7689   CGF.EmitBlock(ContBlock);
7690   Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, MemAddr, InMemBlock,
7691                                  "va_arg.addr");
7692 
7693   if (IsIndirect)
7694     ResAddr = Address(CGF.Builder.CreateLoad(ResAddr, "indirect_arg"), ArgTy,
7695                       TyInfo.Align);
7696 
7697   return ResAddr;
7698 }
7699 
7700 ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
7701   if (RetTy->isVoidType())
7702     return ABIArgInfo::getIgnore();
7703   if (isVectorArgumentType(RetTy))
7704     return ABIArgInfo::getDirect();
7705   if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
7706     return getNaturalAlignIndirect(RetTy);
7707   return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
7708                                                : ABIArgInfo::getDirect());
7709 }
7710 
7711 ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
7712   // Handle the generic C++ ABI.
7713   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
7714     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
7715 
7716   // Integers and enums are extended to full register width.
7717   if (isPromotableIntegerTypeForABI(Ty))
7718     return ABIArgInfo::getExtend(Ty);
7719 
7720   // Handle vector types and vector-like structure types.  Note that
7721   // as opposed to float-like structure types, we do not allow any
7722   // padding for vector-like structures, so verify the sizes match.
7723   uint64_t Size = getContext().getTypeSize(Ty);
7724   QualType SingleElementTy = GetSingleElementType(Ty);
7725   if (isVectorArgumentType(SingleElementTy) &&
7726       getContext().getTypeSize(SingleElementTy) == Size)
7727     return ABIArgInfo::getDirect(CGT.ConvertType(SingleElementTy));
7728 
7729   // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
7730   if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
7731     return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
7732 
7733   // Handle small structures.
7734   if (const RecordType *RT = Ty->getAs<RecordType>()) {
7735     // Structures with flexible arrays have variable length, so really
7736     // fail the size test above.
7737     const RecordDecl *RD = RT->getDecl();
7738     if (RD->hasFlexibleArrayMember())
7739       return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
7740 
7741     // The structure is passed as an unextended integer, a float, or a double.
7742     llvm::Type *PassTy;
7743     if (isFPArgumentType(SingleElementTy)) {
7744       assert(Size == 32 || Size == 64);
7745       if (Size == 32)
7746         PassTy = llvm::Type::getFloatTy(getVMContext());
7747       else
7748         PassTy = llvm::Type::getDoubleTy(getVMContext());
7749     } else
7750       PassTy = llvm::IntegerType::get(getVMContext(), Size);
7751     return ABIArgInfo::getDirect(PassTy);
7752   }
7753 
7754   // Non-structure compounds are passed indirectly.
7755   if (isCompoundType(Ty))
7756     return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
7757 
7758   return ABIArgInfo::getDirect(nullptr);
7759 }
7760 
7761 //===----------------------------------------------------------------------===//
7762 // MSP430 ABI Implementation
7763 //===----------------------------------------------------------------------===//
7764 
7765 namespace {
7766 
7767 class MSP430ABIInfo : public DefaultABIInfo {
7768   static ABIArgInfo complexArgInfo() {
7769     ABIArgInfo Info = ABIArgInfo::getDirect();
7770     Info.setCanBeFlattened(false);
7771     return Info;
7772   }
7773 
7774 public:
7775   MSP430ABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
7776 
7777   ABIArgInfo classifyReturnType(QualType RetTy) const {
7778     if (RetTy->isAnyComplexType())
7779       return complexArgInfo();
7780 
7781     return DefaultABIInfo::classifyReturnType(RetTy);
7782   }
7783 
7784   ABIArgInfo classifyArgumentType(QualType RetTy) const {
7785     if (RetTy->isAnyComplexType())
7786       return complexArgInfo();
7787 
7788     return DefaultABIInfo::classifyArgumentType(RetTy);
7789   }
7790 
7791   // Just copy the original implementations because
7792   // DefaultABIInfo::classify{Return,Argument}Type() are not virtual
7793   void computeInfo(CGFunctionInfo &FI) const override {
7794     if (!getCXXABI().classifyReturnType(FI))
7795       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7796     for (auto &I : FI.arguments())
7797       I.info = classifyArgumentType(I.type);
7798   }
7799 
7800   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7801                     QualType Ty) const override {
7802     return EmitVAArgInstr(CGF, VAListAddr, Ty, classifyArgumentType(Ty));
7803   }
7804 };
7805 
7806 class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
7807 public:
7808   MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
7809       : TargetCodeGenInfo(std::make_unique<MSP430ABIInfo>(CGT)) {}
7810   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
7811                            CodeGen::CodeGenModule &M) const override;
7812 };
7813 
7814 }
7815 
7816 void MSP430TargetCodeGenInfo::setTargetAttributes(
7817     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
7818   if (GV->isDeclaration())
7819     return;
7820   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
7821     const auto *InterruptAttr = FD->getAttr<MSP430InterruptAttr>();
7822     if (!InterruptAttr)
7823       return;
7824 
7825     // Handle 'interrupt' attribute:
7826     llvm::Function *F = cast<llvm::Function>(GV);
7827 
7828     // Step 1: Set ISR calling convention.
7829     F->setCallingConv(llvm::CallingConv::MSP430_INTR);
7830 
7831     // Step 2: Add attributes goodness.
7832     F->addFnAttr(llvm::Attribute::NoInline);
7833     F->addFnAttr("interrupt", llvm::utostr(InterruptAttr->getNumber()));
7834   }
7835 }
7836 
7837 //===----------------------------------------------------------------------===//
7838 // MIPS ABI Implementation.  This works for both little-endian and
7839 // big-endian variants.
7840 //===----------------------------------------------------------------------===//
7841 
7842 namespace {
7843 class MipsABIInfo : public ABIInfo {
7844   bool IsO32;
7845   unsigned MinABIStackAlignInBytes, StackAlignInBytes;
7846   void CoerceToIntArgs(uint64_t TySize,
7847                        SmallVectorImpl<llvm::Type *> &ArgList) const;
7848   llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
7849   llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
7850   llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
7851 public:
7852   MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
7853     ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
7854     StackAlignInBytes(IsO32 ? 8 : 16) {}
7855 
7856   ABIArgInfo classifyReturnType(QualType RetTy) const;
7857   ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
7858   void computeInfo(CGFunctionInfo &FI) const override;
7859   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7860                     QualType Ty) const override;
7861   ABIArgInfo extendType(QualType Ty) const;
7862 };
7863 
7864 class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
7865   unsigned SizeOfUnwindException;
7866 public:
7867   MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
7868       : TargetCodeGenInfo(std::make_unique<MipsABIInfo>(CGT, IsO32)),
7869         SizeOfUnwindException(IsO32 ? 24 : 32) {}
7870 
7871   int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
7872     return 29;
7873   }
7874 
7875   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
7876                            CodeGen::CodeGenModule &CGM) const override {
7877     const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
7878     if (!FD) return;
7879     llvm::Function *Fn = cast<llvm::Function>(GV);
7880 
7881     if (FD->hasAttr<MipsLongCallAttr>())
7882       Fn->addFnAttr("long-call");
7883     else if (FD->hasAttr<MipsShortCallAttr>())
7884       Fn->addFnAttr("short-call");
7885 
7886     // Other attributes do not have a meaning for declarations.
7887     if (GV->isDeclaration())
7888       return;
7889 
7890     if (FD->hasAttr<Mips16Attr>()) {
7891       Fn->addFnAttr("mips16");
7892     }
7893     else if (FD->hasAttr<NoMips16Attr>()) {
7894       Fn->addFnAttr("nomips16");
7895     }
7896 
7897     if (FD->hasAttr<MicroMipsAttr>())
7898       Fn->addFnAttr("micromips");
7899     else if (FD->hasAttr<NoMicroMipsAttr>())
7900       Fn->addFnAttr("nomicromips");
7901 
7902     const MipsInterruptAttr *Attr = FD->getAttr<MipsInterruptAttr>();
7903     if (!Attr)
7904       return;
7905 
7906     const char *Kind;
7907     switch (Attr->getInterrupt()) {
7908     case MipsInterruptAttr::eic:     Kind = "eic"; break;
7909     case MipsInterruptAttr::sw0:     Kind = "sw0"; break;
7910     case MipsInterruptAttr::sw1:     Kind = "sw1"; break;
7911     case MipsInterruptAttr::hw0:     Kind = "hw0"; break;
7912     case MipsInterruptAttr::hw1:     Kind = "hw1"; break;
7913     case MipsInterruptAttr::hw2:     Kind = "hw2"; break;
7914     case MipsInterruptAttr::hw3:     Kind = "hw3"; break;
7915     case MipsInterruptAttr::hw4:     Kind = "hw4"; break;
7916     case MipsInterruptAttr::hw5:     Kind = "hw5"; break;
7917     }
7918 
7919     Fn->addFnAttr("interrupt", Kind);
7920 
7921   }
7922 
7923   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
7924                                llvm::Value *Address) const override;
7925 
7926   unsigned getSizeOfUnwindException() const override {
7927     return SizeOfUnwindException;
7928   }
7929 };
7930 }
7931 
7932 void MipsABIInfo::CoerceToIntArgs(
7933     uint64_t TySize, SmallVectorImpl<llvm::Type *> &ArgList) const {
7934   llvm::IntegerType *IntTy =
7935     llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
7936 
7937   // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
7938   for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
7939     ArgList.push_back(IntTy);
7940 
7941   // If necessary, add one more integer type to ArgList.
7942   unsigned R = TySize % (MinABIStackAlignInBytes * 8);
7943 
7944   if (R)
7945     ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
7946 }
7947 
7948 // In N32/64, an aligned double precision floating point field is passed in
7949 // a register.
7950 llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
7951   SmallVector<llvm::Type*, 8> ArgList, IntArgList;
7952 
7953   if (IsO32) {
7954     CoerceToIntArgs(TySize, ArgList);
7955     return llvm::StructType::get(getVMContext(), ArgList);
7956   }
7957 
7958   if (Ty->isComplexType())
7959     return CGT.ConvertType(Ty);
7960 
7961   const RecordType *RT = Ty->getAs<RecordType>();
7962 
7963   // Unions/vectors are passed in integer registers.
7964   if (!RT || !RT->isStructureOrClassType()) {
7965     CoerceToIntArgs(TySize, ArgList);
7966     return llvm::StructType::get(getVMContext(), ArgList);
7967   }
7968 
7969   const RecordDecl *RD = RT->getDecl();
7970   const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
7971   assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
7972 
7973   uint64_t LastOffset = 0;
7974   unsigned idx = 0;
7975   llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
7976 
7977   // Iterate over fields in the struct/class and check if there are any aligned
7978   // double fields.
7979   for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
7980        i != e; ++i, ++idx) {
7981     const QualType Ty = i->getType();
7982     const BuiltinType *BT = Ty->getAs<BuiltinType>();
7983 
7984     if (!BT || BT->getKind() != BuiltinType::Double)
7985       continue;
7986 
7987     uint64_t Offset = Layout.getFieldOffset(idx);
7988     if (Offset % 64) // Ignore doubles that are not aligned.
7989       continue;
7990 
7991     // Add ((Offset - LastOffset) / 64) args of type i64.
7992     for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
7993       ArgList.push_back(I64);
7994 
7995     // Add double type.
7996     ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
7997     LastOffset = Offset + 64;
7998   }
7999 
8000   CoerceToIntArgs(TySize - LastOffset, IntArgList);
8001   ArgList.append(IntArgList.begin(), IntArgList.end());
8002 
8003   return llvm::StructType::get(getVMContext(), ArgList);
8004 }
8005 
8006 llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
8007                                         uint64_t Offset) const {
8008   if (OrigOffset + MinABIStackAlignInBytes > Offset)
8009     return nullptr;
8010 
8011   return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
8012 }
8013 
8014 ABIArgInfo
8015 MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
8016   Ty = useFirstFieldIfTransparentUnion(Ty);
8017 
8018   uint64_t OrigOffset = Offset;
8019   uint64_t TySize = getContext().getTypeSize(Ty);
8020   uint64_t Align = getContext().getTypeAlign(Ty) / 8;
8021 
8022   Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
8023                    (uint64_t)StackAlignInBytes);
8024   unsigned CurrOffset = llvm::alignTo(Offset, Align);
8025   Offset = CurrOffset + llvm::alignTo(TySize, Align * 8) / 8;
8026 
8027   if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
8028     // Ignore empty aggregates.
8029     if (TySize == 0)
8030       return ABIArgInfo::getIgnore();
8031 
8032     if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
8033       Offset = OrigOffset + MinABIStackAlignInBytes;
8034       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
8035     }
8036 
8037     // If we have reached here, aggregates are passed directly by coercing to
8038     // another structure type. Padding is inserted if the offset of the
8039     // aggregate is unaligned.
8040     ABIArgInfo ArgInfo =
8041         ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
8042                               getPaddingType(OrigOffset, CurrOffset));
8043     ArgInfo.setInReg(true);
8044     return ArgInfo;
8045   }
8046 
8047   // Treat an enum type as its underlying type.
8048   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
8049     Ty = EnumTy->getDecl()->getIntegerType();
8050 
8051   // Make sure we pass indirectly things that are too large.
8052   if (const auto *EIT = Ty->getAs<BitIntType>())
8053     if (EIT->getNumBits() > 128 ||
8054         (EIT->getNumBits() > 64 &&
8055          !getContext().getTargetInfo().hasInt128Type()))
8056       return getNaturalAlignIndirect(Ty);
8057 
8058   // All integral types are promoted to the GPR width.
8059   if (Ty->isIntegralOrEnumerationType())
8060     return extendType(Ty);
8061 
8062   return ABIArgInfo::getDirect(
8063       nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset));
8064 }
8065 
8066 llvm::Type*
8067 MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
8068   const RecordType *RT = RetTy->getAs<RecordType>();
8069   SmallVector<llvm::Type*, 8> RTList;
8070 
8071   if (RT && RT->isStructureOrClassType()) {
8072     const RecordDecl *RD = RT->getDecl();
8073     const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
8074     unsigned FieldCnt = Layout.getFieldCount();
8075 
8076     // N32/64 returns struct/classes in floating point registers if the
8077     // following conditions are met:
8078     // 1. The size of the struct/class is no larger than 128-bit.
8079     // 2. The struct/class has one or two fields all of which are floating
8080     //    point types.
8081     // 3. The offset of the first field is zero (this follows what gcc does).
8082     //
8083     // Any other composite results are returned in integer registers.
8084     //
8085     if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
8086       RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
8087       for (; b != e; ++b) {
8088         const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
8089 
8090         if (!BT || !BT->isFloatingPoint())
8091           break;
8092 
8093         RTList.push_back(CGT.ConvertType(b->getType()));
8094       }
8095 
8096       if (b == e)
8097         return llvm::StructType::get(getVMContext(), RTList,
8098                                      RD->hasAttr<PackedAttr>());
8099 
8100       RTList.clear();
8101     }
8102   }
8103 
8104   CoerceToIntArgs(Size, RTList);
8105   return llvm::StructType::get(getVMContext(), RTList);
8106 }
8107 
8108 ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
8109   uint64_t Size = getContext().getTypeSize(RetTy);
8110 
8111   if (RetTy->isVoidType())
8112     return ABIArgInfo::getIgnore();
8113 
8114   // O32 doesn't treat zero-sized structs differently from other structs.
8115   // However, N32/N64 ignores zero sized return values.
8116   if (!IsO32 && Size == 0)
8117     return ABIArgInfo::getIgnore();
8118 
8119   if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
8120     if (Size <= 128) {
8121       if (RetTy->isAnyComplexType())
8122         return ABIArgInfo::getDirect();
8123 
8124       // O32 returns integer vectors in registers and N32/N64 returns all small
8125       // aggregates in registers.
8126       if (!IsO32 ||
8127           (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) {
8128         ABIArgInfo ArgInfo =
8129             ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
8130         ArgInfo.setInReg(true);
8131         return ArgInfo;
8132       }
8133     }
8134 
8135     return getNaturalAlignIndirect(RetTy);
8136   }
8137 
8138   // Treat an enum type as its underlying type.
8139   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
8140     RetTy = EnumTy->getDecl()->getIntegerType();
8141 
8142   // Make sure we pass indirectly things that are too large.
8143   if (const auto *EIT = RetTy->getAs<BitIntType>())
8144     if (EIT->getNumBits() > 128 ||
8145         (EIT->getNumBits() > 64 &&
8146          !getContext().getTargetInfo().hasInt128Type()))
8147       return getNaturalAlignIndirect(RetTy);
8148 
8149   if (isPromotableIntegerTypeForABI(RetTy))
8150     return ABIArgInfo::getExtend(RetTy);
8151 
8152   if ((RetTy->isUnsignedIntegerOrEnumerationType() ||
8153       RetTy->isSignedIntegerOrEnumerationType()) && Size == 32 && !IsO32)
8154     return ABIArgInfo::getSignExtend(RetTy);
8155 
8156   return ABIArgInfo::getDirect();
8157 }
8158 
8159 void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
8160   ABIArgInfo &RetInfo = FI.getReturnInfo();
8161   if (!getCXXABI().classifyReturnType(FI))
8162     RetInfo = classifyReturnType(FI.getReturnType());
8163 
8164   // Check if a pointer to an aggregate is passed as a hidden argument.
8165   uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
8166 
8167   for (auto &I : FI.arguments())
8168     I.info = classifyArgumentType(I.type, Offset);
8169 }
8170 
8171 Address MipsABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8172                                QualType OrigTy) const {
8173   QualType Ty = OrigTy;
8174 
8175   // Integer arguments are promoted to 32-bit on O32 and 64-bit on N32/N64.
8176   // Pointers are also promoted in the same way but this only matters for N32.
8177   unsigned SlotSizeInBits = IsO32 ? 32 : 64;
8178   unsigned PtrWidth = getTarget().getPointerWidth(0);
8179   bool DidPromote = false;
8180   if ((Ty->isIntegerType() &&
8181           getContext().getIntWidth(Ty) < SlotSizeInBits) ||
8182       (Ty->isPointerType() && PtrWidth < SlotSizeInBits)) {
8183     DidPromote = true;
8184     Ty = getContext().getIntTypeForBitwidth(SlotSizeInBits,
8185                                             Ty->isSignedIntegerType());
8186   }
8187 
8188   auto TyInfo = getContext().getTypeInfoInChars(Ty);
8189 
8190   // The alignment of things in the argument area is never larger than
8191   // StackAlignInBytes.
8192   TyInfo.Align =
8193     std::min(TyInfo.Align, CharUnits::fromQuantity(StackAlignInBytes));
8194 
8195   // MinABIStackAlignInBytes is the size of argument slots on the stack.
8196   CharUnits ArgSlotSize = CharUnits::fromQuantity(MinABIStackAlignInBytes);
8197 
8198   Address Addr = emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
8199                           TyInfo, ArgSlotSize, /*AllowHigherAlign*/ true);
8200 
8201 
8202   // If there was a promotion, "unpromote" into a temporary.
8203   // TODO: can we just use a pointer into a subset of the original slot?
8204   if (DidPromote) {
8205     Address Temp = CGF.CreateMemTemp(OrigTy, "vaarg.promotion-temp");
8206     llvm::Value *Promoted = CGF.Builder.CreateLoad(Addr);
8207 
8208     // Truncate down to the right width.
8209     llvm::Type *IntTy = (OrigTy->isIntegerType() ? Temp.getElementType()
8210                                                  : CGF.IntPtrTy);
8211     llvm::Value *V = CGF.Builder.CreateTrunc(Promoted, IntTy);
8212     if (OrigTy->isPointerType())
8213       V = CGF.Builder.CreateIntToPtr(V, Temp.getElementType());
8214 
8215     CGF.Builder.CreateStore(V, Temp);
8216     Addr = Temp;
8217   }
8218 
8219   return Addr;
8220 }
8221 
8222 ABIArgInfo MipsABIInfo::extendType(QualType Ty) const {
8223   int TySize = getContext().getTypeSize(Ty);
8224 
8225   // MIPS64 ABI requires unsigned 32 bit integers to be sign extended.
8226   if (Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
8227     return ABIArgInfo::getSignExtend(Ty);
8228 
8229   return ABIArgInfo::getExtend(Ty);
8230 }
8231 
8232 bool
8233 MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
8234                                                llvm::Value *Address) const {
8235   // This information comes from gcc's implementation, which seems to
8236   // as canonical as it gets.
8237 
8238   // Everything on MIPS is 4 bytes.  Double-precision FP registers
8239   // are aliased to pairs of single-precision FP registers.
8240   llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
8241 
8242   // 0-31 are the general purpose registers, $0 - $31.
8243   // 32-63 are the floating-point registers, $f0 - $f31.
8244   // 64 and 65 are the multiply/divide registers, $hi and $lo.
8245   // 66 is the (notional, I think) register for signal-handler return.
8246   AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
8247 
8248   // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
8249   // They are one bit wide and ignored here.
8250 
8251   // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
8252   // (coprocessor 1 is the FP unit)
8253   // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
8254   // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
8255   // 176-181 are the DSP accumulator registers.
8256   AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
8257   return false;
8258 }
8259 
8260 //===----------------------------------------------------------------------===//
8261 // M68k ABI Implementation
8262 //===----------------------------------------------------------------------===//
8263 
8264 namespace {
8265 
8266 class M68kTargetCodeGenInfo : public TargetCodeGenInfo {
8267 public:
8268   M68kTargetCodeGenInfo(CodeGenTypes &CGT)
8269       : TargetCodeGenInfo(std::make_unique<DefaultABIInfo>(CGT)) {}
8270   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
8271                            CodeGen::CodeGenModule &M) const override;
8272 };
8273 
8274 } // namespace
8275 
8276 void M68kTargetCodeGenInfo::setTargetAttributes(
8277     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
8278   if (const auto *FD = dyn_cast_or_null<FunctionDecl>(D)) {
8279     if (const auto *attr = FD->getAttr<M68kInterruptAttr>()) {
8280       // Handle 'interrupt' attribute:
8281       llvm::Function *F = cast<llvm::Function>(GV);
8282 
8283       // Step 1: Set ISR calling convention.
8284       F->setCallingConv(llvm::CallingConv::M68k_INTR);
8285 
8286       // Step 2: Add attributes goodness.
8287       F->addFnAttr(llvm::Attribute::NoInline);
8288 
8289       // Step 3: Emit ISR vector alias.
8290       unsigned Num = attr->getNumber() / 2;
8291       llvm::GlobalAlias::create(llvm::Function::ExternalLinkage,
8292                                 "__isr_" + Twine(Num), F);
8293     }
8294   }
8295 }
8296 
8297 //===----------------------------------------------------------------------===//
8298 // AVR ABI Implementation. Documented at
8299 // https://gcc.gnu.org/wiki/avr-gcc#Calling_Convention
8300 // https://gcc.gnu.org/wiki/avr-gcc#Reduced_Tiny
8301 //===----------------------------------------------------------------------===//
8302 
8303 namespace {
8304 class AVRABIInfo : public DefaultABIInfo {
8305 private:
8306   // The total amount of registers can be used to pass parameters. It is 18 on
8307   // AVR, or 6 on AVRTiny.
8308   const unsigned ParamRegs;
8309   // The total amount of registers can be used to pass return value. It is 8 on
8310   // AVR, or 4 on AVRTiny.
8311   const unsigned RetRegs;
8312 
8313 public:
8314   AVRABIInfo(CodeGenTypes &CGT, unsigned NPR, unsigned NRR)
8315       : DefaultABIInfo(CGT), ParamRegs(NPR), RetRegs(NRR) {}
8316 
8317   ABIArgInfo classifyReturnType(QualType Ty, bool &LargeRet) const {
8318     if (isAggregateTypeForABI(Ty)) {
8319       // On AVR, a return struct with size less than or equals to 8 bytes is
8320       // returned directly via registers R18-R25. On AVRTiny, a return struct
8321       // with size less than or equals to 4 bytes is returned directly via
8322       // registers R22-R25.
8323       if (getContext().getTypeSize(Ty) <= RetRegs * 8)
8324         return ABIArgInfo::getDirect();
8325       // A return struct with larger size is returned via a stack
8326       // slot, along with a pointer to it as the function's implicit argument.
8327       LargeRet = true;
8328       return getNaturalAlignIndirect(Ty);
8329     }
8330     // Otherwise we follow the default way which is compatible.
8331     return DefaultABIInfo::classifyReturnType(Ty);
8332   }
8333 
8334   ABIArgInfo classifyArgumentType(QualType Ty, unsigned &NumRegs) const {
8335     unsigned TySize = getContext().getTypeSize(Ty);
8336 
8337     // An int8 type argument always costs two registers like an int16.
8338     if (TySize == 8 && NumRegs >= 2) {
8339       NumRegs -= 2;
8340       return ABIArgInfo::getExtend(Ty);
8341     }
8342 
8343     // If the argument size is an odd number of bytes, round up the size
8344     // to the next even number.
8345     TySize = llvm::alignTo(TySize, 16);
8346 
8347     // Any type including an array/struct type can be passed in rgisters,
8348     // if there are enough registers left.
8349     if (TySize <= NumRegs * 8) {
8350       NumRegs -= TySize / 8;
8351       return ABIArgInfo::getDirect();
8352     }
8353 
8354     // An argument is passed either completely in registers or completely in
8355     // memory. Since there are not enough registers left, current argument
8356     // and all other unprocessed arguments should be passed in memory.
8357     // However we still need to return `ABIArgInfo::getDirect()` other than
8358     // `ABIInfo::getNaturalAlignIndirect(Ty)`, otherwise an extra stack slot
8359     // will be allocated, so the stack frame layout will be incompatible with
8360     // avr-gcc.
8361     NumRegs = 0;
8362     return ABIArgInfo::getDirect();
8363   }
8364 
8365   void computeInfo(CGFunctionInfo &FI) const override {
8366     // Decide the return type.
8367     bool LargeRet = false;
8368     if (!getCXXABI().classifyReturnType(FI))
8369       FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), LargeRet);
8370 
8371     // Decide each argument type. The total number of registers can be used for
8372     // arguments depends on several factors:
8373     // 1. Arguments of varargs functions are passed on the stack. This applies
8374     //    even to the named arguments. So no register can be used.
8375     // 2. Total 18 registers can be used on avr and 6 ones on avrtiny.
8376     // 3. If the return type is a struct with too large size, two registers
8377     //    (out of 18/6) will be cost as an implicit pointer argument.
8378     unsigned NumRegs = ParamRegs;
8379     if (FI.isVariadic())
8380       NumRegs = 0;
8381     else if (LargeRet)
8382       NumRegs -= 2;
8383     for (auto &I : FI.arguments())
8384       I.info = classifyArgumentType(I.type, NumRegs);
8385   }
8386 };
8387 
8388 class AVRTargetCodeGenInfo : public TargetCodeGenInfo {
8389 public:
8390   AVRTargetCodeGenInfo(CodeGenTypes &CGT, unsigned NPR, unsigned NRR)
8391       : TargetCodeGenInfo(std::make_unique<AVRABIInfo>(CGT, NPR, NRR)) {}
8392 
8393   LangAS getGlobalVarAddressSpace(CodeGenModule &CGM,
8394                                   const VarDecl *D) const override {
8395     // Check if global/static variable is defined in address space
8396     // 1~6 (__flash, __flash1, __flash2, __flash3, __flash4, __flash5)
8397     // but not constant.
8398     if (D) {
8399       LangAS AS = D->getType().getAddressSpace();
8400       if (isTargetAddressSpace(AS) && 1 <= toTargetAddressSpace(AS) &&
8401           toTargetAddressSpace(AS) <= 6 && !D->getType().isConstQualified())
8402         CGM.getDiags().Report(D->getLocation(),
8403                               diag::err_verify_nonconst_addrspace)
8404             << "__flash*";
8405     }
8406     return TargetCodeGenInfo::getGlobalVarAddressSpace(CGM, D);
8407   }
8408 
8409   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
8410                            CodeGen::CodeGenModule &CGM) const override {
8411     if (GV->isDeclaration())
8412       return;
8413     const auto *FD = dyn_cast_or_null<FunctionDecl>(D);
8414     if (!FD) return;
8415     auto *Fn = cast<llvm::Function>(GV);
8416 
8417     if (FD->getAttr<AVRInterruptAttr>())
8418       Fn->addFnAttr("interrupt");
8419 
8420     if (FD->getAttr<AVRSignalAttr>())
8421       Fn->addFnAttr("signal");
8422   }
8423 };
8424 }
8425 
8426 //===----------------------------------------------------------------------===//
8427 // TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
8428 // Currently subclassed only to implement custom OpenCL C function attribute
8429 // handling.
8430 //===----------------------------------------------------------------------===//
8431 
8432 namespace {
8433 
8434 class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
8435 public:
8436   TCETargetCodeGenInfo(CodeGenTypes &CGT)
8437     : DefaultTargetCodeGenInfo(CGT) {}
8438 
8439   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
8440                            CodeGen::CodeGenModule &M) const override;
8441 };
8442 
8443 void TCETargetCodeGenInfo::setTargetAttributes(
8444     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
8445   if (GV->isDeclaration())
8446     return;
8447   const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
8448   if (!FD) return;
8449 
8450   llvm::Function *F = cast<llvm::Function>(GV);
8451 
8452   if (M.getLangOpts().OpenCL) {
8453     if (FD->hasAttr<OpenCLKernelAttr>()) {
8454       // OpenCL C Kernel functions are not subject to inlining
8455       F->addFnAttr(llvm::Attribute::NoInline);
8456       const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
8457       if (Attr) {
8458         // Convert the reqd_work_group_size() attributes to metadata.
8459         llvm::LLVMContext &Context = F->getContext();
8460         llvm::NamedMDNode *OpenCLMetadata =
8461             M.getModule().getOrInsertNamedMetadata(
8462                 "opencl.kernel_wg_size_info");
8463 
8464         SmallVector<llvm::Metadata *, 5> Operands;
8465         Operands.push_back(llvm::ConstantAsMetadata::get(F));
8466 
8467         Operands.push_back(
8468             llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
8469                 M.Int32Ty, llvm::APInt(32, Attr->getXDim()))));
8470         Operands.push_back(
8471             llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
8472                 M.Int32Ty, llvm::APInt(32, Attr->getYDim()))));
8473         Operands.push_back(
8474             llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
8475                 M.Int32Ty, llvm::APInt(32, Attr->getZDim()))));
8476 
8477         // Add a boolean constant operand for "required" (true) or "hint"
8478         // (false) for implementing the work_group_size_hint attr later.
8479         // Currently always true as the hint is not yet implemented.
8480         Operands.push_back(
8481             llvm::ConstantAsMetadata::get(llvm::ConstantInt::getTrue(Context)));
8482         OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
8483       }
8484     }
8485   }
8486 }
8487 
8488 }
8489 
8490 //===----------------------------------------------------------------------===//
8491 // Hexagon ABI Implementation
8492 //===----------------------------------------------------------------------===//
8493 
8494 namespace {
8495 
8496 class HexagonABIInfo : public DefaultABIInfo {
8497 public:
8498   HexagonABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
8499 
8500 private:
8501   ABIArgInfo classifyReturnType(QualType RetTy) const;
8502   ABIArgInfo classifyArgumentType(QualType RetTy) const;
8503   ABIArgInfo classifyArgumentType(QualType RetTy, unsigned *RegsLeft) const;
8504 
8505   void computeInfo(CGFunctionInfo &FI) const override;
8506 
8507   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8508                     QualType Ty) const override;
8509   Address EmitVAArgFromMemory(CodeGenFunction &CFG, Address VAListAddr,
8510                               QualType Ty) const;
8511   Address EmitVAArgForHexagon(CodeGenFunction &CFG, Address VAListAddr,
8512                               QualType Ty) const;
8513   Address EmitVAArgForHexagonLinux(CodeGenFunction &CFG, Address VAListAddr,
8514                                    QualType Ty) const;
8515 };
8516 
8517 class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
8518 public:
8519   HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
8520       : TargetCodeGenInfo(std::make_unique<HexagonABIInfo>(CGT)) {}
8521 
8522   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
8523     return 29;
8524   }
8525 
8526   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
8527                            CodeGen::CodeGenModule &GCM) const override {
8528     if (GV->isDeclaration())
8529       return;
8530     const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
8531     if (!FD)
8532       return;
8533   }
8534 };
8535 
8536 } // namespace
8537 
8538 void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
8539   unsigned RegsLeft = 6;
8540   if (!getCXXABI().classifyReturnType(FI))
8541     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
8542   for (auto &I : FI.arguments())
8543     I.info = classifyArgumentType(I.type, &RegsLeft);
8544 }
8545 
8546 static bool HexagonAdjustRegsLeft(uint64_t Size, unsigned *RegsLeft) {
8547   assert(Size <= 64 && "Not expecting to pass arguments larger than 64 bits"
8548                        " through registers");
8549 
8550   if (*RegsLeft == 0)
8551     return false;
8552 
8553   if (Size <= 32) {
8554     (*RegsLeft)--;
8555     return true;
8556   }
8557 
8558   if (2 <= (*RegsLeft & (~1U))) {
8559     *RegsLeft = (*RegsLeft & (~1U)) - 2;
8560     return true;
8561   }
8562 
8563   // Next available register was r5 but candidate was greater than 32-bits so it
8564   // has to go on the stack. However we still consume r5
8565   if (*RegsLeft == 1)
8566     *RegsLeft = 0;
8567 
8568   return false;
8569 }
8570 
8571 ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty,
8572                                                 unsigned *RegsLeft) const {
8573   if (!isAggregateTypeForABI(Ty)) {
8574     // Treat an enum type as its underlying type.
8575     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
8576       Ty = EnumTy->getDecl()->getIntegerType();
8577 
8578     uint64_t Size = getContext().getTypeSize(Ty);
8579     if (Size <= 64)
8580       HexagonAdjustRegsLeft(Size, RegsLeft);
8581 
8582     if (Size > 64 && Ty->isBitIntType())
8583       return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
8584 
8585     return isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
8586                                              : ABIArgInfo::getDirect();
8587   }
8588 
8589   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
8590     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
8591 
8592   // Ignore empty records.
8593   if (isEmptyRecord(getContext(), Ty, true))
8594     return ABIArgInfo::getIgnore();
8595 
8596   uint64_t Size = getContext().getTypeSize(Ty);
8597   unsigned Align = getContext().getTypeAlign(Ty);
8598 
8599   if (Size > 64)
8600     return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
8601 
8602   if (HexagonAdjustRegsLeft(Size, RegsLeft))
8603     Align = Size <= 32 ? 32 : 64;
8604   if (Size <= Align) {
8605     // Pass in the smallest viable integer type.
8606     if (!llvm::isPowerOf2_64(Size))
8607       Size = llvm::NextPowerOf2(Size);
8608     return ABIArgInfo::getDirect(llvm::Type::getIntNTy(getVMContext(), Size));
8609   }
8610   return DefaultABIInfo::classifyArgumentType(Ty);
8611 }
8612 
8613 ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
8614   if (RetTy->isVoidType())
8615     return ABIArgInfo::getIgnore();
8616 
8617   const TargetInfo &T = CGT.getTarget();
8618   uint64_t Size = getContext().getTypeSize(RetTy);
8619 
8620   if (RetTy->getAs<VectorType>()) {
8621     // HVX vectors are returned in vector registers or register pairs.
8622     if (T.hasFeature("hvx")) {
8623       assert(T.hasFeature("hvx-length64b") || T.hasFeature("hvx-length128b"));
8624       uint64_t VecSize = T.hasFeature("hvx-length64b") ? 64*8 : 128*8;
8625       if (Size == VecSize || Size == 2*VecSize)
8626         return ABIArgInfo::getDirectInReg();
8627     }
8628     // Large vector types should be returned via memory.
8629     if (Size > 64)
8630       return getNaturalAlignIndirect(RetTy);
8631   }
8632 
8633   if (!isAggregateTypeForABI(RetTy)) {
8634     // Treat an enum type as its underlying type.
8635     if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
8636       RetTy = EnumTy->getDecl()->getIntegerType();
8637 
8638     if (Size > 64 && RetTy->isBitIntType())
8639       return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
8640 
8641     return isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
8642                                                 : ABIArgInfo::getDirect();
8643   }
8644 
8645   if (isEmptyRecord(getContext(), RetTy, true))
8646     return ABIArgInfo::getIgnore();
8647 
8648   // Aggregates <= 8 bytes are returned in registers, other aggregates
8649   // are returned indirectly.
8650   if (Size <= 64) {
8651     // Return in the smallest viable integer type.
8652     if (!llvm::isPowerOf2_64(Size))
8653       Size = llvm::NextPowerOf2(Size);
8654     return ABIArgInfo::getDirect(llvm::Type::getIntNTy(getVMContext(), Size));
8655   }
8656   return getNaturalAlignIndirect(RetTy, /*ByVal=*/true);
8657 }
8658 
8659 Address HexagonABIInfo::EmitVAArgFromMemory(CodeGenFunction &CGF,
8660                                             Address VAListAddr,
8661                                             QualType Ty) const {
8662   // Load the overflow area pointer.
8663   Address __overflow_area_pointer_p =
8664       CGF.Builder.CreateStructGEP(VAListAddr, 2, "__overflow_area_pointer_p");
8665   llvm::Value *__overflow_area_pointer = CGF.Builder.CreateLoad(
8666       __overflow_area_pointer_p, "__overflow_area_pointer");
8667 
8668   uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8;
8669   if (Align > 4) {
8670     // Alignment should be a power of 2.
8671     assert((Align & (Align - 1)) == 0 && "Alignment is not power of 2!");
8672 
8673     // overflow_arg_area = (overflow_arg_area + align - 1) & -align;
8674     llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int64Ty, Align - 1);
8675 
8676     // Add offset to the current pointer to access the argument.
8677     __overflow_area_pointer =
8678         CGF.Builder.CreateGEP(CGF.Int8Ty, __overflow_area_pointer, Offset);
8679     llvm::Value *AsInt =
8680         CGF.Builder.CreatePtrToInt(__overflow_area_pointer, CGF.Int32Ty);
8681 
8682     // Create a mask which should be "AND"ed
8683     // with (overflow_arg_area + align - 1)
8684     llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int32Ty, -(int)Align);
8685     __overflow_area_pointer = CGF.Builder.CreateIntToPtr(
8686         CGF.Builder.CreateAnd(AsInt, Mask), __overflow_area_pointer->getType(),
8687         "__overflow_area_pointer.align");
8688   }
8689 
8690   // Get the type of the argument from memory and bitcast
8691   // overflow area pointer to the argument type.
8692   llvm::Type *PTy = CGF.ConvertTypeForMem(Ty);
8693   Address AddrTyped = CGF.Builder.CreateElementBitCast(
8694       Address(__overflow_area_pointer, CGF.Int8Ty,
8695               CharUnits::fromQuantity(Align)),
8696       PTy);
8697 
8698   // Round up to the minimum stack alignment for varargs which is 4 bytes.
8699   uint64_t Offset = llvm::alignTo(CGF.getContext().getTypeSize(Ty) / 8, 4);
8700 
8701   __overflow_area_pointer = CGF.Builder.CreateGEP(
8702       CGF.Int8Ty, __overflow_area_pointer,
8703       llvm::ConstantInt::get(CGF.Int32Ty, Offset),
8704       "__overflow_area_pointer.next");
8705   CGF.Builder.CreateStore(__overflow_area_pointer, __overflow_area_pointer_p);
8706 
8707   return AddrTyped;
8708 }
8709 
8710 Address HexagonABIInfo::EmitVAArgForHexagon(CodeGenFunction &CGF,
8711                                             Address VAListAddr,
8712                                             QualType Ty) const {
8713   // FIXME: Need to handle alignment
8714   llvm::Type *BP = CGF.Int8PtrTy;
8715   CGBuilderTy &Builder = CGF.Builder;
8716   Address VAListAddrAsBPP = Builder.CreateElementBitCast(VAListAddr, BP, "ap");
8717   llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
8718   // Handle address alignment for type alignment > 32 bits
8719   uint64_t TyAlign = CGF.getContext().getTypeAlign(Ty) / 8;
8720   if (TyAlign > 4) {
8721     assert((TyAlign & (TyAlign - 1)) == 0 && "Alignment is not power of 2!");
8722     llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int32Ty);
8723     AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt32(TyAlign - 1));
8724     AddrAsInt = Builder.CreateAnd(AddrAsInt, Builder.getInt32(~(TyAlign - 1)));
8725     Addr = Builder.CreateIntToPtr(AddrAsInt, BP);
8726   }
8727   Address AddrTyped = Builder.CreateElementBitCast(
8728       Address(Addr, CGF.Int8Ty, CharUnits::fromQuantity(TyAlign)),
8729       CGF.ConvertType(Ty));
8730 
8731   uint64_t Offset = llvm::alignTo(CGF.getContext().getTypeSize(Ty) / 8, 4);
8732   llvm::Value *NextAddr = Builder.CreateGEP(
8733       CGF.Int8Ty, Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset), "ap.next");
8734   Builder.CreateStore(NextAddr, VAListAddrAsBPP);
8735 
8736   return AddrTyped;
8737 }
8738 
8739 Address HexagonABIInfo::EmitVAArgForHexagonLinux(CodeGenFunction &CGF,
8740                                                  Address VAListAddr,
8741                                                  QualType Ty) const {
8742   int ArgSize = CGF.getContext().getTypeSize(Ty) / 8;
8743 
8744   if (ArgSize > 8)
8745     return EmitVAArgFromMemory(CGF, VAListAddr, Ty);
8746 
8747   // Here we have check if the argument is in register area or
8748   // in overflow area.
8749   // If the saved register area pointer + argsize rounded up to alignment >
8750   // saved register area end pointer, argument is in overflow area.
8751   unsigned RegsLeft = 6;
8752   Ty = CGF.getContext().getCanonicalType(Ty);
8753   (void)classifyArgumentType(Ty, &RegsLeft);
8754 
8755   llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
8756   llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
8757   llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
8758   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
8759 
8760   // Get rounded size of the argument.GCC does not allow vararg of
8761   // size < 4 bytes. We follow the same logic here.
8762   ArgSize = (CGF.getContext().getTypeSize(Ty) <= 32) ? 4 : 8;
8763   int ArgAlign = (CGF.getContext().getTypeSize(Ty) <= 32) ? 4 : 8;
8764 
8765   // Argument may be in saved register area
8766   CGF.EmitBlock(MaybeRegBlock);
8767 
8768   // Load the current saved register area pointer.
8769   Address __current_saved_reg_area_pointer_p = CGF.Builder.CreateStructGEP(
8770       VAListAddr, 0, "__current_saved_reg_area_pointer_p");
8771   llvm::Value *__current_saved_reg_area_pointer = CGF.Builder.CreateLoad(
8772       __current_saved_reg_area_pointer_p, "__current_saved_reg_area_pointer");
8773 
8774   // Load the saved register area end pointer.
8775   Address __saved_reg_area_end_pointer_p = CGF.Builder.CreateStructGEP(
8776       VAListAddr, 1, "__saved_reg_area_end_pointer_p");
8777   llvm::Value *__saved_reg_area_end_pointer = CGF.Builder.CreateLoad(
8778       __saved_reg_area_end_pointer_p, "__saved_reg_area_end_pointer");
8779 
8780   // If the size of argument is > 4 bytes, check if the stack
8781   // location is aligned to 8 bytes
8782   if (ArgAlign > 4) {
8783 
8784     llvm::Value *__current_saved_reg_area_pointer_int =
8785         CGF.Builder.CreatePtrToInt(__current_saved_reg_area_pointer,
8786                                    CGF.Int32Ty);
8787 
8788     __current_saved_reg_area_pointer_int = CGF.Builder.CreateAdd(
8789         __current_saved_reg_area_pointer_int,
8790         llvm::ConstantInt::get(CGF.Int32Ty, (ArgAlign - 1)),
8791         "align_current_saved_reg_area_pointer");
8792 
8793     __current_saved_reg_area_pointer_int =
8794         CGF.Builder.CreateAnd(__current_saved_reg_area_pointer_int,
8795                               llvm::ConstantInt::get(CGF.Int32Ty, -ArgAlign),
8796                               "align_current_saved_reg_area_pointer");
8797 
8798     __current_saved_reg_area_pointer =
8799         CGF.Builder.CreateIntToPtr(__current_saved_reg_area_pointer_int,
8800                                    __current_saved_reg_area_pointer->getType(),
8801                                    "align_current_saved_reg_area_pointer");
8802   }
8803 
8804   llvm::Value *__new_saved_reg_area_pointer =
8805       CGF.Builder.CreateGEP(CGF.Int8Ty, __current_saved_reg_area_pointer,
8806                             llvm::ConstantInt::get(CGF.Int32Ty, ArgSize),
8807                             "__new_saved_reg_area_pointer");
8808 
8809   llvm::Value *UsingStack = nullptr;
8810   UsingStack = CGF.Builder.CreateICmpSGT(__new_saved_reg_area_pointer,
8811                                          __saved_reg_area_end_pointer);
8812 
8813   CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, InRegBlock);
8814 
8815   // Argument in saved register area
8816   // Implement the block where argument is in register saved area
8817   CGF.EmitBlock(InRegBlock);
8818 
8819   llvm::Type *PTy = CGF.ConvertType(Ty);
8820   llvm::Value *__saved_reg_area_p = CGF.Builder.CreateBitCast(
8821       __current_saved_reg_area_pointer, llvm::PointerType::getUnqual(PTy));
8822 
8823   CGF.Builder.CreateStore(__new_saved_reg_area_pointer,
8824                           __current_saved_reg_area_pointer_p);
8825 
8826   CGF.EmitBranch(ContBlock);
8827 
8828   // Argument in overflow area
8829   // Implement the block where the argument is in overflow area.
8830   CGF.EmitBlock(OnStackBlock);
8831 
8832   // Load the overflow area pointer
8833   Address __overflow_area_pointer_p =
8834       CGF.Builder.CreateStructGEP(VAListAddr, 2, "__overflow_area_pointer_p");
8835   llvm::Value *__overflow_area_pointer = CGF.Builder.CreateLoad(
8836       __overflow_area_pointer_p, "__overflow_area_pointer");
8837 
8838   // Align the overflow area pointer according to the alignment of the argument
8839   if (ArgAlign > 4) {
8840     llvm::Value *__overflow_area_pointer_int =
8841         CGF.Builder.CreatePtrToInt(__overflow_area_pointer, CGF.Int32Ty);
8842 
8843     __overflow_area_pointer_int =
8844         CGF.Builder.CreateAdd(__overflow_area_pointer_int,
8845                               llvm::ConstantInt::get(CGF.Int32Ty, ArgAlign - 1),
8846                               "align_overflow_area_pointer");
8847 
8848     __overflow_area_pointer_int =
8849         CGF.Builder.CreateAnd(__overflow_area_pointer_int,
8850                               llvm::ConstantInt::get(CGF.Int32Ty, -ArgAlign),
8851                               "align_overflow_area_pointer");
8852 
8853     __overflow_area_pointer = CGF.Builder.CreateIntToPtr(
8854         __overflow_area_pointer_int, __overflow_area_pointer->getType(),
8855         "align_overflow_area_pointer");
8856   }
8857 
8858   // Get the pointer for next argument in overflow area and store it
8859   // to overflow area pointer.
8860   llvm::Value *__new_overflow_area_pointer = CGF.Builder.CreateGEP(
8861       CGF.Int8Ty, __overflow_area_pointer,
8862       llvm::ConstantInt::get(CGF.Int32Ty, ArgSize),
8863       "__overflow_area_pointer.next");
8864 
8865   CGF.Builder.CreateStore(__new_overflow_area_pointer,
8866                           __overflow_area_pointer_p);
8867 
8868   CGF.Builder.CreateStore(__new_overflow_area_pointer,
8869                           __current_saved_reg_area_pointer_p);
8870 
8871   // Bitcast the overflow area pointer to the type of argument.
8872   llvm::Type *OverflowPTy = CGF.ConvertTypeForMem(Ty);
8873   llvm::Value *__overflow_area_p = CGF.Builder.CreateBitCast(
8874       __overflow_area_pointer, llvm::PointerType::getUnqual(OverflowPTy));
8875 
8876   CGF.EmitBranch(ContBlock);
8877 
8878   // Get the correct pointer to load the variable argument
8879   // Implement the ContBlock
8880   CGF.EmitBlock(ContBlock);
8881 
8882   llvm::Type *MemTy = CGF.ConvertTypeForMem(Ty);
8883   llvm::Type *MemPTy = llvm::PointerType::getUnqual(MemTy);
8884   llvm::PHINode *ArgAddr = CGF.Builder.CreatePHI(MemPTy, 2, "vaarg.addr");
8885   ArgAddr->addIncoming(__saved_reg_area_p, InRegBlock);
8886   ArgAddr->addIncoming(__overflow_area_p, OnStackBlock);
8887 
8888   return Address(ArgAddr, MemTy, CharUnits::fromQuantity(ArgAlign));
8889 }
8890 
8891 Address HexagonABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8892                                   QualType Ty) const {
8893 
8894   if (getTarget().getTriple().isMusl())
8895     return EmitVAArgForHexagonLinux(CGF, VAListAddr, Ty);
8896 
8897   return EmitVAArgForHexagon(CGF, VAListAddr, Ty);
8898 }
8899 
8900 //===----------------------------------------------------------------------===//
8901 // Lanai ABI Implementation
8902 //===----------------------------------------------------------------------===//
8903 
8904 namespace {
8905 class LanaiABIInfo : public DefaultABIInfo {
8906 public:
8907   LanaiABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
8908 
8909   bool shouldUseInReg(QualType Ty, CCState &State) const;
8910 
8911   void computeInfo(CGFunctionInfo &FI) const override {
8912     CCState State(FI);
8913     // Lanai uses 4 registers to pass arguments unless the function has the
8914     // regparm attribute set.
8915     if (FI.getHasRegParm()) {
8916       State.FreeRegs = FI.getRegParm();
8917     } else {
8918       State.FreeRegs = 4;
8919     }
8920 
8921     if (!getCXXABI().classifyReturnType(FI))
8922       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
8923     for (auto &I : FI.arguments())
8924       I.info = classifyArgumentType(I.type, State);
8925   }
8926 
8927   ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
8928   ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
8929 };
8930 } // end anonymous namespace
8931 
8932 bool LanaiABIInfo::shouldUseInReg(QualType Ty, CCState &State) const {
8933   unsigned Size = getContext().getTypeSize(Ty);
8934   unsigned SizeInRegs = llvm::alignTo(Size, 32U) / 32U;
8935 
8936   if (SizeInRegs == 0)
8937     return false;
8938 
8939   if (SizeInRegs > State.FreeRegs) {
8940     State.FreeRegs = 0;
8941     return false;
8942   }
8943 
8944   State.FreeRegs -= SizeInRegs;
8945 
8946   return true;
8947 }
8948 
8949 ABIArgInfo LanaiABIInfo::getIndirectResult(QualType Ty, bool ByVal,
8950                                            CCState &State) const {
8951   if (!ByVal) {
8952     if (State.FreeRegs) {
8953       --State.FreeRegs; // Non-byval indirects just use one pointer.
8954       return getNaturalAlignIndirectInReg(Ty);
8955     }
8956     return getNaturalAlignIndirect(Ty, false);
8957   }
8958 
8959   // Compute the byval alignment.
8960   const unsigned MinABIStackAlignInBytes = 4;
8961   unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
8962   return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true,
8963                                  /*Realign=*/TypeAlign >
8964                                      MinABIStackAlignInBytes);
8965 }
8966 
8967 ABIArgInfo LanaiABIInfo::classifyArgumentType(QualType Ty,
8968                                               CCState &State) const {
8969   // Check with the C++ ABI first.
8970   const RecordType *RT = Ty->getAs<RecordType>();
8971   if (RT) {
8972     CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
8973     if (RAA == CGCXXABI::RAA_Indirect) {
8974       return getIndirectResult(Ty, /*ByVal=*/false, State);
8975     } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
8976       return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
8977     }
8978   }
8979 
8980   if (isAggregateTypeForABI(Ty)) {
8981     // Structures with flexible arrays are always indirect.
8982     if (RT && RT->getDecl()->hasFlexibleArrayMember())
8983       return getIndirectResult(Ty, /*ByVal=*/true, State);
8984 
8985     // Ignore empty structs/unions.
8986     if (isEmptyRecord(getContext(), Ty, true))
8987       return ABIArgInfo::getIgnore();
8988 
8989     llvm::LLVMContext &LLVMContext = getVMContext();
8990     unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
8991     if (SizeInRegs <= State.FreeRegs) {
8992       llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
8993       SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32);
8994       llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
8995       State.FreeRegs -= SizeInRegs;
8996       return ABIArgInfo::getDirectInReg(Result);
8997     } else {
8998       State.FreeRegs = 0;
8999     }
9000     return getIndirectResult(Ty, true, State);
9001   }
9002 
9003   // Treat an enum type as its underlying type.
9004   if (const auto *EnumTy = Ty->getAs<EnumType>())
9005     Ty = EnumTy->getDecl()->getIntegerType();
9006 
9007   bool InReg = shouldUseInReg(Ty, State);
9008 
9009   // Don't pass >64 bit integers in registers.
9010   if (const auto *EIT = Ty->getAs<BitIntType>())
9011     if (EIT->getNumBits() > 64)
9012       return getIndirectResult(Ty, /*ByVal=*/true, State);
9013 
9014   if (isPromotableIntegerTypeForABI(Ty)) {
9015     if (InReg)
9016       return ABIArgInfo::getDirectInReg();
9017     return ABIArgInfo::getExtend(Ty);
9018   }
9019   if (InReg)
9020     return ABIArgInfo::getDirectInReg();
9021   return ABIArgInfo::getDirect();
9022 }
9023 
9024 namespace {
9025 class LanaiTargetCodeGenInfo : public TargetCodeGenInfo {
9026 public:
9027   LanaiTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
9028       : TargetCodeGenInfo(std::make_unique<LanaiABIInfo>(CGT)) {}
9029 };
9030 }
9031 
9032 //===----------------------------------------------------------------------===//
9033 // AMDGPU ABI Implementation
9034 //===----------------------------------------------------------------------===//
9035 
9036 namespace {
9037 
9038 class AMDGPUABIInfo final : public DefaultABIInfo {
9039 private:
9040   static const unsigned MaxNumRegsForArgsRet = 16;
9041 
9042   unsigned numRegsForType(QualType Ty) const;
9043 
9044   bool isHomogeneousAggregateBaseType(QualType Ty) const override;
9045   bool isHomogeneousAggregateSmallEnough(const Type *Base,
9046                                          uint64_t Members) const override;
9047 
9048   // Coerce HIP scalar pointer arguments from generic pointers to global ones.
9049   llvm::Type *coerceKernelArgumentType(llvm::Type *Ty, unsigned FromAS,
9050                                        unsigned ToAS) const {
9051     // Single value types.
9052     auto *PtrTy = llvm::dyn_cast<llvm::PointerType>(Ty);
9053     if (PtrTy && PtrTy->getAddressSpace() == FromAS)
9054       return llvm::PointerType::getWithSamePointeeType(PtrTy, ToAS);
9055     return Ty;
9056   }
9057 
9058 public:
9059   explicit AMDGPUABIInfo(CodeGen::CodeGenTypes &CGT) :
9060     DefaultABIInfo(CGT) {}
9061 
9062   ABIArgInfo classifyReturnType(QualType RetTy) const;
9063   ABIArgInfo classifyKernelArgumentType(QualType Ty) const;
9064   ABIArgInfo classifyArgumentType(QualType Ty, unsigned &NumRegsLeft) const;
9065 
9066   void computeInfo(CGFunctionInfo &FI) const override;
9067   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9068                     QualType Ty) const override;
9069 };
9070 
9071 bool AMDGPUABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
9072   return true;
9073 }
9074 
9075 bool AMDGPUABIInfo::isHomogeneousAggregateSmallEnough(
9076   const Type *Base, uint64_t Members) const {
9077   uint32_t NumRegs = (getContext().getTypeSize(Base) + 31) / 32;
9078 
9079   // Homogeneous Aggregates may occupy at most 16 registers.
9080   return Members * NumRegs <= MaxNumRegsForArgsRet;
9081 }
9082 
9083 /// Estimate number of registers the type will use when passed in registers.
9084 unsigned AMDGPUABIInfo::numRegsForType(QualType Ty) const {
9085   unsigned NumRegs = 0;
9086 
9087   if (const VectorType *VT = Ty->getAs<VectorType>()) {
9088     // Compute from the number of elements. The reported size is based on the
9089     // in-memory size, which includes the padding 4th element for 3-vectors.
9090     QualType EltTy = VT->getElementType();
9091     unsigned EltSize = getContext().getTypeSize(EltTy);
9092 
9093     // 16-bit element vectors should be passed as packed.
9094     if (EltSize == 16)
9095       return (VT->getNumElements() + 1) / 2;
9096 
9097     unsigned EltNumRegs = (EltSize + 31) / 32;
9098     return EltNumRegs * VT->getNumElements();
9099   }
9100 
9101   if (const RecordType *RT = Ty->getAs<RecordType>()) {
9102     const RecordDecl *RD = RT->getDecl();
9103     assert(!RD->hasFlexibleArrayMember());
9104 
9105     for (const FieldDecl *Field : RD->fields()) {
9106       QualType FieldTy = Field->getType();
9107       NumRegs += numRegsForType(FieldTy);
9108     }
9109 
9110     return NumRegs;
9111   }
9112 
9113   return (getContext().getTypeSize(Ty) + 31) / 32;
9114 }
9115 
9116 void AMDGPUABIInfo::computeInfo(CGFunctionInfo &FI) const {
9117   llvm::CallingConv::ID CC = FI.getCallingConvention();
9118 
9119   if (!getCXXABI().classifyReturnType(FI))
9120     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
9121 
9122   unsigned NumRegsLeft = MaxNumRegsForArgsRet;
9123   for (auto &Arg : FI.arguments()) {
9124     if (CC == llvm::CallingConv::AMDGPU_KERNEL) {
9125       Arg.info = classifyKernelArgumentType(Arg.type);
9126     } else {
9127       Arg.info = classifyArgumentType(Arg.type, NumRegsLeft);
9128     }
9129   }
9130 }
9131 
9132 Address AMDGPUABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9133                                  QualType Ty) const {
9134   llvm_unreachable("AMDGPU does not support varargs");
9135 }
9136 
9137 ABIArgInfo AMDGPUABIInfo::classifyReturnType(QualType RetTy) const {
9138   if (isAggregateTypeForABI(RetTy)) {
9139     // Records with non-trivial destructors/copy-constructors should not be
9140     // returned by value.
9141     if (!getRecordArgABI(RetTy, getCXXABI())) {
9142       // Ignore empty structs/unions.
9143       if (isEmptyRecord(getContext(), RetTy, true))
9144         return ABIArgInfo::getIgnore();
9145 
9146       // Lower single-element structs to just return a regular value.
9147       if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
9148         return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
9149 
9150       if (const RecordType *RT = RetTy->getAs<RecordType>()) {
9151         const RecordDecl *RD = RT->getDecl();
9152         if (RD->hasFlexibleArrayMember())
9153           return DefaultABIInfo::classifyReturnType(RetTy);
9154       }
9155 
9156       // Pack aggregates <= 4 bytes into single VGPR or pair.
9157       uint64_t Size = getContext().getTypeSize(RetTy);
9158       if (Size <= 16)
9159         return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
9160 
9161       if (Size <= 32)
9162         return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
9163 
9164       if (Size <= 64) {
9165         llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext());
9166         return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2));
9167       }
9168 
9169       if (numRegsForType(RetTy) <= MaxNumRegsForArgsRet)
9170         return ABIArgInfo::getDirect();
9171     }
9172   }
9173 
9174   // Otherwise just do the default thing.
9175   return DefaultABIInfo::classifyReturnType(RetTy);
9176 }
9177 
9178 /// For kernels all parameters are really passed in a special buffer. It doesn't
9179 /// make sense to pass anything byval, so everything must be direct.
9180 ABIArgInfo AMDGPUABIInfo::classifyKernelArgumentType(QualType Ty) const {
9181   Ty = useFirstFieldIfTransparentUnion(Ty);
9182 
9183   // TODO: Can we omit empty structs?
9184 
9185   if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
9186     Ty = QualType(SeltTy, 0);
9187 
9188   llvm::Type *OrigLTy = CGT.ConvertType(Ty);
9189   llvm::Type *LTy = OrigLTy;
9190   if (getContext().getLangOpts().HIP) {
9191     LTy = coerceKernelArgumentType(
9192         OrigLTy, /*FromAS=*/getContext().getTargetAddressSpace(LangAS::Default),
9193         /*ToAS=*/getContext().getTargetAddressSpace(LangAS::cuda_device));
9194   }
9195 
9196   // FIXME: Should also use this for OpenCL, but it requires addressing the
9197   // problem of kernels being called.
9198   //
9199   // FIXME: This doesn't apply the optimization of coercing pointers in structs
9200   // to global address space when using byref. This would require implementing a
9201   // new kind of coercion of the in-memory type when for indirect arguments.
9202   if (!getContext().getLangOpts().OpenCL && LTy == OrigLTy &&
9203       isAggregateTypeForABI(Ty)) {
9204     return ABIArgInfo::getIndirectAliased(
9205         getContext().getTypeAlignInChars(Ty),
9206         getContext().getTargetAddressSpace(LangAS::opencl_constant),
9207         false /*Realign*/, nullptr /*Padding*/);
9208   }
9209 
9210   // If we set CanBeFlattened to true, CodeGen will expand the struct to its
9211   // individual elements, which confuses the Clover OpenCL backend; therefore we
9212   // have to set it to false here. Other args of getDirect() are just defaults.
9213   return ABIArgInfo::getDirect(LTy, 0, nullptr, false);
9214 }
9215 
9216 ABIArgInfo AMDGPUABIInfo::classifyArgumentType(QualType Ty,
9217                                                unsigned &NumRegsLeft) const {
9218   assert(NumRegsLeft <= MaxNumRegsForArgsRet && "register estimate underflow");
9219 
9220   Ty = useFirstFieldIfTransparentUnion(Ty);
9221 
9222   if (isAggregateTypeForABI(Ty)) {
9223     // Records with non-trivial destructors/copy-constructors should not be
9224     // passed by value.
9225     if (auto RAA = getRecordArgABI(Ty, getCXXABI()))
9226       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
9227 
9228     // Ignore empty structs/unions.
9229     if (isEmptyRecord(getContext(), Ty, true))
9230       return ABIArgInfo::getIgnore();
9231 
9232     // Lower single-element structs to just pass a regular value. TODO: We
9233     // could do reasonable-size multiple-element structs too, using getExpand(),
9234     // though watch out for things like bitfields.
9235     if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
9236       return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
9237 
9238     if (const RecordType *RT = Ty->getAs<RecordType>()) {
9239       const RecordDecl *RD = RT->getDecl();
9240       if (RD->hasFlexibleArrayMember())
9241         return DefaultABIInfo::classifyArgumentType(Ty);
9242     }
9243 
9244     // Pack aggregates <= 8 bytes into single VGPR or pair.
9245     uint64_t Size = getContext().getTypeSize(Ty);
9246     if (Size <= 64) {
9247       unsigned NumRegs = (Size + 31) / 32;
9248       NumRegsLeft -= std::min(NumRegsLeft, NumRegs);
9249 
9250       if (Size <= 16)
9251         return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
9252 
9253       if (Size <= 32)
9254         return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
9255 
9256       // XXX: Should this be i64 instead, and should the limit increase?
9257       llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext());
9258       return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2));
9259     }
9260 
9261     if (NumRegsLeft > 0) {
9262       unsigned NumRegs = numRegsForType(Ty);
9263       if (NumRegsLeft >= NumRegs) {
9264         NumRegsLeft -= NumRegs;
9265         return ABIArgInfo::getDirect();
9266       }
9267     }
9268   }
9269 
9270   // Otherwise just do the default thing.
9271   ABIArgInfo ArgInfo = DefaultABIInfo::classifyArgumentType(Ty);
9272   if (!ArgInfo.isIndirect()) {
9273     unsigned NumRegs = numRegsForType(Ty);
9274     NumRegsLeft -= std::min(NumRegs, NumRegsLeft);
9275   }
9276 
9277   return ArgInfo;
9278 }
9279 
9280 class AMDGPUTargetCodeGenInfo : public TargetCodeGenInfo {
9281 public:
9282   AMDGPUTargetCodeGenInfo(CodeGenTypes &CGT)
9283       : TargetCodeGenInfo(std::make_unique<AMDGPUABIInfo>(CGT)) {}
9284 
9285   void setFunctionDeclAttributes(const FunctionDecl *FD, llvm::Function *F,
9286                                  CodeGenModule &CGM) const;
9287 
9288   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
9289                            CodeGen::CodeGenModule &M) const override;
9290   unsigned getOpenCLKernelCallingConv() const override;
9291 
9292   llvm::Constant *getNullPointer(const CodeGen::CodeGenModule &CGM,
9293       llvm::PointerType *T, QualType QT) const override;
9294 
9295   LangAS getASTAllocaAddressSpace() const override {
9296     return getLangASFromTargetAS(
9297         getABIInfo().getDataLayout().getAllocaAddrSpace());
9298   }
9299   LangAS getGlobalVarAddressSpace(CodeGenModule &CGM,
9300                                   const VarDecl *D) const override;
9301   llvm::SyncScope::ID getLLVMSyncScopeID(const LangOptions &LangOpts,
9302                                          SyncScope Scope,
9303                                          llvm::AtomicOrdering Ordering,
9304                                          llvm::LLVMContext &Ctx) const override;
9305   llvm::Function *
9306   createEnqueuedBlockKernel(CodeGenFunction &CGF,
9307                             llvm::Function *BlockInvokeFunc,
9308                             llvm::Type *BlockTy) const override;
9309   bool shouldEmitStaticExternCAliases() const override;
9310   void setCUDAKernelCallingConvention(const FunctionType *&FT) const override;
9311 };
9312 }
9313 
9314 static bool requiresAMDGPUProtectedVisibility(const Decl *D,
9315                                               llvm::GlobalValue *GV) {
9316   if (GV->getVisibility() != llvm::GlobalValue::HiddenVisibility)
9317     return false;
9318 
9319   return D->hasAttr<OpenCLKernelAttr>() ||
9320          (isa<FunctionDecl>(D) && D->hasAttr<CUDAGlobalAttr>()) ||
9321          (isa<VarDecl>(D) &&
9322           (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>() ||
9323            cast<VarDecl>(D)->getType()->isCUDADeviceBuiltinSurfaceType() ||
9324            cast<VarDecl>(D)->getType()->isCUDADeviceBuiltinTextureType()));
9325 }
9326 
9327 void AMDGPUTargetCodeGenInfo::setFunctionDeclAttributes(
9328     const FunctionDecl *FD, llvm::Function *F, CodeGenModule &M) const {
9329   const auto *ReqdWGS =
9330       M.getLangOpts().OpenCL ? FD->getAttr<ReqdWorkGroupSizeAttr>() : nullptr;
9331   const bool IsOpenCLKernel =
9332       M.getLangOpts().OpenCL && FD->hasAttr<OpenCLKernelAttr>();
9333   const bool IsHIPKernel = M.getLangOpts().HIP && FD->hasAttr<CUDAGlobalAttr>();
9334 
9335   const auto *FlatWGS = FD->getAttr<AMDGPUFlatWorkGroupSizeAttr>();
9336   if (ReqdWGS || FlatWGS) {
9337     unsigned Min = 0;
9338     unsigned Max = 0;
9339     if (FlatWGS) {
9340       Min = FlatWGS->getMin()
9341                 ->EvaluateKnownConstInt(M.getContext())
9342                 .getExtValue();
9343       Max = FlatWGS->getMax()
9344                 ->EvaluateKnownConstInt(M.getContext())
9345                 .getExtValue();
9346     }
9347     if (ReqdWGS && Min == 0 && Max == 0)
9348       Min = Max = ReqdWGS->getXDim() * ReqdWGS->getYDim() * ReqdWGS->getZDim();
9349 
9350     if (Min != 0) {
9351       assert(Min <= Max && "Min must be less than or equal Max");
9352 
9353       std::string AttrVal = llvm::utostr(Min) + "," + llvm::utostr(Max);
9354       F->addFnAttr("amdgpu-flat-work-group-size", AttrVal);
9355     } else
9356       assert(Max == 0 && "Max must be zero");
9357   } else if (IsOpenCLKernel || IsHIPKernel) {
9358     // By default, restrict the maximum size to a value specified by
9359     // --gpu-max-threads-per-block=n or its default value for HIP.
9360     const unsigned OpenCLDefaultMaxWorkGroupSize = 256;
9361     const unsigned DefaultMaxWorkGroupSize =
9362         IsOpenCLKernel ? OpenCLDefaultMaxWorkGroupSize
9363                        : M.getLangOpts().GPUMaxThreadsPerBlock;
9364     std::string AttrVal =
9365         std::string("1,") + llvm::utostr(DefaultMaxWorkGroupSize);
9366     F->addFnAttr("amdgpu-flat-work-group-size", AttrVal);
9367   }
9368 
9369   if (const auto *Attr = FD->getAttr<AMDGPUWavesPerEUAttr>()) {
9370     unsigned Min =
9371         Attr->getMin()->EvaluateKnownConstInt(M.getContext()).getExtValue();
9372     unsigned Max = Attr->getMax() ? Attr->getMax()
9373                                         ->EvaluateKnownConstInt(M.getContext())
9374                                         .getExtValue()
9375                                   : 0;
9376 
9377     if (Min != 0) {
9378       assert((Max == 0 || Min <= Max) && "Min must be less than or equal Max");
9379 
9380       std::string AttrVal = llvm::utostr(Min);
9381       if (Max != 0)
9382         AttrVal = AttrVal + "," + llvm::utostr(Max);
9383       F->addFnAttr("amdgpu-waves-per-eu", AttrVal);
9384     } else
9385       assert(Max == 0 && "Max must be zero");
9386   }
9387 
9388   if (const auto *Attr = FD->getAttr<AMDGPUNumSGPRAttr>()) {
9389     unsigned NumSGPR = Attr->getNumSGPR();
9390 
9391     if (NumSGPR != 0)
9392       F->addFnAttr("amdgpu-num-sgpr", llvm::utostr(NumSGPR));
9393   }
9394 
9395   if (const auto *Attr = FD->getAttr<AMDGPUNumVGPRAttr>()) {
9396     uint32_t NumVGPR = Attr->getNumVGPR();
9397 
9398     if (NumVGPR != 0)
9399       F->addFnAttr("amdgpu-num-vgpr", llvm::utostr(NumVGPR));
9400   }
9401 }
9402 
9403 void AMDGPUTargetCodeGenInfo::setTargetAttributes(
9404     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
9405   if (requiresAMDGPUProtectedVisibility(D, GV)) {
9406     GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
9407     GV->setDSOLocal(true);
9408   }
9409 
9410   if (GV->isDeclaration())
9411     return;
9412 
9413   llvm::Function *F = dyn_cast<llvm::Function>(GV);
9414   if (!F)
9415     return;
9416 
9417   const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
9418   if (FD)
9419     setFunctionDeclAttributes(FD, F, M);
9420 
9421   const bool IsHIPKernel =
9422       M.getLangOpts().HIP && FD && FD->hasAttr<CUDAGlobalAttr>();
9423 
9424   if (IsHIPKernel)
9425     F->addFnAttr("uniform-work-group-size", "true");
9426 
9427   if (M.getContext().getTargetInfo().allowAMDGPUUnsafeFPAtomics())
9428     F->addFnAttr("amdgpu-unsafe-fp-atomics", "true");
9429 
9430   if (!getABIInfo().getCodeGenOpts().EmitIEEENaNCompliantInsts)
9431     F->addFnAttr("amdgpu-ieee", "false");
9432 }
9433 
9434 unsigned AMDGPUTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
9435   return llvm::CallingConv::AMDGPU_KERNEL;
9436 }
9437 
9438 // Currently LLVM assumes null pointers always have value 0,
9439 // which results in incorrectly transformed IR. Therefore, instead of
9440 // emitting null pointers in private and local address spaces, a null
9441 // pointer in generic address space is emitted which is casted to a
9442 // pointer in local or private address space.
9443 llvm::Constant *AMDGPUTargetCodeGenInfo::getNullPointer(
9444     const CodeGen::CodeGenModule &CGM, llvm::PointerType *PT,
9445     QualType QT) const {
9446   if (CGM.getContext().getTargetNullPointerValue(QT) == 0)
9447     return llvm::ConstantPointerNull::get(PT);
9448 
9449   auto &Ctx = CGM.getContext();
9450   auto NPT = llvm::PointerType::getWithSamePointeeType(
9451       PT, Ctx.getTargetAddressSpace(LangAS::opencl_generic));
9452   return llvm::ConstantExpr::getAddrSpaceCast(
9453       llvm::ConstantPointerNull::get(NPT), PT);
9454 }
9455 
9456 LangAS
9457 AMDGPUTargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM,
9458                                                   const VarDecl *D) const {
9459   assert(!CGM.getLangOpts().OpenCL &&
9460          !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) &&
9461          "Address space agnostic languages only");
9462   LangAS DefaultGlobalAS = getLangASFromTargetAS(
9463       CGM.getContext().getTargetAddressSpace(LangAS::opencl_global));
9464   if (!D)
9465     return DefaultGlobalAS;
9466 
9467   LangAS AddrSpace = D->getType().getAddressSpace();
9468   assert(AddrSpace == LangAS::Default || isTargetAddressSpace(AddrSpace));
9469   if (AddrSpace != LangAS::Default)
9470     return AddrSpace;
9471 
9472   // Only promote to address space 4 if VarDecl has constant initialization.
9473   if (CGM.isTypeConstant(D->getType(), false) &&
9474       D->hasConstantInitialization()) {
9475     if (auto ConstAS = CGM.getTarget().getConstantAddressSpace())
9476       return ConstAS.getValue();
9477   }
9478   return DefaultGlobalAS;
9479 }
9480 
9481 llvm::SyncScope::ID
9482 AMDGPUTargetCodeGenInfo::getLLVMSyncScopeID(const LangOptions &LangOpts,
9483                                             SyncScope Scope,
9484                                             llvm::AtomicOrdering Ordering,
9485                                             llvm::LLVMContext &Ctx) const {
9486   std::string Name;
9487   switch (Scope) {
9488   case SyncScope::HIPSingleThread:
9489     Name = "singlethread";
9490     break;
9491   case SyncScope::HIPWavefront:
9492   case SyncScope::OpenCLSubGroup:
9493     Name = "wavefront";
9494     break;
9495   case SyncScope::HIPWorkgroup:
9496   case SyncScope::OpenCLWorkGroup:
9497     Name = "workgroup";
9498     break;
9499   case SyncScope::HIPAgent:
9500   case SyncScope::OpenCLDevice:
9501     Name = "agent";
9502     break;
9503   case SyncScope::HIPSystem:
9504   case SyncScope::OpenCLAllSVMDevices:
9505     Name = "";
9506     break;
9507   }
9508 
9509   if (Ordering != llvm::AtomicOrdering::SequentiallyConsistent) {
9510     if (!Name.empty())
9511       Name = Twine(Twine(Name) + Twine("-")).str();
9512 
9513     Name = Twine(Twine(Name) + Twine("one-as")).str();
9514   }
9515 
9516   return Ctx.getOrInsertSyncScopeID(Name);
9517 }
9518 
9519 bool AMDGPUTargetCodeGenInfo::shouldEmitStaticExternCAliases() const {
9520   return false;
9521 }
9522 
9523 void AMDGPUTargetCodeGenInfo::setCUDAKernelCallingConvention(
9524     const FunctionType *&FT) const {
9525   FT = getABIInfo().getContext().adjustFunctionType(
9526       FT, FT->getExtInfo().withCallingConv(CC_OpenCLKernel));
9527 }
9528 
9529 //===----------------------------------------------------------------------===//
9530 // SPARC v8 ABI Implementation.
9531 // Based on the SPARC Compliance Definition version 2.4.1.
9532 //
9533 // Ensures that complex values are passed in registers.
9534 //
9535 namespace {
9536 class SparcV8ABIInfo : public DefaultABIInfo {
9537 public:
9538   SparcV8ABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
9539 
9540 private:
9541   ABIArgInfo classifyReturnType(QualType RetTy) const;
9542   void computeInfo(CGFunctionInfo &FI) const override;
9543 };
9544 } // end anonymous namespace
9545 
9546 
9547 ABIArgInfo
9548 SparcV8ABIInfo::classifyReturnType(QualType Ty) const {
9549   if (Ty->isAnyComplexType()) {
9550     return ABIArgInfo::getDirect();
9551   }
9552   else {
9553     return DefaultABIInfo::classifyReturnType(Ty);
9554   }
9555 }
9556 
9557 void SparcV8ABIInfo::computeInfo(CGFunctionInfo &FI) const {
9558 
9559   FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
9560   for (auto &Arg : FI.arguments())
9561     Arg.info = classifyArgumentType(Arg.type);
9562 }
9563 
9564 namespace {
9565 class SparcV8TargetCodeGenInfo : public TargetCodeGenInfo {
9566 public:
9567   SparcV8TargetCodeGenInfo(CodeGenTypes &CGT)
9568       : TargetCodeGenInfo(std::make_unique<SparcV8ABIInfo>(CGT)) {}
9569 
9570   llvm::Value *decodeReturnAddress(CodeGen::CodeGenFunction &CGF,
9571                                    llvm::Value *Address) const override {
9572     int Offset;
9573     if (isAggregateTypeForABI(CGF.CurFnInfo->getReturnType()))
9574       Offset = 12;
9575     else
9576       Offset = 8;
9577     return CGF.Builder.CreateGEP(CGF.Int8Ty, Address,
9578                                  llvm::ConstantInt::get(CGF.Int32Ty, Offset));
9579   }
9580 
9581   llvm::Value *encodeReturnAddress(CodeGen::CodeGenFunction &CGF,
9582                                    llvm::Value *Address) const override {
9583     int Offset;
9584     if (isAggregateTypeForABI(CGF.CurFnInfo->getReturnType()))
9585       Offset = -12;
9586     else
9587       Offset = -8;
9588     return CGF.Builder.CreateGEP(CGF.Int8Ty, Address,
9589                                  llvm::ConstantInt::get(CGF.Int32Ty, Offset));
9590   }
9591 };
9592 } // end anonymous namespace
9593 
9594 //===----------------------------------------------------------------------===//
9595 // SPARC v9 ABI Implementation.
9596 // Based on the SPARC Compliance Definition version 2.4.1.
9597 //
9598 // Function arguments a mapped to a nominal "parameter array" and promoted to
9599 // registers depending on their type. Each argument occupies 8 or 16 bytes in
9600 // the array, structs larger than 16 bytes are passed indirectly.
9601 //
9602 // One case requires special care:
9603 //
9604 //   struct mixed {
9605 //     int i;
9606 //     float f;
9607 //   };
9608 //
9609 // When a struct mixed is passed by value, it only occupies 8 bytes in the
9610 // parameter array, but the int is passed in an integer register, and the float
9611 // is passed in a floating point register. This is represented as two arguments
9612 // with the LLVM IR inreg attribute:
9613 //
9614 //   declare void f(i32 inreg %i, float inreg %f)
9615 //
9616 // The code generator will only allocate 4 bytes from the parameter array for
9617 // the inreg arguments. All other arguments are allocated a multiple of 8
9618 // bytes.
9619 //
9620 namespace {
9621 class SparcV9ABIInfo : public ABIInfo {
9622 public:
9623   SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
9624 
9625 private:
9626   ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
9627   void computeInfo(CGFunctionInfo &FI) const override;
9628   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9629                     QualType Ty) const override;
9630 
9631   // Coercion type builder for structs passed in registers. The coercion type
9632   // serves two purposes:
9633   //
9634   // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
9635   //    in registers.
9636   // 2. Expose aligned floating point elements as first-level elements, so the
9637   //    code generator knows to pass them in floating point registers.
9638   //
9639   // We also compute the InReg flag which indicates that the struct contains
9640   // aligned 32-bit floats.
9641   //
9642   struct CoerceBuilder {
9643     llvm::LLVMContext &Context;
9644     const llvm::DataLayout &DL;
9645     SmallVector<llvm::Type*, 8> Elems;
9646     uint64_t Size;
9647     bool InReg;
9648 
9649     CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
9650       : Context(c), DL(dl), Size(0), InReg(false) {}
9651 
9652     // Pad Elems with integers until Size is ToSize.
9653     void pad(uint64_t ToSize) {
9654       assert(ToSize >= Size && "Cannot remove elements");
9655       if (ToSize == Size)
9656         return;
9657 
9658       // Finish the current 64-bit word.
9659       uint64_t Aligned = llvm::alignTo(Size, 64);
9660       if (Aligned > Size && Aligned <= ToSize) {
9661         Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
9662         Size = Aligned;
9663       }
9664 
9665       // Add whole 64-bit words.
9666       while (Size + 64 <= ToSize) {
9667         Elems.push_back(llvm::Type::getInt64Ty(Context));
9668         Size += 64;
9669       }
9670 
9671       // Final in-word padding.
9672       if (Size < ToSize) {
9673         Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
9674         Size = ToSize;
9675       }
9676     }
9677 
9678     // Add a floating point element at Offset.
9679     void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
9680       // Unaligned floats are treated as integers.
9681       if (Offset % Bits)
9682         return;
9683       // The InReg flag is only required if there are any floats < 64 bits.
9684       if (Bits < 64)
9685         InReg = true;
9686       pad(Offset);
9687       Elems.push_back(Ty);
9688       Size = Offset + Bits;
9689     }
9690 
9691     // Add a struct type to the coercion type, starting at Offset (in bits).
9692     void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
9693       const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
9694       for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
9695         llvm::Type *ElemTy = StrTy->getElementType(i);
9696         uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
9697         switch (ElemTy->getTypeID()) {
9698         case llvm::Type::StructTyID:
9699           addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
9700           break;
9701         case llvm::Type::FloatTyID:
9702           addFloat(ElemOffset, ElemTy, 32);
9703           break;
9704         case llvm::Type::DoubleTyID:
9705           addFloat(ElemOffset, ElemTy, 64);
9706           break;
9707         case llvm::Type::FP128TyID:
9708           addFloat(ElemOffset, ElemTy, 128);
9709           break;
9710         case llvm::Type::PointerTyID:
9711           if (ElemOffset % 64 == 0) {
9712             pad(ElemOffset);
9713             Elems.push_back(ElemTy);
9714             Size += 64;
9715           }
9716           break;
9717         default:
9718           break;
9719         }
9720       }
9721     }
9722 
9723     // Check if Ty is a usable substitute for the coercion type.
9724     bool isUsableType(llvm::StructType *Ty) const {
9725       return llvm::makeArrayRef(Elems) == Ty->elements();
9726     }
9727 
9728     // Get the coercion type as a literal struct type.
9729     llvm::Type *getType() const {
9730       if (Elems.size() == 1)
9731         return Elems.front();
9732       else
9733         return llvm::StructType::get(Context, Elems);
9734     }
9735   };
9736 };
9737 } // end anonymous namespace
9738 
9739 ABIArgInfo
9740 SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
9741   if (Ty->isVoidType())
9742     return ABIArgInfo::getIgnore();
9743 
9744   uint64_t Size = getContext().getTypeSize(Ty);
9745 
9746   // Anything too big to fit in registers is passed with an explicit indirect
9747   // pointer / sret pointer.
9748   if (Size > SizeLimit)
9749     return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
9750 
9751   // Treat an enum type as its underlying type.
9752   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
9753     Ty = EnumTy->getDecl()->getIntegerType();
9754 
9755   // Integer types smaller than a register are extended.
9756   if (Size < 64 && Ty->isIntegerType())
9757     return ABIArgInfo::getExtend(Ty);
9758 
9759   if (const auto *EIT = Ty->getAs<BitIntType>())
9760     if (EIT->getNumBits() < 64)
9761       return ABIArgInfo::getExtend(Ty);
9762 
9763   // Other non-aggregates go in registers.
9764   if (!isAggregateTypeForABI(Ty))
9765     return ABIArgInfo::getDirect();
9766 
9767   // If a C++ object has either a non-trivial copy constructor or a non-trivial
9768   // destructor, it is passed with an explicit indirect pointer / sret pointer.
9769   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
9770     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
9771 
9772   // This is a small aggregate type that should be passed in registers.
9773   // Build a coercion type from the LLVM struct type.
9774   llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
9775   if (!StrTy)
9776     return ABIArgInfo::getDirect();
9777 
9778   CoerceBuilder CB(getVMContext(), getDataLayout());
9779   CB.addStruct(0, StrTy);
9780   CB.pad(llvm::alignTo(CB.DL.getTypeSizeInBits(StrTy), 64));
9781 
9782   // Try to use the original type for coercion.
9783   llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
9784 
9785   if (CB.InReg)
9786     return ABIArgInfo::getDirectInReg(CoerceTy);
9787   else
9788     return ABIArgInfo::getDirect(CoerceTy);
9789 }
9790 
9791 Address SparcV9ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9792                                   QualType Ty) const {
9793   ABIArgInfo AI = classifyType(Ty, 16 * 8);
9794   llvm::Type *ArgTy = CGT.ConvertType(Ty);
9795   if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
9796     AI.setCoerceToType(ArgTy);
9797 
9798   CharUnits SlotSize = CharUnits::fromQuantity(8);
9799 
9800   CGBuilderTy &Builder = CGF.Builder;
9801   Address Addr = Address(Builder.CreateLoad(VAListAddr, "ap.cur"),
9802                          getVAListElementType(CGF), SlotSize);
9803   llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
9804 
9805   auto TypeInfo = getContext().getTypeInfoInChars(Ty);
9806 
9807   Address ArgAddr = Address::invalid();
9808   CharUnits Stride;
9809   switch (AI.getKind()) {
9810   case ABIArgInfo::Expand:
9811   case ABIArgInfo::CoerceAndExpand:
9812   case ABIArgInfo::InAlloca:
9813     llvm_unreachable("Unsupported ABI kind for va_arg");
9814 
9815   case ABIArgInfo::Extend: {
9816     Stride = SlotSize;
9817     CharUnits Offset = SlotSize - TypeInfo.Width;
9818     ArgAddr = Builder.CreateConstInBoundsByteGEP(Addr, Offset, "extend");
9819     break;
9820   }
9821 
9822   case ABIArgInfo::Direct: {
9823     auto AllocSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
9824     Stride = CharUnits::fromQuantity(AllocSize).alignTo(SlotSize);
9825     ArgAddr = Addr;
9826     break;
9827   }
9828 
9829   case ABIArgInfo::Indirect:
9830   case ABIArgInfo::IndirectAliased:
9831     Stride = SlotSize;
9832     ArgAddr = Builder.CreateElementBitCast(Addr, ArgPtrTy, "indirect");
9833     ArgAddr = Address(Builder.CreateLoad(ArgAddr, "indirect.arg"), ArgTy,
9834                       TypeInfo.Align);
9835     break;
9836 
9837   case ABIArgInfo::Ignore:
9838     return Address(llvm::UndefValue::get(ArgPtrTy), ArgTy, TypeInfo.Align);
9839   }
9840 
9841   // Update VAList.
9842   Address NextPtr = Builder.CreateConstInBoundsByteGEP(Addr, Stride, "ap.next");
9843   Builder.CreateStore(NextPtr.getPointer(), VAListAddr);
9844 
9845   return Builder.CreateElementBitCast(ArgAddr, ArgTy, "arg.addr");
9846 }
9847 
9848 void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
9849   FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
9850   for (auto &I : FI.arguments())
9851     I.info = classifyType(I.type, 16 * 8);
9852 }
9853 
9854 namespace {
9855 class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
9856 public:
9857   SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
9858       : TargetCodeGenInfo(std::make_unique<SparcV9ABIInfo>(CGT)) {}
9859 
9860   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
9861     return 14;
9862   }
9863 
9864   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
9865                                llvm::Value *Address) const override;
9866 
9867   llvm::Value *decodeReturnAddress(CodeGen::CodeGenFunction &CGF,
9868                                    llvm::Value *Address) const override {
9869     return CGF.Builder.CreateGEP(CGF.Int8Ty, Address,
9870                                  llvm::ConstantInt::get(CGF.Int32Ty, 8));
9871   }
9872 
9873   llvm::Value *encodeReturnAddress(CodeGen::CodeGenFunction &CGF,
9874                                    llvm::Value *Address) const override {
9875     return CGF.Builder.CreateGEP(CGF.Int8Ty, Address,
9876                                  llvm::ConstantInt::get(CGF.Int32Ty, -8));
9877   }
9878 };
9879 } // end anonymous namespace
9880 
9881 bool
9882 SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
9883                                                 llvm::Value *Address) const {
9884   // This is calculated from the LLVM and GCC tables and verified
9885   // against gcc output.  AFAIK all ABIs use the same encoding.
9886 
9887   CodeGen::CGBuilderTy &Builder = CGF.Builder;
9888 
9889   llvm::IntegerType *i8 = CGF.Int8Ty;
9890   llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
9891   llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
9892 
9893   // 0-31: the 8-byte general-purpose registers
9894   AssignToArrayRange(Builder, Address, Eight8, 0, 31);
9895 
9896   // 32-63: f0-31, the 4-byte floating-point registers
9897   AssignToArrayRange(Builder, Address, Four8, 32, 63);
9898 
9899   //   Y   = 64
9900   //   PSR = 65
9901   //   WIM = 66
9902   //   TBR = 67
9903   //   PC  = 68
9904   //   NPC = 69
9905   //   FSR = 70
9906   //   CSR = 71
9907   AssignToArrayRange(Builder, Address, Eight8, 64, 71);
9908 
9909   // 72-87: d0-15, the 8-byte floating-point registers
9910   AssignToArrayRange(Builder, Address, Eight8, 72, 87);
9911 
9912   return false;
9913 }
9914 
9915 // ARC ABI implementation.
9916 namespace {
9917 
9918 class ARCABIInfo : public DefaultABIInfo {
9919 public:
9920   using DefaultABIInfo::DefaultABIInfo;
9921 
9922 private:
9923   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9924                     QualType Ty) const override;
9925 
9926   void updateState(const ABIArgInfo &Info, QualType Ty, CCState &State) const {
9927     if (!State.FreeRegs)
9928       return;
9929     if (Info.isIndirect() && Info.getInReg())
9930       State.FreeRegs--;
9931     else if (Info.isDirect() && Info.getInReg()) {
9932       unsigned sz = (getContext().getTypeSize(Ty) + 31) / 32;
9933       if (sz < State.FreeRegs)
9934         State.FreeRegs -= sz;
9935       else
9936         State.FreeRegs = 0;
9937     }
9938   }
9939 
9940   void computeInfo(CGFunctionInfo &FI) const override {
9941     CCState State(FI);
9942     // ARC uses 8 registers to pass arguments.
9943     State.FreeRegs = 8;
9944 
9945     if (!getCXXABI().classifyReturnType(FI))
9946       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
9947     updateState(FI.getReturnInfo(), FI.getReturnType(), State);
9948     for (auto &I : FI.arguments()) {
9949       I.info = classifyArgumentType(I.type, State.FreeRegs);
9950       updateState(I.info, I.type, State);
9951     }
9952   }
9953 
9954   ABIArgInfo getIndirectByRef(QualType Ty, bool HasFreeRegs) const;
9955   ABIArgInfo getIndirectByValue(QualType Ty) const;
9956   ABIArgInfo classifyArgumentType(QualType Ty, uint8_t FreeRegs) const;
9957   ABIArgInfo classifyReturnType(QualType RetTy) const;
9958 };
9959 
9960 class ARCTargetCodeGenInfo : public TargetCodeGenInfo {
9961 public:
9962   ARCTargetCodeGenInfo(CodeGenTypes &CGT)
9963       : TargetCodeGenInfo(std::make_unique<ARCABIInfo>(CGT)) {}
9964 };
9965 
9966 
9967 ABIArgInfo ARCABIInfo::getIndirectByRef(QualType Ty, bool HasFreeRegs) const {
9968   return HasFreeRegs ? getNaturalAlignIndirectInReg(Ty) :
9969                        getNaturalAlignIndirect(Ty, false);
9970 }
9971 
9972 ABIArgInfo ARCABIInfo::getIndirectByValue(QualType Ty) const {
9973   // Compute the byval alignment.
9974   const unsigned MinABIStackAlignInBytes = 4;
9975   unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
9976   return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true,
9977                                  TypeAlign > MinABIStackAlignInBytes);
9978 }
9979 
9980 Address ARCABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9981                               QualType Ty) const {
9982   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
9983                           getContext().getTypeInfoInChars(Ty),
9984                           CharUnits::fromQuantity(4), true);
9985 }
9986 
9987 ABIArgInfo ARCABIInfo::classifyArgumentType(QualType Ty,
9988                                             uint8_t FreeRegs) const {
9989   // Handle the generic C++ ABI.
9990   const RecordType *RT = Ty->getAs<RecordType>();
9991   if (RT) {
9992     CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
9993     if (RAA == CGCXXABI::RAA_Indirect)
9994       return getIndirectByRef(Ty, FreeRegs > 0);
9995 
9996     if (RAA == CGCXXABI::RAA_DirectInMemory)
9997       return getIndirectByValue(Ty);
9998   }
9999 
10000   // Treat an enum type as its underlying type.
10001   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
10002     Ty = EnumTy->getDecl()->getIntegerType();
10003 
10004   auto SizeInRegs = llvm::alignTo(getContext().getTypeSize(Ty), 32) / 32;
10005 
10006   if (isAggregateTypeForABI(Ty)) {
10007     // Structures with flexible arrays are always indirect.
10008     if (RT && RT->getDecl()->hasFlexibleArrayMember())
10009       return getIndirectByValue(Ty);
10010 
10011     // Ignore empty structs/unions.
10012     if (isEmptyRecord(getContext(), Ty, true))
10013       return ABIArgInfo::getIgnore();
10014 
10015     llvm::LLVMContext &LLVMContext = getVMContext();
10016 
10017     llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
10018     SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32);
10019     llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
10020 
10021     return FreeRegs >= SizeInRegs ?
10022         ABIArgInfo::getDirectInReg(Result) :
10023         ABIArgInfo::getDirect(Result, 0, nullptr, false);
10024   }
10025 
10026   if (const auto *EIT = Ty->getAs<BitIntType>())
10027     if (EIT->getNumBits() > 64)
10028       return getIndirectByValue(Ty);
10029 
10030   return isPromotableIntegerTypeForABI(Ty)
10031              ? (FreeRegs >= SizeInRegs ? ABIArgInfo::getExtendInReg(Ty)
10032                                        : ABIArgInfo::getExtend(Ty))
10033              : (FreeRegs >= SizeInRegs ? ABIArgInfo::getDirectInReg()
10034                                        : ABIArgInfo::getDirect());
10035 }
10036 
10037 ABIArgInfo ARCABIInfo::classifyReturnType(QualType RetTy) const {
10038   if (RetTy->isAnyComplexType())
10039     return ABIArgInfo::getDirectInReg();
10040 
10041   // Arguments of size > 4 registers are indirect.
10042   auto RetSize = llvm::alignTo(getContext().getTypeSize(RetTy), 32) / 32;
10043   if (RetSize > 4)
10044     return getIndirectByRef(RetTy, /*HasFreeRegs*/ true);
10045 
10046   return DefaultABIInfo::classifyReturnType(RetTy);
10047 }
10048 
10049 } // End anonymous namespace.
10050 
10051 //===----------------------------------------------------------------------===//
10052 // XCore ABI Implementation
10053 //===----------------------------------------------------------------------===//
10054 
10055 namespace {
10056 
10057 /// A SmallStringEnc instance is used to build up the TypeString by passing
10058 /// it by reference between functions that append to it.
10059 typedef llvm::SmallString<128> SmallStringEnc;
10060 
10061 /// TypeStringCache caches the meta encodings of Types.
10062 ///
10063 /// The reason for caching TypeStrings is two fold:
10064 ///   1. To cache a type's encoding for later uses;
10065 ///   2. As a means to break recursive member type inclusion.
10066 ///
10067 /// A cache Entry can have a Status of:
10068 ///   NonRecursive:   The type encoding is not recursive;
10069 ///   Recursive:      The type encoding is recursive;
10070 ///   Incomplete:     An incomplete TypeString;
10071 ///   IncompleteUsed: An incomplete TypeString that has been used in a
10072 ///                   Recursive type encoding.
10073 ///
10074 /// A NonRecursive entry will have all of its sub-members expanded as fully
10075 /// as possible. Whilst it may contain types which are recursive, the type
10076 /// itself is not recursive and thus its encoding may be safely used whenever
10077 /// the type is encountered.
10078 ///
10079 /// A Recursive entry will have all of its sub-members expanded as fully as
10080 /// possible. The type itself is recursive and it may contain other types which
10081 /// are recursive. The Recursive encoding must not be used during the expansion
10082 /// of a recursive type's recursive branch. For simplicity the code uses
10083 /// IncompleteCount to reject all usage of Recursive encodings for member types.
10084 ///
10085 /// An Incomplete entry is always a RecordType and only encodes its
10086 /// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and
10087 /// are placed into the cache during type expansion as a means to identify and
10088 /// handle recursive inclusion of types as sub-members. If there is recursion
10089 /// the entry becomes IncompleteUsed.
10090 ///
10091 /// During the expansion of a RecordType's members:
10092 ///
10093 ///   If the cache contains a NonRecursive encoding for the member type, the
10094 ///   cached encoding is used;
10095 ///
10096 ///   If the cache contains a Recursive encoding for the member type, the
10097 ///   cached encoding is 'Swapped' out, as it may be incorrect, and...
10098 ///
10099 ///   If the member is a RecordType, an Incomplete encoding is placed into the
10100 ///   cache to break potential recursive inclusion of itself as a sub-member;
10101 ///
10102 ///   Once a member RecordType has been expanded, its temporary incomplete
10103 ///   entry is removed from the cache. If a Recursive encoding was swapped out
10104 ///   it is swapped back in;
10105 ///
10106 ///   If an incomplete entry is used to expand a sub-member, the incomplete
10107 ///   entry is marked as IncompleteUsed. The cache keeps count of how many
10108 ///   IncompleteUsed entries it currently contains in IncompleteUsedCount;
10109 ///
10110 ///   If a member's encoding is found to be a NonRecursive or Recursive viz:
10111 ///   IncompleteUsedCount==0, the member's encoding is added to the cache.
10112 ///   Else the member is part of a recursive type and thus the recursion has
10113 ///   been exited too soon for the encoding to be correct for the member.
10114 ///
10115 class TypeStringCache {
10116   enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed};
10117   struct Entry {
10118     std::string Str;     // The encoded TypeString for the type.
10119     enum Status State;   // Information about the encoding in 'Str'.
10120     std::string Swapped; // A temporary place holder for a Recursive encoding
10121                          // during the expansion of RecordType's members.
10122   };
10123   std::map<const IdentifierInfo *, struct Entry> Map;
10124   unsigned IncompleteCount;     // Number of Incomplete entries in the Map.
10125   unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map.
10126 public:
10127   TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {}
10128   void addIncomplete(const IdentifierInfo *ID, std::string StubEnc);
10129   bool removeIncomplete(const IdentifierInfo *ID);
10130   void addIfComplete(const IdentifierInfo *ID, StringRef Str,
10131                      bool IsRecursive);
10132   StringRef lookupStr(const IdentifierInfo *ID);
10133 };
10134 
10135 /// TypeString encodings for enum & union fields must be order.
10136 /// FieldEncoding is a helper for this ordering process.
10137 class FieldEncoding {
10138   bool HasName;
10139   std::string Enc;
10140 public:
10141   FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {}
10142   StringRef str() { return Enc; }
10143   bool operator<(const FieldEncoding &rhs) const {
10144     if (HasName != rhs.HasName) return HasName;
10145     return Enc < rhs.Enc;
10146   }
10147 };
10148 
10149 class XCoreABIInfo : public DefaultABIInfo {
10150 public:
10151   XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
10152   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
10153                     QualType Ty) const override;
10154 };
10155 
10156 class XCoreTargetCodeGenInfo : public TargetCodeGenInfo {
10157   mutable TypeStringCache TSC;
10158   void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
10159                     const CodeGen::CodeGenModule &M) const;
10160 
10161 public:
10162   XCoreTargetCodeGenInfo(CodeGenTypes &CGT)
10163       : TargetCodeGenInfo(std::make_unique<XCoreABIInfo>(CGT)) {}
10164   void emitTargetMetadata(CodeGen::CodeGenModule &CGM,
10165                           const llvm::MapVector<GlobalDecl, StringRef>
10166                               &MangledDeclNames) const override;
10167 };
10168 
10169 } // End anonymous namespace.
10170 
10171 // TODO: this implementation is likely now redundant with the default
10172 // EmitVAArg.
10173 Address XCoreABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
10174                                 QualType Ty) const {
10175   CGBuilderTy &Builder = CGF.Builder;
10176 
10177   // Get the VAList.
10178   CharUnits SlotSize = CharUnits::fromQuantity(4);
10179   Address AP = Address(Builder.CreateLoad(VAListAddr),
10180                        getVAListElementType(CGF), SlotSize);
10181 
10182   // Handle the argument.
10183   ABIArgInfo AI = classifyArgumentType(Ty);
10184   CharUnits TypeAlign = getContext().getTypeAlignInChars(Ty);
10185   llvm::Type *ArgTy = CGT.ConvertType(Ty);
10186   if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
10187     AI.setCoerceToType(ArgTy);
10188   llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
10189 
10190   Address Val = Address::invalid();
10191   CharUnits ArgSize = CharUnits::Zero();
10192   switch (AI.getKind()) {
10193   case ABIArgInfo::Expand:
10194   case ABIArgInfo::CoerceAndExpand:
10195   case ABIArgInfo::InAlloca:
10196     llvm_unreachable("Unsupported ABI kind for va_arg");
10197   case ABIArgInfo::Ignore:
10198     Val = Address(llvm::UndefValue::get(ArgPtrTy), ArgTy, TypeAlign);
10199     ArgSize = CharUnits::Zero();
10200     break;
10201   case ABIArgInfo::Extend:
10202   case ABIArgInfo::Direct:
10203     Val = Builder.CreateElementBitCast(AP, ArgTy);
10204     ArgSize = CharUnits::fromQuantity(
10205         getDataLayout().getTypeAllocSize(AI.getCoerceToType()));
10206     ArgSize = ArgSize.alignTo(SlotSize);
10207     break;
10208   case ABIArgInfo::Indirect:
10209   case ABIArgInfo::IndirectAliased:
10210     Val = Builder.CreateElementBitCast(AP, ArgPtrTy);
10211     Val = Address(Builder.CreateLoad(Val), ArgTy, TypeAlign);
10212     ArgSize = SlotSize;
10213     break;
10214   }
10215 
10216   // Increment the VAList.
10217   if (!ArgSize.isZero()) {
10218     Address APN = Builder.CreateConstInBoundsByteGEP(AP, ArgSize);
10219     Builder.CreateStore(APN.getPointer(), VAListAddr);
10220   }
10221 
10222   return Val;
10223 }
10224 
10225 /// During the expansion of a RecordType, an incomplete TypeString is placed
10226 /// into the cache as a means to identify and break recursion.
10227 /// If there is a Recursive encoding in the cache, it is swapped out and will
10228 /// be reinserted by removeIncomplete().
10229 /// All other types of encoding should have been used rather than arriving here.
10230 void TypeStringCache::addIncomplete(const IdentifierInfo *ID,
10231                                     std::string StubEnc) {
10232   if (!ID)
10233     return;
10234   Entry &E = Map[ID];
10235   assert( (E.Str.empty() || E.State == Recursive) &&
10236          "Incorrectly use of addIncomplete");
10237   assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()");
10238   E.Swapped.swap(E.Str); // swap out the Recursive
10239   E.Str.swap(StubEnc);
10240   E.State = Incomplete;
10241   ++IncompleteCount;
10242 }
10243 
10244 /// Once the RecordType has been expanded, the temporary incomplete TypeString
10245 /// must be removed from the cache.
10246 /// If a Recursive was swapped out by addIncomplete(), it will be replaced.
10247 /// Returns true if the RecordType was defined recursively.
10248 bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) {
10249   if (!ID)
10250     return false;
10251   auto I = Map.find(ID);
10252   assert(I != Map.end() && "Entry not present");
10253   Entry &E = I->second;
10254   assert( (E.State == Incomplete ||
10255            E.State == IncompleteUsed) &&
10256          "Entry must be an incomplete type");
10257   bool IsRecursive = false;
10258   if (E.State == IncompleteUsed) {
10259     // We made use of our Incomplete encoding, thus we are recursive.
10260     IsRecursive = true;
10261     --IncompleteUsedCount;
10262   }
10263   if (E.Swapped.empty())
10264     Map.erase(I);
10265   else {
10266     // Swap the Recursive back.
10267     E.Swapped.swap(E.Str);
10268     E.Swapped.clear();
10269     E.State = Recursive;
10270   }
10271   --IncompleteCount;
10272   return IsRecursive;
10273 }
10274 
10275 /// Add the encoded TypeString to the cache only if it is NonRecursive or
10276 /// Recursive (viz: all sub-members were expanded as fully as possible).
10277 void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str,
10278                                     bool IsRecursive) {
10279   if (!ID || IncompleteUsedCount)
10280     return; // No key or it is is an incomplete sub-type so don't add.
10281   Entry &E = Map[ID];
10282   if (IsRecursive && !E.Str.empty()) {
10283     assert(E.State==Recursive && E.Str.size() == Str.size() &&
10284            "This is not the same Recursive entry");
10285     // The parent container was not recursive after all, so we could have used
10286     // this Recursive sub-member entry after all, but we assumed the worse when
10287     // we started viz: IncompleteCount!=0.
10288     return;
10289   }
10290   assert(E.Str.empty() && "Entry already present");
10291   E.Str = Str.str();
10292   E.State = IsRecursive? Recursive : NonRecursive;
10293 }
10294 
10295 /// Return a cached TypeString encoding for the ID. If there isn't one, or we
10296 /// are recursively expanding a type (IncompleteCount != 0) and the cached
10297 /// encoding is Recursive, return an empty StringRef.
10298 StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) {
10299   if (!ID)
10300     return StringRef();   // We have no key.
10301   auto I = Map.find(ID);
10302   if (I == Map.end())
10303     return StringRef();   // We have no encoding.
10304   Entry &E = I->second;
10305   if (E.State == Recursive && IncompleteCount)
10306     return StringRef();   // We don't use Recursive encodings for member types.
10307 
10308   if (E.State == Incomplete) {
10309     // The incomplete type is being used to break out of recursion.
10310     E.State = IncompleteUsed;
10311     ++IncompleteUsedCount;
10312   }
10313   return E.Str;
10314 }
10315 
10316 /// The XCore ABI includes a type information section that communicates symbol
10317 /// type information to the linker. The linker uses this information to verify
10318 /// safety/correctness of things such as array bound and pointers et al.
10319 /// The ABI only requires C (and XC) language modules to emit TypeStrings.
10320 /// This type information (TypeString) is emitted into meta data for all global
10321 /// symbols: definitions, declarations, functions & variables.
10322 ///
10323 /// The TypeString carries type, qualifier, name, size & value details.
10324 /// Please see 'Tools Development Guide' section 2.16.2 for format details:
10325 /// https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf
10326 /// The output is tested by test/CodeGen/xcore-stringtype.c.
10327 ///
10328 static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
10329                           const CodeGen::CodeGenModule &CGM,
10330                           TypeStringCache &TSC);
10331 
10332 /// XCore uses emitTargetMD to emit TypeString metadata for global symbols.
10333 void XCoreTargetCodeGenInfo::emitTargetMD(
10334     const Decl *D, llvm::GlobalValue *GV,
10335     const CodeGen::CodeGenModule &CGM) const {
10336   SmallStringEnc Enc;
10337   if (getTypeString(Enc, D, CGM, TSC)) {
10338     llvm::LLVMContext &Ctx = CGM.getModule().getContext();
10339     llvm::Metadata *MDVals[] = {llvm::ConstantAsMetadata::get(GV),
10340                                 llvm::MDString::get(Ctx, Enc.str())};
10341     llvm::NamedMDNode *MD =
10342       CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings");
10343     MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
10344   }
10345 }
10346 
10347 void XCoreTargetCodeGenInfo::emitTargetMetadata(
10348     CodeGen::CodeGenModule &CGM,
10349     const llvm::MapVector<GlobalDecl, StringRef> &MangledDeclNames) const {
10350   // Warning, new MangledDeclNames may be appended within this loop.
10351   // We rely on MapVector insertions adding new elements to the end
10352   // of the container.
10353   for (unsigned I = 0; I != MangledDeclNames.size(); ++I) {
10354     auto Val = *(MangledDeclNames.begin() + I);
10355     llvm::GlobalValue *GV = CGM.GetGlobalValue(Val.second);
10356     if (GV) {
10357       const Decl *D = Val.first.getDecl()->getMostRecentDecl();
10358       emitTargetMD(D, GV, CGM);
10359     }
10360   }
10361 }
10362 
10363 //===----------------------------------------------------------------------===//
10364 // Base ABI and target codegen info implementation common between SPIR and
10365 // SPIR-V.
10366 //===----------------------------------------------------------------------===//
10367 
10368 namespace {
10369 class CommonSPIRABIInfo : public DefaultABIInfo {
10370 public:
10371   CommonSPIRABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) { setCCs(); }
10372 
10373 private:
10374   void setCCs();
10375 };
10376 
10377 class SPIRVABIInfo : public CommonSPIRABIInfo {
10378 public:
10379   SPIRVABIInfo(CodeGenTypes &CGT) : CommonSPIRABIInfo(CGT) {}
10380   void computeInfo(CGFunctionInfo &FI) const override;
10381 
10382 private:
10383   ABIArgInfo classifyKernelArgumentType(QualType Ty) const;
10384 };
10385 } // end anonymous namespace
10386 namespace {
10387 class CommonSPIRTargetCodeGenInfo : public TargetCodeGenInfo {
10388 public:
10389   CommonSPIRTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
10390       : TargetCodeGenInfo(std::make_unique<CommonSPIRABIInfo>(CGT)) {}
10391   CommonSPIRTargetCodeGenInfo(std::unique_ptr<ABIInfo> ABIInfo)
10392       : TargetCodeGenInfo(std::move(ABIInfo)) {}
10393 
10394   LangAS getASTAllocaAddressSpace() const override {
10395     return getLangASFromTargetAS(
10396         getABIInfo().getDataLayout().getAllocaAddrSpace());
10397   }
10398 
10399   unsigned getOpenCLKernelCallingConv() const override;
10400 };
10401 class SPIRVTargetCodeGenInfo : public CommonSPIRTargetCodeGenInfo {
10402 public:
10403   SPIRVTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
10404       : CommonSPIRTargetCodeGenInfo(std::make_unique<SPIRVABIInfo>(CGT)) {}
10405   void setCUDAKernelCallingConvention(const FunctionType *&FT) const override;
10406 };
10407 } // End anonymous namespace.
10408 
10409 void CommonSPIRABIInfo::setCCs() {
10410   assert(getRuntimeCC() == llvm::CallingConv::C);
10411   RuntimeCC = llvm::CallingConv::SPIR_FUNC;
10412 }
10413 
10414 ABIArgInfo SPIRVABIInfo::classifyKernelArgumentType(QualType Ty) const {
10415   if (getContext().getLangOpts().CUDAIsDevice) {
10416     // Coerce pointer arguments with default address space to CrossWorkGroup
10417     // pointers for HIPSPV/CUDASPV. When the language mode is HIP/CUDA, the
10418     // SPIRTargetInfo maps cuda_device to SPIR-V's CrossWorkGroup address space.
10419     llvm::Type *LTy = CGT.ConvertType(Ty);
10420     auto DefaultAS = getContext().getTargetAddressSpace(LangAS::Default);
10421     auto GlobalAS = getContext().getTargetAddressSpace(LangAS::cuda_device);
10422     auto *PtrTy = llvm::dyn_cast<llvm::PointerType>(LTy);
10423     if (PtrTy && PtrTy->getAddressSpace() == DefaultAS) {
10424       LTy = llvm::PointerType::getWithSamePointeeType(PtrTy, GlobalAS);
10425       return ABIArgInfo::getDirect(LTy, 0, nullptr, false);
10426     }
10427   }
10428   return classifyArgumentType(Ty);
10429 }
10430 
10431 void SPIRVABIInfo::computeInfo(CGFunctionInfo &FI) const {
10432   // The logic is same as in DefaultABIInfo with an exception on the kernel
10433   // arguments handling.
10434   llvm::CallingConv::ID CC = FI.getCallingConvention();
10435 
10436   if (!getCXXABI().classifyReturnType(FI))
10437     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
10438 
10439   for (auto &I : FI.arguments()) {
10440     if (CC == llvm::CallingConv::SPIR_KERNEL) {
10441       I.info = classifyKernelArgumentType(I.type);
10442     } else {
10443       I.info = classifyArgumentType(I.type);
10444     }
10445   }
10446 }
10447 
10448 namespace clang {
10449 namespace CodeGen {
10450 void computeSPIRKernelABIInfo(CodeGenModule &CGM, CGFunctionInfo &FI) {
10451   if (CGM.getTarget().getTriple().isSPIRV())
10452     SPIRVABIInfo(CGM.getTypes()).computeInfo(FI);
10453   else
10454     CommonSPIRABIInfo(CGM.getTypes()).computeInfo(FI);
10455 }
10456 }
10457 }
10458 
10459 unsigned CommonSPIRTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
10460   return llvm::CallingConv::SPIR_KERNEL;
10461 }
10462 
10463 void SPIRVTargetCodeGenInfo::setCUDAKernelCallingConvention(
10464     const FunctionType *&FT) const {
10465   // Convert HIP kernels to SPIR-V kernels.
10466   if (getABIInfo().getContext().getLangOpts().HIP) {
10467     FT = getABIInfo().getContext().adjustFunctionType(
10468         FT, FT->getExtInfo().withCallingConv(CC_OpenCLKernel));
10469     return;
10470   }
10471 }
10472 
10473 static bool appendType(SmallStringEnc &Enc, QualType QType,
10474                        const CodeGen::CodeGenModule &CGM,
10475                        TypeStringCache &TSC);
10476 
10477 /// Helper function for appendRecordType().
10478 /// Builds a SmallVector containing the encoded field types in declaration
10479 /// order.
10480 static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE,
10481                              const RecordDecl *RD,
10482                              const CodeGen::CodeGenModule &CGM,
10483                              TypeStringCache &TSC) {
10484   for (const auto *Field : RD->fields()) {
10485     SmallStringEnc Enc;
10486     Enc += "m(";
10487     Enc += Field->getName();
10488     Enc += "){";
10489     if (Field->isBitField()) {
10490       Enc += "b(";
10491       llvm::raw_svector_ostream OS(Enc);
10492       OS << Field->getBitWidthValue(CGM.getContext());
10493       Enc += ':';
10494     }
10495     if (!appendType(Enc, Field->getType(), CGM, TSC))
10496       return false;
10497     if (Field->isBitField())
10498       Enc += ')';
10499     Enc += '}';
10500     FE.emplace_back(!Field->getName().empty(), Enc);
10501   }
10502   return true;
10503 }
10504 
10505 /// Appends structure and union types to Enc and adds encoding to cache.
10506 /// Recursively calls appendType (via extractFieldType) for each field.
10507 /// Union types have their fields ordered according to the ABI.
10508 static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT,
10509                              const CodeGen::CodeGenModule &CGM,
10510                              TypeStringCache &TSC, const IdentifierInfo *ID) {
10511   // Append the cached TypeString if we have one.
10512   StringRef TypeString = TSC.lookupStr(ID);
10513   if (!TypeString.empty()) {
10514     Enc += TypeString;
10515     return true;
10516   }
10517 
10518   // Start to emit an incomplete TypeString.
10519   size_t Start = Enc.size();
10520   Enc += (RT->isUnionType()? 'u' : 's');
10521   Enc += '(';
10522   if (ID)
10523     Enc += ID->getName();
10524   Enc += "){";
10525 
10526   // We collect all encoded fields and order as necessary.
10527   bool IsRecursive = false;
10528   const RecordDecl *RD = RT->getDecl()->getDefinition();
10529   if (RD && !RD->field_empty()) {
10530     // An incomplete TypeString stub is placed in the cache for this RecordType
10531     // so that recursive calls to this RecordType will use it whilst building a
10532     // complete TypeString for this RecordType.
10533     SmallVector<FieldEncoding, 16> FE;
10534     std::string StubEnc(Enc.substr(Start).str());
10535     StubEnc += '}';  // StubEnc now holds a valid incomplete TypeString.
10536     TSC.addIncomplete(ID, std::move(StubEnc));
10537     if (!extractFieldType(FE, RD, CGM, TSC)) {
10538       (void) TSC.removeIncomplete(ID);
10539       return false;
10540     }
10541     IsRecursive = TSC.removeIncomplete(ID);
10542     // The ABI requires unions to be sorted but not structures.
10543     // See FieldEncoding::operator< for sort algorithm.
10544     if (RT->isUnionType())
10545       llvm::sort(FE);
10546     // We can now complete the TypeString.
10547     unsigned E = FE.size();
10548     for (unsigned I = 0; I != E; ++I) {
10549       if (I)
10550         Enc += ',';
10551       Enc += FE[I].str();
10552     }
10553   }
10554   Enc += '}';
10555   TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive);
10556   return true;
10557 }
10558 
10559 /// Appends enum types to Enc and adds the encoding to the cache.
10560 static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET,
10561                            TypeStringCache &TSC,
10562                            const IdentifierInfo *ID) {
10563   // Append the cached TypeString if we have one.
10564   StringRef TypeString = TSC.lookupStr(ID);
10565   if (!TypeString.empty()) {
10566     Enc += TypeString;
10567     return true;
10568   }
10569 
10570   size_t Start = Enc.size();
10571   Enc += "e(";
10572   if (ID)
10573     Enc += ID->getName();
10574   Enc += "){";
10575 
10576   // We collect all encoded enumerations and order them alphanumerically.
10577   if (const EnumDecl *ED = ET->getDecl()->getDefinition()) {
10578     SmallVector<FieldEncoding, 16> FE;
10579     for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E;
10580          ++I) {
10581       SmallStringEnc EnumEnc;
10582       EnumEnc += "m(";
10583       EnumEnc += I->getName();
10584       EnumEnc += "){";
10585       I->getInitVal().toString(EnumEnc);
10586       EnumEnc += '}';
10587       FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc));
10588     }
10589     llvm::sort(FE);
10590     unsigned E = FE.size();
10591     for (unsigned I = 0; I != E; ++I) {
10592       if (I)
10593         Enc += ',';
10594       Enc += FE[I].str();
10595     }
10596   }
10597   Enc += '}';
10598   TSC.addIfComplete(ID, Enc.substr(Start), false);
10599   return true;
10600 }
10601 
10602 /// Appends type's qualifier to Enc.
10603 /// This is done prior to appending the type's encoding.
10604 static void appendQualifier(SmallStringEnc &Enc, QualType QT) {
10605   // Qualifiers are emitted in alphabetical order.
10606   static const char *const Table[]={"","c:","r:","cr:","v:","cv:","rv:","crv:"};
10607   int Lookup = 0;
10608   if (QT.isConstQualified())
10609     Lookup += 1<<0;
10610   if (QT.isRestrictQualified())
10611     Lookup += 1<<1;
10612   if (QT.isVolatileQualified())
10613     Lookup += 1<<2;
10614   Enc += Table[Lookup];
10615 }
10616 
10617 /// Appends built-in types to Enc.
10618 static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) {
10619   const char *EncType;
10620   switch (BT->getKind()) {
10621     case BuiltinType::Void:
10622       EncType = "0";
10623       break;
10624     case BuiltinType::Bool:
10625       EncType = "b";
10626       break;
10627     case BuiltinType::Char_U:
10628       EncType = "uc";
10629       break;
10630     case BuiltinType::UChar:
10631       EncType = "uc";
10632       break;
10633     case BuiltinType::SChar:
10634       EncType = "sc";
10635       break;
10636     case BuiltinType::UShort:
10637       EncType = "us";
10638       break;
10639     case BuiltinType::Short:
10640       EncType = "ss";
10641       break;
10642     case BuiltinType::UInt:
10643       EncType = "ui";
10644       break;
10645     case BuiltinType::Int:
10646       EncType = "si";
10647       break;
10648     case BuiltinType::ULong:
10649       EncType = "ul";
10650       break;
10651     case BuiltinType::Long:
10652       EncType = "sl";
10653       break;
10654     case BuiltinType::ULongLong:
10655       EncType = "ull";
10656       break;
10657     case BuiltinType::LongLong:
10658       EncType = "sll";
10659       break;
10660     case BuiltinType::Float:
10661       EncType = "ft";
10662       break;
10663     case BuiltinType::Double:
10664       EncType = "d";
10665       break;
10666     case BuiltinType::LongDouble:
10667       EncType = "ld";
10668       break;
10669     default:
10670       return false;
10671   }
10672   Enc += EncType;
10673   return true;
10674 }
10675 
10676 /// Appends a pointer encoding to Enc before calling appendType for the pointee.
10677 static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT,
10678                               const CodeGen::CodeGenModule &CGM,
10679                               TypeStringCache &TSC) {
10680   Enc += "p(";
10681   if (!appendType(Enc, PT->getPointeeType(), CGM, TSC))
10682     return false;
10683   Enc += ')';
10684   return true;
10685 }
10686 
10687 /// Appends array encoding to Enc before calling appendType for the element.
10688 static bool appendArrayType(SmallStringEnc &Enc, QualType QT,
10689                             const ArrayType *AT,
10690                             const CodeGen::CodeGenModule &CGM,
10691                             TypeStringCache &TSC, StringRef NoSizeEnc) {
10692   if (AT->getSizeModifier() != ArrayType::Normal)
10693     return false;
10694   Enc += "a(";
10695   if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
10696     CAT->getSize().toStringUnsigned(Enc);
10697   else
10698     Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "".
10699   Enc += ':';
10700   // The Qualifiers should be attached to the type rather than the array.
10701   appendQualifier(Enc, QT);
10702   if (!appendType(Enc, AT->getElementType(), CGM, TSC))
10703     return false;
10704   Enc += ')';
10705   return true;
10706 }
10707 
10708 /// Appends a function encoding to Enc, calling appendType for the return type
10709 /// and the arguments.
10710 static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT,
10711                              const CodeGen::CodeGenModule &CGM,
10712                              TypeStringCache &TSC) {
10713   Enc += "f{";
10714   if (!appendType(Enc, FT->getReturnType(), CGM, TSC))
10715     return false;
10716   Enc += "}(";
10717   if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) {
10718     // N.B. we are only interested in the adjusted param types.
10719     auto I = FPT->param_type_begin();
10720     auto E = FPT->param_type_end();
10721     if (I != E) {
10722       do {
10723         if (!appendType(Enc, *I, CGM, TSC))
10724           return false;
10725         ++I;
10726         if (I != E)
10727           Enc += ',';
10728       } while (I != E);
10729       if (FPT->isVariadic())
10730         Enc += ",va";
10731     } else {
10732       if (FPT->isVariadic())
10733         Enc += "va";
10734       else
10735         Enc += '0';
10736     }
10737   }
10738   Enc += ')';
10739   return true;
10740 }
10741 
10742 /// Handles the type's qualifier before dispatching a call to handle specific
10743 /// type encodings.
10744 static bool appendType(SmallStringEnc &Enc, QualType QType,
10745                        const CodeGen::CodeGenModule &CGM,
10746                        TypeStringCache &TSC) {
10747 
10748   QualType QT = QType.getCanonicalType();
10749 
10750   if (const ArrayType *AT = QT->getAsArrayTypeUnsafe())
10751     // The Qualifiers should be attached to the type rather than the array.
10752     // Thus we don't call appendQualifier() here.
10753     return appendArrayType(Enc, QT, AT, CGM, TSC, "");
10754 
10755   appendQualifier(Enc, QT);
10756 
10757   if (const BuiltinType *BT = QT->getAs<BuiltinType>())
10758     return appendBuiltinType(Enc, BT);
10759 
10760   if (const PointerType *PT = QT->getAs<PointerType>())
10761     return appendPointerType(Enc, PT, CGM, TSC);
10762 
10763   if (const EnumType *ET = QT->getAs<EnumType>())
10764     return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier());
10765 
10766   if (const RecordType *RT = QT->getAsStructureType())
10767     return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
10768 
10769   if (const RecordType *RT = QT->getAsUnionType())
10770     return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
10771 
10772   if (const FunctionType *FT = QT->getAs<FunctionType>())
10773     return appendFunctionType(Enc, FT, CGM, TSC);
10774 
10775   return false;
10776 }
10777 
10778 static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
10779                           const CodeGen::CodeGenModule &CGM,
10780                           TypeStringCache &TSC) {
10781   if (!D)
10782     return false;
10783 
10784   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
10785     if (FD->getLanguageLinkage() != CLanguageLinkage)
10786       return false;
10787     return appendType(Enc, FD->getType(), CGM, TSC);
10788   }
10789 
10790   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
10791     if (VD->getLanguageLinkage() != CLanguageLinkage)
10792       return false;
10793     QualType QT = VD->getType().getCanonicalType();
10794     if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) {
10795       // Global ArrayTypes are given a size of '*' if the size is unknown.
10796       // The Qualifiers should be attached to the type rather than the array.
10797       // Thus we don't call appendQualifier() here.
10798       return appendArrayType(Enc, QT, AT, CGM, TSC, "*");
10799     }
10800     return appendType(Enc, QT, CGM, TSC);
10801   }
10802   return false;
10803 }
10804 
10805 //===----------------------------------------------------------------------===//
10806 // RISCV ABI Implementation
10807 //===----------------------------------------------------------------------===//
10808 
10809 namespace {
10810 class RISCVABIInfo : public DefaultABIInfo {
10811 private:
10812   // Size of the integer ('x') registers in bits.
10813   unsigned XLen;
10814   // Size of the floating point ('f') registers in bits. Note that the target
10815   // ISA might have a wider FLen than the selected ABI (e.g. an RV32IF target
10816   // with soft float ABI has FLen==0).
10817   unsigned FLen;
10818   static const int NumArgGPRs = 8;
10819   static const int NumArgFPRs = 8;
10820   bool detectFPCCEligibleStructHelper(QualType Ty, CharUnits CurOff,
10821                                       llvm::Type *&Field1Ty,
10822                                       CharUnits &Field1Off,
10823                                       llvm::Type *&Field2Ty,
10824                                       CharUnits &Field2Off) const;
10825 
10826 public:
10827   RISCVABIInfo(CodeGen::CodeGenTypes &CGT, unsigned XLen, unsigned FLen)
10828       : DefaultABIInfo(CGT), XLen(XLen), FLen(FLen) {}
10829 
10830   // DefaultABIInfo's classifyReturnType and classifyArgumentType are
10831   // non-virtual, but computeInfo is virtual, so we overload it.
10832   void computeInfo(CGFunctionInfo &FI) const override;
10833 
10834   ABIArgInfo classifyArgumentType(QualType Ty, bool IsFixed, int &ArgGPRsLeft,
10835                                   int &ArgFPRsLeft) const;
10836   ABIArgInfo classifyReturnType(QualType RetTy) const;
10837 
10838   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
10839                     QualType Ty) const override;
10840 
10841   ABIArgInfo extendType(QualType Ty) const;
10842 
10843   bool detectFPCCEligibleStruct(QualType Ty, llvm::Type *&Field1Ty,
10844                                 CharUnits &Field1Off, llvm::Type *&Field2Ty,
10845                                 CharUnits &Field2Off, int &NeededArgGPRs,
10846                                 int &NeededArgFPRs) const;
10847   ABIArgInfo coerceAndExpandFPCCEligibleStruct(llvm::Type *Field1Ty,
10848                                                CharUnits Field1Off,
10849                                                llvm::Type *Field2Ty,
10850                                                CharUnits Field2Off) const;
10851 };
10852 } // end anonymous namespace
10853 
10854 void RISCVABIInfo::computeInfo(CGFunctionInfo &FI) const {
10855   QualType RetTy = FI.getReturnType();
10856   if (!getCXXABI().classifyReturnType(FI))
10857     FI.getReturnInfo() = classifyReturnType(RetTy);
10858 
10859   // IsRetIndirect is true if classifyArgumentType indicated the value should
10860   // be passed indirect, or if the type size is a scalar greater than 2*XLen
10861   // and not a complex type with elements <= FLen. e.g. fp128 is passed direct
10862   // in LLVM IR, relying on the backend lowering code to rewrite the argument
10863   // list and pass indirectly on RV32.
10864   bool IsRetIndirect = FI.getReturnInfo().getKind() == ABIArgInfo::Indirect;
10865   if (!IsRetIndirect && RetTy->isScalarType() &&
10866       getContext().getTypeSize(RetTy) > (2 * XLen)) {
10867     if (RetTy->isComplexType() && FLen) {
10868       QualType EltTy = RetTy->castAs<ComplexType>()->getElementType();
10869       IsRetIndirect = getContext().getTypeSize(EltTy) > FLen;
10870     } else {
10871       // This is a normal scalar > 2*XLen, such as fp128 on RV32.
10872       IsRetIndirect = true;
10873     }
10874   }
10875 
10876   // We must track the number of GPRs used in order to conform to the RISC-V
10877   // ABI, as integer scalars passed in registers should have signext/zeroext
10878   // when promoted, but are anyext if passed on the stack. As GPR usage is
10879   // different for variadic arguments, we must also track whether we are
10880   // examining a vararg or not.
10881   int ArgGPRsLeft = IsRetIndirect ? NumArgGPRs - 1 : NumArgGPRs;
10882   int ArgFPRsLeft = FLen ? NumArgFPRs : 0;
10883   int NumFixedArgs = FI.getNumRequiredArgs();
10884 
10885   int ArgNum = 0;
10886   for (auto &ArgInfo : FI.arguments()) {
10887     bool IsFixed = ArgNum < NumFixedArgs;
10888     ArgInfo.info =
10889         classifyArgumentType(ArgInfo.type, IsFixed, ArgGPRsLeft, ArgFPRsLeft);
10890     ArgNum++;
10891   }
10892 }
10893 
10894 // Returns true if the struct is a potential candidate for the floating point
10895 // calling convention. If this function returns true, the caller is
10896 // responsible for checking that if there is only a single field then that
10897 // field is a float.
10898 bool RISCVABIInfo::detectFPCCEligibleStructHelper(QualType Ty, CharUnits CurOff,
10899                                                   llvm::Type *&Field1Ty,
10900                                                   CharUnits &Field1Off,
10901                                                   llvm::Type *&Field2Ty,
10902                                                   CharUnits &Field2Off) const {
10903   bool IsInt = Ty->isIntegralOrEnumerationType();
10904   bool IsFloat = Ty->isRealFloatingType();
10905 
10906   if (IsInt || IsFloat) {
10907     uint64_t Size = getContext().getTypeSize(Ty);
10908     if (IsInt && Size > XLen)
10909       return false;
10910     // Can't be eligible if larger than the FP registers. Half precision isn't
10911     // currently supported on RISC-V and the ABI hasn't been confirmed, so
10912     // default to the integer ABI in that case.
10913     if (IsFloat && (Size > FLen || Size < 32))
10914       return false;
10915     // Can't be eligible if an integer type was already found (int+int pairs
10916     // are not eligible).
10917     if (IsInt && Field1Ty && Field1Ty->isIntegerTy())
10918       return false;
10919     if (!Field1Ty) {
10920       Field1Ty = CGT.ConvertType(Ty);
10921       Field1Off = CurOff;
10922       return true;
10923     }
10924     if (!Field2Ty) {
10925       Field2Ty = CGT.ConvertType(Ty);
10926       Field2Off = CurOff;
10927       return true;
10928     }
10929     return false;
10930   }
10931 
10932   if (auto CTy = Ty->getAs<ComplexType>()) {
10933     if (Field1Ty)
10934       return false;
10935     QualType EltTy = CTy->getElementType();
10936     if (getContext().getTypeSize(EltTy) > FLen)
10937       return false;
10938     Field1Ty = CGT.ConvertType(EltTy);
10939     Field1Off = CurOff;
10940     Field2Ty = Field1Ty;
10941     Field2Off = Field1Off + getContext().getTypeSizeInChars(EltTy);
10942     return true;
10943   }
10944 
10945   if (const ConstantArrayType *ATy = getContext().getAsConstantArrayType(Ty)) {
10946     uint64_t ArraySize = ATy->getSize().getZExtValue();
10947     QualType EltTy = ATy->getElementType();
10948     CharUnits EltSize = getContext().getTypeSizeInChars(EltTy);
10949     for (uint64_t i = 0; i < ArraySize; ++i) {
10950       bool Ret = detectFPCCEligibleStructHelper(EltTy, CurOff, Field1Ty,
10951                                                 Field1Off, Field2Ty, Field2Off);
10952       if (!Ret)
10953         return false;
10954       CurOff += EltSize;
10955     }
10956     return true;
10957   }
10958 
10959   if (const auto *RTy = Ty->getAs<RecordType>()) {
10960     // Structures with either a non-trivial destructor or a non-trivial
10961     // copy constructor are not eligible for the FP calling convention.
10962     if (getRecordArgABI(Ty, CGT.getCXXABI()))
10963       return false;
10964     if (isEmptyRecord(getContext(), Ty, true))
10965       return true;
10966     const RecordDecl *RD = RTy->getDecl();
10967     // Unions aren't eligible unless they're empty (which is caught above).
10968     if (RD->isUnion())
10969       return false;
10970     int ZeroWidthBitFieldCount = 0;
10971     for (const FieldDecl *FD : RD->fields()) {
10972       const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
10973       uint64_t FieldOffInBits = Layout.getFieldOffset(FD->getFieldIndex());
10974       QualType QTy = FD->getType();
10975       if (FD->isBitField()) {
10976         unsigned BitWidth = FD->getBitWidthValue(getContext());
10977         // Allow a bitfield with a type greater than XLen as long as the
10978         // bitwidth is XLen or less.
10979         if (getContext().getTypeSize(QTy) > XLen && BitWidth <= XLen)
10980           QTy = getContext().getIntTypeForBitwidth(XLen, false);
10981         if (BitWidth == 0) {
10982           ZeroWidthBitFieldCount++;
10983           continue;
10984         }
10985       }
10986 
10987       bool Ret = detectFPCCEligibleStructHelper(
10988           QTy, CurOff + getContext().toCharUnitsFromBits(FieldOffInBits),
10989           Field1Ty, Field1Off, Field2Ty, Field2Off);
10990       if (!Ret)
10991         return false;
10992 
10993       // As a quirk of the ABI, zero-width bitfields aren't ignored for fp+fp
10994       // or int+fp structs, but are ignored for a struct with an fp field and
10995       // any number of zero-width bitfields.
10996       if (Field2Ty && ZeroWidthBitFieldCount > 0)
10997         return false;
10998     }
10999     return Field1Ty != nullptr;
11000   }
11001 
11002   return false;
11003 }
11004 
11005 // Determine if a struct is eligible for passing according to the floating
11006 // point calling convention (i.e., when flattened it contains a single fp
11007 // value, fp+fp, or int+fp of appropriate size). If so, NeededArgFPRs and
11008 // NeededArgGPRs are incremented appropriately.
11009 bool RISCVABIInfo::detectFPCCEligibleStruct(QualType Ty, llvm::Type *&Field1Ty,
11010                                             CharUnits &Field1Off,
11011                                             llvm::Type *&Field2Ty,
11012                                             CharUnits &Field2Off,
11013                                             int &NeededArgGPRs,
11014                                             int &NeededArgFPRs) const {
11015   Field1Ty = nullptr;
11016   Field2Ty = nullptr;
11017   NeededArgGPRs = 0;
11018   NeededArgFPRs = 0;
11019   bool IsCandidate = detectFPCCEligibleStructHelper(
11020       Ty, CharUnits::Zero(), Field1Ty, Field1Off, Field2Ty, Field2Off);
11021   // Not really a candidate if we have a single int but no float.
11022   if (Field1Ty && !Field2Ty && !Field1Ty->isFloatingPointTy())
11023     return false;
11024   if (!IsCandidate)
11025     return false;
11026   if (Field1Ty && Field1Ty->isFloatingPointTy())
11027     NeededArgFPRs++;
11028   else if (Field1Ty)
11029     NeededArgGPRs++;
11030   if (Field2Ty && Field2Ty->isFloatingPointTy())
11031     NeededArgFPRs++;
11032   else if (Field2Ty)
11033     NeededArgGPRs++;
11034   return true;
11035 }
11036 
11037 // Call getCoerceAndExpand for the two-element flattened struct described by
11038 // Field1Ty, Field1Off, Field2Ty, Field2Off. This method will create an
11039 // appropriate coerceToType and unpaddedCoerceToType.
11040 ABIArgInfo RISCVABIInfo::coerceAndExpandFPCCEligibleStruct(
11041     llvm::Type *Field1Ty, CharUnits Field1Off, llvm::Type *Field2Ty,
11042     CharUnits Field2Off) const {
11043   SmallVector<llvm::Type *, 3> CoerceElts;
11044   SmallVector<llvm::Type *, 2> UnpaddedCoerceElts;
11045   if (!Field1Off.isZero())
11046     CoerceElts.push_back(llvm::ArrayType::get(
11047         llvm::Type::getInt8Ty(getVMContext()), Field1Off.getQuantity()));
11048 
11049   CoerceElts.push_back(Field1Ty);
11050   UnpaddedCoerceElts.push_back(Field1Ty);
11051 
11052   if (!Field2Ty) {
11053     return ABIArgInfo::getCoerceAndExpand(
11054         llvm::StructType::get(getVMContext(), CoerceElts, !Field1Off.isZero()),
11055         UnpaddedCoerceElts[0]);
11056   }
11057 
11058   CharUnits Field2Align =
11059       CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(Field2Ty));
11060   CharUnits Field1End = Field1Off +
11061       CharUnits::fromQuantity(getDataLayout().getTypeStoreSize(Field1Ty));
11062   CharUnits Field2OffNoPadNoPack = Field1End.alignTo(Field2Align);
11063 
11064   CharUnits Padding = CharUnits::Zero();
11065   if (Field2Off > Field2OffNoPadNoPack)
11066     Padding = Field2Off - Field2OffNoPadNoPack;
11067   else if (Field2Off != Field2Align && Field2Off > Field1End)
11068     Padding = Field2Off - Field1End;
11069 
11070   bool IsPacked = !Field2Off.isMultipleOf(Field2Align);
11071 
11072   if (!Padding.isZero())
11073     CoerceElts.push_back(llvm::ArrayType::get(
11074         llvm::Type::getInt8Ty(getVMContext()), Padding.getQuantity()));
11075 
11076   CoerceElts.push_back(Field2Ty);
11077   UnpaddedCoerceElts.push_back(Field2Ty);
11078 
11079   auto CoerceToType =
11080       llvm::StructType::get(getVMContext(), CoerceElts, IsPacked);
11081   auto UnpaddedCoerceToType =
11082       llvm::StructType::get(getVMContext(), UnpaddedCoerceElts, IsPacked);
11083 
11084   return ABIArgInfo::getCoerceAndExpand(CoerceToType, UnpaddedCoerceToType);
11085 }
11086 
11087 ABIArgInfo RISCVABIInfo::classifyArgumentType(QualType Ty, bool IsFixed,
11088                                               int &ArgGPRsLeft,
11089                                               int &ArgFPRsLeft) const {
11090   assert(ArgGPRsLeft <= NumArgGPRs && "Arg GPR tracking underflow");
11091   Ty = useFirstFieldIfTransparentUnion(Ty);
11092 
11093   // Structures with either a non-trivial destructor or a non-trivial
11094   // copy constructor are always passed indirectly.
11095   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
11096     if (ArgGPRsLeft)
11097       ArgGPRsLeft -= 1;
11098     return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA ==
11099                                            CGCXXABI::RAA_DirectInMemory);
11100   }
11101 
11102   // Ignore empty structs/unions.
11103   if (isEmptyRecord(getContext(), Ty, true))
11104     return ABIArgInfo::getIgnore();
11105 
11106   uint64_t Size = getContext().getTypeSize(Ty);
11107 
11108   // Pass floating point values via FPRs if possible.
11109   if (IsFixed && Ty->isFloatingType() && !Ty->isComplexType() &&
11110       FLen >= Size && ArgFPRsLeft) {
11111     ArgFPRsLeft--;
11112     return ABIArgInfo::getDirect();
11113   }
11114 
11115   // Complex types for the hard float ABI must be passed direct rather than
11116   // using CoerceAndExpand.
11117   if (IsFixed && Ty->isComplexType() && FLen && ArgFPRsLeft >= 2) {
11118     QualType EltTy = Ty->castAs<ComplexType>()->getElementType();
11119     if (getContext().getTypeSize(EltTy) <= FLen) {
11120       ArgFPRsLeft -= 2;
11121       return ABIArgInfo::getDirect();
11122     }
11123   }
11124 
11125   if (IsFixed && FLen && Ty->isStructureOrClassType()) {
11126     llvm::Type *Field1Ty = nullptr;
11127     llvm::Type *Field2Ty = nullptr;
11128     CharUnits Field1Off = CharUnits::Zero();
11129     CharUnits Field2Off = CharUnits::Zero();
11130     int NeededArgGPRs = 0;
11131     int NeededArgFPRs = 0;
11132     bool IsCandidate =
11133         detectFPCCEligibleStruct(Ty, Field1Ty, Field1Off, Field2Ty, Field2Off,
11134                                  NeededArgGPRs, NeededArgFPRs);
11135     if (IsCandidate && NeededArgGPRs <= ArgGPRsLeft &&
11136         NeededArgFPRs <= ArgFPRsLeft) {
11137       ArgGPRsLeft -= NeededArgGPRs;
11138       ArgFPRsLeft -= NeededArgFPRs;
11139       return coerceAndExpandFPCCEligibleStruct(Field1Ty, Field1Off, Field2Ty,
11140                                                Field2Off);
11141     }
11142   }
11143 
11144   uint64_t NeededAlign = getContext().getTypeAlign(Ty);
11145   bool MustUseStack = false;
11146   // Determine the number of GPRs needed to pass the current argument
11147   // according to the ABI. 2*XLen-aligned varargs are passed in "aligned"
11148   // register pairs, so may consume 3 registers.
11149   int NeededArgGPRs = 1;
11150   if (!IsFixed && NeededAlign == 2 * XLen)
11151     NeededArgGPRs = 2 + (ArgGPRsLeft % 2);
11152   else if (Size > XLen && Size <= 2 * XLen)
11153     NeededArgGPRs = 2;
11154 
11155   if (NeededArgGPRs > ArgGPRsLeft) {
11156     MustUseStack = true;
11157     NeededArgGPRs = ArgGPRsLeft;
11158   }
11159 
11160   ArgGPRsLeft -= NeededArgGPRs;
11161 
11162   if (!isAggregateTypeForABI(Ty) && !Ty->isVectorType()) {
11163     // Treat an enum type as its underlying type.
11164     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
11165       Ty = EnumTy->getDecl()->getIntegerType();
11166 
11167     // All integral types are promoted to XLen width, unless passed on the
11168     // stack.
11169     if (Size < XLen && Ty->isIntegralOrEnumerationType() && !MustUseStack) {
11170       return extendType(Ty);
11171     }
11172 
11173     if (const auto *EIT = Ty->getAs<BitIntType>()) {
11174       if (EIT->getNumBits() < XLen && !MustUseStack)
11175         return extendType(Ty);
11176       if (EIT->getNumBits() > 128 ||
11177           (!getContext().getTargetInfo().hasInt128Type() &&
11178            EIT->getNumBits() > 64))
11179         return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
11180     }
11181 
11182     return ABIArgInfo::getDirect();
11183   }
11184 
11185   // Aggregates which are <= 2*XLen will be passed in registers if possible,
11186   // so coerce to integers.
11187   if (Size <= 2 * XLen) {
11188     unsigned Alignment = getContext().getTypeAlign(Ty);
11189 
11190     // Use a single XLen int if possible, 2*XLen if 2*XLen alignment is
11191     // required, and a 2-element XLen array if only XLen alignment is required.
11192     if (Size <= XLen) {
11193       return ABIArgInfo::getDirect(
11194           llvm::IntegerType::get(getVMContext(), XLen));
11195     } else if (Alignment == 2 * XLen) {
11196       return ABIArgInfo::getDirect(
11197           llvm::IntegerType::get(getVMContext(), 2 * XLen));
11198     } else {
11199       return ABIArgInfo::getDirect(llvm::ArrayType::get(
11200           llvm::IntegerType::get(getVMContext(), XLen), 2));
11201     }
11202   }
11203   return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
11204 }
11205 
11206 ABIArgInfo RISCVABIInfo::classifyReturnType(QualType RetTy) const {
11207   if (RetTy->isVoidType())
11208     return ABIArgInfo::getIgnore();
11209 
11210   int ArgGPRsLeft = 2;
11211   int ArgFPRsLeft = FLen ? 2 : 0;
11212 
11213   // The rules for return and argument types are the same, so defer to
11214   // classifyArgumentType.
11215   return classifyArgumentType(RetTy, /*IsFixed=*/true, ArgGPRsLeft,
11216                               ArgFPRsLeft);
11217 }
11218 
11219 Address RISCVABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
11220                                 QualType Ty) const {
11221   CharUnits SlotSize = CharUnits::fromQuantity(XLen / 8);
11222 
11223   // Empty records are ignored for parameter passing purposes.
11224   if (isEmptyRecord(getContext(), Ty, true)) {
11225     Address Addr = Address(CGF.Builder.CreateLoad(VAListAddr),
11226                            getVAListElementType(CGF), SlotSize);
11227     Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
11228     return Addr;
11229   }
11230 
11231   auto TInfo = getContext().getTypeInfoInChars(Ty);
11232 
11233   // Arguments bigger than 2*Xlen bytes are passed indirectly.
11234   bool IsIndirect = TInfo.Width > 2 * SlotSize;
11235 
11236   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TInfo,
11237                           SlotSize, /*AllowHigherAlign=*/true);
11238 }
11239 
11240 ABIArgInfo RISCVABIInfo::extendType(QualType Ty) const {
11241   int TySize = getContext().getTypeSize(Ty);
11242   // RV64 ABI requires unsigned 32 bit integers to be sign extended.
11243   if (XLen == 64 && Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
11244     return ABIArgInfo::getSignExtend(Ty);
11245   return ABIArgInfo::getExtend(Ty);
11246 }
11247 
11248 namespace {
11249 class RISCVTargetCodeGenInfo : public TargetCodeGenInfo {
11250 public:
11251   RISCVTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, unsigned XLen,
11252                          unsigned FLen)
11253       : TargetCodeGenInfo(std::make_unique<RISCVABIInfo>(CGT, XLen, FLen)) {}
11254 
11255   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
11256                            CodeGen::CodeGenModule &CGM) const override {
11257     const auto *FD = dyn_cast_or_null<FunctionDecl>(D);
11258     if (!FD) return;
11259 
11260     const auto *Attr = FD->getAttr<RISCVInterruptAttr>();
11261     if (!Attr)
11262       return;
11263 
11264     const char *Kind;
11265     switch (Attr->getInterrupt()) {
11266     case RISCVInterruptAttr::user: Kind = "user"; break;
11267     case RISCVInterruptAttr::supervisor: Kind = "supervisor"; break;
11268     case RISCVInterruptAttr::machine: Kind = "machine"; break;
11269     }
11270 
11271     auto *Fn = cast<llvm::Function>(GV);
11272 
11273     Fn->addFnAttr("interrupt", Kind);
11274   }
11275 };
11276 } // namespace
11277 
11278 //===----------------------------------------------------------------------===//
11279 // VE ABI Implementation.
11280 //
11281 namespace {
11282 class VEABIInfo : public DefaultABIInfo {
11283 public:
11284   VEABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
11285 
11286 private:
11287   ABIArgInfo classifyReturnType(QualType RetTy) const;
11288   ABIArgInfo classifyArgumentType(QualType RetTy) const;
11289   void computeInfo(CGFunctionInfo &FI) const override;
11290 };
11291 } // end anonymous namespace
11292 
11293 ABIArgInfo VEABIInfo::classifyReturnType(QualType Ty) const {
11294   if (Ty->isAnyComplexType())
11295     return ABIArgInfo::getDirect();
11296   uint64_t Size = getContext().getTypeSize(Ty);
11297   if (Size < 64 && Ty->isIntegerType())
11298     return ABIArgInfo::getExtend(Ty);
11299   return DefaultABIInfo::classifyReturnType(Ty);
11300 }
11301 
11302 ABIArgInfo VEABIInfo::classifyArgumentType(QualType Ty) const {
11303   if (Ty->isAnyComplexType())
11304     return ABIArgInfo::getDirect();
11305   uint64_t Size = getContext().getTypeSize(Ty);
11306   if (Size < 64 && Ty->isIntegerType())
11307     return ABIArgInfo::getExtend(Ty);
11308   return DefaultABIInfo::classifyArgumentType(Ty);
11309 }
11310 
11311 void VEABIInfo::computeInfo(CGFunctionInfo &FI) const {
11312   FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
11313   for (auto &Arg : FI.arguments())
11314     Arg.info = classifyArgumentType(Arg.type);
11315 }
11316 
11317 namespace {
11318 class VETargetCodeGenInfo : public TargetCodeGenInfo {
11319 public:
11320   VETargetCodeGenInfo(CodeGenTypes &CGT)
11321       : TargetCodeGenInfo(std::make_unique<VEABIInfo>(CGT)) {}
11322   // VE ABI requires the arguments of variadic and prototype-less functions
11323   // are passed in both registers and memory.
11324   bool isNoProtoCallVariadic(const CallArgList &args,
11325                              const FunctionNoProtoType *fnType) const override {
11326     return true;
11327   }
11328 };
11329 } // end anonymous namespace
11330 
11331 //===----------------------------------------------------------------------===//
11332 // Driver code
11333 //===----------------------------------------------------------------------===//
11334 
11335 bool CodeGenModule::supportsCOMDAT() const {
11336   return getTriple().supportsCOMDAT();
11337 }
11338 
11339 const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
11340   if (TheTargetCodeGenInfo)
11341     return *TheTargetCodeGenInfo;
11342 
11343   // Helper to set the unique_ptr while still keeping the return value.
11344   auto SetCGInfo = [&](TargetCodeGenInfo *P) -> const TargetCodeGenInfo & {
11345     this->TheTargetCodeGenInfo.reset(P);
11346     return *P;
11347   };
11348 
11349   const llvm::Triple &Triple = getTarget().getTriple();
11350   switch (Triple.getArch()) {
11351   default:
11352     return SetCGInfo(new DefaultTargetCodeGenInfo(Types));
11353 
11354   case llvm::Triple::le32:
11355     return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
11356   case llvm::Triple::m68k:
11357     return SetCGInfo(new M68kTargetCodeGenInfo(Types));
11358   case llvm::Triple::mips:
11359   case llvm::Triple::mipsel:
11360     if (Triple.getOS() == llvm::Triple::NaCl)
11361       return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
11362     return SetCGInfo(new MIPSTargetCodeGenInfo(Types, true));
11363 
11364   case llvm::Triple::mips64:
11365   case llvm::Triple::mips64el:
11366     return SetCGInfo(new MIPSTargetCodeGenInfo(Types, false));
11367 
11368   case llvm::Triple::avr: {
11369     // For passing parameters, R8~R25 are used on avr, and R18~R25 are used
11370     // on avrtiny. For passing return value, R18~R25 are used on avr, and
11371     // R22~R25 are used on avrtiny.
11372     unsigned NPR = getTarget().getABI() == "avrtiny" ? 6 : 18;
11373     unsigned NRR = getTarget().getABI() == "avrtiny" ? 4 : 8;
11374     return SetCGInfo(new AVRTargetCodeGenInfo(Types, NPR, NRR));
11375   }
11376 
11377   case llvm::Triple::aarch64:
11378   case llvm::Triple::aarch64_32:
11379   case llvm::Triple::aarch64_be: {
11380     AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS;
11381     if (getTarget().getABI() == "darwinpcs")
11382       Kind = AArch64ABIInfo::DarwinPCS;
11383     else if (Triple.isOSWindows())
11384       return SetCGInfo(
11385           new WindowsAArch64TargetCodeGenInfo(Types, AArch64ABIInfo::Win64));
11386 
11387     return SetCGInfo(new AArch64TargetCodeGenInfo(Types, Kind));
11388   }
11389 
11390   case llvm::Triple::wasm32:
11391   case llvm::Triple::wasm64: {
11392     WebAssemblyABIInfo::ABIKind Kind = WebAssemblyABIInfo::MVP;
11393     if (getTarget().getABI() == "experimental-mv")
11394       Kind = WebAssemblyABIInfo::ExperimentalMV;
11395     return SetCGInfo(new WebAssemblyTargetCodeGenInfo(Types, Kind));
11396   }
11397 
11398   case llvm::Triple::arm:
11399   case llvm::Triple::armeb:
11400   case llvm::Triple::thumb:
11401   case llvm::Triple::thumbeb: {
11402     if (Triple.getOS() == llvm::Triple::Win32) {
11403       return SetCGInfo(
11404           new WindowsARMTargetCodeGenInfo(Types, ARMABIInfo::AAPCS_VFP));
11405     }
11406 
11407     ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
11408     StringRef ABIStr = getTarget().getABI();
11409     if (ABIStr == "apcs-gnu")
11410       Kind = ARMABIInfo::APCS;
11411     else if (ABIStr == "aapcs16")
11412       Kind = ARMABIInfo::AAPCS16_VFP;
11413     else if (CodeGenOpts.FloatABI == "hard" ||
11414              (CodeGenOpts.FloatABI != "soft" &&
11415               (Triple.getEnvironment() == llvm::Triple::GNUEABIHF ||
11416                Triple.getEnvironment() == llvm::Triple::MuslEABIHF ||
11417                Triple.getEnvironment() == llvm::Triple::EABIHF)))
11418       Kind = ARMABIInfo::AAPCS_VFP;
11419 
11420     return SetCGInfo(new ARMTargetCodeGenInfo(Types, Kind));
11421   }
11422 
11423   case llvm::Triple::ppc: {
11424     if (Triple.isOSAIX())
11425       return SetCGInfo(new AIXTargetCodeGenInfo(Types, /*Is64Bit*/ false));
11426 
11427     bool IsSoftFloat =
11428         CodeGenOpts.FloatABI == "soft" || getTarget().hasFeature("spe");
11429     bool RetSmallStructInRegABI =
11430         PPC32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
11431     return SetCGInfo(
11432         new PPC32TargetCodeGenInfo(Types, IsSoftFloat, RetSmallStructInRegABI));
11433   }
11434   case llvm::Triple::ppcle: {
11435     bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
11436     bool RetSmallStructInRegABI =
11437         PPC32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
11438     return SetCGInfo(
11439         new PPC32TargetCodeGenInfo(Types, IsSoftFloat, RetSmallStructInRegABI));
11440   }
11441   case llvm::Triple::ppc64:
11442     if (Triple.isOSAIX())
11443       return SetCGInfo(new AIXTargetCodeGenInfo(Types, /*Is64Bit*/ true));
11444 
11445     if (Triple.isOSBinFormatELF()) {
11446       PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1;
11447       if (getTarget().getABI() == "elfv2")
11448         Kind = PPC64_SVR4_ABIInfo::ELFv2;
11449       bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
11450 
11451       return SetCGInfo(
11452           new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, IsSoftFloat));
11453     }
11454     return SetCGInfo(new PPC64TargetCodeGenInfo(Types));
11455   case llvm::Triple::ppc64le: {
11456     assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
11457     PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2;
11458     if (getTarget().getABI() == "elfv1")
11459       Kind = PPC64_SVR4_ABIInfo::ELFv1;
11460     bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
11461 
11462     return SetCGInfo(
11463         new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, IsSoftFloat));
11464   }
11465 
11466   case llvm::Triple::nvptx:
11467   case llvm::Triple::nvptx64:
11468     return SetCGInfo(new NVPTXTargetCodeGenInfo(Types));
11469 
11470   case llvm::Triple::msp430:
11471     return SetCGInfo(new MSP430TargetCodeGenInfo(Types));
11472 
11473   case llvm::Triple::riscv32:
11474   case llvm::Triple::riscv64: {
11475     StringRef ABIStr = getTarget().getABI();
11476     unsigned XLen = getTarget().getPointerWidth(0);
11477     unsigned ABIFLen = 0;
11478     if (ABIStr.endswith("f"))
11479       ABIFLen = 32;
11480     else if (ABIStr.endswith("d"))
11481       ABIFLen = 64;
11482     return SetCGInfo(new RISCVTargetCodeGenInfo(Types, XLen, ABIFLen));
11483   }
11484 
11485   case llvm::Triple::systemz: {
11486     bool SoftFloat = CodeGenOpts.FloatABI == "soft";
11487     bool HasVector = !SoftFloat && getTarget().getABI() == "vector";
11488     return SetCGInfo(new SystemZTargetCodeGenInfo(Types, HasVector, SoftFloat));
11489   }
11490 
11491   case llvm::Triple::tce:
11492   case llvm::Triple::tcele:
11493     return SetCGInfo(new TCETargetCodeGenInfo(Types));
11494 
11495   case llvm::Triple::x86: {
11496     bool IsDarwinVectorABI = Triple.isOSDarwin();
11497     bool RetSmallStructInRegABI =
11498         X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
11499     bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
11500 
11501     if (Triple.getOS() == llvm::Triple::Win32) {
11502       return SetCGInfo(new WinX86_32TargetCodeGenInfo(
11503           Types, IsDarwinVectorABI, RetSmallStructInRegABI,
11504           IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters));
11505     } else {
11506       return SetCGInfo(new X86_32TargetCodeGenInfo(
11507           Types, IsDarwinVectorABI, RetSmallStructInRegABI,
11508           IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters,
11509           CodeGenOpts.FloatABI == "soft"));
11510     }
11511   }
11512 
11513   case llvm::Triple::x86_64: {
11514     StringRef ABI = getTarget().getABI();
11515     X86AVXABILevel AVXLevel =
11516         (ABI == "avx512"
11517              ? X86AVXABILevel::AVX512
11518              : ABI == "avx" ? X86AVXABILevel::AVX : X86AVXABILevel::None);
11519 
11520     switch (Triple.getOS()) {
11521     case llvm::Triple::Win32:
11522       return SetCGInfo(new WinX86_64TargetCodeGenInfo(Types, AVXLevel));
11523     default:
11524       return SetCGInfo(new X86_64TargetCodeGenInfo(Types, AVXLevel));
11525     }
11526   }
11527   case llvm::Triple::hexagon:
11528     return SetCGInfo(new HexagonTargetCodeGenInfo(Types));
11529   case llvm::Triple::lanai:
11530     return SetCGInfo(new LanaiTargetCodeGenInfo(Types));
11531   case llvm::Triple::r600:
11532     return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
11533   case llvm::Triple::amdgcn:
11534     return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
11535   case llvm::Triple::sparc:
11536     return SetCGInfo(new SparcV8TargetCodeGenInfo(Types));
11537   case llvm::Triple::sparcv9:
11538     return SetCGInfo(new SparcV9TargetCodeGenInfo(Types));
11539   case llvm::Triple::xcore:
11540     return SetCGInfo(new XCoreTargetCodeGenInfo(Types));
11541   case llvm::Triple::arc:
11542     return SetCGInfo(new ARCTargetCodeGenInfo(Types));
11543   case llvm::Triple::spir:
11544   case llvm::Triple::spir64:
11545     return SetCGInfo(new CommonSPIRTargetCodeGenInfo(Types));
11546   case llvm::Triple::spirv32:
11547   case llvm::Triple::spirv64:
11548     return SetCGInfo(new SPIRVTargetCodeGenInfo(Types));
11549   case llvm::Triple::ve:
11550     return SetCGInfo(new VETargetCodeGenInfo(Types));
11551   }
11552 }
11553 
11554 /// Create an OpenCL kernel for an enqueued block.
11555 ///
11556 /// The kernel has the same function type as the block invoke function. Its
11557 /// name is the name of the block invoke function postfixed with "_kernel".
11558 /// It simply calls the block invoke function then returns.
11559 llvm::Function *
11560 TargetCodeGenInfo::createEnqueuedBlockKernel(CodeGenFunction &CGF,
11561                                              llvm::Function *Invoke,
11562                                              llvm::Type *BlockTy) const {
11563   auto *InvokeFT = Invoke->getFunctionType();
11564   auto &C = CGF.getLLVMContext();
11565   std::string Name = Invoke->getName().str() + "_kernel";
11566   auto *FT = llvm::FunctionType::get(llvm::Type::getVoidTy(C),
11567                                      InvokeFT->params(), false);
11568   auto *F = llvm::Function::Create(FT, llvm::GlobalValue::ExternalLinkage, Name,
11569                                    &CGF.CGM.getModule());
11570   auto IP = CGF.Builder.saveIP();
11571   auto *BB = llvm::BasicBlock::Create(C, "entry", F);
11572   auto &Builder = CGF.Builder;
11573   Builder.SetInsertPoint(BB);
11574   llvm::SmallVector<llvm::Value *, 2> Args(llvm::make_pointer_range(F->args()));
11575   llvm::CallInst *call = Builder.CreateCall(Invoke, Args);
11576   call->setCallingConv(Invoke->getCallingConv());
11577   Builder.CreateRetVoid();
11578   Builder.restoreIP(IP);
11579   return F;
11580 }
11581 
11582 /// Create an OpenCL kernel for an enqueued block.
11583 ///
11584 /// The type of the first argument (the block literal) is the struct type
11585 /// of the block literal instead of a pointer type. The first argument
11586 /// (block literal) is passed directly by value to the kernel. The kernel
11587 /// allocates the same type of struct on stack and stores the block literal
11588 /// to it and passes its pointer to the block invoke function. The kernel
11589 /// has "enqueued-block" function attribute and kernel argument metadata.
11590 llvm::Function *AMDGPUTargetCodeGenInfo::createEnqueuedBlockKernel(
11591     CodeGenFunction &CGF, llvm::Function *Invoke,
11592     llvm::Type *BlockTy) const {
11593   auto &Builder = CGF.Builder;
11594   auto &C = CGF.getLLVMContext();
11595 
11596   auto *InvokeFT = Invoke->getFunctionType();
11597   llvm::SmallVector<llvm::Type *, 2> ArgTys;
11598   llvm::SmallVector<llvm::Metadata *, 8> AddressQuals;
11599   llvm::SmallVector<llvm::Metadata *, 8> AccessQuals;
11600   llvm::SmallVector<llvm::Metadata *, 8> ArgTypeNames;
11601   llvm::SmallVector<llvm::Metadata *, 8> ArgBaseTypeNames;
11602   llvm::SmallVector<llvm::Metadata *, 8> ArgTypeQuals;
11603   llvm::SmallVector<llvm::Metadata *, 8> ArgNames;
11604 
11605   ArgTys.push_back(BlockTy);
11606   ArgTypeNames.push_back(llvm::MDString::get(C, "__block_literal"));
11607   AddressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(0)));
11608   ArgBaseTypeNames.push_back(llvm::MDString::get(C, "__block_literal"));
11609   ArgTypeQuals.push_back(llvm::MDString::get(C, ""));
11610   AccessQuals.push_back(llvm::MDString::get(C, "none"));
11611   ArgNames.push_back(llvm::MDString::get(C, "block_literal"));
11612   for (unsigned I = 1, E = InvokeFT->getNumParams(); I < E; ++I) {
11613     ArgTys.push_back(InvokeFT->getParamType(I));
11614     ArgTypeNames.push_back(llvm::MDString::get(C, "void*"));
11615     AddressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(3)));
11616     AccessQuals.push_back(llvm::MDString::get(C, "none"));
11617     ArgBaseTypeNames.push_back(llvm::MDString::get(C, "void*"));
11618     ArgTypeQuals.push_back(llvm::MDString::get(C, ""));
11619     ArgNames.push_back(
11620         llvm::MDString::get(C, (Twine("local_arg") + Twine(I)).str()));
11621   }
11622   std::string Name = Invoke->getName().str() + "_kernel";
11623   auto *FT = llvm::FunctionType::get(llvm::Type::getVoidTy(C), ArgTys, false);
11624   auto *F = llvm::Function::Create(FT, llvm::GlobalValue::InternalLinkage, Name,
11625                                    &CGF.CGM.getModule());
11626   F->addFnAttr("enqueued-block");
11627   auto IP = CGF.Builder.saveIP();
11628   auto *BB = llvm::BasicBlock::Create(C, "entry", F);
11629   Builder.SetInsertPoint(BB);
11630   const auto BlockAlign = CGF.CGM.getDataLayout().getPrefTypeAlign(BlockTy);
11631   auto *BlockPtr = Builder.CreateAlloca(BlockTy, nullptr);
11632   BlockPtr->setAlignment(BlockAlign);
11633   Builder.CreateAlignedStore(F->arg_begin(), BlockPtr, BlockAlign);
11634   auto *Cast = Builder.CreatePointerCast(BlockPtr, InvokeFT->getParamType(0));
11635   llvm::SmallVector<llvm::Value *, 2> Args;
11636   Args.push_back(Cast);
11637   for (auto I = F->arg_begin() + 1, E = F->arg_end(); I != E; ++I)
11638     Args.push_back(I);
11639   llvm::CallInst *call = Builder.CreateCall(Invoke, Args);
11640   call->setCallingConv(Invoke->getCallingConv());
11641   Builder.CreateRetVoid();
11642   Builder.restoreIP(IP);
11643 
11644   F->setMetadata("kernel_arg_addr_space", llvm::MDNode::get(C, AddressQuals));
11645   F->setMetadata("kernel_arg_access_qual", llvm::MDNode::get(C, AccessQuals));
11646   F->setMetadata("kernel_arg_type", llvm::MDNode::get(C, ArgTypeNames));
11647   F->setMetadata("kernel_arg_base_type",
11648                  llvm::MDNode::get(C, ArgBaseTypeNames));
11649   F->setMetadata("kernel_arg_type_qual", llvm::MDNode::get(C, ArgTypeQuals));
11650   if (CGF.CGM.getCodeGenOpts().EmitOpenCLArgMetadata)
11651     F->setMetadata("kernel_arg_name", llvm::MDNode::get(C, ArgNames));
11652 
11653   return F;
11654 }
11655