xref: /openbsd-src/gnu/llvm/clang/lib/CodeGen/TargetInfo.cpp (revision d0fc3bb68efd6c434b4053cd7adb29023cbec341)
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/CodeGen/CGFunctionInfo.h"
25 #include "clang/CodeGen/SwiftCallingConv.h"
26 #include "llvm/ADT/SmallBitVector.h"
27 #include "llvm/ADT/StringExtras.h"
28 #include "llvm/ADT/StringSwitch.h"
29 #include "llvm/ADT/Triple.h"
30 #include "llvm/ADT/Twine.h"
31 #include "llvm/IR/DataLayout.h"
32 #include "llvm/IR/IntrinsicsNVPTX.h"
33 #include "llvm/IR/Type.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include <algorithm> // std::sort
36 
37 using namespace clang;
38 using namespace CodeGen;
39 
40 // Helper for coercing an aggregate argument or return value into an integer
41 // array of the same size (including padding) and alignment.  This alternate
42 // coercion happens only for the RenderScript ABI and can be removed after
43 // runtimes that rely on it are no longer supported.
44 //
45 // RenderScript assumes that the size of the argument / return value in the IR
46 // is the same as the size of the corresponding qualified type. This helper
47 // coerces the aggregate type into an array of the same size (including
48 // padding).  This coercion is used in lieu of expansion of struct members or
49 // other canonical coercions that return a coerced-type of larger size.
50 //
51 // Ty          - The argument / return value type
52 // Context     - The associated ASTContext
53 // LLVMContext - The associated LLVMContext
54 static ABIArgInfo coerceToIntArray(QualType Ty,
55                                    ASTContext &Context,
56                                    llvm::LLVMContext &LLVMContext) {
57   // Alignment and Size are measured in bits.
58   const uint64_t Size = Context.getTypeSize(Ty);
59   const uint64_t Alignment = Context.getTypeAlign(Ty);
60   llvm::Type *IntType = llvm::Type::getIntNTy(LLVMContext, Alignment);
61   const uint64_t NumElements = (Size + Alignment - 1) / Alignment;
62   return ABIArgInfo::getDirect(llvm::ArrayType::get(IntType, NumElements));
63 }
64 
65 static void AssignToArrayRange(CodeGen::CGBuilderTy &Builder,
66                                llvm::Value *Array,
67                                llvm::Value *Value,
68                                unsigned FirstIndex,
69                                unsigned LastIndex) {
70   // Alternatively, we could emit this as a loop in the source.
71   for (unsigned I = FirstIndex; I <= LastIndex; ++I) {
72     llvm::Value *Cell =
73         Builder.CreateConstInBoundsGEP1_32(Builder.getInt8Ty(), Array, I);
74     Builder.CreateAlignedStore(Value, Cell, CharUnits::One());
75   }
76 }
77 
78 static bool isAggregateTypeForABI(QualType T) {
79   return !CodeGenFunction::hasScalarEvaluationKind(T) ||
80          T->isMemberFunctionPointerType();
81 }
82 
83 ABIArgInfo
84 ABIInfo::getNaturalAlignIndirect(QualType Ty, bool ByRef, bool Realign,
85                                  llvm::Type *Padding) const {
86   return ABIArgInfo::getIndirect(getContext().getTypeAlignInChars(Ty),
87                                  ByRef, Realign, Padding);
88 }
89 
90 ABIArgInfo
91 ABIInfo::getNaturalAlignIndirectInReg(QualType Ty, bool Realign) const {
92   return ABIArgInfo::getIndirectInReg(getContext().getTypeAlignInChars(Ty),
93                                       /*ByRef*/ false, Realign);
94 }
95 
96 Address ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
97                              QualType Ty) const {
98   return Address::invalid();
99 }
100 
101 bool ABIInfo::isPromotableIntegerTypeForABI(QualType Ty) const {
102   if (Ty->isPromotableIntegerType())
103     return true;
104 
105   if (const auto *EIT = Ty->getAs<ExtIntType>())
106     if (EIT->getNumBits() < getContext().getTypeSize(getContext().IntTy))
107       return true;
108 
109   return false;
110 }
111 
112 ABIInfo::~ABIInfo() {}
113 
114 /// Does the given lowering require more than the given number of
115 /// registers when expanded?
116 ///
117 /// This is intended to be the basis of a reasonable basic implementation
118 /// of should{Pass,Return}IndirectlyForSwift.
119 ///
120 /// For most targets, a limit of four total registers is reasonable; this
121 /// limits the amount of code required in order to move around the value
122 /// in case it wasn't produced immediately prior to the call by the caller
123 /// (or wasn't produced in exactly the right registers) or isn't used
124 /// immediately within the callee.  But some targets may need to further
125 /// limit the register count due to an inability to support that many
126 /// return registers.
127 static bool occupiesMoreThan(CodeGenTypes &cgt,
128                              ArrayRef<llvm::Type*> scalarTypes,
129                              unsigned maxAllRegisters) {
130   unsigned intCount = 0, fpCount = 0;
131   for (llvm::Type *type : scalarTypes) {
132     if (type->isPointerTy()) {
133       intCount++;
134     } else if (auto intTy = dyn_cast<llvm::IntegerType>(type)) {
135       auto ptrWidth = cgt.getTarget().getPointerWidth(0);
136       intCount += (intTy->getBitWidth() + ptrWidth - 1) / ptrWidth;
137     } else {
138       assert(type->isVectorTy() || type->isFloatingPointTy());
139       fpCount++;
140     }
141   }
142 
143   return (intCount + fpCount > maxAllRegisters);
144 }
145 
146 bool SwiftABIInfo::isLegalVectorTypeForSwift(CharUnits vectorSize,
147                                              llvm::Type *eltTy,
148                                              unsigned numElts) const {
149   // The default implementation of this assumes that the target guarantees
150   // 128-bit SIMD support but nothing more.
151   return (vectorSize.getQuantity() > 8 && vectorSize.getQuantity() <= 16);
152 }
153 
154 static CGCXXABI::RecordArgABI getRecordArgABI(const RecordType *RT,
155                                               CGCXXABI &CXXABI) {
156   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
157   if (!RD) {
158     if (!RT->getDecl()->canPassInRegisters())
159       return CGCXXABI::RAA_Indirect;
160     return CGCXXABI::RAA_Default;
161   }
162   return CXXABI.getRecordArgABI(RD);
163 }
164 
165 static CGCXXABI::RecordArgABI getRecordArgABI(QualType T,
166                                               CGCXXABI &CXXABI) {
167   const RecordType *RT = T->getAs<RecordType>();
168   if (!RT)
169     return CGCXXABI::RAA_Default;
170   return getRecordArgABI(RT, CXXABI);
171 }
172 
173 static bool classifyReturnType(const CGCXXABI &CXXABI, CGFunctionInfo &FI,
174                                const ABIInfo &Info) {
175   QualType Ty = FI.getReturnType();
176 
177   if (const auto *RT = Ty->getAs<RecordType>())
178     if (!isa<CXXRecordDecl>(RT->getDecl()) &&
179         !RT->getDecl()->canPassInRegisters()) {
180       FI.getReturnInfo() = Info.getNaturalAlignIndirect(Ty);
181       return true;
182     }
183 
184   return CXXABI.classifyReturnType(FI);
185 }
186 
187 /// Pass transparent unions as if they were the type of the first element. Sema
188 /// should ensure that all elements of the union have the same "machine type".
189 static QualType useFirstFieldIfTransparentUnion(QualType Ty) {
190   if (const RecordType *UT = Ty->getAsUnionType()) {
191     const RecordDecl *UD = UT->getDecl();
192     if (UD->hasAttr<TransparentUnionAttr>()) {
193       assert(!UD->field_empty() && "sema created an empty transparent union");
194       return UD->field_begin()->getType();
195     }
196   }
197   return Ty;
198 }
199 
200 CGCXXABI &ABIInfo::getCXXABI() const {
201   return CGT.getCXXABI();
202 }
203 
204 ASTContext &ABIInfo::getContext() const {
205   return CGT.getContext();
206 }
207 
208 llvm::LLVMContext &ABIInfo::getVMContext() const {
209   return CGT.getLLVMContext();
210 }
211 
212 const llvm::DataLayout &ABIInfo::getDataLayout() const {
213   return CGT.getDataLayout();
214 }
215 
216 const TargetInfo &ABIInfo::getTarget() const {
217   return CGT.getTarget();
218 }
219 
220 const CodeGenOptions &ABIInfo::getCodeGenOpts() const {
221   return CGT.getCodeGenOpts();
222 }
223 
224 bool ABIInfo::isAndroid() const { return getTarget().getTriple().isAndroid(); }
225 
226 bool ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
227   return false;
228 }
229 
230 bool ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
231                                                 uint64_t Members) const {
232   return false;
233 }
234 
235 LLVM_DUMP_METHOD void ABIArgInfo::dump() const {
236   raw_ostream &OS = llvm::errs();
237   OS << "(ABIArgInfo Kind=";
238   switch (TheKind) {
239   case Direct:
240     OS << "Direct Type=";
241     if (llvm::Type *Ty = getCoerceToType())
242       Ty->print(OS);
243     else
244       OS << "null";
245     break;
246   case Extend:
247     OS << "Extend";
248     break;
249   case Ignore:
250     OS << "Ignore";
251     break;
252   case InAlloca:
253     OS << "InAlloca Offset=" << getInAllocaFieldIndex();
254     break;
255   case Indirect:
256     OS << "Indirect Align=" << getIndirectAlign().getQuantity()
257        << " ByVal=" << getIndirectByVal()
258        << " Realign=" << getIndirectRealign();
259     break;
260   case Expand:
261     OS << "Expand";
262     break;
263   case CoerceAndExpand:
264     OS << "CoerceAndExpand Type=";
265     getCoerceAndExpandType()->print(OS);
266     break;
267   }
268   OS << ")\n";
269 }
270 
271 // Dynamically round a pointer up to a multiple of the given alignment.
272 static llvm::Value *emitRoundPointerUpToAlignment(CodeGenFunction &CGF,
273                                                   llvm::Value *Ptr,
274                                                   CharUnits Align) {
275   llvm::Value *PtrAsInt = Ptr;
276   // OverflowArgArea = (OverflowArgArea + Align - 1) & -Align;
277   PtrAsInt = CGF.Builder.CreatePtrToInt(PtrAsInt, CGF.IntPtrTy);
278   PtrAsInt = CGF.Builder.CreateAdd(PtrAsInt,
279         llvm::ConstantInt::get(CGF.IntPtrTy, Align.getQuantity() - 1));
280   PtrAsInt = CGF.Builder.CreateAnd(PtrAsInt,
281            llvm::ConstantInt::get(CGF.IntPtrTy, -Align.getQuantity()));
282   PtrAsInt = CGF.Builder.CreateIntToPtr(PtrAsInt,
283                                         Ptr->getType(),
284                                         Ptr->getName() + ".aligned");
285   return PtrAsInt;
286 }
287 
288 /// Emit va_arg for a platform using the common void* representation,
289 /// where arguments are simply emitted in an array of slots on the stack.
290 ///
291 /// This version implements the core direct-value passing rules.
292 ///
293 /// \param SlotSize - The size and alignment of a stack slot.
294 ///   Each argument will be allocated to a multiple of this number of
295 ///   slots, and all the slots will be aligned to this value.
296 /// \param AllowHigherAlign - The slot alignment is not a cap;
297 ///   an argument type with an alignment greater than the slot size
298 ///   will be emitted on a higher-alignment address, potentially
299 ///   leaving one or more empty slots behind as padding.  If this
300 ///   is false, the returned address might be less-aligned than
301 ///   DirectAlign.
302 static Address emitVoidPtrDirectVAArg(CodeGenFunction &CGF,
303                                       Address VAListAddr,
304                                       llvm::Type *DirectTy,
305                                       CharUnits DirectSize,
306                                       CharUnits DirectAlign,
307                                       CharUnits SlotSize,
308                                       bool AllowHigherAlign) {
309   // Cast the element type to i8* if necessary.  Some platforms define
310   // va_list as a struct containing an i8* instead of just an i8*.
311   if (VAListAddr.getElementType() != CGF.Int8PtrTy)
312     VAListAddr = CGF.Builder.CreateElementBitCast(VAListAddr, CGF.Int8PtrTy);
313 
314   llvm::Value *Ptr = CGF.Builder.CreateLoad(VAListAddr, "argp.cur");
315 
316   // If the CC aligns values higher than the slot size, do so if needed.
317   Address Addr = Address::invalid();
318   if (AllowHigherAlign && DirectAlign > SlotSize) {
319     Addr = Address(emitRoundPointerUpToAlignment(CGF, Ptr, DirectAlign),
320                                                  DirectAlign);
321   } else {
322     Addr = Address(Ptr, SlotSize);
323   }
324 
325   // Advance the pointer past the argument, then store that back.
326   CharUnits FullDirectSize = DirectSize.alignTo(SlotSize);
327   Address NextPtr =
328       CGF.Builder.CreateConstInBoundsByteGEP(Addr, FullDirectSize, "argp.next");
329   CGF.Builder.CreateStore(NextPtr.getPointer(), VAListAddr);
330 
331   // If the argument is smaller than a slot, and this is a big-endian
332   // target, the argument will be right-adjusted in its slot.
333   if (DirectSize < SlotSize && CGF.CGM.getDataLayout().isBigEndian() &&
334       !DirectTy->isStructTy()) {
335     Addr = CGF.Builder.CreateConstInBoundsByteGEP(Addr, SlotSize - DirectSize);
336   }
337 
338   Addr = CGF.Builder.CreateElementBitCast(Addr, DirectTy);
339   return Addr;
340 }
341 
342 /// Emit va_arg for a platform using the common void* representation,
343 /// where arguments are simply emitted in an array of slots on the stack.
344 ///
345 /// \param IsIndirect - Values of this type are passed indirectly.
346 /// \param ValueInfo - The size and alignment of this type, generally
347 ///   computed with getContext().getTypeInfoInChars(ValueTy).
348 /// \param SlotSizeAndAlign - The size and alignment of a stack slot.
349 ///   Each argument will be allocated to a multiple of this number of
350 ///   slots, and all the slots will be aligned to this value.
351 /// \param AllowHigherAlign - The slot alignment is not a cap;
352 ///   an argument type with an alignment greater than the slot size
353 ///   will be emitted on a higher-alignment address, potentially
354 ///   leaving one or more empty slots behind as padding.
355 static Address emitVoidPtrVAArg(CodeGenFunction &CGF, Address VAListAddr,
356                                 QualType ValueTy, bool IsIndirect,
357                                 std::pair<CharUnits, CharUnits> ValueInfo,
358                                 CharUnits SlotSizeAndAlign,
359                                 bool AllowHigherAlign) {
360   // The size and alignment of the value that was passed directly.
361   CharUnits DirectSize, DirectAlign;
362   if (IsIndirect) {
363     DirectSize = CGF.getPointerSize();
364     DirectAlign = CGF.getPointerAlign();
365   } else {
366     DirectSize = ValueInfo.first;
367     DirectAlign = ValueInfo.second;
368   }
369 
370   // Cast the address we've calculated to the right type.
371   llvm::Type *DirectTy = CGF.ConvertTypeForMem(ValueTy);
372   if (IsIndirect)
373     DirectTy = DirectTy->getPointerTo(0);
374 
375   Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, DirectTy,
376                                         DirectSize, DirectAlign,
377                                         SlotSizeAndAlign,
378                                         AllowHigherAlign);
379 
380   if (IsIndirect) {
381     Addr = Address(CGF.Builder.CreateLoad(Addr), ValueInfo.second);
382   }
383 
384   return Addr;
385 
386 }
387 
388 static Address emitMergePHI(CodeGenFunction &CGF,
389                             Address Addr1, llvm::BasicBlock *Block1,
390                             Address Addr2, llvm::BasicBlock *Block2,
391                             const llvm::Twine &Name = "") {
392   assert(Addr1.getType() == Addr2.getType());
393   llvm::PHINode *PHI = CGF.Builder.CreatePHI(Addr1.getType(), 2, Name);
394   PHI->addIncoming(Addr1.getPointer(), Block1);
395   PHI->addIncoming(Addr2.getPointer(), Block2);
396   CharUnits Align = std::min(Addr1.getAlignment(), Addr2.getAlignment());
397   return Address(PHI, Align);
398 }
399 
400 TargetCodeGenInfo::~TargetCodeGenInfo() = default;
401 
402 // If someone can figure out a general rule for this, that would be great.
403 // It's probably just doomed to be platform-dependent, though.
404 unsigned TargetCodeGenInfo::getSizeOfUnwindException() const {
405   // Verified for:
406   //   x86-64     FreeBSD, Linux, Darwin
407   //   x86-32     FreeBSD, Linux, Darwin
408   //   PowerPC    Linux, Darwin
409   //   ARM        Darwin (*not* EABI)
410   //   AArch64    Linux
411   return 32;
412 }
413 
414 bool TargetCodeGenInfo::isNoProtoCallVariadic(const CallArgList &args,
415                                      const FunctionNoProtoType *fnType) const {
416   // The following conventions are known to require this to be false:
417   //   x86_stdcall
418   //   MIPS
419   // For everything else, we just prefer false unless we opt out.
420   return false;
421 }
422 
423 void
424 TargetCodeGenInfo::getDependentLibraryOption(llvm::StringRef Lib,
425                                              llvm::SmallString<24> &Opt) const {
426   // This assumes the user is passing a library name like "rt" instead of a
427   // filename like "librt.a/so", and that they don't care whether it's static or
428   // dynamic.
429   Opt = "-l";
430   Opt += Lib;
431 }
432 
433 unsigned TargetCodeGenInfo::getOpenCLKernelCallingConv() const {
434   // OpenCL kernels are called via an explicit runtime API with arguments
435   // set with clSetKernelArg(), not as normal sub-functions.
436   // Return SPIR_KERNEL by default as the kernel calling convention to
437   // ensure the fingerprint is fixed such way that each OpenCL argument
438   // gets one matching argument in the produced kernel function argument
439   // list to enable feasible implementation of clSetKernelArg() with
440   // aggregates etc. In case we would use the default C calling conv here,
441   // clSetKernelArg() might break depending on the target-specific
442   // conventions; different targets might split structs passed as values
443   // to multiple function arguments etc.
444   return llvm::CallingConv::SPIR_KERNEL;
445 }
446 
447 llvm::Constant *TargetCodeGenInfo::getNullPointer(const CodeGen::CodeGenModule &CGM,
448     llvm::PointerType *T, QualType QT) const {
449   return llvm::ConstantPointerNull::get(T);
450 }
451 
452 LangAS TargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM,
453                                                    const VarDecl *D) const {
454   assert(!CGM.getLangOpts().OpenCL &&
455          !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) &&
456          "Address space agnostic languages only");
457   return D ? D->getType().getAddressSpace() : LangAS::Default;
458 }
459 
460 llvm::Value *TargetCodeGenInfo::performAddrSpaceCast(
461     CodeGen::CodeGenFunction &CGF, llvm::Value *Src, LangAS SrcAddr,
462     LangAS DestAddr, llvm::Type *DestTy, bool isNonNull) const {
463   // Since target may map different address spaces in AST to the same address
464   // space, an address space conversion may end up as a bitcast.
465   if (auto *C = dyn_cast<llvm::Constant>(Src))
466     return performAddrSpaceCast(CGF.CGM, C, SrcAddr, DestAddr, DestTy);
467   // Try to preserve the source's name to make IR more readable.
468   return CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
469       Src, DestTy, Src->hasName() ? Src->getName() + ".ascast" : "");
470 }
471 
472 llvm::Constant *
473 TargetCodeGenInfo::performAddrSpaceCast(CodeGenModule &CGM, llvm::Constant *Src,
474                                         LangAS SrcAddr, LangAS DestAddr,
475                                         llvm::Type *DestTy) const {
476   // Since target may map different address spaces in AST to the same address
477   // space, an address space conversion may end up as a bitcast.
478   return llvm::ConstantExpr::getPointerCast(Src, DestTy);
479 }
480 
481 llvm::SyncScope::ID
482 TargetCodeGenInfo::getLLVMSyncScopeID(const LangOptions &LangOpts,
483                                       SyncScope Scope,
484                                       llvm::AtomicOrdering Ordering,
485                                       llvm::LLVMContext &Ctx) const {
486   return Ctx.getOrInsertSyncScopeID(""); /* default sync scope */
487 }
488 
489 static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays);
490 
491 /// isEmptyField - Return true iff a the field is "empty", that is it
492 /// is an unnamed bit-field or an (array of) empty record(s).
493 static bool isEmptyField(ASTContext &Context, const FieldDecl *FD,
494                          bool AllowArrays) {
495   if (FD->isUnnamedBitfield())
496     return true;
497 
498   QualType FT = FD->getType();
499 
500   // Constant arrays of empty records count as empty, strip them off.
501   // Constant arrays of zero length always count as empty.
502   bool WasArray = false;
503   if (AllowArrays)
504     while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
505       if (AT->getSize() == 0)
506         return true;
507       FT = AT->getElementType();
508       // The [[no_unique_address]] special case below does not apply to
509       // arrays of C++ empty records, so we need to remember this fact.
510       WasArray = true;
511     }
512 
513   const RecordType *RT = FT->getAs<RecordType>();
514   if (!RT)
515     return false;
516 
517   // C++ record fields are never empty, at least in the Itanium ABI.
518   //
519   // FIXME: We should use a predicate for whether this behavior is true in the
520   // current ABI.
521   //
522   // The exception to the above rule are fields marked with the
523   // [[no_unique_address]] attribute (since C++20).  Those do count as empty
524   // according to the Itanium ABI.  The exception applies only to records,
525   // not arrays of records, so we must also check whether we stripped off an
526   // array type above.
527   if (isa<CXXRecordDecl>(RT->getDecl()) &&
528       (WasArray || !FD->hasAttr<NoUniqueAddressAttr>()))
529     return false;
530 
531   return isEmptyRecord(Context, FT, AllowArrays);
532 }
533 
534 /// isEmptyRecord - Return true iff a structure contains only empty
535 /// fields. Note that a structure with a flexible array member is not
536 /// considered empty.
537 static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) {
538   const RecordType *RT = T->getAs<RecordType>();
539   if (!RT)
540     return false;
541   const RecordDecl *RD = RT->getDecl();
542   if (RD->hasFlexibleArrayMember())
543     return false;
544 
545   // If this is a C++ record, check the bases first.
546   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
547     for (const auto &I : CXXRD->bases())
548       if (!isEmptyRecord(Context, I.getType(), true))
549         return false;
550 
551   for (const auto *I : RD->fields())
552     if (!isEmptyField(Context, I, AllowArrays))
553       return false;
554   return true;
555 }
556 
557 /// isSingleElementStruct - Determine if a structure is a "single
558 /// element struct", i.e. it has exactly one non-empty field or
559 /// exactly one field which is itself a single element
560 /// struct. Structures with flexible array members are never
561 /// considered single element structs.
562 ///
563 /// \return The field declaration for the single non-empty field, if
564 /// it exists.
565 static const Type *isSingleElementStruct(QualType T, ASTContext &Context) {
566   const RecordType *RT = T->getAs<RecordType>();
567   if (!RT)
568     return nullptr;
569 
570   const RecordDecl *RD = RT->getDecl();
571   if (RD->hasFlexibleArrayMember())
572     return nullptr;
573 
574   const Type *Found = nullptr;
575 
576   // If this is a C++ record, check the bases first.
577   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
578     for (const auto &I : CXXRD->bases()) {
579       // Ignore empty records.
580       if (isEmptyRecord(Context, I.getType(), true))
581         continue;
582 
583       // If we already found an element then this isn't a single-element struct.
584       if (Found)
585         return nullptr;
586 
587       // If this is non-empty and not a single element struct, the composite
588       // cannot be a single element struct.
589       Found = isSingleElementStruct(I.getType(), Context);
590       if (!Found)
591         return nullptr;
592     }
593   }
594 
595   // Check for single element.
596   for (const auto *FD : RD->fields()) {
597     QualType FT = FD->getType();
598 
599     // Ignore empty fields.
600     if (isEmptyField(Context, FD, true))
601       continue;
602 
603     // If we already found an element then this isn't a single-element
604     // struct.
605     if (Found)
606       return nullptr;
607 
608     // Treat single element arrays as the element.
609     while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
610       if (AT->getSize().getZExtValue() != 1)
611         break;
612       FT = AT->getElementType();
613     }
614 
615     if (!isAggregateTypeForABI(FT)) {
616       Found = FT.getTypePtr();
617     } else {
618       Found = isSingleElementStruct(FT, Context);
619       if (!Found)
620         return nullptr;
621     }
622   }
623 
624   // We don't consider a struct a single-element struct if it has
625   // padding beyond the element type.
626   if (Found && Context.getTypeSize(Found) != Context.getTypeSize(T))
627     return nullptr;
628 
629   return Found;
630 }
631 
632 namespace {
633 Address EmitVAArgInstr(CodeGenFunction &CGF, Address VAListAddr, QualType Ty,
634                        const ABIArgInfo &AI) {
635   // This default implementation defers to the llvm backend's va_arg
636   // instruction. It can handle only passing arguments directly
637   // (typically only handled in the backend for primitive types), or
638   // aggregates passed indirectly by pointer (NOTE: if the "byval"
639   // flag has ABI impact in the callee, this implementation cannot
640   // work.)
641 
642   // Only a few cases are covered here at the moment -- those needed
643   // by the default abi.
644   llvm::Value *Val;
645 
646   if (AI.isIndirect()) {
647     assert(!AI.getPaddingType() &&
648            "Unexpected PaddingType seen in arginfo in generic VAArg emitter!");
649     assert(
650         !AI.getIndirectRealign() &&
651         "Unexpected IndirectRealign seen in arginfo in generic VAArg emitter!");
652 
653     auto TyInfo = CGF.getContext().getTypeInfoInChars(Ty);
654     CharUnits TyAlignForABI = TyInfo.second;
655 
656     llvm::Type *BaseTy =
657         llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
658     llvm::Value *Addr =
659         CGF.Builder.CreateVAArg(VAListAddr.getPointer(), BaseTy);
660     return Address(Addr, TyAlignForABI);
661   } else {
662     assert((AI.isDirect() || AI.isExtend()) &&
663            "Unexpected ArgInfo Kind in generic VAArg emitter!");
664 
665     assert(!AI.getInReg() &&
666            "Unexpected InReg seen in arginfo in generic VAArg emitter!");
667     assert(!AI.getPaddingType() &&
668            "Unexpected PaddingType seen in arginfo in generic VAArg emitter!");
669     assert(!AI.getDirectOffset() &&
670            "Unexpected DirectOffset seen in arginfo in generic VAArg emitter!");
671     assert(!AI.getCoerceToType() &&
672            "Unexpected CoerceToType seen in arginfo in generic VAArg emitter!");
673 
674     Address Temp = CGF.CreateMemTemp(Ty, "varet");
675     Val = CGF.Builder.CreateVAArg(VAListAddr.getPointer(), CGF.ConvertType(Ty));
676     CGF.Builder.CreateStore(Val, Temp);
677     return Temp;
678   }
679 }
680 
681 /// DefaultABIInfo - The default implementation for ABI specific
682 /// details. This implementation provides information which results in
683 /// self-consistent and sensible LLVM IR generation, but does not
684 /// conform to any particular ABI.
685 class DefaultABIInfo : public ABIInfo {
686 public:
687   DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
688 
689   ABIArgInfo classifyReturnType(QualType RetTy) const;
690   ABIArgInfo classifyArgumentType(QualType RetTy) const;
691 
692   void computeInfo(CGFunctionInfo &FI) const override {
693     if (!getCXXABI().classifyReturnType(FI))
694       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
695     for (auto &I : FI.arguments())
696       I.info = classifyArgumentType(I.type);
697   }
698 
699   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
700                     QualType Ty) const override {
701     return EmitVAArgInstr(CGF, VAListAddr, Ty, classifyArgumentType(Ty));
702   }
703 };
704 
705 class DefaultTargetCodeGenInfo : public TargetCodeGenInfo {
706 public:
707   DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
708       : TargetCodeGenInfo(std::make_unique<DefaultABIInfo>(CGT)) {}
709 };
710 
711 ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const {
712   Ty = useFirstFieldIfTransparentUnion(Ty);
713 
714   if (isAggregateTypeForABI(Ty)) {
715     // Records with non-trivial destructors/copy-constructors should not be
716     // passed by value.
717     if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
718       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
719 
720     return getNaturalAlignIndirect(Ty);
721   }
722 
723   // Treat an enum type as its underlying type.
724   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
725     Ty = EnumTy->getDecl()->getIntegerType();
726 
727   ASTContext &Context = getContext();
728   if (const auto *EIT = Ty->getAs<ExtIntType>())
729     if (EIT->getNumBits() >
730         Context.getTypeSize(Context.getTargetInfo().hasInt128Type()
731                                 ? Context.Int128Ty
732                                 : Context.LongLongTy))
733       return getNaturalAlignIndirect(Ty);
734 
735   return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
736                                             : ABIArgInfo::getDirect());
737 }
738 
739 ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const {
740   if (RetTy->isVoidType())
741     return ABIArgInfo::getIgnore();
742 
743   if (isAggregateTypeForABI(RetTy))
744     return getNaturalAlignIndirect(RetTy);
745 
746   // Treat an enum type as its underlying type.
747   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
748     RetTy = EnumTy->getDecl()->getIntegerType();
749 
750   if (const auto *EIT = RetTy->getAs<ExtIntType>())
751     if (EIT->getNumBits() >
752         getContext().getTypeSize(getContext().getTargetInfo().hasInt128Type()
753                                      ? getContext().Int128Ty
754                                      : getContext().LongLongTy))
755       return getNaturalAlignIndirect(RetTy);
756 
757   return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
758                                                : ABIArgInfo::getDirect());
759 }
760 
761 //===----------------------------------------------------------------------===//
762 // WebAssembly ABI Implementation
763 //
764 // This is a very simple ABI that relies a lot on DefaultABIInfo.
765 //===----------------------------------------------------------------------===//
766 
767 class WebAssemblyABIInfo final : public SwiftABIInfo {
768 public:
769   enum ABIKind {
770     MVP = 0,
771     ExperimentalMV = 1,
772   };
773 
774 private:
775   DefaultABIInfo defaultInfo;
776   ABIKind Kind;
777 
778 public:
779   explicit WebAssemblyABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind)
780       : SwiftABIInfo(CGT), defaultInfo(CGT), Kind(Kind) {}
781 
782 private:
783   ABIArgInfo classifyReturnType(QualType RetTy) const;
784   ABIArgInfo classifyArgumentType(QualType Ty) const;
785 
786   // DefaultABIInfo's classifyReturnType and classifyArgumentType are
787   // non-virtual, but computeInfo and EmitVAArg are virtual, so we
788   // overload them.
789   void computeInfo(CGFunctionInfo &FI) const override {
790     if (!getCXXABI().classifyReturnType(FI))
791       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
792     for (auto &Arg : FI.arguments())
793       Arg.info = classifyArgumentType(Arg.type);
794   }
795 
796   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
797                     QualType Ty) const override;
798 
799   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
800                                     bool asReturnValue) const override {
801     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
802   }
803 
804   bool isSwiftErrorInRegister() const override {
805     return false;
806   }
807 };
808 
809 class WebAssemblyTargetCodeGenInfo final : public TargetCodeGenInfo {
810 public:
811   explicit WebAssemblyTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
812                                         WebAssemblyABIInfo::ABIKind K)
813       : TargetCodeGenInfo(std::make_unique<WebAssemblyABIInfo>(CGT, K)) {}
814 
815   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
816                            CodeGen::CodeGenModule &CGM) const override {
817     TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
818     if (const auto *FD = dyn_cast_or_null<FunctionDecl>(D)) {
819       if (const auto *Attr = FD->getAttr<WebAssemblyImportModuleAttr>()) {
820         llvm::Function *Fn = cast<llvm::Function>(GV);
821         llvm::AttrBuilder B;
822         B.addAttribute("wasm-import-module", Attr->getImportModule());
823         Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
824       }
825       if (const auto *Attr = FD->getAttr<WebAssemblyImportNameAttr>()) {
826         llvm::Function *Fn = cast<llvm::Function>(GV);
827         llvm::AttrBuilder B;
828         B.addAttribute("wasm-import-name", Attr->getImportName());
829         Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
830       }
831       if (const auto *Attr = FD->getAttr<WebAssemblyExportNameAttr>()) {
832         llvm::Function *Fn = cast<llvm::Function>(GV);
833         llvm::AttrBuilder B;
834         B.addAttribute("wasm-export-name", Attr->getExportName());
835         Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
836       }
837     }
838 
839     if (auto *FD = dyn_cast_or_null<FunctionDecl>(D)) {
840       llvm::Function *Fn = cast<llvm::Function>(GV);
841       if (!FD->doesThisDeclarationHaveABody() && !FD->hasPrototype())
842         Fn->addFnAttr("no-prototype");
843     }
844   }
845 };
846 
847 /// Classify argument of given type \p Ty.
848 ABIArgInfo WebAssemblyABIInfo::classifyArgumentType(QualType Ty) const {
849   Ty = useFirstFieldIfTransparentUnion(Ty);
850 
851   if (isAggregateTypeForABI(Ty)) {
852     // Records with non-trivial destructors/copy-constructors should not be
853     // passed by value.
854     if (auto RAA = getRecordArgABI(Ty, getCXXABI()))
855       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
856     // Ignore empty structs/unions.
857     if (isEmptyRecord(getContext(), Ty, true))
858       return ABIArgInfo::getIgnore();
859     // Lower single-element structs to just pass a regular value. TODO: We
860     // could do reasonable-size multiple-element structs too, using getExpand(),
861     // though watch out for things like bitfields.
862     if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
863       return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
864     // For the experimental multivalue ABI, fully expand all other aggregates
865     if (Kind == ABIKind::ExperimentalMV) {
866       const RecordType *RT = Ty->getAs<RecordType>();
867       assert(RT);
868       bool HasBitField = false;
869       for (auto *Field : RT->getDecl()->fields()) {
870         if (Field->isBitField()) {
871           HasBitField = true;
872           break;
873         }
874       }
875       if (!HasBitField)
876         return ABIArgInfo::getExpand();
877     }
878   }
879 
880   // Otherwise just do the default thing.
881   return defaultInfo.classifyArgumentType(Ty);
882 }
883 
884 ABIArgInfo WebAssemblyABIInfo::classifyReturnType(QualType RetTy) const {
885   if (isAggregateTypeForABI(RetTy)) {
886     // Records with non-trivial destructors/copy-constructors should not be
887     // returned by value.
888     if (!getRecordArgABI(RetTy, getCXXABI())) {
889       // Ignore empty structs/unions.
890       if (isEmptyRecord(getContext(), RetTy, true))
891         return ABIArgInfo::getIgnore();
892       // Lower single-element structs to just return a regular value. TODO: We
893       // could do reasonable-size multiple-element structs too, using
894       // ABIArgInfo::getDirect().
895       if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
896         return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
897       // For the experimental multivalue ABI, return all other aggregates
898       if (Kind == ABIKind::ExperimentalMV)
899         return ABIArgInfo::getDirect();
900     }
901   }
902 
903   // Otherwise just do the default thing.
904   return defaultInfo.classifyReturnType(RetTy);
905 }
906 
907 Address WebAssemblyABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
908                                       QualType Ty) const {
909   bool IsIndirect = isAggregateTypeForABI(Ty) &&
910                     !isEmptyRecord(getContext(), Ty, true) &&
911                     !isSingleElementStruct(Ty, getContext());
912   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
913                           getContext().getTypeInfoInChars(Ty),
914                           CharUnits::fromQuantity(4),
915                           /*AllowHigherAlign=*/true);
916 }
917 
918 //===----------------------------------------------------------------------===//
919 // le32/PNaCl bitcode ABI Implementation
920 //
921 // This is a simplified version of the x86_32 ABI.  Arguments and return values
922 // are always passed on the stack.
923 //===----------------------------------------------------------------------===//
924 
925 class PNaClABIInfo : public ABIInfo {
926  public:
927   PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
928 
929   ABIArgInfo classifyReturnType(QualType RetTy) const;
930   ABIArgInfo classifyArgumentType(QualType RetTy) const;
931 
932   void computeInfo(CGFunctionInfo &FI) const override;
933   Address EmitVAArg(CodeGenFunction &CGF,
934                     Address VAListAddr, QualType Ty) const override;
935 };
936 
937 class PNaClTargetCodeGenInfo : public TargetCodeGenInfo {
938  public:
939    PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
940        : TargetCodeGenInfo(std::make_unique<PNaClABIInfo>(CGT)) {}
941 };
942 
943 void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const {
944   if (!getCXXABI().classifyReturnType(FI))
945     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
946 
947   for (auto &I : FI.arguments())
948     I.info = classifyArgumentType(I.type);
949 }
950 
951 Address PNaClABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
952                                 QualType Ty) const {
953   // The PNaCL ABI is a bit odd, in that varargs don't use normal
954   // function classification. Structs get passed directly for varargs
955   // functions, through a rewriting transform in
956   // pnacl-llvm/lib/Transforms/NaCl/ExpandVarArgs.cpp, which allows
957   // this target to actually support a va_arg instructions with an
958   // aggregate type, unlike other targets.
959   return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
960 }
961 
962 /// Classify argument of given type \p Ty.
963 ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const {
964   if (isAggregateTypeForABI(Ty)) {
965     if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
966       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
967     return getNaturalAlignIndirect(Ty);
968   } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
969     // Treat an enum type as its underlying type.
970     Ty = EnumTy->getDecl()->getIntegerType();
971   } else if (Ty->isFloatingType()) {
972     // Floating-point types don't go inreg.
973     return ABIArgInfo::getDirect();
974   } else if (const auto *EIT = Ty->getAs<ExtIntType>()) {
975     // Treat extended integers as integers if <=64, otherwise pass indirectly.
976     if (EIT->getNumBits() > 64)
977       return getNaturalAlignIndirect(Ty);
978     return ABIArgInfo::getDirect();
979   }
980 
981   return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
982                                             : ABIArgInfo::getDirect());
983 }
984 
985 ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const {
986   if (RetTy->isVoidType())
987     return ABIArgInfo::getIgnore();
988 
989   // In the PNaCl ABI we always return records/structures on the stack.
990   if (isAggregateTypeForABI(RetTy))
991     return getNaturalAlignIndirect(RetTy);
992 
993   // Treat extended integers as integers if <=64, otherwise pass indirectly.
994   if (const auto *EIT = RetTy->getAs<ExtIntType>()) {
995     if (EIT->getNumBits() > 64)
996       return getNaturalAlignIndirect(RetTy);
997     return ABIArgInfo::getDirect();
998   }
999 
1000   // Treat an enum type as its underlying type.
1001   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
1002     RetTy = EnumTy->getDecl()->getIntegerType();
1003 
1004   return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
1005                                                : ABIArgInfo::getDirect());
1006 }
1007 
1008 /// IsX86_MMXType - Return true if this is an MMX type.
1009 bool IsX86_MMXType(llvm::Type *IRType) {
1010   // Return true if the type is an MMX type <2 x i32>, <4 x i16>, or <8 x i8>.
1011   return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 &&
1012     cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() &&
1013     IRType->getScalarSizeInBits() != 64;
1014 }
1015 
1016 static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
1017                                           StringRef Constraint,
1018                                           llvm::Type* Ty) {
1019   bool IsMMXCons = llvm::StringSwitch<bool>(Constraint)
1020                      .Cases("y", "&y", "^Ym", true)
1021                      .Default(false);
1022   if (IsMMXCons && Ty->isVectorTy()) {
1023     if (cast<llvm::VectorType>(Ty)->getPrimitiveSizeInBits().getFixedSize() !=
1024         64) {
1025       // Invalid MMX constraint
1026       return nullptr;
1027     }
1028 
1029     return llvm::Type::getX86_MMXTy(CGF.getLLVMContext());
1030   }
1031 
1032   // No operation needed
1033   return Ty;
1034 }
1035 
1036 /// Returns true if this type can be passed in SSE registers with the
1037 /// X86_VectorCall calling convention. Shared between x86_32 and x86_64.
1038 static bool isX86VectorTypeForVectorCall(ASTContext &Context, QualType Ty) {
1039   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
1040     if (BT->isFloatingPoint() && BT->getKind() != BuiltinType::Half) {
1041       if (BT->getKind() == BuiltinType::LongDouble) {
1042         if (&Context.getTargetInfo().getLongDoubleFormat() ==
1043             &llvm::APFloat::x87DoubleExtended())
1044           return false;
1045       }
1046       return true;
1047     }
1048   } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
1049     // vectorcall can pass XMM, YMM, and ZMM vectors. We don't pass SSE1 MMX
1050     // registers specially.
1051     unsigned VecSize = Context.getTypeSize(VT);
1052     if (VecSize == 128 || VecSize == 256 || VecSize == 512)
1053       return true;
1054   }
1055   return false;
1056 }
1057 
1058 /// Returns true if this aggregate is small enough to be passed in SSE registers
1059 /// in the X86_VectorCall calling convention. Shared between x86_32 and x86_64.
1060 static bool isX86VectorCallAggregateSmallEnough(uint64_t NumMembers) {
1061   return NumMembers <= 4;
1062 }
1063 
1064 /// Returns a Homogeneous Vector Aggregate ABIArgInfo, used in X86.
1065 static ABIArgInfo getDirectX86Hva(llvm::Type* T = nullptr) {
1066   auto AI = ABIArgInfo::getDirect(T);
1067   AI.setInReg(true);
1068   AI.setCanBeFlattened(false);
1069   return AI;
1070 }
1071 
1072 //===----------------------------------------------------------------------===//
1073 // X86-32 ABI Implementation
1074 //===----------------------------------------------------------------------===//
1075 
1076 /// Similar to llvm::CCState, but for Clang.
1077 struct CCState {
1078   CCState(CGFunctionInfo &FI)
1079       : IsPreassigned(FI.arg_size()), CC(FI.getCallingConvention()) {}
1080 
1081   llvm::SmallBitVector IsPreassigned;
1082   unsigned CC = CallingConv::CC_C;
1083   unsigned FreeRegs = 0;
1084   unsigned FreeSSERegs = 0;
1085 };
1086 
1087 enum {
1088   // Vectorcall only allows the first 6 parameters to be passed in registers.
1089   VectorcallMaxParamNumAsReg = 6
1090 };
1091 
1092 /// X86_32ABIInfo - The X86-32 ABI information.
1093 class X86_32ABIInfo : public SwiftABIInfo {
1094   enum Class {
1095     Integer,
1096     Float
1097   };
1098 
1099   static const unsigned MinABIStackAlignInBytes = 4;
1100 
1101   bool IsDarwinVectorABI;
1102   bool IsRetSmallStructInRegABI;
1103   bool IsWin32StructABI;
1104   bool IsSoftFloatABI;
1105   bool IsMCUABI;
1106   unsigned DefaultNumRegisterParameters;
1107 
1108   static bool isRegisterSize(unsigned Size) {
1109     return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
1110   }
1111 
1112   bool isHomogeneousAggregateBaseType(QualType Ty) const override {
1113     // FIXME: Assumes vectorcall is in use.
1114     return isX86VectorTypeForVectorCall(getContext(), Ty);
1115   }
1116 
1117   bool isHomogeneousAggregateSmallEnough(const Type *Ty,
1118                                          uint64_t NumMembers) const override {
1119     // FIXME: Assumes vectorcall is in use.
1120     return isX86VectorCallAggregateSmallEnough(NumMembers);
1121   }
1122 
1123   bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context) const;
1124 
1125   /// getIndirectResult - Give a source type \arg Ty, return a suitable result
1126   /// such that the argument will be passed in memory.
1127   ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
1128 
1129   ABIArgInfo getIndirectReturnResult(QualType Ty, CCState &State) const;
1130 
1131   /// Return the alignment to use for the given type on the stack.
1132   unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const;
1133 
1134   Class classify(QualType Ty) const;
1135   ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const;
1136   ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
1137 
1138   /// Updates the number of available free registers, returns
1139   /// true if any registers were allocated.
1140   bool updateFreeRegs(QualType Ty, CCState &State) const;
1141 
1142   bool shouldAggregateUseDirect(QualType Ty, CCState &State, bool &InReg,
1143                                 bool &NeedsPadding) const;
1144   bool shouldPrimitiveUseInReg(QualType Ty, CCState &State) const;
1145 
1146   bool canExpandIndirectArgument(QualType Ty) const;
1147 
1148   /// Rewrite the function info so that all memory arguments use
1149   /// inalloca.
1150   void rewriteWithInAlloca(CGFunctionInfo &FI) const;
1151 
1152   void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
1153                            CharUnits &StackOffset, ABIArgInfo &Info,
1154                            QualType Type) const;
1155   void runVectorCallFirstPass(CGFunctionInfo &FI, CCState &State) const;
1156 
1157 public:
1158 
1159   void computeInfo(CGFunctionInfo &FI) const override;
1160   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
1161                     QualType Ty) const override;
1162 
1163   X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
1164                 bool RetSmallStructInRegABI, bool Win32StructABI,
1165                 unsigned NumRegisterParameters, bool SoftFloatABI)
1166     : SwiftABIInfo(CGT), IsDarwinVectorABI(DarwinVectorABI),
1167       IsRetSmallStructInRegABI(RetSmallStructInRegABI),
1168       IsWin32StructABI(Win32StructABI),
1169       IsSoftFloatABI(SoftFloatABI),
1170       IsMCUABI(CGT.getTarget().getTriple().isOSIAMCU()),
1171       DefaultNumRegisterParameters(NumRegisterParameters) {}
1172 
1173   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
1174                                     bool asReturnValue) const override {
1175     // LLVM's x86-32 lowering currently only assigns up to three
1176     // integer registers and three fp registers.  Oddly, it'll use up to
1177     // four vector registers for vectors, but those can overlap with the
1178     // scalar registers.
1179     return occupiesMoreThan(CGT, scalars, /*total*/ 3);
1180   }
1181 
1182   bool isSwiftErrorInRegister() const override {
1183     // x86-32 lowering does not support passing swifterror in a register.
1184     return false;
1185   }
1186 };
1187 
1188 class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
1189 public:
1190   X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
1191                           bool RetSmallStructInRegABI, bool Win32StructABI,
1192                           unsigned NumRegisterParameters, bool SoftFloatABI)
1193       : TargetCodeGenInfo(std::make_unique<X86_32ABIInfo>(
1194             CGT, DarwinVectorABI, RetSmallStructInRegABI, Win32StructABI,
1195             NumRegisterParameters, SoftFloatABI)) {}
1196 
1197   static bool isStructReturnInRegABI(
1198       const llvm::Triple &Triple, const CodeGenOptions &Opts);
1199 
1200   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
1201                            CodeGen::CodeGenModule &CGM) const override;
1202 
1203   int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
1204     // Darwin uses different dwarf register numbers for EH.
1205     if (CGM.getTarget().getTriple().isOSDarwin()) return 5;
1206     return 4;
1207   }
1208 
1209   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
1210                                llvm::Value *Address) const override;
1211 
1212   llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
1213                                   StringRef Constraint,
1214                                   llvm::Type* Ty) const override {
1215     return X86AdjustInlineAsmType(CGF, Constraint, Ty);
1216   }
1217 
1218   void addReturnRegisterOutputs(CodeGenFunction &CGF, LValue ReturnValue,
1219                                 std::string &Constraints,
1220                                 std::vector<llvm::Type *> &ResultRegTypes,
1221                                 std::vector<llvm::Type *> &ResultTruncRegTypes,
1222                                 std::vector<LValue> &ResultRegDests,
1223                                 std::string &AsmString,
1224                                 unsigned NumOutputs) const override;
1225 
1226   llvm::Constant *
1227   getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
1228     unsigned Sig = (0xeb << 0) |  // jmp rel8
1229                    (0x06 << 8) |  //           .+0x08
1230                    ('v' << 16) |
1231                    ('2' << 24);
1232     return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
1233   }
1234 
1235   StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
1236     return "movl\t%ebp, %ebp"
1237            "\t\t// marker for objc_retainAutoreleaseReturnValue";
1238   }
1239 };
1240 
1241 }
1242 
1243 /// Rewrite input constraint references after adding some output constraints.
1244 /// In the case where there is one output and one input and we add one output,
1245 /// we need to replace all operand references greater than or equal to 1:
1246 ///     mov $0, $1
1247 ///     mov eax, $1
1248 /// The result will be:
1249 ///     mov $0, $2
1250 ///     mov eax, $2
1251 static void rewriteInputConstraintReferences(unsigned FirstIn,
1252                                              unsigned NumNewOuts,
1253                                              std::string &AsmString) {
1254   std::string Buf;
1255   llvm::raw_string_ostream OS(Buf);
1256   size_t Pos = 0;
1257   while (Pos < AsmString.size()) {
1258     size_t DollarStart = AsmString.find('$', Pos);
1259     if (DollarStart == std::string::npos)
1260       DollarStart = AsmString.size();
1261     size_t DollarEnd = AsmString.find_first_not_of('$', DollarStart);
1262     if (DollarEnd == std::string::npos)
1263       DollarEnd = AsmString.size();
1264     OS << StringRef(&AsmString[Pos], DollarEnd - Pos);
1265     Pos = DollarEnd;
1266     size_t NumDollars = DollarEnd - DollarStart;
1267     if (NumDollars % 2 != 0 && Pos < AsmString.size()) {
1268       // We have an operand reference.
1269       size_t DigitStart = Pos;
1270       if (AsmString[DigitStart] == '{') {
1271         OS << '{';
1272         ++DigitStart;
1273       }
1274       size_t DigitEnd = AsmString.find_first_not_of("0123456789", DigitStart);
1275       if (DigitEnd == std::string::npos)
1276         DigitEnd = AsmString.size();
1277       StringRef OperandStr(&AsmString[DigitStart], DigitEnd - DigitStart);
1278       unsigned OperandIndex;
1279       if (!OperandStr.getAsInteger(10, OperandIndex)) {
1280         if (OperandIndex >= FirstIn)
1281           OperandIndex += NumNewOuts;
1282         OS << OperandIndex;
1283       } else {
1284         OS << OperandStr;
1285       }
1286       Pos = DigitEnd;
1287     }
1288   }
1289   AsmString = std::move(OS.str());
1290 }
1291 
1292 /// Add output constraints for EAX:EDX because they are return registers.
1293 void X86_32TargetCodeGenInfo::addReturnRegisterOutputs(
1294     CodeGenFunction &CGF, LValue ReturnSlot, std::string &Constraints,
1295     std::vector<llvm::Type *> &ResultRegTypes,
1296     std::vector<llvm::Type *> &ResultTruncRegTypes,
1297     std::vector<LValue> &ResultRegDests, std::string &AsmString,
1298     unsigned NumOutputs) const {
1299   uint64_t RetWidth = CGF.getContext().getTypeSize(ReturnSlot.getType());
1300 
1301   // Use the EAX constraint if the width is 32 or smaller and EAX:EDX if it is
1302   // larger.
1303   if (!Constraints.empty())
1304     Constraints += ',';
1305   if (RetWidth <= 32) {
1306     Constraints += "={eax}";
1307     ResultRegTypes.push_back(CGF.Int32Ty);
1308   } else {
1309     // Use the 'A' constraint for EAX:EDX.
1310     Constraints += "=A";
1311     ResultRegTypes.push_back(CGF.Int64Ty);
1312   }
1313 
1314   // Truncate EAX or EAX:EDX to an integer of the appropriate size.
1315   llvm::Type *CoerceTy = llvm::IntegerType::get(CGF.getLLVMContext(), RetWidth);
1316   ResultTruncRegTypes.push_back(CoerceTy);
1317 
1318   // Coerce the integer by bitcasting the return slot pointer.
1319   ReturnSlot.setAddress(CGF.Builder.CreateBitCast(ReturnSlot.getAddress(CGF),
1320                                                   CoerceTy->getPointerTo()));
1321   ResultRegDests.push_back(ReturnSlot);
1322 
1323   rewriteInputConstraintReferences(NumOutputs, 1, AsmString);
1324 }
1325 
1326 /// shouldReturnTypeInRegister - Determine if the given type should be
1327 /// returned in a register (for the Darwin and MCU ABI).
1328 bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
1329                                                ASTContext &Context) const {
1330   uint64_t Size = Context.getTypeSize(Ty);
1331 
1332   // For i386, type must be register sized.
1333   // For the MCU ABI, it only needs to be <= 8-byte
1334   if ((IsMCUABI && Size > 64) || (!IsMCUABI && !isRegisterSize(Size)))
1335    return false;
1336 
1337   if (Ty->isVectorType()) {
1338     // 64- and 128- bit vectors inside structures are not returned in
1339     // registers.
1340     if (Size == 64 || Size == 128)
1341       return false;
1342 
1343     return true;
1344   }
1345 
1346   // If this is a builtin, pointer, enum, complex type, member pointer, or
1347   // member function pointer it is ok.
1348   if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() ||
1349       Ty->isAnyComplexType() || Ty->isEnumeralType() ||
1350       Ty->isBlockPointerType() || Ty->isMemberPointerType())
1351     return true;
1352 
1353   // Arrays are treated like records.
1354   if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
1355     return shouldReturnTypeInRegister(AT->getElementType(), Context);
1356 
1357   // Otherwise, it must be a record type.
1358   const RecordType *RT = Ty->getAs<RecordType>();
1359   if (!RT) return false;
1360 
1361   // FIXME: Traverse bases here too.
1362 
1363   // Structure types are passed in register if all fields would be
1364   // passed in a register.
1365   for (const auto *FD : RT->getDecl()->fields()) {
1366     // Empty fields are ignored.
1367     if (isEmptyField(Context, FD, true))
1368       continue;
1369 
1370     // Check fields recursively.
1371     if (!shouldReturnTypeInRegister(FD->getType(), Context))
1372       return false;
1373   }
1374   return true;
1375 }
1376 
1377 static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
1378   // Treat complex types as the element type.
1379   if (const ComplexType *CTy = Ty->getAs<ComplexType>())
1380     Ty = CTy->getElementType();
1381 
1382   // Check for a type which we know has a simple scalar argument-passing
1383   // convention without any padding.  (We're specifically looking for 32
1384   // and 64-bit integer and integer-equivalents, float, and double.)
1385   if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() &&
1386       !Ty->isEnumeralType() && !Ty->isBlockPointerType())
1387     return false;
1388 
1389   uint64_t Size = Context.getTypeSize(Ty);
1390   return Size == 32 || Size == 64;
1391 }
1392 
1393 static bool addFieldSizes(ASTContext &Context, const RecordDecl *RD,
1394                           uint64_t &Size) {
1395   for (const auto *FD : RD->fields()) {
1396     // Scalar arguments on the stack get 4 byte alignment on x86. If the
1397     // argument is smaller than 32-bits, expanding the struct will create
1398     // alignment padding.
1399     if (!is32Or64BitBasicType(FD->getType(), Context))
1400       return false;
1401 
1402     // FIXME: Reject bit-fields wholesale; there are two problems, we don't know
1403     // how to expand them yet, and the predicate for telling if a bitfield still
1404     // counts as "basic" is more complicated than what we were doing previously.
1405     if (FD->isBitField())
1406       return false;
1407 
1408     Size += Context.getTypeSize(FD->getType());
1409   }
1410   return true;
1411 }
1412 
1413 static bool addBaseAndFieldSizes(ASTContext &Context, const CXXRecordDecl *RD,
1414                                  uint64_t &Size) {
1415   // Don't do this if there are any non-empty bases.
1416   for (const CXXBaseSpecifier &Base : RD->bases()) {
1417     if (!addBaseAndFieldSizes(Context, Base.getType()->getAsCXXRecordDecl(),
1418                               Size))
1419       return false;
1420   }
1421   if (!addFieldSizes(Context, RD, Size))
1422     return false;
1423   return true;
1424 }
1425 
1426 /// Test whether an argument type which is to be passed indirectly (on the
1427 /// stack) would have the equivalent layout if it was expanded into separate
1428 /// arguments. If so, we prefer to do the latter to avoid inhibiting
1429 /// optimizations.
1430 bool X86_32ABIInfo::canExpandIndirectArgument(QualType Ty) const {
1431   // We can only expand structure types.
1432   const RecordType *RT = Ty->getAs<RecordType>();
1433   if (!RT)
1434     return false;
1435   const RecordDecl *RD = RT->getDecl();
1436   uint64_t Size = 0;
1437   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
1438     if (!IsWin32StructABI) {
1439       // On non-Windows, we have to conservatively match our old bitcode
1440       // prototypes in order to be ABI-compatible at the bitcode level.
1441       if (!CXXRD->isCLike())
1442         return false;
1443     } else {
1444       // Don't do this for dynamic classes.
1445       if (CXXRD->isDynamicClass())
1446         return false;
1447     }
1448     if (!addBaseAndFieldSizes(getContext(), CXXRD, Size))
1449       return false;
1450   } else {
1451     if (!addFieldSizes(getContext(), RD, Size))
1452       return false;
1453   }
1454 
1455   // We can do this if there was no alignment padding.
1456   return Size == getContext().getTypeSize(Ty);
1457 }
1458 
1459 ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(QualType RetTy, CCState &State) const {
1460   // If the return value is indirect, then the hidden argument is consuming one
1461   // integer register.
1462   if (State.FreeRegs) {
1463     --State.FreeRegs;
1464     if (!IsMCUABI)
1465       return getNaturalAlignIndirectInReg(RetTy);
1466   }
1467   return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
1468 }
1469 
1470 ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy,
1471                                              CCState &State) const {
1472   if (RetTy->isVoidType())
1473     return ABIArgInfo::getIgnore();
1474 
1475   const Type *Base = nullptr;
1476   uint64_t NumElts = 0;
1477   if ((State.CC == llvm::CallingConv::X86_VectorCall ||
1478        State.CC == llvm::CallingConv::X86_RegCall) &&
1479       isHomogeneousAggregate(RetTy, Base, NumElts)) {
1480     // The LLVM struct type for such an aggregate should lower properly.
1481     return ABIArgInfo::getDirect();
1482   }
1483 
1484   if (const VectorType *VT = RetTy->getAs<VectorType>()) {
1485     // On Darwin, some vectors are returned in registers.
1486     if (IsDarwinVectorABI) {
1487       uint64_t Size = getContext().getTypeSize(RetTy);
1488 
1489       // 128-bit vectors are a special case; they are returned in
1490       // registers and we need to make sure to pick a type the LLVM
1491       // backend will like.
1492       if (Size == 128)
1493         return ABIArgInfo::getDirect(llvm::FixedVectorType::get(
1494             llvm::Type::getInt64Ty(getVMContext()), 2));
1495 
1496       // Always return in register if it fits in a general purpose
1497       // register, or if it is 64 bits and has a single element.
1498       if ((Size == 8 || Size == 16 || Size == 32) ||
1499           (Size == 64 && VT->getNumElements() == 1))
1500         return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
1501                                                             Size));
1502 
1503       return getIndirectReturnResult(RetTy, State);
1504     }
1505 
1506     return ABIArgInfo::getDirect();
1507   }
1508 
1509   if (isAggregateTypeForABI(RetTy)) {
1510     if (const RecordType *RT = RetTy->getAs<RecordType>()) {
1511       // Structures with flexible arrays are always indirect.
1512       if (RT->getDecl()->hasFlexibleArrayMember())
1513         return getIndirectReturnResult(RetTy, State);
1514     }
1515 
1516     // If specified, structs and unions are always indirect.
1517     if (!IsRetSmallStructInRegABI && !RetTy->isAnyComplexType())
1518       return getIndirectReturnResult(RetTy, State);
1519 
1520     // Ignore empty structs/unions.
1521     if (isEmptyRecord(getContext(), RetTy, true))
1522       return ABIArgInfo::getIgnore();
1523 
1524     // Small structures which are register sized are generally returned
1525     // in a register.
1526     if (shouldReturnTypeInRegister(RetTy, getContext())) {
1527       uint64_t Size = getContext().getTypeSize(RetTy);
1528 
1529       // As a special-case, if the struct is a "single-element" struct, and
1530       // the field is of type "float" or "double", return it in a
1531       // floating-point register. (MSVC does not apply this special case.)
1532       // We apply a similar transformation for pointer types to improve the
1533       // quality of the generated IR.
1534       if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
1535         if ((!IsWin32StructABI && SeltTy->isRealFloatingType())
1536             || SeltTy->hasPointerRepresentation())
1537           return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
1538 
1539       // FIXME: We should be able to narrow this integer in cases with dead
1540       // padding.
1541       return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
1542     }
1543 
1544     return getIndirectReturnResult(RetTy, State);
1545   }
1546 
1547   // Treat an enum type as its underlying type.
1548   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
1549     RetTy = EnumTy->getDecl()->getIntegerType();
1550 
1551   if (const auto *EIT = RetTy->getAs<ExtIntType>())
1552     if (EIT->getNumBits() > 64)
1553       return getIndirectReturnResult(RetTy, State);
1554 
1555   return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
1556                                                : ABIArgInfo::getDirect());
1557 }
1558 
1559 static bool isSIMDVectorType(ASTContext &Context, QualType Ty) {
1560   return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128;
1561 }
1562 
1563 static bool isRecordWithSIMDVectorType(ASTContext &Context, QualType Ty) {
1564   const RecordType *RT = Ty->getAs<RecordType>();
1565   if (!RT)
1566     return 0;
1567   const RecordDecl *RD = RT->getDecl();
1568 
1569   // If this is a C++ record, check the bases first.
1570   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
1571     for (const auto &I : CXXRD->bases())
1572       if (!isRecordWithSIMDVectorType(Context, I.getType()))
1573         return false;
1574 
1575   for (const auto *i : RD->fields()) {
1576     QualType FT = i->getType();
1577 
1578     if (isSIMDVectorType(Context, FT))
1579       return true;
1580 
1581     if (isRecordWithSIMDVectorType(Context, FT))
1582       return true;
1583   }
1584 
1585   return false;
1586 }
1587 
1588 unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
1589                                                  unsigned Align) const {
1590   // Otherwise, if the alignment is less than or equal to the minimum ABI
1591   // alignment, just use the default; the backend will handle this.
1592   if (Align <= MinABIStackAlignInBytes)
1593     return 0; // Use default alignment.
1594 
1595   // On non-Darwin, the stack type alignment is always 4.
1596   if (!IsDarwinVectorABI) {
1597     // Set explicit alignment, since we may need to realign the top.
1598     return MinABIStackAlignInBytes;
1599   }
1600 
1601   // Otherwise, if the type contains an SSE vector type, the alignment is 16.
1602   if (Align >= 16 && (isSIMDVectorType(getContext(), Ty) ||
1603                       isRecordWithSIMDVectorType(getContext(), Ty)))
1604     return 16;
1605 
1606   return MinABIStackAlignInBytes;
1607 }
1608 
1609 ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal,
1610                                             CCState &State) const {
1611   if (!ByVal) {
1612     if (State.FreeRegs) {
1613       --State.FreeRegs; // Non-byval indirects just use one pointer.
1614       if (!IsMCUABI)
1615         return getNaturalAlignIndirectInReg(Ty);
1616     }
1617     return getNaturalAlignIndirect(Ty, false);
1618   }
1619 
1620   // Compute the byval alignment.
1621   unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
1622   unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign);
1623   if (StackAlign == 0)
1624     return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true);
1625 
1626   // If the stack alignment is less than the type alignment, realign the
1627   // argument.
1628   bool Realign = TypeAlign > StackAlign;
1629   return ABIArgInfo::getIndirect(CharUnits::fromQuantity(StackAlign),
1630                                  /*ByVal=*/true, Realign);
1631 }
1632 
1633 X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const {
1634   const Type *T = isSingleElementStruct(Ty, getContext());
1635   if (!T)
1636     T = Ty.getTypePtr();
1637 
1638   if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
1639     BuiltinType::Kind K = BT->getKind();
1640     if (K == BuiltinType::Float || K == BuiltinType::Double)
1641       return Float;
1642   }
1643   return Integer;
1644 }
1645 
1646 bool X86_32ABIInfo::updateFreeRegs(QualType Ty, CCState &State) const {
1647   if (!IsSoftFloatABI) {
1648     Class C = classify(Ty);
1649     if (C == Float)
1650       return false;
1651   }
1652 
1653   unsigned Size = getContext().getTypeSize(Ty);
1654   unsigned SizeInRegs = (Size + 31) / 32;
1655 
1656   if (SizeInRegs == 0)
1657     return false;
1658 
1659   if (!IsMCUABI) {
1660     if (SizeInRegs > State.FreeRegs) {
1661       State.FreeRegs = 0;
1662       return false;
1663     }
1664   } else {
1665     // The MCU psABI allows passing parameters in-reg even if there are
1666     // earlier parameters that are passed on the stack. Also,
1667     // it does not allow passing >8-byte structs in-register,
1668     // even if there are 3 free registers available.
1669     if (SizeInRegs > State.FreeRegs || SizeInRegs > 2)
1670       return false;
1671   }
1672 
1673   State.FreeRegs -= SizeInRegs;
1674   return true;
1675 }
1676 
1677 bool X86_32ABIInfo::shouldAggregateUseDirect(QualType Ty, CCState &State,
1678                                              bool &InReg,
1679                                              bool &NeedsPadding) const {
1680   // On Windows, aggregates other than HFAs are never passed in registers, and
1681   // they do not consume register slots. Homogenous floating-point aggregates
1682   // (HFAs) have already been dealt with at this point.
1683   if (IsWin32StructABI && isAggregateTypeForABI(Ty))
1684     return false;
1685 
1686   NeedsPadding = false;
1687   InReg = !IsMCUABI;
1688 
1689   if (!updateFreeRegs(Ty, State))
1690     return false;
1691 
1692   if (IsMCUABI)
1693     return true;
1694 
1695   if (State.CC == llvm::CallingConv::X86_FastCall ||
1696       State.CC == llvm::CallingConv::X86_VectorCall ||
1697       State.CC == llvm::CallingConv::X86_RegCall) {
1698     if (getContext().getTypeSize(Ty) <= 32 && State.FreeRegs)
1699       NeedsPadding = true;
1700 
1701     return false;
1702   }
1703 
1704   return true;
1705 }
1706 
1707 bool X86_32ABIInfo::shouldPrimitiveUseInReg(QualType Ty, CCState &State) const {
1708   if (!updateFreeRegs(Ty, State))
1709     return false;
1710 
1711   if (IsMCUABI)
1712     return false;
1713 
1714   if (State.CC == llvm::CallingConv::X86_FastCall ||
1715       State.CC == llvm::CallingConv::X86_VectorCall ||
1716       State.CC == llvm::CallingConv::X86_RegCall) {
1717     if (getContext().getTypeSize(Ty) > 32)
1718       return false;
1719 
1720     return (Ty->isIntegralOrEnumerationType() || Ty->isPointerType() ||
1721         Ty->isReferenceType());
1722   }
1723 
1724   return true;
1725 }
1726 
1727 void X86_32ABIInfo::runVectorCallFirstPass(CGFunctionInfo &FI, CCState &State) const {
1728   // Vectorcall x86 works subtly different than in x64, so the format is
1729   // a bit different than the x64 version.  First, all vector types (not HVAs)
1730   // are assigned, with the first 6 ending up in the [XYZ]MM0-5 registers.
1731   // This differs from the x64 implementation, where the first 6 by INDEX get
1732   // registers.
1733   // In the second pass over the arguments, HVAs are passed in the remaining
1734   // vector registers if possible, or indirectly by address. The address will be
1735   // passed in ECX/EDX if available. Any other arguments are passed according to
1736   // the usual fastcall rules.
1737   MutableArrayRef<CGFunctionInfoArgInfo> Args = FI.arguments();
1738   for (int I = 0, E = Args.size(); I < E; ++I) {
1739     const Type *Base = nullptr;
1740     uint64_t NumElts = 0;
1741     const QualType &Ty = Args[I].type;
1742     if ((Ty->isVectorType() || Ty->isBuiltinType()) &&
1743         isHomogeneousAggregate(Ty, Base, NumElts)) {
1744       if (State.FreeSSERegs >= NumElts) {
1745         State.FreeSSERegs -= NumElts;
1746         Args[I].info = ABIArgInfo::getDirectInReg();
1747         State.IsPreassigned.set(I);
1748       }
1749     }
1750   }
1751 }
1752 
1753 ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
1754                                                CCState &State) const {
1755   // FIXME: Set alignment on indirect arguments.
1756   bool IsFastCall = State.CC == llvm::CallingConv::X86_FastCall;
1757   bool IsRegCall = State.CC == llvm::CallingConv::X86_RegCall;
1758   bool IsVectorCall = State.CC == llvm::CallingConv::X86_VectorCall;
1759 
1760   Ty = useFirstFieldIfTransparentUnion(Ty);
1761   TypeInfo TI = getContext().getTypeInfo(Ty);
1762 
1763   // Check with the C++ ABI first.
1764   const RecordType *RT = Ty->getAs<RecordType>();
1765   if (RT) {
1766     CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
1767     if (RAA == CGCXXABI::RAA_Indirect) {
1768       return getIndirectResult(Ty, false, State);
1769     } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
1770       // The field index doesn't matter, we'll fix it up later.
1771       return ABIArgInfo::getInAlloca(/*FieldIndex=*/0);
1772     }
1773   }
1774 
1775   // Regcall uses the concept of a homogenous vector aggregate, similar
1776   // to other targets.
1777   const Type *Base = nullptr;
1778   uint64_t NumElts = 0;
1779   if ((IsRegCall || IsVectorCall) &&
1780       isHomogeneousAggregate(Ty, Base, NumElts)) {
1781     if (State.FreeSSERegs >= NumElts) {
1782       State.FreeSSERegs -= NumElts;
1783 
1784       // Vectorcall passes HVAs directly and does not flatten them, but regcall
1785       // does.
1786       if (IsVectorCall)
1787         return getDirectX86Hva();
1788 
1789       if (Ty->isBuiltinType() || Ty->isVectorType())
1790         return ABIArgInfo::getDirect();
1791       return ABIArgInfo::getExpand();
1792     }
1793     return getIndirectResult(Ty, /*ByVal=*/false, State);
1794   }
1795 
1796   if (isAggregateTypeForABI(Ty)) {
1797     // Structures with flexible arrays are always indirect.
1798     // FIXME: This should not be byval!
1799     if (RT && RT->getDecl()->hasFlexibleArrayMember())
1800       return getIndirectResult(Ty, true, State);
1801 
1802     // Ignore empty structs/unions on non-Windows.
1803     if (!IsWin32StructABI && isEmptyRecord(getContext(), Ty, true))
1804       return ABIArgInfo::getIgnore();
1805 
1806     llvm::LLVMContext &LLVMContext = getVMContext();
1807     llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
1808     bool NeedsPadding = false;
1809     bool InReg;
1810     if (shouldAggregateUseDirect(Ty, State, InReg, NeedsPadding)) {
1811       unsigned SizeInRegs = (TI.Width + 31) / 32;
1812       SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32);
1813       llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
1814       if (InReg)
1815         return ABIArgInfo::getDirectInReg(Result);
1816       else
1817         return ABIArgInfo::getDirect(Result);
1818     }
1819     llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : nullptr;
1820 
1821     // Pass over-aligned aggregates on Windows indirectly. This behavior was
1822     // added in MSVC 2015.
1823     if (IsWin32StructABI && TI.AlignIsRequired && TI.Align > 32)
1824       return getIndirectResult(Ty, /*ByVal=*/false, State);
1825 
1826     // Expand small (<= 128-bit) record types when we know that the stack layout
1827     // of those arguments will match the struct. This is important because the
1828     // LLVM backend isn't smart enough to remove byval, which inhibits many
1829     // optimizations.
1830     // Don't do this for the MCU if there are still free integer registers
1831     // (see X86_64 ABI for full explanation).
1832     if (TI.Width <= 4 * 32 && (!IsMCUABI || State.FreeRegs == 0) &&
1833         canExpandIndirectArgument(Ty))
1834       return ABIArgInfo::getExpandWithPadding(
1835           IsFastCall || IsVectorCall || IsRegCall, PaddingType);
1836 
1837     return getIndirectResult(Ty, true, State);
1838   }
1839 
1840   if (const VectorType *VT = Ty->getAs<VectorType>()) {
1841     // On Windows, vectors are passed directly if registers are available, or
1842     // indirectly if not. This avoids the need to align argument memory. Pass
1843     // user-defined vector types larger than 512 bits indirectly for simplicity.
1844     if (IsWin32StructABI) {
1845       if (TI.Width <= 512 && State.FreeSSERegs > 0) {
1846         --State.FreeSSERegs;
1847         return ABIArgInfo::getDirectInReg();
1848       }
1849       return getIndirectResult(Ty, /*ByVal=*/false, State);
1850     }
1851 
1852     // On Darwin, some vectors are passed in memory, we handle this by passing
1853     // it as an i8/i16/i32/i64.
1854     if (IsDarwinVectorABI) {
1855       if ((TI.Width == 8 || TI.Width == 16 || TI.Width == 32) ||
1856           (TI.Width == 64 && VT->getNumElements() == 1))
1857         return ABIArgInfo::getDirect(
1858             llvm::IntegerType::get(getVMContext(), TI.Width));
1859     }
1860 
1861     if (IsX86_MMXType(CGT.ConvertType(Ty)))
1862       return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64));
1863 
1864     return ABIArgInfo::getDirect();
1865   }
1866 
1867 
1868   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1869     Ty = EnumTy->getDecl()->getIntegerType();
1870 
1871   bool InReg = shouldPrimitiveUseInReg(Ty, State);
1872 
1873   if (isPromotableIntegerTypeForABI(Ty)) {
1874     if (InReg)
1875       return ABIArgInfo::getExtendInReg(Ty);
1876     return ABIArgInfo::getExtend(Ty);
1877   }
1878 
1879   if (const auto * EIT = Ty->getAs<ExtIntType>()) {
1880     if (EIT->getNumBits() <= 64) {
1881       if (InReg)
1882         return ABIArgInfo::getDirectInReg();
1883       return ABIArgInfo::getDirect();
1884     }
1885     return getIndirectResult(Ty, /*ByVal=*/false, State);
1886   }
1887 
1888   if (InReg)
1889     return ABIArgInfo::getDirectInReg();
1890   return ABIArgInfo::getDirect();
1891 }
1892 
1893 void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const {
1894   CCState State(FI);
1895   if (IsMCUABI)
1896     State.FreeRegs = 3;
1897   else if (State.CC == llvm::CallingConv::X86_FastCall) {
1898     State.FreeRegs = 2;
1899     State.FreeSSERegs = 3;
1900   } else if (State.CC == llvm::CallingConv::X86_VectorCall) {
1901     State.FreeRegs = 2;
1902     State.FreeSSERegs = 6;
1903   } else if (FI.getHasRegParm())
1904     State.FreeRegs = FI.getRegParm();
1905   else if (State.CC == llvm::CallingConv::X86_RegCall) {
1906     State.FreeRegs = 5;
1907     State.FreeSSERegs = 8;
1908   } else if (IsWin32StructABI) {
1909     // Since MSVC 2015, the first three SSE vectors have been passed in
1910     // registers. The rest are passed indirectly.
1911     State.FreeRegs = DefaultNumRegisterParameters;
1912     State.FreeSSERegs = 3;
1913   } else
1914     State.FreeRegs = DefaultNumRegisterParameters;
1915 
1916   if (!::classifyReturnType(getCXXABI(), FI, *this)) {
1917     FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), State);
1918   } else if (FI.getReturnInfo().isIndirect()) {
1919     // The C++ ABI is not aware of register usage, so we have to check if the
1920     // return value was sret and put it in a register ourselves if appropriate.
1921     if (State.FreeRegs) {
1922       --State.FreeRegs;  // The sret parameter consumes a register.
1923       if (!IsMCUABI)
1924         FI.getReturnInfo().setInReg(true);
1925     }
1926   }
1927 
1928   // The chain argument effectively gives us another free register.
1929   if (FI.isChainCall())
1930     ++State.FreeRegs;
1931 
1932   // For vectorcall, do a first pass over the arguments, assigning FP and vector
1933   // arguments to XMM registers as available.
1934   if (State.CC == llvm::CallingConv::X86_VectorCall)
1935     runVectorCallFirstPass(FI, State);
1936 
1937   bool UsedInAlloca = false;
1938   MutableArrayRef<CGFunctionInfoArgInfo> Args = FI.arguments();
1939   for (int I = 0, E = Args.size(); I < E; ++I) {
1940     // Skip arguments that have already been assigned.
1941     if (State.IsPreassigned.test(I))
1942       continue;
1943 
1944     Args[I].info = classifyArgumentType(Args[I].type, State);
1945     UsedInAlloca |= (Args[I].info.getKind() == ABIArgInfo::InAlloca);
1946   }
1947 
1948   // If we needed to use inalloca for any argument, do a second pass and rewrite
1949   // all the memory arguments to use inalloca.
1950   if (UsedInAlloca)
1951     rewriteWithInAlloca(FI);
1952 }
1953 
1954 void
1955 X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
1956                                    CharUnits &StackOffset, ABIArgInfo &Info,
1957                                    QualType Type) const {
1958   // Arguments are always 4-byte-aligned.
1959   CharUnits WordSize = CharUnits::fromQuantity(4);
1960   assert(StackOffset.isMultipleOf(WordSize) && "unaligned inalloca struct");
1961 
1962   // sret pointers and indirect things will require an extra pointer
1963   // indirection, unless they are byval. Most things are byval, and will not
1964   // require this indirection.
1965   bool IsIndirect = false;
1966   if (Info.isIndirect() && !Info.getIndirectByVal())
1967     IsIndirect = true;
1968   Info = ABIArgInfo::getInAlloca(FrameFields.size(), IsIndirect);
1969   llvm::Type *LLTy = CGT.ConvertTypeForMem(Type);
1970   if (IsIndirect)
1971     LLTy = LLTy->getPointerTo(0);
1972   FrameFields.push_back(LLTy);
1973   StackOffset += IsIndirect ? WordSize : getContext().getTypeSizeInChars(Type);
1974 
1975   // Insert padding bytes to respect alignment.
1976   CharUnits FieldEnd = StackOffset;
1977   StackOffset = FieldEnd.alignTo(WordSize);
1978   if (StackOffset != FieldEnd) {
1979     CharUnits NumBytes = StackOffset - FieldEnd;
1980     llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext());
1981     Ty = llvm::ArrayType::get(Ty, NumBytes.getQuantity());
1982     FrameFields.push_back(Ty);
1983   }
1984 }
1985 
1986 static bool isArgInAlloca(const ABIArgInfo &Info) {
1987   // Leave ignored and inreg arguments alone.
1988   switch (Info.getKind()) {
1989   case ABIArgInfo::InAlloca:
1990     return true;
1991   case ABIArgInfo::Ignore:
1992     return false;
1993   case ABIArgInfo::Indirect:
1994   case ABIArgInfo::Direct:
1995   case ABIArgInfo::Extend:
1996     return !Info.getInReg();
1997   case ABIArgInfo::Expand:
1998   case ABIArgInfo::CoerceAndExpand:
1999     // These are aggregate types which are never passed in registers when
2000     // inalloca is involved.
2001     return true;
2002   }
2003   llvm_unreachable("invalid enum");
2004 }
2005 
2006 void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const {
2007   assert(IsWin32StructABI && "inalloca only supported on win32");
2008 
2009   // Build a packed struct type for all of the arguments in memory.
2010   SmallVector<llvm::Type *, 6> FrameFields;
2011 
2012   // The stack alignment is always 4.
2013   CharUnits StackAlign = CharUnits::fromQuantity(4);
2014 
2015   CharUnits StackOffset;
2016   CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end();
2017 
2018   // Put 'this' into the struct before 'sret', if necessary.
2019   bool IsThisCall =
2020       FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall;
2021   ABIArgInfo &Ret = FI.getReturnInfo();
2022   if (Ret.isIndirect() && Ret.isSRetAfterThis() && !IsThisCall &&
2023       isArgInAlloca(I->info)) {
2024     addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
2025     ++I;
2026   }
2027 
2028   // Put the sret parameter into the inalloca struct if it's in memory.
2029   if (Ret.isIndirect() && !Ret.getInReg()) {
2030     addFieldToArgStruct(FrameFields, StackOffset, Ret, FI.getReturnType());
2031     // On Windows, the hidden sret parameter is always returned in eax.
2032     Ret.setInAllocaSRet(IsWin32StructABI);
2033   }
2034 
2035   // Skip the 'this' parameter in ecx.
2036   if (IsThisCall)
2037     ++I;
2038 
2039   // Put arguments passed in memory into the struct.
2040   for (; I != E; ++I) {
2041     if (isArgInAlloca(I->info))
2042       addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
2043   }
2044 
2045   FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields,
2046                                         /*isPacked=*/true),
2047                   StackAlign);
2048 }
2049 
2050 Address X86_32ABIInfo::EmitVAArg(CodeGenFunction &CGF,
2051                                  Address VAListAddr, QualType Ty) const {
2052 
2053   auto TypeInfo = getContext().getTypeInfoInChars(Ty);
2054 
2055   // x86-32 changes the alignment of certain arguments on the stack.
2056   //
2057   // Just messing with TypeInfo like this works because we never pass
2058   // anything indirectly.
2059   TypeInfo.second = CharUnits::fromQuantity(
2060                 getTypeStackAlignInBytes(Ty, TypeInfo.second.getQuantity()));
2061 
2062   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
2063                           TypeInfo, CharUnits::fromQuantity(4),
2064                           /*AllowHigherAlign*/ true);
2065 }
2066 
2067 bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
2068     const llvm::Triple &Triple, const CodeGenOptions &Opts) {
2069   assert(Triple.getArch() == llvm::Triple::x86);
2070 
2071   switch (Opts.getStructReturnConvention()) {
2072   case CodeGenOptions::SRCK_Default:
2073     break;
2074   case CodeGenOptions::SRCK_OnStack:  // -fpcc-struct-return
2075     return false;
2076   case CodeGenOptions::SRCK_InRegs:  // -freg-struct-return
2077     return true;
2078   }
2079 
2080   if (Triple.isOSDarwin() || Triple.isOSIAMCU())
2081     return true;
2082 
2083   switch (Triple.getOS()) {
2084   case llvm::Triple::DragonFly:
2085   case llvm::Triple::FreeBSD:
2086   case llvm::Triple::OpenBSD:
2087   case llvm::Triple::Win32:
2088     return true;
2089   default:
2090     return false;
2091   }
2092 }
2093 
2094 void X86_32TargetCodeGenInfo::setTargetAttributes(
2095     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
2096   if (GV->isDeclaration())
2097     return;
2098   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2099     if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
2100       llvm::Function *Fn = cast<llvm::Function>(GV);
2101       Fn->addFnAttr("stackrealign");
2102     }
2103     if (FD->hasAttr<AnyX86InterruptAttr>()) {
2104       llvm::Function *Fn = cast<llvm::Function>(GV);
2105       Fn->setCallingConv(llvm::CallingConv::X86_INTR);
2106     }
2107   }
2108 }
2109 
2110 bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
2111                                                CodeGen::CodeGenFunction &CGF,
2112                                                llvm::Value *Address) const {
2113   CodeGen::CGBuilderTy &Builder = CGF.Builder;
2114 
2115   llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
2116 
2117   // 0-7 are the eight integer registers;  the order is different
2118   //   on Darwin (for EH), but the range is the same.
2119   // 8 is %eip.
2120   AssignToArrayRange(Builder, Address, Four8, 0, 8);
2121 
2122   if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
2123     // 12-16 are st(0..4).  Not sure why we stop at 4.
2124     // These have size 16, which is sizeof(long double) on
2125     // platforms with 8-byte alignment for that type.
2126     llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
2127     AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
2128 
2129   } else {
2130     // 9 is %eflags, which doesn't get a size on Darwin for some
2131     // reason.
2132     Builder.CreateAlignedStore(
2133         Four8, Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, Address, 9),
2134                                CharUnits::One());
2135 
2136     // 11-16 are st(0..5).  Not sure why we stop at 5.
2137     // These have size 12, which is sizeof(long double) on
2138     // platforms with 4-byte alignment for that type.
2139     llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
2140     AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
2141   }
2142 
2143   return false;
2144 }
2145 
2146 //===----------------------------------------------------------------------===//
2147 // X86-64 ABI Implementation
2148 //===----------------------------------------------------------------------===//
2149 
2150 
2151 namespace {
2152 /// The AVX ABI level for X86 targets.
2153 enum class X86AVXABILevel {
2154   None,
2155   AVX,
2156   AVX512
2157 };
2158 
2159 /// \p returns the size in bits of the largest (native) vector for \p AVXLevel.
2160 static unsigned getNativeVectorSizeForAVXABI(X86AVXABILevel AVXLevel) {
2161   switch (AVXLevel) {
2162   case X86AVXABILevel::AVX512:
2163     return 512;
2164   case X86AVXABILevel::AVX:
2165     return 256;
2166   case X86AVXABILevel::None:
2167     return 128;
2168   }
2169   llvm_unreachable("Unknown AVXLevel");
2170 }
2171 
2172 /// X86_64ABIInfo - The X86_64 ABI information.
2173 class X86_64ABIInfo : public SwiftABIInfo {
2174   enum Class {
2175     Integer = 0,
2176     SSE,
2177     SSEUp,
2178     X87,
2179     X87Up,
2180     ComplexX87,
2181     NoClass,
2182     Memory
2183   };
2184 
2185   /// merge - Implement the X86_64 ABI merging algorithm.
2186   ///
2187   /// Merge an accumulating classification \arg Accum with a field
2188   /// classification \arg Field.
2189   ///
2190   /// \param Accum - The accumulating classification. This should
2191   /// always be either NoClass or the result of a previous merge
2192   /// call. In addition, this should never be Memory (the caller
2193   /// should just return Memory for the aggregate).
2194   static Class merge(Class Accum, Class Field);
2195 
2196   /// postMerge - Implement the X86_64 ABI post merging algorithm.
2197   ///
2198   /// Post merger cleanup, reduces a malformed Hi and Lo pair to
2199   /// final MEMORY or SSE classes when necessary.
2200   ///
2201   /// \param AggregateSize - The size of the current aggregate in
2202   /// the classification process.
2203   ///
2204   /// \param Lo - The classification for the parts of the type
2205   /// residing in the low word of the containing object.
2206   ///
2207   /// \param Hi - The classification for the parts of the type
2208   /// residing in the higher words of the containing object.
2209   ///
2210   void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
2211 
2212   /// classify - Determine the x86_64 register classes in which the
2213   /// given type T should be passed.
2214   ///
2215   /// \param Lo - The classification for the parts of the type
2216   /// residing in the low word of the containing object.
2217   ///
2218   /// \param Hi - The classification for the parts of the type
2219   /// residing in the high word of the containing object.
2220   ///
2221   /// \param OffsetBase - The bit offset of this type in the
2222   /// containing object.  Some parameters are classified different
2223   /// depending on whether they straddle an eightbyte boundary.
2224   ///
2225   /// \param isNamedArg - Whether the argument in question is a "named"
2226   /// argument, as used in AMD64-ABI 3.5.7.
2227   ///
2228   /// If a word is unused its result will be NoClass; if a type should
2229   /// be passed in Memory then at least the classification of \arg Lo
2230   /// will be Memory.
2231   ///
2232   /// The \arg Lo class will be NoClass iff the argument is ignored.
2233   ///
2234   /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
2235   /// also be ComplexX87.
2236   void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi,
2237                 bool isNamedArg) const;
2238 
2239   llvm::Type *GetByteVectorType(QualType Ty) const;
2240   llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
2241                                  unsigned IROffset, QualType SourceTy,
2242                                  unsigned SourceOffset) const;
2243   llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
2244                                      unsigned IROffset, QualType SourceTy,
2245                                      unsigned SourceOffset) const;
2246 
2247   /// getIndirectResult - Give a source type \arg Ty, return a suitable result
2248   /// such that the argument will be returned in memory.
2249   ABIArgInfo getIndirectReturnResult(QualType Ty) const;
2250 
2251   /// getIndirectResult - Give a source type \arg Ty, return a suitable result
2252   /// such that the argument will be passed in memory.
2253   ///
2254   /// \param freeIntRegs - The number of free integer registers remaining
2255   /// available.
2256   ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
2257 
2258   ABIArgInfo classifyReturnType(QualType RetTy) const;
2259 
2260   ABIArgInfo classifyArgumentType(QualType Ty, unsigned freeIntRegs,
2261                                   unsigned &neededInt, unsigned &neededSSE,
2262                                   bool isNamedArg) const;
2263 
2264   ABIArgInfo classifyRegCallStructType(QualType Ty, unsigned &NeededInt,
2265                                        unsigned &NeededSSE) const;
2266 
2267   ABIArgInfo classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
2268                                            unsigned &NeededSSE) const;
2269 
2270   bool IsIllegalVectorType(QualType Ty) const;
2271 
2272   /// The 0.98 ABI revision clarified a lot of ambiguities,
2273   /// unfortunately in ways that were not always consistent with
2274   /// certain previous compilers.  In particular, platforms which
2275   /// required strict binary compatibility with older versions of GCC
2276   /// may need to exempt themselves.
2277   bool honorsRevision0_98() const {
2278     return !getTarget().getTriple().isOSDarwin();
2279   }
2280 
2281   /// GCC classifies <1 x long long> as SSE but some platform ABIs choose to
2282   /// classify it as INTEGER (for compatibility with older clang compilers).
2283   bool classifyIntegerMMXAsSSE() const {
2284     // Clang <= 3.8 did not do this.
2285     if (getContext().getLangOpts().getClangABICompat() <=
2286         LangOptions::ClangABI::Ver3_8)
2287       return false;
2288 
2289     const llvm::Triple &Triple = getTarget().getTriple();
2290     if (Triple.isOSDarwin() || Triple.getOS() == llvm::Triple::PS4)
2291       return false;
2292     if (Triple.isOSFreeBSD() && Triple.getOSMajorVersion() >= 10)
2293       return false;
2294     return true;
2295   }
2296 
2297   // GCC classifies vectors of __int128 as memory.
2298   bool passInt128VectorsInMem() const {
2299     // Clang <= 9.0 did not do this.
2300     if (getContext().getLangOpts().getClangABICompat() <=
2301         LangOptions::ClangABI::Ver9)
2302       return false;
2303 
2304     const llvm::Triple &T = getTarget().getTriple();
2305     return T.isOSLinux() || T.isOSNetBSD();
2306   }
2307 
2308   X86AVXABILevel AVXLevel;
2309   // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
2310   // 64-bit hardware.
2311   bool Has64BitPointers;
2312 
2313 public:
2314   X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) :
2315       SwiftABIInfo(CGT), AVXLevel(AVXLevel),
2316       Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {
2317   }
2318 
2319   bool isPassedUsingAVXType(QualType type) const {
2320     unsigned neededInt, neededSSE;
2321     // The freeIntRegs argument doesn't matter here.
2322     ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE,
2323                                            /*isNamedArg*/true);
2324     if (info.isDirect()) {
2325       llvm::Type *ty = info.getCoerceToType();
2326       if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
2327         return vectorTy->getPrimitiveSizeInBits().getFixedSize() > 128;
2328     }
2329     return false;
2330   }
2331 
2332   void computeInfo(CGFunctionInfo &FI) const override;
2333 
2334   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
2335                     QualType Ty) const override;
2336   Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
2337                       QualType Ty) const override;
2338 
2339   bool has64BitPointers() const {
2340     return Has64BitPointers;
2341   }
2342 
2343   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
2344                                     bool asReturnValue) const override {
2345     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
2346   }
2347   bool isSwiftErrorInRegister() const override {
2348     return true;
2349   }
2350 };
2351 
2352 /// WinX86_64ABIInfo - The Windows X86_64 ABI information.
2353 class WinX86_64ABIInfo : public SwiftABIInfo {
2354 public:
2355   WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
2356       : SwiftABIInfo(CGT), AVXLevel(AVXLevel),
2357         IsMingw64(getTarget().getTriple().isWindowsGNUEnvironment()) {}
2358 
2359   void computeInfo(CGFunctionInfo &FI) const override;
2360 
2361   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
2362                     QualType Ty) const override;
2363 
2364   bool isHomogeneousAggregateBaseType(QualType Ty) const override {
2365     // FIXME: Assumes vectorcall is in use.
2366     return isX86VectorTypeForVectorCall(getContext(), Ty);
2367   }
2368 
2369   bool isHomogeneousAggregateSmallEnough(const Type *Ty,
2370                                          uint64_t NumMembers) const override {
2371     // FIXME: Assumes vectorcall is in use.
2372     return isX86VectorCallAggregateSmallEnough(NumMembers);
2373   }
2374 
2375   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type *> scalars,
2376                                     bool asReturnValue) const override {
2377     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
2378   }
2379 
2380   bool isSwiftErrorInRegister() const override {
2381     return true;
2382   }
2383 
2384 private:
2385   ABIArgInfo classify(QualType Ty, unsigned &FreeSSERegs, bool IsReturnType,
2386                       bool IsVectorCall, bool IsRegCall) const;
2387   ABIArgInfo reclassifyHvaArgType(QualType Ty, unsigned &FreeSSERegs,
2388                                       const ABIArgInfo &current) const;
2389   void computeVectorCallArgs(CGFunctionInfo &FI, unsigned FreeSSERegs,
2390                              bool IsVectorCall, bool IsRegCall) const;
2391 
2392   X86AVXABILevel AVXLevel;
2393 
2394   bool IsMingw64;
2395 };
2396 
2397 class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2398 public:
2399   X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
2400       : TargetCodeGenInfo(std::make_unique<X86_64ABIInfo>(CGT, AVXLevel)) {}
2401 
2402   const X86_64ABIInfo &getABIInfo() const {
2403     return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
2404   }
2405 
2406   /// Disable tail call on x86-64. The epilogue code before the tail jump blocks
2407   /// the autoreleaseRV/retainRV optimization.
2408   bool shouldSuppressTailCallsOfRetainAutoreleasedReturnValue() const override {
2409     return true;
2410   }
2411 
2412   int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
2413     return 7;
2414   }
2415 
2416   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2417                                llvm::Value *Address) const override {
2418     llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
2419 
2420     // 0-15 are the 16 integer registers.
2421     // 16 is %rip.
2422     AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
2423     return false;
2424   }
2425 
2426   llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
2427                                   StringRef Constraint,
2428                                   llvm::Type* Ty) const override {
2429     return X86AdjustInlineAsmType(CGF, Constraint, Ty);
2430   }
2431 
2432   bool isNoProtoCallVariadic(const CallArgList &args,
2433                              const FunctionNoProtoType *fnType) const override {
2434     // The default CC on x86-64 sets %al to the number of SSA
2435     // registers used, and GCC sets this when calling an unprototyped
2436     // function, so we override the default behavior.  However, don't do
2437     // that when AVX types are involved: the ABI explicitly states it is
2438     // undefined, and it doesn't work in practice because of how the ABI
2439     // defines varargs anyway.
2440     if (fnType->getCallConv() == CC_C) {
2441       bool HasAVXType = false;
2442       for (CallArgList::const_iterator
2443              it = args.begin(), ie = args.end(); it != ie; ++it) {
2444         if (getABIInfo().isPassedUsingAVXType(it->Ty)) {
2445           HasAVXType = true;
2446           break;
2447         }
2448       }
2449 
2450       if (!HasAVXType)
2451         return true;
2452     }
2453 
2454     return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
2455   }
2456 
2457   llvm::Constant *
2458   getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
2459     unsigned Sig = (0xeb << 0) | // jmp rel8
2460                    (0x06 << 8) | //           .+0x08
2461                    ('v' << 16) |
2462                    ('2' << 24);
2463     return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
2464   }
2465 
2466   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2467                            CodeGen::CodeGenModule &CGM) const override {
2468     if (GV->isDeclaration())
2469       return;
2470     if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2471       if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
2472         llvm::Function *Fn = cast<llvm::Function>(GV);
2473         Fn->addFnAttr("stackrealign");
2474       }
2475       if (FD->hasAttr<AnyX86InterruptAttr>()) {
2476         llvm::Function *Fn = cast<llvm::Function>(GV);
2477         Fn->setCallingConv(llvm::CallingConv::X86_INTR);
2478       }
2479     }
2480   }
2481 
2482   void checkFunctionCallABI(CodeGenModule &CGM, SourceLocation CallLoc,
2483                             const FunctionDecl *Caller,
2484                             const FunctionDecl *Callee,
2485                             const CallArgList &Args) const override;
2486 };
2487 
2488 static void initFeatureMaps(const ASTContext &Ctx,
2489                             llvm::StringMap<bool> &CallerMap,
2490                             const FunctionDecl *Caller,
2491                             llvm::StringMap<bool> &CalleeMap,
2492                             const FunctionDecl *Callee) {
2493   if (CalleeMap.empty() && CallerMap.empty()) {
2494     // The caller is potentially nullptr in the case where the call isn't in a
2495     // function.  In this case, the getFunctionFeatureMap ensures we just get
2496     // the TU level setting (since it cannot be modified by 'target'..
2497     Ctx.getFunctionFeatureMap(CallerMap, Caller);
2498     Ctx.getFunctionFeatureMap(CalleeMap, Callee);
2499   }
2500 }
2501 
2502 static bool checkAVXParamFeature(DiagnosticsEngine &Diag,
2503                                  SourceLocation CallLoc,
2504                                  const llvm::StringMap<bool> &CallerMap,
2505                                  const llvm::StringMap<bool> &CalleeMap,
2506                                  QualType Ty, StringRef Feature,
2507                                  bool IsArgument) {
2508   bool CallerHasFeat = CallerMap.lookup(Feature);
2509   bool CalleeHasFeat = CalleeMap.lookup(Feature);
2510   if (!CallerHasFeat && !CalleeHasFeat)
2511     return Diag.Report(CallLoc, diag::warn_avx_calling_convention)
2512            << IsArgument << Ty << Feature;
2513 
2514   // Mixing calling conventions here is very clearly an error.
2515   if (!CallerHasFeat || !CalleeHasFeat)
2516     return Diag.Report(CallLoc, diag::err_avx_calling_convention)
2517            << IsArgument << Ty << Feature;
2518 
2519   // Else, both caller and callee have the required feature, so there is no need
2520   // to diagnose.
2521   return false;
2522 }
2523 
2524 static bool checkAVXParam(DiagnosticsEngine &Diag, ASTContext &Ctx,
2525                           SourceLocation CallLoc,
2526                           const llvm::StringMap<bool> &CallerMap,
2527                           const llvm::StringMap<bool> &CalleeMap, QualType Ty,
2528                           bool IsArgument) {
2529   uint64_t Size = Ctx.getTypeSize(Ty);
2530   if (Size > 256)
2531     return checkAVXParamFeature(Diag, CallLoc, CallerMap, CalleeMap, Ty,
2532                                 "avx512f", IsArgument);
2533 
2534   if (Size > 128)
2535     return checkAVXParamFeature(Diag, CallLoc, CallerMap, CalleeMap, Ty, "avx",
2536                                 IsArgument);
2537 
2538   return false;
2539 }
2540 
2541 void X86_64TargetCodeGenInfo::checkFunctionCallABI(
2542     CodeGenModule &CGM, SourceLocation CallLoc, const FunctionDecl *Caller,
2543     const FunctionDecl *Callee, const CallArgList &Args) const {
2544   llvm::StringMap<bool> CallerMap;
2545   llvm::StringMap<bool> CalleeMap;
2546   unsigned ArgIndex = 0;
2547 
2548   // We need to loop through the actual call arguments rather than the the
2549   // function's parameters, in case this variadic.
2550   for (const CallArg &Arg : Args) {
2551     // The "avx" feature changes how vectors >128 in size are passed. "avx512f"
2552     // additionally changes how vectors >256 in size are passed. Like GCC, we
2553     // warn when a function is called with an argument where this will change.
2554     // Unlike GCC, we also error when it is an obvious ABI mismatch, that is,
2555     // the caller and callee features are mismatched.
2556     // Unfortunately, we cannot do this diagnostic in SEMA, since the callee can
2557     // change its ABI with attribute-target after this call.
2558     if (Arg.getType()->isVectorType() &&
2559         CGM.getContext().getTypeSize(Arg.getType()) > 128) {
2560       initFeatureMaps(CGM.getContext(), CallerMap, Caller, CalleeMap, Callee);
2561       QualType Ty = Arg.getType();
2562       // The CallArg seems to have desugared the type already, so for clearer
2563       // diagnostics, replace it with the type in the FunctionDecl if possible.
2564       if (ArgIndex < Callee->getNumParams())
2565         Ty = Callee->getParamDecl(ArgIndex)->getType();
2566 
2567       if (checkAVXParam(CGM.getDiags(), CGM.getContext(), CallLoc, CallerMap,
2568                         CalleeMap, Ty, /*IsArgument*/ true))
2569         return;
2570     }
2571     ++ArgIndex;
2572   }
2573 
2574   // Check return always, as we don't have a good way of knowing in codegen
2575   // whether this value is used, tail-called, etc.
2576   if (Callee->getReturnType()->isVectorType() &&
2577       CGM.getContext().getTypeSize(Callee->getReturnType()) > 128) {
2578     initFeatureMaps(CGM.getContext(), CallerMap, Caller, CalleeMap, Callee);
2579     checkAVXParam(CGM.getDiags(), CGM.getContext(), CallLoc, CallerMap,
2580                   CalleeMap, Callee->getReturnType(),
2581                   /*IsArgument*/ false);
2582   }
2583 }
2584 
2585 static std::string qualifyWindowsLibrary(llvm::StringRef Lib) {
2586   // If the argument does not end in .lib, automatically add the suffix.
2587   // If the argument contains a space, enclose it in quotes.
2588   // This matches the behavior of MSVC.
2589   bool Quote = (Lib.find(" ") != StringRef::npos);
2590   std::string ArgStr = Quote ? "\"" : "";
2591   ArgStr += Lib;
2592   if (!Lib.endswith_lower(".lib") && !Lib.endswith_lower(".a"))
2593     ArgStr += ".lib";
2594   ArgStr += Quote ? "\"" : "";
2595   return ArgStr;
2596 }
2597 
2598 class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
2599 public:
2600   WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
2601         bool DarwinVectorABI, bool RetSmallStructInRegABI, bool Win32StructABI,
2602         unsigned NumRegisterParameters)
2603     : X86_32TargetCodeGenInfo(CGT, DarwinVectorABI, RetSmallStructInRegABI,
2604         Win32StructABI, NumRegisterParameters, false) {}
2605 
2606   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2607                            CodeGen::CodeGenModule &CGM) const override;
2608 
2609   void getDependentLibraryOption(llvm::StringRef Lib,
2610                                  llvm::SmallString<24> &Opt) const override {
2611     Opt = "/DEFAULTLIB:";
2612     Opt += qualifyWindowsLibrary(Lib);
2613   }
2614 
2615   void getDetectMismatchOption(llvm::StringRef Name,
2616                                llvm::StringRef Value,
2617                                llvm::SmallString<32> &Opt) const override {
2618     Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
2619   }
2620 };
2621 
2622 static void addStackProbeTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2623                                           CodeGen::CodeGenModule &CGM) {
2624   if (llvm::Function *Fn = dyn_cast_or_null<llvm::Function>(GV)) {
2625 
2626     if (CGM.getCodeGenOpts().StackProbeSize != 4096)
2627       Fn->addFnAttr("stack-probe-size",
2628                     llvm::utostr(CGM.getCodeGenOpts().StackProbeSize));
2629     if (CGM.getCodeGenOpts().NoStackArgProbe)
2630       Fn->addFnAttr("no-stack-arg-probe");
2631   }
2632 }
2633 
2634 void WinX86_32TargetCodeGenInfo::setTargetAttributes(
2635     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
2636   X86_32TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
2637   if (GV->isDeclaration())
2638     return;
2639   addStackProbeTargetAttributes(D, GV, CGM);
2640 }
2641 
2642 class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2643 public:
2644   WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
2645                              X86AVXABILevel AVXLevel)
2646       : TargetCodeGenInfo(std::make_unique<WinX86_64ABIInfo>(CGT, AVXLevel)) {}
2647 
2648   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2649                            CodeGen::CodeGenModule &CGM) const override;
2650 
2651   int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
2652     return 7;
2653   }
2654 
2655   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2656                                llvm::Value *Address) const override {
2657     llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
2658 
2659     // 0-15 are the 16 integer registers.
2660     // 16 is %rip.
2661     AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
2662     return false;
2663   }
2664 
2665   void getDependentLibraryOption(llvm::StringRef Lib,
2666                                  llvm::SmallString<24> &Opt) const override {
2667     Opt = "/DEFAULTLIB:";
2668     Opt += qualifyWindowsLibrary(Lib);
2669   }
2670 
2671   void getDetectMismatchOption(llvm::StringRef Name,
2672                                llvm::StringRef Value,
2673                                llvm::SmallString<32> &Opt) const override {
2674     Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
2675   }
2676 };
2677 
2678 void WinX86_64TargetCodeGenInfo::setTargetAttributes(
2679     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
2680   TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
2681   if (GV->isDeclaration())
2682     return;
2683   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2684     if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
2685       llvm::Function *Fn = cast<llvm::Function>(GV);
2686       Fn->addFnAttr("stackrealign");
2687     }
2688     if (FD->hasAttr<AnyX86InterruptAttr>()) {
2689       llvm::Function *Fn = cast<llvm::Function>(GV);
2690       Fn->setCallingConv(llvm::CallingConv::X86_INTR);
2691     }
2692   }
2693 
2694   addStackProbeTargetAttributes(D, GV, CGM);
2695 }
2696 }
2697 
2698 void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
2699                               Class &Hi) const {
2700   // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
2701   //
2702   // (a) If one of the classes is Memory, the whole argument is passed in
2703   //     memory.
2704   //
2705   // (b) If X87UP is not preceded by X87, the whole argument is passed in
2706   //     memory.
2707   //
2708   // (c) If the size of the aggregate exceeds two eightbytes and the first
2709   //     eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
2710   //     argument is passed in memory. NOTE: This is necessary to keep the
2711   //     ABI working for processors that don't support the __m256 type.
2712   //
2713   // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
2714   //
2715   // Some of these are enforced by the merging logic.  Others can arise
2716   // only with unions; for example:
2717   //   union { _Complex double; unsigned; }
2718   //
2719   // Note that clauses (b) and (c) were added in 0.98.
2720   //
2721   if (Hi == Memory)
2722     Lo = Memory;
2723   if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
2724     Lo = Memory;
2725   if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
2726     Lo = Memory;
2727   if (Hi == SSEUp && Lo != SSE)
2728     Hi = SSE;
2729 }
2730 
2731 X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
2732   // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
2733   // classified recursively so that always two fields are
2734   // considered. The resulting class is calculated according to
2735   // the classes of the fields in the eightbyte:
2736   //
2737   // (a) If both classes are equal, this is the resulting class.
2738   //
2739   // (b) If one of the classes is NO_CLASS, the resulting class is
2740   // the other class.
2741   //
2742   // (c) If one of the classes is MEMORY, the result is the MEMORY
2743   // class.
2744   //
2745   // (d) If one of the classes is INTEGER, the result is the
2746   // INTEGER.
2747   //
2748   // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
2749   // MEMORY is used as class.
2750   //
2751   // (f) Otherwise class SSE is used.
2752 
2753   // Accum should never be memory (we should have returned) or
2754   // ComplexX87 (because this cannot be passed in a structure).
2755   assert((Accum != Memory && Accum != ComplexX87) &&
2756          "Invalid accumulated classification during merge.");
2757   if (Accum == Field || Field == NoClass)
2758     return Accum;
2759   if (Field == Memory)
2760     return Memory;
2761   if (Accum == NoClass)
2762     return Field;
2763   if (Accum == Integer || Field == Integer)
2764     return Integer;
2765   if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
2766       Accum == X87 || Accum == X87Up)
2767     return Memory;
2768   return SSE;
2769 }
2770 
2771 void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
2772                              Class &Lo, Class &Hi, bool isNamedArg) const {
2773   // FIXME: This code can be simplified by introducing a simple value class for
2774   // Class pairs with appropriate constructor methods for the various
2775   // situations.
2776 
2777   // FIXME: Some of the split computations are wrong; unaligned vectors
2778   // shouldn't be passed in registers for example, so there is no chance they
2779   // can straddle an eightbyte. Verify & simplify.
2780 
2781   Lo = Hi = NoClass;
2782 
2783   Class &Current = OffsetBase < 64 ? Lo : Hi;
2784   Current = Memory;
2785 
2786   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
2787     BuiltinType::Kind k = BT->getKind();
2788 
2789     if (k == BuiltinType::Void) {
2790       Current = NoClass;
2791     } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
2792       Lo = Integer;
2793       Hi = Integer;
2794     } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
2795       Current = Integer;
2796     } else if (k == BuiltinType::Float || k == BuiltinType::Double) {
2797       Current = SSE;
2798     } else if (k == BuiltinType::LongDouble) {
2799       const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
2800       if (LDF == &llvm::APFloat::IEEEquad()) {
2801         Lo = SSE;
2802         Hi = SSEUp;
2803       } else if (LDF == &llvm::APFloat::x87DoubleExtended()) {
2804         Lo = X87;
2805         Hi = X87Up;
2806       } else if (LDF == &llvm::APFloat::IEEEdouble()) {
2807         Current = SSE;
2808       } else
2809         llvm_unreachable("unexpected long double representation!");
2810     }
2811     // FIXME: _Decimal32 and _Decimal64 are SSE.
2812     // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
2813     return;
2814   }
2815 
2816   if (const EnumType *ET = Ty->getAs<EnumType>()) {
2817     // Classify the underlying integer type.
2818     classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
2819     return;
2820   }
2821 
2822   if (Ty->hasPointerRepresentation()) {
2823     Current = Integer;
2824     return;
2825   }
2826 
2827   if (Ty->isMemberPointerType()) {
2828     if (Ty->isMemberFunctionPointerType()) {
2829       if (Has64BitPointers) {
2830         // If Has64BitPointers, this is an {i64, i64}, so classify both
2831         // Lo and Hi now.
2832         Lo = Hi = Integer;
2833       } else {
2834         // Otherwise, with 32-bit pointers, this is an {i32, i32}. If that
2835         // straddles an eightbyte boundary, Hi should be classified as well.
2836         uint64_t EB_FuncPtr = (OffsetBase) / 64;
2837         uint64_t EB_ThisAdj = (OffsetBase + 64 - 1) / 64;
2838         if (EB_FuncPtr != EB_ThisAdj) {
2839           Lo = Hi = Integer;
2840         } else {
2841           Current = Integer;
2842         }
2843       }
2844     } else {
2845       Current = Integer;
2846     }
2847     return;
2848   }
2849 
2850   if (const VectorType *VT = Ty->getAs<VectorType>()) {
2851     uint64_t Size = getContext().getTypeSize(VT);
2852     if (Size == 1 || Size == 8 || Size == 16 || Size == 32) {
2853       // gcc passes the following as integer:
2854       // 4 bytes - <4 x char>, <2 x short>, <1 x int>, <1 x float>
2855       // 2 bytes - <2 x char>, <1 x short>
2856       // 1 byte  - <1 x char>
2857       Current = Integer;
2858 
2859       // If this type crosses an eightbyte boundary, it should be
2860       // split.
2861       uint64_t EB_Lo = (OffsetBase) / 64;
2862       uint64_t EB_Hi = (OffsetBase + Size - 1) / 64;
2863       if (EB_Lo != EB_Hi)
2864         Hi = Lo;
2865     } else if (Size == 64) {
2866       QualType ElementType = VT->getElementType();
2867 
2868       // gcc passes <1 x double> in memory. :(
2869       if (ElementType->isSpecificBuiltinType(BuiltinType::Double))
2870         return;
2871 
2872       // gcc passes <1 x long long> as SSE but clang used to unconditionally
2873       // pass them as integer.  For platforms where clang is the de facto
2874       // platform compiler, we must continue to use integer.
2875       if (!classifyIntegerMMXAsSSE() &&
2876           (ElementType->isSpecificBuiltinType(BuiltinType::LongLong) ||
2877            ElementType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
2878            ElementType->isSpecificBuiltinType(BuiltinType::Long) ||
2879            ElementType->isSpecificBuiltinType(BuiltinType::ULong)))
2880         Current = Integer;
2881       else
2882         Current = SSE;
2883 
2884       // If this type crosses an eightbyte boundary, it should be
2885       // split.
2886       if (OffsetBase && OffsetBase != 64)
2887         Hi = Lo;
2888     } else if (Size == 128 ||
2889                (isNamedArg && Size <= getNativeVectorSizeForAVXABI(AVXLevel))) {
2890       QualType ElementType = VT->getElementType();
2891 
2892       // gcc passes 256 and 512 bit <X x __int128> vectors in memory. :(
2893       if (passInt128VectorsInMem() && Size != 128 &&
2894           (ElementType->isSpecificBuiltinType(BuiltinType::Int128) ||
2895            ElementType->isSpecificBuiltinType(BuiltinType::UInt128)))
2896         return;
2897 
2898       // Arguments of 256-bits are split into four eightbyte chunks. The
2899       // least significant one belongs to class SSE and all the others to class
2900       // SSEUP. The original Lo and Hi design considers that types can't be
2901       // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
2902       // This design isn't correct for 256-bits, but since there're no cases
2903       // where the upper parts would need to be inspected, avoid adding
2904       // complexity and just consider Hi to match the 64-256 part.
2905       //
2906       // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
2907       // registers if they are "named", i.e. not part of the "..." of a
2908       // variadic function.
2909       //
2910       // Similarly, per 3.2.3. of the AVX512 draft, 512-bits ("named") args are
2911       // split into eight eightbyte chunks, one SSE and seven SSEUP.
2912       Lo = SSE;
2913       Hi = SSEUp;
2914     }
2915     return;
2916   }
2917 
2918   if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
2919     QualType ET = getContext().getCanonicalType(CT->getElementType());
2920 
2921     uint64_t Size = getContext().getTypeSize(Ty);
2922     if (ET->isIntegralOrEnumerationType()) {
2923       if (Size <= 64)
2924         Current = Integer;
2925       else if (Size <= 128)
2926         Lo = Hi = Integer;
2927     } else if (ET == getContext().FloatTy) {
2928       Current = SSE;
2929     } else if (ET == getContext().DoubleTy) {
2930       Lo = Hi = SSE;
2931     } else if (ET == getContext().LongDoubleTy) {
2932       const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
2933       if (LDF == &llvm::APFloat::IEEEquad())
2934         Current = Memory;
2935       else if (LDF == &llvm::APFloat::x87DoubleExtended())
2936         Current = ComplexX87;
2937       else if (LDF == &llvm::APFloat::IEEEdouble())
2938         Lo = Hi = SSE;
2939       else
2940         llvm_unreachable("unexpected long double representation!");
2941     }
2942 
2943     // If this complex type crosses an eightbyte boundary then it
2944     // should be split.
2945     uint64_t EB_Real = (OffsetBase) / 64;
2946     uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
2947     if (Hi == NoClass && EB_Real != EB_Imag)
2948       Hi = Lo;
2949 
2950     return;
2951   }
2952 
2953   if (const auto *EITy = Ty->getAs<ExtIntType>()) {
2954     if (EITy->getNumBits() <= 64)
2955       Current = Integer;
2956     else if (EITy->getNumBits() <= 128)
2957       Lo = Hi = Integer;
2958     // Larger values need to get passed in memory.
2959     return;
2960   }
2961 
2962   if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
2963     // Arrays are treated like structures.
2964 
2965     uint64_t Size = getContext().getTypeSize(Ty);
2966 
2967     // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
2968     // than eight eightbytes, ..., it has class MEMORY.
2969     if (Size > 512)
2970       return;
2971 
2972     // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
2973     // fields, it has class MEMORY.
2974     //
2975     // Only need to check alignment of array base.
2976     if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
2977       return;
2978 
2979     // Otherwise implement simplified merge. We could be smarter about
2980     // this, but it isn't worth it and would be harder to verify.
2981     Current = NoClass;
2982     uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
2983     uint64_t ArraySize = AT->getSize().getZExtValue();
2984 
2985     // The only case a 256-bit wide vector could be used is when the array
2986     // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2987     // to work for sizes wider than 128, early check and fallback to memory.
2988     //
2989     if (Size > 128 &&
2990         (Size != EltSize || Size > getNativeVectorSizeForAVXABI(AVXLevel)))
2991       return;
2992 
2993     for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
2994       Class FieldLo, FieldHi;
2995       classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
2996       Lo = merge(Lo, FieldLo);
2997       Hi = merge(Hi, FieldHi);
2998       if (Lo == Memory || Hi == Memory)
2999         break;
3000     }
3001 
3002     postMerge(Size, Lo, Hi);
3003     assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
3004     return;
3005   }
3006 
3007   if (const RecordType *RT = Ty->getAs<RecordType>()) {
3008     uint64_t Size = getContext().getTypeSize(Ty);
3009 
3010     // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
3011     // than eight eightbytes, ..., it has class MEMORY.
3012     if (Size > 512)
3013       return;
3014 
3015     // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
3016     // copy constructor or a non-trivial destructor, it is passed by invisible
3017     // reference.
3018     if (getRecordArgABI(RT, getCXXABI()))
3019       return;
3020 
3021     const RecordDecl *RD = RT->getDecl();
3022 
3023     // Assume variable sized types are passed in memory.
3024     if (RD->hasFlexibleArrayMember())
3025       return;
3026 
3027     const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
3028 
3029     // Reset Lo class, this will be recomputed.
3030     Current = NoClass;
3031 
3032     // If this is a C++ record, classify the bases first.
3033     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3034       for (const auto &I : CXXRD->bases()) {
3035         assert(!I.isVirtual() && !I.getType()->isDependentType() &&
3036                "Unexpected base class!");
3037         const auto *Base =
3038             cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
3039 
3040         // Classify this field.
3041         //
3042         // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
3043         // single eightbyte, each is classified separately. Each eightbyte gets
3044         // initialized to class NO_CLASS.
3045         Class FieldLo, FieldHi;
3046         uint64_t Offset =
3047           OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
3048         classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg);
3049         Lo = merge(Lo, FieldLo);
3050         Hi = merge(Hi, FieldHi);
3051         if (Lo == Memory || Hi == Memory) {
3052           postMerge(Size, Lo, Hi);
3053           return;
3054         }
3055       }
3056     }
3057 
3058     // Classify the fields one at a time, merging the results.
3059     unsigned idx = 0;
3060     for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
3061            i != e; ++i, ++idx) {
3062       uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
3063       bool BitField = i->isBitField();
3064 
3065       // Ignore padding bit-fields.
3066       if (BitField && i->isUnnamedBitfield())
3067         continue;
3068 
3069       // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
3070       // four eightbytes, or it contains unaligned fields, it has class MEMORY.
3071       //
3072       // The only case a 256-bit wide vector could be used is when the struct
3073       // contains a single 256-bit element. Since Lo and Hi logic isn't extended
3074       // to work for sizes wider than 128, early check and fallback to memory.
3075       //
3076       if (Size > 128 && (Size != getContext().getTypeSize(i->getType()) ||
3077                          Size > getNativeVectorSizeForAVXABI(AVXLevel))) {
3078         Lo = Memory;
3079         postMerge(Size, Lo, Hi);
3080         return;
3081       }
3082       // Note, skip this test for bit-fields, see below.
3083       if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
3084         Lo = Memory;
3085         postMerge(Size, Lo, Hi);
3086         return;
3087       }
3088 
3089       // Classify this field.
3090       //
3091       // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
3092       // exceeds a single eightbyte, each is classified
3093       // separately. Each eightbyte gets initialized to class
3094       // NO_CLASS.
3095       Class FieldLo, FieldHi;
3096 
3097       // Bit-fields require special handling, they do not force the
3098       // structure to be passed in memory even if unaligned, and
3099       // therefore they can straddle an eightbyte.
3100       if (BitField) {
3101         assert(!i->isUnnamedBitfield());
3102         uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
3103         uint64_t Size = i->getBitWidthValue(getContext());
3104 
3105         uint64_t EB_Lo = Offset / 64;
3106         uint64_t EB_Hi = (Offset + Size - 1) / 64;
3107 
3108         if (EB_Lo) {
3109           assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
3110           FieldLo = NoClass;
3111           FieldHi = Integer;
3112         } else {
3113           FieldLo = Integer;
3114           FieldHi = EB_Hi ? Integer : NoClass;
3115         }
3116       } else
3117         classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
3118       Lo = merge(Lo, FieldLo);
3119       Hi = merge(Hi, FieldHi);
3120       if (Lo == Memory || Hi == Memory)
3121         break;
3122     }
3123 
3124     postMerge(Size, Lo, Hi);
3125   }
3126 }
3127 
3128 ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
3129   // If this is a scalar LLVM value then assume LLVM will pass it in the right
3130   // place naturally.
3131   if (!isAggregateTypeForABI(Ty)) {
3132     // Treat an enum type as its underlying type.
3133     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3134       Ty = EnumTy->getDecl()->getIntegerType();
3135 
3136     if (Ty->isExtIntType())
3137       return getNaturalAlignIndirect(Ty);
3138 
3139     return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
3140                                               : ABIArgInfo::getDirect());
3141   }
3142 
3143   return getNaturalAlignIndirect(Ty);
3144 }
3145 
3146 bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
3147   if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
3148     uint64_t Size = getContext().getTypeSize(VecTy);
3149     unsigned LargestVector = getNativeVectorSizeForAVXABI(AVXLevel);
3150     if (Size <= 64 || Size > LargestVector)
3151       return true;
3152     QualType EltTy = VecTy->getElementType();
3153     if (passInt128VectorsInMem() &&
3154         (EltTy->isSpecificBuiltinType(BuiltinType::Int128) ||
3155          EltTy->isSpecificBuiltinType(BuiltinType::UInt128)))
3156       return true;
3157   }
3158 
3159   return false;
3160 }
3161 
3162 ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
3163                                             unsigned freeIntRegs) const {
3164   // If this is a scalar LLVM value then assume LLVM will pass it in the right
3165   // place naturally.
3166   //
3167   // This assumption is optimistic, as there could be free registers available
3168   // when we need to pass this argument in memory, and LLVM could try to pass
3169   // the argument in the free register. This does not seem to happen currently,
3170   // but this code would be much safer if we could mark the argument with
3171   // 'onstack'. See PR12193.
3172   if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty) &&
3173       !Ty->isExtIntType()) {
3174     // Treat an enum type as its underlying type.
3175     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3176       Ty = EnumTy->getDecl()->getIntegerType();
3177 
3178     return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
3179                                               : ABIArgInfo::getDirect());
3180   }
3181 
3182   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
3183     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
3184 
3185   // Compute the byval alignment. We specify the alignment of the byval in all
3186   // cases so that the mid-level optimizer knows the alignment of the byval.
3187   unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
3188 
3189   // Attempt to avoid passing indirect results using byval when possible. This
3190   // is important for good codegen.
3191   //
3192   // We do this by coercing the value into a scalar type which the backend can
3193   // handle naturally (i.e., without using byval).
3194   //
3195   // For simplicity, we currently only do this when we have exhausted all of the
3196   // free integer registers. Doing this when there are free integer registers
3197   // would require more care, as we would have to ensure that the coerced value
3198   // did not claim the unused register. That would require either reording the
3199   // arguments to the function (so that any subsequent inreg values came first),
3200   // or only doing this optimization when there were no following arguments that
3201   // might be inreg.
3202   //
3203   // We currently expect it to be rare (particularly in well written code) for
3204   // arguments to be passed on the stack when there are still free integer
3205   // registers available (this would typically imply large structs being passed
3206   // by value), so this seems like a fair tradeoff for now.
3207   //
3208   // We can revisit this if the backend grows support for 'onstack' parameter
3209   // attributes. See PR12193.
3210   if (freeIntRegs == 0) {
3211     uint64_t Size = getContext().getTypeSize(Ty);
3212 
3213     // If this type fits in an eightbyte, coerce it into the matching integral
3214     // type, which will end up on the stack (with alignment 8).
3215     if (Align == 8 && Size <= 64)
3216       return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
3217                                                           Size));
3218   }
3219 
3220   return ABIArgInfo::getIndirect(CharUnits::fromQuantity(Align));
3221 }
3222 
3223 /// The ABI specifies that a value should be passed in a full vector XMM/YMM
3224 /// register. Pick an LLVM IR type that will be passed as a vector register.
3225 llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
3226   // Wrapper structs/arrays that only contain vectors are passed just like
3227   // vectors; strip them off if present.
3228   if (const Type *InnerTy = isSingleElementStruct(Ty, getContext()))
3229     Ty = QualType(InnerTy, 0);
3230 
3231   llvm::Type *IRType = CGT.ConvertType(Ty);
3232   if (isa<llvm::VectorType>(IRType)) {
3233     // Don't pass vXi128 vectors in their native type, the backend can't
3234     // legalize them.
3235     if (passInt128VectorsInMem() &&
3236         cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy(128)) {
3237       // Use a vXi64 vector.
3238       uint64_t Size = getContext().getTypeSize(Ty);
3239       return llvm::FixedVectorType::get(llvm::Type::getInt64Ty(getVMContext()),
3240                                         Size / 64);
3241     }
3242 
3243     return IRType;
3244   }
3245 
3246   if (IRType->getTypeID() == llvm::Type::FP128TyID)
3247     return IRType;
3248 
3249   // We couldn't find the preferred IR vector type for 'Ty'.
3250   uint64_t Size = getContext().getTypeSize(Ty);
3251   assert((Size == 128 || Size == 256 || Size == 512) && "Invalid type found!");
3252 
3253 
3254   // Return a LLVM IR vector type based on the size of 'Ty'.
3255   return llvm::FixedVectorType::get(llvm::Type::getDoubleTy(getVMContext()),
3256                                     Size / 64);
3257 }
3258 
3259 /// BitsContainNoUserData - Return true if the specified [start,end) bit range
3260 /// is known to either be off the end of the specified type or being in
3261 /// alignment padding.  The user type specified is known to be at most 128 bits
3262 /// in size, and have passed through X86_64ABIInfo::classify with a successful
3263 /// classification that put one of the two halves in the INTEGER class.
3264 ///
3265 /// It is conservatively correct to return false.
3266 static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
3267                                   unsigned EndBit, ASTContext &Context) {
3268   // If the bytes being queried are off the end of the type, there is no user
3269   // data hiding here.  This handles analysis of builtins, vectors and other
3270   // types that don't contain interesting padding.
3271   unsigned TySize = (unsigned)Context.getTypeSize(Ty);
3272   if (TySize <= StartBit)
3273     return true;
3274 
3275   if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
3276     unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
3277     unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
3278 
3279     // Check each element to see if the element overlaps with the queried range.
3280     for (unsigned i = 0; i != NumElts; ++i) {
3281       // If the element is after the span we care about, then we're done..
3282       unsigned EltOffset = i*EltSize;
3283       if (EltOffset >= EndBit) break;
3284 
3285       unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
3286       if (!BitsContainNoUserData(AT->getElementType(), EltStart,
3287                                  EndBit-EltOffset, Context))
3288         return false;
3289     }
3290     // If it overlaps no elements, then it is safe to process as padding.
3291     return true;
3292   }
3293 
3294   if (const RecordType *RT = Ty->getAs<RecordType>()) {
3295     const RecordDecl *RD = RT->getDecl();
3296     const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
3297 
3298     // If this is a C++ record, check the bases first.
3299     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3300       for (const auto &I : CXXRD->bases()) {
3301         assert(!I.isVirtual() && !I.getType()->isDependentType() &&
3302                "Unexpected base class!");
3303         const auto *Base =
3304             cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
3305 
3306         // If the base is after the span we care about, ignore it.
3307         unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
3308         if (BaseOffset >= EndBit) continue;
3309 
3310         unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
3311         if (!BitsContainNoUserData(I.getType(), BaseStart,
3312                                    EndBit-BaseOffset, Context))
3313           return false;
3314       }
3315     }
3316 
3317     // Verify that no field has data that overlaps the region of interest.  Yes
3318     // this could be sped up a lot by being smarter about queried fields,
3319     // however we're only looking at structs up to 16 bytes, so we don't care
3320     // much.
3321     unsigned idx = 0;
3322     for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
3323          i != e; ++i, ++idx) {
3324       unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
3325 
3326       // If we found a field after the region we care about, then we're done.
3327       if (FieldOffset >= EndBit) break;
3328 
3329       unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
3330       if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
3331                                  Context))
3332         return false;
3333     }
3334 
3335     // If nothing in this record overlapped the area of interest, then we're
3336     // clean.
3337     return true;
3338   }
3339 
3340   return false;
3341 }
3342 
3343 /// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a
3344 /// float member at the specified offset.  For example, {int,{float}} has a
3345 /// float at offset 4.  It is conservatively correct for this routine to return
3346 /// false.
3347 static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset,
3348                                   const llvm::DataLayout &TD) {
3349   // Base case if we find a float.
3350   if (IROffset == 0 && IRType->isFloatTy())
3351     return true;
3352 
3353   // If this is a struct, recurse into the field at the specified offset.
3354   if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
3355     const llvm::StructLayout *SL = TD.getStructLayout(STy);
3356     unsigned Elt = SL->getElementContainingOffset(IROffset);
3357     IROffset -= SL->getElementOffset(Elt);
3358     return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD);
3359   }
3360 
3361   // If this is an array, recurse into the field at the specified offset.
3362   if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
3363     llvm::Type *EltTy = ATy->getElementType();
3364     unsigned EltSize = TD.getTypeAllocSize(EltTy);
3365     IROffset -= IROffset/EltSize*EltSize;
3366     return ContainsFloatAtOffset(EltTy, IROffset, TD);
3367   }
3368 
3369   return false;
3370 }
3371 
3372 
3373 /// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
3374 /// low 8 bytes of an XMM register, corresponding to the SSE class.
3375 llvm::Type *X86_64ABIInfo::
3376 GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
3377                    QualType SourceTy, unsigned SourceOffset) const {
3378   // The only three choices we have are either double, <2 x float>, or float. We
3379   // pass as float if the last 4 bytes is just padding.  This happens for
3380   // structs that contain 3 floats.
3381   if (BitsContainNoUserData(SourceTy, SourceOffset*8+32,
3382                             SourceOffset*8+64, getContext()))
3383     return llvm::Type::getFloatTy(getVMContext());
3384 
3385   // We want to pass as <2 x float> if the LLVM IR type contains a float at
3386   // offset+0 and offset+4.  Walk the LLVM IR type to find out if this is the
3387   // case.
3388   if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) &&
3389       ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout()))
3390     return llvm::FixedVectorType::get(llvm::Type::getFloatTy(getVMContext()),
3391                                       2);
3392 
3393   return llvm::Type::getDoubleTy(getVMContext());
3394 }
3395 
3396 
3397 /// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
3398 /// an 8-byte GPR.  This means that we either have a scalar or we are talking
3399 /// about the high or low part of an up-to-16-byte struct.  This routine picks
3400 /// the best LLVM IR type to represent this, which may be i64 or may be anything
3401 /// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
3402 /// etc).
3403 ///
3404 /// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
3405 /// the source type.  IROffset is an offset in bytes into the LLVM IR type that
3406 /// the 8-byte value references.  PrefType may be null.
3407 ///
3408 /// SourceTy is the source-level type for the entire argument.  SourceOffset is
3409 /// an offset into this that we're processing (which is always either 0 or 8).
3410 ///
3411 llvm::Type *X86_64ABIInfo::
3412 GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
3413                        QualType SourceTy, unsigned SourceOffset) const {
3414   // If we're dealing with an un-offset LLVM IR type, then it means that we're
3415   // returning an 8-byte unit starting with it.  See if we can safely use it.
3416   if (IROffset == 0) {
3417     // Pointers and int64's always fill the 8-byte unit.
3418     if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
3419         IRType->isIntegerTy(64))
3420       return IRType;
3421 
3422     // If we have a 1/2/4-byte integer, we can use it only if the rest of the
3423     // goodness in the source type is just tail padding.  This is allowed to
3424     // kick in for struct {double,int} on the int, but not on
3425     // struct{double,int,int} because we wouldn't return the second int.  We
3426     // have to do this analysis on the source type because we can't depend on
3427     // unions being lowered a specific way etc.
3428     if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
3429         IRType->isIntegerTy(32) ||
3430         (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
3431       unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
3432           cast<llvm::IntegerType>(IRType)->getBitWidth();
3433 
3434       if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
3435                                 SourceOffset*8+64, getContext()))
3436         return IRType;
3437     }
3438   }
3439 
3440   if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
3441     // If this is a struct, recurse into the field at the specified offset.
3442     const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
3443     if (IROffset < SL->getSizeInBytes()) {
3444       unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
3445       IROffset -= SL->getElementOffset(FieldIdx);
3446 
3447       return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
3448                                     SourceTy, SourceOffset);
3449     }
3450   }
3451 
3452   if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
3453     llvm::Type *EltTy = ATy->getElementType();
3454     unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
3455     unsigned EltOffset = IROffset/EltSize*EltSize;
3456     return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
3457                                   SourceOffset);
3458   }
3459 
3460   // Okay, we don't have any better idea of what to pass, so we pass this in an
3461   // integer register that isn't too big to fit the rest of the struct.
3462   unsigned TySizeInBytes =
3463     (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
3464 
3465   assert(TySizeInBytes != SourceOffset && "Empty field?");
3466 
3467   // It is always safe to classify this as an integer type up to i64 that
3468   // isn't larger than the structure.
3469   return llvm::IntegerType::get(getVMContext(),
3470                                 std::min(TySizeInBytes-SourceOffset, 8U)*8);
3471 }
3472 
3473 
3474 /// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
3475 /// be used as elements of a two register pair to pass or return, return a
3476 /// first class aggregate to represent them.  For example, if the low part of
3477 /// a by-value argument should be passed as i32* and the high part as float,
3478 /// return {i32*, float}.
3479 static llvm::Type *
3480 GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
3481                            const llvm::DataLayout &TD) {
3482   // In order to correctly satisfy the ABI, we need to the high part to start
3483   // at offset 8.  If the high and low parts we inferred are both 4-byte types
3484   // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
3485   // the second element at offset 8.  Check for this:
3486   unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
3487   unsigned HiAlign = TD.getABITypeAlignment(Hi);
3488   unsigned HiStart = llvm::alignTo(LoSize, HiAlign);
3489   assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
3490 
3491   // To handle this, we have to increase the size of the low part so that the
3492   // second element will start at an 8 byte offset.  We can't increase the size
3493   // of the second element because it might make us access off the end of the
3494   // struct.
3495   if (HiStart != 8) {
3496     // There are usually two sorts of types the ABI generation code can produce
3497     // for the low part of a pair that aren't 8 bytes in size: float or
3498     // i8/i16/i32.  This can also include pointers when they are 32-bit (X32 and
3499     // NaCl).
3500     // Promote these to a larger type.
3501     if (Lo->isFloatTy())
3502       Lo = llvm::Type::getDoubleTy(Lo->getContext());
3503     else {
3504       assert((Lo->isIntegerTy() || Lo->isPointerTy())
3505              && "Invalid/unknown lo type");
3506       Lo = llvm::Type::getInt64Ty(Lo->getContext());
3507     }
3508   }
3509 
3510   llvm::StructType *Result = llvm::StructType::get(Lo, Hi);
3511 
3512   // Verify that the second element is at an 8-byte offset.
3513   assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
3514          "Invalid x86-64 argument pair!");
3515   return Result;
3516 }
3517 
3518 ABIArgInfo X86_64ABIInfo::
3519 classifyReturnType(QualType RetTy) const {
3520   // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
3521   // classification algorithm.
3522   X86_64ABIInfo::Class Lo, Hi;
3523   classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
3524 
3525   // Check some invariants.
3526   assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
3527   assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
3528 
3529   llvm::Type *ResType = nullptr;
3530   switch (Lo) {
3531   case NoClass:
3532     if (Hi == NoClass)
3533       return ABIArgInfo::getIgnore();
3534     // If the low part is just padding, it takes no register, leave ResType
3535     // null.
3536     assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3537            "Unknown missing lo part");
3538     break;
3539 
3540   case SSEUp:
3541   case X87Up:
3542     llvm_unreachable("Invalid classification for lo word.");
3543 
3544     // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
3545     // hidden argument.
3546   case Memory:
3547     return getIndirectReturnResult(RetTy);
3548 
3549     // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
3550     // available register of the sequence %rax, %rdx is used.
3551   case Integer:
3552     ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
3553 
3554     // If we have a sign or zero extended integer, make sure to return Extend
3555     // so that the parameter gets the right LLVM IR attributes.
3556     if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3557       // Treat an enum type as its underlying type.
3558       if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
3559         RetTy = EnumTy->getDecl()->getIntegerType();
3560 
3561       if (RetTy->isIntegralOrEnumerationType() &&
3562           isPromotableIntegerTypeForABI(RetTy))
3563         return ABIArgInfo::getExtend(RetTy);
3564     }
3565     break;
3566 
3567     // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
3568     // available SSE register of the sequence %xmm0, %xmm1 is used.
3569   case SSE:
3570     ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
3571     break;
3572 
3573     // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
3574     // returned on the X87 stack in %st0 as 80-bit x87 number.
3575   case X87:
3576     ResType = llvm::Type::getX86_FP80Ty(getVMContext());
3577     break;
3578 
3579     // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
3580     // part of the value is returned in %st0 and the imaginary part in
3581     // %st1.
3582   case ComplexX87:
3583     assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
3584     ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
3585                                     llvm::Type::getX86_FP80Ty(getVMContext()));
3586     break;
3587   }
3588 
3589   llvm::Type *HighPart = nullptr;
3590   switch (Hi) {
3591     // Memory was handled previously and X87 should
3592     // never occur as a hi class.
3593   case Memory:
3594   case X87:
3595     llvm_unreachable("Invalid classification for hi word.");
3596 
3597   case ComplexX87: // Previously handled.
3598   case NoClass:
3599     break;
3600 
3601   case Integer:
3602     HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
3603     if (Lo == NoClass)  // Return HighPart at offset 8 in memory.
3604       return ABIArgInfo::getDirect(HighPart, 8);
3605     break;
3606   case SSE:
3607     HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
3608     if (Lo == NoClass)  // Return HighPart at offset 8 in memory.
3609       return ABIArgInfo::getDirect(HighPart, 8);
3610     break;
3611 
3612     // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
3613     // is passed in the next available eightbyte chunk if the last used
3614     // vector register.
3615     //
3616     // SSEUP should always be preceded by SSE, just widen.
3617   case SSEUp:
3618     assert(Lo == SSE && "Unexpected SSEUp classification.");
3619     ResType = GetByteVectorType(RetTy);
3620     break;
3621 
3622     // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
3623     // returned together with the previous X87 value in %st0.
3624   case X87Up:
3625     // If X87Up is preceded by X87, we don't need to do
3626     // anything. However, in some cases with unions it may not be
3627     // preceded by X87. In such situations we follow gcc and pass the
3628     // extra bits in an SSE reg.
3629     if (Lo != X87) {
3630       HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
3631       if (Lo == NoClass)  // Return HighPart at offset 8 in memory.
3632         return ABIArgInfo::getDirect(HighPart, 8);
3633     }
3634     break;
3635   }
3636 
3637   // If a high part was specified, merge it together with the low part.  It is
3638   // known to pass in the high eightbyte of the result.  We do this by forming a
3639   // first class struct aggregate with the high and low part: {low, high}
3640   if (HighPart)
3641     ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
3642 
3643   return ABIArgInfo::getDirect(ResType);
3644 }
3645 
3646 ABIArgInfo X86_64ABIInfo::classifyArgumentType(
3647   QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE,
3648   bool isNamedArg)
3649   const
3650 {
3651   Ty = useFirstFieldIfTransparentUnion(Ty);
3652 
3653   X86_64ABIInfo::Class Lo, Hi;
3654   classify(Ty, 0, Lo, Hi, isNamedArg);
3655 
3656   // Check some invariants.
3657   // FIXME: Enforce these by construction.
3658   assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
3659   assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
3660 
3661   neededInt = 0;
3662   neededSSE = 0;
3663   llvm::Type *ResType = nullptr;
3664   switch (Lo) {
3665   case NoClass:
3666     if (Hi == NoClass)
3667       return ABIArgInfo::getIgnore();
3668     // If the low part is just padding, it takes no register, leave ResType
3669     // null.
3670     assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3671            "Unknown missing lo part");
3672     break;
3673 
3674     // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
3675     // on the stack.
3676   case Memory:
3677 
3678     // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
3679     // COMPLEX_X87, it is passed in memory.
3680   case X87:
3681   case ComplexX87:
3682     if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect)
3683       ++neededInt;
3684     return getIndirectResult(Ty, freeIntRegs);
3685 
3686   case SSEUp:
3687   case X87Up:
3688     llvm_unreachable("Invalid classification for lo word.");
3689 
3690     // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
3691     // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
3692     // and %r9 is used.
3693   case Integer:
3694     ++neededInt;
3695 
3696     // Pick an 8-byte type based on the preferred type.
3697     ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
3698 
3699     // If we have a sign or zero extended integer, make sure to return Extend
3700     // so that the parameter gets the right LLVM IR attributes.
3701     if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3702       // Treat an enum type as its underlying type.
3703       if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3704         Ty = EnumTy->getDecl()->getIntegerType();
3705 
3706       if (Ty->isIntegralOrEnumerationType() &&
3707           isPromotableIntegerTypeForABI(Ty))
3708         return ABIArgInfo::getExtend(Ty);
3709     }
3710 
3711     break;
3712 
3713     // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
3714     // available SSE register is used, the registers are taken in the
3715     // order from %xmm0 to %xmm7.
3716   case SSE: {
3717     llvm::Type *IRType = CGT.ConvertType(Ty);
3718     ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
3719     ++neededSSE;
3720     break;
3721   }
3722   }
3723 
3724   llvm::Type *HighPart = nullptr;
3725   switch (Hi) {
3726     // Memory was handled previously, ComplexX87 and X87 should
3727     // never occur as hi classes, and X87Up must be preceded by X87,
3728     // which is passed in memory.
3729   case Memory:
3730   case X87:
3731   case ComplexX87:
3732     llvm_unreachable("Invalid classification for hi word.");
3733 
3734   case NoClass: break;
3735 
3736   case Integer:
3737     ++neededInt;
3738     // Pick an 8-byte type based on the preferred type.
3739     HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
3740 
3741     if (Lo == NoClass)  // Pass HighPart at offset 8 in memory.
3742       return ABIArgInfo::getDirect(HighPart, 8);
3743     break;
3744 
3745     // X87Up generally doesn't occur here (long double is passed in
3746     // memory), except in situations involving unions.
3747   case X87Up:
3748   case SSE:
3749     HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
3750 
3751     if (Lo == NoClass)  // Pass HighPart at offset 8 in memory.
3752       return ABIArgInfo::getDirect(HighPart, 8);
3753 
3754     ++neededSSE;
3755     break;
3756 
3757     // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
3758     // eightbyte is passed in the upper half of the last used SSE
3759     // register.  This only happens when 128-bit vectors are passed.
3760   case SSEUp:
3761     assert(Lo == SSE && "Unexpected SSEUp classification");
3762     ResType = GetByteVectorType(Ty);
3763     break;
3764   }
3765 
3766   // If a high part was specified, merge it together with the low part.  It is
3767   // known to pass in the high eightbyte of the result.  We do this by forming a
3768   // first class struct aggregate with the high and low part: {low, high}
3769   if (HighPart)
3770     ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
3771 
3772   return ABIArgInfo::getDirect(ResType);
3773 }
3774 
3775 ABIArgInfo
3776 X86_64ABIInfo::classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
3777                                              unsigned &NeededSSE) const {
3778   auto RT = Ty->getAs<RecordType>();
3779   assert(RT && "classifyRegCallStructType only valid with struct types");
3780 
3781   if (RT->getDecl()->hasFlexibleArrayMember())
3782     return getIndirectReturnResult(Ty);
3783 
3784   // Sum up bases
3785   if (auto CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
3786     if (CXXRD->isDynamicClass()) {
3787       NeededInt = NeededSSE = 0;
3788       return getIndirectReturnResult(Ty);
3789     }
3790 
3791     for (const auto &I : CXXRD->bases())
3792       if (classifyRegCallStructTypeImpl(I.getType(), NeededInt, NeededSSE)
3793               .isIndirect()) {
3794         NeededInt = NeededSSE = 0;
3795         return getIndirectReturnResult(Ty);
3796       }
3797   }
3798 
3799   // Sum up members
3800   for (const auto *FD : RT->getDecl()->fields()) {
3801     if (FD->getType()->isRecordType() && !FD->getType()->isUnionType()) {
3802       if (classifyRegCallStructTypeImpl(FD->getType(), NeededInt, NeededSSE)
3803               .isIndirect()) {
3804         NeededInt = NeededSSE = 0;
3805         return getIndirectReturnResult(Ty);
3806       }
3807     } else {
3808       unsigned LocalNeededInt, LocalNeededSSE;
3809       if (classifyArgumentType(FD->getType(), UINT_MAX, LocalNeededInt,
3810                                LocalNeededSSE, true)
3811               .isIndirect()) {
3812         NeededInt = NeededSSE = 0;
3813         return getIndirectReturnResult(Ty);
3814       }
3815       NeededInt += LocalNeededInt;
3816       NeededSSE += LocalNeededSSE;
3817     }
3818   }
3819 
3820   return ABIArgInfo::getDirect();
3821 }
3822 
3823 ABIArgInfo X86_64ABIInfo::classifyRegCallStructType(QualType Ty,
3824                                                     unsigned &NeededInt,
3825                                                     unsigned &NeededSSE) const {
3826 
3827   NeededInt = 0;
3828   NeededSSE = 0;
3829 
3830   return classifyRegCallStructTypeImpl(Ty, NeededInt, NeededSSE);
3831 }
3832 
3833 void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
3834 
3835   const unsigned CallingConv = FI.getCallingConvention();
3836   // It is possible to force Win64 calling convention on any x86_64 target by
3837   // using __attribute__((ms_abi)). In such case to correctly emit Win64
3838   // compatible code delegate this call to WinX86_64ABIInfo::computeInfo.
3839   if (CallingConv == llvm::CallingConv::Win64) {
3840     WinX86_64ABIInfo Win64ABIInfo(CGT, AVXLevel);
3841     Win64ABIInfo.computeInfo(FI);
3842     return;
3843   }
3844 
3845   bool IsRegCall = CallingConv == llvm::CallingConv::X86_RegCall;
3846 
3847   // Keep track of the number of assigned registers.
3848   unsigned FreeIntRegs = IsRegCall ? 11 : 6;
3849   unsigned FreeSSERegs = IsRegCall ? 16 : 8;
3850   unsigned NeededInt, NeededSSE;
3851 
3852   if (!::classifyReturnType(getCXXABI(), FI, *this)) {
3853     if (IsRegCall && FI.getReturnType()->getTypePtr()->isRecordType() &&
3854         !FI.getReturnType()->getTypePtr()->isUnionType()) {
3855       FI.getReturnInfo() =
3856           classifyRegCallStructType(FI.getReturnType(), NeededInt, NeededSSE);
3857       if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
3858         FreeIntRegs -= NeededInt;
3859         FreeSSERegs -= NeededSSE;
3860       } else {
3861         FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType());
3862       }
3863     } else if (IsRegCall && FI.getReturnType()->getAs<ComplexType>() &&
3864                getContext().getCanonicalType(FI.getReturnType()
3865                                                  ->getAs<ComplexType>()
3866                                                  ->getElementType()) ==
3867                    getContext().LongDoubleTy)
3868       // Complex Long Double Type is passed in Memory when Regcall
3869       // calling convention is used.
3870       FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType());
3871     else
3872       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
3873   }
3874 
3875   // If the return value is indirect, then the hidden argument is consuming one
3876   // integer register.
3877   if (FI.getReturnInfo().isIndirect())
3878     --FreeIntRegs;
3879 
3880   // The chain argument effectively gives us another free register.
3881   if (FI.isChainCall())
3882     ++FreeIntRegs;
3883 
3884   unsigned NumRequiredArgs = FI.getNumRequiredArgs();
3885   // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
3886   // get assigned (in left-to-right order) for passing as follows...
3887   unsigned ArgNo = 0;
3888   for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
3889        it != ie; ++it, ++ArgNo) {
3890     bool IsNamedArg = ArgNo < NumRequiredArgs;
3891 
3892     if (IsRegCall && it->type->isStructureOrClassType())
3893       it->info = classifyRegCallStructType(it->type, NeededInt, NeededSSE);
3894     else
3895       it->info = classifyArgumentType(it->type, FreeIntRegs, NeededInt,
3896                                       NeededSSE, IsNamedArg);
3897 
3898     // AMD64-ABI 3.2.3p3: If there are no registers available for any
3899     // eightbyte of an argument, the whole argument is passed on the
3900     // stack. If registers have already been assigned for some
3901     // eightbytes of such an argument, the assignments get reverted.
3902     if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
3903       FreeIntRegs -= NeededInt;
3904       FreeSSERegs -= NeededSSE;
3905     } else {
3906       it->info = getIndirectResult(it->type, FreeIntRegs);
3907     }
3908   }
3909 }
3910 
3911 static Address EmitX86_64VAArgFromMemory(CodeGenFunction &CGF,
3912                                          Address VAListAddr, QualType Ty) {
3913   Address overflow_arg_area_p =
3914       CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_p");
3915   llvm::Value *overflow_arg_area =
3916     CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
3917 
3918   // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
3919   // byte boundary if alignment needed by type exceeds 8 byte boundary.
3920   // It isn't stated explicitly in the standard, but in practice we use
3921   // alignment greater than 16 where necessary.
3922   CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
3923   if (Align > CharUnits::fromQuantity(8)) {
3924     overflow_arg_area = emitRoundPointerUpToAlignment(CGF, overflow_arg_area,
3925                                                       Align);
3926   }
3927 
3928   // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
3929   llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
3930   llvm::Value *Res =
3931     CGF.Builder.CreateBitCast(overflow_arg_area,
3932                               llvm::PointerType::getUnqual(LTy));
3933 
3934   // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
3935   // l->overflow_arg_area + sizeof(type).
3936   // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
3937   // an 8 byte boundary.
3938 
3939   uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
3940   llvm::Value *Offset =
3941       llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7)  & ~7);
3942   overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
3943                                             "overflow_arg_area.next");
3944   CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
3945 
3946   // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
3947   return Address(Res, Align);
3948 }
3949 
3950 Address X86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3951                                  QualType Ty) const {
3952   // Assume that va_list type is correct; should be pointer to LLVM type:
3953   // struct {
3954   //   i32 gp_offset;
3955   //   i32 fp_offset;
3956   //   i8* overflow_arg_area;
3957   //   i8* reg_save_area;
3958   // };
3959   unsigned neededInt, neededSSE;
3960 
3961   Ty = getContext().getCanonicalType(Ty);
3962   ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
3963                                        /*isNamedArg*/false);
3964 
3965   // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
3966   // in the registers. If not go to step 7.
3967   if (!neededInt && !neededSSE)
3968     return EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
3969 
3970   // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
3971   // general purpose registers needed to pass type and num_fp to hold
3972   // the number of floating point registers needed.
3973 
3974   // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
3975   // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
3976   // l->fp_offset > 304 - num_fp * 16 go to step 7.
3977   //
3978   // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
3979   // register save space).
3980 
3981   llvm::Value *InRegs = nullptr;
3982   Address gp_offset_p = Address::invalid(), fp_offset_p = Address::invalid();
3983   llvm::Value *gp_offset = nullptr, *fp_offset = nullptr;
3984   if (neededInt) {
3985     gp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "gp_offset_p");
3986     gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
3987     InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
3988     InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
3989   }
3990 
3991   if (neededSSE) {
3992     fp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 1, "fp_offset_p");
3993     fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
3994     llvm::Value *FitsInFP =
3995       llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
3996     FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
3997     InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
3998   }
3999 
4000   llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
4001   llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
4002   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
4003   CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
4004 
4005   // Emit code to load the value if it was passed in registers.
4006 
4007   CGF.EmitBlock(InRegBlock);
4008 
4009   // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
4010   // an offset of l->gp_offset and/or l->fp_offset. This may require
4011   // copying to a temporary location in case the parameter is passed
4012   // in different register classes or requires an alignment greater
4013   // than 8 for general purpose registers and 16 for XMM registers.
4014   //
4015   // FIXME: This really results in shameful code when we end up needing to
4016   // collect arguments from different places; often what should result in a
4017   // simple assembling of a structure from scattered addresses has many more
4018   // loads than necessary. Can we clean this up?
4019   llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
4020   llvm::Value *RegSaveArea = CGF.Builder.CreateLoad(
4021       CGF.Builder.CreateStructGEP(VAListAddr, 3), "reg_save_area");
4022 
4023   Address RegAddr = Address::invalid();
4024   if (neededInt && neededSSE) {
4025     // FIXME: Cleanup.
4026     assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
4027     llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
4028     Address Tmp = CGF.CreateMemTemp(Ty);
4029     Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
4030     assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
4031     llvm::Type *TyLo = ST->getElementType(0);
4032     llvm::Type *TyHi = ST->getElementType(1);
4033     assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
4034            "Unexpected ABI info for mixed regs");
4035     llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
4036     llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
4037     llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegSaveArea, gp_offset);
4038     llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegSaveArea, fp_offset);
4039     llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr;
4040     llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr;
4041 
4042     // Copy the first element.
4043     // FIXME: Our choice of alignment here and below is probably pessimistic.
4044     llvm::Value *V = CGF.Builder.CreateAlignedLoad(
4045         TyLo, CGF.Builder.CreateBitCast(RegLoAddr, PTyLo),
4046         CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyLo)));
4047     CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
4048 
4049     // Copy the second element.
4050     V = CGF.Builder.CreateAlignedLoad(
4051         TyHi, CGF.Builder.CreateBitCast(RegHiAddr, PTyHi),
4052         CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyHi)));
4053     CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
4054 
4055     RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
4056   } else if (neededInt) {
4057     RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, gp_offset),
4058                       CharUnits::fromQuantity(8));
4059     RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
4060 
4061     // Copy to a temporary if necessary to ensure the appropriate alignment.
4062     std::pair<CharUnits, CharUnits> SizeAlign =
4063         getContext().getTypeInfoInChars(Ty);
4064     uint64_t TySize = SizeAlign.first.getQuantity();
4065     CharUnits TyAlign = SizeAlign.second;
4066 
4067     // Copy into a temporary if the type is more aligned than the
4068     // register save area.
4069     if (TyAlign.getQuantity() > 8) {
4070       Address Tmp = CGF.CreateMemTemp(Ty);
4071       CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, false);
4072       RegAddr = Tmp;
4073     }
4074 
4075   } else if (neededSSE == 1) {
4076     RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
4077                       CharUnits::fromQuantity(16));
4078     RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
4079   } else {
4080     assert(neededSSE == 2 && "Invalid number of needed registers!");
4081     // SSE registers are spaced 16 bytes apart in the register save
4082     // area, we need to collect the two eightbytes together.
4083     // The ABI isn't explicit about this, but it seems reasonable
4084     // to assume that the slots are 16-byte aligned, since the stack is
4085     // naturally 16-byte aligned and the prologue is expected to store
4086     // all the SSE registers to the RSA.
4087     Address RegAddrLo = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
4088                                 CharUnits::fromQuantity(16));
4089     Address RegAddrHi =
4090       CGF.Builder.CreateConstInBoundsByteGEP(RegAddrLo,
4091                                              CharUnits::fromQuantity(16));
4092     llvm::Type *ST = AI.canHaveCoerceToType()
4093                          ? AI.getCoerceToType()
4094                          : llvm::StructType::get(CGF.DoubleTy, CGF.DoubleTy);
4095     llvm::Value *V;
4096     Address Tmp = CGF.CreateMemTemp(Ty);
4097     Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
4098     V = CGF.Builder.CreateLoad(CGF.Builder.CreateElementBitCast(
4099         RegAddrLo, ST->getStructElementType(0)));
4100     CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
4101     V = CGF.Builder.CreateLoad(CGF.Builder.CreateElementBitCast(
4102         RegAddrHi, ST->getStructElementType(1)));
4103     CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
4104 
4105     RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
4106   }
4107 
4108   // AMD64-ABI 3.5.7p5: Step 5. Set:
4109   // l->gp_offset = l->gp_offset + num_gp * 8
4110   // l->fp_offset = l->fp_offset + num_fp * 16.
4111   if (neededInt) {
4112     llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
4113     CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
4114                             gp_offset_p);
4115   }
4116   if (neededSSE) {
4117     llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
4118     CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
4119                             fp_offset_p);
4120   }
4121   CGF.EmitBranch(ContBlock);
4122 
4123   // Emit code to load the value if it was passed in memory.
4124 
4125   CGF.EmitBlock(InMemBlock);
4126   Address MemAddr = EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
4127 
4128   // Return the appropriate result.
4129 
4130   CGF.EmitBlock(ContBlock);
4131   Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, MemAddr, InMemBlock,
4132                                  "vaarg.addr");
4133   return ResAddr;
4134 }
4135 
4136 Address X86_64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
4137                                    QualType Ty) const {
4138   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
4139                           CGF.getContext().getTypeInfoInChars(Ty),
4140                           CharUnits::fromQuantity(8),
4141                           /*allowHigherAlign*/ false);
4142 }
4143 
4144 ABIArgInfo
4145 WinX86_64ABIInfo::reclassifyHvaArgType(QualType Ty, unsigned &FreeSSERegs,
4146                                     const ABIArgInfo &current) const {
4147   // Assumes vectorCall calling convention.
4148   const Type *Base = nullptr;
4149   uint64_t NumElts = 0;
4150 
4151   if (!Ty->isBuiltinType() && !Ty->isVectorType() &&
4152       isHomogeneousAggregate(Ty, Base, NumElts) && FreeSSERegs >= NumElts) {
4153     FreeSSERegs -= NumElts;
4154     return getDirectX86Hva();
4155   }
4156   return current;
4157 }
4158 
4159 ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, unsigned &FreeSSERegs,
4160                                       bool IsReturnType, bool IsVectorCall,
4161                                       bool IsRegCall) const {
4162 
4163   if (Ty->isVoidType())
4164     return ABIArgInfo::getIgnore();
4165 
4166   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4167     Ty = EnumTy->getDecl()->getIntegerType();
4168 
4169   TypeInfo Info = getContext().getTypeInfo(Ty);
4170   uint64_t Width = Info.Width;
4171   CharUnits Align = getContext().toCharUnitsFromBits(Info.Align);
4172 
4173   const RecordType *RT = Ty->getAs<RecordType>();
4174   if (RT) {
4175     if (!IsReturnType) {
4176       if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
4177         return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
4178     }
4179 
4180     if (RT->getDecl()->hasFlexibleArrayMember())
4181       return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
4182 
4183   }
4184 
4185   const Type *Base = nullptr;
4186   uint64_t NumElts = 0;
4187   // vectorcall adds the concept of a homogenous vector aggregate, similar to
4188   // other targets.
4189   if ((IsVectorCall || IsRegCall) &&
4190       isHomogeneousAggregate(Ty, Base, NumElts)) {
4191     if (IsRegCall) {
4192       if (FreeSSERegs >= NumElts) {
4193         FreeSSERegs -= NumElts;
4194         if (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())
4195           return ABIArgInfo::getDirect();
4196         return ABIArgInfo::getExpand();
4197       }
4198       return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
4199     } else if (IsVectorCall) {
4200       if (FreeSSERegs >= NumElts &&
4201           (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())) {
4202         FreeSSERegs -= NumElts;
4203         return ABIArgInfo::getDirect();
4204       } else if (IsReturnType) {
4205         return ABIArgInfo::getExpand();
4206       } else if (!Ty->isBuiltinType() && !Ty->isVectorType()) {
4207         // HVAs are delayed and reclassified in the 2nd step.
4208         return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
4209       }
4210     }
4211   }
4212 
4213   if (Ty->isMemberPointerType()) {
4214     // If the member pointer is represented by an LLVM int or ptr, pass it
4215     // directly.
4216     llvm::Type *LLTy = CGT.ConvertType(Ty);
4217     if (LLTy->isPointerTy() || LLTy->isIntegerTy())
4218       return ABIArgInfo::getDirect();
4219   }
4220 
4221   if (RT || Ty->isAnyComplexType() || Ty->isMemberPointerType()) {
4222     // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
4223     // not 1, 2, 4, or 8 bytes, must be passed by reference."
4224     if (Width > 64 || !llvm::isPowerOf2_64(Width))
4225       return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
4226 
4227     // Otherwise, coerce it to a small integer.
4228     return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Width));
4229   }
4230 
4231   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4232     switch (BT->getKind()) {
4233     case BuiltinType::Bool:
4234       // Bool type is always extended to the ABI, other builtin types are not
4235       // extended.
4236       return ABIArgInfo::getExtend(Ty);
4237 
4238     case BuiltinType::LongDouble:
4239       // Mingw64 GCC uses the old 80 bit extended precision floating point
4240       // unit. It passes them indirectly through memory.
4241       if (IsMingw64) {
4242         const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
4243         if (LDF == &llvm::APFloat::x87DoubleExtended())
4244           return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
4245       }
4246       break;
4247 
4248     case BuiltinType::Int128:
4249     case BuiltinType::UInt128:
4250       // If it's a parameter type, the normal ABI rule is that arguments larger
4251       // than 8 bytes are passed indirectly. GCC follows it. We follow it too,
4252       // even though it isn't particularly efficient.
4253       if (!IsReturnType)
4254         return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
4255 
4256       // Mingw64 GCC returns i128 in XMM0. Coerce to v2i64 to handle that.
4257       // Clang matches them for compatibility.
4258       return ABIArgInfo::getDirect(llvm::FixedVectorType::get(
4259           llvm::Type::getInt64Ty(getVMContext()), 2));
4260 
4261     default:
4262       break;
4263     }
4264   }
4265 
4266   if (Ty->isExtIntType()) {
4267     // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
4268     // not 1, 2, 4, or 8 bytes, must be passed by reference."
4269     // However, non-power-of-two _ExtInts will be passed as 1,2,4 or 8 bytes
4270     // anyway as long is it fits in them, so we don't have to check the power of
4271     // 2.
4272     if (Width <= 64)
4273       return ABIArgInfo::getDirect();
4274     return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
4275   }
4276 
4277   return ABIArgInfo::getDirect();
4278 }
4279 
4280 void WinX86_64ABIInfo::computeVectorCallArgs(CGFunctionInfo &FI,
4281                                              unsigned FreeSSERegs,
4282                                              bool IsVectorCall,
4283                                              bool IsRegCall) const {
4284   unsigned Count = 0;
4285   for (auto &I : FI.arguments()) {
4286     // Vectorcall in x64 only permits the first 6 arguments to be passed
4287     // as XMM/YMM registers.
4288     if (Count < VectorcallMaxParamNumAsReg)
4289       I.info = classify(I.type, FreeSSERegs, false, IsVectorCall, IsRegCall);
4290     else {
4291       // Since these cannot be passed in registers, pretend no registers
4292       // are left.
4293       unsigned ZeroSSERegsAvail = 0;
4294       I.info = classify(I.type, /*FreeSSERegs=*/ZeroSSERegsAvail, false,
4295                         IsVectorCall, IsRegCall);
4296     }
4297     ++Count;
4298   }
4299 
4300   for (auto &I : FI.arguments()) {
4301     I.info = reclassifyHvaArgType(I.type, FreeSSERegs, I.info);
4302   }
4303 }
4304 
4305 void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
4306   const unsigned CC = FI.getCallingConvention();
4307   bool IsVectorCall = CC == llvm::CallingConv::X86_VectorCall;
4308   bool IsRegCall = CC == llvm::CallingConv::X86_RegCall;
4309 
4310   // If __attribute__((sysv_abi)) is in use, use the SysV argument
4311   // classification rules.
4312   if (CC == llvm::CallingConv::X86_64_SysV) {
4313     X86_64ABIInfo SysVABIInfo(CGT, AVXLevel);
4314     SysVABIInfo.computeInfo(FI);
4315     return;
4316   }
4317 
4318   unsigned FreeSSERegs = 0;
4319   if (IsVectorCall) {
4320     // We can use up to 4 SSE return registers with vectorcall.
4321     FreeSSERegs = 4;
4322   } else if (IsRegCall) {
4323     // RegCall gives us 16 SSE registers.
4324     FreeSSERegs = 16;
4325   }
4326 
4327   if (!getCXXABI().classifyReturnType(FI))
4328     FI.getReturnInfo() = classify(FI.getReturnType(), FreeSSERegs, true,
4329                                   IsVectorCall, IsRegCall);
4330 
4331   if (IsVectorCall) {
4332     // We can use up to 6 SSE register parameters with vectorcall.
4333     FreeSSERegs = 6;
4334   } else if (IsRegCall) {
4335     // RegCall gives us 16 SSE registers, we can reuse the return registers.
4336     FreeSSERegs = 16;
4337   }
4338 
4339   if (IsVectorCall) {
4340     computeVectorCallArgs(FI, FreeSSERegs, IsVectorCall, IsRegCall);
4341   } else {
4342     for (auto &I : FI.arguments())
4343       I.info = classify(I.type, FreeSSERegs, false, IsVectorCall, IsRegCall);
4344   }
4345 
4346 }
4347 
4348 Address WinX86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4349                                     QualType Ty) const {
4350 
4351   bool IsIndirect = false;
4352 
4353   // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
4354   // not 1, 2, 4, or 8 bytes, must be passed by reference."
4355   if (isAggregateTypeForABI(Ty) || Ty->isMemberPointerType()) {
4356     uint64_t Width = getContext().getTypeSize(Ty);
4357     IsIndirect = Width > 64 || !llvm::isPowerOf2_64(Width);
4358   }
4359 
4360   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
4361                           CGF.getContext().getTypeInfoInChars(Ty),
4362                           CharUnits::fromQuantity(8),
4363                           /*allowHigherAlign*/ false);
4364 }
4365 
4366 static bool PPC_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4367                                         llvm::Value *Address, bool Is64Bit,
4368                                         bool IsAIX) {
4369   // This is calculated from the LLVM and GCC tables and verified
4370   // against gcc output.  AFAIK all PPC ABIs use the same encoding.
4371 
4372   CodeGen::CGBuilderTy &Builder = CGF.Builder;
4373 
4374   llvm::IntegerType *i8 = CGF.Int8Ty;
4375   llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
4376   llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
4377   llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
4378 
4379   // 0-31: r0-31, the 4-byte or 8-byte general-purpose registers
4380   AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 0, 31);
4381 
4382   // 32-63: fp0-31, the 8-byte floating-point registers
4383   AssignToArrayRange(Builder, Address, Eight8, 32, 63);
4384 
4385   // 64-67 are various 4-byte or 8-byte special-purpose registers:
4386   // 64: mq
4387   // 65: lr
4388   // 66: ctr
4389   // 67: ap
4390   AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 64, 67);
4391 
4392   // 68-76 are various 4-byte special-purpose registers:
4393   // 68-75 cr0-7
4394   // 76: xer
4395   AssignToArrayRange(Builder, Address, Four8, 68, 76);
4396 
4397   // 77-108: v0-31, the 16-byte vector registers
4398   AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
4399 
4400   // 109: vrsave
4401   // 110: vscr
4402   AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 109, 110);
4403 
4404   // AIX does not utilize the rest of the registers.
4405   if (IsAIX)
4406     return false;
4407 
4408   // 111: spe_acc
4409   // 112: spefscr
4410   // 113: sfp
4411   AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 111, 113);
4412 
4413   if (!Is64Bit)
4414     return false;
4415 
4416   // TODO: Need to verify if these registers are used on 64 bit AIX with Power8
4417   // or above CPU.
4418   // 64-bit only registers:
4419   // 114: tfhar
4420   // 115: tfiar
4421   // 116: texasr
4422   AssignToArrayRange(Builder, Address, Eight8, 114, 116);
4423 
4424   return false;
4425 }
4426 
4427 // AIX
4428 namespace {
4429 /// AIXABIInfo - The AIX XCOFF ABI information.
4430 class AIXABIInfo : public ABIInfo {
4431   const bool Is64Bit;
4432   const unsigned PtrByteSize;
4433   CharUnits getParamTypeAlignment(QualType Ty) const;
4434 
4435 public:
4436   AIXABIInfo(CodeGen::CodeGenTypes &CGT, bool Is64Bit)
4437       : ABIInfo(CGT), Is64Bit(Is64Bit), PtrByteSize(Is64Bit ? 8 : 4) {}
4438 
4439   bool isPromotableTypeForABI(QualType Ty) const;
4440 
4441   ABIArgInfo classifyReturnType(QualType RetTy) const;
4442   ABIArgInfo classifyArgumentType(QualType Ty) const;
4443 
4444   void computeInfo(CGFunctionInfo &FI) const override {
4445     if (!getCXXABI().classifyReturnType(FI))
4446       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
4447 
4448     for (auto &I : FI.arguments())
4449       I.info = classifyArgumentType(I.type);
4450   }
4451 
4452   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4453                     QualType Ty) const override;
4454 };
4455 
4456 class AIXTargetCodeGenInfo : public TargetCodeGenInfo {
4457   const bool Is64Bit;
4458 
4459 public:
4460   AIXTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool Is64Bit)
4461       : TargetCodeGenInfo(std::make_unique<AIXABIInfo>(CGT, Is64Bit)),
4462         Is64Bit(Is64Bit) {}
4463   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4464     return 1; // r1 is the dedicated stack pointer
4465   }
4466 
4467   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4468                                llvm::Value *Address) const override;
4469 };
4470 } // namespace
4471 
4472 // Return true if the ABI requires Ty to be passed sign- or zero-
4473 // extended to 32/64 bits.
4474 bool AIXABIInfo::isPromotableTypeForABI(QualType Ty) const {
4475   // Treat an enum type as its underlying type.
4476   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4477     Ty = EnumTy->getDecl()->getIntegerType();
4478 
4479   // Promotable integer types are required to be promoted by the ABI.
4480   if (Ty->isPromotableIntegerType())
4481     return true;
4482 
4483   if (!Is64Bit)
4484     return false;
4485 
4486   // For 64 bit mode, in addition to the usual promotable integer types, we also
4487   // need to extend all 32-bit types, since the ABI requires promotion to 64
4488   // bits.
4489   if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
4490     switch (BT->getKind()) {
4491     case BuiltinType::Int:
4492     case BuiltinType::UInt:
4493       return true;
4494     default:
4495       break;
4496     }
4497 
4498   return false;
4499 }
4500 
4501 ABIArgInfo AIXABIInfo::classifyReturnType(QualType RetTy) const {
4502   if (RetTy->isAnyComplexType())
4503     llvm::report_fatal_error("complex type is not supported on AIX yet");
4504 
4505   if (RetTy->isVectorType())
4506     llvm::report_fatal_error("vector type is not supported on AIX yet");
4507 
4508   if (RetTy->isVoidType())
4509     return ABIArgInfo::getIgnore();
4510 
4511   // TODO:  Evaluate if AIX power alignment rule would have an impact on the
4512   // alignment here.
4513   if (isAggregateTypeForABI(RetTy))
4514     return getNaturalAlignIndirect(RetTy);
4515 
4516   return (isPromotableTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
4517                                         : ABIArgInfo::getDirect());
4518 }
4519 
4520 ABIArgInfo AIXABIInfo::classifyArgumentType(QualType Ty) const {
4521   Ty = useFirstFieldIfTransparentUnion(Ty);
4522 
4523   if (Ty->isAnyComplexType())
4524     llvm::report_fatal_error("complex type is not supported on AIX yet");
4525 
4526   if (Ty->isVectorType())
4527     llvm::report_fatal_error("vector type is not supported on AIX yet");
4528 
4529   // TODO:  Evaluate if AIX power alignment rule would have an impact on the
4530   // alignment here.
4531   if (isAggregateTypeForABI(Ty)) {
4532     // Records with non-trivial destructors/copy-constructors should not be
4533     // passed by value.
4534     if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
4535       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
4536 
4537     CharUnits CCAlign = getParamTypeAlignment(Ty);
4538     CharUnits TyAlign = getContext().getTypeAlignInChars(Ty);
4539 
4540     return ABIArgInfo::getIndirect(CCAlign, /*ByVal*/ true,
4541                                    /*Realign*/ TyAlign > CCAlign);
4542   }
4543 
4544   return (isPromotableTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
4545                                      : ABIArgInfo::getDirect());
4546 }
4547 
4548 CharUnits AIXABIInfo::getParamTypeAlignment(QualType Ty) const {
4549   if (Ty->isAnyComplexType())
4550     llvm::report_fatal_error("complex type is not supported on AIX yet");
4551 
4552   if (Ty->isVectorType())
4553     llvm::report_fatal_error("vector type is not supported on AIX yet");
4554 
4555   // If the structure contains a vector type, the alignment is 16.
4556   if (isRecordWithSIMDVectorType(getContext(), Ty))
4557     return CharUnits::fromQuantity(16);
4558 
4559   return CharUnits::fromQuantity(PtrByteSize);
4560 }
4561 
4562 Address AIXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4563                               QualType Ty) const {
4564   if (Ty->isAnyComplexType())
4565     llvm::report_fatal_error("complex type is not supported on AIX yet");
4566 
4567   if (Ty->isVectorType())
4568     llvm::report_fatal_error("vector type is not supported on AIX yet");
4569 
4570   auto TypeInfo = getContext().getTypeInfoInChars(Ty);
4571   TypeInfo.second = getParamTypeAlignment(Ty);
4572 
4573   CharUnits SlotSize = CharUnits::fromQuantity(PtrByteSize);
4574 
4575   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false, TypeInfo,
4576                           SlotSize, /*AllowHigher*/ true);
4577 }
4578 
4579 bool AIXTargetCodeGenInfo::initDwarfEHRegSizeTable(
4580     CodeGen::CodeGenFunction &CGF, llvm::Value *Address) const {
4581   return PPC_initDwarfEHRegSizeTable(CGF, Address, Is64Bit, /*IsAIX*/ true);
4582 }
4583 
4584 // PowerPC-32
4585 namespace {
4586 /// PPC32_SVR4_ABIInfo - The 32-bit PowerPC ELF (SVR4) ABI information.
4587 class PPC32_SVR4_ABIInfo : public DefaultABIInfo {
4588   bool IsSoftFloatABI;
4589   bool IsRetSmallStructInRegABI;
4590 
4591   CharUnits getParamTypeAlignment(QualType Ty) const;
4592 
4593 public:
4594   PPC32_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, bool SoftFloatABI,
4595                      bool RetSmallStructInRegABI)
4596       : DefaultABIInfo(CGT), IsSoftFloatABI(SoftFloatABI),
4597         IsRetSmallStructInRegABI(RetSmallStructInRegABI) {}
4598 
4599   ABIArgInfo classifyReturnType(QualType RetTy) const;
4600 
4601   void computeInfo(CGFunctionInfo &FI) const override {
4602     if (!getCXXABI().classifyReturnType(FI))
4603       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
4604     for (auto &I : FI.arguments())
4605       I.info = classifyArgumentType(I.type);
4606   }
4607 
4608   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4609                     QualType Ty) const override;
4610 };
4611 
4612 class PPC32TargetCodeGenInfo : public TargetCodeGenInfo {
4613 public:
4614   PPC32TargetCodeGenInfo(CodeGenTypes &CGT, bool SoftFloatABI,
4615                          bool RetSmallStructInRegABI)
4616       : TargetCodeGenInfo(std::make_unique<PPC32_SVR4_ABIInfo>(
4617             CGT, SoftFloatABI, RetSmallStructInRegABI)) {}
4618 
4619   static bool isStructReturnInRegABI(const llvm::Triple &Triple,
4620                                      const CodeGenOptions &Opts);
4621 
4622   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4623     // This is recovered from gcc output.
4624     return 1; // r1 is the dedicated stack pointer
4625   }
4626 
4627   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4628                                llvm::Value *Address) const override;
4629 };
4630 }
4631 
4632 CharUnits PPC32_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const {
4633   // Complex types are passed just like their elements.
4634   if (const ComplexType *CTy = Ty->getAs<ComplexType>())
4635     Ty = CTy->getElementType();
4636 
4637   if (Ty->isVectorType())
4638     return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16
4639                                                                        : 4);
4640 
4641   // For single-element float/vector structs, we consider the whole type
4642   // to have the same alignment requirements as its single element.
4643   const Type *AlignTy = nullptr;
4644   if (const Type *EltType = isSingleElementStruct(Ty, getContext())) {
4645     const BuiltinType *BT = EltType->getAs<BuiltinType>();
4646     if ((EltType->isVectorType() && getContext().getTypeSize(EltType) == 128) ||
4647         (BT && BT->isFloatingPoint()))
4648       AlignTy = EltType;
4649   }
4650 
4651   if (AlignTy)
4652     return CharUnits::fromQuantity(AlignTy->isVectorType() ? 16 : 4);
4653   return CharUnits::fromQuantity(4);
4654 }
4655 
4656 ABIArgInfo PPC32_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
4657   uint64_t Size;
4658 
4659   // -msvr4-struct-return puts small aggregates in GPR3 and GPR4.
4660   if (isAggregateTypeForABI(RetTy) && IsRetSmallStructInRegABI &&
4661       (Size = getContext().getTypeSize(RetTy)) <= 64) {
4662     // System V ABI (1995), page 3-22, specified:
4663     // > A structure or union whose size is less than or equal to 8 bytes
4664     // > shall be returned in r3 and r4, as if it were first stored in the
4665     // > 8-byte aligned memory area and then the low addressed word were
4666     // > loaded into r3 and the high-addressed word into r4.  Bits beyond
4667     // > the last member of the structure or union are not defined.
4668     //
4669     // GCC for big-endian PPC32 inserts the pad before the first member,
4670     // not "beyond the last member" of the struct.  To stay compatible
4671     // with GCC, we coerce the struct to an integer of the same size.
4672     // LLVM will extend it and return i32 in r3, or i64 in r3:r4.
4673     if (Size == 0)
4674       return ABIArgInfo::getIgnore();
4675     else {
4676       llvm::Type *CoerceTy = llvm::Type::getIntNTy(getVMContext(), Size);
4677       return ABIArgInfo::getDirect(CoerceTy);
4678     }
4679   }
4680 
4681   return DefaultABIInfo::classifyReturnType(RetTy);
4682 }
4683 
4684 // TODO: this implementation is now likely redundant with
4685 // DefaultABIInfo::EmitVAArg.
4686 Address PPC32_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAList,
4687                                       QualType Ty) const {
4688   if (getTarget().getTriple().isOSDarwin()) {
4689     auto TI = getContext().getTypeInfoInChars(Ty);
4690     TI.second = getParamTypeAlignment(Ty);
4691 
4692     CharUnits SlotSize = CharUnits::fromQuantity(4);
4693     return emitVoidPtrVAArg(CGF, VAList, Ty,
4694                             classifyArgumentType(Ty).isIndirect(), TI, SlotSize,
4695                             /*AllowHigherAlign=*/true);
4696   }
4697 
4698   const unsigned OverflowLimit = 8;
4699   if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
4700     // TODO: Implement this. For now ignore.
4701     (void)CTy;
4702     return Address::invalid(); // FIXME?
4703   }
4704 
4705   // struct __va_list_tag {
4706   //   unsigned char gpr;
4707   //   unsigned char fpr;
4708   //   unsigned short reserved;
4709   //   void *overflow_arg_area;
4710   //   void *reg_save_area;
4711   // };
4712 
4713   bool isI64 = Ty->isIntegerType() && getContext().getTypeSize(Ty) == 64;
4714   bool isInt = !Ty->isFloatingType();
4715   bool isF64 = Ty->isFloatingType() && getContext().getTypeSize(Ty) == 64;
4716 
4717   // All aggregates are passed indirectly?  That doesn't seem consistent
4718   // with the argument-lowering code.
4719   bool isIndirect = isAggregateTypeForABI(Ty);
4720 
4721   CGBuilderTy &Builder = CGF.Builder;
4722 
4723   // The calling convention either uses 1-2 GPRs or 1 FPR.
4724   Address NumRegsAddr = Address::invalid();
4725   if (isInt || IsSoftFloatABI) {
4726     NumRegsAddr = Builder.CreateStructGEP(VAList, 0, "gpr");
4727   } else {
4728     NumRegsAddr = Builder.CreateStructGEP(VAList, 1, "fpr");
4729   }
4730 
4731   llvm::Value *NumRegs = Builder.CreateLoad(NumRegsAddr, "numUsedRegs");
4732 
4733   // "Align" the register count when TY is i64.
4734   if (isI64 || (isF64 && IsSoftFloatABI)) {
4735     NumRegs = Builder.CreateAdd(NumRegs, Builder.getInt8(1));
4736     NumRegs = Builder.CreateAnd(NumRegs, Builder.getInt8((uint8_t) ~1U));
4737   }
4738 
4739   llvm::Value *CC =
4740       Builder.CreateICmpULT(NumRegs, Builder.getInt8(OverflowLimit), "cond");
4741 
4742   llvm::BasicBlock *UsingRegs = CGF.createBasicBlock("using_regs");
4743   llvm::BasicBlock *UsingOverflow = CGF.createBasicBlock("using_overflow");
4744   llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
4745 
4746   Builder.CreateCondBr(CC, UsingRegs, UsingOverflow);
4747 
4748   llvm::Type *DirectTy = CGF.ConvertType(Ty);
4749   if (isIndirect) DirectTy = DirectTy->getPointerTo(0);
4750 
4751   // Case 1: consume registers.
4752   Address RegAddr = Address::invalid();
4753   {
4754     CGF.EmitBlock(UsingRegs);
4755 
4756     Address RegSaveAreaPtr = Builder.CreateStructGEP(VAList, 4);
4757     RegAddr = Address(Builder.CreateLoad(RegSaveAreaPtr),
4758                       CharUnits::fromQuantity(8));
4759     assert(RegAddr.getElementType() == CGF.Int8Ty);
4760 
4761     // Floating-point registers start after the general-purpose registers.
4762     if (!(isInt || IsSoftFloatABI)) {
4763       RegAddr = Builder.CreateConstInBoundsByteGEP(RegAddr,
4764                                                    CharUnits::fromQuantity(32));
4765     }
4766 
4767     // Get the address of the saved value by scaling the number of
4768     // registers we've used by the number of
4769     CharUnits RegSize = CharUnits::fromQuantity((isInt || IsSoftFloatABI) ? 4 : 8);
4770     llvm::Value *RegOffset =
4771       Builder.CreateMul(NumRegs, Builder.getInt8(RegSize.getQuantity()));
4772     RegAddr = Address(Builder.CreateInBoundsGEP(CGF.Int8Ty,
4773                                             RegAddr.getPointer(), RegOffset),
4774                       RegAddr.getAlignment().alignmentOfArrayElement(RegSize));
4775     RegAddr = Builder.CreateElementBitCast(RegAddr, DirectTy);
4776 
4777     // Increase the used-register count.
4778     NumRegs =
4779       Builder.CreateAdd(NumRegs,
4780                         Builder.getInt8((isI64 || (isF64 && IsSoftFloatABI)) ? 2 : 1));
4781     Builder.CreateStore(NumRegs, NumRegsAddr);
4782 
4783     CGF.EmitBranch(Cont);
4784   }
4785 
4786   // Case 2: consume space in the overflow area.
4787   Address MemAddr = Address::invalid();
4788   {
4789     CGF.EmitBlock(UsingOverflow);
4790 
4791     Builder.CreateStore(Builder.getInt8(OverflowLimit), NumRegsAddr);
4792 
4793     // Everything in the overflow area is rounded up to a size of at least 4.
4794     CharUnits OverflowAreaAlign = CharUnits::fromQuantity(4);
4795 
4796     CharUnits Size;
4797     if (!isIndirect) {
4798       auto TypeInfo = CGF.getContext().getTypeInfoInChars(Ty);
4799       Size = TypeInfo.first.alignTo(OverflowAreaAlign);
4800     } else {
4801       Size = CGF.getPointerSize();
4802     }
4803 
4804     Address OverflowAreaAddr = Builder.CreateStructGEP(VAList, 3);
4805     Address OverflowArea(Builder.CreateLoad(OverflowAreaAddr, "argp.cur"),
4806                          OverflowAreaAlign);
4807     // Round up address of argument to alignment
4808     CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
4809     if (Align > OverflowAreaAlign) {
4810       llvm::Value *Ptr = OverflowArea.getPointer();
4811       OverflowArea = Address(emitRoundPointerUpToAlignment(CGF, Ptr, Align),
4812                                                            Align);
4813     }
4814 
4815     MemAddr = Builder.CreateElementBitCast(OverflowArea, DirectTy);
4816 
4817     // Increase the overflow area.
4818     OverflowArea = Builder.CreateConstInBoundsByteGEP(OverflowArea, Size);
4819     Builder.CreateStore(OverflowArea.getPointer(), OverflowAreaAddr);
4820     CGF.EmitBranch(Cont);
4821   }
4822 
4823   CGF.EmitBlock(Cont);
4824 
4825   // Merge the cases with a phi.
4826   Address Result = emitMergePHI(CGF, RegAddr, UsingRegs, MemAddr, UsingOverflow,
4827                                 "vaarg.addr");
4828 
4829   // Load the pointer if the argument was passed indirectly.
4830   if (isIndirect) {
4831     Result = Address(Builder.CreateLoad(Result, "aggr"),
4832                      getContext().getTypeAlignInChars(Ty));
4833   }
4834 
4835   return Result;
4836 }
4837 
4838 bool PPC32TargetCodeGenInfo::isStructReturnInRegABI(
4839     const llvm::Triple &Triple, const CodeGenOptions &Opts) {
4840   assert(Triple.getArch() == llvm::Triple::ppc);
4841 
4842   switch (Opts.getStructReturnConvention()) {
4843   case CodeGenOptions::SRCK_Default:
4844     break;
4845   case CodeGenOptions::SRCK_OnStack: // -maix-struct-return
4846     return false;
4847   case CodeGenOptions::SRCK_InRegs: // -msvr4-struct-return
4848     return true;
4849   }
4850 
4851   if (Triple.isOSBinFormatELF() && !Triple.isOSLinux())
4852     return true;
4853 
4854   return false;
4855 }
4856 
4857 bool
4858 PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4859                                                 llvm::Value *Address) const {
4860   return PPC_initDwarfEHRegSizeTable(CGF, Address, /*Is64Bit*/ false,
4861                                      /*IsAIX*/ false);
4862 }
4863 
4864 // PowerPC-64
4865 
4866 namespace {
4867 /// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
4868 class PPC64_SVR4_ABIInfo : public SwiftABIInfo {
4869 public:
4870   enum ABIKind {
4871     ELFv1 = 0,
4872     ELFv2
4873   };
4874 
4875 private:
4876   static const unsigned GPRBits = 64;
4877   ABIKind Kind;
4878   bool HasQPX;
4879   bool IsSoftFloatABI;
4880 
4881   // A vector of float or double will be promoted to <4 x f32> or <4 x f64> and
4882   // will be passed in a QPX register.
4883   bool IsQPXVectorTy(const Type *Ty) const {
4884     if (!HasQPX)
4885       return false;
4886 
4887     if (const VectorType *VT = Ty->getAs<VectorType>()) {
4888       unsigned NumElements = VT->getNumElements();
4889       if (NumElements == 1)
4890         return false;
4891 
4892       if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double)) {
4893         if (getContext().getTypeSize(Ty) <= 256)
4894           return true;
4895       } else if (VT->getElementType()->
4896                    isSpecificBuiltinType(BuiltinType::Float)) {
4897         if (getContext().getTypeSize(Ty) <= 128)
4898           return true;
4899       }
4900     }
4901 
4902     return false;
4903   }
4904 
4905   bool IsQPXVectorTy(QualType Ty) const {
4906     return IsQPXVectorTy(Ty.getTypePtr());
4907   }
4908 
4909 public:
4910   PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind, bool HasQPX,
4911                      bool SoftFloatABI)
4912       : SwiftABIInfo(CGT), Kind(Kind), HasQPX(HasQPX),
4913         IsSoftFloatABI(SoftFloatABI) {}
4914 
4915   bool isPromotableTypeForABI(QualType Ty) const;
4916   CharUnits getParamTypeAlignment(QualType Ty) const;
4917 
4918   ABIArgInfo classifyReturnType(QualType RetTy) const;
4919   ABIArgInfo classifyArgumentType(QualType Ty) const;
4920 
4921   bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4922   bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4923                                          uint64_t Members) const override;
4924 
4925   // TODO: We can add more logic to computeInfo to improve performance.
4926   // Example: For aggregate arguments that fit in a register, we could
4927   // use getDirectInReg (as is done below for structs containing a single
4928   // floating-point value) to avoid pushing them to memory on function
4929   // entry.  This would require changing the logic in PPCISelLowering
4930   // when lowering the parameters in the caller and args in the callee.
4931   void computeInfo(CGFunctionInfo &FI) const override {
4932     if (!getCXXABI().classifyReturnType(FI))
4933       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
4934     for (auto &I : FI.arguments()) {
4935       // We rely on the default argument classification for the most part.
4936       // One exception:  An aggregate containing a single floating-point
4937       // or vector item must be passed in a register if one is available.
4938       const Type *T = isSingleElementStruct(I.type, getContext());
4939       if (T) {
4940         const BuiltinType *BT = T->getAs<BuiltinType>();
4941         if (IsQPXVectorTy(T) ||
4942             (T->isVectorType() && getContext().getTypeSize(T) == 128) ||
4943             (BT && BT->isFloatingPoint())) {
4944           QualType QT(T, 0);
4945           I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
4946           continue;
4947         }
4948       }
4949       I.info = classifyArgumentType(I.type);
4950     }
4951   }
4952 
4953   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4954                     QualType Ty) const override;
4955 
4956   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
4957                                     bool asReturnValue) const override {
4958     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
4959   }
4960 
4961   bool isSwiftErrorInRegister() const override {
4962     return false;
4963   }
4964 };
4965 
4966 class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
4967 
4968 public:
4969   PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT,
4970                                PPC64_SVR4_ABIInfo::ABIKind Kind, bool HasQPX,
4971                                bool SoftFloatABI)
4972       : TargetCodeGenInfo(std::make_unique<PPC64_SVR4_ABIInfo>(
4973             CGT, Kind, HasQPX, SoftFloatABI)) {}
4974 
4975   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4976     // This is recovered from gcc output.
4977     return 1; // r1 is the dedicated stack pointer
4978   }
4979 
4980   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4981                                llvm::Value *Address) const override;
4982 };
4983 
4984 class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
4985 public:
4986   PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
4987 
4988   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4989     // This is recovered from gcc output.
4990     return 1; // r1 is the dedicated stack pointer
4991   }
4992 
4993   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4994                                llvm::Value *Address) const override;
4995 };
4996 
4997 }
4998 
4999 // Return true if the ABI requires Ty to be passed sign- or zero-
5000 // extended to 64 bits.
5001 bool
5002 PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
5003   // Treat an enum type as its underlying type.
5004   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5005     Ty = EnumTy->getDecl()->getIntegerType();
5006 
5007   // Promotable integer types are required to be promoted by the ABI.
5008   if (isPromotableIntegerTypeForABI(Ty))
5009     return true;
5010 
5011   // In addition to the usual promotable integer types, we also need to
5012   // extend all 32-bit types, since the ABI requires promotion to 64 bits.
5013   if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
5014     switch (BT->getKind()) {
5015     case BuiltinType::Int:
5016     case BuiltinType::UInt:
5017       return true;
5018     default:
5019       break;
5020     }
5021 
5022   if (const auto *EIT = Ty->getAs<ExtIntType>())
5023     if (EIT->getNumBits() < 64)
5024       return true;
5025 
5026   return false;
5027 }
5028 
5029 /// isAlignedParamType - Determine whether a type requires 16-byte or
5030 /// higher alignment in the parameter area.  Always returns at least 8.
5031 CharUnits PPC64_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const {
5032   // Complex types are passed just like their elements.
5033   if (const ComplexType *CTy = Ty->getAs<ComplexType>())
5034     Ty = CTy->getElementType();
5035 
5036   // Only vector types of size 16 bytes need alignment (larger types are
5037   // passed via reference, smaller types are not aligned).
5038   if (IsQPXVectorTy(Ty)) {
5039     if (getContext().getTypeSize(Ty) > 128)
5040       return CharUnits::fromQuantity(32);
5041 
5042     return CharUnits::fromQuantity(16);
5043   } else if (Ty->isVectorType()) {
5044     return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16 : 8);
5045   }
5046 
5047   // For single-element float/vector structs, we consider the whole type
5048   // to have the same alignment requirements as its single element.
5049   const Type *AlignAsType = nullptr;
5050   const Type *EltType = isSingleElementStruct(Ty, getContext());
5051   if (EltType) {
5052     const BuiltinType *BT = EltType->getAs<BuiltinType>();
5053     if (IsQPXVectorTy(EltType) || (EltType->isVectorType() &&
5054          getContext().getTypeSize(EltType) == 128) ||
5055         (BT && BT->isFloatingPoint()))
5056       AlignAsType = EltType;
5057   }
5058 
5059   // Likewise for ELFv2 homogeneous aggregates.
5060   const Type *Base = nullptr;
5061   uint64_t Members = 0;
5062   if (!AlignAsType && Kind == ELFv2 &&
5063       isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members))
5064     AlignAsType = Base;
5065 
5066   // With special case aggregates, only vector base types need alignment.
5067   if (AlignAsType && IsQPXVectorTy(AlignAsType)) {
5068     if (getContext().getTypeSize(AlignAsType) > 128)
5069       return CharUnits::fromQuantity(32);
5070 
5071     return CharUnits::fromQuantity(16);
5072   } else if (AlignAsType) {
5073     return CharUnits::fromQuantity(AlignAsType->isVectorType() ? 16 : 8);
5074   }
5075 
5076   // Otherwise, we only need alignment for any aggregate type that
5077   // has an alignment requirement of >= 16 bytes.
5078   if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128) {
5079     if (HasQPX && getContext().getTypeAlign(Ty) >= 256)
5080       return CharUnits::fromQuantity(32);
5081     return CharUnits::fromQuantity(16);
5082   }
5083 
5084   return CharUnits::fromQuantity(8);
5085 }
5086 
5087 /// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous
5088 /// aggregate.  Base is set to the base element type, and Members is set
5089 /// to the number of base elements.
5090 bool ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base,
5091                                      uint64_t &Members) const {
5092   if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
5093     uint64_t NElements = AT->getSize().getZExtValue();
5094     if (NElements == 0)
5095       return false;
5096     if (!isHomogeneousAggregate(AT->getElementType(), Base, Members))
5097       return false;
5098     Members *= NElements;
5099   } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
5100     const RecordDecl *RD = RT->getDecl();
5101     if (RD->hasFlexibleArrayMember())
5102       return false;
5103 
5104     Members = 0;
5105 
5106     // If this is a C++ record, check the bases first.
5107     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
5108       for (const auto &I : CXXRD->bases()) {
5109         // Ignore empty records.
5110         if (isEmptyRecord(getContext(), I.getType(), true))
5111           continue;
5112 
5113         uint64_t FldMembers;
5114         if (!isHomogeneousAggregate(I.getType(), Base, FldMembers))
5115           return false;
5116 
5117         Members += FldMembers;
5118       }
5119     }
5120 
5121     for (const auto *FD : RD->fields()) {
5122       // Ignore (non-zero arrays of) empty records.
5123       QualType FT = FD->getType();
5124       while (const ConstantArrayType *AT =
5125              getContext().getAsConstantArrayType(FT)) {
5126         if (AT->getSize().getZExtValue() == 0)
5127           return false;
5128         FT = AT->getElementType();
5129       }
5130       if (isEmptyRecord(getContext(), FT, true))
5131         continue;
5132 
5133       // For compatibility with GCC, ignore empty bitfields in C++ mode.
5134       if (getContext().getLangOpts().CPlusPlus &&
5135           FD->isZeroLengthBitField(getContext()))
5136         continue;
5137 
5138       uint64_t FldMembers;
5139       if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers))
5140         return false;
5141 
5142       Members = (RD->isUnion() ?
5143                  std::max(Members, FldMembers) : Members + FldMembers);
5144     }
5145 
5146     if (!Base)
5147       return false;
5148 
5149     // Ensure there is no padding.
5150     if (getContext().getTypeSize(Base) * Members !=
5151         getContext().getTypeSize(Ty))
5152       return false;
5153   } else {
5154     Members = 1;
5155     if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
5156       Members = 2;
5157       Ty = CT->getElementType();
5158     }
5159 
5160     // Most ABIs only support float, double, and some vector type widths.
5161     if (!isHomogeneousAggregateBaseType(Ty))
5162       return false;
5163 
5164     // The base type must be the same for all members.  Types that
5165     // agree in both total size and mode (float vs. vector) are
5166     // treated as being equivalent here.
5167     const Type *TyPtr = Ty.getTypePtr();
5168     if (!Base) {
5169       Base = TyPtr;
5170       // If it's a non-power-of-2 vector, its size is already a power-of-2,
5171       // so make sure to widen it explicitly.
5172       if (const VectorType *VT = Base->getAs<VectorType>()) {
5173         QualType EltTy = VT->getElementType();
5174         unsigned NumElements =
5175             getContext().getTypeSize(VT) / getContext().getTypeSize(EltTy);
5176         Base = getContext()
5177                    .getVectorType(EltTy, NumElements, VT->getVectorKind())
5178                    .getTypePtr();
5179       }
5180     }
5181 
5182     if (Base->isVectorType() != TyPtr->isVectorType() ||
5183         getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr))
5184       return false;
5185   }
5186   return Members > 0 && isHomogeneousAggregateSmallEnough(Base, Members);
5187 }
5188 
5189 bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
5190   // Homogeneous aggregates for ELFv2 must have base types of float,
5191   // double, long double, or 128-bit vectors.
5192   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
5193     if (BT->getKind() == BuiltinType::Float ||
5194         BT->getKind() == BuiltinType::Double ||
5195         BT->getKind() == BuiltinType::LongDouble ||
5196         (getContext().getTargetInfo().hasFloat128Type() &&
5197           (BT->getKind() == BuiltinType::Float128))) {
5198       if (IsSoftFloatABI)
5199         return false;
5200       return true;
5201     }
5202   }
5203   if (const VectorType *VT = Ty->getAs<VectorType>()) {
5204     if (getContext().getTypeSize(VT) == 128 || IsQPXVectorTy(Ty))
5205       return true;
5206   }
5207   return false;
5208 }
5209 
5210 bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateSmallEnough(
5211     const Type *Base, uint64_t Members) const {
5212   // Vector and fp128 types require one register, other floating point types
5213   // require one or two registers depending on their size.
5214   uint32_t NumRegs =
5215       ((getContext().getTargetInfo().hasFloat128Type() &&
5216           Base->isFloat128Type()) ||
5217         Base->isVectorType()) ? 1
5218                               : (getContext().getTypeSize(Base) + 63) / 64;
5219 
5220   // Homogeneous Aggregates may occupy at most 8 registers.
5221   return Members * NumRegs <= 8;
5222 }
5223 
5224 ABIArgInfo
5225 PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
5226   Ty = useFirstFieldIfTransparentUnion(Ty);
5227 
5228   if (Ty->isAnyComplexType())
5229     return ABIArgInfo::getDirect();
5230 
5231   // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes)
5232   // or via reference (larger than 16 bytes).
5233   if (Ty->isVectorType() && !IsQPXVectorTy(Ty)) {
5234     uint64_t Size = getContext().getTypeSize(Ty);
5235     if (Size > 128)
5236       return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
5237     else if (Size < 128) {
5238       llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
5239       return ABIArgInfo::getDirect(CoerceTy);
5240     }
5241   }
5242 
5243   if (const auto *EIT = Ty->getAs<ExtIntType>())
5244     if (EIT->getNumBits() > 128)
5245       return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
5246 
5247   if (isAggregateTypeForABI(Ty)) {
5248     if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
5249       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
5250 
5251     uint64_t ABIAlign = getParamTypeAlignment(Ty).getQuantity();
5252     uint64_t TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity();
5253 
5254     // ELFv2 homogeneous aggregates are passed as array types.
5255     const Type *Base = nullptr;
5256     uint64_t Members = 0;
5257     if (Kind == ELFv2 &&
5258         isHomogeneousAggregate(Ty, Base, Members)) {
5259       llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
5260       llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
5261       return ABIArgInfo::getDirect(CoerceTy);
5262     }
5263 
5264     // If an aggregate may end up fully in registers, we do not
5265     // use the ByVal method, but pass the aggregate as array.
5266     // This is usually beneficial since we avoid forcing the
5267     // back-end to store the argument to memory.
5268     uint64_t Bits = getContext().getTypeSize(Ty);
5269     if (Bits > 0 && Bits <= 8 * GPRBits) {
5270       llvm::Type *CoerceTy;
5271 
5272       // Types up to 8 bytes are passed as integer type (which will be
5273       // properly aligned in the argument save area doubleword).
5274       if (Bits <= GPRBits)
5275         CoerceTy =
5276             llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
5277       // Larger types are passed as arrays, with the base type selected
5278       // according to the required alignment in the save area.
5279       else {
5280         uint64_t RegBits = ABIAlign * 8;
5281         uint64_t NumRegs = llvm::alignTo(Bits, RegBits) / RegBits;
5282         llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits);
5283         CoerceTy = llvm::ArrayType::get(RegTy, NumRegs);
5284       }
5285 
5286       return ABIArgInfo::getDirect(CoerceTy);
5287     }
5288 
5289     // All other aggregates are passed ByVal.
5290     return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
5291                                    /*ByVal=*/true,
5292                                    /*Realign=*/TyAlign > ABIAlign);
5293   }
5294 
5295   return (isPromotableTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
5296                                      : ABIArgInfo::getDirect());
5297 }
5298 
5299 ABIArgInfo
5300 PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
5301   if (RetTy->isVoidType())
5302     return ABIArgInfo::getIgnore();
5303 
5304   if (RetTy->isAnyComplexType())
5305     return ABIArgInfo::getDirect();
5306 
5307   // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes)
5308   // or via reference (larger than 16 bytes).
5309   if (RetTy->isVectorType() && !IsQPXVectorTy(RetTy)) {
5310     uint64_t Size = getContext().getTypeSize(RetTy);
5311     if (Size > 128)
5312       return getNaturalAlignIndirect(RetTy);
5313     else if (Size < 128) {
5314       llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
5315       return ABIArgInfo::getDirect(CoerceTy);
5316     }
5317   }
5318 
5319   if (const auto *EIT = RetTy->getAs<ExtIntType>())
5320     if (EIT->getNumBits() > 128)
5321       return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
5322 
5323   if (isAggregateTypeForABI(RetTy)) {
5324     // ELFv2 homogeneous aggregates are returned as array types.
5325     const Type *Base = nullptr;
5326     uint64_t Members = 0;
5327     if (Kind == ELFv2 &&
5328         isHomogeneousAggregate(RetTy, Base, Members)) {
5329       llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
5330       llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
5331       return ABIArgInfo::getDirect(CoerceTy);
5332     }
5333 
5334     // ELFv2 small aggregates are returned in up to two registers.
5335     uint64_t Bits = getContext().getTypeSize(RetTy);
5336     if (Kind == ELFv2 && Bits <= 2 * GPRBits) {
5337       if (Bits == 0)
5338         return ABIArgInfo::getIgnore();
5339 
5340       llvm::Type *CoerceTy;
5341       if (Bits > GPRBits) {
5342         CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits);
5343         CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy);
5344       } else
5345         CoerceTy =
5346             llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
5347       return ABIArgInfo::getDirect(CoerceTy);
5348     }
5349 
5350     // All other aggregates are returned indirectly.
5351     return getNaturalAlignIndirect(RetTy);
5352   }
5353 
5354   return (isPromotableTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
5355                                         : ABIArgInfo::getDirect());
5356 }
5357 
5358 // Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
5359 Address PPC64_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5360                                       QualType Ty) const {
5361   auto TypeInfo = getContext().getTypeInfoInChars(Ty);
5362   TypeInfo.second = getParamTypeAlignment(Ty);
5363 
5364   CharUnits SlotSize = CharUnits::fromQuantity(8);
5365 
5366   // If we have a complex type and the base type is smaller than 8 bytes,
5367   // the ABI calls for the real and imaginary parts to be right-adjusted
5368   // in separate doublewords.  However, Clang expects us to produce a
5369   // pointer to a structure with the two parts packed tightly.  So generate
5370   // loads of the real and imaginary parts relative to the va_list pointer,
5371   // and store them to a temporary structure.
5372   if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
5373     CharUnits EltSize = TypeInfo.first / 2;
5374     if (EltSize < SlotSize) {
5375       Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, CGF.Int8Ty,
5376                                             SlotSize * 2, SlotSize,
5377                                             SlotSize, /*AllowHigher*/ true);
5378 
5379       Address RealAddr = Addr;
5380       Address ImagAddr = RealAddr;
5381       if (CGF.CGM.getDataLayout().isBigEndian()) {
5382         RealAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr,
5383                                                           SlotSize - EltSize);
5384         ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(ImagAddr,
5385                                                       2 * SlotSize - EltSize);
5386       } else {
5387         ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, SlotSize);
5388       }
5389 
5390       llvm::Type *EltTy = CGF.ConvertTypeForMem(CTy->getElementType());
5391       RealAddr = CGF.Builder.CreateElementBitCast(RealAddr, EltTy);
5392       ImagAddr = CGF.Builder.CreateElementBitCast(ImagAddr, EltTy);
5393       llvm::Value *Real = CGF.Builder.CreateLoad(RealAddr, ".vareal");
5394       llvm::Value *Imag = CGF.Builder.CreateLoad(ImagAddr, ".vaimag");
5395 
5396       Address Temp = CGF.CreateMemTemp(Ty, "vacplx");
5397       CGF.EmitStoreOfComplex({Real, Imag}, CGF.MakeAddrLValue(Temp, Ty),
5398                              /*init*/ true);
5399       return Temp;
5400     }
5401   }
5402 
5403   // Otherwise, just use the general rule.
5404   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
5405                           TypeInfo, SlotSize, /*AllowHigher*/ true);
5406 }
5407 
5408 bool
5409 PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
5410   CodeGen::CodeGenFunction &CGF,
5411   llvm::Value *Address) const {
5412   return PPC_initDwarfEHRegSizeTable(CGF, Address, /*Is64Bit*/ true,
5413                                      /*IsAIX*/ false);
5414 }
5415 
5416 bool
5417 PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
5418                                                 llvm::Value *Address) const {
5419   return PPC_initDwarfEHRegSizeTable(CGF, Address, /*Is64Bit*/ true,
5420                                      /*IsAIX*/ false);
5421 }
5422 
5423 //===----------------------------------------------------------------------===//
5424 // AArch64 ABI Implementation
5425 //===----------------------------------------------------------------------===//
5426 
5427 namespace {
5428 
5429 class AArch64ABIInfo : public SwiftABIInfo {
5430 public:
5431   enum ABIKind {
5432     AAPCS = 0,
5433     DarwinPCS,
5434     Win64
5435   };
5436 
5437 private:
5438   ABIKind Kind;
5439 
5440 public:
5441   AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind)
5442     : SwiftABIInfo(CGT), Kind(Kind) {}
5443 
5444 private:
5445   ABIKind getABIKind() const { return Kind; }
5446   bool isDarwinPCS() const { return Kind == DarwinPCS; }
5447 
5448   ABIArgInfo classifyReturnType(QualType RetTy, bool IsVariadic) const;
5449   ABIArgInfo classifyArgumentType(QualType RetTy) const;
5450   bool isHomogeneousAggregateBaseType(QualType Ty) const override;
5451   bool isHomogeneousAggregateSmallEnough(const Type *Ty,
5452                                          uint64_t Members) const override;
5453 
5454   bool isIllegalVectorType(QualType Ty) const;
5455 
5456   void computeInfo(CGFunctionInfo &FI) const override {
5457     if (!::classifyReturnType(getCXXABI(), FI, *this))
5458       FI.getReturnInfo() =
5459           classifyReturnType(FI.getReturnType(), FI.isVariadic());
5460 
5461     for (auto &it : FI.arguments())
5462       it.info = classifyArgumentType(it.type);
5463   }
5464 
5465   Address EmitDarwinVAArg(Address VAListAddr, QualType Ty,
5466                           CodeGenFunction &CGF) const;
5467 
5468   Address EmitAAPCSVAArg(Address VAListAddr, QualType Ty,
5469                          CodeGenFunction &CGF) const;
5470 
5471   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5472                     QualType Ty) const override {
5473     llvm::Type *BaseTy = CGF.ConvertType(Ty);
5474     if (isa<llvm::ScalableVectorType>(BaseTy))
5475       llvm::report_fatal_error("Passing SVE types to variadic functions is "
5476                                "currently not supported");
5477 
5478     return Kind == Win64 ? EmitMSVAArg(CGF, VAListAddr, Ty)
5479                          : isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF)
5480                                          : EmitAAPCSVAArg(VAListAddr, Ty, CGF);
5481   }
5482 
5483   Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
5484                       QualType Ty) const override;
5485 
5486   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
5487                                     bool asReturnValue) const override {
5488     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
5489   }
5490   bool isSwiftErrorInRegister() const override {
5491     return true;
5492   }
5493 
5494   bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy,
5495                                  unsigned elts) const override;
5496 
5497   bool allowBFloatArgsAndRet() const override {
5498     return getTarget().hasBFloat16Type();
5499   }
5500 };
5501 
5502 class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
5503 public:
5504   AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind)
5505       : TargetCodeGenInfo(std::make_unique<AArch64ABIInfo>(CGT, Kind)) {}
5506 
5507   StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
5508     return "mov\tfp, fp\t\t// marker for objc_retainAutoreleaseReturnValue";
5509   }
5510 
5511   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
5512     return 31;
5513   }
5514 
5515   bool doesReturnSlotInterfereWithArgs() const override { return false; }
5516 
5517   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5518                            CodeGen::CodeGenModule &CGM) const override {
5519     const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
5520     if (!FD)
5521       return;
5522 
5523     LangOptions::SignReturnAddressScopeKind Scope =
5524         CGM.getLangOpts().getSignReturnAddressScope();
5525     LangOptions::SignReturnAddressKeyKind Key =
5526         CGM.getLangOpts().getSignReturnAddressKey();
5527     bool BranchTargetEnforcement = CGM.getLangOpts().BranchTargetEnforcement;
5528     if (const auto *TA = FD->getAttr<TargetAttr>()) {
5529       ParsedTargetAttr Attr = TA->parse();
5530       if (!Attr.BranchProtection.empty()) {
5531         TargetInfo::BranchProtectionInfo BPI;
5532         StringRef Error;
5533         (void)CGM.getTarget().validateBranchProtection(Attr.BranchProtection,
5534                                                        BPI, Error);
5535         assert(Error.empty());
5536         Scope = BPI.SignReturnAddr;
5537         Key = BPI.SignKey;
5538         BranchTargetEnforcement = BPI.BranchTargetEnforcement;
5539       }
5540     }
5541 
5542     auto *Fn = cast<llvm::Function>(GV);
5543     if (Scope != LangOptions::SignReturnAddressScopeKind::None) {
5544       Fn->addFnAttr("sign-return-address",
5545                     Scope == LangOptions::SignReturnAddressScopeKind::All
5546                         ? "all"
5547                         : "non-leaf");
5548 
5549       Fn->addFnAttr("sign-return-address-key",
5550                     Key == LangOptions::SignReturnAddressKeyKind::AKey
5551                         ? "a_key"
5552                         : "b_key");
5553     }
5554 
5555     if (BranchTargetEnforcement)
5556       Fn->addFnAttr("branch-target-enforcement");
5557   }
5558 };
5559 
5560 class WindowsAArch64TargetCodeGenInfo : public AArch64TargetCodeGenInfo {
5561 public:
5562   WindowsAArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind K)
5563       : AArch64TargetCodeGenInfo(CGT, K) {}
5564 
5565   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5566                            CodeGen::CodeGenModule &CGM) const override;
5567 
5568   void getDependentLibraryOption(llvm::StringRef Lib,
5569                                  llvm::SmallString<24> &Opt) const override {
5570     Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib);
5571   }
5572 
5573   void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value,
5574                                llvm::SmallString<32> &Opt) const override {
5575     Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
5576   }
5577 };
5578 
5579 void WindowsAArch64TargetCodeGenInfo::setTargetAttributes(
5580     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
5581   AArch64TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
5582   if (GV->isDeclaration())
5583     return;
5584   addStackProbeTargetAttributes(D, GV, CGM);
5585 }
5586 }
5587 
5588 ABIArgInfo AArch64ABIInfo::classifyArgumentType(QualType Ty) const {
5589   Ty = useFirstFieldIfTransparentUnion(Ty);
5590 
5591   // Handle illegal vector types here.
5592   if (isIllegalVectorType(Ty)) {
5593     uint64_t Size = getContext().getTypeSize(Ty);
5594     // Android promotes <2 x i8> to i16, not i32
5595     if (isAndroid() && (Size <= 16)) {
5596       llvm::Type *ResType = llvm::Type::getInt16Ty(getVMContext());
5597       return ABIArgInfo::getDirect(ResType);
5598     }
5599     if (Size <= 32) {
5600       llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext());
5601       return ABIArgInfo::getDirect(ResType);
5602     }
5603     if (Size == 64) {
5604       auto *ResType =
5605           llvm::FixedVectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2);
5606       return ABIArgInfo::getDirect(ResType);
5607     }
5608     if (Size == 128) {
5609       auto *ResType =
5610           llvm::FixedVectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4);
5611       return ABIArgInfo::getDirect(ResType);
5612     }
5613     return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
5614   }
5615 
5616   if (!isAggregateTypeForABI(Ty)) {
5617     // Treat an enum type as its underlying type.
5618     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5619       Ty = EnumTy->getDecl()->getIntegerType();
5620 
5621     if (const auto *EIT = Ty->getAs<ExtIntType>())
5622       if (EIT->getNumBits() > 128)
5623         return getNaturalAlignIndirect(Ty);
5624 
5625     return (isPromotableIntegerTypeForABI(Ty) && isDarwinPCS()
5626                 ? ABIArgInfo::getExtend(Ty)
5627                 : ABIArgInfo::getDirect());
5628   }
5629 
5630   // Structures with either a non-trivial destructor or a non-trivial
5631   // copy constructor are always indirect.
5632   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
5633     return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA ==
5634                                      CGCXXABI::RAA_DirectInMemory);
5635   }
5636 
5637   // Empty records are always ignored on Darwin, but actually passed in C++ mode
5638   // elsewhere for GNU compatibility.
5639   uint64_t Size = getContext().getTypeSize(Ty);
5640   bool IsEmpty = isEmptyRecord(getContext(), Ty, true);
5641   if (IsEmpty || Size == 0) {
5642     if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS())
5643       return ABIArgInfo::getIgnore();
5644 
5645     // GNU C mode. The only argument that gets ignored is an empty one with size
5646     // 0.
5647     if (IsEmpty && Size == 0)
5648       return ABIArgInfo::getIgnore();
5649     return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
5650   }
5651 
5652   // Homogeneous Floating-point Aggregates (HFAs) need to be expanded.
5653   const Type *Base = nullptr;
5654   uint64_t Members = 0;
5655   if (isHomogeneousAggregate(Ty, Base, Members)) {
5656     return ABIArgInfo::getDirect(
5657         llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members));
5658   }
5659 
5660   // Aggregates <= 16 bytes are passed directly in registers or on the stack.
5661   if (Size <= 128) {
5662     // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
5663     // same size and alignment.
5664     if (getTarget().isRenderScriptTarget()) {
5665       return coerceToIntArray(Ty, getContext(), getVMContext());
5666     }
5667     unsigned Alignment;
5668     if (Kind == AArch64ABIInfo::AAPCS) {
5669       Alignment = getContext().getTypeUnadjustedAlign(Ty);
5670       Alignment = Alignment < 128 ? 64 : 128;
5671     } else {
5672       Alignment = std::max(getContext().getTypeAlign(Ty),
5673                            (unsigned)getTarget().getPointerWidth(0));
5674     }
5675     Size = llvm::alignTo(Size, Alignment);
5676 
5677     // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
5678     // For aggregates with 16-byte alignment, we use i128.
5679     llvm::Type *BaseTy = llvm::Type::getIntNTy(getVMContext(), Alignment);
5680     return ABIArgInfo::getDirect(
5681         Size == Alignment ? BaseTy
5682                           : llvm::ArrayType::get(BaseTy, Size / Alignment));
5683   }
5684 
5685   return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
5686 }
5687 
5688 ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy,
5689                                               bool IsVariadic) const {
5690   if (RetTy->isVoidType())
5691     return ABIArgInfo::getIgnore();
5692 
5693   // Large vector types should be returned via memory.
5694   if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
5695     return getNaturalAlignIndirect(RetTy);
5696 
5697   if (!isAggregateTypeForABI(RetTy)) {
5698     // Treat an enum type as its underlying type.
5699     if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5700       RetTy = EnumTy->getDecl()->getIntegerType();
5701 
5702     if (const auto *EIT = RetTy->getAs<ExtIntType>())
5703       if (EIT->getNumBits() > 128)
5704         return getNaturalAlignIndirect(RetTy);
5705 
5706     return (isPromotableIntegerTypeForABI(RetTy) && isDarwinPCS()
5707                 ? ABIArgInfo::getExtend(RetTy)
5708                 : ABIArgInfo::getDirect());
5709   }
5710 
5711   uint64_t Size = getContext().getTypeSize(RetTy);
5712   if (isEmptyRecord(getContext(), RetTy, true) || Size == 0)
5713     return ABIArgInfo::getIgnore();
5714 
5715   const Type *Base = nullptr;
5716   uint64_t Members = 0;
5717   if (isHomogeneousAggregate(RetTy, Base, Members) &&
5718       !(getTarget().getTriple().getArch() == llvm::Triple::aarch64_32 &&
5719         IsVariadic))
5720     // Homogeneous Floating-point Aggregates (HFAs) are returned directly.
5721     return ABIArgInfo::getDirect();
5722 
5723   // Aggregates <= 16 bytes are returned directly in registers or on the stack.
5724   if (Size <= 128) {
5725     // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
5726     // same size and alignment.
5727     if (getTarget().isRenderScriptTarget()) {
5728       return coerceToIntArray(RetTy, getContext(), getVMContext());
5729     }
5730     unsigned Alignment = getContext().getTypeAlign(RetTy);
5731     Size = llvm::alignTo(Size, 64); // round up to multiple of 8 bytes
5732 
5733     // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
5734     // For aggregates with 16-byte alignment, we use i128.
5735     if (Alignment < 128 && Size == 128) {
5736       llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
5737       return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
5738     }
5739     return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
5740   }
5741 
5742   return getNaturalAlignIndirect(RetTy);
5743 }
5744 
5745 /// isIllegalVectorType - check whether the vector type is legal for AArch64.
5746 bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const {
5747   if (const VectorType *VT = Ty->getAs<VectorType>()) {
5748     // Check whether VT is legal.
5749     unsigned NumElements = VT->getNumElements();
5750     uint64_t Size = getContext().getTypeSize(VT);
5751     // NumElements should be power of 2.
5752     if (!llvm::isPowerOf2_32(NumElements))
5753       return true;
5754 
5755     // arm64_32 has to be compatible with the ARM logic here, which allows huge
5756     // vectors for some reason.
5757     llvm::Triple Triple = getTarget().getTriple();
5758     if (Triple.getArch() == llvm::Triple::aarch64_32 &&
5759         Triple.isOSBinFormatMachO())
5760       return Size <= 32;
5761 
5762     return Size != 64 && (Size != 128 || NumElements == 1);
5763   }
5764   return false;
5765 }
5766 
5767 bool AArch64ABIInfo::isLegalVectorTypeForSwift(CharUnits totalSize,
5768                                                llvm::Type *eltTy,
5769                                                unsigned elts) const {
5770   if (!llvm::isPowerOf2_32(elts))
5771     return false;
5772   if (totalSize.getQuantity() != 8 &&
5773       (totalSize.getQuantity() != 16 || elts == 1))
5774     return false;
5775   return true;
5776 }
5777 
5778 bool AArch64ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
5779   // Homogeneous aggregates for AAPCS64 must have base types of a floating
5780   // point type or a short-vector type. This is the same as the 32-bit ABI,
5781   // but with the difference that any floating-point type is allowed,
5782   // including __fp16.
5783   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
5784     if (BT->isFloatingPoint())
5785       return true;
5786   } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
5787     unsigned VecSize = getContext().getTypeSize(VT);
5788     if (VecSize == 64 || VecSize == 128)
5789       return true;
5790   }
5791   return false;
5792 }
5793 
5794 bool AArch64ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
5795                                                        uint64_t Members) const {
5796   return Members <= 4;
5797 }
5798 
5799 Address AArch64ABIInfo::EmitAAPCSVAArg(Address VAListAddr,
5800                                             QualType Ty,
5801                                             CodeGenFunction &CGF) const {
5802   ABIArgInfo AI = classifyArgumentType(Ty);
5803   bool IsIndirect = AI.isIndirect();
5804 
5805   llvm::Type *BaseTy = CGF.ConvertType(Ty);
5806   if (IsIndirect)
5807     BaseTy = llvm::PointerType::getUnqual(BaseTy);
5808   else if (AI.getCoerceToType())
5809     BaseTy = AI.getCoerceToType();
5810 
5811   unsigned NumRegs = 1;
5812   if (llvm::ArrayType *ArrTy = dyn_cast<llvm::ArrayType>(BaseTy)) {
5813     BaseTy = ArrTy->getElementType();
5814     NumRegs = ArrTy->getNumElements();
5815   }
5816   bool IsFPR = BaseTy->isFloatingPointTy() || BaseTy->isVectorTy();
5817 
5818   // The AArch64 va_list type and handling is specified in the Procedure Call
5819   // Standard, section B.4:
5820   //
5821   // struct {
5822   //   void *__stack;
5823   //   void *__gr_top;
5824   //   void *__vr_top;
5825   //   int __gr_offs;
5826   //   int __vr_offs;
5827   // };
5828 
5829   llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
5830   llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
5831   llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
5832   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
5833 
5834   CharUnits TySize = getContext().getTypeSizeInChars(Ty);
5835   CharUnits TyAlign = getContext().getTypeUnadjustedAlignInChars(Ty);
5836 
5837   Address reg_offs_p = Address::invalid();
5838   llvm::Value *reg_offs = nullptr;
5839   int reg_top_index;
5840   int RegSize = IsIndirect ? 8 : TySize.getQuantity();
5841   if (!IsFPR) {
5842     // 3 is the field number of __gr_offs
5843     reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 3, "gr_offs_p");
5844     reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
5845     reg_top_index = 1; // field number for __gr_top
5846     RegSize = llvm::alignTo(RegSize, 8);
5847   } else {
5848     // 4 is the field number of __vr_offs.
5849     reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 4, "vr_offs_p");
5850     reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
5851     reg_top_index = 2; // field number for __vr_top
5852     RegSize = 16 * NumRegs;
5853   }
5854 
5855   //=======================================
5856   // Find out where argument was passed
5857   //=======================================
5858 
5859   // If reg_offs >= 0 we're already using the stack for this type of
5860   // argument. We don't want to keep updating reg_offs (in case it overflows,
5861   // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
5862   // whatever they get).
5863   llvm::Value *UsingStack = nullptr;
5864   UsingStack = CGF.Builder.CreateICmpSGE(
5865       reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0));
5866 
5867   CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
5868 
5869   // Otherwise, at least some kind of argument could go in these registers, the
5870   // question is whether this particular type is too big.
5871   CGF.EmitBlock(MaybeRegBlock);
5872 
5873   // Integer arguments may need to correct register alignment (for example a
5874   // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
5875   // align __gr_offs to calculate the potential address.
5876   if (!IsFPR && !IsIndirect && TyAlign.getQuantity() > 8) {
5877     int Align = TyAlign.getQuantity();
5878 
5879     reg_offs = CGF.Builder.CreateAdd(
5880         reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
5881         "align_regoffs");
5882     reg_offs = CGF.Builder.CreateAnd(
5883         reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align),
5884         "aligned_regoffs");
5885   }
5886 
5887   // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
5888   // The fact that this is done unconditionally reflects the fact that
5889   // allocating an argument to the stack also uses up all the remaining
5890   // registers of the appropriate kind.
5891   llvm::Value *NewOffset = nullptr;
5892   NewOffset = CGF.Builder.CreateAdd(
5893       reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs");
5894   CGF.Builder.CreateStore(NewOffset, reg_offs_p);
5895 
5896   // Now we're in a position to decide whether this argument really was in
5897   // registers or not.
5898   llvm::Value *InRegs = nullptr;
5899   InRegs = CGF.Builder.CreateICmpSLE(
5900       NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg");
5901 
5902   CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
5903 
5904   //=======================================
5905   // Argument was in registers
5906   //=======================================
5907 
5908   // Now we emit the code for if the argument was originally passed in
5909   // registers. First start the appropriate block:
5910   CGF.EmitBlock(InRegBlock);
5911 
5912   llvm::Value *reg_top = nullptr;
5913   Address reg_top_p =
5914       CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index, "reg_top_p");
5915   reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
5916   Address BaseAddr(CGF.Builder.CreateInBoundsGEP(reg_top, reg_offs),
5917                    CharUnits::fromQuantity(IsFPR ? 16 : 8));
5918   Address RegAddr = Address::invalid();
5919   llvm::Type *MemTy = CGF.ConvertTypeForMem(Ty);
5920 
5921   if (IsIndirect) {
5922     // If it's been passed indirectly (actually a struct), whatever we find from
5923     // stored registers or on the stack will actually be a struct **.
5924     MemTy = llvm::PointerType::getUnqual(MemTy);
5925   }
5926 
5927   const Type *Base = nullptr;
5928   uint64_t NumMembers = 0;
5929   bool IsHFA = isHomogeneousAggregate(Ty, Base, NumMembers);
5930   if (IsHFA && NumMembers > 1) {
5931     // Homogeneous aggregates passed in registers will have their elements split
5932     // and stored 16-bytes apart regardless of size (they're notionally in qN,
5933     // qN+1, ...). We reload and store into a temporary local variable
5934     // contiguously.
5935     assert(!IsIndirect && "Homogeneous aggregates should be passed directly");
5936     auto BaseTyInfo = getContext().getTypeInfoInChars(QualType(Base, 0));
5937     llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
5938     llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
5939     Address Tmp = CGF.CreateTempAlloca(HFATy,
5940                                        std::max(TyAlign, BaseTyInfo.second));
5941 
5942     // On big-endian platforms, the value will be right-aligned in its slot.
5943     int Offset = 0;
5944     if (CGF.CGM.getDataLayout().isBigEndian() &&
5945         BaseTyInfo.first.getQuantity() < 16)
5946       Offset = 16 - BaseTyInfo.first.getQuantity();
5947 
5948     for (unsigned i = 0; i < NumMembers; ++i) {
5949       CharUnits BaseOffset = CharUnits::fromQuantity(16 * i + Offset);
5950       Address LoadAddr =
5951         CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, BaseOffset);
5952       LoadAddr = CGF.Builder.CreateElementBitCast(LoadAddr, BaseTy);
5953 
5954       Address StoreAddr = CGF.Builder.CreateConstArrayGEP(Tmp, i);
5955 
5956       llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
5957       CGF.Builder.CreateStore(Elem, StoreAddr);
5958     }
5959 
5960     RegAddr = CGF.Builder.CreateElementBitCast(Tmp, MemTy);
5961   } else {
5962     // Otherwise the object is contiguous in memory.
5963 
5964     // It might be right-aligned in its slot.
5965     CharUnits SlotSize = BaseAddr.getAlignment();
5966     if (CGF.CGM.getDataLayout().isBigEndian() && !IsIndirect &&
5967         (IsHFA || !isAggregateTypeForABI(Ty)) &&
5968         TySize < SlotSize) {
5969       CharUnits Offset = SlotSize - TySize;
5970       BaseAddr = CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, Offset);
5971     }
5972 
5973     RegAddr = CGF.Builder.CreateElementBitCast(BaseAddr, MemTy);
5974   }
5975 
5976   CGF.EmitBranch(ContBlock);
5977 
5978   //=======================================
5979   // Argument was on the stack
5980   //=======================================
5981   CGF.EmitBlock(OnStackBlock);
5982 
5983   Address stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "stack_p");
5984   llvm::Value *OnStackPtr = CGF.Builder.CreateLoad(stack_p, "stack");
5985 
5986   // Again, stack arguments may need realignment. In this case both integer and
5987   // floating-point ones might be affected.
5988   if (!IsIndirect && TyAlign.getQuantity() > 8) {
5989     int Align = TyAlign.getQuantity();
5990 
5991     OnStackPtr = CGF.Builder.CreatePtrToInt(OnStackPtr, CGF.Int64Ty);
5992 
5993     OnStackPtr = CGF.Builder.CreateAdd(
5994         OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
5995         "align_stack");
5996     OnStackPtr = CGF.Builder.CreateAnd(
5997         OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, -Align),
5998         "align_stack");
5999 
6000     OnStackPtr = CGF.Builder.CreateIntToPtr(OnStackPtr, CGF.Int8PtrTy);
6001   }
6002   Address OnStackAddr(OnStackPtr,
6003                       std::max(CharUnits::fromQuantity(8), TyAlign));
6004 
6005   // All stack slots are multiples of 8 bytes.
6006   CharUnits StackSlotSize = CharUnits::fromQuantity(8);
6007   CharUnits StackSize;
6008   if (IsIndirect)
6009     StackSize = StackSlotSize;
6010   else
6011     StackSize = TySize.alignTo(StackSlotSize);
6012 
6013   llvm::Value *StackSizeC = CGF.Builder.getSize(StackSize);
6014   llvm::Value *NewStack =
6015       CGF.Builder.CreateInBoundsGEP(OnStackPtr, StackSizeC, "new_stack");
6016 
6017   // Write the new value of __stack for the next call to va_arg
6018   CGF.Builder.CreateStore(NewStack, stack_p);
6019 
6020   if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) &&
6021       TySize < StackSlotSize) {
6022     CharUnits Offset = StackSlotSize - TySize;
6023     OnStackAddr = CGF.Builder.CreateConstInBoundsByteGEP(OnStackAddr, Offset);
6024   }
6025 
6026   OnStackAddr = CGF.Builder.CreateElementBitCast(OnStackAddr, MemTy);
6027 
6028   CGF.EmitBranch(ContBlock);
6029 
6030   //=======================================
6031   // Tidy up
6032   //=======================================
6033   CGF.EmitBlock(ContBlock);
6034 
6035   Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
6036                                  OnStackAddr, OnStackBlock, "vaargs.addr");
6037 
6038   if (IsIndirect)
6039     return Address(CGF.Builder.CreateLoad(ResAddr, "vaarg.addr"),
6040                    TyAlign);
6041 
6042   return ResAddr;
6043 }
6044 
6045 Address AArch64ABIInfo::EmitDarwinVAArg(Address VAListAddr, QualType Ty,
6046                                         CodeGenFunction &CGF) const {
6047   // The backend's lowering doesn't support va_arg for aggregates or
6048   // illegal vector types.  Lower VAArg here for these cases and use
6049   // the LLVM va_arg instruction for everything else.
6050   if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty))
6051     return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
6052 
6053   uint64_t PointerSize = getTarget().getPointerWidth(0) / 8;
6054   CharUnits SlotSize = CharUnits::fromQuantity(PointerSize);
6055 
6056   // Empty records are ignored for parameter passing purposes.
6057   if (isEmptyRecord(getContext(), Ty, true)) {
6058     Address Addr(CGF.Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
6059     Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
6060     return Addr;
6061   }
6062 
6063   // The size of the actual thing passed, which might end up just
6064   // being a pointer for indirect types.
6065   auto TyInfo = getContext().getTypeInfoInChars(Ty);
6066 
6067   // Arguments bigger than 16 bytes which aren't homogeneous
6068   // aggregates should be passed indirectly.
6069   bool IsIndirect = false;
6070   if (TyInfo.first.getQuantity() > 16) {
6071     const Type *Base = nullptr;
6072     uint64_t Members = 0;
6073     IsIndirect = !isHomogeneousAggregate(Ty, Base, Members);
6074   }
6075 
6076   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
6077                           TyInfo, SlotSize, /*AllowHigherAlign*/ true);
6078 }
6079 
6080 Address AArch64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
6081                                     QualType Ty) const {
6082   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
6083                           CGF.getContext().getTypeInfoInChars(Ty),
6084                           CharUnits::fromQuantity(8),
6085                           /*allowHigherAlign*/ false);
6086 }
6087 
6088 //===----------------------------------------------------------------------===//
6089 // ARM ABI Implementation
6090 //===----------------------------------------------------------------------===//
6091 
6092 namespace {
6093 
6094 class ARMABIInfo : public SwiftABIInfo {
6095 public:
6096   enum ABIKind {
6097     APCS = 0,
6098     AAPCS = 1,
6099     AAPCS_VFP = 2,
6100     AAPCS16_VFP = 3,
6101   };
6102 
6103 private:
6104   ABIKind Kind;
6105   bool IsFloatABISoftFP;
6106 
6107 public:
6108   ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind)
6109       : SwiftABIInfo(CGT), Kind(_Kind) {
6110     setCCs();
6111     IsFloatABISoftFP = CGT.getCodeGenOpts().FloatABI == "softfp" ||
6112         CGT.getCodeGenOpts().FloatABI == ""; // default
6113   }
6114 
6115   bool isEABI() const {
6116     switch (getTarget().getTriple().getEnvironment()) {
6117     case llvm::Triple::Android:
6118     case llvm::Triple::EABI:
6119     case llvm::Triple::EABIHF:
6120     case llvm::Triple::GNUEABI:
6121     case llvm::Triple::GNUEABIHF:
6122     case llvm::Triple::MuslEABI:
6123     case llvm::Triple::MuslEABIHF:
6124       return true;
6125     default:
6126       return false;
6127     }
6128   }
6129 
6130   bool isEABIHF() const {
6131     switch (getTarget().getTriple().getEnvironment()) {
6132     case llvm::Triple::EABIHF:
6133     case llvm::Triple::GNUEABIHF:
6134     case llvm::Triple::MuslEABIHF:
6135       return true;
6136     default:
6137       return false;
6138     }
6139   }
6140 
6141   ABIKind getABIKind() const { return Kind; }
6142 
6143   bool allowBFloatArgsAndRet() const override {
6144     return !IsFloatABISoftFP && getTarget().hasBFloat16Type();
6145   }
6146 
6147 private:
6148   ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic,
6149                                 unsigned functionCallConv) const;
6150   ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic,
6151                                   unsigned functionCallConv) const;
6152   ABIArgInfo classifyHomogeneousAggregate(QualType Ty, const Type *Base,
6153                                           uint64_t Members) const;
6154   ABIArgInfo coerceIllegalVector(QualType Ty) const;
6155   bool isIllegalVectorType(QualType Ty) const;
6156   bool containsAnyFP16Vectors(QualType Ty) const;
6157 
6158   bool isHomogeneousAggregateBaseType(QualType Ty) const override;
6159   bool isHomogeneousAggregateSmallEnough(const Type *Ty,
6160                                          uint64_t Members) const override;
6161 
6162   bool isEffectivelyAAPCS_VFP(unsigned callConvention, bool acceptHalf) const;
6163 
6164   void computeInfo(CGFunctionInfo &FI) const override;
6165 
6166   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6167                     QualType Ty) const override;
6168 
6169   llvm::CallingConv::ID getLLVMDefaultCC() const;
6170   llvm::CallingConv::ID getABIDefaultCC() const;
6171   void setCCs();
6172 
6173   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
6174                                     bool asReturnValue) const override {
6175     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
6176   }
6177   bool isSwiftErrorInRegister() const override {
6178     return true;
6179   }
6180   bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy,
6181                                  unsigned elts) const override;
6182 };
6183 
6184 class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
6185 public:
6186   ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
6187       : TargetCodeGenInfo(std::make_unique<ARMABIInfo>(CGT, K)) {}
6188 
6189   const ARMABIInfo &getABIInfo() const {
6190     return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
6191   }
6192 
6193   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
6194     return 13;
6195   }
6196 
6197   StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
6198     return "mov\tr7, r7\t\t// marker for objc_retainAutoreleaseReturnValue";
6199   }
6200 
6201   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
6202                                llvm::Value *Address) const override {
6203     llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
6204 
6205     // 0-15 are the 16 integer registers.
6206     AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
6207     return false;
6208   }
6209 
6210   unsigned getSizeOfUnwindException() const override {
6211     if (getABIInfo().isEABI()) return 88;
6212     return TargetCodeGenInfo::getSizeOfUnwindException();
6213   }
6214 
6215   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
6216                            CodeGen::CodeGenModule &CGM) const override {
6217     if (GV->isDeclaration())
6218       return;
6219     const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
6220     if (!FD)
6221       return;
6222 
6223     const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
6224     if (!Attr)
6225       return;
6226 
6227     const char *Kind;
6228     switch (Attr->getInterrupt()) {
6229     case ARMInterruptAttr::Generic: Kind = ""; break;
6230     case ARMInterruptAttr::IRQ:     Kind = "IRQ"; break;
6231     case ARMInterruptAttr::FIQ:     Kind = "FIQ"; break;
6232     case ARMInterruptAttr::SWI:     Kind = "SWI"; break;
6233     case ARMInterruptAttr::ABORT:   Kind = "ABORT"; break;
6234     case ARMInterruptAttr::UNDEF:   Kind = "UNDEF"; break;
6235     }
6236 
6237     llvm::Function *Fn = cast<llvm::Function>(GV);
6238 
6239     Fn->addFnAttr("interrupt", Kind);
6240 
6241     ARMABIInfo::ABIKind ABI = cast<ARMABIInfo>(getABIInfo()).getABIKind();
6242     if (ABI == ARMABIInfo::APCS)
6243       return;
6244 
6245     // AAPCS guarantees that sp will be 8-byte aligned on any public interface,
6246     // however this is not necessarily true on taking any interrupt. Instruct
6247     // the backend to perform a realignment as part of the function prologue.
6248     llvm::AttrBuilder B;
6249     B.addStackAlignmentAttr(8);
6250     Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
6251   }
6252 };
6253 
6254 class WindowsARMTargetCodeGenInfo : public ARMTargetCodeGenInfo {
6255 public:
6256   WindowsARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
6257       : ARMTargetCodeGenInfo(CGT, K) {}
6258 
6259   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
6260                            CodeGen::CodeGenModule &CGM) const override;
6261 
6262   void getDependentLibraryOption(llvm::StringRef Lib,
6263                                  llvm::SmallString<24> &Opt) const override {
6264     Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib);
6265   }
6266 
6267   void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value,
6268                                llvm::SmallString<32> &Opt) const override {
6269     Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
6270   }
6271 };
6272 
6273 void WindowsARMTargetCodeGenInfo::setTargetAttributes(
6274     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
6275   ARMTargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
6276   if (GV->isDeclaration())
6277     return;
6278   addStackProbeTargetAttributes(D, GV, CGM);
6279 }
6280 }
6281 
6282 void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
6283   if (!::classifyReturnType(getCXXABI(), FI, *this))
6284     FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), FI.isVariadic(),
6285                                             FI.getCallingConvention());
6286 
6287   for (auto &I : FI.arguments())
6288     I.info = classifyArgumentType(I.type, FI.isVariadic(),
6289                                   FI.getCallingConvention());
6290 
6291 
6292   // Always honor user-specified calling convention.
6293   if (FI.getCallingConvention() != llvm::CallingConv::C)
6294     return;
6295 
6296   llvm::CallingConv::ID cc = getRuntimeCC();
6297   if (cc != llvm::CallingConv::C)
6298     FI.setEffectiveCallingConvention(cc);
6299 }
6300 
6301 /// Return the default calling convention that LLVM will use.
6302 llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
6303   // The default calling convention that LLVM will infer.
6304   if (isEABIHF() || getTarget().getTriple().isWatchABI())
6305     return llvm::CallingConv::ARM_AAPCS_VFP;
6306   else if (isEABI())
6307     return llvm::CallingConv::ARM_AAPCS;
6308   else
6309     return llvm::CallingConv::ARM_APCS;
6310 }
6311 
6312 /// Return the calling convention that our ABI would like us to use
6313 /// as the C calling convention.
6314 llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
6315   switch (getABIKind()) {
6316   case APCS: return llvm::CallingConv::ARM_APCS;
6317   case AAPCS: return llvm::CallingConv::ARM_AAPCS;
6318   case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
6319   case AAPCS16_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
6320   }
6321   llvm_unreachable("bad ABI kind");
6322 }
6323 
6324 void ARMABIInfo::setCCs() {
6325   assert(getRuntimeCC() == llvm::CallingConv::C);
6326 
6327   // Don't muddy up the IR with a ton of explicit annotations if
6328   // they'd just match what LLVM will infer from the triple.
6329   llvm::CallingConv::ID abiCC = getABIDefaultCC();
6330   if (abiCC != getLLVMDefaultCC())
6331     RuntimeCC = abiCC;
6332 }
6333 
6334 ABIArgInfo ARMABIInfo::coerceIllegalVector(QualType Ty) const {
6335   uint64_t Size = getContext().getTypeSize(Ty);
6336   if (Size <= 32) {
6337     llvm::Type *ResType =
6338         llvm::Type::getInt32Ty(getVMContext());
6339     return ABIArgInfo::getDirect(ResType);
6340   }
6341   if (Size == 64 || Size == 128) {
6342     auto *ResType = llvm::FixedVectorType::get(
6343         llvm::Type::getInt32Ty(getVMContext()), Size / 32);
6344     return ABIArgInfo::getDirect(ResType);
6345   }
6346   return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
6347 }
6348 
6349 ABIArgInfo ARMABIInfo::classifyHomogeneousAggregate(QualType Ty,
6350                                                     const Type *Base,
6351                                                     uint64_t Members) const {
6352   assert(Base && "Base class should be set for homogeneous aggregate");
6353   // Base can be a floating-point or a vector.
6354   if (const VectorType *VT = Base->getAs<VectorType>()) {
6355     // FP16 vectors should be converted to integer vectors
6356     if (!getTarget().hasLegalHalfType() && containsAnyFP16Vectors(Ty)) {
6357       uint64_t Size = getContext().getTypeSize(VT);
6358       auto *NewVecTy = llvm::FixedVectorType::get(
6359           llvm::Type::getInt32Ty(getVMContext()), Size / 32);
6360       llvm::Type *Ty = llvm::ArrayType::get(NewVecTy, Members);
6361       return ABIArgInfo::getDirect(Ty, 0, nullptr, false);
6362     }
6363   }
6364   return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
6365 }
6366 
6367 ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty, bool isVariadic,
6368                                             unsigned functionCallConv) const {
6369   // 6.1.2.1 The following argument types are VFP CPRCs:
6370   //   A single-precision floating-point type (including promoted
6371   //   half-precision types); A double-precision floating-point type;
6372   //   A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
6373   //   with a Base Type of a single- or double-precision floating-point type,
6374   //   64-bit containerized vectors or 128-bit containerized vectors with one
6375   //   to four Elements.
6376   // Variadic functions should always marshal to the base standard.
6377   bool IsAAPCS_VFP =
6378       !isVariadic && isEffectivelyAAPCS_VFP(functionCallConv, /* AAPCS16 */ false);
6379 
6380   Ty = useFirstFieldIfTransparentUnion(Ty);
6381 
6382   // Handle illegal vector types here.
6383   if (isIllegalVectorType(Ty))
6384     return coerceIllegalVector(Ty);
6385 
6386   if (!isAggregateTypeForABI(Ty)) {
6387     // Treat an enum type as its underlying type.
6388     if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
6389       Ty = EnumTy->getDecl()->getIntegerType();
6390     }
6391 
6392     if (const auto *EIT = Ty->getAs<ExtIntType>())
6393       if (EIT->getNumBits() > 64)
6394         return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
6395 
6396     return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
6397                                               : ABIArgInfo::getDirect());
6398   }
6399 
6400   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
6401     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
6402   }
6403 
6404   // Ignore empty records.
6405   if (isEmptyRecord(getContext(), Ty, true))
6406     return ABIArgInfo::getIgnore();
6407 
6408   if (IsAAPCS_VFP) {
6409     // Homogeneous Aggregates need to be expanded when we can fit the aggregate
6410     // into VFP registers.
6411     const Type *Base = nullptr;
6412     uint64_t Members = 0;
6413     if (isHomogeneousAggregate(Ty, Base, Members))
6414       return classifyHomogeneousAggregate(Ty, Base, Members);
6415   } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
6416     // WatchOS does have homogeneous aggregates. Note that we intentionally use
6417     // this convention even for a variadic function: the backend will use GPRs
6418     // if needed.
6419     const Type *Base = nullptr;
6420     uint64_t Members = 0;
6421     if (isHomogeneousAggregate(Ty, Base, Members)) {
6422       assert(Base && Members <= 4 && "unexpected homogeneous aggregate");
6423       llvm::Type *Ty =
6424         llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members);
6425       return ABIArgInfo::getDirect(Ty, 0, nullptr, false);
6426     }
6427   }
6428 
6429   if (getABIKind() == ARMABIInfo::AAPCS16_VFP &&
6430       getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(16)) {
6431     // WatchOS is adopting the 64-bit AAPCS rule on composite types: if they're
6432     // bigger than 128-bits, they get placed in space allocated by the caller,
6433     // and a pointer is passed.
6434     return ABIArgInfo::getIndirect(
6435         CharUnits::fromQuantity(getContext().getTypeAlign(Ty) / 8), false);
6436   }
6437 
6438   // Support byval for ARM.
6439   // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
6440   // most 8-byte. We realign the indirect argument if type alignment is bigger
6441   // than ABI alignment.
6442   uint64_t ABIAlign = 4;
6443   uint64_t TyAlign;
6444   if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
6445       getABIKind() == ARMABIInfo::AAPCS) {
6446     TyAlign = getContext().getTypeUnadjustedAlignInChars(Ty).getQuantity();
6447     ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
6448   } else {
6449     TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity();
6450   }
6451   if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
6452     assert(getABIKind() != ARMABIInfo::AAPCS16_VFP && "unexpected byval");
6453     return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
6454                                    /*ByVal=*/true,
6455                                    /*Realign=*/TyAlign > ABIAlign);
6456   }
6457 
6458   // On RenderScript, coerce Aggregates <= 64 bytes to an integer array of
6459   // same size and alignment.
6460   if (getTarget().isRenderScriptTarget()) {
6461     return coerceToIntArray(Ty, getContext(), getVMContext());
6462   }
6463 
6464   // Otherwise, pass by coercing to a structure of the appropriate size.
6465   llvm::Type* ElemTy;
6466   unsigned SizeRegs;
6467   // FIXME: Try to match the types of the arguments more accurately where
6468   // we can.
6469   if (TyAlign <= 4) {
6470     ElemTy = llvm::Type::getInt32Ty(getVMContext());
6471     SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
6472   } else {
6473     ElemTy = llvm::Type::getInt64Ty(getVMContext());
6474     SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
6475   }
6476 
6477   return ABIArgInfo::getDirect(llvm::ArrayType::get(ElemTy, SizeRegs));
6478 }
6479 
6480 static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
6481                               llvm::LLVMContext &VMContext) {
6482   // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
6483   // is called integer-like if its size is less than or equal to one word, and
6484   // the offset of each of its addressable sub-fields is zero.
6485 
6486   uint64_t Size = Context.getTypeSize(Ty);
6487 
6488   // Check that the type fits in a word.
6489   if (Size > 32)
6490     return false;
6491 
6492   // FIXME: Handle vector types!
6493   if (Ty->isVectorType())
6494     return false;
6495 
6496   // Float types are never treated as "integer like".
6497   if (Ty->isRealFloatingType())
6498     return false;
6499 
6500   // If this is a builtin or pointer type then it is ok.
6501   if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
6502     return true;
6503 
6504   // Small complex integer types are "integer like".
6505   if (const ComplexType *CT = Ty->getAs<ComplexType>())
6506     return isIntegerLikeType(CT->getElementType(), Context, VMContext);
6507 
6508   // Single element and zero sized arrays should be allowed, by the definition
6509   // above, but they are not.
6510 
6511   // Otherwise, it must be a record type.
6512   const RecordType *RT = Ty->getAs<RecordType>();
6513   if (!RT) return false;
6514 
6515   // Ignore records with flexible arrays.
6516   const RecordDecl *RD = RT->getDecl();
6517   if (RD->hasFlexibleArrayMember())
6518     return false;
6519 
6520   // Check that all sub-fields are at offset 0, and are themselves "integer
6521   // like".
6522   const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
6523 
6524   bool HadField = false;
6525   unsigned idx = 0;
6526   for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
6527        i != e; ++i, ++idx) {
6528     const FieldDecl *FD = *i;
6529 
6530     // Bit-fields are not addressable, we only need to verify they are "integer
6531     // like". We still have to disallow a subsequent non-bitfield, for example:
6532     //   struct { int : 0; int x }
6533     // is non-integer like according to gcc.
6534     if (FD->isBitField()) {
6535       if (!RD->isUnion())
6536         HadField = true;
6537 
6538       if (!isIntegerLikeType(FD->getType(), Context, VMContext))
6539         return false;
6540 
6541       continue;
6542     }
6543 
6544     // Check if this field is at offset 0.
6545     if (Layout.getFieldOffset(idx) != 0)
6546       return false;
6547 
6548     if (!isIntegerLikeType(FD->getType(), Context, VMContext))
6549       return false;
6550 
6551     // Only allow at most one field in a structure. This doesn't match the
6552     // wording above, but follows gcc in situations with a field following an
6553     // empty structure.
6554     if (!RD->isUnion()) {
6555       if (HadField)
6556         return false;
6557 
6558       HadField = true;
6559     }
6560   }
6561 
6562   return true;
6563 }
6564 
6565 ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy, bool isVariadic,
6566                                           unsigned functionCallConv) const {
6567 
6568   // Variadic functions should always marshal to the base standard.
6569   bool IsAAPCS_VFP =
6570       !isVariadic && isEffectivelyAAPCS_VFP(functionCallConv, /* AAPCS16 */ true);
6571 
6572   if (RetTy->isVoidType())
6573     return ABIArgInfo::getIgnore();
6574 
6575   if (const VectorType *VT = RetTy->getAs<VectorType>()) {
6576     // Large vector types should be returned via memory.
6577     if (getContext().getTypeSize(RetTy) > 128)
6578       return getNaturalAlignIndirect(RetTy);
6579     // TODO: FP16/BF16 vectors should be converted to integer vectors
6580     // This check is similar  to isIllegalVectorType - refactor?
6581     if ((!getTarget().hasLegalHalfType() &&
6582         (VT->getElementType()->isFloat16Type() ||
6583          VT->getElementType()->isHalfType())) ||
6584         (IsFloatABISoftFP &&
6585          VT->getElementType()->isBFloat16Type()))
6586       return coerceIllegalVector(RetTy);
6587   }
6588 
6589   if (!isAggregateTypeForABI(RetTy)) {
6590     // Treat an enum type as its underlying type.
6591     if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6592       RetTy = EnumTy->getDecl()->getIntegerType();
6593 
6594     if (const auto *EIT = RetTy->getAs<ExtIntType>())
6595       if (EIT->getNumBits() > 64)
6596         return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
6597 
6598     return isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
6599                                                 : ABIArgInfo::getDirect();
6600   }
6601 
6602   // Are we following APCS?
6603   if (getABIKind() == APCS) {
6604     if (isEmptyRecord(getContext(), RetTy, false))
6605       return ABIArgInfo::getIgnore();
6606 
6607     // Complex types are all returned as packed integers.
6608     //
6609     // FIXME: Consider using 2 x vector types if the back end handles them
6610     // correctly.
6611     if (RetTy->isAnyComplexType())
6612       return ABIArgInfo::getDirect(llvm::IntegerType::get(
6613           getVMContext(), getContext().getTypeSize(RetTy)));
6614 
6615     // Integer like structures are returned in r0.
6616     if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
6617       // Return in the smallest viable integer type.
6618       uint64_t Size = getContext().getTypeSize(RetTy);
6619       if (Size <= 8)
6620         return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6621       if (Size <= 16)
6622         return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6623       return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6624     }
6625 
6626     // Otherwise return in memory.
6627     return getNaturalAlignIndirect(RetTy);
6628   }
6629 
6630   // Otherwise this is an AAPCS variant.
6631 
6632   if (isEmptyRecord(getContext(), RetTy, true))
6633     return ABIArgInfo::getIgnore();
6634 
6635   // Check for homogeneous aggregates with AAPCS-VFP.
6636   if (IsAAPCS_VFP) {
6637     const Type *Base = nullptr;
6638     uint64_t Members = 0;
6639     if (isHomogeneousAggregate(RetTy, Base, Members))
6640       return classifyHomogeneousAggregate(RetTy, Base, Members);
6641   }
6642 
6643   // Aggregates <= 4 bytes are returned in r0; other aggregates
6644   // are returned indirectly.
6645   uint64_t Size = getContext().getTypeSize(RetTy);
6646   if (Size <= 32) {
6647     // On RenderScript, coerce Aggregates <= 4 bytes to an integer array of
6648     // same size and alignment.
6649     if (getTarget().isRenderScriptTarget()) {
6650       return coerceToIntArray(RetTy, getContext(), getVMContext());
6651     }
6652     if (getDataLayout().isBigEndian())
6653       // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4)
6654       return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6655 
6656     // Return in the smallest viable integer type.
6657     if (Size <= 8)
6658       return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6659     if (Size <= 16)
6660       return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6661     return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6662   } else if (Size <= 128 && getABIKind() == AAPCS16_VFP) {
6663     llvm::Type *Int32Ty = llvm::Type::getInt32Ty(getVMContext());
6664     llvm::Type *CoerceTy =
6665         llvm::ArrayType::get(Int32Ty, llvm::alignTo(Size, 32) / 32);
6666     return ABIArgInfo::getDirect(CoerceTy);
6667   }
6668 
6669   return getNaturalAlignIndirect(RetTy);
6670 }
6671 
6672 /// isIllegalVector - check whether Ty is an illegal vector type.
6673 bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
6674   if (const VectorType *VT = Ty->getAs<VectorType> ()) {
6675     // On targets that don't support half, fp16 or bfloat, they are expanded
6676     // into float, and we don't want the ABI to depend on whether or not they
6677     // are supported in hardware. Thus return false to coerce vectors of these
6678     // types into integer vectors.
6679     // We do not depend on hasLegalHalfType for bfloat as it is a
6680     // separate IR type.
6681     if ((!getTarget().hasLegalHalfType() &&
6682         (VT->getElementType()->isFloat16Type() ||
6683          VT->getElementType()->isHalfType())) ||
6684         (IsFloatABISoftFP &&
6685          VT->getElementType()->isBFloat16Type()))
6686       return true;
6687     if (isAndroid()) {
6688       // Android shipped using Clang 3.1, which supported a slightly different
6689       // vector ABI. The primary differences were that 3-element vector types
6690       // were legal, and so were sub 32-bit vectors (i.e. <2 x i8>). This path
6691       // accepts that legacy behavior for Android only.
6692       // Check whether VT is legal.
6693       unsigned NumElements = VT->getNumElements();
6694       // NumElements should be power of 2 or equal to 3.
6695       if (!llvm::isPowerOf2_32(NumElements) && NumElements != 3)
6696         return true;
6697     } else {
6698       // Check whether VT is legal.
6699       unsigned NumElements = VT->getNumElements();
6700       uint64_t Size = getContext().getTypeSize(VT);
6701       // NumElements should be power of 2.
6702       if (!llvm::isPowerOf2_32(NumElements))
6703         return true;
6704       // Size should be greater than 32 bits.
6705       return Size <= 32;
6706     }
6707   }
6708   return false;
6709 }
6710 
6711 /// Return true if a type contains any 16-bit floating point vectors
6712 bool ARMABIInfo::containsAnyFP16Vectors(QualType Ty) const {
6713   if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
6714     uint64_t NElements = AT->getSize().getZExtValue();
6715     if (NElements == 0)
6716       return false;
6717     return containsAnyFP16Vectors(AT->getElementType());
6718   } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
6719     const RecordDecl *RD = RT->getDecl();
6720 
6721     // If this is a C++ record, check the bases first.
6722     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
6723       if (llvm::any_of(CXXRD->bases(), [this](const CXXBaseSpecifier &B) {
6724             return containsAnyFP16Vectors(B.getType());
6725           }))
6726         return true;
6727 
6728     if (llvm::any_of(RD->fields(), [this](FieldDecl *FD) {
6729           return FD && containsAnyFP16Vectors(FD->getType());
6730         }))
6731       return true;
6732 
6733     return false;
6734   } else {
6735     if (const VectorType *VT = Ty->getAs<VectorType>())
6736       return (VT->getElementType()->isFloat16Type() ||
6737               VT->getElementType()->isBFloat16Type() ||
6738               VT->getElementType()->isHalfType());
6739     return false;
6740   }
6741 }
6742 
6743 bool ARMABIInfo::isLegalVectorTypeForSwift(CharUnits vectorSize,
6744                                            llvm::Type *eltTy,
6745                                            unsigned numElts) const {
6746   if (!llvm::isPowerOf2_32(numElts))
6747     return false;
6748   unsigned size = getDataLayout().getTypeStoreSizeInBits(eltTy);
6749   if (size > 64)
6750     return false;
6751   if (vectorSize.getQuantity() != 8 &&
6752       (vectorSize.getQuantity() != 16 || numElts == 1))
6753     return false;
6754   return true;
6755 }
6756 
6757 bool ARMABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
6758   // Homogeneous aggregates for AAPCS-VFP must have base types of float,
6759   // double, or 64-bit or 128-bit vectors.
6760   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
6761     if (BT->getKind() == BuiltinType::Float ||
6762         BT->getKind() == BuiltinType::Double ||
6763         BT->getKind() == BuiltinType::LongDouble)
6764       return true;
6765   } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
6766     unsigned VecSize = getContext().getTypeSize(VT);
6767     if (VecSize == 64 || VecSize == 128)
6768       return true;
6769   }
6770   return false;
6771 }
6772 
6773 bool ARMABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
6774                                                    uint64_t Members) const {
6775   return Members <= 4;
6776 }
6777 
6778 bool ARMABIInfo::isEffectivelyAAPCS_VFP(unsigned callConvention,
6779                                         bool acceptHalf) const {
6780   // Give precedence to user-specified calling conventions.
6781   if (callConvention != llvm::CallingConv::C)
6782     return (callConvention == llvm::CallingConv::ARM_AAPCS_VFP);
6783   else
6784     return (getABIKind() == AAPCS_VFP) ||
6785            (acceptHalf && (getABIKind() == AAPCS16_VFP));
6786 }
6787 
6788 Address ARMABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6789                               QualType Ty) const {
6790   CharUnits SlotSize = CharUnits::fromQuantity(4);
6791 
6792   // Empty records are ignored for parameter passing purposes.
6793   if (isEmptyRecord(getContext(), Ty, true)) {
6794     Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize);
6795     Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
6796     return Addr;
6797   }
6798 
6799   CharUnits TySize = getContext().getTypeSizeInChars(Ty);
6800   CharUnits TyAlignForABI = getContext().getTypeUnadjustedAlignInChars(Ty);
6801 
6802   // Use indirect if size of the illegal vector is bigger than 16 bytes.
6803   bool IsIndirect = false;
6804   const Type *Base = nullptr;
6805   uint64_t Members = 0;
6806   if (TySize > CharUnits::fromQuantity(16) && isIllegalVectorType(Ty)) {
6807     IsIndirect = true;
6808 
6809   // ARMv7k passes structs bigger than 16 bytes indirectly, in space
6810   // allocated by the caller.
6811   } else if (TySize > CharUnits::fromQuantity(16) &&
6812              getABIKind() == ARMABIInfo::AAPCS16_VFP &&
6813              !isHomogeneousAggregate(Ty, Base, Members)) {
6814     IsIndirect = true;
6815 
6816   // Otherwise, bound the type's ABI alignment.
6817   // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
6818   // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
6819   // Our callers should be prepared to handle an under-aligned address.
6820   } else if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
6821              getABIKind() == ARMABIInfo::AAPCS) {
6822     TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
6823     TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(8));
6824   } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
6825     // ARMv7k allows type alignment up to 16 bytes.
6826     TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
6827     TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(16));
6828   } else {
6829     TyAlignForABI = CharUnits::fromQuantity(4);
6830   }
6831 
6832   std::pair<CharUnits, CharUnits> TyInfo = { TySize, TyAlignForABI };
6833   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TyInfo,
6834                           SlotSize, /*AllowHigherAlign*/ true);
6835 }
6836 
6837 //===----------------------------------------------------------------------===//
6838 // NVPTX ABI Implementation
6839 //===----------------------------------------------------------------------===//
6840 
6841 namespace {
6842 
6843 class NVPTXTargetCodeGenInfo;
6844 
6845 class NVPTXABIInfo : public ABIInfo {
6846   NVPTXTargetCodeGenInfo &CGInfo;
6847 
6848 public:
6849   NVPTXABIInfo(CodeGenTypes &CGT, NVPTXTargetCodeGenInfo &Info)
6850       : ABIInfo(CGT), CGInfo(Info) {}
6851 
6852   ABIArgInfo classifyReturnType(QualType RetTy) const;
6853   ABIArgInfo classifyArgumentType(QualType Ty) const;
6854 
6855   void computeInfo(CGFunctionInfo &FI) const override;
6856   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6857                     QualType Ty) const override;
6858   bool isUnsupportedType(QualType T) const;
6859   ABIArgInfo coerceToIntArrayWithLimit(QualType Ty, unsigned MaxSize) const;
6860 };
6861 
6862 class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
6863 public:
6864   NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
6865       : TargetCodeGenInfo(std::make_unique<NVPTXABIInfo>(CGT, *this)) {}
6866 
6867   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
6868                            CodeGen::CodeGenModule &M) const override;
6869   bool shouldEmitStaticExternCAliases() const override;
6870 
6871   llvm::Type *getCUDADeviceBuiltinSurfaceDeviceType() const override {
6872     // On the device side, surface reference is represented as an object handle
6873     // in 64-bit integer.
6874     return llvm::Type::getInt64Ty(getABIInfo().getVMContext());
6875   }
6876 
6877   llvm::Type *getCUDADeviceBuiltinTextureDeviceType() const override {
6878     // On the device side, texture reference is represented as an object handle
6879     // in 64-bit integer.
6880     return llvm::Type::getInt64Ty(getABIInfo().getVMContext());
6881   }
6882 
6883   bool emitCUDADeviceBuiltinSurfaceDeviceCopy(CodeGenFunction &CGF, LValue Dst,
6884                                               LValue Src) const override {
6885     emitBuiltinSurfTexDeviceCopy(CGF, Dst, Src);
6886     return true;
6887   }
6888 
6889   bool emitCUDADeviceBuiltinTextureDeviceCopy(CodeGenFunction &CGF, LValue Dst,
6890                                               LValue Src) const override {
6891     emitBuiltinSurfTexDeviceCopy(CGF, Dst, Src);
6892     return true;
6893   }
6894 
6895 private:
6896   // Adds a NamedMDNode with GV, Name, and Operand as operands, and adds the
6897   // resulting MDNode to the nvvm.annotations MDNode.
6898   static void addNVVMMetadata(llvm::GlobalValue *GV, StringRef Name,
6899                               int Operand);
6900 
6901   static void emitBuiltinSurfTexDeviceCopy(CodeGenFunction &CGF, LValue Dst,
6902                                            LValue Src) {
6903     llvm::Value *Handle = nullptr;
6904     llvm::Constant *C =
6905         llvm::dyn_cast<llvm::Constant>(Src.getAddress(CGF).getPointer());
6906     // Lookup `addrspacecast` through the constant pointer if any.
6907     if (auto *ASC = llvm::dyn_cast_or_null<llvm::AddrSpaceCastOperator>(C))
6908       C = llvm::cast<llvm::Constant>(ASC->getPointerOperand());
6909     if (auto *GV = llvm::dyn_cast_or_null<llvm::GlobalVariable>(C)) {
6910       // Load the handle from the specific global variable using
6911       // `nvvm.texsurf.handle.internal` intrinsic.
6912       Handle = CGF.EmitRuntimeCall(
6913           CGF.CGM.getIntrinsic(llvm::Intrinsic::nvvm_texsurf_handle_internal,
6914                                {GV->getType()}),
6915           {GV}, "texsurf_handle");
6916     } else
6917       Handle = CGF.EmitLoadOfScalar(Src, SourceLocation());
6918     CGF.EmitStoreOfScalar(Handle, Dst);
6919   }
6920 };
6921 
6922 /// Checks if the type is unsupported directly by the current target.
6923 bool NVPTXABIInfo::isUnsupportedType(QualType T) const {
6924   ASTContext &Context = getContext();
6925   if (!Context.getTargetInfo().hasFloat16Type() && T->isFloat16Type())
6926     return true;
6927   if (!Context.getTargetInfo().hasFloat128Type() &&
6928       (T->isFloat128Type() ||
6929        (T->isRealFloatingType() && Context.getTypeSize(T) == 128)))
6930     return true;
6931   if (const auto *EIT = T->getAs<ExtIntType>())
6932     return EIT->getNumBits() >
6933            (Context.getTargetInfo().hasInt128Type() ? 128U : 64U);
6934   if (!Context.getTargetInfo().hasInt128Type() && T->isIntegerType() &&
6935       Context.getTypeSize(T) > 64U)
6936     return true;
6937   if (const auto *AT = T->getAsArrayTypeUnsafe())
6938     return isUnsupportedType(AT->getElementType());
6939   const auto *RT = T->getAs<RecordType>();
6940   if (!RT)
6941     return false;
6942   const RecordDecl *RD = RT->getDecl();
6943 
6944   // If this is a C++ record, check the bases first.
6945   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
6946     for (const CXXBaseSpecifier &I : CXXRD->bases())
6947       if (isUnsupportedType(I.getType()))
6948         return true;
6949 
6950   for (const FieldDecl *I : RD->fields())
6951     if (isUnsupportedType(I->getType()))
6952       return true;
6953   return false;
6954 }
6955 
6956 /// Coerce the given type into an array with maximum allowed size of elements.
6957 ABIArgInfo NVPTXABIInfo::coerceToIntArrayWithLimit(QualType Ty,
6958                                                    unsigned MaxSize) const {
6959   // Alignment and Size are measured in bits.
6960   const uint64_t Size = getContext().getTypeSize(Ty);
6961   const uint64_t Alignment = getContext().getTypeAlign(Ty);
6962   const unsigned Div = std::min<unsigned>(MaxSize, Alignment);
6963   llvm::Type *IntType = llvm::Type::getIntNTy(getVMContext(), Div);
6964   const uint64_t NumElements = (Size + Div - 1) / Div;
6965   return ABIArgInfo::getDirect(llvm::ArrayType::get(IntType, NumElements));
6966 }
6967 
6968 ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
6969   if (RetTy->isVoidType())
6970     return ABIArgInfo::getIgnore();
6971 
6972   if (getContext().getLangOpts().OpenMP &&
6973       getContext().getLangOpts().OpenMPIsDevice && isUnsupportedType(RetTy))
6974     return coerceToIntArrayWithLimit(RetTy, 64);
6975 
6976   // note: this is different from default ABI
6977   if (!RetTy->isScalarType())
6978     return ABIArgInfo::getDirect();
6979 
6980   // Treat an enum type as its underlying type.
6981   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6982     RetTy = EnumTy->getDecl()->getIntegerType();
6983 
6984   return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
6985                                                : ABIArgInfo::getDirect());
6986 }
6987 
6988 ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
6989   // Treat an enum type as its underlying type.
6990   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6991     Ty = EnumTy->getDecl()->getIntegerType();
6992 
6993   // Return aggregates type as indirect by value
6994   if (isAggregateTypeForABI(Ty)) {
6995     // Under CUDA device compilation, tex/surf builtin types are replaced with
6996     // object types and passed directly.
6997     if (getContext().getLangOpts().CUDAIsDevice) {
6998       if (Ty->isCUDADeviceBuiltinSurfaceType())
6999         return ABIArgInfo::getDirect(
7000             CGInfo.getCUDADeviceBuiltinSurfaceDeviceType());
7001       if (Ty->isCUDADeviceBuiltinTextureType())
7002         return ABIArgInfo::getDirect(
7003             CGInfo.getCUDADeviceBuiltinTextureDeviceType());
7004     }
7005     return getNaturalAlignIndirect(Ty, /* byval */ true);
7006   }
7007 
7008   if (const auto *EIT = Ty->getAs<ExtIntType>()) {
7009     if ((EIT->getNumBits() > 128) ||
7010         (!getContext().getTargetInfo().hasInt128Type() &&
7011          EIT->getNumBits() > 64))
7012       return getNaturalAlignIndirect(Ty, /* byval */ true);
7013   }
7014 
7015   return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
7016                                             : ABIArgInfo::getDirect());
7017 }
7018 
7019 void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
7020   if (!getCXXABI().classifyReturnType(FI))
7021     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7022   for (auto &I : FI.arguments())
7023     I.info = classifyArgumentType(I.type);
7024 
7025   // Always honor user-specified calling convention.
7026   if (FI.getCallingConvention() != llvm::CallingConv::C)
7027     return;
7028 
7029   FI.setEffectiveCallingConvention(getRuntimeCC());
7030 }
7031 
7032 Address NVPTXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7033                                 QualType Ty) const {
7034   llvm_unreachable("NVPTX does not support varargs");
7035 }
7036 
7037 void NVPTXTargetCodeGenInfo::setTargetAttributes(
7038     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
7039   if (GV->isDeclaration())
7040     return;
7041   const VarDecl *VD = dyn_cast_or_null<VarDecl>(D);
7042   if (VD) {
7043     if (M.getLangOpts().CUDA) {
7044       if (VD->getType()->isCUDADeviceBuiltinSurfaceType())
7045         addNVVMMetadata(GV, "surface", 1);
7046       else if (VD->getType()->isCUDADeviceBuiltinTextureType())
7047         addNVVMMetadata(GV, "texture", 1);
7048       return;
7049     }
7050   }
7051 
7052   const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
7053   if (!FD) return;
7054 
7055   llvm::Function *F = cast<llvm::Function>(GV);
7056 
7057   // Perform special handling in OpenCL mode
7058   if (M.getLangOpts().OpenCL) {
7059     // Use OpenCL function attributes to check for kernel functions
7060     // By default, all functions are device functions
7061     if (FD->hasAttr<OpenCLKernelAttr>()) {
7062       // OpenCL __kernel functions get kernel metadata
7063       // Create !{<func-ref>, metadata !"kernel", i32 1} node
7064       addNVVMMetadata(F, "kernel", 1);
7065       // And kernel functions are not subject to inlining
7066       F->addFnAttr(llvm::Attribute::NoInline);
7067     }
7068   }
7069 
7070   // Perform special handling in CUDA mode.
7071   if (M.getLangOpts().CUDA) {
7072     // CUDA __global__ functions get a kernel metadata entry.  Since
7073     // __global__ functions cannot be called from the device, we do not
7074     // need to set the noinline attribute.
7075     if (FD->hasAttr<CUDAGlobalAttr>()) {
7076       // Create !{<func-ref>, metadata !"kernel", i32 1} node
7077       addNVVMMetadata(F, "kernel", 1);
7078     }
7079     if (CUDALaunchBoundsAttr *Attr = FD->getAttr<CUDALaunchBoundsAttr>()) {
7080       // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node
7081       llvm::APSInt MaxThreads(32);
7082       MaxThreads = Attr->getMaxThreads()->EvaluateKnownConstInt(M.getContext());
7083       if (MaxThreads > 0)
7084         addNVVMMetadata(F, "maxntidx", MaxThreads.getExtValue());
7085 
7086       // min blocks is an optional argument for CUDALaunchBoundsAttr. If it was
7087       // not specified in __launch_bounds__ or if the user specified a 0 value,
7088       // we don't have to add a PTX directive.
7089       if (Attr->getMinBlocks()) {
7090         llvm::APSInt MinBlocks(32);
7091         MinBlocks = Attr->getMinBlocks()->EvaluateKnownConstInt(M.getContext());
7092         if (MinBlocks > 0)
7093           // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node
7094           addNVVMMetadata(F, "minctasm", MinBlocks.getExtValue());
7095       }
7096     }
7097   }
7098 }
7099 
7100 void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::GlobalValue *GV,
7101                                              StringRef Name, int Operand) {
7102   llvm::Module *M = GV->getParent();
7103   llvm::LLVMContext &Ctx = M->getContext();
7104 
7105   // Get "nvvm.annotations" metadata node
7106   llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
7107 
7108   llvm::Metadata *MDVals[] = {
7109       llvm::ConstantAsMetadata::get(GV), llvm::MDString::get(Ctx, Name),
7110       llvm::ConstantAsMetadata::get(
7111           llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand))};
7112   // Append metadata to nvvm.annotations
7113   MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
7114 }
7115 
7116 bool NVPTXTargetCodeGenInfo::shouldEmitStaticExternCAliases() const {
7117   return false;
7118 }
7119 }
7120 
7121 //===----------------------------------------------------------------------===//
7122 // SystemZ ABI Implementation
7123 //===----------------------------------------------------------------------===//
7124 
7125 namespace {
7126 
7127 class SystemZABIInfo : public SwiftABIInfo {
7128   bool HasVector;
7129   bool IsSoftFloatABI;
7130 
7131 public:
7132   SystemZABIInfo(CodeGenTypes &CGT, bool HV, bool SF)
7133     : SwiftABIInfo(CGT), HasVector(HV), IsSoftFloatABI(SF) {}
7134 
7135   bool isPromotableIntegerTypeForABI(QualType Ty) const;
7136   bool isCompoundType(QualType Ty) const;
7137   bool isVectorArgumentType(QualType Ty) const;
7138   bool isFPArgumentType(QualType Ty) const;
7139   QualType GetSingleElementType(QualType Ty) const;
7140 
7141   ABIArgInfo classifyReturnType(QualType RetTy) const;
7142   ABIArgInfo classifyArgumentType(QualType ArgTy) const;
7143 
7144   void computeInfo(CGFunctionInfo &FI) const override {
7145     if (!getCXXABI().classifyReturnType(FI))
7146       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7147     for (auto &I : FI.arguments())
7148       I.info = classifyArgumentType(I.type);
7149   }
7150 
7151   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7152                     QualType Ty) const override;
7153 
7154   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
7155                                     bool asReturnValue) const override {
7156     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
7157   }
7158   bool isSwiftErrorInRegister() const override {
7159     return false;
7160   }
7161 };
7162 
7163 class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
7164 public:
7165   SystemZTargetCodeGenInfo(CodeGenTypes &CGT, bool HasVector, bool SoftFloatABI)
7166       : TargetCodeGenInfo(
7167             std::make_unique<SystemZABIInfo>(CGT, HasVector, SoftFloatABI)) {}
7168 };
7169 
7170 }
7171 
7172 bool SystemZABIInfo::isPromotableIntegerTypeForABI(QualType Ty) const {
7173   // Treat an enum type as its underlying type.
7174   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7175     Ty = EnumTy->getDecl()->getIntegerType();
7176 
7177   // Promotable integer types are required to be promoted by the ABI.
7178   if (ABIInfo::isPromotableIntegerTypeForABI(Ty))
7179     return true;
7180 
7181   if (const auto *EIT = Ty->getAs<ExtIntType>())
7182     if (EIT->getNumBits() < 64)
7183       return true;
7184 
7185   // 32-bit values must also be promoted.
7186   if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
7187     switch (BT->getKind()) {
7188     case BuiltinType::Int:
7189     case BuiltinType::UInt:
7190       return true;
7191     default:
7192       return false;
7193     }
7194   return false;
7195 }
7196 
7197 bool SystemZABIInfo::isCompoundType(QualType Ty) const {
7198   return (Ty->isAnyComplexType() ||
7199           Ty->isVectorType() ||
7200           isAggregateTypeForABI(Ty));
7201 }
7202 
7203 bool SystemZABIInfo::isVectorArgumentType(QualType Ty) const {
7204   return (HasVector &&
7205           Ty->isVectorType() &&
7206           getContext().getTypeSize(Ty) <= 128);
7207 }
7208 
7209 bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
7210   if (IsSoftFloatABI)
7211     return false;
7212 
7213   if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
7214     switch (BT->getKind()) {
7215     case BuiltinType::Float:
7216     case BuiltinType::Double:
7217       return true;
7218     default:
7219       return false;
7220     }
7221 
7222   return false;
7223 }
7224 
7225 QualType SystemZABIInfo::GetSingleElementType(QualType Ty) const {
7226   const RecordType *RT = Ty->getAs<RecordType>();
7227 
7228   if (RT && RT->isStructureOrClassType()) {
7229     const RecordDecl *RD = RT->getDecl();
7230     QualType Found;
7231 
7232     // If this is a C++ record, check the bases first.
7233     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
7234       for (const auto &I : CXXRD->bases()) {
7235         QualType Base = I.getType();
7236 
7237         // Empty bases don't affect things either way.
7238         if (isEmptyRecord(getContext(), Base, true))
7239           continue;
7240 
7241         if (!Found.isNull())
7242           return Ty;
7243         Found = GetSingleElementType(Base);
7244       }
7245 
7246     // Check the fields.
7247     for (const auto *FD : RD->fields()) {
7248       // For compatibility with GCC, ignore empty bitfields in C++ mode.
7249       // Unlike isSingleElementStruct(), empty structure and array fields
7250       // do count.  So do anonymous bitfields that aren't zero-sized.
7251       if (getContext().getLangOpts().CPlusPlus &&
7252           FD->isZeroLengthBitField(getContext()))
7253         continue;
7254       // Like isSingleElementStruct(), ignore C++20 empty data members.
7255       if (FD->hasAttr<NoUniqueAddressAttr>() &&
7256           isEmptyRecord(getContext(), FD->getType(), true))
7257         continue;
7258 
7259       // Unlike isSingleElementStruct(), arrays do not count.
7260       // Nested structures still do though.
7261       if (!Found.isNull())
7262         return Ty;
7263       Found = GetSingleElementType(FD->getType());
7264     }
7265 
7266     // Unlike isSingleElementStruct(), trailing padding is allowed.
7267     // An 8-byte aligned struct s { float f; } is passed as a double.
7268     if (!Found.isNull())
7269       return Found;
7270   }
7271 
7272   return Ty;
7273 }
7274 
7275 Address SystemZABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7276                                   QualType Ty) const {
7277   // Assume that va_list type is correct; should be pointer to LLVM type:
7278   // struct {
7279   //   i64 __gpr;
7280   //   i64 __fpr;
7281   //   i8 *__overflow_arg_area;
7282   //   i8 *__reg_save_area;
7283   // };
7284 
7285   // Every non-vector argument occupies 8 bytes and is passed by preference
7286   // in either GPRs or FPRs.  Vector arguments occupy 8 or 16 bytes and are
7287   // always passed on the stack.
7288   Ty = getContext().getCanonicalType(Ty);
7289   auto TyInfo = getContext().getTypeInfoInChars(Ty);
7290   llvm::Type *ArgTy = CGF.ConvertTypeForMem(Ty);
7291   llvm::Type *DirectTy = ArgTy;
7292   ABIArgInfo AI = classifyArgumentType(Ty);
7293   bool IsIndirect = AI.isIndirect();
7294   bool InFPRs = false;
7295   bool IsVector = false;
7296   CharUnits UnpaddedSize;
7297   CharUnits DirectAlign;
7298   if (IsIndirect) {
7299     DirectTy = llvm::PointerType::getUnqual(DirectTy);
7300     UnpaddedSize = DirectAlign = CharUnits::fromQuantity(8);
7301   } else {
7302     if (AI.getCoerceToType())
7303       ArgTy = AI.getCoerceToType();
7304     InFPRs = (!IsSoftFloatABI && (ArgTy->isFloatTy() || ArgTy->isDoubleTy()));
7305     IsVector = ArgTy->isVectorTy();
7306     UnpaddedSize = TyInfo.first;
7307     DirectAlign = TyInfo.second;
7308   }
7309   CharUnits PaddedSize = CharUnits::fromQuantity(8);
7310   if (IsVector && UnpaddedSize > PaddedSize)
7311     PaddedSize = CharUnits::fromQuantity(16);
7312   assert((UnpaddedSize <= PaddedSize) && "Invalid argument size.");
7313 
7314   CharUnits Padding = (PaddedSize - UnpaddedSize);
7315 
7316   llvm::Type *IndexTy = CGF.Int64Ty;
7317   llvm::Value *PaddedSizeV =
7318     llvm::ConstantInt::get(IndexTy, PaddedSize.getQuantity());
7319 
7320   if (IsVector) {
7321     // Work out the address of a vector argument on the stack.
7322     // Vector arguments are always passed in the high bits of a
7323     // single (8 byte) or double (16 byte) stack slot.
7324     Address OverflowArgAreaPtr =
7325         CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr");
7326     Address OverflowArgArea =
7327       Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
7328               TyInfo.second);
7329     Address MemAddr =
7330       CGF.Builder.CreateElementBitCast(OverflowArgArea, DirectTy, "mem_addr");
7331 
7332     // Update overflow_arg_area_ptr pointer
7333     llvm::Value *NewOverflowArgArea =
7334       CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
7335                             "overflow_arg_area");
7336     CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
7337 
7338     return MemAddr;
7339   }
7340 
7341   assert(PaddedSize.getQuantity() == 8);
7342 
7343   unsigned MaxRegs, RegCountField, RegSaveIndex;
7344   CharUnits RegPadding;
7345   if (InFPRs) {
7346     MaxRegs = 4; // Maximum of 4 FPR arguments
7347     RegCountField = 1; // __fpr
7348     RegSaveIndex = 16; // save offset for f0
7349     RegPadding = CharUnits(); // floats are passed in the high bits of an FPR
7350   } else {
7351     MaxRegs = 5; // Maximum of 5 GPR arguments
7352     RegCountField = 0; // __gpr
7353     RegSaveIndex = 2; // save offset for r2
7354     RegPadding = Padding; // values are passed in the low bits of a GPR
7355   }
7356 
7357   Address RegCountPtr =
7358       CGF.Builder.CreateStructGEP(VAListAddr, RegCountField, "reg_count_ptr");
7359   llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
7360   llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
7361   llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
7362                                                  "fits_in_regs");
7363 
7364   llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
7365   llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
7366   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
7367   CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
7368 
7369   // Emit code to load the value if it was passed in registers.
7370   CGF.EmitBlock(InRegBlock);
7371 
7372   // Work out the address of an argument register.
7373   llvm::Value *ScaledRegCount =
7374     CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
7375   llvm::Value *RegBase =
7376     llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize.getQuantity()
7377                                       + RegPadding.getQuantity());
7378   llvm::Value *RegOffset =
7379     CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
7380   Address RegSaveAreaPtr =
7381       CGF.Builder.CreateStructGEP(VAListAddr, 3, "reg_save_area_ptr");
7382   llvm::Value *RegSaveArea =
7383     CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
7384   Address RawRegAddr(CGF.Builder.CreateGEP(RegSaveArea, RegOffset,
7385                                            "raw_reg_addr"),
7386                      PaddedSize);
7387   Address RegAddr =
7388     CGF.Builder.CreateElementBitCast(RawRegAddr, DirectTy, "reg_addr");
7389 
7390   // Update the register count
7391   llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
7392   llvm::Value *NewRegCount =
7393     CGF.Builder.CreateAdd(RegCount, One, "reg_count");
7394   CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
7395   CGF.EmitBranch(ContBlock);
7396 
7397   // Emit code to load the value if it was passed in memory.
7398   CGF.EmitBlock(InMemBlock);
7399 
7400   // Work out the address of a stack argument.
7401   Address OverflowArgAreaPtr =
7402       CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr");
7403   Address OverflowArgArea =
7404     Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
7405             PaddedSize);
7406   Address RawMemAddr =
7407     CGF.Builder.CreateConstByteGEP(OverflowArgArea, Padding, "raw_mem_addr");
7408   Address MemAddr =
7409     CGF.Builder.CreateElementBitCast(RawMemAddr, DirectTy, "mem_addr");
7410 
7411   // Update overflow_arg_area_ptr pointer
7412   llvm::Value *NewOverflowArgArea =
7413     CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
7414                           "overflow_arg_area");
7415   CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
7416   CGF.EmitBranch(ContBlock);
7417 
7418   // Return the appropriate result.
7419   CGF.EmitBlock(ContBlock);
7420   Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
7421                                  MemAddr, InMemBlock, "va_arg.addr");
7422 
7423   if (IsIndirect)
7424     ResAddr = Address(CGF.Builder.CreateLoad(ResAddr, "indirect_arg"),
7425                       TyInfo.second);
7426 
7427   return ResAddr;
7428 }
7429 
7430 ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
7431   if (RetTy->isVoidType())
7432     return ABIArgInfo::getIgnore();
7433   if (isVectorArgumentType(RetTy))
7434     return ABIArgInfo::getDirect();
7435   if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
7436     return getNaturalAlignIndirect(RetTy);
7437   return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
7438                                                : ABIArgInfo::getDirect());
7439 }
7440 
7441 ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
7442   // Handle the generic C++ ABI.
7443   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
7444     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
7445 
7446   // Integers and enums are extended to full register width.
7447   if (isPromotableIntegerTypeForABI(Ty))
7448     return ABIArgInfo::getExtend(Ty);
7449 
7450   // Handle vector types and vector-like structure types.  Note that
7451   // as opposed to float-like structure types, we do not allow any
7452   // padding for vector-like structures, so verify the sizes match.
7453   uint64_t Size = getContext().getTypeSize(Ty);
7454   QualType SingleElementTy = GetSingleElementType(Ty);
7455   if (isVectorArgumentType(SingleElementTy) &&
7456       getContext().getTypeSize(SingleElementTy) == Size)
7457     return ABIArgInfo::getDirect(CGT.ConvertType(SingleElementTy));
7458 
7459   // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
7460   if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
7461     return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
7462 
7463   // Handle small structures.
7464   if (const RecordType *RT = Ty->getAs<RecordType>()) {
7465     // Structures with flexible arrays have variable length, so really
7466     // fail the size test above.
7467     const RecordDecl *RD = RT->getDecl();
7468     if (RD->hasFlexibleArrayMember())
7469       return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
7470 
7471     // The structure is passed as an unextended integer, a float, or a double.
7472     llvm::Type *PassTy;
7473     if (isFPArgumentType(SingleElementTy)) {
7474       assert(Size == 32 || Size == 64);
7475       if (Size == 32)
7476         PassTy = llvm::Type::getFloatTy(getVMContext());
7477       else
7478         PassTy = llvm::Type::getDoubleTy(getVMContext());
7479     } else
7480       PassTy = llvm::IntegerType::get(getVMContext(), Size);
7481     return ABIArgInfo::getDirect(PassTy);
7482   }
7483 
7484   // Non-structure compounds are passed indirectly.
7485   if (isCompoundType(Ty))
7486     return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
7487 
7488   return ABIArgInfo::getDirect(nullptr);
7489 }
7490 
7491 //===----------------------------------------------------------------------===//
7492 // MSP430 ABI Implementation
7493 //===----------------------------------------------------------------------===//
7494 
7495 namespace {
7496 
7497 class MSP430ABIInfo : public DefaultABIInfo {
7498   static ABIArgInfo complexArgInfo() {
7499     ABIArgInfo Info = ABIArgInfo::getDirect();
7500     Info.setCanBeFlattened(false);
7501     return Info;
7502   }
7503 
7504 public:
7505   MSP430ABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
7506 
7507   ABIArgInfo classifyReturnType(QualType RetTy) const {
7508     if (RetTy->isAnyComplexType())
7509       return complexArgInfo();
7510 
7511     return DefaultABIInfo::classifyReturnType(RetTy);
7512   }
7513 
7514   ABIArgInfo classifyArgumentType(QualType RetTy) const {
7515     if (RetTy->isAnyComplexType())
7516       return complexArgInfo();
7517 
7518     return DefaultABIInfo::classifyArgumentType(RetTy);
7519   }
7520 
7521   // Just copy the original implementations because
7522   // DefaultABIInfo::classify{Return,Argument}Type() are not virtual
7523   void computeInfo(CGFunctionInfo &FI) const override {
7524     if (!getCXXABI().classifyReturnType(FI))
7525       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7526     for (auto &I : FI.arguments())
7527       I.info = classifyArgumentType(I.type);
7528   }
7529 
7530   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7531                     QualType Ty) const override {
7532     return EmitVAArgInstr(CGF, VAListAddr, Ty, classifyArgumentType(Ty));
7533   }
7534 };
7535 
7536 class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
7537 public:
7538   MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
7539       : TargetCodeGenInfo(std::make_unique<MSP430ABIInfo>(CGT)) {}
7540   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
7541                            CodeGen::CodeGenModule &M) const override;
7542 };
7543 
7544 }
7545 
7546 void MSP430TargetCodeGenInfo::setTargetAttributes(
7547     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
7548   if (GV->isDeclaration())
7549     return;
7550   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
7551     const auto *InterruptAttr = FD->getAttr<MSP430InterruptAttr>();
7552     if (!InterruptAttr)
7553       return;
7554 
7555     // Handle 'interrupt' attribute:
7556     llvm::Function *F = cast<llvm::Function>(GV);
7557 
7558     // Step 1: Set ISR calling convention.
7559     F->setCallingConv(llvm::CallingConv::MSP430_INTR);
7560 
7561     // Step 2: Add attributes goodness.
7562     F->addFnAttr(llvm::Attribute::NoInline);
7563     F->addFnAttr("interrupt", llvm::utostr(InterruptAttr->getNumber()));
7564   }
7565 }
7566 
7567 //===----------------------------------------------------------------------===//
7568 // MIPS ABI Implementation.  This works for both little-endian and
7569 // big-endian variants.
7570 //===----------------------------------------------------------------------===//
7571 
7572 namespace {
7573 class MipsABIInfo : public ABIInfo {
7574   bool IsO32;
7575   unsigned MinABIStackAlignInBytes, StackAlignInBytes;
7576   void CoerceToIntArgs(uint64_t TySize,
7577                        SmallVectorImpl<llvm::Type *> &ArgList) const;
7578   llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
7579   llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
7580   llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
7581 public:
7582   MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
7583     ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
7584     StackAlignInBytes(IsO32 ? 8 : 16) {}
7585 
7586   ABIArgInfo classifyReturnType(QualType RetTy) const;
7587   ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
7588   void computeInfo(CGFunctionInfo &FI) const override;
7589   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7590                     QualType Ty) const override;
7591   ABIArgInfo extendType(QualType Ty) const;
7592 };
7593 
7594 class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
7595   unsigned SizeOfUnwindException;
7596 public:
7597   MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
7598       : TargetCodeGenInfo(std::make_unique<MipsABIInfo>(CGT, IsO32)),
7599         SizeOfUnwindException(IsO32 ? 24 : 32) {}
7600 
7601   int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
7602     return 29;
7603   }
7604 
7605   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
7606                            CodeGen::CodeGenModule &CGM) const override {
7607     const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
7608     if (!FD) return;
7609     llvm::Function *Fn = cast<llvm::Function>(GV);
7610 
7611     if (FD->hasAttr<MipsLongCallAttr>())
7612       Fn->addFnAttr("long-call");
7613     else if (FD->hasAttr<MipsShortCallAttr>())
7614       Fn->addFnAttr("short-call");
7615 
7616     // Other attributes do not have a meaning for declarations.
7617     if (GV->isDeclaration())
7618       return;
7619 
7620     if (FD->hasAttr<Mips16Attr>()) {
7621       Fn->addFnAttr("mips16");
7622     }
7623     else if (FD->hasAttr<NoMips16Attr>()) {
7624       Fn->addFnAttr("nomips16");
7625     }
7626 
7627     if (FD->hasAttr<MicroMipsAttr>())
7628       Fn->addFnAttr("micromips");
7629     else if (FD->hasAttr<NoMicroMipsAttr>())
7630       Fn->addFnAttr("nomicromips");
7631 
7632     const MipsInterruptAttr *Attr = FD->getAttr<MipsInterruptAttr>();
7633     if (!Attr)
7634       return;
7635 
7636     const char *Kind;
7637     switch (Attr->getInterrupt()) {
7638     case MipsInterruptAttr::eic:     Kind = "eic"; break;
7639     case MipsInterruptAttr::sw0:     Kind = "sw0"; break;
7640     case MipsInterruptAttr::sw1:     Kind = "sw1"; break;
7641     case MipsInterruptAttr::hw0:     Kind = "hw0"; break;
7642     case MipsInterruptAttr::hw1:     Kind = "hw1"; break;
7643     case MipsInterruptAttr::hw2:     Kind = "hw2"; break;
7644     case MipsInterruptAttr::hw3:     Kind = "hw3"; break;
7645     case MipsInterruptAttr::hw4:     Kind = "hw4"; break;
7646     case MipsInterruptAttr::hw5:     Kind = "hw5"; break;
7647     }
7648 
7649     Fn->addFnAttr("interrupt", Kind);
7650 
7651   }
7652 
7653   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
7654                                llvm::Value *Address) const override;
7655 
7656   unsigned getSizeOfUnwindException() const override {
7657     return SizeOfUnwindException;
7658   }
7659 };
7660 }
7661 
7662 void MipsABIInfo::CoerceToIntArgs(
7663     uint64_t TySize, SmallVectorImpl<llvm::Type *> &ArgList) const {
7664   llvm::IntegerType *IntTy =
7665     llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
7666 
7667   // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
7668   for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
7669     ArgList.push_back(IntTy);
7670 
7671   // If necessary, add one more integer type to ArgList.
7672   unsigned R = TySize % (MinABIStackAlignInBytes * 8);
7673 
7674   if (R)
7675     ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
7676 }
7677 
7678 // In N32/64, an aligned double precision floating point field is passed in
7679 // a register.
7680 llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
7681   SmallVector<llvm::Type*, 8> ArgList, IntArgList;
7682 
7683   if (IsO32) {
7684     CoerceToIntArgs(TySize, ArgList);
7685     return llvm::StructType::get(getVMContext(), ArgList);
7686   }
7687 
7688   if (Ty->isComplexType())
7689     return CGT.ConvertType(Ty);
7690 
7691   const RecordType *RT = Ty->getAs<RecordType>();
7692 
7693   // Unions/vectors are passed in integer registers.
7694   if (!RT || !RT->isStructureOrClassType()) {
7695     CoerceToIntArgs(TySize, ArgList);
7696     return llvm::StructType::get(getVMContext(), ArgList);
7697   }
7698 
7699   const RecordDecl *RD = RT->getDecl();
7700   const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
7701   assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
7702 
7703   uint64_t LastOffset = 0;
7704   unsigned idx = 0;
7705   llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
7706 
7707   // Iterate over fields in the struct/class and check if there are any aligned
7708   // double fields.
7709   for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
7710        i != e; ++i, ++idx) {
7711     const QualType Ty = i->getType();
7712     const BuiltinType *BT = Ty->getAs<BuiltinType>();
7713 
7714     if (!BT || BT->getKind() != BuiltinType::Double)
7715       continue;
7716 
7717     uint64_t Offset = Layout.getFieldOffset(idx);
7718     if (Offset % 64) // Ignore doubles that are not aligned.
7719       continue;
7720 
7721     // Add ((Offset - LastOffset) / 64) args of type i64.
7722     for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
7723       ArgList.push_back(I64);
7724 
7725     // Add double type.
7726     ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
7727     LastOffset = Offset + 64;
7728   }
7729 
7730   CoerceToIntArgs(TySize - LastOffset, IntArgList);
7731   ArgList.append(IntArgList.begin(), IntArgList.end());
7732 
7733   return llvm::StructType::get(getVMContext(), ArgList);
7734 }
7735 
7736 llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
7737                                         uint64_t Offset) const {
7738   if (OrigOffset + MinABIStackAlignInBytes > Offset)
7739     return nullptr;
7740 
7741   return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
7742 }
7743 
7744 ABIArgInfo
7745 MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
7746   Ty = useFirstFieldIfTransparentUnion(Ty);
7747 
7748   uint64_t OrigOffset = Offset;
7749   uint64_t TySize = getContext().getTypeSize(Ty);
7750   uint64_t Align = getContext().getTypeAlign(Ty) / 8;
7751 
7752   Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
7753                    (uint64_t)StackAlignInBytes);
7754   unsigned CurrOffset = llvm::alignTo(Offset, Align);
7755   Offset = CurrOffset + llvm::alignTo(TySize, Align * 8) / 8;
7756 
7757   if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
7758     // Ignore empty aggregates.
7759     if (TySize == 0)
7760       return ABIArgInfo::getIgnore();
7761 
7762     if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
7763       Offset = OrigOffset + MinABIStackAlignInBytes;
7764       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
7765     }
7766 
7767     // If we have reached here, aggregates are passed directly by coercing to
7768     // another structure type. Padding is inserted if the offset of the
7769     // aggregate is unaligned.
7770     ABIArgInfo ArgInfo =
7771         ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
7772                               getPaddingType(OrigOffset, CurrOffset));
7773     ArgInfo.setInReg(true);
7774     return ArgInfo;
7775   }
7776 
7777   // Treat an enum type as its underlying type.
7778   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7779     Ty = EnumTy->getDecl()->getIntegerType();
7780 
7781   // Make sure we pass indirectly things that are too large.
7782   if (const auto *EIT = Ty->getAs<ExtIntType>())
7783     if (EIT->getNumBits() > 128 ||
7784         (EIT->getNumBits() > 64 &&
7785          !getContext().getTargetInfo().hasInt128Type()))
7786       return getNaturalAlignIndirect(Ty);
7787 
7788   // All integral types are promoted to the GPR width.
7789   if (Ty->isIntegralOrEnumerationType())
7790     return extendType(Ty);
7791 
7792   return ABIArgInfo::getDirect(
7793       nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset));
7794 }
7795 
7796 llvm::Type*
7797 MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
7798   const RecordType *RT = RetTy->getAs<RecordType>();
7799   SmallVector<llvm::Type*, 8> RTList;
7800 
7801   if (RT && RT->isStructureOrClassType()) {
7802     const RecordDecl *RD = RT->getDecl();
7803     const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
7804     unsigned FieldCnt = Layout.getFieldCount();
7805 
7806     // N32/64 returns struct/classes in floating point registers if the
7807     // following conditions are met:
7808     // 1. The size of the struct/class is no larger than 128-bit.
7809     // 2. The struct/class has one or two fields all of which are floating
7810     //    point types.
7811     // 3. The offset of the first field is zero (this follows what gcc does).
7812     //
7813     // Any other composite results are returned in integer registers.
7814     //
7815     if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
7816       RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
7817       for (; b != e; ++b) {
7818         const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
7819 
7820         if (!BT || !BT->isFloatingPoint())
7821           break;
7822 
7823         RTList.push_back(CGT.ConvertType(b->getType()));
7824       }
7825 
7826       if (b == e)
7827         return llvm::StructType::get(getVMContext(), RTList,
7828                                      RD->hasAttr<PackedAttr>());
7829 
7830       RTList.clear();
7831     }
7832   }
7833 
7834   CoerceToIntArgs(Size, RTList);
7835   return llvm::StructType::get(getVMContext(), RTList);
7836 }
7837 
7838 ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
7839   uint64_t Size = getContext().getTypeSize(RetTy);
7840 
7841   if (RetTy->isVoidType())
7842     return ABIArgInfo::getIgnore();
7843 
7844   // O32 doesn't treat zero-sized structs differently from other structs.
7845   // However, N32/N64 ignores zero sized return values.
7846   if (!IsO32 && Size == 0)
7847     return ABIArgInfo::getIgnore();
7848 
7849   if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
7850     if (Size <= 128) {
7851       if (RetTy->isAnyComplexType())
7852         return ABIArgInfo::getDirect();
7853 
7854       // O32 returns integer vectors in registers and N32/N64 returns all small
7855       // aggregates in registers.
7856       if (!IsO32 ||
7857           (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) {
7858         ABIArgInfo ArgInfo =
7859             ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
7860         ArgInfo.setInReg(true);
7861         return ArgInfo;
7862       }
7863     }
7864 
7865     return getNaturalAlignIndirect(RetTy);
7866   }
7867 
7868   // Treat an enum type as its underlying type.
7869   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
7870     RetTy = EnumTy->getDecl()->getIntegerType();
7871 
7872   // Make sure we pass indirectly things that are too large.
7873   if (const auto *EIT = RetTy->getAs<ExtIntType>())
7874     if (EIT->getNumBits() > 128 ||
7875         (EIT->getNumBits() > 64 &&
7876          !getContext().getTargetInfo().hasInt128Type()))
7877       return getNaturalAlignIndirect(RetTy);
7878 
7879   if (isPromotableIntegerTypeForABI(RetTy))
7880     return ABIArgInfo::getExtend(RetTy);
7881 
7882   if ((RetTy->isUnsignedIntegerOrEnumerationType() ||
7883       RetTy->isSignedIntegerOrEnumerationType()) && Size == 32 && !IsO32)
7884     return ABIArgInfo::getSignExtend(RetTy);
7885 
7886   return ABIArgInfo::getDirect();
7887 }
7888 
7889 void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
7890   ABIArgInfo &RetInfo = FI.getReturnInfo();
7891   if (!getCXXABI().classifyReturnType(FI))
7892     RetInfo = classifyReturnType(FI.getReturnType());
7893 
7894   // Check if a pointer to an aggregate is passed as a hidden argument.
7895   uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
7896 
7897   for (auto &I : FI.arguments())
7898     I.info = classifyArgumentType(I.type, Offset);
7899 }
7900 
7901 Address MipsABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7902                                QualType OrigTy) const {
7903   QualType Ty = OrigTy;
7904 
7905   // Integer arguments are promoted to 32-bit on O32 and 64-bit on N32/N64.
7906   // Pointers are also promoted in the same way but this only matters for N32.
7907   unsigned SlotSizeInBits = IsO32 ? 32 : 64;
7908   unsigned PtrWidth = getTarget().getPointerWidth(0);
7909   bool DidPromote = false;
7910   if ((Ty->isIntegerType() &&
7911           getContext().getIntWidth(Ty) < SlotSizeInBits) ||
7912       (Ty->isPointerType() && PtrWidth < SlotSizeInBits)) {
7913     DidPromote = true;
7914     Ty = getContext().getIntTypeForBitwidth(SlotSizeInBits,
7915                                             Ty->isSignedIntegerType());
7916   }
7917 
7918   auto TyInfo = getContext().getTypeInfoInChars(Ty);
7919 
7920   // The alignment of things in the argument area is never larger than
7921   // StackAlignInBytes.
7922   TyInfo.second =
7923     std::min(TyInfo.second, CharUnits::fromQuantity(StackAlignInBytes));
7924 
7925   // MinABIStackAlignInBytes is the size of argument slots on the stack.
7926   CharUnits ArgSlotSize = CharUnits::fromQuantity(MinABIStackAlignInBytes);
7927 
7928   Address Addr = emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
7929                           TyInfo, ArgSlotSize, /*AllowHigherAlign*/ true);
7930 
7931 
7932   // If there was a promotion, "unpromote" into a temporary.
7933   // TODO: can we just use a pointer into a subset of the original slot?
7934   if (DidPromote) {
7935     Address Temp = CGF.CreateMemTemp(OrigTy, "vaarg.promotion-temp");
7936     llvm::Value *Promoted = CGF.Builder.CreateLoad(Addr);
7937 
7938     // Truncate down to the right width.
7939     llvm::Type *IntTy = (OrigTy->isIntegerType() ? Temp.getElementType()
7940                                                  : CGF.IntPtrTy);
7941     llvm::Value *V = CGF.Builder.CreateTrunc(Promoted, IntTy);
7942     if (OrigTy->isPointerType())
7943       V = CGF.Builder.CreateIntToPtr(V, Temp.getElementType());
7944 
7945     CGF.Builder.CreateStore(V, Temp);
7946     Addr = Temp;
7947   }
7948 
7949   return Addr;
7950 }
7951 
7952 ABIArgInfo MipsABIInfo::extendType(QualType Ty) const {
7953   int TySize = getContext().getTypeSize(Ty);
7954 
7955   // MIPS64 ABI requires unsigned 32 bit integers to be sign extended.
7956   if (Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
7957     return ABIArgInfo::getSignExtend(Ty);
7958 
7959   return ABIArgInfo::getExtend(Ty);
7960 }
7961 
7962 bool
7963 MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
7964                                                llvm::Value *Address) const {
7965   // This information comes from gcc's implementation, which seems to
7966   // as canonical as it gets.
7967 
7968   // Everything on MIPS is 4 bytes.  Double-precision FP registers
7969   // are aliased to pairs of single-precision FP registers.
7970   llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
7971 
7972   // 0-31 are the general purpose registers, $0 - $31.
7973   // 32-63 are the floating-point registers, $f0 - $f31.
7974   // 64 and 65 are the multiply/divide registers, $hi and $lo.
7975   // 66 is the (notional, I think) register for signal-handler return.
7976   AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
7977 
7978   // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
7979   // They are one bit wide and ignored here.
7980 
7981   // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
7982   // (coprocessor 1 is the FP unit)
7983   // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
7984   // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
7985   // 176-181 are the DSP accumulator registers.
7986   AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
7987   return false;
7988 }
7989 
7990 //===----------------------------------------------------------------------===//
7991 // AVR ABI Implementation.
7992 //===----------------------------------------------------------------------===//
7993 
7994 namespace {
7995 class AVRTargetCodeGenInfo : public TargetCodeGenInfo {
7996 public:
7997   AVRTargetCodeGenInfo(CodeGenTypes &CGT)
7998       : TargetCodeGenInfo(std::make_unique<DefaultABIInfo>(CGT)) {}
7999 
8000   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
8001                            CodeGen::CodeGenModule &CGM) const override {
8002     if (GV->isDeclaration())
8003       return;
8004     const auto *FD = dyn_cast_or_null<FunctionDecl>(D);
8005     if (!FD) return;
8006     auto *Fn = cast<llvm::Function>(GV);
8007 
8008     if (FD->getAttr<AVRInterruptAttr>())
8009       Fn->addFnAttr("interrupt");
8010 
8011     if (FD->getAttr<AVRSignalAttr>())
8012       Fn->addFnAttr("signal");
8013   }
8014 };
8015 }
8016 
8017 //===----------------------------------------------------------------------===//
8018 // TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
8019 // Currently subclassed only to implement custom OpenCL C function attribute
8020 // handling.
8021 //===----------------------------------------------------------------------===//
8022 
8023 namespace {
8024 
8025 class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
8026 public:
8027   TCETargetCodeGenInfo(CodeGenTypes &CGT)
8028     : DefaultTargetCodeGenInfo(CGT) {}
8029 
8030   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
8031                            CodeGen::CodeGenModule &M) const override;
8032 };
8033 
8034 void TCETargetCodeGenInfo::setTargetAttributes(
8035     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
8036   if (GV->isDeclaration())
8037     return;
8038   const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
8039   if (!FD) return;
8040 
8041   llvm::Function *F = cast<llvm::Function>(GV);
8042 
8043   if (M.getLangOpts().OpenCL) {
8044     if (FD->hasAttr<OpenCLKernelAttr>()) {
8045       // OpenCL C Kernel functions are not subject to inlining
8046       F->addFnAttr(llvm::Attribute::NoInline);
8047       const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
8048       if (Attr) {
8049         // Convert the reqd_work_group_size() attributes to metadata.
8050         llvm::LLVMContext &Context = F->getContext();
8051         llvm::NamedMDNode *OpenCLMetadata =
8052             M.getModule().getOrInsertNamedMetadata(
8053                 "opencl.kernel_wg_size_info");
8054 
8055         SmallVector<llvm::Metadata *, 5> Operands;
8056         Operands.push_back(llvm::ConstantAsMetadata::get(F));
8057 
8058         Operands.push_back(
8059             llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
8060                 M.Int32Ty, llvm::APInt(32, Attr->getXDim()))));
8061         Operands.push_back(
8062             llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
8063                 M.Int32Ty, llvm::APInt(32, Attr->getYDim()))));
8064         Operands.push_back(
8065             llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
8066                 M.Int32Ty, llvm::APInt(32, Attr->getZDim()))));
8067 
8068         // Add a boolean constant operand for "required" (true) or "hint"
8069         // (false) for implementing the work_group_size_hint attr later.
8070         // Currently always true as the hint is not yet implemented.
8071         Operands.push_back(
8072             llvm::ConstantAsMetadata::get(llvm::ConstantInt::getTrue(Context)));
8073         OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
8074       }
8075     }
8076   }
8077 }
8078 
8079 }
8080 
8081 //===----------------------------------------------------------------------===//
8082 // Hexagon ABI Implementation
8083 //===----------------------------------------------------------------------===//
8084 
8085 namespace {
8086 
8087 class HexagonABIInfo : public DefaultABIInfo {
8088 public:
8089   HexagonABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
8090 
8091 private:
8092   ABIArgInfo classifyReturnType(QualType RetTy) const;
8093   ABIArgInfo classifyArgumentType(QualType RetTy) const;
8094   ABIArgInfo classifyArgumentType(QualType RetTy, unsigned *RegsLeft) const;
8095 
8096   void computeInfo(CGFunctionInfo &FI) const override;
8097 
8098   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8099                     QualType Ty) const override;
8100   Address EmitVAArgFromMemory(CodeGenFunction &CFG, Address VAListAddr,
8101                               QualType Ty) const;
8102   Address EmitVAArgForHexagon(CodeGenFunction &CFG, Address VAListAddr,
8103                               QualType Ty) const;
8104   Address EmitVAArgForHexagonLinux(CodeGenFunction &CFG, Address VAListAddr,
8105                                    QualType Ty) const;
8106 };
8107 
8108 class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
8109 public:
8110   HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
8111       : TargetCodeGenInfo(std::make_unique<HexagonABIInfo>(CGT)) {}
8112 
8113   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
8114     return 29;
8115   }
8116 
8117   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
8118                            CodeGen::CodeGenModule &GCM) const override {
8119     if (GV->isDeclaration())
8120       return;
8121     const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
8122     if (!FD)
8123       return;
8124   }
8125 };
8126 
8127 } // namespace
8128 
8129 void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
8130   unsigned RegsLeft = 6;
8131   if (!getCXXABI().classifyReturnType(FI))
8132     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
8133   for (auto &I : FI.arguments())
8134     I.info = classifyArgumentType(I.type, &RegsLeft);
8135 }
8136 
8137 static bool HexagonAdjustRegsLeft(uint64_t Size, unsigned *RegsLeft) {
8138   assert(Size <= 64 && "Not expecting to pass arguments larger than 64 bits"
8139                        " through registers");
8140 
8141   if (*RegsLeft == 0)
8142     return false;
8143 
8144   if (Size <= 32) {
8145     (*RegsLeft)--;
8146     return true;
8147   }
8148 
8149   if (2 <= (*RegsLeft & (~1U))) {
8150     *RegsLeft = (*RegsLeft & (~1U)) - 2;
8151     return true;
8152   }
8153 
8154   // Next available register was r5 but candidate was greater than 32-bits so it
8155   // has to go on the stack. However we still consume r5
8156   if (*RegsLeft == 1)
8157     *RegsLeft = 0;
8158 
8159   return false;
8160 }
8161 
8162 ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty,
8163                                                 unsigned *RegsLeft) const {
8164   if (!isAggregateTypeForABI(Ty)) {
8165     // Treat an enum type as its underlying type.
8166     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
8167       Ty = EnumTy->getDecl()->getIntegerType();
8168 
8169     uint64_t Size = getContext().getTypeSize(Ty);
8170     if (Size <= 64)
8171       HexagonAdjustRegsLeft(Size, RegsLeft);
8172 
8173     if (Size > 64 && Ty->isExtIntType())
8174       return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
8175 
8176     return isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
8177                                              : ABIArgInfo::getDirect();
8178   }
8179 
8180   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
8181     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
8182 
8183   // Ignore empty records.
8184   if (isEmptyRecord(getContext(), Ty, true))
8185     return ABIArgInfo::getIgnore();
8186 
8187   uint64_t Size = getContext().getTypeSize(Ty);
8188   unsigned Align = getContext().getTypeAlign(Ty);
8189 
8190   if (Size > 64)
8191     return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
8192 
8193   if (HexagonAdjustRegsLeft(Size, RegsLeft))
8194     Align = Size <= 32 ? 32 : 64;
8195   if (Size <= Align) {
8196     // Pass in the smallest viable integer type.
8197     if (!llvm::isPowerOf2_64(Size))
8198       Size = llvm::NextPowerOf2(Size);
8199     return ABIArgInfo::getDirect(llvm::Type::getIntNTy(getVMContext(), Size));
8200   }
8201   return DefaultABIInfo::classifyArgumentType(Ty);
8202 }
8203 
8204 ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
8205   if (RetTy->isVoidType())
8206     return ABIArgInfo::getIgnore();
8207 
8208   const TargetInfo &T = CGT.getTarget();
8209   uint64_t Size = getContext().getTypeSize(RetTy);
8210 
8211   if (RetTy->getAs<VectorType>()) {
8212     // HVX vectors are returned in vector registers or register pairs.
8213     if (T.hasFeature("hvx")) {
8214       assert(T.hasFeature("hvx-length64b") || T.hasFeature("hvx-length128b"));
8215       uint64_t VecSize = T.hasFeature("hvx-length64b") ? 64*8 : 128*8;
8216       if (Size == VecSize || Size == 2*VecSize)
8217         return ABIArgInfo::getDirectInReg();
8218     }
8219     // Large vector types should be returned via memory.
8220     if (Size > 64)
8221       return getNaturalAlignIndirect(RetTy);
8222   }
8223 
8224   if (!isAggregateTypeForABI(RetTy)) {
8225     // Treat an enum type as its underlying type.
8226     if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
8227       RetTy = EnumTy->getDecl()->getIntegerType();
8228 
8229     if (Size > 64 && RetTy->isExtIntType())
8230       return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
8231 
8232     return isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
8233                                                 : ABIArgInfo::getDirect();
8234   }
8235 
8236   if (isEmptyRecord(getContext(), RetTy, true))
8237     return ABIArgInfo::getIgnore();
8238 
8239   // Aggregates <= 8 bytes are returned in registers, other aggregates
8240   // are returned indirectly.
8241   if (Size <= 64) {
8242     // Return in the smallest viable integer type.
8243     if (!llvm::isPowerOf2_64(Size))
8244       Size = llvm::NextPowerOf2(Size);
8245     return ABIArgInfo::getDirect(llvm::Type::getIntNTy(getVMContext(), Size));
8246   }
8247   return getNaturalAlignIndirect(RetTy, /*ByVal=*/true);
8248 }
8249 
8250 Address HexagonABIInfo::EmitVAArgFromMemory(CodeGenFunction &CGF,
8251                                             Address VAListAddr,
8252                                             QualType Ty) const {
8253   // Load the overflow area pointer.
8254   Address __overflow_area_pointer_p =
8255       CGF.Builder.CreateStructGEP(VAListAddr, 2, "__overflow_area_pointer_p");
8256   llvm::Value *__overflow_area_pointer = CGF.Builder.CreateLoad(
8257       __overflow_area_pointer_p, "__overflow_area_pointer");
8258 
8259   uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8;
8260   if (Align > 4) {
8261     // Alignment should be a power of 2.
8262     assert((Align & (Align - 1)) == 0 && "Alignment is not power of 2!");
8263 
8264     // overflow_arg_area = (overflow_arg_area + align - 1) & -align;
8265     llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int64Ty, Align - 1);
8266 
8267     // Add offset to the current pointer to access the argument.
8268     __overflow_area_pointer =
8269         CGF.Builder.CreateGEP(__overflow_area_pointer, Offset);
8270     llvm::Value *AsInt =
8271         CGF.Builder.CreatePtrToInt(__overflow_area_pointer, CGF.Int32Ty);
8272 
8273     // Create a mask which should be "AND"ed
8274     // with (overflow_arg_area + align - 1)
8275     llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int32Ty, -(int)Align);
8276     __overflow_area_pointer = CGF.Builder.CreateIntToPtr(
8277         CGF.Builder.CreateAnd(AsInt, Mask), __overflow_area_pointer->getType(),
8278         "__overflow_area_pointer.align");
8279   }
8280 
8281   // Get the type of the argument from memory and bitcast
8282   // overflow area pointer to the argument type.
8283   llvm::Type *PTy = CGF.ConvertTypeForMem(Ty);
8284   Address AddrTyped = CGF.Builder.CreateBitCast(
8285       Address(__overflow_area_pointer, CharUnits::fromQuantity(Align)),
8286       llvm::PointerType::getUnqual(PTy));
8287 
8288   // Round up to the minimum stack alignment for varargs which is 4 bytes.
8289   uint64_t Offset = llvm::alignTo(CGF.getContext().getTypeSize(Ty) / 8, 4);
8290 
8291   __overflow_area_pointer = CGF.Builder.CreateGEP(
8292       __overflow_area_pointer, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
8293       "__overflow_area_pointer.next");
8294   CGF.Builder.CreateStore(__overflow_area_pointer, __overflow_area_pointer_p);
8295 
8296   return AddrTyped;
8297 }
8298 
8299 Address HexagonABIInfo::EmitVAArgForHexagon(CodeGenFunction &CGF,
8300                                             Address VAListAddr,
8301                                             QualType Ty) const {
8302   // FIXME: Need to handle alignment
8303   llvm::Type *BP = CGF.Int8PtrTy;
8304   llvm::Type *BPP = CGF.Int8PtrPtrTy;
8305   CGBuilderTy &Builder = CGF.Builder;
8306   Address VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
8307   llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
8308   // Handle address alignment for type alignment > 32 bits
8309   uint64_t TyAlign = CGF.getContext().getTypeAlign(Ty) / 8;
8310   if (TyAlign > 4) {
8311     assert((TyAlign & (TyAlign - 1)) == 0 && "Alignment is not power of 2!");
8312     llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int32Ty);
8313     AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt32(TyAlign - 1));
8314     AddrAsInt = Builder.CreateAnd(AddrAsInt, Builder.getInt32(~(TyAlign - 1)));
8315     Addr = Builder.CreateIntToPtr(AddrAsInt, BP);
8316   }
8317   llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
8318   Address AddrTyped = Builder.CreateBitCast(
8319       Address(Addr, CharUnits::fromQuantity(TyAlign)), PTy);
8320 
8321   uint64_t Offset = llvm::alignTo(CGF.getContext().getTypeSize(Ty) / 8, 4);
8322   llvm::Value *NextAddr = Builder.CreateGEP(
8323       Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset), "ap.next");
8324   Builder.CreateStore(NextAddr, VAListAddrAsBPP);
8325 
8326   return AddrTyped;
8327 }
8328 
8329 Address HexagonABIInfo::EmitVAArgForHexagonLinux(CodeGenFunction &CGF,
8330                                                  Address VAListAddr,
8331                                                  QualType Ty) const {
8332   int ArgSize = CGF.getContext().getTypeSize(Ty) / 8;
8333 
8334   if (ArgSize > 8)
8335     return EmitVAArgFromMemory(CGF, VAListAddr, Ty);
8336 
8337   // Here we have check if the argument is in register area or
8338   // in overflow area.
8339   // If the saved register area pointer + argsize rounded up to alignment >
8340   // saved register area end pointer, argument is in overflow area.
8341   unsigned RegsLeft = 6;
8342   Ty = CGF.getContext().getCanonicalType(Ty);
8343   (void)classifyArgumentType(Ty, &RegsLeft);
8344 
8345   llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
8346   llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
8347   llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
8348   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
8349 
8350   // Get rounded size of the argument.GCC does not allow vararg of
8351   // size < 4 bytes. We follow the same logic here.
8352   ArgSize = (CGF.getContext().getTypeSize(Ty) <= 32) ? 4 : 8;
8353   int ArgAlign = (CGF.getContext().getTypeSize(Ty) <= 32) ? 4 : 8;
8354 
8355   // Argument may be in saved register area
8356   CGF.EmitBlock(MaybeRegBlock);
8357 
8358   // Load the current saved register area pointer.
8359   Address __current_saved_reg_area_pointer_p = CGF.Builder.CreateStructGEP(
8360       VAListAddr, 0, "__current_saved_reg_area_pointer_p");
8361   llvm::Value *__current_saved_reg_area_pointer = CGF.Builder.CreateLoad(
8362       __current_saved_reg_area_pointer_p, "__current_saved_reg_area_pointer");
8363 
8364   // Load the saved register area end pointer.
8365   Address __saved_reg_area_end_pointer_p = CGF.Builder.CreateStructGEP(
8366       VAListAddr, 1, "__saved_reg_area_end_pointer_p");
8367   llvm::Value *__saved_reg_area_end_pointer = CGF.Builder.CreateLoad(
8368       __saved_reg_area_end_pointer_p, "__saved_reg_area_end_pointer");
8369 
8370   // If the size of argument is > 4 bytes, check if the stack
8371   // location is aligned to 8 bytes
8372   if (ArgAlign > 4) {
8373 
8374     llvm::Value *__current_saved_reg_area_pointer_int =
8375         CGF.Builder.CreatePtrToInt(__current_saved_reg_area_pointer,
8376                                    CGF.Int32Ty);
8377 
8378     __current_saved_reg_area_pointer_int = CGF.Builder.CreateAdd(
8379         __current_saved_reg_area_pointer_int,
8380         llvm::ConstantInt::get(CGF.Int32Ty, (ArgAlign - 1)),
8381         "align_current_saved_reg_area_pointer");
8382 
8383     __current_saved_reg_area_pointer_int =
8384         CGF.Builder.CreateAnd(__current_saved_reg_area_pointer_int,
8385                               llvm::ConstantInt::get(CGF.Int32Ty, -ArgAlign),
8386                               "align_current_saved_reg_area_pointer");
8387 
8388     __current_saved_reg_area_pointer =
8389         CGF.Builder.CreateIntToPtr(__current_saved_reg_area_pointer_int,
8390                                    __current_saved_reg_area_pointer->getType(),
8391                                    "align_current_saved_reg_area_pointer");
8392   }
8393 
8394   llvm::Value *__new_saved_reg_area_pointer =
8395       CGF.Builder.CreateGEP(__current_saved_reg_area_pointer,
8396                             llvm::ConstantInt::get(CGF.Int32Ty, ArgSize),
8397                             "__new_saved_reg_area_pointer");
8398 
8399   llvm::Value *UsingStack = 0;
8400   UsingStack = CGF.Builder.CreateICmpSGT(__new_saved_reg_area_pointer,
8401                                          __saved_reg_area_end_pointer);
8402 
8403   CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, InRegBlock);
8404 
8405   // Argument in saved register area
8406   // Implement the block where argument is in register saved area
8407   CGF.EmitBlock(InRegBlock);
8408 
8409   llvm::Type *PTy = CGF.ConvertType(Ty);
8410   llvm::Value *__saved_reg_area_p = CGF.Builder.CreateBitCast(
8411       __current_saved_reg_area_pointer, llvm::PointerType::getUnqual(PTy));
8412 
8413   CGF.Builder.CreateStore(__new_saved_reg_area_pointer,
8414                           __current_saved_reg_area_pointer_p);
8415 
8416   CGF.EmitBranch(ContBlock);
8417 
8418   // Argument in overflow area
8419   // Implement the block where the argument is in overflow area.
8420   CGF.EmitBlock(OnStackBlock);
8421 
8422   // Load the overflow area pointer
8423   Address __overflow_area_pointer_p =
8424       CGF.Builder.CreateStructGEP(VAListAddr, 2, "__overflow_area_pointer_p");
8425   llvm::Value *__overflow_area_pointer = CGF.Builder.CreateLoad(
8426       __overflow_area_pointer_p, "__overflow_area_pointer");
8427 
8428   // Align the overflow area pointer according to the alignment of the argument
8429   if (ArgAlign > 4) {
8430     llvm::Value *__overflow_area_pointer_int =
8431         CGF.Builder.CreatePtrToInt(__overflow_area_pointer, CGF.Int32Ty);
8432 
8433     __overflow_area_pointer_int =
8434         CGF.Builder.CreateAdd(__overflow_area_pointer_int,
8435                               llvm::ConstantInt::get(CGF.Int32Ty, ArgAlign - 1),
8436                               "align_overflow_area_pointer");
8437 
8438     __overflow_area_pointer_int =
8439         CGF.Builder.CreateAnd(__overflow_area_pointer_int,
8440                               llvm::ConstantInt::get(CGF.Int32Ty, -ArgAlign),
8441                               "align_overflow_area_pointer");
8442 
8443     __overflow_area_pointer = CGF.Builder.CreateIntToPtr(
8444         __overflow_area_pointer_int, __overflow_area_pointer->getType(),
8445         "align_overflow_area_pointer");
8446   }
8447 
8448   // Get the pointer for next argument in overflow area and store it
8449   // to overflow area pointer.
8450   llvm::Value *__new_overflow_area_pointer = CGF.Builder.CreateGEP(
8451       __overflow_area_pointer, llvm::ConstantInt::get(CGF.Int32Ty, ArgSize),
8452       "__overflow_area_pointer.next");
8453 
8454   CGF.Builder.CreateStore(__new_overflow_area_pointer,
8455                           __overflow_area_pointer_p);
8456 
8457   CGF.Builder.CreateStore(__new_overflow_area_pointer,
8458                           __current_saved_reg_area_pointer_p);
8459 
8460   // Bitcast the overflow area pointer to the type of argument.
8461   llvm::Type *OverflowPTy = CGF.ConvertTypeForMem(Ty);
8462   llvm::Value *__overflow_area_p = CGF.Builder.CreateBitCast(
8463       __overflow_area_pointer, llvm::PointerType::getUnqual(OverflowPTy));
8464 
8465   CGF.EmitBranch(ContBlock);
8466 
8467   // Get the correct pointer to load the variable argument
8468   // Implement the ContBlock
8469   CGF.EmitBlock(ContBlock);
8470 
8471   llvm::Type *MemPTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
8472   llvm::PHINode *ArgAddr = CGF.Builder.CreatePHI(MemPTy, 2, "vaarg.addr");
8473   ArgAddr->addIncoming(__saved_reg_area_p, InRegBlock);
8474   ArgAddr->addIncoming(__overflow_area_p, OnStackBlock);
8475 
8476   return Address(ArgAddr, CharUnits::fromQuantity(ArgAlign));
8477 }
8478 
8479 Address HexagonABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8480                                   QualType Ty) const {
8481 
8482   if (getTarget().getTriple().isMusl())
8483     return EmitVAArgForHexagonLinux(CGF, VAListAddr, Ty);
8484 
8485   return EmitVAArgForHexagon(CGF, VAListAddr, Ty);
8486 }
8487 
8488 //===----------------------------------------------------------------------===//
8489 // Lanai ABI Implementation
8490 //===----------------------------------------------------------------------===//
8491 
8492 namespace {
8493 class LanaiABIInfo : public DefaultABIInfo {
8494 public:
8495   LanaiABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
8496 
8497   bool shouldUseInReg(QualType Ty, CCState &State) const;
8498 
8499   void computeInfo(CGFunctionInfo &FI) const override {
8500     CCState State(FI);
8501     // Lanai uses 4 registers to pass arguments unless the function has the
8502     // regparm attribute set.
8503     if (FI.getHasRegParm()) {
8504       State.FreeRegs = FI.getRegParm();
8505     } else {
8506       State.FreeRegs = 4;
8507     }
8508 
8509     if (!getCXXABI().classifyReturnType(FI))
8510       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
8511     for (auto &I : FI.arguments())
8512       I.info = classifyArgumentType(I.type, State);
8513   }
8514 
8515   ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
8516   ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
8517 };
8518 } // end anonymous namespace
8519 
8520 bool LanaiABIInfo::shouldUseInReg(QualType Ty, CCState &State) const {
8521   unsigned Size = getContext().getTypeSize(Ty);
8522   unsigned SizeInRegs = llvm::alignTo(Size, 32U) / 32U;
8523 
8524   if (SizeInRegs == 0)
8525     return false;
8526 
8527   if (SizeInRegs > State.FreeRegs) {
8528     State.FreeRegs = 0;
8529     return false;
8530   }
8531 
8532   State.FreeRegs -= SizeInRegs;
8533 
8534   return true;
8535 }
8536 
8537 ABIArgInfo LanaiABIInfo::getIndirectResult(QualType Ty, bool ByVal,
8538                                            CCState &State) const {
8539   if (!ByVal) {
8540     if (State.FreeRegs) {
8541       --State.FreeRegs; // Non-byval indirects just use one pointer.
8542       return getNaturalAlignIndirectInReg(Ty);
8543     }
8544     return getNaturalAlignIndirect(Ty, false);
8545   }
8546 
8547   // Compute the byval alignment.
8548   const unsigned MinABIStackAlignInBytes = 4;
8549   unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
8550   return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true,
8551                                  /*Realign=*/TypeAlign >
8552                                      MinABIStackAlignInBytes);
8553 }
8554 
8555 ABIArgInfo LanaiABIInfo::classifyArgumentType(QualType Ty,
8556                                               CCState &State) const {
8557   // Check with the C++ ABI first.
8558   const RecordType *RT = Ty->getAs<RecordType>();
8559   if (RT) {
8560     CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
8561     if (RAA == CGCXXABI::RAA_Indirect) {
8562       return getIndirectResult(Ty, /*ByVal=*/false, State);
8563     } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
8564       return getNaturalAlignIndirect(Ty, /*ByRef=*/true);
8565     }
8566   }
8567 
8568   if (isAggregateTypeForABI(Ty)) {
8569     // Structures with flexible arrays are always indirect.
8570     if (RT && RT->getDecl()->hasFlexibleArrayMember())
8571       return getIndirectResult(Ty, /*ByVal=*/true, State);
8572 
8573     // Ignore empty structs/unions.
8574     if (isEmptyRecord(getContext(), Ty, true))
8575       return ABIArgInfo::getIgnore();
8576 
8577     llvm::LLVMContext &LLVMContext = getVMContext();
8578     unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
8579     if (SizeInRegs <= State.FreeRegs) {
8580       llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
8581       SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32);
8582       llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
8583       State.FreeRegs -= SizeInRegs;
8584       return ABIArgInfo::getDirectInReg(Result);
8585     } else {
8586       State.FreeRegs = 0;
8587     }
8588     return getIndirectResult(Ty, true, State);
8589   }
8590 
8591   // Treat an enum type as its underlying type.
8592   if (const auto *EnumTy = Ty->getAs<EnumType>())
8593     Ty = EnumTy->getDecl()->getIntegerType();
8594 
8595   bool InReg = shouldUseInReg(Ty, State);
8596 
8597   // Don't pass >64 bit integers in registers.
8598   if (const auto *EIT = Ty->getAs<ExtIntType>())
8599     if (EIT->getNumBits() > 64)
8600       return getIndirectResult(Ty, /*ByVal=*/true, State);
8601 
8602   if (isPromotableIntegerTypeForABI(Ty)) {
8603     if (InReg)
8604       return ABIArgInfo::getDirectInReg();
8605     return ABIArgInfo::getExtend(Ty);
8606   }
8607   if (InReg)
8608     return ABIArgInfo::getDirectInReg();
8609   return ABIArgInfo::getDirect();
8610 }
8611 
8612 namespace {
8613 class LanaiTargetCodeGenInfo : public TargetCodeGenInfo {
8614 public:
8615   LanaiTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
8616       : TargetCodeGenInfo(std::make_unique<LanaiABIInfo>(CGT)) {}
8617 };
8618 }
8619 
8620 //===----------------------------------------------------------------------===//
8621 // AMDGPU ABI Implementation
8622 //===----------------------------------------------------------------------===//
8623 
8624 namespace {
8625 
8626 class AMDGPUABIInfo final : public DefaultABIInfo {
8627 private:
8628   static const unsigned MaxNumRegsForArgsRet = 16;
8629 
8630   unsigned numRegsForType(QualType Ty) const;
8631 
8632   bool isHomogeneousAggregateBaseType(QualType Ty) const override;
8633   bool isHomogeneousAggregateSmallEnough(const Type *Base,
8634                                          uint64_t Members) const override;
8635 
8636   // Coerce HIP pointer arguments from generic pointers to global ones.
8637   llvm::Type *coerceKernelArgumentType(llvm::Type *Ty, unsigned FromAS,
8638                                        unsigned ToAS) const {
8639     // Structure types.
8640     if (auto STy = dyn_cast<llvm::StructType>(Ty)) {
8641       SmallVector<llvm::Type *, 8> EltTys;
8642       bool Changed = false;
8643       for (auto T : STy->elements()) {
8644         auto NT = coerceKernelArgumentType(T, FromAS, ToAS);
8645         EltTys.push_back(NT);
8646         Changed |= (NT != T);
8647       }
8648       // Skip if there is no change in element types.
8649       if (!Changed)
8650         return STy;
8651       if (STy->hasName())
8652         return llvm::StructType::create(
8653             EltTys, (STy->getName() + ".coerce").str(), STy->isPacked());
8654       return llvm::StructType::get(getVMContext(), EltTys, STy->isPacked());
8655     }
8656     // Array types.
8657     if (auto ATy = dyn_cast<llvm::ArrayType>(Ty)) {
8658       auto T = ATy->getElementType();
8659       auto NT = coerceKernelArgumentType(T, FromAS, ToAS);
8660       // Skip if there is no change in that element type.
8661       if (NT == T)
8662         return ATy;
8663       return llvm::ArrayType::get(NT, ATy->getNumElements());
8664     }
8665     // Single value types.
8666     if (Ty->isPointerTy() && Ty->getPointerAddressSpace() == FromAS)
8667       return llvm::PointerType::get(
8668           cast<llvm::PointerType>(Ty)->getElementType(), ToAS);
8669     return Ty;
8670   }
8671 
8672 public:
8673   explicit AMDGPUABIInfo(CodeGen::CodeGenTypes &CGT) :
8674     DefaultABIInfo(CGT) {}
8675 
8676   ABIArgInfo classifyReturnType(QualType RetTy) const;
8677   ABIArgInfo classifyKernelArgumentType(QualType Ty) const;
8678   ABIArgInfo classifyArgumentType(QualType Ty, unsigned &NumRegsLeft) const;
8679 
8680   void computeInfo(CGFunctionInfo &FI) const override;
8681   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8682                     QualType Ty) const override;
8683 };
8684 
8685 bool AMDGPUABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
8686   return true;
8687 }
8688 
8689 bool AMDGPUABIInfo::isHomogeneousAggregateSmallEnough(
8690   const Type *Base, uint64_t Members) const {
8691   uint32_t NumRegs = (getContext().getTypeSize(Base) + 31) / 32;
8692 
8693   // Homogeneous Aggregates may occupy at most 16 registers.
8694   return Members * NumRegs <= MaxNumRegsForArgsRet;
8695 }
8696 
8697 /// Estimate number of registers the type will use when passed in registers.
8698 unsigned AMDGPUABIInfo::numRegsForType(QualType Ty) const {
8699   unsigned NumRegs = 0;
8700 
8701   if (const VectorType *VT = Ty->getAs<VectorType>()) {
8702     // Compute from the number of elements. The reported size is based on the
8703     // in-memory size, which includes the padding 4th element for 3-vectors.
8704     QualType EltTy = VT->getElementType();
8705     unsigned EltSize = getContext().getTypeSize(EltTy);
8706 
8707     // 16-bit element vectors should be passed as packed.
8708     if (EltSize == 16)
8709       return (VT->getNumElements() + 1) / 2;
8710 
8711     unsigned EltNumRegs = (EltSize + 31) / 32;
8712     return EltNumRegs * VT->getNumElements();
8713   }
8714 
8715   if (const RecordType *RT = Ty->getAs<RecordType>()) {
8716     const RecordDecl *RD = RT->getDecl();
8717     assert(!RD->hasFlexibleArrayMember());
8718 
8719     for (const FieldDecl *Field : RD->fields()) {
8720       QualType FieldTy = Field->getType();
8721       NumRegs += numRegsForType(FieldTy);
8722     }
8723 
8724     return NumRegs;
8725   }
8726 
8727   return (getContext().getTypeSize(Ty) + 31) / 32;
8728 }
8729 
8730 void AMDGPUABIInfo::computeInfo(CGFunctionInfo &FI) const {
8731   llvm::CallingConv::ID CC = FI.getCallingConvention();
8732 
8733   if (!getCXXABI().classifyReturnType(FI))
8734     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
8735 
8736   unsigned NumRegsLeft = MaxNumRegsForArgsRet;
8737   for (auto &Arg : FI.arguments()) {
8738     if (CC == llvm::CallingConv::AMDGPU_KERNEL) {
8739       Arg.info = classifyKernelArgumentType(Arg.type);
8740     } else {
8741       Arg.info = classifyArgumentType(Arg.type, NumRegsLeft);
8742     }
8743   }
8744 }
8745 
8746 Address AMDGPUABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8747                                  QualType Ty) const {
8748   llvm_unreachable("AMDGPU does not support varargs");
8749 }
8750 
8751 ABIArgInfo AMDGPUABIInfo::classifyReturnType(QualType RetTy) const {
8752   if (isAggregateTypeForABI(RetTy)) {
8753     // Records with non-trivial destructors/copy-constructors should not be
8754     // returned by value.
8755     if (!getRecordArgABI(RetTy, getCXXABI())) {
8756       // Ignore empty structs/unions.
8757       if (isEmptyRecord(getContext(), RetTy, true))
8758         return ABIArgInfo::getIgnore();
8759 
8760       // Lower single-element structs to just return a regular value.
8761       if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
8762         return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
8763 
8764       if (const RecordType *RT = RetTy->getAs<RecordType>()) {
8765         const RecordDecl *RD = RT->getDecl();
8766         if (RD->hasFlexibleArrayMember())
8767           return DefaultABIInfo::classifyReturnType(RetTy);
8768       }
8769 
8770       // Pack aggregates <= 4 bytes into single VGPR or pair.
8771       uint64_t Size = getContext().getTypeSize(RetTy);
8772       if (Size <= 16)
8773         return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
8774 
8775       if (Size <= 32)
8776         return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
8777 
8778       if (Size <= 64) {
8779         llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext());
8780         return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2));
8781       }
8782 
8783       if (numRegsForType(RetTy) <= MaxNumRegsForArgsRet)
8784         return ABIArgInfo::getDirect();
8785     }
8786   }
8787 
8788   // Otherwise just do the default thing.
8789   return DefaultABIInfo::classifyReturnType(RetTy);
8790 }
8791 
8792 /// For kernels all parameters are really passed in a special buffer. It doesn't
8793 /// make sense to pass anything byval, so everything must be direct.
8794 ABIArgInfo AMDGPUABIInfo::classifyKernelArgumentType(QualType Ty) const {
8795   Ty = useFirstFieldIfTransparentUnion(Ty);
8796 
8797   // TODO: Can we omit empty structs?
8798 
8799   llvm::Type *LTy = nullptr;
8800   if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
8801     LTy = CGT.ConvertType(QualType(SeltTy, 0));
8802 
8803   if (getContext().getLangOpts().HIP) {
8804     if (!LTy)
8805       LTy = CGT.ConvertType(Ty);
8806     LTy = coerceKernelArgumentType(
8807         LTy, /*FromAS=*/getContext().getTargetAddressSpace(LangAS::Default),
8808         /*ToAS=*/getContext().getTargetAddressSpace(LangAS::cuda_device));
8809   }
8810 
8811   // If we set CanBeFlattened to true, CodeGen will expand the struct to its
8812   // individual elements, which confuses the Clover OpenCL backend; therefore we
8813   // have to set it to false here. Other args of getDirect() are just defaults.
8814   return ABIArgInfo::getDirect(LTy, 0, nullptr, false);
8815 }
8816 
8817 ABIArgInfo AMDGPUABIInfo::classifyArgumentType(QualType Ty,
8818                                                unsigned &NumRegsLeft) const {
8819   assert(NumRegsLeft <= MaxNumRegsForArgsRet && "register estimate underflow");
8820 
8821   Ty = useFirstFieldIfTransparentUnion(Ty);
8822 
8823   if (isAggregateTypeForABI(Ty)) {
8824     // Records with non-trivial destructors/copy-constructors should not be
8825     // passed by value.
8826     if (auto RAA = getRecordArgABI(Ty, getCXXABI()))
8827       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
8828 
8829     // Ignore empty structs/unions.
8830     if (isEmptyRecord(getContext(), Ty, true))
8831       return ABIArgInfo::getIgnore();
8832 
8833     // Lower single-element structs to just pass a regular value. TODO: We
8834     // could do reasonable-size multiple-element structs too, using getExpand(),
8835     // though watch out for things like bitfields.
8836     if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
8837       return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
8838 
8839     if (const RecordType *RT = Ty->getAs<RecordType>()) {
8840       const RecordDecl *RD = RT->getDecl();
8841       if (RD->hasFlexibleArrayMember())
8842         return DefaultABIInfo::classifyArgumentType(Ty);
8843     }
8844 
8845     // Pack aggregates <= 8 bytes into single VGPR or pair.
8846     uint64_t Size = getContext().getTypeSize(Ty);
8847     if (Size <= 64) {
8848       unsigned NumRegs = (Size + 31) / 32;
8849       NumRegsLeft -= std::min(NumRegsLeft, NumRegs);
8850 
8851       if (Size <= 16)
8852         return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
8853 
8854       if (Size <= 32)
8855         return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
8856 
8857       // XXX: Should this be i64 instead, and should the limit increase?
8858       llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext());
8859       return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2));
8860     }
8861 
8862     if (NumRegsLeft > 0) {
8863       unsigned NumRegs = numRegsForType(Ty);
8864       if (NumRegsLeft >= NumRegs) {
8865         NumRegsLeft -= NumRegs;
8866         return ABIArgInfo::getDirect();
8867       }
8868     }
8869   }
8870 
8871   // Otherwise just do the default thing.
8872   ABIArgInfo ArgInfo = DefaultABIInfo::classifyArgumentType(Ty);
8873   if (!ArgInfo.isIndirect()) {
8874     unsigned NumRegs = numRegsForType(Ty);
8875     NumRegsLeft -= std::min(NumRegs, NumRegsLeft);
8876   }
8877 
8878   return ArgInfo;
8879 }
8880 
8881 class AMDGPUTargetCodeGenInfo : public TargetCodeGenInfo {
8882 public:
8883   AMDGPUTargetCodeGenInfo(CodeGenTypes &CGT)
8884       : TargetCodeGenInfo(std::make_unique<AMDGPUABIInfo>(CGT)) {}
8885   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
8886                            CodeGen::CodeGenModule &M) const override;
8887   unsigned getOpenCLKernelCallingConv() const override;
8888 
8889   llvm::Constant *getNullPointer(const CodeGen::CodeGenModule &CGM,
8890       llvm::PointerType *T, QualType QT) const override;
8891 
8892   LangAS getASTAllocaAddressSpace() const override {
8893     return getLangASFromTargetAS(
8894         getABIInfo().getDataLayout().getAllocaAddrSpace());
8895   }
8896   LangAS getGlobalVarAddressSpace(CodeGenModule &CGM,
8897                                   const VarDecl *D) const override;
8898   llvm::SyncScope::ID getLLVMSyncScopeID(const LangOptions &LangOpts,
8899                                          SyncScope Scope,
8900                                          llvm::AtomicOrdering Ordering,
8901                                          llvm::LLVMContext &Ctx) const override;
8902   llvm::Function *
8903   createEnqueuedBlockKernel(CodeGenFunction &CGF,
8904                             llvm::Function *BlockInvokeFunc,
8905                             llvm::Value *BlockLiteral) const override;
8906   bool shouldEmitStaticExternCAliases() const override;
8907   void setCUDAKernelCallingConvention(const FunctionType *&FT) const override;
8908 };
8909 }
8910 
8911 static bool requiresAMDGPUProtectedVisibility(const Decl *D,
8912                                               llvm::GlobalValue *GV) {
8913   if (GV->getVisibility() != llvm::GlobalValue::HiddenVisibility)
8914     return false;
8915 
8916   return D->hasAttr<OpenCLKernelAttr>() ||
8917          (isa<FunctionDecl>(D) && D->hasAttr<CUDAGlobalAttr>()) ||
8918          (isa<VarDecl>(D) &&
8919           (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>() ||
8920            cast<VarDecl>(D)->getType()->isCUDADeviceBuiltinSurfaceType() ||
8921            cast<VarDecl>(D)->getType()->isCUDADeviceBuiltinTextureType()));
8922 }
8923 
8924 void AMDGPUTargetCodeGenInfo::setTargetAttributes(
8925     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
8926   if (requiresAMDGPUProtectedVisibility(D, GV)) {
8927     GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
8928     GV->setDSOLocal(true);
8929   }
8930 
8931   if (GV->isDeclaration())
8932     return;
8933   const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
8934   if (!FD)
8935     return;
8936 
8937   llvm::Function *F = cast<llvm::Function>(GV);
8938 
8939   const auto *ReqdWGS = M.getLangOpts().OpenCL ?
8940     FD->getAttr<ReqdWorkGroupSizeAttr>() : nullptr;
8941 
8942 
8943   const bool IsOpenCLKernel = M.getLangOpts().OpenCL &&
8944                               FD->hasAttr<OpenCLKernelAttr>();
8945   const bool IsHIPKernel = M.getLangOpts().HIP &&
8946                            FD->hasAttr<CUDAGlobalAttr>();
8947   if ((IsOpenCLKernel || IsHIPKernel) &&
8948       (M.getTriple().getOS() == llvm::Triple::AMDHSA))
8949     F->addFnAttr("amdgpu-implicitarg-num-bytes", "56");
8950 
8951   if (IsHIPKernel)
8952     F->addFnAttr("uniform-work-group-size", "true");
8953 
8954 
8955   const auto *FlatWGS = FD->getAttr<AMDGPUFlatWorkGroupSizeAttr>();
8956   if (ReqdWGS || FlatWGS) {
8957     unsigned Min = 0;
8958     unsigned Max = 0;
8959     if (FlatWGS) {
8960       Min = FlatWGS->getMin()
8961                 ->EvaluateKnownConstInt(M.getContext())
8962                 .getExtValue();
8963       Max = FlatWGS->getMax()
8964                 ->EvaluateKnownConstInt(M.getContext())
8965                 .getExtValue();
8966     }
8967     if (ReqdWGS && Min == 0 && Max == 0)
8968       Min = Max = ReqdWGS->getXDim() * ReqdWGS->getYDim() * ReqdWGS->getZDim();
8969 
8970     if (Min != 0) {
8971       assert(Min <= Max && "Min must be less than or equal Max");
8972 
8973       std::string AttrVal = llvm::utostr(Min) + "," + llvm::utostr(Max);
8974       F->addFnAttr("amdgpu-flat-work-group-size", AttrVal);
8975     } else
8976       assert(Max == 0 && "Max must be zero");
8977   } else if (IsOpenCLKernel || IsHIPKernel) {
8978     // By default, restrict the maximum size to a value specified by
8979     // --gpu-max-threads-per-block=n or its default value for HIP.
8980     const unsigned OpenCLDefaultMaxWorkGroupSize = 256;
8981     const unsigned DefaultMaxWorkGroupSize =
8982         IsOpenCLKernel ? OpenCLDefaultMaxWorkGroupSize
8983                        : M.getLangOpts().GPUMaxThreadsPerBlock;
8984     std::string AttrVal =
8985         std::string("1,") + llvm::utostr(DefaultMaxWorkGroupSize);
8986     F->addFnAttr("amdgpu-flat-work-group-size", AttrVal);
8987   }
8988 
8989   if (const auto *Attr = FD->getAttr<AMDGPUWavesPerEUAttr>()) {
8990     unsigned Min =
8991         Attr->getMin()->EvaluateKnownConstInt(M.getContext()).getExtValue();
8992     unsigned Max = Attr->getMax() ? Attr->getMax()
8993                                         ->EvaluateKnownConstInt(M.getContext())
8994                                         .getExtValue()
8995                                   : 0;
8996 
8997     if (Min != 0) {
8998       assert((Max == 0 || Min <= Max) && "Min must be less than or equal Max");
8999 
9000       std::string AttrVal = llvm::utostr(Min);
9001       if (Max != 0)
9002         AttrVal = AttrVal + "," + llvm::utostr(Max);
9003       F->addFnAttr("amdgpu-waves-per-eu", AttrVal);
9004     } else
9005       assert(Max == 0 && "Max must be zero");
9006   }
9007 
9008   if (const auto *Attr = FD->getAttr<AMDGPUNumSGPRAttr>()) {
9009     unsigned NumSGPR = Attr->getNumSGPR();
9010 
9011     if (NumSGPR != 0)
9012       F->addFnAttr("amdgpu-num-sgpr", llvm::utostr(NumSGPR));
9013   }
9014 
9015   if (const auto *Attr = FD->getAttr<AMDGPUNumVGPRAttr>()) {
9016     uint32_t NumVGPR = Attr->getNumVGPR();
9017 
9018     if (NumVGPR != 0)
9019       F->addFnAttr("amdgpu-num-vgpr", llvm::utostr(NumVGPR));
9020   }
9021 }
9022 
9023 unsigned AMDGPUTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
9024   return llvm::CallingConv::AMDGPU_KERNEL;
9025 }
9026 
9027 // Currently LLVM assumes null pointers always have value 0,
9028 // which results in incorrectly transformed IR. Therefore, instead of
9029 // emitting null pointers in private and local address spaces, a null
9030 // pointer in generic address space is emitted which is casted to a
9031 // pointer in local or private address space.
9032 llvm::Constant *AMDGPUTargetCodeGenInfo::getNullPointer(
9033     const CodeGen::CodeGenModule &CGM, llvm::PointerType *PT,
9034     QualType QT) const {
9035   if (CGM.getContext().getTargetNullPointerValue(QT) == 0)
9036     return llvm::ConstantPointerNull::get(PT);
9037 
9038   auto &Ctx = CGM.getContext();
9039   auto NPT = llvm::PointerType::get(PT->getElementType(),
9040       Ctx.getTargetAddressSpace(LangAS::opencl_generic));
9041   return llvm::ConstantExpr::getAddrSpaceCast(
9042       llvm::ConstantPointerNull::get(NPT), PT);
9043 }
9044 
9045 LangAS
9046 AMDGPUTargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM,
9047                                                   const VarDecl *D) const {
9048   assert(!CGM.getLangOpts().OpenCL &&
9049          !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) &&
9050          "Address space agnostic languages only");
9051   LangAS DefaultGlobalAS = getLangASFromTargetAS(
9052       CGM.getContext().getTargetAddressSpace(LangAS::opencl_global));
9053   if (!D)
9054     return DefaultGlobalAS;
9055 
9056   LangAS AddrSpace = D->getType().getAddressSpace();
9057   assert(AddrSpace == LangAS::Default || isTargetAddressSpace(AddrSpace));
9058   if (AddrSpace != LangAS::Default)
9059     return AddrSpace;
9060 
9061   if (CGM.isTypeConstant(D->getType(), false)) {
9062     if (auto ConstAS = CGM.getTarget().getConstantAddressSpace())
9063       return ConstAS.getValue();
9064   }
9065   return DefaultGlobalAS;
9066 }
9067 
9068 llvm::SyncScope::ID
9069 AMDGPUTargetCodeGenInfo::getLLVMSyncScopeID(const LangOptions &LangOpts,
9070                                             SyncScope Scope,
9071                                             llvm::AtomicOrdering Ordering,
9072                                             llvm::LLVMContext &Ctx) const {
9073   std::string Name;
9074   switch (Scope) {
9075   case SyncScope::OpenCLWorkGroup:
9076     Name = "workgroup";
9077     break;
9078   case SyncScope::OpenCLDevice:
9079     Name = "agent";
9080     break;
9081   case SyncScope::OpenCLAllSVMDevices:
9082     Name = "";
9083     break;
9084   case SyncScope::OpenCLSubGroup:
9085     Name = "wavefront";
9086   }
9087 
9088   if (Ordering != llvm::AtomicOrdering::SequentiallyConsistent) {
9089     if (!Name.empty())
9090       Name = Twine(Twine(Name) + Twine("-")).str();
9091 
9092     Name = Twine(Twine(Name) + Twine("one-as")).str();
9093   }
9094 
9095   return Ctx.getOrInsertSyncScopeID(Name);
9096 }
9097 
9098 bool AMDGPUTargetCodeGenInfo::shouldEmitStaticExternCAliases() const {
9099   return false;
9100 }
9101 
9102 void AMDGPUTargetCodeGenInfo::setCUDAKernelCallingConvention(
9103     const FunctionType *&FT) const {
9104   FT = getABIInfo().getContext().adjustFunctionType(
9105       FT, FT->getExtInfo().withCallingConv(CC_OpenCLKernel));
9106 }
9107 
9108 //===----------------------------------------------------------------------===//
9109 // SPARC v8 ABI Implementation.
9110 // Based on the SPARC Compliance Definition version 2.4.1.
9111 //
9112 // Ensures that complex values are passed in registers.
9113 //
9114 namespace {
9115 class SparcV8ABIInfo : public DefaultABIInfo {
9116 public:
9117   SparcV8ABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
9118 
9119 private:
9120   ABIArgInfo classifyReturnType(QualType RetTy) const;
9121   void computeInfo(CGFunctionInfo &FI) const override;
9122 };
9123 } // end anonymous namespace
9124 
9125 
9126 ABIArgInfo
9127 SparcV8ABIInfo::classifyReturnType(QualType Ty) const {
9128   if (Ty->isAnyComplexType()) {
9129     return ABIArgInfo::getDirect();
9130   }
9131   else {
9132     return DefaultABIInfo::classifyReturnType(Ty);
9133   }
9134 }
9135 
9136 void SparcV8ABIInfo::computeInfo(CGFunctionInfo &FI) const {
9137 
9138   FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
9139   for (auto &Arg : FI.arguments())
9140     Arg.info = classifyArgumentType(Arg.type);
9141 }
9142 
9143 namespace {
9144 class SparcV8TargetCodeGenInfo : public TargetCodeGenInfo {
9145 public:
9146   SparcV8TargetCodeGenInfo(CodeGenTypes &CGT)
9147       : TargetCodeGenInfo(std::make_unique<SparcV8ABIInfo>(CGT)) {}
9148 };
9149 } // end anonymous namespace
9150 
9151 //===----------------------------------------------------------------------===//
9152 // SPARC v9 ABI Implementation.
9153 // Based on the SPARC Compliance Definition version 2.4.1.
9154 //
9155 // Function arguments a mapped to a nominal "parameter array" and promoted to
9156 // registers depending on their type. Each argument occupies 8 or 16 bytes in
9157 // the array, structs larger than 16 bytes are passed indirectly.
9158 //
9159 // One case requires special care:
9160 //
9161 //   struct mixed {
9162 //     int i;
9163 //     float f;
9164 //   };
9165 //
9166 // When a struct mixed is passed by value, it only occupies 8 bytes in the
9167 // parameter array, but the int is passed in an integer register, and the float
9168 // is passed in a floating point register. This is represented as two arguments
9169 // with the LLVM IR inreg attribute:
9170 //
9171 //   declare void f(i32 inreg %i, float inreg %f)
9172 //
9173 // The code generator will only allocate 4 bytes from the parameter array for
9174 // the inreg arguments. All other arguments are allocated a multiple of 8
9175 // bytes.
9176 //
9177 namespace {
9178 class SparcV9ABIInfo : public ABIInfo {
9179 public:
9180   SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
9181 
9182 private:
9183   ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
9184   void computeInfo(CGFunctionInfo &FI) const override;
9185   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9186                     QualType Ty) const override;
9187 
9188   // Coercion type builder for structs passed in registers. The coercion type
9189   // serves two purposes:
9190   //
9191   // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
9192   //    in registers.
9193   // 2. Expose aligned floating point elements as first-level elements, so the
9194   //    code generator knows to pass them in floating point registers.
9195   //
9196   // We also compute the InReg flag which indicates that the struct contains
9197   // aligned 32-bit floats.
9198   //
9199   struct CoerceBuilder {
9200     llvm::LLVMContext &Context;
9201     const llvm::DataLayout &DL;
9202     SmallVector<llvm::Type*, 8> Elems;
9203     uint64_t Size;
9204     bool InReg;
9205 
9206     CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
9207       : Context(c), DL(dl), Size(0), InReg(false) {}
9208 
9209     // Pad Elems with integers until Size is ToSize.
9210     void pad(uint64_t ToSize) {
9211       assert(ToSize >= Size && "Cannot remove elements");
9212       if (ToSize == Size)
9213         return;
9214 
9215       // Finish the current 64-bit word.
9216       uint64_t Aligned = llvm::alignTo(Size, 64);
9217       if (Aligned > Size && Aligned <= ToSize) {
9218         Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
9219         Size = Aligned;
9220       }
9221 
9222       // Add whole 64-bit words.
9223       while (Size + 64 <= ToSize) {
9224         Elems.push_back(llvm::Type::getInt64Ty(Context));
9225         Size += 64;
9226       }
9227 
9228       // Final in-word padding.
9229       if (Size < ToSize) {
9230         Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
9231         Size = ToSize;
9232       }
9233     }
9234 
9235     // Add a floating point element at Offset.
9236     void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
9237       // Unaligned floats are treated as integers.
9238       if (Offset % Bits)
9239         return;
9240       // The InReg flag is only required if there are any floats < 64 bits.
9241       if (Bits < 64)
9242         InReg = true;
9243       pad(Offset);
9244       Elems.push_back(Ty);
9245       Size = Offset + Bits;
9246     }
9247 
9248     // Add a struct type to the coercion type, starting at Offset (in bits).
9249     void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
9250       const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
9251       for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
9252         llvm::Type *ElemTy = StrTy->getElementType(i);
9253         uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
9254         switch (ElemTy->getTypeID()) {
9255         case llvm::Type::StructTyID:
9256           addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
9257           break;
9258         case llvm::Type::FloatTyID:
9259           addFloat(ElemOffset, ElemTy, 32);
9260           break;
9261         case llvm::Type::DoubleTyID:
9262           addFloat(ElemOffset, ElemTy, 64);
9263           break;
9264         case llvm::Type::FP128TyID:
9265           addFloat(ElemOffset, ElemTy, 128);
9266           break;
9267         case llvm::Type::PointerTyID:
9268           if (ElemOffset % 64 == 0) {
9269             pad(ElemOffset);
9270             Elems.push_back(ElemTy);
9271             Size += 64;
9272           }
9273           break;
9274         default:
9275           break;
9276         }
9277       }
9278     }
9279 
9280     // Check if Ty is a usable substitute for the coercion type.
9281     bool isUsableType(llvm::StructType *Ty) const {
9282       return llvm::makeArrayRef(Elems) == Ty->elements();
9283     }
9284 
9285     // Get the coercion type as a literal struct type.
9286     llvm::Type *getType() const {
9287       if (Elems.size() == 1)
9288         return Elems.front();
9289       else
9290         return llvm::StructType::get(Context, Elems);
9291     }
9292   };
9293 };
9294 } // end anonymous namespace
9295 
9296 ABIArgInfo
9297 SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
9298   if (Ty->isVoidType())
9299     return ABIArgInfo::getIgnore();
9300 
9301   uint64_t Size = getContext().getTypeSize(Ty);
9302 
9303   // Anything too big to fit in registers is passed with an explicit indirect
9304   // pointer / sret pointer.
9305   if (Size > SizeLimit)
9306     return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
9307 
9308   // Treat an enum type as its underlying type.
9309   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
9310     Ty = EnumTy->getDecl()->getIntegerType();
9311 
9312   // Integer types smaller than a register are extended.
9313   if (Size < 64 && Ty->isIntegerType())
9314     return ABIArgInfo::getExtend(Ty);
9315 
9316   if (const auto *EIT = Ty->getAs<ExtIntType>())
9317     if (EIT->getNumBits() < 64)
9318       return ABIArgInfo::getExtend(Ty);
9319 
9320   // Other non-aggregates go in registers.
9321   if (!isAggregateTypeForABI(Ty))
9322     return ABIArgInfo::getDirect();
9323 
9324   // If a C++ object has either a non-trivial copy constructor or a non-trivial
9325   // destructor, it is passed with an explicit indirect pointer / sret pointer.
9326   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
9327     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
9328 
9329   // This is a small aggregate type that should be passed in registers.
9330   // Build a coercion type from the LLVM struct type.
9331   llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
9332   if (!StrTy)
9333     return ABIArgInfo::getDirect();
9334 
9335   CoerceBuilder CB(getVMContext(), getDataLayout());
9336   CB.addStruct(0, StrTy);
9337   CB.pad(llvm::alignTo(CB.DL.getTypeSizeInBits(StrTy), 64));
9338 
9339   // Try to use the original type for coercion.
9340   llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
9341 
9342   if (CB.InReg)
9343     return ABIArgInfo::getDirectInReg(CoerceTy);
9344   else
9345     return ABIArgInfo::getDirect(CoerceTy);
9346 }
9347 
9348 Address SparcV9ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9349                                   QualType Ty) const {
9350   ABIArgInfo AI = classifyType(Ty, 16 * 8);
9351   llvm::Type *ArgTy = CGT.ConvertType(Ty);
9352   if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
9353     AI.setCoerceToType(ArgTy);
9354 
9355   CharUnits SlotSize = CharUnits::fromQuantity(8);
9356 
9357   CGBuilderTy &Builder = CGF.Builder;
9358   Address Addr(Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
9359   llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
9360 
9361   auto TypeInfo = getContext().getTypeInfoInChars(Ty);
9362 
9363   Address ArgAddr = Address::invalid();
9364   CharUnits Stride;
9365   switch (AI.getKind()) {
9366   case ABIArgInfo::Expand:
9367   case ABIArgInfo::CoerceAndExpand:
9368   case ABIArgInfo::InAlloca:
9369     llvm_unreachable("Unsupported ABI kind for va_arg");
9370 
9371   case ABIArgInfo::Extend: {
9372     Stride = SlotSize;
9373     CharUnits Offset = SlotSize - TypeInfo.first;
9374     ArgAddr = Builder.CreateConstInBoundsByteGEP(Addr, Offset, "extend");
9375     break;
9376   }
9377 
9378   case ABIArgInfo::Direct: {
9379     auto AllocSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
9380     Stride = CharUnits::fromQuantity(AllocSize).alignTo(SlotSize);
9381     ArgAddr = Addr;
9382     break;
9383   }
9384 
9385   case ABIArgInfo::Indirect:
9386     Stride = SlotSize;
9387     ArgAddr = Builder.CreateElementBitCast(Addr, ArgPtrTy, "indirect");
9388     ArgAddr = Address(Builder.CreateLoad(ArgAddr, "indirect.arg"),
9389                       TypeInfo.second);
9390     break;
9391 
9392   case ABIArgInfo::Ignore:
9393     return Address(llvm::UndefValue::get(ArgPtrTy), TypeInfo.second);
9394   }
9395 
9396   // Update VAList.
9397   Address NextPtr = Builder.CreateConstInBoundsByteGEP(Addr, Stride, "ap.next");
9398   Builder.CreateStore(NextPtr.getPointer(), VAListAddr);
9399 
9400   return Builder.CreateBitCast(ArgAddr, ArgPtrTy, "arg.addr");
9401 }
9402 
9403 void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
9404   FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
9405   for (auto &I : FI.arguments())
9406     I.info = classifyType(I.type, 16 * 8);
9407 }
9408 
9409 namespace {
9410 class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
9411 public:
9412   SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
9413       : TargetCodeGenInfo(std::make_unique<SparcV9ABIInfo>(CGT)) {}
9414 
9415   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
9416     return 14;
9417   }
9418 
9419   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
9420                                llvm::Value *Address) const override;
9421 };
9422 } // end anonymous namespace
9423 
9424 bool
9425 SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
9426                                                 llvm::Value *Address) const {
9427   // This is calculated from the LLVM and GCC tables and verified
9428   // against gcc output.  AFAIK all ABIs use the same encoding.
9429 
9430   CodeGen::CGBuilderTy &Builder = CGF.Builder;
9431 
9432   llvm::IntegerType *i8 = CGF.Int8Ty;
9433   llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
9434   llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
9435 
9436   // 0-31: the 8-byte general-purpose registers
9437   AssignToArrayRange(Builder, Address, Eight8, 0, 31);
9438 
9439   // 32-63: f0-31, the 4-byte floating-point registers
9440   AssignToArrayRange(Builder, Address, Four8, 32, 63);
9441 
9442   //   Y   = 64
9443   //   PSR = 65
9444   //   WIM = 66
9445   //   TBR = 67
9446   //   PC  = 68
9447   //   NPC = 69
9448   //   FSR = 70
9449   //   CSR = 71
9450   AssignToArrayRange(Builder, Address, Eight8, 64, 71);
9451 
9452   // 72-87: d0-15, the 8-byte floating-point registers
9453   AssignToArrayRange(Builder, Address, Eight8, 72, 87);
9454 
9455   return false;
9456 }
9457 
9458 // ARC ABI implementation.
9459 namespace {
9460 
9461 class ARCABIInfo : public DefaultABIInfo {
9462 public:
9463   using DefaultABIInfo::DefaultABIInfo;
9464 
9465 private:
9466   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9467                     QualType Ty) const override;
9468 
9469   void updateState(const ABIArgInfo &Info, QualType Ty, CCState &State) const {
9470     if (!State.FreeRegs)
9471       return;
9472     if (Info.isIndirect() && Info.getInReg())
9473       State.FreeRegs--;
9474     else if (Info.isDirect() && Info.getInReg()) {
9475       unsigned sz = (getContext().getTypeSize(Ty) + 31) / 32;
9476       if (sz < State.FreeRegs)
9477         State.FreeRegs -= sz;
9478       else
9479         State.FreeRegs = 0;
9480     }
9481   }
9482 
9483   void computeInfo(CGFunctionInfo &FI) const override {
9484     CCState State(FI);
9485     // ARC uses 8 registers to pass arguments.
9486     State.FreeRegs = 8;
9487 
9488     if (!getCXXABI().classifyReturnType(FI))
9489       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
9490     updateState(FI.getReturnInfo(), FI.getReturnType(), State);
9491     for (auto &I : FI.arguments()) {
9492       I.info = classifyArgumentType(I.type, State.FreeRegs);
9493       updateState(I.info, I.type, State);
9494     }
9495   }
9496 
9497   ABIArgInfo getIndirectByRef(QualType Ty, bool HasFreeRegs) const;
9498   ABIArgInfo getIndirectByValue(QualType Ty) const;
9499   ABIArgInfo classifyArgumentType(QualType Ty, uint8_t FreeRegs) const;
9500   ABIArgInfo classifyReturnType(QualType RetTy) const;
9501 };
9502 
9503 class ARCTargetCodeGenInfo : public TargetCodeGenInfo {
9504 public:
9505   ARCTargetCodeGenInfo(CodeGenTypes &CGT)
9506       : TargetCodeGenInfo(std::make_unique<ARCABIInfo>(CGT)) {}
9507 };
9508 
9509 
9510 ABIArgInfo ARCABIInfo::getIndirectByRef(QualType Ty, bool HasFreeRegs) const {
9511   return HasFreeRegs ? getNaturalAlignIndirectInReg(Ty) :
9512                        getNaturalAlignIndirect(Ty, false);
9513 }
9514 
9515 ABIArgInfo ARCABIInfo::getIndirectByValue(QualType Ty) const {
9516   // Compute the byval alignment.
9517   const unsigned MinABIStackAlignInBytes = 4;
9518   unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
9519   return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true,
9520                                  TypeAlign > MinABIStackAlignInBytes);
9521 }
9522 
9523 Address ARCABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9524                               QualType Ty) const {
9525   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
9526                           getContext().getTypeInfoInChars(Ty),
9527                           CharUnits::fromQuantity(4), true);
9528 }
9529 
9530 ABIArgInfo ARCABIInfo::classifyArgumentType(QualType Ty,
9531                                             uint8_t FreeRegs) const {
9532   // Handle the generic C++ ABI.
9533   const RecordType *RT = Ty->getAs<RecordType>();
9534   if (RT) {
9535     CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
9536     if (RAA == CGCXXABI::RAA_Indirect)
9537       return getIndirectByRef(Ty, FreeRegs > 0);
9538 
9539     if (RAA == CGCXXABI::RAA_DirectInMemory)
9540       return getIndirectByValue(Ty);
9541   }
9542 
9543   // Treat an enum type as its underlying type.
9544   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
9545     Ty = EnumTy->getDecl()->getIntegerType();
9546 
9547   auto SizeInRegs = llvm::alignTo(getContext().getTypeSize(Ty), 32) / 32;
9548 
9549   if (isAggregateTypeForABI(Ty)) {
9550     // Structures with flexible arrays are always indirect.
9551     if (RT && RT->getDecl()->hasFlexibleArrayMember())
9552       return getIndirectByValue(Ty);
9553 
9554     // Ignore empty structs/unions.
9555     if (isEmptyRecord(getContext(), Ty, true))
9556       return ABIArgInfo::getIgnore();
9557 
9558     llvm::LLVMContext &LLVMContext = getVMContext();
9559 
9560     llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
9561     SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32);
9562     llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
9563 
9564     return FreeRegs >= SizeInRegs ?
9565         ABIArgInfo::getDirectInReg(Result) :
9566         ABIArgInfo::getDirect(Result, 0, nullptr, false);
9567   }
9568 
9569   if (const auto *EIT = Ty->getAs<ExtIntType>())
9570     if (EIT->getNumBits() > 64)
9571       return getIndirectByValue(Ty);
9572 
9573   return isPromotableIntegerTypeForABI(Ty)
9574              ? (FreeRegs >= SizeInRegs ? ABIArgInfo::getExtendInReg(Ty)
9575                                        : ABIArgInfo::getExtend(Ty))
9576              : (FreeRegs >= SizeInRegs ? ABIArgInfo::getDirectInReg()
9577                                        : ABIArgInfo::getDirect());
9578 }
9579 
9580 ABIArgInfo ARCABIInfo::classifyReturnType(QualType RetTy) const {
9581   if (RetTy->isAnyComplexType())
9582     return ABIArgInfo::getDirectInReg();
9583 
9584   // Arguments of size > 4 registers are indirect.
9585   auto RetSize = llvm::alignTo(getContext().getTypeSize(RetTy), 32) / 32;
9586   if (RetSize > 4)
9587     return getIndirectByRef(RetTy, /*HasFreeRegs*/ true);
9588 
9589   return DefaultABIInfo::classifyReturnType(RetTy);
9590 }
9591 
9592 } // End anonymous namespace.
9593 
9594 //===----------------------------------------------------------------------===//
9595 // XCore ABI Implementation
9596 //===----------------------------------------------------------------------===//
9597 
9598 namespace {
9599 
9600 /// A SmallStringEnc instance is used to build up the TypeString by passing
9601 /// it by reference between functions that append to it.
9602 typedef llvm::SmallString<128> SmallStringEnc;
9603 
9604 /// TypeStringCache caches the meta encodings of Types.
9605 ///
9606 /// The reason for caching TypeStrings is two fold:
9607 ///   1. To cache a type's encoding for later uses;
9608 ///   2. As a means to break recursive member type inclusion.
9609 ///
9610 /// A cache Entry can have a Status of:
9611 ///   NonRecursive:   The type encoding is not recursive;
9612 ///   Recursive:      The type encoding is recursive;
9613 ///   Incomplete:     An incomplete TypeString;
9614 ///   IncompleteUsed: An incomplete TypeString that has been used in a
9615 ///                   Recursive type encoding.
9616 ///
9617 /// A NonRecursive entry will have all of its sub-members expanded as fully
9618 /// as possible. Whilst it may contain types which are recursive, the type
9619 /// itself is not recursive and thus its encoding may be safely used whenever
9620 /// the type is encountered.
9621 ///
9622 /// A Recursive entry will have all of its sub-members expanded as fully as
9623 /// possible. The type itself is recursive and it may contain other types which
9624 /// are recursive. The Recursive encoding must not be used during the expansion
9625 /// of a recursive type's recursive branch. For simplicity the code uses
9626 /// IncompleteCount to reject all usage of Recursive encodings for member types.
9627 ///
9628 /// An Incomplete entry is always a RecordType and only encodes its
9629 /// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and
9630 /// are placed into the cache during type expansion as a means to identify and
9631 /// handle recursive inclusion of types as sub-members. If there is recursion
9632 /// the entry becomes IncompleteUsed.
9633 ///
9634 /// During the expansion of a RecordType's members:
9635 ///
9636 ///   If the cache contains a NonRecursive encoding for the member type, the
9637 ///   cached encoding is used;
9638 ///
9639 ///   If the cache contains a Recursive encoding for the member type, the
9640 ///   cached encoding is 'Swapped' out, as it may be incorrect, and...
9641 ///
9642 ///   If the member is a RecordType, an Incomplete encoding is placed into the
9643 ///   cache to break potential recursive inclusion of itself as a sub-member;
9644 ///
9645 ///   Once a member RecordType has been expanded, its temporary incomplete
9646 ///   entry is removed from the cache. If a Recursive encoding was swapped out
9647 ///   it is swapped back in;
9648 ///
9649 ///   If an incomplete entry is used to expand a sub-member, the incomplete
9650 ///   entry is marked as IncompleteUsed. The cache keeps count of how many
9651 ///   IncompleteUsed entries it currently contains in IncompleteUsedCount;
9652 ///
9653 ///   If a member's encoding is found to be a NonRecursive or Recursive viz:
9654 ///   IncompleteUsedCount==0, the member's encoding is added to the cache.
9655 ///   Else the member is part of a recursive type and thus the recursion has
9656 ///   been exited too soon for the encoding to be correct for the member.
9657 ///
9658 class TypeStringCache {
9659   enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed};
9660   struct Entry {
9661     std::string Str;     // The encoded TypeString for the type.
9662     enum Status State;   // Information about the encoding in 'Str'.
9663     std::string Swapped; // A temporary place holder for a Recursive encoding
9664                          // during the expansion of RecordType's members.
9665   };
9666   std::map<const IdentifierInfo *, struct Entry> Map;
9667   unsigned IncompleteCount;     // Number of Incomplete entries in the Map.
9668   unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map.
9669 public:
9670   TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {}
9671   void addIncomplete(const IdentifierInfo *ID, std::string StubEnc);
9672   bool removeIncomplete(const IdentifierInfo *ID);
9673   void addIfComplete(const IdentifierInfo *ID, StringRef Str,
9674                      bool IsRecursive);
9675   StringRef lookupStr(const IdentifierInfo *ID);
9676 };
9677 
9678 /// TypeString encodings for enum & union fields must be order.
9679 /// FieldEncoding is a helper for this ordering process.
9680 class FieldEncoding {
9681   bool HasName;
9682   std::string Enc;
9683 public:
9684   FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {}
9685   StringRef str() { return Enc; }
9686   bool operator<(const FieldEncoding &rhs) const {
9687     if (HasName != rhs.HasName) return HasName;
9688     return Enc < rhs.Enc;
9689   }
9690 };
9691 
9692 class XCoreABIInfo : public DefaultABIInfo {
9693 public:
9694   XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
9695   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9696                     QualType Ty) const override;
9697 };
9698 
9699 class XCoreTargetCodeGenInfo : public TargetCodeGenInfo {
9700   mutable TypeStringCache TSC;
9701   void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
9702                     const CodeGen::CodeGenModule &M) const;
9703 
9704 public:
9705   XCoreTargetCodeGenInfo(CodeGenTypes &CGT)
9706       : TargetCodeGenInfo(std::make_unique<XCoreABIInfo>(CGT)) {}
9707   void emitTargetMetadata(CodeGen::CodeGenModule &CGM,
9708                           const llvm::MapVector<GlobalDecl, StringRef>
9709                               &MangledDeclNames) const override;
9710 };
9711 
9712 } // End anonymous namespace.
9713 
9714 // TODO: this implementation is likely now redundant with the default
9715 // EmitVAArg.
9716 Address XCoreABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9717                                 QualType Ty) const {
9718   CGBuilderTy &Builder = CGF.Builder;
9719 
9720   // Get the VAList.
9721   CharUnits SlotSize = CharUnits::fromQuantity(4);
9722   Address AP(Builder.CreateLoad(VAListAddr), SlotSize);
9723 
9724   // Handle the argument.
9725   ABIArgInfo AI = classifyArgumentType(Ty);
9726   CharUnits TypeAlign = getContext().getTypeAlignInChars(Ty);
9727   llvm::Type *ArgTy = CGT.ConvertType(Ty);
9728   if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
9729     AI.setCoerceToType(ArgTy);
9730   llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
9731 
9732   Address Val = Address::invalid();
9733   CharUnits ArgSize = CharUnits::Zero();
9734   switch (AI.getKind()) {
9735   case ABIArgInfo::Expand:
9736   case ABIArgInfo::CoerceAndExpand:
9737   case ABIArgInfo::InAlloca:
9738     llvm_unreachable("Unsupported ABI kind for va_arg");
9739   case ABIArgInfo::Ignore:
9740     Val = Address(llvm::UndefValue::get(ArgPtrTy), TypeAlign);
9741     ArgSize = CharUnits::Zero();
9742     break;
9743   case ABIArgInfo::Extend:
9744   case ABIArgInfo::Direct:
9745     Val = Builder.CreateBitCast(AP, ArgPtrTy);
9746     ArgSize = CharUnits::fromQuantity(
9747                        getDataLayout().getTypeAllocSize(AI.getCoerceToType()));
9748     ArgSize = ArgSize.alignTo(SlotSize);
9749     break;
9750   case ABIArgInfo::Indirect:
9751     Val = Builder.CreateElementBitCast(AP, ArgPtrTy);
9752     Val = Address(Builder.CreateLoad(Val), TypeAlign);
9753     ArgSize = SlotSize;
9754     break;
9755   }
9756 
9757   // Increment the VAList.
9758   if (!ArgSize.isZero()) {
9759     Address APN = Builder.CreateConstInBoundsByteGEP(AP, ArgSize);
9760     Builder.CreateStore(APN.getPointer(), VAListAddr);
9761   }
9762 
9763   return Val;
9764 }
9765 
9766 /// During the expansion of a RecordType, an incomplete TypeString is placed
9767 /// into the cache as a means to identify and break recursion.
9768 /// If there is a Recursive encoding in the cache, it is swapped out and will
9769 /// be reinserted by removeIncomplete().
9770 /// All other types of encoding should have been used rather than arriving here.
9771 void TypeStringCache::addIncomplete(const IdentifierInfo *ID,
9772                                     std::string StubEnc) {
9773   if (!ID)
9774     return;
9775   Entry &E = Map[ID];
9776   assert( (E.Str.empty() || E.State == Recursive) &&
9777          "Incorrectly use of addIncomplete");
9778   assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()");
9779   E.Swapped.swap(E.Str); // swap out the Recursive
9780   E.Str.swap(StubEnc);
9781   E.State = Incomplete;
9782   ++IncompleteCount;
9783 }
9784 
9785 /// Once the RecordType has been expanded, the temporary incomplete TypeString
9786 /// must be removed from the cache.
9787 /// If a Recursive was swapped out by addIncomplete(), it will be replaced.
9788 /// Returns true if the RecordType was defined recursively.
9789 bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) {
9790   if (!ID)
9791     return false;
9792   auto I = Map.find(ID);
9793   assert(I != Map.end() && "Entry not present");
9794   Entry &E = I->second;
9795   assert( (E.State == Incomplete ||
9796            E.State == IncompleteUsed) &&
9797          "Entry must be an incomplete type");
9798   bool IsRecursive = false;
9799   if (E.State == IncompleteUsed) {
9800     // We made use of our Incomplete encoding, thus we are recursive.
9801     IsRecursive = true;
9802     --IncompleteUsedCount;
9803   }
9804   if (E.Swapped.empty())
9805     Map.erase(I);
9806   else {
9807     // Swap the Recursive back.
9808     E.Swapped.swap(E.Str);
9809     E.Swapped.clear();
9810     E.State = Recursive;
9811   }
9812   --IncompleteCount;
9813   return IsRecursive;
9814 }
9815 
9816 /// Add the encoded TypeString to the cache only if it is NonRecursive or
9817 /// Recursive (viz: all sub-members were expanded as fully as possible).
9818 void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str,
9819                                     bool IsRecursive) {
9820   if (!ID || IncompleteUsedCount)
9821     return; // No key or it is is an incomplete sub-type so don't add.
9822   Entry &E = Map[ID];
9823   if (IsRecursive && !E.Str.empty()) {
9824     assert(E.State==Recursive && E.Str.size() == Str.size() &&
9825            "This is not the same Recursive entry");
9826     // The parent container was not recursive after all, so we could have used
9827     // this Recursive sub-member entry after all, but we assumed the worse when
9828     // we started viz: IncompleteCount!=0.
9829     return;
9830   }
9831   assert(E.Str.empty() && "Entry already present");
9832   E.Str = Str.str();
9833   E.State = IsRecursive? Recursive : NonRecursive;
9834 }
9835 
9836 /// Return a cached TypeString encoding for the ID. If there isn't one, or we
9837 /// are recursively expanding a type (IncompleteCount != 0) and the cached
9838 /// encoding is Recursive, return an empty StringRef.
9839 StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) {
9840   if (!ID)
9841     return StringRef();   // We have no key.
9842   auto I = Map.find(ID);
9843   if (I == Map.end())
9844     return StringRef();   // We have no encoding.
9845   Entry &E = I->second;
9846   if (E.State == Recursive && IncompleteCount)
9847     return StringRef();   // We don't use Recursive encodings for member types.
9848 
9849   if (E.State == Incomplete) {
9850     // The incomplete type is being used to break out of recursion.
9851     E.State = IncompleteUsed;
9852     ++IncompleteUsedCount;
9853   }
9854   return E.Str;
9855 }
9856 
9857 /// The XCore ABI includes a type information section that communicates symbol
9858 /// type information to the linker. The linker uses this information to verify
9859 /// safety/correctness of things such as array bound and pointers et al.
9860 /// The ABI only requires C (and XC) language modules to emit TypeStrings.
9861 /// This type information (TypeString) is emitted into meta data for all global
9862 /// symbols: definitions, declarations, functions & variables.
9863 ///
9864 /// The TypeString carries type, qualifier, name, size & value details.
9865 /// Please see 'Tools Development Guide' section 2.16.2 for format details:
9866 /// https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf
9867 /// The output is tested by test/CodeGen/xcore-stringtype.c.
9868 ///
9869 static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
9870                           const CodeGen::CodeGenModule &CGM,
9871                           TypeStringCache &TSC);
9872 
9873 /// XCore uses emitTargetMD to emit TypeString metadata for global symbols.
9874 void XCoreTargetCodeGenInfo::emitTargetMD(
9875     const Decl *D, llvm::GlobalValue *GV,
9876     const CodeGen::CodeGenModule &CGM) const {
9877   SmallStringEnc Enc;
9878   if (getTypeString(Enc, D, CGM, TSC)) {
9879     llvm::LLVMContext &Ctx = CGM.getModule().getContext();
9880     llvm::Metadata *MDVals[] = {llvm::ConstantAsMetadata::get(GV),
9881                                 llvm::MDString::get(Ctx, Enc.str())};
9882     llvm::NamedMDNode *MD =
9883       CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings");
9884     MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
9885   }
9886 }
9887 
9888 void XCoreTargetCodeGenInfo::emitTargetMetadata(
9889     CodeGen::CodeGenModule &CGM,
9890     const llvm::MapVector<GlobalDecl, StringRef> &MangledDeclNames) const {
9891   // Warning, new MangledDeclNames may be appended within this loop.
9892   // We rely on MapVector insertions adding new elements to the end
9893   // of the container.
9894   for (unsigned I = 0; I != MangledDeclNames.size(); ++I) {
9895     auto Val = *(MangledDeclNames.begin() + I);
9896     llvm::GlobalValue *GV = CGM.GetGlobalValue(Val.second);
9897     if (GV) {
9898       const Decl *D = Val.first.getDecl()->getMostRecentDecl();
9899       emitTargetMD(D, GV, CGM);
9900     }
9901   }
9902 }
9903 //===----------------------------------------------------------------------===//
9904 // SPIR ABI Implementation
9905 //===----------------------------------------------------------------------===//
9906 
9907 namespace {
9908 class SPIRTargetCodeGenInfo : public TargetCodeGenInfo {
9909 public:
9910   SPIRTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
9911       : TargetCodeGenInfo(std::make_unique<DefaultABIInfo>(CGT)) {}
9912   unsigned getOpenCLKernelCallingConv() const override;
9913 };
9914 
9915 } // End anonymous namespace.
9916 
9917 namespace clang {
9918 namespace CodeGen {
9919 void computeSPIRKernelABIInfo(CodeGenModule &CGM, CGFunctionInfo &FI) {
9920   DefaultABIInfo SPIRABI(CGM.getTypes());
9921   SPIRABI.computeInfo(FI);
9922 }
9923 }
9924 }
9925 
9926 unsigned SPIRTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
9927   return llvm::CallingConv::SPIR_KERNEL;
9928 }
9929 
9930 static bool appendType(SmallStringEnc &Enc, QualType QType,
9931                        const CodeGen::CodeGenModule &CGM,
9932                        TypeStringCache &TSC);
9933 
9934 /// Helper function for appendRecordType().
9935 /// Builds a SmallVector containing the encoded field types in declaration
9936 /// order.
9937 static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE,
9938                              const RecordDecl *RD,
9939                              const CodeGen::CodeGenModule &CGM,
9940                              TypeStringCache &TSC) {
9941   for (const auto *Field : RD->fields()) {
9942     SmallStringEnc Enc;
9943     Enc += "m(";
9944     Enc += Field->getName();
9945     Enc += "){";
9946     if (Field->isBitField()) {
9947       Enc += "b(";
9948       llvm::raw_svector_ostream OS(Enc);
9949       OS << Field->getBitWidthValue(CGM.getContext());
9950       Enc += ':';
9951     }
9952     if (!appendType(Enc, Field->getType(), CGM, TSC))
9953       return false;
9954     if (Field->isBitField())
9955       Enc += ')';
9956     Enc += '}';
9957     FE.emplace_back(!Field->getName().empty(), Enc);
9958   }
9959   return true;
9960 }
9961 
9962 /// Appends structure and union types to Enc and adds encoding to cache.
9963 /// Recursively calls appendType (via extractFieldType) for each field.
9964 /// Union types have their fields ordered according to the ABI.
9965 static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT,
9966                              const CodeGen::CodeGenModule &CGM,
9967                              TypeStringCache &TSC, const IdentifierInfo *ID) {
9968   // Append the cached TypeString if we have one.
9969   StringRef TypeString = TSC.lookupStr(ID);
9970   if (!TypeString.empty()) {
9971     Enc += TypeString;
9972     return true;
9973   }
9974 
9975   // Start to emit an incomplete TypeString.
9976   size_t Start = Enc.size();
9977   Enc += (RT->isUnionType()? 'u' : 's');
9978   Enc += '(';
9979   if (ID)
9980     Enc += ID->getName();
9981   Enc += "){";
9982 
9983   // We collect all encoded fields and order as necessary.
9984   bool IsRecursive = false;
9985   const RecordDecl *RD = RT->getDecl()->getDefinition();
9986   if (RD && !RD->field_empty()) {
9987     // An incomplete TypeString stub is placed in the cache for this RecordType
9988     // so that recursive calls to this RecordType will use it whilst building a
9989     // complete TypeString for this RecordType.
9990     SmallVector<FieldEncoding, 16> FE;
9991     std::string StubEnc(Enc.substr(Start).str());
9992     StubEnc += '}';  // StubEnc now holds a valid incomplete TypeString.
9993     TSC.addIncomplete(ID, std::move(StubEnc));
9994     if (!extractFieldType(FE, RD, CGM, TSC)) {
9995       (void) TSC.removeIncomplete(ID);
9996       return false;
9997     }
9998     IsRecursive = TSC.removeIncomplete(ID);
9999     // The ABI requires unions to be sorted but not structures.
10000     // See FieldEncoding::operator< for sort algorithm.
10001     if (RT->isUnionType())
10002       llvm::sort(FE);
10003     // We can now complete the TypeString.
10004     unsigned E = FE.size();
10005     for (unsigned I = 0; I != E; ++I) {
10006       if (I)
10007         Enc += ',';
10008       Enc += FE[I].str();
10009     }
10010   }
10011   Enc += '}';
10012   TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive);
10013   return true;
10014 }
10015 
10016 /// Appends enum types to Enc and adds the encoding to the cache.
10017 static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET,
10018                            TypeStringCache &TSC,
10019                            const IdentifierInfo *ID) {
10020   // Append the cached TypeString if we have one.
10021   StringRef TypeString = TSC.lookupStr(ID);
10022   if (!TypeString.empty()) {
10023     Enc += TypeString;
10024     return true;
10025   }
10026 
10027   size_t Start = Enc.size();
10028   Enc += "e(";
10029   if (ID)
10030     Enc += ID->getName();
10031   Enc += "){";
10032 
10033   // We collect all encoded enumerations and order them alphanumerically.
10034   if (const EnumDecl *ED = ET->getDecl()->getDefinition()) {
10035     SmallVector<FieldEncoding, 16> FE;
10036     for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E;
10037          ++I) {
10038       SmallStringEnc EnumEnc;
10039       EnumEnc += "m(";
10040       EnumEnc += I->getName();
10041       EnumEnc += "){";
10042       I->getInitVal().toString(EnumEnc);
10043       EnumEnc += '}';
10044       FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc));
10045     }
10046     llvm::sort(FE);
10047     unsigned E = FE.size();
10048     for (unsigned I = 0; I != E; ++I) {
10049       if (I)
10050         Enc += ',';
10051       Enc += FE[I].str();
10052     }
10053   }
10054   Enc += '}';
10055   TSC.addIfComplete(ID, Enc.substr(Start), false);
10056   return true;
10057 }
10058 
10059 /// Appends type's qualifier to Enc.
10060 /// This is done prior to appending the type's encoding.
10061 static void appendQualifier(SmallStringEnc &Enc, QualType QT) {
10062   // Qualifiers are emitted in alphabetical order.
10063   static const char *const Table[]={"","c:","r:","cr:","v:","cv:","rv:","crv:"};
10064   int Lookup = 0;
10065   if (QT.isConstQualified())
10066     Lookup += 1<<0;
10067   if (QT.isRestrictQualified())
10068     Lookup += 1<<1;
10069   if (QT.isVolatileQualified())
10070     Lookup += 1<<2;
10071   Enc += Table[Lookup];
10072 }
10073 
10074 /// Appends built-in types to Enc.
10075 static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) {
10076   const char *EncType;
10077   switch (BT->getKind()) {
10078     case BuiltinType::Void:
10079       EncType = "0";
10080       break;
10081     case BuiltinType::Bool:
10082       EncType = "b";
10083       break;
10084     case BuiltinType::Char_U:
10085       EncType = "uc";
10086       break;
10087     case BuiltinType::UChar:
10088       EncType = "uc";
10089       break;
10090     case BuiltinType::SChar:
10091       EncType = "sc";
10092       break;
10093     case BuiltinType::UShort:
10094       EncType = "us";
10095       break;
10096     case BuiltinType::Short:
10097       EncType = "ss";
10098       break;
10099     case BuiltinType::UInt:
10100       EncType = "ui";
10101       break;
10102     case BuiltinType::Int:
10103       EncType = "si";
10104       break;
10105     case BuiltinType::ULong:
10106       EncType = "ul";
10107       break;
10108     case BuiltinType::Long:
10109       EncType = "sl";
10110       break;
10111     case BuiltinType::ULongLong:
10112       EncType = "ull";
10113       break;
10114     case BuiltinType::LongLong:
10115       EncType = "sll";
10116       break;
10117     case BuiltinType::Float:
10118       EncType = "ft";
10119       break;
10120     case BuiltinType::Double:
10121       EncType = "d";
10122       break;
10123     case BuiltinType::LongDouble:
10124       EncType = "ld";
10125       break;
10126     default:
10127       return false;
10128   }
10129   Enc += EncType;
10130   return true;
10131 }
10132 
10133 /// Appends a pointer encoding to Enc before calling appendType for the pointee.
10134 static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT,
10135                               const CodeGen::CodeGenModule &CGM,
10136                               TypeStringCache &TSC) {
10137   Enc += "p(";
10138   if (!appendType(Enc, PT->getPointeeType(), CGM, TSC))
10139     return false;
10140   Enc += ')';
10141   return true;
10142 }
10143 
10144 /// Appends array encoding to Enc before calling appendType for the element.
10145 static bool appendArrayType(SmallStringEnc &Enc, QualType QT,
10146                             const ArrayType *AT,
10147                             const CodeGen::CodeGenModule &CGM,
10148                             TypeStringCache &TSC, StringRef NoSizeEnc) {
10149   if (AT->getSizeModifier() != ArrayType::Normal)
10150     return false;
10151   Enc += "a(";
10152   if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
10153     CAT->getSize().toStringUnsigned(Enc);
10154   else
10155     Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "".
10156   Enc += ':';
10157   // The Qualifiers should be attached to the type rather than the array.
10158   appendQualifier(Enc, QT);
10159   if (!appendType(Enc, AT->getElementType(), CGM, TSC))
10160     return false;
10161   Enc += ')';
10162   return true;
10163 }
10164 
10165 /// Appends a function encoding to Enc, calling appendType for the return type
10166 /// and the arguments.
10167 static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT,
10168                              const CodeGen::CodeGenModule &CGM,
10169                              TypeStringCache &TSC) {
10170   Enc += "f{";
10171   if (!appendType(Enc, FT->getReturnType(), CGM, TSC))
10172     return false;
10173   Enc += "}(";
10174   if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) {
10175     // N.B. we are only interested in the adjusted param types.
10176     auto I = FPT->param_type_begin();
10177     auto E = FPT->param_type_end();
10178     if (I != E) {
10179       do {
10180         if (!appendType(Enc, *I, CGM, TSC))
10181           return false;
10182         ++I;
10183         if (I != E)
10184           Enc += ',';
10185       } while (I != E);
10186       if (FPT->isVariadic())
10187         Enc += ",va";
10188     } else {
10189       if (FPT->isVariadic())
10190         Enc += "va";
10191       else
10192         Enc += '0';
10193     }
10194   }
10195   Enc += ')';
10196   return true;
10197 }
10198 
10199 /// Handles the type's qualifier before dispatching a call to handle specific
10200 /// type encodings.
10201 static bool appendType(SmallStringEnc &Enc, QualType QType,
10202                        const CodeGen::CodeGenModule &CGM,
10203                        TypeStringCache &TSC) {
10204 
10205   QualType QT = QType.getCanonicalType();
10206 
10207   if (const ArrayType *AT = QT->getAsArrayTypeUnsafe())
10208     // The Qualifiers should be attached to the type rather than the array.
10209     // Thus we don't call appendQualifier() here.
10210     return appendArrayType(Enc, QT, AT, CGM, TSC, "");
10211 
10212   appendQualifier(Enc, QT);
10213 
10214   if (const BuiltinType *BT = QT->getAs<BuiltinType>())
10215     return appendBuiltinType(Enc, BT);
10216 
10217   if (const PointerType *PT = QT->getAs<PointerType>())
10218     return appendPointerType(Enc, PT, CGM, TSC);
10219 
10220   if (const EnumType *ET = QT->getAs<EnumType>())
10221     return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier());
10222 
10223   if (const RecordType *RT = QT->getAsStructureType())
10224     return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
10225 
10226   if (const RecordType *RT = QT->getAsUnionType())
10227     return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
10228 
10229   if (const FunctionType *FT = QT->getAs<FunctionType>())
10230     return appendFunctionType(Enc, FT, CGM, TSC);
10231 
10232   return false;
10233 }
10234 
10235 static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
10236                           const CodeGen::CodeGenModule &CGM,
10237                           TypeStringCache &TSC) {
10238   if (!D)
10239     return false;
10240 
10241   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
10242     if (FD->getLanguageLinkage() != CLanguageLinkage)
10243       return false;
10244     return appendType(Enc, FD->getType(), CGM, TSC);
10245   }
10246 
10247   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
10248     if (VD->getLanguageLinkage() != CLanguageLinkage)
10249       return false;
10250     QualType QT = VD->getType().getCanonicalType();
10251     if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) {
10252       // Global ArrayTypes are given a size of '*' if the size is unknown.
10253       // The Qualifiers should be attached to the type rather than the array.
10254       // Thus we don't call appendQualifier() here.
10255       return appendArrayType(Enc, QT, AT, CGM, TSC, "*");
10256     }
10257     return appendType(Enc, QT, CGM, TSC);
10258   }
10259   return false;
10260 }
10261 
10262 //===----------------------------------------------------------------------===//
10263 // RISCV ABI Implementation
10264 //===----------------------------------------------------------------------===//
10265 
10266 namespace {
10267 class RISCVABIInfo : public DefaultABIInfo {
10268 private:
10269   // Size of the integer ('x') registers in bits.
10270   unsigned XLen;
10271   // Size of the floating point ('f') registers in bits. Note that the target
10272   // ISA might have a wider FLen than the selected ABI (e.g. an RV32IF target
10273   // with soft float ABI has FLen==0).
10274   unsigned FLen;
10275   static const int NumArgGPRs = 8;
10276   static const int NumArgFPRs = 8;
10277   bool detectFPCCEligibleStructHelper(QualType Ty, CharUnits CurOff,
10278                                       llvm::Type *&Field1Ty,
10279                                       CharUnits &Field1Off,
10280                                       llvm::Type *&Field2Ty,
10281                                       CharUnits &Field2Off) const;
10282 
10283 public:
10284   RISCVABIInfo(CodeGen::CodeGenTypes &CGT, unsigned XLen, unsigned FLen)
10285       : DefaultABIInfo(CGT), XLen(XLen), FLen(FLen) {}
10286 
10287   // DefaultABIInfo's classifyReturnType and classifyArgumentType are
10288   // non-virtual, but computeInfo is virtual, so we overload it.
10289   void computeInfo(CGFunctionInfo &FI) const override;
10290 
10291   ABIArgInfo classifyArgumentType(QualType Ty, bool IsFixed, int &ArgGPRsLeft,
10292                                   int &ArgFPRsLeft) const;
10293   ABIArgInfo classifyReturnType(QualType RetTy) const;
10294 
10295   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
10296                     QualType Ty) const override;
10297 
10298   ABIArgInfo extendType(QualType Ty) const;
10299 
10300   bool detectFPCCEligibleStruct(QualType Ty, llvm::Type *&Field1Ty,
10301                                 CharUnits &Field1Off, llvm::Type *&Field2Ty,
10302                                 CharUnits &Field2Off, int &NeededArgGPRs,
10303                                 int &NeededArgFPRs) const;
10304   ABIArgInfo coerceAndExpandFPCCEligibleStruct(llvm::Type *Field1Ty,
10305                                                CharUnits Field1Off,
10306                                                llvm::Type *Field2Ty,
10307                                                CharUnits Field2Off) const;
10308 };
10309 } // end anonymous namespace
10310 
10311 void RISCVABIInfo::computeInfo(CGFunctionInfo &FI) const {
10312   QualType RetTy = FI.getReturnType();
10313   if (!getCXXABI().classifyReturnType(FI))
10314     FI.getReturnInfo() = classifyReturnType(RetTy);
10315 
10316   // IsRetIndirect is true if classifyArgumentType indicated the value should
10317   // be passed indirect, or if the type size is a scalar greater than 2*XLen
10318   // and not a complex type with elements <= FLen. e.g. fp128 is passed direct
10319   // in LLVM IR, relying on the backend lowering code to rewrite the argument
10320   // list and pass indirectly on RV32.
10321   bool IsRetIndirect = FI.getReturnInfo().getKind() == ABIArgInfo::Indirect;
10322   if (!IsRetIndirect && RetTy->isScalarType() &&
10323       getContext().getTypeSize(RetTy) > (2 * XLen)) {
10324     if (RetTy->isComplexType() && FLen) {
10325       QualType EltTy = RetTy->getAs<ComplexType>()->getElementType();
10326       IsRetIndirect = getContext().getTypeSize(EltTy) > FLen;
10327     } else {
10328       // This is a normal scalar > 2*XLen, such as fp128 on RV32.
10329       IsRetIndirect = true;
10330     }
10331   }
10332 
10333   // We must track the number of GPRs used in order to conform to the RISC-V
10334   // ABI, as integer scalars passed in registers should have signext/zeroext
10335   // when promoted, but are anyext if passed on the stack. As GPR usage is
10336   // different for variadic arguments, we must also track whether we are
10337   // examining a vararg or not.
10338   int ArgGPRsLeft = IsRetIndirect ? NumArgGPRs - 1 : NumArgGPRs;
10339   int ArgFPRsLeft = FLen ? NumArgFPRs : 0;
10340   int NumFixedArgs = FI.getNumRequiredArgs();
10341 
10342   int ArgNum = 0;
10343   for (auto &ArgInfo : FI.arguments()) {
10344     bool IsFixed = ArgNum < NumFixedArgs;
10345     ArgInfo.info =
10346         classifyArgumentType(ArgInfo.type, IsFixed, ArgGPRsLeft, ArgFPRsLeft);
10347     ArgNum++;
10348   }
10349 }
10350 
10351 // Returns true if the struct is a potential candidate for the floating point
10352 // calling convention. If this function returns true, the caller is
10353 // responsible for checking that if there is only a single field then that
10354 // field is a float.
10355 bool RISCVABIInfo::detectFPCCEligibleStructHelper(QualType Ty, CharUnits CurOff,
10356                                                   llvm::Type *&Field1Ty,
10357                                                   CharUnits &Field1Off,
10358                                                   llvm::Type *&Field2Ty,
10359                                                   CharUnits &Field2Off) const {
10360   bool IsInt = Ty->isIntegralOrEnumerationType();
10361   bool IsFloat = Ty->isRealFloatingType();
10362 
10363   if (IsInt || IsFloat) {
10364     uint64_t Size = getContext().getTypeSize(Ty);
10365     if (IsInt && Size > XLen)
10366       return false;
10367     // Can't be eligible if larger than the FP registers. Half precision isn't
10368     // currently supported on RISC-V and the ABI hasn't been confirmed, so
10369     // default to the integer ABI in that case.
10370     if (IsFloat && (Size > FLen || Size < 32))
10371       return false;
10372     // Can't be eligible if an integer type was already found (int+int pairs
10373     // are not eligible).
10374     if (IsInt && Field1Ty && Field1Ty->isIntegerTy())
10375       return false;
10376     if (!Field1Ty) {
10377       Field1Ty = CGT.ConvertType(Ty);
10378       Field1Off = CurOff;
10379       return true;
10380     }
10381     if (!Field2Ty) {
10382       Field2Ty = CGT.ConvertType(Ty);
10383       Field2Off = CurOff;
10384       return true;
10385     }
10386     return false;
10387   }
10388 
10389   if (auto CTy = Ty->getAs<ComplexType>()) {
10390     if (Field1Ty)
10391       return false;
10392     QualType EltTy = CTy->getElementType();
10393     if (getContext().getTypeSize(EltTy) > FLen)
10394       return false;
10395     Field1Ty = CGT.ConvertType(EltTy);
10396     Field1Off = CurOff;
10397     Field2Ty = Field1Ty;
10398     Field2Off = Field1Off + getContext().getTypeSizeInChars(EltTy);
10399     return true;
10400   }
10401 
10402   if (const ConstantArrayType *ATy = getContext().getAsConstantArrayType(Ty)) {
10403     uint64_t ArraySize = ATy->getSize().getZExtValue();
10404     QualType EltTy = ATy->getElementType();
10405     CharUnits EltSize = getContext().getTypeSizeInChars(EltTy);
10406     for (uint64_t i = 0; i < ArraySize; ++i) {
10407       bool Ret = detectFPCCEligibleStructHelper(EltTy, CurOff, Field1Ty,
10408                                                 Field1Off, Field2Ty, Field2Off);
10409       if (!Ret)
10410         return false;
10411       CurOff += EltSize;
10412     }
10413     return true;
10414   }
10415 
10416   if (const auto *RTy = Ty->getAs<RecordType>()) {
10417     // Structures with either a non-trivial destructor or a non-trivial
10418     // copy constructor are not eligible for the FP calling convention.
10419     if (getRecordArgABI(Ty, CGT.getCXXABI()))
10420       return false;
10421     if (isEmptyRecord(getContext(), Ty, true))
10422       return true;
10423     const RecordDecl *RD = RTy->getDecl();
10424     // Unions aren't eligible unless they're empty (which is caught above).
10425     if (RD->isUnion())
10426       return false;
10427     int ZeroWidthBitFieldCount = 0;
10428     for (const FieldDecl *FD : RD->fields()) {
10429       const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
10430       uint64_t FieldOffInBits = Layout.getFieldOffset(FD->getFieldIndex());
10431       QualType QTy = FD->getType();
10432       if (FD->isBitField()) {
10433         unsigned BitWidth = FD->getBitWidthValue(getContext());
10434         // Allow a bitfield with a type greater than XLen as long as the
10435         // bitwidth is XLen or less.
10436         if (getContext().getTypeSize(QTy) > XLen && BitWidth <= XLen)
10437           QTy = getContext().getIntTypeForBitwidth(XLen, false);
10438         if (BitWidth == 0) {
10439           ZeroWidthBitFieldCount++;
10440           continue;
10441         }
10442       }
10443 
10444       bool Ret = detectFPCCEligibleStructHelper(
10445           QTy, CurOff + getContext().toCharUnitsFromBits(FieldOffInBits),
10446           Field1Ty, Field1Off, Field2Ty, Field2Off);
10447       if (!Ret)
10448         return false;
10449 
10450       // As a quirk of the ABI, zero-width bitfields aren't ignored for fp+fp
10451       // or int+fp structs, but are ignored for a struct with an fp field and
10452       // any number of zero-width bitfields.
10453       if (Field2Ty && ZeroWidthBitFieldCount > 0)
10454         return false;
10455     }
10456     return Field1Ty != nullptr;
10457   }
10458 
10459   return false;
10460 }
10461 
10462 // Determine if a struct is eligible for passing according to the floating
10463 // point calling convention (i.e., when flattened it contains a single fp
10464 // value, fp+fp, or int+fp of appropriate size). If so, NeededArgFPRs and
10465 // NeededArgGPRs are incremented appropriately.
10466 bool RISCVABIInfo::detectFPCCEligibleStruct(QualType Ty, llvm::Type *&Field1Ty,
10467                                             CharUnits &Field1Off,
10468                                             llvm::Type *&Field2Ty,
10469                                             CharUnits &Field2Off,
10470                                             int &NeededArgGPRs,
10471                                             int &NeededArgFPRs) const {
10472   Field1Ty = nullptr;
10473   Field2Ty = nullptr;
10474   NeededArgGPRs = 0;
10475   NeededArgFPRs = 0;
10476   bool IsCandidate = detectFPCCEligibleStructHelper(
10477       Ty, CharUnits::Zero(), Field1Ty, Field1Off, Field2Ty, Field2Off);
10478   // Not really a candidate if we have a single int but no float.
10479   if (Field1Ty && !Field2Ty && !Field1Ty->isFloatingPointTy())
10480     return false;
10481   if (!IsCandidate)
10482     return false;
10483   if (Field1Ty && Field1Ty->isFloatingPointTy())
10484     NeededArgFPRs++;
10485   else if (Field1Ty)
10486     NeededArgGPRs++;
10487   if (Field2Ty && Field2Ty->isFloatingPointTy())
10488     NeededArgFPRs++;
10489   else if (Field2Ty)
10490     NeededArgGPRs++;
10491   return true;
10492 }
10493 
10494 // Call getCoerceAndExpand for the two-element flattened struct described by
10495 // Field1Ty, Field1Off, Field2Ty, Field2Off. This method will create an
10496 // appropriate coerceToType and unpaddedCoerceToType.
10497 ABIArgInfo RISCVABIInfo::coerceAndExpandFPCCEligibleStruct(
10498     llvm::Type *Field1Ty, CharUnits Field1Off, llvm::Type *Field2Ty,
10499     CharUnits Field2Off) const {
10500   SmallVector<llvm::Type *, 3> CoerceElts;
10501   SmallVector<llvm::Type *, 2> UnpaddedCoerceElts;
10502   if (!Field1Off.isZero())
10503     CoerceElts.push_back(llvm::ArrayType::get(
10504         llvm::Type::getInt8Ty(getVMContext()), Field1Off.getQuantity()));
10505 
10506   CoerceElts.push_back(Field1Ty);
10507   UnpaddedCoerceElts.push_back(Field1Ty);
10508 
10509   if (!Field2Ty) {
10510     return ABIArgInfo::getCoerceAndExpand(
10511         llvm::StructType::get(getVMContext(), CoerceElts, !Field1Off.isZero()),
10512         UnpaddedCoerceElts[0]);
10513   }
10514 
10515   CharUnits Field2Align =
10516       CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(Field2Ty));
10517   CharUnits Field1End = Field1Off +
10518       CharUnits::fromQuantity(getDataLayout().getTypeStoreSize(Field1Ty));
10519   CharUnits Field2OffNoPadNoPack = Field1End.alignTo(Field2Align);
10520 
10521   CharUnits Padding = CharUnits::Zero();
10522   if (Field2Off > Field2OffNoPadNoPack)
10523     Padding = Field2Off - Field2OffNoPadNoPack;
10524   else if (Field2Off != Field2Align && Field2Off > Field1End)
10525     Padding = Field2Off - Field1End;
10526 
10527   bool IsPacked = !Field2Off.isMultipleOf(Field2Align);
10528 
10529   if (!Padding.isZero())
10530     CoerceElts.push_back(llvm::ArrayType::get(
10531         llvm::Type::getInt8Ty(getVMContext()), Padding.getQuantity()));
10532 
10533   CoerceElts.push_back(Field2Ty);
10534   UnpaddedCoerceElts.push_back(Field2Ty);
10535 
10536   auto CoerceToType =
10537       llvm::StructType::get(getVMContext(), CoerceElts, IsPacked);
10538   auto UnpaddedCoerceToType =
10539       llvm::StructType::get(getVMContext(), UnpaddedCoerceElts, IsPacked);
10540 
10541   return ABIArgInfo::getCoerceAndExpand(CoerceToType, UnpaddedCoerceToType);
10542 }
10543 
10544 ABIArgInfo RISCVABIInfo::classifyArgumentType(QualType Ty, bool IsFixed,
10545                                               int &ArgGPRsLeft,
10546                                               int &ArgFPRsLeft) const {
10547   assert(ArgGPRsLeft <= NumArgGPRs && "Arg GPR tracking underflow");
10548   Ty = useFirstFieldIfTransparentUnion(Ty);
10549 
10550   // Structures with either a non-trivial destructor or a non-trivial
10551   // copy constructor are always passed indirectly.
10552   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
10553     if (ArgGPRsLeft)
10554       ArgGPRsLeft -= 1;
10555     return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA ==
10556                                            CGCXXABI::RAA_DirectInMemory);
10557   }
10558 
10559   // Ignore empty structs/unions.
10560   if (isEmptyRecord(getContext(), Ty, true))
10561     return ABIArgInfo::getIgnore();
10562 
10563   uint64_t Size = getContext().getTypeSize(Ty);
10564 
10565   // Pass floating point values via FPRs if possible.
10566   if (IsFixed && Ty->isFloatingType() && !Ty->isComplexType() &&
10567       FLen >= Size && ArgFPRsLeft) {
10568     ArgFPRsLeft--;
10569     return ABIArgInfo::getDirect();
10570   }
10571 
10572   // Complex types for the hard float ABI must be passed direct rather than
10573   // using CoerceAndExpand.
10574   if (IsFixed && Ty->isComplexType() && FLen && ArgFPRsLeft >= 2) {
10575     QualType EltTy = Ty->castAs<ComplexType>()->getElementType();
10576     if (getContext().getTypeSize(EltTy) <= FLen) {
10577       ArgFPRsLeft -= 2;
10578       return ABIArgInfo::getDirect();
10579     }
10580   }
10581 
10582   if (IsFixed && FLen && Ty->isStructureOrClassType()) {
10583     llvm::Type *Field1Ty = nullptr;
10584     llvm::Type *Field2Ty = nullptr;
10585     CharUnits Field1Off = CharUnits::Zero();
10586     CharUnits Field2Off = CharUnits::Zero();
10587     int NeededArgGPRs;
10588     int NeededArgFPRs;
10589     bool IsCandidate =
10590         detectFPCCEligibleStruct(Ty, Field1Ty, Field1Off, Field2Ty, Field2Off,
10591                                  NeededArgGPRs, NeededArgFPRs);
10592     if (IsCandidate && NeededArgGPRs <= ArgGPRsLeft &&
10593         NeededArgFPRs <= ArgFPRsLeft) {
10594       ArgGPRsLeft -= NeededArgGPRs;
10595       ArgFPRsLeft -= NeededArgFPRs;
10596       return coerceAndExpandFPCCEligibleStruct(Field1Ty, Field1Off, Field2Ty,
10597                                                Field2Off);
10598     }
10599   }
10600 
10601   uint64_t NeededAlign = getContext().getTypeAlign(Ty);
10602   bool MustUseStack = false;
10603   // Determine the number of GPRs needed to pass the current argument
10604   // according to the ABI. 2*XLen-aligned varargs are passed in "aligned"
10605   // register pairs, so may consume 3 registers.
10606   int NeededArgGPRs = 1;
10607   if (!IsFixed && NeededAlign == 2 * XLen)
10608     NeededArgGPRs = 2 + (ArgGPRsLeft % 2);
10609   else if (Size > XLen && Size <= 2 * XLen)
10610     NeededArgGPRs = 2;
10611 
10612   if (NeededArgGPRs > ArgGPRsLeft) {
10613     MustUseStack = true;
10614     NeededArgGPRs = ArgGPRsLeft;
10615   }
10616 
10617   ArgGPRsLeft -= NeededArgGPRs;
10618 
10619   if (!isAggregateTypeForABI(Ty) && !Ty->isVectorType()) {
10620     // Treat an enum type as its underlying type.
10621     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
10622       Ty = EnumTy->getDecl()->getIntegerType();
10623 
10624     // All integral types are promoted to XLen width, unless passed on the
10625     // stack.
10626     if (Size < XLen && Ty->isIntegralOrEnumerationType() && !MustUseStack) {
10627       return extendType(Ty);
10628     }
10629 
10630     if (const auto *EIT = Ty->getAs<ExtIntType>()) {
10631       if (EIT->getNumBits() < XLen && !MustUseStack)
10632         return extendType(Ty);
10633       if (EIT->getNumBits() > 128 ||
10634           (!getContext().getTargetInfo().hasInt128Type() &&
10635            EIT->getNumBits() > 64))
10636         return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
10637     }
10638 
10639     return ABIArgInfo::getDirect();
10640   }
10641 
10642   // Aggregates which are <= 2*XLen will be passed in registers if possible,
10643   // so coerce to integers.
10644   if (Size <= 2 * XLen) {
10645     unsigned Alignment = getContext().getTypeAlign(Ty);
10646 
10647     // Use a single XLen int if possible, 2*XLen if 2*XLen alignment is
10648     // required, and a 2-element XLen array if only XLen alignment is required.
10649     if (Size <= XLen) {
10650       return ABIArgInfo::getDirect(
10651           llvm::IntegerType::get(getVMContext(), XLen));
10652     } else if (Alignment == 2 * XLen) {
10653       return ABIArgInfo::getDirect(
10654           llvm::IntegerType::get(getVMContext(), 2 * XLen));
10655     } else {
10656       return ABIArgInfo::getDirect(llvm::ArrayType::get(
10657           llvm::IntegerType::get(getVMContext(), XLen), 2));
10658     }
10659   }
10660   return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
10661 }
10662 
10663 ABIArgInfo RISCVABIInfo::classifyReturnType(QualType RetTy) const {
10664   if (RetTy->isVoidType())
10665     return ABIArgInfo::getIgnore();
10666 
10667   int ArgGPRsLeft = 2;
10668   int ArgFPRsLeft = FLen ? 2 : 0;
10669 
10670   // The rules for return and argument types are the same, so defer to
10671   // classifyArgumentType.
10672   return classifyArgumentType(RetTy, /*IsFixed=*/true, ArgGPRsLeft,
10673                               ArgFPRsLeft);
10674 }
10675 
10676 Address RISCVABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
10677                                 QualType Ty) const {
10678   CharUnits SlotSize = CharUnits::fromQuantity(XLen / 8);
10679 
10680   // Empty records are ignored for parameter passing purposes.
10681   if (isEmptyRecord(getContext(), Ty, true)) {
10682     Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize);
10683     Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
10684     return Addr;
10685   }
10686 
10687   std::pair<CharUnits, CharUnits> SizeAndAlign =
10688       getContext().getTypeInfoInChars(Ty);
10689 
10690   // Arguments bigger than 2*Xlen bytes are passed indirectly.
10691   bool IsIndirect = SizeAndAlign.first > 2 * SlotSize;
10692 
10693   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, SizeAndAlign,
10694                           SlotSize, /*AllowHigherAlign=*/true);
10695 }
10696 
10697 ABIArgInfo RISCVABIInfo::extendType(QualType Ty) const {
10698   int TySize = getContext().getTypeSize(Ty);
10699   // RV64 ABI requires unsigned 32 bit integers to be sign extended.
10700   if (XLen == 64 && Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
10701     return ABIArgInfo::getSignExtend(Ty);
10702   return ABIArgInfo::getExtend(Ty);
10703 }
10704 
10705 namespace {
10706 class RISCVTargetCodeGenInfo : public TargetCodeGenInfo {
10707 public:
10708   RISCVTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, unsigned XLen,
10709                          unsigned FLen)
10710       : TargetCodeGenInfo(std::make_unique<RISCVABIInfo>(CGT, XLen, FLen)) {}
10711 
10712   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
10713                            CodeGen::CodeGenModule &CGM) const override {
10714     const auto *FD = dyn_cast_or_null<FunctionDecl>(D);
10715     if (!FD) return;
10716 
10717     const auto *Attr = FD->getAttr<RISCVInterruptAttr>();
10718     if (!Attr)
10719       return;
10720 
10721     const char *Kind;
10722     switch (Attr->getInterrupt()) {
10723     case RISCVInterruptAttr::user: Kind = "user"; break;
10724     case RISCVInterruptAttr::supervisor: Kind = "supervisor"; break;
10725     case RISCVInterruptAttr::machine: Kind = "machine"; break;
10726     }
10727 
10728     auto *Fn = cast<llvm::Function>(GV);
10729 
10730     Fn->addFnAttr("interrupt", Kind);
10731   }
10732 };
10733 } // namespace
10734 
10735 //===----------------------------------------------------------------------===//
10736 // VE ABI Implementation.
10737 //
10738 namespace {
10739 class VEABIInfo : public DefaultABIInfo {
10740 public:
10741   VEABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
10742 
10743 private:
10744   ABIArgInfo classifyReturnType(QualType RetTy) const;
10745   ABIArgInfo classifyArgumentType(QualType RetTy) const;
10746   void computeInfo(CGFunctionInfo &FI) const override;
10747 };
10748 } // end anonymous namespace
10749 
10750 ABIArgInfo VEABIInfo::classifyReturnType(QualType Ty) const {
10751   if (Ty->isAnyComplexType()) {
10752     return ABIArgInfo::getDirect();
10753   }
10754   return DefaultABIInfo::classifyReturnType(Ty);
10755 }
10756 
10757 ABIArgInfo VEABIInfo::classifyArgumentType(QualType Ty) const {
10758   if (Ty->isAnyComplexType()) {
10759     return ABIArgInfo::getDirect();
10760   }
10761   return DefaultABIInfo::classifyArgumentType(Ty);
10762 }
10763 
10764 void VEABIInfo::computeInfo(CGFunctionInfo &FI) const {
10765 
10766   FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
10767   for (auto &Arg : FI.arguments())
10768     Arg.info = classifyArgumentType(Arg.type);
10769 }
10770 
10771 namespace {
10772 class VETargetCodeGenInfo : public TargetCodeGenInfo {
10773 public:
10774   VETargetCodeGenInfo(CodeGenTypes &CGT)
10775       : TargetCodeGenInfo(std::make_unique<VEABIInfo>(CGT)) {}
10776   // VE ABI requires the arguments of variadic and prototype-less functions
10777   // are passed in both registers and memory.
10778   bool isNoProtoCallVariadic(const CallArgList &args,
10779                              const FunctionNoProtoType *fnType) const override {
10780     return true;
10781   }
10782 };
10783 } // end anonymous namespace
10784 
10785 //===----------------------------------------------------------------------===//
10786 // Driver code
10787 //===----------------------------------------------------------------------===//
10788 
10789 bool CodeGenModule::supportsCOMDAT() const {
10790   return getTriple().supportsCOMDAT();
10791 }
10792 
10793 const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
10794   if (TheTargetCodeGenInfo)
10795     return *TheTargetCodeGenInfo;
10796 
10797   // Helper to set the unique_ptr while still keeping the return value.
10798   auto SetCGInfo = [&](TargetCodeGenInfo *P) -> const TargetCodeGenInfo & {
10799     this->TheTargetCodeGenInfo.reset(P);
10800     return *P;
10801   };
10802 
10803   const llvm::Triple &Triple = getTarget().getTriple();
10804   switch (Triple.getArch()) {
10805   default:
10806     return SetCGInfo(new DefaultTargetCodeGenInfo(Types));
10807 
10808   case llvm::Triple::le32:
10809     return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
10810   case llvm::Triple::mips:
10811   case llvm::Triple::mipsel:
10812     if (Triple.getOS() == llvm::Triple::NaCl)
10813       return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
10814     return SetCGInfo(new MIPSTargetCodeGenInfo(Types, true));
10815 
10816   case llvm::Triple::mips64:
10817   case llvm::Triple::mips64el:
10818     return SetCGInfo(new MIPSTargetCodeGenInfo(Types, false));
10819 
10820   case llvm::Triple::avr:
10821     return SetCGInfo(new AVRTargetCodeGenInfo(Types));
10822 
10823   case llvm::Triple::aarch64:
10824   case llvm::Triple::aarch64_32:
10825   case llvm::Triple::aarch64_be: {
10826     AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS;
10827     if (getTarget().getABI() == "darwinpcs")
10828       Kind = AArch64ABIInfo::DarwinPCS;
10829     else if (Triple.isOSWindows())
10830       return SetCGInfo(
10831           new WindowsAArch64TargetCodeGenInfo(Types, AArch64ABIInfo::Win64));
10832 
10833     return SetCGInfo(new AArch64TargetCodeGenInfo(Types, Kind));
10834   }
10835 
10836   case llvm::Triple::wasm32:
10837   case llvm::Triple::wasm64: {
10838     WebAssemblyABIInfo::ABIKind Kind = WebAssemblyABIInfo::MVP;
10839     if (getTarget().getABI() == "experimental-mv")
10840       Kind = WebAssemblyABIInfo::ExperimentalMV;
10841     return SetCGInfo(new WebAssemblyTargetCodeGenInfo(Types, Kind));
10842   }
10843 
10844   case llvm::Triple::arm:
10845   case llvm::Triple::armeb:
10846   case llvm::Triple::thumb:
10847   case llvm::Triple::thumbeb: {
10848     if (Triple.getOS() == llvm::Triple::Win32) {
10849       return SetCGInfo(
10850           new WindowsARMTargetCodeGenInfo(Types, ARMABIInfo::AAPCS_VFP));
10851     }
10852 
10853     ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
10854     StringRef ABIStr = getTarget().getABI();
10855     if (ABIStr == "apcs-gnu")
10856       Kind = ARMABIInfo::APCS;
10857     else if (ABIStr == "aapcs16")
10858       Kind = ARMABIInfo::AAPCS16_VFP;
10859     else if (CodeGenOpts.FloatABI == "hard" ||
10860              (CodeGenOpts.FloatABI != "soft" &&
10861               (Triple.getEnvironment() == llvm::Triple::GNUEABIHF ||
10862                Triple.getEnvironment() == llvm::Triple::MuslEABIHF ||
10863                Triple.getEnvironment() == llvm::Triple::EABIHF)))
10864       Kind = ARMABIInfo::AAPCS_VFP;
10865 
10866     return SetCGInfo(new ARMTargetCodeGenInfo(Types, Kind));
10867   }
10868 
10869   case llvm::Triple::ppc: {
10870     if (Triple.isOSAIX())
10871       return SetCGInfo(new AIXTargetCodeGenInfo(Types, /*Is64Bit*/ false));
10872 
10873     bool IsSoftFloat =
10874         CodeGenOpts.FloatABI == "soft" || getTarget().hasFeature("spe");
10875     bool RetSmallStructInRegABI =
10876         PPC32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
10877     return SetCGInfo(
10878         new PPC32TargetCodeGenInfo(Types, IsSoftFloat, RetSmallStructInRegABI));
10879   }
10880   case llvm::Triple::ppc64:
10881     if (Triple.isOSAIX())
10882       return SetCGInfo(new AIXTargetCodeGenInfo(Types, /*Is64Bit*/ true));
10883 
10884     if (Triple.isOSBinFormatELF()) {
10885       PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1;
10886       if (getTarget().getABI() == "elfv2")
10887         Kind = PPC64_SVR4_ABIInfo::ELFv2;
10888       bool HasQPX = getTarget().getABI() == "elfv1-qpx";
10889       bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
10890 
10891       return SetCGInfo(new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX,
10892                                                         IsSoftFloat));
10893     }
10894     return SetCGInfo(new PPC64TargetCodeGenInfo(Types));
10895   case llvm::Triple::ppc64le: {
10896     assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
10897     PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2;
10898     if (getTarget().getABI() == "elfv1" || getTarget().getABI() == "elfv1-qpx")
10899       Kind = PPC64_SVR4_ABIInfo::ELFv1;
10900     bool HasQPX = getTarget().getABI() == "elfv1-qpx";
10901     bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
10902 
10903     return SetCGInfo(new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX,
10904                                                       IsSoftFloat));
10905   }
10906 
10907   case llvm::Triple::nvptx:
10908   case llvm::Triple::nvptx64:
10909     return SetCGInfo(new NVPTXTargetCodeGenInfo(Types));
10910 
10911   case llvm::Triple::msp430:
10912     return SetCGInfo(new MSP430TargetCodeGenInfo(Types));
10913 
10914   case llvm::Triple::riscv32:
10915   case llvm::Triple::riscv64: {
10916     StringRef ABIStr = getTarget().getABI();
10917     unsigned XLen = getTarget().getPointerWidth(0);
10918     unsigned ABIFLen = 0;
10919     if (ABIStr.endswith("f"))
10920       ABIFLen = 32;
10921     else if (ABIStr.endswith("d"))
10922       ABIFLen = 64;
10923     return SetCGInfo(new RISCVTargetCodeGenInfo(Types, XLen, ABIFLen));
10924   }
10925 
10926   case llvm::Triple::systemz: {
10927     bool SoftFloat = CodeGenOpts.FloatABI == "soft";
10928     bool HasVector = !SoftFloat && getTarget().getABI() == "vector";
10929     return SetCGInfo(new SystemZTargetCodeGenInfo(Types, HasVector, SoftFloat));
10930   }
10931 
10932   case llvm::Triple::tce:
10933   case llvm::Triple::tcele:
10934     return SetCGInfo(new TCETargetCodeGenInfo(Types));
10935 
10936   case llvm::Triple::x86: {
10937     bool IsDarwinVectorABI = Triple.isOSDarwin();
10938     bool RetSmallStructInRegABI =
10939         X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
10940     bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
10941 
10942     if (Triple.getOS() == llvm::Triple::Win32) {
10943       return SetCGInfo(new WinX86_32TargetCodeGenInfo(
10944           Types, IsDarwinVectorABI, RetSmallStructInRegABI,
10945           IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters));
10946     } else {
10947       return SetCGInfo(new X86_32TargetCodeGenInfo(
10948           Types, IsDarwinVectorABI, RetSmallStructInRegABI,
10949           IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters,
10950           CodeGenOpts.FloatABI == "soft"));
10951     }
10952   }
10953 
10954   case llvm::Triple::x86_64: {
10955     StringRef ABI = getTarget().getABI();
10956     X86AVXABILevel AVXLevel =
10957         (ABI == "avx512"
10958              ? X86AVXABILevel::AVX512
10959              : ABI == "avx" ? X86AVXABILevel::AVX : X86AVXABILevel::None);
10960 
10961     switch (Triple.getOS()) {
10962     case llvm::Triple::Win32:
10963       return SetCGInfo(new WinX86_64TargetCodeGenInfo(Types, AVXLevel));
10964     default:
10965       return SetCGInfo(new X86_64TargetCodeGenInfo(Types, AVXLevel));
10966     }
10967   }
10968   case llvm::Triple::hexagon:
10969     return SetCGInfo(new HexagonTargetCodeGenInfo(Types));
10970   case llvm::Triple::lanai:
10971     return SetCGInfo(new LanaiTargetCodeGenInfo(Types));
10972   case llvm::Triple::r600:
10973     return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
10974   case llvm::Triple::amdgcn:
10975     return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
10976   case llvm::Triple::sparc:
10977     return SetCGInfo(new SparcV8TargetCodeGenInfo(Types));
10978   case llvm::Triple::sparcv9:
10979     return SetCGInfo(new SparcV9TargetCodeGenInfo(Types));
10980   case llvm::Triple::xcore:
10981     return SetCGInfo(new XCoreTargetCodeGenInfo(Types));
10982   case llvm::Triple::arc:
10983     return SetCGInfo(new ARCTargetCodeGenInfo(Types));
10984   case llvm::Triple::spir:
10985   case llvm::Triple::spir64:
10986     return SetCGInfo(new SPIRTargetCodeGenInfo(Types));
10987   case llvm::Triple::ve:
10988     return SetCGInfo(new VETargetCodeGenInfo(Types));
10989   }
10990 }
10991 
10992 /// Create an OpenCL kernel for an enqueued block.
10993 ///
10994 /// The kernel has the same function type as the block invoke function. Its
10995 /// name is the name of the block invoke function postfixed with "_kernel".
10996 /// It simply calls the block invoke function then returns.
10997 llvm::Function *
10998 TargetCodeGenInfo::createEnqueuedBlockKernel(CodeGenFunction &CGF,
10999                                              llvm::Function *Invoke,
11000                                              llvm::Value *BlockLiteral) const {
11001   auto *InvokeFT = Invoke->getFunctionType();
11002   llvm::SmallVector<llvm::Type *, 2> ArgTys;
11003   for (auto &P : InvokeFT->params())
11004     ArgTys.push_back(P);
11005   auto &C = CGF.getLLVMContext();
11006   std::string Name = Invoke->getName().str() + "_kernel";
11007   auto *FT = llvm::FunctionType::get(llvm::Type::getVoidTy(C), ArgTys, false);
11008   auto *F = llvm::Function::Create(FT, llvm::GlobalValue::InternalLinkage, Name,
11009                                    &CGF.CGM.getModule());
11010   auto IP = CGF.Builder.saveIP();
11011   auto *BB = llvm::BasicBlock::Create(C, "entry", F);
11012   auto &Builder = CGF.Builder;
11013   Builder.SetInsertPoint(BB);
11014   llvm::SmallVector<llvm::Value *, 2> Args;
11015   for (auto &A : F->args())
11016     Args.push_back(&A);
11017   Builder.CreateCall(Invoke, Args);
11018   Builder.CreateRetVoid();
11019   Builder.restoreIP(IP);
11020   return F;
11021 }
11022 
11023 /// Create an OpenCL kernel for an enqueued block.
11024 ///
11025 /// The type of the first argument (the block literal) is the struct type
11026 /// of the block literal instead of a pointer type. The first argument
11027 /// (block literal) is passed directly by value to the kernel. The kernel
11028 /// allocates the same type of struct on stack and stores the block literal
11029 /// to it and passes its pointer to the block invoke function. The kernel
11030 /// has "enqueued-block" function attribute and kernel argument metadata.
11031 llvm::Function *AMDGPUTargetCodeGenInfo::createEnqueuedBlockKernel(
11032     CodeGenFunction &CGF, llvm::Function *Invoke,
11033     llvm::Value *BlockLiteral) const {
11034   auto &Builder = CGF.Builder;
11035   auto &C = CGF.getLLVMContext();
11036 
11037   auto *BlockTy = BlockLiteral->getType()->getPointerElementType();
11038   auto *InvokeFT = Invoke->getFunctionType();
11039   llvm::SmallVector<llvm::Type *, 2> ArgTys;
11040   llvm::SmallVector<llvm::Metadata *, 8> AddressQuals;
11041   llvm::SmallVector<llvm::Metadata *, 8> AccessQuals;
11042   llvm::SmallVector<llvm::Metadata *, 8> ArgTypeNames;
11043   llvm::SmallVector<llvm::Metadata *, 8> ArgBaseTypeNames;
11044   llvm::SmallVector<llvm::Metadata *, 8> ArgTypeQuals;
11045   llvm::SmallVector<llvm::Metadata *, 8> ArgNames;
11046 
11047   ArgTys.push_back(BlockTy);
11048   ArgTypeNames.push_back(llvm::MDString::get(C, "__block_literal"));
11049   AddressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(0)));
11050   ArgBaseTypeNames.push_back(llvm::MDString::get(C, "__block_literal"));
11051   ArgTypeQuals.push_back(llvm::MDString::get(C, ""));
11052   AccessQuals.push_back(llvm::MDString::get(C, "none"));
11053   ArgNames.push_back(llvm::MDString::get(C, "block_literal"));
11054   for (unsigned I = 1, E = InvokeFT->getNumParams(); I < E; ++I) {
11055     ArgTys.push_back(InvokeFT->getParamType(I));
11056     ArgTypeNames.push_back(llvm::MDString::get(C, "void*"));
11057     AddressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(3)));
11058     AccessQuals.push_back(llvm::MDString::get(C, "none"));
11059     ArgBaseTypeNames.push_back(llvm::MDString::get(C, "void*"));
11060     ArgTypeQuals.push_back(llvm::MDString::get(C, ""));
11061     ArgNames.push_back(
11062         llvm::MDString::get(C, (Twine("local_arg") + Twine(I)).str()));
11063   }
11064   std::string Name = Invoke->getName().str() + "_kernel";
11065   auto *FT = llvm::FunctionType::get(llvm::Type::getVoidTy(C), ArgTys, false);
11066   auto *F = llvm::Function::Create(FT, llvm::GlobalValue::InternalLinkage, Name,
11067                                    &CGF.CGM.getModule());
11068   F->addFnAttr("enqueued-block");
11069   auto IP = CGF.Builder.saveIP();
11070   auto *BB = llvm::BasicBlock::Create(C, "entry", F);
11071   Builder.SetInsertPoint(BB);
11072   const auto BlockAlign = CGF.CGM.getDataLayout().getPrefTypeAlign(BlockTy);
11073   auto *BlockPtr = Builder.CreateAlloca(BlockTy, nullptr);
11074   BlockPtr->setAlignment(BlockAlign);
11075   Builder.CreateAlignedStore(F->arg_begin(), BlockPtr, BlockAlign);
11076   auto *Cast = Builder.CreatePointerCast(BlockPtr, InvokeFT->getParamType(0));
11077   llvm::SmallVector<llvm::Value *, 2> Args;
11078   Args.push_back(Cast);
11079   for (auto I = F->arg_begin() + 1, E = F->arg_end(); I != E; ++I)
11080     Args.push_back(I);
11081   Builder.CreateCall(Invoke, Args);
11082   Builder.CreateRetVoid();
11083   Builder.restoreIP(IP);
11084 
11085   F->setMetadata("kernel_arg_addr_space", llvm::MDNode::get(C, AddressQuals));
11086   F->setMetadata("kernel_arg_access_qual", llvm::MDNode::get(C, AccessQuals));
11087   F->setMetadata("kernel_arg_type", llvm::MDNode::get(C, ArgTypeNames));
11088   F->setMetadata("kernel_arg_base_type",
11089                  llvm::MDNode::get(C, ArgBaseTypeNames));
11090   F->setMetadata("kernel_arg_type_qual", llvm::MDNode::get(C, ArgTypeQuals));
11091   if (CGF.CGM.getCodeGenOpts().EmitOpenCLArgMetadata)
11092     F->setMetadata("kernel_arg_name", llvm::MDNode::get(C, ArgNames));
11093 
11094   return F;
11095 }
11096