1 //===---- TargetInfo.cpp - Encapsulate target details -----------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // These classes wrap the information about a call or function
10 // definition used to handle ABI compliancy.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "TargetInfo.h"
15 #include "ABIInfo.h"
16 #include "CGBlocks.h"
17 #include "CGCXXABI.h"
18 #include "CGValue.h"
19 #include "CodeGenFunction.h"
20 #include "clang/AST/Attr.h"
21 #include "clang/AST/RecordLayout.h"
22 #include "clang/Basic/CodeGenOptions.h"
23 #include "clang/Basic/DiagnosticFrontend.h"
24 #include "clang/Basic/Builtins.h"
25 #include "clang/CodeGen/CGFunctionInfo.h"
26 #include "clang/CodeGen/SwiftCallingConv.h"
27 #include "llvm/ADT/SmallBitVector.h"
28 #include "llvm/ADT/StringExtras.h"
29 #include "llvm/ADT/StringSwitch.h"
30 #include "llvm/ADT/Triple.h"
31 #include "llvm/ADT/Twine.h"
32 #include "llvm/IR/DataLayout.h"
33 #include "llvm/IR/IntrinsicsNVPTX.h"
34 #include "llvm/IR/IntrinsicsS390.h"
35 #include "llvm/IR/Type.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include <algorithm> // std::sort
38 
39 using namespace clang;
40 using namespace CodeGen;
41 
42 // Helper for coercing an aggregate argument or return value into an integer
43 // array of the same size (including padding) and alignment.  This alternate
44 // coercion happens only for the RenderScript ABI and can be removed after
45 // runtimes that rely on it are no longer supported.
46 //
47 // RenderScript assumes that the size of the argument / return value in the IR
48 // is the same as the size of the corresponding qualified type. This helper
49 // coerces the aggregate type into an array of the same size (including
50 // padding).  This coercion is used in lieu of expansion of struct members or
51 // other canonical coercions that return a coerced-type of larger size.
52 //
53 // Ty          - The argument / return value type
54 // Context     - The associated ASTContext
55 // LLVMContext - The associated LLVMContext
56 static ABIArgInfo coerceToIntArray(QualType Ty,
57                                    ASTContext &Context,
58                                    llvm::LLVMContext &LLVMContext) {
59   // Alignment and Size are measured in bits.
60   const uint64_t Size = Context.getTypeSize(Ty);
61   const uint64_t Alignment = Context.getTypeAlign(Ty);
62   llvm::Type *IntType = llvm::Type::getIntNTy(LLVMContext, Alignment);
63   const uint64_t NumElements = (Size + Alignment - 1) / Alignment;
64   return ABIArgInfo::getDirect(llvm::ArrayType::get(IntType, NumElements));
65 }
66 
67 static void AssignToArrayRange(CodeGen::CGBuilderTy &Builder,
68                                llvm::Value *Array,
69                                llvm::Value *Value,
70                                unsigned FirstIndex,
71                                unsigned LastIndex) {
72   // Alternatively, we could emit this as a loop in the source.
73   for (unsigned I = FirstIndex; I <= LastIndex; ++I) {
74     llvm::Value *Cell =
75         Builder.CreateConstInBoundsGEP1_32(Builder.getInt8Ty(), Array, I);
76     Builder.CreateAlignedStore(Value, Cell, CharUnits::One());
77   }
78 }
79 
80 static bool isAggregateTypeForABI(QualType T) {
81   return !CodeGenFunction::hasScalarEvaluationKind(T) ||
82          T->isMemberFunctionPointerType();
83 }
84 
85 ABIArgInfo ABIInfo::getNaturalAlignIndirect(QualType Ty, bool ByVal,
86                                             bool Realign,
87                                             llvm::Type *Padding) const {
88   return ABIArgInfo::getIndirect(getContext().getTypeAlignInChars(Ty), ByVal,
89                                  Realign, Padding);
90 }
91 
92 ABIArgInfo
93 ABIInfo::getNaturalAlignIndirectInReg(QualType Ty, bool Realign) const {
94   return ABIArgInfo::getIndirectInReg(getContext().getTypeAlignInChars(Ty),
95                                       /*ByVal*/ false, Realign);
96 }
97 
98 Address ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
99                              QualType Ty) const {
100   return Address::invalid();
101 }
102 
103 bool ABIInfo::isPromotableIntegerTypeForABI(QualType Ty) const {
104   if (Ty->isPromotableIntegerType())
105     return true;
106 
107   if (const auto *EIT = Ty->getAs<BitIntType>())
108     if (EIT->getNumBits() < getContext().getTypeSize(getContext().IntTy))
109       return true;
110 
111   return false;
112 }
113 
114 ABIInfo::~ABIInfo() {}
115 
116 /// Does the given lowering require more than the given number of
117 /// registers when expanded?
118 ///
119 /// This is intended to be the basis of a reasonable basic implementation
120 /// of should{Pass,Return}IndirectlyForSwift.
121 ///
122 /// For most targets, a limit of four total registers is reasonable; this
123 /// limits the amount of code required in order to move around the value
124 /// in case it wasn't produced immediately prior to the call by the caller
125 /// (or wasn't produced in exactly the right registers) or isn't used
126 /// immediately within the callee.  But some targets may need to further
127 /// limit the register count due to an inability to support that many
128 /// return registers.
129 static bool occupiesMoreThan(CodeGenTypes &cgt,
130                              ArrayRef<llvm::Type*> scalarTypes,
131                              unsigned maxAllRegisters) {
132   unsigned intCount = 0, fpCount = 0;
133   for (llvm::Type *type : scalarTypes) {
134     if (type->isPointerTy()) {
135       intCount++;
136     } else if (auto intTy = dyn_cast<llvm::IntegerType>(type)) {
137       auto ptrWidth = cgt.getTarget().getPointerWidth(0);
138       intCount += (intTy->getBitWidth() + ptrWidth - 1) / ptrWidth;
139     } else {
140       assert(type->isVectorTy() || type->isFloatingPointTy());
141       fpCount++;
142     }
143   }
144 
145   return (intCount + fpCount > maxAllRegisters);
146 }
147 
148 bool SwiftABIInfo::isLegalVectorTypeForSwift(CharUnits vectorSize,
149                                              llvm::Type *eltTy,
150                                              unsigned numElts) const {
151   // The default implementation of this assumes that the target guarantees
152   // 128-bit SIMD support but nothing more.
153   return (vectorSize.getQuantity() > 8 && vectorSize.getQuantity() <= 16);
154 }
155 
156 static CGCXXABI::RecordArgABI getRecordArgABI(const RecordType *RT,
157                                               CGCXXABI &CXXABI) {
158   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
159   if (!RD) {
160     if (!RT->getDecl()->canPassInRegisters())
161       return CGCXXABI::RAA_Indirect;
162     return CGCXXABI::RAA_Default;
163   }
164   return CXXABI.getRecordArgABI(RD);
165 }
166 
167 static CGCXXABI::RecordArgABI getRecordArgABI(QualType T,
168                                               CGCXXABI &CXXABI) {
169   const RecordType *RT = T->getAs<RecordType>();
170   if (!RT)
171     return CGCXXABI::RAA_Default;
172   return getRecordArgABI(RT, CXXABI);
173 }
174 
175 static bool classifyReturnType(const CGCXXABI &CXXABI, CGFunctionInfo &FI,
176                                const ABIInfo &Info) {
177   QualType Ty = FI.getReturnType();
178 
179   if (const auto *RT = Ty->getAs<RecordType>())
180     if (!isa<CXXRecordDecl>(RT->getDecl()) &&
181         !RT->getDecl()->canPassInRegisters()) {
182       FI.getReturnInfo() = Info.getNaturalAlignIndirect(Ty);
183       return true;
184     }
185 
186   return CXXABI.classifyReturnType(FI);
187 }
188 
189 /// Pass transparent unions as if they were the type of the first element. Sema
190 /// should ensure that all elements of the union have the same "machine type".
191 static QualType useFirstFieldIfTransparentUnion(QualType Ty) {
192   if (const RecordType *UT = Ty->getAsUnionType()) {
193     const RecordDecl *UD = UT->getDecl();
194     if (UD->hasAttr<TransparentUnionAttr>()) {
195       assert(!UD->field_empty() && "sema created an empty transparent union");
196       return UD->field_begin()->getType();
197     }
198   }
199   return Ty;
200 }
201 
202 CGCXXABI &ABIInfo::getCXXABI() const {
203   return CGT.getCXXABI();
204 }
205 
206 ASTContext &ABIInfo::getContext() const {
207   return CGT.getContext();
208 }
209 
210 llvm::LLVMContext &ABIInfo::getVMContext() const {
211   return CGT.getLLVMContext();
212 }
213 
214 const llvm::DataLayout &ABIInfo::getDataLayout() const {
215   return CGT.getDataLayout();
216 }
217 
218 const TargetInfo &ABIInfo::getTarget() const {
219   return CGT.getTarget();
220 }
221 
222 const CodeGenOptions &ABIInfo::getCodeGenOpts() const {
223   return CGT.getCodeGenOpts();
224 }
225 
226 bool ABIInfo::isAndroid() const { return getTarget().getTriple().isAndroid(); }
227 
228 bool ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
229   return false;
230 }
231 
232 bool ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
233                                                 uint64_t Members) const {
234   return false;
235 }
236 
237 LLVM_DUMP_METHOD void ABIArgInfo::dump() const {
238   raw_ostream &OS = llvm::errs();
239   OS << "(ABIArgInfo Kind=";
240   switch (TheKind) {
241   case Direct:
242     OS << "Direct Type=";
243     if (llvm::Type *Ty = getCoerceToType())
244       Ty->print(OS);
245     else
246       OS << "null";
247     break;
248   case Extend:
249     OS << "Extend";
250     break;
251   case Ignore:
252     OS << "Ignore";
253     break;
254   case InAlloca:
255     OS << "InAlloca Offset=" << getInAllocaFieldIndex();
256     break;
257   case Indirect:
258     OS << "Indirect Align=" << getIndirectAlign().getQuantity()
259        << " ByVal=" << getIndirectByVal()
260        << " Realign=" << getIndirectRealign();
261     break;
262   case IndirectAliased:
263     OS << "Indirect Align=" << getIndirectAlign().getQuantity()
264        << " AadrSpace=" << getIndirectAddrSpace()
265        << " Realign=" << getIndirectRealign();
266     break;
267   case Expand:
268     OS << "Expand";
269     break;
270   case CoerceAndExpand:
271     OS << "CoerceAndExpand Type=";
272     getCoerceAndExpandType()->print(OS);
273     break;
274   }
275   OS << ")\n";
276 }
277 
278 // Dynamically round a pointer up to a multiple of the given alignment.
279 static llvm::Value *emitRoundPointerUpToAlignment(CodeGenFunction &CGF,
280                                                   llvm::Value *Ptr,
281                                                   CharUnits Align) {
282   llvm::Value *PtrAsInt = Ptr;
283   // OverflowArgArea = (OverflowArgArea + Align - 1) & -Align;
284   PtrAsInt = CGF.Builder.CreatePtrToInt(PtrAsInt, CGF.IntPtrTy);
285   PtrAsInt = CGF.Builder.CreateAdd(PtrAsInt,
286         llvm::ConstantInt::get(CGF.IntPtrTy, Align.getQuantity() - 1));
287   PtrAsInt = CGF.Builder.CreateAnd(PtrAsInt,
288            llvm::ConstantInt::get(CGF.IntPtrTy, -Align.getQuantity()));
289   PtrAsInt = CGF.Builder.CreateIntToPtr(PtrAsInt,
290                                         Ptr->getType(),
291                                         Ptr->getName() + ".aligned");
292   return PtrAsInt;
293 }
294 
295 /// Emit va_arg for a platform using the common void* representation,
296 /// where arguments are simply emitted in an array of slots on the stack.
297 ///
298 /// This version implements the core direct-value passing rules.
299 ///
300 /// \param SlotSize - The size and alignment of a stack slot.
301 ///   Each argument will be allocated to a multiple of this number of
302 ///   slots, and all the slots will be aligned to this value.
303 /// \param AllowHigherAlign - The slot alignment is not a cap;
304 ///   an argument type with an alignment greater than the slot size
305 ///   will be emitted on a higher-alignment address, potentially
306 ///   leaving one or more empty slots behind as padding.  If this
307 ///   is false, the returned address might be less-aligned than
308 ///   DirectAlign.
309 static Address emitVoidPtrDirectVAArg(CodeGenFunction &CGF,
310                                       Address VAListAddr,
311                                       llvm::Type *DirectTy,
312                                       CharUnits DirectSize,
313                                       CharUnits DirectAlign,
314                                       CharUnits SlotSize,
315                                       bool AllowHigherAlign) {
316   // Cast the element type to i8* if necessary.  Some platforms define
317   // va_list as a struct containing an i8* instead of just an i8*.
318   if (VAListAddr.getElementType() != CGF.Int8PtrTy)
319     VAListAddr = CGF.Builder.CreateElementBitCast(VAListAddr, CGF.Int8PtrTy);
320 
321   llvm::Value *Ptr = CGF.Builder.CreateLoad(VAListAddr, "argp.cur");
322 
323   // If the CC aligns values higher than the slot size, do so if needed.
324   Address Addr = Address::invalid();
325   if (AllowHigherAlign && DirectAlign > SlotSize) {
326     Addr = Address(emitRoundPointerUpToAlignment(CGF, Ptr, DirectAlign),
327                                                  DirectAlign);
328   } else {
329     Addr = Address(Ptr, SlotSize);
330   }
331 
332   // Advance the pointer past the argument, then store that back.
333   CharUnits FullDirectSize = DirectSize.alignTo(SlotSize);
334   Address NextPtr =
335       CGF.Builder.CreateConstInBoundsByteGEP(Addr, FullDirectSize, "argp.next");
336   CGF.Builder.CreateStore(NextPtr.getPointer(), VAListAddr);
337 
338   // If the argument is smaller than a slot, and this is a big-endian
339   // target, the argument will be right-adjusted in its slot.
340   if (DirectSize < SlotSize && CGF.CGM.getDataLayout().isBigEndian() &&
341       !DirectTy->isStructTy()) {
342     Addr = CGF.Builder.CreateConstInBoundsByteGEP(Addr, SlotSize - DirectSize);
343   }
344 
345   Addr = CGF.Builder.CreateElementBitCast(Addr, DirectTy);
346   return Addr;
347 }
348 
349 /// Emit va_arg for a platform using the common void* representation,
350 /// where arguments are simply emitted in an array of slots on the stack.
351 ///
352 /// \param IsIndirect - Values of this type are passed indirectly.
353 /// \param ValueInfo - The size and alignment of this type, generally
354 ///   computed with getContext().getTypeInfoInChars(ValueTy).
355 /// \param SlotSizeAndAlign - The size and alignment of a stack slot.
356 ///   Each argument will be allocated to a multiple of this number of
357 ///   slots, and all the slots will be aligned to this value.
358 /// \param AllowHigherAlign - The slot alignment is not a cap;
359 ///   an argument type with an alignment greater than the slot size
360 ///   will be emitted on a higher-alignment address, potentially
361 ///   leaving one or more empty slots behind as padding.
362 static Address emitVoidPtrVAArg(CodeGenFunction &CGF, Address VAListAddr,
363                                 QualType ValueTy, bool IsIndirect,
364                                 TypeInfoChars ValueInfo,
365                                 CharUnits SlotSizeAndAlign,
366                                 bool AllowHigherAlign) {
367   // The size and alignment of the value that was passed directly.
368   CharUnits DirectSize, DirectAlign;
369   if (IsIndirect) {
370     DirectSize = CGF.getPointerSize();
371     DirectAlign = CGF.getPointerAlign();
372   } else {
373     DirectSize = ValueInfo.Width;
374     DirectAlign = ValueInfo.Align;
375   }
376 
377   // Cast the address we've calculated to the right type.
378   llvm::Type *DirectTy = CGF.ConvertTypeForMem(ValueTy);
379   if (IsIndirect)
380     DirectTy = DirectTy->getPointerTo(0);
381 
382   Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, DirectTy,
383                                         DirectSize, DirectAlign,
384                                         SlotSizeAndAlign,
385                                         AllowHigherAlign);
386 
387   if (IsIndirect) {
388     Addr = Address(CGF.Builder.CreateLoad(Addr), ValueInfo.Align);
389   }
390 
391   return Addr;
392 
393 }
394 
395 static Address complexTempStructure(CodeGenFunction &CGF, Address VAListAddr,
396                                     QualType Ty, CharUnits SlotSize,
397                                     CharUnits EltSize, const ComplexType *CTy) {
398   Address Addr =
399       emitVoidPtrDirectVAArg(CGF, VAListAddr, CGF.Int8Ty, SlotSize * 2,
400                              SlotSize, SlotSize, /*AllowHigher*/ true);
401 
402   Address RealAddr = Addr;
403   Address ImagAddr = RealAddr;
404   if (CGF.CGM.getDataLayout().isBigEndian()) {
405     RealAddr =
406         CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, SlotSize - EltSize);
407     ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(ImagAddr,
408                                                       2 * SlotSize - EltSize);
409   } else {
410     ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, SlotSize);
411   }
412 
413   llvm::Type *EltTy = CGF.ConvertTypeForMem(CTy->getElementType());
414   RealAddr = CGF.Builder.CreateElementBitCast(RealAddr, EltTy);
415   ImagAddr = CGF.Builder.CreateElementBitCast(ImagAddr, EltTy);
416   llvm::Value *Real = CGF.Builder.CreateLoad(RealAddr, ".vareal");
417   llvm::Value *Imag = CGF.Builder.CreateLoad(ImagAddr, ".vaimag");
418 
419   Address Temp = CGF.CreateMemTemp(Ty, "vacplx");
420   CGF.EmitStoreOfComplex({Real, Imag}, CGF.MakeAddrLValue(Temp, Ty),
421                          /*init*/ true);
422   return Temp;
423 }
424 
425 static Address emitMergePHI(CodeGenFunction &CGF,
426                             Address Addr1, llvm::BasicBlock *Block1,
427                             Address Addr2, llvm::BasicBlock *Block2,
428                             const llvm::Twine &Name = "") {
429   assert(Addr1.getType() == Addr2.getType());
430   llvm::PHINode *PHI = CGF.Builder.CreatePHI(Addr1.getType(), 2, Name);
431   PHI->addIncoming(Addr1.getPointer(), Block1);
432   PHI->addIncoming(Addr2.getPointer(), Block2);
433   CharUnits Align = std::min(Addr1.getAlignment(), Addr2.getAlignment());
434   return Address(PHI, Addr1.getElementType(), Align);
435 }
436 
437 TargetCodeGenInfo::~TargetCodeGenInfo() = default;
438 
439 // If someone can figure out a general rule for this, that would be great.
440 // It's probably just doomed to be platform-dependent, though.
441 unsigned TargetCodeGenInfo::getSizeOfUnwindException() const {
442   // Verified for:
443   //   x86-64     FreeBSD, Linux, Darwin
444   //   x86-32     FreeBSD, Linux, Darwin
445   //   PowerPC    Linux, Darwin
446   //   ARM        Darwin (*not* EABI)
447   //   AArch64    Linux
448   return 32;
449 }
450 
451 bool TargetCodeGenInfo::isNoProtoCallVariadic(const CallArgList &args,
452                                      const FunctionNoProtoType *fnType) const {
453   // The following conventions are known to require this to be false:
454   //   x86_stdcall
455   //   MIPS
456   // For everything else, we just prefer false unless we opt out.
457   return false;
458 }
459 
460 void
461 TargetCodeGenInfo::getDependentLibraryOption(llvm::StringRef Lib,
462                                              llvm::SmallString<24> &Opt) const {
463   // This assumes the user is passing a library name like "rt" instead of a
464   // filename like "librt.a/so", and that they don't care whether it's static or
465   // dynamic.
466   Opt = "-l";
467   Opt += Lib;
468 }
469 
470 unsigned TargetCodeGenInfo::getOpenCLKernelCallingConv() const {
471   // OpenCL kernels are called via an explicit runtime API with arguments
472   // set with clSetKernelArg(), not as normal sub-functions.
473   // Return SPIR_KERNEL by default as the kernel calling convention to
474   // ensure the fingerprint is fixed such way that each OpenCL argument
475   // gets one matching argument in the produced kernel function argument
476   // list to enable feasible implementation of clSetKernelArg() with
477   // aggregates etc. In case we would use the default C calling conv here,
478   // clSetKernelArg() might break depending on the target-specific
479   // conventions; different targets might split structs passed as values
480   // to multiple function arguments etc.
481   return llvm::CallingConv::SPIR_KERNEL;
482 }
483 
484 llvm::Constant *TargetCodeGenInfo::getNullPointer(const CodeGen::CodeGenModule &CGM,
485     llvm::PointerType *T, QualType QT) const {
486   return llvm::ConstantPointerNull::get(T);
487 }
488 
489 LangAS TargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM,
490                                                    const VarDecl *D) const {
491   assert(!CGM.getLangOpts().OpenCL &&
492          !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) &&
493          "Address space agnostic languages only");
494   return D ? D->getType().getAddressSpace() : LangAS::Default;
495 }
496 
497 llvm::Value *TargetCodeGenInfo::performAddrSpaceCast(
498     CodeGen::CodeGenFunction &CGF, llvm::Value *Src, LangAS SrcAddr,
499     LangAS DestAddr, llvm::Type *DestTy, bool isNonNull) const {
500   // Since target may map different address spaces in AST to the same address
501   // space, an address space conversion may end up as a bitcast.
502   if (auto *C = dyn_cast<llvm::Constant>(Src))
503     return performAddrSpaceCast(CGF.CGM, C, SrcAddr, DestAddr, DestTy);
504   // Try to preserve the source's name to make IR more readable.
505   return CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
506       Src, DestTy, Src->hasName() ? Src->getName() + ".ascast" : "");
507 }
508 
509 llvm::Constant *
510 TargetCodeGenInfo::performAddrSpaceCast(CodeGenModule &CGM, llvm::Constant *Src,
511                                         LangAS SrcAddr, LangAS DestAddr,
512                                         llvm::Type *DestTy) const {
513   // Since target may map different address spaces in AST to the same address
514   // space, an address space conversion may end up as a bitcast.
515   return llvm::ConstantExpr::getPointerCast(Src, DestTy);
516 }
517 
518 llvm::SyncScope::ID
519 TargetCodeGenInfo::getLLVMSyncScopeID(const LangOptions &LangOpts,
520                                       SyncScope Scope,
521                                       llvm::AtomicOrdering Ordering,
522                                       llvm::LLVMContext &Ctx) const {
523   return Ctx.getOrInsertSyncScopeID(""); /* default sync scope */
524 }
525 
526 static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays);
527 
528 /// isEmptyField - Return true iff a the field is "empty", that is it
529 /// is an unnamed bit-field or an (array of) empty record(s).
530 static bool isEmptyField(ASTContext &Context, const FieldDecl *FD,
531                          bool AllowArrays) {
532   if (FD->isUnnamedBitfield())
533     return true;
534 
535   QualType FT = FD->getType();
536 
537   // Constant arrays of empty records count as empty, strip them off.
538   // Constant arrays of zero length always count as empty.
539   bool WasArray = false;
540   if (AllowArrays)
541     while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
542       if (AT->getSize() == 0)
543         return true;
544       FT = AT->getElementType();
545       // The [[no_unique_address]] special case below does not apply to
546       // arrays of C++ empty records, so we need to remember this fact.
547       WasArray = true;
548     }
549 
550   const RecordType *RT = FT->getAs<RecordType>();
551   if (!RT)
552     return false;
553 
554   // C++ record fields are never empty, at least in the Itanium ABI.
555   //
556   // FIXME: We should use a predicate for whether this behavior is true in the
557   // current ABI.
558   //
559   // The exception to the above rule are fields marked with the
560   // [[no_unique_address]] attribute (since C++20).  Those do count as empty
561   // according to the Itanium ABI.  The exception applies only to records,
562   // not arrays of records, so we must also check whether we stripped off an
563   // array type above.
564   if (isa<CXXRecordDecl>(RT->getDecl()) &&
565       (WasArray || !FD->hasAttr<NoUniqueAddressAttr>()))
566     return false;
567 
568   return isEmptyRecord(Context, FT, AllowArrays);
569 }
570 
571 /// isEmptyRecord - Return true iff a structure contains only empty
572 /// fields. Note that a structure with a flexible array member is not
573 /// considered empty.
574 static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) {
575   const RecordType *RT = T->getAs<RecordType>();
576   if (!RT)
577     return false;
578   const RecordDecl *RD = RT->getDecl();
579   if (RD->hasFlexibleArrayMember())
580     return false;
581 
582   // If this is a C++ record, check the bases first.
583   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
584     for (const auto &I : CXXRD->bases())
585       if (!isEmptyRecord(Context, I.getType(), true))
586         return false;
587 
588   for (const auto *I : RD->fields())
589     if (!isEmptyField(Context, I, AllowArrays))
590       return false;
591   return true;
592 }
593 
594 /// isSingleElementStruct - Determine if a structure is a "single
595 /// element struct", i.e. it has exactly one non-empty field or
596 /// exactly one field which is itself a single element
597 /// struct. Structures with flexible array members are never
598 /// considered single element structs.
599 ///
600 /// \return The field declaration for the single non-empty field, if
601 /// it exists.
602 static const Type *isSingleElementStruct(QualType T, ASTContext &Context) {
603   const RecordType *RT = T->getAs<RecordType>();
604   if (!RT)
605     return nullptr;
606 
607   const RecordDecl *RD = RT->getDecl();
608   if (RD->hasFlexibleArrayMember())
609     return nullptr;
610 
611   const Type *Found = nullptr;
612 
613   // If this is a C++ record, check the bases first.
614   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
615     for (const auto &I : CXXRD->bases()) {
616       // Ignore empty records.
617       if (isEmptyRecord(Context, I.getType(), true))
618         continue;
619 
620       // If we already found an element then this isn't a single-element struct.
621       if (Found)
622         return nullptr;
623 
624       // If this is non-empty and not a single element struct, the composite
625       // cannot be a single element struct.
626       Found = isSingleElementStruct(I.getType(), Context);
627       if (!Found)
628         return nullptr;
629     }
630   }
631 
632   // Check for single element.
633   for (const auto *FD : RD->fields()) {
634     QualType FT = FD->getType();
635 
636     // Ignore empty fields.
637     if (isEmptyField(Context, FD, true))
638       continue;
639 
640     // If we already found an element then this isn't a single-element
641     // struct.
642     if (Found)
643       return nullptr;
644 
645     // Treat single element arrays as the element.
646     while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
647       if (AT->getSize().getZExtValue() != 1)
648         break;
649       FT = AT->getElementType();
650     }
651 
652     if (!isAggregateTypeForABI(FT)) {
653       Found = FT.getTypePtr();
654     } else {
655       Found = isSingleElementStruct(FT, Context);
656       if (!Found)
657         return nullptr;
658     }
659   }
660 
661   // We don't consider a struct a single-element struct if it has
662   // padding beyond the element type.
663   if (Found && Context.getTypeSize(Found) != Context.getTypeSize(T))
664     return nullptr;
665 
666   return Found;
667 }
668 
669 namespace {
670 Address EmitVAArgInstr(CodeGenFunction &CGF, Address VAListAddr, QualType Ty,
671                        const ABIArgInfo &AI) {
672   // This default implementation defers to the llvm backend's va_arg
673   // instruction. It can handle only passing arguments directly
674   // (typically only handled in the backend for primitive types), or
675   // aggregates passed indirectly by pointer (NOTE: if the "byval"
676   // flag has ABI impact in the callee, this implementation cannot
677   // work.)
678 
679   // Only a few cases are covered here at the moment -- those needed
680   // by the default abi.
681   llvm::Value *Val;
682 
683   if (AI.isIndirect()) {
684     assert(!AI.getPaddingType() &&
685            "Unexpected PaddingType seen in arginfo in generic VAArg emitter!");
686     assert(
687         !AI.getIndirectRealign() &&
688         "Unexpected IndirectRealign seen in arginfo in generic VAArg emitter!");
689 
690     auto TyInfo = CGF.getContext().getTypeInfoInChars(Ty);
691     CharUnits TyAlignForABI = TyInfo.Align;
692 
693     llvm::Type *BaseTy =
694         llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
695     llvm::Value *Addr =
696         CGF.Builder.CreateVAArg(VAListAddr.getPointer(), BaseTy);
697     return Address(Addr, TyAlignForABI);
698   } else {
699     assert((AI.isDirect() || AI.isExtend()) &&
700            "Unexpected ArgInfo Kind in generic VAArg emitter!");
701 
702     assert(!AI.getInReg() &&
703            "Unexpected InReg seen in arginfo in generic VAArg emitter!");
704     assert(!AI.getPaddingType() &&
705            "Unexpected PaddingType seen in arginfo in generic VAArg emitter!");
706     assert(!AI.getDirectOffset() &&
707            "Unexpected DirectOffset seen in arginfo in generic VAArg emitter!");
708     assert(!AI.getCoerceToType() &&
709            "Unexpected CoerceToType seen in arginfo in generic VAArg emitter!");
710 
711     Address Temp = CGF.CreateMemTemp(Ty, "varet");
712     Val = CGF.Builder.CreateVAArg(VAListAddr.getPointer(),
713                                   CGF.ConvertTypeForMem(Ty));
714     CGF.Builder.CreateStore(Val, Temp);
715     return Temp;
716   }
717 }
718 
719 /// DefaultABIInfo - The default implementation for ABI specific
720 /// details. This implementation provides information which results in
721 /// self-consistent and sensible LLVM IR generation, but does not
722 /// conform to any particular ABI.
723 class DefaultABIInfo : public ABIInfo {
724 public:
725   DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
726 
727   ABIArgInfo classifyReturnType(QualType RetTy) const;
728   ABIArgInfo classifyArgumentType(QualType RetTy) const;
729 
730   void computeInfo(CGFunctionInfo &FI) const override {
731     if (!getCXXABI().classifyReturnType(FI))
732       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
733     for (auto &I : FI.arguments())
734       I.info = classifyArgumentType(I.type);
735   }
736 
737   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
738                     QualType Ty) const override {
739     return EmitVAArgInstr(CGF, VAListAddr, Ty, classifyArgumentType(Ty));
740   }
741 };
742 
743 class DefaultTargetCodeGenInfo : public TargetCodeGenInfo {
744 public:
745   DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
746       : TargetCodeGenInfo(std::make_unique<DefaultABIInfo>(CGT)) {}
747 };
748 
749 ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const {
750   Ty = useFirstFieldIfTransparentUnion(Ty);
751 
752   if (isAggregateTypeForABI(Ty)) {
753     // Records with non-trivial destructors/copy-constructors should not be
754     // passed by value.
755     if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
756       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
757 
758     return getNaturalAlignIndirect(Ty);
759   }
760 
761   // Treat an enum type as its underlying type.
762   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
763     Ty = EnumTy->getDecl()->getIntegerType();
764 
765   ASTContext &Context = getContext();
766   if (const auto *EIT = Ty->getAs<BitIntType>())
767     if (EIT->getNumBits() >
768         Context.getTypeSize(Context.getTargetInfo().hasInt128Type()
769                                 ? Context.Int128Ty
770                                 : Context.LongLongTy))
771       return getNaturalAlignIndirect(Ty);
772 
773   return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
774                                             : ABIArgInfo::getDirect());
775 }
776 
777 ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const {
778   if (RetTy->isVoidType())
779     return ABIArgInfo::getIgnore();
780 
781   if (isAggregateTypeForABI(RetTy))
782     return getNaturalAlignIndirect(RetTy);
783 
784   // Treat an enum type as its underlying type.
785   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
786     RetTy = EnumTy->getDecl()->getIntegerType();
787 
788   if (const auto *EIT = RetTy->getAs<BitIntType>())
789     if (EIT->getNumBits() >
790         getContext().getTypeSize(getContext().getTargetInfo().hasInt128Type()
791                                      ? getContext().Int128Ty
792                                      : getContext().LongLongTy))
793       return getNaturalAlignIndirect(RetTy);
794 
795   return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
796                                                : ABIArgInfo::getDirect());
797 }
798 
799 //===----------------------------------------------------------------------===//
800 // WebAssembly ABI Implementation
801 //
802 // This is a very simple ABI that relies a lot on DefaultABIInfo.
803 //===----------------------------------------------------------------------===//
804 
805 class WebAssemblyABIInfo final : public SwiftABIInfo {
806 public:
807   enum ABIKind {
808     MVP = 0,
809     ExperimentalMV = 1,
810   };
811 
812 private:
813   DefaultABIInfo defaultInfo;
814   ABIKind Kind;
815 
816 public:
817   explicit WebAssemblyABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind)
818       : SwiftABIInfo(CGT), defaultInfo(CGT), Kind(Kind) {}
819 
820 private:
821   ABIArgInfo classifyReturnType(QualType RetTy) const;
822   ABIArgInfo classifyArgumentType(QualType Ty) const;
823 
824   // DefaultABIInfo's classifyReturnType and classifyArgumentType are
825   // non-virtual, but computeInfo and EmitVAArg are virtual, so we
826   // overload them.
827   void computeInfo(CGFunctionInfo &FI) const override {
828     if (!getCXXABI().classifyReturnType(FI))
829       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
830     for (auto &Arg : FI.arguments())
831       Arg.info = classifyArgumentType(Arg.type);
832   }
833 
834   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
835                     QualType Ty) const override;
836 
837   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
838                                     bool asReturnValue) const override {
839     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
840   }
841 
842   bool isSwiftErrorInRegister() const override {
843     return false;
844   }
845 };
846 
847 class WebAssemblyTargetCodeGenInfo final : public TargetCodeGenInfo {
848 public:
849   explicit WebAssemblyTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
850                                         WebAssemblyABIInfo::ABIKind K)
851       : TargetCodeGenInfo(std::make_unique<WebAssemblyABIInfo>(CGT, K)) {}
852 
853   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
854                            CodeGen::CodeGenModule &CGM) const override {
855     TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
856     if (const auto *FD = dyn_cast_or_null<FunctionDecl>(D)) {
857       if (const auto *Attr = FD->getAttr<WebAssemblyImportModuleAttr>()) {
858         llvm::Function *Fn = cast<llvm::Function>(GV);
859         llvm::AttrBuilder B(GV->getContext());
860         B.addAttribute("wasm-import-module", Attr->getImportModule());
861         Fn->addFnAttrs(B);
862       }
863       if (const auto *Attr = FD->getAttr<WebAssemblyImportNameAttr>()) {
864         llvm::Function *Fn = cast<llvm::Function>(GV);
865         llvm::AttrBuilder B(GV->getContext());
866         B.addAttribute("wasm-import-name", Attr->getImportName());
867         Fn->addFnAttrs(B);
868       }
869       if (const auto *Attr = FD->getAttr<WebAssemblyExportNameAttr>()) {
870         llvm::Function *Fn = cast<llvm::Function>(GV);
871         llvm::AttrBuilder B(GV->getContext());
872         B.addAttribute("wasm-export-name", Attr->getExportName());
873         Fn->addFnAttrs(B);
874       }
875     }
876 
877     if (auto *FD = dyn_cast_or_null<FunctionDecl>(D)) {
878       llvm::Function *Fn = cast<llvm::Function>(GV);
879       if (!FD->doesThisDeclarationHaveABody() && !FD->hasPrototype())
880         Fn->addFnAttr("no-prototype");
881     }
882   }
883 };
884 
885 /// Classify argument of given type \p Ty.
886 ABIArgInfo WebAssemblyABIInfo::classifyArgumentType(QualType Ty) const {
887   Ty = useFirstFieldIfTransparentUnion(Ty);
888 
889   if (isAggregateTypeForABI(Ty)) {
890     // Records with non-trivial destructors/copy-constructors should not be
891     // passed by value.
892     if (auto RAA = getRecordArgABI(Ty, getCXXABI()))
893       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
894     // Ignore empty structs/unions.
895     if (isEmptyRecord(getContext(), Ty, true))
896       return ABIArgInfo::getIgnore();
897     // Lower single-element structs to just pass a regular value. TODO: We
898     // could do reasonable-size multiple-element structs too, using getExpand(),
899     // though watch out for things like bitfields.
900     if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
901       return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
902     // For the experimental multivalue ABI, fully expand all other aggregates
903     if (Kind == ABIKind::ExperimentalMV) {
904       const RecordType *RT = Ty->getAs<RecordType>();
905       assert(RT);
906       bool HasBitField = false;
907       for (auto *Field : RT->getDecl()->fields()) {
908         if (Field->isBitField()) {
909           HasBitField = true;
910           break;
911         }
912       }
913       if (!HasBitField)
914         return ABIArgInfo::getExpand();
915     }
916   }
917 
918   // Otherwise just do the default thing.
919   return defaultInfo.classifyArgumentType(Ty);
920 }
921 
922 ABIArgInfo WebAssemblyABIInfo::classifyReturnType(QualType RetTy) const {
923   if (isAggregateTypeForABI(RetTy)) {
924     // Records with non-trivial destructors/copy-constructors should not be
925     // returned by value.
926     if (!getRecordArgABI(RetTy, getCXXABI())) {
927       // Ignore empty structs/unions.
928       if (isEmptyRecord(getContext(), RetTy, true))
929         return ABIArgInfo::getIgnore();
930       // Lower single-element structs to just return a regular value. TODO: We
931       // could do reasonable-size multiple-element structs too, using
932       // ABIArgInfo::getDirect().
933       if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
934         return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
935       // For the experimental multivalue ABI, return all other aggregates
936       if (Kind == ABIKind::ExperimentalMV)
937         return ABIArgInfo::getDirect();
938     }
939   }
940 
941   // Otherwise just do the default thing.
942   return defaultInfo.classifyReturnType(RetTy);
943 }
944 
945 Address WebAssemblyABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
946                                       QualType Ty) const {
947   bool IsIndirect = isAggregateTypeForABI(Ty) &&
948                     !isEmptyRecord(getContext(), Ty, true) &&
949                     !isSingleElementStruct(Ty, getContext());
950   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
951                           getContext().getTypeInfoInChars(Ty),
952                           CharUnits::fromQuantity(4),
953                           /*AllowHigherAlign=*/true);
954 }
955 
956 //===----------------------------------------------------------------------===//
957 // le32/PNaCl bitcode ABI Implementation
958 //
959 // This is a simplified version of the x86_32 ABI.  Arguments and return values
960 // are always passed on the stack.
961 //===----------------------------------------------------------------------===//
962 
963 class PNaClABIInfo : public ABIInfo {
964  public:
965   PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
966 
967   ABIArgInfo classifyReturnType(QualType RetTy) const;
968   ABIArgInfo classifyArgumentType(QualType RetTy) const;
969 
970   void computeInfo(CGFunctionInfo &FI) const override;
971   Address EmitVAArg(CodeGenFunction &CGF,
972                     Address VAListAddr, QualType Ty) const override;
973 };
974 
975 class PNaClTargetCodeGenInfo : public TargetCodeGenInfo {
976  public:
977    PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
978        : TargetCodeGenInfo(std::make_unique<PNaClABIInfo>(CGT)) {}
979 };
980 
981 void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const {
982   if (!getCXXABI().classifyReturnType(FI))
983     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
984 
985   for (auto &I : FI.arguments())
986     I.info = classifyArgumentType(I.type);
987 }
988 
989 Address PNaClABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
990                                 QualType Ty) const {
991   // The PNaCL ABI is a bit odd, in that varargs don't use normal
992   // function classification. Structs get passed directly for varargs
993   // functions, through a rewriting transform in
994   // pnacl-llvm/lib/Transforms/NaCl/ExpandVarArgs.cpp, which allows
995   // this target to actually support a va_arg instructions with an
996   // aggregate type, unlike other targets.
997   return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
998 }
999 
1000 /// Classify argument of given type \p Ty.
1001 ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const {
1002   if (isAggregateTypeForABI(Ty)) {
1003     if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
1004       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
1005     return getNaturalAlignIndirect(Ty);
1006   } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
1007     // Treat an enum type as its underlying type.
1008     Ty = EnumTy->getDecl()->getIntegerType();
1009   } else if (Ty->isFloatingType()) {
1010     // Floating-point types don't go inreg.
1011     return ABIArgInfo::getDirect();
1012   } else if (const auto *EIT = Ty->getAs<BitIntType>()) {
1013     // Treat bit-precise integers as integers if <= 64, otherwise pass
1014     // indirectly.
1015     if (EIT->getNumBits() > 64)
1016       return getNaturalAlignIndirect(Ty);
1017     return ABIArgInfo::getDirect();
1018   }
1019 
1020   return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
1021                                             : ABIArgInfo::getDirect());
1022 }
1023 
1024 ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const {
1025   if (RetTy->isVoidType())
1026     return ABIArgInfo::getIgnore();
1027 
1028   // In the PNaCl ABI we always return records/structures on the stack.
1029   if (isAggregateTypeForABI(RetTy))
1030     return getNaturalAlignIndirect(RetTy);
1031 
1032   // Treat bit-precise integers as integers if <= 64, otherwise pass indirectly.
1033   if (const auto *EIT = RetTy->getAs<BitIntType>()) {
1034     if (EIT->getNumBits() > 64)
1035       return getNaturalAlignIndirect(RetTy);
1036     return ABIArgInfo::getDirect();
1037   }
1038 
1039   // Treat an enum type as its underlying type.
1040   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
1041     RetTy = EnumTy->getDecl()->getIntegerType();
1042 
1043   return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
1044                                                : ABIArgInfo::getDirect());
1045 }
1046 
1047 /// IsX86_MMXType - Return true if this is an MMX type.
1048 bool IsX86_MMXType(llvm::Type *IRType) {
1049   // Return true if the type is an MMX type <2 x i32>, <4 x i16>, or <8 x i8>.
1050   return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 &&
1051     cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() &&
1052     IRType->getScalarSizeInBits() != 64;
1053 }
1054 
1055 static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
1056                                           StringRef Constraint,
1057                                           llvm::Type* Ty) {
1058   bool IsMMXCons = llvm::StringSwitch<bool>(Constraint)
1059                      .Cases("y", "&y", "^Ym", true)
1060                      .Default(false);
1061   if (IsMMXCons && Ty->isVectorTy()) {
1062     if (cast<llvm::VectorType>(Ty)->getPrimitiveSizeInBits().getFixedSize() !=
1063         64) {
1064       // Invalid MMX constraint
1065       return nullptr;
1066     }
1067 
1068     return llvm::Type::getX86_MMXTy(CGF.getLLVMContext());
1069   }
1070 
1071   // No operation needed
1072   return Ty;
1073 }
1074 
1075 /// Returns true if this type can be passed in SSE registers with the
1076 /// X86_VectorCall calling convention. Shared between x86_32 and x86_64.
1077 static bool isX86VectorTypeForVectorCall(ASTContext &Context, QualType Ty) {
1078   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
1079     if (BT->isFloatingPoint() && BT->getKind() != BuiltinType::Half) {
1080       if (BT->getKind() == BuiltinType::LongDouble) {
1081         if (&Context.getTargetInfo().getLongDoubleFormat() ==
1082             &llvm::APFloat::x87DoubleExtended())
1083           return false;
1084       }
1085       return true;
1086     }
1087   } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
1088     // vectorcall can pass XMM, YMM, and ZMM vectors. We don't pass SSE1 MMX
1089     // registers specially.
1090     unsigned VecSize = Context.getTypeSize(VT);
1091     if (VecSize == 128 || VecSize == 256 || VecSize == 512)
1092       return true;
1093   }
1094   return false;
1095 }
1096 
1097 /// Returns true if this aggregate is small enough to be passed in SSE registers
1098 /// in the X86_VectorCall calling convention. Shared between x86_32 and x86_64.
1099 static bool isX86VectorCallAggregateSmallEnough(uint64_t NumMembers) {
1100   return NumMembers <= 4;
1101 }
1102 
1103 /// Returns a Homogeneous Vector Aggregate ABIArgInfo, used in X86.
1104 static ABIArgInfo getDirectX86Hva(llvm::Type* T = nullptr) {
1105   auto AI = ABIArgInfo::getDirect(T);
1106   AI.setInReg(true);
1107   AI.setCanBeFlattened(false);
1108   return AI;
1109 }
1110 
1111 //===----------------------------------------------------------------------===//
1112 // X86-32 ABI Implementation
1113 //===----------------------------------------------------------------------===//
1114 
1115 /// Similar to llvm::CCState, but for Clang.
1116 struct CCState {
1117   CCState(CGFunctionInfo &FI)
1118       : IsPreassigned(FI.arg_size()), CC(FI.getCallingConvention()) {}
1119 
1120   llvm::SmallBitVector IsPreassigned;
1121   unsigned CC = CallingConv::CC_C;
1122   unsigned FreeRegs = 0;
1123   unsigned FreeSSERegs = 0;
1124 };
1125 
1126 /// X86_32ABIInfo - The X86-32 ABI information.
1127 class X86_32ABIInfo : public SwiftABIInfo {
1128   enum Class {
1129     Integer,
1130     Float
1131   };
1132 
1133   static const unsigned MinABIStackAlignInBytes = 4;
1134 
1135   bool IsDarwinVectorABI;
1136   bool IsRetSmallStructInRegABI;
1137   bool IsWin32StructABI;
1138   bool IsSoftFloatABI;
1139   bool IsMCUABI;
1140   bool IsLinuxABI;
1141   unsigned DefaultNumRegisterParameters;
1142 
1143   static bool isRegisterSize(unsigned Size) {
1144     return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
1145   }
1146 
1147   bool isHomogeneousAggregateBaseType(QualType Ty) const override {
1148     // FIXME: Assumes vectorcall is in use.
1149     return isX86VectorTypeForVectorCall(getContext(), Ty);
1150   }
1151 
1152   bool isHomogeneousAggregateSmallEnough(const Type *Ty,
1153                                          uint64_t NumMembers) const override {
1154     // FIXME: Assumes vectorcall is in use.
1155     return isX86VectorCallAggregateSmallEnough(NumMembers);
1156   }
1157 
1158   bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context) const;
1159 
1160   /// getIndirectResult - Give a source type \arg Ty, return a suitable result
1161   /// such that the argument will be passed in memory.
1162   ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
1163 
1164   ABIArgInfo getIndirectReturnResult(QualType Ty, CCState &State) const;
1165 
1166   /// Return the alignment to use for the given type on the stack.
1167   unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const;
1168 
1169   Class classify(QualType Ty) const;
1170   ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const;
1171   ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
1172 
1173   /// Updates the number of available free registers, returns
1174   /// true if any registers were allocated.
1175   bool updateFreeRegs(QualType Ty, CCState &State) const;
1176 
1177   bool shouldAggregateUseDirect(QualType Ty, CCState &State, bool &InReg,
1178                                 bool &NeedsPadding) const;
1179   bool shouldPrimitiveUseInReg(QualType Ty, CCState &State) const;
1180 
1181   bool canExpandIndirectArgument(QualType Ty) const;
1182 
1183   /// Rewrite the function info so that all memory arguments use
1184   /// inalloca.
1185   void rewriteWithInAlloca(CGFunctionInfo &FI) const;
1186 
1187   void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
1188                            CharUnits &StackOffset, ABIArgInfo &Info,
1189                            QualType Type) const;
1190   void runVectorCallFirstPass(CGFunctionInfo &FI, CCState &State) const;
1191 
1192 public:
1193 
1194   void computeInfo(CGFunctionInfo &FI) const override;
1195   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
1196                     QualType Ty) const override;
1197 
1198   X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
1199                 bool RetSmallStructInRegABI, bool Win32StructABI,
1200                 unsigned NumRegisterParameters, bool SoftFloatABI)
1201     : SwiftABIInfo(CGT), IsDarwinVectorABI(DarwinVectorABI),
1202       IsRetSmallStructInRegABI(RetSmallStructInRegABI),
1203       IsWin32StructABI(Win32StructABI), IsSoftFloatABI(SoftFloatABI),
1204       IsMCUABI(CGT.getTarget().getTriple().isOSIAMCU()),
1205       IsLinuxABI(CGT.getTarget().getTriple().isOSLinux() ||
1206                  CGT.getTarget().getTriple().isOSCygMing()),
1207       DefaultNumRegisterParameters(NumRegisterParameters) {}
1208 
1209   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
1210                                     bool asReturnValue) const override {
1211     // LLVM's x86-32 lowering currently only assigns up to three
1212     // integer registers and three fp registers.  Oddly, it'll use up to
1213     // four vector registers for vectors, but those can overlap with the
1214     // scalar registers.
1215     return occupiesMoreThan(CGT, scalars, /*total*/ 3);
1216   }
1217 
1218   bool isSwiftErrorInRegister() const override {
1219     // x86-32 lowering does not support passing swifterror in a register.
1220     return false;
1221   }
1222 };
1223 
1224 class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
1225 public:
1226   X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
1227                           bool RetSmallStructInRegABI, bool Win32StructABI,
1228                           unsigned NumRegisterParameters, bool SoftFloatABI)
1229       : TargetCodeGenInfo(std::make_unique<X86_32ABIInfo>(
1230             CGT, DarwinVectorABI, RetSmallStructInRegABI, Win32StructABI,
1231             NumRegisterParameters, SoftFloatABI)) {}
1232 
1233   static bool isStructReturnInRegABI(
1234       const llvm::Triple &Triple, const CodeGenOptions &Opts);
1235 
1236   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
1237                            CodeGen::CodeGenModule &CGM) const override;
1238 
1239   int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
1240     // Darwin uses different dwarf register numbers for EH.
1241     if (CGM.getTarget().getTriple().isOSDarwin()) return 5;
1242     return 4;
1243   }
1244 
1245   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
1246                                llvm::Value *Address) const override;
1247 
1248   llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
1249                                   StringRef Constraint,
1250                                   llvm::Type* Ty) const override {
1251     return X86AdjustInlineAsmType(CGF, Constraint, Ty);
1252   }
1253 
1254   void addReturnRegisterOutputs(CodeGenFunction &CGF, LValue ReturnValue,
1255                                 std::string &Constraints,
1256                                 std::vector<llvm::Type *> &ResultRegTypes,
1257                                 std::vector<llvm::Type *> &ResultTruncRegTypes,
1258                                 std::vector<LValue> &ResultRegDests,
1259                                 std::string &AsmString,
1260                                 unsigned NumOutputs) const override;
1261 
1262   llvm::Constant *
1263   getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
1264     unsigned Sig = (0xeb << 0) |  // jmp rel8
1265                    (0x06 << 8) |  //           .+0x08
1266                    ('v' << 16) |
1267                    ('2' << 24);
1268     return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
1269   }
1270 
1271   StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
1272     return "movl\t%ebp, %ebp"
1273            "\t\t// marker for objc_retainAutoreleaseReturnValue";
1274   }
1275 };
1276 
1277 }
1278 
1279 /// Rewrite input constraint references after adding some output constraints.
1280 /// In the case where there is one output and one input and we add one output,
1281 /// we need to replace all operand references greater than or equal to 1:
1282 ///     mov $0, $1
1283 ///     mov eax, $1
1284 /// The result will be:
1285 ///     mov $0, $2
1286 ///     mov eax, $2
1287 static void rewriteInputConstraintReferences(unsigned FirstIn,
1288                                              unsigned NumNewOuts,
1289                                              std::string &AsmString) {
1290   std::string Buf;
1291   llvm::raw_string_ostream OS(Buf);
1292   size_t Pos = 0;
1293   while (Pos < AsmString.size()) {
1294     size_t DollarStart = AsmString.find('$', Pos);
1295     if (DollarStart == std::string::npos)
1296       DollarStart = AsmString.size();
1297     size_t DollarEnd = AsmString.find_first_not_of('$', DollarStart);
1298     if (DollarEnd == std::string::npos)
1299       DollarEnd = AsmString.size();
1300     OS << StringRef(&AsmString[Pos], DollarEnd - Pos);
1301     Pos = DollarEnd;
1302     size_t NumDollars = DollarEnd - DollarStart;
1303     if (NumDollars % 2 != 0 && Pos < AsmString.size()) {
1304       // We have an operand reference.
1305       size_t DigitStart = Pos;
1306       if (AsmString[DigitStart] == '{') {
1307         OS << '{';
1308         ++DigitStart;
1309       }
1310       size_t DigitEnd = AsmString.find_first_not_of("0123456789", DigitStart);
1311       if (DigitEnd == std::string::npos)
1312         DigitEnd = AsmString.size();
1313       StringRef OperandStr(&AsmString[DigitStart], DigitEnd - DigitStart);
1314       unsigned OperandIndex;
1315       if (!OperandStr.getAsInteger(10, OperandIndex)) {
1316         if (OperandIndex >= FirstIn)
1317           OperandIndex += NumNewOuts;
1318         OS << OperandIndex;
1319       } else {
1320         OS << OperandStr;
1321       }
1322       Pos = DigitEnd;
1323     }
1324   }
1325   AsmString = std::move(OS.str());
1326 }
1327 
1328 /// Add output constraints for EAX:EDX because they are return registers.
1329 void X86_32TargetCodeGenInfo::addReturnRegisterOutputs(
1330     CodeGenFunction &CGF, LValue ReturnSlot, std::string &Constraints,
1331     std::vector<llvm::Type *> &ResultRegTypes,
1332     std::vector<llvm::Type *> &ResultTruncRegTypes,
1333     std::vector<LValue> &ResultRegDests, std::string &AsmString,
1334     unsigned NumOutputs) const {
1335   uint64_t RetWidth = CGF.getContext().getTypeSize(ReturnSlot.getType());
1336 
1337   // Use the EAX constraint if the width is 32 or smaller and EAX:EDX if it is
1338   // larger.
1339   if (!Constraints.empty())
1340     Constraints += ',';
1341   if (RetWidth <= 32) {
1342     Constraints += "={eax}";
1343     ResultRegTypes.push_back(CGF.Int32Ty);
1344   } else {
1345     // Use the 'A' constraint for EAX:EDX.
1346     Constraints += "=A";
1347     ResultRegTypes.push_back(CGF.Int64Ty);
1348   }
1349 
1350   // Truncate EAX or EAX:EDX to an integer of the appropriate size.
1351   llvm::Type *CoerceTy = llvm::IntegerType::get(CGF.getLLVMContext(), RetWidth);
1352   ResultTruncRegTypes.push_back(CoerceTy);
1353 
1354   // Coerce the integer by bitcasting the return slot pointer.
1355   ReturnSlot.setAddress(
1356       CGF.Builder.CreateElementBitCast(ReturnSlot.getAddress(CGF), CoerceTy));
1357   ResultRegDests.push_back(ReturnSlot);
1358 
1359   rewriteInputConstraintReferences(NumOutputs, 1, AsmString);
1360 }
1361 
1362 /// shouldReturnTypeInRegister - Determine if the given type should be
1363 /// returned in a register (for the Darwin and MCU ABI).
1364 bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
1365                                                ASTContext &Context) const {
1366   uint64_t Size = Context.getTypeSize(Ty);
1367 
1368   // For i386, type must be register sized.
1369   // For the MCU ABI, it only needs to be <= 8-byte
1370   if ((IsMCUABI && Size > 64) || (!IsMCUABI && !isRegisterSize(Size)))
1371    return false;
1372 
1373   if (Ty->isVectorType()) {
1374     // 64- and 128- bit vectors inside structures are not returned in
1375     // registers.
1376     if (Size == 64 || Size == 128)
1377       return false;
1378 
1379     return true;
1380   }
1381 
1382   // If this is a builtin, pointer, enum, complex type, member pointer, or
1383   // member function pointer it is ok.
1384   if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() ||
1385       Ty->isAnyComplexType() || Ty->isEnumeralType() ||
1386       Ty->isBlockPointerType() || Ty->isMemberPointerType())
1387     return true;
1388 
1389   // Arrays are treated like records.
1390   if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
1391     return shouldReturnTypeInRegister(AT->getElementType(), Context);
1392 
1393   // Otherwise, it must be a record type.
1394   const RecordType *RT = Ty->getAs<RecordType>();
1395   if (!RT) return false;
1396 
1397   // FIXME: Traverse bases here too.
1398 
1399   // Structure types are passed in register if all fields would be
1400   // passed in a register.
1401   for (const auto *FD : RT->getDecl()->fields()) {
1402     // Empty fields are ignored.
1403     if (isEmptyField(Context, FD, true))
1404       continue;
1405 
1406     // Check fields recursively.
1407     if (!shouldReturnTypeInRegister(FD->getType(), Context))
1408       return false;
1409   }
1410   return true;
1411 }
1412 
1413 static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
1414   // Treat complex types as the element type.
1415   if (const ComplexType *CTy = Ty->getAs<ComplexType>())
1416     Ty = CTy->getElementType();
1417 
1418   // Check for a type which we know has a simple scalar argument-passing
1419   // convention without any padding.  (We're specifically looking for 32
1420   // and 64-bit integer and integer-equivalents, float, and double.)
1421   if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() &&
1422       !Ty->isEnumeralType() && !Ty->isBlockPointerType())
1423     return false;
1424 
1425   uint64_t Size = Context.getTypeSize(Ty);
1426   return Size == 32 || Size == 64;
1427 }
1428 
1429 static bool addFieldSizes(ASTContext &Context, const RecordDecl *RD,
1430                           uint64_t &Size) {
1431   for (const auto *FD : RD->fields()) {
1432     // Scalar arguments on the stack get 4 byte alignment on x86. If the
1433     // argument is smaller than 32-bits, expanding the struct will create
1434     // alignment padding.
1435     if (!is32Or64BitBasicType(FD->getType(), Context))
1436       return false;
1437 
1438     // FIXME: Reject bit-fields wholesale; there are two problems, we don't know
1439     // how to expand them yet, and the predicate for telling if a bitfield still
1440     // counts as "basic" is more complicated than what we were doing previously.
1441     if (FD->isBitField())
1442       return false;
1443 
1444     Size += Context.getTypeSize(FD->getType());
1445   }
1446   return true;
1447 }
1448 
1449 static bool addBaseAndFieldSizes(ASTContext &Context, const CXXRecordDecl *RD,
1450                                  uint64_t &Size) {
1451   // Don't do this if there are any non-empty bases.
1452   for (const CXXBaseSpecifier &Base : RD->bases()) {
1453     if (!addBaseAndFieldSizes(Context, Base.getType()->getAsCXXRecordDecl(),
1454                               Size))
1455       return false;
1456   }
1457   if (!addFieldSizes(Context, RD, Size))
1458     return false;
1459   return true;
1460 }
1461 
1462 /// Test whether an argument type which is to be passed indirectly (on the
1463 /// stack) would have the equivalent layout if it was expanded into separate
1464 /// arguments. If so, we prefer to do the latter to avoid inhibiting
1465 /// optimizations.
1466 bool X86_32ABIInfo::canExpandIndirectArgument(QualType Ty) const {
1467   // We can only expand structure types.
1468   const RecordType *RT = Ty->getAs<RecordType>();
1469   if (!RT)
1470     return false;
1471   const RecordDecl *RD = RT->getDecl();
1472   uint64_t Size = 0;
1473   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
1474     if (!IsWin32StructABI) {
1475       // On non-Windows, we have to conservatively match our old bitcode
1476       // prototypes in order to be ABI-compatible at the bitcode level.
1477       if (!CXXRD->isCLike())
1478         return false;
1479     } else {
1480       // Don't do this for dynamic classes.
1481       if (CXXRD->isDynamicClass())
1482         return false;
1483     }
1484     if (!addBaseAndFieldSizes(getContext(), CXXRD, Size))
1485       return false;
1486   } else {
1487     if (!addFieldSizes(getContext(), RD, Size))
1488       return false;
1489   }
1490 
1491   // We can do this if there was no alignment padding.
1492   return Size == getContext().getTypeSize(Ty);
1493 }
1494 
1495 ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(QualType RetTy, CCState &State) const {
1496   // If the return value is indirect, then the hidden argument is consuming one
1497   // integer register.
1498   if (State.FreeRegs) {
1499     --State.FreeRegs;
1500     if (!IsMCUABI)
1501       return getNaturalAlignIndirectInReg(RetTy);
1502   }
1503   return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
1504 }
1505 
1506 ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy,
1507                                              CCState &State) const {
1508   if (RetTy->isVoidType())
1509     return ABIArgInfo::getIgnore();
1510 
1511   const Type *Base = nullptr;
1512   uint64_t NumElts = 0;
1513   if ((State.CC == llvm::CallingConv::X86_VectorCall ||
1514        State.CC == llvm::CallingConv::X86_RegCall) &&
1515       isHomogeneousAggregate(RetTy, Base, NumElts)) {
1516     // The LLVM struct type for such an aggregate should lower properly.
1517     return ABIArgInfo::getDirect();
1518   }
1519 
1520   if (const VectorType *VT = RetTy->getAs<VectorType>()) {
1521     // On Darwin, some vectors are returned in registers.
1522     if (IsDarwinVectorABI) {
1523       uint64_t Size = getContext().getTypeSize(RetTy);
1524 
1525       // 128-bit vectors are a special case; they are returned in
1526       // registers and we need to make sure to pick a type the LLVM
1527       // backend will like.
1528       if (Size == 128)
1529         return ABIArgInfo::getDirect(llvm::FixedVectorType::get(
1530             llvm::Type::getInt64Ty(getVMContext()), 2));
1531 
1532       // Always return in register if it fits in a general purpose
1533       // register, or if it is 64 bits and has a single element.
1534       if ((Size == 8 || Size == 16 || Size == 32) ||
1535           (Size == 64 && VT->getNumElements() == 1))
1536         return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
1537                                                             Size));
1538 
1539       return getIndirectReturnResult(RetTy, State);
1540     }
1541 
1542     return ABIArgInfo::getDirect();
1543   }
1544 
1545   if (isAggregateTypeForABI(RetTy)) {
1546     if (const RecordType *RT = RetTy->getAs<RecordType>()) {
1547       // Structures with flexible arrays are always indirect.
1548       if (RT->getDecl()->hasFlexibleArrayMember())
1549         return getIndirectReturnResult(RetTy, State);
1550     }
1551 
1552     // If specified, structs and unions are always indirect.
1553     if (!IsRetSmallStructInRegABI && !RetTy->isAnyComplexType())
1554       return getIndirectReturnResult(RetTy, State);
1555 
1556     // Ignore empty structs/unions.
1557     if (isEmptyRecord(getContext(), RetTy, true))
1558       return ABIArgInfo::getIgnore();
1559 
1560     // Return complex of _Float16 as <2 x half> so the backend will use xmm0.
1561     if (const ComplexType *CT = RetTy->getAs<ComplexType>()) {
1562       QualType ET = getContext().getCanonicalType(CT->getElementType());
1563       if (ET->isFloat16Type())
1564         return ABIArgInfo::getDirect(llvm::FixedVectorType::get(
1565             llvm::Type::getHalfTy(getVMContext()), 2));
1566     }
1567 
1568     // Small structures which are register sized are generally returned
1569     // in a register.
1570     if (shouldReturnTypeInRegister(RetTy, getContext())) {
1571       uint64_t Size = getContext().getTypeSize(RetTy);
1572 
1573       // As a special-case, if the struct is a "single-element" struct, and
1574       // the field is of type "float" or "double", return it in a
1575       // floating-point register. (MSVC does not apply this special case.)
1576       // We apply a similar transformation for pointer types to improve the
1577       // quality of the generated IR.
1578       if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
1579         if ((!IsWin32StructABI && SeltTy->isRealFloatingType())
1580             || SeltTy->hasPointerRepresentation())
1581           return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
1582 
1583       // FIXME: We should be able to narrow this integer in cases with dead
1584       // padding.
1585       return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
1586     }
1587 
1588     return getIndirectReturnResult(RetTy, State);
1589   }
1590 
1591   // Treat an enum type as its underlying type.
1592   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
1593     RetTy = EnumTy->getDecl()->getIntegerType();
1594 
1595   if (const auto *EIT = RetTy->getAs<BitIntType>())
1596     if (EIT->getNumBits() > 64)
1597       return getIndirectReturnResult(RetTy, State);
1598 
1599   return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
1600                                                : ABIArgInfo::getDirect());
1601 }
1602 
1603 static bool isSIMDVectorType(ASTContext &Context, QualType Ty) {
1604   return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128;
1605 }
1606 
1607 static bool isRecordWithSIMDVectorType(ASTContext &Context, QualType Ty) {
1608   const RecordType *RT = Ty->getAs<RecordType>();
1609   if (!RT)
1610     return false;
1611   const RecordDecl *RD = RT->getDecl();
1612 
1613   // If this is a C++ record, check the bases first.
1614   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
1615     for (const auto &I : CXXRD->bases())
1616       if (!isRecordWithSIMDVectorType(Context, I.getType()))
1617         return false;
1618 
1619   for (const auto *i : RD->fields()) {
1620     QualType FT = i->getType();
1621 
1622     if (isSIMDVectorType(Context, FT))
1623       return true;
1624 
1625     if (isRecordWithSIMDVectorType(Context, FT))
1626       return true;
1627   }
1628 
1629   return false;
1630 }
1631 
1632 unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
1633                                                  unsigned Align) const {
1634   // Otherwise, if the alignment is less than or equal to the minimum ABI
1635   // alignment, just use the default; the backend will handle this.
1636   if (Align <= MinABIStackAlignInBytes)
1637     return 0; // Use default alignment.
1638 
1639   if (IsLinuxABI) {
1640     // Exclude other System V OS (e.g Darwin, PS4 and FreeBSD) since we don't
1641     // want to spend any effort dealing with the ramifications of ABI breaks.
1642     //
1643     // If the vector type is __m128/__m256/__m512, return the default alignment.
1644     if (Ty->isVectorType() && (Align == 16 || Align == 32 || Align == 64))
1645       return Align;
1646   }
1647   // On non-Darwin, the stack type alignment is always 4.
1648   if (!IsDarwinVectorABI) {
1649     // Set explicit alignment, since we may need to realign the top.
1650     return MinABIStackAlignInBytes;
1651   }
1652 
1653   // Otherwise, if the type contains an SSE vector type, the alignment is 16.
1654   if (Align >= 16 && (isSIMDVectorType(getContext(), Ty) ||
1655                       isRecordWithSIMDVectorType(getContext(), Ty)))
1656     return 16;
1657 
1658   return MinABIStackAlignInBytes;
1659 }
1660 
1661 ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal,
1662                                             CCState &State) const {
1663   if (!ByVal) {
1664     if (State.FreeRegs) {
1665       --State.FreeRegs; // Non-byval indirects just use one pointer.
1666       if (!IsMCUABI)
1667         return getNaturalAlignIndirectInReg(Ty);
1668     }
1669     return getNaturalAlignIndirect(Ty, false);
1670   }
1671 
1672   // Compute the byval alignment.
1673   unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
1674   unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign);
1675   if (StackAlign == 0)
1676     return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true);
1677 
1678   // If the stack alignment is less than the type alignment, realign the
1679   // argument.
1680   bool Realign = TypeAlign > StackAlign;
1681   return ABIArgInfo::getIndirect(CharUnits::fromQuantity(StackAlign),
1682                                  /*ByVal=*/true, Realign);
1683 }
1684 
1685 X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const {
1686   const Type *T = isSingleElementStruct(Ty, getContext());
1687   if (!T)
1688     T = Ty.getTypePtr();
1689 
1690   if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
1691     BuiltinType::Kind K = BT->getKind();
1692     if (K == BuiltinType::Float || K == BuiltinType::Double)
1693       return Float;
1694   }
1695   return Integer;
1696 }
1697 
1698 bool X86_32ABIInfo::updateFreeRegs(QualType Ty, CCState &State) const {
1699   if (!IsSoftFloatABI) {
1700     Class C = classify(Ty);
1701     if (C == Float)
1702       return false;
1703   }
1704 
1705   unsigned Size = getContext().getTypeSize(Ty);
1706   unsigned SizeInRegs = (Size + 31) / 32;
1707 
1708   if (SizeInRegs == 0)
1709     return false;
1710 
1711   if (!IsMCUABI) {
1712     if (SizeInRegs > State.FreeRegs) {
1713       State.FreeRegs = 0;
1714       return false;
1715     }
1716   } else {
1717     // The MCU psABI allows passing parameters in-reg even if there are
1718     // earlier parameters that are passed on the stack. Also,
1719     // it does not allow passing >8-byte structs in-register,
1720     // even if there are 3 free registers available.
1721     if (SizeInRegs > State.FreeRegs || SizeInRegs > 2)
1722       return false;
1723   }
1724 
1725   State.FreeRegs -= SizeInRegs;
1726   return true;
1727 }
1728 
1729 bool X86_32ABIInfo::shouldAggregateUseDirect(QualType Ty, CCState &State,
1730                                              bool &InReg,
1731                                              bool &NeedsPadding) const {
1732   // On Windows, aggregates other than HFAs are never passed in registers, and
1733   // they do not consume register slots. Homogenous floating-point aggregates
1734   // (HFAs) have already been dealt with at this point.
1735   if (IsWin32StructABI && isAggregateTypeForABI(Ty))
1736     return false;
1737 
1738   NeedsPadding = false;
1739   InReg = !IsMCUABI;
1740 
1741   if (!updateFreeRegs(Ty, State))
1742     return false;
1743 
1744   if (IsMCUABI)
1745     return true;
1746 
1747   if (State.CC == llvm::CallingConv::X86_FastCall ||
1748       State.CC == llvm::CallingConv::X86_VectorCall ||
1749       State.CC == llvm::CallingConv::X86_RegCall) {
1750     if (getContext().getTypeSize(Ty) <= 32 && State.FreeRegs)
1751       NeedsPadding = true;
1752 
1753     return false;
1754   }
1755 
1756   return true;
1757 }
1758 
1759 bool X86_32ABIInfo::shouldPrimitiveUseInReg(QualType Ty, CCState &State) const {
1760   if (!updateFreeRegs(Ty, State))
1761     return false;
1762 
1763   if (IsMCUABI)
1764     return false;
1765 
1766   if (State.CC == llvm::CallingConv::X86_FastCall ||
1767       State.CC == llvm::CallingConv::X86_VectorCall ||
1768       State.CC == llvm::CallingConv::X86_RegCall) {
1769     if (getContext().getTypeSize(Ty) > 32)
1770       return false;
1771 
1772     return (Ty->isIntegralOrEnumerationType() || Ty->isPointerType() ||
1773         Ty->isReferenceType());
1774   }
1775 
1776   return true;
1777 }
1778 
1779 void X86_32ABIInfo::runVectorCallFirstPass(CGFunctionInfo &FI, CCState &State) const {
1780   // Vectorcall x86 works subtly different than in x64, so the format is
1781   // a bit different than the x64 version.  First, all vector types (not HVAs)
1782   // are assigned, with the first 6 ending up in the [XYZ]MM0-5 registers.
1783   // This differs from the x64 implementation, where the first 6 by INDEX get
1784   // registers.
1785   // In the second pass over the arguments, HVAs are passed in the remaining
1786   // vector registers if possible, or indirectly by address. The address will be
1787   // passed in ECX/EDX if available. Any other arguments are passed according to
1788   // the usual fastcall rules.
1789   MutableArrayRef<CGFunctionInfoArgInfo> Args = FI.arguments();
1790   for (int I = 0, E = Args.size(); I < E; ++I) {
1791     const Type *Base = nullptr;
1792     uint64_t NumElts = 0;
1793     const QualType &Ty = Args[I].type;
1794     if ((Ty->isVectorType() || Ty->isBuiltinType()) &&
1795         isHomogeneousAggregate(Ty, Base, NumElts)) {
1796       if (State.FreeSSERegs >= NumElts) {
1797         State.FreeSSERegs -= NumElts;
1798         Args[I].info = ABIArgInfo::getDirectInReg();
1799         State.IsPreassigned.set(I);
1800       }
1801     }
1802   }
1803 }
1804 
1805 ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
1806                                                CCState &State) const {
1807   // FIXME: Set alignment on indirect arguments.
1808   bool IsFastCall = State.CC == llvm::CallingConv::X86_FastCall;
1809   bool IsRegCall = State.CC == llvm::CallingConv::X86_RegCall;
1810   bool IsVectorCall = State.CC == llvm::CallingConv::X86_VectorCall;
1811 
1812   Ty = useFirstFieldIfTransparentUnion(Ty);
1813   TypeInfo TI = getContext().getTypeInfo(Ty);
1814 
1815   // Check with the C++ ABI first.
1816   const RecordType *RT = Ty->getAs<RecordType>();
1817   if (RT) {
1818     CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
1819     if (RAA == CGCXXABI::RAA_Indirect) {
1820       return getIndirectResult(Ty, false, State);
1821     } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
1822       // The field index doesn't matter, we'll fix it up later.
1823       return ABIArgInfo::getInAlloca(/*FieldIndex=*/0);
1824     }
1825   }
1826 
1827   // Regcall uses the concept of a homogenous vector aggregate, similar
1828   // to other targets.
1829   const Type *Base = nullptr;
1830   uint64_t NumElts = 0;
1831   if ((IsRegCall || IsVectorCall) &&
1832       isHomogeneousAggregate(Ty, Base, NumElts)) {
1833     if (State.FreeSSERegs >= NumElts) {
1834       State.FreeSSERegs -= NumElts;
1835 
1836       // Vectorcall passes HVAs directly and does not flatten them, but regcall
1837       // does.
1838       if (IsVectorCall)
1839         return getDirectX86Hva();
1840 
1841       if (Ty->isBuiltinType() || Ty->isVectorType())
1842         return ABIArgInfo::getDirect();
1843       return ABIArgInfo::getExpand();
1844     }
1845     return getIndirectResult(Ty, /*ByVal=*/false, State);
1846   }
1847 
1848   if (isAggregateTypeForABI(Ty)) {
1849     // Structures with flexible arrays are always indirect.
1850     // FIXME: This should not be byval!
1851     if (RT && RT->getDecl()->hasFlexibleArrayMember())
1852       return getIndirectResult(Ty, true, State);
1853 
1854     // Ignore empty structs/unions on non-Windows.
1855     if (!IsWin32StructABI && isEmptyRecord(getContext(), Ty, true))
1856       return ABIArgInfo::getIgnore();
1857 
1858     llvm::LLVMContext &LLVMContext = getVMContext();
1859     llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
1860     bool NeedsPadding = false;
1861     bool InReg;
1862     if (shouldAggregateUseDirect(Ty, State, InReg, NeedsPadding)) {
1863       unsigned SizeInRegs = (TI.Width + 31) / 32;
1864       SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32);
1865       llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
1866       if (InReg)
1867         return ABIArgInfo::getDirectInReg(Result);
1868       else
1869         return ABIArgInfo::getDirect(Result);
1870     }
1871     llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : nullptr;
1872 
1873     // Pass over-aligned aggregates on Windows indirectly. This behavior was
1874     // added in MSVC 2015.
1875     if (IsWin32StructABI && TI.isAlignRequired() && TI.Align > 32)
1876       return getIndirectResult(Ty, /*ByVal=*/false, State);
1877 
1878     // Expand small (<= 128-bit) record types when we know that the stack layout
1879     // of those arguments will match the struct. This is important because the
1880     // LLVM backend isn't smart enough to remove byval, which inhibits many
1881     // optimizations.
1882     // Don't do this for the MCU if there are still free integer registers
1883     // (see X86_64 ABI for full explanation).
1884     if (TI.Width <= 4 * 32 && (!IsMCUABI || State.FreeRegs == 0) &&
1885         canExpandIndirectArgument(Ty))
1886       return ABIArgInfo::getExpandWithPadding(
1887           IsFastCall || IsVectorCall || IsRegCall, PaddingType);
1888 
1889     return getIndirectResult(Ty, true, State);
1890   }
1891 
1892   if (const VectorType *VT = Ty->getAs<VectorType>()) {
1893     // On Windows, vectors are passed directly if registers are available, or
1894     // indirectly if not. This avoids the need to align argument memory. Pass
1895     // user-defined vector types larger than 512 bits indirectly for simplicity.
1896     if (IsWin32StructABI) {
1897       if (TI.Width <= 512 && State.FreeSSERegs > 0) {
1898         --State.FreeSSERegs;
1899         return ABIArgInfo::getDirectInReg();
1900       }
1901       return getIndirectResult(Ty, /*ByVal=*/false, State);
1902     }
1903 
1904     // On Darwin, some vectors are passed in memory, we handle this by passing
1905     // it as an i8/i16/i32/i64.
1906     if (IsDarwinVectorABI) {
1907       if ((TI.Width == 8 || TI.Width == 16 || TI.Width == 32) ||
1908           (TI.Width == 64 && VT->getNumElements() == 1))
1909         return ABIArgInfo::getDirect(
1910             llvm::IntegerType::get(getVMContext(), TI.Width));
1911     }
1912 
1913     if (IsX86_MMXType(CGT.ConvertType(Ty)))
1914       return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64));
1915 
1916     return ABIArgInfo::getDirect();
1917   }
1918 
1919 
1920   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1921     Ty = EnumTy->getDecl()->getIntegerType();
1922 
1923   bool InReg = shouldPrimitiveUseInReg(Ty, State);
1924 
1925   if (isPromotableIntegerTypeForABI(Ty)) {
1926     if (InReg)
1927       return ABIArgInfo::getExtendInReg(Ty);
1928     return ABIArgInfo::getExtend(Ty);
1929   }
1930 
1931   if (const auto *EIT = Ty->getAs<BitIntType>()) {
1932     if (EIT->getNumBits() <= 64) {
1933       if (InReg)
1934         return ABIArgInfo::getDirectInReg();
1935       return ABIArgInfo::getDirect();
1936     }
1937     return getIndirectResult(Ty, /*ByVal=*/false, State);
1938   }
1939 
1940   if (InReg)
1941     return ABIArgInfo::getDirectInReg();
1942   return ABIArgInfo::getDirect();
1943 }
1944 
1945 void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const {
1946   CCState State(FI);
1947   if (IsMCUABI)
1948     State.FreeRegs = 3;
1949   else if (State.CC == llvm::CallingConv::X86_FastCall) {
1950     State.FreeRegs = 2;
1951     State.FreeSSERegs = 3;
1952   } else if (State.CC == llvm::CallingConv::X86_VectorCall) {
1953     State.FreeRegs = 2;
1954     State.FreeSSERegs = 6;
1955   } else if (FI.getHasRegParm())
1956     State.FreeRegs = FI.getRegParm();
1957   else if (State.CC == llvm::CallingConv::X86_RegCall) {
1958     State.FreeRegs = 5;
1959     State.FreeSSERegs = 8;
1960   } else if (IsWin32StructABI) {
1961     // Since MSVC 2015, the first three SSE vectors have been passed in
1962     // registers. The rest are passed indirectly.
1963     State.FreeRegs = DefaultNumRegisterParameters;
1964     State.FreeSSERegs = 3;
1965   } else
1966     State.FreeRegs = DefaultNumRegisterParameters;
1967 
1968   if (!::classifyReturnType(getCXXABI(), FI, *this)) {
1969     FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), State);
1970   } else if (FI.getReturnInfo().isIndirect()) {
1971     // The C++ ABI is not aware of register usage, so we have to check if the
1972     // return value was sret and put it in a register ourselves if appropriate.
1973     if (State.FreeRegs) {
1974       --State.FreeRegs;  // The sret parameter consumes a register.
1975       if (!IsMCUABI)
1976         FI.getReturnInfo().setInReg(true);
1977     }
1978   }
1979 
1980   // The chain argument effectively gives us another free register.
1981   if (FI.isChainCall())
1982     ++State.FreeRegs;
1983 
1984   // For vectorcall, do a first pass over the arguments, assigning FP and vector
1985   // arguments to XMM registers as available.
1986   if (State.CC == llvm::CallingConv::X86_VectorCall)
1987     runVectorCallFirstPass(FI, State);
1988 
1989   bool UsedInAlloca = false;
1990   MutableArrayRef<CGFunctionInfoArgInfo> Args = FI.arguments();
1991   for (int I = 0, E = Args.size(); I < E; ++I) {
1992     // Skip arguments that have already been assigned.
1993     if (State.IsPreassigned.test(I))
1994       continue;
1995 
1996     Args[I].info = classifyArgumentType(Args[I].type, State);
1997     UsedInAlloca |= (Args[I].info.getKind() == ABIArgInfo::InAlloca);
1998   }
1999 
2000   // If we needed to use inalloca for any argument, do a second pass and rewrite
2001   // all the memory arguments to use inalloca.
2002   if (UsedInAlloca)
2003     rewriteWithInAlloca(FI);
2004 }
2005 
2006 void
2007 X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
2008                                    CharUnits &StackOffset, ABIArgInfo &Info,
2009                                    QualType Type) const {
2010   // Arguments are always 4-byte-aligned.
2011   CharUnits WordSize = CharUnits::fromQuantity(4);
2012   assert(StackOffset.isMultipleOf(WordSize) && "unaligned inalloca struct");
2013 
2014   // sret pointers and indirect things will require an extra pointer
2015   // indirection, unless they are byval. Most things are byval, and will not
2016   // require this indirection.
2017   bool IsIndirect = false;
2018   if (Info.isIndirect() && !Info.getIndirectByVal())
2019     IsIndirect = true;
2020   Info = ABIArgInfo::getInAlloca(FrameFields.size(), IsIndirect);
2021   llvm::Type *LLTy = CGT.ConvertTypeForMem(Type);
2022   if (IsIndirect)
2023     LLTy = LLTy->getPointerTo(0);
2024   FrameFields.push_back(LLTy);
2025   StackOffset += IsIndirect ? WordSize : getContext().getTypeSizeInChars(Type);
2026 
2027   // Insert padding bytes to respect alignment.
2028   CharUnits FieldEnd = StackOffset;
2029   StackOffset = FieldEnd.alignTo(WordSize);
2030   if (StackOffset != FieldEnd) {
2031     CharUnits NumBytes = StackOffset - FieldEnd;
2032     llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext());
2033     Ty = llvm::ArrayType::get(Ty, NumBytes.getQuantity());
2034     FrameFields.push_back(Ty);
2035   }
2036 }
2037 
2038 static bool isArgInAlloca(const ABIArgInfo &Info) {
2039   // Leave ignored and inreg arguments alone.
2040   switch (Info.getKind()) {
2041   case ABIArgInfo::InAlloca:
2042     return true;
2043   case ABIArgInfo::Ignore:
2044   case ABIArgInfo::IndirectAliased:
2045     return false;
2046   case ABIArgInfo::Indirect:
2047   case ABIArgInfo::Direct:
2048   case ABIArgInfo::Extend:
2049     return !Info.getInReg();
2050   case ABIArgInfo::Expand:
2051   case ABIArgInfo::CoerceAndExpand:
2052     // These are aggregate types which are never passed in registers when
2053     // inalloca is involved.
2054     return true;
2055   }
2056   llvm_unreachable("invalid enum");
2057 }
2058 
2059 void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const {
2060   assert(IsWin32StructABI && "inalloca only supported on win32");
2061 
2062   // Build a packed struct type for all of the arguments in memory.
2063   SmallVector<llvm::Type *, 6> FrameFields;
2064 
2065   // The stack alignment is always 4.
2066   CharUnits StackAlign = CharUnits::fromQuantity(4);
2067 
2068   CharUnits StackOffset;
2069   CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end();
2070 
2071   // Put 'this' into the struct before 'sret', if necessary.
2072   bool IsThisCall =
2073       FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall;
2074   ABIArgInfo &Ret = FI.getReturnInfo();
2075   if (Ret.isIndirect() && Ret.isSRetAfterThis() && !IsThisCall &&
2076       isArgInAlloca(I->info)) {
2077     addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
2078     ++I;
2079   }
2080 
2081   // Put the sret parameter into the inalloca struct if it's in memory.
2082   if (Ret.isIndirect() && !Ret.getInReg()) {
2083     addFieldToArgStruct(FrameFields, StackOffset, Ret, FI.getReturnType());
2084     // On Windows, the hidden sret parameter is always returned in eax.
2085     Ret.setInAllocaSRet(IsWin32StructABI);
2086   }
2087 
2088   // Skip the 'this' parameter in ecx.
2089   if (IsThisCall)
2090     ++I;
2091 
2092   // Put arguments passed in memory into the struct.
2093   for (; I != E; ++I) {
2094     if (isArgInAlloca(I->info))
2095       addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
2096   }
2097 
2098   FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields,
2099                                         /*isPacked=*/true),
2100                   StackAlign);
2101 }
2102 
2103 Address X86_32ABIInfo::EmitVAArg(CodeGenFunction &CGF,
2104                                  Address VAListAddr, QualType Ty) const {
2105 
2106   auto TypeInfo = getContext().getTypeInfoInChars(Ty);
2107 
2108   // x86-32 changes the alignment of certain arguments on the stack.
2109   //
2110   // Just messing with TypeInfo like this works because we never pass
2111   // anything indirectly.
2112   TypeInfo.Align = CharUnits::fromQuantity(
2113                 getTypeStackAlignInBytes(Ty, TypeInfo.Align.getQuantity()));
2114 
2115   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
2116                           TypeInfo, CharUnits::fromQuantity(4),
2117                           /*AllowHigherAlign*/ true);
2118 }
2119 
2120 bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
2121     const llvm::Triple &Triple, const CodeGenOptions &Opts) {
2122   assert(Triple.getArch() == llvm::Triple::x86);
2123 
2124   switch (Opts.getStructReturnConvention()) {
2125   case CodeGenOptions::SRCK_Default:
2126     break;
2127   case CodeGenOptions::SRCK_OnStack:  // -fpcc-struct-return
2128     return false;
2129   case CodeGenOptions::SRCK_InRegs:  // -freg-struct-return
2130     return true;
2131   }
2132 
2133   if (Triple.isOSDarwin() || Triple.isOSIAMCU())
2134     return true;
2135 
2136   switch (Triple.getOS()) {
2137   case llvm::Triple::DragonFly:
2138   case llvm::Triple::FreeBSD:
2139   case llvm::Triple::OpenBSD:
2140   case llvm::Triple::Win32:
2141     return true;
2142   default:
2143     return false;
2144   }
2145 }
2146 
2147 static void addX86InterruptAttrs(const FunctionDecl *FD, llvm::GlobalValue *GV,
2148                                  CodeGen::CodeGenModule &CGM) {
2149   if (!FD->hasAttr<AnyX86InterruptAttr>())
2150     return;
2151 
2152   llvm::Function *Fn = cast<llvm::Function>(GV);
2153   Fn->setCallingConv(llvm::CallingConv::X86_INTR);
2154   if (FD->getNumParams() == 0)
2155     return;
2156 
2157   auto PtrTy = cast<PointerType>(FD->getParamDecl(0)->getType());
2158   llvm::Type *ByValTy = CGM.getTypes().ConvertType(PtrTy->getPointeeType());
2159   llvm::Attribute NewAttr = llvm::Attribute::getWithByValType(
2160     Fn->getContext(), ByValTy);
2161   Fn->addParamAttr(0, NewAttr);
2162 }
2163 
2164 void X86_32TargetCodeGenInfo::setTargetAttributes(
2165     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
2166   if (GV->isDeclaration())
2167     return;
2168   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2169     if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
2170       llvm::Function *Fn = cast<llvm::Function>(GV);
2171       Fn->addFnAttr("stackrealign");
2172     }
2173 
2174     addX86InterruptAttrs(FD, GV, CGM);
2175   }
2176 }
2177 
2178 bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
2179                                                CodeGen::CodeGenFunction &CGF,
2180                                                llvm::Value *Address) const {
2181   CodeGen::CGBuilderTy &Builder = CGF.Builder;
2182 
2183   llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
2184 
2185   // 0-7 are the eight integer registers;  the order is different
2186   //   on Darwin (for EH), but the range is the same.
2187   // 8 is %eip.
2188   AssignToArrayRange(Builder, Address, Four8, 0, 8);
2189 
2190   if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
2191     // 12-16 are st(0..4).  Not sure why we stop at 4.
2192     // These have size 16, which is sizeof(long double) on
2193     // platforms with 8-byte alignment for that type.
2194     llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
2195     AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
2196 
2197   } else {
2198     // 9 is %eflags, which doesn't get a size on Darwin for some
2199     // reason.
2200     Builder.CreateAlignedStore(
2201         Four8, Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, Address, 9),
2202                                CharUnits::One());
2203 
2204     // 11-16 are st(0..5).  Not sure why we stop at 5.
2205     // These have size 12, which is sizeof(long double) on
2206     // platforms with 4-byte alignment for that type.
2207     llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
2208     AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
2209   }
2210 
2211   return false;
2212 }
2213 
2214 //===----------------------------------------------------------------------===//
2215 // X86-64 ABI Implementation
2216 //===----------------------------------------------------------------------===//
2217 
2218 
2219 namespace {
2220 /// The AVX ABI level for X86 targets.
2221 enum class X86AVXABILevel {
2222   None,
2223   AVX,
2224   AVX512
2225 };
2226 
2227 /// \p returns the size in bits of the largest (native) vector for \p AVXLevel.
2228 static unsigned getNativeVectorSizeForAVXABI(X86AVXABILevel AVXLevel) {
2229   switch (AVXLevel) {
2230   case X86AVXABILevel::AVX512:
2231     return 512;
2232   case X86AVXABILevel::AVX:
2233     return 256;
2234   case X86AVXABILevel::None:
2235     return 128;
2236   }
2237   llvm_unreachable("Unknown AVXLevel");
2238 }
2239 
2240 /// X86_64ABIInfo - The X86_64 ABI information.
2241 class X86_64ABIInfo : public SwiftABIInfo {
2242   enum Class {
2243     Integer = 0,
2244     SSE,
2245     SSEUp,
2246     X87,
2247     X87Up,
2248     ComplexX87,
2249     NoClass,
2250     Memory
2251   };
2252 
2253   /// merge - Implement the X86_64 ABI merging algorithm.
2254   ///
2255   /// Merge an accumulating classification \arg Accum with a field
2256   /// classification \arg Field.
2257   ///
2258   /// \param Accum - The accumulating classification. This should
2259   /// always be either NoClass or the result of a previous merge
2260   /// call. In addition, this should never be Memory (the caller
2261   /// should just return Memory for the aggregate).
2262   static Class merge(Class Accum, Class Field);
2263 
2264   /// postMerge - Implement the X86_64 ABI post merging algorithm.
2265   ///
2266   /// Post merger cleanup, reduces a malformed Hi and Lo pair to
2267   /// final MEMORY or SSE classes when necessary.
2268   ///
2269   /// \param AggregateSize - The size of the current aggregate in
2270   /// the classification process.
2271   ///
2272   /// \param Lo - The classification for the parts of the type
2273   /// residing in the low word of the containing object.
2274   ///
2275   /// \param Hi - The classification for the parts of the type
2276   /// residing in the higher words of the containing object.
2277   ///
2278   void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
2279 
2280   /// classify - Determine the x86_64 register classes in which the
2281   /// given type T should be passed.
2282   ///
2283   /// \param Lo - The classification for the parts of the type
2284   /// residing in the low word of the containing object.
2285   ///
2286   /// \param Hi - The classification for the parts of the type
2287   /// residing in the high word of the containing object.
2288   ///
2289   /// \param OffsetBase - The bit offset of this type in the
2290   /// containing object.  Some parameters are classified different
2291   /// depending on whether they straddle an eightbyte boundary.
2292   ///
2293   /// \param isNamedArg - Whether the argument in question is a "named"
2294   /// argument, as used in AMD64-ABI 3.5.7.
2295   ///
2296   /// If a word is unused its result will be NoClass; if a type should
2297   /// be passed in Memory then at least the classification of \arg Lo
2298   /// will be Memory.
2299   ///
2300   /// The \arg Lo class will be NoClass iff the argument is ignored.
2301   ///
2302   /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
2303   /// also be ComplexX87.
2304   void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi,
2305                 bool isNamedArg) const;
2306 
2307   llvm::Type *GetByteVectorType(QualType Ty) const;
2308   llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
2309                                  unsigned IROffset, QualType SourceTy,
2310                                  unsigned SourceOffset) const;
2311   llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
2312                                      unsigned IROffset, QualType SourceTy,
2313                                      unsigned SourceOffset) const;
2314 
2315   /// getIndirectResult - Give a source type \arg Ty, return a suitable result
2316   /// such that the argument will be returned in memory.
2317   ABIArgInfo getIndirectReturnResult(QualType Ty) const;
2318 
2319   /// getIndirectResult - Give a source type \arg Ty, return a suitable result
2320   /// such that the argument will be passed in memory.
2321   ///
2322   /// \param freeIntRegs - The number of free integer registers remaining
2323   /// available.
2324   ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
2325 
2326   ABIArgInfo classifyReturnType(QualType RetTy) const;
2327 
2328   ABIArgInfo classifyArgumentType(QualType Ty, unsigned freeIntRegs,
2329                                   unsigned &neededInt, unsigned &neededSSE,
2330                                   bool isNamedArg) const;
2331 
2332   ABIArgInfo classifyRegCallStructType(QualType Ty, unsigned &NeededInt,
2333                                        unsigned &NeededSSE) const;
2334 
2335   ABIArgInfo classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
2336                                            unsigned &NeededSSE) const;
2337 
2338   bool IsIllegalVectorType(QualType Ty) const;
2339 
2340   /// The 0.98 ABI revision clarified a lot of ambiguities,
2341   /// unfortunately in ways that were not always consistent with
2342   /// certain previous compilers.  In particular, platforms which
2343   /// required strict binary compatibility with older versions of GCC
2344   /// may need to exempt themselves.
2345   bool honorsRevision0_98() const {
2346     return !getTarget().getTriple().isOSDarwin();
2347   }
2348 
2349   /// GCC classifies <1 x long long> as SSE but some platform ABIs choose to
2350   /// classify it as INTEGER (for compatibility with older clang compilers).
2351   bool classifyIntegerMMXAsSSE() const {
2352     // Clang <= 3.8 did not do this.
2353     if (getContext().getLangOpts().getClangABICompat() <=
2354         LangOptions::ClangABI::Ver3_8)
2355       return false;
2356 
2357     const llvm::Triple &Triple = getTarget().getTriple();
2358     if (Triple.isOSDarwin() || Triple.getOS() == llvm::Triple::PS4)
2359       return false;
2360     if (Triple.isOSFreeBSD() && Triple.getOSMajorVersion() >= 10)
2361       return false;
2362     return true;
2363   }
2364 
2365   // GCC classifies vectors of __int128 as memory.
2366   bool passInt128VectorsInMem() const {
2367     // Clang <= 9.0 did not do this.
2368     if (getContext().getLangOpts().getClangABICompat() <=
2369         LangOptions::ClangABI::Ver9)
2370       return false;
2371 
2372     const llvm::Triple &T = getTarget().getTriple();
2373     return T.isOSLinux() || T.isOSNetBSD();
2374   }
2375 
2376   X86AVXABILevel AVXLevel;
2377   // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
2378   // 64-bit hardware.
2379   bool Has64BitPointers;
2380 
2381 public:
2382   X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) :
2383       SwiftABIInfo(CGT), AVXLevel(AVXLevel),
2384       Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {
2385   }
2386 
2387   bool isPassedUsingAVXType(QualType type) const {
2388     unsigned neededInt, neededSSE;
2389     // The freeIntRegs argument doesn't matter here.
2390     ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE,
2391                                            /*isNamedArg*/true);
2392     if (info.isDirect()) {
2393       llvm::Type *ty = info.getCoerceToType();
2394       if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
2395         return vectorTy->getPrimitiveSizeInBits().getFixedSize() > 128;
2396     }
2397     return false;
2398   }
2399 
2400   void computeInfo(CGFunctionInfo &FI) const override;
2401 
2402   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
2403                     QualType Ty) const override;
2404   Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
2405                       QualType Ty) const override;
2406 
2407   bool has64BitPointers() const {
2408     return Has64BitPointers;
2409   }
2410 
2411   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
2412                                     bool asReturnValue) const override {
2413     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
2414   }
2415   bool isSwiftErrorInRegister() const override {
2416     return true;
2417   }
2418 };
2419 
2420 /// WinX86_64ABIInfo - The Windows X86_64 ABI information.
2421 class WinX86_64ABIInfo : public SwiftABIInfo {
2422 public:
2423   WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
2424       : SwiftABIInfo(CGT), AVXLevel(AVXLevel),
2425         IsMingw64(getTarget().getTriple().isWindowsGNUEnvironment()) {}
2426 
2427   void computeInfo(CGFunctionInfo &FI) const override;
2428 
2429   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
2430                     QualType Ty) const override;
2431 
2432   bool isHomogeneousAggregateBaseType(QualType Ty) const override {
2433     // FIXME: Assumes vectorcall is in use.
2434     return isX86VectorTypeForVectorCall(getContext(), Ty);
2435   }
2436 
2437   bool isHomogeneousAggregateSmallEnough(const Type *Ty,
2438                                          uint64_t NumMembers) const override {
2439     // FIXME: Assumes vectorcall is in use.
2440     return isX86VectorCallAggregateSmallEnough(NumMembers);
2441   }
2442 
2443   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type *> scalars,
2444                                     bool asReturnValue) const override {
2445     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
2446   }
2447 
2448   bool isSwiftErrorInRegister() const override {
2449     return true;
2450   }
2451 
2452 private:
2453   ABIArgInfo classify(QualType Ty, unsigned &FreeSSERegs, bool IsReturnType,
2454                       bool IsVectorCall, bool IsRegCall) const;
2455   ABIArgInfo reclassifyHvaArgForVectorCall(QualType Ty, unsigned &FreeSSERegs,
2456                                            const ABIArgInfo &current) const;
2457 
2458   X86AVXABILevel AVXLevel;
2459 
2460   bool IsMingw64;
2461 };
2462 
2463 class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2464 public:
2465   X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
2466       : TargetCodeGenInfo(std::make_unique<X86_64ABIInfo>(CGT, AVXLevel)) {}
2467 
2468   const X86_64ABIInfo &getABIInfo() const {
2469     return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
2470   }
2471 
2472   /// Disable tail call on x86-64. The epilogue code before the tail jump blocks
2473   /// autoreleaseRV/retainRV and autoreleaseRV/unsafeClaimRV optimizations.
2474   bool markARCOptimizedReturnCallsAsNoTail() const override { return true; }
2475 
2476   int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
2477     return 7;
2478   }
2479 
2480   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2481                                llvm::Value *Address) const override {
2482     llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
2483 
2484     // 0-15 are the 16 integer registers.
2485     // 16 is %rip.
2486     AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
2487     return false;
2488   }
2489 
2490   llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
2491                                   StringRef Constraint,
2492                                   llvm::Type* Ty) const override {
2493     return X86AdjustInlineAsmType(CGF, Constraint, Ty);
2494   }
2495 
2496   bool isNoProtoCallVariadic(const CallArgList &args,
2497                              const FunctionNoProtoType *fnType) const override {
2498     // The default CC on x86-64 sets %al to the number of SSA
2499     // registers used, and GCC sets this when calling an unprototyped
2500     // function, so we override the default behavior.  However, don't do
2501     // that when AVX types are involved: the ABI explicitly states it is
2502     // undefined, and it doesn't work in practice because of how the ABI
2503     // defines varargs anyway.
2504     if (fnType->getCallConv() == CC_C) {
2505       bool HasAVXType = false;
2506       for (CallArgList::const_iterator
2507              it = args.begin(), ie = args.end(); it != ie; ++it) {
2508         if (getABIInfo().isPassedUsingAVXType(it->Ty)) {
2509           HasAVXType = true;
2510           break;
2511         }
2512       }
2513 
2514       if (!HasAVXType)
2515         return true;
2516     }
2517 
2518     return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
2519   }
2520 
2521   llvm::Constant *
2522   getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
2523     unsigned Sig = (0xeb << 0) | // jmp rel8
2524                    (0x06 << 8) | //           .+0x08
2525                    ('v' << 16) |
2526                    ('2' << 24);
2527     return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
2528   }
2529 
2530   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2531                            CodeGen::CodeGenModule &CGM) const override {
2532     if (GV->isDeclaration())
2533       return;
2534     if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2535       if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
2536         llvm::Function *Fn = cast<llvm::Function>(GV);
2537         Fn->addFnAttr("stackrealign");
2538       }
2539 
2540       addX86InterruptAttrs(FD, GV, CGM);
2541     }
2542   }
2543 
2544   void checkFunctionCallABI(CodeGenModule &CGM, SourceLocation CallLoc,
2545                             const FunctionDecl *Caller,
2546                             const FunctionDecl *Callee,
2547                             const CallArgList &Args) const override;
2548 };
2549 
2550 static void initFeatureMaps(const ASTContext &Ctx,
2551                             llvm::StringMap<bool> &CallerMap,
2552                             const FunctionDecl *Caller,
2553                             llvm::StringMap<bool> &CalleeMap,
2554                             const FunctionDecl *Callee) {
2555   if (CalleeMap.empty() && CallerMap.empty()) {
2556     // The caller is potentially nullptr in the case where the call isn't in a
2557     // function.  In this case, the getFunctionFeatureMap ensures we just get
2558     // the TU level setting (since it cannot be modified by 'target'..
2559     Ctx.getFunctionFeatureMap(CallerMap, Caller);
2560     Ctx.getFunctionFeatureMap(CalleeMap, Callee);
2561   }
2562 }
2563 
2564 static bool checkAVXParamFeature(DiagnosticsEngine &Diag,
2565                                  SourceLocation CallLoc,
2566                                  const llvm::StringMap<bool> &CallerMap,
2567                                  const llvm::StringMap<bool> &CalleeMap,
2568                                  QualType Ty, StringRef Feature,
2569                                  bool IsArgument) {
2570   bool CallerHasFeat = CallerMap.lookup(Feature);
2571   bool CalleeHasFeat = CalleeMap.lookup(Feature);
2572   if (!CallerHasFeat && !CalleeHasFeat)
2573     return Diag.Report(CallLoc, diag::warn_avx_calling_convention)
2574            << IsArgument << Ty << Feature;
2575 
2576   // Mixing calling conventions here is very clearly an error.
2577   if (!CallerHasFeat || !CalleeHasFeat)
2578     return Diag.Report(CallLoc, diag::err_avx_calling_convention)
2579            << IsArgument << Ty << Feature;
2580 
2581   // Else, both caller and callee have the required feature, so there is no need
2582   // to diagnose.
2583   return false;
2584 }
2585 
2586 static bool checkAVXParam(DiagnosticsEngine &Diag, ASTContext &Ctx,
2587                           SourceLocation CallLoc,
2588                           const llvm::StringMap<bool> &CallerMap,
2589                           const llvm::StringMap<bool> &CalleeMap, QualType Ty,
2590                           bool IsArgument) {
2591   uint64_t Size = Ctx.getTypeSize(Ty);
2592   if (Size > 256)
2593     return checkAVXParamFeature(Diag, CallLoc, CallerMap, CalleeMap, Ty,
2594                                 "avx512f", IsArgument);
2595 
2596   if (Size > 128)
2597     return checkAVXParamFeature(Diag, CallLoc, CallerMap, CalleeMap, Ty, "avx",
2598                                 IsArgument);
2599 
2600   return false;
2601 }
2602 
2603 void X86_64TargetCodeGenInfo::checkFunctionCallABI(
2604     CodeGenModule &CGM, SourceLocation CallLoc, const FunctionDecl *Caller,
2605     const FunctionDecl *Callee, const CallArgList &Args) const {
2606   llvm::StringMap<bool> CallerMap;
2607   llvm::StringMap<bool> CalleeMap;
2608   unsigned ArgIndex = 0;
2609 
2610   // We need to loop through the actual call arguments rather than the the
2611   // function's parameters, in case this variadic.
2612   for (const CallArg &Arg : Args) {
2613     // The "avx" feature changes how vectors >128 in size are passed. "avx512f"
2614     // additionally changes how vectors >256 in size are passed. Like GCC, we
2615     // warn when a function is called with an argument where this will change.
2616     // Unlike GCC, we also error when it is an obvious ABI mismatch, that is,
2617     // the caller and callee features are mismatched.
2618     // Unfortunately, we cannot do this diagnostic in SEMA, since the callee can
2619     // change its ABI with attribute-target after this call.
2620     if (Arg.getType()->isVectorType() &&
2621         CGM.getContext().getTypeSize(Arg.getType()) > 128) {
2622       initFeatureMaps(CGM.getContext(), CallerMap, Caller, CalleeMap, Callee);
2623       QualType Ty = Arg.getType();
2624       // The CallArg seems to have desugared the type already, so for clearer
2625       // diagnostics, replace it with the type in the FunctionDecl if possible.
2626       if (ArgIndex < Callee->getNumParams())
2627         Ty = Callee->getParamDecl(ArgIndex)->getType();
2628 
2629       if (checkAVXParam(CGM.getDiags(), CGM.getContext(), CallLoc, CallerMap,
2630                         CalleeMap, Ty, /*IsArgument*/ true))
2631         return;
2632     }
2633     ++ArgIndex;
2634   }
2635 
2636   // Check return always, as we don't have a good way of knowing in codegen
2637   // whether this value is used, tail-called, etc.
2638   if (Callee->getReturnType()->isVectorType() &&
2639       CGM.getContext().getTypeSize(Callee->getReturnType()) > 128) {
2640     initFeatureMaps(CGM.getContext(), CallerMap, Caller, CalleeMap, Callee);
2641     checkAVXParam(CGM.getDiags(), CGM.getContext(), CallLoc, CallerMap,
2642                   CalleeMap, Callee->getReturnType(),
2643                   /*IsArgument*/ false);
2644   }
2645 }
2646 
2647 static std::string qualifyWindowsLibrary(llvm::StringRef Lib) {
2648   // If the argument does not end in .lib, automatically add the suffix.
2649   // If the argument contains a space, enclose it in quotes.
2650   // This matches the behavior of MSVC.
2651   bool Quote = Lib.contains(' ');
2652   std::string ArgStr = Quote ? "\"" : "";
2653   ArgStr += Lib;
2654   if (!Lib.endswith_insensitive(".lib") && !Lib.endswith_insensitive(".a"))
2655     ArgStr += ".lib";
2656   ArgStr += Quote ? "\"" : "";
2657   return ArgStr;
2658 }
2659 
2660 class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
2661 public:
2662   WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
2663         bool DarwinVectorABI, bool RetSmallStructInRegABI, bool Win32StructABI,
2664         unsigned NumRegisterParameters)
2665     : X86_32TargetCodeGenInfo(CGT, DarwinVectorABI, RetSmallStructInRegABI,
2666         Win32StructABI, NumRegisterParameters, false) {}
2667 
2668   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2669                            CodeGen::CodeGenModule &CGM) const override;
2670 
2671   void getDependentLibraryOption(llvm::StringRef Lib,
2672                                  llvm::SmallString<24> &Opt) const override {
2673     Opt = "/DEFAULTLIB:";
2674     Opt += qualifyWindowsLibrary(Lib);
2675   }
2676 
2677   void getDetectMismatchOption(llvm::StringRef Name,
2678                                llvm::StringRef Value,
2679                                llvm::SmallString<32> &Opt) const override {
2680     Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
2681   }
2682 };
2683 
2684 static void addStackProbeTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2685                                           CodeGen::CodeGenModule &CGM) {
2686   if (llvm::Function *Fn = dyn_cast_or_null<llvm::Function>(GV)) {
2687 
2688     if (CGM.getCodeGenOpts().StackProbeSize != 4096)
2689       Fn->addFnAttr("stack-probe-size",
2690                     llvm::utostr(CGM.getCodeGenOpts().StackProbeSize));
2691     if (CGM.getCodeGenOpts().NoStackArgProbe)
2692       Fn->addFnAttr("no-stack-arg-probe");
2693   }
2694 }
2695 
2696 void WinX86_32TargetCodeGenInfo::setTargetAttributes(
2697     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
2698   X86_32TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
2699   if (GV->isDeclaration())
2700     return;
2701   addStackProbeTargetAttributes(D, GV, CGM);
2702 }
2703 
2704 class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2705 public:
2706   WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
2707                              X86AVXABILevel AVXLevel)
2708       : TargetCodeGenInfo(std::make_unique<WinX86_64ABIInfo>(CGT, AVXLevel)) {}
2709 
2710   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2711                            CodeGen::CodeGenModule &CGM) const override;
2712 
2713   int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
2714     return 7;
2715   }
2716 
2717   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2718                                llvm::Value *Address) const override {
2719     llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
2720 
2721     // 0-15 are the 16 integer registers.
2722     // 16 is %rip.
2723     AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
2724     return false;
2725   }
2726 
2727   void getDependentLibraryOption(llvm::StringRef Lib,
2728                                  llvm::SmallString<24> &Opt) const override {
2729     Opt = "/DEFAULTLIB:";
2730     Opt += qualifyWindowsLibrary(Lib);
2731   }
2732 
2733   void getDetectMismatchOption(llvm::StringRef Name,
2734                                llvm::StringRef Value,
2735                                llvm::SmallString<32> &Opt) const override {
2736     Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
2737   }
2738 };
2739 
2740 void WinX86_64TargetCodeGenInfo::setTargetAttributes(
2741     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
2742   TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
2743   if (GV->isDeclaration())
2744     return;
2745   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2746     if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
2747       llvm::Function *Fn = cast<llvm::Function>(GV);
2748       Fn->addFnAttr("stackrealign");
2749     }
2750 
2751     addX86InterruptAttrs(FD, GV, CGM);
2752   }
2753 
2754   addStackProbeTargetAttributes(D, GV, CGM);
2755 }
2756 }
2757 
2758 void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
2759                               Class &Hi) const {
2760   // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
2761   //
2762   // (a) If one of the classes is Memory, the whole argument is passed in
2763   //     memory.
2764   //
2765   // (b) If X87UP is not preceded by X87, the whole argument is passed in
2766   //     memory.
2767   //
2768   // (c) If the size of the aggregate exceeds two eightbytes and the first
2769   //     eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
2770   //     argument is passed in memory. NOTE: This is necessary to keep the
2771   //     ABI working for processors that don't support the __m256 type.
2772   //
2773   // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
2774   //
2775   // Some of these are enforced by the merging logic.  Others can arise
2776   // only with unions; for example:
2777   //   union { _Complex double; unsigned; }
2778   //
2779   // Note that clauses (b) and (c) were added in 0.98.
2780   //
2781   if (Hi == Memory)
2782     Lo = Memory;
2783   if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
2784     Lo = Memory;
2785   if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
2786     Lo = Memory;
2787   if (Hi == SSEUp && Lo != SSE)
2788     Hi = SSE;
2789 }
2790 
2791 X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
2792   // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
2793   // classified recursively so that always two fields are
2794   // considered. The resulting class is calculated according to
2795   // the classes of the fields in the eightbyte:
2796   //
2797   // (a) If both classes are equal, this is the resulting class.
2798   //
2799   // (b) If one of the classes is NO_CLASS, the resulting class is
2800   // the other class.
2801   //
2802   // (c) If one of the classes is MEMORY, the result is the MEMORY
2803   // class.
2804   //
2805   // (d) If one of the classes is INTEGER, the result is the
2806   // INTEGER.
2807   //
2808   // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
2809   // MEMORY is used as class.
2810   //
2811   // (f) Otherwise class SSE is used.
2812 
2813   // Accum should never be memory (we should have returned) or
2814   // ComplexX87 (because this cannot be passed in a structure).
2815   assert((Accum != Memory && Accum != ComplexX87) &&
2816          "Invalid accumulated classification during merge.");
2817   if (Accum == Field || Field == NoClass)
2818     return Accum;
2819   if (Field == Memory)
2820     return Memory;
2821   if (Accum == NoClass)
2822     return Field;
2823   if (Accum == Integer || Field == Integer)
2824     return Integer;
2825   if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
2826       Accum == X87 || Accum == X87Up)
2827     return Memory;
2828   return SSE;
2829 }
2830 
2831 void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
2832                              Class &Lo, Class &Hi, bool isNamedArg) const {
2833   // FIXME: This code can be simplified by introducing a simple value class for
2834   // Class pairs with appropriate constructor methods for the various
2835   // situations.
2836 
2837   // FIXME: Some of the split computations are wrong; unaligned vectors
2838   // shouldn't be passed in registers for example, so there is no chance they
2839   // can straddle an eightbyte. Verify & simplify.
2840 
2841   Lo = Hi = NoClass;
2842 
2843   Class &Current = OffsetBase < 64 ? Lo : Hi;
2844   Current = Memory;
2845 
2846   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
2847     BuiltinType::Kind k = BT->getKind();
2848 
2849     if (k == BuiltinType::Void) {
2850       Current = NoClass;
2851     } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
2852       Lo = Integer;
2853       Hi = Integer;
2854     } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
2855       Current = Integer;
2856     } else if (k == BuiltinType::Float || k == BuiltinType::Double ||
2857                k == BuiltinType::Float16) {
2858       Current = SSE;
2859     } else if (k == BuiltinType::LongDouble) {
2860       const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
2861       if (LDF == &llvm::APFloat::IEEEquad()) {
2862         Lo = SSE;
2863         Hi = SSEUp;
2864       } else if (LDF == &llvm::APFloat::x87DoubleExtended()) {
2865         Lo = X87;
2866         Hi = X87Up;
2867       } else if (LDF == &llvm::APFloat::IEEEdouble()) {
2868         Current = SSE;
2869       } else
2870         llvm_unreachable("unexpected long double representation!");
2871     }
2872     // FIXME: _Decimal32 and _Decimal64 are SSE.
2873     // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
2874     return;
2875   }
2876 
2877   if (const EnumType *ET = Ty->getAs<EnumType>()) {
2878     // Classify the underlying integer type.
2879     classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
2880     return;
2881   }
2882 
2883   if (Ty->hasPointerRepresentation()) {
2884     Current = Integer;
2885     return;
2886   }
2887 
2888   if (Ty->isMemberPointerType()) {
2889     if (Ty->isMemberFunctionPointerType()) {
2890       if (Has64BitPointers) {
2891         // If Has64BitPointers, this is an {i64, i64}, so classify both
2892         // Lo and Hi now.
2893         Lo = Hi = Integer;
2894       } else {
2895         // Otherwise, with 32-bit pointers, this is an {i32, i32}. If that
2896         // straddles an eightbyte boundary, Hi should be classified as well.
2897         uint64_t EB_FuncPtr = (OffsetBase) / 64;
2898         uint64_t EB_ThisAdj = (OffsetBase + 64 - 1) / 64;
2899         if (EB_FuncPtr != EB_ThisAdj) {
2900           Lo = Hi = Integer;
2901         } else {
2902           Current = Integer;
2903         }
2904       }
2905     } else {
2906       Current = Integer;
2907     }
2908     return;
2909   }
2910 
2911   if (const VectorType *VT = Ty->getAs<VectorType>()) {
2912     uint64_t Size = getContext().getTypeSize(VT);
2913     if (Size == 1 || Size == 8 || Size == 16 || Size == 32) {
2914       // gcc passes the following as integer:
2915       // 4 bytes - <4 x char>, <2 x short>, <1 x int>, <1 x float>
2916       // 2 bytes - <2 x char>, <1 x short>
2917       // 1 byte  - <1 x char>
2918       Current = Integer;
2919 
2920       // If this type crosses an eightbyte boundary, it should be
2921       // split.
2922       uint64_t EB_Lo = (OffsetBase) / 64;
2923       uint64_t EB_Hi = (OffsetBase + Size - 1) / 64;
2924       if (EB_Lo != EB_Hi)
2925         Hi = Lo;
2926     } else if (Size == 64) {
2927       QualType ElementType = VT->getElementType();
2928 
2929       // gcc passes <1 x double> in memory. :(
2930       if (ElementType->isSpecificBuiltinType(BuiltinType::Double))
2931         return;
2932 
2933       // gcc passes <1 x long long> as SSE but clang used to unconditionally
2934       // pass them as integer.  For platforms where clang is the de facto
2935       // platform compiler, we must continue to use integer.
2936       if (!classifyIntegerMMXAsSSE() &&
2937           (ElementType->isSpecificBuiltinType(BuiltinType::LongLong) ||
2938            ElementType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
2939            ElementType->isSpecificBuiltinType(BuiltinType::Long) ||
2940            ElementType->isSpecificBuiltinType(BuiltinType::ULong)))
2941         Current = Integer;
2942       else
2943         Current = SSE;
2944 
2945       // If this type crosses an eightbyte boundary, it should be
2946       // split.
2947       if (OffsetBase && OffsetBase != 64)
2948         Hi = Lo;
2949     } else if (Size == 128 ||
2950                (isNamedArg && Size <= getNativeVectorSizeForAVXABI(AVXLevel))) {
2951       QualType ElementType = VT->getElementType();
2952 
2953       // gcc passes 256 and 512 bit <X x __int128> vectors in memory. :(
2954       if (passInt128VectorsInMem() && Size != 128 &&
2955           (ElementType->isSpecificBuiltinType(BuiltinType::Int128) ||
2956            ElementType->isSpecificBuiltinType(BuiltinType::UInt128)))
2957         return;
2958 
2959       // Arguments of 256-bits are split into four eightbyte chunks. The
2960       // least significant one belongs to class SSE and all the others to class
2961       // SSEUP. The original Lo and Hi design considers that types can't be
2962       // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
2963       // This design isn't correct for 256-bits, but since there're no cases
2964       // where the upper parts would need to be inspected, avoid adding
2965       // complexity and just consider Hi to match the 64-256 part.
2966       //
2967       // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
2968       // registers if they are "named", i.e. not part of the "..." of a
2969       // variadic function.
2970       //
2971       // Similarly, per 3.2.3. of the AVX512 draft, 512-bits ("named") args are
2972       // split into eight eightbyte chunks, one SSE and seven SSEUP.
2973       Lo = SSE;
2974       Hi = SSEUp;
2975     }
2976     return;
2977   }
2978 
2979   if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
2980     QualType ET = getContext().getCanonicalType(CT->getElementType());
2981 
2982     uint64_t Size = getContext().getTypeSize(Ty);
2983     if (ET->isIntegralOrEnumerationType()) {
2984       if (Size <= 64)
2985         Current = Integer;
2986       else if (Size <= 128)
2987         Lo = Hi = Integer;
2988     } else if (ET->isFloat16Type() || ET == getContext().FloatTy) {
2989       Current = SSE;
2990     } else if (ET == getContext().DoubleTy) {
2991       Lo = Hi = SSE;
2992     } else if (ET == getContext().LongDoubleTy) {
2993       const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
2994       if (LDF == &llvm::APFloat::IEEEquad())
2995         Current = Memory;
2996       else if (LDF == &llvm::APFloat::x87DoubleExtended())
2997         Current = ComplexX87;
2998       else if (LDF == &llvm::APFloat::IEEEdouble())
2999         Lo = Hi = SSE;
3000       else
3001         llvm_unreachable("unexpected long double representation!");
3002     }
3003 
3004     // If this complex type crosses an eightbyte boundary then it
3005     // should be split.
3006     uint64_t EB_Real = (OffsetBase) / 64;
3007     uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
3008     if (Hi == NoClass && EB_Real != EB_Imag)
3009       Hi = Lo;
3010 
3011     return;
3012   }
3013 
3014   if (const auto *EITy = Ty->getAs<BitIntType>()) {
3015     if (EITy->getNumBits() <= 64)
3016       Current = Integer;
3017     else if (EITy->getNumBits() <= 128)
3018       Lo = Hi = Integer;
3019     // Larger values need to get passed in memory.
3020     return;
3021   }
3022 
3023   if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
3024     // Arrays are treated like structures.
3025 
3026     uint64_t Size = getContext().getTypeSize(Ty);
3027 
3028     // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
3029     // than eight eightbytes, ..., it has class MEMORY.
3030     if (Size > 512)
3031       return;
3032 
3033     // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
3034     // fields, it has class MEMORY.
3035     //
3036     // Only need to check alignment of array base.
3037     if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
3038       return;
3039 
3040     // Otherwise implement simplified merge. We could be smarter about
3041     // this, but it isn't worth it and would be harder to verify.
3042     Current = NoClass;
3043     uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
3044     uint64_t ArraySize = AT->getSize().getZExtValue();
3045 
3046     // The only case a 256-bit wide vector could be used is when the array
3047     // contains a single 256-bit element. Since Lo and Hi logic isn't extended
3048     // to work for sizes wider than 128, early check and fallback to memory.
3049     //
3050     if (Size > 128 &&
3051         (Size != EltSize || Size > getNativeVectorSizeForAVXABI(AVXLevel)))
3052       return;
3053 
3054     for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
3055       Class FieldLo, FieldHi;
3056       classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
3057       Lo = merge(Lo, FieldLo);
3058       Hi = merge(Hi, FieldHi);
3059       if (Lo == Memory || Hi == Memory)
3060         break;
3061     }
3062 
3063     postMerge(Size, Lo, Hi);
3064     assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
3065     return;
3066   }
3067 
3068   if (const RecordType *RT = Ty->getAs<RecordType>()) {
3069     uint64_t Size = getContext().getTypeSize(Ty);
3070 
3071     // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
3072     // than eight eightbytes, ..., it has class MEMORY.
3073     if (Size > 512)
3074       return;
3075 
3076     // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
3077     // copy constructor or a non-trivial destructor, it is passed by invisible
3078     // reference.
3079     if (getRecordArgABI(RT, getCXXABI()))
3080       return;
3081 
3082     const RecordDecl *RD = RT->getDecl();
3083 
3084     // Assume variable sized types are passed in memory.
3085     if (RD->hasFlexibleArrayMember())
3086       return;
3087 
3088     const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
3089 
3090     // Reset Lo class, this will be recomputed.
3091     Current = NoClass;
3092 
3093     // If this is a C++ record, classify the bases first.
3094     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3095       for (const auto &I : CXXRD->bases()) {
3096         assert(!I.isVirtual() && !I.getType()->isDependentType() &&
3097                "Unexpected base class!");
3098         const auto *Base =
3099             cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
3100 
3101         // Classify this field.
3102         //
3103         // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
3104         // single eightbyte, each is classified separately. Each eightbyte gets
3105         // initialized to class NO_CLASS.
3106         Class FieldLo, FieldHi;
3107         uint64_t Offset =
3108           OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
3109         classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg);
3110         Lo = merge(Lo, FieldLo);
3111         Hi = merge(Hi, FieldHi);
3112         if (Lo == Memory || Hi == Memory) {
3113           postMerge(Size, Lo, Hi);
3114           return;
3115         }
3116       }
3117     }
3118 
3119     // Classify the fields one at a time, merging the results.
3120     unsigned idx = 0;
3121     bool UseClang11Compat = getContext().getLangOpts().getClangABICompat() <=
3122                                 LangOptions::ClangABI::Ver11 ||
3123                             getContext().getTargetInfo().getTriple().isPS4();
3124     bool IsUnion = RT->isUnionType() && !UseClang11Compat;
3125 
3126     for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
3127            i != e; ++i, ++idx) {
3128       uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
3129       bool BitField = i->isBitField();
3130 
3131       // Ignore padding bit-fields.
3132       if (BitField && i->isUnnamedBitfield())
3133         continue;
3134 
3135       // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
3136       // eight eightbytes, or it contains unaligned fields, it has class MEMORY.
3137       //
3138       // The only case a 256-bit or a 512-bit wide vector could be used is when
3139       // the struct contains a single 256-bit or 512-bit element. Early check
3140       // and fallback to memory.
3141       //
3142       // FIXME: Extended the Lo and Hi logic properly to work for size wider
3143       // than 128.
3144       if (Size > 128 &&
3145           ((!IsUnion && Size != getContext().getTypeSize(i->getType())) ||
3146            Size > getNativeVectorSizeForAVXABI(AVXLevel))) {
3147         Lo = Memory;
3148         postMerge(Size, Lo, Hi);
3149         return;
3150       }
3151       // Note, skip this test for bit-fields, see below.
3152       if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
3153         Lo = Memory;
3154         postMerge(Size, Lo, Hi);
3155         return;
3156       }
3157 
3158       // Classify this field.
3159       //
3160       // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
3161       // exceeds a single eightbyte, each is classified
3162       // separately. Each eightbyte gets initialized to class
3163       // NO_CLASS.
3164       Class FieldLo, FieldHi;
3165 
3166       // Bit-fields require special handling, they do not force the
3167       // structure to be passed in memory even if unaligned, and
3168       // therefore they can straddle an eightbyte.
3169       if (BitField) {
3170         assert(!i->isUnnamedBitfield());
3171         uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
3172         uint64_t Size = i->getBitWidthValue(getContext());
3173 
3174         uint64_t EB_Lo = Offset / 64;
3175         uint64_t EB_Hi = (Offset + Size - 1) / 64;
3176 
3177         if (EB_Lo) {
3178           assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
3179           FieldLo = NoClass;
3180           FieldHi = Integer;
3181         } else {
3182           FieldLo = Integer;
3183           FieldHi = EB_Hi ? Integer : NoClass;
3184         }
3185       } else
3186         classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
3187       Lo = merge(Lo, FieldLo);
3188       Hi = merge(Hi, FieldHi);
3189       if (Lo == Memory || Hi == Memory)
3190         break;
3191     }
3192 
3193     postMerge(Size, Lo, Hi);
3194   }
3195 }
3196 
3197 ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
3198   // If this is a scalar LLVM value then assume LLVM will pass it in the right
3199   // place naturally.
3200   if (!isAggregateTypeForABI(Ty)) {
3201     // Treat an enum type as its underlying type.
3202     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3203       Ty = EnumTy->getDecl()->getIntegerType();
3204 
3205     if (Ty->isBitIntType())
3206       return getNaturalAlignIndirect(Ty);
3207 
3208     return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
3209                                               : ABIArgInfo::getDirect());
3210   }
3211 
3212   return getNaturalAlignIndirect(Ty);
3213 }
3214 
3215 bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
3216   if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
3217     uint64_t Size = getContext().getTypeSize(VecTy);
3218     unsigned LargestVector = getNativeVectorSizeForAVXABI(AVXLevel);
3219     if (Size <= 64 || Size > LargestVector)
3220       return true;
3221     QualType EltTy = VecTy->getElementType();
3222     if (passInt128VectorsInMem() &&
3223         (EltTy->isSpecificBuiltinType(BuiltinType::Int128) ||
3224          EltTy->isSpecificBuiltinType(BuiltinType::UInt128)))
3225       return true;
3226   }
3227 
3228   return false;
3229 }
3230 
3231 ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
3232                                             unsigned freeIntRegs) const {
3233   // If this is a scalar LLVM value then assume LLVM will pass it in the right
3234   // place naturally.
3235   //
3236   // This assumption is optimistic, as there could be free registers available
3237   // when we need to pass this argument in memory, and LLVM could try to pass
3238   // the argument in the free register. This does not seem to happen currently,
3239   // but this code would be much safer if we could mark the argument with
3240   // 'onstack'. See PR12193.
3241   if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty) &&
3242       !Ty->isBitIntType()) {
3243     // Treat an enum type as its underlying type.
3244     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3245       Ty = EnumTy->getDecl()->getIntegerType();
3246 
3247     return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
3248                                               : ABIArgInfo::getDirect());
3249   }
3250 
3251   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
3252     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
3253 
3254   // Compute the byval alignment. We specify the alignment of the byval in all
3255   // cases so that the mid-level optimizer knows the alignment of the byval.
3256   unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
3257 
3258   // Attempt to avoid passing indirect results using byval when possible. This
3259   // is important for good codegen.
3260   //
3261   // We do this by coercing the value into a scalar type which the backend can
3262   // handle naturally (i.e., without using byval).
3263   //
3264   // For simplicity, we currently only do this when we have exhausted all of the
3265   // free integer registers. Doing this when there are free integer registers
3266   // would require more care, as we would have to ensure that the coerced value
3267   // did not claim the unused register. That would require either reording the
3268   // arguments to the function (so that any subsequent inreg values came first),
3269   // or only doing this optimization when there were no following arguments that
3270   // might be inreg.
3271   //
3272   // We currently expect it to be rare (particularly in well written code) for
3273   // arguments to be passed on the stack when there are still free integer
3274   // registers available (this would typically imply large structs being passed
3275   // by value), so this seems like a fair tradeoff for now.
3276   //
3277   // We can revisit this if the backend grows support for 'onstack' parameter
3278   // attributes. See PR12193.
3279   if (freeIntRegs == 0) {
3280     uint64_t Size = getContext().getTypeSize(Ty);
3281 
3282     // If this type fits in an eightbyte, coerce it into the matching integral
3283     // type, which will end up on the stack (with alignment 8).
3284     if (Align == 8 && Size <= 64)
3285       return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
3286                                                           Size));
3287   }
3288 
3289   return ABIArgInfo::getIndirect(CharUnits::fromQuantity(Align));
3290 }
3291 
3292 /// The ABI specifies that a value should be passed in a full vector XMM/YMM
3293 /// register. Pick an LLVM IR type that will be passed as a vector register.
3294 llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
3295   // Wrapper structs/arrays that only contain vectors are passed just like
3296   // vectors; strip them off if present.
3297   if (const Type *InnerTy = isSingleElementStruct(Ty, getContext()))
3298     Ty = QualType(InnerTy, 0);
3299 
3300   llvm::Type *IRType = CGT.ConvertType(Ty);
3301   if (isa<llvm::VectorType>(IRType)) {
3302     // Don't pass vXi128 vectors in their native type, the backend can't
3303     // legalize them.
3304     if (passInt128VectorsInMem() &&
3305         cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy(128)) {
3306       // Use a vXi64 vector.
3307       uint64_t Size = getContext().getTypeSize(Ty);
3308       return llvm::FixedVectorType::get(llvm::Type::getInt64Ty(getVMContext()),
3309                                         Size / 64);
3310     }
3311 
3312     return IRType;
3313   }
3314 
3315   if (IRType->getTypeID() == llvm::Type::FP128TyID)
3316     return IRType;
3317 
3318   // We couldn't find the preferred IR vector type for 'Ty'.
3319   uint64_t Size = getContext().getTypeSize(Ty);
3320   assert((Size == 128 || Size == 256 || Size == 512) && "Invalid type found!");
3321 
3322 
3323   // Return a LLVM IR vector type based on the size of 'Ty'.
3324   return llvm::FixedVectorType::get(llvm::Type::getDoubleTy(getVMContext()),
3325                                     Size / 64);
3326 }
3327 
3328 /// BitsContainNoUserData - Return true if the specified [start,end) bit range
3329 /// is known to either be off the end of the specified type or being in
3330 /// alignment padding.  The user type specified is known to be at most 128 bits
3331 /// in size, and have passed through X86_64ABIInfo::classify with a successful
3332 /// classification that put one of the two halves in the INTEGER class.
3333 ///
3334 /// It is conservatively correct to return false.
3335 static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
3336                                   unsigned EndBit, ASTContext &Context) {
3337   // If the bytes being queried are off the end of the type, there is no user
3338   // data hiding here.  This handles analysis of builtins, vectors and other
3339   // types that don't contain interesting padding.
3340   unsigned TySize = (unsigned)Context.getTypeSize(Ty);
3341   if (TySize <= StartBit)
3342     return true;
3343 
3344   if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
3345     unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
3346     unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
3347 
3348     // Check each element to see if the element overlaps with the queried range.
3349     for (unsigned i = 0; i != NumElts; ++i) {
3350       // If the element is after the span we care about, then we're done..
3351       unsigned EltOffset = i*EltSize;
3352       if (EltOffset >= EndBit) break;
3353 
3354       unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
3355       if (!BitsContainNoUserData(AT->getElementType(), EltStart,
3356                                  EndBit-EltOffset, Context))
3357         return false;
3358     }
3359     // If it overlaps no elements, then it is safe to process as padding.
3360     return true;
3361   }
3362 
3363   if (const RecordType *RT = Ty->getAs<RecordType>()) {
3364     const RecordDecl *RD = RT->getDecl();
3365     const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
3366 
3367     // If this is a C++ record, check the bases first.
3368     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3369       for (const auto &I : CXXRD->bases()) {
3370         assert(!I.isVirtual() && !I.getType()->isDependentType() &&
3371                "Unexpected base class!");
3372         const auto *Base =
3373             cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
3374 
3375         // If the base is after the span we care about, ignore it.
3376         unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
3377         if (BaseOffset >= EndBit) continue;
3378 
3379         unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
3380         if (!BitsContainNoUserData(I.getType(), BaseStart,
3381                                    EndBit-BaseOffset, Context))
3382           return false;
3383       }
3384     }
3385 
3386     // Verify that no field has data that overlaps the region of interest.  Yes
3387     // this could be sped up a lot by being smarter about queried fields,
3388     // however we're only looking at structs up to 16 bytes, so we don't care
3389     // much.
3390     unsigned idx = 0;
3391     for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
3392          i != e; ++i, ++idx) {
3393       unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
3394 
3395       // If we found a field after the region we care about, then we're done.
3396       if (FieldOffset >= EndBit) break;
3397 
3398       unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
3399       if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
3400                                  Context))
3401         return false;
3402     }
3403 
3404     // If nothing in this record overlapped the area of interest, then we're
3405     // clean.
3406     return true;
3407   }
3408 
3409   return false;
3410 }
3411 
3412 /// getFPTypeAtOffset - Return a floating point type at the specified offset.
3413 static llvm::Type *getFPTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
3414                                      const llvm::DataLayout &TD) {
3415   if (IROffset == 0 && IRType->isFloatingPointTy())
3416     return IRType;
3417 
3418   // If this is a struct, recurse into the field at the specified offset.
3419   if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
3420     if (!STy->getNumContainedTypes())
3421       return nullptr;
3422 
3423     const llvm::StructLayout *SL = TD.getStructLayout(STy);
3424     unsigned Elt = SL->getElementContainingOffset(IROffset);
3425     IROffset -= SL->getElementOffset(Elt);
3426     return getFPTypeAtOffset(STy->getElementType(Elt), IROffset, TD);
3427   }
3428 
3429   // If this is an array, recurse into the field at the specified offset.
3430   if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
3431     llvm::Type *EltTy = ATy->getElementType();
3432     unsigned EltSize = TD.getTypeAllocSize(EltTy);
3433     IROffset -= IROffset / EltSize * EltSize;
3434     return getFPTypeAtOffset(EltTy, IROffset, TD);
3435   }
3436 
3437   return nullptr;
3438 }
3439 
3440 /// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
3441 /// low 8 bytes of an XMM register, corresponding to the SSE class.
3442 llvm::Type *X86_64ABIInfo::
3443 GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
3444                    QualType SourceTy, unsigned SourceOffset) const {
3445   const llvm::DataLayout &TD = getDataLayout();
3446   unsigned SourceSize =
3447       (unsigned)getContext().getTypeSize(SourceTy) / 8 - SourceOffset;
3448   llvm::Type *T0 = getFPTypeAtOffset(IRType, IROffset, TD);
3449   if (!T0 || T0->isDoubleTy())
3450     return llvm::Type::getDoubleTy(getVMContext());
3451 
3452   // Get the adjacent FP type.
3453   llvm::Type *T1 = nullptr;
3454   unsigned T0Size = TD.getTypeAllocSize(T0);
3455   if (SourceSize > T0Size)
3456       T1 = getFPTypeAtOffset(IRType, IROffset + T0Size, TD);
3457   if (T1 == nullptr) {
3458     // Check if IRType is a half + float. float type will be in IROffset+4 due
3459     // to its alignment.
3460     if (T0->isHalfTy() && SourceSize > 4)
3461       T1 = getFPTypeAtOffset(IRType, IROffset + 4, TD);
3462     // If we can't get a second FP type, return a simple half or float.
3463     // avx512fp16-abi.c:pr51813_2 shows it works to return float for
3464     // {float, i8} too.
3465     if (T1 == nullptr)
3466       return T0;
3467   }
3468 
3469   if (T0->isFloatTy() && T1->isFloatTy())
3470     return llvm::FixedVectorType::get(T0, 2);
3471 
3472   if (T0->isHalfTy() && T1->isHalfTy()) {
3473     llvm::Type *T2 = nullptr;
3474     if (SourceSize > 4)
3475       T2 = getFPTypeAtOffset(IRType, IROffset + 4, TD);
3476     if (T2 == nullptr)
3477       return llvm::FixedVectorType::get(T0, 2);
3478     return llvm::FixedVectorType::get(T0, 4);
3479   }
3480 
3481   if (T0->isHalfTy() || T1->isHalfTy())
3482     return llvm::FixedVectorType::get(llvm::Type::getHalfTy(getVMContext()), 4);
3483 
3484   return llvm::Type::getDoubleTy(getVMContext());
3485 }
3486 
3487 
3488 /// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
3489 /// an 8-byte GPR.  This means that we either have a scalar or we are talking
3490 /// about the high or low part of an up-to-16-byte struct.  This routine picks
3491 /// the best LLVM IR type to represent this, which may be i64 or may be anything
3492 /// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
3493 /// etc).
3494 ///
3495 /// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
3496 /// the source type.  IROffset is an offset in bytes into the LLVM IR type that
3497 /// the 8-byte value references.  PrefType may be null.
3498 ///
3499 /// SourceTy is the source-level type for the entire argument.  SourceOffset is
3500 /// an offset into this that we're processing (which is always either 0 or 8).
3501 ///
3502 llvm::Type *X86_64ABIInfo::
3503 GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
3504                        QualType SourceTy, unsigned SourceOffset) const {
3505   // If we're dealing with an un-offset LLVM IR type, then it means that we're
3506   // returning an 8-byte unit starting with it.  See if we can safely use it.
3507   if (IROffset == 0) {
3508     // Pointers and int64's always fill the 8-byte unit.
3509     if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
3510         IRType->isIntegerTy(64))
3511       return IRType;
3512 
3513     // If we have a 1/2/4-byte integer, we can use it only if the rest of the
3514     // goodness in the source type is just tail padding.  This is allowed to
3515     // kick in for struct {double,int} on the int, but not on
3516     // struct{double,int,int} because we wouldn't return the second int.  We
3517     // have to do this analysis on the source type because we can't depend on
3518     // unions being lowered a specific way etc.
3519     if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
3520         IRType->isIntegerTy(32) ||
3521         (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
3522       unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
3523           cast<llvm::IntegerType>(IRType)->getBitWidth();
3524 
3525       if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
3526                                 SourceOffset*8+64, getContext()))
3527         return IRType;
3528     }
3529   }
3530 
3531   if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
3532     // If this is a struct, recurse into the field at the specified offset.
3533     const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
3534     if (IROffset < SL->getSizeInBytes()) {
3535       unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
3536       IROffset -= SL->getElementOffset(FieldIdx);
3537 
3538       return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
3539                                     SourceTy, SourceOffset);
3540     }
3541   }
3542 
3543   if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
3544     llvm::Type *EltTy = ATy->getElementType();
3545     unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
3546     unsigned EltOffset = IROffset/EltSize*EltSize;
3547     return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
3548                                   SourceOffset);
3549   }
3550 
3551   // Okay, we don't have any better idea of what to pass, so we pass this in an
3552   // integer register that isn't too big to fit the rest of the struct.
3553   unsigned TySizeInBytes =
3554     (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
3555 
3556   assert(TySizeInBytes != SourceOffset && "Empty field?");
3557 
3558   // It is always safe to classify this as an integer type up to i64 that
3559   // isn't larger than the structure.
3560   return llvm::IntegerType::get(getVMContext(),
3561                                 std::min(TySizeInBytes-SourceOffset, 8U)*8);
3562 }
3563 
3564 
3565 /// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
3566 /// be used as elements of a two register pair to pass or return, return a
3567 /// first class aggregate to represent them.  For example, if the low part of
3568 /// a by-value argument should be passed as i32* and the high part as float,
3569 /// return {i32*, float}.
3570 static llvm::Type *
3571 GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
3572                            const llvm::DataLayout &TD) {
3573   // In order to correctly satisfy the ABI, we need to the high part to start
3574   // at offset 8.  If the high and low parts we inferred are both 4-byte types
3575   // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
3576   // the second element at offset 8.  Check for this:
3577   unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
3578   unsigned HiAlign = TD.getABITypeAlignment(Hi);
3579   unsigned HiStart = llvm::alignTo(LoSize, HiAlign);
3580   assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
3581 
3582   // To handle this, we have to increase the size of the low part so that the
3583   // second element will start at an 8 byte offset.  We can't increase the size
3584   // of the second element because it might make us access off the end of the
3585   // struct.
3586   if (HiStart != 8) {
3587     // There are usually two sorts of types the ABI generation code can produce
3588     // for the low part of a pair that aren't 8 bytes in size: half, float or
3589     // i8/i16/i32.  This can also include pointers when they are 32-bit (X32 and
3590     // NaCl).
3591     // Promote these to a larger type.
3592     if (Lo->isHalfTy() || Lo->isFloatTy())
3593       Lo = llvm::Type::getDoubleTy(Lo->getContext());
3594     else {
3595       assert((Lo->isIntegerTy() || Lo->isPointerTy())
3596              && "Invalid/unknown lo type");
3597       Lo = llvm::Type::getInt64Ty(Lo->getContext());
3598     }
3599   }
3600 
3601   llvm::StructType *Result = llvm::StructType::get(Lo, Hi);
3602 
3603   // Verify that the second element is at an 8-byte offset.
3604   assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
3605          "Invalid x86-64 argument pair!");
3606   return Result;
3607 }
3608 
3609 ABIArgInfo X86_64ABIInfo::
3610 classifyReturnType(QualType RetTy) const {
3611   // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
3612   // classification algorithm.
3613   X86_64ABIInfo::Class Lo, Hi;
3614   classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
3615 
3616   // Check some invariants.
3617   assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
3618   assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
3619 
3620   llvm::Type *ResType = nullptr;
3621   switch (Lo) {
3622   case NoClass:
3623     if (Hi == NoClass)
3624       return ABIArgInfo::getIgnore();
3625     // If the low part is just padding, it takes no register, leave ResType
3626     // null.
3627     assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3628            "Unknown missing lo part");
3629     break;
3630 
3631   case SSEUp:
3632   case X87Up:
3633     llvm_unreachable("Invalid classification for lo word.");
3634 
3635     // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
3636     // hidden argument.
3637   case Memory:
3638     return getIndirectReturnResult(RetTy);
3639 
3640     // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
3641     // available register of the sequence %rax, %rdx is used.
3642   case Integer:
3643     ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
3644 
3645     // If we have a sign or zero extended integer, make sure to return Extend
3646     // so that the parameter gets the right LLVM IR attributes.
3647     if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3648       // Treat an enum type as its underlying type.
3649       if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
3650         RetTy = EnumTy->getDecl()->getIntegerType();
3651 
3652       if (RetTy->isIntegralOrEnumerationType() &&
3653           isPromotableIntegerTypeForABI(RetTy))
3654         return ABIArgInfo::getExtend(RetTy);
3655     }
3656     break;
3657 
3658     // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
3659     // available SSE register of the sequence %xmm0, %xmm1 is used.
3660   case SSE:
3661     ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
3662     break;
3663 
3664     // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
3665     // returned on the X87 stack in %st0 as 80-bit x87 number.
3666   case X87:
3667     ResType = llvm::Type::getX86_FP80Ty(getVMContext());
3668     break;
3669 
3670     // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
3671     // part of the value is returned in %st0 and the imaginary part in
3672     // %st1.
3673   case ComplexX87:
3674     assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
3675     ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
3676                                     llvm::Type::getX86_FP80Ty(getVMContext()));
3677     break;
3678   }
3679 
3680   llvm::Type *HighPart = nullptr;
3681   switch (Hi) {
3682     // Memory was handled previously and X87 should
3683     // never occur as a hi class.
3684   case Memory:
3685   case X87:
3686     llvm_unreachable("Invalid classification for hi word.");
3687 
3688   case ComplexX87: // Previously handled.
3689   case NoClass:
3690     break;
3691 
3692   case Integer:
3693     HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
3694     if (Lo == NoClass)  // Return HighPart at offset 8 in memory.
3695       return ABIArgInfo::getDirect(HighPart, 8);
3696     break;
3697   case SSE:
3698     HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
3699     if (Lo == NoClass)  // Return HighPart at offset 8 in memory.
3700       return ABIArgInfo::getDirect(HighPart, 8);
3701     break;
3702 
3703     // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
3704     // is passed in the next available eightbyte chunk if the last used
3705     // vector register.
3706     //
3707     // SSEUP should always be preceded by SSE, just widen.
3708   case SSEUp:
3709     assert(Lo == SSE && "Unexpected SSEUp classification.");
3710     ResType = GetByteVectorType(RetTy);
3711     break;
3712 
3713     // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
3714     // returned together with the previous X87 value in %st0.
3715   case X87Up:
3716     // If X87Up is preceded by X87, we don't need to do
3717     // anything. However, in some cases with unions it may not be
3718     // preceded by X87. In such situations we follow gcc and pass the
3719     // extra bits in an SSE reg.
3720     if (Lo != X87) {
3721       HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
3722       if (Lo == NoClass)  // Return HighPart at offset 8 in memory.
3723         return ABIArgInfo::getDirect(HighPart, 8);
3724     }
3725     break;
3726   }
3727 
3728   // If a high part was specified, merge it together with the low part.  It is
3729   // known to pass in the high eightbyte of the result.  We do this by forming a
3730   // first class struct aggregate with the high and low part: {low, high}
3731   if (HighPart)
3732     ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
3733 
3734   return ABIArgInfo::getDirect(ResType);
3735 }
3736 
3737 ABIArgInfo X86_64ABIInfo::classifyArgumentType(
3738   QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE,
3739   bool isNamedArg)
3740   const
3741 {
3742   Ty = useFirstFieldIfTransparentUnion(Ty);
3743 
3744   X86_64ABIInfo::Class Lo, Hi;
3745   classify(Ty, 0, Lo, Hi, isNamedArg);
3746 
3747   // Check some invariants.
3748   // FIXME: Enforce these by construction.
3749   assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
3750   assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
3751 
3752   neededInt = 0;
3753   neededSSE = 0;
3754   llvm::Type *ResType = nullptr;
3755   switch (Lo) {
3756   case NoClass:
3757     if (Hi == NoClass)
3758       return ABIArgInfo::getIgnore();
3759     // If the low part is just padding, it takes no register, leave ResType
3760     // null.
3761     assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3762            "Unknown missing lo part");
3763     break;
3764 
3765     // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
3766     // on the stack.
3767   case Memory:
3768 
3769     // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
3770     // COMPLEX_X87, it is passed in memory.
3771   case X87:
3772   case ComplexX87:
3773     if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect)
3774       ++neededInt;
3775     return getIndirectResult(Ty, freeIntRegs);
3776 
3777   case SSEUp:
3778   case X87Up:
3779     llvm_unreachable("Invalid classification for lo word.");
3780 
3781     // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
3782     // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
3783     // and %r9 is used.
3784   case Integer:
3785     ++neededInt;
3786 
3787     // Pick an 8-byte type based on the preferred type.
3788     ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
3789 
3790     // If we have a sign or zero extended integer, make sure to return Extend
3791     // so that the parameter gets the right LLVM IR attributes.
3792     if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3793       // Treat an enum type as its underlying type.
3794       if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3795         Ty = EnumTy->getDecl()->getIntegerType();
3796 
3797       if (Ty->isIntegralOrEnumerationType() &&
3798           isPromotableIntegerTypeForABI(Ty))
3799         return ABIArgInfo::getExtend(Ty);
3800     }
3801 
3802     break;
3803 
3804     // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
3805     // available SSE register is used, the registers are taken in the
3806     // order from %xmm0 to %xmm7.
3807   case SSE: {
3808     llvm::Type *IRType = CGT.ConvertType(Ty);
3809     ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
3810     ++neededSSE;
3811     break;
3812   }
3813   }
3814 
3815   llvm::Type *HighPart = nullptr;
3816   switch (Hi) {
3817     // Memory was handled previously, ComplexX87 and X87 should
3818     // never occur as hi classes, and X87Up must be preceded by X87,
3819     // which is passed in memory.
3820   case Memory:
3821   case X87:
3822   case ComplexX87:
3823     llvm_unreachable("Invalid classification for hi word.");
3824 
3825   case NoClass: break;
3826 
3827   case Integer:
3828     ++neededInt;
3829     // Pick an 8-byte type based on the preferred type.
3830     HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
3831 
3832     if (Lo == NoClass)  // Pass HighPart at offset 8 in memory.
3833       return ABIArgInfo::getDirect(HighPart, 8);
3834     break;
3835 
3836     // X87Up generally doesn't occur here (long double is passed in
3837     // memory), except in situations involving unions.
3838   case X87Up:
3839   case SSE:
3840     HighPart = GetSSETypeAtOffset(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 
3845     ++neededSSE;
3846     break;
3847 
3848     // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
3849     // eightbyte is passed in the upper half of the last used SSE
3850     // register.  This only happens when 128-bit vectors are passed.
3851   case SSEUp:
3852     assert(Lo == SSE && "Unexpected SSEUp classification");
3853     ResType = GetByteVectorType(Ty);
3854     break;
3855   }
3856 
3857   // If a high part was specified, merge it together with the low part.  It is
3858   // known to pass in the high eightbyte of the result.  We do this by forming a
3859   // first class struct aggregate with the high and low part: {low, high}
3860   if (HighPart)
3861     ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
3862 
3863   return ABIArgInfo::getDirect(ResType);
3864 }
3865 
3866 ABIArgInfo
3867 X86_64ABIInfo::classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
3868                                              unsigned &NeededSSE) const {
3869   auto RT = Ty->getAs<RecordType>();
3870   assert(RT && "classifyRegCallStructType only valid with struct types");
3871 
3872   if (RT->getDecl()->hasFlexibleArrayMember())
3873     return getIndirectReturnResult(Ty);
3874 
3875   // Sum up bases
3876   if (auto CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
3877     if (CXXRD->isDynamicClass()) {
3878       NeededInt = NeededSSE = 0;
3879       return getIndirectReturnResult(Ty);
3880     }
3881 
3882     for (const auto &I : CXXRD->bases())
3883       if (classifyRegCallStructTypeImpl(I.getType(), NeededInt, NeededSSE)
3884               .isIndirect()) {
3885         NeededInt = NeededSSE = 0;
3886         return getIndirectReturnResult(Ty);
3887       }
3888   }
3889 
3890   // Sum up members
3891   for (const auto *FD : RT->getDecl()->fields()) {
3892     if (FD->getType()->isRecordType() && !FD->getType()->isUnionType()) {
3893       if (classifyRegCallStructTypeImpl(FD->getType(), NeededInt, NeededSSE)
3894               .isIndirect()) {
3895         NeededInt = NeededSSE = 0;
3896         return getIndirectReturnResult(Ty);
3897       }
3898     } else {
3899       unsigned LocalNeededInt, LocalNeededSSE;
3900       if (classifyArgumentType(FD->getType(), UINT_MAX, LocalNeededInt,
3901                                LocalNeededSSE, true)
3902               .isIndirect()) {
3903         NeededInt = NeededSSE = 0;
3904         return getIndirectReturnResult(Ty);
3905       }
3906       NeededInt += LocalNeededInt;
3907       NeededSSE += LocalNeededSSE;
3908     }
3909   }
3910 
3911   return ABIArgInfo::getDirect();
3912 }
3913 
3914 ABIArgInfo X86_64ABIInfo::classifyRegCallStructType(QualType Ty,
3915                                                     unsigned &NeededInt,
3916                                                     unsigned &NeededSSE) const {
3917 
3918   NeededInt = 0;
3919   NeededSSE = 0;
3920 
3921   return classifyRegCallStructTypeImpl(Ty, NeededInt, NeededSSE);
3922 }
3923 
3924 void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
3925 
3926   const unsigned CallingConv = FI.getCallingConvention();
3927   // It is possible to force Win64 calling convention on any x86_64 target by
3928   // using __attribute__((ms_abi)). In such case to correctly emit Win64
3929   // compatible code delegate this call to WinX86_64ABIInfo::computeInfo.
3930   if (CallingConv == llvm::CallingConv::Win64) {
3931     WinX86_64ABIInfo Win64ABIInfo(CGT, AVXLevel);
3932     Win64ABIInfo.computeInfo(FI);
3933     return;
3934   }
3935 
3936   bool IsRegCall = CallingConv == llvm::CallingConv::X86_RegCall;
3937 
3938   // Keep track of the number of assigned registers.
3939   unsigned FreeIntRegs = IsRegCall ? 11 : 6;
3940   unsigned FreeSSERegs = IsRegCall ? 16 : 8;
3941   unsigned NeededInt, NeededSSE;
3942 
3943   if (!::classifyReturnType(getCXXABI(), FI, *this)) {
3944     if (IsRegCall && FI.getReturnType()->getTypePtr()->isRecordType() &&
3945         !FI.getReturnType()->getTypePtr()->isUnionType()) {
3946       FI.getReturnInfo() =
3947           classifyRegCallStructType(FI.getReturnType(), NeededInt, NeededSSE);
3948       if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
3949         FreeIntRegs -= NeededInt;
3950         FreeSSERegs -= NeededSSE;
3951       } else {
3952         FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType());
3953       }
3954     } else if (IsRegCall && FI.getReturnType()->getAs<ComplexType>() &&
3955                getContext().getCanonicalType(FI.getReturnType()
3956                                                  ->getAs<ComplexType>()
3957                                                  ->getElementType()) ==
3958                    getContext().LongDoubleTy)
3959       // Complex Long Double Type is passed in Memory when Regcall
3960       // calling convention is used.
3961       FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType());
3962     else
3963       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
3964   }
3965 
3966   // If the return value is indirect, then the hidden argument is consuming one
3967   // integer register.
3968   if (FI.getReturnInfo().isIndirect())
3969     --FreeIntRegs;
3970 
3971   // The chain argument effectively gives us another free register.
3972   if (FI.isChainCall())
3973     ++FreeIntRegs;
3974 
3975   unsigned NumRequiredArgs = FI.getNumRequiredArgs();
3976   // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
3977   // get assigned (in left-to-right order) for passing as follows...
3978   unsigned ArgNo = 0;
3979   for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
3980        it != ie; ++it, ++ArgNo) {
3981     bool IsNamedArg = ArgNo < NumRequiredArgs;
3982 
3983     if (IsRegCall && it->type->isStructureOrClassType())
3984       it->info = classifyRegCallStructType(it->type, NeededInt, NeededSSE);
3985     else
3986       it->info = classifyArgumentType(it->type, FreeIntRegs, NeededInt,
3987                                       NeededSSE, IsNamedArg);
3988 
3989     // AMD64-ABI 3.2.3p3: If there are no registers available for any
3990     // eightbyte of an argument, the whole argument is passed on the
3991     // stack. If registers have already been assigned for some
3992     // eightbytes of such an argument, the assignments get reverted.
3993     if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
3994       FreeIntRegs -= NeededInt;
3995       FreeSSERegs -= NeededSSE;
3996     } else {
3997       it->info = getIndirectResult(it->type, FreeIntRegs);
3998     }
3999   }
4000 }
4001 
4002 static Address EmitX86_64VAArgFromMemory(CodeGenFunction &CGF,
4003                                          Address VAListAddr, QualType Ty) {
4004   Address overflow_arg_area_p =
4005       CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_p");
4006   llvm::Value *overflow_arg_area =
4007     CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
4008 
4009   // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
4010   // byte boundary if alignment needed by type exceeds 8 byte boundary.
4011   // It isn't stated explicitly in the standard, but in practice we use
4012   // alignment greater than 16 where necessary.
4013   CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
4014   if (Align > CharUnits::fromQuantity(8)) {
4015     overflow_arg_area = emitRoundPointerUpToAlignment(CGF, overflow_arg_area,
4016                                                       Align);
4017   }
4018 
4019   // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
4020   llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
4021   llvm::Value *Res =
4022     CGF.Builder.CreateBitCast(overflow_arg_area,
4023                               llvm::PointerType::getUnqual(LTy));
4024 
4025   // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
4026   // l->overflow_arg_area + sizeof(type).
4027   // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
4028   // an 8 byte boundary.
4029 
4030   uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
4031   llvm::Value *Offset =
4032       llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7)  & ~7);
4033   overflow_arg_area = CGF.Builder.CreateGEP(CGF.Int8Ty, overflow_arg_area,
4034                                             Offset, "overflow_arg_area.next");
4035   CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
4036 
4037   // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
4038   return Address(Res, LTy, Align);
4039 }
4040 
4041 Address X86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4042                                  QualType Ty) const {
4043   // Assume that va_list type is correct; should be pointer to LLVM type:
4044   // struct {
4045   //   i32 gp_offset;
4046   //   i32 fp_offset;
4047   //   i8* overflow_arg_area;
4048   //   i8* reg_save_area;
4049   // };
4050   unsigned neededInt, neededSSE;
4051 
4052   Ty = getContext().getCanonicalType(Ty);
4053   ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
4054                                        /*isNamedArg*/false);
4055 
4056   // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
4057   // in the registers. If not go to step 7.
4058   if (!neededInt && !neededSSE)
4059     return EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
4060 
4061   // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
4062   // general purpose registers needed to pass type and num_fp to hold
4063   // the number of floating point registers needed.
4064 
4065   // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
4066   // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
4067   // l->fp_offset > 304 - num_fp * 16 go to step 7.
4068   //
4069   // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
4070   // register save space).
4071 
4072   llvm::Value *InRegs = nullptr;
4073   Address gp_offset_p = Address::invalid(), fp_offset_p = Address::invalid();
4074   llvm::Value *gp_offset = nullptr, *fp_offset = nullptr;
4075   if (neededInt) {
4076     gp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "gp_offset_p");
4077     gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
4078     InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
4079     InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
4080   }
4081 
4082   if (neededSSE) {
4083     fp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 1, "fp_offset_p");
4084     fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
4085     llvm::Value *FitsInFP =
4086       llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
4087     FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
4088     InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
4089   }
4090 
4091   llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
4092   llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
4093   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
4094   CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
4095 
4096   // Emit code to load the value if it was passed in registers.
4097 
4098   CGF.EmitBlock(InRegBlock);
4099 
4100   // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
4101   // an offset of l->gp_offset and/or l->fp_offset. This may require
4102   // copying to a temporary location in case the parameter is passed
4103   // in different register classes or requires an alignment greater
4104   // than 8 for general purpose registers and 16 for XMM registers.
4105   //
4106   // FIXME: This really results in shameful code when we end up needing to
4107   // collect arguments from different places; often what should result in a
4108   // simple assembling of a structure from scattered addresses has many more
4109   // loads than necessary. Can we clean this up?
4110   llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
4111   llvm::Value *RegSaveArea = CGF.Builder.CreateLoad(
4112       CGF.Builder.CreateStructGEP(VAListAddr, 3), "reg_save_area");
4113 
4114   Address RegAddr = Address::invalid();
4115   if (neededInt && neededSSE) {
4116     // FIXME: Cleanup.
4117     assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
4118     llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
4119     Address Tmp = CGF.CreateMemTemp(Ty);
4120     Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
4121     assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
4122     llvm::Type *TyLo = ST->getElementType(0);
4123     llvm::Type *TyHi = ST->getElementType(1);
4124     assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
4125            "Unexpected ABI info for mixed regs");
4126     llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
4127     llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
4128     llvm::Value *GPAddr =
4129         CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, gp_offset);
4130     llvm::Value *FPAddr =
4131         CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, fp_offset);
4132     llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr;
4133     llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr;
4134 
4135     // Copy the first element.
4136     // FIXME: Our choice of alignment here and below is probably pessimistic.
4137     llvm::Value *V = CGF.Builder.CreateAlignedLoad(
4138         TyLo, CGF.Builder.CreateBitCast(RegLoAddr, PTyLo),
4139         CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyLo)));
4140     CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
4141 
4142     // Copy the second element.
4143     V = CGF.Builder.CreateAlignedLoad(
4144         TyHi, CGF.Builder.CreateBitCast(RegHiAddr, PTyHi),
4145         CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyHi)));
4146     CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
4147 
4148     RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
4149   } else if (neededInt) {
4150     RegAddr = Address(CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, gp_offset),
4151                       CGF.Int8Ty, CharUnits::fromQuantity(8));
4152     RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
4153 
4154     // Copy to a temporary if necessary to ensure the appropriate alignment.
4155     auto TInfo = getContext().getTypeInfoInChars(Ty);
4156     uint64_t TySize = TInfo.Width.getQuantity();
4157     CharUnits TyAlign = TInfo.Align;
4158 
4159     // Copy into a temporary if the type is more aligned than the
4160     // register save area.
4161     if (TyAlign.getQuantity() > 8) {
4162       Address Tmp = CGF.CreateMemTemp(Ty);
4163       CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, false);
4164       RegAddr = Tmp;
4165     }
4166 
4167   } else if (neededSSE == 1) {
4168     RegAddr = Address(CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, fp_offset),
4169                       CGF.Int8Ty, CharUnits::fromQuantity(16));
4170     RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
4171   } else {
4172     assert(neededSSE == 2 && "Invalid number of needed registers!");
4173     // SSE registers are spaced 16 bytes apart in the register save
4174     // area, we need to collect the two eightbytes together.
4175     // The ABI isn't explicit about this, but it seems reasonable
4176     // to assume that the slots are 16-byte aligned, since the stack is
4177     // naturally 16-byte aligned and the prologue is expected to store
4178     // all the SSE registers to the RSA.
4179     Address RegAddrLo = Address(CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea,
4180                                                       fp_offset),
4181                                 CGF.Int8Ty, CharUnits::fromQuantity(16));
4182     Address RegAddrHi =
4183       CGF.Builder.CreateConstInBoundsByteGEP(RegAddrLo,
4184                                              CharUnits::fromQuantity(16));
4185     llvm::Type *ST = AI.canHaveCoerceToType()
4186                          ? AI.getCoerceToType()
4187                          : llvm::StructType::get(CGF.DoubleTy, CGF.DoubleTy);
4188     llvm::Value *V;
4189     Address Tmp = CGF.CreateMemTemp(Ty);
4190     Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
4191     V = CGF.Builder.CreateLoad(CGF.Builder.CreateElementBitCast(
4192         RegAddrLo, ST->getStructElementType(0)));
4193     CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
4194     V = CGF.Builder.CreateLoad(CGF.Builder.CreateElementBitCast(
4195         RegAddrHi, ST->getStructElementType(1)));
4196     CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
4197 
4198     RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
4199   }
4200 
4201   // AMD64-ABI 3.5.7p5: Step 5. Set:
4202   // l->gp_offset = l->gp_offset + num_gp * 8
4203   // l->fp_offset = l->fp_offset + num_fp * 16.
4204   if (neededInt) {
4205     llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
4206     CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
4207                             gp_offset_p);
4208   }
4209   if (neededSSE) {
4210     llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
4211     CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
4212                             fp_offset_p);
4213   }
4214   CGF.EmitBranch(ContBlock);
4215 
4216   // Emit code to load the value if it was passed in memory.
4217 
4218   CGF.EmitBlock(InMemBlock);
4219   Address MemAddr = EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
4220 
4221   // Return the appropriate result.
4222 
4223   CGF.EmitBlock(ContBlock);
4224   Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, MemAddr, InMemBlock,
4225                                  "vaarg.addr");
4226   return ResAddr;
4227 }
4228 
4229 Address X86_64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
4230                                    QualType Ty) const {
4231   // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
4232   // not 1, 2, 4, or 8 bytes, must be passed by reference."
4233   uint64_t Width = getContext().getTypeSize(Ty);
4234   bool IsIndirect = Width > 64 || !llvm::isPowerOf2_64(Width);
4235 
4236   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
4237                           CGF.getContext().getTypeInfoInChars(Ty),
4238                           CharUnits::fromQuantity(8),
4239                           /*allowHigherAlign*/ false);
4240 }
4241 
4242 ABIArgInfo WinX86_64ABIInfo::reclassifyHvaArgForVectorCall(
4243     QualType Ty, unsigned &FreeSSERegs, const ABIArgInfo &current) const {
4244   const Type *Base = nullptr;
4245   uint64_t NumElts = 0;
4246 
4247   if (!Ty->isBuiltinType() && !Ty->isVectorType() &&
4248       isHomogeneousAggregate(Ty, Base, NumElts) && FreeSSERegs >= NumElts) {
4249     FreeSSERegs -= NumElts;
4250     return getDirectX86Hva();
4251   }
4252   return current;
4253 }
4254 
4255 ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, unsigned &FreeSSERegs,
4256                                       bool IsReturnType, bool IsVectorCall,
4257                                       bool IsRegCall) const {
4258 
4259   if (Ty->isVoidType())
4260     return ABIArgInfo::getIgnore();
4261 
4262   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4263     Ty = EnumTy->getDecl()->getIntegerType();
4264 
4265   TypeInfo Info = getContext().getTypeInfo(Ty);
4266   uint64_t Width = Info.Width;
4267   CharUnits Align = getContext().toCharUnitsFromBits(Info.Align);
4268 
4269   const RecordType *RT = Ty->getAs<RecordType>();
4270   if (RT) {
4271     if (!IsReturnType) {
4272       if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
4273         return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
4274     }
4275 
4276     if (RT->getDecl()->hasFlexibleArrayMember())
4277       return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
4278 
4279   }
4280 
4281   const Type *Base = nullptr;
4282   uint64_t NumElts = 0;
4283   // vectorcall adds the concept of a homogenous vector aggregate, similar to
4284   // other targets.
4285   if ((IsVectorCall || IsRegCall) &&
4286       isHomogeneousAggregate(Ty, Base, NumElts)) {
4287     if (IsRegCall) {
4288       if (FreeSSERegs >= NumElts) {
4289         FreeSSERegs -= NumElts;
4290         if (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())
4291           return ABIArgInfo::getDirect();
4292         return ABIArgInfo::getExpand();
4293       }
4294       return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
4295     } else if (IsVectorCall) {
4296       if (FreeSSERegs >= NumElts &&
4297           (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())) {
4298         FreeSSERegs -= NumElts;
4299         return ABIArgInfo::getDirect();
4300       } else if (IsReturnType) {
4301         return ABIArgInfo::getExpand();
4302       } else if (!Ty->isBuiltinType() && !Ty->isVectorType()) {
4303         // HVAs are delayed and reclassified in the 2nd step.
4304         return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
4305       }
4306     }
4307   }
4308 
4309   if (Ty->isMemberPointerType()) {
4310     // If the member pointer is represented by an LLVM int or ptr, pass it
4311     // directly.
4312     llvm::Type *LLTy = CGT.ConvertType(Ty);
4313     if (LLTy->isPointerTy() || LLTy->isIntegerTy())
4314       return ABIArgInfo::getDirect();
4315   }
4316 
4317   if (RT || Ty->isAnyComplexType() || Ty->isMemberPointerType()) {
4318     // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
4319     // not 1, 2, 4, or 8 bytes, must be passed by reference."
4320     if (Width > 64 || !llvm::isPowerOf2_64(Width))
4321       return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
4322 
4323     // Otherwise, coerce it to a small integer.
4324     return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Width));
4325   }
4326 
4327   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4328     switch (BT->getKind()) {
4329     case BuiltinType::Bool:
4330       // Bool type is always extended to the ABI, other builtin types are not
4331       // extended.
4332       return ABIArgInfo::getExtend(Ty);
4333 
4334     case BuiltinType::LongDouble:
4335       // Mingw64 GCC uses the old 80 bit extended precision floating point
4336       // unit. It passes them indirectly through memory.
4337       if (IsMingw64) {
4338         const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
4339         if (LDF == &llvm::APFloat::x87DoubleExtended())
4340           return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
4341       }
4342       break;
4343 
4344     case BuiltinType::Int128:
4345     case BuiltinType::UInt128:
4346       // If it's a parameter type, the normal ABI rule is that arguments larger
4347       // than 8 bytes are passed indirectly. GCC follows it. We follow it too,
4348       // even though it isn't particularly efficient.
4349       if (!IsReturnType)
4350         return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
4351 
4352       // Mingw64 GCC returns i128 in XMM0. Coerce to v2i64 to handle that.
4353       // Clang matches them for compatibility.
4354       return ABIArgInfo::getDirect(llvm::FixedVectorType::get(
4355           llvm::Type::getInt64Ty(getVMContext()), 2));
4356 
4357     default:
4358       break;
4359     }
4360   }
4361 
4362   if (Ty->isBitIntType()) {
4363     // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
4364     // not 1, 2, 4, or 8 bytes, must be passed by reference."
4365     // However, non-power-of-two bit-precise integers will be passed as 1, 2, 4,
4366     // or 8 bytes anyway as long is it fits in them, so we don't have to check
4367     // the power of 2.
4368     if (Width <= 64)
4369       return ABIArgInfo::getDirect();
4370     return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
4371   }
4372 
4373   return ABIArgInfo::getDirect();
4374 }
4375 
4376 void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
4377   const unsigned CC = FI.getCallingConvention();
4378   bool IsVectorCall = CC == llvm::CallingConv::X86_VectorCall;
4379   bool IsRegCall = CC == llvm::CallingConv::X86_RegCall;
4380 
4381   // If __attribute__((sysv_abi)) is in use, use the SysV argument
4382   // classification rules.
4383   if (CC == llvm::CallingConv::X86_64_SysV) {
4384     X86_64ABIInfo SysVABIInfo(CGT, AVXLevel);
4385     SysVABIInfo.computeInfo(FI);
4386     return;
4387   }
4388 
4389   unsigned FreeSSERegs = 0;
4390   if (IsVectorCall) {
4391     // We can use up to 4 SSE return registers with vectorcall.
4392     FreeSSERegs = 4;
4393   } else if (IsRegCall) {
4394     // RegCall gives us 16 SSE registers.
4395     FreeSSERegs = 16;
4396   }
4397 
4398   if (!getCXXABI().classifyReturnType(FI))
4399     FI.getReturnInfo() = classify(FI.getReturnType(), FreeSSERegs, true,
4400                                   IsVectorCall, IsRegCall);
4401 
4402   if (IsVectorCall) {
4403     // We can use up to 6 SSE register parameters with vectorcall.
4404     FreeSSERegs = 6;
4405   } else if (IsRegCall) {
4406     // RegCall gives us 16 SSE registers, we can reuse the return registers.
4407     FreeSSERegs = 16;
4408   }
4409 
4410   unsigned ArgNum = 0;
4411   unsigned ZeroSSERegs = 0;
4412   for (auto &I : FI.arguments()) {
4413     // Vectorcall in x64 only permits the first 6 arguments to be passed as
4414     // XMM/YMM registers. After the sixth argument, pretend no vector
4415     // registers are left.
4416     unsigned *MaybeFreeSSERegs =
4417         (IsVectorCall && ArgNum >= 6) ? &ZeroSSERegs : &FreeSSERegs;
4418     I.info =
4419         classify(I.type, *MaybeFreeSSERegs, false, IsVectorCall, IsRegCall);
4420     ++ArgNum;
4421   }
4422 
4423   if (IsVectorCall) {
4424     // For vectorcall, assign aggregate HVAs to any free vector registers in a
4425     // second pass.
4426     for (auto &I : FI.arguments())
4427       I.info = reclassifyHvaArgForVectorCall(I.type, FreeSSERegs, I.info);
4428   }
4429 }
4430 
4431 Address WinX86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4432                                     QualType Ty) const {
4433   // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
4434   // not 1, 2, 4, or 8 bytes, must be passed by reference."
4435   uint64_t Width = getContext().getTypeSize(Ty);
4436   bool IsIndirect = Width > 64 || !llvm::isPowerOf2_64(Width);
4437 
4438   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
4439                           CGF.getContext().getTypeInfoInChars(Ty),
4440                           CharUnits::fromQuantity(8),
4441                           /*allowHigherAlign*/ false);
4442 }
4443 
4444 static bool PPC_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4445                                         llvm::Value *Address, bool Is64Bit,
4446                                         bool IsAIX) {
4447   // This is calculated from the LLVM and GCC tables and verified
4448   // against gcc output.  AFAIK all PPC ABIs use the same encoding.
4449 
4450   CodeGen::CGBuilderTy &Builder = CGF.Builder;
4451 
4452   llvm::IntegerType *i8 = CGF.Int8Ty;
4453   llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
4454   llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
4455   llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
4456 
4457   // 0-31: r0-31, the 4-byte or 8-byte general-purpose registers
4458   AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 0, 31);
4459 
4460   // 32-63: fp0-31, the 8-byte floating-point registers
4461   AssignToArrayRange(Builder, Address, Eight8, 32, 63);
4462 
4463   // 64-67 are various 4-byte or 8-byte special-purpose registers:
4464   // 64: mq
4465   // 65: lr
4466   // 66: ctr
4467   // 67: ap
4468   AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 64, 67);
4469 
4470   // 68-76 are various 4-byte special-purpose registers:
4471   // 68-75 cr0-7
4472   // 76: xer
4473   AssignToArrayRange(Builder, Address, Four8, 68, 76);
4474 
4475   // 77-108: v0-31, the 16-byte vector registers
4476   AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
4477 
4478   // 109: vrsave
4479   // 110: vscr
4480   AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 109, 110);
4481 
4482   // AIX does not utilize the rest of the registers.
4483   if (IsAIX)
4484     return false;
4485 
4486   // 111: spe_acc
4487   // 112: spefscr
4488   // 113: sfp
4489   AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 111, 113);
4490 
4491   if (!Is64Bit)
4492     return false;
4493 
4494   // TODO: Need to verify if these registers are used on 64 bit AIX with Power8
4495   // or above CPU.
4496   // 64-bit only registers:
4497   // 114: tfhar
4498   // 115: tfiar
4499   // 116: texasr
4500   AssignToArrayRange(Builder, Address, Eight8, 114, 116);
4501 
4502   return false;
4503 }
4504 
4505 // AIX
4506 namespace {
4507 /// AIXABIInfo - The AIX XCOFF ABI information.
4508 class AIXABIInfo : public ABIInfo {
4509   const bool Is64Bit;
4510   const unsigned PtrByteSize;
4511   CharUnits getParamTypeAlignment(QualType Ty) const;
4512 
4513 public:
4514   AIXABIInfo(CodeGen::CodeGenTypes &CGT, bool Is64Bit)
4515       : ABIInfo(CGT), Is64Bit(Is64Bit), PtrByteSize(Is64Bit ? 8 : 4) {}
4516 
4517   bool isPromotableTypeForABI(QualType Ty) const;
4518 
4519   ABIArgInfo classifyReturnType(QualType RetTy) const;
4520   ABIArgInfo classifyArgumentType(QualType Ty) const;
4521 
4522   void computeInfo(CGFunctionInfo &FI) const override {
4523     if (!getCXXABI().classifyReturnType(FI))
4524       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
4525 
4526     for (auto &I : FI.arguments())
4527       I.info = classifyArgumentType(I.type);
4528   }
4529 
4530   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4531                     QualType Ty) const override;
4532 };
4533 
4534 class AIXTargetCodeGenInfo : public TargetCodeGenInfo {
4535   const bool Is64Bit;
4536 
4537 public:
4538   AIXTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool Is64Bit)
4539       : TargetCodeGenInfo(std::make_unique<AIXABIInfo>(CGT, Is64Bit)),
4540         Is64Bit(Is64Bit) {}
4541   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4542     return 1; // r1 is the dedicated stack pointer
4543   }
4544 
4545   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4546                                llvm::Value *Address) const override;
4547 };
4548 } // namespace
4549 
4550 // Return true if the ABI requires Ty to be passed sign- or zero-
4551 // extended to 32/64 bits.
4552 bool AIXABIInfo::isPromotableTypeForABI(QualType Ty) const {
4553   // Treat an enum type as its underlying type.
4554   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4555     Ty = EnumTy->getDecl()->getIntegerType();
4556 
4557   // Promotable integer types are required to be promoted by the ABI.
4558   if (Ty->isPromotableIntegerType())
4559     return true;
4560 
4561   if (!Is64Bit)
4562     return false;
4563 
4564   // For 64 bit mode, in addition to the usual promotable integer types, we also
4565   // need to extend all 32-bit types, since the ABI requires promotion to 64
4566   // bits.
4567   if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
4568     switch (BT->getKind()) {
4569     case BuiltinType::Int:
4570     case BuiltinType::UInt:
4571       return true;
4572     default:
4573       break;
4574     }
4575 
4576   return false;
4577 }
4578 
4579 ABIArgInfo AIXABIInfo::classifyReturnType(QualType RetTy) const {
4580   if (RetTy->isAnyComplexType())
4581     return ABIArgInfo::getDirect();
4582 
4583   if (RetTy->isVectorType())
4584     return ABIArgInfo::getDirect();
4585 
4586   if (RetTy->isVoidType())
4587     return ABIArgInfo::getIgnore();
4588 
4589   if (isAggregateTypeForABI(RetTy))
4590     return getNaturalAlignIndirect(RetTy);
4591 
4592   return (isPromotableTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
4593                                         : ABIArgInfo::getDirect());
4594 }
4595 
4596 ABIArgInfo AIXABIInfo::classifyArgumentType(QualType Ty) const {
4597   Ty = useFirstFieldIfTransparentUnion(Ty);
4598 
4599   if (Ty->isAnyComplexType())
4600     return ABIArgInfo::getDirect();
4601 
4602   if (Ty->isVectorType())
4603     return ABIArgInfo::getDirect();
4604 
4605   if (isAggregateTypeForABI(Ty)) {
4606     // Records with non-trivial destructors/copy-constructors should not be
4607     // passed by value.
4608     if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
4609       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
4610 
4611     CharUnits CCAlign = getParamTypeAlignment(Ty);
4612     CharUnits TyAlign = getContext().getTypeAlignInChars(Ty);
4613 
4614     return ABIArgInfo::getIndirect(CCAlign, /*ByVal*/ true,
4615                                    /*Realign*/ TyAlign > CCAlign);
4616   }
4617 
4618   return (isPromotableTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
4619                                      : ABIArgInfo::getDirect());
4620 }
4621 
4622 CharUnits AIXABIInfo::getParamTypeAlignment(QualType Ty) const {
4623   // Complex types are passed just like their elements.
4624   if (const ComplexType *CTy = Ty->getAs<ComplexType>())
4625     Ty = CTy->getElementType();
4626 
4627   if (Ty->isVectorType())
4628     return CharUnits::fromQuantity(16);
4629 
4630   // If the structure contains a vector type, the alignment is 16.
4631   if (isRecordWithSIMDVectorType(getContext(), Ty))
4632     return CharUnits::fromQuantity(16);
4633 
4634   return CharUnits::fromQuantity(PtrByteSize);
4635 }
4636 
4637 Address AIXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4638                               QualType Ty) const {
4639 
4640   auto TypeInfo = getContext().getTypeInfoInChars(Ty);
4641   TypeInfo.Align = getParamTypeAlignment(Ty);
4642 
4643   CharUnits SlotSize = CharUnits::fromQuantity(PtrByteSize);
4644 
4645   // If we have a complex type and the base type is smaller than the register
4646   // size, the ABI calls for the real and imaginary parts to be right-adjusted
4647   // in separate words in 32bit mode or doublewords in 64bit mode. However,
4648   // Clang expects us to produce a pointer to a structure with the two parts
4649   // packed tightly. So generate loads of the real and imaginary parts relative
4650   // to the va_list pointer, and store them to a temporary structure. We do the
4651   // same as the PPC64ABI here.
4652   if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
4653     CharUnits EltSize = TypeInfo.Width / 2;
4654     if (EltSize < SlotSize)
4655       return complexTempStructure(CGF, VAListAddr, Ty, SlotSize, EltSize, CTy);
4656   }
4657 
4658   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false, TypeInfo,
4659                           SlotSize, /*AllowHigher*/ true);
4660 }
4661 
4662 bool AIXTargetCodeGenInfo::initDwarfEHRegSizeTable(
4663     CodeGen::CodeGenFunction &CGF, llvm::Value *Address) const {
4664   return PPC_initDwarfEHRegSizeTable(CGF, Address, Is64Bit, /*IsAIX*/ true);
4665 }
4666 
4667 // PowerPC-32
4668 namespace {
4669 /// PPC32_SVR4_ABIInfo - The 32-bit PowerPC ELF (SVR4) ABI information.
4670 class PPC32_SVR4_ABIInfo : public DefaultABIInfo {
4671   bool IsSoftFloatABI;
4672   bool IsRetSmallStructInRegABI;
4673 
4674   CharUnits getParamTypeAlignment(QualType Ty) const;
4675 
4676 public:
4677   PPC32_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, bool SoftFloatABI,
4678                      bool RetSmallStructInRegABI)
4679       : DefaultABIInfo(CGT), IsSoftFloatABI(SoftFloatABI),
4680         IsRetSmallStructInRegABI(RetSmallStructInRegABI) {}
4681 
4682   ABIArgInfo classifyReturnType(QualType RetTy) const;
4683 
4684   void computeInfo(CGFunctionInfo &FI) const override {
4685     if (!getCXXABI().classifyReturnType(FI))
4686       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
4687     for (auto &I : FI.arguments())
4688       I.info = classifyArgumentType(I.type);
4689   }
4690 
4691   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4692                     QualType Ty) const override;
4693 };
4694 
4695 class PPC32TargetCodeGenInfo : public TargetCodeGenInfo {
4696 public:
4697   PPC32TargetCodeGenInfo(CodeGenTypes &CGT, bool SoftFloatABI,
4698                          bool RetSmallStructInRegABI)
4699       : TargetCodeGenInfo(std::make_unique<PPC32_SVR4_ABIInfo>(
4700             CGT, SoftFloatABI, RetSmallStructInRegABI)) {}
4701 
4702   static bool isStructReturnInRegABI(const llvm::Triple &Triple,
4703                                      const CodeGenOptions &Opts);
4704 
4705   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4706     // This is recovered from gcc output.
4707     return 1; // r1 is the dedicated stack pointer
4708   }
4709 
4710   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4711                                llvm::Value *Address) const override;
4712 };
4713 }
4714 
4715 CharUnits PPC32_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const {
4716   // Complex types are passed just like their elements.
4717   if (const ComplexType *CTy = Ty->getAs<ComplexType>())
4718     Ty = CTy->getElementType();
4719 
4720   if (Ty->isVectorType())
4721     return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16
4722                                                                        : 4);
4723 
4724   // For single-element float/vector structs, we consider the whole type
4725   // to have the same alignment requirements as its single element.
4726   const Type *AlignTy = nullptr;
4727   if (const Type *EltType = isSingleElementStruct(Ty, getContext())) {
4728     const BuiltinType *BT = EltType->getAs<BuiltinType>();
4729     if ((EltType->isVectorType() && getContext().getTypeSize(EltType) == 128) ||
4730         (BT && BT->isFloatingPoint()))
4731       AlignTy = EltType;
4732   }
4733 
4734   if (AlignTy)
4735     return CharUnits::fromQuantity(AlignTy->isVectorType() ? 16 : 4);
4736   return CharUnits::fromQuantity(4);
4737 }
4738 
4739 ABIArgInfo PPC32_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
4740   uint64_t Size;
4741 
4742   // -msvr4-struct-return puts small aggregates in GPR3 and GPR4.
4743   if (isAggregateTypeForABI(RetTy) && IsRetSmallStructInRegABI &&
4744       (Size = getContext().getTypeSize(RetTy)) <= 64) {
4745     // System V ABI (1995), page 3-22, specified:
4746     // > A structure or union whose size is less than or equal to 8 bytes
4747     // > shall be returned in r3 and r4, as if it were first stored in the
4748     // > 8-byte aligned memory area and then the low addressed word were
4749     // > loaded into r3 and the high-addressed word into r4.  Bits beyond
4750     // > the last member of the structure or union are not defined.
4751     //
4752     // GCC for big-endian PPC32 inserts the pad before the first member,
4753     // not "beyond the last member" of the struct.  To stay compatible
4754     // with GCC, we coerce the struct to an integer of the same size.
4755     // LLVM will extend it and return i32 in r3, or i64 in r3:r4.
4756     if (Size == 0)
4757       return ABIArgInfo::getIgnore();
4758     else {
4759       llvm::Type *CoerceTy = llvm::Type::getIntNTy(getVMContext(), Size);
4760       return ABIArgInfo::getDirect(CoerceTy);
4761     }
4762   }
4763 
4764   return DefaultABIInfo::classifyReturnType(RetTy);
4765 }
4766 
4767 // TODO: this implementation is now likely redundant with
4768 // DefaultABIInfo::EmitVAArg.
4769 Address PPC32_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAList,
4770                                       QualType Ty) const {
4771   if (getTarget().getTriple().isOSDarwin()) {
4772     auto TI = getContext().getTypeInfoInChars(Ty);
4773     TI.Align = getParamTypeAlignment(Ty);
4774 
4775     CharUnits SlotSize = CharUnits::fromQuantity(4);
4776     return emitVoidPtrVAArg(CGF, VAList, Ty,
4777                             classifyArgumentType(Ty).isIndirect(), TI, SlotSize,
4778                             /*AllowHigherAlign=*/true);
4779   }
4780 
4781   const unsigned OverflowLimit = 8;
4782   if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
4783     // TODO: Implement this. For now ignore.
4784     (void)CTy;
4785     return Address::invalid(); // FIXME?
4786   }
4787 
4788   // struct __va_list_tag {
4789   //   unsigned char gpr;
4790   //   unsigned char fpr;
4791   //   unsigned short reserved;
4792   //   void *overflow_arg_area;
4793   //   void *reg_save_area;
4794   // };
4795 
4796   bool isI64 = Ty->isIntegerType() && getContext().getTypeSize(Ty) == 64;
4797   bool isInt = !Ty->isFloatingType();
4798   bool isF64 = Ty->isFloatingType() && getContext().getTypeSize(Ty) == 64;
4799 
4800   // All aggregates are passed indirectly?  That doesn't seem consistent
4801   // with the argument-lowering code.
4802   bool isIndirect = isAggregateTypeForABI(Ty);
4803 
4804   CGBuilderTy &Builder = CGF.Builder;
4805 
4806   // The calling convention either uses 1-2 GPRs or 1 FPR.
4807   Address NumRegsAddr = Address::invalid();
4808   if (isInt || IsSoftFloatABI) {
4809     NumRegsAddr = Builder.CreateStructGEP(VAList, 0, "gpr");
4810   } else {
4811     NumRegsAddr = Builder.CreateStructGEP(VAList, 1, "fpr");
4812   }
4813 
4814   llvm::Value *NumRegs = Builder.CreateLoad(NumRegsAddr, "numUsedRegs");
4815 
4816   // "Align" the register count when TY is i64.
4817   if (isI64 || (isF64 && IsSoftFloatABI)) {
4818     NumRegs = Builder.CreateAdd(NumRegs, Builder.getInt8(1));
4819     NumRegs = Builder.CreateAnd(NumRegs, Builder.getInt8((uint8_t) ~1U));
4820   }
4821 
4822   llvm::Value *CC =
4823       Builder.CreateICmpULT(NumRegs, Builder.getInt8(OverflowLimit), "cond");
4824 
4825   llvm::BasicBlock *UsingRegs = CGF.createBasicBlock("using_regs");
4826   llvm::BasicBlock *UsingOverflow = CGF.createBasicBlock("using_overflow");
4827   llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
4828 
4829   Builder.CreateCondBr(CC, UsingRegs, UsingOverflow);
4830 
4831   llvm::Type *DirectTy = CGF.ConvertType(Ty);
4832   if (isIndirect) DirectTy = DirectTy->getPointerTo(0);
4833 
4834   // Case 1: consume registers.
4835   Address RegAddr = Address::invalid();
4836   {
4837     CGF.EmitBlock(UsingRegs);
4838 
4839     Address RegSaveAreaPtr = Builder.CreateStructGEP(VAList, 4);
4840     RegAddr = Address(Builder.CreateLoad(RegSaveAreaPtr),
4841                       CharUnits::fromQuantity(8));
4842     assert(RegAddr.getElementType() == CGF.Int8Ty);
4843 
4844     // Floating-point registers start after the general-purpose registers.
4845     if (!(isInt || IsSoftFloatABI)) {
4846       RegAddr = Builder.CreateConstInBoundsByteGEP(RegAddr,
4847                                                    CharUnits::fromQuantity(32));
4848     }
4849 
4850     // Get the address of the saved value by scaling the number of
4851     // registers we've used by the number of
4852     CharUnits RegSize = CharUnits::fromQuantity((isInt || IsSoftFloatABI) ? 4 : 8);
4853     llvm::Value *RegOffset =
4854       Builder.CreateMul(NumRegs, Builder.getInt8(RegSize.getQuantity()));
4855     RegAddr = Address(Builder.CreateInBoundsGEP(CGF.Int8Ty,
4856                                             RegAddr.getPointer(), RegOffset),
4857                       RegAddr.getAlignment().alignmentOfArrayElement(RegSize));
4858     RegAddr = Builder.CreateElementBitCast(RegAddr, DirectTy);
4859 
4860     // Increase the used-register count.
4861     NumRegs =
4862       Builder.CreateAdd(NumRegs,
4863                         Builder.getInt8((isI64 || (isF64 && IsSoftFloatABI)) ? 2 : 1));
4864     Builder.CreateStore(NumRegs, NumRegsAddr);
4865 
4866     CGF.EmitBranch(Cont);
4867   }
4868 
4869   // Case 2: consume space in the overflow area.
4870   Address MemAddr = Address::invalid();
4871   {
4872     CGF.EmitBlock(UsingOverflow);
4873 
4874     Builder.CreateStore(Builder.getInt8(OverflowLimit), NumRegsAddr);
4875 
4876     // Everything in the overflow area is rounded up to a size of at least 4.
4877     CharUnits OverflowAreaAlign = CharUnits::fromQuantity(4);
4878 
4879     CharUnits Size;
4880     if (!isIndirect) {
4881       auto TypeInfo = CGF.getContext().getTypeInfoInChars(Ty);
4882       Size = TypeInfo.Width.alignTo(OverflowAreaAlign);
4883     } else {
4884       Size = CGF.getPointerSize();
4885     }
4886 
4887     Address OverflowAreaAddr = Builder.CreateStructGEP(VAList, 3);
4888     Address OverflowArea(Builder.CreateLoad(OverflowAreaAddr, "argp.cur"),
4889                          OverflowAreaAlign);
4890     // Round up address of argument to alignment
4891     CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
4892     if (Align > OverflowAreaAlign) {
4893       llvm::Value *Ptr = OverflowArea.getPointer();
4894       OverflowArea = Address(emitRoundPointerUpToAlignment(CGF, Ptr, Align),
4895                                                            Align);
4896     }
4897 
4898     MemAddr = Builder.CreateElementBitCast(OverflowArea, DirectTy);
4899 
4900     // Increase the overflow area.
4901     OverflowArea = Builder.CreateConstInBoundsByteGEP(OverflowArea, Size);
4902     Builder.CreateStore(OverflowArea.getPointer(), OverflowAreaAddr);
4903     CGF.EmitBranch(Cont);
4904   }
4905 
4906   CGF.EmitBlock(Cont);
4907 
4908   // Merge the cases with a phi.
4909   Address Result = emitMergePHI(CGF, RegAddr, UsingRegs, MemAddr, UsingOverflow,
4910                                 "vaarg.addr");
4911 
4912   // Load the pointer if the argument was passed indirectly.
4913   if (isIndirect) {
4914     Result = Address(Builder.CreateLoad(Result, "aggr"),
4915                      getContext().getTypeAlignInChars(Ty));
4916   }
4917 
4918   return Result;
4919 }
4920 
4921 bool PPC32TargetCodeGenInfo::isStructReturnInRegABI(
4922     const llvm::Triple &Triple, const CodeGenOptions &Opts) {
4923   assert(Triple.isPPC32());
4924 
4925   switch (Opts.getStructReturnConvention()) {
4926   case CodeGenOptions::SRCK_Default:
4927     break;
4928   case CodeGenOptions::SRCK_OnStack: // -maix-struct-return
4929     return false;
4930   case CodeGenOptions::SRCK_InRegs: // -msvr4-struct-return
4931     return true;
4932   }
4933 
4934   if (Triple.isOSBinFormatELF() && !Triple.isOSLinux())
4935     return true;
4936 
4937   return false;
4938 }
4939 
4940 bool
4941 PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4942                                                 llvm::Value *Address) const {
4943   return PPC_initDwarfEHRegSizeTable(CGF, Address, /*Is64Bit*/ false,
4944                                      /*IsAIX*/ false);
4945 }
4946 
4947 // PowerPC-64
4948 
4949 namespace {
4950 /// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
4951 class PPC64_SVR4_ABIInfo : public SwiftABIInfo {
4952 public:
4953   enum ABIKind {
4954     ELFv1 = 0,
4955     ELFv2
4956   };
4957 
4958 private:
4959   static const unsigned GPRBits = 64;
4960   ABIKind Kind;
4961   bool IsSoftFloatABI;
4962 
4963 public:
4964   PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind,
4965                      bool SoftFloatABI)
4966       : SwiftABIInfo(CGT), Kind(Kind), IsSoftFloatABI(SoftFloatABI) {}
4967 
4968   bool isPromotableTypeForABI(QualType Ty) const;
4969   CharUnits getParamTypeAlignment(QualType Ty) const;
4970 
4971   ABIArgInfo classifyReturnType(QualType RetTy) const;
4972   ABIArgInfo classifyArgumentType(QualType Ty) const;
4973 
4974   bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4975   bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4976                                          uint64_t Members) const override;
4977 
4978   // TODO: We can add more logic to computeInfo to improve performance.
4979   // Example: For aggregate arguments that fit in a register, we could
4980   // use getDirectInReg (as is done below for structs containing a single
4981   // floating-point value) to avoid pushing them to memory on function
4982   // entry.  This would require changing the logic in PPCISelLowering
4983   // when lowering the parameters in the caller and args in the callee.
4984   void computeInfo(CGFunctionInfo &FI) const override {
4985     if (!getCXXABI().classifyReturnType(FI))
4986       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
4987     for (auto &I : FI.arguments()) {
4988       // We rely on the default argument classification for the most part.
4989       // One exception:  An aggregate containing a single floating-point
4990       // or vector item must be passed in a register if one is available.
4991       const Type *T = isSingleElementStruct(I.type, getContext());
4992       if (T) {
4993         const BuiltinType *BT = T->getAs<BuiltinType>();
4994         if ((T->isVectorType() && getContext().getTypeSize(T) == 128) ||
4995             (BT && BT->isFloatingPoint())) {
4996           QualType QT(T, 0);
4997           I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
4998           continue;
4999         }
5000       }
5001       I.info = classifyArgumentType(I.type);
5002     }
5003   }
5004 
5005   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5006                     QualType Ty) const override;
5007 
5008   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
5009                                     bool asReturnValue) const override {
5010     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
5011   }
5012 
5013   bool isSwiftErrorInRegister() const override {
5014     return false;
5015   }
5016 };
5017 
5018 class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
5019 
5020 public:
5021   PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT,
5022                                PPC64_SVR4_ABIInfo::ABIKind Kind,
5023                                bool SoftFloatABI)
5024       : TargetCodeGenInfo(
5025             std::make_unique<PPC64_SVR4_ABIInfo>(CGT, Kind, SoftFloatABI)) {}
5026 
5027   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
5028     // This is recovered from gcc output.
5029     return 1; // r1 is the dedicated stack pointer
5030   }
5031 
5032   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
5033                                llvm::Value *Address) const override;
5034 };
5035 
5036 class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
5037 public:
5038   PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
5039 
5040   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
5041     // This is recovered from gcc output.
5042     return 1; // r1 is the dedicated stack pointer
5043   }
5044 
5045   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
5046                                llvm::Value *Address) const override;
5047 };
5048 
5049 }
5050 
5051 // Return true if the ABI requires Ty to be passed sign- or zero-
5052 // extended to 64 bits.
5053 bool
5054 PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
5055   // Treat an enum type as its underlying type.
5056   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5057     Ty = EnumTy->getDecl()->getIntegerType();
5058 
5059   // Promotable integer types are required to be promoted by the ABI.
5060   if (isPromotableIntegerTypeForABI(Ty))
5061     return true;
5062 
5063   // In addition to the usual promotable integer types, we also need to
5064   // extend all 32-bit types, since the ABI requires promotion to 64 bits.
5065   if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
5066     switch (BT->getKind()) {
5067     case BuiltinType::Int:
5068     case BuiltinType::UInt:
5069       return true;
5070     default:
5071       break;
5072     }
5073 
5074   if (const auto *EIT = Ty->getAs<BitIntType>())
5075     if (EIT->getNumBits() < 64)
5076       return true;
5077 
5078   return false;
5079 }
5080 
5081 /// isAlignedParamType - Determine whether a type requires 16-byte or
5082 /// higher alignment in the parameter area.  Always returns at least 8.
5083 CharUnits PPC64_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const {
5084   // Complex types are passed just like their elements.
5085   if (const ComplexType *CTy = Ty->getAs<ComplexType>())
5086     Ty = CTy->getElementType();
5087 
5088   auto FloatUsesVector = [this](QualType Ty){
5089     return Ty->isRealFloatingType() && &getContext().getFloatTypeSemantics(
5090                                            Ty) == &llvm::APFloat::IEEEquad();
5091   };
5092 
5093   // Only vector types of size 16 bytes need alignment (larger types are
5094   // passed via reference, smaller types are not aligned).
5095   if (Ty->isVectorType()) {
5096     return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16 : 8);
5097   } else if (FloatUsesVector(Ty)) {
5098     // According to ABI document section 'Optional Save Areas': If extended
5099     // precision floating-point values in IEEE BINARY 128 QUADRUPLE PRECISION
5100     // format are supported, map them to a single quadword, quadword aligned.
5101     return CharUnits::fromQuantity(16);
5102   }
5103 
5104   // For single-element float/vector structs, we consider the whole type
5105   // to have the same alignment requirements as its single element.
5106   const Type *AlignAsType = nullptr;
5107   const Type *EltType = isSingleElementStruct(Ty, getContext());
5108   if (EltType) {
5109     const BuiltinType *BT = EltType->getAs<BuiltinType>();
5110     if ((EltType->isVectorType() && getContext().getTypeSize(EltType) == 128) ||
5111         (BT && BT->isFloatingPoint()))
5112       AlignAsType = EltType;
5113   }
5114 
5115   // Likewise for ELFv2 homogeneous aggregates.
5116   const Type *Base = nullptr;
5117   uint64_t Members = 0;
5118   if (!AlignAsType && Kind == ELFv2 &&
5119       isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members))
5120     AlignAsType = Base;
5121 
5122   // With special case aggregates, only vector base types need alignment.
5123   if (AlignAsType) {
5124     bool UsesVector = AlignAsType->isVectorType() ||
5125                       FloatUsesVector(QualType(AlignAsType, 0));
5126     return CharUnits::fromQuantity(UsesVector ? 16 : 8);
5127   }
5128 
5129   // Otherwise, we only need alignment for any aggregate type that
5130   // has an alignment requirement of >= 16 bytes.
5131   if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128) {
5132     return CharUnits::fromQuantity(16);
5133   }
5134 
5135   return CharUnits::fromQuantity(8);
5136 }
5137 
5138 /// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous
5139 /// aggregate.  Base is set to the base element type, and Members is set
5140 /// to the number of base elements.
5141 bool ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base,
5142                                      uint64_t &Members) const {
5143   if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
5144     uint64_t NElements = AT->getSize().getZExtValue();
5145     if (NElements == 0)
5146       return false;
5147     if (!isHomogeneousAggregate(AT->getElementType(), Base, Members))
5148       return false;
5149     Members *= NElements;
5150   } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
5151     const RecordDecl *RD = RT->getDecl();
5152     if (RD->hasFlexibleArrayMember())
5153       return false;
5154 
5155     Members = 0;
5156 
5157     // If this is a C++ record, check the properties of the record such as
5158     // bases and ABI specific restrictions
5159     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
5160       if (!getCXXABI().isPermittedToBeHomogeneousAggregate(CXXRD))
5161         return false;
5162 
5163       for (const auto &I : CXXRD->bases()) {
5164         // Ignore empty records.
5165         if (isEmptyRecord(getContext(), I.getType(), true))
5166           continue;
5167 
5168         uint64_t FldMembers;
5169         if (!isHomogeneousAggregate(I.getType(), Base, FldMembers))
5170           return false;
5171 
5172         Members += FldMembers;
5173       }
5174     }
5175 
5176     for (const auto *FD : RD->fields()) {
5177       // Ignore (non-zero arrays of) empty records.
5178       QualType FT = FD->getType();
5179       while (const ConstantArrayType *AT =
5180              getContext().getAsConstantArrayType(FT)) {
5181         if (AT->getSize().getZExtValue() == 0)
5182           return false;
5183         FT = AT->getElementType();
5184       }
5185       if (isEmptyRecord(getContext(), FT, true))
5186         continue;
5187 
5188       // For compatibility with GCC, ignore empty bitfields in C++ mode.
5189       if (getContext().getLangOpts().CPlusPlus &&
5190           FD->isZeroLengthBitField(getContext()))
5191         continue;
5192 
5193       uint64_t FldMembers;
5194       if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers))
5195         return false;
5196 
5197       Members = (RD->isUnion() ?
5198                  std::max(Members, FldMembers) : Members + FldMembers);
5199     }
5200 
5201     if (!Base)
5202       return false;
5203 
5204     // Ensure there is no padding.
5205     if (getContext().getTypeSize(Base) * Members !=
5206         getContext().getTypeSize(Ty))
5207       return false;
5208   } else {
5209     Members = 1;
5210     if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
5211       Members = 2;
5212       Ty = CT->getElementType();
5213     }
5214 
5215     // Most ABIs only support float, double, and some vector type widths.
5216     if (!isHomogeneousAggregateBaseType(Ty))
5217       return false;
5218 
5219     // The base type must be the same for all members.  Types that
5220     // agree in both total size and mode (float vs. vector) are
5221     // treated as being equivalent here.
5222     const Type *TyPtr = Ty.getTypePtr();
5223     if (!Base) {
5224       Base = TyPtr;
5225       // If it's a non-power-of-2 vector, its size is already a power-of-2,
5226       // so make sure to widen it explicitly.
5227       if (const VectorType *VT = Base->getAs<VectorType>()) {
5228         QualType EltTy = VT->getElementType();
5229         unsigned NumElements =
5230             getContext().getTypeSize(VT) / getContext().getTypeSize(EltTy);
5231         Base = getContext()
5232                    .getVectorType(EltTy, NumElements, VT->getVectorKind())
5233                    .getTypePtr();
5234       }
5235     }
5236 
5237     if (Base->isVectorType() != TyPtr->isVectorType() ||
5238         getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr))
5239       return false;
5240   }
5241   return Members > 0 && isHomogeneousAggregateSmallEnough(Base, Members);
5242 }
5243 
5244 bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
5245   // Homogeneous aggregates for ELFv2 must have base types of float,
5246   // double, long double, or 128-bit vectors.
5247   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
5248     if (BT->getKind() == BuiltinType::Float ||
5249         BT->getKind() == BuiltinType::Double ||
5250         BT->getKind() == BuiltinType::LongDouble ||
5251         BT->getKind() == BuiltinType::Ibm128 ||
5252         (getContext().getTargetInfo().hasFloat128Type() &&
5253          (BT->getKind() == BuiltinType::Float128))) {
5254       if (IsSoftFloatABI)
5255         return false;
5256       return true;
5257     }
5258   }
5259   if (const VectorType *VT = Ty->getAs<VectorType>()) {
5260     if (getContext().getTypeSize(VT) == 128)
5261       return true;
5262   }
5263   return false;
5264 }
5265 
5266 bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateSmallEnough(
5267     const Type *Base, uint64_t Members) const {
5268   // Vector and fp128 types require one register, other floating point types
5269   // require one or two registers depending on their size.
5270   uint32_t NumRegs =
5271       ((getContext().getTargetInfo().hasFloat128Type() &&
5272           Base->isFloat128Type()) ||
5273         Base->isVectorType()) ? 1
5274                               : (getContext().getTypeSize(Base) + 63) / 64;
5275 
5276   // Homogeneous Aggregates may occupy at most 8 registers.
5277   return Members * NumRegs <= 8;
5278 }
5279 
5280 ABIArgInfo
5281 PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
5282   Ty = useFirstFieldIfTransparentUnion(Ty);
5283 
5284   if (Ty->isAnyComplexType())
5285     return ABIArgInfo::getDirect();
5286 
5287   // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes)
5288   // or via reference (larger than 16 bytes).
5289   if (Ty->isVectorType()) {
5290     uint64_t Size = getContext().getTypeSize(Ty);
5291     if (Size > 128)
5292       return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
5293     else if (Size < 128) {
5294       llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
5295       return ABIArgInfo::getDirect(CoerceTy);
5296     }
5297   }
5298 
5299   if (const auto *EIT = Ty->getAs<BitIntType>())
5300     if (EIT->getNumBits() > 128)
5301       return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
5302 
5303   if (isAggregateTypeForABI(Ty)) {
5304     if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
5305       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
5306 
5307     uint64_t ABIAlign = getParamTypeAlignment(Ty).getQuantity();
5308     uint64_t TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity();
5309 
5310     // ELFv2 homogeneous aggregates are passed as array types.
5311     const Type *Base = nullptr;
5312     uint64_t Members = 0;
5313     if (Kind == ELFv2 &&
5314         isHomogeneousAggregate(Ty, Base, Members)) {
5315       llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
5316       llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
5317       return ABIArgInfo::getDirect(CoerceTy);
5318     }
5319 
5320     // If an aggregate may end up fully in registers, we do not
5321     // use the ByVal method, but pass the aggregate as array.
5322     // This is usually beneficial since we avoid forcing the
5323     // back-end to store the argument to memory.
5324     uint64_t Bits = getContext().getTypeSize(Ty);
5325     if (Bits > 0 && Bits <= 8 * GPRBits) {
5326       llvm::Type *CoerceTy;
5327 
5328       // Types up to 8 bytes are passed as integer type (which will be
5329       // properly aligned in the argument save area doubleword).
5330       if (Bits <= GPRBits)
5331         CoerceTy =
5332             llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
5333       // Larger types are passed as arrays, with the base type selected
5334       // according to the required alignment in the save area.
5335       else {
5336         uint64_t RegBits = ABIAlign * 8;
5337         uint64_t NumRegs = llvm::alignTo(Bits, RegBits) / RegBits;
5338         llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits);
5339         CoerceTy = llvm::ArrayType::get(RegTy, NumRegs);
5340       }
5341 
5342       return ABIArgInfo::getDirect(CoerceTy);
5343     }
5344 
5345     // All other aggregates are passed ByVal.
5346     return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
5347                                    /*ByVal=*/true,
5348                                    /*Realign=*/TyAlign > ABIAlign);
5349   }
5350 
5351   return (isPromotableTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
5352                                      : ABIArgInfo::getDirect());
5353 }
5354 
5355 ABIArgInfo
5356 PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
5357   if (RetTy->isVoidType())
5358     return ABIArgInfo::getIgnore();
5359 
5360   if (RetTy->isAnyComplexType())
5361     return ABIArgInfo::getDirect();
5362 
5363   // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes)
5364   // or via reference (larger than 16 bytes).
5365   if (RetTy->isVectorType()) {
5366     uint64_t Size = getContext().getTypeSize(RetTy);
5367     if (Size > 128)
5368       return getNaturalAlignIndirect(RetTy);
5369     else if (Size < 128) {
5370       llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
5371       return ABIArgInfo::getDirect(CoerceTy);
5372     }
5373   }
5374 
5375   if (const auto *EIT = RetTy->getAs<BitIntType>())
5376     if (EIT->getNumBits() > 128)
5377       return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
5378 
5379   if (isAggregateTypeForABI(RetTy)) {
5380     // ELFv2 homogeneous aggregates are returned as array types.
5381     const Type *Base = nullptr;
5382     uint64_t Members = 0;
5383     if (Kind == ELFv2 &&
5384         isHomogeneousAggregate(RetTy, Base, Members)) {
5385       llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
5386       llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
5387       return ABIArgInfo::getDirect(CoerceTy);
5388     }
5389 
5390     // ELFv2 small aggregates are returned in up to two registers.
5391     uint64_t Bits = getContext().getTypeSize(RetTy);
5392     if (Kind == ELFv2 && Bits <= 2 * GPRBits) {
5393       if (Bits == 0)
5394         return ABIArgInfo::getIgnore();
5395 
5396       llvm::Type *CoerceTy;
5397       if (Bits > GPRBits) {
5398         CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits);
5399         CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy);
5400       } else
5401         CoerceTy =
5402             llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
5403       return ABIArgInfo::getDirect(CoerceTy);
5404     }
5405 
5406     // All other aggregates are returned indirectly.
5407     return getNaturalAlignIndirect(RetTy);
5408   }
5409 
5410   return (isPromotableTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
5411                                         : ABIArgInfo::getDirect());
5412 }
5413 
5414 // Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
5415 Address PPC64_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5416                                       QualType Ty) const {
5417   auto TypeInfo = getContext().getTypeInfoInChars(Ty);
5418   TypeInfo.Align = getParamTypeAlignment(Ty);
5419 
5420   CharUnits SlotSize = CharUnits::fromQuantity(8);
5421 
5422   // If we have a complex type and the base type is smaller than 8 bytes,
5423   // the ABI calls for the real and imaginary parts to be right-adjusted
5424   // in separate doublewords.  However, Clang expects us to produce a
5425   // pointer to a structure with the two parts packed tightly.  So generate
5426   // loads of the real and imaginary parts relative to the va_list pointer,
5427   // and store them to a temporary structure.
5428   if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
5429     CharUnits EltSize = TypeInfo.Width / 2;
5430     if (EltSize < SlotSize)
5431       return complexTempStructure(CGF, VAListAddr, Ty, SlotSize, EltSize, CTy);
5432   }
5433 
5434   // Otherwise, just use the general rule.
5435   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
5436                           TypeInfo, SlotSize, /*AllowHigher*/ true);
5437 }
5438 
5439 bool
5440 PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
5441   CodeGen::CodeGenFunction &CGF,
5442   llvm::Value *Address) const {
5443   return PPC_initDwarfEHRegSizeTable(CGF, Address, /*Is64Bit*/ true,
5444                                      /*IsAIX*/ false);
5445 }
5446 
5447 bool
5448 PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
5449                                                 llvm::Value *Address) const {
5450   return PPC_initDwarfEHRegSizeTable(CGF, Address, /*Is64Bit*/ true,
5451                                      /*IsAIX*/ false);
5452 }
5453 
5454 //===----------------------------------------------------------------------===//
5455 // AArch64 ABI Implementation
5456 //===----------------------------------------------------------------------===//
5457 
5458 namespace {
5459 
5460 class AArch64ABIInfo : public SwiftABIInfo {
5461 public:
5462   enum ABIKind {
5463     AAPCS = 0,
5464     DarwinPCS,
5465     Win64
5466   };
5467 
5468 private:
5469   ABIKind Kind;
5470 
5471 public:
5472   AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind)
5473     : SwiftABIInfo(CGT), Kind(Kind) {}
5474 
5475 private:
5476   ABIKind getABIKind() const { return Kind; }
5477   bool isDarwinPCS() const { return Kind == DarwinPCS; }
5478 
5479   ABIArgInfo classifyReturnType(QualType RetTy, bool IsVariadic) const;
5480   ABIArgInfo classifyArgumentType(QualType RetTy, bool IsVariadic,
5481                                   unsigned CallingConvention) const;
5482   ABIArgInfo coerceIllegalVector(QualType Ty) const;
5483   bool isHomogeneousAggregateBaseType(QualType Ty) const override;
5484   bool isHomogeneousAggregateSmallEnough(const Type *Ty,
5485                                          uint64_t Members) const override;
5486 
5487   bool isIllegalVectorType(QualType Ty) const;
5488 
5489   void computeInfo(CGFunctionInfo &FI) const override {
5490     if (!::classifyReturnType(getCXXABI(), FI, *this))
5491       FI.getReturnInfo() =
5492           classifyReturnType(FI.getReturnType(), FI.isVariadic());
5493 
5494     for (auto &it : FI.arguments())
5495       it.info = classifyArgumentType(it.type, FI.isVariadic(),
5496                                      FI.getCallingConvention());
5497   }
5498 
5499   Address EmitDarwinVAArg(Address VAListAddr, QualType Ty,
5500                           CodeGenFunction &CGF) const;
5501 
5502   Address EmitAAPCSVAArg(Address VAListAddr, QualType Ty,
5503                          CodeGenFunction &CGF) const;
5504 
5505   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5506                     QualType Ty) const override {
5507     llvm::Type *BaseTy = CGF.ConvertType(Ty);
5508     if (isa<llvm::ScalableVectorType>(BaseTy))
5509       llvm::report_fatal_error("Passing SVE types to variadic functions is "
5510                                "currently not supported");
5511 
5512     return Kind == Win64 ? EmitMSVAArg(CGF, VAListAddr, Ty)
5513                          : isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF)
5514                                          : EmitAAPCSVAArg(VAListAddr, Ty, CGF);
5515   }
5516 
5517   Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
5518                       QualType Ty) const override;
5519 
5520   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
5521                                     bool asReturnValue) const override {
5522     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
5523   }
5524   bool isSwiftErrorInRegister() const override {
5525     return true;
5526   }
5527 
5528   bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy,
5529                                  unsigned elts) const override;
5530 
5531   bool allowBFloatArgsAndRet() const override {
5532     return getTarget().hasBFloat16Type();
5533   }
5534 };
5535 
5536 class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
5537 public:
5538   AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind)
5539       : TargetCodeGenInfo(std::make_unique<AArch64ABIInfo>(CGT, Kind)) {}
5540 
5541   StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
5542     return "mov\tfp, fp\t\t// marker for objc_retainAutoreleaseReturnValue";
5543   }
5544 
5545   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
5546     return 31;
5547   }
5548 
5549   bool doesReturnSlotInterfereWithArgs() const override { return false; }
5550 
5551   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5552                            CodeGen::CodeGenModule &CGM) const override {
5553     const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
5554     if (!FD)
5555       return;
5556 
5557     const auto *TA = FD->getAttr<TargetAttr>();
5558     if (TA == nullptr)
5559       return;
5560 
5561     ParsedTargetAttr Attr = TA->parse();
5562     if (Attr.BranchProtection.empty())
5563       return;
5564 
5565     TargetInfo::BranchProtectionInfo BPI;
5566     StringRef Error;
5567     (void)CGM.getTarget().validateBranchProtection(
5568         Attr.BranchProtection, Attr.Architecture, BPI, Error);
5569     assert(Error.empty());
5570 
5571     auto *Fn = cast<llvm::Function>(GV);
5572     static const char *SignReturnAddrStr[] = {"none", "non-leaf", "all"};
5573     Fn->addFnAttr("sign-return-address", SignReturnAddrStr[static_cast<int>(BPI.SignReturnAddr)]);
5574 
5575     if (BPI.SignReturnAddr != LangOptions::SignReturnAddressScopeKind::None) {
5576       Fn->addFnAttr("sign-return-address-key",
5577                     BPI.SignKey == LangOptions::SignReturnAddressKeyKind::AKey
5578                         ? "a_key"
5579                         : "b_key");
5580     }
5581 
5582     Fn->addFnAttr("branch-target-enforcement",
5583                   BPI.BranchTargetEnforcement ? "true" : "false");
5584   }
5585 
5586   bool isScalarizableAsmOperand(CodeGen::CodeGenFunction &CGF,
5587                                 llvm::Type *Ty) const override {
5588     if (CGF.getTarget().hasFeature("ls64")) {
5589       auto *ST = dyn_cast<llvm::StructType>(Ty);
5590       if (ST && ST->getNumElements() == 1) {
5591         auto *AT = dyn_cast<llvm::ArrayType>(ST->getElementType(0));
5592         if (AT && AT->getNumElements() == 8 &&
5593             AT->getElementType()->isIntegerTy(64))
5594           return true;
5595       }
5596     }
5597     return TargetCodeGenInfo::isScalarizableAsmOperand(CGF, Ty);
5598   }
5599 };
5600 
5601 class WindowsAArch64TargetCodeGenInfo : public AArch64TargetCodeGenInfo {
5602 public:
5603   WindowsAArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind K)
5604       : AArch64TargetCodeGenInfo(CGT, K) {}
5605 
5606   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5607                            CodeGen::CodeGenModule &CGM) const override;
5608 
5609   void getDependentLibraryOption(llvm::StringRef Lib,
5610                                  llvm::SmallString<24> &Opt) const override {
5611     Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib);
5612   }
5613 
5614   void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value,
5615                                llvm::SmallString<32> &Opt) const override {
5616     Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
5617   }
5618 };
5619 
5620 void WindowsAArch64TargetCodeGenInfo::setTargetAttributes(
5621     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
5622   AArch64TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
5623   if (GV->isDeclaration())
5624     return;
5625   addStackProbeTargetAttributes(D, GV, CGM);
5626 }
5627 }
5628 
5629 ABIArgInfo AArch64ABIInfo::coerceIllegalVector(QualType Ty) const {
5630   assert(Ty->isVectorType() && "expected vector type!");
5631 
5632   const auto *VT = Ty->castAs<VectorType>();
5633   if (VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector) {
5634     assert(VT->getElementType()->isBuiltinType() && "expected builtin type!");
5635     assert(VT->getElementType()->castAs<BuiltinType>()->getKind() ==
5636                BuiltinType::UChar &&
5637            "unexpected builtin type for SVE predicate!");
5638     return ABIArgInfo::getDirect(llvm::ScalableVectorType::get(
5639         llvm::Type::getInt1Ty(getVMContext()), 16));
5640   }
5641 
5642   if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector) {
5643     assert(VT->getElementType()->isBuiltinType() && "expected builtin type!");
5644 
5645     const auto *BT = VT->getElementType()->castAs<BuiltinType>();
5646     llvm::ScalableVectorType *ResType = nullptr;
5647     switch (BT->getKind()) {
5648     default:
5649       llvm_unreachable("unexpected builtin type for SVE vector!");
5650     case BuiltinType::SChar:
5651     case BuiltinType::UChar:
5652       ResType = llvm::ScalableVectorType::get(
5653           llvm::Type::getInt8Ty(getVMContext()), 16);
5654       break;
5655     case BuiltinType::Short:
5656     case BuiltinType::UShort:
5657       ResType = llvm::ScalableVectorType::get(
5658           llvm::Type::getInt16Ty(getVMContext()), 8);
5659       break;
5660     case BuiltinType::Int:
5661     case BuiltinType::UInt:
5662       ResType = llvm::ScalableVectorType::get(
5663           llvm::Type::getInt32Ty(getVMContext()), 4);
5664       break;
5665     case BuiltinType::Long:
5666     case BuiltinType::ULong:
5667       ResType = llvm::ScalableVectorType::get(
5668           llvm::Type::getInt64Ty(getVMContext()), 2);
5669       break;
5670     case BuiltinType::Half:
5671       ResType = llvm::ScalableVectorType::get(
5672           llvm::Type::getHalfTy(getVMContext()), 8);
5673       break;
5674     case BuiltinType::Float:
5675       ResType = llvm::ScalableVectorType::get(
5676           llvm::Type::getFloatTy(getVMContext()), 4);
5677       break;
5678     case BuiltinType::Double:
5679       ResType = llvm::ScalableVectorType::get(
5680           llvm::Type::getDoubleTy(getVMContext()), 2);
5681       break;
5682     case BuiltinType::BFloat16:
5683       ResType = llvm::ScalableVectorType::get(
5684           llvm::Type::getBFloatTy(getVMContext()), 8);
5685       break;
5686     }
5687     return ABIArgInfo::getDirect(ResType);
5688   }
5689 
5690   uint64_t Size = getContext().getTypeSize(Ty);
5691   // Android promotes <2 x i8> to i16, not i32
5692   if (isAndroid() && (Size <= 16)) {
5693     llvm::Type *ResType = llvm::Type::getInt16Ty(getVMContext());
5694     return ABIArgInfo::getDirect(ResType);
5695   }
5696   if (Size <= 32) {
5697     llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext());
5698     return ABIArgInfo::getDirect(ResType);
5699   }
5700   if (Size == 64) {
5701     auto *ResType =
5702         llvm::FixedVectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2);
5703     return ABIArgInfo::getDirect(ResType);
5704   }
5705   if (Size == 128) {
5706     auto *ResType =
5707         llvm::FixedVectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4);
5708     return ABIArgInfo::getDirect(ResType);
5709   }
5710   return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
5711 }
5712 
5713 ABIArgInfo
5714 AArch64ABIInfo::classifyArgumentType(QualType Ty, bool IsVariadic,
5715                                      unsigned CallingConvention) const {
5716   Ty = useFirstFieldIfTransparentUnion(Ty);
5717 
5718   // Handle illegal vector types here.
5719   if (isIllegalVectorType(Ty))
5720     return coerceIllegalVector(Ty);
5721 
5722   if (!isAggregateTypeForABI(Ty)) {
5723     // Treat an enum type as its underlying type.
5724     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5725       Ty = EnumTy->getDecl()->getIntegerType();
5726 
5727     if (const auto *EIT = Ty->getAs<BitIntType>())
5728       if (EIT->getNumBits() > 128)
5729         return getNaturalAlignIndirect(Ty);
5730 
5731     return (isPromotableIntegerTypeForABI(Ty) && isDarwinPCS()
5732                 ? ABIArgInfo::getExtend(Ty)
5733                 : ABIArgInfo::getDirect());
5734   }
5735 
5736   // Structures with either a non-trivial destructor or a non-trivial
5737   // copy constructor are always indirect.
5738   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
5739     return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA ==
5740                                      CGCXXABI::RAA_DirectInMemory);
5741   }
5742 
5743   // Empty records are always ignored on Darwin, but actually passed in C++ mode
5744   // elsewhere for GNU compatibility.
5745   uint64_t Size = getContext().getTypeSize(Ty);
5746   bool IsEmpty = isEmptyRecord(getContext(), Ty, true);
5747   if (IsEmpty || Size == 0) {
5748     if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS())
5749       return ABIArgInfo::getIgnore();
5750 
5751     // GNU C mode. The only argument that gets ignored is an empty one with size
5752     // 0.
5753     if (IsEmpty && Size == 0)
5754       return ABIArgInfo::getIgnore();
5755     return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
5756   }
5757 
5758   // Homogeneous Floating-point Aggregates (HFAs) need to be expanded.
5759   const Type *Base = nullptr;
5760   uint64_t Members = 0;
5761   bool IsWin64 = Kind == Win64 || CallingConvention == llvm::CallingConv::Win64;
5762   bool IsWinVariadic = IsWin64 && IsVariadic;
5763   // In variadic functions on Windows, all composite types are treated alike,
5764   // no special handling of HFAs/HVAs.
5765   if (!IsWinVariadic && isHomogeneousAggregate(Ty, Base, Members)) {
5766     if (Kind != AArch64ABIInfo::AAPCS)
5767       return ABIArgInfo::getDirect(
5768           llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members));
5769 
5770     // For alignment adjusted HFAs, cap the argument alignment to 16, leave it
5771     // default otherwise.
5772     unsigned Align =
5773         getContext().getTypeUnadjustedAlignInChars(Ty).getQuantity();
5774     unsigned BaseAlign = getContext().getTypeAlignInChars(Base).getQuantity();
5775     Align = (Align > BaseAlign && Align >= 16) ? 16 : 0;
5776     return ABIArgInfo::getDirect(
5777         llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members), 0,
5778         nullptr, true, Align);
5779   }
5780 
5781   // Aggregates <= 16 bytes are passed directly in registers or on the stack.
5782   if (Size <= 128) {
5783     // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
5784     // same size and alignment.
5785     if (getTarget().isRenderScriptTarget()) {
5786       return coerceToIntArray(Ty, getContext(), getVMContext());
5787     }
5788     unsigned Alignment;
5789     if (Kind == AArch64ABIInfo::AAPCS) {
5790       Alignment = getContext().getTypeUnadjustedAlign(Ty);
5791       Alignment = Alignment < 128 ? 64 : 128;
5792     } else {
5793       Alignment = std::max(getContext().getTypeAlign(Ty),
5794                            (unsigned)getTarget().getPointerWidth(0));
5795     }
5796     Size = llvm::alignTo(Size, Alignment);
5797 
5798     // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
5799     // For aggregates with 16-byte alignment, we use i128.
5800     llvm::Type *BaseTy = llvm::Type::getIntNTy(getVMContext(), Alignment);
5801     return ABIArgInfo::getDirect(
5802         Size == Alignment ? BaseTy
5803                           : llvm::ArrayType::get(BaseTy, Size / Alignment));
5804   }
5805 
5806   return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
5807 }
5808 
5809 ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy,
5810                                               bool IsVariadic) const {
5811   if (RetTy->isVoidType())
5812     return ABIArgInfo::getIgnore();
5813 
5814   if (const auto *VT = RetTy->getAs<VectorType>()) {
5815     if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector ||
5816         VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector)
5817       return coerceIllegalVector(RetTy);
5818   }
5819 
5820   // Large vector types should be returned via memory.
5821   if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
5822     return getNaturalAlignIndirect(RetTy);
5823 
5824   if (!isAggregateTypeForABI(RetTy)) {
5825     // Treat an enum type as its underlying type.
5826     if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5827       RetTy = EnumTy->getDecl()->getIntegerType();
5828 
5829     if (const auto *EIT = RetTy->getAs<BitIntType>())
5830       if (EIT->getNumBits() > 128)
5831         return getNaturalAlignIndirect(RetTy);
5832 
5833     return (isPromotableIntegerTypeForABI(RetTy) && isDarwinPCS()
5834                 ? ABIArgInfo::getExtend(RetTy)
5835                 : ABIArgInfo::getDirect());
5836   }
5837 
5838   uint64_t Size = getContext().getTypeSize(RetTy);
5839   if (isEmptyRecord(getContext(), RetTy, true) || Size == 0)
5840     return ABIArgInfo::getIgnore();
5841 
5842   const Type *Base = nullptr;
5843   uint64_t Members = 0;
5844   if (isHomogeneousAggregate(RetTy, Base, Members) &&
5845       !(getTarget().getTriple().getArch() == llvm::Triple::aarch64_32 &&
5846         IsVariadic))
5847     // Homogeneous Floating-point Aggregates (HFAs) are returned directly.
5848     return ABIArgInfo::getDirect();
5849 
5850   // Aggregates <= 16 bytes are returned directly in registers or on the stack.
5851   if (Size <= 128) {
5852     // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
5853     // same size and alignment.
5854     if (getTarget().isRenderScriptTarget()) {
5855       return coerceToIntArray(RetTy, getContext(), getVMContext());
5856     }
5857 
5858     if (Size <= 64 && getDataLayout().isLittleEndian()) {
5859       // Composite types are returned in lower bits of a 64-bit register for LE,
5860       // and in higher bits for BE. However, integer types are always returned
5861       // in lower bits for both LE and BE, and they are not rounded up to
5862       // 64-bits. We can skip rounding up of composite types for LE, but not for
5863       // BE, otherwise composite types will be indistinguishable from integer
5864       // types.
5865       return ABIArgInfo::getDirect(
5866           llvm::IntegerType::get(getVMContext(), Size));
5867     }
5868 
5869     unsigned Alignment = getContext().getTypeAlign(RetTy);
5870     Size = llvm::alignTo(Size, 64); // round up to multiple of 8 bytes
5871 
5872     // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
5873     // For aggregates with 16-byte alignment, we use i128.
5874     if (Alignment < 128 && Size == 128) {
5875       llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
5876       return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
5877     }
5878     return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
5879   }
5880 
5881   return getNaturalAlignIndirect(RetTy);
5882 }
5883 
5884 /// isIllegalVectorType - check whether the vector type is legal for AArch64.
5885 bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const {
5886   if (const VectorType *VT = Ty->getAs<VectorType>()) {
5887     // Check whether VT is a fixed-length SVE vector. These types are
5888     // represented as scalable vectors in function args/return and must be
5889     // coerced from fixed vectors.
5890     if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector ||
5891         VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector)
5892       return true;
5893 
5894     // Check whether VT is legal.
5895     unsigned NumElements = VT->getNumElements();
5896     uint64_t Size = getContext().getTypeSize(VT);
5897     // NumElements should be power of 2.
5898     if (!llvm::isPowerOf2_32(NumElements))
5899       return true;
5900 
5901     // arm64_32 has to be compatible with the ARM logic here, which allows huge
5902     // vectors for some reason.
5903     llvm::Triple Triple = getTarget().getTriple();
5904     if (Triple.getArch() == llvm::Triple::aarch64_32 &&
5905         Triple.isOSBinFormatMachO())
5906       return Size <= 32;
5907 
5908     return Size != 64 && (Size != 128 || NumElements == 1);
5909   }
5910   return false;
5911 }
5912 
5913 bool AArch64ABIInfo::isLegalVectorTypeForSwift(CharUnits totalSize,
5914                                                llvm::Type *eltTy,
5915                                                unsigned elts) const {
5916   if (!llvm::isPowerOf2_32(elts))
5917     return false;
5918   if (totalSize.getQuantity() != 8 &&
5919       (totalSize.getQuantity() != 16 || elts == 1))
5920     return false;
5921   return true;
5922 }
5923 
5924 bool AArch64ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
5925   // Homogeneous aggregates for AAPCS64 must have base types of a floating
5926   // point type or a short-vector type. This is the same as the 32-bit ABI,
5927   // but with the difference that any floating-point type is allowed,
5928   // including __fp16.
5929   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
5930     if (BT->isFloatingPoint())
5931       return true;
5932   } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
5933     unsigned VecSize = getContext().getTypeSize(VT);
5934     if (VecSize == 64 || VecSize == 128)
5935       return true;
5936   }
5937   return false;
5938 }
5939 
5940 bool AArch64ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
5941                                                        uint64_t Members) const {
5942   return Members <= 4;
5943 }
5944 
5945 Address AArch64ABIInfo::EmitAAPCSVAArg(Address VAListAddr, QualType Ty,
5946                                        CodeGenFunction &CGF) const {
5947   ABIArgInfo AI = classifyArgumentType(Ty, /*IsVariadic=*/true,
5948                                        CGF.CurFnInfo->getCallingConvention());
5949   bool IsIndirect = AI.isIndirect();
5950 
5951   llvm::Type *BaseTy = CGF.ConvertType(Ty);
5952   if (IsIndirect)
5953     BaseTy = llvm::PointerType::getUnqual(BaseTy);
5954   else if (AI.getCoerceToType())
5955     BaseTy = AI.getCoerceToType();
5956 
5957   unsigned NumRegs = 1;
5958   if (llvm::ArrayType *ArrTy = dyn_cast<llvm::ArrayType>(BaseTy)) {
5959     BaseTy = ArrTy->getElementType();
5960     NumRegs = ArrTy->getNumElements();
5961   }
5962   bool IsFPR = BaseTy->isFloatingPointTy() || BaseTy->isVectorTy();
5963 
5964   // The AArch64 va_list type and handling is specified in the Procedure Call
5965   // Standard, section B.4:
5966   //
5967   // struct {
5968   //   void *__stack;
5969   //   void *__gr_top;
5970   //   void *__vr_top;
5971   //   int __gr_offs;
5972   //   int __vr_offs;
5973   // };
5974 
5975   llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
5976   llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
5977   llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
5978   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
5979 
5980   CharUnits TySize = getContext().getTypeSizeInChars(Ty);
5981   CharUnits TyAlign = getContext().getTypeUnadjustedAlignInChars(Ty);
5982 
5983   Address reg_offs_p = Address::invalid();
5984   llvm::Value *reg_offs = nullptr;
5985   int reg_top_index;
5986   int RegSize = IsIndirect ? 8 : TySize.getQuantity();
5987   if (!IsFPR) {
5988     // 3 is the field number of __gr_offs
5989     reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 3, "gr_offs_p");
5990     reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
5991     reg_top_index = 1; // field number for __gr_top
5992     RegSize = llvm::alignTo(RegSize, 8);
5993   } else {
5994     // 4 is the field number of __vr_offs.
5995     reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 4, "vr_offs_p");
5996     reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
5997     reg_top_index = 2; // field number for __vr_top
5998     RegSize = 16 * NumRegs;
5999   }
6000 
6001   //=======================================
6002   // Find out where argument was passed
6003   //=======================================
6004 
6005   // If reg_offs >= 0 we're already using the stack for this type of
6006   // argument. We don't want to keep updating reg_offs (in case it overflows,
6007   // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
6008   // whatever they get).
6009   llvm::Value *UsingStack = nullptr;
6010   UsingStack = CGF.Builder.CreateICmpSGE(
6011       reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0));
6012 
6013   CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
6014 
6015   // Otherwise, at least some kind of argument could go in these registers, the
6016   // question is whether this particular type is too big.
6017   CGF.EmitBlock(MaybeRegBlock);
6018 
6019   // Integer arguments may need to correct register alignment (for example a
6020   // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
6021   // align __gr_offs to calculate the potential address.
6022   if (!IsFPR && !IsIndirect && TyAlign.getQuantity() > 8) {
6023     int Align = TyAlign.getQuantity();
6024 
6025     reg_offs = CGF.Builder.CreateAdd(
6026         reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
6027         "align_regoffs");
6028     reg_offs = CGF.Builder.CreateAnd(
6029         reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align),
6030         "aligned_regoffs");
6031   }
6032 
6033   // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
6034   // The fact that this is done unconditionally reflects the fact that
6035   // allocating an argument to the stack also uses up all the remaining
6036   // registers of the appropriate kind.
6037   llvm::Value *NewOffset = nullptr;
6038   NewOffset = CGF.Builder.CreateAdd(
6039       reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs");
6040   CGF.Builder.CreateStore(NewOffset, reg_offs_p);
6041 
6042   // Now we're in a position to decide whether this argument really was in
6043   // registers or not.
6044   llvm::Value *InRegs = nullptr;
6045   InRegs = CGF.Builder.CreateICmpSLE(
6046       NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg");
6047 
6048   CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
6049 
6050   //=======================================
6051   // Argument was in registers
6052   //=======================================
6053 
6054   // Now we emit the code for if the argument was originally passed in
6055   // registers. First start the appropriate block:
6056   CGF.EmitBlock(InRegBlock);
6057 
6058   llvm::Value *reg_top = nullptr;
6059   Address reg_top_p =
6060       CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index, "reg_top_p");
6061   reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
6062   Address BaseAddr(CGF.Builder.CreateInBoundsGEP(CGF.Int8Ty, reg_top, reg_offs),
6063                    CharUnits::fromQuantity(IsFPR ? 16 : 8));
6064   Address RegAddr = Address::invalid();
6065   llvm::Type *MemTy = CGF.ConvertTypeForMem(Ty);
6066 
6067   if (IsIndirect) {
6068     // If it's been passed indirectly (actually a struct), whatever we find from
6069     // stored registers or on the stack will actually be a struct **.
6070     MemTy = llvm::PointerType::getUnqual(MemTy);
6071   }
6072 
6073   const Type *Base = nullptr;
6074   uint64_t NumMembers = 0;
6075   bool IsHFA = isHomogeneousAggregate(Ty, Base, NumMembers);
6076   if (IsHFA && NumMembers > 1) {
6077     // Homogeneous aggregates passed in registers will have their elements split
6078     // and stored 16-bytes apart regardless of size (they're notionally in qN,
6079     // qN+1, ...). We reload and store into a temporary local variable
6080     // contiguously.
6081     assert(!IsIndirect && "Homogeneous aggregates should be passed directly");
6082     auto BaseTyInfo = getContext().getTypeInfoInChars(QualType(Base, 0));
6083     llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
6084     llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
6085     Address Tmp = CGF.CreateTempAlloca(HFATy,
6086                                        std::max(TyAlign, BaseTyInfo.Align));
6087 
6088     // On big-endian platforms, the value will be right-aligned in its slot.
6089     int Offset = 0;
6090     if (CGF.CGM.getDataLayout().isBigEndian() &&
6091         BaseTyInfo.Width.getQuantity() < 16)
6092       Offset = 16 - BaseTyInfo.Width.getQuantity();
6093 
6094     for (unsigned i = 0; i < NumMembers; ++i) {
6095       CharUnits BaseOffset = CharUnits::fromQuantity(16 * i + Offset);
6096       Address LoadAddr =
6097         CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, BaseOffset);
6098       LoadAddr = CGF.Builder.CreateElementBitCast(LoadAddr, BaseTy);
6099 
6100       Address StoreAddr = CGF.Builder.CreateConstArrayGEP(Tmp, i);
6101 
6102       llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
6103       CGF.Builder.CreateStore(Elem, StoreAddr);
6104     }
6105 
6106     RegAddr = CGF.Builder.CreateElementBitCast(Tmp, MemTy);
6107   } else {
6108     // Otherwise the object is contiguous in memory.
6109 
6110     // It might be right-aligned in its slot.
6111     CharUnits SlotSize = BaseAddr.getAlignment();
6112     if (CGF.CGM.getDataLayout().isBigEndian() && !IsIndirect &&
6113         (IsHFA || !isAggregateTypeForABI(Ty)) &&
6114         TySize < SlotSize) {
6115       CharUnits Offset = SlotSize - TySize;
6116       BaseAddr = CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, Offset);
6117     }
6118 
6119     RegAddr = CGF.Builder.CreateElementBitCast(BaseAddr, MemTy);
6120   }
6121 
6122   CGF.EmitBranch(ContBlock);
6123 
6124   //=======================================
6125   // Argument was on the stack
6126   //=======================================
6127   CGF.EmitBlock(OnStackBlock);
6128 
6129   Address stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "stack_p");
6130   llvm::Value *OnStackPtr = CGF.Builder.CreateLoad(stack_p, "stack");
6131 
6132   // Again, stack arguments may need realignment. In this case both integer and
6133   // floating-point ones might be affected.
6134   if (!IsIndirect && TyAlign.getQuantity() > 8) {
6135     int Align = TyAlign.getQuantity();
6136 
6137     OnStackPtr = CGF.Builder.CreatePtrToInt(OnStackPtr, CGF.Int64Ty);
6138 
6139     OnStackPtr = CGF.Builder.CreateAdd(
6140         OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
6141         "align_stack");
6142     OnStackPtr = CGF.Builder.CreateAnd(
6143         OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, -Align),
6144         "align_stack");
6145 
6146     OnStackPtr = CGF.Builder.CreateIntToPtr(OnStackPtr, CGF.Int8PtrTy);
6147   }
6148   Address OnStackAddr(OnStackPtr,
6149                       std::max(CharUnits::fromQuantity(8), TyAlign));
6150 
6151   // All stack slots are multiples of 8 bytes.
6152   CharUnits StackSlotSize = CharUnits::fromQuantity(8);
6153   CharUnits StackSize;
6154   if (IsIndirect)
6155     StackSize = StackSlotSize;
6156   else
6157     StackSize = TySize.alignTo(StackSlotSize);
6158 
6159   llvm::Value *StackSizeC = CGF.Builder.getSize(StackSize);
6160   llvm::Value *NewStack = CGF.Builder.CreateInBoundsGEP(
6161       CGF.Int8Ty, OnStackPtr, StackSizeC, "new_stack");
6162 
6163   // Write the new value of __stack for the next call to va_arg
6164   CGF.Builder.CreateStore(NewStack, stack_p);
6165 
6166   if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) &&
6167       TySize < StackSlotSize) {
6168     CharUnits Offset = StackSlotSize - TySize;
6169     OnStackAddr = CGF.Builder.CreateConstInBoundsByteGEP(OnStackAddr, Offset);
6170   }
6171 
6172   OnStackAddr = CGF.Builder.CreateElementBitCast(OnStackAddr, MemTy);
6173 
6174   CGF.EmitBranch(ContBlock);
6175 
6176   //=======================================
6177   // Tidy up
6178   //=======================================
6179   CGF.EmitBlock(ContBlock);
6180 
6181   Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
6182                                  OnStackAddr, OnStackBlock, "vaargs.addr");
6183 
6184   if (IsIndirect)
6185     return Address(CGF.Builder.CreateLoad(ResAddr, "vaarg.addr"),
6186                    TyAlign);
6187 
6188   return ResAddr;
6189 }
6190 
6191 Address AArch64ABIInfo::EmitDarwinVAArg(Address VAListAddr, QualType Ty,
6192                                         CodeGenFunction &CGF) const {
6193   // The backend's lowering doesn't support va_arg for aggregates or
6194   // illegal vector types.  Lower VAArg here for these cases and use
6195   // the LLVM va_arg instruction for everything else.
6196   if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty))
6197     return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
6198 
6199   uint64_t PointerSize = getTarget().getPointerWidth(0) / 8;
6200   CharUnits SlotSize = CharUnits::fromQuantity(PointerSize);
6201 
6202   // Empty records are ignored for parameter passing purposes.
6203   if (isEmptyRecord(getContext(), Ty, true)) {
6204     Address Addr(CGF.Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
6205     Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
6206     return Addr;
6207   }
6208 
6209   // The size of the actual thing passed, which might end up just
6210   // being a pointer for indirect types.
6211   auto TyInfo = getContext().getTypeInfoInChars(Ty);
6212 
6213   // Arguments bigger than 16 bytes which aren't homogeneous
6214   // aggregates should be passed indirectly.
6215   bool IsIndirect = false;
6216   if (TyInfo.Width.getQuantity() > 16) {
6217     const Type *Base = nullptr;
6218     uint64_t Members = 0;
6219     IsIndirect = !isHomogeneousAggregate(Ty, Base, Members);
6220   }
6221 
6222   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
6223                           TyInfo, SlotSize, /*AllowHigherAlign*/ true);
6224 }
6225 
6226 Address AArch64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
6227                                     QualType Ty) const {
6228   bool IsIndirect = false;
6229 
6230   // Composites larger than 16 bytes are passed by reference.
6231   if (isAggregateTypeForABI(Ty) && getContext().getTypeSize(Ty) > 128)
6232     IsIndirect = true;
6233 
6234   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
6235                           CGF.getContext().getTypeInfoInChars(Ty),
6236                           CharUnits::fromQuantity(8),
6237                           /*allowHigherAlign*/ false);
6238 }
6239 
6240 //===----------------------------------------------------------------------===//
6241 // ARM ABI Implementation
6242 //===----------------------------------------------------------------------===//
6243 
6244 namespace {
6245 
6246 class ARMABIInfo : public SwiftABIInfo {
6247 public:
6248   enum ABIKind {
6249     APCS = 0,
6250     AAPCS = 1,
6251     AAPCS_VFP = 2,
6252     AAPCS16_VFP = 3,
6253   };
6254 
6255 private:
6256   ABIKind Kind;
6257   bool IsFloatABISoftFP;
6258 
6259 public:
6260   ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind)
6261       : SwiftABIInfo(CGT), Kind(_Kind) {
6262     setCCs();
6263     IsFloatABISoftFP = CGT.getCodeGenOpts().FloatABI == "softfp" ||
6264         CGT.getCodeGenOpts().FloatABI == ""; // default
6265   }
6266 
6267   bool isEABI() const {
6268     switch (getTarget().getTriple().getEnvironment()) {
6269     case llvm::Triple::Android:
6270     case llvm::Triple::EABI:
6271     case llvm::Triple::EABIHF:
6272     case llvm::Triple::GNUEABI:
6273     case llvm::Triple::GNUEABIHF:
6274     case llvm::Triple::MuslEABI:
6275     case llvm::Triple::MuslEABIHF:
6276       return true;
6277     default:
6278       return false;
6279     }
6280   }
6281 
6282   bool isEABIHF() const {
6283     switch (getTarget().getTriple().getEnvironment()) {
6284     case llvm::Triple::EABIHF:
6285     case llvm::Triple::GNUEABIHF:
6286     case llvm::Triple::MuslEABIHF:
6287       return true;
6288     default:
6289       return false;
6290     }
6291   }
6292 
6293   ABIKind getABIKind() const { return Kind; }
6294 
6295   bool allowBFloatArgsAndRet() const override {
6296     return !IsFloatABISoftFP && getTarget().hasBFloat16Type();
6297   }
6298 
6299 private:
6300   ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic,
6301                                 unsigned functionCallConv) const;
6302   ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic,
6303                                   unsigned functionCallConv) const;
6304   ABIArgInfo classifyHomogeneousAggregate(QualType Ty, const Type *Base,
6305                                           uint64_t Members) const;
6306   ABIArgInfo coerceIllegalVector(QualType Ty) const;
6307   bool isIllegalVectorType(QualType Ty) const;
6308   bool containsAnyFP16Vectors(QualType Ty) const;
6309 
6310   bool isHomogeneousAggregateBaseType(QualType Ty) const override;
6311   bool isHomogeneousAggregateSmallEnough(const Type *Ty,
6312                                          uint64_t Members) const override;
6313 
6314   bool isEffectivelyAAPCS_VFP(unsigned callConvention, bool acceptHalf) const;
6315 
6316   void computeInfo(CGFunctionInfo &FI) const override;
6317 
6318   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6319                     QualType Ty) const override;
6320 
6321   llvm::CallingConv::ID getLLVMDefaultCC() const;
6322   llvm::CallingConv::ID getABIDefaultCC() const;
6323   void setCCs();
6324 
6325   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
6326                                     bool asReturnValue) const override {
6327     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
6328   }
6329   bool isSwiftErrorInRegister() const override {
6330     return true;
6331   }
6332   bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy,
6333                                  unsigned elts) const override;
6334 };
6335 
6336 class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
6337 public:
6338   ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
6339       : TargetCodeGenInfo(std::make_unique<ARMABIInfo>(CGT, K)) {}
6340 
6341   const ARMABIInfo &getABIInfo() const {
6342     return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
6343   }
6344 
6345   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
6346     return 13;
6347   }
6348 
6349   StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
6350     return "mov\tr7, r7\t\t// marker for objc_retainAutoreleaseReturnValue";
6351   }
6352 
6353   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
6354                                llvm::Value *Address) const override {
6355     llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
6356 
6357     // 0-15 are the 16 integer registers.
6358     AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
6359     return false;
6360   }
6361 
6362   unsigned getSizeOfUnwindException() const override {
6363     if (getABIInfo().isEABI()) return 88;
6364     return TargetCodeGenInfo::getSizeOfUnwindException();
6365   }
6366 
6367   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
6368                            CodeGen::CodeGenModule &CGM) const override {
6369     if (GV->isDeclaration())
6370       return;
6371     const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
6372     if (!FD)
6373       return;
6374     auto *Fn = cast<llvm::Function>(GV);
6375 
6376     if (const auto *TA = FD->getAttr<TargetAttr>()) {
6377       ParsedTargetAttr Attr = TA->parse();
6378       if (!Attr.BranchProtection.empty()) {
6379         TargetInfo::BranchProtectionInfo BPI;
6380         StringRef DiagMsg;
6381         StringRef Arch = Attr.Architecture.empty()
6382                              ? CGM.getTarget().getTargetOpts().CPU
6383                              : Attr.Architecture;
6384         if (!CGM.getTarget().validateBranchProtection(Attr.BranchProtection,
6385                                                       Arch, BPI, DiagMsg)) {
6386           CGM.getDiags().Report(
6387               D->getLocation(),
6388               diag::warn_target_unsupported_branch_protection_attribute)
6389               << Arch;
6390         } else {
6391           static const char *SignReturnAddrStr[] = {"none", "non-leaf", "all"};
6392           assert(static_cast<unsigned>(BPI.SignReturnAddr) <= 2 &&
6393                  "Unexpected SignReturnAddressScopeKind");
6394           Fn->addFnAttr(
6395               "sign-return-address",
6396               SignReturnAddrStr[static_cast<int>(BPI.SignReturnAddr)]);
6397 
6398           Fn->addFnAttr("branch-target-enforcement",
6399                         BPI.BranchTargetEnforcement ? "true" : "false");
6400         }
6401       } else if (CGM.getLangOpts().BranchTargetEnforcement ||
6402                  CGM.getLangOpts().hasSignReturnAddress()) {
6403         // If the Branch Protection attribute is missing, validate the target
6404         // Architecture attribute against Branch Protection command line
6405         // settings.
6406         if (!CGM.getTarget().isBranchProtectionSupportedArch(Attr.Architecture))
6407           CGM.getDiags().Report(
6408               D->getLocation(),
6409               diag::warn_target_unsupported_branch_protection_attribute)
6410               << Attr.Architecture;
6411       }
6412     }
6413 
6414     const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
6415     if (!Attr)
6416       return;
6417 
6418     const char *Kind;
6419     switch (Attr->getInterrupt()) {
6420     case ARMInterruptAttr::Generic: Kind = ""; break;
6421     case ARMInterruptAttr::IRQ:     Kind = "IRQ"; break;
6422     case ARMInterruptAttr::FIQ:     Kind = "FIQ"; break;
6423     case ARMInterruptAttr::SWI:     Kind = "SWI"; break;
6424     case ARMInterruptAttr::ABORT:   Kind = "ABORT"; break;
6425     case ARMInterruptAttr::UNDEF:   Kind = "UNDEF"; break;
6426     }
6427 
6428     Fn->addFnAttr("interrupt", Kind);
6429 
6430     ARMABIInfo::ABIKind ABI = cast<ARMABIInfo>(getABIInfo()).getABIKind();
6431     if (ABI == ARMABIInfo::APCS)
6432       return;
6433 
6434     // AAPCS guarantees that sp will be 8-byte aligned on any public interface,
6435     // however this is not necessarily true on taking any interrupt. Instruct
6436     // the backend to perform a realignment as part of the function prologue.
6437     llvm::AttrBuilder B(Fn->getContext());
6438     B.addStackAlignmentAttr(8);
6439     Fn->addFnAttrs(B);
6440   }
6441 };
6442 
6443 class WindowsARMTargetCodeGenInfo : public ARMTargetCodeGenInfo {
6444 public:
6445   WindowsARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
6446       : ARMTargetCodeGenInfo(CGT, K) {}
6447 
6448   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
6449                            CodeGen::CodeGenModule &CGM) const override;
6450 
6451   void getDependentLibraryOption(llvm::StringRef Lib,
6452                                  llvm::SmallString<24> &Opt) const override {
6453     Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib);
6454   }
6455 
6456   void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value,
6457                                llvm::SmallString<32> &Opt) const override {
6458     Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
6459   }
6460 };
6461 
6462 void WindowsARMTargetCodeGenInfo::setTargetAttributes(
6463     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
6464   ARMTargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
6465   if (GV->isDeclaration())
6466     return;
6467   addStackProbeTargetAttributes(D, GV, CGM);
6468 }
6469 }
6470 
6471 void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
6472   if (!::classifyReturnType(getCXXABI(), FI, *this))
6473     FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), FI.isVariadic(),
6474                                             FI.getCallingConvention());
6475 
6476   for (auto &I : FI.arguments())
6477     I.info = classifyArgumentType(I.type, FI.isVariadic(),
6478                                   FI.getCallingConvention());
6479 
6480 
6481   // Always honor user-specified calling convention.
6482   if (FI.getCallingConvention() != llvm::CallingConv::C)
6483     return;
6484 
6485   llvm::CallingConv::ID cc = getRuntimeCC();
6486   if (cc != llvm::CallingConv::C)
6487     FI.setEffectiveCallingConvention(cc);
6488 }
6489 
6490 /// Return the default calling convention that LLVM will use.
6491 llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
6492   // The default calling convention that LLVM will infer.
6493   if (isEABIHF() || getTarget().getTriple().isWatchABI())
6494     return llvm::CallingConv::ARM_AAPCS_VFP;
6495   else if (isEABI())
6496     return llvm::CallingConv::ARM_AAPCS;
6497   else
6498     return llvm::CallingConv::ARM_APCS;
6499 }
6500 
6501 /// Return the calling convention that our ABI would like us to use
6502 /// as the C calling convention.
6503 llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
6504   switch (getABIKind()) {
6505   case APCS: return llvm::CallingConv::ARM_APCS;
6506   case AAPCS: return llvm::CallingConv::ARM_AAPCS;
6507   case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
6508   case AAPCS16_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
6509   }
6510   llvm_unreachable("bad ABI kind");
6511 }
6512 
6513 void ARMABIInfo::setCCs() {
6514   assert(getRuntimeCC() == llvm::CallingConv::C);
6515 
6516   // Don't muddy up the IR with a ton of explicit annotations if
6517   // they'd just match what LLVM will infer from the triple.
6518   llvm::CallingConv::ID abiCC = getABIDefaultCC();
6519   if (abiCC != getLLVMDefaultCC())
6520     RuntimeCC = abiCC;
6521 }
6522 
6523 ABIArgInfo ARMABIInfo::coerceIllegalVector(QualType Ty) const {
6524   uint64_t Size = getContext().getTypeSize(Ty);
6525   if (Size <= 32) {
6526     llvm::Type *ResType =
6527         llvm::Type::getInt32Ty(getVMContext());
6528     return ABIArgInfo::getDirect(ResType);
6529   }
6530   if (Size == 64 || Size == 128) {
6531     auto *ResType = llvm::FixedVectorType::get(
6532         llvm::Type::getInt32Ty(getVMContext()), Size / 32);
6533     return ABIArgInfo::getDirect(ResType);
6534   }
6535   return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
6536 }
6537 
6538 ABIArgInfo ARMABIInfo::classifyHomogeneousAggregate(QualType Ty,
6539                                                     const Type *Base,
6540                                                     uint64_t Members) const {
6541   assert(Base && "Base class should be set for homogeneous aggregate");
6542   // Base can be a floating-point or a vector.
6543   if (const VectorType *VT = Base->getAs<VectorType>()) {
6544     // FP16 vectors should be converted to integer vectors
6545     if (!getTarget().hasLegalHalfType() && containsAnyFP16Vectors(Ty)) {
6546       uint64_t Size = getContext().getTypeSize(VT);
6547       auto *NewVecTy = llvm::FixedVectorType::get(
6548           llvm::Type::getInt32Ty(getVMContext()), Size / 32);
6549       llvm::Type *Ty = llvm::ArrayType::get(NewVecTy, Members);
6550       return ABIArgInfo::getDirect(Ty, 0, nullptr, false);
6551     }
6552   }
6553   unsigned Align = 0;
6554   if (getABIKind() == ARMABIInfo::AAPCS ||
6555       getABIKind() == ARMABIInfo::AAPCS_VFP) {
6556     // For alignment adjusted HFAs, cap the argument alignment to 8, leave it
6557     // default otherwise.
6558     Align = getContext().getTypeUnadjustedAlignInChars(Ty).getQuantity();
6559     unsigned BaseAlign = getContext().getTypeAlignInChars(Base).getQuantity();
6560     Align = (Align > BaseAlign && Align >= 8) ? 8 : 0;
6561   }
6562   return ABIArgInfo::getDirect(nullptr, 0, nullptr, false, Align);
6563 }
6564 
6565 ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty, bool isVariadic,
6566                                             unsigned functionCallConv) const {
6567   // 6.1.2.1 The following argument types are VFP CPRCs:
6568   //   A single-precision floating-point type (including promoted
6569   //   half-precision types); A double-precision floating-point type;
6570   //   A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
6571   //   with a Base Type of a single- or double-precision floating-point type,
6572   //   64-bit containerized vectors or 128-bit containerized vectors with one
6573   //   to four Elements.
6574   // Variadic functions should always marshal to the base standard.
6575   bool IsAAPCS_VFP =
6576       !isVariadic && isEffectivelyAAPCS_VFP(functionCallConv, /* AAPCS16 */ false);
6577 
6578   Ty = useFirstFieldIfTransparentUnion(Ty);
6579 
6580   // Handle illegal vector types here.
6581   if (isIllegalVectorType(Ty))
6582     return coerceIllegalVector(Ty);
6583 
6584   if (!isAggregateTypeForABI(Ty)) {
6585     // Treat an enum type as its underlying type.
6586     if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
6587       Ty = EnumTy->getDecl()->getIntegerType();
6588     }
6589 
6590     if (const auto *EIT = Ty->getAs<BitIntType>())
6591       if (EIT->getNumBits() > 64)
6592         return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
6593 
6594     return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
6595                                               : ABIArgInfo::getDirect());
6596   }
6597 
6598   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
6599     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
6600   }
6601 
6602   // Ignore empty records.
6603   if (isEmptyRecord(getContext(), Ty, true))
6604     return ABIArgInfo::getIgnore();
6605 
6606   if (IsAAPCS_VFP) {
6607     // Homogeneous Aggregates need to be expanded when we can fit the aggregate
6608     // into VFP registers.
6609     const Type *Base = nullptr;
6610     uint64_t Members = 0;
6611     if (isHomogeneousAggregate(Ty, Base, Members))
6612       return classifyHomogeneousAggregate(Ty, Base, Members);
6613   } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
6614     // WatchOS does have homogeneous aggregates. Note that we intentionally use
6615     // this convention even for a variadic function: the backend will use GPRs
6616     // if needed.
6617     const Type *Base = nullptr;
6618     uint64_t Members = 0;
6619     if (isHomogeneousAggregate(Ty, Base, Members)) {
6620       assert(Base && Members <= 4 && "unexpected homogeneous aggregate");
6621       llvm::Type *Ty =
6622         llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members);
6623       return ABIArgInfo::getDirect(Ty, 0, nullptr, false);
6624     }
6625   }
6626 
6627   if (getABIKind() == ARMABIInfo::AAPCS16_VFP &&
6628       getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(16)) {
6629     // WatchOS is adopting the 64-bit AAPCS rule on composite types: if they're
6630     // bigger than 128-bits, they get placed in space allocated by the caller,
6631     // and a pointer is passed.
6632     return ABIArgInfo::getIndirect(
6633         CharUnits::fromQuantity(getContext().getTypeAlign(Ty) / 8), false);
6634   }
6635 
6636   // Support byval for ARM.
6637   // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
6638   // most 8-byte. We realign the indirect argument if type alignment is bigger
6639   // than ABI alignment.
6640   uint64_t ABIAlign = 4;
6641   uint64_t TyAlign;
6642   if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
6643       getABIKind() == ARMABIInfo::AAPCS) {
6644     TyAlign = getContext().getTypeUnadjustedAlignInChars(Ty).getQuantity();
6645     ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
6646   } else {
6647     TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity();
6648   }
6649   if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
6650     assert(getABIKind() != ARMABIInfo::AAPCS16_VFP && "unexpected byval");
6651     return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
6652                                    /*ByVal=*/true,
6653                                    /*Realign=*/TyAlign > ABIAlign);
6654   }
6655 
6656   // On RenderScript, coerce Aggregates <= 64 bytes to an integer array of
6657   // same size and alignment.
6658   if (getTarget().isRenderScriptTarget()) {
6659     return coerceToIntArray(Ty, getContext(), getVMContext());
6660   }
6661 
6662   // Otherwise, pass by coercing to a structure of the appropriate size.
6663   llvm::Type* ElemTy;
6664   unsigned SizeRegs;
6665   // FIXME: Try to match the types of the arguments more accurately where
6666   // we can.
6667   if (TyAlign <= 4) {
6668     ElemTy = llvm::Type::getInt32Ty(getVMContext());
6669     SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
6670   } else {
6671     ElemTy = llvm::Type::getInt64Ty(getVMContext());
6672     SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
6673   }
6674 
6675   return ABIArgInfo::getDirect(llvm::ArrayType::get(ElemTy, SizeRegs));
6676 }
6677 
6678 static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
6679                               llvm::LLVMContext &VMContext) {
6680   // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
6681   // is called integer-like if its size is less than or equal to one word, and
6682   // the offset of each of its addressable sub-fields is zero.
6683 
6684   uint64_t Size = Context.getTypeSize(Ty);
6685 
6686   // Check that the type fits in a word.
6687   if (Size > 32)
6688     return false;
6689 
6690   // FIXME: Handle vector types!
6691   if (Ty->isVectorType())
6692     return false;
6693 
6694   // Float types are never treated as "integer like".
6695   if (Ty->isRealFloatingType())
6696     return false;
6697 
6698   // If this is a builtin or pointer type then it is ok.
6699   if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
6700     return true;
6701 
6702   // Small complex integer types are "integer like".
6703   if (const ComplexType *CT = Ty->getAs<ComplexType>())
6704     return isIntegerLikeType(CT->getElementType(), Context, VMContext);
6705 
6706   // Single element and zero sized arrays should be allowed, by the definition
6707   // above, but they are not.
6708 
6709   // Otherwise, it must be a record type.
6710   const RecordType *RT = Ty->getAs<RecordType>();
6711   if (!RT) return false;
6712 
6713   // Ignore records with flexible arrays.
6714   const RecordDecl *RD = RT->getDecl();
6715   if (RD->hasFlexibleArrayMember())
6716     return false;
6717 
6718   // Check that all sub-fields are at offset 0, and are themselves "integer
6719   // like".
6720   const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
6721 
6722   bool HadField = false;
6723   unsigned idx = 0;
6724   for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
6725        i != e; ++i, ++idx) {
6726     const FieldDecl *FD = *i;
6727 
6728     // Bit-fields are not addressable, we only need to verify they are "integer
6729     // like". We still have to disallow a subsequent non-bitfield, for example:
6730     //   struct { int : 0; int x }
6731     // is non-integer like according to gcc.
6732     if (FD->isBitField()) {
6733       if (!RD->isUnion())
6734         HadField = true;
6735 
6736       if (!isIntegerLikeType(FD->getType(), Context, VMContext))
6737         return false;
6738 
6739       continue;
6740     }
6741 
6742     // Check if this field is at offset 0.
6743     if (Layout.getFieldOffset(idx) != 0)
6744       return false;
6745 
6746     if (!isIntegerLikeType(FD->getType(), Context, VMContext))
6747       return false;
6748 
6749     // Only allow at most one field in a structure. This doesn't match the
6750     // wording above, but follows gcc in situations with a field following an
6751     // empty structure.
6752     if (!RD->isUnion()) {
6753       if (HadField)
6754         return false;
6755 
6756       HadField = true;
6757     }
6758   }
6759 
6760   return true;
6761 }
6762 
6763 ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy, bool isVariadic,
6764                                           unsigned functionCallConv) const {
6765 
6766   // Variadic functions should always marshal to the base standard.
6767   bool IsAAPCS_VFP =
6768       !isVariadic && isEffectivelyAAPCS_VFP(functionCallConv, /* AAPCS16 */ true);
6769 
6770   if (RetTy->isVoidType())
6771     return ABIArgInfo::getIgnore();
6772 
6773   if (const VectorType *VT = RetTy->getAs<VectorType>()) {
6774     // Large vector types should be returned via memory.
6775     if (getContext().getTypeSize(RetTy) > 128)
6776       return getNaturalAlignIndirect(RetTy);
6777     // TODO: FP16/BF16 vectors should be converted to integer vectors
6778     // This check is similar  to isIllegalVectorType - refactor?
6779     if ((!getTarget().hasLegalHalfType() &&
6780         (VT->getElementType()->isFloat16Type() ||
6781          VT->getElementType()->isHalfType())) ||
6782         (IsFloatABISoftFP &&
6783          VT->getElementType()->isBFloat16Type()))
6784       return coerceIllegalVector(RetTy);
6785   }
6786 
6787   if (!isAggregateTypeForABI(RetTy)) {
6788     // Treat an enum type as its underlying type.
6789     if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6790       RetTy = EnumTy->getDecl()->getIntegerType();
6791 
6792     if (const auto *EIT = RetTy->getAs<BitIntType>())
6793       if (EIT->getNumBits() > 64)
6794         return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
6795 
6796     return isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
6797                                                 : ABIArgInfo::getDirect();
6798   }
6799 
6800   // Are we following APCS?
6801   if (getABIKind() == APCS) {
6802     if (isEmptyRecord(getContext(), RetTy, false))
6803       return ABIArgInfo::getIgnore();
6804 
6805     // Complex types are all returned as packed integers.
6806     //
6807     // FIXME: Consider using 2 x vector types if the back end handles them
6808     // correctly.
6809     if (RetTy->isAnyComplexType())
6810       return ABIArgInfo::getDirect(llvm::IntegerType::get(
6811           getVMContext(), getContext().getTypeSize(RetTy)));
6812 
6813     // Integer like structures are returned in r0.
6814     if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
6815       // Return in the smallest viable integer type.
6816       uint64_t Size = getContext().getTypeSize(RetTy);
6817       if (Size <= 8)
6818         return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6819       if (Size <= 16)
6820         return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6821       return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6822     }
6823 
6824     // Otherwise return in memory.
6825     return getNaturalAlignIndirect(RetTy);
6826   }
6827 
6828   // Otherwise this is an AAPCS variant.
6829 
6830   if (isEmptyRecord(getContext(), RetTy, true))
6831     return ABIArgInfo::getIgnore();
6832 
6833   // Check for homogeneous aggregates with AAPCS-VFP.
6834   if (IsAAPCS_VFP) {
6835     const Type *Base = nullptr;
6836     uint64_t Members = 0;
6837     if (isHomogeneousAggregate(RetTy, Base, Members))
6838       return classifyHomogeneousAggregate(RetTy, Base, Members);
6839   }
6840 
6841   // Aggregates <= 4 bytes are returned in r0; other aggregates
6842   // are returned indirectly.
6843   uint64_t Size = getContext().getTypeSize(RetTy);
6844   if (Size <= 32) {
6845     // On RenderScript, coerce Aggregates <= 4 bytes to an integer array of
6846     // same size and alignment.
6847     if (getTarget().isRenderScriptTarget()) {
6848       return coerceToIntArray(RetTy, getContext(), getVMContext());
6849     }
6850     if (getDataLayout().isBigEndian())
6851       // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4)
6852       return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6853 
6854     // Return in the smallest viable integer type.
6855     if (Size <= 8)
6856       return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6857     if (Size <= 16)
6858       return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6859     return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6860   } else if (Size <= 128 && getABIKind() == AAPCS16_VFP) {
6861     llvm::Type *Int32Ty = llvm::Type::getInt32Ty(getVMContext());
6862     llvm::Type *CoerceTy =
6863         llvm::ArrayType::get(Int32Ty, llvm::alignTo(Size, 32) / 32);
6864     return ABIArgInfo::getDirect(CoerceTy);
6865   }
6866 
6867   return getNaturalAlignIndirect(RetTy);
6868 }
6869 
6870 /// isIllegalVector - check whether Ty is an illegal vector type.
6871 bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
6872   if (const VectorType *VT = Ty->getAs<VectorType> ()) {
6873     // On targets that don't support half, fp16 or bfloat, they are expanded
6874     // into float, and we don't want the ABI to depend on whether or not they
6875     // are supported in hardware. Thus return false to coerce vectors of these
6876     // types into integer vectors.
6877     // We do not depend on hasLegalHalfType for bfloat as it is a
6878     // separate IR type.
6879     if ((!getTarget().hasLegalHalfType() &&
6880         (VT->getElementType()->isFloat16Type() ||
6881          VT->getElementType()->isHalfType())) ||
6882         (IsFloatABISoftFP &&
6883          VT->getElementType()->isBFloat16Type()))
6884       return true;
6885     if (isAndroid()) {
6886       // Android shipped using Clang 3.1, which supported a slightly different
6887       // vector ABI. The primary differences were that 3-element vector types
6888       // were legal, and so were sub 32-bit vectors (i.e. <2 x i8>). This path
6889       // accepts that legacy behavior for Android only.
6890       // Check whether VT is legal.
6891       unsigned NumElements = VT->getNumElements();
6892       // NumElements should be power of 2 or equal to 3.
6893       if (!llvm::isPowerOf2_32(NumElements) && NumElements != 3)
6894         return true;
6895     } else {
6896       // Check whether VT is legal.
6897       unsigned NumElements = VT->getNumElements();
6898       uint64_t Size = getContext().getTypeSize(VT);
6899       // NumElements should be power of 2.
6900       if (!llvm::isPowerOf2_32(NumElements))
6901         return true;
6902       // Size should be greater than 32 bits.
6903       return Size <= 32;
6904     }
6905   }
6906   return false;
6907 }
6908 
6909 /// Return true if a type contains any 16-bit floating point vectors
6910 bool ARMABIInfo::containsAnyFP16Vectors(QualType Ty) const {
6911   if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
6912     uint64_t NElements = AT->getSize().getZExtValue();
6913     if (NElements == 0)
6914       return false;
6915     return containsAnyFP16Vectors(AT->getElementType());
6916   } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
6917     const RecordDecl *RD = RT->getDecl();
6918 
6919     // If this is a C++ record, check the bases first.
6920     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
6921       if (llvm::any_of(CXXRD->bases(), [this](const CXXBaseSpecifier &B) {
6922             return containsAnyFP16Vectors(B.getType());
6923           }))
6924         return true;
6925 
6926     if (llvm::any_of(RD->fields(), [this](FieldDecl *FD) {
6927           return FD && containsAnyFP16Vectors(FD->getType());
6928         }))
6929       return true;
6930 
6931     return false;
6932   } else {
6933     if (const VectorType *VT = Ty->getAs<VectorType>())
6934       return (VT->getElementType()->isFloat16Type() ||
6935               VT->getElementType()->isBFloat16Type() ||
6936               VT->getElementType()->isHalfType());
6937     return false;
6938   }
6939 }
6940 
6941 bool ARMABIInfo::isLegalVectorTypeForSwift(CharUnits vectorSize,
6942                                            llvm::Type *eltTy,
6943                                            unsigned numElts) const {
6944   if (!llvm::isPowerOf2_32(numElts))
6945     return false;
6946   unsigned size = getDataLayout().getTypeStoreSizeInBits(eltTy);
6947   if (size > 64)
6948     return false;
6949   if (vectorSize.getQuantity() != 8 &&
6950       (vectorSize.getQuantity() != 16 || numElts == 1))
6951     return false;
6952   return true;
6953 }
6954 
6955 bool ARMABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
6956   // Homogeneous aggregates for AAPCS-VFP must have base types of float,
6957   // double, or 64-bit or 128-bit vectors.
6958   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
6959     if (BT->getKind() == BuiltinType::Float ||
6960         BT->getKind() == BuiltinType::Double ||
6961         BT->getKind() == BuiltinType::LongDouble)
6962       return true;
6963   } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
6964     unsigned VecSize = getContext().getTypeSize(VT);
6965     if (VecSize == 64 || VecSize == 128)
6966       return true;
6967   }
6968   return false;
6969 }
6970 
6971 bool ARMABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
6972                                                    uint64_t Members) const {
6973   return Members <= 4;
6974 }
6975 
6976 bool ARMABIInfo::isEffectivelyAAPCS_VFP(unsigned callConvention,
6977                                         bool acceptHalf) const {
6978   // Give precedence to user-specified calling conventions.
6979   if (callConvention != llvm::CallingConv::C)
6980     return (callConvention == llvm::CallingConv::ARM_AAPCS_VFP);
6981   else
6982     return (getABIKind() == AAPCS_VFP) ||
6983            (acceptHalf && (getABIKind() == AAPCS16_VFP));
6984 }
6985 
6986 Address ARMABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6987                               QualType Ty) const {
6988   CharUnits SlotSize = CharUnits::fromQuantity(4);
6989 
6990   // Empty records are ignored for parameter passing purposes.
6991   if (isEmptyRecord(getContext(), Ty, true)) {
6992     Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize);
6993     Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
6994     return Addr;
6995   }
6996 
6997   CharUnits TySize = getContext().getTypeSizeInChars(Ty);
6998   CharUnits TyAlignForABI = getContext().getTypeUnadjustedAlignInChars(Ty);
6999 
7000   // Use indirect if size of the illegal vector is bigger than 16 bytes.
7001   bool IsIndirect = false;
7002   const Type *Base = nullptr;
7003   uint64_t Members = 0;
7004   if (TySize > CharUnits::fromQuantity(16) && isIllegalVectorType(Ty)) {
7005     IsIndirect = true;
7006 
7007   // ARMv7k passes structs bigger than 16 bytes indirectly, in space
7008   // allocated by the caller.
7009   } else if (TySize > CharUnits::fromQuantity(16) &&
7010              getABIKind() == ARMABIInfo::AAPCS16_VFP &&
7011              !isHomogeneousAggregate(Ty, Base, Members)) {
7012     IsIndirect = true;
7013 
7014   // Otherwise, bound the type's ABI alignment.
7015   // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
7016   // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
7017   // Our callers should be prepared to handle an under-aligned address.
7018   } else if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
7019              getABIKind() == ARMABIInfo::AAPCS) {
7020     TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
7021     TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(8));
7022   } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
7023     // ARMv7k allows type alignment up to 16 bytes.
7024     TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
7025     TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(16));
7026   } else {
7027     TyAlignForABI = CharUnits::fromQuantity(4);
7028   }
7029 
7030   TypeInfoChars TyInfo(TySize, TyAlignForABI, AlignRequirementKind::None);
7031   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TyInfo,
7032                           SlotSize, /*AllowHigherAlign*/ true);
7033 }
7034 
7035 //===----------------------------------------------------------------------===//
7036 // NVPTX ABI Implementation
7037 //===----------------------------------------------------------------------===//
7038 
7039 namespace {
7040 
7041 class NVPTXTargetCodeGenInfo;
7042 
7043 class NVPTXABIInfo : public ABIInfo {
7044   NVPTXTargetCodeGenInfo &CGInfo;
7045 
7046 public:
7047   NVPTXABIInfo(CodeGenTypes &CGT, NVPTXTargetCodeGenInfo &Info)
7048       : ABIInfo(CGT), CGInfo(Info) {}
7049 
7050   ABIArgInfo classifyReturnType(QualType RetTy) const;
7051   ABIArgInfo classifyArgumentType(QualType Ty) const;
7052 
7053   void computeInfo(CGFunctionInfo &FI) const override;
7054   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7055                     QualType Ty) const override;
7056   bool isUnsupportedType(QualType T) const;
7057   ABIArgInfo coerceToIntArrayWithLimit(QualType Ty, unsigned MaxSize) const;
7058 };
7059 
7060 class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
7061 public:
7062   NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
7063       : TargetCodeGenInfo(std::make_unique<NVPTXABIInfo>(CGT, *this)) {}
7064 
7065   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
7066                            CodeGen::CodeGenModule &M) const override;
7067   bool shouldEmitStaticExternCAliases() const override;
7068 
7069   llvm::Type *getCUDADeviceBuiltinSurfaceDeviceType() const override {
7070     // On the device side, surface reference is represented as an object handle
7071     // in 64-bit integer.
7072     return llvm::Type::getInt64Ty(getABIInfo().getVMContext());
7073   }
7074 
7075   llvm::Type *getCUDADeviceBuiltinTextureDeviceType() const override {
7076     // On the device side, texture reference is represented as an object handle
7077     // in 64-bit integer.
7078     return llvm::Type::getInt64Ty(getABIInfo().getVMContext());
7079   }
7080 
7081   bool emitCUDADeviceBuiltinSurfaceDeviceCopy(CodeGenFunction &CGF, LValue Dst,
7082                                               LValue Src) const override {
7083     emitBuiltinSurfTexDeviceCopy(CGF, Dst, Src);
7084     return true;
7085   }
7086 
7087   bool emitCUDADeviceBuiltinTextureDeviceCopy(CodeGenFunction &CGF, LValue Dst,
7088                                               LValue Src) const override {
7089     emitBuiltinSurfTexDeviceCopy(CGF, Dst, Src);
7090     return true;
7091   }
7092 
7093 private:
7094   // Adds a NamedMDNode with GV, Name, and Operand as operands, and adds the
7095   // resulting MDNode to the nvvm.annotations MDNode.
7096   static void addNVVMMetadata(llvm::GlobalValue *GV, StringRef Name,
7097                               int Operand);
7098 
7099   static void emitBuiltinSurfTexDeviceCopy(CodeGenFunction &CGF, LValue Dst,
7100                                            LValue Src) {
7101     llvm::Value *Handle = nullptr;
7102     llvm::Constant *C =
7103         llvm::dyn_cast<llvm::Constant>(Src.getAddress(CGF).getPointer());
7104     // Lookup `addrspacecast` through the constant pointer if any.
7105     if (auto *ASC = llvm::dyn_cast_or_null<llvm::AddrSpaceCastOperator>(C))
7106       C = llvm::cast<llvm::Constant>(ASC->getPointerOperand());
7107     if (auto *GV = llvm::dyn_cast_or_null<llvm::GlobalVariable>(C)) {
7108       // Load the handle from the specific global variable using
7109       // `nvvm.texsurf.handle.internal` intrinsic.
7110       Handle = CGF.EmitRuntimeCall(
7111           CGF.CGM.getIntrinsic(llvm::Intrinsic::nvvm_texsurf_handle_internal,
7112                                {GV->getType()}),
7113           {GV}, "texsurf_handle");
7114     } else
7115       Handle = CGF.EmitLoadOfScalar(Src, SourceLocation());
7116     CGF.EmitStoreOfScalar(Handle, Dst);
7117   }
7118 };
7119 
7120 /// Checks if the type is unsupported directly by the current target.
7121 bool NVPTXABIInfo::isUnsupportedType(QualType T) const {
7122   ASTContext &Context = getContext();
7123   if (!Context.getTargetInfo().hasFloat16Type() && T->isFloat16Type())
7124     return true;
7125   if (!Context.getTargetInfo().hasFloat128Type() &&
7126       (T->isFloat128Type() ||
7127        (T->isRealFloatingType() && Context.getTypeSize(T) == 128)))
7128     return true;
7129   if (const auto *EIT = T->getAs<BitIntType>())
7130     return EIT->getNumBits() >
7131            (Context.getTargetInfo().hasInt128Type() ? 128U : 64U);
7132   if (!Context.getTargetInfo().hasInt128Type() && T->isIntegerType() &&
7133       Context.getTypeSize(T) > 64U)
7134     return true;
7135   if (const auto *AT = T->getAsArrayTypeUnsafe())
7136     return isUnsupportedType(AT->getElementType());
7137   const auto *RT = T->getAs<RecordType>();
7138   if (!RT)
7139     return false;
7140   const RecordDecl *RD = RT->getDecl();
7141 
7142   // If this is a C++ record, check the bases first.
7143   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
7144     for (const CXXBaseSpecifier &I : CXXRD->bases())
7145       if (isUnsupportedType(I.getType()))
7146         return true;
7147 
7148   for (const FieldDecl *I : RD->fields())
7149     if (isUnsupportedType(I->getType()))
7150       return true;
7151   return false;
7152 }
7153 
7154 /// Coerce the given type into an array with maximum allowed size of elements.
7155 ABIArgInfo NVPTXABIInfo::coerceToIntArrayWithLimit(QualType Ty,
7156                                                    unsigned MaxSize) const {
7157   // Alignment and Size are measured in bits.
7158   const uint64_t Size = getContext().getTypeSize(Ty);
7159   const uint64_t Alignment = getContext().getTypeAlign(Ty);
7160   const unsigned Div = std::min<unsigned>(MaxSize, Alignment);
7161   llvm::Type *IntType = llvm::Type::getIntNTy(getVMContext(), Div);
7162   const uint64_t NumElements = (Size + Div - 1) / Div;
7163   return ABIArgInfo::getDirect(llvm::ArrayType::get(IntType, NumElements));
7164 }
7165 
7166 ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
7167   if (RetTy->isVoidType())
7168     return ABIArgInfo::getIgnore();
7169 
7170   if (getContext().getLangOpts().OpenMP &&
7171       getContext().getLangOpts().OpenMPIsDevice && isUnsupportedType(RetTy))
7172     return coerceToIntArrayWithLimit(RetTy, 64);
7173 
7174   // note: this is different from default ABI
7175   if (!RetTy->isScalarType())
7176     return ABIArgInfo::getDirect();
7177 
7178   // Treat an enum type as its underlying type.
7179   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
7180     RetTy = EnumTy->getDecl()->getIntegerType();
7181 
7182   return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
7183                                                : ABIArgInfo::getDirect());
7184 }
7185 
7186 ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
7187   // Treat an enum type as its underlying type.
7188   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7189     Ty = EnumTy->getDecl()->getIntegerType();
7190 
7191   // Return aggregates type as indirect by value
7192   if (isAggregateTypeForABI(Ty)) {
7193     // Under CUDA device compilation, tex/surf builtin types are replaced with
7194     // object types and passed directly.
7195     if (getContext().getLangOpts().CUDAIsDevice) {
7196       if (Ty->isCUDADeviceBuiltinSurfaceType())
7197         return ABIArgInfo::getDirect(
7198             CGInfo.getCUDADeviceBuiltinSurfaceDeviceType());
7199       if (Ty->isCUDADeviceBuiltinTextureType())
7200         return ABIArgInfo::getDirect(
7201             CGInfo.getCUDADeviceBuiltinTextureDeviceType());
7202     }
7203     return getNaturalAlignIndirect(Ty, /* byval */ true);
7204   }
7205 
7206   if (const auto *EIT = Ty->getAs<BitIntType>()) {
7207     if ((EIT->getNumBits() > 128) ||
7208         (!getContext().getTargetInfo().hasInt128Type() &&
7209          EIT->getNumBits() > 64))
7210       return getNaturalAlignIndirect(Ty, /* byval */ true);
7211   }
7212 
7213   return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
7214                                             : ABIArgInfo::getDirect());
7215 }
7216 
7217 void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
7218   if (!getCXXABI().classifyReturnType(FI))
7219     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7220   for (auto &I : FI.arguments())
7221     I.info = classifyArgumentType(I.type);
7222 
7223   // Always honor user-specified calling convention.
7224   if (FI.getCallingConvention() != llvm::CallingConv::C)
7225     return;
7226 
7227   FI.setEffectiveCallingConvention(getRuntimeCC());
7228 }
7229 
7230 Address NVPTXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7231                                 QualType Ty) const {
7232   llvm_unreachable("NVPTX does not support varargs");
7233 }
7234 
7235 void NVPTXTargetCodeGenInfo::setTargetAttributes(
7236     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
7237   if (GV->isDeclaration())
7238     return;
7239   const VarDecl *VD = dyn_cast_or_null<VarDecl>(D);
7240   if (VD) {
7241     if (M.getLangOpts().CUDA) {
7242       if (VD->getType()->isCUDADeviceBuiltinSurfaceType())
7243         addNVVMMetadata(GV, "surface", 1);
7244       else if (VD->getType()->isCUDADeviceBuiltinTextureType())
7245         addNVVMMetadata(GV, "texture", 1);
7246       return;
7247     }
7248   }
7249 
7250   const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
7251   if (!FD) return;
7252 
7253   llvm::Function *F = cast<llvm::Function>(GV);
7254 
7255   // Perform special handling in OpenCL mode
7256   if (M.getLangOpts().OpenCL) {
7257     // Use OpenCL function attributes to check for kernel functions
7258     // By default, all functions are device functions
7259     if (FD->hasAttr<OpenCLKernelAttr>()) {
7260       // OpenCL __kernel functions get kernel metadata
7261       // Create !{<func-ref>, metadata !"kernel", i32 1} node
7262       addNVVMMetadata(F, "kernel", 1);
7263       // And kernel functions are not subject to inlining
7264       F->addFnAttr(llvm::Attribute::NoInline);
7265     }
7266   }
7267 
7268   // Perform special handling in CUDA mode.
7269   if (M.getLangOpts().CUDA) {
7270     // CUDA __global__ functions get a kernel metadata entry.  Since
7271     // __global__ functions cannot be called from the device, we do not
7272     // need to set the noinline attribute.
7273     if (FD->hasAttr<CUDAGlobalAttr>()) {
7274       // Create !{<func-ref>, metadata !"kernel", i32 1} node
7275       addNVVMMetadata(F, "kernel", 1);
7276     }
7277     if (CUDALaunchBoundsAttr *Attr = FD->getAttr<CUDALaunchBoundsAttr>()) {
7278       // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node
7279       llvm::APSInt MaxThreads(32);
7280       MaxThreads = Attr->getMaxThreads()->EvaluateKnownConstInt(M.getContext());
7281       if (MaxThreads > 0)
7282         addNVVMMetadata(F, "maxntidx", MaxThreads.getExtValue());
7283 
7284       // min blocks is an optional argument for CUDALaunchBoundsAttr. If it was
7285       // not specified in __launch_bounds__ or if the user specified a 0 value,
7286       // we don't have to add a PTX directive.
7287       if (Attr->getMinBlocks()) {
7288         llvm::APSInt MinBlocks(32);
7289         MinBlocks = Attr->getMinBlocks()->EvaluateKnownConstInt(M.getContext());
7290         if (MinBlocks > 0)
7291           // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node
7292           addNVVMMetadata(F, "minctasm", MinBlocks.getExtValue());
7293       }
7294     }
7295   }
7296 }
7297 
7298 void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::GlobalValue *GV,
7299                                              StringRef Name, int Operand) {
7300   llvm::Module *M = GV->getParent();
7301   llvm::LLVMContext &Ctx = M->getContext();
7302 
7303   // Get "nvvm.annotations" metadata node
7304   llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
7305 
7306   llvm::Metadata *MDVals[] = {
7307       llvm::ConstantAsMetadata::get(GV), llvm::MDString::get(Ctx, Name),
7308       llvm::ConstantAsMetadata::get(
7309           llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand))};
7310   // Append metadata to nvvm.annotations
7311   MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
7312 }
7313 
7314 bool NVPTXTargetCodeGenInfo::shouldEmitStaticExternCAliases() const {
7315   return false;
7316 }
7317 }
7318 
7319 //===----------------------------------------------------------------------===//
7320 // SystemZ ABI Implementation
7321 //===----------------------------------------------------------------------===//
7322 
7323 namespace {
7324 
7325 class SystemZABIInfo : public SwiftABIInfo {
7326   bool HasVector;
7327   bool IsSoftFloatABI;
7328 
7329 public:
7330   SystemZABIInfo(CodeGenTypes &CGT, bool HV, bool SF)
7331     : SwiftABIInfo(CGT), HasVector(HV), IsSoftFloatABI(SF) {}
7332 
7333   bool isPromotableIntegerTypeForABI(QualType Ty) const;
7334   bool isCompoundType(QualType Ty) const;
7335   bool isVectorArgumentType(QualType Ty) const;
7336   bool isFPArgumentType(QualType Ty) const;
7337   QualType GetSingleElementType(QualType Ty) const;
7338 
7339   ABIArgInfo classifyReturnType(QualType RetTy) const;
7340   ABIArgInfo classifyArgumentType(QualType ArgTy) const;
7341 
7342   void computeInfo(CGFunctionInfo &FI) const override {
7343     if (!getCXXABI().classifyReturnType(FI))
7344       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7345     for (auto &I : FI.arguments())
7346       I.info = classifyArgumentType(I.type);
7347   }
7348 
7349   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7350                     QualType Ty) const override;
7351 
7352   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
7353                                     bool asReturnValue) const override {
7354     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
7355   }
7356   bool isSwiftErrorInRegister() const override {
7357     return false;
7358   }
7359 };
7360 
7361 class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
7362 public:
7363   SystemZTargetCodeGenInfo(CodeGenTypes &CGT, bool HasVector, bool SoftFloatABI)
7364       : TargetCodeGenInfo(
7365             std::make_unique<SystemZABIInfo>(CGT, HasVector, SoftFloatABI)) {}
7366 
7367   llvm::Value *testFPKind(llvm::Value *V, unsigned BuiltinID,
7368                           CGBuilderTy &Builder,
7369                           CodeGenModule &CGM) const override {
7370     assert(V->getType()->isFloatingPointTy() && "V should have an FP type.");
7371     // Only use TDC in constrained FP mode.
7372     if (!Builder.getIsFPConstrained())
7373       return nullptr;
7374 
7375     llvm::Type *Ty = V->getType();
7376     if (Ty->isFloatTy() || Ty->isDoubleTy() || Ty->isFP128Ty()) {
7377       llvm::Module &M = CGM.getModule();
7378       auto &Ctx = M.getContext();
7379       llvm::Function *TDCFunc =
7380           llvm::Intrinsic::getDeclaration(&M, llvm::Intrinsic::s390_tdc, Ty);
7381       unsigned TDCBits = 0;
7382       switch (BuiltinID) {
7383       case Builtin::BI__builtin_isnan:
7384         TDCBits = 0xf;
7385         break;
7386       case Builtin::BIfinite:
7387       case Builtin::BI__finite:
7388       case Builtin::BIfinitef:
7389       case Builtin::BI__finitef:
7390       case Builtin::BIfinitel:
7391       case Builtin::BI__finitel:
7392       case Builtin::BI__builtin_isfinite:
7393         TDCBits = 0xfc0;
7394         break;
7395       case Builtin::BI__builtin_isinf:
7396         TDCBits = 0x30;
7397         break;
7398       default:
7399         break;
7400       }
7401       if (TDCBits)
7402         return Builder.CreateCall(
7403             TDCFunc,
7404             {V, llvm::ConstantInt::get(llvm::Type::getInt64Ty(Ctx), TDCBits)});
7405     }
7406     return nullptr;
7407   }
7408 };
7409 }
7410 
7411 bool SystemZABIInfo::isPromotableIntegerTypeForABI(QualType Ty) const {
7412   // Treat an enum type as its underlying type.
7413   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7414     Ty = EnumTy->getDecl()->getIntegerType();
7415 
7416   // Promotable integer types are required to be promoted by the ABI.
7417   if (ABIInfo::isPromotableIntegerTypeForABI(Ty))
7418     return true;
7419 
7420   if (const auto *EIT = Ty->getAs<BitIntType>())
7421     if (EIT->getNumBits() < 64)
7422       return true;
7423 
7424   // 32-bit values must also be promoted.
7425   if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
7426     switch (BT->getKind()) {
7427     case BuiltinType::Int:
7428     case BuiltinType::UInt:
7429       return true;
7430     default:
7431       return false;
7432     }
7433   return false;
7434 }
7435 
7436 bool SystemZABIInfo::isCompoundType(QualType Ty) const {
7437   return (Ty->isAnyComplexType() ||
7438           Ty->isVectorType() ||
7439           isAggregateTypeForABI(Ty));
7440 }
7441 
7442 bool SystemZABIInfo::isVectorArgumentType(QualType Ty) const {
7443   return (HasVector &&
7444           Ty->isVectorType() &&
7445           getContext().getTypeSize(Ty) <= 128);
7446 }
7447 
7448 bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
7449   if (IsSoftFloatABI)
7450     return false;
7451 
7452   if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
7453     switch (BT->getKind()) {
7454     case BuiltinType::Float:
7455     case BuiltinType::Double:
7456       return true;
7457     default:
7458       return false;
7459     }
7460 
7461   return false;
7462 }
7463 
7464 QualType SystemZABIInfo::GetSingleElementType(QualType Ty) const {
7465   const RecordType *RT = Ty->getAs<RecordType>();
7466 
7467   if (RT && RT->isStructureOrClassType()) {
7468     const RecordDecl *RD = RT->getDecl();
7469     QualType Found;
7470 
7471     // If this is a C++ record, check the bases first.
7472     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
7473       for (const auto &I : CXXRD->bases()) {
7474         QualType Base = I.getType();
7475 
7476         // Empty bases don't affect things either way.
7477         if (isEmptyRecord(getContext(), Base, true))
7478           continue;
7479 
7480         if (!Found.isNull())
7481           return Ty;
7482         Found = GetSingleElementType(Base);
7483       }
7484 
7485     // Check the fields.
7486     for (const auto *FD : RD->fields()) {
7487       // For compatibility with GCC, ignore empty bitfields in C++ mode.
7488       // Unlike isSingleElementStruct(), empty structure and array fields
7489       // do count.  So do anonymous bitfields that aren't zero-sized.
7490       if (getContext().getLangOpts().CPlusPlus &&
7491           FD->isZeroLengthBitField(getContext()))
7492         continue;
7493       // Like isSingleElementStruct(), ignore C++20 empty data members.
7494       if (FD->hasAttr<NoUniqueAddressAttr>() &&
7495           isEmptyRecord(getContext(), FD->getType(), true))
7496         continue;
7497 
7498       // Unlike isSingleElementStruct(), arrays do not count.
7499       // Nested structures still do though.
7500       if (!Found.isNull())
7501         return Ty;
7502       Found = GetSingleElementType(FD->getType());
7503     }
7504 
7505     // Unlike isSingleElementStruct(), trailing padding is allowed.
7506     // An 8-byte aligned struct s { float f; } is passed as a double.
7507     if (!Found.isNull())
7508       return Found;
7509   }
7510 
7511   return Ty;
7512 }
7513 
7514 Address SystemZABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7515                                   QualType Ty) const {
7516   // Assume that va_list type is correct; should be pointer to LLVM type:
7517   // struct {
7518   //   i64 __gpr;
7519   //   i64 __fpr;
7520   //   i8 *__overflow_arg_area;
7521   //   i8 *__reg_save_area;
7522   // };
7523 
7524   // Every non-vector argument occupies 8 bytes and is passed by preference
7525   // in either GPRs or FPRs.  Vector arguments occupy 8 or 16 bytes and are
7526   // always passed on the stack.
7527   Ty = getContext().getCanonicalType(Ty);
7528   auto TyInfo = getContext().getTypeInfoInChars(Ty);
7529   llvm::Type *ArgTy = CGF.ConvertTypeForMem(Ty);
7530   llvm::Type *DirectTy = ArgTy;
7531   ABIArgInfo AI = classifyArgumentType(Ty);
7532   bool IsIndirect = AI.isIndirect();
7533   bool InFPRs = false;
7534   bool IsVector = false;
7535   CharUnits UnpaddedSize;
7536   CharUnits DirectAlign;
7537   if (IsIndirect) {
7538     DirectTy = llvm::PointerType::getUnqual(DirectTy);
7539     UnpaddedSize = DirectAlign = CharUnits::fromQuantity(8);
7540   } else {
7541     if (AI.getCoerceToType())
7542       ArgTy = AI.getCoerceToType();
7543     InFPRs = (!IsSoftFloatABI && (ArgTy->isFloatTy() || ArgTy->isDoubleTy()));
7544     IsVector = ArgTy->isVectorTy();
7545     UnpaddedSize = TyInfo.Width;
7546     DirectAlign = TyInfo.Align;
7547   }
7548   CharUnits PaddedSize = CharUnits::fromQuantity(8);
7549   if (IsVector && UnpaddedSize > PaddedSize)
7550     PaddedSize = CharUnits::fromQuantity(16);
7551   assert((UnpaddedSize <= PaddedSize) && "Invalid argument size.");
7552 
7553   CharUnits Padding = (PaddedSize - UnpaddedSize);
7554 
7555   llvm::Type *IndexTy = CGF.Int64Ty;
7556   llvm::Value *PaddedSizeV =
7557     llvm::ConstantInt::get(IndexTy, PaddedSize.getQuantity());
7558 
7559   if (IsVector) {
7560     // Work out the address of a vector argument on the stack.
7561     // Vector arguments are always passed in the high bits of a
7562     // single (8 byte) or double (16 byte) stack slot.
7563     Address OverflowArgAreaPtr =
7564         CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr");
7565     Address OverflowArgArea =
7566       Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
7567               TyInfo.Align);
7568     Address MemAddr =
7569       CGF.Builder.CreateElementBitCast(OverflowArgArea, DirectTy, "mem_addr");
7570 
7571     // Update overflow_arg_area_ptr pointer
7572     llvm::Value *NewOverflowArgArea =
7573       CGF.Builder.CreateGEP(OverflowArgArea.getElementType(),
7574                             OverflowArgArea.getPointer(), PaddedSizeV,
7575                             "overflow_arg_area");
7576     CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
7577 
7578     return MemAddr;
7579   }
7580 
7581   assert(PaddedSize.getQuantity() == 8);
7582 
7583   unsigned MaxRegs, RegCountField, RegSaveIndex;
7584   CharUnits RegPadding;
7585   if (InFPRs) {
7586     MaxRegs = 4; // Maximum of 4 FPR arguments
7587     RegCountField = 1; // __fpr
7588     RegSaveIndex = 16; // save offset for f0
7589     RegPadding = CharUnits(); // floats are passed in the high bits of an FPR
7590   } else {
7591     MaxRegs = 5; // Maximum of 5 GPR arguments
7592     RegCountField = 0; // __gpr
7593     RegSaveIndex = 2; // save offset for r2
7594     RegPadding = Padding; // values are passed in the low bits of a GPR
7595   }
7596 
7597   Address RegCountPtr =
7598       CGF.Builder.CreateStructGEP(VAListAddr, RegCountField, "reg_count_ptr");
7599   llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
7600   llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
7601   llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
7602                                                  "fits_in_regs");
7603 
7604   llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
7605   llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
7606   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
7607   CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
7608 
7609   // Emit code to load the value if it was passed in registers.
7610   CGF.EmitBlock(InRegBlock);
7611 
7612   // Work out the address of an argument register.
7613   llvm::Value *ScaledRegCount =
7614     CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
7615   llvm::Value *RegBase =
7616     llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize.getQuantity()
7617                                       + RegPadding.getQuantity());
7618   llvm::Value *RegOffset =
7619     CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
7620   Address RegSaveAreaPtr =
7621       CGF.Builder.CreateStructGEP(VAListAddr, 3, "reg_save_area_ptr");
7622   llvm::Value *RegSaveArea =
7623     CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
7624   Address RawRegAddr(CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, RegOffset,
7625                                            "raw_reg_addr"),
7626                      PaddedSize);
7627   Address RegAddr =
7628     CGF.Builder.CreateElementBitCast(RawRegAddr, DirectTy, "reg_addr");
7629 
7630   // Update the register count
7631   llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
7632   llvm::Value *NewRegCount =
7633     CGF.Builder.CreateAdd(RegCount, One, "reg_count");
7634   CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
7635   CGF.EmitBranch(ContBlock);
7636 
7637   // Emit code to load the value if it was passed in memory.
7638   CGF.EmitBlock(InMemBlock);
7639 
7640   // Work out the address of a stack argument.
7641   Address OverflowArgAreaPtr =
7642       CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr");
7643   Address OverflowArgArea =
7644     Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
7645             PaddedSize);
7646   Address RawMemAddr =
7647     CGF.Builder.CreateConstByteGEP(OverflowArgArea, Padding, "raw_mem_addr");
7648   Address MemAddr =
7649     CGF.Builder.CreateElementBitCast(RawMemAddr, DirectTy, "mem_addr");
7650 
7651   // Update overflow_arg_area_ptr pointer
7652   llvm::Value *NewOverflowArgArea =
7653     CGF.Builder.CreateGEP(OverflowArgArea.getElementType(),
7654                           OverflowArgArea.getPointer(), PaddedSizeV,
7655                           "overflow_arg_area");
7656   CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
7657   CGF.EmitBranch(ContBlock);
7658 
7659   // Return the appropriate result.
7660   CGF.EmitBlock(ContBlock);
7661   Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
7662                                  MemAddr, InMemBlock, "va_arg.addr");
7663 
7664   if (IsIndirect)
7665     ResAddr = Address(CGF.Builder.CreateLoad(ResAddr, "indirect_arg"),
7666                       TyInfo.Align);
7667 
7668   return ResAddr;
7669 }
7670 
7671 ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
7672   if (RetTy->isVoidType())
7673     return ABIArgInfo::getIgnore();
7674   if (isVectorArgumentType(RetTy))
7675     return ABIArgInfo::getDirect();
7676   if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
7677     return getNaturalAlignIndirect(RetTy);
7678   return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
7679                                                : ABIArgInfo::getDirect());
7680 }
7681 
7682 ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
7683   // Handle the generic C++ ABI.
7684   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
7685     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
7686 
7687   // Integers and enums are extended to full register width.
7688   if (isPromotableIntegerTypeForABI(Ty))
7689     return ABIArgInfo::getExtend(Ty);
7690 
7691   // Handle vector types and vector-like structure types.  Note that
7692   // as opposed to float-like structure types, we do not allow any
7693   // padding for vector-like structures, so verify the sizes match.
7694   uint64_t Size = getContext().getTypeSize(Ty);
7695   QualType SingleElementTy = GetSingleElementType(Ty);
7696   if (isVectorArgumentType(SingleElementTy) &&
7697       getContext().getTypeSize(SingleElementTy) == Size)
7698     return ABIArgInfo::getDirect(CGT.ConvertType(SingleElementTy));
7699 
7700   // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
7701   if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
7702     return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
7703 
7704   // Handle small structures.
7705   if (const RecordType *RT = Ty->getAs<RecordType>()) {
7706     // Structures with flexible arrays have variable length, so really
7707     // fail the size test above.
7708     const RecordDecl *RD = RT->getDecl();
7709     if (RD->hasFlexibleArrayMember())
7710       return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
7711 
7712     // The structure is passed as an unextended integer, a float, or a double.
7713     llvm::Type *PassTy;
7714     if (isFPArgumentType(SingleElementTy)) {
7715       assert(Size == 32 || Size == 64);
7716       if (Size == 32)
7717         PassTy = llvm::Type::getFloatTy(getVMContext());
7718       else
7719         PassTy = llvm::Type::getDoubleTy(getVMContext());
7720     } else
7721       PassTy = llvm::IntegerType::get(getVMContext(), Size);
7722     return ABIArgInfo::getDirect(PassTy);
7723   }
7724 
7725   // Non-structure compounds are passed indirectly.
7726   if (isCompoundType(Ty))
7727     return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
7728 
7729   return ABIArgInfo::getDirect(nullptr);
7730 }
7731 
7732 //===----------------------------------------------------------------------===//
7733 // MSP430 ABI Implementation
7734 //===----------------------------------------------------------------------===//
7735 
7736 namespace {
7737 
7738 class MSP430ABIInfo : public DefaultABIInfo {
7739   static ABIArgInfo complexArgInfo() {
7740     ABIArgInfo Info = ABIArgInfo::getDirect();
7741     Info.setCanBeFlattened(false);
7742     return Info;
7743   }
7744 
7745 public:
7746   MSP430ABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
7747 
7748   ABIArgInfo classifyReturnType(QualType RetTy) const {
7749     if (RetTy->isAnyComplexType())
7750       return complexArgInfo();
7751 
7752     return DefaultABIInfo::classifyReturnType(RetTy);
7753   }
7754 
7755   ABIArgInfo classifyArgumentType(QualType RetTy) const {
7756     if (RetTy->isAnyComplexType())
7757       return complexArgInfo();
7758 
7759     return DefaultABIInfo::classifyArgumentType(RetTy);
7760   }
7761 
7762   // Just copy the original implementations because
7763   // DefaultABIInfo::classify{Return,Argument}Type() are not virtual
7764   void computeInfo(CGFunctionInfo &FI) const override {
7765     if (!getCXXABI().classifyReturnType(FI))
7766       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7767     for (auto &I : FI.arguments())
7768       I.info = classifyArgumentType(I.type);
7769   }
7770 
7771   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7772                     QualType Ty) const override {
7773     return EmitVAArgInstr(CGF, VAListAddr, Ty, classifyArgumentType(Ty));
7774   }
7775 };
7776 
7777 class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
7778 public:
7779   MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
7780       : TargetCodeGenInfo(std::make_unique<MSP430ABIInfo>(CGT)) {}
7781   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
7782                            CodeGen::CodeGenModule &M) const override;
7783 };
7784 
7785 }
7786 
7787 void MSP430TargetCodeGenInfo::setTargetAttributes(
7788     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
7789   if (GV->isDeclaration())
7790     return;
7791   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
7792     const auto *InterruptAttr = FD->getAttr<MSP430InterruptAttr>();
7793     if (!InterruptAttr)
7794       return;
7795 
7796     // Handle 'interrupt' attribute:
7797     llvm::Function *F = cast<llvm::Function>(GV);
7798 
7799     // Step 1: Set ISR calling convention.
7800     F->setCallingConv(llvm::CallingConv::MSP430_INTR);
7801 
7802     // Step 2: Add attributes goodness.
7803     F->addFnAttr(llvm::Attribute::NoInline);
7804     F->addFnAttr("interrupt", llvm::utostr(InterruptAttr->getNumber()));
7805   }
7806 }
7807 
7808 //===----------------------------------------------------------------------===//
7809 // MIPS ABI Implementation.  This works for both little-endian and
7810 // big-endian variants.
7811 //===----------------------------------------------------------------------===//
7812 
7813 namespace {
7814 class MipsABIInfo : public ABIInfo {
7815   bool IsO32;
7816   unsigned MinABIStackAlignInBytes, StackAlignInBytes;
7817   void CoerceToIntArgs(uint64_t TySize,
7818                        SmallVectorImpl<llvm::Type *> &ArgList) const;
7819   llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
7820   llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
7821   llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
7822 public:
7823   MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
7824     ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
7825     StackAlignInBytes(IsO32 ? 8 : 16) {}
7826 
7827   ABIArgInfo classifyReturnType(QualType RetTy) const;
7828   ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
7829   void computeInfo(CGFunctionInfo &FI) const override;
7830   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7831                     QualType Ty) const override;
7832   ABIArgInfo extendType(QualType Ty) const;
7833 };
7834 
7835 class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
7836   unsigned SizeOfUnwindException;
7837 public:
7838   MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
7839       : TargetCodeGenInfo(std::make_unique<MipsABIInfo>(CGT, IsO32)),
7840         SizeOfUnwindException(IsO32 ? 24 : 32) {}
7841 
7842   int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
7843     return 29;
7844   }
7845 
7846   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
7847                            CodeGen::CodeGenModule &CGM) const override {
7848     const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
7849     if (!FD) return;
7850     llvm::Function *Fn = cast<llvm::Function>(GV);
7851 
7852     if (FD->hasAttr<MipsLongCallAttr>())
7853       Fn->addFnAttr("long-call");
7854     else if (FD->hasAttr<MipsShortCallAttr>())
7855       Fn->addFnAttr("short-call");
7856 
7857     // Other attributes do not have a meaning for declarations.
7858     if (GV->isDeclaration())
7859       return;
7860 
7861     if (FD->hasAttr<Mips16Attr>()) {
7862       Fn->addFnAttr("mips16");
7863     }
7864     else if (FD->hasAttr<NoMips16Attr>()) {
7865       Fn->addFnAttr("nomips16");
7866     }
7867 
7868     if (FD->hasAttr<MicroMipsAttr>())
7869       Fn->addFnAttr("micromips");
7870     else if (FD->hasAttr<NoMicroMipsAttr>())
7871       Fn->addFnAttr("nomicromips");
7872 
7873     const MipsInterruptAttr *Attr = FD->getAttr<MipsInterruptAttr>();
7874     if (!Attr)
7875       return;
7876 
7877     const char *Kind;
7878     switch (Attr->getInterrupt()) {
7879     case MipsInterruptAttr::eic:     Kind = "eic"; break;
7880     case MipsInterruptAttr::sw0:     Kind = "sw0"; break;
7881     case MipsInterruptAttr::sw1:     Kind = "sw1"; break;
7882     case MipsInterruptAttr::hw0:     Kind = "hw0"; break;
7883     case MipsInterruptAttr::hw1:     Kind = "hw1"; break;
7884     case MipsInterruptAttr::hw2:     Kind = "hw2"; break;
7885     case MipsInterruptAttr::hw3:     Kind = "hw3"; break;
7886     case MipsInterruptAttr::hw4:     Kind = "hw4"; break;
7887     case MipsInterruptAttr::hw5:     Kind = "hw5"; break;
7888     }
7889 
7890     Fn->addFnAttr("interrupt", Kind);
7891 
7892   }
7893 
7894   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
7895                                llvm::Value *Address) const override;
7896 
7897   unsigned getSizeOfUnwindException() const override {
7898     return SizeOfUnwindException;
7899   }
7900 };
7901 }
7902 
7903 void MipsABIInfo::CoerceToIntArgs(
7904     uint64_t TySize, SmallVectorImpl<llvm::Type *> &ArgList) const {
7905   llvm::IntegerType *IntTy =
7906     llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
7907 
7908   // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
7909   for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
7910     ArgList.push_back(IntTy);
7911 
7912   // If necessary, add one more integer type to ArgList.
7913   unsigned R = TySize % (MinABIStackAlignInBytes * 8);
7914 
7915   if (R)
7916     ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
7917 }
7918 
7919 // In N32/64, an aligned double precision floating point field is passed in
7920 // a register.
7921 llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
7922   SmallVector<llvm::Type*, 8> ArgList, IntArgList;
7923 
7924   if (IsO32) {
7925     CoerceToIntArgs(TySize, ArgList);
7926     return llvm::StructType::get(getVMContext(), ArgList);
7927   }
7928 
7929   if (Ty->isComplexType())
7930     return CGT.ConvertType(Ty);
7931 
7932   const RecordType *RT = Ty->getAs<RecordType>();
7933 
7934   // Unions/vectors are passed in integer registers.
7935   if (!RT || !RT->isStructureOrClassType()) {
7936     CoerceToIntArgs(TySize, ArgList);
7937     return llvm::StructType::get(getVMContext(), ArgList);
7938   }
7939 
7940   const RecordDecl *RD = RT->getDecl();
7941   const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
7942   assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
7943 
7944   uint64_t LastOffset = 0;
7945   unsigned idx = 0;
7946   llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
7947 
7948   // Iterate over fields in the struct/class and check if there are any aligned
7949   // double fields.
7950   for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
7951        i != e; ++i, ++idx) {
7952     const QualType Ty = i->getType();
7953     const BuiltinType *BT = Ty->getAs<BuiltinType>();
7954 
7955     if (!BT || BT->getKind() != BuiltinType::Double)
7956       continue;
7957 
7958     uint64_t Offset = Layout.getFieldOffset(idx);
7959     if (Offset % 64) // Ignore doubles that are not aligned.
7960       continue;
7961 
7962     // Add ((Offset - LastOffset) / 64) args of type i64.
7963     for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
7964       ArgList.push_back(I64);
7965 
7966     // Add double type.
7967     ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
7968     LastOffset = Offset + 64;
7969   }
7970 
7971   CoerceToIntArgs(TySize - LastOffset, IntArgList);
7972   ArgList.append(IntArgList.begin(), IntArgList.end());
7973 
7974   return llvm::StructType::get(getVMContext(), ArgList);
7975 }
7976 
7977 llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
7978                                         uint64_t Offset) const {
7979   if (OrigOffset + MinABIStackAlignInBytes > Offset)
7980     return nullptr;
7981 
7982   return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
7983 }
7984 
7985 ABIArgInfo
7986 MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
7987   Ty = useFirstFieldIfTransparentUnion(Ty);
7988 
7989   uint64_t OrigOffset = Offset;
7990   uint64_t TySize = getContext().getTypeSize(Ty);
7991   uint64_t Align = getContext().getTypeAlign(Ty) / 8;
7992 
7993   Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
7994                    (uint64_t)StackAlignInBytes);
7995   unsigned CurrOffset = llvm::alignTo(Offset, Align);
7996   Offset = CurrOffset + llvm::alignTo(TySize, Align * 8) / 8;
7997 
7998   if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
7999     // Ignore empty aggregates.
8000     if (TySize == 0)
8001       return ABIArgInfo::getIgnore();
8002 
8003     if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
8004       Offset = OrigOffset + MinABIStackAlignInBytes;
8005       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
8006     }
8007 
8008     // If we have reached here, aggregates are passed directly by coercing to
8009     // another structure type. Padding is inserted if the offset of the
8010     // aggregate is unaligned.
8011     ABIArgInfo ArgInfo =
8012         ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
8013                               getPaddingType(OrigOffset, CurrOffset));
8014     ArgInfo.setInReg(true);
8015     return ArgInfo;
8016   }
8017 
8018   // Treat an enum type as its underlying type.
8019   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
8020     Ty = EnumTy->getDecl()->getIntegerType();
8021 
8022   // Make sure we pass indirectly things that are too large.
8023   if (const auto *EIT = Ty->getAs<BitIntType>())
8024     if (EIT->getNumBits() > 128 ||
8025         (EIT->getNumBits() > 64 &&
8026          !getContext().getTargetInfo().hasInt128Type()))
8027       return getNaturalAlignIndirect(Ty);
8028 
8029   // All integral types are promoted to the GPR width.
8030   if (Ty->isIntegralOrEnumerationType())
8031     return extendType(Ty);
8032 
8033   return ABIArgInfo::getDirect(
8034       nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset));
8035 }
8036 
8037 llvm::Type*
8038 MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
8039   const RecordType *RT = RetTy->getAs<RecordType>();
8040   SmallVector<llvm::Type*, 8> RTList;
8041 
8042   if (RT && RT->isStructureOrClassType()) {
8043     const RecordDecl *RD = RT->getDecl();
8044     const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
8045     unsigned FieldCnt = Layout.getFieldCount();
8046 
8047     // N32/64 returns struct/classes in floating point registers if the
8048     // following conditions are met:
8049     // 1. The size of the struct/class is no larger than 128-bit.
8050     // 2. The struct/class has one or two fields all of which are floating
8051     //    point types.
8052     // 3. The offset of the first field is zero (this follows what gcc does).
8053     //
8054     // Any other composite results are returned in integer registers.
8055     //
8056     if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
8057       RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
8058       for (; b != e; ++b) {
8059         const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
8060 
8061         if (!BT || !BT->isFloatingPoint())
8062           break;
8063 
8064         RTList.push_back(CGT.ConvertType(b->getType()));
8065       }
8066 
8067       if (b == e)
8068         return llvm::StructType::get(getVMContext(), RTList,
8069                                      RD->hasAttr<PackedAttr>());
8070 
8071       RTList.clear();
8072     }
8073   }
8074 
8075   CoerceToIntArgs(Size, RTList);
8076   return llvm::StructType::get(getVMContext(), RTList);
8077 }
8078 
8079 ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
8080   uint64_t Size = getContext().getTypeSize(RetTy);
8081 
8082   if (RetTy->isVoidType())
8083     return ABIArgInfo::getIgnore();
8084 
8085   // O32 doesn't treat zero-sized structs differently from other structs.
8086   // However, N32/N64 ignores zero sized return values.
8087   if (!IsO32 && Size == 0)
8088     return ABIArgInfo::getIgnore();
8089 
8090   if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
8091     if (Size <= 128) {
8092       if (RetTy->isAnyComplexType())
8093         return ABIArgInfo::getDirect();
8094 
8095       // O32 returns integer vectors in registers and N32/N64 returns all small
8096       // aggregates in registers.
8097       if (!IsO32 ||
8098           (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) {
8099         ABIArgInfo ArgInfo =
8100             ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
8101         ArgInfo.setInReg(true);
8102         return ArgInfo;
8103       }
8104     }
8105 
8106     return getNaturalAlignIndirect(RetTy);
8107   }
8108 
8109   // Treat an enum type as its underlying type.
8110   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
8111     RetTy = EnumTy->getDecl()->getIntegerType();
8112 
8113   // Make sure we pass indirectly things that are too large.
8114   if (const auto *EIT = RetTy->getAs<BitIntType>())
8115     if (EIT->getNumBits() > 128 ||
8116         (EIT->getNumBits() > 64 &&
8117          !getContext().getTargetInfo().hasInt128Type()))
8118       return getNaturalAlignIndirect(RetTy);
8119 
8120   if (isPromotableIntegerTypeForABI(RetTy))
8121     return ABIArgInfo::getExtend(RetTy);
8122 
8123   if ((RetTy->isUnsignedIntegerOrEnumerationType() ||
8124       RetTy->isSignedIntegerOrEnumerationType()) && Size == 32 && !IsO32)
8125     return ABIArgInfo::getSignExtend(RetTy);
8126 
8127   return ABIArgInfo::getDirect();
8128 }
8129 
8130 void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
8131   ABIArgInfo &RetInfo = FI.getReturnInfo();
8132   if (!getCXXABI().classifyReturnType(FI))
8133     RetInfo = classifyReturnType(FI.getReturnType());
8134 
8135   // Check if a pointer to an aggregate is passed as a hidden argument.
8136   uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
8137 
8138   for (auto &I : FI.arguments())
8139     I.info = classifyArgumentType(I.type, Offset);
8140 }
8141 
8142 Address MipsABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8143                                QualType OrigTy) const {
8144   QualType Ty = OrigTy;
8145 
8146   // Integer arguments are promoted to 32-bit on O32 and 64-bit on N32/N64.
8147   // Pointers are also promoted in the same way but this only matters for N32.
8148   unsigned SlotSizeInBits = IsO32 ? 32 : 64;
8149   unsigned PtrWidth = getTarget().getPointerWidth(0);
8150   bool DidPromote = false;
8151   if ((Ty->isIntegerType() &&
8152           getContext().getIntWidth(Ty) < SlotSizeInBits) ||
8153       (Ty->isPointerType() && PtrWidth < SlotSizeInBits)) {
8154     DidPromote = true;
8155     Ty = getContext().getIntTypeForBitwidth(SlotSizeInBits,
8156                                             Ty->isSignedIntegerType());
8157   }
8158 
8159   auto TyInfo = getContext().getTypeInfoInChars(Ty);
8160 
8161   // The alignment of things in the argument area is never larger than
8162   // StackAlignInBytes.
8163   TyInfo.Align =
8164     std::min(TyInfo.Align, CharUnits::fromQuantity(StackAlignInBytes));
8165 
8166   // MinABIStackAlignInBytes is the size of argument slots on the stack.
8167   CharUnits ArgSlotSize = CharUnits::fromQuantity(MinABIStackAlignInBytes);
8168 
8169   Address Addr = emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
8170                           TyInfo, ArgSlotSize, /*AllowHigherAlign*/ true);
8171 
8172 
8173   // If there was a promotion, "unpromote" into a temporary.
8174   // TODO: can we just use a pointer into a subset of the original slot?
8175   if (DidPromote) {
8176     Address Temp = CGF.CreateMemTemp(OrigTy, "vaarg.promotion-temp");
8177     llvm::Value *Promoted = CGF.Builder.CreateLoad(Addr);
8178 
8179     // Truncate down to the right width.
8180     llvm::Type *IntTy = (OrigTy->isIntegerType() ? Temp.getElementType()
8181                                                  : CGF.IntPtrTy);
8182     llvm::Value *V = CGF.Builder.CreateTrunc(Promoted, IntTy);
8183     if (OrigTy->isPointerType())
8184       V = CGF.Builder.CreateIntToPtr(V, Temp.getElementType());
8185 
8186     CGF.Builder.CreateStore(V, Temp);
8187     Addr = Temp;
8188   }
8189 
8190   return Addr;
8191 }
8192 
8193 ABIArgInfo MipsABIInfo::extendType(QualType Ty) const {
8194   int TySize = getContext().getTypeSize(Ty);
8195 
8196   // MIPS64 ABI requires unsigned 32 bit integers to be sign extended.
8197   if (Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
8198     return ABIArgInfo::getSignExtend(Ty);
8199 
8200   return ABIArgInfo::getExtend(Ty);
8201 }
8202 
8203 bool
8204 MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
8205                                                llvm::Value *Address) const {
8206   // This information comes from gcc's implementation, which seems to
8207   // as canonical as it gets.
8208 
8209   // Everything on MIPS is 4 bytes.  Double-precision FP registers
8210   // are aliased to pairs of single-precision FP registers.
8211   llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
8212 
8213   // 0-31 are the general purpose registers, $0 - $31.
8214   // 32-63 are the floating-point registers, $f0 - $f31.
8215   // 64 and 65 are the multiply/divide registers, $hi and $lo.
8216   // 66 is the (notional, I think) register for signal-handler return.
8217   AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
8218 
8219   // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
8220   // They are one bit wide and ignored here.
8221 
8222   // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
8223   // (coprocessor 1 is the FP unit)
8224   // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
8225   // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
8226   // 176-181 are the DSP accumulator registers.
8227   AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
8228   return false;
8229 }
8230 
8231 //===----------------------------------------------------------------------===//
8232 // M68k ABI Implementation
8233 //===----------------------------------------------------------------------===//
8234 
8235 namespace {
8236 
8237 class M68kTargetCodeGenInfo : public TargetCodeGenInfo {
8238 public:
8239   M68kTargetCodeGenInfo(CodeGenTypes &CGT)
8240       : TargetCodeGenInfo(std::make_unique<DefaultABIInfo>(CGT)) {}
8241   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
8242                            CodeGen::CodeGenModule &M) const override;
8243 };
8244 
8245 } // namespace
8246 
8247 void M68kTargetCodeGenInfo::setTargetAttributes(
8248     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
8249   if (const auto *FD = dyn_cast_or_null<FunctionDecl>(D)) {
8250     if (const auto *attr = FD->getAttr<M68kInterruptAttr>()) {
8251       // Handle 'interrupt' attribute:
8252       llvm::Function *F = cast<llvm::Function>(GV);
8253 
8254       // Step 1: Set ISR calling convention.
8255       F->setCallingConv(llvm::CallingConv::M68k_INTR);
8256 
8257       // Step 2: Add attributes goodness.
8258       F->addFnAttr(llvm::Attribute::NoInline);
8259 
8260       // Step 3: Emit ISR vector alias.
8261       unsigned Num = attr->getNumber() / 2;
8262       llvm::GlobalAlias::create(llvm::Function::ExternalLinkage,
8263                                 "__isr_" + Twine(Num), F);
8264     }
8265   }
8266 }
8267 
8268 //===----------------------------------------------------------------------===//
8269 // AVR ABI Implementation. Documented at
8270 // https://gcc.gnu.org/wiki/avr-gcc#Calling_Convention
8271 // https://gcc.gnu.org/wiki/avr-gcc#Reduced_Tiny
8272 //===----------------------------------------------------------------------===//
8273 
8274 namespace {
8275 class AVRABIInfo : public DefaultABIInfo {
8276 public:
8277   AVRABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
8278 
8279   ABIArgInfo classifyReturnType(QualType Ty) const {
8280     // A return struct with size less than or equal to 8 bytes is returned
8281     // directly via registers R18-R25.
8282     if (isAggregateTypeForABI(Ty) && getContext().getTypeSize(Ty) <= 64)
8283       return ABIArgInfo::getDirect();
8284     else
8285       return DefaultABIInfo::classifyReturnType(Ty);
8286   }
8287 
8288   // Just copy the original implementation of DefaultABIInfo::computeInfo(),
8289   // since DefaultABIInfo::classify{Return,Argument}Type() are not virtual.
8290   void computeInfo(CGFunctionInfo &FI) const override {
8291     if (!getCXXABI().classifyReturnType(FI))
8292       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
8293     for (auto &I : FI.arguments())
8294       I.info = classifyArgumentType(I.type);
8295   }
8296 };
8297 
8298 class AVRTargetCodeGenInfo : public TargetCodeGenInfo {
8299 public:
8300   AVRTargetCodeGenInfo(CodeGenTypes &CGT)
8301       : TargetCodeGenInfo(std::make_unique<AVRABIInfo>(CGT)) {}
8302 
8303   LangAS getGlobalVarAddressSpace(CodeGenModule &CGM,
8304                                   const VarDecl *D) const override {
8305     // Check if global/static variable is defined in address space
8306     // 1~6 (__flash, __flash1, __flash2, __flash3, __flash4, __flash5)
8307     // but not constant.
8308     if (D) {
8309       LangAS AS = D->getType().getAddressSpace();
8310       if (isTargetAddressSpace(AS) && 1 <= toTargetAddressSpace(AS) &&
8311           toTargetAddressSpace(AS) <= 6 && !D->getType().isConstQualified())
8312         CGM.getDiags().Report(D->getLocation(),
8313                               diag::err_verify_nonconst_addrspace)
8314             << "__flash*";
8315     }
8316     return TargetCodeGenInfo::getGlobalVarAddressSpace(CGM, D);
8317   }
8318 
8319   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
8320                            CodeGen::CodeGenModule &CGM) const override {
8321     if (GV->isDeclaration())
8322       return;
8323     const auto *FD = dyn_cast_or_null<FunctionDecl>(D);
8324     if (!FD) return;
8325     auto *Fn = cast<llvm::Function>(GV);
8326 
8327     if (FD->getAttr<AVRInterruptAttr>())
8328       Fn->addFnAttr("interrupt");
8329 
8330     if (FD->getAttr<AVRSignalAttr>())
8331       Fn->addFnAttr("signal");
8332   }
8333 };
8334 }
8335 
8336 //===----------------------------------------------------------------------===//
8337 // TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
8338 // Currently subclassed only to implement custom OpenCL C function attribute
8339 // handling.
8340 //===----------------------------------------------------------------------===//
8341 
8342 namespace {
8343 
8344 class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
8345 public:
8346   TCETargetCodeGenInfo(CodeGenTypes &CGT)
8347     : DefaultTargetCodeGenInfo(CGT) {}
8348 
8349   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
8350                            CodeGen::CodeGenModule &M) const override;
8351 };
8352 
8353 void TCETargetCodeGenInfo::setTargetAttributes(
8354     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
8355   if (GV->isDeclaration())
8356     return;
8357   const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
8358   if (!FD) return;
8359 
8360   llvm::Function *F = cast<llvm::Function>(GV);
8361 
8362   if (M.getLangOpts().OpenCL) {
8363     if (FD->hasAttr<OpenCLKernelAttr>()) {
8364       // OpenCL C Kernel functions are not subject to inlining
8365       F->addFnAttr(llvm::Attribute::NoInline);
8366       const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
8367       if (Attr) {
8368         // Convert the reqd_work_group_size() attributes to metadata.
8369         llvm::LLVMContext &Context = F->getContext();
8370         llvm::NamedMDNode *OpenCLMetadata =
8371             M.getModule().getOrInsertNamedMetadata(
8372                 "opencl.kernel_wg_size_info");
8373 
8374         SmallVector<llvm::Metadata *, 5> Operands;
8375         Operands.push_back(llvm::ConstantAsMetadata::get(F));
8376 
8377         Operands.push_back(
8378             llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
8379                 M.Int32Ty, llvm::APInt(32, Attr->getXDim()))));
8380         Operands.push_back(
8381             llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
8382                 M.Int32Ty, llvm::APInt(32, Attr->getYDim()))));
8383         Operands.push_back(
8384             llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
8385                 M.Int32Ty, llvm::APInt(32, Attr->getZDim()))));
8386 
8387         // Add a boolean constant operand for "required" (true) or "hint"
8388         // (false) for implementing the work_group_size_hint attr later.
8389         // Currently always true as the hint is not yet implemented.
8390         Operands.push_back(
8391             llvm::ConstantAsMetadata::get(llvm::ConstantInt::getTrue(Context)));
8392         OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
8393       }
8394     }
8395   }
8396 }
8397 
8398 }
8399 
8400 //===----------------------------------------------------------------------===//
8401 // Hexagon ABI Implementation
8402 //===----------------------------------------------------------------------===//
8403 
8404 namespace {
8405 
8406 class HexagonABIInfo : public DefaultABIInfo {
8407 public:
8408   HexagonABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
8409 
8410 private:
8411   ABIArgInfo classifyReturnType(QualType RetTy) const;
8412   ABIArgInfo classifyArgumentType(QualType RetTy) const;
8413   ABIArgInfo classifyArgumentType(QualType RetTy, unsigned *RegsLeft) const;
8414 
8415   void computeInfo(CGFunctionInfo &FI) const override;
8416 
8417   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8418                     QualType Ty) const override;
8419   Address EmitVAArgFromMemory(CodeGenFunction &CFG, Address VAListAddr,
8420                               QualType Ty) const;
8421   Address EmitVAArgForHexagon(CodeGenFunction &CFG, Address VAListAddr,
8422                               QualType Ty) const;
8423   Address EmitVAArgForHexagonLinux(CodeGenFunction &CFG, Address VAListAddr,
8424                                    QualType Ty) const;
8425 };
8426 
8427 class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
8428 public:
8429   HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
8430       : TargetCodeGenInfo(std::make_unique<HexagonABIInfo>(CGT)) {}
8431 
8432   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
8433     return 29;
8434   }
8435 
8436   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
8437                            CodeGen::CodeGenModule &GCM) const override {
8438     if (GV->isDeclaration())
8439       return;
8440     const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
8441     if (!FD)
8442       return;
8443   }
8444 };
8445 
8446 } // namespace
8447 
8448 void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
8449   unsigned RegsLeft = 6;
8450   if (!getCXXABI().classifyReturnType(FI))
8451     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
8452   for (auto &I : FI.arguments())
8453     I.info = classifyArgumentType(I.type, &RegsLeft);
8454 }
8455 
8456 static bool HexagonAdjustRegsLeft(uint64_t Size, unsigned *RegsLeft) {
8457   assert(Size <= 64 && "Not expecting to pass arguments larger than 64 bits"
8458                        " through registers");
8459 
8460   if (*RegsLeft == 0)
8461     return false;
8462 
8463   if (Size <= 32) {
8464     (*RegsLeft)--;
8465     return true;
8466   }
8467 
8468   if (2 <= (*RegsLeft & (~1U))) {
8469     *RegsLeft = (*RegsLeft & (~1U)) - 2;
8470     return true;
8471   }
8472 
8473   // Next available register was r5 but candidate was greater than 32-bits so it
8474   // has to go on the stack. However we still consume r5
8475   if (*RegsLeft == 1)
8476     *RegsLeft = 0;
8477 
8478   return false;
8479 }
8480 
8481 ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty,
8482                                                 unsigned *RegsLeft) const {
8483   if (!isAggregateTypeForABI(Ty)) {
8484     // Treat an enum type as its underlying type.
8485     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
8486       Ty = EnumTy->getDecl()->getIntegerType();
8487 
8488     uint64_t Size = getContext().getTypeSize(Ty);
8489     if (Size <= 64)
8490       HexagonAdjustRegsLeft(Size, RegsLeft);
8491 
8492     if (Size > 64 && Ty->isBitIntType())
8493       return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
8494 
8495     return isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
8496                                              : ABIArgInfo::getDirect();
8497   }
8498 
8499   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
8500     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
8501 
8502   // Ignore empty records.
8503   if (isEmptyRecord(getContext(), Ty, true))
8504     return ABIArgInfo::getIgnore();
8505 
8506   uint64_t Size = getContext().getTypeSize(Ty);
8507   unsigned Align = getContext().getTypeAlign(Ty);
8508 
8509   if (Size > 64)
8510     return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
8511 
8512   if (HexagonAdjustRegsLeft(Size, RegsLeft))
8513     Align = Size <= 32 ? 32 : 64;
8514   if (Size <= Align) {
8515     // Pass in the smallest viable integer type.
8516     if (!llvm::isPowerOf2_64(Size))
8517       Size = llvm::NextPowerOf2(Size);
8518     return ABIArgInfo::getDirect(llvm::Type::getIntNTy(getVMContext(), Size));
8519   }
8520   return DefaultABIInfo::classifyArgumentType(Ty);
8521 }
8522 
8523 ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
8524   if (RetTy->isVoidType())
8525     return ABIArgInfo::getIgnore();
8526 
8527   const TargetInfo &T = CGT.getTarget();
8528   uint64_t Size = getContext().getTypeSize(RetTy);
8529 
8530   if (RetTy->getAs<VectorType>()) {
8531     // HVX vectors are returned in vector registers or register pairs.
8532     if (T.hasFeature("hvx")) {
8533       assert(T.hasFeature("hvx-length64b") || T.hasFeature("hvx-length128b"));
8534       uint64_t VecSize = T.hasFeature("hvx-length64b") ? 64*8 : 128*8;
8535       if (Size == VecSize || Size == 2*VecSize)
8536         return ABIArgInfo::getDirectInReg();
8537     }
8538     // Large vector types should be returned via memory.
8539     if (Size > 64)
8540       return getNaturalAlignIndirect(RetTy);
8541   }
8542 
8543   if (!isAggregateTypeForABI(RetTy)) {
8544     // Treat an enum type as its underlying type.
8545     if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
8546       RetTy = EnumTy->getDecl()->getIntegerType();
8547 
8548     if (Size > 64 && RetTy->isBitIntType())
8549       return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
8550 
8551     return isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
8552                                                 : ABIArgInfo::getDirect();
8553   }
8554 
8555   if (isEmptyRecord(getContext(), RetTy, true))
8556     return ABIArgInfo::getIgnore();
8557 
8558   // Aggregates <= 8 bytes are returned in registers, other aggregates
8559   // are returned indirectly.
8560   if (Size <= 64) {
8561     // Return in the smallest viable integer type.
8562     if (!llvm::isPowerOf2_64(Size))
8563       Size = llvm::NextPowerOf2(Size);
8564     return ABIArgInfo::getDirect(llvm::Type::getIntNTy(getVMContext(), Size));
8565   }
8566   return getNaturalAlignIndirect(RetTy, /*ByVal=*/true);
8567 }
8568 
8569 Address HexagonABIInfo::EmitVAArgFromMemory(CodeGenFunction &CGF,
8570                                             Address VAListAddr,
8571                                             QualType Ty) const {
8572   // Load the overflow area pointer.
8573   Address __overflow_area_pointer_p =
8574       CGF.Builder.CreateStructGEP(VAListAddr, 2, "__overflow_area_pointer_p");
8575   llvm::Value *__overflow_area_pointer = CGF.Builder.CreateLoad(
8576       __overflow_area_pointer_p, "__overflow_area_pointer");
8577 
8578   uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8;
8579   if (Align > 4) {
8580     // Alignment should be a power of 2.
8581     assert((Align & (Align - 1)) == 0 && "Alignment is not power of 2!");
8582 
8583     // overflow_arg_area = (overflow_arg_area + align - 1) & -align;
8584     llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int64Ty, Align - 1);
8585 
8586     // Add offset to the current pointer to access the argument.
8587     __overflow_area_pointer =
8588         CGF.Builder.CreateGEP(CGF.Int8Ty, __overflow_area_pointer, Offset);
8589     llvm::Value *AsInt =
8590         CGF.Builder.CreatePtrToInt(__overflow_area_pointer, CGF.Int32Ty);
8591 
8592     // Create a mask which should be "AND"ed
8593     // with (overflow_arg_area + align - 1)
8594     llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int32Ty, -(int)Align);
8595     __overflow_area_pointer = CGF.Builder.CreateIntToPtr(
8596         CGF.Builder.CreateAnd(AsInt, Mask), __overflow_area_pointer->getType(),
8597         "__overflow_area_pointer.align");
8598   }
8599 
8600   // Get the type of the argument from memory and bitcast
8601   // overflow area pointer to the argument type.
8602   llvm::Type *PTy = CGF.ConvertTypeForMem(Ty);
8603   Address AddrTyped = CGF.Builder.CreateElementBitCast(
8604       Address(__overflow_area_pointer, CharUnits::fromQuantity(Align)), PTy);
8605 
8606   // Round up to the minimum stack alignment for varargs which is 4 bytes.
8607   uint64_t Offset = llvm::alignTo(CGF.getContext().getTypeSize(Ty) / 8, 4);
8608 
8609   __overflow_area_pointer = CGF.Builder.CreateGEP(
8610       CGF.Int8Ty, __overflow_area_pointer,
8611       llvm::ConstantInt::get(CGF.Int32Ty, Offset),
8612       "__overflow_area_pointer.next");
8613   CGF.Builder.CreateStore(__overflow_area_pointer, __overflow_area_pointer_p);
8614 
8615   return AddrTyped;
8616 }
8617 
8618 Address HexagonABIInfo::EmitVAArgForHexagon(CodeGenFunction &CGF,
8619                                             Address VAListAddr,
8620                                             QualType Ty) const {
8621   // FIXME: Need to handle alignment
8622   llvm::Type *BP = CGF.Int8PtrTy;
8623   CGBuilderTy &Builder = CGF.Builder;
8624   Address VAListAddrAsBPP = Builder.CreateElementBitCast(VAListAddr, BP, "ap");
8625   llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
8626   // Handle address alignment for type alignment > 32 bits
8627   uint64_t TyAlign = CGF.getContext().getTypeAlign(Ty) / 8;
8628   if (TyAlign > 4) {
8629     assert((TyAlign & (TyAlign - 1)) == 0 && "Alignment is not power of 2!");
8630     llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int32Ty);
8631     AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt32(TyAlign - 1));
8632     AddrAsInt = Builder.CreateAnd(AddrAsInt, Builder.getInt32(~(TyAlign - 1)));
8633     Addr = Builder.CreateIntToPtr(AddrAsInt, BP);
8634   }
8635   Address AddrTyped = Builder.CreateElementBitCast(
8636       Address(Addr, CharUnits::fromQuantity(TyAlign)), CGF.ConvertType(Ty));
8637 
8638   uint64_t Offset = llvm::alignTo(CGF.getContext().getTypeSize(Ty) / 8, 4);
8639   llvm::Value *NextAddr = Builder.CreateGEP(
8640       CGF.Int8Ty, Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset), "ap.next");
8641   Builder.CreateStore(NextAddr, VAListAddrAsBPP);
8642 
8643   return AddrTyped;
8644 }
8645 
8646 Address HexagonABIInfo::EmitVAArgForHexagonLinux(CodeGenFunction &CGF,
8647                                                  Address VAListAddr,
8648                                                  QualType Ty) const {
8649   int ArgSize = CGF.getContext().getTypeSize(Ty) / 8;
8650 
8651   if (ArgSize > 8)
8652     return EmitVAArgFromMemory(CGF, VAListAddr, Ty);
8653 
8654   // Here we have check if the argument is in register area or
8655   // in overflow area.
8656   // If the saved register area pointer + argsize rounded up to alignment >
8657   // saved register area end pointer, argument is in overflow area.
8658   unsigned RegsLeft = 6;
8659   Ty = CGF.getContext().getCanonicalType(Ty);
8660   (void)classifyArgumentType(Ty, &RegsLeft);
8661 
8662   llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
8663   llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
8664   llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
8665   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
8666 
8667   // Get rounded size of the argument.GCC does not allow vararg of
8668   // size < 4 bytes. We follow the same logic here.
8669   ArgSize = (CGF.getContext().getTypeSize(Ty) <= 32) ? 4 : 8;
8670   int ArgAlign = (CGF.getContext().getTypeSize(Ty) <= 32) ? 4 : 8;
8671 
8672   // Argument may be in saved register area
8673   CGF.EmitBlock(MaybeRegBlock);
8674 
8675   // Load the current saved register area pointer.
8676   Address __current_saved_reg_area_pointer_p = CGF.Builder.CreateStructGEP(
8677       VAListAddr, 0, "__current_saved_reg_area_pointer_p");
8678   llvm::Value *__current_saved_reg_area_pointer = CGF.Builder.CreateLoad(
8679       __current_saved_reg_area_pointer_p, "__current_saved_reg_area_pointer");
8680 
8681   // Load the saved register area end pointer.
8682   Address __saved_reg_area_end_pointer_p = CGF.Builder.CreateStructGEP(
8683       VAListAddr, 1, "__saved_reg_area_end_pointer_p");
8684   llvm::Value *__saved_reg_area_end_pointer = CGF.Builder.CreateLoad(
8685       __saved_reg_area_end_pointer_p, "__saved_reg_area_end_pointer");
8686 
8687   // If the size of argument is > 4 bytes, check if the stack
8688   // location is aligned to 8 bytes
8689   if (ArgAlign > 4) {
8690 
8691     llvm::Value *__current_saved_reg_area_pointer_int =
8692         CGF.Builder.CreatePtrToInt(__current_saved_reg_area_pointer,
8693                                    CGF.Int32Ty);
8694 
8695     __current_saved_reg_area_pointer_int = CGF.Builder.CreateAdd(
8696         __current_saved_reg_area_pointer_int,
8697         llvm::ConstantInt::get(CGF.Int32Ty, (ArgAlign - 1)),
8698         "align_current_saved_reg_area_pointer");
8699 
8700     __current_saved_reg_area_pointer_int =
8701         CGF.Builder.CreateAnd(__current_saved_reg_area_pointer_int,
8702                               llvm::ConstantInt::get(CGF.Int32Ty, -ArgAlign),
8703                               "align_current_saved_reg_area_pointer");
8704 
8705     __current_saved_reg_area_pointer =
8706         CGF.Builder.CreateIntToPtr(__current_saved_reg_area_pointer_int,
8707                                    __current_saved_reg_area_pointer->getType(),
8708                                    "align_current_saved_reg_area_pointer");
8709   }
8710 
8711   llvm::Value *__new_saved_reg_area_pointer =
8712       CGF.Builder.CreateGEP(CGF.Int8Ty, __current_saved_reg_area_pointer,
8713                             llvm::ConstantInt::get(CGF.Int32Ty, ArgSize),
8714                             "__new_saved_reg_area_pointer");
8715 
8716   llvm::Value *UsingStack = nullptr;
8717   UsingStack = CGF.Builder.CreateICmpSGT(__new_saved_reg_area_pointer,
8718                                          __saved_reg_area_end_pointer);
8719 
8720   CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, InRegBlock);
8721 
8722   // Argument in saved register area
8723   // Implement the block where argument is in register saved area
8724   CGF.EmitBlock(InRegBlock);
8725 
8726   llvm::Type *PTy = CGF.ConvertType(Ty);
8727   llvm::Value *__saved_reg_area_p = CGF.Builder.CreateBitCast(
8728       __current_saved_reg_area_pointer, llvm::PointerType::getUnqual(PTy));
8729 
8730   CGF.Builder.CreateStore(__new_saved_reg_area_pointer,
8731                           __current_saved_reg_area_pointer_p);
8732 
8733   CGF.EmitBranch(ContBlock);
8734 
8735   // Argument in overflow area
8736   // Implement the block where the argument is in overflow area.
8737   CGF.EmitBlock(OnStackBlock);
8738 
8739   // Load the overflow area pointer
8740   Address __overflow_area_pointer_p =
8741       CGF.Builder.CreateStructGEP(VAListAddr, 2, "__overflow_area_pointer_p");
8742   llvm::Value *__overflow_area_pointer = CGF.Builder.CreateLoad(
8743       __overflow_area_pointer_p, "__overflow_area_pointer");
8744 
8745   // Align the overflow area pointer according to the alignment of the argument
8746   if (ArgAlign > 4) {
8747     llvm::Value *__overflow_area_pointer_int =
8748         CGF.Builder.CreatePtrToInt(__overflow_area_pointer, CGF.Int32Ty);
8749 
8750     __overflow_area_pointer_int =
8751         CGF.Builder.CreateAdd(__overflow_area_pointer_int,
8752                               llvm::ConstantInt::get(CGF.Int32Ty, ArgAlign - 1),
8753                               "align_overflow_area_pointer");
8754 
8755     __overflow_area_pointer_int =
8756         CGF.Builder.CreateAnd(__overflow_area_pointer_int,
8757                               llvm::ConstantInt::get(CGF.Int32Ty, -ArgAlign),
8758                               "align_overflow_area_pointer");
8759 
8760     __overflow_area_pointer = CGF.Builder.CreateIntToPtr(
8761         __overflow_area_pointer_int, __overflow_area_pointer->getType(),
8762         "align_overflow_area_pointer");
8763   }
8764 
8765   // Get the pointer for next argument in overflow area and store it
8766   // to overflow area pointer.
8767   llvm::Value *__new_overflow_area_pointer = CGF.Builder.CreateGEP(
8768       CGF.Int8Ty, __overflow_area_pointer,
8769       llvm::ConstantInt::get(CGF.Int32Ty, ArgSize),
8770       "__overflow_area_pointer.next");
8771 
8772   CGF.Builder.CreateStore(__new_overflow_area_pointer,
8773                           __overflow_area_pointer_p);
8774 
8775   CGF.Builder.CreateStore(__new_overflow_area_pointer,
8776                           __current_saved_reg_area_pointer_p);
8777 
8778   // Bitcast the overflow area pointer to the type of argument.
8779   llvm::Type *OverflowPTy = CGF.ConvertTypeForMem(Ty);
8780   llvm::Value *__overflow_area_p = CGF.Builder.CreateBitCast(
8781       __overflow_area_pointer, llvm::PointerType::getUnqual(OverflowPTy));
8782 
8783   CGF.EmitBranch(ContBlock);
8784 
8785   // Get the correct pointer to load the variable argument
8786   // Implement the ContBlock
8787   CGF.EmitBlock(ContBlock);
8788 
8789   llvm::Type *MemPTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
8790   llvm::PHINode *ArgAddr = CGF.Builder.CreatePHI(MemPTy, 2, "vaarg.addr");
8791   ArgAddr->addIncoming(__saved_reg_area_p, InRegBlock);
8792   ArgAddr->addIncoming(__overflow_area_p, OnStackBlock);
8793 
8794   return Address(ArgAddr, CharUnits::fromQuantity(ArgAlign));
8795 }
8796 
8797 Address HexagonABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8798                                   QualType Ty) const {
8799 
8800   if (getTarget().getTriple().isMusl())
8801     return EmitVAArgForHexagonLinux(CGF, VAListAddr, Ty);
8802 
8803   return EmitVAArgForHexagon(CGF, VAListAddr, Ty);
8804 }
8805 
8806 //===----------------------------------------------------------------------===//
8807 // Lanai ABI Implementation
8808 //===----------------------------------------------------------------------===//
8809 
8810 namespace {
8811 class LanaiABIInfo : public DefaultABIInfo {
8812 public:
8813   LanaiABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
8814 
8815   bool shouldUseInReg(QualType Ty, CCState &State) const;
8816 
8817   void computeInfo(CGFunctionInfo &FI) const override {
8818     CCState State(FI);
8819     // Lanai uses 4 registers to pass arguments unless the function has the
8820     // regparm attribute set.
8821     if (FI.getHasRegParm()) {
8822       State.FreeRegs = FI.getRegParm();
8823     } else {
8824       State.FreeRegs = 4;
8825     }
8826 
8827     if (!getCXXABI().classifyReturnType(FI))
8828       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
8829     for (auto &I : FI.arguments())
8830       I.info = classifyArgumentType(I.type, State);
8831   }
8832 
8833   ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
8834   ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
8835 };
8836 } // end anonymous namespace
8837 
8838 bool LanaiABIInfo::shouldUseInReg(QualType Ty, CCState &State) const {
8839   unsigned Size = getContext().getTypeSize(Ty);
8840   unsigned SizeInRegs = llvm::alignTo(Size, 32U) / 32U;
8841 
8842   if (SizeInRegs == 0)
8843     return false;
8844 
8845   if (SizeInRegs > State.FreeRegs) {
8846     State.FreeRegs = 0;
8847     return false;
8848   }
8849 
8850   State.FreeRegs -= SizeInRegs;
8851 
8852   return true;
8853 }
8854 
8855 ABIArgInfo LanaiABIInfo::getIndirectResult(QualType Ty, bool ByVal,
8856                                            CCState &State) const {
8857   if (!ByVal) {
8858     if (State.FreeRegs) {
8859       --State.FreeRegs; // Non-byval indirects just use one pointer.
8860       return getNaturalAlignIndirectInReg(Ty);
8861     }
8862     return getNaturalAlignIndirect(Ty, false);
8863   }
8864 
8865   // Compute the byval alignment.
8866   const unsigned MinABIStackAlignInBytes = 4;
8867   unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
8868   return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true,
8869                                  /*Realign=*/TypeAlign >
8870                                      MinABIStackAlignInBytes);
8871 }
8872 
8873 ABIArgInfo LanaiABIInfo::classifyArgumentType(QualType Ty,
8874                                               CCState &State) const {
8875   // Check with the C++ ABI first.
8876   const RecordType *RT = Ty->getAs<RecordType>();
8877   if (RT) {
8878     CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
8879     if (RAA == CGCXXABI::RAA_Indirect) {
8880       return getIndirectResult(Ty, /*ByVal=*/false, State);
8881     } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
8882       return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
8883     }
8884   }
8885 
8886   if (isAggregateTypeForABI(Ty)) {
8887     // Structures with flexible arrays are always indirect.
8888     if (RT && RT->getDecl()->hasFlexibleArrayMember())
8889       return getIndirectResult(Ty, /*ByVal=*/true, State);
8890 
8891     // Ignore empty structs/unions.
8892     if (isEmptyRecord(getContext(), Ty, true))
8893       return ABIArgInfo::getIgnore();
8894 
8895     llvm::LLVMContext &LLVMContext = getVMContext();
8896     unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
8897     if (SizeInRegs <= State.FreeRegs) {
8898       llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
8899       SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32);
8900       llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
8901       State.FreeRegs -= SizeInRegs;
8902       return ABIArgInfo::getDirectInReg(Result);
8903     } else {
8904       State.FreeRegs = 0;
8905     }
8906     return getIndirectResult(Ty, true, State);
8907   }
8908 
8909   // Treat an enum type as its underlying type.
8910   if (const auto *EnumTy = Ty->getAs<EnumType>())
8911     Ty = EnumTy->getDecl()->getIntegerType();
8912 
8913   bool InReg = shouldUseInReg(Ty, State);
8914 
8915   // Don't pass >64 bit integers in registers.
8916   if (const auto *EIT = Ty->getAs<BitIntType>())
8917     if (EIT->getNumBits() > 64)
8918       return getIndirectResult(Ty, /*ByVal=*/true, State);
8919 
8920   if (isPromotableIntegerTypeForABI(Ty)) {
8921     if (InReg)
8922       return ABIArgInfo::getDirectInReg();
8923     return ABIArgInfo::getExtend(Ty);
8924   }
8925   if (InReg)
8926     return ABIArgInfo::getDirectInReg();
8927   return ABIArgInfo::getDirect();
8928 }
8929 
8930 namespace {
8931 class LanaiTargetCodeGenInfo : public TargetCodeGenInfo {
8932 public:
8933   LanaiTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
8934       : TargetCodeGenInfo(std::make_unique<LanaiABIInfo>(CGT)) {}
8935 };
8936 }
8937 
8938 //===----------------------------------------------------------------------===//
8939 // AMDGPU ABI Implementation
8940 //===----------------------------------------------------------------------===//
8941 
8942 namespace {
8943 
8944 class AMDGPUABIInfo final : public DefaultABIInfo {
8945 private:
8946   static const unsigned MaxNumRegsForArgsRet = 16;
8947 
8948   unsigned numRegsForType(QualType Ty) const;
8949 
8950   bool isHomogeneousAggregateBaseType(QualType Ty) const override;
8951   bool isHomogeneousAggregateSmallEnough(const Type *Base,
8952                                          uint64_t Members) const override;
8953 
8954   // Coerce HIP scalar pointer arguments from generic pointers to global ones.
8955   llvm::Type *coerceKernelArgumentType(llvm::Type *Ty, unsigned FromAS,
8956                                        unsigned ToAS) const {
8957     // Single value types.
8958     auto *PtrTy = llvm::dyn_cast<llvm::PointerType>(Ty);
8959     if (PtrTy && PtrTy->getAddressSpace() == FromAS)
8960       return llvm::PointerType::getWithSamePointeeType(PtrTy, ToAS);
8961     return Ty;
8962   }
8963 
8964 public:
8965   explicit AMDGPUABIInfo(CodeGen::CodeGenTypes &CGT) :
8966     DefaultABIInfo(CGT) {}
8967 
8968   ABIArgInfo classifyReturnType(QualType RetTy) const;
8969   ABIArgInfo classifyKernelArgumentType(QualType Ty) const;
8970   ABIArgInfo classifyArgumentType(QualType Ty, unsigned &NumRegsLeft) const;
8971 
8972   void computeInfo(CGFunctionInfo &FI) const override;
8973   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8974                     QualType Ty) const override;
8975 };
8976 
8977 bool AMDGPUABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
8978   return true;
8979 }
8980 
8981 bool AMDGPUABIInfo::isHomogeneousAggregateSmallEnough(
8982   const Type *Base, uint64_t Members) const {
8983   uint32_t NumRegs = (getContext().getTypeSize(Base) + 31) / 32;
8984 
8985   // Homogeneous Aggregates may occupy at most 16 registers.
8986   return Members * NumRegs <= MaxNumRegsForArgsRet;
8987 }
8988 
8989 /// Estimate number of registers the type will use when passed in registers.
8990 unsigned AMDGPUABIInfo::numRegsForType(QualType Ty) const {
8991   unsigned NumRegs = 0;
8992 
8993   if (const VectorType *VT = Ty->getAs<VectorType>()) {
8994     // Compute from the number of elements. The reported size is based on the
8995     // in-memory size, which includes the padding 4th element for 3-vectors.
8996     QualType EltTy = VT->getElementType();
8997     unsigned EltSize = getContext().getTypeSize(EltTy);
8998 
8999     // 16-bit element vectors should be passed as packed.
9000     if (EltSize == 16)
9001       return (VT->getNumElements() + 1) / 2;
9002 
9003     unsigned EltNumRegs = (EltSize + 31) / 32;
9004     return EltNumRegs * VT->getNumElements();
9005   }
9006 
9007   if (const RecordType *RT = Ty->getAs<RecordType>()) {
9008     const RecordDecl *RD = RT->getDecl();
9009     assert(!RD->hasFlexibleArrayMember());
9010 
9011     for (const FieldDecl *Field : RD->fields()) {
9012       QualType FieldTy = Field->getType();
9013       NumRegs += numRegsForType(FieldTy);
9014     }
9015 
9016     return NumRegs;
9017   }
9018 
9019   return (getContext().getTypeSize(Ty) + 31) / 32;
9020 }
9021 
9022 void AMDGPUABIInfo::computeInfo(CGFunctionInfo &FI) const {
9023   llvm::CallingConv::ID CC = FI.getCallingConvention();
9024 
9025   if (!getCXXABI().classifyReturnType(FI))
9026     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
9027 
9028   unsigned NumRegsLeft = MaxNumRegsForArgsRet;
9029   for (auto &Arg : FI.arguments()) {
9030     if (CC == llvm::CallingConv::AMDGPU_KERNEL) {
9031       Arg.info = classifyKernelArgumentType(Arg.type);
9032     } else {
9033       Arg.info = classifyArgumentType(Arg.type, NumRegsLeft);
9034     }
9035   }
9036 }
9037 
9038 Address AMDGPUABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9039                                  QualType Ty) const {
9040   llvm_unreachable("AMDGPU does not support varargs");
9041 }
9042 
9043 ABIArgInfo AMDGPUABIInfo::classifyReturnType(QualType RetTy) const {
9044   if (isAggregateTypeForABI(RetTy)) {
9045     // Records with non-trivial destructors/copy-constructors should not be
9046     // returned by value.
9047     if (!getRecordArgABI(RetTy, getCXXABI())) {
9048       // Ignore empty structs/unions.
9049       if (isEmptyRecord(getContext(), RetTy, true))
9050         return ABIArgInfo::getIgnore();
9051 
9052       // Lower single-element structs to just return a regular value.
9053       if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
9054         return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
9055 
9056       if (const RecordType *RT = RetTy->getAs<RecordType>()) {
9057         const RecordDecl *RD = RT->getDecl();
9058         if (RD->hasFlexibleArrayMember())
9059           return DefaultABIInfo::classifyReturnType(RetTy);
9060       }
9061 
9062       // Pack aggregates <= 4 bytes into single VGPR or pair.
9063       uint64_t Size = getContext().getTypeSize(RetTy);
9064       if (Size <= 16)
9065         return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
9066 
9067       if (Size <= 32)
9068         return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
9069 
9070       if (Size <= 64) {
9071         llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext());
9072         return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2));
9073       }
9074 
9075       if (numRegsForType(RetTy) <= MaxNumRegsForArgsRet)
9076         return ABIArgInfo::getDirect();
9077     }
9078   }
9079 
9080   // Otherwise just do the default thing.
9081   return DefaultABIInfo::classifyReturnType(RetTy);
9082 }
9083 
9084 /// For kernels all parameters are really passed in a special buffer. It doesn't
9085 /// make sense to pass anything byval, so everything must be direct.
9086 ABIArgInfo AMDGPUABIInfo::classifyKernelArgumentType(QualType Ty) const {
9087   Ty = useFirstFieldIfTransparentUnion(Ty);
9088 
9089   // TODO: Can we omit empty structs?
9090 
9091   if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
9092     Ty = QualType(SeltTy, 0);
9093 
9094   llvm::Type *OrigLTy = CGT.ConvertType(Ty);
9095   llvm::Type *LTy = OrigLTy;
9096   if (getContext().getLangOpts().HIP) {
9097     LTy = coerceKernelArgumentType(
9098         OrigLTy, /*FromAS=*/getContext().getTargetAddressSpace(LangAS::Default),
9099         /*ToAS=*/getContext().getTargetAddressSpace(LangAS::cuda_device));
9100   }
9101 
9102   // FIXME: Should also use this for OpenCL, but it requires addressing the
9103   // problem of kernels being called.
9104   //
9105   // FIXME: This doesn't apply the optimization of coercing pointers in structs
9106   // to global address space when using byref. This would require implementing a
9107   // new kind of coercion of the in-memory type when for indirect arguments.
9108   if (!getContext().getLangOpts().OpenCL && LTy == OrigLTy &&
9109       isAggregateTypeForABI(Ty)) {
9110     return ABIArgInfo::getIndirectAliased(
9111         getContext().getTypeAlignInChars(Ty),
9112         getContext().getTargetAddressSpace(LangAS::opencl_constant),
9113         false /*Realign*/, nullptr /*Padding*/);
9114   }
9115 
9116   // If we set CanBeFlattened to true, CodeGen will expand the struct to its
9117   // individual elements, which confuses the Clover OpenCL backend; therefore we
9118   // have to set it to false here. Other args of getDirect() are just defaults.
9119   return ABIArgInfo::getDirect(LTy, 0, nullptr, false);
9120 }
9121 
9122 ABIArgInfo AMDGPUABIInfo::classifyArgumentType(QualType Ty,
9123                                                unsigned &NumRegsLeft) const {
9124   assert(NumRegsLeft <= MaxNumRegsForArgsRet && "register estimate underflow");
9125 
9126   Ty = useFirstFieldIfTransparentUnion(Ty);
9127 
9128   if (isAggregateTypeForABI(Ty)) {
9129     // Records with non-trivial destructors/copy-constructors should not be
9130     // passed by value.
9131     if (auto RAA = getRecordArgABI(Ty, getCXXABI()))
9132       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
9133 
9134     // Ignore empty structs/unions.
9135     if (isEmptyRecord(getContext(), Ty, true))
9136       return ABIArgInfo::getIgnore();
9137 
9138     // Lower single-element structs to just pass a regular value. TODO: We
9139     // could do reasonable-size multiple-element structs too, using getExpand(),
9140     // though watch out for things like bitfields.
9141     if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
9142       return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
9143 
9144     if (const RecordType *RT = Ty->getAs<RecordType>()) {
9145       const RecordDecl *RD = RT->getDecl();
9146       if (RD->hasFlexibleArrayMember())
9147         return DefaultABIInfo::classifyArgumentType(Ty);
9148     }
9149 
9150     // Pack aggregates <= 8 bytes into single VGPR or pair.
9151     uint64_t Size = getContext().getTypeSize(Ty);
9152     if (Size <= 64) {
9153       unsigned NumRegs = (Size + 31) / 32;
9154       NumRegsLeft -= std::min(NumRegsLeft, NumRegs);
9155 
9156       if (Size <= 16)
9157         return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
9158 
9159       if (Size <= 32)
9160         return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
9161 
9162       // XXX: Should this be i64 instead, and should the limit increase?
9163       llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext());
9164       return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2));
9165     }
9166 
9167     if (NumRegsLeft > 0) {
9168       unsigned NumRegs = numRegsForType(Ty);
9169       if (NumRegsLeft >= NumRegs) {
9170         NumRegsLeft -= NumRegs;
9171         return ABIArgInfo::getDirect();
9172       }
9173     }
9174   }
9175 
9176   // Otherwise just do the default thing.
9177   ABIArgInfo ArgInfo = DefaultABIInfo::classifyArgumentType(Ty);
9178   if (!ArgInfo.isIndirect()) {
9179     unsigned NumRegs = numRegsForType(Ty);
9180     NumRegsLeft -= std::min(NumRegs, NumRegsLeft);
9181   }
9182 
9183   return ArgInfo;
9184 }
9185 
9186 class AMDGPUTargetCodeGenInfo : public TargetCodeGenInfo {
9187 public:
9188   AMDGPUTargetCodeGenInfo(CodeGenTypes &CGT)
9189       : TargetCodeGenInfo(std::make_unique<AMDGPUABIInfo>(CGT)) {}
9190 
9191   void setFunctionDeclAttributes(const FunctionDecl *FD, llvm::Function *F,
9192                                  CodeGenModule &CGM) const;
9193 
9194   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
9195                            CodeGen::CodeGenModule &M) const override;
9196   unsigned getOpenCLKernelCallingConv() const override;
9197 
9198   llvm::Constant *getNullPointer(const CodeGen::CodeGenModule &CGM,
9199       llvm::PointerType *T, QualType QT) const override;
9200 
9201   LangAS getASTAllocaAddressSpace() const override {
9202     return getLangASFromTargetAS(
9203         getABIInfo().getDataLayout().getAllocaAddrSpace());
9204   }
9205   LangAS getGlobalVarAddressSpace(CodeGenModule &CGM,
9206                                   const VarDecl *D) const override;
9207   llvm::SyncScope::ID getLLVMSyncScopeID(const LangOptions &LangOpts,
9208                                          SyncScope Scope,
9209                                          llvm::AtomicOrdering Ordering,
9210                                          llvm::LLVMContext &Ctx) const override;
9211   llvm::Function *
9212   createEnqueuedBlockKernel(CodeGenFunction &CGF,
9213                             llvm::Function *BlockInvokeFunc,
9214                             llvm::Value *BlockLiteral) const override;
9215   bool shouldEmitStaticExternCAliases() const override;
9216   void setCUDAKernelCallingConvention(const FunctionType *&FT) const override;
9217 };
9218 }
9219 
9220 static bool requiresAMDGPUProtectedVisibility(const Decl *D,
9221                                               llvm::GlobalValue *GV) {
9222   if (GV->getVisibility() != llvm::GlobalValue::HiddenVisibility)
9223     return false;
9224 
9225   return D->hasAttr<OpenCLKernelAttr>() ||
9226          (isa<FunctionDecl>(D) && D->hasAttr<CUDAGlobalAttr>()) ||
9227          (isa<VarDecl>(D) &&
9228           (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>() ||
9229            cast<VarDecl>(D)->getType()->isCUDADeviceBuiltinSurfaceType() ||
9230            cast<VarDecl>(D)->getType()->isCUDADeviceBuiltinTextureType()));
9231 }
9232 
9233 void AMDGPUTargetCodeGenInfo::setFunctionDeclAttributes(
9234     const FunctionDecl *FD, llvm::Function *F, CodeGenModule &M) const {
9235   const auto *ReqdWGS =
9236       M.getLangOpts().OpenCL ? FD->getAttr<ReqdWorkGroupSizeAttr>() : nullptr;
9237   const bool IsOpenCLKernel =
9238       M.getLangOpts().OpenCL && FD->hasAttr<OpenCLKernelAttr>();
9239   const bool IsHIPKernel = M.getLangOpts().HIP && FD->hasAttr<CUDAGlobalAttr>();
9240 
9241   const auto *FlatWGS = FD->getAttr<AMDGPUFlatWorkGroupSizeAttr>();
9242   if (ReqdWGS || FlatWGS) {
9243     unsigned Min = 0;
9244     unsigned Max = 0;
9245     if (FlatWGS) {
9246       Min = FlatWGS->getMin()
9247                 ->EvaluateKnownConstInt(M.getContext())
9248                 .getExtValue();
9249       Max = FlatWGS->getMax()
9250                 ->EvaluateKnownConstInt(M.getContext())
9251                 .getExtValue();
9252     }
9253     if (ReqdWGS && Min == 0 && Max == 0)
9254       Min = Max = ReqdWGS->getXDim() * ReqdWGS->getYDim() * ReqdWGS->getZDim();
9255 
9256     if (Min != 0) {
9257       assert(Min <= Max && "Min must be less than or equal Max");
9258 
9259       std::string AttrVal = llvm::utostr(Min) + "," + llvm::utostr(Max);
9260       F->addFnAttr("amdgpu-flat-work-group-size", AttrVal);
9261     } else
9262       assert(Max == 0 && "Max must be zero");
9263   } else if (IsOpenCLKernel || IsHIPKernel) {
9264     // By default, restrict the maximum size to a value specified by
9265     // --gpu-max-threads-per-block=n or its default value for HIP.
9266     const unsigned OpenCLDefaultMaxWorkGroupSize = 256;
9267     const unsigned DefaultMaxWorkGroupSize =
9268         IsOpenCLKernel ? OpenCLDefaultMaxWorkGroupSize
9269                        : M.getLangOpts().GPUMaxThreadsPerBlock;
9270     std::string AttrVal =
9271         std::string("1,") + llvm::utostr(DefaultMaxWorkGroupSize);
9272     F->addFnAttr("amdgpu-flat-work-group-size", AttrVal);
9273   }
9274 
9275   if (const auto *Attr = FD->getAttr<AMDGPUWavesPerEUAttr>()) {
9276     unsigned Min =
9277         Attr->getMin()->EvaluateKnownConstInt(M.getContext()).getExtValue();
9278     unsigned Max = Attr->getMax() ? Attr->getMax()
9279                                         ->EvaluateKnownConstInt(M.getContext())
9280                                         .getExtValue()
9281                                   : 0;
9282 
9283     if (Min != 0) {
9284       assert((Max == 0 || Min <= Max) && "Min must be less than or equal Max");
9285 
9286       std::string AttrVal = llvm::utostr(Min);
9287       if (Max != 0)
9288         AttrVal = AttrVal + "," + llvm::utostr(Max);
9289       F->addFnAttr("amdgpu-waves-per-eu", AttrVal);
9290     } else
9291       assert(Max == 0 && "Max must be zero");
9292   }
9293 
9294   if (const auto *Attr = FD->getAttr<AMDGPUNumSGPRAttr>()) {
9295     unsigned NumSGPR = Attr->getNumSGPR();
9296 
9297     if (NumSGPR != 0)
9298       F->addFnAttr("amdgpu-num-sgpr", llvm::utostr(NumSGPR));
9299   }
9300 
9301   if (const auto *Attr = FD->getAttr<AMDGPUNumVGPRAttr>()) {
9302     uint32_t NumVGPR = Attr->getNumVGPR();
9303 
9304     if (NumVGPR != 0)
9305       F->addFnAttr("amdgpu-num-vgpr", llvm::utostr(NumVGPR));
9306   }
9307 }
9308 
9309 void AMDGPUTargetCodeGenInfo::setTargetAttributes(
9310     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
9311   if (requiresAMDGPUProtectedVisibility(D, GV)) {
9312     GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
9313     GV->setDSOLocal(true);
9314   }
9315 
9316   if (GV->isDeclaration())
9317     return;
9318 
9319   llvm::Function *F = dyn_cast<llvm::Function>(GV);
9320   if (!F)
9321     return;
9322 
9323   const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
9324   if (FD)
9325     setFunctionDeclAttributes(FD, F, M);
9326 
9327   const bool IsHIPKernel =
9328       M.getLangOpts().HIP && FD && FD->hasAttr<CUDAGlobalAttr>();
9329 
9330   if (IsHIPKernel)
9331     F->addFnAttr("uniform-work-group-size", "true");
9332 
9333   if (M.getContext().getTargetInfo().allowAMDGPUUnsafeFPAtomics())
9334     F->addFnAttr("amdgpu-unsafe-fp-atomics", "true");
9335 
9336   if (!getABIInfo().getCodeGenOpts().EmitIEEENaNCompliantInsts)
9337     F->addFnAttr("amdgpu-ieee", "false");
9338 }
9339 
9340 unsigned AMDGPUTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
9341   return llvm::CallingConv::AMDGPU_KERNEL;
9342 }
9343 
9344 // Currently LLVM assumes null pointers always have value 0,
9345 // which results in incorrectly transformed IR. Therefore, instead of
9346 // emitting null pointers in private and local address spaces, a null
9347 // pointer in generic address space is emitted which is casted to a
9348 // pointer in local or private address space.
9349 llvm::Constant *AMDGPUTargetCodeGenInfo::getNullPointer(
9350     const CodeGen::CodeGenModule &CGM, llvm::PointerType *PT,
9351     QualType QT) const {
9352   if (CGM.getContext().getTargetNullPointerValue(QT) == 0)
9353     return llvm::ConstantPointerNull::get(PT);
9354 
9355   auto &Ctx = CGM.getContext();
9356   auto NPT = llvm::PointerType::getWithSamePointeeType(
9357       PT, Ctx.getTargetAddressSpace(LangAS::opencl_generic));
9358   return llvm::ConstantExpr::getAddrSpaceCast(
9359       llvm::ConstantPointerNull::get(NPT), PT);
9360 }
9361 
9362 LangAS
9363 AMDGPUTargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM,
9364                                                   const VarDecl *D) const {
9365   assert(!CGM.getLangOpts().OpenCL &&
9366          !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) &&
9367          "Address space agnostic languages only");
9368   LangAS DefaultGlobalAS = getLangASFromTargetAS(
9369       CGM.getContext().getTargetAddressSpace(LangAS::opencl_global));
9370   if (!D)
9371     return DefaultGlobalAS;
9372 
9373   LangAS AddrSpace = D->getType().getAddressSpace();
9374   assert(AddrSpace == LangAS::Default || isTargetAddressSpace(AddrSpace));
9375   if (AddrSpace != LangAS::Default)
9376     return AddrSpace;
9377 
9378   // Only promote to address space 4 if VarDecl has constant initialization.
9379   if (CGM.isTypeConstant(D->getType(), false) &&
9380       D->hasConstantInitialization()) {
9381     if (auto ConstAS = CGM.getTarget().getConstantAddressSpace())
9382       return ConstAS.getValue();
9383   }
9384   return DefaultGlobalAS;
9385 }
9386 
9387 llvm::SyncScope::ID
9388 AMDGPUTargetCodeGenInfo::getLLVMSyncScopeID(const LangOptions &LangOpts,
9389                                             SyncScope Scope,
9390                                             llvm::AtomicOrdering Ordering,
9391                                             llvm::LLVMContext &Ctx) const {
9392   std::string Name;
9393   switch (Scope) {
9394   case SyncScope::HIPSingleThread:
9395     Name = "singlethread";
9396     break;
9397   case SyncScope::HIPWavefront:
9398   case SyncScope::OpenCLSubGroup:
9399     Name = "wavefront";
9400     break;
9401   case SyncScope::HIPWorkgroup:
9402   case SyncScope::OpenCLWorkGroup:
9403     Name = "workgroup";
9404     break;
9405   case SyncScope::HIPAgent:
9406   case SyncScope::OpenCLDevice:
9407     Name = "agent";
9408     break;
9409   case SyncScope::HIPSystem:
9410   case SyncScope::OpenCLAllSVMDevices:
9411     Name = "";
9412     break;
9413   }
9414 
9415   if (Ordering != llvm::AtomicOrdering::SequentiallyConsistent) {
9416     if (!Name.empty())
9417       Name = Twine(Twine(Name) + Twine("-")).str();
9418 
9419     Name = Twine(Twine(Name) + Twine("one-as")).str();
9420   }
9421 
9422   return Ctx.getOrInsertSyncScopeID(Name);
9423 }
9424 
9425 bool AMDGPUTargetCodeGenInfo::shouldEmitStaticExternCAliases() const {
9426   return false;
9427 }
9428 
9429 void AMDGPUTargetCodeGenInfo::setCUDAKernelCallingConvention(
9430     const FunctionType *&FT) const {
9431   FT = getABIInfo().getContext().adjustFunctionType(
9432       FT, FT->getExtInfo().withCallingConv(CC_OpenCLKernel));
9433 }
9434 
9435 //===----------------------------------------------------------------------===//
9436 // SPARC v8 ABI Implementation.
9437 // Based on the SPARC Compliance Definition version 2.4.1.
9438 //
9439 // Ensures that complex values are passed in registers.
9440 //
9441 namespace {
9442 class SparcV8ABIInfo : public DefaultABIInfo {
9443 public:
9444   SparcV8ABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
9445 
9446 private:
9447   ABIArgInfo classifyReturnType(QualType RetTy) const;
9448   void computeInfo(CGFunctionInfo &FI) const override;
9449 };
9450 } // end anonymous namespace
9451 
9452 
9453 ABIArgInfo
9454 SparcV8ABIInfo::classifyReturnType(QualType Ty) const {
9455   if (Ty->isAnyComplexType()) {
9456     return ABIArgInfo::getDirect();
9457   }
9458   else {
9459     return DefaultABIInfo::classifyReturnType(Ty);
9460   }
9461 }
9462 
9463 void SparcV8ABIInfo::computeInfo(CGFunctionInfo &FI) const {
9464 
9465   FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
9466   for (auto &Arg : FI.arguments())
9467     Arg.info = classifyArgumentType(Arg.type);
9468 }
9469 
9470 namespace {
9471 class SparcV8TargetCodeGenInfo : public TargetCodeGenInfo {
9472 public:
9473   SparcV8TargetCodeGenInfo(CodeGenTypes &CGT)
9474       : TargetCodeGenInfo(std::make_unique<SparcV8ABIInfo>(CGT)) {}
9475 
9476   llvm::Value *decodeReturnAddress(CodeGen::CodeGenFunction &CGF,
9477                                    llvm::Value *Address) const override {
9478     int Offset;
9479     if (isAggregateTypeForABI(CGF.CurFnInfo->getReturnType()))
9480       Offset = 12;
9481     else
9482       Offset = 8;
9483     return CGF.Builder.CreateGEP(CGF.Int8Ty, Address,
9484                                  llvm::ConstantInt::get(CGF.Int32Ty, Offset));
9485   }
9486 
9487   llvm::Value *encodeReturnAddress(CodeGen::CodeGenFunction &CGF,
9488                                    llvm::Value *Address) const override {
9489     int Offset;
9490     if (isAggregateTypeForABI(CGF.CurFnInfo->getReturnType()))
9491       Offset = -12;
9492     else
9493       Offset = -8;
9494     return CGF.Builder.CreateGEP(CGF.Int8Ty, Address,
9495                                  llvm::ConstantInt::get(CGF.Int32Ty, Offset));
9496   }
9497 };
9498 } // end anonymous namespace
9499 
9500 //===----------------------------------------------------------------------===//
9501 // SPARC v9 ABI Implementation.
9502 // Based on the SPARC Compliance Definition version 2.4.1.
9503 //
9504 // Function arguments a mapped to a nominal "parameter array" and promoted to
9505 // registers depending on their type. Each argument occupies 8 or 16 bytes in
9506 // the array, structs larger than 16 bytes are passed indirectly.
9507 //
9508 // One case requires special care:
9509 //
9510 //   struct mixed {
9511 //     int i;
9512 //     float f;
9513 //   };
9514 //
9515 // When a struct mixed is passed by value, it only occupies 8 bytes in the
9516 // parameter array, but the int is passed in an integer register, and the float
9517 // is passed in a floating point register. This is represented as two arguments
9518 // with the LLVM IR inreg attribute:
9519 //
9520 //   declare void f(i32 inreg %i, float inreg %f)
9521 //
9522 // The code generator will only allocate 4 bytes from the parameter array for
9523 // the inreg arguments. All other arguments are allocated a multiple of 8
9524 // bytes.
9525 //
9526 namespace {
9527 class SparcV9ABIInfo : public ABIInfo {
9528 public:
9529   SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
9530 
9531 private:
9532   ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
9533   void computeInfo(CGFunctionInfo &FI) const override;
9534   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9535                     QualType Ty) const override;
9536 
9537   // Coercion type builder for structs passed in registers. The coercion type
9538   // serves two purposes:
9539   //
9540   // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
9541   //    in registers.
9542   // 2. Expose aligned floating point elements as first-level elements, so the
9543   //    code generator knows to pass them in floating point registers.
9544   //
9545   // We also compute the InReg flag which indicates that the struct contains
9546   // aligned 32-bit floats.
9547   //
9548   struct CoerceBuilder {
9549     llvm::LLVMContext &Context;
9550     const llvm::DataLayout &DL;
9551     SmallVector<llvm::Type*, 8> Elems;
9552     uint64_t Size;
9553     bool InReg;
9554 
9555     CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
9556       : Context(c), DL(dl), Size(0), InReg(false) {}
9557 
9558     // Pad Elems with integers until Size is ToSize.
9559     void pad(uint64_t ToSize) {
9560       assert(ToSize >= Size && "Cannot remove elements");
9561       if (ToSize == Size)
9562         return;
9563 
9564       // Finish the current 64-bit word.
9565       uint64_t Aligned = llvm::alignTo(Size, 64);
9566       if (Aligned > Size && Aligned <= ToSize) {
9567         Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
9568         Size = Aligned;
9569       }
9570 
9571       // Add whole 64-bit words.
9572       while (Size + 64 <= ToSize) {
9573         Elems.push_back(llvm::Type::getInt64Ty(Context));
9574         Size += 64;
9575       }
9576 
9577       // Final in-word padding.
9578       if (Size < ToSize) {
9579         Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
9580         Size = ToSize;
9581       }
9582     }
9583 
9584     // Add a floating point element at Offset.
9585     void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
9586       // Unaligned floats are treated as integers.
9587       if (Offset % Bits)
9588         return;
9589       // The InReg flag is only required if there are any floats < 64 bits.
9590       if (Bits < 64)
9591         InReg = true;
9592       pad(Offset);
9593       Elems.push_back(Ty);
9594       Size = Offset + Bits;
9595     }
9596 
9597     // Add a struct type to the coercion type, starting at Offset (in bits).
9598     void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
9599       const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
9600       for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
9601         llvm::Type *ElemTy = StrTy->getElementType(i);
9602         uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
9603         switch (ElemTy->getTypeID()) {
9604         case llvm::Type::StructTyID:
9605           addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
9606           break;
9607         case llvm::Type::FloatTyID:
9608           addFloat(ElemOffset, ElemTy, 32);
9609           break;
9610         case llvm::Type::DoubleTyID:
9611           addFloat(ElemOffset, ElemTy, 64);
9612           break;
9613         case llvm::Type::FP128TyID:
9614           addFloat(ElemOffset, ElemTy, 128);
9615           break;
9616         case llvm::Type::PointerTyID:
9617           if (ElemOffset % 64 == 0) {
9618             pad(ElemOffset);
9619             Elems.push_back(ElemTy);
9620             Size += 64;
9621           }
9622           break;
9623         default:
9624           break;
9625         }
9626       }
9627     }
9628 
9629     // Check if Ty is a usable substitute for the coercion type.
9630     bool isUsableType(llvm::StructType *Ty) const {
9631       return llvm::makeArrayRef(Elems) == Ty->elements();
9632     }
9633 
9634     // Get the coercion type as a literal struct type.
9635     llvm::Type *getType() const {
9636       if (Elems.size() == 1)
9637         return Elems.front();
9638       else
9639         return llvm::StructType::get(Context, Elems);
9640     }
9641   };
9642 };
9643 } // end anonymous namespace
9644 
9645 ABIArgInfo
9646 SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
9647   if (Ty->isVoidType())
9648     return ABIArgInfo::getIgnore();
9649 
9650   uint64_t Size = getContext().getTypeSize(Ty);
9651 
9652   // Anything too big to fit in registers is passed with an explicit indirect
9653   // pointer / sret pointer.
9654   if (Size > SizeLimit)
9655     return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
9656 
9657   // Treat an enum type as its underlying type.
9658   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
9659     Ty = EnumTy->getDecl()->getIntegerType();
9660 
9661   // Integer types smaller than a register are extended.
9662   if (Size < 64 && Ty->isIntegerType())
9663     return ABIArgInfo::getExtend(Ty);
9664 
9665   if (const auto *EIT = Ty->getAs<BitIntType>())
9666     if (EIT->getNumBits() < 64)
9667       return ABIArgInfo::getExtend(Ty);
9668 
9669   // Other non-aggregates go in registers.
9670   if (!isAggregateTypeForABI(Ty))
9671     return ABIArgInfo::getDirect();
9672 
9673   // If a C++ object has either a non-trivial copy constructor or a non-trivial
9674   // destructor, it is passed with an explicit indirect pointer / sret pointer.
9675   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
9676     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
9677 
9678   // This is a small aggregate type that should be passed in registers.
9679   // Build a coercion type from the LLVM struct type.
9680   llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
9681   if (!StrTy)
9682     return ABIArgInfo::getDirect();
9683 
9684   CoerceBuilder CB(getVMContext(), getDataLayout());
9685   CB.addStruct(0, StrTy);
9686   CB.pad(llvm::alignTo(CB.DL.getTypeSizeInBits(StrTy), 64));
9687 
9688   // Try to use the original type for coercion.
9689   llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
9690 
9691   if (CB.InReg)
9692     return ABIArgInfo::getDirectInReg(CoerceTy);
9693   else
9694     return ABIArgInfo::getDirect(CoerceTy);
9695 }
9696 
9697 Address SparcV9ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9698                                   QualType Ty) const {
9699   ABIArgInfo AI = classifyType(Ty, 16 * 8);
9700   llvm::Type *ArgTy = CGT.ConvertType(Ty);
9701   if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
9702     AI.setCoerceToType(ArgTy);
9703 
9704   CharUnits SlotSize = CharUnits::fromQuantity(8);
9705 
9706   CGBuilderTy &Builder = CGF.Builder;
9707   Address Addr(Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
9708   llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
9709 
9710   auto TypeInfo = getContext().getTypeInfoInChars(Ty);
9711 
9712   Address ArgAddr = Address::invalid();
9713   CharUnits Stride;
9714   switch (AI.getKind()) {
9715   case ABIArgInfo::Expand:
9716   case ABIArgInfo::CoerceAndExpand:
9717   case ABIArgInfo::InAlloca:
9718     llvm_unreachable("Unsupported ABI kind for va_arg");
9719 
9720   case ABIArgInfo::Extend: {
9721     Stride = SlotSize;
9722     CharUnits Offset = SlotSize - TypeInfo.Width;
9723     ArgAddr = Builder.CreateConstInBoundsByteGEP(Addr, Offset, "extend");
9724     break;
9725   }
9726 
9727   case ABIArgInfo::Direct: {
9728     auto AllocSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
9729     Stride = CharUnits::fromQuantity(AllocSize).alignTo(SlotSize);
9730     ArgAddr = Addr;
9731     break;
9732   }
9733 
9734   case ABIArgInfo::Indirect:
9735   case ABIArgInfo::IndirectAliased:
9736     Stride = SlotSize;
9737     ArgAddr = Builder.CreateElementBitCast(Addr, ArgPtrTy, "indirect");
9738     ArgAddr = Address(Builder.CreateLoad(ArgAddr, "indirect.arg"),
9739                       TypeInfo.Align);
9740     break;
9741 
9742   case ABIArgInfo::Ignore:
9743     return Address(llvm::UndefValue::get(ArgPtrTy), TypeInfo.Align);
9744   }
9745 
9746   // Update VAList.
9747   Address NextPtr = Builder.CreateConstInBoundsByteGEP(Addr, Stride, "ap.next");
9748   Builder.CreateStore(NextPtr.getPointer(), VAListAddr);
9749 
9750   return Builder.CreateElementBitCast(ArgAddr, ArgTy, "arg.addr");
9751 }
9752 
9753 void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
9754   FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
9755   for (auto &I : FI.arguments())
9756     I.info = classifyType(I.type, 16 * 8);
9757 }
9758 
9759 namespace {
9760 class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
9761 public:
9762   SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
9763       : TargetCodeGenInfo(std::make_unique<SparcV9ABIInfo>(CGT)) {}
9764 
9765   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
9766     return 14;
9767   }
9768 
9769   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
9770                                llvm::Value *Address) const override;
9771 
9772   llvm::Value *decodeReturnAddress(CodeGen::CodeGenFunction &CGF,
9773                                    llvm::Value *Address) const override {
9774     return CGF.Builder.CreateGEP(CGF.Int8Ty, Address,
9775                                  llvm::ConstantInt::get(CGF.Int32Ty, 8));
9776   }
9777 
9778   llvm::Value *encodeReturnAddress(CodeGen::CodeGenFunction &CGF,
9779                                    llvm::Value *Address) const override {
9780     return CGF.Builder.CreateGEP(CGF.Int8Ty, Address,
9781                                  llvm::ConstantInt::get(CGF.Int32Ty, -8));
9782   }
9783 };
9784 } // end anonymous namespace
9785 
9786 bool
9787 SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
9788                                                 llvm::Value *Address) const {
9789   // This is calculated from the LLVM and GCC tables and verified
9790   // against gcc output.  AFAIK all ABIs use the same encoding.
9791 
9792   CodeGen::CGBuilderTy &Builder = CGF.Builder;
9793 
9794   llvm::IntegerType *i8 = CGF.Int8Ty;
9795   llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
9796   llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
9797 
9798   // 0-31: the 8-byte general-purpose registers
9799   AssignToArrayRange(Builder, Address, Eight8, 0, 31);
9800 
9801   // 32-63: f0-31, the 4-byte floating-point registers
9802   AssignToArrayRange(Builder, Address, Four8, 32, 63);
9803 
9804   //   Y   = 64
9805   //   PSR = 65
9806   //   WIM = 66
9807   //   TBR = 67
9808   //   PC  = 68
9809   //   NPC = 69
9810   //   FSR = 70
9811   //   CSR = 71
9812   AssignToArrayRange(Builder, Address, Eight8, 64, 71);
9813 
9814   // 72-87: d0-15, the 8-byte floating-point registers
9815   AssignToArrayRange(Builder, Address, Eight8, 72, 87);
9816 
9817   return false;
9818 }
9819 
9820 // ARC ABI implementation.
9821 namespace {
9822 
9823 class ARCABIInfo : public DefaultABIInfo {
9824 public:
9825   using DefaultABIInfo::DefaultABIInfo;
9826 
9827 private:
9828   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9829                     QualType Ty) const override;
9830 
9831   void updateState(const ABIArgInfo &Info, QualType Ty, CCState &State) const {
9832     if (!State.FreeRegs)
9833       return;
9834     if (Info.isIndirect() && Info.getInReg())
9835       State.FreeRegs--;
9836     else if (Info.isDirect() && Info.getInReg()) {
9837       unsigned sz = (getContext().getTypeSize(Ty) + 31) / 32;
9838       if (sz < State.FreeRegs)
9839         State.FreeRegs -= sz;
9840       else
9841         State.FreeRegs = 0;
9842     }
9843   }
9844 
9845   void computeInfo(CGFunctionInfo &FI) const override {
9846     CCState State(FI);
9847     // ARC uses 8 registers to pass arguments.
9848     State.FreeRegs = 8;
9849 
9850     if (!getCXXABI().classifyReturnType(FI))
9851       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
9852     updateState(FI.getReturnInfo(), FI.getReturnType(), State);
9853     for (auto &I : FI.arguments()) {
9854       I.info = classifyArgumentType(I.type, State.FreeRegs);
9855       updateState(I.info, I.type, State);
9856     }
9857   }
9858 
9859   ABIArgInfo getIndirectByRef(QualType Ty, bool HasFreeRegs) const;
9860   ABIArgInfo getIndirectByValue(QualType Ty) const;
9861   ABIArgInfo classifyArgumentType(QualType Ty, uint8_t FreeRegs) const;
9862   ABIArgInfo classifyReturnType(QualType RetTy) const;
9863 };
9864 
9865 class ARCTargetCodeGenInfo : public TargetCodeGenInfo {
9866 public:
9867   ARCTargetCodeGenInfo(CodeGenTypes &CGT)
9868       : TargetCodeGenInfo(std::make_unique<ARCABIInfo>(CGT)) {}
9869 };
9870 
9871 
9872 ABIArgInfo ARCABIInfo::getIndirectByRef(QualType Ty, bool HasFreeRegs) const {
9873   return HasFreeRegs ? getNaturalAlignIndirectInReg(Ty) :
9874                        getNaturalAlignIndirect(Ty, false);
9875 }
9876 
9877 ABIArgInfo ARCABIInfo::getIndirectByValue(QualType Ty) const {
9878   // Compute the byval alignment.
9879   const unsigned MinABIStackAlignInBytes = 4;
9880   unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
9881   return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true,
9882                                  TypeAlign > MinABIStackAlignInBytes);
9883 }
9884 
9885 Address ARCABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9886                               QualType Ty) const {
9887   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
9888                           getContext().getTypeInfoInChars(Ty),
9889                           CharUnits::fromQuantity(4), true);
9890 }
9891 
9892 ABIArgInfo ARCABIInfo::classifyArgumentType(QualType Ty,
9893                                             uint8_t FreeRegs) const {
9894   // Handle the generic C++ ABI.
9895   const RecordType *RT = Ty->getAs<RecordType>();
9896   if (RT) {
9897     CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
9898     if (RAA == CGCXXABI::RAA_Indirect)
9899       return getIndirectByRef(Ty, FreeRegs > 0);
9900 
9901     if (RAA == CGCXXABI::RAA_DirectInMemory)
9902       return getIndirectByValue(Ty);
9903   }
9904 
9905   // Treat an enum type as its underlying type.
9906   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
9907     Ty = EnumTy->getDecl()->getIntegerType();
9908 
9909   auto SizeInRegs = llvm::alignTo(getContext().getTypeSize(Ty), 32) / 32;
9910 
9911   if (isAggregateTypeForABI(Ty)) {
9912     // Structures with flexible arrays are always indirect.
9913     if (RT && RT->getDecl()->hasFlexibleArrayMember())
9914       return getIndirectByValue(Ty);
9915 
9916     // Ignore empty structs/unions.
9917     if (isEmptyRecord(getContext(), Ty, true))
9918       return ABIArgInfo::getIgnore();
9919 
9920     llvm::LLVMContext &LLVMContext = getVMContext();
9921 
9922     llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
9923     SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32);
9924     llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
9925 
9926     return FreeRegs >= SizeInRegs ?
9927         ABIArgInfo::getDirectInReg(Result) :
9928         ABIArgInfo::getDirect(Result, 0, nullptr, false);
9929   }
9930 
9931   if (const auto *EIT = Ty->getAs<BitIntType>())
9932     if (EIT->getNumBits() > 64)
9933       return getIndirectByValue(Ty);
9934 
9935   return isPromotableIntegerTypeForABI(Ty)
9936              ? (FreeRegs >= SizeInRegs ? ABIArgInfo::getExtendInReg(Ty)
9937                                        : ABIArgInfo::getExtend(Ty))
9938              : (FreeRegs >= SizeInRegs ? ABIArgInfo::getDirectInReg()
9939                                        : ABIArgInfo::getDirect());
9940 }
9941 
9942 ABIArgInfo ARCABIInfo::classifyReturnType(QualType RetTy) const {
9943   if (RetTy->isAnyComplexType())
9944     return ABIArgInfo::getDirectInReg();
9945 
9946   // Arguments of size > 4 registers are indirect.
9947   auto RetSize = llvm::alignTo(getContext().getTypeSize(RetTy), 32) / 32;
9948   if (RetSize > 4)
9949     return getIndirectByRef(RetTy, /*HasFreeRegs*/ true);
9950 
9951   return DefaultABIInfo::classifyReturnType(RetTy);
9952 }
9953 
9954 } // End anonymous namespace.
9955 
9956 //===----------------------------------------------------------------------===//
9957 // XCore ABI Implementation
9958 //===----------------------------------------------------------------------===//
9959 
9960 namespace {
9961 
9962 /// A SmallStringEnc instance is used to build up the TypeString by passing
9963 /// it by reference between functions that append to it.
9964 typedef llvm::SmallString<128> SmallStringEnc;
9965 
9966 /// TypeStringCache caches the meta encodings of Types.
9967 ///
9968 /// The reason for caching TypeStrings is two fold:
9969 ///   1. To cache a type's encoding for later uses;
9970 ///   2. As a means to break recursive member type inclusion.
9971 ///
9972 /// A cache Entry can have a Status of:
9973 ///   NonRecursive:   The type encoding is not recursive;
9974 ///   Recursive:      The type encoding is recursive;
9975 ///   Incomplete:     An incomplete TypeString;
9976 ///   IncompleteUsed: An incomplete TypeString that has been used in a
9977 ///                   Recursive type encoding.
9978 ///
9979 /// A NonRecursive entry will have all of its sub-members expanded as fully
9980 /// as possible. Whilst it may contain types which are recursive, the type
9981 /// itself is not recursive and thus its encoding may be safely used whenever
9982 /// the type is encountered.
9983 ///
9984 /// A Recursive entry will have all of its sub-members expanded as fully as
9985 /// possible. The type itself is recursive and it may contain other types which
9986 /// are recursive. The Recursive encoding must not be used during the expansion
9987 /// of a recursive type's recursive branch. For simplicity the code uses
9988 /// IncompleteCount to reject all usage of Recursive encodings for member types.
9989 ///
9990 /// An Incomplete entry is always a RecordType and only encodes its
9991 /// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and
9992 /// are placed into the cache during type expansion as a means to identify and
9993 /// handle recursive inclusion of types as sub-members. If there is recursion
9994 /// the entry becomes IncompleteUsed.
9995 ///
9996 /// During the expansion of a RecordType's members:
9997 ///
9998 ///   If the cache contains a NonRecursive encoding for the member type, the
9999 ///   cached encoding is used;
10000 ///
10001 ///   If the cache contains a Recursive encoding for the member type, the
10002 ///   cached encoding is 'Swapped' out, as it may be incorrect, and...
10003 ///
10004 ///   If the member is a RecordType, an Incomplete encoding is placed into the
10005 ///   cache to break potential recursive inclusion of itself as a sub-member;
10006 ///
10007 ///   Once a member RecordType has been expanded, its temporary incomplete
10008 ///   entry is removed from the cache. If a Recursive encoding was swapped out
10009 ///   it is swapped back in;
10010 ///
10011 ///   If an incomplete entry is used to expand a sub-member, the incomplete
10012 ///   entry is marked as IncompleteUsed. The cache keeps count of how many
10013 ///   IncompleteUsed entries it currently contains in IncompleteUsedCount;
10014 ///
10015 ///   If a member's encoding is found to be a NonRecursive or Recursive viz:
10016 ///   IncompleteUsedCount==0, the member's encoding is added to the cache.
10017 ///   Else the member is part of a recursive type and thus the recursion has
10018 ///   been exited too soon for the encoding to be correct for the member.
10019 ///
10020 class TypeStringCache {
10021   enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed};
10022   struct Entry {
10023     std::string Str;     // The encoded TypeString for the type.
10024     enum Status State;   // Information about the encoding in 'Str'.
10025     std::string Swapped; // A temporary place holder for a Recursive encoding
10026                          // during the expansion of RecordType's members.
10027   };
10028   std::map<const IdentifierInfo *, struct Entry> Map;
10029   unsigned IncompleteCount;     // Number of Incomplete entries in the Map.
10030   unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map.
10031 public:
10032   TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {}
10033   void addIncomplete(const IdentifierInfo *ID, std::string StubEnc);
10034   bool removeIncomplete(const IdentifierInfo *ID);
10035   void addIfComplete(const IdentifierInfo *ID, StringRef Str,
10036                      bool IsRecursive);
10037   StringRef lookupStr(const IdentifierInfo *ID);
10038 };
10039 
10040 /// TypeString encodings for enum & union fields must be order.
10041 /// FieldEncoding is a helper for this ordering process.
10042 class FieldEncoding {
10043   bool HasName;
10044   std::string Enc;
10045 public:
10046   FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {}
10047   StringRef str() { return Enc; }
10048   bool operator<(const FieldEncoding &rhs) const {
10049     if (HasName != rhs.HasName) return HasName;
10050     return Enc < rhs.Enc;
10051   }
10052 };
10053 
10054 class XCoreABIInfo : public DefaultABIInfo {
10055 public:
10056   XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
10057   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
10058                     QualType Ty) const override;
10059 };
10060 
10061 class XCoreTargetCodeGenInfo : public TargetCodeGenInfo {
10062   mutable TypeStringCache TSC;
10063   void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
10064                     const CodeGen::CodeGenModule &M) const;
10065 
10066 public:
10067   XCoreTargetCodeGenInfo(CodeGenTypes &CGT)
10068       : TargetCodeGenInfo(std::make_unique<XCoreABIInfo>(CGT)) {}
10069   void emitTargetMetadata(CodeGen::CodeGenModule &CGM,
10070                           const llvm::MapVector<GlobalDecl, StringRef>
10071                               &MangledDeclNames) const override;
10072 };
10073 
10074 } // End anonymous namespace.
10075 
10076 // TODO: this implementation is likely now redundant with the default
10077 // EmitVAArg.
10078 Address XCoreABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
10079                                 QualType Ty) const {
10080   CGBuilderTy &Builder = CGF.Builder;
10081 
10082   // Get the VAList.
10083   CharUnits SlotSize = CharUnits::fromQuantity(4);
10084   Address AP(Builder.CreateLoad(VAListAddr), SlotSize);
10085 
10086   // Handle the argument.
10087   ABIArgInfo AI = classifyArgumentType(Ty);
10088   CharUnits TypeAlign = getContext().getTypeAlignInChars(Ty);
10089   llvm::Type *ArgTy = CGT.ConvertType(Ty);
10090   if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
10091     AI.setCoerceToType(ArgTy);
10092   llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
10093 
10094   Address Val = Address::invalid();
10095   CharUnits ArgSize = CharUnits::Zero();
10096   switch (AI.getKind()) {
10097   case ABIArgInfo::Expand:
10098   case ABIArgInfo::CoerceAndExpand:
10099   case ABIArgInfo::InAlloca:
10100     llvm_unreachable("Unsupported ABI kind for va_arg");
10101   case ABIArgInfo::Ignore:
10102     Val = Address(llvm::UndefValue::get(ArgPtrTy), TypeAlign);
10103     ArgSize = CharUnits::Zero();
10104     break;
10105   case ABIArgInfo::Extend:
10106   case ABIArgInfo::Direct:
10107     Val = Builder.CreateElementBitCast(AP, ArgTy);
10108     ArgSize = CharUnits::fromQuantity(
10109         getDataLayout().getTypeAllocSize(AI.getCoerceToType()));
10110     ArgSize = ArgSize.alignTo(SlotSize);
10111     break;
10112   case ABIArgInfo::Indirect:
10113   case ABIArgInfo::IndirectAliased:
10114     Val = Builder.CreateElementBitCast(AP, ArgPtrTy);
10115     Val = Address(Builder.CreateLoad(Val), TypeAlign);
10116     ArgSize = SlotSize;
10117     break;
10118   }
10119 
10120   // Increment the VAList.
10121   if (!ArgSize.isZero()) {
10122     Address APN = Builder.CreateConstInBoundsByteGEP(AP, ArgSize);
10123     Builder.CreateStore(APN.getPointer(), VAListAddr);
10124   }
10125 
10126   return Val;
10127 }
10128 
10129 /// During the expansion of a RecordType, an incomplete TypeString is placed
10130 /// into the cache as a means to identify and break recursion.
10131 /// If there is a Recursive encoding in the cache, it is swapped out and will
10132 /// be reinserted by removeIncomplete().
10133 /// All other types of encoding should have been used rather than arriving here.
10134 void TypeStringCache::addIncomplete(const IdentifierInfo *ID,
10135                                     std::string StubEnc) {
10136   if (!ID)
10137     return;
10138   Entry &E = Map[ID];
10139   assert( (E.Str.empty() || E.State == Recursive) &&
10140          "Incorrectly use of addIncomplete");
10141   assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()");
10142   E.Swapped.swap(E.Str); // swap out the Recursive
10143   E.Str.swap(StubEnc);
10144   E.State = Incomplete;
10145   ++IncompleteCount;
10146 }
10147 
10148 /// Once the RecordType has been expanded, the temporary incomplete TypeString
10149 /// must be removed from the cache.
10150 /// If a Recursive was swapped out by addIncomplete(), it will be replaced.
10151 /// Returns true if the RecordType was defined recursively.
10152 bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) {
10153   if (!ID)
10154     return false;
10155   auto I = Map.find(ID);
10156   assert(I != Map.end() && "Entry not present");
10157   Entry &E = I->second;
10158   assert( (E.State == Incomplete ||
10159            E.State == IncompleteUsed) &&
10160          "Entry must be an incomplete type");
10161   bool IsRecursive = false;
10162   if (E.State == IncompleteUsed) {
10163     // We made use of our Incomplete encoding, thus we are recursive.
10164     IsRecursive = true;
10165     --IncompleteUsedCount;
10166   }
10167   if (E.Swapped.empty())
10168     Map.erase(I);
10169   else {
10170     // Swap the Recursive back.
10171     E.Swapped.swap(E.Str);
10172     E.Swapped.clear();
10173     E.State = Recursive;
10174   }
10175   --IncompleteCount;
10176   return IsRecursive;
10177 }
10178 
10179 /// Add the encoded TypeString to the cache only if it is NonRecursive or
10180 /// Recursive (viz: all sub-members were expanded as fully as possible).
10181 void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str,
10182                                     bool IsRecursive) {
10183   if (!ID || IncompleteUsedCount)
10184     return; // No key or it is is an incomplete sub-type so don't add.
10185   Entry &E = Map[ID];
10186   if (IsRecursive && !E.Str.empty()) {
10187     assert(E.State==Recursive && E.Str.size() == Str.size() &&
10188            "This is not the same Recursive entry");
10189     // The parent container was not recursive after all, so we could have used
10190     // this Recursive sub-member entry after all, but we assumed the worse when
10191     // we started viz: IncompleteCount!=0.
10192     return;
10193   }
10194   assert(E.Str.empty() && "Entry already present");
10195   E.Str = Str.str();
10196   E.State = IsRecursive? Recursive : NonRecursive;
10197 }
10198 
10199 /// Return a cached TypeString encoding for the ID. If there isn't one, or we
10200 /// are recursively expanding a type (IncompleteCount != 0) and the cached
10201 /// encoding is Recursive, return an empty StringRef.
10202 StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) {
10203   if (!ID)
10204     return StringRef();   // We have no key.
10205   auto I = Map.find(ID);
10206   if (I == Map.end())
10207     return StringRef();   // We have no encoding.
10208   Entry &E = I->second;
10209   if (E.State == Recursive && IncompleteCount)
10210     return StringRef();   // We don't use Recursive encodings for member types.
10211 
10212   if (E.State == Incomplete) {
10213     // The incomplete type is being used to break out of recursion.
10214     E.State = IncompleteUsed;
10215     ++IncompleteUsedCount;
10216   }
10217   return E.Str;
10218 }
10219 
10220 /// The XCore ABI includes a type information section that communicates symbol
10221 /// type information to the linker. The linker uses this information to verify
10222 /// safety/correctness of things such as array bound and pointers et al.
10223 /// The ABI only requires C (and XC) language modules to emit TypeStrings.
10224 /// This type information (TypeString) is emitted into meta data for all global
10225 /// symbols: definitions, declarations, functions & variables.
10226 ///
10227 /// The TypeString carries type, qualifier, name, size & value details.
10228 /// Please see 'Tools Development Guide' section 2.16.2 for format details:
10229 /// https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf
10230 /// The output is tested by test/CodeGen/xcore-stringtype.c.
10231 ///
10232 static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
10233                           const CodeGen::CodeGenModule &CGM,
10234                           TypeStringCache &TSC);
10235 
10236 /// XCore uses emitTargetMD to emit TypeString metadata for global symbols.
10237 void XCoreTargetCodeGenInfo::emitTargetMD(
10238     const Decl *D, llvm::GlobalValue *GV,
10239     const CodeGen::CodeGenModule &CGM) const {
10240   SmallStringEnc Enc;
10241   if (getTypeString(Enc, D, CGM, TSC)) {
10242     llvm::LLVMContext &Ctx = CGM.getModule().getContext();
10243     llvm::Metadata *MDVals[] = {llvm::ConstantAsMetadata::get(GV),
10244                                 llvm::MDString::get(Ctx, Enc.str())};
10245     llvm::NamedMDNode *MD =
10246       CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings");
10247     MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
10248   }
10249 }
10250 
10251 void XCoreTargetCodeGenInfo::emitTargetMetadata(
10252     CodeGen::CodeGenModule &CGM,
10253     const llvm::MapVector<GlobalDecl, StringRef> &MangledDeclNames) const {
10254   // Warning, new MangledDeclNames may be appended within this loop.
10255   // We rely on MapVector insertions adding new elements to the end
10256   // of the container.
10257   for (unsigned I = 0; I != MangledDeclNames.size(); ++I) {
10258     auto Val = *(MangledDeclNames.begin() + I);
10259     llvm::GlobalValue *GV = CGM.GetGlobalValue(Val.second);
10260     if (GV) {
10261       const Decl *D = Val.first.getDecl()->getMostRecentDecl();
10262       emitTargetMD(D, GV, CGM);
10263     }
10264   }
10265 }
10266 
10267 //===----------------------------------------------------------------------===//
10268 // Base ABI and target codegen info implementation common between SPIR and
10269 // SPIR-V.
10270 //===----------------------------------------------------------------------===//
10271 
10272 namespace {
10273 class CommonSPIRABIInfo : public DefaultABIInfo {
10274 public:
10275   CommonSPIRABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) { setCCs(); }
10276 
10277 private:
10278   void setCCs();
10279 };
10280 
10281 class SPIRVABIInfo : public CommonSPIRABIInfo {
10282 public:
10283   SPIRVABIInfo(CodeGenTypes &CGT) : CommonSPIRABIInfo(CGT) {}
10284   void computeInfo(CGFunctionInfo &FI) const override;
10285 
10286 private:
10287   ABIArgInfo classifyKernelArgumentType(QualType Ty) const;
10288 };
10289 } // end anonymous namespace
10290 namespace {
10291 class CommonSPIRTargetCodeGenInfo : public TargetCodeGenInfo {
10292 public:
10293   CommonSPIRTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
10294       : TargetCodeGenInfo(std::make_unique<CommonSPIRABIInfo>(CGT)) {}
10295   CommonSPIRTargetCodeGenInfo(std::unique_ptr<ABIInfo> ABIInfo)
10296       : TargetCodeGenInfo(std::move(ABIInfo)) {}
10297 
10298   LangAS getASTAllocaAddressSpace() const override {
10299     return getLangASFromTargetAS(
10300         getABIInfo().getDataLayout().getAllocaAddrSpace());
10301   }
10302 
10303   unsigned getOpenCLKernelCallingConv() const override;
10304 };
10305 class SPIRVTargetCodeGenInfo : public CommonSPIRTargetCodeGenInfo {
10306 public:
10307   SPIRVTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
10308       : CommonSPIRTargetCodeGenInfo(std::make_unique<SPIRVABIInfo>(CGT)) {}
10309   void setCUDAKernelCallingConvention(const FunctionType *&FT) const override;
10310 };
10311 } // End anonymous namespace.
10312 
10313 void CommonSPIRABIInfo::setCCs() {
10314   assert(getRuntimeCC() == llvm::CallingConv::C);
10315   RuntimeCC = llvm::CallingConv::SPIR_FUNC;
10316 }
10317 
10318 ABIArgInfo SPIRVABIInfo::classifyKernelArgumentType(QualType Ty) const {
10319   if (getContext().getLangOpts().HIP) {
10320     // Coerce pointer arguments with default address space to CrossWorkGroup
10321     // pointers for HIPSPV. When the language mode is HIP, the SPIRTargetInfo
10322     // maps cuda_device to SPIR-V's CrossWorkGroup address space.
10323     llvm::Type *LTy = CGT.ConvertType(Ty);
10324     auto DefaultAS = getContext().getTargetAddressSpace(LangAS::Default);
10325     auto GlobalAS = getContext().getTargetAddressSpace(LangAS::cuda_device);
10326     auto *PtrTy = llvm::dyn_cast<llvm::PointerType>(LTy);
10327     if (PtrTy && PtrTy->getAddressSpace() == DefaultAS) {
10328       LTy = llvm::PointerType::getWithSamePointeeType(PtrTy, GlobalAS);
10329       return ABIArgInfo::getDirect(LTy, 0, nullptr, false);
10330     }
10331   }
10332   return classifyArgumentType(Ty);
10333 }
10334 
10335 void SPIRVABIInfo::computeInfo(CGFunctionInfo &FI) const {
10336   // The logic is same as in DefaultABIInfo with an exception on the kernel
10337   // arguments handling.
10338   llvm::CallingConv::ID CC = FI.getCallingConvention();
10339 
10340   if (!getCXXABI().classifyReturnType(FI))
10341     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
10342 
10343   for (auto &I : FI.arguments()) {
10344     if (CC == llvm::CallingConv::SPIR_KERNEL) {
10345       I.info = classifyKernelArgumentType(I.type);
10346     } else {
10347       I.info = classifyArgumentType(I.type);
10348     }
10349   }
10350 }
10351 
10352 namespace clang {
10353 namespace CodeGen {
10354 void computeSPIRKernelABIInfo(CodeGenModule &CGM, CGFunctionInfo &FI) {
10355   if (CGM.getTarget().getTriple().isSPIRV())
10356     SPIRVABIInfo(CGM.getTypes()).computeInfo(FI);
10357   else
10358     CommonSPIRABIInfo(CGM.getTypes()).computeInfo(FI);
10359 }
10360 }
10361 }
10362 
10363 unsigned CommonSPIRTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
10364   return llvm::CallingConv::SPIR_KERNEL;
10365 }
10366 
10367 void SPIRVTargetCodeGenInfo::setCUDAKernelCallingConvention(
10368     const FunctionType *&FT) const {
10369   // Convert HIP kernels to SPIR-V kernels.
10370   if (getABIInfo().getContext().getLangOpts().HIP) {
10371     FT = getABIInfo().getContext().adjustFunctionType(
10372         FT, FT->getExtInfo().withCallingConv(CC_OpenCLKernel));
10373     return;
10374   }
10375 }
10376 
10377 static bool appendType(SmallStringEnc &Enc, QualType QType,
10378                        const CodeGen::CodeGenModule &CGM,
10379                        TypeStringCache &TSC);
10380 
10381 /// Helper function for appendRecordType().
10382 /// Builds a SmallVector containing the encoded field types in declaration
10383 /// order.
10384 static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE,
10385                              const RecordDecl *RD,
10386                              const CodeGen::CodeGenModule &CGM,
10387                              TypeStringCache &TSC) {
10388   for (const auto *Field : RD->fields()) {
10389     SmallStringEnc Enc;
10390     Enc += "m(";
10391     Enc += Field->getName();
10392     Enc += "){";
10393     if (Field->isBitField()) {
10394       Enc += "b(";
10395       llvm::raw_svector_ostream OS(Enc);
10396       OS << Field->getBitWidthValue(CGM.getContext());
10397       Enc += ':';
10398     }
10399     if (!appendType(Enc, Field->getType(), CGM, TSC))
10400       return false;
10401     if (Field->isBitField())
10402       Enc += ')';
10403     Enc += '}';
10404     FE.emplace_back(!Field->getName().empty(), Enc);
10405   }
10406   return true;
10407 }
10408 
10409 /// Appends structure and union types to Enc and adds encoding to cache.
10410 /// Recursively calls appendType (via extractFieldType) for each field.
10411 /// Union types have their fields ordered according to the ABI.
10412 static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT,
10413                              const CodeGen::CodeGenModule &CGM,
10414                              TypeStringCache &TSC, const IdentifierInfo *ID) {
10415   // Append the cached TypeString if we have one.
10416   StringRef TypeString = TSC.lookupStr(ID);
10417   if (!TypeString.empty()) {
10418     Enc += TypeString;
10419     return true;
10420   }
10421 
10422   // Start to emit an incomplete TypeString.
10423   size_t Start = Enc.size();
10424   Enc += (RT->isUnionType()? 'u' : 's');
10425   Enc += '(';
10426   if (ID)
10427     Enc += ID->getName();
10428   Enc += "){";
10429 
10430   // We collect all encoded fields and order as necessary.
10431   bool IsRecursive = false;
10432   const RecordDecl *RD = RT->getDecl()->getDefinition();
10433   if (RD && !RD->field_empty()) {
10434     // An incomplete TypeString stub is placed in the cache for this RecordType
10435     // so that recursive calls to this RecordType will use it whilst building a
10436     // complete TypeString for this RecordType.
10437     SmallVector<FieldEncoding, 16> FE;
10438     std::string StubEnc(Enc.substr(Start).str());
10439     StubEnc += '}';  // StubEnc now holds a valid incomplete TypeString.
10440     TSC.addIncomplete(ID, std::move(StubEnc));
10441     if (!extractFieldType(FE, RD, CGM, TSC)) {
10442       (void) TSC.removeIncomplete(ID);
10443       return false;
10444     }
10445     IsRecursive = TSC.removeIncomplete(ID);
10446     // The ABI requires unions to be sorted but not structures.
10447     // See FieldEncoding::operator< for sort algorithm.
10448     if (RT->isUnionType())
10449       llvm::sort(FE);
10450     // We can now complete the TypeString.
10451     unsigned E = FE.size();
10452     for (unsigned I = 0; I != E; ++I) {
10453       if (I)
10454         Enc += ',';
10455       Enc += FE[I].str();
10456     }
10457   }
10458   Enc += '}';
10459   TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive);
10460   return true;
10461 }
10462 
10463 /// Appends enum types to Enc and adds the encoding to the cache.
10464 static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET,
10465                            TypeStringCache &TSC,
10466                            const IdentifierInfo *ID) {
10467   // Append the cached TypeString if we have one.
10468   StringRef TypeString = TSC.lookupStr(ID);
10469   if (!TypeString.empty()) {
10470     Enc += TypeString;
10471     return true;
10472   }
10473 
10474   size_t Start = Enc.size();
10475   Enc += "e(";
10476   if (ID)
10477     Enc += ID->getName();
10478   Enc += "){";
10479 
10480   // We collect all encoded enumerations and order them alphanumerically.
10481   if (const EnumDecl *ED = ET->getDecl()->getDefinition()) {
10482     SmallVector<FieldEncoding, 16> FE;
10483     for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E;
10484          ++I) {
10485       SmallStringEnc EnumEnc;
10486       EnumEnc += "m(";
10487       EnumEnc += I->getName();
10488       EnumEnc += "){";
10489       I->getInitVal().toString(EnumEnc);
10490       EnumEnc += '}';
10491       FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc));
10492     }
10493     llvm::sort(FE);
10494     unsigned E = FE.size();
10495     for (unsigned I = 0; I != E; ++I) {
10496       if (I)
10497         Enc += ',';
10498       Enc += FE[I].str();
10499     }
10500   }
10501   Enc += '}';
10502   TSC.addIfComplete(ID, Enc.substr(Start), false);
10503   return true;
10504 }
10505 
10506 /// Appends type's qualifier to Enc.
10507 /// This is done prior to appending the type's encoding.
10508 static void appendQualifier(SmallStringEnc &Enc, QualType QT) {
10509   // Qualifiers are emitted in alphabetical order.
10510   static const char *const Table[]={"","c:","r:","cr:","v:","cv:","rv:","crv:"};
10511   int Lookup = 0;
10512   if (QT.isConstQualified())
10513     Lookup += 1<<0;
10514   if (QT.isRestrictQualified())
10515     Lookup += 1<<1;
10516   if (QT.isVolatileQualified())
10517     Lookup += 1<<2;
10518   Enc += Table[Lookup];
10519 }
10520 
10521 /// Appends built-in types to Enc.
10522 static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) {
10523   const char *EncType;
10524   switch (BT->getKind()) {
10525     case BuiltinType::Void:
10526       EncType = "0";
10527       break;
10528     case BuiltinType::Bool:
10529       EncType = "b";
10530       break;
10531     case BuiltinType::Char_U:
10532       EncType = "uc";
10533       break;
10534     case BuiltinType::UChar:
10535       EncType = "uc";
10536       break;
10537     case BuiltinType::SChar:
10538       EncType = "sc";
10539       break;
10540     case BuiltinType::UShort:
10541       EncType = "us";
10542       break;
10543     case BuiltinType::Short:
10544       EncType = "ss";
10545       break;
10546     case BuiltinType::UInt:
10547       EncType = "ui";
10548       break;
10549     case BuiltinType::Int:
10550       EncType = "si";
10551       break;
10552     case BuiltinType::ULong:
10553       EncType = "ul";
10554       break;
10555     case BuiltinType::Long:
10556       EncType = "sl";
10557       break;
10558     case BuiltinType::ULongLong:
10559       EncType = "ull";
10560       break;
10561     case BuiltinType::LongLong:
10562       EncType = "sll";
10563       break;
10564     case BuiltinType::Float:
10565       EncType = "ft";
10566       break;
10567     case BuiltinType::Double:
10568       EncType = "d";
10569       break;
10570     case BuiltinType::LongDouble:
10571       EncType = "ld";
10572       break;
10573     default:
10574       return false;
10575   }
10576   Enc += EncType;
10577   return true;
10578 }
10579 
10580 /// Appends a pointer encoding to Enc before calling appendType for the pointee.
10581 static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT,
10582                               const CodeGen::CodeGenModule &CGM,
10583                               TypeStringCache &TSC) {
10584   Enc += "p(";
10585   if (!appendType(Enc, PT->getPointeeType(), CGM, TSC))
10586     return false;
10587   Enc += ')';
10588   return true;
10589 }
10590 
10591 /// Appends array encoding to Enc before calling appendType for the element.
10592 static bool appendArrayType(SmallStringEnc &Enc, QualType QT,
10593                             const ArrayType *AT,
10594                             const CodeGen::CodeGenModule &CGM,
10595                             TypeStringCache &TSC, StringRef NoSizeEnc) {
10596   if (AT->getSizeModifier() != ArrayType::Normal)
10597     return false;
10598   Enc += "a(";
10599   if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
10600     CAT->getSize().toStringUnsigned(Enc);
10601   else
10602     Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "".
10603   Enc += ':';
10604   // The Qualifiers should be attached to the type rather than the array.
10605   appendQualifier(Enc, QT);
10606   if (!appendType(Enc, AT->getElementType(), CGM, TSC))
10607     return false;
10608   Enc += ')';
10609   return true;
10610 }
10611 
10612 /// Appends a function encoding to Enc, calling appendType for the return type
10613 /// and the arguments.
10614 static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT,
10615                              const CodeGen::CodeGenModule &CGM,
10616                              TypeStringCache &TSC) {
10617   Enc += "f{";
10618   if (!appendType(Enc, FT->getReturnType(), CGM, TSC))
10619     return false;
10620   Enc += "}(";
10621   if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) {
10622     // N.B. we are only interested in the adjusted param types.
10623     auto I = FPT->param_type_begin();
10624     auto E = FPT->param_type_end();
10625     if (I != E) {
10626       do {
10627         if (!appendType(Enc, *I, CGM, TSC))
10628           return false;
10629         ++I;
10630         if (I != E)
10631           Enc += ',';
10632       } while (I != E);
10633       if (FPT->isVariadic())
10634         Enc += ",va";
10635     } else {
10636       if (FPT->isVariadic())
10637         Enc += "va";
10638       else
10639         Enc += '0';
10640     }
10641   }
10642   Enc += ')';
10643   return true;
10644 }
10645 
10646 /// Handles the type's qualifier before dispatching a call to handle specific
10647 /// type encodings.
10648 static bool appendType(SmallStringEnc &Enc, QualType QType,
10649                        const CodeGen::CodeGenModule &CGM,
10650                        TypeStringCache &TSC) {
10651 
10652   QualType QT = QType.getCanonicalType();
10653 
10654   if (const ArrayType *AT = QT->getAsArrayTypeUnsafe())
10655     // The Qualifiers should be attached to the type rather than the array.
10656     // Thus we don't call appendQualifier() here.
10657     return appendArrayType(Enc, QT, AT, CGM, TSC, "");
10658 
10659   appendQualifier(Enc, QT);
10660 
10661   if (const BuiltinType *BT = QT->getAs<BuiltinType>())
10662     return appendBuiltinType(Enc, BT);
10663 
10664   if (const PointerType *PT = QT->getAs<PointerType>())
10665     return appendPointerType(Enc, PT, CGM, TSC);
10666 
10667   if (const EnumType *ET = QT->getAs<EnumType>())
10668     return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier());
10669 
10670   if (const RecordType *RT = QT->getAsStructureType())
10671     return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
10672 
10673   if (const RecordType *RT = QT->getAsUnionType())
10674     return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
10675 
10676   if (const FunctionType *FT = QT->getAs<FunctionType>())
10677     return appendFunctionType(Enc, FT, CGM, TSC);
10678 
10679   return false;
10680 }
10681 
10682 static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
10683                           const CodeGen::CodeGenModule &CGM,
10684                           TypeStringCache &TSC) {
10685   if (!D)
10686     return false;
10687 
10688   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
10689     if (FD->getLanguageLinkage() != CLanguageLinkage)
10690       return false;
10691     return appendType(Enc, FD->getType(), CGM, TSC);
10692   }
10693 
10694   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
10695     if (VD->getLanguageLinkage() != CLanguageLinkage)
10696       return false;
10697     QualType QT = VD->getType().getCanonicalType();
10698     if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) {
10699       // Global ArrayTypes are given a size of '*' if the size is unknown.
10700       // The Qualifiers should be attached to the type rather than the array.
10701       // Thus we don't call appendQualifier() here.
10702       return appendArrayType(Enc, QT, AT, CGM, TSC, "*");
10703     }
10704     return appendType(Enc, QT, CGM, TSC);
10705   }
10706   return false;
10707 }
10708 
10709 //===----------------------------------------------------------------------===//
10710 // RISCV ABI Implementation
10711 //===----------------------------------------------------------------------===//
10712 
10713 namespace {
10714 class RISCVABIInfo : public DefaultABIInfo {
10715 private:
10716   // Size of the integer ('x') registers in bits.
10717   unsigned XLen;
10718   // Size of the floating point ('f') registers in bits. Note that the target
10719   // ISA might have a wider FLen than the selected ABI (e.g. an RV32IF target
10720   // with soft float ABI has FLen==0).
10721   unsigned FLen;
10722   static const int NumArgGPRs = 8;
10723   static const int NumArgFPRs = 8;
10724   bool detectFPCCEligibleStructHelper(QualType Ty, CharUnits CurOff,
10725                                       llvm::Type *&Field1Ty,
10726                                       CharUnits &Field1Off,
10727                                       llvm::Type *&Field2Ty,
10728                                       CharUnits &Field2Off) const;
10729 
10730 public:
10731   RISCVABIInfo(CodeGen::CodeGenTypes &CGT, unsigned XLen, unsigned FLen)
10732       : DefaultABIInfo(CGT), XLen(XLen), FLen(FLen) {}
10733 
10734   // DefaultABIInfo's classifyReturnType and classifyArgumentType are
10735   // non-virtual, but computeInfo is virtual, so we overload it.
10736   void computeInfo(CGFunctionInfo &FI) const override;
10737 
10738   ABIArgInfo classifyArgumentType(QualType Ty, bool IsFixed, int &ArgGPRsLeft,
10739                                   int &ArgFPRsLeft) const;
10740   ABIArgInfo classifyReturnType(QualType RetTy) const;
10741 
10742   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
10743                     QualType Ty) const override;
10744 
10745   ABIArgInfo extendType(QualType Ty) const;
10746 
10747   bool detectFPCCEligibleStruct(QualType Ty, llvm::Type *&Field1Ty,
10748                                 CharUnits &Field1Off, llvm::Type *&Field2Ty,
10749                                 CharUnits &Field2Off, int &NeededArgGPRs,
10750                                 int &NeededArgFPRs) const;
10751   ABIArgInfo coerceAndExpandFPCCEligibleStruct(llvm::Type *Field1Ty,
10752                                                CharUnits Field1Off,
10753                                                llvm::Type *Field2Ty,
10754                                                CharUnits Field2Off) const;
10755 };
10756 } // end anonymous namespace
10757 
10758 void RISCVABIInfo::computeInfo(CGFunctionInfo &FI) const {
10759   QualType RetTy = FI.getReturnType();
10760   if (!getCXXABI().classifyReturnType(FI))
10761     FI.getReturnInfo() = classifyReturnType(RetTy);
10762 
10763   // IsRetIndirect is true if classifyArgumentType indicated the value should
10764   // be passed indirect, or if the type size is a scalar greater than 2*XLen
10765   // and not a complex type with elements <= FLen. e.g. fp128 is passed direct
10766   // in LLVM IR, relying on the backend lowering code to rewrite the argument
10767   // list and pass indirectly on RV32.
10768   bool IsRetIndirect = FI.getReturnInfo().getKind() == ABIArgInfo::Indirect;
10769   if (!IsRetIndirect && RetTy->isScalarType() &&
10770       getContext().getTypeSize(RetTy) > (2 * XLen)) {
10771     if (RetTy->isComplexType() && FLen) {
10772       QualType EltTy = RetTy->castAs<ComplexType>()->getElementType();
10773       IsRetIndirect = getContext().getTypeSize(EltTy) > FLen;
10774     } else {
10775       // This is a normal scalar > 2*XLen, such as fp128 on RV32.
10776       IsRetIndirect = true;
10777     }
10778   }
10779 
10780   // We must track the number of GPRs used in order to conform to the RISC-V
10781   // ABI, as integer scalars passed in registers should have signext/zeroext
10782   // when promoted, but are anyext if passed on the stack. As GPR usage is
10783   // different for variadic arguments, we must also track whether we are
10784   // examining a vararg or not.
10785   int ArgGPRsLeft = IsRetIndirect ? NumArgGPRs - 1 : NumArgGPRs;
10786   int ArgFPRsLeft = FLen ? NumArgFPRs : 0;
10787   int NumFixedArgs = FI.getNumRequiredArgs();
10788 
10789   int ArgNum = 0;
10790   for (auto &ArgInfo : FI.arguments()) {
10791     bool IsFixed = ArgNum < NumFixedArgs;
10792     ArgInfo.info =
10793         classifyArgumentType(ArgInfo.type, IsFixed, ArgGPRsLeft, ArgFPRsLeft);
10794     ArgNum++;
10795   }
10796 }
10797 
10798 // Returns true if the struct is a potential candidate for the floating point
10799 // calling convention. If this function returns true, the caller is
10800 // responsible for checking that if there is only a single field then that
10801 // field is a float.
10802 bool RISCVABIInfo::detectFPCCEligibleStructHelper(QualType Ty, CharUnits CurOff,
10803                                                   llvm::Type *&Field1Ty,
10804                                                   CharUnits &Field1Off,
10805                                                   llvm::Type *&Field2Ty,
10806                                                   CharUnits &Field2Off) const {
10807   bool IsInt = Ty->isIntegralOrEnumerationType();
10808   bool IsFloat = Ty->isRealFloatingType();
10809 
10810   if (IsInt || IsFloat) {
10811     uint64_t Size = getContext().getTypeSize(Ty);
10812     if (IsInt && Size > XLen)
10813       return false;
10814     // Can't be eligible if larger than the FP registers. Half precision isn't
10815     // currently supported on RISC-V and the ABI hasn't been confirmed, so
10816     // default to the integer ABI in that case.
10817     if (IsFloat && (Size > FLen || Size < 32))
10818       return false;
10819     // Can't be eligible if an integer type was already found (int+int pairs
10820     // are not eligible).
10821     if (IsInt && Field1Ty && Field1Ty->isIntegerTy())
10822       return false;
10823     if (!Field1Ty) {
10824       Field1Ty = CGT.ConvertType(Ty);
10825       Field1Off = CurOff;
10826       return true;
10827     }
10828     if (!Field2Ty) {
10829       Field2Ty = CGT.ConvertType(Ty);
10830       Field2Off = CurOff;
10831       return true;
10832     }
10833     return false;
10834   }
10835 
10836   if (auto CTy = Ty->getAs<ComplexType>()) {
10837     if (Field1Ty)
10838       return false;
10839     QualType EltTy = CTy->getElementType();
10840     if (getContext().getTypeSize(EltTy) > FLen)
10841       return false;
10842     Field1Ty = CGT.ConvertType(EltTy);
10843     Field1Off = CurOff;
10844     Field2Ty = Field1Ty;
10845     Field2Off = Field1Off + getContext().getTypeSizeInChars(EltTy);
10846     return true;
10847   }
10848 
10849   if (const ConstantArrayType *ATy = getContext().getAsConstantArrayType(Ty)) {
10850     uint64_t ArraySize = ATy->getSize().getZExtValue();
10851     QualType EltTy = ATy->getElementType();
10852     CharUnits EltSize = getContext().getTypeSizeInChars(EltTy);
10853     for (uint64_t i = 0; i < ArraySize; ++i) {
10854       bool Ret = detectFPCCEligibleStructHelper(EltTy, CurOff, Field1Ty,
10855                                                 Field1Off, Field2Ty, Field2Off);
10856       if (!Ret)
10857         return false;
10858       CurOff += EltSize;
10859     }
10860     return true;
10861   }
10862 
10863   if (const auto *RTy = Ty->getAs<RecordType>()) {
10864     // Structures with either a non-trivial destructor or a non-trivial
10865     // copy constructor are not eligible for the FP calling convention.
10866     if (getRecordArgABI(Ty, CGT.getCXXABI()))
10867       return false;
10868     if (isEmptyRecord(getContext(), Ty, true))
10869       return true;
10870     const RecordDecl *RD = RTy->getDecl();
10871     // Unions aren't eligible unless they're empty (which is caught above).
10872     if (RD->isUnion())
10873       return false;
10874     int ZeroWidthBitFieldCount = 0;
10875     for (const FieldDecl *FD : RD->fields()) {
10876       const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
10877       uint64_t FieldOffInBits = Layout.getFieldOffset(FD->getFieldIndex());
10878       QualType QTy = FD->getType();
10879       if (FD->isBitField()) {
10880         unsigned BitWidth = FD->getBitWidthValue(getContext());
10881         // Allow a bitfield with a type greater than XLen as long as the
10882         // bitwidth is XLen or less.
10883         if (getContext().getTypeSize(QTy) > XLen && BitWidth <= XLen)
10884           QTy = getContext().getIntTypeForBitwidth(XLen, false);
10885         if (BitWidth == 0) {
10886           ZeroWidthBitFieldCount++;
10887           continue;
10888         }
10889       }
10890 
10891       bool Ret = detectFPCCEligibleStructHelper(
10892           QTy, CurOff + getContext().toCharUnitsFromBits(FieldOffInBits),
10893           Field1Ty, Field1Off, Field2Ty, Field2Off);
10894       if (!Ret)
10895         return false;
10896 
10897       // As a quirk of the ABI, zero-width bitfields aren't ignored for fp+fp
10898       // or int+fp structs, but are ignored for a struct with an fp field and
10899       // any number of zero-width bitfields.
10900       if (Field2Ty && ZeroWidthBitFieldCount > 0)
10901         return false;
10902     }
10903     return Field1Ty != nullptr;
10904   }
10905 
10906   return false;
10907 }
10908 
10909 // Determine if a struct is eligible for passing according to the floating
10910 // point calling convention (i.e., when flattened it contains a single fp
10911 // value, fp+fp, or int+fp of appropriate size). If so, NeededArgFPRs and
10912 // NeededArgGPRs are incremented appropriately.
10913 bool RISCVABIInfo::detectFPCCEligibleStruct(QualType Ty, llvm::Type *&Field1Ty,
10914                                             CharUnits &Field1Off,
10915                                             llvm::Type *&Field2Ty,
10916                                             CharUnits &Field2Off,
10917                                             int &NeededArgGPRs,
10918                                             int &NeededArgFPRs) const {
10919   Field1Ty = nullptr;
10920   Field2Ty = nullptr;
10921   NeededArgGPRs = 0;
10922   NeededArgFPRs = 0;
10923   bool IsCandidate = detectFPCCEligibleStructHelper(
10924       Ty, CharUnits::Zero(), Field1Ty, Field1Off, Field2Ty, Field2Off);
10925   // Not really a candidate if we have a single int but no float.
10926   if (Field1Ty && !Field2Ty && !Field1Ty->isFloatingPointTy())
10927     return false;
10928   if (!IsCandidate)
10929     return false;
10930   if (Field1Ty && Field1Ty->isFloatingPointTy())
10931     NeededArgFPRs++;
10932   else if (Field1Ty)
10933     NeededArgGPRs++;
10934   if (Field2Ty && Field2Ty->isFloatingPointTy())
10935     NeededArgFPRs++;
10936   else if (Field2Ty)
10937     NeededArgGPRs++;
10938   return true;
10939 }
10940 
10941 // Call getCoerceAndExpand for the two-element flattened struct described by
10942 // Field1Ty, Field1Off, Field2Ty, Field2Off. This method will create an
10943 // appropriate coerceToType and unpaddedCoerceToType.
10944 ABIArgInfo RISCVABIInfo::coerceAndExpandFPCCEligibleStruct(
10945     llvm::Type *Field1Ty, CharUnits Field1Off, llvm::Type *Field2Ty,
10946     CharUnits Field2Off) const {
10947   SmallVector<llvm::Type *, 3> CoerceElts;
10948   SmallVector<llvm::Type *, 2> UnpaddedCoerceElts;
10949   if (!Field1Off.isZero())
10950     CoerceElts.push_back(llvm::ArrayType::get(
10951         llvm::Type::getInt8Ty(getVMContext()), Field1Off.getQuantity()));
10952 
10953   CoerceElts.push_back(Field1Ty);
10954   UnpaddedCoerceElts.push_back(Field1Ty);
10955 
10956   if (!Field2Ty) {
10957     return ABIArgInfo::getCoerceAndExpand(
10958         llvm::StructType::get(getVMContext(), CoerceElts, !Field1Off.isZero()),
10959         UnpaddedCoerceElts[0]);
10960   }
10961 
10962   CharUnits Field2Align =
10963       CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(Field2Ty));
10964   CharUnits Field1End = Field1Off +
10965       CharUnits::fromQuantity(getDataLayout().getTypeStoreSize(Field1Ty));
10966   CharUnits Field2OffNoPadNoPack = Field1End.alignTo(Field2Align);
10967 
10968   CharUnits Padding = CharUnits::Zero();
10969   if (Field2Off > Field2OffNoPadNoPack)
10970     Padding = Field2Off - Field2OffNoPadNoPack;
10971   else if (Field2Off != Field2Align && Field2Off > Field1End)
10972     Padding = Field2Off - Field1End;
10973 
10974   bool IsPacked = !Field2Off.isMultipleOf(Field2Align);
10975 
10976   if (!Padding.isZero())
10977     CoerceElts.push_back(llvm::ArrayType::get(
10978         llvm::Type::getInt8Ty(getVMContext()), Padding.getQuantity()));
10979 
10980   CoerceElts.push_back(Field2Ty);
10981   UnpaddedCoerceElts.push_back(Field2Ty);
10982 
10983   auto CoerceToType =
10984       llvm::StructType::get(getVMContext(), CoerceElts, IsPacked);
10985   auto UnpaddedCoerceToType =
10986       llvm::StructType::get(getVMContext(), UnpaddedCoerceElts, IsPacked);
10987 
10988   return ABIArgInfo::getCoerceAndExpand(CoerceToType, UnpaddedCoerceToType);
10989 }
10990 
10991 ABIArgInfo RISCVABIInfo::classifyArgumentType(QualType Ty, bool IsFixed,
10992                                               int &ArgGPRsLeft,
10993                                               int &ArgFPRsLeft) const {
10994   assert(ArgGPRsLeft <= NumArgGPRs && "Arg GPR tracking underflow");
10995   Ty = useFirstFieldIfTransparentUnion(Ty);
10996 
10997   // Structures with either a non-trivial destructor or a non-trivial
10998   // copy constructor are always passed indirectly.
10999   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
11000     if (ArgGPRsLeft)
11001       ArgGPRsLeft -= 1;
11002     return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA ==
11003                                            CGCXXABI::RAA_DirectInMemory);
11004   }
11005 
11006   // Ignore empty structs/unions.
11007   if (isEmptyRecord(getContext(), Ty, true))
11008     return ABIArgInfo::getIgnore();
11009 
11010   uint64_t Size = getContext().getTypeSize(Ty);
11011 
11012   // Pass floating point values via FPRs if possible.
11013   if (IsFixed && Ty->isFloatingType() && !Ty->isComplexType() &&
11014       FLen >= Size && ArgFPRsLeft) {
11015     ArgFPRsLeft--;
11016     return ABIArgInfo::getDirect();
11017   }
11018 
11019   // Complex types for the hard float ABI must be passed direct rather than
11020   // using CoerceAndExpand.
11021   if (IsFixed && Ty->isComplexType() && FLen && ArgFPRsLeft >= 2) {
11022     QualType EltTy = Ty->castAs<ComplexType>()->getElementType();
11023     if (getContext().getTypeSize(EltTy) <= FLen) {
11024       ArgFPRsLeft -= 2;
11025       return ABIArgInfo::getDirect();
11026     }
11027   }
11028 
11029   if (IsFixed && FLen && Ty->isStructureOrClassType()) {
11030     llvm::Type *Field1Ty = nullptr;
11031     llvm::Type *Field2Ty = nullptr;
11032     CharUnits Field1Off = CharUnits::Zero();
11033     CharUnits Field2Off = CharUnits::Zero();
11034     int NeededArgGPRs = 0;
11035     int NeededArgFPRs = 0;
11036     bool IsCandidate =
11037         detectFPCCEligibleStruct(Ty, Field1Ty, Field1Off, Field2Ty, Field2Off,
11038                                  NeededArgGPRs, NeededArgFPRs);
11039     if (IsCandidate && NeededArgGPRs <= ArgGPRsLeft &&
11040         NeededArgFPRs <= ArgFPRsLeft) {
11041       ArgGPRsLeft -= NeededArgGPRs;
11042       ArgFPRsLeft -= NeededArgFPRs;
11043       return coerceAndExpandFPCCEligibleStruct(Field1Ty, Field1Off, Field2Ty,
11044                                                Field2Off);
11045     }
11046   }
11047 
11048   uint64_t NeededAlign = getContext().getTypeAlign(Ty);
11049   bool MustUseStack = false;
11050   // Determine the number of GPRs needed to pass the current argument
11051   // according to the ABI. 2*XLen-aligned varargs are passed in "aligned"
11052   // register pairs, so may consume 3 registers.
11053   int NeededArgGPRs = 1;
11054   if (!IsFixed && NeededAlign == 2 * XLen)
11055     NeededArgGPRs = 2 + (ArgGPRsLeft % 2);
11056   else if (Size > XLen && Size <= 2 * XLen)
11057     NeededArgGPRs = 2;
11058 
11059   if (NeededArgGPRs > ArgGPRsLeft) {
11060     MustUseStack = true;
11061     NeededArgGPRs = ArgGPRsLeft;
11062   }
11063 
11064   ArgGPRsLeft -= NeededArgGPRs;
11065 
11066   if (!isAggregateTypeForABI(Ty) && !Ty->isVectorType()) {
11067     // Treat an enum type as its underlying type.
11068     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
11069       Ty = EnumTy->getDecl()->getIntegerType();
11070 
11071     // All integral types are promoted to XLen width, unless passed on the
11072     // stack.
11073     if (Size < XLen && Ty->isIntegralOrEnumerationType() && !MustUseStack) {
11074       return extendType(Ty);
11075     }
11076 
11077     if (const auto *EIT = Ty->getAs<BitIntType>()) {
11078       if (EIT->getNumBits() < XLen && !MustUseStack)
11079         return extendType(Ty);
11080       if (EIT->getNumBits() > 128 ||
11081           (!getContext().getTargetInfo().hasInt128Type() &&
11082            EIT->getNumBits() > 64))
11083         return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
11084     }
11085 
11086     return ABIArgInfo::getDirect();
11087   }
11088 
11089   // Aggregates which are <= 2*XLen will be passed in registers if possible,
11090   // so coerce to integers.
11091   if (Size <= 2 * XLen) {
11092     unsigned Alignment = getContext().getTypeAlign(Ty);
11093 
11094     // Use a single XLen int if possible, 2*XLen if 2*XLen alignment is
11095     // required, and a 2-element XLen array if only XLen alignment is required.
11096     if (Size <= XLen) {
11097       return ABIArgInfo::getDirect(
11098           llvm::IntegerType::get(getVMContext(), XLen));
11099     } else if (Alignment == 2 * XLen) {
11100       return ABIArgInfo::getDirect(
11101           llvm::IntegerType::get(getVMContext(), 2 * XLen));
11102     } else {
11103       return ABIArgInfo::getDirect(llvm::ArrayType::get(
11104           llvm::IntegerType::get(getVMContext(), XLen), 2));
11105     }
11106   }
11107   return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
11108 }
11109 
11110 ABIArgInfo RISCVABIInfo::classifyReturnType(QualType RetTy) const {
11111   if (RetTy->isVoidType())
11112     return ABIArgInfo::getIgnore();
11113 
11114   int ArgGPRsLeft = 2;
11115   int ArgFPRsLeft = FLen ? 2 : 0;
11116 
11117   // The rules for return and argument types are the same, so defer to
11118   // classifyArgumentType.
11119   return classifyArgumentType(RetTy, /*IsFixed=*/true, ArgGPRsLeft,
11120                               ArgFPRsLeft);
11121 }
11122 
11123 Address RISCVABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
11124                                 QualType Ty) const {
11125   CharUnits SlotSize = CharUnits::fromQuantity(XLen / 8);
11126 
11127   // Empty records are ignored for parameter passing purposes.
11128   if (isEmptyRecord(getContext(), Ty, true)) {
11129     Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize);
11130     Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
11131     return Addr;
11132   }
11133 
11134   auto TInfo = getContext().getTypeInfoInChars(Ty);
11135 
11136   // Arguments bigger than 2*Xlen bytes are passed indirectly.
11137   bool IsIndirect = TInfo.Width > 2 * SlotSize;
11138 
11139   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TInfo,
11140                           SlotSize, /*AllowHigherAlign=*/true);
11141 }
11142 
11143 ABIArgInfo RISCVABIInfo::extendType(QualType Ty) const {
11144   int TySize = getContext().getTypeSize(Ty);
11145   // RV64 ABI requires unsigned 32 bit integers to be sign extended.
11146   if (XLen == 64 && Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
11147     return ABIArgInfo::getSignExtend(Ty);
11148   return ABIArgInfo::getExtend(Ty);
11149 }
11150 
11151 namespace {
11152 class RISCVTargetCodeGenInfo : public TargetCodeGenInfo {
11153 public:
11154   RISCVTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, unsigned XLen,
11155                          unsigned FLen)
11156       : TargetCodeGenInfo(std::make_unique<RISCVABIInfo>(CGT, XLen, FLen)) {}
11157 
11158   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
11159                            CodeGen::CodeGenModule &CGM) const override {
11160     const auto *FD = dyn_cast_or_null<FunctionDecl>(D);
11161     if (!FD) return;
11162 
11163     const auto *Attr = FD->getAttr<RISCVInterruptAttr>();
11164     if (!Attr)
11165       return;
11166 
11167     const char *Kind;
11168     switch (Attr->getInterrupt()) {
11169     case RISCVInterruptAttr::user: Kind = "user"; break;
11170     case RISCVInterruptAttr::supervisor: Kind = "supervisor"; break;
11171     case RISCVInterruptAttr::machine: Kind = "machine"; break;
11172     }
11173 
11174     auto *Fn = cast<llvm::Function>(GV);
11175 
11176     Fn->addFnAttr("interrupt", Kind);
11177   }
11178 };
11179 } // namespace
11180 
11181 //===----------------------------------------------------------------------===//
11182 // VE ABI Implementation.
11183 //
11184 namespace {
11185 class VEABIInfo : public DefaultABIInfo {
11186 public:
11187   VEABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
11188 
11189 private:
11190   ABIArgInfo classifyReturnType(QualType RetTy) const;
11191   ABIArgInfo classifyArgumentType(QualType RetTy) const;
11192   void computeInfo(CGFunctionInfo &FI) const override;
11193 };
11194 } // end anonymous namespace
11195 
11196 ABIArgInfo VEABIInfo::classifyReturnType(QualType Ty) const {
11197   if (Ty->isAnyComplexType())
11198     return ABIArgInfo::getDirect();
11199   uint64_t Size = getContext().getTypeSize(Ty);
11200   if (Size < 64 && Ty->isIntegerType())
11201     return ABIArgInfo::getExtend(Ty);
11202   return DefaultABIInfo::classifyReturnType(Ty);
11203 }
11204 
11205 ABIArgInfo VEABIInfo::classifyArgumentType(QualType Ty) const {
11206   if (Ty->isAnyComplexType())
11207     return ABIArgInfo::getDirect();
11208   uint64_t Size = getContext().getTypeSize(Ty);
11209   if (Size < 64 && Ty->isIntegerType())
11210     return ABIArgInfo::getExtend(Ty);
11211   return DefaultABIInfo::classifyArgumentType(Ty);
11212 }
11213 
11214 void VEABIInfo::computeInfo(CGFunctionInfo &FI) const {
11215   FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
11216   for (auto &Arg : FI.arguments())
11217     Arg.info = classifyArgumentType(Arg.type);
11218 }
11219 
11220 namespace {
11221 class VETargetCodeGenInfo : public TargetCodeGenInfo {
11222 public:
11223   VETargetCodeGenInfo(CodeGenTypes &CGT)
11224       : TargetCodeGenInfo(std::make_unique<VEABIInfo>(CGT)) {}
11225   // VE ABI requires the arguments of variadic and prototype-less functions
11226   // are passed in both registers and memory.
11227   bool isNoProtoCallVariadic(const CallArgList &args,
11228                              const FunctionNoProtoType *fnType) const override {
11229     return true;
11230   }
11231 };
11232 } // end anonymous namespace
11233 
11234 //===----------------------------------------------------------------------===//
11235 // Driver code
11236 //===----------------------------------------------------------------------===//
11237 
11238 bool CodeGenModule::supportsCOMDAT() const {
11239   return getTriple().supportsCOMDAT();
11240 }
11241 
11242 const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
11243   if (TheTargetCodeGenInfo)
11244     return *TheTargetCodeGenInfo;
11245 
11246   // Helper to set the unique_ptr while still keeping the return value.
11247   auto SetCGInfo = [&](TargetCodeGenInfo *P) -> const TargetCodeGenInfo & {
11248     this->TheTargetCodeGenInfo.reset(P);
11249     return *P;
11250   };
11251 
11252   const llvm::Triple &Triple = getTarget().getTriple();
11253   switch (Triple.getArch()) {
11254   default:
11255     return SetCGInfo(new DefaultTargetCodeGenInfo(Types));
11256 
11257   case llvm::Triple::le32:
11258     return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
11259   case llvm::Triple::m68k:
11260     return SetCGInfo(new M68kTargetCodeGenInfo(Types));
11261   case llvm::Triple::mips:
11262   case llvm::Triple::mipsel:
11263     if (Triple.getOS() == llvm::Triple::NaCl)
11264       return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
11265     return SetCGInfo(new MIPSTargetCodeGenInfo(Types, true));
11266 
11267   case llvm::Triple::mips64:
11268   case llvm::Triple::mips64el:
11269     return SetCGInfo(new MIPSTargetCodeGenInfo(Types, false));
11270 
11271   case llvm::Triple::avr:
11272     return SetCGInfo(new AVRTargetCodeGenInfo(Types));
11273 
11274   case llvm::Triple::aarch64:
11275   case llvm::Triple::aarch64_32:
11276   case llvm::Triple::aarch64_be: {
11277     AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS;
11278     if (getTarget().getABI() == "darwinpcs")
11279       Kind = AArch64ABIInfo::DarwinPCS;
11280     else if (Triple.isOSWindows())
11281       return SetCGInfo(
11282           new WindowsAArch64TargetCodeGenInfo(Types, AArch64ABIInfo::Win64));
11283 
11284     return SetCGInfo(new AArch64TargetCodeGenInfo(Types, Kind));
11285   }
11286 
11287   case llvm::Triple::wasm32:
11288   case llvm::Triple::wasm64: {
11289     WebAssemblyABIInfo::ABIKind Kind = WebAssemblyABIInfo::MVP;
11290     if (getTarget().getABI() == "experimental-mv")
11291       Kind = WebAssemblyABIInfo::ExperimentalMV;
11292     return SetCGInfo(new WebAssemblyTargetCodeGenInfo(Types, Kind));
11293   }
11294 
11295   case llvm::Triple::arm:
11296   case llvm::Triple::armeb:
11297   case llvm::Triple::thumb:
11298   case llvm::Triple::thumbeb: {
11299     if (Triple.getOS() == llvm::Triple::Win32) {
11300       return SetCGInfo(
11301           new WindowsARMTargetCodeGenInfo(Types, ARMABIInfo::AAPCS_VFP));
11302     }
11303 
11304     ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
11305     StringRef ABIStr = getTarget().getABI();
11306     if (ABIStr == "apcs-gnu")
11307       Kind = ARMABIInfo::APCS;
11308     else if (ABIStr == "aapcs16")
11309       Kind = ARMABIInfo::AAPCS16_VFP;
11310     else if (CodeGenOpts.FloatABI == "hard" ||
11311              (CodeGenOpts.FloatABI != "soft" &&
11312               (Triple.getEnvironment() == llvm::Triple::GNUEABIHF ||
11313                Triple.getEnvironment() == llvm::Triple::MuslEABIHF ||
11314                Triple.getEnvironment() == llvm::Triple::EABIHF)))
11315       Kind = ARMABIInfo::AAPCS_VFP;
11316 
11317     return SetCGInfo(new ARMTargetCodeGenInfo(Types, Kind));
11318   }
11319 
11320   case llvm::Triple::ppc: {
11321     if (Triple.isOSAIX())
11322       return SetCGInfo(new AIXTargetCodeGenInfo(Types, /*Is64Bit*/ false));
11323 
11324     bool IsSoftFloat =
11325         CodeGenOpts.FloatABI == "soft" || getTarget().hasFeature("spe");
11326     bool RetSmallStructInRegABI =
11327         PPC32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
11328     return SetCGInfo(
11329         new PPC32TargetCodeGenInfo(Types, IsSoftFloat, RetSmallStructInRegABI));
11330   }
11331   case llvm::Triple::ppcle: {
11332     bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
11333     bool RetSmallStructInRegABI =
11334         PPC32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
11335     return SetCGInfo(
11336         new PPC32TargetCodeGenInfo(Types, IsSoftFloat, RetSmallStructInRegABI));
11337   }
11338   case llvm::Triple::ppc64:
11339     if (Triple.isOSAIX())
11340       return SetCGInfo(new AIXTargetCodeGenInfo(Types, /*Is64Bit*/ true));
11341 
11342     if (Triple.isOSBinFormatELF()) {
11343       PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1;
11344       if (getTarget().getABI() == "elfv2")
11345         Kind = PPC64_SVR4_ABIInfo::ELFv2;
11346       bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
11347 
11348       return SetCGInfo(
11349           new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, IsSoftFloat));
11350     }
11351     return SetCGInfo(new PPC64TargetCodeGenInfo(Types));
11352   case llvm::Triple::ppc64le: {
11353     assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
11354     PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2;
11355     if (getTarget().getABI() == "elfv1")
11356       Kind = PPC64_SVR4_ABIInfo::ELFv1;
11357     bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
11358 
11359     return SetCGInfo(
11360         new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, IsSoftFloat));
11361   }
11362 
11363   case llvm::Triple::nvptx:
11364   case llvm::Triple::nvptx64:
11365     return SetCGInfo(new NVPTXTargetCodeGenInfo(Types));
11366 
11367   case llvm::Triple::msp430:
11368     return SetCGInfo(new MSP430TargetCodeGenInfo(Types));
11369 
11370   case llvm::Triple::riscv32:
11371   case llvm::Triple::riscv64: {
11372     StringRef ABIStr = getTarget().getABI();
11373     unsigned XLen = getTarget().getPointerWidth(0);
11374     unsigned ABIFLen = 0;
11375     if (ABIStr.endswith("f"))
11376       ABIFLen = 32;
11377     else if (ABIStr.endswith("d"))
11378       ABIFLen = 64;
11379     return SetCGInfo(new RISCVTargetCodeGenInfo(Types, XLen, ABIFLen));
11380   }
11381 
11382   case llvm::Triple::systemz: {
11383     bool SoftFloat = CodeGenOpts.FloatABI == "soft";
11384     bool HasVector = !SoftFloat && getTarget().getABI() == "vector";
11385     return SetCGInfo(new SystemZTargetCodeGenInfo(Types, HasVector, SoftFloat));
11386   }
11387 
11388   case llvm::Triple::tce:
11389   case llvm::Triple::tcele:
11390     return SetCGInfo(new TCETargetCodeGenInfo(Types));
11391 
11392   case llvm::Triple::x86: {
11393     bool IsDarwinVectorABI = Triple.isOSDarwin();
11394     bool RetSmallStructInRegABI =
11395         X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
11396     bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
11397 
11398     if (Triple.getOS() == llvm::Triple::Win32) {
11399       return SetCGInfo(new WinX86_32TargetCodeGenInfo(
11400           Types, IsDarwinVectorABI, RetSmallStructInRegABI,
11401           IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters));
11402     } else {
11403       return SetCGInfo(new X86_32TargetCodeGenInfo(
11404           Types, IsDarwinVectorABI, RetSmallStructInRegABI,
11405           IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters,
11406           CodeGenOpts.FloatABI == "soft"));
11407     }
11408   }
11409 
11410   case llvm::Triple::x86_64: {
11411     StringRef ABI = getTarget().getABI();
11412     X86AVXABILevel AVXLevel =
11413         (ABI == "avx512"
11414              ? X86AVXABILevel::AVX512
11415              : ABI == "avx" ? X86AVXABILevel::AVX : X86AVXABILevel::None);
11416 
11417     switch (Triple.getOS()) {
11418     case llvm::Triple::Win32:
11419       return SetCGInfo(new WinX86_64TargetCodeGenInfo(Types, AVXLevel));
11420     default:
11421       return SetCGInfo(new X86_64TargetCodeGenInfo(Types, AVXLevel));
11422     }
11423   }
11424   case llvm::Triple::hexagon:
11425     return SetCGInfo(new HexagonTargetCodeGenInfo(Types));
11426   case llvm::Triple::lanai:
11427     return SetCGInfo(new LanaiTargetCodeGenInfo(Types));
11428   case llvm::Triple::r600:
11429     return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
11430   case llvm::Triple::amdgcn:
11431     return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
11432   case llvm::Triple::sparc:
11433     return SetCGInfo(new SparcV8TargetCodeGenInfo(Types));
11434   case llvm::Triple::sparcv9:
11435     return SetCGInfo(new SparcV9TargetCodeGenInfo(Types));
11436   case llvm::Triple::xcore:
11437     return SetCGInfo(new XCoreTargetCodeGenInfo(Types));
11438   case llvm::Triple::arc:
11439     return SetCGInfo(new ARCTargetCodeGenInfo(Types));
11440   case llvm::Triple::spir:
11441   case llvm::Triple::spir64:
11442     return SetCGInfo(new CommonSPIRTargetCodeGenInfo(Types));
11443   case llvm::Triple::spirv32:
11444   case llvm::Triple::spirv64:
11445     return SetCGInfo(new SPIRVTargetCodeGenInfo(Types));
11446   case llvm::Triple::ve:
11447     return SetCGInfo(new VETargetCodeGenInfo(Types));
11448   }
11449 }
11450 
11451 /// Create an OpenCL kernel for an enqueued block.
11452 ///
11453 /// The kernel has the same function type as the block invoke function. Its
11454 /// name is the name of the block invoke function postfixed with "_kernel".
11455 /// It simply calls the block invoke function then returns.
11456 llvm::Function *
11457 TargetCodeGenInfo::createEnqueuedBlockKernel(CodeGenFunction &CGF,
11458                                              llvm::Function *Invoke,
11459                                              llvm::Value *BlockLiteral) const {
11460   auto *InvokeFT = Invoke->getFunctionType();
11461   llvm::SmallVector<llvm::Type *, 2> ArgTys;
11462   for (auto &P : InvokeFT->params())
11463     ArgTys.push_back(P);
11464   auto &C = CGF.getLLVMContext();
11465   std::string Name = Invoke->getName().str() + "_kernel";
11466   auto *FT = llvm::FunctionType::get(llvm::Type::getVoidTy(C), ArgTys, false);
11467   auto *F = llvm::Function::Create(FT, llvm::GlobalValue::ExternalLinkage, Name,
11468                                    &CGF.CGM.getModule());
11469   auto IP = CGF.Builder.saveIP();
11470   auto *BB = llvm::BasicBlock::Create(C, "entry", F);
11471   auto &Builder = CGF.Builder;
11472   Builder.SetInsertPoint(BB);
11473   llvm::SmallVector<llvm::Value *, 2> Args;
11474   for (auto &A : F->args())
11475     Args.push_back(&A);
11476   llvm::CallInst *call = Builder.CreateCall(Invoke, Args);
11477   call->setCallingConv(Invoke->getCallingConv());
11478   Builder.CreateRetVoid();
11479   Builder.restoreIP(IP);
11480   return F;
11481 }
11482 
11483 /// Create an OpenCL kernel for an enqueued block.
11484 ///
11485 /// The type of the first argument (the block literal) is the struct type
11486 /// of the block literal instead of a pointer type. The first argument
11487 /// (block literal) is passed directly by value to the kernel. The kernel
11488 /// allocates the same type of struct on stack and stores the block literal
11489 /// to it and passes its pointer to the block invoke function. The kernel
11490 /// has "enqueued-block" function attribute and kernel argument metadata.
11491 llvm::Function *AMDGPUTargetCodeGenInfo::createEnqueuedBlockKernel(
11492     CodeGenFunction &CGF, llvm::Function *Invoke,
11493     llvm::Value *BlockLiteral) const {
11494   auto &Builder = CGF.Builder;
11495   auto &C = CGF.getLLVMContext();
11496 
11497   auto *BlockTy = BlockLiteral->getType()->getPointerElementType();
11498   auto *InvokeFT = Invoke->getFunctionType();
11499   llvm::SmallVector<llvm::Type *, 2> ArgTys;
11500   llvm::SmallVector<llvm::Metadata *, 8> AddressQuals;
11501   llvm::SmallVector<llvm::Metadata *, 8> AccessQuals;
11502   llvm::SmallVector<llvm::Metadata *, 8> ArgTypeNames;
11503   llvm::SmallVector<llvm::Metadata *, 8> ArgBaseTypeNames;
11504   llvm::SmallVector<llvm::Metadata *, 8> ArgTypeQuals;
11505   llvm::SmallVector<llvm::Metadata *, 8> ArgNames;
11506 
11507   ArgTys.push_back(BlockTy);
11508   ArgTypeNames.push_back(llvm::MDString::get(C, "__block_literal"));
11509   AddressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(0)));
11510   ArgBaseTypeNames.push_back(llvm::MDString::get(C, "__block_literal"));
11511   ArgTypeQuals.push_back(llvm::MDString::get(C, ""));
11512   AccessQuals.push_back(llvm::MDString::get(C, "none"));
11513   ArgNames.push_back(llvm::MDString::get(C, "block_literal"));
11514   for (unsigned I = 1, E = InvokeFT->getNumParams(); I < E; ++I) {
11515     ArgTys.push_back(InvokeFT->getParamType(I));
11516     ArgTypeNames.push_back(llvm::MDString::get(C, "void*"));
11517     AddressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(3)));
11518     AccessQuals.push_back(llvm::MDString::get(C, "none"));
11519     ArgBaseTypeNames.push_back(llvm::MDString::get(C, "void*"));
11520     ArgTypeQuals.push_back(llvm::MDString::get(C, ""));
11521     ArgNames.push_back(
11522         llvm::MDString::get(C, (Twine("local_arg") + Twine(I)).str()));
11523   }
11524   std::string Name = Invoke->getName().str() + "_kernel";
11525   auto *FT = llvm::FunctionType::get(llvm::Type::getVoidTy(C), ArgTys, false);
11526   auto *F = llvm::Function::Create(FT, llvm::GlobalValue::InternalLinkage, Name,
11527                                    &CGF.CGM.getModule());
11528   F->addFnAttr("enqueued-block");
11529   auto IP = CGF.Builder.saveIP();
11530   auto *BB = llvm::BasicBlock::Create(C, "entry", F);
11531   Builder.SetInsertPoint(BB);
11532   const auto BlockAlign = CGF.CGM.getDataLayout().getPrefTypeAlign(BlockTy);
11533   auto *BlockPtr = Builder.CreateAlloca(BlockTy, nullptr);
11534   BlockPtr->setAlignment(BlockAlign);
11535   Builder.CreateAlignedStore(F->arg_begin(), BlockPtr, BlockAlign);
11536   auto *Cast = Builder.CreatePointerCast(BlockPtr, InvokeFT->getParamType(0));
11537   llvm::SmallVector<llvm::Value *, 2> Args;
11538   Args.push_back(Cast);
11539   for (auto I = F->arg_begin() + 1, E = F->arg_end(); I != E; ++I)
11540     Args.push_back(I);
11541   llvm::CallInst *call = Builder.CreateCall(Invoke, Args);
11542   call->setCallingConv(Invoke->getCallingConv());
11543   Builder.CreateRetVoid();
11544   Builder.restoreIP(IP);
11545 
11546   F->setMetadata("kernel_arg_addr_space", llvm::MDNode::get(C, AddressQuals));
11547   F->setMetadata("kernel_arg_access_qual", llvm::MDNode::get(C, AccessQuals));
11548   F->setMetadata("kernel_arg_type", llvm::MDNode::get(C, ArgTypeNames));
11549   F->setMetadata("kernel_arg_base_type",
11550                  llvm::MDNode::get(C, ArgBaseTypeNames));
11551   F->setMetadata("kernel_arg_type_qual", llvm::MDNode::get(C, ArgTypeQuals));
11552   if (CGF.CGM.getCodeGenOpts().EmitOpenCLArgMetadata)
11553     F->setMetadata("kernel_arg_name", llvm::MDNode::get(C, ArgNames));
11554 
11555   return F;
11556 }
11557