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 ABIInfo::getNaturalAlignIndirect(QualType Ty, bool ByVal,
84                                             bool Realign,
85                                             llvm::Type *Padding) const {
86   return ABIArgInfo::getIndirect(getContext().getTypeAlignInChars(Ty), ByVal,
87                                  Realign, Padding);
88 }
89 
90 ABIArgInfo
91 ABIInfo::getNaturalAlignIndirectInReg(QualType Ty, bool Realign) const {
92   return ABIArgInfo::getIndirectInReg(getContext().getTypeAlignInChars(Ty),
93                                       /*ByVal*/ 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 IndirectAliased:
261     OS << "Indirect Align=" << getIndirectAlign().getQuantity()
262        << " AadrSpace=" << getIndirectAddrSpace()
263        << " Realign=" << getIndirectRealign();
264     break;
265   case Expand:
266     OS << "Expand";
267     break;
268   case CoerceAndExpand:
269     OS << "CoerceAndExpand Type=";
270     getCoerceAndExpandType()->print(OS);
271     break;
272   }
273   OS << ")\n";
274 }
275 
276 // Dynamically round a pointer up to a multiple of the given alignment.
277 static llvm::Value *emitRoundPointerUpToAlignment(CodeGenFunction &CGF,
278                                                   llvm::Value *Ptr,
279                                                   CharUnits Align) {
280   llvm::Value *PtrAsInt = Ptr;
281   // OverflowArgArea = (OverflowArgArea + Align - 1) & -Align;
282   PtrAsInt = CGF.Builder.CreatePtrToInt(PtrAsInt, CGF.IntPtrTy);
283   PtrAsInt = CGF.Builder.CreateAdd(PtrAsInt,
284         llvm::ConstantInt::get(CGF.IntPtrTy, Align.getQuantity() - 1));
285   PtrAsInt = CGF.Builder.CreateAnd(PtrAsInt,
286            llvm::ConstantInt::get(CGF.IntPtrTy, -Align.getQuantity()));
287   PtrAsInt = CGF.Builder.CreateIntToPtr(PtrAsInt,
288                                         Ptr->getType(),
289                                         Ptr->getName() + ".aligned");
290   return PtrAsInt;
291 }
292 
293 /// Emit va_arg for a platform using the common void* representation,
294 /// where arguments are simply emitted in an array of slots on the stack.
295 ///
296 /// This version implements the core direct-value passing rules.
297 ///
298 /// \param SlotSize - The size and alignment of a stack slot.
299 ///   Each argument will be allocated to a multiple of this number of
300 ///   slots, and all the slots will be aligned to this value.
301 /// \param AllowHigherAlign - The slot alignment is not a cap;
302 ///   an argument type with an alignment greater than the slot size
303 ///   will be emitted on a higher-alignment address, potentially
304 ///   leaving one or more empty slots behind as padding.  If this
305 ///   is false, the returned address might be less-aligned than
306 ///   DirectAlign.
307 static Address emitVoidPtrDirectVAArg(CodeGenFunction &CGF,
308                                       Address VAListAddr,
309                                       llvm::Type *DirectTy,
310                                       CharUnits DirectSize,
311                                       CharUnits DirectAlign,
312                                       CharUnits SlotSize,
313                                       bool AllowHigherAlign) {
314   // Cast the element type to i8* if necessary.  Some platforms define
315   // va_list as a struct containing an i8* instead of just an i8*.
316   if (VAListAddr.getElementType() != CGF.Int8PtrTy)
317     VAListAddr = CGF.Builder.CreateElementBitCast(VAListAddr, CGF.Int8PtrTy);
318 
319   llvm::Value *Ptr = CGF.Builder.CreateLoad(VAListAddr, "argp.cur");
320 
321   // If the CC aligns values higher than the slot size, do so if needed.
322   Address Addr = Address::invalid();
323   if (AllowHigherAlign && DirectAlign > SlotSize) {
324     Addr = Address(emitRoundPointerUpToAlignment(CGF, Ptr, DirectAlign),
325                                                  DirectAlign);
326   } else {
327     Addr = Address(Ptr, SlotSize);
328   }
329 
330   // Advance the pointer past the argument, then store that back.
331   CharUnits FullDirectSize = DirectSize.alignTo(SlotSize);
332   Address NextPtr =
333       CGF.Builder.CreateConstInBoundsByteGEP(Addr, FullDirectSize, "argp.next");
334   CGF.Builder.CreateStore(NextPtr.getPointer(), VAListAddr);
335 
336   // If the argument is smaller than a slot, and this is a big-endian
337   // target, the argument will be right-adjusted in its slot.
338   if (DirectSize < SlotSize && CGF.CGM.getDataLayout().isBigEndian() &&
339       !DirectTy->isStructTy()) {
340     Addr = CGF.Builder.CreateConstInBoundsByteGEP(Addr, SlotSize - DirectSize);
341   }
342 
343   Addr = CGF.Builder.CreateElementBitCast(Addr, DirectTy);
344   return Addr;
345 }
346 
347 /// Emit va_arg for a platform using the common void* representation,
348 /// where arguments are simply emitted in an array of slots on the stack.
349 ///
350 /// \param IsIndirect - Values of this type are passed indirectly.
351 /// \param ValueInfo - The size and alignment of this type, generally
352 ///   computed with getContext().getTypeInfoInChars(ValueTy).
353 /// \param SlotSizeAndAlign - The size and alignment of a stack slot.
354 ///   Each argument will be allocated to a multiple of this number of
355 ///   slots, and all the slots will be aligned to this value.
356 /// \param AllowHigherAlign - The slot alignment is not a cap;
357 ///   an argument type with an alignment greater than the slot size
358 ///   will be emitted on a higher-alignment address, potentially
359 ///   leaving one or more empty slots behind as padding.
360 static Address emitVoidPtrVAArg(CodeGenFunction &CGF, Address VAListAddr,
361                                 QualType ValueTy, bool IsIndirect,
362                                 TypeInfoChars ValueInfo,
363                                 CharUnits SlotSizeAndAlign,
364                                 bool AllowHigherAlign) {
365   // The size and alignment of the value that was passed directly.
366   CharUnits DirectSize, DirectAlign;
367   if (IsIndirect) {
368     DirectSize = CGF.getPointerSize();
369     DirectAlign = CGF.getPointerAlign();
370   } else {
371     DirectSize = ValueInfo.Width;
372     DirectAlign = ValueInfo.Align;
373   }
374 
375   // Cast the address we've calculated to the right type.
376   llvm::Type *DirectTy = CGF.ConvertTypeForMem(ValueTy);
377   if (IsIndirect)
378     DirectTy = DirectTy->getPointerTo(0);
379 
380   Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, DirectTy,
381                                         DirectSize, DirectAlign,
382                                         SlotSizeAndAlign,
383                                         AllowHigherAlign);
384 
385   if (IsIndirect) {
386     Addr = Address(CGF.Builder.CreateLoad(Addr), ValueInfo.Align);
387   }
388 
389   return Addr;
390 
391 }
392 
393 static Address emitMergePHI(CodeGenFunction &CGF,
394                             Address Addr1, llvm::BasicBlock *Block1,
395                             Address Addr2, llvm::BasicBlock *Block2,
396                             const llvm::Twine &Name = "") {
397   assert(Addr1.getType() == Addr2.getType());
398   llvm::PHINode *PHI = CGF.Builder.CreatePHI(Addr1.getType(), 2, Name);
399   PHI->addIncoming(Addr1.getPointer(), Block1);
400   PHI->addIncoming(Addr2.getPointer(), Block2);
401   CharUnits Align = std::min(Addr1.getAlignment(), Addr2.getAlignment());
402   return Address(PHI, Align);
403 }
404 
405 TargetCodeGenInfo::~TargetCodeGenInfo() = default;
406 
407 // If someone can figure out a general rule for this, that would be great.
408 // It's probably just doomed to be platform-dependent, though.
409 unsigned TargetCodeGenInfo::getSizeOfUnwindException() const {
410   // Verified for:
411   //   x86-64     FreeBSD, Linux, Darwin
412   //   x86-32     FreeBSD, Linux, Darwin
413   //   PowerPC    Linux, Darwin
414   //   ARM        Darwin (*not* EABI)
415   //   AArch64    Linux
416   return 32;
417 }
418 
419 bool TargetCodeGenInfo::isNoProtoCallVariadic(const CallArgList &args,
420                                      const FunctionNoProtoType *fnType) const {
421   // The following conventions are known to require this to be false:
422   //   x86_stdcall
423   //   MIPS
424   // For everything else, we just prefer false unless we opt out.
425   return false;
426 }
427 
428 void
429 TargetCodeGenInfo::getDependentLibraryOption(llvm::StringRef Lib,
430                                              llvm::SmallString<24> &Opt) const {
431   // This assumes the user is passing a library name like "rt" instead of a
432   // filename like "librt.a/so", and that they don't care whether it's static or
433   // dynamic.
434   Opt = "-l";
435   Opt += Lib;
436 }
437 
438 unsigned TargetCodeGenInfo::getOpenCLKernelCallingConv() const {
439   // OpenCL kernels are called via an explicit runtime API with arguments
440   // set with clSetKernelArg(), not as normal sub-functions.
441   // Return SPIR_KERNEL by default as the kernel calling convention to
442   // ensure the fingerprint is fixed such way that each OpenCL argument
443   // gets one matching argument in the produced kernel function argument
444   // list to enable feasible implementation of clSetKernelArg() with
445   // aggregates etc. In case we would use the default C calling conv here,
446   // clSetKernelArg() might break depending on the target-specific
447   // conventions; different targets might split structs passed as values
448   // to multiple function arguments etc.
449   return llvm::CallingConv::SPIR_KERNEL;
450 }
451 
452 llvm::Constant *TargetCodeGenInfo::getNullPointer(const CodeGen::CodeGenModule &CGM,
453     llvm::PointerType *T, QualType QT) const {
454   return llvm::ConstantPointerNull::get(T);
455 }
456 
457 LangAS TargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM,
458                                                    const VarDecl *D) const {
459   assert(!CGM.getLangOpts().OpenCL &&
460          !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) &&
461          "Address space agnostic languages only");
462   return D ? D->getType().getAddressSpace() : LangAS::Default;
463 }
464 
465 llvm::Value *TargetCodeGenInfo::performAddrSpaceCast(
466     CodeGen::CodeGenFunction &CGF, llvm::Value *Src, LangAS SrcAddr,
467     LangAS DestAddr, llvm::Type *DestTy, bool isNonNull) const {
468   // Since target may map different address spaces in AST to the same address
469   // space, an address space conversion may end up as a bitcast.
470   if (auto *C = dyn_cast<llvm::Constant>(Src))
471     return performAddrSpaceCast(CGF.CGM, C, SrcAddr, DestAddr, DestTy);
472   // Try to preserve the source's name to make IR more readable.
473   return CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
474       Src, DestTy, Src->hasName() ? Src->getName() + ".ascast" : "");
475 }
476 
477 llvm::Constant *
478 TargetCodeGenInfo::performAddrSpaceCast(CodeGenModule &CGM, llvm::Constant *Src,
479                                         LangAS SrcAddr, LangAS DestAddr,
480                                         llvm::Type *DestTy) const {
481   // Since target may map different address spaces in AST to the same address
482   // space, an address space conversion may end up as a bitcast.
483   return llvm::ConstantExpr::getPointerCast(Src, DestTy);
484 }
485 
486 llvm::SyncScope::ID
487 TargetCodeGenInfo::getLLVMSyncScopeID(const LangOptions &LangOpts,
488                                       SyncScope Scope,
489                                       llvm::AtomicOrdering Ordering,
490                                       llvm::LLVMContext &Ctx) const {
491   return Ctx.getOrInsertSyncScopeID(""); /* default sync scope */
492 }
493 
494 static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays);
495 
496 /// isEmptyField - Return true iff a the field is "empty", that is it
497 /// is an unnamed bit-field or an (array of) empty record(s).
498 static bool isEmptyField(ASTContext &Context, const FieldDecl *FD,
499                          bool AllowArrays) {
500   if (FD->isUnnamedBitfield())
501     return true;
502 
503   QualType FT = FD->getType();
504 
505   // Constant arrays of empty records count as empty, strip them off.
506   // Constant arrays of zero length always count as empty.
507   bool WasArray = false;
508   if (AllowArrays)
509     while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
510       if (AT->getSize() == 0)
511         return true;
512       FT = AT->getElementType();
513       // The [[no_unique_address]] special case below does not apply to
514       // arrays of C++ empty records, so we need to remember this fact.
515       WasArray = true;
516     }
517 
518   const RecordType *RT = FT->getAs<RecordType>();
519   if (!RT)
520     return false;
521 
522   // C++ record fields are never empty, at least in the Itanium ABI.
523   //
524   // FIXME: We should use a predicate for whether this behavior is true in the
525   // current ABI.
526   //
527   // The exception to the above rule are fields marked with the
528   // [[no_unique_address]] attribute (since C++20).  Those do count as empty
529   // according to the Itanium ABI.  The exception applies only to records,
530   // not arrays of records, so we must also check whether we stripped off an
531   // array type above.
532   if (isa<CXXRecordDecl>(RT->getDecl()) &&
533       (WasArray || !FD->hasAttr<NoUniqueAddressAttr>()))
534     return false;
535 
536   return isEmptyRecord(Context, FT, AllowArrays);
537 }
538 
539 /// isEmptyRecord - Return true iff a structure contains only empty
540 /// fields. Note that a structure with a flexible array member is not
541 /// considered empty.
542 static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) {
543   const RecordType *RT = T->getAs<RecordType>();
544   if (!RT)
545     return false;
546   const RecordDecl *RD = RT->getDecl();
547   if (RD->hasFlexibleArrayMember())
548     return false;
549 
550   // If this is a C++ record, check the bases first.
551   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
552     for (const auto &I : CXXRD->bases())
553       if (!isEmptyRecord(Context, I.getType(), true))
554         return false;
555 
556   for (const auto *I : RD->fields())
557     if (!isEmptyField(Context, I, AllowArrays))
558       return false;
559   return true;
560 }
561 
562 /// isSingleElementStruct - Determine if a structure is a "single
563 /// element struct", i.e. it has exactly one non-empty field or
564 /// exactly one field which is itself a single element
565 /// struct. Structures with flexible array members are never
566 /// considered single element structs.
567 ///
568 /// \return The field declaration for the single non-empty field, if
569 /// it exists.
570 static const Type *isSingleElementStruct(QualType T, ASTContext &Context) {
571   const RecordType *RT = T->getAs<RecordType>();
572   if (!RT)
573     return nullptr;
574 
575   const RecordDecl *RD = RT->getDecl();
576   if (RD->hasFlexibleArrayMember())
577     return nullptr;
578 
579   const Type *Found = nullptr;
580 
581   // If this is a C++ record, check the bases first.
582   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
583     for (const auto &I : CXXRD->bases()) {
584       // Ignore empty records.
585       if (isEmptyRecord(Context, I.getType(), true))
586         continue;
587 
588       // If we already found an element then this isn't a single-element struct.
589       if (Found)
590         return nullptr;
591 
592       // If this is non-empty and not a single element struct, the composite
593       // cannot be a single element struct.
594       Found = isSingleElementStruct(I.getType(), Context);
595       if (!Found)
596         return nullptr;
597     }
598   }
599 
600   // Check for single element.
601   for (const auto *FD : RD->fields()) {
602     QualType FT = FD->getType();
603 
604     // Ignore empty fields.
605     if (isEmptyField(Context, FD, true))
606       continue;
607 
608     // If we already found an element then this isn't a single-element
609     // struct.
610     if (Found)
611       return nullptr;
612 
613     // Treat single element arrays as the element.
614     while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
615       if (AT->getSize().getZExtValue() != 1)
616         break;
617       FT = AT->getElementType();
618     }
619 
620     if (!isAggregateTypeForABI(FT)) {
621       Found = FT.getTypePtr();
622     } else {
623       Found = isSingleElementStruct(FT, Context);
624       if (!Found)
625         return nullptr;
626     }
627   }
628 
629   // We don't consider a struct a single-element struct if it has
630   // padding beyond the element type.
631   if (Found && Context.getTypeSize(Found) != Context.getTypeSize(T))
632     return nullptr;
633 
634   return Found;
635 }
636 
637 namespace {
638 Address EmitVAArgInstr(CodeGenFunction &CGF, Address VAListAddr, QualType Ty,
639                        const ABIArgInfo &AI) {
640   // This default implementation defers to the llvm backend's va_arg
641   // instruction. It can handle only passing arguments directly
642   // (typically only handled in the backend for primitive types), or
643   // aggregates passed indirectly by pointer (NOTE: if the "byval"
644   // flag has ABI impact in the callee, this implementation cannot
645   // work.)
646 
647   // Only a few cases are covered here at the moment -- those needed
648   // by the default abi.
649   llvm::Value *Val;
650 
651   if (AI.isIndirect()) {
652     assert(!AI.getPaddingType() &&
653            "Unexpected PaddingType seen in arginfo in generic VAArg emitter!");
654     assert(
655         !AI.getIndirectRealign() &&
656         "Unexpected IndirectRealign seen in arginfo in generic VAArg emitter!");
657 
658     auto TyInfo = CGF.getContext().getTypeInfoInChars(Ty);
659     CharUnits TyAlignForABI = TyInfo.Align;
660 
661     llvm::Type *BaseTy =
662         llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
663     llvm::Value *Addr =
664         CGF.Builder.CreateVAArg(VAListAddr.getPointer(), BaseTy);
665     return Address(Addr, TyAlignForABI);
666   } else {
667     assert((AI.isDirect() || AI.isExtend()) &&
668            "Unexpected ArgInfo Kind in generic VAArg emitter!");
669 
670     assert(!AI.getInReg() &&
671            "Unexpected InReg seen in arginfo in generic VAArg emitter!");
672     assert(!AI.getPaddingType() &&
673            "Unexpected PaddingType seen in arginfo in generic VAArg emitter!");
674     assert(!AI.getDirectOffset() &&
675            "Unexpected DirectOffset seen in arginfo in generic VAArg emitter!");
676     assert(!AI.getCoerceToType() &&
677            "Unexpected CoerceToType seen in arginfo in generic VAArg emitter!");
678 
679     Address Temp = CGF.CreateMemTemp(Ty, "varet");
680     Val = CGF.Builder.CreateVAArg(VAListAddr.getPointer(), CGF.ConvertType(Ty));
681     CGF.Builder.CreateStore(Val, Temp);
682     return Temp;
683   }
684 }
685 
686 /// DefaultABIInfo - The default implementation for ABI specific
687 /// details. This implementation provides information which results in
688 /// self-consistent and sensible LLVM IR generation, but does not
689 /// conform to any particular ABI.
690 class DefaultABIInfo : public ABIInfo {
691 public:
692   DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
693 
694   ABIArgInfo classifyReturnType(QualType RetTy) const;
695   ABIArgInfo classifyArgumentType(QualType RetTy) const;
696 
697   void computeInfo(CGFunctionInfo &FI) const override {
698     if (!getCXXABI().classifyReturnType(FI))
699       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
700     for (auto &I : FI.arguments())
701       I.info = classifyArgumentType(I.type);
702   }
703 
704   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
705                     QualType Ty) const override {
706     return EmitVAArgInstr(CGF, VAListAddr, Ty, classifyArgumentType(Ty));
707   }
708 };
709 
710 class DefaultTargetCodeGenInfo : public TargetCodeGenInfo {
711 public:
712   DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
713       : TargetCodeGenInfo(std::make_unique<DefaultABIInfo>(CGT)) {}
714 };
715 
716 ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const {
717   Ty = useFirstFieldIfTransparentUnion(Ty);
718 
719   if (isAggregateTypeForABI(Ty)) {
720     // Records with non-trivial destructors/copy-constructors should not be
721     // passed by value.
722     if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
723       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
724 
725     return getNaturalAlignIndirect(Ty);
726   }
727 
728   // Treat an enum type as its underlying type.
729   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
730     Ty = EnumTy->getDecl()->getIntegerType();
731 
732   ASTContext &Context = getContext();
733   if (const auto *EIT = Ty->getAs<ExtIntType>())
734     if (EIT->getNumBits() >
735         Context.getTypeSize(Context.getTargetInfo().hasInt128Type()
736                                 ? Context.Int128Ty
737                                 : Context.LongLongTy))
738       return getNaturalAlignIndirect(Ty);
739 
740   return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
741                                             : ABIArgInfo::getDirect());
742 }
743 
744 ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const {
745   if (RetTy->isVoidType())
746     return ABIArgInfo::getIgnore();
747 
748   if (isAggregateTypeForABI(RetTy))
749     return getNaturalAlignIndirect(RetTy);
750 
751   // Treat an enum type as its underlying type.
752   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
753     RetTy = EnumTy->getDecl()->getIntegerType();
754 
755   if (const auto *EIT = RetTy->getAs<ExtIntType>())
756     if (EIT->getNumBits() >
757         getContext().getTypeSize(getContext().getTargetInfo().hasInt128Type()
758                                      ? getContext().Int128Ty
759                                      : getContext().LongLongTy))
760       return getNaturalAlignIndirect(RetTy);
761 
762   return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
763                                                : ABIArgInfo::getDirect());
764 }
765 
766 //===----------------------------------------------------------------------===//
767 // WebAssembly ABI Implementation
768 //
769 // This is a very simple ABI that relies a lot on DefaultABIInfo.
770 //===----------------------------------------------------------------------===//
771 
772 class WebAssemblyABIInfo final : public SwiftABIInfo {
773 public:
774   enum ABIKind {
775     MVP = 0,
776     ExperimentalMV = 1,
777   };
778 
779 private:
780   DefaultABIInfo defaultInfo;
781   ABIKind Kind;
782 
783 public:
784   explicit WebAssemblyABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind)
785       : SwiftABIInfo(CGT), defaultInfo(CGT), Kind(Kind) {}
786 
787 private:
788   ABIArgInfo classifyReturnType(QualType RetTy) const;
789   ABIArgInfo classifyArgumentType(QualType Ty) const;
790 
791   // DefaultABIInfo's classifyReturnType and classifyArgumentType are
792   // non-virtual, but computeInfo and EmitVAArg are virtual, so we
793   // overload them.
794   void computeInfo(CGFunctionInfo &FI) const override {
795     if (!getCXXABI().classifyReturnType(FI))
796       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
797     for (auto &Arg : FI.arguments())
798       Arg.info = classifyArgumentType(Arg.type);
799   }
800 
801   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
802                     QualType Ty) const override;
803 
804   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
805                                     bool asReturnValue) const override {
806     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
807   }
808 
809   bool isSwiftErrorInRegister() const override {
810     return false;
811   }
812 };
813 
814 class WebAssemblyTargetCodeGenInfo final : public TargetCodeGenInfo {
815 public:
816   explicit WebAssemblyTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
817                                         WebAssemblyABIInfo::ABIKind K)
818       : TargetCodeGenInfo(std::make_unique<WebAssemblyABIInfo>(CGT, K)) {}
819 
820   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
821                            CodeGen::CodeGenModule &CGM) const override {
822     TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
823     if (const auto *FD = dyn_cast_or_null<FunctionDecl>(D)) {
824       if (const auto *Attr = FD->getAttr<WebAssemblyImportModuleAttr>()) {
825         llvm::Function *Fn = cast<llvm::Function>(GV);
826         llvm::AttrBuilder B;
827         B.addAttribute("wasm-import-module", Attr->getImportModule());
828         Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
829       }
830       if (const auto *Attr = FD->getAttr<WebAssemblyImportNameAttr>()) {
831         llvm::Function *Fn = cast<llvm::Function>(GV);
832         llvm::AttrBuilder B;
833         B.addAttribute("wasm-import-name", Attr->getImportName());
834         Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
835       }
836       if (const auto *Attr = FD->getAttr<WebAssemblyExportNameAttr>()) {
837         llvm::Function *Fn = cast<llvm::Function>(GV);
838         llvm::AttrBuilder B;
839         B.addAttribute("wasm-export-name", Attr->getExportName());
840         Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
841       }
842     }
843 
844     if (auto *FD = dyn_cast_or_null<FunctionDecl>(D)) {
845       llvm::Function *Fn = cast<llvm::Function>(GV);
846       if (!FD->doesThisDeclarationHaveABody() && !FD->hasPrototype())
847         Fn->addFnAttr("no-prototype");
848     }
849   }
850 };
851 
852 /// Classify argument of given type \p Ty.
853 ABIArgInfo WebAssemblyABIInfo::classifyArgumentType(QualType Ty) const {
854   Ty = useFirstFieldIfTransparentUnion(Ty);
855 
856   if (isAggregateTypeForABI(Ty)) {
857     // Records with non-trivial destructors/copy-constructors should not be
858     // passed by value.
859     if (auto RAA = getRecordArgABI(Ty, getCXXABI()))
860       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
861     // Ignore empty structs/unions.
862     if (isEmptyRecord(getContext(), Ty, true))
863       return ABIArgInfo::getIgnore();
864     // Lower single-element structs to just pass a regular value. TODO: We
865     // could do reasonable-size multiple-element structs too, using getExpand(),
866     // though watch out for things like bitfields.
867     if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
868       return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
869     // For the experimental multivalue ABI, fully expand all other aggregates
870     if (Kind == ABIKind::ExperimentalMV) {
871       const RecordType *RT = Ty->getAs<RecordType>();
872       assert(RT);
873       bool HasBitField = false;
874       for (auto *Field : RT->getDecl()->fields()) {
875         if (Field->isBitField()) {
876           HasBitField = true;
877           break;
878         }
879       }
880       if (!HasBitField)
881         return ABIArgInfo::getExpand();
882     }
883   }
884 
885   // Otherwise just do the default thing.
886   return defaultInfo.classifyArgumentType(Ty);
887 }
888 
889 ABIArgInfo WebAssemblyABIInfo::classifyReturnType(QualType RetTy) const {
890   if (isAggregateTypeForABI(RetTy)) {
891     // Records with non-trivial destructors/copy-constructors should not be
892     // returned by value.
893     if (!getRecordArgABI(RetTy, getCXXABI())) {
894       // Ignore empty structs/unions.
895       if (isEmptyRecord(getContext(), RetTy, true))
896         return ABIArgInfo::getIgnore();
897       // Lower single-element structs to just return a regular value. TODO: We
898       // could do reasonable-size multiple-element structs too, using
899       // ABIArgInfo::getDirect().
900       if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
901         return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
902       // For the experimental multivalue ABI, return all other aggregates
903       if (Kind == ABIKind::ExperimentalMV)
904         return ABIArgInfo::getDirect();
905     }
906   }
907 
908   // Otherwise just do the default thing.
909   return defaultInfo.classifyReturnType(RetTy);
910 }
911 
912 Address WebAssemblyABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
913                                       QualType Ty) const {
914   bool IsIndirect = isAggregateTypeForABI(Ty) &&
915                     !isEmptyRecord(getContext(), Ty, true) &&
916                     !isSingleElementStruct(Ty, getContext());
917   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
918                           getContext().getTypeInfoInChars(Ty),
919                           CharUnits::fromQuantity(4),
920                           /*AllowHigherAlign=*/true);
921 }
922 
923 //===----------------------------------------------------------------------===//
924 // le32/PNaCl bitcode ABI Implementation
925 //
926 // This is a simplified version of the x86_32 ABI.  Arguments and return values
927 // are always passed on the stack.
928 //===----------------------------------------------------------------------===//
929 
930 class PNaClABIInfo : public ABIInfo {
931  public:
932   PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
933 
934   ABIArgInfo classifyReturnType(QualType RetTy) const;
935   ABIArgInfo classifyArgumentType(QualType RetTy) const;
936 
937   void computeInfo(CGFunctionInfo &FI) const override;
938   Address EmitVAArg(CodeGenFunction &CGF,
939                     Address VAListAddr, QualType Ty) const override;
940 };
941 
942 class PNaClTargetCodeGenInfo : public TargetCodeGenInfo {
943  public:
944    PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
945        : TargetCodeGenInfo(std::make_unique<PNaClABIInfo>(CGT)) {}
946 };
947 
948 void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const {
949   if (!getCXXABI().classifyReturnType(FI))
950     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
951 
952   for (auto &I : FI.arguments())
953     I.info = classifyArgumentType(I.type);
954 }
955 
956 Address PNaClABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
957                                 QualType Ty) const {
958   // The PNaCL ABI is a bit odd, in that varargs don't use normal
959   // function classification. Structs get passed directly for varargs
960   // functions, through a rewriting transform in
961   // pnacl-llvm/lib/Transforms/NaCl/ExpandVarArgs.cpp, which allows
962   // this target to actually support a va_arg instructions with an
963   // aggregate type, unlike other targets.
964   return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
965 }
966 
967 /// Classify argument of given type \p Ty.
968 ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const {
969   if (isAggregateTypeForABI(Ty)) {
970     if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
971       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
972     return getNaturalAlignIndirect(Ty);
973   } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
974     // Treat an enum type as its underlying type.
975     Ty = EnumTy->getDecl()->getIntegerType();
976   } else if (Ty->isFloatingType()) {
977     // Floating-point types don't go inreg.
978     return ABIArgInfo::getDirect();
979   } else if (const auto *EIT = Ty->getAs<ExtIntType>()) {
980     // Treat extended integers as integers if <=64, otherwise pass indirectly.
981     if (EIT->getNumBits() > 64)
982       return getNaturalAlignIndirect(Ty);
983     return ABIArgInfo::getDirect();
984   }
985 
986   return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
987                                             : ABIArgInfo::getDirect());
988 }
989 
990 ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const {
991   if (RetTy->isVoidType())
992     return ABIArgInfo::getIgnore();
993 
994   // In the PNaCl ABI we always return records/structures on the stack.
995   if (isAggregateTypeForABI(RetTy))
996     return getNaturalAlignIndirect(RetTy);
997 
998   // Treat extended integers as integers if <=64, otherwise pass indirectly.
999   if (const auto *EIT = RetTy->getAs<ExtIntType>()) {
1000     if (EIT->getNumBits() > 64)
1001       return getNaturalAlignIndirect(RetTy);
1002     return ABIArgInfo::getDirect();
1003   }
1004 
1005   // Treat an enum type as its underlying type.
1006   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
1007     RetTy = EnumTy->getDecl()->getIntegerType();
1008 
1009   return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
1010                                                : ABIArgInfo::getDirect());
1011 }
1012 
1013 /// IsX86_MMXType - Return true if this is an MMX type.
1014 bool IsX86_MMXType(llvm::Type *IRType) {
1015   // Return true if the type is an MMX type <2 x i32>, <4 x i16>, or <8 x i8>.
1016   return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 &&
1017     cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() &&
1018     IRType->getScalarSizeInBits() != 64;
1019 }
1020 
1021 static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
1022                                           StringRef Constraint,
1023                                           llvm::Type* Ty) {
1024   bool IsMMXCons = llvm::StringSwitch<bool>(Constraint)
1025                      .Cases("y", "&y", "^Ym", true)
1026                      .Default(false);
1027   if (IsMMXCons && Ty->isVectorTy()) {
1028     if (cast<llvm::VectorType>(Ty)->getPrimitiveSizeInBits().getFixedSize() !=
1029         64) {
1030       // Invalid MMX constraint
1031       return nullptr;
1032     }
1033 
1034     return llvm::Type::getX86_MMXTy(CGF.getLLVMContext());
1035   }
1036 
1037   // No operation needed
1038   return Ty;
1039 }
1040 
1041 /// Returns true if this type can be passed in SSE registers with the
1042 /// X86_VectorCall calling convention. Shared between x86_32 and x86_64.
1043 static bool isX86VectorTypeForVectorCall(ASTContext &Context, QualType Ty) {
1044   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
1045     if (BT->isFloatingPoint() && BT->getKind() != BuiltinType::Half) {
1046       if (BT->getKind() == BuiltinType::LongDouble) {
1047         if (&Context.getTargetInfo().getLongDoubleFormat() ==
1048             &llvm::APFloat::x87DoubleExtended())
1049           return false;
1050       }
1051       return true;
1052     }
1053   } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
1054     // vectorcall can pass XMM, YMM, and ZMM vectors. We don't pass SSE1 MMX
1055     // registers specially.
1056     unsigned VecSize = Context.getTypeSize(VT);
1057     if (VecSize == 128 || VecSize == 256 || VecSize == 512)
1058       return true;
1059   }
1060   return false;
1061 }
1062 
1063 /// Returns true if this aggregate is small enough to be passed in SSE registers
1064 /// in the X86_VectorCall calling convention. Shared between x86_32 and x86_64.
1065 static bool isX86VectorCallAggregateSmallEnough(uint64_t NumMembers) {
1066   return NumMembers <= 4;
1067 }
1068 
1069 /// Returns a Homogeneous Vector Aggregate ABIArgInfo, used in X86.
1070 static ABIArgInfo getDirectX86Hva(llvm::Type* T = nullptr) {
1071   auto AI = ABIArgInfo::getDirect(T);
1072   AI.setInReg(true);
1073   AI.setCanBeFlattened(false);
1074   return AI;
1075 }
1076 
1077 //===----------------------------------------------------------------------===//
1078 // X86-32 ABI Implementation
1079 //===----------------------------------------------------------------------===//
1080 
1081 /// Similar to llvm::CCState, but for Clang.
1082 struct CCState {
1083   CCState(CGFunctionInfo &FI)
1084       : IsPreassigned(FI.arg_size()), CC(FI.getCallingConvention()) {}
1085 
1086   llvm::SmallBitVector IsPreassigned;
1087   unsigned CC = CallingConv::CC_C;
1088   unsigned FreeRegs = 0;
1089   unsigned FreeSSERegs = 0;
1090 };
1091 
1092 enum {
1093   // Vectorcall only allows the first 6 parameters to be passed in registers.
1094   VectorcallMaxParamNumAsReg = 6
1095 };
1096 
1097 /// X86_32ABIInfo - The X86-32 ABI information.
1098 class X86_32ABIInfo : public SwiftABIInfo {
1099   enum Class {
1100     Integer,
1101     Float
1102   };
1103 
1104   static const unsigned MinABIStackAlignInBytes = 4;
1105 
1106   bool IsDarwinVectorABI;
1107   bool IsRetSmallStructInRegABI;
1108   bool IsWin32StructABI;
1109   bool IsSoftFloatABI;
1110   bool IsMCUABI;
1111   unsigned DefaultNumRegisterParameters;
1112 
1113   static bool isRegisterSize(unsigned Size) {
1114     return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
1115   }
1116 
1117   bool isHomogeneousAggregateBaseType(QualType Ty) const override {
1118     // FIXME: Assumes vectorcall is in use.
1119     return isX86VectorTypeForVectorCall(getContext(), Ty);
1120   }
1121 
1122   bool isHomogeneousAggregateSmallEnough(const Type *Ty,
1123                                          uint64_t NumMembers) const override {
1124     // FIXME: Assumes vectorcall is in use.
1125     return isX86VectorCallAggregateSmallEnough(NumMembers);
1126   }
1127 
1128   bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context) const;
1129 
1130   /// getIndirectResult - Give a source type \arg Ty, return a suitable result
1131   /// such that the argument will be passed in memory.
1132   ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
1133 
1134   ABIArgInfo getIndirectReturnResult(QualType Ty, CCState &State) const;
1135 
1136   /// Return the alignment to use for the given type on the stack.
1137   unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const;
1138 
1139   Class classify(QualType Ty) const;
1140   ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const;
1141   ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
1142 
1143   /// Updates the number of available free registers, returns
1144   /// true if any registers were allocated.
1145   bool updateFreeRegs(QualType Ty, CCState &State) const;
1146 
1147   bool shouldAggregateUseDirect(QualType Ty, CCState &State, bool &InReg,
1148                                 bool &NeedsPadding) const;
1149   bool shouldPrimitiveUseInReg(QualType Ty, CCState &State) const;
1150 
1151   bool canExpandIndirectArgument(QualType Ty) const;
1152 
1153   /// Rewrite the function info so that all memory arguments use
1154   /// inalloca.
1155   void rewriteWithInAlloca(CGFunctionInfo &FI) const;
1156 
1157   void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
1158                            CharUnits &StackOffset, ABIArgInfo &Info,
1159                            QualType Type) const;
1160   void runVectorCallFirstPass(CGFunctionInfo &FI, CCState &State) const;
1161 
1162 public:
1163 
1164   void computeInfo(CGFunctionInfo &FI) const override;
1165   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
1166                     QualType Ty) const override;
1167 
1168   X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
1169                 bool RetSmallStructInRegABI, bool Win32StructABI,
1170                 unsigned NumRegisterParameters, bool SoftFloatABI)
1171     : SwiftABIInfo(CGT), IsDarwinVectorABI(DarwinVectorABI),
1172       IsRetSmallStructInRegABI(RetSmallStructInRegABI),
1173       IsWin32StructABI(Win32StructABI),
1174       IsSoftFloatABI(SoftFloatABI),
1175       IsMCUABI(CGT.getTarget().getTriple().isOSIAMCU()),
1176       DefaultNumRegisterParameters(NumRegisterParameters) {}
1177 
1178   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
1179                                     bool asReturnValue) const override {
1180     // LLVM's x86-32 lowering currently only assigns up to three
1181     // integer registers and three fp registers.  Oddly, it'll use up to
1182     // four vector registers for vectors, but those can overlap with the
1183     // scalar registers.
1184     return occupiesMoreThan(CGT, scalars, /*total*/ 3);
1185   }
1186 
1187   bool isSwiftErrorInRegister() const override {
1188     // x86-32 lowering does not support passing swifterror in a register.
1189     return false;
1190   }
1191 };
1192 
1193 class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
1194 public:
1195   X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
1196                           bool RetSmallStructInRegABI, bool Win32StructABI,
1197                           unsigned NumRegisterParameters, bool SoftFloatABI)
1198       : TargetCodeGenInfo(std::make_unique<X86_32ABIInfo>(
1199             CGT, DarwinVectorABI, RetSmallStructInRegABI, Win32StructABI,
1200             NumRegisterParameters, SoftFloatABI)) {}
1201 
1202   static bool isStructReturnInRegABI(
1203       const llvm::Triple &Triple, const CodeGenOptions &Opts);
1204 
1205   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
1206                            CodeGen::CodeGenModule &CGM) const override;
1207 
1208   int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
1209     // Darwin uses different dwarf register numbers for EH.
1210     if (CGM.getTarget().getTriple().isOSDarwin()) return 5;
1211     return 4;
1212   }
1213 
1214   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
1215                                llvm::Value *Address) const override;
1216 
1217   llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
1218                                   StringRef Constraint,
1219                                   llvm::Type* Ty) const override {
1220     return X86AdjustInlineAsmType(CGF, Constraint, Ty);
1221   }
1222 
1223   void addReturnRegisterOutputs(CodeGenFunction &CGF, LValue ReturnValue,
1224                                 std::string &Constraints,
1225                                 std::vector<llvm::Type *> &ResultRegTypes,
1226                                 std::vector<llvm::Type *> &ResultTruncRegTypes,
1227                                 std::vector<LValue> &ResultRegDests,
1228                                 std::string &AsmString,
1229                                 unsigned NumOutputs) const override;
1230 
1231   llvm::Constant *
1232   getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
1233     unsigned Sig = (0xeb << 0) |  // jmp rel8
1234                    (0x06 << 8) |  //           .+0x08
1235                    ('v' << 16) |
1236                    ('2' << 24);
1237     return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
1238   }
1239 
1240   StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
1241     return "movl\t%ebp, %ebp"
1242            "\t\t// marker for objc_retainAutoreleaseReturnValue";
1243   }
1244 };
1245 
1246 }
1247 
1248 /// Rewrite input constraint references after adding some output constraints.
1249 /// In the case where there is one output and one input and we add one output,
1250 /// we need to replace all operand references greater than or equal to 1:
1251 ///     mov $0, $1
1252 ///     mov eax, $1
1253 /// The result will be:
1254 ///     mov $0, $2
1255 ///     mov eax, $2
1256 static void rewriteInputConstraintReferences(unsigned FirstIn,
1257                                              unsigned NumNewOuts,
1258                                              std::string &AsmString) {
1259   std::string Buf;
1260   llvm::raw_string_ostream OS(Buf);
1261   size_t Pos = 0;
1262   while (Pos < AsmString.size()) {
1263     size_t DollarStart = AsmString.find('$', Pos);
1264     if (DollarStart == std::string::npos)
1265       DollarStart = AsmString.size();
1266     size_t DollarEnd = AsmString.find_first_not_of('$', DollarStart);
1267     if (DollarEnd == std::string::npos)
1268       DollarEnd = AsmString.size();
1269     OS << StringRef(&AsmString[Pos], DollarEnd - Pos);
1270     Pos = DollarEnd;
1271     size_t NumDollars = DollarEnd - DollarStart;
1272     if (NumDollars % 2 != 0 && Pos < AsmString.size()) {
1273       // We have an operand reference.
1274       size_t DigitStart = Pos;
1275       if (AsmString[DigitStart] == '{') {
1276         OS << '{';
1277         ++DigitStart;
1278       }
1279       size_t DigitEnd = AsmString.find_first_not_of("0123456789", DigitStart);
1280       if (DigitEnd == std::string::npos)
1281         DigitEnd = AsmString.size();
1282       StringRef OperandStr(&AsmString[DigitStart], DigitEnd - DigitStart);
1283       unsigned OperandIndex;
1284       if (!OperandStr.getAsInteger(10, OperandIndex)) {
1285         if (OperandIndex >= FirstIn)
1286           OperandIndex += NumNewOuts;
1287         OS << OperandIndex;
1288       } else {
1289         OS << OperandStr;
1290       }
1291       Pos = DigitEnd;
1292     }
1293   }
1294   AsmString = std::move(OS.str());
1295 }
1296 
1297 /// Add output constraints for EAX:EDX because they are return registers.
1298 void X86_32TargetCodeGenInfo::addReturnRegisterOutputs(
1299     CodeGenFunction &CGF, LValue ReturnSlot, std::string &Constraints,
1300     std::vector<llvm::Type *> &ResultRegTypes,
1301     std::vector<llvm::Type *> &ResultTruncRegTypes,
1302     std::vector<LValue> &ResultRegDests, std::string &AsmString,
1303     unsigned NumOutputs) const {
1304   uint64_t RetWidth = CGF.getContext().getTypeSize(ReturnSlot.getType());
1305 
1306   // Use the EAX constraint if the width is 32 or smaller and EAX:EDX if it is
1307   // larger.
1308   if (!Constraints.empty())
1309     Constraints += ',';
1310   if (RetWidth <= 32) {
1311     Constraints += "={eax}";
1312     ResultRegTypes.push_back(CGF.Int32Ty);
1313   } else {
1314     // Use the 'A' constraint for EAX:EDX.
1315     Constraints += "=A";
1316     ResultRegTypes.push_back(CGF.Int64Ty);
1317   }
1318 
1319   // Truncate EAX or EAX:EDX to an integer of the appropriate size.
1320   llvm::Type *CoerceTy = llvm::IntegerType::get(CGF.getLLVMContext(), RetWidth);
1321   ResultTruncRegTypes.push_back(CoerceTy);
1322 
1323   // Coerce the integer by bitcasting the return slot pointer.
1324   ReturnSlot.setAddress(CGF.Builder.CreateBitCast(ReturnSlot.getAddress(CGF),
1325                                                   CoerceTy->getPointerTo()));
1326   ResultRegDests.push_back(ReturnSlot);
1327 
1328   rewriteInputConstraintReferences(NumOutputs, 1, AsmString);
1329 }
1330 
1331 /// shouldReturnTypeInRegister - Determine if the given type should be
1332 /// returned in a register (for the Darwin and MCU ABI).
1333 bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
1334                                                ASTContext &Context) const {
1335   uint64_t Size = Context.getTypeSize(Ty);
1336 
1337   // For i386, type must be register sized.
1338   // For the MCU ABI, it only needs to be <= 8-byte
1339   if ((IsMCUABI && Size > 64) || (!IsMCUABI && !isRegisterSize(Size)))
1340    return false;
1341 
1342   if (Ty->isVectorType()) {
1343     // 64- and 128- bit vectors inside structures are not returned in
1344     // registers.
1345     if (Size == 64 || Size == 128)
1346       return false;
1347 
1348     return true;
1349   }
1350 
1351   // If this is a builtin, pointer, enum, complex type, member pointer, or
1352   // member function pointer it is ok.
1353   if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() ||
1354       Ty->isAnyComplexType() || Ty->isEnumeralType() ||
1355       Ty->isBlockPointerType() || Ty->isMemberPointerType())
1356     return true;
1357 
1358   // Arrays are treated like records.
1359   if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
1360     return shouldReturnTypeInRegister(AT->getElementType(), Context);
1361 
1362   // Otherwise, it must be a record type.
1363   const RecordType *RT = Ty->getAs<RecordType>();
1364   if (!RT) return false;
1365 
1366   // FIXME: Traverse bases here too.
1367 
1368   // Structure types are passed in register if all fields would be
1369   // passed in a register.
1370   for (const auto *FD : RT->getDecl()->fields()) {
1371     // Empty fields are ignored.
1372     if (isEmptyField(Context, FD, true))
1373       continue;
1374 
1375     // Check fields recursively.
1376     if (!shouldReturnTypeInRegister(FD->getType(), Context))
1377       return false;
1378   }
1379   return true;
1380 }
1381 
1382 static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
1383   // Treat complex types as the element type.
1384   if (const ComplexType *CTy = Ty->getAs<ComplexType>())
1385     Ty = CTy->getElementType();
1386 
1387   // Check for a type which we know has a simple scalar argument-passing
1388   // convention without any padding.  (We're specifically looking for 32
1389   // and 64-bit integer and integer-equivalents, float, and double.)
1390   if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() &&
1391       !Ty->isEnumeralType() && !Ty->isBlockPointerType())
1392     return false;
1393 
1394   uint64_t Size = Context.getTypeSize(Ty);
1395   return Size == 32 || Size == 64;
1396 }
1397 
1398 static bool addFieldSizes(ASTContext &Context, const RecordDecl *RD,
1399                           uint64_t &Size) {
1400   for (const auto *FD : RD->fields()) {
1401     // Scalar arguments on the stack get 4 byte alignment on x86. If the
1402     // argument is smaller than 32-bits, expanding the struct will create
1403     // alignment padding.
1404     if (!is32Or64BitBasicType(FD->getType(), Context))
1405       return false;
1406 
1407     // FIXME: Reject bit-fields wholesale; there are two problems, we don't know
1408     // how to expand them yet, and the predicate for telling if a bitfield still
1409     // counts as "basic" is more complicated than what we were doing previously.
1410     if (FD->isBitField())
1411       return false;
1412 
1413     Size += Context.getTypeSize(FD->getType());
1414   }
1415   return true;
1416 }
1417 
1418 static bool addBaseAndFieldSizes(ASTContext &Context, const CXXRecordDecl *RD,
1419                                  uint64_t &Size) {
1420   // Don't do this if there are any non-empty bases.
1421   for (const CXXBaseSpecifier &Base : RD->bases()) {
1422     if (!addBaseAndFieldSizes(Context, Base.getType()->getAsCXXRecordDecl(),
1423                               Size))
1424       return false;
1425   }
1426   if (!addFieldSizes(Context, RD, Size))
1427     return false;
1428   return true;
1429 }
1430 
1431 /// Test whether an argument type which is to be passed indirectly (on the
1432 /// stack) would have the equivalent layout if it was expanded into separate
1433 /// arguments. If so, we prefer to do the latter to avoid inhibiting
1434 /// optimizations.
1435 bool X86_32ABIInfo::canExpandIndirectArgument(QualType Ty) const {
1436   // We can only expand structure types.
1437   const RecordType *RT = Ty->getAs<RecordType>();
1438   if (!RT)
1439     return false;
1440   const RecordDecl *RD = RT->getDecl();
1441   uint64_t Size = 0;
1442   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
1443     if (!IsWin32StructABI) {
1444       // On non-Windows, we have to conservatively match our old bitcode
1445       // prototypes in order to be ABI-compatible at the bitcode level.
1446       if (!CXXRD->isCLike())
1447         return false;
1448     } else {
1449       // Don't do this for dynamic classes.
1450       if (CXXRD->isDynamicClass())
1451         return false;
1452     }
1453     if (!addBaseAndFieldSizes(getContext(), CXXRD, Size))
1454       return false;
1455   } else {
1456     if (!addFieldSizes(getContext(), RD, Size))
1457       return false;
1458   }
1459 
1460   // We can do this if there was no alignment padding.
1461   return Size == getContext().getTypeSize(Ty);
1462 }
1463 
1464 ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(QualType RetTy, CCState &State) const {
1465   // If the return value is indirect, then the hidden argument is consuming one
1466   // integer register.
1467   if (State.FreeRegs) {
1468     --State.FreeRegs;
1469     if (!IsMCUABI)
1470       return getNaturalAlignIndirectInReg(RetTy);
1471   }
1472   return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
1473 }
1474 
1475 ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy,
1476                                              CCState &State) const {
1477   if (RetTy->isVoidType())
1478     return ABIArgInfo::getIgnore();
1479 
1480   const Type *Base = nullptr;
1481   uint64_t NumElts = 0;
1482   if ((State.CC == llvm::CallingConv::X86_VectorCall ||
1483        State.CC == llvm::CallingConv::X86_RegCall) &&
1484       isHomogeneousAggregate(RetTy, Base, NumElts)) {
1485     // The LLVM struct type for such an aggregate should lower properly.
1486     return ABIArgInfo::getDirect();
1487   }
1488 
1489   if (const VectorType *VT = RetTy->getAs<VectorType>()) {
1490     // On Darwin, some vectors are returned in registers.
1491     if (IsDarwinVectorABI) {
1492       uint64_t Size = getContext().getTypeSize(RetTy);
1493 
1494       // 128-bit vectors are a special case; they are returned in
1495       // registers and we need to make sure to pick a type the LLVM
1496       // backend will like.
1497       if (Size == 128)
1498         return ABIArgInfo::getDirect(llvm::FixedVectorType::get(
1499             llvm::Type::getInt64Ty(getVMContext()), 2));
1500 
1501       // Always return in register if it fits in a general purpose
1502       // register, or if it is 64 bits and has a single element.
1503       if ((Size == 8 || Size == 16 || Size == 32) ||
1504           (Size == 64 && VT->getNumElements() == 1))
1505         return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
1506                                                             Size));
1507 
1508       return getIndirectReturnResult(RetTy, State);
1509     }
1510 
1511     return ABIArgInfo::getDirect();
1512   }
1513 
1514   if (isAggregateTypeForABI(RetTy)) {
1515     if (const RecordType *RT = RetTy->getAs<RecordType>()) {
1516       // Structures with flexible arrays are always indirect.
1517       if (RT->getDecl()->hasFlexibleArrayMember())
1518         return getIndirectReturnResult(RetTy, State);
1519     }
1520 
1521     // If specified, structs and unions are always indirect.
1522     if (!IsRetSmallStructInRegABI && !RetTy->isAnyComplexType())
1523       return getIndirectReturnResult(RetTy, State);
1524 
1525     // Ignore empty structs/unions.
1526     if (isEmptyRecord(getContext(), RetTy, true))
1527       return ABIArgInfo::getIgnore();
1528 
1529     // Small structures which are register sized are generally returned
1530     // in a register.
1531     if (shouldReturnTypeInRegister(RetTy, getContext())) {
1532       uint64_t Size = getContext().getTypeSize(RetTy);
1533 
1534       // As a special-case, if the struct is a "single-element" struct, and
1535       // the field is of type "float" or "double", return it in a
1536       // floating-point register. (MSVC does not apply this special case.)
1537       // We apply a similar transformation for pointer types to improve the
1538       // quality of the generated IR.
1539       if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
1540         if ((!IsWin32StructABI && SeltTy->isRealFloatingType())
1541             || SeltTy->hasPointerRepresentation())
1542           return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
1543 
1544       // FIXME: We should be able to narrow this integer in cases with dead
1545       // padding.
1546       return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
1547     }
1548 
1549     return getIndirectReturnResult(RetTy, State);
1550   }
1551 
1552   // Treat an enum type as its underlying type.
1553   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
1554     RetTy = EnumTy->getDecl()->getIntegerType();
1555 
1556   if (const auto *EIT = RetTy->getAs<ExtIntType>())
1557     if (EIT->getNumBits() > 64)
1558       return getIndirectReturnResult(RetTy, State);
1559 
1560   return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
1561                                                : ABIArgInfo::getDirect());
1562 }
1563 
1564 static bool isSIMDVectorType(ASTContext &Context, QualType Ty) {
1565   return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128;
1566 }
1567 
1568 static bool isRecordWithSIMDVectorType(ASTContext &Context, QualType Ty) {
1569   const RecordType *RT = Ty->getAs<RecordType>();
1570   if (!RT)
1571     return 0;
1572   const RecordDecl *RD = RT->getDecl();
1573 
1574   // If this is a C++ record, check the bases first.
1575   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
1576     for (const auto &I : CXXRD->bases())
1577       if (!isRecordWithSIMDVectorType(Context, I.getType()))
1578         return false;
1579 
1580   for (const auto *i : RD->fields()) {
1581     QualType FT = i->getType();
1582 
1583     if (isSIMDVectorType(Context, FT))
1584       return true;
1585 
1586     if (isRecordWithSIMDVectorType(Context, FT))
1587       return true;
1588   }
1589 
1590   return false;
1591 }
1592 
1593 unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
1594                                                  unsigned Align) const {
1595   // Otherwise, if the alignment is less than or equal to the minimum ABI
1596   // alignment, just use the default; the backend will handle this.
1597   if (Align <= MinABIStackAlignInBytes)
1598     return 0; // Use default alignment.
1599 
1600   // On non-Darwin, the stack type alignment is always 4.
1601   if (!IsDarwinVectorABI) {
1602     // Set explicit alignment, since we may need to realign the top.
1603     return MinABIStackAlignInBytes;
1604   }
1605 
1606   // Otherwise, if the type contains an SSE vector type, the alignment is 16.
1607   if (Align >= 16 && (isSIMDVectorType(getContext(), Ty) ||
1608                       isRecordWithSIMDVectorType(getContext(), Ty)))
1609     return 16;
1610 
1611   return MinABIStackAlignInBytes;
1612 }
1613 
1614 ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal,
1615                                             CCState &State) const {
1616   if (!ByVal) {
1617     if (State.FreeRegs) {
1618       --State.FreeRegs; // Non-byval indirects just use one pointer.
1619       if (!IsMCUABI)
1620         return getNaturalAlignIndirectInReg(Ty);
1621     }
1622     return getNaturalAlignIndirect(Ty, false);
1623   }
1624 
1625   // Compute the byval alignment.
1626   unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
1627   unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign);
1628   if (StackAlign == 0)
1629     return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true);
1630 
1631   // If the stack alignment is less than the type alignment, realign the
1632   // argument.
1633   bool Realign = TypeAlign > StackAlign;
1634   return ABIArgInfo::getIndirect(CharUnits::fromQuantity(StackAlign),
1635                                  /*ByVal=*/true, Realign);
1636 }
1637 
1638 X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const {
1639   const Type *T = isSingleElementStruct(Ty, getContext());
1640   if (!T)
1641     T = Ty.getTypePtr();
1642 
1643   if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
1644     BuiltinType::Kind K = BT->getKind();
1645     if (K == BuiltinType::Float || K == BuiltinType::Double)
1646       return Float;
1647   }
1648   return Integer;
1649 }
1650 
1651 bool X86_32ABIInfo::updateFreeRegs(QualType Ty, CCState &State) const {
1652   if (!IsSoftFloatABI) {
1653     Class C = classify(Ty);
1654     if (C == Float)
1655       return false;
1656   }
1657 
1658   unsigned Size = getContext().getTypeSize(Ty);
1659   unsigned SizeInRegs = (Size + 31) / 32;
1660 
1661   if (SizeInRegs == 0)
1662     return false;
1663 
1664   if (!IsMCUABI) {
1665     if (SizeInRegs > State.FreeRegs) {
1666       State.FreeRegs = 0;
1667       return false;
1668     }
1669   } else {
1670     // The MCU psABI allows passing parameters in-reg even if there are
1671     // earlier parameters that are passed on the stack. Also,
1672     // it does not allow passing >8-byte structs in-register,
1673     // even if there are 3 free registers available.
1674     if (SizeInRegs > State.FreeRegs || SizeInRegs > 2)
1675       return false;
1676   }
1677 
1678   State.FreeRegs -= SizeInRegs;
1679   return true;
1680 }
1681 
1682 bool X86_32ABIInfo::shouldAggregateUseDirect(QualType Ty, CCState &State,
1683                                              bool &InReg,
1684                                              bool &NeedsPadding) const {
1685   // On Windows, aggregates other than HFAs are never passed in registers, and
1686   // they do not consume register slots. Homogenous floating-point aggregates
1687   // (HFAs) have already been dealt with at this point.
1688   if (IsWin32StructABI && isAggregateTypeForABI(Ty))
1689     return false;
1690 
1691   NeedsPadding = false;
1692   InReg = !IsMCUABI;
1693 
1694   if (!updateFreeRegs(Ty, State))
1695     return false;
1696 
1697   if (IsMCUABI)
1698     return true;
1699 
1700   if (State.CC == llvm::CallingConv::X86_FastCall ||
1701       State.CC == llvm::CallingConv::X86_VectorCall ||
1702       State.CC == llvm::CallingConv::X86_RegCall) {
1703     if (getContext().getTypeSize(Ty) <= 32 && State.FreeRegs)
1704       NeedsPadding = true;
1705 
1706     return false;
1707   }
1708 
1709   return true;
1710 }
1711 
1712 bool X86_32ABIInfo::shouldPrimitiveUseInReg(QualType Ty, CCState &State) const {
1713   if (!updateFreeRegs(Ty, State))
1714     return false;
1715 
1716   if (IsMCUABI)
1717     return false;
1718 
1719   if (State.CC == llvm::CallingConv::X86_FastCall ||
1720       State.CC == llvm::CallingConv::X86_VectorCall ||
1721       State.CC == llvm::CallingConv::X86_RegCall) {
1722     if (getContext().getTypeSize(Ty) > 32)
1723       return false;
1724 
1725     return (Ty->isIntegralOrEnumerationType() || Ty->isPointerType() ||
1726         Ty->isReferenceType());
1727   }
1728 
1729   return true;
1730 }
1731 
1732 void X86_32ABIInfo::runVectorCallFirstPass(CGFunctionInfo &FI, CCState &State) const {
1733   // Vectorcall x86 works subtly different than in x64, so the format is
1734   // a bit different than the x64 version.  First, all vector types (not HVAs)
1735   // are assigned, with the first 6 ending up in the [XYZ]MM0-5 registers.
1736   // This differs from the x64 implementation, where the first 6 by INDEX get
1737   // registers.
1738   // In the second pass over the arguments, HVAs are passed in the remaining
1739   // vector registers if possible, or indirectly by address. The address will be
1740   // passed in ECX/EDX if available. Any other arguments are passed according to
1741   // the usual fastcall rules.
1742   MutableArrayRef<CGFunctionInfoArgInfo> Args = FI.arguments();
1743   for (int I = 0, E = Args.size(); I < E; ++I) {
1744     const Type *Base = nullptr;
1745     uint64_t NumElts = 0;
1746     const QualType &Ty = Args[I].type;
1747     if ((Ty->isVectorType() || Ty->isBuiltinType()) &&
1748         isHomogeneousAggregate(Ty, Base, NumElts)) {
1749       if (State.FreeSSERegs >= NumElts) {
1750         State.FreeSSERegs -= NumElts;
1751         Args[I].info = ABIArgInfo::getDirectInReg();
1752         State.IsPreassigned.set(I);
1753       }
1754     }
1755   }
1756 }
1757 
1758 ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
1759                                                CCState &State) const {
1760   // FIXME: Set alignment on indirect arguments.
1761   bool IsFastCall = State.CC == llvm::CallingConv::X86_FastCall;
1762   bool IsRegCall = State.CC == llvm::CallingConv::X86_RegCall;
1763   bool IsVectorCall = State.CC == llvm::CallingConv::X86_VectorCall;
1764 
1765   Ty = useFirstFieldIfTransparentUnion(Ty);
1766   TypeInfo TI = getContext().getTypeInfo(Ty);
1767 
1768   // Check with the C++ ABI first.
1769   const RecordType *RT = Ty->getAs<RecordType>();
1770   if (RT) {
1771     CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
1772     if (RAA == CGCXXABI::RAA_Indirect) {
1773       return getIndirectResult(Ty, false, State);
1774     } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
1775       // The field index doesn't matter, we'll fix it up later.
1776       return ABIArgInfo::getInAlloca(/*FieldIndex=*/0);
1777     }
1778   }
1779 
1780   // Regcall uses the concept of a homogenous vector aggregate, similar
1781   // to other targets.
1782   const Type *Base = nullptr;
1783   uint64_t NumElts = 0;
1784   if ((IsRegCall || IsVectorCall) &&
1785       isHomogeneousAggregate(Ty, Base, NumElts)) {
1786     if (State.FreeSSERegs >= NumElts) {
1787       State.FreeSSERegs -= NumElts;
1788 
1789       // Vectorcall passes HVAs directly and does not flatten them, but regcall
1790       // does.
1791       if (IsVectorCall)
1792         return getDirectX86Hva();
1793 
1794       if (Ty->isBuiltinType() || Ty->isVectorType())
1795         return ABIArgInfo::getDirect();
1796       return ABIArgInfo::getExpand();
1797     }
1798     return getIndirectResult(Ty, /*ByVal=*/false, State);
1799   }
1800 
1801   if (isAggregateTypeForABI(Ty)) {
1802     // Structures with flexible arrays are always indirect.
1803     // FIXME: This should not be byval!
1804     if (RT && RT->getDecl()->hasFlexibleArrayMember())
1805       return getIndirectResult(Ty, true, State);
1806 
1807     // Ignore empty structs/unions on non-Windows.
1808     if (!IsWin32StructABI && isEmptyRecord(getContext(), Ty, true))
1809       return ABIArgInfo::getIgnore();
1810 
1811     llvm::LLVMContext &LLVMContext = getVMContext();
1812     llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
1813     bool NeedsPadding = false;
1814     bool InReg;
1815     if (shouldAggregateUseDirect(Ty, State, InReg, NeedsPadding)) {
1816       unsigned SizeInRegs = (TI.Width + 31) / 32;
1817       SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32);
1818       llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
1819       if (InReg)
1820         return ABIArgInfo::getDirectInReg(Result);
1821       else
1822         return ABIArgInfo::getDirect(Result);
1823     }
1824     llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : nullptr;
1825 
1826     // Pass over-aligned aggregates on Windows indirectly. This behavior was
1827     // added in MSVC 2015.
1828     if (IsWin32StructABI && TI.AlignIsRequired && TI.Align > 32)
1829       return getIndirectResult(Ty, /*ByVal=*/false, State);
1830 
1831     // Expand small (<= 128-bit) record types when we know that the stack layout
1832     // of those arguments will match the struct. This is important because the
1833     // LLVM backend isn't smart enough to remove byval, which inhibits many
1834     // optimizations.
1835     // Don't do this for the MCU if there are still free integer registers
1836     // (see X86_64 ABI for full explanation).
1837     if (TI.Width <= 4 * 32 && (!IsMCUABI || State.FreeRegs == 0) &&
1838         canExpandIndirectArgument(Ty))
1839       return ABIArgInfo::getExpandWithPadding(
1840           IsFastCall || IsVectorCall || IsRegCall, PaddingType);
1841 
1842     return getIndirectResult(Ty, true, State);
1843   }
1844 
1845   if (const VectorType *VT = Ty->getAs<VectorType>()) {
1846     // On Windows, vectors are passed directly if registers are available, or
1847     // indirectly if not. This avoids the need to align argument memory. Pass
1848     // user-defined vector types larger than 512 bits indirectly for simplicity.
1849     if (IsWin32StructABI) {
1850       if (TI.Width <= 512 && State.FreeSSERegs > 0) {
1851         --State.FreeSSERegs;
1852         return ABIArgInfo::getDirectInReg();
1853       }
1854       return getIndirectResult(Ty, /*ByVal=*/false, State);
1855     }
1856 
1857     // On Darwin, some vectors are passed in memory, we handle this by passing
1858     // it as an i8/i16/i32/i64.
1859     if (IsDarwinVectorABI) {
1860       if ((TI.Width == 8 || TI.Width == 16 || TI.Width == 32) ||
1861           (TI.Width == 64 && VT->getNumElements() == 1))
1862         return ABIArgInfo::getDirect(
1863             llvm::IntegerType::get(getVMContext(), TI.Width));
1864     }
1865 
1866     if (IsX86_MMXType(CGT.ConvertType(Ty)))
1867       return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64));
1868 
1869     return ABIArgInfo::getDirect();
1870   }
1871 
1872 
1873   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1874     Ty = EnumTy->getDecl()->getIntegerType();
1875 
1876   bool InReg = shouldPrimitiveUseInReg(Ty, State);
1877 
1878   if (isPromotableIntegerTypeForABI(Ty)) {
1879     if (InReg)
1880       return ABIArgInfo::getExtendInReg(Ty);
1881     return ABIArgInfo::getExtend(Ty);
1882   }
1883 
1884   if (const auto * EIT = Ty->getAs<ExtIntType>()) {
1885     if (EIT->getNumBits() <= 64) {
1886       if (InReg)
1887         return ABIArgInfo::getDirectInReg();
1888       return ABIArgInfo::getDirect();
1889     }
1890     return getIndirectResult(Ty, /*ByVal=*/false, State);
1891   }
1892 
1893   if (InReg)
1894     return ABIArgInfo::getDirectInReg();
1895   return ABIArgInfo::getDirect();
1896 }
1897 
1898 void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const {
1899   CCState State(FI);
1900   if (IsMCUABI)
1901     State.FreeRegs = 3;
1902   else if (State.CC == llvm::CallingConv::X86_FastCall) {
1903     State.FreeRegs = 2;
1904     State.FreeSSERegs = 3;
1905   } else if (State.CC == llvm::CallingConv::X86_VectorCall) {
1906     State.FreeRegs = 2;
1907     State.FreeSSERegs = 6;
1908   } else if (FI.getHasRegParm())
1909     State.FreeRegs = FI.getRegParm();
1910   else if (State.CC == llvm::CallingConv::X86_RegCall) {
1911     State.FreeRegs = 5;
1912     State.FreeSSERegs = 8;
1913   } else if (IsWin32StructABI) {
1914     // Since MSVC 2015, the first three SSE vectors have been passed in
1915     // registers. The rest are passed indirectly.
1916     State.FreeRegs = DefaultNumRegisterParameters;
1917     State.FreeSSERegs = 3;
1918   } else
1919     State.FreeRegs = DefaultNumRegisterParameters;
1920 
1921   if (!::classifyReturnType(getCXXABI(), FI, *this)) {
1922     FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), State);
1923   } else if (FI.getReturnInfo().isIndirect()) {
1924     // The C++ ABI is not aware of register usage, so we have to check if the
1925     // return value was sret and put it in a register ourselves if appropriate.
1926     if (State.FreeRegs) {
1927       --State.FreeRegs;  // The sret parameter consumes a register.
1928       if (!IsMCUABI)
1929         FI.getReturnInfo().setInReg(true);
1930     }
1931   }
1932 
1933   // The chain argument effectively gives us another free register.
1934   if (FI.isChainCall())
1935     ++State.FreeRegs;
1936 
1937   // For vectorcall, do a first pass over the arguments, assigning FP and vector
1938   // arguments to XMM registers as available.
1939   if (State.CC == llvm::CallingConv::X86_VectorCall)
1940     runVectorCallFirstPass(FI, State);
1941 
1942   bool UsedInAlloca = false;
1943   MutableArrayRef<CGFunctionInfoArgInfo> Args = FI.arguments();
1944   for (int I = 0, E = Args.size(); I < E; ++I) {
1945     // Skip arguments that have already been assigned.
1946     if (State.IsPreassigned.test(I))
1947       continue;
1948 
1949     Args[I].info = classifyArgumentType(Args[I].type, State);
1950     UsedInAlloca |= (Args[I].info.getKind() == ABIArgInfo::InAlloca);
1951   }
1952 
1953   // If we needed to use inalloca for any argument, do a second pass and rewrite
1954   // all the memory arguments to use inalloca.
1955   if (UsedInAlloca)
1956     rewriteWithInAlloca(FI);
1957 }
1958 
1959 void
1960 X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
1961                                    CharUnits &StackOffset, ABIArgInfo &Info,
1962                                    QualType Type) const {
1963   // Arguments are always 4-byte-aligned.
1964   CharUnits WordSize = CharUnits::fromQuantity(4);
1965   assert(StackOffset.isMultipleOf(WordSize) && "unaligned inalloca struct");
1966 
1967   // sret pointers and indirect things will require an extra pointer
1968   // indirection, unless they are byval. Most things are byval, and will not
1969   // require this indirection.
1970   bool IsIndirect = false;
1971   if (Info.isIndirect() && !Info.getIndirectByVal())
1972     IsIndirect = true;
1973   Info = ABIArgInfo::getInAlloca(FrameFields.size(), IsIndirect);
1974   llvm::Type *LLTy = CGT.ConvertTypeForMem(Type);
1975   if (IsIndirect)
1976     LLTy = LLTy->getPointerTo(0);
1977   FrameFields.push_back(LLTy);
1978   StackOffset += IsIndirect ? WordSize : getContext().getTypeSizeInChars(Type);
1979 
1980   // Insert padding bytes to respect alignment.
1981   CharUnits FieldEnd = StackOffset;
1982   StackOffset = FieldEnd.alignTo(WordSize);
1983   if (StackOffset != FieldEnd) {
1984     CharUnits NumBytes = StackOffset - FieldEnd;
1985     llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext());
1986     Ty = llvm::ArrayType::get(Ty, NumBytes.getQuantity());
1987     FrameFields.push_back(Ty);
1988   }
1989 }
1990 
1991 static bool isArgInAlloca(const ABIArgInfo &Info) {
1992   // Leave ignored and inreg arguments alone.
1993   switch (Info.getKind()) {
1994   case ABIArgInfo::InAlloca:
1995     return true;
1996   case ABIArgInfo::Ignore:
1997   case ABIArgInfo::IndirectAliased:
1998     return false;
1999   case ABIArgInfo::Indirect:
2000   case ABIArgInfo::Direct:
2001   case ABIArgInfo::Extend:
2002     return !Info.getInReg();
2003   case ABIArgInfo::Expand:
2004   case ABIArgInfo::CoerceAndExpand:
2005     // These are aggregate types which are never passed in registers when
2006     // inalloca is involved.
2007     return true;
2008   }
2009   llvm_unreachable("invalid enum");
2010 }
2011 
2012 void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const {
2013   assert(IsWin32StructABI && "inalloca only supported on win32");
2014 
2015   // Build a packed struct type for all of the arguments in memory.
2016   SmallVector<llvm::Type *, 6> FrameFields;
2017 
2018   // The stack alignment is always 4.
2019   CharUnits StackAlign = CharUnits::fromQuantity(4);
2020 
2021   CharUnits StackOffset;
2022   CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end();
2023 
2024   // Put 'this' into the struct before 'sret', if necessary.
2025   bool IsThisCall =
2026       FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall;
2027   ABIArgInfo &Ret = FI.getReturnInfo();
2028   if (Ret.isIndirect() && Ret.isSRetAfterThis() && !IsThisCall &&
2029       isArgInAlloca(I->info)) {
2030     addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
2031     ++I;
2032   }
2033 
2034   // Put the sret parameter into the inalloca struct if it's in memory.
2035   if (Ret.isIndirect() && !Ret.getInReg()) {
2036     addFieldToArgStruct(FrameFields, StackOffset, Ret, FI.getReturnType());
2037     // On Windows, the hidden sret parameter is always returned in eax.
2038     Ret.setInAllocaSRet(IsWin32StructABI);
2039   }
2040 
2041   // Skip the 'this' parameter in ecx.
2042   if (IsThisCall)
2043     ++I;
2044 
2045   // Put arguments passed in memory into the struct.
2046   for (; I != E; ++I) {
2047     if (isArgInAlloca(I->info))
2048       addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
2049   }
2050 
2051   FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields,
2052                                         /*isPacked=*/true),
2053                   StackAlign);
2054 }
2055 
2056 Address X86_32ABIInfo::EmitVAArg(CodeGenFunction &CGF,
2057                                  Address VAListAddr, QualType Ty) const {
2058 
2059   auto TypeInfo = getContext().getTypeInfoInChars(Ty);
2060 
2061   // x86-32 changes the alignment of certain arguments on the stack.
2062   //
2063   // Just messing with TypeInfo like this works because we never pass
2064   // anything indirectly.
2065   TypeInfo.Align = CharUnits::fromQuantity(
2066                 getTypeStackAlignInBytes(Ty, TypeInfo.Align.getQuantity()));
2067 
2068   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
2069                           TypeInfo, CharUnits::fromQuantity(4),
2070                           /*AllowHigherAlign*/ true);
2071 }
2072 
2073 bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
2074     const llvm::Triple &Triple, const CodeGenOptions &Opts) {
2075   assert(Triple.getArch() == llvm::Triple::x86);
2076 
2077   switch (Opts.getStructReturnConvention()) {
2078   case CodeGenOptions::SRCK_Default:
2079     break;
2080   case CodeGenOptions::SRCK_OnStack:  // -fpcc-struct-return
2081     return false;
2082   case CodeGenOptions::SRCK_InRegs:  // -freg-struct-return
2083     return true;
2084   }
2085 
2086   if (Triple.isOSDarwin() || Triple.isOSIAMCU())
2087     return true;
2088 
2089   switch (Triple.getOS()) {
2090   case llvm::Triple::DragonFly:
2091   case llvm::Triple::FreeBSD:
2092   case llvm::Triple::OpenBSD:
2093   case llvm::Triple::Win32:
2094     return true;
2095   default:
2096     return false;
2097   }
2098 }
2099 
2100 void X86_32TargetCodeGenInfo::setTargetAttributes(
2101     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
2102   if (GV->isDeclaration())
2103     return;
2104   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2105     if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
2106       llvm::Function *Fn = cast<llvm::Function>(GV);
2107       Fn->addFnAttr("stackrealign");
2108     }
2109     if (FD->hasAttr<AnyX86InterruptAttr>()) {
2110       llvm::Function *Fn = cast<llvm::Function>(GV);
2111       Fn->setCallingConv(llvm::CallingConv::X86_INTR);
2112     }
2113   }
2114 }
2115 
2116 bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
2117                                                CodeGen::CodeGenFunction &CGF,
2118                                                llvm::Value *Address) const {
2119   CodeGen::CGBuilderTy &Builder = CGF.Builder;
2120 
2121   llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
2122 
2123   // 0-7 are the eight integer registers;  the order is different
2124   //   on Darwin (for EH), but the range is the same.
2125   // 8 is %eip.
2126   AssignToArrayRange(Builder, Address, Four8, 0, 8);
2127 
2128   if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
2129     // 12-16 are st(0..4).  Not sure why we stop at 4.
2130     // These have size 16, which is sizeof(long double) on
2131     // platforms with 8-byte alignment for that type.
2132     llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
2133     AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
2134 
2135   } else {
2136     // 9 is %eflags, which doesn't get a size on Darwin for some
2137     // reason.
2138     Builder.CreateAlignedStore(
2139         Four8, Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, Address, 9),
2140                                CharUnits::One());
2141 
2142     // 11-16 are st(0..5).  Not sure why we stop at 5.
2143     // These have size 12, which is sizeof(long double) on
2144     // platforms with 4-byte alignment for that type.
2145     llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
2146     AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
2147   }
2148 
2149   return false;
2150 }
2151 
2152 //===----------------------------------------------------------------------===//
2153 // X86-64 ABI Implementation
2154 //===----------------------------------------------------------------------===//
2155 
2156 
2157 namespace {
2158 /// The AVX ABI level for X86 targets.
2159 enum class X86AVXABILevel {
2160   None,
2161   AVX,
2162   AVX512
2163 };
2164 
2165 /// \p returns the size in bits of the largest (native) vector for \p AVXLevel.
2166 static unsigned getNativeVectorSizeForAVXABI(X86AVXABILevel AVXLevel) {
2167   switch (AVXLevel) {
2168   case X86AVXABILevel::AVX512:
2169     return 512;
2170   case X86AVXABILevel::AVX:
2171     return 256;
2172   case X86AVXABILevel::None:
2173     return 128;
2174   }
2175   llvm_unreachable("Unknown AVXLevel");
2176 }
2177 
2178 /// X86_64ABIInfo - The X86_64 ABI information.
2179 class X86_64ABIInfo : public SwiftABIInfo {
2180   enum Class {
2181     Integer = 0,
2182     SSE,
2183     SSEUp,
2184     X87,
2185     X87Up,
2186     ComplexX87,
2187     NoClass,
2188     Memory
2189   };
2190 
2191   /// merge - Implement the X86_64 ABI merging algorithm.
2192   ///
2193   /// Merge an accumulating classification \arg Accum with a field
2194   /// classification \arg Field.
2195   ///
2196   /// \param Accum - The accumulating classification. This should
2197   /// always be either NoClass or the result of a previous merge
2198   /// call. In addition, this should never be Memory (the caller
2199   /// should just return Memory for the aggregate).
2200   static Class merge(Class Accum, Class Field);
2201 
2202   /// postMerge - Implement the X86_64 ABI post merging algorithm.
2203   ///
2204   /// Post merger cleanup, reduces a malformed Hi and Lo pair to
2205   /// final MEMORY or SSE classes when necessary.
2206   ///
2207   /// \param AggregateSize - The size of the current aggregate in
2208   /// the classification process.
2209   ///
2210   /// \param Lo - The classification for the parts of the type
2211   /// residing in the low word of the containing object.
2212   ///
2213   /// \param Hi - The classification for the parts of the type
2214   /// residing in the higher words of the containing object.
2215   ///
2216   void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
2217 
2218   /// classify - Determine the x86_64 register classes in which the
2219   /// given type T should be passed.
2220   ///
2221   /// \param Lo - The classification for the parts of the type
2222   /// residing in the low word of the containing object.
2223   ///
2224   /// \param Hi - The classification for the parts of the type
2225   /// residing in the high word of the containing object.
2226   ///
2227   /// \param OffsetBase - The bit offset of this type in the
2228   /// containing object.  Some parameters are classified different
2229   /// depending on whether they straddle an eightbyte boundary.
2230   ///
2231   /// \param isNamedArg - Whether the argument in question is a "named"
2232   /// argument, as used in AMD64-ABI 3.5.7.
2233   ///
2234   /// If a word is unused its result will be NoClass; if a type should
2235   /// be passed in Memory then at least the classification of \arg Lo
2236   /// will be Memory.
2237   ///
2238   /// The \arg Lo class will be NoClass iff the argument is ignored.
2239   ///
2240   /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
2241   /// also be ComplexX87.
2242   void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi,
2243                 bool isNamedArg) const;
2244 
2245   llvm::Type *GetByteVectorType(QualType Ty) const;
2246   llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
2247                                  unsigned IROffset, QualType SourceTy,
2248                                  unsigned SourceOffset) const;
2249   llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
2250                                      unsigned IROffset, QualType SourceTy,
2251                                      unsigned SourceOffset) const;
2252 
2253   /// getIndirectResult - Give a source type \arg Ty, return a suitable result
2254   /// such that the argument will be returned in memory.
2255   ABIArgInfo getIndirectReturnResult(QualType Ty) const;
2256 
2257   /// getIndirectResult - Give a source type \arg Ty, return a suitable result
2258   /// such that the argument will be passed in memory.
2259   ///
2260   /// \param freeIntRegs - The number of free integer registers remaining
2261   /// available.
2262   ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
2263 
2264   ABIArgInfo classifyReturnType(QualType RetTy) const;
2265 
2266   ABIArgInfo classifyArgumentType(QualType Ty, unsigned freeIntRegs,
2267                                   unsigned &neededInt, unsigned &neededSSE,
2268                                   bool isNamedArg) const;
2269 
2270   ABIArgInfo classifyRegCallStructType(QualType Ty, unsigned &NeededInt,
2271                                        unsigned &NeededSSE) const;
2272 
2273   ABIArgInfo classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
2274                                            unsigned &NeededSSE) const;
2275 
2276   bool IsIllegalVectorType(QualType Ty) const;
2277 
2278   /// The 0.98 ABI revision clarified a lot of ambiguities,
2279   /// unfortunately in ways that were not always consistent with
2280   /// certain previous compilers.  In particular, platforms which
2281   /// required strict binary compatibility with older versions of GCC
2282   /// may need to exempt themselves.
2283   bool honorsRevision0_98() const {
2284     return !getTarget().getTriple().isOSDarwin();
2285   }
2286 
2287   /// GCC classifies <1 x long long> as SSE but some platform ABIs choose to
2288   /// classify it as INTEGER (for compatibility with older clang compilers).
2289   bool classifyIntegerMMXAsSSE() const {
2290     // Clang <= 3.8 did not do this.
2291     if (getContext().getLangOpts().getClangABICompat() <=
2292         LangOptions::ClangABI::Ver3_8)
2293       return false;
2294 
2295     const llvm::Triple &Triple = getTarget().getTriple();
2296     if (Triple.isOSDarwin() || Triple.getOS() == llvm::Triple::PS4)
2297       return false;
2298     if (Triple.isOSFreeBSD() && Triple.getOSMajorVersion() >= 10)
2299       return false;
2300     return true;
2301   }
2302 
2303   // GCC classifies vectors of __int128 as memory.
2304   bool passInt128VectorsInMem() const {
2305     // Clang <= 9.0 did not do this.
2306     if (getContext().getLangOpts().getClangABICompat() <=
2307         LangOptions::ClangABI::Ver9)
2308       return false;
2309 
2310     const llvm::Triple &T = getTarget().getTriple();
2311     return T.isOSLinux() || T.isOSNetBSD();
2312   }
2313 
2314   X86AVXABILevel AVXLevel;
2315   // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
2316   // 64-bit hardware.
2317   bool Has64BitPointers;
2318 
2319 public:
2320   X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) :
2321       SwiftABIInfo(CGT), AVXLevel(AVXLevel),
2322       Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {
2323   }
2324 
2325   bool isPassedUsingAVXType(QualType type) const {
2326     unsigned neededInt, neededSSE;
2327     // The freeIntRegs argument doesn't matter here.
2328     ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE,
2329                                            /*isNamedArg*/true);
2330     if (info.isDirect()) {
2331       llvm::Type *ty = info.getCoerceToType();
2332       if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
2333         return vectorTy->getPrimitiveSizeInBits().getFixedSize() > 128;
2334     }
2335     return false;
2336   }
2337 
2338   void computeInfo(CGFunctionInfo &FI) const override;
2339 
2340   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
2341                     QualType Ty) const override;
2342   Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
2343                       QualType Ty) const override;
2344 
2345   bool has64BitPointers() const {
2346     return Has64BitPointers;
2347   }
2348 
2349   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
2350                                     bool asReturnValue) const override {
2351     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
2352   }
2353   bool isSwiftErrorInRegister() const override {
2354     return true;
2355   }
2356 };
2357 
2358 /// WinX86_64ABIInfo - The Windows X86_64 ABI information.
2359 class WinX86_64ABIInfo : public SwiftABIInfo {
2360 public:
2361   WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
2362       : SwiftABIInfo(CGT), AVXLevel(AVXLevel),
2363         IsMingw64(getTarget().getTriple().isWindowsGNUEnvironment()) {}
2364 
2365   void computeInfo(CGFunctionInfo &FI) const override;
2366 
2367   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
2368                     QualType Ty) const override;
2369 
2370   bool isHomogeneousAggregateBaseType(QualType Ty) const override {
2371     // FIXME: Assumes vectorcall is in use.
2372     return isX86VectorTypeForVectorCall(getContext(), Ty);
2373   }
2374 
2375   bool isHomogeneousAggregateSmallEnough(const Type *Ty,
2376                                          uint64_t NumMembers) const override {
2377     // FIXME: Assumes vectorcall is in use.
2378     return isX86VectorCallAggregateSmallEnough(NumMembers);
2379   }
2380 
2381   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type *> scalars,
2382                                     bool asReturnValue) const override {
2383     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
2384   }
2385 
2386   bool isSwiftErrorInRegister() const override {
2387     return true;
2388   }
2389 
2390 private:
2391   ABIArgInfo classify(QualType Ty, unsigned &FreeSSERegs, bool IsReturnType,
2392                       bool IsVectorCall, bool IsRegCall) const;
2393   ABIArgInfo reclassifyHvaArgType(QualType Ty, unsigned &FreeSSERegs,
2394                                       const ABIArgInfo &current) const;
2395   void computeVectorCallArgs(CGFunctionInfo &FI, unsigned FreeSSERegs,
2396                              bool IsVectorCall, bool IsRegCall) const;
2397 
2398   X86AVXABILevel AVXLevel;
2399 
2400   bool IsMingw64;
2401 };
2402 
2403 class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2404 public:
2405   X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
2406       : TargetCodeGenInfo(std::make_unique<X86_64ABIInfo>(CGT, AVXLevel)) {}
2407 
2408   const X86_64ABIInfo &getABIInfo() const {
2409     return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
2410   }
2411 
2412   /// Disable tail call on x86-64. The epilogue code before the tail jump blocks
2413   /// autoreleaseRV/retainRV and autoreleaseRV/unsafeClaimRV optimizations.
2414   bool markARCOptimizedReturnCallsAsNoTail() const override { return true; }
2415 
2416   int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
2417     return 7;
2418   }
2419 
2420   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2421                                llvm::Value *Address) const override {
2422     llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
2423 
2424     // 0-15 are the 16 integer registers.
2425     // 16 is %rip.
2426     AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
2427     return false;
2428   }
2429 
2430   llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
2431                                   StringRef Constraint,
2432                                   llvm::Type* Ty) const override {
2433     return X86AdjustInlineAsmType(CGF, Constraint, Ty);
2434   }
2435 
2436   bool isNoProtoCallVariadic(const CallArgList &args,
2437                              const FunctionNoProtoType *fnType) const override {
2438     // The default CC on x86-64 sets %al to the number of SSA
2439     // registers used, and GCC sets this when calling an unprototyped
2440     // function, so we override the default behavior.  However, don't do
2441     // that when AVX types are involved: the ABI explicitly states it is
2442     // undefined, and it doesn't work in practice because of how the ABI
2443     // defines varargs anyway.
2444     if (fnType->getCallConv() == CC_C) {
2445       bool HasAVXType = false;
2446       for (CallArgList::const_iterator
2447              it = args.begin(), ie = args.end(); it != ie; ++it) {
2448         if (getABIInfo().isPassedUsingAVXType(it->Ty)) {
2449           HasAVXType = true;
2450           break;
2451         }
2452       }
2453 
2454       if (!HasAVXType)
2455         return true;
2456     }
2457 
2458     return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
2459   }
2460 
2461   llvm::Constant *
2462   getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
2463     unsigned Sig = (0xeb << 0) | // jmp rel8
2464                    (0x06 << 8) | //           .+0x08
2465                    ('v' << 16) |
2466                    ('2' << 24);
2467     return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
2468   }
2469 
2470   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2471                            CodeGen::CodeGenModule &CGM) const override {
2472     if (GV->isDeclaration())
2473       return;
2474     if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2475       if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
2476         llvm::Function *Fn = cast<llvm::Function>(GV);
2477         Fn->addFnAttr("stackrealign");
2478       }
2479       if (FD->hasAttr<AnyX86InterruptAttr>()) {
2480         llvm::Function *Fn = cast<llvm::Function>(GV);
2481         Fn->setCallingConv(llvm::CallingConv::X86_INTR);
2482       }
2483     }
2484   }
2485 
2486   void checkFunctionCallABI(CodeGenModule &CGM, SourceLocation CallLoc,
2487                             const FunctionDecl *Caller,
2488                             const FunctionDecl *Callee,
2489                             const CallArgList &Args) const override;
2490 };
2491 
2492 static void initFeatureMaps(const ASTContext &Ctx,
2493                             llvm::StringMap<bool> &CallerMap,
2494                             const FunctionDecl *Caller,
2495                             llvm::StringMap<bool> &CalleeMap,
2496                             const FunctionDecl *Callee) {
2497   if (CalleeMap.empty() && CallerMap.empty()) {
2498     // The caller is potentially nullptr in the case where the call isn't in a
2499     // function.  In this case, the getFunctionFeatureMap ensures we just get
2500     // the TU level setting (since it cannot be modified by 'target'..
2501     Ctx.getFunctionFeatureMap(CallerMap, Caller);
2502     Ctx.getFunctionFeatureMap(CalleeMap, Callee);
2503   }
2504 }
2505 
2506 static bool checkAVXParamFeature(DiagnosticsEngine &Diag,
2507                                  SourceLocation CallLoc,
2508                                  const llvm::StringMap<bool> &CallerMap,
2509                                  const llvm::StringMap<bool> &CalleeMap,
2510                                  QualType Ty, StringRef Feature,
2511                                  bool IsArgument) {
2512   bool CallerHasFeat = CallerMap.lookup(Feature);
2513   bool CalleeHasFeat = CalleeMap.lookup(Feature);
2514   if (!CallerHasFeat && !CalleeHasFeat)
2515     return Diag.Report(CallLoc, diag::warn_avx_calling_convention)
2516            << IsArgument << Ty << Feature;
2517 
2518   // Mixing calling conventions here is very clearly an error.
2519   if (!CallerHasFeat || !CalleeHasFeat)
2520     return Diag.Report(CallLoc, diag::err_avx_calling_convention)
2521            << IsArgument << Ty << Feature;
2522 
2523   // Else, both caller and callee have the required feature, so there is no need
2524   // to diagnose.
2525   return false;
2526 }
2527 
2528 static bool checkAVXParam(DiagnosticsEngine &Diag, ASTContext &Ctx,
2529                           SourceLocation CallLoc,
2530                           const llvm::StringMap<bool> &CallerMap,
2531                           const llvm::StringMap<bool> &CalleeMap, QualType Ty,
2532                           bool IsArgument) {
2533   uint64_t Size = Ctx.getTypeSize(Ty);
2534   if (Size > 256)
2535     return checkAVXParamFeature(Diag, CallLoc, CallerMap, CalleeMap, Ty,
2536                                 "avx512f", IsArgument);
2537 
2538   if (Size > 128)
2539     return checkAVXParamFeature(Diag, CallLoc, CallerMap, CalleeMap, Ty, "avx",
2540                                 IsArgument);
2541 
2542   return false;
2543 }
2544 
2545 void X86_64TargetCodeGenInfo::checkFunctionCallABI(
2546     CodeGenModule &CGM, SourceLocation CallLoc, const FunctionDecl *Caller,
2547     const FunctionDecl *Callee, const CallArgList &Args) const {
2548   llvm::StringMap<bool> CallerMap;
2549   llvm::StringMap<bool> CalleeMap;
2550   unsigned ArgIndex = 0;
2551 
2552   // We need to loop through the actual call arguments rather than the the
2553   // function's parameters, in case this variadic.
2554   for (const CallArg &Arg : Args) {
2555     // The "avx" feature changes how vectors >128 in size are passed. "avx512f"
2556     // additionally changes how vectors >256 in size are passed. Like GCC, we
2557     // warn when a function is called with an argument where this will change.
2558     // Unlike GCC, we also error when it is an obvious ABI mismatch, that is,
2559     // the caller and callee features are mismatched.
2560     // Unfortunately, we cannot do this diagnostic in SEMA, since the callee can
2561     // change its ABI with attribute-target after this call.
2562     if (Arg.getType()->isVectorType() &&
2563         CGM.getContext().getTypeSize(Arg.getType()) > 128) {
2564       initFeatureMaps(CGM.getContext(), CallerMap, Caller, CalleeMap, Callee);
2565       QualType Ty = Arg.getType();
2566       // The CallArg seems to have desugared the type already, so for clearer
2567       // diagnostics, replace it with the type in the FunctionDecl if possible.
2568       if (ArgIndex < Callee->getNumParams())
2569         Ty = Callee->getParamDecl(ArgIndex)->getType();
2570 
2571       if (checkAVXParam(CGM.getDiags(), CGM.getContext(), CallLoc, CallerMap,
2572                         CalleeMap, Ty, /*IsArgument*/ true))
2573         return;
2574     }
2575     ++ArgIndex;
2576   }
2577 
2578   // Check return always, as we don't have a good way of knowing in codegen
2579   // whether this value is used, tail-called, etc.
2580   if (Callee->getReturnType()->isVectorType() &&
2581       CGM.getContext().getTypeSize(Callee->getReturnType()) > 128) {
2582     initFeatureMaps(CGM.getContext(), CallerMap, Caller, CalleeMap, Callee);
2583     checkAVXParam(CGM.getDiags(), CGM.getContext(), CallLoc, CallerMap,
2584                   CalleeMap, Callee->getReturnType(),
2585                   /*IsArgument*/ false);
2586   }
2587 }
2588 
2589 static std::string qualifyWindowsLibrary(llvm::StringRef Lib) {
2590   // If the argument does not end in .lib, automatically add the suffix.
2591   // If the argument contains a space, enclose it in quotes.
2592   // This matches the behavior of MSVC.
2593   bool Quote = (Lib.find(" ") != StringRef::npos);
2594   std::string ArgStr = Quote ? "\"" : "";
2595   ArgStr += Lib;
2596   if (!Lib.endswith_lower(".lib") && !Lib.endswith_lower(".a"))
2597     ArgStr += ".lib";
2598   ArgStr += Quote ? "\"" : "";
2599   return ArgStr;
2600 }
2601 
2602 class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
2603 public:
2604   WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
2605         bool DarwinVectorABI, bool RetSmallStructInRegABI, bool Win32StructABI,
2606         unsigned NumRegisterParameters)
2607     : X86_32TargetCodeGenInfo(CGT, DarwinVectorABI, RetSmallStructInRegABI,
2608         Win32StructABI, NumRegisterParameters, false) {}
2609 
2610   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2611                            CodeGen::CodeGenModule &CGM) const override;
2612 
2613   void getDependentLibraryOption(llvm::StringRef Lib,
2614                                  llvm::SmallString<24> &Opt) const override {
2615     Opt = "/DEFAULTLIB:";
2616     Opt += qualifyWindowsLibrary(Lib);
2617   }
2618 
2619   void getDetectMismatchOption(llvm::StringRef Name,
2620                                llvm::StringRef Value,
2621                                llvm::SmallString<32> &Opt) const override {
2622     Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
2623   }
2624 };
2625 
2626 static void addStackProbeTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2627                                           CodeGen::CodeGenModule &CGM) {
2628   if (llvm::Function *Fn = dyn_cast_or_null<llvm::Function>(GV)) {
2629 
2630     if (CGM.getCodeGenOpts().StackProbeSize != 4096)
2631       Fn->addFnAttr("stack-probe-size",
2632                     llvm::utostr(CGM.getCodeGenOpts().StackProbeSize));
2633     if (CGM.getCodeGenOpts().NoStackArgProbe)
2634       Fn->addFnAttr("no-stack-arg-probe");
2635   }
2636 }
2637 
2638 void WinX86_32TargetCodeGenInfo::setTargetAttributes(
2639     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
2640   X86_32TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
2641   if (GV->isDeclaration())
2642     return;
2643   addStackProbeTargetAttributes(D, GV, CGM);
2644 }
2645 
2646 class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2647 public:
2648   WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
2649                              X86AVXABILevel AVXLevel)
2650       : TargetCodeGenInfo(std::make_unique<WinX86_64ABIInfo>(CGT, AVXLevel)) {}
2651 
2652   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2653                            CodeGen::CodeGenModule &CGM) const override;
2654 
2655   int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
2656     return 7;
2657   }
2658 
2659   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2660                                llvm::Value *Address) const override {
2661     llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
2662 
2663     // 0-15 are the 16 integer registers.
2664     // 16 is %rip.
2665     AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
2666     return false;
2667   }
2668 
2669   void getDependentLibraryOption(llvm::StringRef Lib,
2670                                  llvm::SmallString<24> &Opt) const override {
2671     Opt = "/DEFAULTLIB:";
2672     Opt += qualifyWindowsLibrary(Lib);
2673   }
2674 
2675   void getDetectMismatchOption(llvm::StringRef Name,
2676                                llvm::StringRef Value,
2677                                llvm::SmallString<32> &Opt) const override {
2678     Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
2679   }
2680 };
2681 
2682 void WinX86_64TargetCodeGenInfo::setTargetAttributes(
2683     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
2684   TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
2685   if (GV->isDeclaration())
2686     return;
2687   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2688     if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
2689       llvm::Function *Fn = cast<llvm::Function>(GV);
2690       Fn->addFnAttr("stackrealign");
2691     }
2692     if (FD->hasAttr<AnyX86InterruptAttr>()) {
2693       llvm::Function *Fn = cast<llvm::Function>(GV);
2694       Fn->setCallingConv(llvm::CallingConv::X86_INTR);
2695     }
2696   }
2697 
2698   addStackProbeTargetAttributes(D, GV, CGM);
2699 }
2700 }
2701 
2702 void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
2703                               Class &Hi) const {
2704   // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
2705   //
2706   // (a) If one of the classes is Memory, the whole argument is passed in
2707   //     memory.
2708   //
2709   // (b) If X87UP is not preceded by X87, the whole argument is passed in
2710   //     memory.
2711   //
2712   // (c) If the size of the aggregate exceeds two eightbytes and the first
2713   //     eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
2714   //     argument is passed in memory. NOTE: This is necessary to keep the
2715   //     ABI working for processors that don't support the __m256 type.
2716   //
2717   // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
2718   //
2719   // Some of these are enforced by the merging logic.  Others can arise
2720   // only with unions; for example:
2721   //   union { _Complex double; unsigned; }
2722   //
2723   // Note that clauses (b) and (c) were added in 0.98.
2724   //
2725   if (Hi == Memory)
2726     Lo = Memory;
2727   if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
2728     Lo = Memory;
2729   if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
2730     Lo = Memory;
2731   if (Hi == SSEUp && Lo != SSE)
2732     Hi = SSE;
2733 }
2734 
2735 X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
2736   // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
2737   // classified recursively so that always two fields are
2738   // considered. The resulting class is calculated according to
2739   // the classes of the fields in the eightbyte:
2740   //
2741   // (a) If both classes are equal, this is the resulting class.
2742   //
2743   // (b) If one of the classes is NO_CLASS, the resulting class is
2744   // the other class.
2745   //
2746   // (c) If one of the classes is MEMORY, the result is the MEMORY
2747   // class.
2748   //
2749   // (d) If one of the classes is INTEGER, the result is the
2750   // INTEGER.
2751   //
2752   // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
2753   // MEMORY is used as class.
2754   //
2755   // (f) Otherwise class SSE is used.
2756 
2757   // Accum should never be memory (we should have returned) or
2758   // ComplexX87 (because this cannot be passed in a structure).
2759   assert((Accum != Memory && Accum != ComplexX87) &&
2760          "Invalid accumulated classification during merge.");
2761   if (Accum == Field || Field == NoClass)
2762     return Accum;
2763   if (Field == Memory)
2764     return Memory;
2765   if (Accum == NoClass)
2766     return Field;
2767   if (Accum == Integer || Field == Integer)
2768     return Integer;
2769   if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
2770       Accum == X87 || Accum == X87Up)
2771     return Memory;
2772   return SSE;
2773 }
2774 
2775 void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
2776                              Class &Lo, Class &Hi, bool isNamedArg) const {
2777   // FIXME: This code can be simplified by introducing a simple value class for
2778   // Class pairs with appropriate constructor methods for the various
2779   // situations.
2780 
2781   // FIXME: Some of the split computations are wrong; unaligned vectors
2782   // shouldn't be passed in registers for example, so there is no chance they
2783   // can straddle an eightbyte. Verify & simplify.
2784 
2785   Lo = Hi = NoClass;
2786 
2787   Class &Current = OffsetBase < 64 ? Lo : Hi;
2788   Current = Memory;
2789 
2790   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
2791     BuiltinType::Kind k = BT->getKind();
2792 
2793     if (k == BuiltinType::Void) {
2794       Current = NoClass;
2795     } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
2796       Lo = Integer;
2797       Hi = Integer;
2798     } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
2799       Current = Integer;
2800     } else if (k == BuiltinType::Float || k == BuiltinType::Double) {
2801       Current = SSE;
2802     } else if (k == BuiltinType::LongDouble) {
2803       const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
2804       if (LDF == &llvm::APFloat::IEEEquad()) {
2805         Lo = SSE;
2806         Hi = SSEUp;
2807       } else if (LDF == &llvm::APFloat::x87DoubleExtended()) {
2808         Lo = X87;
2809         Hi = X87Up;
2810       } else if (LDF == &llvm::APFloat::IEEEdouble()) {
2811         Current = SSE;
2812       } else
2813         llvm_unreachable("unexpected long double representation!");
2814     }
2815     // FIXME: _Decimal32 and _Decimal64 are SSE.
2816     // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
2817     return;
2818   }
2819 
2820   if (const EnumType *ET = Ty->getAs<EnumType>()) {
2821     // Classify the underlying integer type.
2822     classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
2823     return;
2824   }
2825 
2826   if (Ty->hasPointerRepresentation()) {
2827     Current = Integer;
2828     return;
2829   }
2830 
2831   if (Ty->isMemberPointerType()) {
2832     if (Ty->isMemberFunctionPointerType()) {
2833       if (Has64BitPointers) {
2834         // If Has64BitPointers, this is an {i64, i64}, so classify both
2835         // Lo and Hi now.
2836         Lo = Hi = Integer;
2837       } else {
2838         // Otherwise, with 32-bit pointers, this is an {i32, i32}. If that
2839         // straddles an eightbyte boundary, Hi should be classified as well.
2840         uint64_t EB_FuncPtr = (OffsetBase) / 64;
2841         uint64_t EB_ThisAdj = (OffsetBase + 64 - 1) / 64;
2842         if (EB_FuncPtr != EB_ThisAdj) {
2843           Lo = Hi = Integer;
2844         } else {
2845           Current = Integer;
2846         }
2847       }
2848     } else {
2849       Current = Integer;
2850     }
2851     return;
2852   }
2853 
2854   if (const VectorType *VT = Ty->getAs<VectorType>()) {
2855     uint64_t Size = getContext().getTypeSize(VT);
2856     if (Size == 1 || Size == 8 || Size == 16 || Size == 32) {
2857       // gcc passes the following as integer:
2858       // 4 bytes - <4 x char>, <2 x short>, <1 x int>, <1 x float>
2859       // 2 bytes - <2 x char>, <1 x short>
2860       // 1 byte  - <1 x char>
2861       Current = Integer;
2862 
2863       // If this type crosses an eightbyte boundary, it should be
2864       // split.
2865       uint64_t EB_Lo = (OffsetBase) / 64;
2866       uint64_t EB_Hi = (OffsetBase + Size - 1) / 64;
2867       if (EB_Lo != EB_Hi)
2868         Hi = Lo;
2869     } else if (Size == 64) {
2870       QualType ElementType = VT->getElementType();
2871 
2872       // gcc passes <1 x double> in memory. :(
2873       if (ElementType->isSpecificBuiltinType(BuiltinType::Double))
2874         return;
2875 
2876       // gcc passes <1 x long long> as SSE but clang used to unconditionally
2877       // pass them as integer.  For platforms where clang is the de facto
2878       // platform compiler, we must continue to use integer.
2879       if (!classifyIntegerMMXAsSSE() &&
2880           (ElementType->isSpecificBuiltinType(BuiltinType::LongLong) ||
2881            ElementType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
2882            ElementType->isSpecificBuiltinType(BuiltinType::Long) ||
2883            ElementType->isSpecificBuiltinType(BuiltinType::ULong)))
2884         Current = Integer;
2885       else
2886         Current = SSE;
2887 
2888       // If this type crosses an eightbyte boundary, it should be
2889       // split.
2890       if (OffsetBase && OffsetBase != 64)
2891         Hi = Lo;
2892     } else if (Size == 128 ||
2893                (isNamedArg && Size <= getNativeVectorSizeForAVXABI(AVXLevel))) {
2894       QualType ElementType = VT->getElementType();
2895 
2896       // gcc passes 256 and 512 bit <X x __int128> vectors in memory. :(
2897       if (passInt128VectorsInMem() && Size != 128 &&
2898           (ElementType->isSpecificBuiltinType(BuiltinType::Int128) ||
2899            ElementType->isSpecificBuiltinType(BuiltinType::UInt128)))
2900         return;
2901 
2902       // Arguments of 256-bits are split into four eightbyte chunks. The
2903       // least significant one belongs to class SSE and all the others to class
2904       // SSEUP. The original Lo and Hi design considers that types can't be
2905       // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
2906       // This design isn't correct for 256-bits, but since there're no cases
2907       // where the upper parts would need to be inspected, avoid adding
2908       // complexity and just consider Hi to match the 64-256 part.
2909       //
2910       // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
2911       // registers if they are "named", i.e. not part of the "..." of a
2912       // variadic function.
2913       //
2914       // Similarly, per 3.2.3. of the AVX512 draft, 512-bits ("named") args are
2915       // split into eight eightbyte chunks, one SSE and seven SSEUP.
2916       Lo = SSE;
2917       Hi = SSEUp;
2918     }
2919     return;
2920   }
2921 
2922   if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
2923     QualType ET = getContext().getCanonicalType(CT->getElementType());
2924 
2925     uint64_t Size = getContext().getTypeSize(Ty);
2926     if (ET->isIntegralOrEnumerationType()) {
2927       if (Size <= 64)
2928         Current = Integer;
2929       else if (Size <= 128)
2930         Lo = Hi = Integer;
2931     } else if (ET == getContext().FloatTy) {
2932       Current = SSE;
2933     } else if (ET == getContext().DoubleTy) {
2934       Lo = Hi = SSE;
2935     } else if (ET == getContext().LongDoubleTy) {
2936       const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
2937       if (LDF == &llvm::APFloat::IEEEquad())
2938         Current = Memory;
2939       else if (LDF == &llvm::APFloat::x87DoubleExtended())
2940         Current = ComplexX87;
2941       else if (LDF == &llvm::APFloat::IEEEdouble())
2942         Lo = Hi = SSE;
2943       else
2944         llvm_unreachable("unexpected long double representation!");
2945     }
2946 
2947     // If this complex type crosses an eightbyte boundary then it
2948     // should be split.
2949     uint64_t EB_Real = (OffsetBase) / 64;
2950     uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
2951     if (Hi == NoClass && EB_Real != EB_Imag)
2952       Hi = Lo;
2953 
2954     return;
2955   }
2956 
2957   if (const auto *EITy = Ty->getAs<ExtIntType>()) {
2958     if (EITy->getNumBits() <= 64)
2959       Current = Integer;
2960     else if (EITy->getNumBits() <= 128)
2961       Lo = Hi = Integer;
2962     // Larger values need to get passed in memory.
2963     return;
2964   }
2965 
2966   if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
2967     // Arrays are treated like structures.
2968 
2969     uint64_t Size = getContext().getTypeSize(Ty);
2970 
2971     // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
2972     // than eight eightbytes, ..., it has class MEMORY.
2973     if (Size > 512)
2974       return;
2975 
2976     // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
2977     // fields, it has class MEMORY.
2978     //
2979     // Only need to check alignment of array base.
2980     if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
2981       return;
2982 
2983     // Otherwise implement simplified merge. We could be smarter about
2984     // this, but it isn't worth it and would be harder to verify.
2985     Current = NoClass;
2986     uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
2987     uint64_t ArraySize = AT->getSize().getZExtValue();
2988 
2989     // The only case a 256-bit wide vector could be used is when the array
2990     // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2991     // to work for sizes wider than 128, early check and fallback to memory.
2992     //
2993     if (Size > 128 &&
2994         (Size != EltSize || Size > getNativeVectorSizeForAVXABI(AVXLevel)))
2995       return;
2996 
2997     for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
2998       Class FieldLo, FieldHi;
2999       classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
3000       Lo = merge(Lo, FieldLo);
3001       Hi = merge(Hi, FieldHi);
3002       if (Lo == Memory || Hi == Memory)
3003         break;
3004     }
3005 
3006     postMerge(Size, Lo, Hi);
3007     assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
3008     return;
3009   }
3010 
3011   if (const RecordType *RT = Ty->getAs<RecordType>()) {
3012     uint64_t Size = getContext().getTypeSize(Ty);
3013 
3014     // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
3015     // than eight eightbytes, ..., it has class MEMORY.
3016     if (Size > 512)
3017       return;
3018 
3019     // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
3020     // copy constructor or a non-trivial destructor, it is passed by invisible
3021     // reference.
3022     if (getRecordArgABI(RT, getCXXABI()))
3023       return;
3024 
3025     const RecordDecl *RD = RT->getDecl();
3026 
3027     // Assume variable sized types are passed in memory.
3028     if (RD->hasFlexibleArrayMember())
3029       return;
3030 
3031     const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
3032 
3033     // Reset Lo class, this will be recomputed.
3034     Current = NoClass;
3035 
3036     // If this is a C++ record, classify the bases first.
3037     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3038       for (const auto &I : CXXRD->bases()) {
3039         assert(!I.isVirtual() && !I.getType()->isDependentType() &&
3040                "Unexpected base class!");
3041         const auto *Base =
3042             cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
3043 
3044         // Classify this field.
3045         //
3046         // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
3047         // single eightbyte, each is classified separately. Each eightbyte gets
3048         // initialized to class NO_CLASS.
3049         Class FieldLo, FieldHi;
3050         uint64_t Offset =
3051           OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
3052         classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg);
3053         Lo = merge(Lo, FieldLo);
3054         Hi = merge(Hi, FieldHi);
3055         if (Lo == Memory || Hi == Memory) {
3056           postMerge(Size, Lo, Hi);
3057           return;
3058         }
3059       }
3060     }
3061 
3062     // Classify the fields one at a time, merging the results.
3063     unsigned idx = 0;
3064     bool IsUnion = RT->isUnionType();
3065     for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
3066            i != e; ++i, ++idx) {
3067       uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
3068       bool BitField = i->isBitField();
3069 
3070       // Ignore padding bit-fields.
3071       if (BitField && i->isUnnamedBitfield())
3072         continue;
3073 
3074       // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
3075       // eight eightbytes, or it contains unaligned fields, it has class MEMORY.
3076       //
3077       // The only case a 256-bit or a 512-bit wide vector could be used is when
3078       // the struct contains a single 256-bit or 512-bit element. Early check
3079       // and fallback to memory.
3080       //
3081       // FIXME: Extended the Lo and Hi logic properly to work for size wider
3082       // than 128.
3083       if (Size > 128 &&
3084           ((!IsUnion && Size != getContext().getTypeSize(i->getType())) ||
3085            Size > getNativeVectorSizeForAVXABI(AVXLevel))) {
3086         Lo = Memory;
3087         postMerge(Size, Lo, Hi);
3088         return;
3089       }
3090       // Note, skip this test for bit-fields, see below.
3091       if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
3092         Lo = Memory;
3093         postMerge(Size, Lo, Hi);
3094         return;
3095       }
3096 
3097       // Classify this field.
3098       //
3099       // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
3100       // exceeds a single eightbyte, each is classified
3101       // separately. Each eightbyte gets initialized to class
3102       // NO_CLASS.
3103       Class FieldLo, FieldHi;
3104 
3105       // Bit-fields require special handling, they do not force the
3106       // structure to be passed in memory even if unaligned, and
3107       // therefore they can straddle an eightbyte.
3108       if (BitField) {
3109         assert(!i->isUnnamedBitfield());
3110         uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
3111         uint64_t Size = i->getBitWidthValue(getContext());
3112 
3113         uint64_t EB_Lo = Offset / 64;
3114         uint64_t EB_Hi = (Offset + Size - 1) / 64;
3115 
3116         if (EB_Lo) {
3117           assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
3118           FieldLo = NoClass;
3119           FieldHi = Integer;
3120         } else {
3121           FieldLo = Integer;
3122           FieldHi = EB_Hi ? Integer : NoClass;
3123         }
3124       } else
3125         classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
3126       Lo = merge(Lo, FieldLo);
3127       Hi = merge(Hi, FieldHi);
3128       if (Lo == Memory || Hi == Memory)
3129         break;
3130     }
3131 
3132     postMerge(Size, Lo, Hi);
3133   }
3134 }
3135 
3136 ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
3137   // If this is a scalar LLVM value then assume LLVM will pass it in the right
3138   // place naturally.
3139   if (!isAggregateTypeForABI(Ty)) {
3140     // Treat an enum type as its underlying type.
3141     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3142       Ty = EnumTy->getDecl()->getIntegerType();
3143 
3144     if (Ty->isExtIntType())
3145       return getNaturalAlignIndirect(Ty);
3146 
3147     return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
3148                                               : ABIArgInfo::getDirect());
3149   }
3150 
3151   return getNaturalAlignIndirect(Ty);
3152 }
3153 
3154 bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
3155   if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
3156     uint64_t Size = getContext().getTypeSize(VecTy);
3157     unsigned LargestVector = getNativeVectorSizeForAVXABI(AVXLevel);
3158     if (Size <= 64 || Size > LargestVector)
3159       return true;
3160     QualType EltTy = VecTy->getElementType();
3161     if (passInt128VectorsInMem() &&
3162         (EltTy->isSpecificBuiltinType(BuiltinType::Int128) ||
3163          EltTy->isSpecificBuiltinType(BuiltinType::UInt128)))
3164       return true;
3165   }
3166 
3167   return false;
3168 }
3169 
3170 ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
3171                                             unsigned freeIntRegs) const {
3172   // If this is a scalar LLVM value then assume LLVM will pass it in the right
3173   // place naturally.
3174   //
3175   // This assumption is optimistic, as there could be free registers available
3176   // when we need to pass this argument in memory, and LLVM could try to pass
3177   // the argument in the free register. This does not seem to happen currently,
3178   // but this code would be much safer if we could mark the argument with
3179   // 'onstack'. See PR12193.
3180   if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty) &&
3181       !Ty->isExtIntType()) {
3182     // Treat an enum type as its underlying type.
3183     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3184       Ty = EnumTy->getDecl()->getIntegerType();
3185 
3186     return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
3187                                               : ABIArgInfo::getDirect());
3188   }
3189 
3190   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
3191     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
3192 
3193   // Compute the byval alignment. We specify the alignment of the byval in all
3194   // cases so that the mid-level optimizer knows the alignment of the byval.
3195   unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
3196 
3197   // Attempt to avoid passing indirect results using byval when possible. This
3198   // is important for good codegen.
3199   //
3200   // We do this by coercing the value into a scalar type which the backend can
3201   // handle naturally (i.e., without using byval).
3202   //
3203   // For simplicity, we currently only do this when we have exhausted all of the
3204   // free integer registers. Doing this when there are free integer registers
3205   // would require more care, as we would have to ensure that the coerced value
3206   // did not claim the unused register. That would require either reording the
3207   // arguments to the function (so that any subsequent inreg values came first),
3208   // or only doing this optimization when there were no following arguments that
3209   // might be inreg.
3210   //
3211   // We currently expect it to be rare (particularly in well written code) for
3212   // arguments to be passed on the stack when there are still free integer
3213   // registers available (this would typically imply large structs being passed
3214   // by value), so this seems like a fair tradeoff for now.
3215   //
3216   // We can revisit this if the backend grows support for 'onstack' parameter
3217   // attributes. See PR12193.
3218   if (freeIntRegs == 0) {
3219     uint64_t Size = getContext().getTypeSize(Ty);
3220 
3221     // If this type fits in an eightbyte, coerce it into the matching integral
3222     // type, which will end up on the stack (with alignment 8).
3223     if (Align == 8 && Size <= 64)
3224       return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
3225                                                           Size));
3226   }
3227 
3228   return ABIArgInfo::getIndirect(CharUnits::fromQuantity(Align));
3229 }
3230 
3231 /// The ABI specifies that a value should be passed in a full vector XMM/YMM
3232 /// register. Pick an LLVM IR type that will be passed as a vector register.
3233 llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
3234   // Wrapper structs/arrays that only contain vectors are passed just like
3235   // vectors; strip them off if present.
3236   if (const Type *InnerTy = isSingleElementStruct(Ty, getContext()))
3237     Ty = QualType(InnerTy, 0);
3238 
3239   llvm::Type *IRType = CGT.ConvertType(Ty);
3240   if (isa<llvm::VectorType>(IRType)) {
3241     // Don't pass vXi128 vectors in their native type, the backend can't
3242     // legalize them.
3243     if (passInt128VectorsInMem() &&
3244         cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy(128)) {
3245       // Use a vXi64 vector.
3246       uint64_t Size = getContext().getTypeSize(Ty);
3247       return llvm::FixedVectorType::get(llvm::Type::getInt64Ty(getVMContext()),
3248                                         Size / 64);
3249     }
3250 
3251     return IRType;
3252   }
3253 
3254   if (IRType->getTypeID() == llvm::Type::FP128TyID)
3255     return IRType;
3256 
3257   // We couldn't find the preferred IR vector type for 'Ty'.
3258   uint64_t Size = getContext().getTypeSize(Ty);
3259   assert((Size == 128 || Size == 256 || Size == 512) && "Invalid type found!");
3260 
3261 
3262   // Return a LLVM IR vector type based on the size of 'Ty'.
3263   return llvm::FixedVectorType::get(llvm::Type::getDoubleTy(getVMContext()),
3264                                     Size / 64);
3265 }
3266 
3267 /// BitsContainNoUserData - Return true if the specified [start,end) bit range
3268 /// is known to either be off the end of the specified type or being in
3269 /// alignment padding.  The user type specified is known to be at most 128 bits
3270 /// in size, and have passed through X86_64ABIInfo::classify with a successful
3271 /// classification that put one of the two halves in the INTEGER class.
3272 ///
3273 /// It is conservatively correct to return false.
3274 static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
3275                                   unsigned EndBit, ASTContext &Context) {
3276   // If the bytes being queried are off the end of the type, there is no user
3277   // data hiding here.  This handles analysis of builtins, vectors and other
3278   // types that don't contain interesting padding.
3279   unsigned TySize = (unsigned)Context.getTypeSize(Ty);
3280   if (TySize <= StartBit)
3281     return true;
3282 
3283   if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
3284     unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
3285     unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
3286 
3287     // Check each element to see if the element overlaps with the queried range.
3288     for (unsigned i = 0; i != NumElts; ++i) {
3289       // If the element is after the span we care about, then we're done..
3290       unsigned EltOffset = i*EltSize;
3291       if (EltOffset >= EndBit) break;
3292 
3293       unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
3294       if (!BitsContainNoUserData(AT->getElementType(), EltStart,
3295                                  EndBit-EltOffset, Context))
3296         return false;
3297     }
3298     // If it overlaps no elements, then it is safe to process as padding.
3299     return true;
3300   }
3301 
3302   if (const RecordType *RT = Ty->getAs<RecordType>()) {
3303     const RecordDecl *RD = RT->getDecl();
3304     const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
3305 
3306     // If this is a C++ record, check the bases first.
3307     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3308       for (const auto &I : CXXRD->bases()) {
3309         assert(!I.isVirtual() && !I.getType()->isDependentType() &&
3310                "Unexpected base class!");
3311         const auto *Base =
3312             cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
3313 
3314         // If the base is after the span we care about, ignore it.
3315         unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
3316         if (BaseOffset >= EndBit) continue;
3317 
3318         unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
3319         if (!BitsContainNoUserData(I.getType(), BaseStart,
3320                                    EndBit-BaseOffset, Context))
3321           return false;
3322       }
3323     }
3324 
3325     // Verify that no field has data that overlaps the region of interest.  Yes
3326     // this could be sped up a lot by being smarter about queried fields,
3327     // however we're only looking at structs up to 16 bytes, so we don't care
3328     // much.
3329     unsigned idx = 0;
3330     for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
3331          i != e; ++i, ++idx) {
3332       unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
3333 
3334       // If we found a field after the region we care about, then we're done.
3335       if (FieldOffset >= EndBit) break;
3336 
3337       unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
3338       if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
3339                                  Context))
3340         return false;
3341     }
3342 
3343     // If nothing in this record overlapped the area of interest, then we're
3344     // clean.
3345     return true;
3346   }
3347 
3348   return false;
3349 }
3350 
3351 /// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a
3352 /// float member at the specified offset.  For example, {int,{float}} has a
3353 /// float at offset 4.  It is conservatively correct for this routine to return
3354 /// false.
3355 static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset,
3356                                   const llvm::DataLayout &TD) {
3357   // Base case if we find a float.
3358   if (IROffset == 0 && IRType->isFloatTy())
3359     return true;
3360 
3361   // If this is a struct, recurse into the field at the specified offset.
3362   if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
3363     const llvm::StructLayout *SL = TD.getStructLayout(STy);
3364     unsigned Elt = SL->getElementContainingOffset(IROffset);
3365     IROffset -= SL->getElementOffset(Elt);
3366     return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD);
3367   }
3368 
3369   // If this is an array, recurse into the field at the specified offset.
3370   if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
3371     llvm::Type *EltTy = ATy->getElementType();
3372     unsigned EltSize = TD.getTypeAllocSize(EltTy);
3373     IROffset -= IROffset/EltSize*EltSize;
3374     return ContainsFloatAtOffset(EltTy, IROffset, TD);
3375   }
3376 
3377   return false;
3378 }
3379 
3380 
3381 /// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
3382 /// low 8 bytes of an XMM register, corresponding to the SSE class.
3383 llvm::Type *X86_64ABIInfo::
3384 GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
3385                    QualType SourceTy, unsigned SourceOffset) const {
3386   // The only three choices we have are either double, <2 x float>, or float. We
3387   // pass as float if the last 4 bytes is just padding.  This happens for
3388   // structs that contain 3 floats.
3389   if (BitsContainNoUserData(SourceTy, SourceOffset*8+32,
3390                             SourceOffset*8+64, getContext()))
3391     return llvm::Type::getFloatTy(getVMContext());
3392 
3393   // We want to pass as <2 x float> if the LLVM IR type contains a float at
3394   // offset+0 and offset+4.  Walk the LLVM IR type to find out if this is the
3395   // case.
3396   if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) &&
3397       ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout()))
3398     return llvm::FixedVectorType::get(llvm::Type::getFloatTy(getVMContext()),
3399                                       2);
3400 
3401   return llvm::Type::getDoubleTy(getVMContext());
3402 }
3403 
3404 
3405 /// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
3406 /// an 8-byte GPR.  This means that we either have a scalar or we are talking
3407 /// about the high or low part of an up-to-16-byte struct.  This routine picks
3408 /// the best LLVM IR type to represent this, which may be i64 or may be anything
3409 /// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
3410 /// etc).
3411 ///
3412 /// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
3413 /// the source type.  IROffset is an offset in bytes into the LLVM IR type that
3414 /// the 8-byte value references.  PrefType may be null.
3415 ///
3416 /// SourceTy is the source-level type for the entire argument.  SourceOffset is
3417 /// an offset into this that we're processing (which is always either 0 or 8).
3418 ///
3419 llvm::Type *X86_64ABIInfo::
3420 GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
3421                        QualType SourceTy, unsigned SourceOffset) const {
3422   // If we're dealing with an un-offset LLVM IR type, then it means that we're
3423   // returning an 8-byte unit starting with it.  See if we can safely use it.
3424   if (IROffset == 0) {
3425     // Pointers and int64's always fill the 8-byte unit.
3426     if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
3427         IRType->isIntegerTy(64))
3428       return IRType;
3429 
3430     // If we have a 1/2/4-byte integer, we can use it only if the rest of the
3431     // goodness in the source type is just tail padding.  This is allowed to
3432     // kick in for struct {double,int} on the int, but not on
3433     // struct{double,int,int} because we wouldn't return the second int.  We
3434     // have to do this analysis on the source type because we can't depend on
3435     // unions being lowered a specific way etc.
3436     if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
3437         IRType->isIntegerTy(32) ||
3438         (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
3439       unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
3440           cast<llvm::IntegerType>(IRType)->getBitWidth();
3441 
3442       if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
3443                                 SourceOffset*8+64, getContext()))
3444         return IRType;
3445     }
3446   }
3447 
3448   if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
3449     // If this is a struct, recurse into the field at the specified offset.
3450     const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
3451     if (IROffset < SL->getSizeInBytes()) {
3452       unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
3453       IROffset -= SL->getElementOffset(FieldIdx);
3454 
3455       return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
3456                                     SourceTy, SourceOffset);
3457     }
3458   }
3459 
3460   if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
3461     llvm::Type *EltTy = ATy->getElementType();
3462     unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
3463     unsigned EltOffset = IROffset/EltSize*EltSize;
3464     return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
3465                                   SourceOffset);
3466   }
3467 
3468   // Okay, we don't have any better idea of what to pass, so we pass this in an
3469   // integer register that isn't too big to fit the rest of the struct.
3470   unsigned TySizeInBytes =
3471     (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
3472 
3473   assert(TySizeInBytes != SourceOffset && "Empty field?");
3474 
3475   // It is always safe to classify this as an integer type up to i64 that
3476   // isn't larger than the structure.
3477   return llvm::IntegerType::get(getVMContext(),
3478                                 std::min(TySizeInBytes-SourceOffset, 8U)*8);
3479 }
3480 
3481 
3482 /// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
3483 /// be used as elements of a two register pair to pass or return, return a
3484 /// first class aggregate to represent them.  For example, if the low part of
3485 /// a by-value argument should be passed as i32* and the high part as float,
3486 /// return {i32*, float}.
3487 static llvm::Type *
3488 GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
3489                            const llvm::DataLayout &TD) {
3490   // In order to correctly satisfy the ABI, we need to the high part to start
3491   // at offset 8.  If the high and low parts we inferred are both 4-byte types
3492   // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
3493   // the second element at offset 8.  Check for this:
3494   unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
3495   unsigned HiAlign = TD.getABITypeAlignment(Hi);
3496   unsigned HiStart = llvm::alignTo(LoSize, HiAlign);
3497   assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
3498 
3499   // To handle this, we have to increase the size of the low part so that the
3500   // second element will start at an 8 byte offset.  We can't increase the size
3501   // of the second element because it might make us access off the end of the
3502   // struct.
3503   if (HiStart != 8) {
3504     // There are usually two sorts of types the ABI generation code can produce
3505     // for the low part of a pair that aren't 8 bytes in size: float or
3506     // i8/i16/i32.  This can also include pointers when they are 32-bit (X32 and
3507     // NaCl).
3508     // Promote these to a larger type.
3509     if (Lo->isFloatTy())
3510       Lo = llvm::Type::getDoubleTy(Lo->getContext());
3511     else {
3512       assert((Lo->isIntegerTy() || Lo->isPointerTy())
3513              && "Invalid/unknown lo type");
3514       Lo = llvm::Type::getInt64Ty(Lo->getContext());
3515     }
3516   }
3517 
3518   llvm::StructType *Result = llvm::StructType::get(Lo, Hi);
3519 
3520   // Verify that the second element is at an 8-byte offset.
3521   assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
3522          "Invalid x86-64 argument pair!");
3523   return Result;
3524 }
3525 
3526 ABIArgInfo X86_64ABIInfo::
3527 classifyReturnType(QualType RetTy) const {
3528   // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
3529   // classification algorithm.
3530   X86_64ABIInfo::Class Lo, Hi;
3531   classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
3532 
3533   // Check some invariants.
3534   assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
3535   assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
3536 
3537   llvm::Type *ResType = nullptr;
3538   switch (Lo) {
3539   case NoClass:
3540     if (Hi == NoClass)
3541       return ABIArgInfo::getIgnore();
3542     // If the low part is just padding, it takes no register, leave ResType
3543     // null.
3544     assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3545            "Unknown missing lo part");
3546     break;
3547 
3548   case SSEUp:
3549   case X87Up:
3550     llvm_unreachable("Invalid classification for lo word.");
3551 
3552     // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
3553     // hidden argument.
3554   case Memory:
3555     return getIndirectReturnResult(RetTy);
3556 
3557     // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
3558     // available register of the sequence %rax, %rdx is used.
3559   case Integer:
3560     ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
3561 
3562     // If we have a sign or zero extended integer, make sure to return Extend
3563     // so that the parameter gets the right LLVM IR attributes.
3564     if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3565       // Treat an enum type as its underlying type.
3566       if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
3567         RetTy = EnumTy->getDecl()->getIntegerType();
3568 
3569       if (RetTy->isIntegralOrEnumerationType() &&
3570           isPromotableIntegerTypeForABI(RetTy))
3571         return ABIArgInfo::getExtend(RetTy);
3572     }
3573     break;
3574 
3575     // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
3576     // available SSE register of the sequence %xmm0, %xmm1 is used.
3577   case SSE:
3578     ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
3579     break;
3580 
3581     // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
3582     // returned on the X87 stack in %st0 as 80-bit x87 number.
3583   case X87:
3584     ResType = llvm::Type::getX86_FP80Ty(getVMContext());
3585     break;
3586 
3587     // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
3588     // part of the value is returned in %st0 and the imaginary part in
3589     // %st1.
3590   case ComplexX87:
3591     assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
3592     ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
3593                                     llvm::Type::getX86_FP80Ty(getVMContext()));
3594     break;
3595   }
3596 
3597   llvm::Type *HighPart = nullptr;
3598   switch (Hi) {
3599     // Memory was handled previously and X87 should
3600     // never occur as a hi class.
3601   case Memory:
3602   case X87:
3603     llvm_unreachable("Invalid classification for hi word.");
3604 
3605   case ComplexX87: // Previously handled.
3606   case NoClass:
3607     break;
3608 
3609   case Integer:
3610     HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
3611     if (Lo == NoClass)  // Return HighPart at offset 8 in memory.
3612       return ABIArgInfo::getDirect(HighPart, 8);
3613     break;
3614   case SSE:
3615     HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
3616     if (Lo == NoClass)  // Return HighPart at offset 8 in memory.
3617       return ABIArgInfo::getDirect(HighPart, 8);
3618     break;
3619 
3620     // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
3621     // is passed in the next available eightbyte chunk if the last used
3622     // vector register.
3623     //
3624     // SSEUP should always be preceded by SSE, just widen.
3625   case SSEUp:
3626     assert(Lo == SSE && "Unexpected SSEUp classification.");
3627     ResType = GetByteVectorType(RetTy);
3628     break;
3629 
3630     // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
3631     // returned together with the previous X87 value in %st0.
3632   case X87Up:
3633     // If X87Up is preceded by X87, we don't need to do
3634     // anything. However, in some cases with unions it may not be
3635     // preceded by X87. In such situations we follow gcc and pass the
3636     // extra bits in an SSE reg.
3637     if (Lo != X87) {
3638       HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
3639       if (Lo == NoClass)  // Return HighPart at offset 8 in memory.
3640         return ABIArgInfo::getDirect(HighPart, 8);
3641     }
3642     break;
3643   }
3644 
3645   // If a high part was specified, merge it together with the low part.  It is
3646   // known to pass in the high eightbyte of the result.  We do this by forming a
3647   // first class struct aggregate with the high and low part: {low, high}
3648   if (HighPart)
3649     ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
3650 
3651   return ABIArgInfo::getDirect(ResType);
3652 }
3653 
3654 ABIArgInfo X86_64ABIInfo::classifyArgumentType(
3655   QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE,
3656   bool isNamedArg)
3657   const
3658 {
3659   Ty = useFirstFieldIfTransparentUnion(Ty);
3660 
3661   X86_64ABIInfo::Class Lo, Hi;
3662   classify(Ty, 0, Lo, Hi, isNamedArg);
3663 
3664   // Check some invariants.
3665   // FIXME: Enforce these by construction.
3666   assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
3667   assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
3668 
3669   neededInt = 0;
3670   neededSSE = 0;
3671   llvm::Type *ResType = nullptr;
3672   switch (Lo) {
3673   case NoClass:
3674     if (Hi == NoClass)
3675       return ABIArgInfo::getIgnore();
3676     // If the low part is just padding, it takes no register, leave ResType
3677     // null.
3678     assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3679            "Unknown missing lo part");
3680     break;
3681 
3682     // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
3683     // on the stack.
3684   case Memory:
3685 
3686     // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
3687     // COMPLEX_X87, it is passed in memory.
3688   case X87:
3689   case ComplexX87:
3690     if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect)
3691       ++neededInt;
3692     return getIndirectResult(Ty, freeIntRegs);
3693 
3694   case SSEUp:
3695   case X87Up:
3696     llvm_unreachable("Invalid classification for lo word.");
3697 
3698     // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
3699     // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
3700     // and %r9 is used.
3701   case Integer:
3702     ++neededInt;
3703 
3704     // Pick an 8-byte type based on the preferred type.
3705     ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
3706 
3707     // If we have a sign or zero extended integer, make sure to return Extend
3708     // so that the parameter gets the right LLVM IR attributes.
3709     if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3710       // Treat an enum type as its underlying type.
3711       if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3712         Ty = EnumTy->getDecl()->getIntegerType();
3713 
3714       if (Ty->isIntegralOrEnumerationType() &&
3715           isPromotableIntegerTypeForABI(Ty))
3716         return ABIArgInfo::getExtend(Ty);
3717     }
3718 
3719     break;
3720 
3721     // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
3722     // available SSE register is used, the registers are taken in the
3723     // order from %xmm0 to %xmm7.
3724   case SSE: {
3725     llvm::Type *IRType = CGT.ConvertType(Ty);
3726     ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
3727     ++neededSSE;
3728     break;
3729   }
3730   }
3731 
3732   llvm::Type *HighPart = nullptr;
3733   switch (Hi) {
3734     // Memory was handled previously, ComplexX87 and X87 should
3735     // never occur as hi classes, and X87Up must be preceded by X87,
3736     // which is passed in memory.
3737   case Memory:
3738   case X87:
3739   case ComplexX87:
3740     llvm_unreachable("Invalid classification for hi word.");
3741 
3742   case NoClass: break;
3743 
3744   case Integer:
3745     ++neededInt;
3746     // Pick an 8-byte type based on the preferred type.
3747     HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
3748 
3749     if (Lo == NoClass)  // Pass HighPart at offset 8 in memory.
3750       return ABIArgInfo::getDirect(HighPart, 8);
3751     break;
3752 
3753     // X87Up generally doesn't occur here (long double is passed in
3754     // memory), except in situations involving unions.
3755   case X87Up:
3756   case SSE:
3757     HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
3758 
3759     if (Lo == NoClass)  // Pass HighPart at offset 8 in memory.
3760       return ABIArgInfo::getDirect(HighPart, 8);
3761 
3762     ++neededSSE;
3763     break;
3764 
3765     // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
3766     // eightbyte is passed in the upper half of the last used SSE
3767     // register.  This only happens when 128-bit vectors are passed.
3768   case SSEUp:
3769     assert(Lo == SSE && "Unexpected SSEUp classification");
3770     ResType = GetByteVectorType(Ty);
3771     break;
3772   }
3773 
3774   // If a high part was specified, merge it together with the low part.  It is
3775   // known to pass in the high eightbyte of the result.  We do this by forming a
3776   // first class struct aggregate with the high and low part: {low, high}
3777   if (HighPart)
3778     ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
3779 
3780   return ABIArgInfo::getDirect(ResType);
3781 }
3782 
3783 ABIArgInfo
3784 X86_64ABIInfo::classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
3785                                              unsigned &NeededSSE) const {
3786   auto RT = Ty->getAs<RecordType>();
3787   assert(RT && "classifyRegCallStructType only valid with struct types");
3788 
3789   if (RT->getDecl()->hasFlexibleArrayMember())
3790     return getIndirectReturnResult(Ty);
3791 
3792   // Sum up bases
3793   if (auto CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
3794     if (CXXRD->isDynamicClass()) {
3795       NeededInt = NeededSSE = 0;
3796       return getIndirectReturnResult(Ty);
3797     }
3798 
3799     for (const auto &I : CXXRD->bases())
3800       if (classifyRegCallStructTypeImpl(I.getType(), NeededInt, NeededSSE)
3801               .isIndirect()) {
3802         NeededInt = NeededSSE = 0;
3803         return getIndirectReturnResult(Ty);
3804       }
3805   }
3806 
3807   // Sum up members
3808   for (const auto *FD : RT->getDecl()->fields()) {
3809     if (FD->getType()->isRecordType() && !FD->getType()->isUnionType()) {
3810       if (classifyRegCallStructTypeImpl(FD->getType(), NeededInt, NeededSSE)
3811               .isIndirect()) {
3812         NeededInt = NeededSSE = 0;
3813         return getIndirectReturnResult(Ty);
3814       }
3815     } else {
3816       unsigned LocalNeededInt, LocalNeededSSE;
3817       if (classifyArgumentType(FD->getType(), UINT_MAX, LocalNeededInt,
3818                                LocalNeededSSE, true)
3819               .isIndirect()) {
3820         NeededInt = NeededSSE = 0;
3821         return getIndirectReturnResult(Ty);
3822       }
3823       NeededInt += LocalNeededInt;
3824       NeededSSE += LocalNeededSSE;
3825     }
3826   }
3827 
3828   return ABIArgInfo::getDirect();
3829 }
3830 
3831 ABIArgInfo X86_64ABIInfo::classifyRegCallStructType(QualType Ty,
3832                                                     unsigned &NeededInt,
3833                                                     unsigned &NeededSSE) const {
3834 
3835   NeededInt = 0;
3836   NeededSSE = 0;
3837 
3838   return classifyRegCallStructTypeImpl(Ty, NeededInt, NeededSSE);
3839 }
3840 
3841 void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
3842 
3843   const unsigned CallingConv = FI.getCallingConvention();
3844   // It is possible to force Win64 calling convention on any x86_64 target by
3845   // using __attribute__((ms_abi)). In such case to correctly emit Win64
3846   // compatible code delegate this call to WinX86_64ABIInfo::computeInfo.
3847   if (CallingConv == llvm::CallingConv::Win64) {
3848     WinX86_64ABIInfo Win64ABIInfo(CGT, AVXLevel);
3849     Win64ABIInfo.computeInfo(FI);
3850     return;
3851   }
3852 
3853   bool IsRegCall = CallingConv == llvm::CallingConv::X86_RegCall;
3854 
3855   // Keep track of the number of assigned registers.
3856   unsigned FreeIntRegs = IsRegCall ? 11 : 6;
3857   unsigned FreeSSERegs = IsRegCall ? 16 : 8;
3858   unsigned NeededInt, NeededSSE;
3859 
3860   if (!::classifyReturnType(getCXXABI(), FI, *this)) {
3861     if (IsRegCall && FI.getReturnType()->getTypePtr()->isRecordType() &&
3862         !FI.getReturnType()->getTypePtr()->isUnionType()) {
3863       FI.getReturnInfo() =
3864           classifyRegCallStructType(FI.getReturnType(), NeededInt, NeededSSE);
3865       if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
3866         FreeIntRegs -= NeededInt;
3867         FreeSSERegs -= NeededSSE;
3868       } else {
3869         FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType());
3870       }
3871     } else if (IsRegCall && FI.getReturnType()->getAs<ComplexType>() &&
3872                getContext().getCanonicalType(FI.getReturnType()
3873                                                  ->getAs<ComplexType>()
3874                                                  ->getElementType()) ==
3875                    getContext().LongDoubleTy)
3876       // Complex Long Double Type is passed in Memory when Regcall
3877       // calling convention is used.
3878       FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType());
3879     else
3880       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
3881   }
3882 
3883   // If the return value is indirect, then the hidden argument is consuming one
3884   // integer register.
3885   if (FI.getReturnInfo().isIndirect())
3886     --FreeIntRegs;
3887 
3888   // The chain argument effectively gives us another free register.
3889   if (FI.isChainCall())
3890     ++FreeIntRegs;
3891 
3892   unsigned NumRequiredArgs = FI.getNumRequiredArgs();
3893   // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
3894   // get assigned (in left-to-right order) for passing as follows...
3895   unsigned ArgNo = 0;
3896   for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
3897        it != ie; ++it, ++ArgNo) {
3898     bool IsNamedArg = ArgNo < NumRequiredArgs;
3899 
3900     if (IsRegCall && it->type->isStructureOrClassType())
3901       it->info = classifyRegCallStructType(it->type, NeededInt, NeededSSE);
3902     else
3903       it->info = classifyArgumentType(it->type, FreeIntRegs, NeededInt,
3904                                       NeededSSE, IsNamedArg);
3905 
3906     // AMD64-ABI 3.2.3p3: If there are no registers available for any
3907     // eightbyte of an argument, the whole argument is passed on the
3908     // stack. If registers have already been assigned for some
3909     // eightbytes of such an argument, the assignments get reverted.
3910     if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
3911       FreeIntRegs -= NeededInt;
3912       FreeSSERegs -= NeededSSE;
3913     } else {
3914       it->info = getIndirectResult(it->type, FreeIntRegs);
3915     }
3916   }
3917 }
3918 
3919 static Address EmitX86_64VAArgFromMemory(CodeGenFunction &CGF,
3920                                          Address VAListAddr, QualType Ty) {
3921   Address overflow_arg_area_p =
3922       CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_p");
3923   llvm::Value *overflow_arg_area =
3924     CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
3925 
3926   // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
3927   // byte boundary if alignment needed by type exceeds 8 byte boundary.
3928   // It isn't stated explicitly in the standard, but in practice we use
3929   // alignment greater than 16 where necessary.
3930   CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
3931   if (Align > CharUnits::fromQuantity(8)) {
3932     overflow_arg_area = emitRoundPointerUpToAlignment(CGF, overflow_arg_area,
3933                                                       Align);
3934   }
3935 
3936   // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
3937   llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
3938   llvm::Value *Res =
3939     CGF.Builder.CreateBitCast(overflow_arg_area,
3940                               llvm::PointerType::getUnqual(LTy));
3941 
3942   // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
3943   // l->overflow_arg_area + sizeof(type).
3944   // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
3945   // an 8 byte boundary.
3946 
3947   uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
3948   llvm::Value *Offset =
3949       llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7)  & ~7);
3950   overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
3951                                             "overflow_arg_area.next");
3952   CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
3953 
3954   // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
3955   return Address(Res, Align);
3956 }
3957 
3958 Address X86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3959                                  QualType Ty) const {
3960   // Assume that va_list type is correct; should be pointer to LLVM type:
3961   // struct {
3962   //   i32 gp_offset;
3963   //   i32 fp_offset;
3964   //   i8* overflow_arg_area;
3965   //   i8* reg_save_area;
3966   // };
3967   unsigned neededInt, neededSSE;
3968 
3969   Ty = getContext().getCanonicalType(Ty);
3970   ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
3971                                        /*isNamedArg*/false);
3972 
3973   // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
3974   // in the registers. If not go to step 7.
3975   if (!neededInt && !neededSSE)
3976     return EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
3977 
3978   // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
3979   // general purpose registers needed to pass type and num_fp to hold
3980   // the number of floating point registers needed.
3981 
3982   // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
3983   // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
3984   // l->fp_offset > 304 - num_fp * 16 go to step 7.
3985   //
3986   // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
3987   // register save space).
3988 
3989   llvm::Value *InRegs = nullptr;
3990   Address gp_offset_p = Address::invalid(), fp_offset_p = Address::invalid();
3991   llvm::Value *gp_offset = nullptr, *fp_offset = nullptr;
3992   if (neededInt) {
3993     gp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "gp_offset_p");
3994     gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
3995     InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
3996     InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
3997   }
3998 
3999   if (neededSSE) {
4000     fp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 1, "fp_offset_p");
4001     fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
4002     llvm::Value *FitsInFP =
4003       llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
4004     FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
4005     InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
4006   }
4007 
4008   llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
4009   llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
4010   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
4011   CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
4012 
4013   // Emit code to load the value if it was passed in registers.
4014 
4015   CGF.EmitBlock(InRegBlock);
4016 
4017   // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
4018   // an offset of l->gp_offset and/or l->fp_offset. This may require
4019   // copying to a temporary location in case the parameter is passed
4020   // in different register classes or requires an alignment greater
4021   // than 8 for general purpose registers and 16 for XMM registers.
4022   //
4023   // FIXME: This really results in shameful code when we end up needing to
4024   // collect arguments from different places; often what should result in a
4025   // simple assembling of a structure from scattered addresses has many more
4026   // loads than necessary. Can we clean this up?
4027   llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
4028   llvm::Value *RegSaveArea = CGF.Builder.CreateLoad(
4029       CGF.Builder.CreateStructGEP(VAListAddr, 3), "reg_save_area");
4030 
4031   Address RegAddr = Address::invalid();
4032   if (neededInt && neededSSE) {
4033     // FIXME: Cleanup.
4034     assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
4035     llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
4036     Address Tmp = CGF.CreateMemTemp(Ty);
4037     Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
4038     assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
4039     llvm::Type *TyLo = ST->getElementType(0);
4040     llvm::Type *TyHi = ST->getElementType(1);
4041     assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
4042            "Unexpected ABI info for mixed regs");
4043     llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
4044     llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
4045     llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegSaveArea, gp_offset);
4046     llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegSaveArea, fp_offset);
4047     llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr;
4048     llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr;
4049 
4050     // Copy the first element.
4051     // FIXME: Our choice of alignment here and below is probably pessimistic.
4052     llvm::Value *V = CGF.Builder.CreateAlignedLoad(
4053         TyLo, CGF.Builder.CreateBitCast(RegLoAddr, PTyLo),
4054         CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyLo)));
4055     CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
4056 
4057     // Copy the second element.
4058     V = CGF.Builder.CreateAlignedLoad(
4059         TyHi, CGF.Builder.CreateBitCast(RegHiAddr, PTyHi),
4060         CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyHi)));
4061     CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
4062 
4063     RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
4064   } else if (neededInt) {
4065     RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, gp_offset),
4066                       CharUnits::fromQuantity(8));
4067     RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
4068 
4069     // Copy to a temporary if necessary to ensure the appropriate alignment.
4070     auto TInfo = getContext().getTypeInfoInChars(Ty);
4071     uint64_t TySize = TInfo.Width.getQuantity();
4072     CharUnits TyAlign = TInfo.Align;
4073 
4074     // Copy into a temporary if the type is more aligned than the
4075     // register save area.
4076     if (TyAlign.getQuantity() > 8) {
4077       Address Tmp = CGF.CreateMemTemp(Ty);
4078       CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, false);
4079       RegAddr = Tmp;
4080     }
4081 
4082   } else if (neededSSE == 1) {
4083     RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
4084                       CharUnits::fromQuantity(16));
4085     RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
4086   } else {
4087     assert(neededSSE == 2 && "Invalid number of needed registers!");
4088     // SSE registers are spaced 16 bytes apart in the register save
4089     // area, we need to collect the two eightbytes together.
4090     // The ABI isn't explicit about this, but it seems reasonable
4091     // to assume that the slots are 16-byte aligned, since the stack is
4092     // naturally 16-byte aligned and the prologue is expected to store
4093     // all the SSE registers to the RSA.
4094     Address RegAddrLo = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
4095                                 CharUnits::fromQuantity(16));
4096     Address RegAddrHi =
4097       CGF.Builder.CreateConstInBoundsByteGEP(RegAddrLo,
4098                                              CharUnits::fromQuantity(16));
4099     llvm::Type *ST = AI.canHaveCoerceToType()
4100                          ? AI.getCoerceToType()
4101                          : llvm::StructType::get(CGF.DoubleTy, CGF.DoubleTy);
4102     llvm::Value *V;
4103     Address Tmp = CGF.CreateMemTemp(Ty);
4104     Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
4105     V = CGF.Builder.CreateLoad(CGF.Builder.CreateElementBitCast(
4106         RegAddrLo, ST->getStructElementType(0)));
4107     CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
4108     V = CGF.Builder.CreateLoad(CGF.Builder.CreateElementBitCast(
4109         RegAddrHi, ST->getStructElementType(1)));
4110     CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
4111 
4112     RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
4113   }
4114 
4115   // AMD64-ABI 3.5.7p5: Step 5. Set:
4116   // l->gp_offset = l->gp_offset + num_gp * 8
4117   // l->fp_offset = l->fp_offset + num_fp * 16.
4118   if (neededInt) {
4119     llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
4120     CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
4121                             gp_offset_p);
4122   }
4123   if (neededSSE) {
4124     llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
4125     CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
4126                             fp_offset_p);
4127   }
4128   CGF.EmitBranch(ContBlock);
4129 
4130   // Emit code to load the value if it was passed in memory.
4131 
4132   CGF.EmitBlock(InMemBlock);
4133   Address MemAddr = EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
4134 
4135   // Return the appropriate result.
4136 
4137   CGF.EmitBlock(ContBlock);
4138   Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, MemAddr, InMemBlock,
4139                                  "vaarg.addr");
4140   return ResAddr;
4141 }
4142 
4143 Address X86_64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
4144                                    QualType Ty) const {
4145   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
4146                           CGF.getContext().getTypeInfoInChars(Ty),
4147                           CharUnits::fromQuantity(8),
4148                           /*allowHigherAlign*/ false);
4149 }
4150 
4151 ABIArgInfo
4152 WinX86_64ABIInfo::reclassifyHvaArgType(QualType Ty, unsigned &FreeSSERegs,
4153                                     const ABIArgInfo &current) const {
4154   // Assumes vectorCall calling convention.
4155   const Type *Base = nullptr;
4156   uint64_t NumElts = 0;
4157 
4158   if (!Ty->isBuiltinType() && !Ty->isVectorType() &&
4159       isHomogeneousAggregate(Ty, Base, NumElts) && FreeSSERegs >= NumElts) {
4160     FreeSSERegs -= NumElts;
4161     return getDirectX86Hva();
4162   }
4163   return current;
4164 }
4165 
4166 ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, unsigned &FreeSSERegs,
4167                                       bool IsReturnType, bool IsVectorCall,
4168                                       bool IsRegCall) const {
4169 
4170   if (Ty->isVoidType())
4171     return ABIArgInfo::getIgnore();
4172 
4173   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4174     Ty = EnumTy->getDecl()->getIntegerType();
4175 
4176   TypeInfo Info = getContext().getTypeInfo(Ty);
4177   uint64_t Width = Info.Width;
4178   CharUnits Align = getContext().toCharUnitsFromBits(Info.Align);
4179 
4180   const RecordType *RT = Ty->getAs<RecordType>();
4181   if (RT) {
4182     if (!IsReturnType) {
4183       if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
4184         return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
4185     }
4186 
4187     if (RT->getDecl()->hasFlexibleArrayMember())
4188       return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
4189 
4190   }
4191 
4192   const Type *Base = nullptr;
4193   uint64_t NumElts = 0;
4194   // vectorcall adds the concept of a homogenous vector aggregate, similar to
4195   // other targets.
4196   if ((IsVectorCall || IsRegCall) &&
4197       isHomogeneousAggregate(Ty, Base, NumElts)) {
4198     if (IsRegCall) {
4199       if (FreeSSERegs >= NumElts) {
4200         FreeSSERegs -= NumElts;
4201         if (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())
4202           return ABIArgInfo::getDirect();
4203         return ABIArgInfo::getExpand();
4204       }
4205       return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
4206     } else if (IsVectorCall) {
4207       if (FreeSSERegs >= NumElts &&
4208           (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())) {
4209         FreeSSERegs -= NumElts;
4210         return ABIArgInfo::getDirect();
4211       } else if (IsReturnType) {
4212         return ABIArgInfo::getExpand();
4213       } else if (!Ty->isBuiltinType() && !Ty->isVectorType()) {
4214         // HVAs are delayed and reclassified in the 2nd step.
4215         return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
4216       }
4217     }
4218   }
4219 
4220   if (Ty->isMemberPointerType()) {
4221     // If the member pointer is represented by an LLVM int or ptr, pass it
4222     // directly.
4223     llvm::Type *LLTy = CGT.ConvertType(Ty);
4224     if (LLTy->isPointerTy() || LLTy->isIntegerTy())
4225       return ABIArgInfo::getDirect();
4226   }
4227 
4228   if (RT || Ty->isAnyComplexType() || Ty->isMemberPointerType()) {
4229     // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
4230     // not 1, 2, 4, or 8 bytes, must be passed by reference."
4231     if (Width > 64 || !llvm::isPowerOf2_64(Width))
4232       return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
4233 
4234     // Otherwise, coerce it to a small integer.
4235     return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Width));
4236   }
4237 
4238   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4239     switch (BT->getKind()) {
4240     case BuiltinType::Bool:
4241       // Bool type is always extended to the ABI, other builtin types are not
4242       // extended.
4243       return ABIArgInfo::getExtend(Ty);
4244 
4245     case BuiltinType::LongDouble:
4246       // Mingw64 GCC uses the old 80 bit extended precision floating point
4247       // unit. It passes them indirectly through memory.
4248       if (IsMingw64) {
4249         const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
4250         if (LDF == &llvm::APFloat::x87DoubleExtended())
4251           return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
4252       }
4253       break;
4254 
4255     case BuiltinType::Int128:
4256     case BuiltinType::UInt128:
4257       // If it's a parameter type, the normal ABI rule is that arguments larger
4258       // than 8 bytes are passed indirectly. GCC follows it. We follow it too,
4259       // even though it isn't particularly efficient.
4260       if (!IsReturnType)
4261         return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
4262 
4263       // Mingw64 GCC returns i128 in XMM0. Coerce to v2i64 to handle that.
4264       // Clang matches them for compatibility.
4265       return ABIArgInfo::getDirect(llvm::FixedVectorType::get(
4266           llvm::Type::getInt64Ty(getVMContext()), 2));
4267 
4268     default:
4269       break;
4270     }
4271   }
4272 
4273   if (Ty->isExtIntType()) {
4274     // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
4275     // not 1, 2, 4, or 8 bytes, must be passed by reference."
4276     // However, non-power-of-two _ExtInts will be passed as 1,2,4 or 8 bytes
4277     // anyway as long is it fits in them, so we don't have to check the power of
4278     // 2.
4279     if (Width <= 64)
4280       return ABIArgInfo::getDirect();
4281     return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
4282   }
4283 
4284   return ABIArgInfo::getDirect();
4285 }
4286 
4287 void WinX86_64ABIInfo::computeVectorCallArgs(CGFunctionInfo &FI,
4288                                              unsigned FreeSSERegs,
4289                                              bool IsVectorCall,
4290                                              bool IsRegCall) const {
4291   unsigned Count = 0;
4292   for (auto &I : FI.arguments()) {
4293     // Vectorcall in x64 only permits the first 6 arguments to be passed
4294     // as XMM/YMM registers.
4295     if (Count < VectorcallMaxParamNumAsReg)
4296       I.info = classify(I.type, FreeSSERegs, false, IsVectorCall, IsRegCall);
4297     else {
4298       // Since these cannot be passed in registers, pretend no registers
4299       // are left.
4300       unsigned ZeroSSERegsAvail = 0;
4301       I.info = classify(I.type, /*FreeSSERegs=*/ZeroSSERegsAvail, false,
4302                         IsVectorCall, IsRegCall);
4303     }
4304     ++Count;
4305   }
4306 
4307   for (auto &I : FI.arguments()) {
4308     I.info = reclassifyHvaArgType(I.type, FreeSSERegs, I.info);
4309   }
4310 }
4311 
4312 void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
4313   const unsigned CC = FI.getCallingConvention();
4314   bool IsVectorCall = CC == llvm::CallingConv::X86_VectorCall;
4315   bool IsRegCall = CC == llvm::CallingConv::X86_RegCall;
4316 
4317   // If __attribute__((sysv_abi)) is in use, use the SysV argument
4318   // classification rules.
4319   if (CC == llvm::CallingConv::X86_64_SysV) {
4320     X86_64ABIInfo SysVABIInfo(CGT, AVXLevel);
4321     SysVABIInfo.computeInfo(FI);
4322     return;
4323   }
4324 
4325   unsigned FreeSSERegs = 0;
4326   if (IsVectorCall) {
4327     // We can use up to 4 SSE return registers with vectorcall.
4328     FreeSSERegs = 4;
4329   } else if (IsRegCall) {
4330     // RegCall gives us 16 SSE registers.
4331     FreeSSERegs = 16;
4332   }
4333 
4334   if (!getCXXABI().classifyReturnType(FI))
4335     FI.getReturnInfo() = classify(FI.getReturnType(), FreeSSERegs, true,
4336                                   IsVectorCall, IsRegCall);
4337 
4338   if (IsVectorCall) {
4339     // We can use up to 6 SSE register parameters with vectorcall.
4340     FreeSSERegs = 6;
4341   } else if (IsRegCall) {
4342     // RegCall gives us 16 SSE registers, we can reuse the return registers.
4343     FreeSSERegs = 16;
4344   }
4345 
4346   if (IsVectorCall) {
4347     computeVectorCallArgs(FI, FreeSSERegs, IsVectorCall, IsRegCall);
4348   } else {
4349     for (auto &I : FI.arguments())
4350       I.info = classify(I.type, FreeSSERegs, false, IsVectorCall, IsRegCall);
4351   }
4352 
4353 }
4354 
4355 Address WinX86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4356                                     QualType Ty) const {
4357 
4358   bool IsIndirect = false;
4359 
4360   // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
4361   // not 1, 2, 4, or 8 bytes, must be passed by reference."
4362   if (isAggregateTypeForABI(Ty) || Ty->isMemberPointerType()) {
4363     uint64_t Width = getContext().getTypeSize(Ty);
4364     IsIndirect = Width > 64 || !llvm::isPowerOf2_64(Width);
4365   }
4366 
4367   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
4368                           CGF.getContext().getTypeInfoInChars(Ty),
4369                           CharUnits::fromQuantity(8),
4370                           /*allowHigherAlign*/ false);
4371 }
4372 
4373 static bool PPC_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4374                                         llvm::Value *Address, bool Is64Bit,
4375                                         bool IsAIX) {
4376   // This is calculated from the LLVM and GCC tables and verified
4377   // against gcc output.  AFAIK all PPC ABIs use the same encoding.
4378 
4379   CodeGen::CGBuilderTy &Builder = CGF.Builder;
4380 
4381   llvm::IntegerType *i8 = CGF.Int8Ty;
4382   llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
4383   llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
4384   llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
4385 
4386   // 0-31: r0-31, the 4-byte or 8-byte general-purpose registers
4387   AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 0, 31);
4388 
4389   // 32-63: fp0-31, the 8-byte floating-point registers
4390   AssignToArrayRange(Builder, Address, Eight8, 32, 63);
4391 
4392   // 64-67 are various 4-byte or 8-byte special-purpose registers:
4393   // 64: mq
4394   // 65: lr
4395   // 66: ctr
4396   // 67: ap
4397   AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 64, 67);
4398 
4399   // 68-76 are various 4-byte special-purpose registers:
4400   // 68-75 cr0-7
4401   // 76: xer
4402   AssignToArrayRange(Builder, Address, Four8, 68, 76);
4403 
4404   // 77-108: v0-31, the 16-byte vector registers
4405   AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
4406 
4407   // 109: vrsave
4408   // 110: vscr
4409   AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 109, 110);
4410 
4411   // AIX does not utilize the rest of the registers.
4412   if (IsAIX)
4413     return false;
4414 
4415   // 111: spe_acc
4416   // 112: spefscr
4417   // 113: sfp
4418   AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 111, 113);
4419 
4420   if (!Is64Bit)
4421     return false;
4422 
4423   // TODO: Need to verify if these registers are used on 64 bit AIX with Power8
4424   // or above CPU.
4425   // 64-bit only registers:
4426   // 114: tfhar
4427   // 115: tfiar
4428   // 116: texasr
4429   AssignToArrayRange(Builder, Address, Eight8, 114, 116);
4430 
4431   return false;
4432 }
4433 
4434 // AIX
4435 namespace {
4436 /// AIXABIInfo - The AIX XCOFF ABI information.
4437 class AIXABIInfo : public ABIInfo {
4438   const bool Is64Bit;
4439   const unsigned PtrByteSize;
4440   CharUnits getParamTypeAlignment(QualType Ty) const;
4441 
4442 public:
4443   AIXABIInfo(CodeGen::CodeGenTypes &CGT, bool Is64Bit)
4444       : ABIInfo(CGT), Is64Bit(Is64Bit), PtrByteSize(Is64Bit ? 8 : 4) {}
4445 
4446   bool isPromotableTypeForABI(QualType Ty) const;
4447 
4448   ABIArgInfo classifyReturnType(QualType RetTy) const;
4449   ABIArgInfo classifyArgumentType(QualType Ty) const;
4450 
4451   void computeInfo(CGFunctionInfo &FI) const override {
4452     if (!getCXXABI().classifyReturnType(FI))
4453       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
4454 
4455     for (auto &I : FI.arguments())
4456       I.info = classifyArgumentType(I.type);
4457   }
4458 
4459   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4460                     QualType Ty) const override;
4461 };
4462 
4463 class AIXTargetCodeGenInfo : public TargetCodeGenInfo {
4464   const bool Is64Bit;
4465 
4466 public:
4467   AIXTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool Is64Bit)
4468       : TargetCodeGenInfo(std::make_unique<AIXABIInfo>(CGT, Is64Bit)),
4469         Is64Bit(Is64Bit) {}
4470   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4471     return 1; // r1 is the dedicated stack pointer
4472   }
4473 
4474   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4475                                llvm::Value *Address) const override;
4476 };
4477 } // namespace
4478 
4479 // Return true if the ABI requires Ty to be passed sign- or zero-
4480 // extended to 32/64 bits.
4481 bool AIXABIInfo::isPromotableTypeForABI(QualType Ty) const {
4482   // Treat an enum type as its underlying type.
4483   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4484     Ty = EnumTy->getDecl()->getIntegerType();
4485 
4486   // Promotable integer types are required to be promoted by the ABI.
4487   if (Ty->isPromotableIntegerType())
4488     return true;
4489 
4490   if (!Is64Bit)
4491     return false;
4492 
4493   // For 64 bit mode, in addition to the usual promotable integer types, we also
4494   // need to extend all 32-bit types, since the ABI requires promotion to 64
4495   // bits.
4496   if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
4497     switch (BT->getKind()) {
4498     case BuiltinType::Int:
4499     case BuiltinType::UInt:
4500       return true;
4501     default:
4502       break;
4503     }
4504 
4505   return false;
4506 }
4507 
4508 ABIArgInfo AIXABIInfo::classifyReturnType(QualType RetTy) const {
4509   if (RetTy->isAnyComplexType())
4510     return ABIArgInfo::getDirect();
4511 
4512   if (RetTy->isVectorType())
4513     llvm::report_fatal_error("vector type is not supported on AIX yet");
4514 
4515   if (RetTy->isVoidType())
4516     return ABIArgInfo::getIgnore();
4517 
4518   if (isAggregateTypeForABI(RetTy))
4519     return getNaturalAlignIndirect(RetTy);
4520 
4521   return (isPromotableTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
4522                                         : ABIArgInfo::getDirect());
4523 }
4524 
4525 ABIArgInfo AIXABIInfo::classifyArgumentType(QualType Ty) const {
4526   Ty = useFirstFieldIfTransparentUnion(Ty);
4527 
4528   if (Ty->isAnyComplexType())
4529     return ABIArgInfo::getDirect();
4530 
4531   if (Ty->isVectorType())
4532     llvm::report_fatal_error("vector type is not supported on AIX yet");
4533 
4534   if (isAggregateTypeForABI(Ty)) {
4535     // Records with non-trivial destructors/copy-constructors should not be
4536     // passed by value.
4537     if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
4538       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
4539 
4540     CharUnits CCAlign = getParamTypeAlignment(Ty);
4541     CharUnits TyAlign = getContext().getTypeAlignInChars(Ty);
4542 
4543     return ABIArgInfo::getIndirect(CCAlign, /*ByVal*/ true,
4544                                    /*Realign*/ TyAlign > CCAlign);
4545   }
4546 
4547   return (isPromotableTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
4548                                      : ABIArgInfo::getDirect());
4549 }
4550 
4551 CharUnits AIXABIInfo::getParamTypeAlignment(QualType Ty) const {
4552   // Complex types are passed just like their elements.
4553   if (const ComplexType *CTy = Ty->getAs<ComplexType>())
4554     Ty = CTy->getElementType();
4555 
4556   if (Ty->isVectorType())
4557     llvm::report_fatal_error("vector type is not supported on AIX yet");
4558 
4559   // If the structure contains a vector type, the alignment is 16.
4560   if (isRecordWithSIMDVectorType(getContext(), Ty))
4561     return CharUnits::fromQuantity(16);
4562 
4563   return CharUnits::fromQuantity(PtrByteSize);
4564 }
4565 
4566 Address AIXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4567                               QualType Ty) const {
4568   if (Ty->isAnyComplexType())
4569     llvm::report_fatal_error("complex type is not supported on AIX yet");
4570 
4571   if (Ty->isVectorType())
4572     llvm::report_fatal_error("vector type is not supported on AIX yet");
4573 
4574   auto TypeInfo = getContext().getTypeInfoInChars(Ty);
4575   TypeInfo.Align = getParamTypeAlignment(Ty);
4576 
4577   CharUnits SlotSize = CharUnits::fromQuantity(PtrByteSize);
4578 
4579   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false, TypeInfo,
4580                           SlotSize, /*AllowHigher*/ true);
4581 }
4582 
4583 bool AIXTargetCodeGenInfo::initDwarfEHRegSizeTable(
4584     CodeGen::CodeGenFunction &CGF, llvm::Value *Address) const {
4585   return PPC_initDwarfEHRegSizeTable(CGF, Address, Is64Bit, /*IsAIX*/ true);
4586 }
4587 
4588 // PowerPC-32
4589 namespace {
4590 /// PPC32_SVR4_ABIInfo - The 32-bit PowerPC ELF (SVR4) ABI information.
4591 class PPC32_SVR4_ABIInfo : public DefaultABIInfo {
4592   bool IsSoftFloatABI;
4593   bool IsRetSmallStructInRegABI;
4594 
4595   CharUnits getParamTypeAlignment(QualType Ty) const;
4596 
4597 public:
4598   PPC32_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, bool SoftFloatABI,
4599                      bool RetSmallStructInRegABI)
4600       : DefaultABIInfo(CGT), IsSoftFloatABI(SoftFloatABI),
4601         IsRetSmallStructInRegABI(RetSmallStructInRegABI) {}
4602 
4603   ABIArgInfo classifyReturnType(QualType RetTy) const;
4604 
4605   void computeInfo(CGFunctionInfo &FI) const override {
4606     if (!getCXXABI().classifyReturnType(FI))
4607       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
4608     for (auto &I : FI.arguments())
4609       I.info = classifyArgumentType(I.type);
4610   }
4611 
4612   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4613                     QualType Ty) const override;
4614 };
4615 
4616 class PPC32TargetCodeGenInfo : public TargetCodeGenInfo {
4617 public:
4618   PPC32TargetCodeGenInfo(CodeGenTypes &CGT, bool SoftFloatABI,
4619                          bool RetSmallStructInRegABI)
4620       : TargetCodeGenInfo(std::make_unique<PPC32_SVR4_ABIInfo>(
4621             CGT, SoftFloatABI, RetSmallStructInRegABI)) {}
4622 
4623   static bool isStructReturnInRegABI(const llvm::Triple &Triple,
4624                                      const CodeGenOptions &Opts);
4625 
4626   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4627     // This is recovered from gcc output.
4628     return 1; // r1 is the dedicated stack pointer
4629   }
4630 
4631   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4632                                llvm::Value *Address) const override;
4633 };
4634 }
4635 
4636 CharUnits PPC32_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const {
4637   // Complex types are passed just like their elements.
4638   if (const ComplexType *CTy = Ty->getAs<ComplexType>())
4639     Ty = CTy->getElementType();
4640 
4641   if (Ty->isVectorType())
4642     return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16
4643                                                                        : 4);
4644 
4645   // For single-element float/vector structs, we consider the whole type
4646   // to have the same alignment requirements as its single element.
4647   const Type *AlignTy = nullptr;
4648   if (const Type *EltType = isSingleElementStruct(Ty, getContext())) {
4649     const BuiltinType *BT = EltType->getAs<BuiltinType>();
4650     if ((EltType->isVectorType() && getContext().getTypeSize(EltType) == 128) ||
4651         (BT && BT->isFloatingPoint()))
4652       AlignTy = EltType;
4653   }
4654 
4655   if (AlignTy)
4656     return CharUnits::fromQuantity(AlignTy->isVectorType() ? 16 : 4);
4657   return CharUnits::fromQuantity(4);
4658 }
4659 
4660 ABIArgInfo PPC32_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
4661   uint64_t Size;
4662 
4663   // -msvr4-struct-return puts small aggregates in GPR3 and GPR4.
4664   if (isAggregateTypeForABI(RetTy) && IsRetSmallStructInRegABI &&
4665       (Size = getContext().getTypeSize(RetTy)) <= 64) {
4666     // System V ABI (1995), page 3-22, specified:
4667     // > A structure or union whose size is less than or equal to 8 bytes
4668     // > shall be returned in r3 and r4, as if it were first stored in the
4669     // > 8-byte aligned memory area and then the low addressed word were
4670     // > loaded into r3 and the high-addressed word into r4.  Bits beyond
4671     // > the last member of the structure or union are not defined.
4672     //
4673     // GCC for big-endian PPC32 inserts the pad before the first member,
4674     // not "beyond the last member" of the struct.  To stay compatible
4675     // with GCC, we coerce the struct to an integer of the same size.
4676     // LLVM will extend it and return i32 in r3, or i64 in r3:r4.
4677     if (Size == 0)
4678       return ABIArgInfo::getIgnore();
4679     else {
4680       llvm::Type *CoerceTy = llvm::Type::getIntNTy(getVMContext(), Size);
4681       return ABIArgInfo::getDirect(CoerceTy);
4682     }
4683   }
4684 
4685   return DefaultABIInfo::classifyReturnType(RetTy);
4686 }
4687 
4688 // TODO: this implementation is now likely redundant with
4689 // DefaultABIInfo::EmitVAArg.
4690 Address PPC32_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAList,
4691                                       QualType Ty) const {
4692   if (getTarget().getTriple().isOSDarwin()) {
4693     auto TI = getContext().getTypeInfoInChars(Ty);
4694     TI.Align = getParamTypeAlignment(Ty);
4695 
4696     CharUnits SlotSize = CharUnits::fromQuantity(4);
4697     return emitVoidPtrVAArg(CGF, VAList, Ty,
4698                             classifyArgumentType(Ty).isIndirect(), TI, SlotSize,
4699                             /*AllowHigherAlign=*/true);
4700   }
4701 
4702   const unsigned OverflowLimit = 8;
4703   if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
4704     // TODO: Implement this. For now ignore.
4705     (void)CTy;
4706     return Address::invalid(); // FIXME?
4707   }
4708 
4709   // struct __va_list_tag {
4710   //   unsigned char gpr;
4711   //   unsigned char fpr;
4712   //   unsigned short reserved;
4713   //   void *overflow_arg_area;
4714   //   void *reg_save_area;
4715   // };
4716 
4717   bool isI64 = Ty->isIntegerType() && getContext().getTypeSize(Ty) == 64;
4718   bool isInt =
4719       Ty->isIntegerType() || Ty->isPointerType() || Ty->isAggregateType();
4720   bool isF64 = Ty->isFloatingType() && getContext().getTypeSize(Ty) == 64;
4721 
4722   // All aggregates are passed indirectly?  That doesn't seem consistent
4723   // with the argument-lowering code.
4724   bool isIndirect = Ty->isAggregateType();
4725 
4726   CGBuilderTy &Builder = CGF.Builder;
4727 
4728   // The calling convention either uses 1-2 GPRs or 1 FPR.
4729   Address NumRegsAddr = Address::invalid();
4730   if (isInt || IsSoftFloatABI) {
4731     NumRegsAddr = Builder.CreateStructGEP(VAList, 0, "gpr");
4732   } else {
4733     NumRegsAddr = Builder.CreateStructGEP(VAList, 1, "fpr");
4734   }
4735 
4736   llvm::Value *NumRegs = Builder.CreateLoad(NumRegsAddr, "numUsedRegs");
4737 
4738   // "Align" the register count when TY is i64.
4739   if (isI64 || (isF64 && IsSoftFloatABI)) {
4740     NumRegs = Builder.CreateAdd(NumRegs, Builder.getInt8(1));
4741     NumRegs = Builder.CreateAnd(NumRegs, Builder.getInt8((uint8_t) ~1U));
4742   }
4743 
4744   llvm::Value *CC =
4745       Builder.CreateICmpULT(NumRegs, Builder.getInt8(OverflowLimit), "cond");
4746 
4747   llvm::BasicBlock *UsingRegs = CGF.createBasicBlock("using_regs");
4748   llvm::BasicBlock *UsingOverflow = CGF.createBasicBlock("using_overflow");
4749   llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
4750 
4751   Builder.CreateCondBr(CC, UsingRegs, UsingOverflow);
4752 
4753   llvm::Type *DirectTy = CGF.ConvertType(Ty);
4754   if (isIndirect) DirectTy = DirectTy->getPointerTo(0);
4755 
4756   // Case 1: consume registers.
4757   Address RegAddr = Address::invalid();
4758   {
4759     CGF.EmitBlock(UsingRegs);
4760 
4761     Address RegSaveAreaPtr = Builder.CreateStructGEP(VAList, 4);
4762     RegAddr = Address(Builder.CreateLoad(RegSaveAreaPtr),
4763                       CharUnits::fromQuantity(8));
4764     assert(RegAddr.getElementType() == CGF.Int8Ty);
4765 
4766     // Floating-point registers start after the general-purpose registers.
4767     if (!(isInt || IsSoftFloatABI)) {
4768       RegAddr = Builder.CreateConstInBoundsByteGEP(RegAddr,
4769                                                    CharUnits::fromQuantity(32));
4770     }
4771 
4772     // Get the address of the saved value by scaling the number of
4773     // registers we've used by the number of
4774     CharUnits RegSize = CharUnits::fromQuantity((isInt || IsSoftFloatABI) ? 4 : 8);
4775     llvm::Value *RegOffset =
4776       Builder.CreateMul(NumRegs, Builder.getInt8(RegSize.getQuantity()));
4777     RegAddr = Address(Builder.CreateInBoundsGEP(CGF.Int8Ty,
4778                                             RegAddr.getPointer(), RegOffset),
4779                       RegAddr.getAlignment().alignmentOfArrayElement(RegSize));
4780     RegAddr = Builder.CreateElementBitCast(RegAddr, DirectTy);
4781 
4782     // Increase the used-register count.
4783     NumRegs =
4784       Builder.CreateAdd(NumRegs,
4785                         Builder.getInt8((isI64 || (isF64 && IsSoftFloatABI)) ? 2 : 1));
4786     Builder.CreateStore(NumRegs, NumRegsAddr);
4787 
4788     CGF.EmitBranch(Cont);
4789   }
4790 
4791   // Case 2: consume space in the overflow area.
4792   Address MemAddr = Address::invalid();
4793   {
4794     CGF.EmitBlock(UsingOverflow);
4795 
4796     Builder.CreateStore(Builder.getInt8(OverflowLimit), NumRegsAddr);
4797 
4798     // Everything in the overflow area is rounded up to a size of at least 4.
4799     CharUnits OverflowAreaAlign = CharUnits::fromQuantity(4);
4800 
4801     CharUnits Size;
4802     if (!isIndirect) {
4803       auto TypeInfo = CGF.getContext().getTypeInfoInChars(Ty);
4804       Size = TypeInfo.Width.alignTo(OverflowAreaAlign);
4805     } else {
4806       Size = CGF.getPointerSize();
4807     }
4808 
4809     Address OverflowAreaAddr = Builder.CreateStructGEP(VAList, 3);
4810     Address OverflowArea(Builder.CreateLoad(OverflowAreaAddr, "argp.cur"),
4811                          OverflowAreaAlign);
4812     // Round up address of argument to alignment
4813     CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
4814     if (Align > OverflowAreaAlign) {
4815       llvm::Value *Ptr = OverflowArea.getPointer();
4816       OverflowArea = Address(emitRoundPointerUpToAlignment(CGF, Ptr, Align),
4817                                                            Align);
4818     }
4819 
4820     MemAddr = Builder.CreateElementBitCast(OverflowArea, DirectTy);
4821 
4822     // Increase the overflow area.
4823     OverflowArea = Builder.CreateConstInBoundsByteGEP(OverflowArea, Size);
4824     Builder.CreateStore(OverflowArea.getPointer(), OverflowAreaAddr);
4825     CGF.EmitBranch(Cont);
4826   }
4827 
4828   CGF.EmitBlock(Cont);
4829 
4830   // Merge the cases with a phi.
4831   Address Result = emitMergePHI(CGF, RegAddr, UsingRegs, MemAddr, UsingOverflow,
4832                                 "vaarg.addr");
4833 
4834   // Load the pointer if the argument was passed indirectly.
4835   if (isIndirect) {
4836     Result = Address(Builder.CreateLoad(Result, "aggr"),
4837                      getContext().getTypeAlignInChars(Ty));
4838   }
4839 
4840   return Result;
4841 }
4842 
4843 bool PPC32TargetCodeGenInfo::isStructReturnInRegABI(
4844     const llvm::Triple &Triple, const CodeGenOptions &Opts) {
4845   assert(Triple.getArch() == llvm::Triple::ppc);
4846 
4847   switch (Opts.getStructReturnConvention()) {
4848   case CodeGenOptions::SRCK_Default:
4849     break;
4850   case CodeGenOptions::SRCK_OnStack: // -maix-struct-return
4851     return false;
4852   case CodeGenOptions::SRCK_InRegs: // -msvr4-struct-return
4853     return true;
4854   }
4855 
4856   if (Triple.isOSBinFormatELF() && !Triple.isOSLinux())
4857     return true;
4858 
4859   return false;
4860 }
4861 
4862 bool
4863 PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4864                                                 llvm::Value *Address) const {
4865   return PPC_initDwarfEHRegSizeTable(CGF, Address, /*Is64Bit*/ false,
4866                                      /*IsAIX*/ false);
4867 }
4868 
4869 // PowerPC-64
4870 
4871 namespace {
4872 /// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
4873 class PPC64_SVR4_ABIInfo : public SwiftABIInfo {
4874 public:
4875   enum ABIKind {
4876     ELFv1 = 0,
4877     ELFv2
4878   };
4879 
4880 private:
4881   static const unsigned GPRBits = 64;
4882   ABIKind Kind;
4883   bool HasQPX;
4884   bool IsSoftFloatABI;
4885 
4886   // A vector of float or double will be promoted to <4 x f32> or <4 x f64> and
4887   // will be passed in a QPX register.
4888   bool IsQPXVectorTy(const Type *Ty) const {
4889     if (!HasQPX)
4890       return false;
4891 
4892     if (const VectorType *VT = Ty->getAs<VectorType>()) {
4893       unsigned NumElements = VT->getNumElements();
4894       if (NumElements == 1)
4895         return false;
4896 
4897       if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double)) {
4898         if (getContext().getTypeSize(Ty) <= 256)
4899           return true;
4900       } else if (VT->getElementType()->
4901                    isSpecificBuiltinType(BuiltinType::Float)) {
4902         if (getContext().getTypeSize(Ty) <= 128)
4903           return true;
4904       }
4905     }
4906 
4907     return false;
4908   }
4909 
4910   bool IsQPXVectorTy(QualType Ty) const {
4911     return IsQPXVectorTy(Ty.getTypePtr());
4912   }
4913 
4914 public:
4915   PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind, bool HasQPX,
4916                      bool SoftFloatABI)
4917       : SwiftABIInfo(CGT), Kind(Kind), HasQPX(HasQPX),
4918         IsSoftFloatABI(SoftFloatABI) {}
4919 
4920   bool isPromotableTypeForABI(QualType Ty) const;
4921   CharUnits getParamTypeAlignment(QualType Ty) const;
4922 
4923   ABIArgInfo classifyReturnType(QualType RetTy) const;
4924   ABIArgInfo classifyArgumentType(QualType Ty) const;
4925 
4926   bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4927   bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4928                                          uint64_t Members) const override;
4929 
4930   // TODO: We can add more logic to computeInfo to improve performance.
4931   // Example: For aggregate arguments that fit in a register, we could
4932   // use getDirectInReg (as is done below for structs containing a single
4933   // floating-point value) to avoid pushing them to memory on function
4934   // entry.  This would require changing the logic in PPCISelLowering
4935   // when lowering the parameters in the caller and args in the callee.
4936   void computeInfo(CGFunctionInfo &FI) const override {
4937     if (!getCXXABI().classifyReturnType(FI))
4938       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
4939     for (auto &I : FI.arguments()) {
4940       // We rely on the default argument classification for the most part.
4941       // One exception:  An aggregate containing a single floating-point
4942       // or vector item must be passed in a register if one is available.
4943       const Type *T = isSingleElementStruct(I.type, getContext());
4944       if (T) {
4945         const BuiltinType *BT = T->getAs<BuiltinType>();
4946         if (IsQPXVectorTy(T) ||
4947             (T->isVectorType() && getContext().getTypeSize(T) == 128) ||
4948             (BT && BT->isFloatingPoint())) {
4949           QualType QT(T, 0);
4950           I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
4951           continue;
4952         }
4953       }
4954       I.info = classifyArgumentType(I.type);
4955     }
4956   }
4957 
4958   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4959                     QualType Ty) const override;
4960 
4961   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
4962                                     bool asReturnValue) const override {
4963     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
4964   }
4965 
4966   bool isSwiftErrorInRegister() const override {
4967     return false;
4968   }
4969 };
4970 
4971 class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
4972 
4973 public:
4974   PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT,
4975                                PPC64_SVR4_ABIInfo::ABIKind Kind, bool HasQPX,
4976                                bool SoftFloatABI)
4977       : TargetCodeGenInfo(std::make_unique<PPC64_SVR4_ABIInfo>(
4978             CGT, Kind, HasQPX, SoftFloatABI)) {}
4979 
4980   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4981     // This is recovered from gcc output.
4982     return 1; // r1 is the dedicated stack pointer
4983   }
4984 
4985   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4986                                llvm::Value *Address) const override;
4987 };
4988 
4989 class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
4990 public:
4991   PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
4992 
4993   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4994     // This is recovered from gcc output.
4995     return 1; // r1 is the dedicated stack pointer
4996   }
4997 
4998   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4999                                llvm::Value *Address) const override;
5000 };
5001 
5002 }
5003 
5004 // Return true if the ABI requires Ty to be passed sign- or zero-
5005 // extended to 64 bits.
5006 bool
5007 PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
5008   // Treat an enum type as its underlying type.
5009   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5010     Ty = EnumTy->getDecl()->getIntegerType();
5011 
5012   // Promotable integer types are required to be promoted by the ABI.
5013   if (isPromotableIntegerTypeForABI(Ty))
5014     return true;
5015 
5016   // In addition to the usual promotable integer types, we also need to
5017   // extend all 32-bit types, since the ABI requires promotion to 64 bits.
5018   if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
5019     switch (BT->getKind()) {
5020     case BuiltinType::Int:
5021     case BuiltinType::UInt:
5022       return true;
5023     default:
5024       break;
5025     }
5026 
5027   if (const auto *EIT = Ty->getAs<ExtIntType>())
5028     if (EIT->getNumBits() < 64)
5029       return true;
5030 
5031   return false;
5032 }
5033 
5034 /// isAlignedParamType - Determine whether a type requires 16-byte or
5035 /// higher alignment in the parameter area.  Always returns at least 8.
5036 CharUnits PPC64_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const {
5037   // Complex types are passed just like their elements.
5038   if (const ComplexType *CTy = Ty->getAs<ComplexType>())
5039     Ty = CTy->getElementType();
5040 
5041   // Only vector types of size 16 bytes need alignment (larger types are
5042   // passed via reference, smaller types are not aligned).
5043   if (IsQPXVectorTy(Ty)) {
5044     if (getContext().getTypeSize(Ty) > 128)
5045       return CharUnits::fromQuantity(32);
5046 
5047     return CharUnits::fromQuantity(16);
5048   } else if (Ty->isVectorType()) {
5049     return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16 : 8);
5050   }
5051 
5052   // For single-element float/vector structs, we consider the whole type
5053   // to have the same alignment requirements as its single element.
5054   const Type *AlignAsType = nullptr;
5055   const Type *EltType = isSingleElementStruct(Ty, getContext());
5056   if (EltType) {
5057     const BuiltinType *BT = EltType->getAs<BuiltinType>();
5058     if (IsQPXVectorTy(EltType) || (EltType->isVectorType() &&
5059          getContext().getTypeSize(EltType) == 128) ||
5060         (BT && BT->isFloatingPoint()))
5061       AlignAsType = EltType;
5062   }
5063 
5064   // Likewise for ELFv2 homogeneous aggregates.
5065   const Type *Base = nullptr;
5066   uint64_t Members = 0;
5067   if (!AlignAsType && Kind == ELFv2 &&
5068       isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members))
5069     AlignAsType = Base;
5070 
5071   // With special case aggregates, only vector base types need alignment.
5072   if (AlignAsType && IsQPXVectorTy(AlignAsType)) {
5073     if (getContext().getTypeSize(AlignAsType) > 128)
5074       return CharUnits::fromQuantity(32);
5075 
5076     return CharUnits::fromQuantity(16);
5077   } else if (AlignAsType) {
5078     return CharUnits::fromQuantity(AlignAsType->isVectorType() ? 16 : 8);
5079   }
5080 
5081   // Otherwise, we only need alignment for any aggregate type that
5082   // has an alignment requirement of >= 16 bytes.
5083   if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128) {
5084     if (HasQPX && getContext().getTypeAlign(Ty) >= 256)
5085       return CharUnits::fromQuantity(32);
5086     return CharUnits::fromQuantity(16);
5087   }
5088 
5089   return CharUnits::fromQuantity(8);
5090 }
5091 
5092 /// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous
5093 /// aggregate.  Base is set to the base element type, and Members is set
5094 /// to the number of base elements.
5095 bool ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base,
5096                                      uint64_t &Members) const {
5097   if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
5098     uint64_t NElements = AT->getSize().getZExtValue();
5099     if (NElements == 0)
5100       return false;
5101     if (!isHomogeneousAggregate(AT->getElementType(), Base, Members))
5102       return false;
5103     Members *= NElements;
5104   } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
5105     const RecordDecl *RD = RT->getDecl();
5106     if (RD->hasFlexibleArrayMember())
5107       return false;
5108 
5109     Members = 0;
5110 
5111     // If this is a C++ record, check the bases first.
5112     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
5113       for (const auto &I : CXXRD->bases()) {
5114         // Ignore empty records.
5115         if (isEmptyRecord(getContext(), I.getType(), true))
5116           continue;
5117 
5118         uint64_t FldMembers;
5119         if (!isHomogeneousAggregate(I.getType(), Base, FldMembers))
5120           return false;
5121 
5122         Members += FldMembers;
5123       }
5124     }
5125 
5126     for (const auto *FD : RD->fields()) {
5127       // Ignore (non-zero arrays of) empty records.
5128       QualType FT = FD->getType();
5129       while (const ConstantArrayType *AT =
5130              getContext().getAsConstantArrayType(FT)) {
5131         if (AT->getSize().getZExtValue() == 0)
5132           return false;
5133         FT = AT->getElementType();
5134       }
5135       if (isEmptyRecord(getContext(), FT, true))
5136         continue;
5137 
5138       // For compatibility with GCC, ignore empty bitfields in C++ mode.
5139       if (getContext().getLangOpts().CPlusPlus &&
5140           FD->isZeroLengthBitField(getContext()))
5141         continue;
5142 
5143       uint64_t FldMembers;
5144       if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers))
5145         return false;
5146 
5147       Members = (RD->isUnion() ?
5148                  std::max(Members, FldMembers) : Members + FldMembers);
5149     }
5150 
5151     if (!Base)
5152       return false;
5153 
5154     // Ensure there is no padding.
5155     if (getContext().getTypeSize(Base) * Members !=
5156         getContext().getTypeSize(Ty))
5157       return false;
5158   } else {
5159     Members = 1;
5160     if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
5161       Members = 2;
5162       Ty = CT->getElementType();
5163     }
5164 
5165     // Most ABIs only support float, double, and some vector type widths.
5166     if (!isHomogeneousAggregateBaseType(Ty))
5167       return false;
5168 
5169     // The base type must be the same for all members.  Types that
5170     // agree in both total size and mode (float vs. vector) are
5171     // treated as being equivalent here.
5172     const Type *TyPtr = Ty.getTypePtr();
5173     if (!Base) {
5174       Base = TyPtr;
5175       // If it's a non-power-of-2 vector, its size is already a power-of-2,
5176       // so make sure to widen it explicitly.
5177       if (const VectorType *VT = Base->getAs<VectorType>()) {
5178         QualType EltTy = VT->getElementType();
5179         unsigned NumElements =
5180             getContext().getTypeSize(VT) / getContext().getTypeSize(EltTy);
5181         Base = getContext()
5182                    .getVectorType(EltTy, NumElements, VT->getVectorKind())
5183                    .getTypePtr();
5184       }
5185     }
5186 
5187     if (Base->isVectorType() != TyPtr->isVectorType() ||
5188         getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr))
5189       return false;
5190   }
5191   return Members > 0 && isHomogeneousAggregateSmallEnough(Base, Members);
5192 }
5193 
5194 bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
5195   // Homogeneous aggregates for ELFv2 must have base types of float,
5196   // double, long double, or 128-bit vectors.
5197   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
5198     if (BT->getKind() == BuiltinType::Float ||
5199         BT->getKind() == BuiltinType::Double ||
5200         BT->getKind() == BuiltinType::LongDouble ||
5201         (getContext().getTargetInfo().hasFloat128Type() &&
5202           (BT->getKind() == BuiltinType::Float128))) {
5203       if (IsSoftFloatABI)
5204         return false;
5205       return true;
5206     }
5207   }
5208   if (const VectorType *VT = Ty->getAs<VectorType>()) {
5209     if (getContext().getTypeSize(VT) == 128 || IsQPXVectorTy(Ty))
5210       return true;
5211   }
5212   return false;
5213 }
5214 
5215 bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateSmallEnough(
5216     const Type *Base, uint64_t Members) const {
5217   // Vector and fp128 types require one register, other floating point types
5218   // require one or two registers depending on their size.
5219   uint32_t NumRegs =
5220       ((getContext().getTargetInfo().hasFloat128Type() &&
5221           Base->isFloat128Type()) ||
5222         Base->isVectorType()) ? 1
5223                               : (getContext().getTypeSize(Base) + 63) / 64;
5224 
5225   // Homogeneous Aggregates may occupy at most 8 registers.
5226   return Members * NumRegs <= 8;
5227 }
5228 
5229 ABIArgInfo
5230 PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
5231   Ty = useFirstFieldIfTransparentUnion(Ty);
5232 
5233   if (Ty->isAnyComplexType())
5234     return ABIArgInfo::getDirect();
5235 
5236   // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes)
5237   // or via reference (larger than 16 bytes).
5238   if (Ty->isVectorType() && !IsQPXVectorTy(Ty)) {
5239     uint64_t Size = getContext().getTypeSize(Ty);
5240     if (Size > 128)
5241       return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
5242     else if (Size < 128) {
5243       llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
5244       return ABIArgInfo::getDirect(CoerceTy);
5245     }
5246   }
5247 
5248   if (const auto *EIT = Ty->getAs<ExtIntType>())
5249     if (EIT->getNumBits() > 128)
5250       return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
5251 
5252   if (isAggregateTypeForABI(Ty)) {
5253     if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
5254       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
5255 
5256     uint64_t ABIAlign = getParamTypeAlignment(Ty).getQuantity();
5257     uint64_t TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity();
5258 
5259     // ELFv2 homogeneous aggregates are passed as array types.
5260     const Type *Base = nullptr;
5261     uint64_t Members = 0;
5262     if (Kind == ELFv2 &&
5263         isHomogeneousAggregate(Ty, Base, Members)) {
5264       llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
5265       llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
5266       return ABIArgInfo::getDirect(CoerceTy);
5267     }
5268 
5269     // If an aggregate may end up fully in registers, we do not
5270     // use the ByVal method, but pass the aggregate as array.
5271     // This is usually beneficial since we avoid forcing the
5272     // back-end to store the argument to memory.
5273     uint64_t Bits = getContext().getTypeSize(Ty);
5274     if (Bits > 0 && Bits <= 8 * GPRBits) {
5275       llvm::Type *CoerceTy;
5276 
5277       // Types up to 8 bytes are passed as integer type (which will be
5278       // properly aligned in the argument save area doubleword).
5279       if (Bits <= GPRBits)
5280         CoerceTy =
5281             llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
5282       // Larger types are passed as arrays, with the base type selected
5283       // according to the required alignment in the save area.
5284       else {
5285         uint64_t RegBits = ABIAlign * 8;
5286         uint64_t NumRegs = llvm::alignTo(Bits, RegBits) / RegBits;
5287         llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits);
5288         CoerceTy = llvm::ArrayType::get(RegTy, NumRegs);
5289       }
5290 
5291       return ABIArgInfo::getDirect(CoerceTy);
5292     }
5293 
5294     // All other aggregates are passed ByVal.
5295     return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
5296                                    /*ByVal=*/true,
5297                                    /*Realign=*/TyAlign > ABIAlign);
5298   }
5299 
5300   return (isPromotableTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
5301                                      : ABIArgInfo::getDirect());
5302 }
5303 
5304 ABIArgInfo
5305 PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
5306   if (RetTy->isVoidType())
5307     return ABIArgInfo::getIgnore();
5308 
5309   if (RetTy->isAnyComplexType())
5310     return ABIArgInfo::getDirect();
5311 
5312   // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes)
5313   // or via reference (larger than 16 bytes).
5314   if (RetTy->isVectorType() && !IsQPXVectorTy(RetTy)) {
5315     uint64_t Size = getContext().getTypeSize(RetTy);
5316     if (Size > 128)
5317       return getNaturalAlignIndirect(RetTy);
5318     else if (Size < 128) {
5319       llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
5320       return ABIArgInfo::getDirect(CoerceTy);
5321     }
5322   }
5323 
5324   if (const auto *EIT = RetTy->getAs<ExtIntType>())
5325     if (EIT->getNumBits() > 128)
5326       return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
5327 
5328   if (isAggregateTypeForABI(RetTy)) {
5329     // ELFv2 homogeneous aggregates are returned as array types.
5330     const Type *Base = nullptr;
5331     uint64_t Members = 0;
5332     if (Kind == ELFv2 &&
5333         isHomogeneousAggregate(RetTy, Base, Members)) {
5334       llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
5335       llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
5336       return ABIArgInfo::getDirect(CoerceTy);
5337     }
5338 
5339     // ELFv2 small aggregates are returned in up to two registers.
5340     uint64_t Bits = getContext().getTypeSize(RetTy);
5341     if (Kind == ELFv2 && Bits <= 2 * GPRBits) {
5342       if (Bits == 0)
5343         return ABIArgInfo::getIgnore();
5344 
5345       llvm::Type *CoerceTy;
5346       if (Bits > GPRBits) {
5347         CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits);
5348         CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy);
5349       } else
5350         CoerceTy =
5351             llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
5352       return ABIArgInfo::getDirect(CoerceTy);
5353     }
5354 
5355     // All other aggregates are returned indirectly.
5356     return getNaturalAlignIndirect(RetTy);
5357   }
5358 
5359   return (isPromotableTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
5360                                         : ABIArgInfo::getDirect());
5361 }
5362 
5363 // Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
5364 Address PPC64_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5365                                       QualType Ty) const {
5366   auto TypeInfo = getContext().getTypeInfoInChars(Ty);
5367   TypeInfo.Align = getParamTypeAlignment(Ty);
5368 
5369   CharUnits SlotSize = CharUnits::fromQuantity(8);
5370 
5371   // If we have a complex type and the base type is smaller than 8 bytes,
5372   // the ABI calls for the real and imaginary parts to be right-adjusted
5373   // in separate doublewords.  However, Clang expects us to produce a
5374   // pointer to a structure with the two parts packed tightly.  So generate
5375   // loads of the real and imaginary parts relative to the va_list pointer,
5376   // and store them to a temporary structure.
5377   if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
5378     CharUnits EltSize = TypeInfo.Width / 2;
5379     if (EltSize < SlotSize) {
5380       Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, CGF.Int8Ty,
5381                                             SlotSize * 2, SlotSize,
5382                                             SlotSize, /*AllowHigher*/ true);
5383 
5384       Address RealAddr = Addr;
5385       Address ImagAddr = RealAddr;
5386       if (CGF.CGM.getDataLayout().isBigEndian()) {
5387         RealAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr,
5388                                                           SlotSize - EltSize);
5389         ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(ImagAddr,
5390                                                       2 * SlotSize - EltSize);
5391       } else {
5392         ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, SlotSize);
5393       }
5394 
5395       llvm::Type *EltTy = CGF.ConvertTypeForMem(CTy->getElementType());
5396       RealAddr = CGF.Builder.CreateElementBitCast(RealAddr, EltTy);
5397       ImagAddr = CGF.Builder.CreateElementBitCast(ImagAddr, EltTy);
5398       llvm::Value *Real = CGF.Builder.CreateLoad(RealAddr, ".vareal");
5399       llvm::Value *Imag = CGF.Builder.CreateLoad(ImagAddr, ".vaimag");
5400 
5401       Address Temp = CGF.CreateMemTemp(Ty, "vacplx");
5402       CGF.EmitStoreOfComplex({Real, Imag}, CGF.MakeAddrLValue(Temp, Ty),
5403                              /*init*/ true);
5404       return Temp;
5405     }
5406   }
5407 
5408   // Otherwise, just use the general rule.
5409   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
5410                           TypeInfo, SlotSize, /*AllowHigher*/ true);
5411 }
5412 
5413 bool
5414 PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
5415   CodeGen::CodeGenFunction &CGF,
5416   llvm::Value *Address) const {
5417   return PPC_initDwarfEHRegSizeTable(CGF, Address, /*Is64Bit*/ true,
5418                                      /*IsAIX*/ false);
5419 }
5420 
5421 bool
5422 PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
5423                                                 llvm::Value *Address) const {
5424   return PPC_initDwarfEHRegSizeTable(CGF, Address, /*Is64Bit*/ true,
5425                                      /*IsAIX*/ false);
5426 }
5427 
5428 //===----------------------------------------------------------------------===//
5429 // AArch64 ABI Implementation
5430 //===----------------------------------------------------------------------===//
5431 
5432 namespace {
5433 
5434 class AArch64ABIInfo : public SwiftABIInfo {
5435 public:
5436   enum ABIKind {
5437     AAPCS = 0,
5438     DarwinPCS,
5439     Win64
5440   };
5441 
5442 private:
5443   ABIKind Kind;
5444 
5445 public:
5446   AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind)
5447     : SwiftABIInfo(CGT), Kind(Kind) {}
5448 
5449 private:
5450   ABIKind getABIKind() const { return Kind; }
5451   bool isDarwinPCS() const { return Kind == DarwinPCS; }
5452 
5453   ABIArgInfo classifyReturnType(QualType RetTy, bool IsVariadic) const;
5454   ABIArgInfo classifyArgumentType(QualType RetTy) const;
5455   ABIArgInfo coerceIllegalVector(QualType Ty) const;
5456   bool isHomogeneousAggregateBaseType(QualType Ty) const override;
5457   bool isHomogeneousAggregateSmallEnough(const Type *Ty,
5458                                          uint64_t Members) const override;
5459 
5460   bool isIllegalVectorType(QualType Ty) const;
5461 
5462   void computeInfo(CGFunctionInfo &FI) const override {
5463     if (!::classifyReturnType(getCXXABI(), FI, *this))
5464       FI.getReturnInfo() =
5465           classifyReturnType(FI.getReturnType(), FI.isVariadic());
5466 
5467     for (auto &it : FI.arguments())
5468       it.info = classifyArgumentType(it.type);
5469   }
5470 
5471   Address EmitDarwinVAArg(Address VAListAddr, QualType Ty,
5472                           CodeGenFunction &CGF) const;
5473 
5474   Address EmitAAPCSVAArg(Address VAListAddr, QualType Ty,
5475                          CodeGenFunction &CGF) const;
5476 
5477   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5478                     QualType Ty) const override {
5479     return Kind == Win64 ? EmitMSVAArg(CGF, VAListAddr, Ty)
5480                          : isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF)
5481                                          : EmitAAPCSVAArg(VAListAddr, Ty, CGF);
5482   }
5483 
5484   Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
5485                       QualType Ty) const override;
5486 
5487   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
5488                                     bool asReturnValue) const override {
5489     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
5490   }
5491   bool isSwiftErrorInRegister() const override {
5492     return true;
5493   }
5494 
5495   bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy,
5496                                  unsigned elts) const override;
5497 
5498   bool allowBFloatArgsAndRet() const override {
5499     return getTarget().hasBFloat16Type();
5500   }
5501 };
5502 
5503 class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
5504 public:
5505   AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind)
5506       : TargetCodeGenInfo(std::make_unique<AArch64ABIInfo>(CGT, Kind)) {}
5507 
5508   StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
5509     return "mov\tfp, fp\t\t// marker for objc_retainAutoreleaseReturnValue";
5510   }
5511 
5512   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
5513     return 31;
5514   }
5515 
5516   bool doesReturnSlotInterfereWithArgs() const override { return false; }
5517 
5518   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5519                            CodeGen::CodeGenModule &CGM) const override {
5520     const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
5521     if (!FD)
5522       return;
5523 
5524     const auto *TA = FD->getAttr<TargetAttr>();
5525     if (TA == nullptr)
5526       return;
5527 
5528     ParsedTargetAttr Attr = TA->parse();
5529     if (Attr.BranchProtection.empty())
5530       return;
5531 
5532     TargetInfo::BranchProtectionInfo BPI;
5533     StringRef Error;
5534     (void)CGM.getTarget().validateBranchProtection(Attr.BranchProtection,
5535                                                    BPI, Error);
5536     assert(Error.empty());
5537 
5538     auto *Fn = cast<llvm::Function>(GV);
5539     static const char *SignReturnAddrStr[] = {"none", "non-leaf", "all"};
5540     Fn->addFnAttr("sign-return-address", SignReturnAddrStr[static_cast<int>(BPI.SignReturnAddr)]);
5541 
5542     if (BPI.SignReturnAddr != LangOptions::SignReturnAddressScopeKind::None) {
5543       Fn->addFnAttr("sign-return-address-key",
5544                     BPI.SignKey == LangOptions::SignReturnAddressKeyKind::AKey
5545                         ? "a_key"
5546                         : "b_key");
5547     }
5548 
5549     Fn->addFnAttr("branch-target-enforcement",
5550                   BPI.BranchTargetEnforcement ? "true" : "false");
5551   }
5552 };
5553 
5554 class WindowsAArch64TargetCodeGenInfo : public AArch64TargetCodeGenInfo {
5555 public:
5556   WindowsAArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind K)
5557       : AArch64TargetCodeGenInfo(CGT, K) {}
5558 
5559   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5560                            CodeGen::CodeGenModule &CGM) const override;
5561 
5562   void getDependentLibraryOption(llvm::StringRef Lib,
5563                                  llvm::SmallString<24> &Opt) const override {
5564     Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib);
5565   }
5566 
5567   void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value,
5568                                llvm::SmallString<32> &Opt) const override {
5569     Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
5570   }
5571 };
5572 
5573 void WindowsAArch64TargetCodeGenInfo::setTargetAttributes(
5574     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
5575   AArch64TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
5576   if (GV->isDeclaration())
5577     return;
5578   addStackProbeTargetAttributes(D, GV, CGM);
5579 }
5580 }
5581 
5582 ABIArgInfo AArch64ABIInfo::coerceIllegalVector(QualType Ty) const {
5583   assert(Ty->isVectorType() && "expected vector type!");
5584 
5585   const auto *VT = Ty->castAs<VectorType>();
5586   if (VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector) {
5587     assert(VT->getElementType()->isBuiltinType() && "expected builtin type!");
5588     assert(VT->getElementType()->castAs<BuiltinType>()->getKind() ==
5589                BuiltinType::UChar &&
5590            "unexpected builtin type for SVE predicate!");
5591     return ABIArgInfo::getDirect(llvm::ScalableVectorType::get(
5592         llvm::Type::getInt1Ty(getVMContext()), 16));
5593   }
5594 
5595   if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector) {
5596     assert(VT->getElementType()->isBuiltinType() && "expected builtin type!");
5597 
5598     const auto *BT = VT->getElementType()->castAs<BuiltinType>();
5599     llvm::ScalableVectorType *ResType = nullptr;
5600     switch (BT->getKind()) {
5601     default:
5602       llvm_unreachable("unexpected builtin type for SVE vector!");
5603     case BuiltinType::SChar:
5604     case BuiltinType::UChar:
5605       ResType = llvm::ScalableVectorType::get(
5606           llvm::Type::getInt8Ty(getVMContext()), 16);
5607       break;
5608     case BuiltinType::Short:
5609     case BuiltinType::UShort:
5610       ResType = llvm::ScalableVectorType::get(
5611           llvm::Type::getInt16Ty(getVMContext()), 8);
5612       break;
5613     case BuiltinType::Int:
5614     case BuiltinType::UInt:
5615       ResType = llvm::ScalableVectorType::get(
5616           llvm::Type::getInt32Ty(getVMContext()), 4);
5617       break;
5618     case BuiltinType::Long:
5619     case BuiltinType::ULong:
5620       ResType = llvm::ScalableVectorType::get(
5621           llvm::Type::getInt64Ty(getVMContext()), 2);
5622       break;
5623     case BuiltinType::Half:
5624       ResType = llvm::ScalableVectorType::get(
5625           llvm::Type::getHalfTy(getVMContext()), 8);
5626       break;
5627     case BuiltinType::Float:
5628       ResType = llvm::ScalableVectorType::get(
5629           llvm::Type::getFloatTy(getVMContext()), 4);
5630       break;
5631     case BuiltinType::Double:
5632       ResType = llvm::ScalableVectorType::get(
5633           llvm::Type::getDoubleTy(getVMContext()), 2);
5634       break;
5635     case BuiltinType::BFloat16:
5636       ResType = llvm::ScalableVectorType::get(
5637           llvm::Type::getBFloatTy(getVMContext()), 8);
5638       break;
5639     }
5640     return ABIArgInfo::getDirect(ResType);
5641   }
5642 
5643   uint64_t Size = getContext().getTypeSize(Ty);
5644   // Android promotes <2 x i8> to i16, not i32
5645   if (isAndroid() && (Size <= 16)) {
5646     llvm::Type *ResType = llvm::Type::getInt16Ty(getVMContext());
5647     return ABIArgInfo::getDirect(ResType);
5648   }
5649   if (Size <= 32) {
5650     llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext());
5651     return ABIArgInfo::getDirect(ResType);
5652   }
5653   if (Size == 64) {
5654     auto *ResType =
5655         llvm::FixedVectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2);
5656     return ABIArgInfo::getDirect(ResType);
5657   }
5658   if (Size == 128) {
5659     auto *ResType =
5660         llvm::FixedVectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4);
5661     return ABIArgInfo::getDirect(ResType);
5662   }
5663   return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
5664 }
5665 
5666 ABIArgInfo AArch64ABIInfo::classifyArgumentType(QualType Ty) const {
5667   Ty = useFirstFieldIfTransparentUnion(Ty);
5668 
5669   // Handle illegal vector types here.
5670   if (isIllegalVectorType(Ty))
5671     return coerceIllegalVector(Ty);
5672 
5673   if (!isAggregateTypeForABI(Ty)) {
5674     // Treat an enum type as its underlying type.
5675     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5676       Ty = EnumTy->getDecl()->getIntegerType();
5677 
5678     if (const auto *EIT = Ty->getAs<ExtIntType>())
5679       if (EIT->getNumBits() > 128)
5680         return getNaturalAlignIndirect(Ty);
5681 
5682     return (isPromotableIntegerTypeForABI(Ty) && isDarwinPCS()
5683                 ? ABIArgInfo::getExtend(Ty)
5684                 : ABIArgInfo::getDirect());
5685   }
5686 
5687   // Structures with either a non-trivial destructor or a non-trivial
5688   // copy constructor are always indirect.
5689   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
5690     return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA ==
5691                                      CGCXXABI::RAA_DirectInMemory);
5692   }
5693 
5694   // Empty records are always ignored on Darwin, but actually passed in C++ mode
5695   // elsewhere for GNU compatibility.
5696   uint64_t Size = getContext().getTypeSize(Ty);
5697   bool IsEmpty = isEmptyRecord(getContext(), Ty, true);
5698   if (IsEmpty || Size == 0) {
5699     if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS())
5700       return ABIArgInfo::getIgnore();
5701 
5702     // GNU C mode. The only argument that gets ignored is an empty one with size
5703     // 0.
5704     if (IsEmpty && Size == 0)
5705       return ABIArgInfo::getIgnore();
5706     return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
5707   }
5708 
5709   // Homogeneous Floating-point Aggregates (HFAs) need to be expanded.
5710   const Type *Base = nullptr;
5711   uint64_t Members = 0;
5712   if (isHomogeneousAggregate(Ty, Base, Members)) {
5713     return ABIArgInfo::getDirect(
5714         llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members));
5715   }
5716 
5717   // Aggregates <= 16 bytes are passed directly in registers or on the stack.
5718   if (Size <= 128) {
5719     // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
5720     // same size and alignment.
5721     if (getTarget().isRenderScriptTarget()) {
5722       return coerceToIntArray(Ty, getContext(), getVMContext());
5723     }
5724     unsigned Alignment;
5725     if (Kind == AArch64ABIInfo::AAPCS) {
5726       Alignment = getContext().getTypeUnadjustedAlign(Ty);
5727       Alignment = Alignment < 128 ? 64 : 128;
5728     } else {
5729       Alignment = std::max(getContext().getTypeAlign(Ty),
5730                            (unsigned)getTarget().getPointerWidth(0));
5731     }
5732     Size = llvm::alignTo(Size, Alignment);
5733 
5734     // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
5735     // For aggregates with 16-byte alignment, we use i128.
5736     llvm::Type *BaseTy = llvm::Type::getIntNTy(getVMContext(), Alignment);
5737     return ABIArgInfo::getDirect(
5738         Size == Alignment ? BaseTy
5739                           : llvm::ArrayType::get(BaseTy, Size / Alignment));
5740   }
5741 
5742   return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
5743 }
5744 
5745 ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy,
5746                                               bool IsVariadic) const {
5747   if (RetTy->isVoidType())
5748     return ABIArgInfo::getIgnore();
5749 
5750   if (const auto *VT = RetTy->getAs<VectorType>()) {
5751     if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector ||
5752         VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector)
5753       return coerceIllegalVector(RetTy);
5754   }
5755 
5756   // Large vector types should be returned via memory.
5757   if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
5758     return getNaturalAlignIndirect(RetTy);
5759 
5760   if (!isAggregateTypeForABI(RetTy)) {
5761     // Treat an enum type as its underlying type.
5762     if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5763       RetTy = EnumTy->getDecl()->getIntegerType();
5764 
5765     if (const auto *EIT = RetTy->getAs<ExtIntType>())
5766       if (EIT->getNumBits() > 128)
5767         return getNaturalAlignIndirect(RetTy);
5768 
5769     return (isPromotableIntegerTypeForABI(RetTy) && isDarwinPCS()
5770                 ? ABIArgInfo::getExtend(RetTy)
5771                 : ABIArgInfo::getDirect());
5772   }
5773 
5774   uint64_t Size = getContext().getTypeSize(RetTy);
5775   if (isEmptyRecord(getContext(), RetTy, true) || Size == 0)
5776     return ABIArgInfo::getIgnore();
5777 
5778   const Type *Base = nullptr;
5779   uint64_t Members = 0;
5780   if (isHomogeneousAggregate(RetTy, Base, Members) &&
5781       !(getTarget().getTriple().getArch() == llvm::Triple::aarch64_32 &&
5782         IsVariadic))
5783     // Homogeneous Floating-point Aggregates (HFAs) are returned directly.
5784     return ABIArgInfo::getDirect();
5785 
5786   // Aggregates <= 16 bytes are returned directly in registers or on the stack.
5787   if (Size <= 128) {
5788     // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
5789     // same size and alignment.
5790     if (getTarget().isRenderScriptTarget()) {
5791       return coerceToIntArray(RetTy, getContext(), getVMContext());
5792     }
5793     unsigned Alignment = getContext().getTypeAlign(RetTy);
5794     Size = llvm::alignTo(Size, 64); // round up to multiple of 8 bytes
5795 
5796     // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
5797     // For aggregates with 16-byte alignment, we use i128.
5798     if (Alignment < 128 && Size == 128) {
5799       llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
5800       return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
5801     }
5802     return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
5803   }
5804 
5805   return getNaturalAlignIndirect(RetTy);
5806 }
5807 
5808 /// isIllegalVectorType - check whether the vector type is legal for AArch64.
5809 bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const {
5810   if (const VectorType *VT = Ty->getAs<VectorType>()) {
5811     // Check whether VT is a fixed-length SVE vector. These types are
5812     // represented as scalable vectors in function args/return and must be
5813     // coerced from fixed vectors.
5814     if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector ||
5815         VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector)
5816       return true;
5817 
5818     // Check whether VT is legal.
5819     unsigned NumElements = VT->getNumElements();
5820     uint64_t Size = getContext().getTypeSize(VT);
5821     // NumElements should be power of 2.
5822     if (!llvm::isPowerOf2_32(NumElements))
5823       return true;
5824 
5825     // arm64_32 has to be compatible with the ARM logic here, which allows huge
5826     // vectors for some reason.
5827     llvm::Triple Triple = getTarget().getTriple();
5828     if (Triple.getArch() == llvm::Triple::aarch64_32 &&
5829         Triple.isOSBinFormatMachO())
5830       return Size <= 32;
5831 
5832     return Size != 64 && (Size != 128 || NumElements == 1);
5833   }
5834   return false;
5835 }
5836 
5837 bool AArch64ABIInfo::isLegalVectorTypeForSwift(CharUnits totalSize,
5838                                                llvm::Type *eltTy,
5839                                                unsigned elts) const {
5840   if (!llvm::isPowerOf2_32(elts))
5841     return false;
5842   if (totalSize.getQuantity() != 8 &&
5843       (totalSize.getQuantity() != 16 || elts == 1))
5844     return false;
5845   return true;
5846 }
5847 
5848 bool AArch64ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
5849   // Homogeneous aggregates for AAPCS64 must have base types of a floating
5850   // point type or a short-vector type. This is the same as the 32-bit ABI,
5851   // but with the difference that any floating-point type is allowed,
5852   // including __fp16.
5853   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
5854     if (BT->isFloatingPoint())
5855       return true;
5856   } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
5857     unsigned VecSize = getContext().getTypeSize(VT);
5858     if (VecSize == 64 || VecSize == 128)
5859       return true;
5860   }
5861   return false;
5862 }
5863 
5864 bool AArch64ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
5865                                                        uint64_t Members) const {
5866   return Members <= 4;
5867 }
5868 
5869 Address AArch64ABIInfo::EmitAAPCSVAArg(Address VAListAddr,
5870                                             QualType Ty,
5871                                             CodeGenFunction &CGF) const {
5872   ABIArgInfo AI = classifyArgumentType(Ty);
5873   bool IsIndirect = AI.isIndirect();
5874 
5875   llvm::Type *BaseTy = CGF.ConvertType(Ty);
5876   if (IsIndirect)
5877     BaseTy = llvm::PointerType::getUnqual(BaseTy);
5878   else if (AI.getCoerceToType())
5879     BaseTy = AI.getCoerceToType();
5880 
5881   unsigned NumRegs = 1;
5882   if (llvm::ArrayType *ArrTy = dyn_cast<llvm::ArrayType>(BaseTy)) {
5883     BaseTy = ArrTy->getElementType();
5884     NumRegs = ArrTy->getNumElements();
5885   }
5886   bool IsFPR = BaseTy->isFloatingPointTy() || BaseTy->isVectorTy();
5887 
5888   // The AArch64 va_list type and handling is specified in the Procedure Call
5889   // Standard, section B.4:
5890   //
5891   // struct {
5892   //   void *__stack;
5893   //   void *__gr_top;
5894   //   void *__vr_top;
5895   //   int __gr_offs;
5896   //   int __vr_offs;
5897   // };
5898 
5899   llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
5900   llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
5901   llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
5902   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
5903 
5904   CharUnits TySize = getContext().getTypeSizeInChars(Ty);
5905   CharUnits TyAlign = getContext().getTypeUnadjustedAlignInChars(Ty);
5906 
5907   Address reg_offs_p = Address::invalid();
5908   llvm::Value *reg_offs = nullptr;
5909   int reg_top_index;
5910   int RegSize = IsIndirect ? 8 : TySize.getQuantity();
5911   if (!IsFPR) {
5912     // 3 is the field number of __gr_offs
5913     reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 3, "gr_offs_p");
5914     reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
5915     reg_top_index = 1; // field number for __gr_top
5916     RegSize = llvm::alignTo(RegSize, 8);
5917   } else {
5918     // 4 is the field number of __vr_offs.
5919     reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 4, "vr_offs_p");
5920     reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
5921     reg_top_index = 2; // field number for __vr_top
5922     RegSize = 16 * NumRegs;
5923   }
5924 
5925   //=======================================
5926   // Find out where argument was passed
5927   //=======================================
5928 
5929   // If reg_offs >= 0 we're already using the stack for this type of
5930   // argument. We don't want to keep updating reg_offs (in case it overflows,
5931   // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
5932   // whatever they get).
5933   llvm::Value *UsingStack = nullptr;
5934   UsingStack = CGF.Builder.CreateICmpSGE(
5935       reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0));
5936 
5937   CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
5938 
5939   // Otherwise, at least some kind of argument could go in these registers, the
5940   // question is whether this particular type is too big.
5941   CGF.EmitBlock(MaybeRegBlock);
5942 
5943   // Integer arguments may need to correct register alignment (for example a
5944   // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
5945   // align __gr_offs to calculate the potential address.
5946   if (!IsFPR && !IsIndirect && TyAlign.getQuantity() > 8) {
5947     int Align = TyAlign.getQuantity();
5948 
5949     reg_offs = CGF.Builder.CreateAdd(
5950         reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
5951         "align_regoffs");
5952     reg_offs = CGF.Builder.CreateAnd(
5953         reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align),
5954         "aligned_regoffs");
5955   }
5956 
5957   // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
5958   // The fact that this is done unconditionally reflects the fact that
5959   // allocating an argument to the stack also uses up all the remaining
5960   // registers of the appropriate kind.
5961   llvm::Value *NewOffset = nullptr;
5962   NewOffset = CGF.Builder.CreateAdd(
5963       reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs");
5964   CGF.Builder.CreateStore(NewOffset, reg_offs_p);
5965 
5966   // Now we're in a position to decide whether this argument really was in
5967   // registers or not.
5968   llvm::Value *InRegs = nullptr;
5969   InRegs = CGF.Builder.CreateICmpSLE(
5970       NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg");
5971 
5972   CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
5973 
5974   //=======================================
5975   // Argument was in registers
5976   //=======================================
5977 
5978   // Now we emit the code for if the argument was originally passed in
5979   // registers. First start the appropriate block:
5980   CGF.EmitBlock(InRegBlock);
5981 
5982   llvm::Value *reg_top = nullptr;
5983   Address reg_top_p =
5984       CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index, "reg_top_p");
5985   reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
5986   Address BaseAddr(CGF.Builder.CreateInBoundsGEP(reg_top, reg_offs),
5987                    CharUnits::fromQuantity(IsFPR ? 16 : 8));
5988   Address RegAddr = Address::invalid();
5989   llvm::Type *MemTy = CGF.ConvertTypeForMem(Ty);
5990 
5991   if (IsIndirect) {
5992     // If it's been passed indirectly (actually a struct), whatever we find from
5993     // stored registers or on the stack will actually be a struct **.
5994     MemTy = llvm::PointerType::getUnqual(MemTy);
5995   }
5996 
5997   const Type *Base = nullptr;
5998   uint64_t NumMembers = 0;
5999   bool IsHFA = isHomogeneousAggregate(Ty, Base, NumMembers);
6000   if (IsHFA && NumMembers > 1) {
6001     // Homogeneous aggregates passed in registers will have their elements split
6002     // and stored 16-bytes apart regardless of size (they're notionally in qN,
6003     // qN+1, ...). We reload and store into a temporary local variable
6004     // contiguously.
6005     assert(!IsIndirect && "Homogeneous aggregates should be passed directly");
6006     auto BaseTyInfo = getContext().getTypeInfoInChars(QualType(Base, 0));
6007     llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
6008     llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
6009     Address Tmp = CGF.CreateTempAlloca(HFATy,
6010                                        std::max(TyAlign, BaseTyInfo.Align));
6011 
6012     // On big-endian platforms, the value will be right-aligned in its slot.
6013     int Offset = 0;
6014     if (CGF.CGM.getDataLayout().isBigEndian() &&
6015         BaseTyInfo.Width.getQuantity() < 16)
6016       Offset = 16 - BaseTyInfo.Width.getQuantity();
6017 
6018     for (unsigned i = 0; i < NumMembers; ++i) {
6019       CharUnits BaseOffset = CharUnits::fromQuantity(16 * i + Offset);
6020       Address LoadAddr =
6021         CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, BaseOffset);
6022       LoadAddr = CGF.Builder.CreateElementBitCast(LoadAddr, BaseTy);
6023 
6024       Address StoreAddr = CGF.Builder.CreateConstArrayGEP(Tmp, i);
6025 
6026       llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
6027       CGF.Builder.CreateStore(Elem, StoreAddr);
6028     }
6029 
6030     RegAddr = CGF.Builder.CreateElementBitCast(Tmp, MemTy);
6031   } else {
6032     // Otherwise the object is contiguous in memory.
6033 
6034     // It might be right-aligned in its slot.
6035     CharUnits SlotSize = BaseAddr.getAlignment();
6036     if (CGF.CGM.getDataLayout().isBigEndian() && !IsIndirect &&
6037         (IsHFA || !isAggregateTypeForABI(Ty)) &&
6038         TySize < SlotSize) {
6039       CharUnits Offset = SlotSize - TySize;
6040       BaseAddr = CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, Offset);
6041     }
6042 
6043     RegAddr = CGF.Builder.CreateElementBitCast(BaseAddr, MemTy);
6044   }
6045 
6046   CGF.EmitBranch(ContBlock);
6047 
6048   //=======================================
6049   // Argument was on the stack
6050   //=======================================
6051   CGF.EmitBlock(OnStackBlock);
6052 
6053   Address stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "stack_p");
6054   llvm::Value *OnStackPtr = CGF.Builder.CreateLoad(stack_p, "stack");
6055 
6056   // Again, stack arguments may need realignment. In this case both integer and
6057   // floating-point ones might be affected.
6058   if (!IsIndirect && TyAlign.getQuantity() > 8) {
6059     int Align = TyAlign.getQuantity();
6060 
6061     OnStackPtr = CGF.Builder.CreatePtrToInt(OnStackPtr, CGF.Int64Ty);
6062 
6063     OnStackPtr = CGF.Builder.CreateAdd(
6064         OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
6065         "align_stack");
6066     OnStackPtr = CGF.Builder.CreateAnd(
6067         OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, -Align),
6068         "align_stack");
6069 
6070     OnStackPtr = CGF.Builder.CreateIntToPtr(OnStackPtr, CGF.Int8PtrTy);
6071   }
6072   Address OnStackAddr(OnStackPtr,
6073                       std::max(CharUnits::fromQuantity(8), TyAlign));
6074 
6075   // All stack slots are multiples of 8 bytes.
6076   CharUnits StackSlotSize = CharUnits::fromQuantity(8);
6077   CharUnits StackSize;
6078   if (IsIndirect)
6079     StackSize = StackSlotSize;
6080   else
6081     StackSize = TySize.alignTo(StackSlotSize);
6082 
6083   llvm::Value *StackSizeC = CGF.Builder.getSize(StackSize);
6084   llvm::Value *NewStack =
6085       CGF.Builder.CreateInBoundsGEP(OnStackPtr, StackSizeC, "new_stack");
6086 
6087   // Write the new value of __stack for the next call to va_arg
6088   CGF.Builder.CreateStore(NewStack, stack_p);
6089 
6090   if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) &&
6091       TySize < StackSlotSize) {
6092     CharUnits Offset = StackSlotSize - TySize;
6093     OnStackAddr = CGF.Builder.CreateConstInBoundsByteGEP(OnStackAddr, Offset);
6094   }
6095 
6096   OnStackAddr = CGF.Builder.CreateElementBitCast(OnStackAddr, MemTy);
6097 
6098   CGF.EmitBranch(ContBlock);
6099 
6100   //=======================================
6101   // Tidy up
6102   //=======================================
6103   CGF.EmitBlock(ContBlock);
6104 
6105   Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
6106                                  OnStackAddr, OnStackBlock, "vaargs.addr");
6107 
6108   if (IsIndirect)
6109     return Address(CGF.Builder.CreateLoad(ResAddr, "vaarg.addr"),
6110                    TyAlign);
6111 
6112   return ResAddr;
6113 }
6114 
6115 Address AArch64ABIInfo::EmitDarwinVAArg(Address VAListAddr, QualType Ty,
6116                                         CodeGenFunction &CGF) const {
6117   // The backend's lowering doesn't support va_arg for aggregates or
6118   // illegal vector types.  Lower VAArg here for these cases and use
6119   // the LLVM va_arg instruction for everything else.
6120   if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty))
6121     return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
6122 
6123   uint64_t PointerSize = getTarget().getPointerWidth(0) / 8;
6124   CharUnits SlotSize = CharUnits::fromQuantity(PointerSize);
6125 
6126   // Empty records are ignored for parameter passing purposes.
6127   if (isEmptyRecord(getContext(), Ty, true)) {
6128     Address Addr(CGF.Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
6129     Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
6130     return Addr;
6131   }
6132 
6133   // The size of the actual thing passed, which might end up just
6134   // being a pointer for indirect types.
6135   auto TyInfo = getContext().getTypeInfoInChars(Ty);
6136 
6137   // Arguments bigger than 16 bytes which aren't homogeneous
6138   // aggregates should be passed indirectly.
6139   bool IsIndirect = false;
6140   if (TyInfo.Width.getQuantity() > 16) {
6141     const Type *Base = nullptr;
6142     uint64_t Members = 0;
6143     IsIndirect = !isHomogeneousAggregate(Ty, Base, Members);
6144   }
6145 
6146   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
6147                           TyInfo, SlotSize, /*AllowHigherAlign*/ true);
6148 }
6149 
6150 Address AArch64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
6151                                     QualType Ty) const {
6152   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
6153                           CGF.getContext().getTypeInfoInChars(Ty),
6154                           CharUnits::fromQuantity(8),
6155                           /*allowHigherAlign*/ false);
6156 }
6157 
6158 //===----------------------------------------------------------------------===//
6159 // ARM ABI Implementation
6160 //===----------------------------------------------------------------------===//
6161 
6162 namespace {
6163 
6164 class ARMABIInfo : public SwiftABIInfo {
6165 public:
6166   enum ABIKind {
6167     APCS = 0,
6168     AAPCS = 1,
6169     AAPCS_VFP = 2,
6170     AAPCS16_VFP = 3,
6171   };
6172 
6173 private:
6174   ABIKind Kind;
6175   bool IsFloatABISoftFP;
6176 
6177 public:
6178   ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind)
6179       : SwiftABIInfo(CGT), Kind(_Kind) {
6180     setCCs();
6181     IsFloatABISoftFP = CGT.getCodeGenOpts().FloatABI == "softfp" ||
6182         CGT.getCodeGenOpts().FloatABI == ""; // default
6183   }
6184 
6185   bool isEABI() const {
6186     switch (getTarget().getTriple().getEnvironment()) {
6187     case llvm::Triple::Android:
6188     case llvm::Triple::EABI:
6189     case llvm::Triple::EABIHF:
6190     case llvm::Triple::GNUEABI:
6191     case llvm::Triple::GNUEABIHF:
6192     case llvm::Triple::MuslEABI:
6193     case llvm::Triple::MuslEABIHF:
6194       return true;
6195     default:
6196       return false;
6197     }
6198   }
6199 
6200   bool isEABIHF() const {
6201     switch (getTarget().getTriple().getEnvironment()) {
6202     case llvm::Triple::EABIHF:
6203     case llvm::Triple::GNUEABIHF:
6204     case llvm::Triple::MuslEABIHF:
6205       return true;
6206     default:
6207       return false;
6208     }
6209   }
6210 
6211   ABIKind getABIKind() const { return Kind; }
6212 
6213   bool allowBFloatArgsAndRet() const override {
6214     return !IsFloatABISoftFP && getTarget().hasBFloat16Type();
6215   }
6216 
6217 private:
6218   ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic,
6219                                 unsigned functionCallConv) const;
6220   ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic,
6221                                   unsigned functionCallConv) const;
6222   ABIArgInfo classifyHomogeneousAggregate(QualType Ty, const Type *Base,
6223                                           uint64_t Members) const;
6224   ABIArgInfo coerceIllegalVector(QualType Ty) const;
6225   bool isIllegalVectorType(QualType Ty) const;
6226   bool containsAnyFP16Vectors(QualType Ty) const;
6227 
6228   bool isHomogeneousAggregateBaseType(QualType Ty) const override;
6229   bool isHomogeneousAggregateSmallEnough(const Type *Ty,
6230                                          uint64_t Members) const override;
6231 
6232   bool isEffectivelyAAPCS_VFP(unsigned callConvention, bool acceptHalf) const;
6233 
6234   void computeInfo(CGFunctionInfo &FI) const override;
6235 
6236   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6237                     QualType Ty) const override;
6238 
6239   llvm::CallingConv::ID getLLVMDefaultCC() const;
6240   llvm::CallingConv::ID getABIDefaultCC() const;
6241   void setCCs();
6242 
6243   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
6244                                     bool asReturnValue) const override {
6245     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
6246   }
6247   bool isSwiftErrorInRegister() const override {
6248     return true;
6249   }
6250   bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy,
6251                                  unsigned elts) const override;
6252 };
6253 
6254 class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
6255 public:
6256   ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
6257       : TargetCodeGenInfo(std::make_unique<ARMABIInfo>(CGT, K)) {}
6258 
6259   const ARMABIInfo &getABIInfo() const {
6260     return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
6261   }
6262 
6263   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
6264     return 13;
6265   }
6266 
6267   StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
6268     return "mov\tr7, r7\t\t// marker for objc_retainAutoreleaseReturnValue";
6269   }
6270 
6271   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
6272                                llvm::Value *Address) const override {
6273     llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
6274 
6275     // 0-15 are the 16 integer registers.
6276     AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
6277     return false;
6278   }
6279 
6280   unsigned getSizeOfUnwindException() const override {
6281     if (getABIInfo().isEABI()) return 88;
6282     return TargetCodeGenInfo::getSizeOfUnwindException();
6283   }
6284 
6285   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
6286                            CodeGen::CodeGenModule &CGM) const override {
6287     if (GV->isDeclaration())
6288       return;
6289     const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
6290     if (!FD)
6291       return;
6292 
6293     const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
6294     if (!Attr)
6295       return;
6296 
6297     const char *Kind;
6298     switch (Attr->getInterrupt()) {
6299     case ARMInterruptAttr::Generic: Kind = ""; break;
6300     case ARMInterruptAttr::IRQ:     Kind = "IRQ"; break;
6301     case ARMInterruptAttr::FIQ:     Kind = "FIQ"; break;
6302     case ARMInterruptAttr::SWI:     Kind = "SWI"; break;
6303     case ARMInterruptAttr::ABORT:   Kind = "ABORT"; break;
6304     case ARMInterruptAttr::UNDEF:   Kind = "UNDEF"; break;
6305     }
6306 
6307     llvm::Function *Fn = cast<llvm::Function>(GV);
6308 
6309     Fn->addFnAttr("interrupt", Kind);
6310 
6311     ARMABIInfo::ABIKind ABI = cast<ARMABIInfo>(getABIInfo()).getABIKind();
6312     if (ABI == ARMABIInfo::APCS)
6313       return;
6314 
6315     // AAPCS guarantees that sp will be 8-byte aligned on any public interface,
6316     // however this is not necessarily true on taking any interrupt. Instruct
6317     // the backend to perform a realignment as part of the function prologue.
6318     llvm::AttrBuilder B;
6319     B.addStackAlignmentAttr(8);
6320     Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
6321   }
6322 };
6323 
6324 class WindowsARMTargetCodeGenInfo : public ARMTargetCodeGenInfo {
6325 public:
6326   WindowsARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
6327       : ARMTargetCodeGenInfo(CGT, K) {}
6328 
6329   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
6330                            CodeGen::CodeGenModule &CGM) const override;
6331 
6332   void getDependentLibraryOption(llvm::StringRef Lib,
6333                                  llvm::SmallString<24> &Opt) const override {
6334     Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib);
6335   }
6336 
6337   void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value,
6338                                llvm::SmallString<32> &Opt) const override {
6339     Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
6340   }
6341 };
6342 
6343 void WindowsARMTargetCodeGenInfo::setTargetAttributes(
6344     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
6345   ARMTargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
6346   if (GV->isDeclaration())
6347     return;
6348   addStackProbeTargetAttributes(D, GV, CGM);
6349 }
6350 }
6351 
6352 void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
6353   if (!::classifyReturnType(getCXXABI(), FI, *this))
6354     FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), FI.isVariadic(),
6355                                             FI.getCallingConvention());
6356 
6357   for (auto &I : FI.arguments())
6358     I.info = classifyArgumentType(I.type, FI.isVariadic(),
6359                                   FI.getCallingConvention());
6360 
6361 
6362   // Always honor user-specified calling convention.
6363   if (FI.getCallingConvention() != llvm::CallingConv::C)
6364     return;
6365 
6366   llvm::CallingConv::ID cc = getRuntimeCC();
6367   if (cc != llvm::CallingConv::C)
6368     FI.setEffectiveCallingConvention(cc);
6369 }
6370 
6371 /// Return the default calling convention that LLVM will use.
6372 llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
6373   // The default calling convention that LLVM will infer.
6374   if (isEABIHF() || getTarget().getTriple().isWatchABI())
6375     return llvm::CallingConv::ARM_AAPCS_VFP;
6376   else if (isEABI())
6377     return llvm::CallingConv::ARM_AAPCS;
6378   else
6379     return llvm::CallingConv::ARM_APCS;
6380 }
6381 
6382 /// Return the calling convention that our ABI would like us to use
6383 /// as the C calling convention.
6384 llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
6385   switch (getABIKind()) {
6386   case APCS: return llvm::CallingConv::ARM_APCS;
6387   case AAPCS: return llvm::CallingConv::ARM_AAPCS;
6388   case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
6389   case AAPCS16_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
6390   }
6391   llvm_unreachable("bad ABI kind");
6392 }
6393 
6394 void ARMABIInfo::setCCs() {
6395   assert(getRuntimeCC() == llvm::CallingConv::C);
6396 
6397   // Don't muddy up the IR with a ton of explicit annotations if
6398   // they'd just match what LLVM will infer from the triple.
6399   llvm::CallingConv::ID abiCC = getABIDefaultCC();
6400   if (abiCC != getLLVMDefaultCC())
6401     RuntimeCC = abiCC;
6402 }
6403 
6404 ABIArgInfo ARMABIInfo::coerceIllegalVector(QualType Ty) const {
6405   uint64_t Size = getContext().getTypeSize(Ty);
6406   if (Size <= 32) {
6407     llvm::Type *ResType =
6408         llvm::Type::getInt32Ty(getVMContext());
6409     return ABIArgInfo::getDirect(ResType);
6410   }
6411   if (Size == 64 || Size == 128) {
6412     auto *ResType = llvm::FixedVectorType::get(
6413         llvm::Type::getInt32Ty(getVMContext()), Size / 32);
6414     return ABIArgInfo::getDirect(ResType);
6415   }
6416   return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
6417 }
6418 
6419 ABIArgInfo ARMABIInfo::classifyHomogeneousAggregate(QualType Ty,
6420                                                     const Type *Base,
6421                                                     uint64_t Members) const {
6422   assert(Base && "Base class should be set for homogeneous aggregate");
6423   // Base can be a floating-point or a vector.
6424   if (const VectorType *VT = Base->getAs<VectorType>()) {
6425     // FP16 vectors should be converted to integer vectors
6426     if (!getTarget().hasLegalHalfType() && containsAnyFP16Vectors(Ty)) {
6427       uint64_t Size = getContext().getTypeSize(VT);
6428       auto *NewVecTy = llvm::FixedVectorType::get(
6429           llvm::Type::getInt32Ty(getVMContext()), Size / 32);
6430       llvm::Type *Ty = llvm::ArrayType::get(NewVecTy, Members);
6431       return ABIArgInfo::getDirect(Ty, 0, nullptr, false);
6432     }
6433   }
6434   return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
6435 }
6436 
6437 ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty, bool isVariadic,
6438                                             unsigned functionCallConv) const {
6439   // 6.1.2.1 The following argument types are VFP CPRCs:
6440   //   A single-precision floating-point type (including promoted
6441   //   half-precision types); A double-precision floating-point type;
6442   //   A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
6443   //   with a Base Type of a single- or double-precision floating-point type,
6444   //   64-bit containerized vectors or 128-bit containerized vectors with one
6445   //   to four Elements.
6446   // Variadic functions should always marshal to the base standard.
6447   bool IsAAPCS_VFP =
6448       !isVariadic && isEffectivelyAAPCS_VFP(functionCallConv, /* AAPCS16 */ false);
6449 
6450   Ty = useFirstFieldIfTransparentUnion(Ty);
6451 
6452   // Handle illegal vector types here.
6453   if (isIllegalVectorType(Ty))
6454     return coerceIllegalVector(Ty);
6455 
6456   if (!isAggregateTypeForABI(Ty)) {
6457     // Treat an enum type as its underlying type.
6458     if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
6459       Ty = EnumTy->getDecl()->getIntegerType();
6460     }
6461 
6462     if (const auto *EIT = Ty->getAs<ExtIntType>())
6463       if (EIT->getNumBits() > 64)
6464         return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
6465 
6466     return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
6467                                               : ABIArgInfo::getDirect());
6468   }
6469 
6470   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
6471     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
6472   }
6473 
6474   // Ignore empty records.
6475   if (isEmptyRecord(getContext(), Ty, true))
6476     return ABIArgInfo::getIgnore();
6477 
6478   if (IsAAPCS_VFP) {
6479     // Homogeneous Aggregates need to be expanded when we can fit the aggregate
6480     // into VFP registers.
6481     const Type *Base = nullptr;
6482     uint64_t Members = 0;
6483     if (isHomogeneousAggregate(Ty, Base, Members))
6484       return classifyHomogeneousAggregate(Ty, Base, Members);
6485   } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
6486     // WatchOS does have homogeneous aggregates. Note that we intentionally use
6487     // this convention even for a variadic function: the backend will use GPRs
6488     // if needed.
6489     const Type *Base = nullptr;
6490     uint64_t Members = 0;
6491     if (isHomogeneousAggregate(Ty, Base, Members)) {
6492       assert(Base && Members <= 4 && "unexpected homogeneous aggregate");
6493       llvm::Type *Ty =
6494         llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members);
6495       return ABIArgInfo::getDirect(Ty, 0, nullptr, false);
6496     }
6497   }
6498 
6499   if (getABIKind() == ARMABIInfo::AAPCS16_VFP &&
6500       getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(16)) {
6501     // WatchOS is adopting the 64-bit AAPCS rule on composite types: if they're
6502     // bigger than 128-bits, they get placed in space allocated by the caller,
6503     // and a pointer is passed.
6504     return ABIArgInfo::getIndirect(
6505         CharUnits::fromQuantity(getContext().getTypeAlign(Ty) / 8), false);
6506   }
6507 
6508   // Support byval for ARM.
6509   // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
6510   // most 8-byte. We realign the indirect argument if type alignment is bigger
6511   // than ABI alignment.
6512   uint64_t ABIAlign = 4;
6513   uint64_t TyAlign;
6514   if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
6515       getABIKind() == ARMABIInfo::AAPCS) {
6516     TyAlign = getContext().getTypeUnadjustedAlignInChars(Ty).getQuantity();
6517     ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
6518   } else {
6519     TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity();
6520   }
6521   if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
6522     assert(getABIKind() != ARMABIInfo::AAPCS16_VFP && "unexpected byval");
6523     return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
6524                                    /*ByVal=*/true,
6525                                    /*Realign=*/TyAlign > ABIAlign);
6526   }
6527 
6528   // On RenderScript, coerce Aggregates <= 64 bytes to an integer array of
6529   // same size and alignment.
6530   if (getTarget().isRenderScriptTarget()) {
6531     return coerceToIntArray(Ty, getContext(), getVMContext());
6532   }
6533 
6534   // Otherwise, pass by coercing to a structure of the appropriate size.
6535   llvm::Type* ElemTy;
6536   unsigned SizeRegs;
6537   // FIXME: Try to match the types of the arguments more accurately where
6538   // we can.
6539   if (TyAlign <= 4) {
6540     ElemTy = llvm::Type::getInt32Ty(getVMContext());
6541     SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
6542   } else {
6543     ElemTy = llvm::Type::getInt64Ty(getVMContext());
6544     SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
6545   }
6546 
6547   return ABIArgInfo::getDirect(llvm::ArrayType::get(ElemTy, SizeRegs));
6548 }
6549 
6550 static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
6551                               llvm::LLVMContext &VMContext) {
6552   // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
6553   // is called integer-like if its size is less than or equal to one word, and
6554   // the offset of each of its addressable sub-fields is zero.
6555 
6556   uint64_t Size = Context.getTypeSize(Ty);
6557 
6558   // Check that the type fits in a word.
6559   if (Size > 32)
6560     return false;
6561 
6562   // FIXME: Handle vector types!
6563   if (Ty->isVectorType())
6564     return false;
6565 
6566   // Float types are never treated as "integer like".
6567   if (Ty->isRealFloatingType())
6568     return false;
6569 
6570   // If this is a builtin or pointer type then it is ok.
6571   if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
6572     return true;
6573 
6574   // Small complex integer types are "integer like".
6575   if (const ComplexType *CT = Ty->getAs<ComplexType>())
6576     return isIntegerLikeType(CT->getElementType(), Context, VMContext);
6577 
6578   // Single element and zero sized arrays should be allowed, by the definition
6579   // above, but they are not.
6580 
6581   // Otherwise, it must be a record type.
6582   const RecordType *RT = Ty->getAs<RecordType>();
6583   if (!RT) return false;
6584 
6585   // Ignore records with flexible arrays.
6586   const RecordDecl *RD = RT->getDecl();
6587   if (RD->hasFlexibleArrayMember())
6588     return false;
6589 
6590   // Check that all sub-fields are at offset 0, and are themselves "integer
6591   // like".
6592   const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
6593 
6594   bool HadField = false;
6595   unsigned idx = 0;
6596   for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
6597        i != e; ++i, ++idx) {
6598     const FieldDecl *FD = *i;
6599 
6600     // Bit-fields are not addressable, we only need to verify they are "integer
6601     // like". We still have to disallow a subsequent non-bitfield, for example:
6602     //   struct { int : 0; int x }
6603     // is non-integer like according to gcc.
6604     if (FD->isBitField()) {
6605       if (!RD->isUnion())
6606         HadField = true;
6607 
6608       if (!isIntegerLikeType(FD->getType(), Context, VMContext))
6609         return false;
6610 
6611       continue;
6612     }
6613 
6614     // Check if this field is at offset 0.
6615     if (Layout.getFieldOffset(idx) != 0)
6616       return false;
6617 
6618     if (!isIntegerLikeType(FD->getType(), Context, VMContext))
6619       return false;
6620 
6621     // Only allow at most one field in a structure. This doesn't match the
6622     // wording above, but follows gcc in situations with a field following an
6623     // empty structure.
6624     if (!RD->isUnion()) {
6625       if (HadField)
6626         return false;
6627 
6628       HadField = true;
6629     }
6630   }
6631 
6632   return true;
6633 }
6634 
6635 ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy, bool isVariadic,
6636                                           unsigned functionCallConv) const {
6637 
6638   // Variadic functions should always marshal to the base standard.
6639   bool IsAAPCS_VFP =
6640       !isVariadic && isEffectivelyAAPCS_VFP(functionCallConv, /* AAPCS16 */ true);
6641 
6642   if (RetTy->isVoidType())
6643     return ABIArgInfo::getIgnore();
6644 
6645   if (const VectorType *VT = RetTy->getAs<VectorType>()) {
6646     // Large vector types should be returned via memory.
6647     if (getContext().getTypeSize(RetTy) > 128)
6648       return getNaturalAlignIndirect(RetTy);
6649     // TODO: FP16/BF16 vectors should be converted to integer vectors
6650     // This check is similar  to isIllegalVectorType - refactor?
6651     if ((!getTarget().hasLegalHalfType() &&
6652         (VT->getElementType()->isFloat16Type() ||
6653          VT->getElementType()->isHalfType())) ||
6654         (IsFloatABISoftFP &&
6655          VT->getElementType()->isBFloat16Type()))
6656       return coerceIllegalVector(RetTy);
6657   }
6658 
6659   if (!isAggregateTypeForABI(RetTy)) {
6660     // Treat an enum type as its underlying type.
6661     if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6662       RetTy = EnumTy->getDecl()->getIntegerType();
6663 
6664     if (const auto *EIT = RetTy->getAs<ExtIntType>())
6665       if (EIT->getNumBits() > 64)
6666         return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
6667 
6668     return isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
6669                                                 : ABIArgInfo::getDirect();
6670   }
6671 
6672   // Are we following APCS?
6673   if (getABIKind() == APCS) {
6674     if (isEmptyRecord(getContext(), RetTy, false))
6675       return ABIArgInfo::getIgnore();
6676 
6677     // Complex types are all returned as packed integers.
6678     //
6679     // FIXME: Consider using 2 x vector types if the back end handles them
6680     // correctly.
6681     if (RetTy->isAnyComplexType())
6682       return ABIArgInfo::getDirect(llvm::IntegerType::get(
6683           getVMContext(), getContext().getTypeSize(RetTy)));
6684 
6685     // Integer like structures are returned in r0.
6686     if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
6687       // Return in the smallest viable integer type.
6688       uint64_t Size = getContext().getTypeSize(RetTy);
6689       if (Size <= 8)
6690         return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6691       if (Size <= 16)
6692         return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6693       return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6694     }
6695 
6696     // Otherwise return in memory.
6697     return getNaturalAlignIndirect(RetTy);
6698   }
6699 
6700   // Otherwise this is an AAPCS variant.
6701 
6702   if (isEmptyRecord(getContext(), RetTy, true))
6703     return ABIArgInfo::getIgnore();
6704 
6705   // Check for homogeneous aggregates with AAPCS-VFP.
6706   if (IsAAPCS_VFP) {
6707     const Type *Base = nullptr;
6708     uint64_t Members = 0;
6709     if (isHomogeneousAggregate(RetTy, Base, Members))
6710       return classifyHomogeneousAggregate(RetTy, Base, Members);
6711   }
6712 
6713   // Aggregates <= 4 bytes are returned in r0; other aggregates
6714   // are returned indirectly.
6715   uint64_t Size = getContext().getTypeSize(RetTy);
6716   if (Size <= 32) {
6717     // On RenderScript, coerce Aggregates <= 4 bytes to an integer array of
6718     // same size and alignment.
6719     if (getTarget().isRenderScriptTarget()) {
6720       return coerceToIntArray(RetTy, getContext(), getVMContext());
6721     }
6722     if (getDataLayout().isBigEndian())
6723       // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4)
6724       return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6725 
6726     // Return in the smallest viable integer type.
6727     if (Size <= 8)
6728       return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6729     if (Size <= 16)
6730       return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6731     return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6732   } else if (Size <= 128 && getABIKind() == AAPCS16_VFP) {
6733     llvm::Type *Int32Ty = llvm::Type::getInt32Ty(getVMContext());
6734     llvm::Type *CoerceTy =
6735         llvm::ArrayType::get(Int32Ty, llvm::alignTo(Size, 32) / 32);
6736     return ABIArgInfo::getDirect(CoerceTy);
6737   }
6738 
6739   return getNaturalAlignIndirect(RetTy);
6740 }
6741 
6742 /// isIllegalVector - check whether Ty is an illegal vector type.
6743 bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
6744   if (const VectorType *VT = Ty->getAs<VectorType> ()) {
6745     // On targets that don't support half, fp16 or bfloat, they are expanded
6746     // into float, and we don't want the ABI to depend on whether or not they
6747     // are supported in hardware. Thus return false to coerce vectors of these
6748     // types into integer vectors.
6749     // We do not depend on hasLegalHalfType for bfloat as it is a
6750     // separate IR type.
6751     if ((!getTarget().hasLegalHalfType() &&
6752         (VT->getElementType()->isFloat16Type() ||
6753          VT->getElementType()->isHalfType())) ||
6754         (IsFloatABISoftFP &&
6755          VT->getElementType()->isBFloat16Type()))
6756       return true;
6757     if (isAndroid()) {
6758       // Android shipped using Clang 3.1, which supported a slightly different
6759       // vector ABI. The primary differences were that 3-element vector types
6760       // were legal, and so were sub 32-bit vectors (i.e. <2 x i8>). This path
6761       // accepts that legacy behavior for Android only.
6762       // Check whether VT is legal.
6763       unsigned NumElements = VT->getNumElements();
6764       // NumElements should be power of 2 or equal to 3.
6765       if (!llvm::isPowerOf2_32(NumElements) && NumElements != 3)
6766         return true;
6767     } else {
6768       // Check whether VT is legal.
6769       unsigned NumElements = VT->getNumElements();
6770       uint64_t Size = getContext().getTypeSize(VT);
6771       // NumElements should be power of 2.
6772       if (!llvm::isPowerOf2_32(NumElements))
6773         return true;
6774       // Size should be greater than 32 bits.
6775       return Size <= 32;
6776     }
6777   }
6778   return false;
6779 }
6780 
6781 /// Return true if a type contains any 16-bit floating point vectors
6782 bool ARMABIInfo::containsAnyFP16Vectors(QualType Ty) const {
6783   if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
6784     uint64_t NElements = AT->getSize().getZExtValue();
6785     if (NElements == 0)
6786       return false;
6787     return containsAnyFP16Vectors(AT->getElementType());
6788   } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
6789     const RecordDecl *RD = RT->getDecl();
6790 
6791     // If this is a C++ record, check the bases first.
6792     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
6793       if (llvm::any_of(CXXRD->bases(), [this](const CXXBaseSpecifier &B) {
6794             return containsAnyFP16Vectors(B.getType());
6795           }))
6796         return true;
6797 
6798     if (llvm::any_of(RD->fields(), [this](FieldDecl *FD) {
6799           return FD && containsAnyFP16Vectors(FD->getType());
6800         }))
6801       return true;
6802 
6803     return false;
6804   } else {
6805     if (const VectorType *VT = Ty->getAs<VectorType>())
6806       return (VT->getElementType()->isFloat16Type() ||
6807               VT->getElementType()->isBFloat16Type() ||
6808               VT->getElementType()->isHalfType());
6809     return false;
6810   }
6811 }
6812 
6813 bool ARMABIInfo::isLegalVectorTypeForSwift(CharUnits vectorSize,
6814                                            llvm::Type *eltTy,
6815                                            unsigned numElts) const {
6816   if (!llvm::isPowerOf2_32(numElts))
6817     return false;
6818   unsigned size = getDataLayout().getTypeStoreSizeInBits(eltTy);
6819   if (size > 64)
6820     return false;
6821   if (vectorSize.getQuantity() != 8 &&
6822       (vectorSize.getQuantity() != 16 || numElts == 1))
6823     return false;
6824   return true;
6825 }
6826 
6827 bool ARMABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
6828   // Homogeneous aggregates for AAPCS-VFP must have base types of float,
6829   // double, or 64-bit or 128-bit vectors.
6830   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
6831     if (BT->getKind() == BuiltinType::Float ||
6832         BT->getKind() == BuiltinType::Double ||
6833         BT->getKind() == BuiltinType::LongDouble)
6834       return true;
6835   } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
6836     unsigned VecSize = getContext().getTypeSize(VT);
6837     if (VecSize == 64 || VecSize == 128)
6838       return true;
6839   }
6840   return false;
6841 }
6842 
6843 bool ARMABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
6844                                                    uint64_t Members) const {
6845   return Members <= 4;
6846 }
6847 
6848 bool ARMABIInfo::isEffectivelyAAPCS_VFP(unsigned callConvention,
6849                                         bool acceptHalf) const {
6850   // Give precedence to user-specified calling conventions.
6851   if (callConvention != llvm::CallingConv::C)
6852     return (callConvention == llvm::CallingConv::ARM_AAPCS_VFP);
6853   else
6854     return (getABIKind() == AAPCS_VFP) ||
6855            (acceptHalf && (getABIKind() == AAPCS16_VFP));
6856 }
6857 
6858 Address ARMABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6859                               QualType Ty) const {
6860   CharUnits SlotSize = CharUnits::fromQuantity(4);
6861 
6862   // Empty records are ignored for parameter passing purposes.
6863   if (isEmptyRecord(getContext(), Ty, true)) {
6864     Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize);
6865     Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
6866     return Addr;
6867   }
6868 
6869   CharUnits TySize = getContext().getTypeSizeInChars(Ty);
6870   CharUnits TyAlignForABI = getContext().getTypeUnadjustedAlignInChars(Ty);
6871 
6872   // Use indirect if size of the illegal vector is bigger than 16 bytes.
6873   bool IsIndirect = false;
6874   const Type *Base = nullptr;
6875   uint64_t Members = 0;
6876   if (TySize > CharUnits::fromQuantity(16) && isIllegalVectorType(Ty)) {
6877     IsIndirect = true;
6878 
6879   // ARMv7k passes structs bigger than 16 bytes indirectly, in space
6880   // allocated by the caller.
6881   } else if (TySize > CharUnits::fromQuantity(16) &&
6882              getABIKind() == ARMABIInfo::AAPCS16_VFP &&
6883              !isHomogeneousAggregate(Ty, Base, Members)) {
6884     IsIndirect = true;
6885 
6886   // Otherwise, bound the type's ABI alignment.
6887   // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
6888   // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
6889   // Our callers should be prepared to handle an under-aligned address.
6890   } else if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
6891              getABIKind() == ARMABIInfo::AAPCS) {
6892     TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
6893     TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(8));
6894   } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
6895     // ARMv7k allows type alignment up to 16 bytes.
6896     TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
6897     TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(16));
6898   } else {
6899     TyAlignForABI = CharUnits::fromQuantity(4);
6900   }
6901 
6902   TypeInfoChars TyInfo(TySize, TyAlignForABI, false);
6903   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TyInfo,
6904                           SlotSize, /*AllowHigherAlign*/ true);
6905 }
6906 
6907 //===----------------------------------------------------------------------===//
6908 // NVPTX ABI Implementation
6909 //===----------------------------------------------------------------------===//
6910 
6911 namespace {
6912 
6913 class NVPTXTargetCodeGenInfo;
6914 
6915 class NVPTXABIInfo : public ABIInfo {
6916   NVPTXTargetCodeGenInfo &CGInfo;
6917 
6918 public:
6919   NVPTXABIInfo(CodeGenTypes &CGT, NVPTXTargetCodeGenInfo &Info)
6920       : ABIInfo(CGT), CGInfo(Info) {}
6921 
6922   ABIArgInfo classifyReturnType(QualType RetTy) const;
6923   ABIArgInfo classifyArgumentType(QualType Ty) const;
6924 
6925   void computeInfo(CGFunctionInfo &FI) const override;
6926   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6927                     QualType Ty) const override;
6928   bool isUnsupportedType(QualType T) const;
6929   ABIArgInfo coerceToIntArrayWithLimit(QualType Ty, unsigned MaxSize) const;
6930 };
6931 
6932 class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
6933 public:
6934   NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
6935       : TargetCodeGenInfo(std::make_unique<NVPTXABIInfo>(CGT, *this)) {}
6936 
6937   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
6938                            CodeGen::CodeGenModule &M) const override;
6939   bool shouldEmitStaticExternCAliases() const override;
6940 
6941   llvm::Type *getCUDADeviceBuiltinSurfaceDeviceType() const override {
6942     // On the device side, surface reference is represented as an object handle
6943     // in 64-bit integer.
6944     return llvm::Type::getInt64Ty(getABIInfo().getVMContext());
6945   }
6946 
6947   llvm::Type *getCUDADeviceBuiltinTextureDeviceType() const override {
6948     // On the device side, texture reference is represented as an object handle
6949     // in 64-bit integer.
6950     return llvm::Type::getInt64Ty(getABIInfo().getVMContext());
6951   }
6952 
6953   bool emitCUDADeviceBuiltinSurfaceDeviceCopy(CodeGenFunction &CGF, LValue Dst,
6954                                               LValue Src) const override {
6955     emitBuiltinSurfTexDeviceCopy(CGF, Dst, Src);
6956     return true;
6957   }
6958 
6959   bool emitCUDADeviceBuiltinTextureDeviceCopy(CodeGenFunction &CGF, LValue Dst,
6960                                               LValue Src) const override {
6961     emitBuiltinSurfTexDeviceCopy(CGF, Dst, Src);
6962     return true;
6963   }
6964 
6965 private:
6966   // Adds a NamedMDNode with GV, Name, and Operand as operands, and adds the
6967   // resulting MDNode to the nvvm.annotations MDNode.
6968   static void addNVVMMetadata(llvm::GlobalValue *GV, StringRef Name,
6969                               int Operand);
6970 
6971   static void emitBuiltinSurfTexDeviceCopy(CodeGenFunction &CGF, LValue Dst,
6972                                            LValue Src) {
6973     llvm::Value *Handle = nullptr;
6974     llvm::Constant *C =
6975         llvm::dyn_cast<llvm::Constant>(Src.getAddress(CGF).getPointer());
6976     // Lookup `addrspacecast` through the constant pointer if any.
6977     if (auto *ASC = llvm::dyn_cast_or_null<llvm::AddrSpaceCastOperator>(C))
6978       C = llvm::cast<llvm::Constant>(ASC->getPointerOperand());
6979     if (auto *GV = llvm::dyn_cast_or_null<llvm::GlobalVariable>(C)) {
6980       // Load the handle from the specific global variable using
6981       // `nvvm.texsurf.handle.internal` intrinsic.
6982       Handle = CGF.EmitRuntimeCall(
6983           CGF.CGM.getIntrinsic(llvm::Intrinsic::nvvm_texsurf_handle_internal,
6984                                {GV->getType()}),
6985           {GV}, "texsurf_handle");
6986     } else
6987       Handle = CGF.EmitLoadOfScalar(Src, SourceLocation());
6988     CGF.EmitStoreOfScalar(Handle, Dst);
6989   }
6990 };
6991 
6992 /// Checks if the type is unsupported directly by the current target.
6993 bool NVPTXABIInfo::isUnsupportedType(QualType T) const {
6994   ASTContext &Context = getContext();
6995   if (!Context.getTargetInfo().hasFloat16Type() && T->isFloat16Type())
6996     return true;
6997   if (!Context.getTargetInfo().hasFloat128Type() &&
6998       (T->isFloat128Type() ||
6999        (T->isRealFloatingType() && Context.getTypeSize(T) == 128)))
7000     return true;
7001   if (const auto *EIT = T->getAs<ExtIntType>())
7002     return EIT->getNumBits() >
7003            (Context.getTargetInfo().hasInt128Type() ? 128U : 64U);
7004   if (!Context.getTargetInfo().hasInt128Type() && T->isIntegerType() &&
7005       Context.getTypeSize(T) > 64U)
7006     return true;
7007   if (const auto *AT = T->getAsArrayTypeUnsafe())
7008     return isUnsupportedType(AT->getElementType());
7009   const auto *RT = T->getAs<RecordType>();
7010   if (!RT)
7011     return false;
7012   const RecordDecl *RD = RT->getDecl();
7013 
7014   // If this is a C++ record, check the bases first.
7015   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
7016     for (const CXXBaseSpecifier &I : CXXRD->bases())
7017       if (isUnsupportedType(I.getType()))
7018         return true;
7019 
7020   for (const FieldDecl *I : RD->fields())
7021     if (isUnsupportedType(I->getType()))
7022       return true;
7023   return false;
7024 }
7025 
7026 /// Coerce the given type into an array with maximum allowed size of elements.
7027 ABIArgInfo NVPTXABIInfo::coerceToIntArrayWithLimit(QualType Ty,
7028                                                    unsigned MaxSize) const {
7029   // Alignment and Size are measured in bits.
7030   const uint64_t Size = getContext().getTypeSize(Ty);
7031   const uint64_t Alignment = getContext().getTypeAlign(Ty);
7032   const unsigned Div = std::min<unsigned>(MaxSize, Alignment);
7033   llvm::Type *IntType = llvm::Type::getIntNTy(getVMContext(), Div);
7034   const uint64_t NumElements = (Size + Div - 1) / Div;
7035   return ABIArgInfo::getDirect(llvm::ArrayType::get(IntType, NumElements));
7036 }
7037 
7038 ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
7039   if (RetTy->isVoidType())
7040     return ABIArgInfo::getIgnore();
7041 
7042   if (getContext().getLangOpts().OpenMP &&
7043       getContext().getLangOpts().OpenMPIsDevice && isUnsupportedType(RetTy))
7044     return coerceToIntArrayWithLimit(RetTy, 64);
7045 
7046   // note: this is different from default ABI
7047   if (!RetTy->isScalarType())
7048     return ABIArgInfo::getDirect();
7049 
7050   // Treat an enum type as its underlying type.
7051   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
7052     RetTy = EnumTy->getDecl()->getIntegerType();
7053 
7054   return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
7055                                                : ABIArgInfo::getDirect());
7056 }
7057 
7058 ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
7059   // Treat an enum type as its underlying type.
7060   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7061     Ty = EnumTy->getDecl()->getIntegerType();
7062 
7063   // Return aggregates type as indirect by value
7064   if (isAggregateTypeForABI(Ty)) {
7065     // Under CUDA device compilation, tex/surf builtin types are replaced with
7066     // object types and passed directly.
7067     if (getContext().getLangOpts().CUDAIsDevice) {
7068       if (Ty->isCUDADeviceBuiltinSurfaceType())
7069         return ABIArgInfo::getDirect(
7070             CGInfo.getCUDADeviceBuiltinSurfaceDeviceType());
7071       if (Ty->isCUDADeviceBuiltinTextureType())
7072         return ABIArgInfo::getDirect(
7073             CGInfo.getCUDADeviceBuiltinTextureDeviceType());
7074     }
7075     return getNaturalAlignIndirect(Ty, /* byval */ true);
7076   }
7077 
7078   if (const auto *EIT = Ty->getAs<ExtIntType>()) {
7079     if ((EIT->getNumBits() > 128) ||
7080         (!getContext().getTargetInfo().hasInt128Type() &&
7081          EIT->getNumBits() > 64))
7082       return getNaturalAlignIndirect(Ty, /* byval */ true);
7083   }
7084 
7085   return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
7086                                             : ABIArgInfo::getDirect());
7087 }
7088 
7089 void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
7090   if (!getCXXABI().classifyReturnType(FI))
7091     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7092   for (auto &I : FI.arguments())
7093     I.info = classifyArgumentType(I.type);
7094 
7095   // Always honor user-specified calling convention.
7096   if (FI.getCallingConvention() != llvm::CallingConv::C)
7097     return;
7098 
7099   FI.setEffectiveCallingConvention(getRuntimeCC());
7100 }
7101 
7102 Address NVPTXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7103                                 QualType Ty) const {
7104   llvm_unreachable("NVPTX does not support varargs");
7105 }
7106 
7107 void NVPTXTargetCodeGenInfo::setTargetAttributes(
7108     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
7109   if (GV->isDeclaration())
7110     return;
7111   const VarDecl *VD = dyn_cast_or_null<VarDecl>(D);
7112   if (VD) {
7113     if (M.getLangOpts().CUDA) {
7114       if (VD->getType()->isCUDADeviceBuiltinSurfaceType())
7115         addNVVMMetadata(GV, "surface", 1);
7116       else if (VD->getType()->isCUDADeviceBuiltinTextureType())
7117         addNVVMMetadata(GV, "texture", 1);
7118       return;
7119     }
7120   }
7121 
7122   const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
7123   if (!FD) return;
7124 
7125   llvm::Function *F = cast<llvm::Function>(GV);
7126 
7127   // Perform special handling in OpenCL mode
7128   if (M.getLangOpts().OpenCL) {
7129     // Use OpenCL function attributes to check for kernel functions
7130     // By default, all functions are device functions
7131     if (FD->hasAttr<OpenCLKernelAttr>()) {
7132       // OpenCL __kernel functions get kernel metadata
7133       // Create !{<func-ref>, metadata !"kernel", i32 1} node
7134       addNVVMMetadata(F, "kernel", 1);
7135       // And kernel functions are not subject to inlining
7136       F->addFnAttr(llvm::Attribute::NoInline);
7137     }
7138   }
7139 
7140   // Perform special handling in CUDA mode.
7141   if (M.getLangOpts().CUDA) {
7142     // CUDA __global__ functions get a kernel metadata entry.  Since
7143     // __global__ functions cannot be called from the device, we do not
7144     // need to set the noinline attribute.
7145     if (FD->hasAttr<CUDAGlobalAttr>()) {
7146       // Create !{<func-ref>, metadata !"kernel", i32 1} node
7147       addNVVMMetadata(F, "kernel", 1);
7148     }
7149     if (CUDALaunchBoundsAttr *Attr = FD->getAttr<CUDALaunchBoundsAttr>()) {
7150       // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node
7151       llvm::APSInt MaxThreads(32);
7152       MaxThreads = Attr->getMaxThreads()->EvaluateKnownConstInt(M.getContext());
7153       if (MaxThreads > 0)
7154         addNVVMMetadata(F, "maxntidx", MaxThreads.getExtValue());
7155 
7156       // min blocks is an optional argument for CUDALaunchBoundsAttr. If it was
7157       // not specified in __launch_bounds__ or if the user specified a 0 value,
7158       // we don't have to add a PTX directive.
7159       if (Attr->getMinBlocks()) {
7160         llvm::APSInt MinBlocks(32);
7161         MinBlocks = Attr->getMinBlocks()->EvaluateKnownConstInt(M.getContext());
7162         if (MinBlocks > 0)
7163           // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node
7164           addNVVMMetadata(F, "minctasm", MinBlocks.getExtValue());
7165       }
7166     }
7167   }
7168 }
7169 
7170 void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::GlobalValue *GV,
7171                                              StringRef Name, int Operand) {
7172   llvm::Module *M = GV->getParent();
7173   llvm::LLVMContext &Ctx = M->getContext();
7174 
7175   // Get "nvvm.annotations" metadata node
7176   llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
7177 
7178   llvm::Metadata *MDVals[] = {
7179       llvm::ConstantAsMetadata::get(GV), llvm::MDString::get(Ctx, Name),
7180       llvm::ConstantAsMetadata::get(
7181           llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand))};
7182   // Append metadata to nvvm.annotations
7183   MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
7184 }
7185 
7186 bool NVPTXTargetCodeGenInfo::shouldEmitStaticExternCAliases() const {
7187   return false;
7188 }
7189 }
7190 
7191 //===----------------------------------------------------------------------===//
7192 // SystemZ ABI Implementation
7193 //===----------------------------------------------------------------------===//
7194 
7195 namespace {
7196 
7197 class SystemZABIInfo : public SwiftABIInfo {
7198   bool HasVector;
7199   bool IsSoftFloatABI;
7200 
7201 public:
7202   SystemZABIInfo(CodeGenTypes &CGT, bool HV, bool SF)
7203     : SwiftABIInfo(CGT), HasVector(HV), IsSoftFloatABI(SF) {}
7204 
7205   bool isPromotableIntegerTypeForABI(QualType Ty) const;
7206   bool isCompoundType(QualType Ty) const;
7207   bool isVectorArgumentType(QualType Ty) const;
7208   bool isFPArgumentType(QualType Ty) const;
7209   QualType GetSingleElementType(QualType Ty) const;
7210 
7211   ABIArgInfo classifyReturnType(QualType RetTy) const;
7212   ABIArgInfo classifyArgumentType(QualType ArgTy) const;
7213 
7214   void computeInfo(CGFunctionInfo &FI) const override {
7215     if (!getCXXABI().classifyReturnType(FI))
7216       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7217     for (auto &I : FI.arguments())
7218       I.info = classifyArgumentType(I.type);
7219   }
7220 
7221   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7222                     QualType Ty) const override;
7223 
7224   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
7225                                     bool asReturnValue) const override {
7226     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
7227   }
7228   bool isSwiftErrorInRegister() const override {
7229     return false;
7230   }
7231 };
7232 
7233 class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
7234 public:
7235   SystemZTargetCodeGenInfo(CodeGenTypes &CGT, bool HasVector, bool SoftFloatABI)
7236       : TargetCodeGenInfo(
7237             std::make_unique<SystemZABIInfo>(CGT, HasVector, SoftFloatABI)) {}
7238 };
7239 
7240 }
7241 
7242 bool SystemZABIInfo::isPromotableIntegerTypeForABI(QualType Ty) const {
7243   // Treat an enum type as its underlying type.
7244   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7245     Ty = EnumTy->getDecl()->getIntegerType();
7246 
7247   // Promotable integer types are required to be promoted by the ABI.
7248   if (ABIInfo::isPromotableIntegerTypeForABI(Ty))
7249     return true;
7250 
7251   if (const auto *EIT = Ty->getAs<ExtIntType>())
7252     if (EIT->getNumBits() < 64)
7253       return true;
7254 
7255   // 32-bit values must also be promoted.
7256   if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
7257     switch (BT->getKind()) {
7258     case BuiltinType::Int:
7259     case BuiltinType::UInt:
7260       return true;
7261     default:
7262       return false;
7263     }
7264   return false;
7265 }
7266 
7267 bool SystemZABIInfo::isCompoundType(QualType Ty) const {
7268   return (Ty->isAnyComplexType() ||
7269           Ty->isVectorType() ||
7270           isAggregateTypeForABI(Ty));
7271 }
7272 
7273 bool SystemZABIInfo::isVectorArgumentType(QualType Ty) const {
7274   return (HasVector &&
7275           Ty->isVectorType() &&
7276           getContext().getTypeSize(Ty) <= 128);
7277 }
7278 
7279 bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
7280   if (IsSoftFloatABI)
7281     return false;
7282 
7283   if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
7284     switch (BT->getKind()) {
7285     case BuiltinType::Float:
7286     case BuiltinType::Double:
7287       return true;
7288     default:
7289       return false;
7290     }
7291 
7292   return false;
7293 }
7294 
7295 QualType SystemZABIInfo::GetSingleElementType(QualType Ty) const {
7296   const RecordType *RT = Ty->getAs<RecordType>();
7297 
7298   if (RT && RT->isStructureOrClassType()) {
7299     const RecordDecl *RD = RT->getDecl();
7300     QualType Found;
7301 
7302     // If this is a C++ record, check the bases first.
7303     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
7304       for (const auto &I : CXXRD->bases()) {
7305         QualType Base = I.getType();
7306 
7307         // Empty bases don't affect things either way.
7308         if (isEmptyRecord(getContext(), Base, true))
7309           continue;
7310 
7311         if (!Found.isNull())
7312           return Ty;
7313         Found = GetSingleElementType(Base);
7314       }
7315 
7316     // Check the fields.
7317     for (const auto *FD : RD->fields()) {
7318       // For compatibility with GCC, ignore empty bitfields in C++ mode.
7319       // Unlike isSingleElementStruct(), empty structure and array fields
7320       // do count.  So do anonymous bitfields that aren't zero-sized.
7321       if (getContext().getLangOpts().CPlusPlus &&
7322           FD->isZeroLengthBitField(getContext()))
7323         continue;
7324       // Like isSingleElementStruct(), ignore C++20 empty data members.
7325       if (FD->hasAttr<NoUniqueAddressAttr>() &&
7326           isEmptyRecord(getContext(), FD->getType(), true))
7327         continue;
7328 
7329       // Unlike isSingleElementStruct(), arrays do not count.
7330       // Nested structures still do though.
7331       if (!Found.isNull())
7332         return Ty;
7333       Found = GetSingleElementType(FD->getType());
7334     }
7335 
7336     // Unlike isSingleElementStruct(), trailing padding is allowed.
7337     // An 8-byte aligned struct s { float f; } is passed as a double.
7338     if (!Found.isNull())
7339       return Found;
7340   }
7341 
7342   return Ty;
7343 }
7344 
7345 Address SystemZABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7346                                   QualType Ty) const {
7347   // Assume that va_list type is correct; should be pointer to LLVM type:
7348   // struct {
7349   //   i64 __gpr;
7350   //   i64 __fpr;
7351   //   i8 *__overflow_arg_area;
7352   //   i8 *__reg_save_area;
7353   // };
7354 
7355   // Every non-vector argument occupies 8 bytes and is passed by preference
7356   // in either GPRs or FPRs.  Vector arguments occupy 8 or 16 bytes and are
7357   // always passed on the stack.
7358   Ty = getContext().getCanonicalType(Ty);
7359   auto TyInfo = getContext().getTypeInfoInChars(Ty);
7360   llvm::Type *ArgTy = CGF.ConvertTypeForMem(Ty);
7361   llvm::Type *DirectTy = ArgTy;
7362   ABIArgInfo AI = classifyArgumentType(Ty);
7363   bool IsIndirect = AI.isIndirect();
7364   bool InFPRs = false;
7365   bool IsVector = false;
7366   CharUnits UnpaddedSize;
7367   CharUnits DirectAlign;
7368   if (IsIndirect) {
7369     DirectTy = llvm::PointerType::getUnqual(DirectTy);
7370     UnpaddedSize = DirectAlign = CharUnits::fromQuantity(8);
7371   } else {
7372     if (AI.getCoerceToType())
7373       ArgTy = AI.getCoerceToType();
7374     InFPRs = (!IsSoftFloatABI && (ArgTy->isFloatTy() || ArgTy->isDoubleTy()));
7375     IsVector = ArgTy->isVectorTy();
7376     UnpaddedSize = TyInfo.Width;
7377     DirectAlign = TyInfo.Align;
7378   }
7379   CharUnits PaddedSize = CharUnits::fromQuantity(8);
7380   if (IsVector && UnpaddedSize > PaddedSize)
7381     PaddedSize = CharUnits::fromQuantity(16);
7382   assert((UnpaddedSize <= PaddedSize) && "Invalid argument size.");
7383 
7384   CharUnits Padding = (PaddedSize - UnpaddedSize);
7385 
7386   llvm::Type *IndexTy = CGF.Int64Ty;
7387   llvm::Value *PaddedSizeV =
7388     llvm::ConstantInt::get(IndexTy, PaddedSize.getQuantity());
7389 
7390   if (IsVector) {
7391     // Work out the address of a vector argument on the stack.
7392     // Vector arguments are always passed in the high bits of a
7393     // single (8 byte) or double (16 byte) stack slot.
7394     Address OverflowArgAreaPtr =
7395         CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr");
7396     Address OverflowArgArea =
7397       Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
7398               TyInfo.Align);
7399     Address MemAddr =
7400       CGF.Builder.CreateElementBitCast(OverflowArgArea, DirectTy, "mem_addr");
7401 
7402     // Update overflow_arg_area_ptr pointer
7403     llvm::Value *NewOverflowArgArea =
7404       CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
7405                             "overflow_arg_area");
7406     CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
7407 
7408     return MemAddr;
7409   }
7410 
7411   assert(PaddedSize.getQuantity() == 8);
7412 
7413   unsigned MaxRegs, RegCountField, RegSaveIndex;
7414   CharUnits RegPadding;
7415   if (InFPRs) {
7416     MaxRegs = 4; // Maximum of 4 FPR arguments
7417     RegCountField = 1; // __fpr
7418     RegSaveIndex = 16; // save offset for f0
7419     RegPadding = CharUnits(); // floats are passed in the high bits of an FPR
7420   } else {
7421     MaxRegs = 5; // Maximum of 5 GPR arguments
7422     RegCountField = 0; // __gpr
7423     RegSaveIndex = 2; // save offset for r2
7424     RegPadding = Padding; // values are passed in the low bits of a GPR
7425   }
7426 
7427   Address RegCountPtr =
7428       CGF.Builder.CreateStructGEP(VAListAddr, RegCountField, "reg_count_ptr");
7429   llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
7430   llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
7431   llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
7432                                                  "fits_in_regs");
7433 
7434   llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
7435   llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
7436   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
7437   CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
7438 
7439   // Emit code to load the value if it was passed in registers.
7440   CGF.EmitBlock(InRegBlock);
7441 
7442   // Work out the address of an argument register.
7443   llvm::Value *ScaledRegCount =
7444     CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
7445   llvm::Value *RegBase =
7446     llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize.getQuantity()
7447                                       + RegPadding.getQuantity());
7448   llvm::Value *RegOffset =
7449     CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
7450   Address RegSaveAreaPtr =
7451       CGF.Builder.CreateStructGEP(VAListAddr, 3, "reg_save_area_ptr");
7452   llvm::Value *RegSaveArea =
7453     CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
7454   Address RawRegAddr(CGF.Builder.CreateGEP(RegSaveArea, RegOffset,
7455                                            "raw_reg_addr"),
7456                      PaddedSize);
7457   Address RegAddr =
7458     CGF.Builder.CreateElementBitCast(RawRegAddr, DirectTy, "reg_addr");
7459 
7460   // Update the register count
7461   llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
7462   llvm::Value *NewRegCount =
7463     CGF.Builder.CreateAdd(RegCount, One, "reg_count");
7464   CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
7465   CGF.EmitBranch(ContBlock);
7466 
7467   // Emit code to load the value if it was passed in memory.
7468   CGF.EmitBlock(InMemBlock);
7469 
7470   // Work out the address of a stack argument.
7471   Address OverflowArgAreaPtr =
7472       CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr");
7473   Address OverflowArgArea =
7474     Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
7475             PaddedSize);
7476   Address RawMemAddr =
7477     CGF.Builder.CreateConstByteGEP(OverflowArgArea, Padding, "raw_mem_addr");
7478   Address MemAddr =
7479     CGF.Builder.CreateElementBitCast(RawMemAddr, DirectTy, "mem_addr");
7480 
7481   // Update overflow_arg_area_ptr pointer
7482   llvm::Value *NewOverflowArgArea =
7483     CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
7484                           "overflow_arg_area");
7485   CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
7486   CGF.EmitBranch(ContBlock);
7487 
7488   // Return the appropriate result.
7489   CGF.EmitBlock(ContBlock);
7490   Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
7491                                  MemAddr, InMemBlock, "va_arg.addr");
7492 
7493   if (IsIndirect)
7494     ResAddr = Address(CGF.Builder.CreateLoad(ResAddr, "indirect_arg"),
7495                       TyInfo.Align);
7496 
7497   return ResAddr;
7498 }
7499 
7500 ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
7501   if (RetTy->isVoidType())
7502     return ABIArgInfo::getIgnore();
7503   if (isVectorArgumentType(RetTy))
7504     return ABIArgInfo::getDirect();
7505   if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
7506     return getNaturalAlignIndirect(RetTy);
7507   return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
7508                                                : ABIArgInfo::getDirect());
7509 }
7510 
7511 ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
7512   // Handle the generic C++ ABI.
7513   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
7514     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
7515 
7516   // Integers and enums are extended to full register width.
7517   if (isPromotableIntegerTypeForABI(Ty))
7518     return ABIArgInfo::getExtend(Ty);
7519 
7520   // Handle vector types and vector-like structure types.  Note that
7521   // as opposed to float-like structure types, we do not allow any
7522   // padding for vector-like structures, so verify the sizes match.
7523   uint64_t Size = getContext().getTypeSize(Ty);
7524   QualType SingleElementTy = GetSingleElementType(Ty);
7525   if (isVectorArgumentType(SingleElementTy) &&
7526       getContext().getTypeSize(SingleElementTy) == Size)
7527     return ABIArgInfo::getDirect(CGT.ConvertType(SingleElementTy));
7528 
7529   // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
7530   if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
7531     return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
7532 
7533   // Handle small structures.
7534   if (const RecordType *RT = Ty->getAs<RecordType>()) {
7535     // Structures with flexible arrays have variable length, so really
7536     // fail the size test above.
7537     const RecordDecl *RD = RT->getDecl();
7538     if (RD->hasFlexibleArrayMember())
7539       return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
7540 
7541     // The structure is passed as an unextended integer, a float, or a double.
7542     llvm::Type *PassTy;
7543     if (isFPArgumentType(SingleElementTy)) {
7544       assert(Size == 32 || Size == 64);
7545       if (Size == 32)
7546         PassTy = llvm::Type::getFloatTy(getVMContext());
7547       else
7548         PassTy = llvm::Type::getDoubleTy(getVMContext());
7549     } else
7550       PassTy = llvm::IntegerType::get(getVMContext(), Size);
7551     return ABIArgInfo::getDirect(PassTy);
7552   }
7553 
7554   // Non-structure compounds are passed indirectly.
7555   if (isCompoundType(Ty))
7556     return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
7557 
7558   return ABIArgInfo::getDirect(nullptr);
7559 }
7560 
7561 //===----------------------------------------------------------------------===//
7562 // MSP430 ABI Implementation
7563 //===----------------------------------------------------------------------===//
7564 
7565 namespace {
7566 
7567 class MSP430ABIInfo : public DefaultABIInfo {
7568   static ABIArgInfo complexArgInfo() {
7569     ABIArgInfo Info = ABIArgInfo::getDirect();
7570     Info.setCanBeFlattened(false);
7571     return Info;
7572   }
7573 
7574 public:
7575   MSP430ABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
7576 
7577   ABIArgInfo classifyReturnType(QualType RetTy) const {
7578     if (RetTy->isAnyComplexType())
7579       return complexArgInfo();
7580 
7581     return DefaultABIInfo::classifyReturnType(RetTy);
7582   }
7583 
7584   ABIArgInfo classifyArgumentType(QualType RetTy) const {
7585     if (RetTy->isAnyComplexType())
7586       return complexArgInfo();
7587 
7588     return DefaultABIInfo::classifyArgumentType(RetTy);
7589   }
7590 
7591   // Just copy the original implementations because
7592   // DefaultABIInfo::classify{Return,Argument}Type() are not virtual
7593   void computeInfo(CGFunctionInfo &FI) const override {
7594     if (!getCXXABI().classifyReturnType(FI))
7595       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7596     for (auto &I : FI.arguments())
7597       I.info = classifyArgumentType(I.type);
7598   }
7599 
7600   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7601                     QualType Ty) const override {
7602     return EmitVAArgInstr(CGF, VAListAddr, Ty, classifyArgumentType(Ty));
7603   }
7604 };
7605 
7606 class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
7607 public:
7608   MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
7609       : TargetCodeGenInfo(std::make_unique<MSP430ABIInfo>(CGT)) {}
7610   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
7611                            CodeGen::CodeGenModule &M) const override;
7612 };
7613 
7614 }
7615 
7616 void MSP430TargetCodeGenInfo::setTargetAttributes(
7617     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
7618   if (GV->isDeclaration())
7619     return;
7620   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
7621     const auto *InterruptAttr = FD->getAttr<MSP430InterruptAttr>();
7622     if (!InterruptAttr)
7623       return;
7624 
7625     // Handle 'interrupt' attribute:
7626     llvm::Function *F = cast<llvm::Function>(GV);
7627 
7628     // Step 1: Set ISR calling convention.
7629     F->setCallingConv(llvm::CallingConv::MSP430_INTR);
7630 
7631     // Step 2: Add attributes goodness.
7632     F->addFnAttr(llvm::Attribute::NoInline);
7633     F->addFnAttr("interrupt", llvm::utostr(InterruptAttr->getNumber()));
7634   }
7635 }
7636 
7637 //===----------------------------------------------------------------------===//
7638 // MIPS ABI Implementation.  This works for both little-endian and
7639 // big-endian variants.
7640 //===----------------------------------------------------------------------===//
7641 
7642 namespace {
7643 class MipsABIInfo : public ABIInfo {
7644   bool IsO32;
7645   unsigned MinABIStackAlignInBytes, StackAlignInBytes;
7646   void CoerceToIntArgs(uint64_t TySize,
7647                        SmallVectorImpl<llvm::Type *> &ArgList) const;
7648   llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
7649   llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
7650   llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
7651 public:
7652   MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
7653     ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
7654     StackAlignInBytes(IsO32 ? 8 : 16) {}
7655 
7656   ABIArgInfo classifyReturnType(QualType RetTy) const;
7657   ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
7658   void computeInfo(CGFunctionInfo &FI) const override;
7659   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7660                     QualType Ty) const override;
7661   ABIArgInfo extendType(QualType Ty) const;
7662 };
7663 
7664 class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
7665   unsigned SizeOfUnwindException;
7666 public:
7667   MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
7668       : TargetCodeGenInfo(std::make_unique<MipsABIInfo>(CGT, IsO32)),
7669         SizeOfUnwindException(IsO32 ? 24 : 32) {}
7670 
7671   int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
7672     return 29;
7673   }
7674 
7675   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
7676                            CodeGen::CodeGenModule &CGM) const override {
7677     const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
7678     if (!FD) return;
7679     llvm::Function *Fn = cast<llvm::Function>(GV);
7680 
7681     if (FD->hasAttr<MipsLongCallAttr>())
7682       Fn->addFnAttr("long-call");
7683     else if (FD->hasAttr<MipsShortCallAttr>())
7684       Fn->addFnAttr("short-call");
7685 
7686     // Other attributes do not have a meaning for declarations.
7687     if (GV->isDeclaration())
7688       return;
7689 
7690     if (FD->hasAttr<Mips16Attr>()) {
7691       Fn->addFnAttr("mips16");
7692     }
7693     else if (FD->hasAttr<NoMips16Attr>()) {
7694       Fn->addFnAttr("nomips16");
7695     }
7696 
7697     if (FD->hasAttr<MicroMipsAttr>())
7698       Fn->addFnAttr("micromips");
7699     else if (FD->hasAttr<NoMicroMipsAttr>())
7700       Fn->addFnAttr("nomicromips");
7701 
7702     const MipsInterruptAttr *Attr = FD->getAttr<MipsInterruptAttr>();
7703     if (!Attr)
7704       return;
7705 
7706     const char *Kind;
7707     switch (Attr->getInterrupt()) {
7708     case MipsInterruptAttr::eic:     Kind = "eic"; break;
7709     case MipsInterruptAttr::sw0:     Kind = "sw0"; break;
7710     case MipsInterruptAttr::sw1:     Kind = "sw1"; break;
7711     case MipsInterruptAttr::hw0:     Kind = "hw0"; break;
7712     case MipsInterruptAttr::hw1:     Kind = "hw1"; break;
7713     case MipsInterruptAttr::hw2:     Kind = "hw2"; break;
7714     case MipsInterruptAttr::hw3:     Kind = "hw3"; break;
7715     case MipsInterruptAttr::hw4:     Kind = "hw4"; break;
7716     case MipsInterruptAttr::hw5:     Kind = "hw5"; break;
7717     }
7718 
7719     Fn->addFnAttr("interrupt", Kind);
7720 
7721   }
7722 
7723   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
7724                                llvm::Value *Address) const override;
7725 
7726   unsigned getSizeOfUnwindException() const override {
7727     return SizeOfUnwindException;
7728   }
7729 };
7730 }
7731 
7732 void MipsABIInfo::CoerceToIntArgs(
7733     uint64_t TySize, SmallVectorImpl<llvm::Type *> &ArgList) const {
7734   llvm::IntegerType *IntTy =
7735     llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
7736 
7737   // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
7738   for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
7739     ArgList.push_back(IntTy);
7740 
7741   // If necessary, add one more integer type to ArgList.
7742   unsigned R = TySize % (MinABIStackAlignInBytes * 8);
7743 
7744   if (R)
7745     ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
7746 }
7747 
7748 // In N32/64, an aligned double precision floating point field is passed in
7749 // a register.
7750 llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
7751   SmallVector<llvm::Type*, 8> ArgList, IntArgList;
7752 
7753   if (IsO32) {
7754     CoerceToIntArgs(TySize, ArgList);
7755     return llvm::StructType::get(getVMContext(), ArgList);
7756   }
7757 
7758   if (Ty->isComplexType())
7759     return CGT.ConvertType(Ty);
7760 
7761   const RecordType *RT = Ty->getAs<RecordType>();
7762 
7763   // Unions/vectors are passed in integer registers.
7764   if (!RT || !RT->isStructureOrClassType()) {
7765     CoerceToIntArgs(TySize, ArgList);
7766     return llvm::StructType::get(getVMContext(), ArgList);
7767   }
7768 
7769   const RecordDecl *RD = RT->getDecl();
7770   const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
7771   assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
7772 
7773   uint64_t LastOffset = 0;
7774   unsigned idx = 0;
7775   llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
7776 
7777   // Iterate over fields in the struct/class and check if there are any aligned
7778   // double fields.
7779   for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
7780        i != e; ++i, ++idx) {
7781     const QualType Ty = i->getType();
7782     const BuiltinType *BT = Ty->getAs<BuiltinType>();
7783 
7784     if (!BT || BT->getKind() != BuiltinType::Double)
7785       continue;
7786 
7787     uint64_t Offset = Layout.getFieldOffset(idx);
7788     if (Offset % 64) // Ignore doubles that are not aligned.
7789       continue;
7790 
7791     // Add ((Offset - LastOffset) / 64) args of type i64.
7792     for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
7793       ArgList.push_back(I64);
7794 
7795     // Add double type.
7796     ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
7797     LastOffset = Offset + 64;
7798   }
7799 
7800   CoerceToIntArgs(TySize - LastOffset, IntArgList);
7801   ArgList.append(IntArgList.begin(), IntArgList.end());
7802 
7803   return llvm::StructType::get(getVMContext(), ArgList);
7804 }
7805 
7806 llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
7807                                         uint64_t Offset) const {
7808   if (OrigOffset + MinABIStackAlignInBytes > Offset)
7809     return nullptr;
7810 
7811   return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
7812 }
7813 
7814 ABIArgInfo
7815 MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
7816   Ty = useFirstFieldIfTransparentUnion(Ty);
7817 
7818   uint64_t OrigOffset = Offset;
7819   uint64_t TySize = getContext().getTypeSize(Ty);
7820   uint64_t Align = getContext().getTypeAlign(Ty) / 8;
7821 
7822   Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
7823                    (uint64_t)StackAlignInBytes);
7824   unsigned CurrOffset = llvm::alignTo(Offset, Align);
7825   Offset = CurrOffset + llvm::alignTo(TySize, Align * 8) / 8;
7826 
7827   if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
7828     // Ignore empty aggregates.
7829     if (TySize == 0)
7830       return ABIArgInfo::getIgnore();
7831 
7832     if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
7833       Offset = OrigOffset + MinABIStackAlignInBytes;
7834       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
7835     }
7836 
7837     // If we have reached here, aggregates are passed directly by coercing to
7838     // another structure type. Padding is inserted if the offset of the
7839     // aggregate is unaligned.
7840     ABIArgInfo ArgInfo =
7841         ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
7842                               getPaddingType(OrigOffset, CurrOffset));
7843     ArgInfo.setInReg(true);
7844     return ArgInfo;
7845   }
7846 
7847   // Treat an enum type as its underlying type.
7848   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7849     Ty = EnumTy->getDecl()->getIntegerType();
7850 
7851   // Make sure we pass indirectly things that are too large.
7852   if (const auto *EIT = Ty->getAs<ExtIntType>())
7853     if (EIT->getNumBits() > 128 ||
7854         (EIT->getNumBits() > 64 &&
7855          !getContext().getTargetInfo().hasInt128Type()))
7856       return getNaturalAlignIndirect(Ty);
7857 
7858   // All integral types are promoted to the GPR width.
7859   if (Ty->isIntegralOrEnumerationType())
7860     return extendType(Ty);
7861 
7862   return ABIArgInfo::getDirect(
7863       nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset));
7864 }
7865 
7866 llvm::Type*
7867 MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
7868   const RecordType *RT = RetTy->getAs<RecordType>();
7869   SmallVector<llvm::Type*, 8> RTList;
7870 
7871   if (RT && RT->isStructureOrClassType()) {
7872     const RecordDecl *RD = RT->getDecl();
7873     const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
7874     unsigned FieldCnt = Layout.getFieldCount();
7875 
7876     // N32/64 returns struct/classes in floating point registers if the
7877     // following conditions are met:
7878     // 1. The size of the struct/class is no larger than 128-bit.
7879     // 2. The struct/class has one or two fields all of which are floating
7880     //    point types.
7881     // 3. The offset of the first field is zero (this follows what gcc does).
7882     //
7883     // Any other composite results are returned in integer registers.
7884     //
7885     if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
7886       RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
7887       for (; b != e; ++b) {
7888         const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
7889 
7890         if (!BT || !BT->isFloatingPoint())
7891           break;
7892 
7893         RTList.push_back(CGT.ConvertType(b->getType()));
7894       }
7895 
7896       if (b == e)
7897         return llvm::StructType::get(getVMContext(), RTList,
7898                                      RD->hasAttr<PackedAttr>());
7899 
7900       RTList.clear();
7901     }
7902   }
7903 
7904   CoerceToIntArgs(Size, RTList);
7905   return llvm::StructType::get(getVMContext(), RTList);
7906 }
7907 
7908 ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
7909   uint64_t Size = getContext().getTypeSize(RetTy);
7910 
7911   if (RetTy->isVoidType())
7912     return ABIArgInfo::getIgnore();
7913 
7914   // O32 doesn't treat zero-sized structs differently from other structs.
7915   // However, N32/N64 ignores zero sized return values.
7916   if (!IsO32 && Size == 0)
7917     return ABIArgInfo::getIgnore();
7918 
7919   if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
7920     if (Size <= 128) {
7921       if (RetTy->isAnyComplexType())
7922         return ABIArgInfo::getDirect();
7923 
7924       // O32 returns integer vectors in registers and N32/N64 returns all small
7925       // aggregates in registers.
7926       if (!IsO32 ||
7927           (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) {
7928         ABIArgInfo ArgInfo =
7929             ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
7930         ArgInfo.setInReg(true);
7931         return ArgInfo;
7932       }
7933     }
7934 
7935     return getNaturalAlignIndirect(RetTy);
7936   }
7937 
7938   // Treat an enum type as its underlying type.
7939   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
7940     RetTy = EnumTy->getDecl()->getIntegerType();
7941 
7942   // Make sure we pass indirectly things that are too large.
7943   if (const auto *EIT = RetTy->getAs<ExtIntType>())
7944     if (EIT->getNumBits() > 128 ||
7945         (EIT->getNumBits() > 64 &&
7946          !getContext().getTargetInfo().hasInt128Type()))
7947       return getNaturalAlignIndirect(RetTy);
7948 
7949   if (isPromotableIntegerTypeForABI(RetTy))
7950     return ABIArgInfo::getExtend(RetTy);
7951 
7952   if ((RetTy->isUnsignedIntegerOrEnumerationType() ||
7953       RetTy->isSignedIntegerOrEnumerationType()) && Size == 32 && !IsO32)
7954     return ABIArgInfo::getSignExtend(RetTy);
7955 
7956   return ABIArgInfo::getDirect();
7957 }
7958 
7959 void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
7960   ABIArgInfo &RetInfo = FI.getReturnInfo();
7961   if (!getCXXABI().classifyReturnType(FI))
7962     RetInfo = classifyReturnType(FI.getReturnType());
7963 
7964   // Check if a pointer to an aggregate is passed as a hidden argument.
7965   uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
7966 
7967   for (auto &I : FI.arguments())
7968     I.info = classifyArgumentType(I.type, Offset);
7969 }
7970 
7971 Address MipsABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7972                                QualType OrigTy) const {
7973   QualType Ty = OrigTy;
7974 
7975   // Integer arguments are promoted to 32-bit on O32 and 64-bit on N32/N64.
7976   // Pointers are also promoted in the same way but this only matters for N32.
7977   unsigned SlotSizeInBits = IsO32 ? 32 : 64;
7978   unsigned PtrWidth = getTarget().getPointerWidth(0);
7979   bool DidPromote = false;
7980   if ((Ty->isIntegerType() &&
7981           getContext().getIntWidth(Ty) < SlotSizeInBits) ||
7982       (Ty->isPointerType() && PtrWidth < SlotSizeInBits)) {
7983     DidPromote = true;
7984     Ty = getContext().getIntTypeForBitwidth(SlotSizeInBits,
7985                                             Ty->isSignedIntegerType());
7986   }
7987 
7988   auto TyInfo = getContext().getTypeInfoInChars(Ty);
7989 
7990   // The alignment of things in the argument area is never larger than
7991   // StackAlignInBytes.
7992   TyInfo.Align =
7993     std::min(TyInfo.Align, CharUnits::fromQuantity(StackAlignInBytes));
7994 
7995   // MinABIStackAlignInBytes is the size of argument slots on the stack.
7996   CharUnits ArgSlotSize = CharUnits::fromQuantity(MinABIStackAlignInBytes);
7997 
7998   Address Addr = emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
7999                           TyInfo, ArgSlotSize, /*AllowHigherAlign*/ true);
8000 
8001 
8002   // If there was a promotion, "unpromote" into a temporary.
8003   // TODO: can we just use a pointer into a subset of the original slot?
8004   if (DidPromote) {
8005     Address Temp = CGF.CreateMemTemp(OrigTy, "vaarg.promotion-temp");
8006     llvm::Value *Promoted = CGF.Builder.CreateLoad(Addr);
8007 
8008     // Truncate down to the right width.
8009     llvm::Type *IntTy = (OrigTy->isIntegerType() ? Temp.getElementType()
8010                                                  : CGF.IntPtrTy);
8011     llvm::Value *V = CGF.Builder.CreateTrunc(Promoted, IntTy);
8012     if (OrigTy->isPointerType())
8013       V = CGF.Builder.CreateIntToPtr(V, Temp.getElementType());
8014 
8015     CGF.Builder.CreateStore(V, Temp);
8016     Addr = Temp;
8017   }
8018 
8019   return Addr;
8020 }
8021 
8022 ABIArgInfo MipsABIInfo::extendType(QualType Ty) const {
8023   int TySize = getContext().getTypeSize(Ty);
8024 
8025   // MIPS64 ABI requires unsigned 32 bit integers to be sign extended.
8026   if (Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
8027     return ABIArgInfo::getSignExtend(Ty);
8028 
8029   return ABIArgInfo::getExtend(Ty);
8030 }
8031 
8032 bool
8033 MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
8034                                                llvm::Value *Address) const {
8035   // This information comes from gcc's implementation, which seems to
8036   // as canonical as it gets.
8037 
8038   // Everything on MIPS is 4 bytes.  Double-precision FP registers
8039   // are aliased to pairs of single-precision FP registers.
8040   llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
8041 
8042   // 0-31 are the general purpose registers, $0 - $31.
8043   // 32-63 are the floating-point registers, $f0 - $f31.
8044   // 64 and 65 are the multiply/divide registers, $hi and $lo.
8045   // 66 is the (notional, I think) register for signal-handler return.
8046   AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
8047 
8048   // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
8049   // They are one bit wide and ignored here.
8050 
8051   // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
8052   // (coprocessor 1 is the FP unit)
8053   // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
8054   // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
8055   // 176-181 are the DSP accumulator registers.
8056   AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
8057   return false;
8058 }
8059 
8060 //===----------------------------------------------------------------------===//
8061 // AVR ABI Implementation.
8062 //===----------------------------------------------------------------------===//
8063 
8064 namespace {
8065 class AVRTargetCodeGenInfo : public TargetCodeGenInfo {
8066 public:
8067   AVRTargetCodeGenInfo(CodeGenTypes &CGT)
8068       : TargetCodeGenInfo(std::make_unique<DefaultABIInfo>(CGT)) {}
8069 
8070   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
8071                            CodeGen::CodeGenModule &CGM) const override {
8072     if (GV->isDeclaration())
8073       return;
8074     const auto *FD = dyn_cast_or_null<FunctionDecl>(D);
8075     if (!FD) return;
8076     auto *Fn = cast<llvm::Function>(GV);
8077 
8078     if (FD->getAttr<AVRInterruptAttr>())
8079       Fn->addFnAttr("interrupt");
8080 
8081     if (FD->getAttr<AVRSignalAttr>())
8082       Fn->addFnAttr("signal");
8083   }
8084 };
8085 }
8086 
8087 //===----------------------------------------------------------------------===//
8088 // TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
8089 // Currently subclassed only to implement custom OpenCL C function attribute
8090 // handling.
8091 //===----------------------------------------------------------------------===//
8092 
8093 namespace {
8094 
8095 class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
8096 public:
8097   TCETargetCodeGenInfo(CodeGenTypes &CGT)
8098     : DefaultTargetCodeGenInfo(CGT) {}
8099 
8100   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
8101                            CodeGen::CodeGenModule &M) const override;
8102 };
8103 
8104 void TCETargetCodeGenInfo::setTargetAttributes(
8105     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
8106   if (GV->isDeclaration())
8107     return;
8108   const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
8109   if (!FD) return;
8110 
8111   llvm::Function *F = cast<llvm::Function>(GV);
8112 
8113   if (M.getLangOpts().OpenCL) {
8114     if (FD->hasAttr<OpenCLKernelAttr>()) {
8115       // OpenCL C Kernel functions are not subject to inlining
8116       F->addFnAttr(llvm::Attribute::NoInline);
8117       const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
8118       if (Attr) {
8119         // Convert the reqd_work_group_size() attributes to metadata.
8120         llvm::LLVMContext &Context = F->getContext();
8121         llvm::NamedMDNode *OpenCLMetadata =
8122             M.getModule().getOrInsertNamedMetadata(
8123                 "opencl.kernel_wg_size_info");
8124 
8125         SmallVector<llvm::Metadata *, 5> Operands;
8126         Operands.push_back(llvm::ConstantAsMetadata::get(F));
8127 
8128         Operands.push_back(
8129             llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
8130                 M.Int32Ty, llvm::APInt(32, Attr->getXDim()))));
8131         Operands.push_back(
8132             llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
8133                 M.Int32Ty, llvm::APInt(32, Attr->getYDim()))));
8134         Operands.push_back(
8135             llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
8136                 M.Int32Ty, llvm::APInt(32, Attr->getZDim()))));
8137 
8138         // Add a boolean constant operand for "required" (true) or "hint"
8139         // (false) for implementing the work_group_size_hint attr later.
8140         // Currently always true as the hint is not yet implemented.
8141         Operands.push_back(
8142             llvm::ConstantAsMetadata::get(llvm::ConstantInt::getTrue(Context)));
8143         OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
8144       }
8145     }
8146   }
8147 }
8148 
8149 }
8150 
8151 //===----------------------------------------------------------------------===//
8152 // Hexagon ABI Implementation
8153 //===----------------------------------------------------------------------===//
8154 
8155 namespace {
8156 
8157 class HexagonABIInfo : public DefaultABIInfo {
8158 public:
8159   HexagonABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
8160 
8161 private:
8162   ABIArgInfo classifyReturnType(QualType RetTy) const;
8163   ABIArgInfo classifyArgumentType(QualType RetTy) const;
8164   ABIArgInfo classifyArgumentType(QualType RetTy, unsigned *RegsLeft) const;
8165 
8166   void computeInfo(CGFunctionInfo &FI) const override;
8167 
8168   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8169                     QualType Ty) const override;
8170   Address EmitVAArgFromMemory(CodeGenFunction &CFG, Address VAListAddr,
8171                               QualType Ty) const;
8172   Address EmitVAArgForHexagon(CodeGenFunction &CFG, Address VAListAddr,
8173                               QualType Ty) const;
8174   Address EmitVAArgForHexagonLinux(CodeGenFunction &CFG, Address VAListAddr,
8175                                    QualType Ty) const;
8176 };
8177 
8178 class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
8179 public:
8180   HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
8181       : TargetCodeGenInfo(std::make_unique<HexagonABIInfo>(CGT)) {}
8182 
8183   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
8184     return 29;
8185   }
8186 
8187   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
8188                            CodeGen::CodeGenModule &GCM) const override {
8189     if (GV->isDeclaration())
8190       return;
8191     const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
8192     if (!FD)
8193       return;
8194   }
8195 };
8196 
8197 } // namespace
8198 
8199 void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
8200   unsigned RegsLeft = 6;
8201   if (!getCXXABI().classifyReturnType(FI))
8202     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
8203   for (auto &I : FI.arguments())
8204     I.info = classifyArgumentType(I.type, &RegsLeft);
8205 }
8206 
8207 static bool HexagonAdjustRegsLeft(uint64_t Size, unsigned *RegsLeft) {
8208   assert(Size <= 64 && "Not expecting to pass arguments larger than 64 bits"
8209                        " through registers");
8210 
8211   if (*RegsLeft == 0)
8212     return false;
8213 
8214   if (Size <= 32) {
8215     (*RegsLeft)--;
8216     return true;
8217   }
8218 
8219   if (2 <= (*RegsLeft & (~1U))) {
8220     *RegsLeft = (*RegsLeft & (~1U)) - 2;
8221     return true;
8222   }
8223 
8224   // Next available register was r5 but candidate was greater than 32-bits so it
8225   // has to go on the stack. However we still consume r5
8226   if (*RegsLeft == 1)
8227     *RegsLeft = 0;
8228 
8229   return false;
8230 }
8231 
8232 ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty,
8233                                                 unsigned *RegsLeft) const {
8234   if (!isAggregateTypeForABI(Ty)) {
8235     // Treat an enum type as its underlying type.
8236     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
8237       Ty = EnumTy->getDecl()->getIntegerType();
8238 
8239     uint64_t Size = getContext().getTypeSize(Ty);
8240     if (Size <= 64)
8241       HexagonAdjustRegsLeft(Size, RegsLeft);
8242 
8243     if (Size > 64 && Ty->isExtIntType())
8244       return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
8245 
8246     return isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
8247                                              : ABIArgInfo::getDirect();
8248   }
8249 
8250   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
8251     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
8252 
8253   // Ignore empty records.
8254   if (isEmptyRecord(getContext(), Ty, true))
8255     return ABIArgInfo::getIgnore();
8256 
8257   uint64_t Size = getContext().getTypeSize(Ty);
8258   unsigned Align = getContext().getTypeAlign(Ty);
8259 
8260   if (Size > 64)
8261     return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
8262 
8263   if (HexagonAdjustRegsLeft(Size, RegsLeft))
8264     Align = Size <= 32 ? 32 : 64;
8265   if (Size <= Align) {
8266     // Pass in the smallest viable integer type.
8267     if (!llvm::isPowerOf2_64(Size))
8268       Size = llvm::NextPowerOf2(Size);
8269     return ABIArgInfo::getDirect(llvm::Type::getIntNTy(getVMContext(), Size));
8270   }
8271   return DefaultABIInfo::classifyArgumentType(Ty);
8272 }
8273 
8274 ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
8275   if (RetTy->isVoidType())
8276     return ABIArgInfo::getIgnore();
8277 
8278   const TargetInfo &T = CGT.getTarget();
8279   uint64_t Size = getContext().getTypeSize(RetTy);
8280 
8281   if (RetTy->getAs<VectorType>()) {
8282     // HVX vectors are returned in vector registers or register pairs.
8283     if (T.hasFeature("hvx")) {
8284       assert(T.hasFeature("hvx-length64b") || T.hasFeature("hvx-length128b"));
8285       uint64_t VecSize = T.hasFeature("hvx-length64b") ? 64*8 : 128*8;
8286       if (Size == VecSize || Size == 2*VecSize)
8287         return ABIArgInfo::getDirectInReg();
8288     }
8289     // Large vector types should be returned via memory.
8290     if (Size > 64)
8291       return getNaturalAlignIndirect(RetTy);
8292   }
8293 
8294   if (!isAggregateTypeForABI(RetTy)) {
8295     // Treat an enum type as its underlying type.
8296     if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
8297       RetTy = EnumTy->getDecl()->getIntegerType();
8298 
8299     if (Size > 64 && RetTy->isExtIntType())
8300       return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
8301 
8302     return isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
8303                                                 : ABIArgInfo::getDirect();
8304   }
8305 
8306   if (isEmptyRecord(getContext(), RetTy, true))
8307     return ABIArgInfo::getIgnore();
8308 
8309   // Aggregates <= 8 bytes are returned in registers, other aggregates
8310   // are returned indirectly.
8311   if (Size <= 64) {
8312     // Return in the smallest viable integer type.
8313     if (!llvm::isPowerOf2_64(Size))
8314       Size = llvm::NextPowerOf2(Size);
8315     return ABIArgInfo::getDirect(llvm::Type::getIntNTy(getVMContext(), Size));
8316   }
8317   return getNaturalAlignIndirect(RetTy, /*ByVal=*/true);
8318 }
8319 
8320 Address HexagonABIInfo::EmitVAArgFromMemory(CodeGenFunction &CGF,
8321                                             Address VAListAddr,
8322                                             QualType Ty) const {
8323   // Load the overflow area pointer.
8324   Address __overflow_area_pointer_p =
8325       CGF.Builder.CreateStructGEP(VAListAddr, 2, "__overflow_area_pointer_p");
8326   llvm::Value *__overflow_area_pointer = CGF.Builder.CreateLoad(
8327       __overflow_area_pointer_p, "__overflow_area_pointer");
8328 
8329   uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8;
8330   if (Align > 4) {
8331     // Alignment should be a power of 2.
8332     assert((Align & (Align - 1)) == 0 && "Alignment is not power of 2!");
8333 
8334     // overflow_arg_area = (overflow_arg_area + align - 1) & -align;
8335     llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int64Ty, Align - 1);
8336 
8337     // Add offset to the current pointer to access the argument.
8338     __overflow_area_pointer =
8339         CGF.Builder.CreateGEP(__overflow_area_pointer, Offset);
8340     llvm::Value *AsInt =
8341         CGF.Builder.CreatePtrToInt(__overflow_area_pointer, CGF.Int32Ty);
8342 
8343     // Create a mask which should be "AND"ed
8344     // with (overflow_arg_area + align - 1)
8345     llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int32Ty, -(int)Align);
8346     __overflow_area_pointer = CGF.Builder.CreateIntToPtr(
8347         CGF.Builder.CreateAnd(AsInt, Mask), __overflow_area_pointer->getType(),
8348         "__overflow_area_pointer.align");
8349   }
8350 
8351   // Get the type of the argument from memory and bitcast
8352   // overflow area pointer to the argument type.
8353   llvm::Type *PTy = CGF.ConvertTypeForMem(Ty);
8354   Address AddrTyped = CGF.Builder.CreateBitCast(
8355       Address(__overflow_area_pointer, CharUnits::fromQuantity(Align)),
8356       llvm::PointerType::getUnqual(PTy));
8357 
8358   // Round up to the minimum stack alignment for varargs which is 4 bytes.
8359   uint64_t Offset = llvm::alignTo(CGF.getContext().getTypeSize(Ty) / 8, 4);
8360 
8361   __overflow_area_pointer = CGF.Builder.CreateGEP(
8362       __overflow_area_pointer, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
8363       "__overflow_area_pointer.next");
8364   CGF.Builder.CreateStore(__overflow_area_pointer, __overflow_area_pointer_p);
8365 
8366   return AddrTyped;
8367 }
8368 
8369 Address HexagonABIInfo::EmitVAArgForHexagon(CodeGenFunction &CGF,
8370                                             Address VAListAddr,
8371                                             QualType Ty) const {
8372   // FIXME: Need to handle alignment
8373   llvm::Type *BP = CGF.Int8PtrTy;
8374   llvm::Type *BPP = CGF.Int8PtrPtrTy;
8375   CGBuilderTy &Builder = CGF.Builder;
8376   Address VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
8377   llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
8378   // Handle address alignment for type alignment > 32 bits
8379   uint64_t TyAlign = CGF.getContext().getTypeAlign(Ty) / 8;
8380   if (TyAlign > 4) {
8381     assert((TyAlign & (TyAlign - 1)) == 0 && "Alignment is not power of 2!");
8382     llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int32Ty);
8383     AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt32(TyAlign - 1));
8384     AddrAsInt = Builder.CreateAnd(AddrAsInt, Builder.getInt32(~(TyAlign - 1)));
8385     Addr = Builder.CreateIntToPtr(AddrAsInt, BP);
8386   }
8387   llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
8388   Address AddrTyped = Builder.CreateBitCast(
8389       Address(Addr, CharUnits::fromQuantity(TyAlign)), PTy);
8390 
8391   uint64_t Offset = llvm::alignTo(CGF.getContext().getTypeSize(Ty) / 8, 4);
8392   llvm::Value *NextAddr = Builder.CreateGEP(
8393       Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset), "ap.next");
8394   Builder.CreateStore(NextAddr, VAListAddrAsBPP);
8395 
8396   return AddrTyped;
8397 }
8398 
8399 Address HexagonABIInfo::EmitVAArgForHexagonLinux(CodeGenFunction &CGF,
8400                                                  Address VAListAddr,
8401                                                  QualType Ty) const {
8402   int ArgSize = CGF.getContext().getTypeSize(Ty) / 8;
8403 
8404   if (ArgSize > 8)
8405     return EmitVAArgFromMemory(CGF, VAListAddr, Ty);
8406 
8407   // Here we have check if the argument is in register area or
8408   // in overflow area.
8409   // If the saved register area pointer + argsize rounded up to alignment >
8410   // saved register area end pointer, argument is in overflow area.
8411   unsigned RegsLeft = 6;
8412   Ty = CGF.getContext().getCanonicalType(Ty);
8413   (void)classifyArgumentType(Ty, &RegsLeft);
8414 
8415   llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
8416   llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
8417   llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
8418   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
8419 
8420   // Get rounded size of the argument.GCC does not allow vararg of
8421   // size < 4 bytes. We follow the same logic here.
8422   ArgSize = (CGF.getContext().getTypeSize(Ty) <= 32) ? 4 : 8;
8423   int ArgAlign = (CGF.getContext().getTypeSize(Ty) <= 32) ? 4 : 8;
8424 
8425   // Argument may be in saved register area
8426   CGF.EmitBlock(MaybeRegBlock);
8427 
8428   // Load the current saved register area pointer.
8429   Address __current_saved_reg_area_pointer_p = CGF.Builder.CreateStructGEP(
8430       VAListAddr, 0, "__current_saved_reg_area_pointer_p");
8431   llvm::Value *__current_saved_reg_area_pointer = CGF.Builder.CreateLoad(
8432       __current_saved_reg_area_pointer_p, "__current_saved_reg_area_pointer");
8433 
8434   // Load the saved register area end pointer.
8435   Address __saved_reg_area_end_pointer_p = CGF.Builder.CreateStructGEP(
8436       VAListAddr, 1, "__saved_reg_area_end_pointer_p");
8437   llvm::Value *__saved_reg_area_end_pointer = CGF.Builder.CreateLoad(
8438       __saved_reg_area_end_pointer_p, "__saved_reg_area_end_pointer");
8439 
8440   // If the size of argument is > 4 bytes, check if the stack
8441   // location is aligned to 8 bytes
8442   if (ArgAlign > 4) {
8443 
8444     llvm::Value *__current_saved_reg_area_pointer_int =
8445         CGF.Builder.CreatePtrToInt(__current_saved_reg_area_pointer,
8446                                    CGF.Int32Ty);
8447 
8448     __current_saved_reg_area_pointer_int = CGF.Builder.CreateAdd(
8449         __current_saved_reg_area_pointer_int,
8450         llvm::ConstantInt::get(CGF.Int32Ty, (ArgAlign - 1)),
8451         "align_current_saved_reg_area_pointer");
8452 
8453     __current_saved_reg_area_pointer_int =
8454         CGF.Builder.CreateAnd(__current_saved_reg_area_pointer_int,
8455                               llvm::ConstantInt::get(CGF.Int32Ty, -ArgAlign),
8456                               "align_current_saved_reg_area_pointer");
8457 
8458     __current_saved_reg_area_pointer =
8459         CGF.Builder.CreateIntToPtr(__current_saved_reg_area_pointer_int,
8460                                    __current_saved_reg_area_pointer->getType(),
8461                                    "align_current_saved_reg_area_pointer");
8462   }
8463 
8464   llvm::Value *__new_saved_reg_area_pointer =
8465       CGF.Builder.CreateGEP(__current_saved_reg_area_pointer,
8466                             llvm::ConstantInt::get(CGF.Int32Ty, ArgSize),
8467                             "__new_saved_reg_area_pointer");
8468 
8469   llvm::Value *UsingStack = 0;
8470   UsingStack = CGF.Builder.CreateICmpSGT(__new_saved_reg_area_pointer,
8471                                          __saved_reg_area_end_pointer);
8472 
8473   CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, InRegBlock);
8474 
8475   // Argument in saved register area
8476   // Implement the block where argument is in register saved area
8477   CGF.EmitBlock(InRegBlock);
8478 
8479   llvm::Type *PTy = CGF.ConvertType(Ty);
8480   llvm::Value *__saved_reg_area_p = CGF.Builder.CreateBitCast(
8481       __current_saved_reg_area_pointer, llvm::PointerType::getUnqual(PTy));
8482 
8483   CGF.Builder.CreateStore(__new_saved_reg_area_pointer,
8484                           __current_saved_reg_area_pointer_p);
8485 
8486   CGF.EmitBranch(ContBlock);
8487 
8488   // Argument in overflow area
8489   // Implement the block where the argument is in overflow area.
8490   CGF.EmitBlock(OnStackBlock);
8491 
8492   // Load the overflow area pointer
8493   Address __overflow_area_pointer_p =
8494       CGF.Builder.CreateStructGEP(VAListAddr, 2, "__overflow_area_pointer_p");
8495   llvm::Value *__overflow_area_pointer = CGF.Builder.CreateLoad(
8496       __overflow_area_pointer_p, "__overflow_area_pointer");
8497 
8498   // Align the overflow area pointer according to the alignment of the argument
8499   if (ArgAlign > 4) {
8500     llvm::Value *__overflow_area_pointer_int =
8501         CGF.Builder.CreatePtrToInt(__overflow_area_pointer, CGF.Int32Ty);
8502 
8503     __overflow_area_pointer_int =
8504         CGF.Builder.CreateAdd(__overflow_area_pointer_int,
8505                               llvm::ConstantInt::get(CGF.Int32Ty, ArgAlign - 1),
8506                               "align_overflow_area_pointer");
8507 
8508     __overflow_area_pointer_int =
8509         CGF.Builder.CreateAnd(__overflow_area_pointer_int,
8510                               llvm::ConstantInt::get(CGF.Int32Ty, -ArgAlign),
8511                               "align_overflow_area_pointer");
8512 
8513     __overflow_area_pointer = CGF.Builder.CreateIntToPtr(
8514         __overflow_area_pointer_int, __overflow_area_pointer->getType(),
8515         "align_overflow_area_pointer");
8516   }
8517 
8518   // Get the pointer for next argument in overflow area and store it
8519   // to overflow area pointer.
8520   llvm::Value *__new_overflow_area_pointer = CGF.Builder.CreateGEP(
8521       __overflow_area_pointer, llvm::ConstantInt::get(CGF.Int32Ty, ArgSize),
8522       "__overflow_area_pointer.next");
8523 
8524   CGF.Builder.CreateStore(__new_overflow_area_pointer,
8525                           __overflow_area_pointer_p);
8526 
8527   CGF.Builder.CreateStore(__new_overflow_area_pointer,
8528                           __current_saved_reg_area_pointer_p);
8529 
8530   // Bitcast the overflow area pointer to the type of argument.
8531   llvm::Type *OverflowPTy = CGF.ConvertTypeForMem(Ty);
8532   llvm::Value *__overflow_area_p = CGF.Builder.CreateBitCast(
8533       __overflow_area_pointer, llvm::PointerType::getUnqual(OverflowPTy));
8534 
8535   CGF.EmitBranch(ContBlock);
8536 
8537   // Get the correct pointer to load the variable argument
8538   // Implement the ContBlock
8539   CGF.EmitBlock(ContBlock);
8540 
8541   llvm::Type *MemPTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
8542   llvm::PHINode *ArgAddr = CGF.Builder.CreatePHI(MemPTy, 2, "vaarg.addr");
8543   ArgAddr->addIncoming(__saved_reg_area_p, InRegBlock);
8544   ArgAddr->addIncoming(__overflow_area_p, OnStackBlock);
8545 
8546   return Address(ArgAddr, CharUnits::fromQuantity(ArgAlign));
8547 }
8548 
8549 Address HexagonABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8550                                   QualType Ty) const {
8551 
8552   if (getTarget().getTriple().isMusl())
8553     return EmitVAArgForHexagonLinux(CGF, VAListAddr, Ty);
8554 
8555   return EmitVAArgForHexagon(CGF, VAListAddr, Ty);
8556 }
8557 
8558 //===----------------------------------------------------------------------===//
8559 // Lanai ABI Implementation
8560 //===----------------------------------------------------------------------===//
8561 
8562 namespace {
8563 class LanaiABIInfo : public DefaultABIInfo {
8564 public:
8565   LanaiABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
8566 
8567   bool shouldUseInReg(QualType Ty, CCState &State) const;
8568 
8569   void computeInfo(CGFunctionInfo &FI) const override {
8570     CCState State(FI);
8571     // Lanai uses 4 registers to pass arguments unless the function has the
8572     // regparm attribute set.
8573     if (FI.getHasRegParm()) {
8574       State.FreeRegs = FI.getRegParm();
8575     } else {
8576       State.FreeRegs = 4;
8577     }
8578 
8579     if (!getCXXABI().classifyReturnType(FI))
8580       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
8581     for (auto &I : FI.arguments())
8582       I.info = classifyArgumentType(I.type, State);
8583   }
8584 
8585   ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
8586   ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
8587 };
8588 } // end anonymous namespace
8589 
8590 bool LanaiABIInfo::shouldUseInReg(QualType Ty, CCState &State) const {
8591   unsigned Size = getContext().getTypeSize(Ty);
8592   unsigned SizeInRegs = llvm::alignTo(Size, 32U) / 32U;
8593 
8594   if (SizeInRegs == 0)
8595     return false;
8596 
8597   if (SizeInRegs > State.FreeRegs) {
8598     State.FreeRegs = 0;
8599     return false;
8600   }
8601 
8602   State.FreeRegs -= SizeInRegs;
8603 
8604   return true;
8605 }
8606 
8607 ABIArgInfo LanaiABIInfo::getIndirectResult(QualType Ty, bool ByVal,
8608                                            CCState &State) const {
8609   if (!ByVal) {
8610     if (State.FreeRegs) {
8611       --State.FreeRegs; // Non-byval indirects just use one pointer.
8612       return getNaturalAlignIndirectInReg(Ty);
8613     }
8614     return getNaturalAlignIndirect(Ty, false);
8615   }
8616 
8617   // Compute the byval alignment.
8618   const unsigned MinABIStackAlignInBytes = 4;
8619   unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
8620   return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true,
8621                                  /*Realign=*/TypeAlign >
8622                                      MinABIStackAlignInBytes);
8623 }
8624 
8625 ABIArgInfo LanaiABIInfo::classifyArgumentType(QualType Ty,
8626                                               CCState &State) const {
8627   // Check with the C++ ABI first.
8628   const RecordType *RT = Ty->getAs<RecordType>();
8629   if (RT) {
8630     CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
8631     if (RAA == CGCXXABI::RAA_Indirect) {
8632       return getIndirectResult(Ty, /*ByVal=*/false, State);
8633     } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
8634       return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
8635     }
8636   }
8637 
8638   if (isAggregateTypeForABI(Ty)) {
8639     // Structures with flexible arrays are always indirect.
8640     if (RT && RT->getDecl()->hasFlexibleArrayMember())
8641       return getIndirectResult(Ty, /*ByVal=*/true, State);
8642 
8643     // Ignore empty structs/unions.
8644     if (isEmptyRecord(getContext(), Ty, true))
8645       return ABIArgInfo::getIgnore();
8646 
8647     llvm::LLVMContext &LLVMContext = getVMContext();
8648     unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
8649     if (SizeInRegs <= State.FreeRegs) {
8650       llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
8651       SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32);
8652       llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
8653       State.FreeRegs -= SizeInRegs;
8654       return ABIArgInfo::getDirectInReg(Result);
8655     } else {
8656       State.FreeRegs = 0;
8657     }
8658     return getIndirectResult(Ty, true, State);
8659   }
8660 
8661   // Treat an enum type as its underlying type.
8662   if (const auto *EnumTy = Ty->getAs<EnumType>())
8663     Ty = EnumTy->getDecl()->getIntegerType();
8664 
8665   bool InReg = shouldUseInReg(Ty, State);
8666 
8667   // Don't pass >64 bit integers in registers.
8668   if (const auto *EIT = Ty->getAs<ExtIntType>())
8669     if (EIT->getNumBits() > 64)
8670       return getIndirectResult(Ty, /*ByVal=*/true, State);
8671 
8672   if (isPromotableIntegerTypeForABI(Ty)) {
8673     if (InReg)
8674       return ABIArgInfo::getDirectInReg();
8675     return ABIArgInfo::getExtend(Ty);
8676   }
8677   if (InReg)
8678     return ABIArgInfo::getDirectInReg();
8679   return ABIArgInfo::getDirect();
8680 }
8681 
8682 namespace {
8683 class LanaiTargetCodeGenInfo : public TargetCodeGenInfo {
8684 public:
8685   LanaiTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
8686       : TargetCodeGenInfo(std::make_unique<LanaiABIInfo>(CGT)) {}
8687 };
8688 }
8689 
8690 //===----------------------------------------------------------------------===//
8691 // AMDGPU ABI Implementation
8692 //===----------------------------------------------------------------------===//
8693 
8694 namespace {
8695 
8696 class AMDGPUABIInfo final : public DefaultABIInfo {
8697 private:
8698   static const unsigned MaxNumRegsForArgsRet = 16;
8699 
8700   unsigned numRegsForType(QualType Ty) const;
8701 
8702   bool isHomogeneousAggregateBaseType(QualType Ty) const override;
8703   bool isHomogeneousAggregateSmallEnough(const Type *Base,
8704                                          uint64_t Members) const override;
8705 
8706   // Coerce HIP pointer arguments from generic pointers to global ones.
8707   llvm::Type *coerceKernelArgumentType(llvm::Type *Ty, unsigned FromAS,
8708                                        unsigned ToAS) const {
8709     // Structure types.
8710     if (auto STy = dyn_cast<llvm::StructType>(Ty)) {
8711       SmallVector<llvm::Type *, 8> EltTys;
8712       bool Changed = false;
8713       for (auto T : STy->elements()) {
8714         auto NT = coerceKernelArgumentType(T, FromAS, ToAS);
8715         EltTys.push_back(NT);
8716         Changed |= (NT != T);
8717       }
8718       // Skip if there is no change in element types.
8719       if (!Changed)
8720         return STy;
8721       if (STy->hasName())
8722         return llvm::StructType::create(
8723             EltTys, (STy->getName() + ".coerce").str(), STy->isPacked());
8724       return llvm::StructType::get(getVMContext(), EltTys, STy->isPacked());
8725     }
8726     // Array types.
8727     if (auto ATy = dyn_cast<llvm::ArrayType>(Ty)) {
8728       auto T = ATy->getElementType();
8729       auto NT = coerceKernelArgumentType(T, FromAS, ToAS);
8730       // Skip if there is no change in that element type.
8731       if (NT == T)
8732         return ATy;
8733       return llvm::ArrayType::get(NT, ATy->getNumElements());
8734     }
8735     // Single value types.
8736     if (Ty->isPointerTy() && Ty->getPointerAddressSpace() == FromAS)
8737       return llvm::PointerType::get(
8738           cast<llvm::PointerType>(Ty)->getElementType(), ToAS);
8739     return Ty;
8740   }
8741 
8742 public:
8743   explicit AMDGPUABIInfo(CodeGen::CodeGenTypes &CGT) :
8744     DefaultABIInfo(CGT) {}
8745 
8746   ABIArgInfo classifyReturnType(QualType RetTy) const;
8747   ABIArgInfo classifyKernelArgumentType(QualType Ty) const;
8748   ABIArgInfo classifyArgumentType(QualType Ty, unsigned &NumRegsLeft) const;
8749 
8750   void computeInfo(CGFunctionInfo &FI) const override;
8751   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8752                     QualType Ty) const override;
8753 };
8754 
8755 bool AMDGPUABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
8756   return true;
8757 }
8758 
8759 bool AMDGPUABIInfo::isHomogeneousAggregateSmallEnough(
8760   const Type *Base, uint64_t Members) const {
8761   uint32_t NumRegs = (getContext().getTypeSize(Base) + 31) / 32;
8762 
8763   // Homogeneous Aggregates may occupy at most 16 registers.
8764   return Members * NumRegs <= MaxNumRegsForArgsRet;
8765 }
8766 
8767 /// Estimate number of registers the type will use when passed in registers.
8768 unsigned AMDGPUABIInfo::numRegsForType(QualType Ty) const {
8769   unsigned NumRegs = 0;
8770 
8771   if (const VectorType *VT = Ty->getAs<VectorType>()) {
8772     // Compute from the number of elements. The reported size is based on the
8773     // in-memory size, which includes the padding 4th element for 3-vectors.
8774     QualType EltTy = VT->getElementType();
8775     unsigned EltSize = getContext().getTypeSize(EltTy);
8776 
8777     // 16-bit element vectors should be passed as packed.
8778     if (EltSize == 16)
8779       return (VT->getNumElements() + 1) / 2;
8780 
8781     unsigned EltNumRegs = (EltSize + 31) / 32;
8782     return EltNumRegs * VT->getNumElements();
8783   }
8784 
8785   if (const RecordType *RT = Ty->getAs<RecordType>()) {
8786     const RecordDecl *RD = RT->getDecl();
8787     assert(!RD->hasFlexibleArrayMember());
8788 
8789     for (const FieldDecl *Field : RD->fields()) {
8790       QualType FieldTy = Field->getType();
8791       NumRegs += numRegsForType(FieldTy);
8792     }
8793 
8794     return NumRegs;
8795   }
8796 
8797   return (getContext().getTypeSize(Ty) + 31) / 32;
8798 }
8799 
8800 void AMDGPUABIInfo::computeInfo(CGFunctionInfo &FI) const {
8801   llvm::CallingConv::ID CC = FI.getCallingConvention();
8802 
8803   if (!getCXXABI().classifyReturnType(FI))
8804     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
8805 
8806   unsigned NumRegsLeft = MaxNumRegsForArgsRet;
8807   for (auto &Arg : FI.arguments()) {
8808     if (CC == llvm::CallingConv::AMDGPU_KERNEL) {
8809       Arg.info = classifyKernelArgumentType(Arg.type);
8810     } else {
8811       Arg.info = classifyArgumentType(Arg.type, NumRegsLeft);
8812     }
8813   }
8814 }
8815 
8816 Address AMDGPUABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8817                                  QualType Ty) const {
8818   llvm_unreachable("AMDGPU does not support varargs");
8819 }
8820 
8821 ABIArgInfo AMDGPUABIInfo::classifyReturnType(QualType RetTy) const {
8822   if (isAggregateTypeForABI(RetTy)) {
8823     // Records with non-trivial destructors/copy-constructors should not be
8824     // returned by value.
8825     if (!getRecordArgABI(RetTy, getCXXABI())) {
8826       // Ignore empty structs/unions.
8827       if (isEmptyRecord(getContext(), RetTy, true))
8828         return ABIArgInfo::getIgnore();
8829 
8830       // Lower single-element structs to just return a regular value.
8831       if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
8832         return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
8833 
8834       if (const RecordType *RT = RetTy->getAs<RecordType>()) {
8835         const RecordDecl *RD = RT->getDecl();
8836         if (RD->hasFlexibleArrayMember())
8837           return DefaultABIInfo::classifyReturnType(RetTy);
8838       }
8839 
8840       // Pack aggregates <= 4 bytes into single VGPR or pair.
8841       uint64_t Size = getContext().getTypeSize(RetTy);
8842       if (Size <= 16)
8843         return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
8844 
8845       if (Size <= 32)
8846         return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
8847 
8848       if (Size <= 64) {
8849         llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext());
8850         return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2));
8851       }
8852 
8853       if (numRegsForType(RetTy) <= MaxNumRegsForArgsRet)
8854         return ABIArgInfo::getDirect();
8855     }
8856   }
8857 
8858   // Otherwise just do the default thing.
8859   return DefaultABIInfo::classifyReturnType(RetTy);
8860 }
8861 
8862 /// For kernels all parameters are really passed in a special buffer. It doesn't
8863 /// make sense to pass anything byval, so everything must be direct.
8864 ABIArgInfo AMDGPUABIInfo::classifyKernelArgumentType(QualType Ty) const {
8865   Ty = useFirstFieldIfTransparentUnion(Ty);
8866 
8867   // TODO: Can we omit empty structs?
8868 
8869   if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
8870     Ty = QualType(SeltTy, 0);
8871 
8872   llvm::Type *OrigLTy = CGT.ConvertType(Ty);
8873   llvm::Type *LTy = OrigLTy;
8874   if (getContext().getLangOpts().HIP) {
8875     LTy = coerceKernelArgumentType(
8876         OrigLTy, /*FromAS=*/getContext().getTargetAddressSpace(LangAS::Default),
8877         /*ToAS=*/getContext().getTargetAddressSpace(LangAS::cuda_device));
8878   }
8879 
8880   // FIXME: Should also use this for OpenCL, but it requires addressing the
8881   // problem of kernels being called.
8882   //
8883   // FIXME: This doesn't apply the optimization of coercing pointers in structs
8884   // to global address space when using byref. This would require implementing a
8885   // new kind of coercion of the in-memory type when for indirect arguments.
8886   if (!getContext().getLangOpts().OpenCL && LTy == OrigLTy &&
8887       isAggregateTypeForABI(Ty)) {
8888     return ABIArgInfo::getIndirectAliased(
8889         getContext().getTypeAlignInChars(Ty),
8890         getContext().getTargetAddressSpace(LangAS::opencl_constant),
8891         false /*Realign*/, nullptr /*Padding*/);
8892   }
8893 
8894   // If we set CanBeFlattened to true, CodeGen will expand the struct to its
8895   // individual elements, which confuses the Clover OpenCL backend; therefore we
8896   // have to set it to false here. Other args of getDirect() are just defaults.
8897   return ABIArgInfo::getDirect(LTy, 0, nullptr, false);
8898 }
8899 
8900 ABIArgInfo AMDGPUABIInfo::classifyArgumentType(QualType Ty,
8901                                                unsigned &NumRegsLeft) const {
8902   assert(NumRegsLeft <= MaxNumRegsForArgsRet && "register estimate underflow");
8903 
8904   Ty = useFirstFieldIfTransparentUnion(Ty);
8905 
8906   if (isAggregateTypeForABI(Ty)) {
8907     // Records with non-trivial destructors/copy-constructors should not be
8908     // passed by value.
8909     if (auto RAA = getRecordArgABI(Ty, getCXXABI()))
8910       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
8911 
8912     // Ignore empty structs/unions.
8913     if (isEmptyRecord(getContext(), Ty, true))
8914       return ABIArgInfo::getIgnore();
8915 
8916     // Lower single-element structs to just pass a regular value. TODO: We
8917     // could do reasonable-size multiple-element structs too, using getExpand(),
8918     // though watch out for things like bitfields.
8919     if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
8920       return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
8921 
8922     if (const RecordType *RT = Ty->getAs<RecordType>()) {
8923       const RecordDecl *RD = RT->getDecl();
8924       if (RD->hasFlexibleArrayMember())
8925         return DefaultABIInfo::classifyArgumentType(Ty);
8926     }
8927 
8928     // Pack aggregates <= 8 bytes into single VGPR or pair.
8929     uint64_t Size = getContext().getTypeSize(Ty);
8930     if (Size <= 64) {
8931       unsigned NumRegs = (Size + 31) / 32;
8932       NumRegsLeft -= std::min(NumRegsLeft, NumRegs);
8933 
8934       if (Size <= 16)
8935         return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
8936 
8937       if (Size <= 32)
8938         return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
8939 
8940       // XXX: Should this be i64 instead, and should the limit increase?
8941       llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext());
8942       return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2));
8943     }
8944 
8945     if (NumRegsLeft > 0) {
8946       unsigned NumRegs = numRegsForType(Ty);
8947       if (NumRegsLeft >= NumRegs) {
8948         NumRegsLeft -= NumRegs;
8949         return ABIArgInfo::getDirect();
8950       }
8951     }
8952   }
8953 
8954   // Otherwise just do the default thing.
8955   ABIArgInfo ArgInfo = DefaultABIInfo::classifyArgumentType(Ty);
8956   if (!ArgInfo.isIndirect()) {
8957     unsigned NumRegs = numRegsForType(Ty);
8958     NumRegsLeft -= std::min(NumRegs, NumRegsLeft);
8959   }
8960 
8961   return ArgInfo;
8962 }
8963 
8964 class AMDGPUTargetCodeGenInfo : public TargetCodeGenInfo {
8965 public:
8966   AMDGPUTargetCodeGenInfo(CodeGenTypes &CGT)
8967       : TargetCodeGenInfo(std::make_unique<AMDGPUABIInfo>(CGT)) {}
8968   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
8969                            CodeGen::CodeGenModule &M) const override;
8970   unsigned getOpenCLKernelCallingConv() const override;
8971 
8972   llvm::Constant *getNullPointer(const CodeGen::CodeGenModule &CGM,
8973       llvm::PointerType *T, QualType QT) const override;
8974 
8975   LangAS getASTAllocaAddressSpace() const override {
8976     return getLangASFromTargetAS(
8977         getABIInfo().getDataLayout().getAllocaAddrSpace());
8978   }
8979   LangAS getGlobalVarAddressSpace(CodeGenModule &CGM,
8980                                   const VarDecl *D) const override;
8981   llvm::SyncScope::ID getLLVMSyncScopeID(const LangOptions &LangOpts,
8982                                          SyncScope Scope,
8983                                          llvm::AtomicOrdering Ordering,
8984                                          llvm::LLVMContext &Ctx) const override;
8985   llvm::Function *
8986   createEnqueuedBlockKernel(CodeGenFunction &CGF,
8987                             llvm::Function *BlockInvokeFunc,
8988                             llvm::Value *BlockLiteral) const override;
8989   bool shouldEmitStaticExternCAliases() const override;
8990   void setCUDAKernelCallingConvention(const FunctionType *&FT) const override;
8991 };
8992 }
8993 
8994 static bool requiresAMDGPUProtectedVisibility(const Decl *D,
8995                                               llvm::GlobalValue *GV) {
8996   if (GV->getVisibility() != llvm::GlobalValue::HiddenVisibility)
8997     return false;
8998 
8999   return D->hasAttr<OpenCLKernelAttr>() ||
9000          (isa<FunctionDecl>(D) && D->hasAttr<CUDAGlobalAttr>()) ||
9001          (isa<VarDecl>(D) &&
9002           (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>() ||
9003            cast<VarDecl>(D)->getType()->isCUDADeviceBuiltinSurfaceType() ||
9004            cast<VarDecl>(D)->getType()->isCUDADeviceBuiltinTextureType()));
9005 }
9006 
9007 void AMDGPUTargetCodeGenInfo::setTargetAttributes(
9008     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
9009   if (requiresAMDGPUProtectedVisibility(D, GV)) {
9010     GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
9011     GV->setDSOLocal(true);
9012   }
9013 
9014   if (GV->isDeclaration())
9015     return;
9016   const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
9017   if (!FD)
9018     return;
9019 
9020   llvm::Function *F = cast<llvm::Function>(GV);
9021 
9022   const auto *ReqdWGS = M.getLangOpts().OpenCL ?
9023     FD->getAttr<ReqdWorkGroupSizeAttr>() : nullptr;
9024 
9025 
9026   const bool IsOpenCLKernel = M.getLangOpts().OpenCL &&
9027                               FD->hasAttr<OpenCLKernelAttr>();
9028   const bool IsHIPKernel = M.getLangOpts().HIP &&
9029                            FD->hasAttr<CUDAGlobalAttr>();
9030   if ((IsOpenCLKernel || IsHIPKernel) &&
9031       (M.getTriple().getOS() == llvm::Triple::AMDHSA))
9032     F->addFnAttr("amdgpu-implicitarg-num-bytes", "56");
9033 
9034   if (IsHIPKernel)
9035     F->addFnAttr("uniform-work-group-size", "true");
9036 
9037 
9038   const auto *FlatWGS = FD->getAttr<AMDGPUFlatWorkGroupSizeAttr>();
9039   if (ReqdWGS || FlatWGS) {
9040     unsigned Min = 0;
9041     unsigned Max = 0;
9042     if (FlatWGS) {
9043       Min = FlatWGS->getMin()
9044                 ->EvaluateKnownConstInt(M.getContext())
9045                 .getExtValue();
9046       Max = FlatWGS->getMax()
9047                 ->EvaluateKnownConstInt(M.getContext())
9048                 .getExtValue();
9049     }
9050     if (ReqdWGS && Min == 0 && Max == 0)
9051       Min = Max = ReqdWGS->getXDim() * ReqdWGS->getYDim() * ReqdWGS->getZDim();
9052 
9053     if (Min != 0) {
9054       assert(Min <= Max && "Min must be less than or equal Max");
9055 
9056       std::string AttrVal = llvm::utostr(Min) + "," + llvm::utostr(Max);
9057       F->addFnAttr("amdgpu-flat-work-group-size", AttrVal);
9058     } else
9059       assert(Max == 0 && "Max must be zero");
9060   } else if (IsOpenCLKernel || IsHIPKernel) {
9061     // By default, restrict the maximum size to a value specified by
9062     // --gpu-max-threads-per-block=n or its default value.
9063     std::string AttrVal =
9064         std::string("1,") + llvm::utostr(M.getLangOpts().GPUMaxThreadsPerBlock);
9065     F->addFnAttr("amdgpu-flat-work-group-size", AttrVal);
9066   }
9067 
9068   if (const auto *Attr = FD->getAttr<AMDGPUWavesPerEUAttr>()) {
9069     unsigned Min =
9070         Attr->getMin()->EvaluateKnownConstInt(M.getContext()).getExtValue();
9071     unsigned Max = Attr->getMax() ? Attr->getMax()
9072                                         ->EvaluateKnownConstInt(M.getContext())
9073                                         .getExtValue()
9074                                   : 0;
9075 
9076     if (Min != 0) {
9077       assert((Max == 0 || Min <= Max) && "Min must be less than or equal Max");
9078 
9079       std::string AttrVal = llvm::utostr(Min);
9080       if (Max != 0)
9081         AttrVal = AttrVal + "," + llvm::utostr(Max);
9082       F->addFnAttr("amdgpu-waves-per-eu", AttrVal);
9083     } else
9084       assert(Max == 0 && "Max must be zero");
9085   }
9086 
9087   if (const auto *Attr = FD->getAttr<AMDGPUNumSGPRAttr>()) {
9088     unsigned NumSGPR = Attr->getNumSGPR();
9089 
9090     if (NumSGPR != 0)
9091       F->addFnAttr("amdgpu-num-sgpr", llvm::utostr(NumSGPR));
9092   }
9093 
9094   if (const auto *Attr = FD->getAttr<AMDGPUNumVGPRAttr>()) {
9095     uint32_t NumVGPR = Attr->getNumVGPR();
9096 
9097     if (NumVGPR != 0)
9098       F->addFnAttr("amdgpu-num-vgpr", llvm::utostr(NumVGPR));
9099   }
9100 }
9101 
9102 unsigned AMDGPUTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
9103   return llvm::CallingConv::AMDGPU_KERNEL;
9104 }
9105 
9106 // Currently LLVM assumes null pointers always have value 0,
9107 // which results in incorrectly transformed IR. Therefore, instead of
9108 // emitting null pointers in private and local address spaces, a null
9109 // pointer in generic address space is emitted which is casted to a
9110 // pointer in local or private address space.
9111 llvm::Constant *AMDGPUTargetCodeGenInfo::getNullPointer(
9112     const CodeGen::CodeGenModule &CGM, llvm::PointerType *PT,
9113     QualType QT) const {
9114   if (CGM.getContext().getTargetNullPointerValue(QT) == 0)
9115     return llvm::ConstantPointerNull::get(PT);
9116 
9117   auto &Ctx = CGM.getContext();
9118   auto NPT = llvm::PointerType::get(PT->getElementType(),
9119       Ctx.getTargetAddressSpace(LangAS::opencl_generic));
9120   return llvm::ConstantExpr::getAddrSpaceCast(
9121       llvm::ConstantPointerNull::get(NPT), PT);
9122 }
9123 
9124 LangAS
9125 AMDGPUTargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM,
9126                                                   const VarDecl *D) const {
9127   assert(!CGM.getLangOpts().OpenCL &&
9128          !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) &&
9129          "Address space agnostic languages only");
9130   LangAS DefaultGlobalAS = getLangASFromTargetAS(
9131       CGM.getContext().getTargetAddressSpace(LangAS::opencl_global));
9132   if (!D)
9133     return DefaultGlobalAS;
9134 
9135   LangAS AddrSpace = D->getType().getAddressSpace();
9136   assert(AddrSpace == LangAS::Default || isTargetAddressSpace(AddrSpace));
9137   if (AddrSpace != LangAS::Default)
9138     return AddrSpace;
9139 
9140   if (CGM.isTypeConstant(D->getType(), false)) {
9141     if (auto ConstAS = CGM.getTarget().getConstantAddressSpace())
9142       return ConstAS.getValue();
9143   }
9144   return DefaultGlobalAS;
9145 }
9146 
9147 llvm::SyncScope::ID
9148 AMDGPUTargetCodeGenInfo::getLLVMSyncScopeID(const LangOptions &LangOpts,
9149                                             SyncScope Scope,
9150                                             llvm::AtomicOrdering Ordering,
9151                                             llvm::LLVMContext &Ctx) const {
9152   std::string Name;
9153   switch (Scope) {
9154   case SyncScope::OpenCLWorkGroup:
9155     Name = "workgroup";
9156     break;
9157   case SyncScope::OpenCLDevice:
9158     Name = "agent";
9159     break;
9160   case SyncScope::OpenCLAllSVMDevices:
9161     Name = "";
9162     break;
9163   case SyncScope::OpenCLSubGroup:
9164     Name = "wavefront";
9165   }
9166 
9167   if (Ordering != llvm::AtomicOrdering::SequentiallyConsistent) {
9168     if (!Name.empty())
9169       Name = Twine(Twine(Name) + Twine("-")).str();
9170 
9171     Name = Twine(Twine(Name) + Twine("one-as")).str();
9172   }
9173 
9174   return Ctx.getOrInsertSyncScopeID(Name);
9175 }
9176 
9177 bool AMDGPUTargetCodeGenInfo::shouldEmitStaticExternCAliases() const {
9178   return false;
9179 }
9180 
9181 void AMDGPUTargetCodeGenInfo::setCUDAKernelCallingConvention(
9182     const FunctionType *&FT) const {
9183   FT = getABIInfo().getContext().adjustFunctionType(
9184       FT, FT->getExtInfo().withCallingConv(CC_OpenCLKernel));
9185 }
9186 
9187 //===----------------------------------------------------------------------===//
9188 // SPARC v8 ABI Implementation.
9189 // Based on the SPARC Compliance Definition version 2.4.1.
9190 //
9191 // Ensures that complex values are passed in registers.
9192 //
9193 namespace {
9194 class SparcV8ABIInfo : public DefaultABIInfo {
9195 public:
9196   SparcV8ABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
9197 
9198 private:
9199   ABIArgInfo classifyReturnType(QualType RetTy) const;
9200   void computeInfo(CGFunctionInfo &FI) const override;
9201 };
9202 } // end anonymous namespace
9203 
9204 
9205 ABIArgInfo
9206 SparcV8ABIInfo::classifyReturnType(QualType Ty) const {
9207   if (Ty->isAnyComplexType()) {
9208     return ABIArgInfo::getDirect();
9209   }
9210   else {
9211     return DefaultABIInfo::classifyReturnType(Ty);
9212   }
9213 }
9214 
9215 void SparcV8ABIInfo::computeInfo(CGFunctionInfo &FI) const {
9216 
9217   FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
9218   for (auto &Arg : FI.arguments())
9219     Arg.info = classifyArgumentType(Arg.type);
9220 }
9221 
9222 namespace {
9223 class SparcV8TargetCodeGenInfo : public TargetCodeGenInfo {
9224 public:
9225   SparcV8TargetCodeGenInfo(CodeGenTypes &CGT)
9226       : TargetCodeGenInfo(std::make_unique<SparcV8ABIInfo>(CGT)) {}
9227 };
9228 } // end anonymous namespace
9229 
9230 //===----------------------------------------------------------------------===//
9231 // SPARC v9 ABI Implementation.
9232 // Based on the SPARC Compliance Definition version 2.4.1.
9233 //
9234 // Function arguments a mapped to a nominal "parameter array" and promoted to
9235 // registers depending on their type. Each argument occupies 8 or 16 bytes in
9236 // the array, structs larger than 16 bytes are passed indirectly.
9237 //
9238 // One case requires special care:
9239 //
9240 //   struct mixed {
9241 //     int i;
9242 //     float f;
9243 //   };
9244 //
9245 // When a struct mixed is passed by value, it only occupies 8 bytes in the
9246 // parameter array, but the int is passed in an integer register, and the float
9247 // is passed in a floating point register. This is represented as two arguments
9248 // with the LLVM IR inreg attribute:
9249 //
9250 //   declare void f(i32 inreg %i, float inreg %f)
9251 //
9252 // The code generator will only allocate 4 bytes from the parameter array for
9253 // the inreg arguments. All other arguments are allocated a multiple of 8
9254 // bytes.
9255 //
9256 namespace {
9257 class SparcV9ABIInfo : public ABIInfo {
9258 public:
9259   SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
9260 
9261 private:
9262   ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
9263   void computeInfo(CGFunctionInfo &FI) const override;
9264   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9265                     QualType Ty) const override;
9266 
9267   // Coercion type builder for structs passed in registers. The coercion type
9268   // serves two purposes:
9269   //
9270   // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
9271   //    in registers.
9272   // 2. Expose aligned floating point elements as first-level elements, so the
9273   //    code generator knows to pass them in floating point registers.
9274   //
9275   // We also compute the InReg flag which indicates that the struct contains
9276   // aligned 32-bit floats.
9277   //
9278   struct CoerceBuilder {
9279     llvm::LLVMContext &Context;
9280     const llvm::DataLayout &DL;
9281     SmallVector<llvm::Type*, 8> Elems;
9282     uint64_t Size;
9283     bool InReg;
9284 
9285     CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
9286       : Context(c), DL(dl), Size(0), InReg(false) {}
9287 
9288     // Pad Elems with integers until Size is ToSize.
9289     void pad(uint64_t ToSize) {
9290       assert(ToSize >= Size && "Cannot remove elements");
9291       if (ToSize == Size)
9292         return;
9293 
9294       // Finish the current 64-bit word.
9295       uint64_t Aligned = llvm::alignTo(Size, 64);
9296       if (Aligned > Size && Aligned <= ToSize) {
9297         Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
9298         Size = Aligned;
9299       }
9300 
9301       // Add whole 64-bit words.
9302       while (Size + 64 <= ToSize) {
9303         Elems.push_back(llvm::Type::getInt64Ty(Context));
9304         Size += 64;
9305       }
9306 
9307       // Final in-word padding.
9308       if (Size < ToSize) {
9309         Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
9310         Size = ToSize;
9311       }
9312     }
9313 
9314     // Add a floating point element at Offset.
9315     void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
9316       // Unaligned floats are treated as integers.
9317       if (Offset % Bits)
9318         return;
9319       // The InReg flag is only required if there are any floats < 64 bits.
9320       if (Bits < 64)
9321         InReg = true;
9322       pad(Offset);
9323       Elems.push_back(Ty);
9324       Size = Offset + Bits;
9325     }
9326 
9327     // Add a struct type to the coercion type, starting at Offset (in bits).
9328     void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
9329       const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
9330       for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
9331         llvm::Type *ElemTy = StrTy->getElementType(i);
9332         uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
9333         switch (ElemTy->getTypeID()) {
9334         case llvm::Type::StructTyID:
9335           addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
9336           break;
9337         case llvm::Type::FloatTyID:
9338           addFloat(ElemOffset, ElemTy, 32);
9339           break;
9340         case llvm::Type::DoubleTyID:
9341           addFloat(ElemOffset, ElemTy, 64);
9342           break;
9343         case llvm::Type::FP128TyID:
9344           addFloat(ElemOffset, ElemTy, 128);
9345           break;
9346         case llvm::Type::PointerTyID:
9347           if (ElemOffset % 64 == 0) {
9348             pad(ElemOffset);
9349             Elems.push_back(ElemTy);
9350             Size += 64;
9351           }
9352           break;
9353         default:
9354           break;
9355         }
9356       }
9357     }
9358 
9359     // Check if Ty is a usable substitute for the coercion type.
9360     bool isUsableType(llvm::StructType *Ty) const {
9361       return llvm::makeArrayRef(Elems) == Ty->elements();
9362     }
9363 
9364     // Get the coercion type as a literal struct type.
9365     llvm::Type *getType() const {
9366       if (Elems.size() == 1)
9367         return Elems.front();
9368       else
9369         return llvm::StructType::get(Context, Elems);
9370     }
9371   };
9372 };
9373 } // end anonymous namespace
9374 
9375 ABIArgInfo
9376 SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
9377   if (Ty->isVoidType())
9378     return ABIArgInfo::getIgnore();
9379 
9380   uint64_t Size = getContext().getTypeSize(Ty);
9381 
9382   // Anything too big to fit in registers is passed with an explicit indirect
9383   // pointer / sret pointer.
9384   if (Size > SizeLimit)
9385     return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
9386 
9387   // Treat an enum type as its underlying type.
9388   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
9389     Ty = EnumTy->getDecl()->getIntegerType();
9390 
9391   // Integer types smaller than a register are extended.
9392   if (Size < 64 && Ty->isIntegerType())
9393     return ABIArgInfo::getExtend(Ty);
9394 
9395   if (const auto *EIT = Ty->getAs<ExtIntType>())
9396     if (EIT->getNumBits() < 64)
9397       return ABIArgInfo::getExtend(Ty);
9398 
9399   // Other non-aggregates go in registers.
9400   if (!isAggregateTypeForABI(Ty))
9401     return ABIArgInfo::getDirect();
9402 
9403   // If a C++ object has either a non-trivial copy constructor or a non-trivial
9404   // destructor, it is passed with an explicit indirect pointer / sret pointer.
9405   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
9406     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
9407 
9408   // This is a small aggregate type that should be passed in registers.
9409   // Build a coercion type from the LLVM struct type.
9410   llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
9411   if (!StrTy)
9412     return ABIArgInfo::getDirect();
9413 
9414   CoerceBuilder CB(getVMContext(), getDataLayout());
9415   CB.addStruct(0, StrTy);
9416   CB.pad(llvm::alignTo(CB.DL.getTypeSizeInBits(StrTy), 64));
9417 
9418   // Try to use the original type for coercion.
9419   llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
9420 
9421   if (CB.InReg)
9422     return ABIArgInfo::getDirectInReg(CoerceTy);
9423   else
9424     return ABIArgInfo::getDirect(CoerceTy);
9425 }
9426 
9427 Address SparcV9ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9428                                   QualType Ty) const {
9429   ABIArgInfo AI = classifyType(Ty, 16 * 8);
9430   llvm::Type *ArgTy = CGT.ConvertType(Ty);
9431   if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
9432     AI.setCoerceToType(ArgTy);
9433 
9434   CharUnits SlotSize = CharUnits::fromQuantity(8);
9435 
9436   CGBuilderTy &Builder = CGF.Builder;
9437   Address Addr(Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
9438   llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
9439 
9440   auto TypeInfo = getContext().getTypeInfoInChars(Ty);
9441 
9442   Address ArgAddr = Address::invalid();
9443   CharUnits Stride;
9444   switch (AI.getKind()) {
9445   case ABIArgInfo::Expand:
9446   case ABIArgInfo::CoerceAndExpand:
9447   case ABIArgInfo::InAlloca:
9448     llvm_unreachable("Unsupported ABI kind for va_arg");
9449 
9450   case ABIArgInfo::Extend: {
9451     Stride = SlotSize;
9452     CharUnits Offset = SlotSize - TypeInfo.Width;
9453     ArgAddr = Builder.CreateConstInBoundsByteGEP(Addr, Offset, "extend");
9454     break;
9455   }
9456 
9457   case ABIArgInfo::Direct: {
9458     auto AllocSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
9459     Stride = CharUnits::fromQuantity(AllocSize).alignTo(SlotSize);
9460     ArgAddr = Addr;
9461     break;
9462   }
9463 
9464   case ABIArgInfo::Indirect:
9465   case ABIArgInfo::IndirectAliased:
9466     Stride = SlotSize;
9467     ArgAddr = Builder.CreateElementBitCast(Addr, ArgPtrTy, "indirect");
9468     ArgAddr = Address(Builder.CreateLoad(ArgAddr, "indirect.arg"),
9469                       TypeInfo.Align);
9470     break;
9471 
9472   case ABIArgInfo::Ignore:
9473     return Address(llvm::UndefValue::get(ArgPtrTy), TypeInfo.Align);
9474   }
9475 
9476   // Update VAList.
9477   Address NextPtr = Builder.CreateConstInBoundsByteGEP(Addr, Stride, "ap.next");
9478   Builder.CreateStore(NextPtr.getPointer(), VAListAddr);
9479 
9480   return Builder.CreateBitCast(ArgAddr, ArgPtrTy, "arg.addr");
9481 }
9482 
9483 void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
9484   FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
9485   for (auto &I : FI.arguments())
9486     I.info = classifyType(I.type, 16 * 8);
9487 }
9488 
9489 namespace {
9490 class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
9491 public:
9492   SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
9493       : TargetCodeGenInfo(std::make_unique<SparcV9ABIInfo>(CGT)) {}
9494 
9495   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
9496     return 14;
9497   }
9498 
9499   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
9500                                llvm::Value *Address) const override;
9501 };
9502 } // end anonymous namespace
9503 
9504 bool
9505 SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
9506                                                 llvm::Value *Address) const {
9507   // This is calculated from the LLVM and GCC tables and verified
9508   // against gcc output.  AFAIK all ABIs use the same encoding.
9509 
9510   CodeGen::CGBuilderTy &Builder = CGF.Builder;
9511 
9512   llvm::IntegerType *i8 = CGF.Int8Ty;
9513   llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
9514   llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
9515 
9516   // 0-31: the 8-byte general-purpose registers
9517   AssignToArrayRange(Builder, Address, Eight8, 0, 31);
9518 
9519   // 32-63: f0-31, the 4-byte floating-point registers
9520   AssignToArrayRange(Builder, Address, Four8, 32, 63);
9521 
9522   //   Y   = 64
9523   //   PSR = 65
9524   //   WIM = 66
9525   //   TBR = 67
9526   //   PC  = 68
9527   //   NPC = 69
9528   //   FSR = 70
9529   //   CSR = 71
9530   AssignToArrayRange(Builder, Address, Eight8, 64, 71);
9531 
9532   // 72-87: d0-15, the 8-byte floating-point registers
9533   AssignToArrayRange(Builder, Address, Eight8, 72, 87);
9534 
9535   return false;
9536 }
9537 
9538 // ARC ABI implementation.
9539 namespace {
9540 
9541 class ARCABIInfo : public DefaultABIInfo {
9542 public:
9543   using DefaultABIInfo::DefaultABIInfo;
9544 
9545 private:
9546   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9547                     QualType Ty) const override;
9548 
9549   void updateState(const ABIArgInfo &Info, QualType Ty, CCState &State) const {
9550     if (!State.FreeRegs)
9551       return;
9552     if (Info.isIndirect() && Info.getInReg())
9553       State.FreeRegs--;
9554     else if (Info.isDirect() && Info.getInReg()) {
9555       unsigned sz = (getContext().getTypeSize(Ty) + 31) / 32;
9556       if (sz < State.FreeRegs)
9557         State.FreeRegs -= sz;
9558       else
9559         State.FreeRegs = 0;
9560     }
9561   }
9562 
9563   void computeInfo(CGFunctionInfo &FI) const override {
9564     CCState State(FI);
9565     // ARC uses 8 registers to pass arguments.
9566     State.FreeRegs = 8;
9567 
9568     if (!getCXXABI().classifyReturnType(FI))
9569       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
9570     updateState(FI.getReturnInfo(), FI.getReturnType(), State);
9571     for (auto &I : FI.arguments()) {
9572       I.info = classifyArgumentType(I.type, State.FreeRegs);
9573       updateState(I.info, I.type, State);
9574     }
9575   }
9576 
9577   ABIArgInfo getIndirectByRef(QualType Ty, bool HasFreeRegs) const;
9578   ABIArgInfo getIndirectByValue(QualType Ty) const;
9579   ABIArgInfo classifyArgumentType(QualType Ty, uint8_t FreeRegs) const;
9580   ABIArgInfo classifyReturnType(QualType RetTy) const;
9581 };
9582 
9583 class ARCTargetCodeGenInfo : public TargetCodeGenInfo {
9584 public:
9585   ARCTargetCodeGenInfo(CodeGenTypes &CGT)
9586       : TargetCodeGenInfo(std::make_unique<ARCABIInfo>(CGT)) {}
9587 };
9588 
9589 
9590 ABIArgInfo ARCABIInfo::getIndirectByRef(QualType Ty, bool HasFreeRegs) const {
9591   return HasFreeRegs ? getNaturalAlignIndirectInReg(Ty) :
9592                        getNaturalAlignIndirect(Ty, false);
9593 }
9594 
9595 ABIArgInfo ARCABIInfo::getIndirectByValue(QualType Ty) const {
9596   // Compute the byval alignment.
9597   const unsigned MinABIStackAlignInBytes = 4;
9598   unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
9599   return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true,
9600                                  TypeAlign > MinABIStackAlignInBytes);
9601 }
9602 
9603 Address ARCABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9604                               QualType Ty) const {
9605   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
9606                           getContext().getTypeInfoInChars(Ty),
9607                           CharUnits::fromQuantity(4), true);
9608 }
9609 
9610 ABIArgInfo ARCABIInfo::classifyArgumentType(QualType Ty,
9611                                             uint8_t FreeRegs) const {
9612   // Handle the generic C++ ABI.
9613   const RecordType *RT = Ty->getAs<RecordType>();
9614   if (RT) {
9615     CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
9616     if (RAA == CGCXXABI::RAA_Indirect)
9617       return getIndirectByRef(Ty, FreeRegs > 0);
9618 
9619     if (RAA == CGCXXABI::RAA_DirectInMemory)
9620       return getIndirectByValue(Ty);
9621   }
9622 
9623   // Treat an enum type as its underlying type.
9624   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
9625     Ty = EnumTy->getDecl()->getIntegerType();
9626 
9627   auto SizeInRegs = llvm::alignTo(getContext().getTypeSize(Ty), 32) / 32;
9628 
9629   if (isAggregateTypeForABI(Ty)) {
9630     // Structures with flexible arrays are always indirect.
9631     if (RT && RT->getDecl()->hasFlexibleArrayMember())
9632       return getIndirectByValue(Ty);
9633 
9634     // Ignore empty structs/unions.
9635     if (isEmptyRecord(getContext(), Ty, true))
9636       return ABIArgInfo::getIgnore();
9637 
9638     llvm::LLVMContext &LLVMContext = getVMContext();
9639 
9640     llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
9641     SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32);
9642     llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
9643 
9644     return FreeRegs >= SizeInRegs ?
9645         ABIArgInfo::getDirectInReg(Result) :
9646         ABIArgInfo::getDirect(Result, 0, nullptr, false);
9647   }
9648 
9649   if (const auto *EIT = Ty->getAs<ExtIntType>())
9650     if (EIT->getNumBits() > 64)
9651       return getIndirectByValue(Ty);
9652 
9653   return isPromotableIntegerTypeForABI(Ty)
9654              ? (FreeRegs >= SizeInRegs ? ABIArgInfo::getExtendInReg(Ty)
9655                                        : ABIArgInfo::getExtend(Ty))
9656              : (FreeRegs >= SizeInRegs ? ABIArgInfo::getDirectInReg()
9657                                        : ABIArgInfo::getDirect());
9658 }
9659 
9660 ABIArgInfo ARCABIInfo::classifyReturnType(QualType RetTy) const {
9661   if (RetTy->isAnyComplexType())
9662     return ABIArgInfo::getDirectInReg();
9663 
9664   // Arguments of size > 4 registers are indirect.
9665   auto RetSize = llvm::alignTo(getContext().getTypeSize(RetTy), 32) / 32;
9666   if (RetSize > 4)
9667     return getIndirectByRef(RetTy, /*HasFreeRegs*/ true);
9668 
9669   return DefaultABIInfo::classifyReturnType(RetTy);
9670 }
9671 
9672 } // End anonymous namespace.
9673 
9674 //===----------------------------------------------------------------------===//
9675 // XCore ABI Implementation
9676 //===----------------------------------------------------------------------===//
9677 
9678 namespace {
9679 
9680 /// A SmallStringEnc instance is used to build up the TypeString by passing
9681 /// it by reference between functions that append to it.
9682 typedef llvm::SmallString<128> SmallStringEnc;
9683 
9684 /// TypeStringCache caches the meta encodings of Types.
9685 ///
9686 /// The reason for caching TypeStrings is two fold:
9687 ///   1. To cache a type's encoding for later uses;
9688 ///   2. As a means to break recursive member type inclusion.
9689 ///
9690 /// A cache Entry can have a Status of:
9691 ///   NonRecursive:   The type encoding is not recursive;
9692 ///   Recursive:      The type encoding is recursive;
9693 ///   Incomplete:     An incomplete TypeString;
9694 ///   IncompleteUsed: An incomplete TypeString that has been used in a
9695 ///                   Recursive type encoding.
9696 ///
9697 /// A NonRecursive entry will have all of its sub-members expanded as fully
9698 /// as possible. Whilst it may contain types which are recursive, the type
9699 /// itself is not recursive and thus its encoding may be safely used whenever
9700 /// the type is encountered.
9701 ///
9702 /// A Recursive entry will have all of its sub-members expanded as fully as
9703 /// possible. The type itself is recursive and it may contain other types which
9704 /// are recursive. The Recursive encoding must not be used during the expansion
9705 /// of a recursive type's recursive branch. For simplicity the code uses
9706 /// IncompleteCount to reject all usage of Recursive encodings for member types.
9707 ///
9708 /// An Incomplete entry is always a RecordType and only encodes its
9709 /// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and
9710 /// are placed into the cache during type expansion as a means to identify and
9711 /// handle recursive inclusion of types as sub-members. If there is recursion
9712 /// the entry becomes IncompleteUsed.
9713 ///
9714 /// During the expansion of a RecordType's members:
9715 ///
9716 ///   If the cache contains a NonRecursive encoding for the member type, the
9717 ///   cached encoding is used;
9718 ///
9719 ///   If the cache contains a Recursive encoding for the member type, the
9720 ///   cached encoding is 'Swapped' out, as it may be incorrect, and...
9721 ///
9722 ///   If the member is a RecordType, an Incomplete encoding is placed into the
9723 ///   cache to break potential recursive inclusion of itself as a sub-member;
9724 ///
9725 ///   Once a member RecordType has been expanded, its temporary incomplete
9726 ///   entry is removed from the cache. If a Recursive encoding was swapped out
9727 ///   it is swapped back in;
9728 ///
9729 ///   If an incomplete entry is used to expand a sub-member, the incomplete
9730 ///   entry is marked as IncompleteUsed. The cache keeps count of how many
9731 ///   IncompleteUsed entries it currently contains in IncompleteUsedCount;
9732 ///
9733 ///   If a member's encoding is found to be a NonRecursive or Recursive viz:
9734 ///   IncompleteUsedCount==0, the member's encoding is added to the cache.
9735 ///   Else the member is part of a recursive type and thus the recursion has
9736 ///   been exited too soon for the encoding to be correct for the member.
9737 ///
9738 class TypeStringCache {
9739   enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed};
9740   struct Entry {
9741     std::string Str;     // The encoded TypeString for the type.
9742     enum Status State;   // Information about the encoding in 'Str'.
9743     std::string Swapped; // A temporary place holder for a Recursive encoding
9744                          // during the expansion of RecordType's members.
9745   };
9746   std::map<const IdentifierInfo *, struct Entry> Map;
9747   unsigned IncompleteCount;     // Number of Incomplete entries in the Map.
9748   unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map.
9749 public:
9750   TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {}
9751   void addIncomplete(const IdentifierInfo *ID, std::string StubEnc);
9752   bool removeIncomplete(const IdentifierInfo *ID);
9753   void addIfComplete(const IdentifierInfo *ID, StringRef Str,
9754                      bool IsRecursive);
9755   StringRef lookupStr(const IdentifierInfo *ID);
9756 };
9757 
9758 /// TypeString encodings for enum & union fields must be order.
9759 /// FieldEncoding is a helper for this ordering process.
9760 class FieldEncoding {
9761   bool HasName;
9762   std::string Enc;
9763 public:
9764   FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {}
9765   StringRef str() { return Enc; }
9766   bool operator<(const FieldEncoding &rhs) const {
9767     if (HasName != rhs.HasName) return HasName;
9768     return Enc < rhs.Enc;
9769   }
9770 };
9771 
9772 class XCoreABIInfo : public DefaultABIInfo {
9773 public:
9774   XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
9775   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9776                     QualType Ty) const override;
9777 };
9778 
9779 class XCoreTargetCodeGenInfo : public TargetCodeGenInfo {
9780   mutable TypeStringCache TSC;
9781   void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
9782                     const CodeGen::CodeGenModule &M) const;
9783 
9784 public:
9785   XCoreTargetCodeGenInfo(CodeGenTypes &CGT)
9786       : TargetCodeGenInfo(std::make_unique<XCoreABIInfo>(CGT)) {}
9787   void emitTargetMetadata(CodeGen::CodeGenModule &CGM,
9788                           const llvm::MapVector<GlobalDecl, StringRef>
9789                               &MangledDeclNames) const override;
9790 };
9791 
9792 } // End anonymous namespace.
9793 
9794 // TODO: this implementation is likely now redundant with the default
9795 // EmitVAArg.
9796 Address XCoreABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9797                                 QualType Ty) const {
9798   CGBuilderTy &Builder = CGF.Builder;
9799 
9800   // Get the VAList.
9801   CharUnits SlotSize = CharUnits::fromQuantity(4);
9802   Address AP(Builder.CreateLoad(VAListAddr), SlotSize);
9803 
9804   // Handle the argument.
9805   ABIArgInfo AI = classifyArgumentType(Ty);
9806   CharUnits TypeAlign = getContext().getTypeAlignInChars(Ty);
9807   llvm::Type *ArgTy = CGT.ConvertType(Ty);
9808   if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
9809     AI.setCoerceToType(ArgTy);
9810   llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
9811 
9812   Address Val = Address::invalid();
9813   CharUnits ArgSize = CharUnits::Zero();
9814   switch (AI.getKind()) {
9815   case ABIArgInfo::Expand:
9816   case ABIArgInfo::CoerceAndExpand:
9817   case ABIArgInfo::InAlloca:
9818     llvm_unreachable("Unsupported ABI kind for va_arg");
9819   case ABIArgInfo::Ignore:
9820     Val = Address(llvm::UndefValue::get(ArgPtrTy), TypeAlign);
9821     ArgSize = CharUnits::Zero();
9822     break;
9823   case ABIArgInfo::Extend:
9824   case ABIArgInfo::Direct:
9825     Val = Builder.CreateBitCast(AP, ArgPtrTy);
9826     ArgSize = CharUnits::fromQuantity(
9827                        getDataLayout().getTypeAllocSize(AI.getCoerceToType()));
9828     ArgSize = ArgSize.alignTo(SlotSize);
9829     break;
9830   case ABIArgInfo::Indirect:
9831   case ABIArgInfo::IndirectAliased:
9832     Val = Builder.CreateElementBitCast(AP, ArgPtrTy);
9833     Val = Address(Builder.CreateLoad(Val), TypeAlign);
9834     ArgSize = SlotSize;
9835     break;
9836   }
9837 
9838   // Increment the VAList.
9839   if (!ArgSize.isZero()) {
9840     Address APN = Builder.CreateConstInBoundsByteGEP(AP, ArgSize);
9841     Builder.CreateStore(APN.getPointer(), VAListAddr);
9842   }
9843 
9844   return Val;
9845 }
9846 
9847 /// During the expansion of a RecordType, an incomplete TypeString is placed
9848 /// into the cache as a means to identify and break recursion.
9849 /// If there is a Recursive encoding in the cache, it is swapped out and will
9850 /// be reinserted by removeIncomplete().
9851 /// All other types of encoding should have been used rather than arriving here.
9852 void TypeStringCache::addIncomplete(const IdentifierInfo *ID,
9853                                     std::string StubEnc) {
9854   if (!ID)
9855     return;
9856   Entry &E = Map[ID];
9857   assert( (E.Str.empty() || E.State == Recursive) &&
9858          "Incorrectly use of addIncomplete");
9859   assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()");
9860   E.Swapped.swap(E.Str); // swap out the Recursive
9861   E.Str.swap(StubEnc);
9862   E.State = Incomplete;
9863   ++IncompleteCount;
9864 }
9865 
9866 /// Once the RecordType has been expanded, the temporary incomplete TypeString
9867 /// must be removed from the cache.
9868 /// If a Recursive was swapped out by addIncomplete(), it will be replaced.
9869 /// Returns true if the RecordType was defined recursively.
9870 bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) {
9871   if (!ID)
9872     return false;
9873   auto I = Map.find(ID);
9874   assert(I != Map.end() && "Entry not present");
9875   Entry &E = I->second;
9876   assert( (E.State == Incomplete ||
9877            E.State == IncompleteUsed) &&
9878          "Entry must be an incomplete type");
9879   bool IsRecursive = false;
9880   if (E.State == IncompleteUsed) {
9881     // We made use of our Incomplete encoding, thus we are recursive.
9882     IsRecursive = true;
9883     --IncompleteUsedCount;
9884   }
9885   if (E.Swapped.empty())
9886     Map.erase(I);
9887   else {
9888     // Swap the Recursive back.
9889     E.Swapped.swap(E.Str);
9890     E.Swapped.clear();
9891     E.State = Recursive;
9892   }
9893   --IncompleteCount;
9894   return IsRecursive;
9895 }
9896 
9897 /// Add the encoded TypeString to the cache only if it is NonRecursive or
9898 /// Recursive (viz: all sub-members were expanded as fully as possible).
9899 void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str,
9900                                     bool IsRecursive) {
9901   if (!ID || IncompleteUsedCount)
9902     return; // No key or it is is an incomplete sub-type so don't add.
9903   Entry &E = Map[ID];
9904   if (IsRecursive && !E.Str.empty()) {
9905     assert(E.State==Recursive && E.Str.size() == Str.size() &&
9906            "This is not the same Recursive entry");
9907     // The parent container was not recursive after all, so we could have used
9908     // this Recursive sub-member entry after all, but we assumed the worse when
9909     // we started viz: IncompleteCount!=0.
9910     return;
9911   }
9912   assert(E.Str.empty() && "Entry already present");
9913   E.Str = Str.str();
9914   E.State = IsRecursive? Recursive : NonRecursive;
9915 }
9916 
9917 /// Return a cached TypeString encoding for the ID. If there isn't one, or we
9918 /// are recursively expanding a type (IncompleteCount != 0) and the cached
9919 /// encoding is Recursive, return an empty StringRef.
9920 StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) {
9921   if (!ID)
9922     return StringRef();   // We have no key.
9923   auto I = Map.find(ID);
9924   if (I == Map.end())
9925     return StringRef();   // We have no encoding.
9926   Entry &E = I->second;
9927   if (E.State == Recursive && IncompleteCount)
9928     return StringRef();   // We don't use Recursive encodings for member types.
9929 
9930   if (E.State == Incomplete) {
9931     // The incomplete type is being used to break out of recursion.
9932     E.State = IncompleteUsed;
9933     ++IncompleteUsedCount;
9934   }
9935   return E.Str;
9936 }
9937 
9938 /// The XCore ABI includes a type information section that communicates symbol
9939 /// type information to the linker. The linker uses this information to verify
9940 /// safety/correctness of things such as array bound and pointers et al.
9941 /// The ABI only requires C (and XC) language modules to emit TypeStrings.
9942 /// This type information (TypeString) is emitted into meta data for all global
9943 /// symbols: definitions, declarations, functions & variables.
9944 ///
9945 /// The TypeString carries type, qualifier, name, size & value details.
9946 /// Please see 'Tools Development Guide' section 2.16.2 for format details:
9947 /// https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf
9948 /// The output is tested by test/CodeGen/xcore-stringtype.c.
9949 ///
9950 static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
9951                           const CodeGen::CodeGenModule &CGM,
9952                           TypeStringCache &TSC);
9953 
9954 /// XCore uses emitTargetMD to emit TypeString metadata for global symbols.
9955 void XCoreTargetCodeGenInfo::emitTargetMD(
9956     const Decl *D, llvm::GlobalValue *GV,
9957     const CodeGen::CodeGenModule &CGM) const {
9958   SmallStringEnc Enc;
9959   if (getTypeString(Enc, D, CGM, TSC)) {
9960     llvm::LLVMContext &Ctx = CGM.getModule().getContext();
9961     llvm::Metadata *MDVals[] = {llvm::ConstantAsMetadata::get(GV),
9962                                 llvm::MDString::get(Ctx, Enc.str())};
9963     llvm::NamedMDNode *MD =
9964       CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings");
9965     MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
9966   }
9967 }
9968 
9969 void XCoreTargetCodeGenInfo::emitTargetMetadata(
9970     CodeGen::CodeGenModule &CGM,
9971     const llvm::MapVector<GlobalDecl, StringRef> &MangledDeclNames) const {
9972   // Warning, new MangledDeclNames may be appended within this loop.
9973   // We rely on MapVector insertions adding new elements to the end
9974   // of the container.
9975   for (unsigned I = 0; I != MangledDeclNames.size(); ++I) {
9976     auto Val = *(MangledDeclNames.begin() + I);
9977     llvm::GlobalValue *GV = CGM.GetGlobalValue(Val.second);
9978     if (GV) {
9979       const Decl *D = Val.first.getDecl()->getMostRecentDecl();
9980       emitTargetMD(D, GV, CGM);
9981     }
9982   }
9983 }
9984 //===----------------------------------------------------------------------===//
9985 // SPIR ABI Implementation
9986 //===----------------------------------------------------------------------===//
9987 
9988 namespace {
9989 class SPIRTargetCodeGenInfo : public TargetCodeGenInfo {
9990 public:
9991   SPIRTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
9992       : TargetCodeGenInfo(std::make_unique<DefaultABIInfo>(CGT)) {}
9993   unsigned getOpenCLKernelCallingConv() const override;
9994 };
9995 
9996 } // End anonymous namespace.
9997 
9998 namespace clang {
9999 namespace CodeGen {
10000 void computeSPIRKernelABIInfo(CodeGenModule &CGM, CGFunctionInfo &FI) {
10001   DefaultABIInfo SPIRABI(CGM.getTypes());
10002   SPIRABI.computeInfo(FI);
10003 }
10004 }
10005 }
10006 
10007 unsigned SPIRTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
10008   return llvm::CallingConv::SPIR_KERNEL;
10009 }
10010 
10011 static bool appendType(SmallStringEnc &Enc, QualType QType,
10012                        const CodeGen::CodeGenModule &CGM,
10013                        TypeStringCache &TSC);
10014 
10015 /// Helper function for appendRecordType().
10016 /// Builds a SmallVector containing the encoded field types in declaration
10017 /// order.
10018 static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE,
10019                              const RecordDecl *RD,
10020                              const CodeGen::CodeGenModule &CGM,
10021                              TypeStringCache &TSC) {
10022   for (const auto *Field : RD->fields()) {
10023     SmallStringEnc Enc;
10024     Enc += "m(";
10025     Enc += Field->getName();
10026     Enc += "){";
10027     if (Field->isBitField()) {
10028       Enc += "b(";
10029       llvm::raw_svector_ostream OS(Enc);
10030       OS << Field->getBitWidthValue(CGM.getContext());
10031       Enc += ':';
10032     }
10033     if (!appendType(Enc, Field->getType(), CGM, TSC))
10034       return false;
10035     if (Field->isBitField())
10036       Enc += ')';
10037     Enc += '}';
10038     FE.emplace_back(!Field->getName().empty(), Enc);
10039   }
10040   return true;
10041 }
10042 
10043 /// Appends structure and union types to Enc and adds encoding to cache.
10044 /// Recursively calls appendType (via extractFieldType) for each field.
10045 /// Union types have their fields ordered according to the ABI.
10046 static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT,
10047                              const CodeGen::CodeGenModule &CGM,
10048                              TypeStringCache &TSC, const IdentifierInfo *ID) {
10049   // Append the cached TypeString if we have one.
10050   StringRef TypeString = TSC.lookupStr(ID);
10051   if (!TypeString.empty()) {
10052     Enc += TypeString;
10053     return true;
10054   }
10055 
10056   // Start to emit an incomplete TypeString.
10057   size_t Start = Enc.size();
10058   Enc += (RT->isUnionType()? 'u' : 's');
10059   Enc += '(';
10060   if (ID)
10061     Enc += ID->getName();
10062   Enc += "){";
10063 
10064   // We collect all encoded fields and order as necessary.
10065   bool IsRecursive = false;
10066   const RecordDecl *RD = RT->getDecl()->getDefinition();
10067   if (RD && !RD->field_empty()) {
10068     // An incomplete TypeString stub is placed in the cache for this RecordType
10069     // so that recursive calls to this RecordType will use it whilst building a
10070     // complete TypeString for this RecordType.
10071     SmallVector<FieldEncoding, 16> FE;
10072     std::string StubEnc(Enc.substr(Start).str());
10073     StubEnc += '}';  // StubEnc now holds a valid incomplete TypeString.
10074     TSC.addIncomplete(ID, std::move(StubEnc));
10075     if (!extractFieldType(FE, RD, CGM, TSC)) {
10076       (void) TSC.removeIncomplete(ID);
10077       return false;
10078     }
10079     IsRecursive = TSC.removeIncomplete(ID);
10080     // The ABI requires unions to be sorted but not structures.
10081     // See FieldEncoding::operator< for sort algorithm.
10082     if (RT->isUnionType())
10083       llvm::sort(FE);
10084     // We can now complete the TypeString.
10085     unsigned E = FE.size();
10086     for (unsigned I = 0; I != E; ++I) {
10087       if (I)
10088         Enc += ',';
10089       Enc += FE[I].str();
10090     }
10091   }
10092   Enc += '}';
10093   TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive);
10094   return true;
10095 }
10096 
10097 /// Appends enum types to Enc and adds the encoding to the cache.
10098 static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET,
10099                            TypeStringCache &TSC,
10100                            const IdentifierInfo *ID) {
10101   // Append the cached TypeString if we have one.
10102   StringRef TypeString = TSC.lookupStr(ID);
10103   if (!TypeString.empty()) {
10104     Enc += TypeString;
10105     return true;
10106   }
10107 
10108   size_t Start = Enc.size();
10109   Enc += "e(";
10110   if (ID)
10111     Enc += ID->getName();
10112   Enc += "){";
10113 
10114   // We collect all encoded enumerations and order them alphanumerically.
10115   if (const EnumDecl *ED = ET->getDecl()->getDefinition()) {
10116     SmallVector<FieldEncoding, 16> FE;
10117     for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E;
10118          ++I) {
10119       SmallStringEnc EnumEnc;
10120       EnumEnc += "m(";
10121       EnumEnc += I->getName();
10122       EnumEnc += "){";
10123       I->getInitVal().toString(EnumEnc);
10124       EnumEnc += '}';
10125       FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc));
10126     }
10127     llvm::sort(FE);
10128     unsigned E = FE.size();
10129     for (unsigned I = 0; I != E; ++I) {
10130       if (I)
10131         Enc += ',';
10132       Enc += FE[I].str();
10133     }
10134   }
10135   Enc += '}';
10136   TSC.addIfComplete(ID, Enc.substr(Start), false);
10137   return true;
10138 }
10139 
10140 /// Appends type's qualifier to Enc.
10141 /// This is done prior to appending the type's encoding.
10142 static void appendQualifier(SmallStringEnc &Enc, QualType QT) {
10143   // Qualifiers are emitted in alphabetical order.
10144   static const char *const Table[]={"","c:","r:","cr:","v:","cv:","rv:","crv:"};
10145   int Lookup = 0;
10146   if (QT.isConstQualified())
10147     Lookup += 1<<0;
10148   if (QT.isRestrictQualified())
10149     Lookup += 1<<1;
10150   if (QT.isVolatileQualified())
10151     Lookup += 1<<2;
10152   Enc += Table[Lookup];
10153 }
10154 
10155 /// Appends built-in types to Enc.
10156 static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) {
10157   const char *EncType;
10158   switch (BT->getKind()) {
10159     case BuiltinType::Void:
10160       EncType = "0";
10161       break;
10162     case BuiltinType::Bool:
10163       EncType = "b";
10164       break;
10165     case BuiltinType::Char_U:
10166       EncType = "uc";
10167       break;
10168     case BuiltinType::UChar:
10169       EncType = "uc";
10170       break;
10171     case BuiltinType::SChar:
10172       EncType = "sc";
10173       break;
10174     case BuiltinType::UShort:
10175       EncType = "us";
10176       break;
10177     case BuiltinType::Short:
10178       EncType = "ss";
10179       break;
10180     case BuiltinType::UInt:
10181       EncType = "ui";
10182       break;
10183     case BuiltinType::Int:
10184       EncType = "si";
10185       break;
10186     case BuiltinType::ULong:
10187       EncType = "ul";
10188       break;
10189     case BuiltinType::Long:
10190       EncType = "sl";
10191       break;
10192     case BuiltinType::ULongLong:
10193       EncType = "ull";
10194       break;
10195     case BuiltinType::LongLong:
10196       EncType = "sll";
10197       break;
10198     case BuiltinType::Float:
10199       EncType = "ft";
10200       break;
10201     case BuiltinType::Double:
10202       EncType = "d";
10203       break;
10204     case BuiltinType::LongDouble:
10205       EncType = "ld";
10206       break;
10207     default:
10208       return false;
10209   }
10210   Enc += EncType;
10211   return true;
10212 }
10213 
10214 /// Appends a pointer encoding to Enc before calling appendType for the pointee.
10215 static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT,
10216                               const CodeGen::CodeGenModule &CGM,
10217                               TypeStringCache &TSC) {
10218   Enc += "p(";
10219   if (!appendType(Enc, PT->getPointeeType(), CGM, TSC))
10220     return false;
10221   Enc += ')';
10222   return true;
10223 }
10224 
10225 /// Appends array encoding to Enc before calling appendType for the element.
10226 static bool appendArrayType(SmallStringEnc &Enc, QualType QT,
10227                             const ArrayType *AT,
10228                             const CodeGen::CodeGenModule &CGM,
10229                             TypeStringCache &TSC, StringRef NoSizeEnc) {
10230   if (AT->getSizeModifier() != ArrayType::Normal)
10231     return false;
10232   Enc += "a(";
10233   if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
10234     CAT->getSize().toStringUnsigned(Enc);
10235   else
10236     Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "".
10237   Enc += ':';
10238   // The Qualifiers should be attached to the type rather than the array.
10239   appendQualifier(Enc, QT);
10240   if (!appendType(Enc, AT->getElementType(), CGM, TSC))
10241     return false;
10242   Enc += ')';
10243   return true;
10244 }
10245 
10246 /// Appends a function encoding to Enc, calling appendType for the return type
10247 /// and the arguments.
10248 static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT,
10249                              const CodeGen::CodeGenModule &CGM,
10250                              TypeStringCache &TSC) {
10251   Enc += "f{";
10252   if (!appendType(Enc, FT->getReturnType(), CGM, TSC))
10253     return false;
10254   Enc += "}(";
10255   if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) {
10256     // N.B. we are only interested in the adjusted param types.
10257     auto I = FPT->param_type_begin();
10258     auto E = FPT->param_type_end();
10259     if (I != E) {
10260       do {
10261         if (!appendType(Enc, *I, CGM, TSC))
10262           return false;
10263         ++I;
10264         if (I != E)
10265           Enc += ',';
10266       } while (I != E);
10267       if (FPT->isVariadic())
10268         Enc += ",va";
10269     } else {
10270       if (FPT->isVariadic())
10271         Enc += "va";
10272       else
10273         Enc += '0';
10274     }
10275   }
10276   Enc += ')';
10277   return true;
10278 }
10279 
10280 /// Handles the type's qualifier before dispatching a call to handle specific
10281 /// type encodings.
10282 static bool appendType(SmallStringEnc &Enc, QualType QType,
10283                        const CodeGen::CodeGenModule &CGM,
10284                        TypeStringCache &TSC) {
10285 
10286   QualType QT = QType.getCanonicalType();
10287 
10288   if (const ArrayType *AT = QT->getAsArrayTypeUnsafe())
10289     // The Qualifiers should be attached to the type rather than the array.
10290     // Thus we don't call appendQualifier() here.
10291     return appendArrayType(Enc, QT, AT, CGM, TSC, "");
10292 
10293   appendQualifier(Enc, QT);
10294 
10295   if (const BuiltinType *BT = QT->getAs<BuiltinType>())
10296     return appendBuiltinType(Enc, BT);
10297 
10298   if (const PointerType *PT = QT->getAs<PointerType>())
10299     return appendPointerType(Enc, PT, CGM, TSC);
10300 
10301   if (const EnumType *ET = QT->getAs<EnumType>())
10302     return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier());
10303 
10304   if (const RecordType *RT = QT->getAsStructureType())
10305     return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
10306 
10307   if (const RecordType *RT = QT->getAsUnionType())
10308     return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
10309 
10310   if (const FunctionType *FT = QT->getAs<FunctionType>())
10311     return appendFunctionType(Enc, FT, CGM, TSC);
10312 
10313   return false;
10314 }
10315 
10316 static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
10317                           const CodeGen::CodeGenModule &CGM,
10318                           TypeStringCache &TSC) {
10319   if (!D)
10320     return false;
10321 
10322   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
10323     if (FD->getLanguageLinkage() != CLanguageLinkage)
10324       return false;
10325     return appendType(Enc, FD->getType(), CGM, TSC);
10326   }
10327 
10328   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
10329     if (VD->getLanguageLinkage() != CLanguageLinkage)
10330       return false;
10331     QualType QT = VD->getType().getCanonicalType();
10332     if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) {
10333       // Global ArrayTypes are given a size of '*' if the size is unknown.
10334       // The Qualifiers should be attached to the type rather than the array.
10335       // Thus we don't call appendQualifier() here.
10336       return appendArrayType(Enc, QT, AT, CGM, TSC, "*");
10337     }
10338     return appendType(Enc, QT, CGM, TSC);
10339   }
10340   return false;
10341 }
10342 
10343 //===----------------------------------------------------------------------===//
10344 // RISCV ABI Implementation
10345 //===----------------------------------------------------------------------===//
10346 
10347 namespace {
10348 class RISCVABIInfo : public DefaultABIInfo {
10349 private:
10350   // Size of the integer ('x') registers in bits.
10351   unsigned XLen;
10352   // Size of the floating point ('f') registers in bits. Note that the target
10353   // ISA might have a wider FLen than the selected ABI (e.g. an RV32IF target
10354   // with soft float ABI has FLen==0).
10355   unsigned FLen;
10356   static const int NumArgGPRs = 8;
10357   static const int NumArgFPRs = 8;
10358   bool detectFPCCEligibleStructHelper(QualType Ty, CharUnits CurOff,
10359                                       llvm::Type *&Field1Ty,
10360                                       CharUnits &Field1Off,
10361                                       llvm::Type *&Field2Ty,
10362                                       CharUnits &Field2Off) const;
10363 
10364 public:
10365   RISCVABIInfo(CodeGen::CodeGenTypes &CGT, unsigned XLen, unsigned FLen)
10366       : DefaultABIInfo(CGT), XLen(XLen), FLen(FLen) {}
10367 
10368   // DefaultABIInfo's classifyReturnType and classifyArgumentType are
10369   // non-virtual, but computeInfo is virtual, so we overload it.
10370   void computeInfo(CGFunctionInfo &FI) const override;
10371 
10372   ABIArgInfo classifyArgumentType(QualType Ty, bool IsFixed, int &ArgGPRsLeft,
10373                                   int &ArgFPRsLeft) const;
10374   ABIArgInfo classifyReturnType(QualType RetTy) const;
10375 
10376   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
10377                     QualType Ty) const override;
10378 
10379   ABIArgInfo extendType(QualType Ty) const;
10380 
10381   bool detectFPCCEligibleStruct(QualType Ty, llvm::Type *&Field1Ty,
10382                                 CharUnits &Field1Off, llvm::Type *&Field2Ty,
10383                                 CharUnits &Field2Off, int &NeededArgGPRs,
10384                                 int &NeededArgFPRs) const;
10385   ABIArgInfo coerceAndExpandFPCCEligibleStruct(llvm::Type *Field1Ty,
10386                                                CharUnits Field1Off,
10387                                                llvm::Type *Field2Ty,
10388                                                CharUnits Field2Off) const;
10389 };
10390 } // end anonymous namespace
10391 
10392 void RISCVABIInfo::computeInfo(CGFunctionInfo &FI) const {
10393   QualType RetTy = FI.getReturnType();
10394   if (!getCXXABI().classifyReturnType(FI))
10395     FI.getReturnInfo() = classifyReturnType(RetTy);
10396 
10397   // IsRetIndirect is true if classifyArgumentType indicated the value should
10398   // be passed indirect, or if the type size is a scalar greater than 2*XLen
10399   // and not a complex type with elements <= FLen. e.g. fp128 is passed direct
10400   // in LLVM IR, relying on the backend lowering code to rewrite the argument
10401   // list and pass indirectly on RV32.
10402   bool IsRetIndirect = FI.getReturnInfo().getKind() == ABIArgInfo::Indirect;
10403   if (!IsRetIndirect && RetTy->isScalarType() &&
10404       getContext().getTypeSize(RetTy) > (2 * XLen)) {
10405     if (RetTy->isComplexType() && FLen) {
10406       QualType EltTy = RetTy->getAs<ComplexType>()->getElementType();
10407       IsRetIndirect = getContext().getTypeSize(EltTy) > FLen;
10408     } else {
10409       // This is a normal scalar > 2*XLen, such as fp128 on RV32.
10410       IsRetIndirect = true;
10411     }
10412   }
10413 
10414   // We must track the number of GPRs used in order to conform to the RISC-V
10415   // ABI, as integer scalars passed in registers should have signext/zeroext
10416   // when promoted, but are anyext if passed on the stack. As GPR usage is
10417   // different for variadic arguments, we must also track whether we are
10418   // examining a vararg or not.
10419   int ArgGPRsLeft = IsRetIndirect ? NumArgGPRs - 1 : NumArgGPRs;
10420   int ArgFPRsLeft = FLen ? NumArgFPRs : 0;
10421   int NumFixedArgs = FI.getNumRequiredArgs();
10422 
10423   int ArgNum = 0;
10424   for (auto &ArgInfo : FI.arguments()) {
10425     bool IsFixed = ArgNum < NumFixedArgs;
10426     ArgInfo.info =
10427         classifyArgumentType(ArgInfo.type, IsFixed, ArgGPRsLeft, ArgFPRsLeft);
10428     ArgNum++;
10429   }
10430 }
10431 
10432 // Returns true if the struct is a potential candidate for the floating point
10433 // calling convention. If this function returns true, the caller is
10434 // responsible for checking that if there is only a single field then that
10435 // field is a float.
10436 bool RISCVABIInfo::detectFPCCEligibleStructHelper(QualType Ty, CharUnits CurOff,
10437                                                   llvm::Type *&Field1Ty,
10438                                                   CharUnits &Field1Off,
10439                                                   llvm::Type *&Field2Ty,
10440                                                   CharUnits &Field2Off) const {
10441   bool IsInt = Ty->isIntegralOrEnumerationType();
10442   bool IsFloat = Ty->isRealFloatingType();
10443 
10444   if (IsInt || IsFloat) {
10445     uint64_t Size = getContext().getTypeSize(Ty);
10446     if (IsInt && Size > XLen)
10447       return false;
10448     // Can't be eligible if larger than the FP registers. Half precision isn't
10449     // currently supported on RISC-V and the ABI hasn't been confirmed, so
10450     // default to the integer ABI in that case.
10451     if (IsFloat && (Size > FLen || Size < 32))
10452       return false;
10453     // Can't be eligible if an integer type was already found (int+int pairs
10454     // are not eligible).
10455     if (IsInt && Field1Ty && Field1Ty->isIntegerTy())
10456       return false;
10457     if (!Field1Ty) {
10458       Field1Ty = CGT.ConvertType(Ty);
10459       Field1Off = CurOff;
10460       return true;
10461     }
10462     if (!Field2Ty) {
10463       Field2Ty = CGT.ConvertType(Ty);
10464       Field2Off = CurOff;
10465       return true;
10466     }
10467     return false;
10468   }
10469 
10470   if (auto CTy = Ty->getAs<ComplexType>()) {
10471     if (Field1Ty)
10472       return false;
10473     QualType EltTy = CTy->getElementType();
10474     if (getContext().getTypeSize(EltTy) > FLen)
10475       return false;
10476     Field1Ty = CGT.ConvertType(EltTy);
10477     Field1Off = CurOff;
10478     assert(CurOff.isZero() && "Unexpected offset for first field");
10479     Field2Ty = Field1Ty;
10480     Field2Off = Field1Off + getContext().getTypeSizeInChars(EltTy);
10481     return true;
10482   }
10483 
10484   if (const ConstantArrayType *ATy = getContext().getAsConstantArrayType(Ty)) {
10485     uint64_t ArraySize = ATy->getSize().getZExtValue();
10486     QualType EltTy = ATy->getElementType();
10487     CharUnits EltSize = getContext().getTypeSizeInChars(EltTy);
10488     for (uint64_t i = 0; i < ArraySize; ++i) {
10489       bool Ret = detectFPCCEligibleStructHelper(EltTy, CurOff, Field1Ty,
10490                                                 Field1Off, Field2Ty, Field2Off);
10491       if (!Ret)
10492         return false;
10493       CurOff += EltSize;
10494     }
10495     return true;
10496   }
10497 
10498   if (const auto *RTy = Ty->getAs<RecordType>()) {
10499     // Structures with either a non-trivial destructor or a non-trivial
10500     // copy constructor are not eligible for the FP calling convention.
10501     if (getRecordArgABI(Ty, CGT.getCXXABI()))
10502       return false;
10503     if (isEmptyRecord(getContext(), Ty, true))
10504       return true;
10505     const RecordDecl *RD = RTy->getDecl();
10506     // Unions aren't eligible unless they're empty (which is caught above).
10507     if (RD->isUnion())
10508       return false;
10509     int ZeroWidthBitFieldCount = 0;
10510     for (const FieldDecl *FD : RD->fields()) {
10511       const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
10512       uint64_t FieldOffInBits = Layout.getFieldOffset(FD->getFieldIndex());
10513       QualType QTy = FD->getType();
10514       if (FD->isBitField()) {
10515         unsigned BitWidth = FD->getBitWidthValue(getContext());
10516         // Allow a bitfield with a type greater than XLen as long as the
10517         // bitwidth is XLen or less.
10518         if (getContext().getTypeSize(QTy) > XLen && BitWidth <= XLen)
10519           QTy = getContext().getIntTypeForBitwidth(XLen, false);
10520         if (BitWidth == 0) {
10521           ZeroWidthBitFieldCount++;
10522           continue;
10523         }
10524       }
10525 
10526       bool Ret = detectFPCCEligibleStructHelper(
10527           QTy, CurOff + getContext().toCharUnitsFromBits(FieldOffInBits),
10528           Field1Ty, Field1Off, Field2Ty, Field2Off);
10529       if (!Ret)
10530         return false;
10531 
10532       // As a quirk of the ABI, zero-width bitfields aren't ignored for fp+fp
10533       // or int+fp structs, but are ignored for a struct with an fp field and
10534       // any number of zero-width bitfields.
10535       if (Field2Ty && ZeroWidthBitFieldCount > 0)
10536         return false;
10537     }
10538     return Field1Ty != nullptr;
10539   }
10540 
10541   return false;
10542 }
10543 
10544 // Determine if a struct is eligible for passing according to the floating
10545 // point calling convention (i.e., when flattened it contains a single fp
10546 // value, fp+fp, or int+fp of appropriate size). If so, NeededArgFPRs and
10547 // NeededArgGPRs are incremented appropriately.
10548 bool RISCVABIInfo::detectFPCCEligibleStruct(QualType Ty, llvm::Type *&Field1Ty,
10549                                             CharUnits &Field1Off,
10550                                             llvm::Type *&Field2Ty,
10551                                             CharUnits &Field2Off,
10552                                             int &NeededArgGPRs,
10553                                             int &NeededArgFPRs) const {
10554   Field1Ty = nullptr;
10555   Field2Ty = nullptr;
10556   NeededArgGPRs = 0;
10557   NeededArgFPRs = 0;
10558   bool IsCandidate = detectFPCCEligibleStructHelper(
10559       Ty, CharUnits::Zero(), Field1Ty, Field1Off, Field2Ty, Field2Off);
10560   // Not really a candidate if we have a single int but no float.
10561   if (Field1Ty && !Field2Ty && !Field1Ty->isFloatingPointTy())
10562     return false;
10563   if (!IsCandidate)
10564     return false;
10565   if (Field1Ty && Field1Ty->isFloatingPointTy())
10566     NeededArgFPRs++;
10567   else if (Field1Ty)
10568     NeededArgGPRs++;
10569   if (Field2Ty && Field2Ty->isFloatingPointTy())
10570     NeededArgFPRs++;
10571   else if (Field2Ty)
10572     NeededArgGPRs++;
10573   return IsCandidate;
10574 }
10575 
10576 // Call getCoerceAndExpand for the two-element flattened struct described by
10577 // Field1Ty, Field1Off, Field2Ty, Field2Off. This method will create an
10578 // appropriate coerceToType and unpaddedCoerceToType.
10579 ABIArgInfo RISCVABIInfo::coerceAndExpandFPCCEligibleStruct(
10580     llvm::Type *Field1Ty, CharUnits Field1Off, llvm::Type *Field2Ty,
10581     CharUnits Field2Off) const {
10582   SmallVector<llvm::Type *, 3> CoerceElts;
10583   SmallVector<llvm::Type *, 2> UnpaddedCoerceElts;
10584   if (!Field1Off.isZero())
10585     CoerceElts.push_back(llvm::ArrayType::get(
10586         llvm::Type::getInt8Ty(getVMContext()), Field1Off.getQuantity()));
10587 
10588   CoerceElts.push_back(Field1Ty);
10589   UnpaddedCoerceElts.push_back(Field1Ty);
10590 
10591   if (!Field2Ty) {
10592     return ABIArgInfo::getCoerceAndExpand(
10593         llvm::StructType::get(getVMContext(), CoerceElts, !Field1Off.isZero()),
10594         UnpaddedCoerceElts[0]);
10595   }
10596 
10597   CharUnits Field2Align =
10598       CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(Field2Ty));
10599   CharUnits Field1Size =
10600       CharUnits::fromQuantity(getDataLayout().getTypeStoreSize(Field1Ty));
10601   CharUnits Field2OffNoPadNoPack = Field1Size.alignTo(Field2Align);
10602 
10603   CharUnits Padding = CharUnits::Zero();
10604   if (Field2Off > Field2OffNoPadNoPack)
10605     Padding = Field2Off - Field2OffNoPadNoPack;
10606   else if (Field2Off != Field2Align && Field2Off > Field1Size)
10607     Padding = Field2Off - Field1Size;
10608 
10609   bool IsPacked = !Field2Off.isMultipleOf(Field2Align);
10610 
10611   if (!Padding.isZero())
10612     CoerceElts.push_back(llvm::ArrayType::get(
10613         llvm::Type::getInt8Ty(getVMContext()), Padding.getQuantity()));
10614 
10615   CoerceElts.push_back(Field2Ty);
10616   UnpaddedCoerceElts.push_back(Field2Ty);
10617 
10618   auto CoerceToType =
10619       llvm::StructType::get(getVMContext(), CoerceElts, IsPacked);
10620   auto UnpaddedCoerceToType =
10621       llvm::StructType::get(getVMContext(), UnpaddedCoerceElts, IsPacked);
10622 
10623   return ABIArgInfo::getCoerceAndExpand(CoerceToType, UnpaddedCoerceToType);
10624 }
10625 
10626 ABIArgInfo RISCVABIInfo::classifyArgumentType(QualType Ty, bool IsFixed,
10627                                               int &ArgGPRsLeft,
10628                                               int &ArgFPRsLeft) const {
10629   assert(ArgGPRsLeft <= NumArgGPRs && "Arg GPR tracking underflow");
10630   Ty = useFirstFieldIfTransparentUnion(Ty);
10631 
10632   // Structures with either a non-trivial destructor or a non-trivial
10633   // copy constructor are always passed indirectly.
10634   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
10635     if (ArgGPRsLeft)
10636       ArgGPRsLeft -= 1;
10637     return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA ==
10638                                            CGCXXABI::RAA_DirectInMemory);
10639   }
10640 
10641   // Ignore empty structs/unions.
10642   if (isEmptyRecord(getContext(), Ty, true))
10643     return ABIArgInfo::getIgnore();
10644 
10645   uint64_t Size = getContext().getTypeSize(Ty);
10646 
10647   // Pass floating point values via FPRs if possible.
10648   if (IsFixed && Ty->isFloatingType() && !Ty->isComplexType() &&
10649       FLen >= Size && ArgFPRsLeft) {
10650     ArgFPRsLeft--;
10651     return ABIArgInfo::getDirect();
10652   }
10653 
10654   // Complex types for the hard float ABI must be passed direct rather than
10655   // using CoerceAndExpand.
10656   if (IsFixed && Ty->isComplexType() && FLen && ArgFPRsLeft >= 2) {
10657     QualType EltTy = Ty->castAs<ComplexType>()->getElementType();
10658     if (getContext().getTypeSize(EltTy) <= FLen) {
10659       ArgFPRsLeft -= 2;
10660       return ABIArgInfo::getDirect();
10661     }
10662   }
10663 
10664   if (IsFixed && FLen && Ty->isStructureOrClassType()) {
10665     llvm::Type *Field1Ty = nullptr;
10666     llvm::Type *Field2Ty = nullptr;
10667     CharUnits Field1Off = CharUnits::Zero();
10668     CharUnits Field2Off = CharUnits::Zero();
10669     int NeededArgGPRs;
10670     int NeededArgFPRs;
10671     bool IsCandidate =
10672         detectFPCCEligibleStruct(Ty, Field1Ty, Field1Off, Field2Ty, Field2Off,
10673                                  NeededArgGPRs, NeededArgFPRs);
10674     if (IsCandidate && NeededArgGPRs <= ArgGPRsLeft &&
10675         NeededArgFPRs <= ArgFPRsLeft) {
10676       ArgGPRsLeft -= NeededArgGPRs;
10677       ArgFPRsLeft -= NeededArgFPRs;
10678       return coerceAndExpandFPCCEligibleStruct(Field1Ty, Field1Off, Field2Ty,
10679                                                Field2Off);
10680     }
10681   }
10682 
10683   uint64_t NeededAlign = getContext().getTypeAlign(Ty);
10684   bool MustUseStack = false;
10685   // Determine the number of GPRs needed to pass the current argument
10686   // according to the ABI. 2*XLen-aligned varargs are passed in "aligned"
10687   // register pairs, so may consume 3 registers.
10688   int NeededArgGPRs = 1;
10689   if (!IsFixed && NeededAlign == 2 * XLen)
10690     NeededArgGPRs = 2 + (ArgGPRsLeft % 2);
10691   else if (Size > XLen && Size <= 2 * XLen)
10692     NeededArgGPRs = 2;
10693 
10694   if (NeededArgGPRs > ArgGPRsLeft) {
10695     MustUseStack = true;
10696     NeededArgGPRs = ArgGPRsLeft;
10697   }
10698 
10699   ArgGPRsLeft -= NeededArgGPRs;
10700 
10701   if (!isAggregateTypeForABI(Ty) && !Ty->isVectorType()) {
10702     // Treat an enum type as its underlying type.
10703     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
10704       Ty = EnumTy->getDecl()->getIntegerType();
10705 
10706     // All integral types are promoted to XLen width, unless passed on the
10707     // stack.
10708     if (Size < XLen && Ty->isIntegralOrEnumerationType() && !MustUseStack) {
10709       return extendType(Ty);
10710     }
10711 
10712     if (const auto *EIT = Ty->getAs<ExtIntType>()) {
10713       if (EIT->getNumBits() < XLen && !MustUseStack)
10714         return extendType(Ty);
10715       if (EIT->getNumBits() > 128 ||
10716           (!getContext().getTargetInfo().hasInt128Type() &&
10717            EIT->getNumBits() > 64))
10718         return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
10719     }
10720 
10721     return ABIArgInfo::getDirect();
10722   }
10723 
10724   // Aggregates which are <= 2*XLen will be passed in registers if possible,
10725   // so coerce to integers.
10726   if (Size <= 2 * XLen) {
10727     unsigned Alignment = getContext().getTypeAlign(Ty);
10728 
10729     // Use a single XLen int if possible, 2*XLen if 2*XLen alignment is
10730     // required, and a 2-element XLen array if only XLen alignment is required.
10731     if (Size <= XLen) {
10732       return ABIArgInfo::getDirect(
10733           llvm::IntegerType::get(getVMContext(), XLen));
10734     } else if (Alignment == 2 * XLen) {
10735       return ABIArgInfo::getDirect(
10736           llvm::IntegerType::get(getVMContext(), 2 * XLen));
10737     } else {
10738       return ABIArgInfo::getDirect(llvm::ArrayType::get(
10739           llvm::IntegerType::get(getVMContext(), XLen), 2));
10740     }
10741   }
10742   return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
10743 }
10744 
10745 ABIArgInfo RISCVABIInfo::classifyReturnType(QualType RetTy) const {
10746   if (RetTy->isVoidType())
10747     return ABIArgInfo::getIgnore();
10748 
10749   int ArgGPRsLeft = 2;
10750   int ArgFPRsLeft = FLen ? 2 : 0;
10751 
10752   // The rules for return and argument types are the same, so defer to
10753   // classifyArgumentType.
10754   return classifyArgumentType(RetTy, /*IsFixed=*/true, ArgGPRsLeft,
10755                               ArgFPRsLeft);
10756 }
10757 
10758 Address RISCVABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
10759                                 QualType Ty) const {
10760   CharUnits SlotSize = CharUnits::fromQuantity(XLen / 8);
10761 
10762   // Empty records are ignored for parameter passing purposes.
10763   if (isEmptyRecord(getContext(), Ty, true)) {
10764     Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize);
10765     Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
10766     return Addr;
10767   }
10768 
10769   auto TInfo = getContext().getTypeInfoInChars(Ty);
10770 
10771   // Arguments bigger than 2*Xlen bytes are passed indirectly.
10772   bool IsIndirect = TInfo.Width > 2 * SlotSize;
10773 
10774   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TInfo,
10775                           SlotSize, /*AllowHigherAlign=*/true);
10776 }
10777 
10778 ABIArgInfo RISCVABIInfo::extendType(QualType Ty) const {
10779   int TySize = getContext().getTypeSize(Ty);
10780   // RV64 ABI requires unsigned 32 bit integers to be sign extended.
10781   if (XLen == 64 && Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
10782     return ABIArgInfo::getSignExtend(Ty);
10783   return ABIArgInfo::getExtend(Ty);
10784 }
10785 
10786 namespace {
10787 class RISCVTargetCodeGenInfo : public TargetCodeGenInfo {
10788 public:
10789   RISCVTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, unsigned XLen,
10790                          unsigned FLen)
10791       : TargetCodeGenInfo(std::make_unique<RISCVABIInfo>(CGT, XLen, FLen)) {}
10792 
10793   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
10794                            CodeGen::CodeGenModule &CGM) const override {
10795     const auto *FD = dyn_cast_or_null<FunctionDecl>(D);
10796     if (!FD) return;
10797 
10798     const auto *Attr = FD->getAttr<RISCVInterruptAttr>();
10799     if (!Attr)
10800       return;
10801 
10802     const char *Kind;
10803     switch (Attr->getInterrupt()) {
10804     case RISCVInterruptAttr::user: Kind = "user"; break;
10805     case RISCVInterruptAttr::supervisor: Kind = "supervisor"; break;
10806     case RISCVInterruptAttr::machine: Kind = "machine"; break;
10807     }
10808 
10809     auto *Fn = cast<llvm::Function>(GV);
10810 
10811     Fn->addFnAttr("interrupt", Kind);
10812   }
10813 };
10814 } // namespace
10815 
10816 //===----------------------------------------------------------------------===//
10817 // VE ABI Implementation.
10818 //
10819 namespace {
10820 class VEABIInfo : public DefaultABIInfo {
10821 public:
10822   VEABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
10823 
10824 private:
10825   ABIArgInfo classifyReturnType(QualType RetTy) const;
10826   ABIArgInfo classifyArgumentType(QualType RetTy) const;
10827   void computeInfo(CGFunctionInfo &FI) const override;
10828 };
10829 } // end anonymous namespace
10830 
10831 ABIArgInfo VEABIInfo::classifyReturnType(QualType Ty) const {
10832   if (Ty->isAnyComplexType())
10833     return ABIArgInfo::getDirect();
10834   uint64_t Size = getContext().getTypeSize(Ty);
10835   if (Size < 64 && Ty->isIntegerType())
10836     return ABIArgInfo::getExtend(Ty);
10837   return DefaultABIInfo::classifyReturnType(Ty);
10838 }
10839 
10840 ABIArgInfo VEABIInfo::classifyArgumentType(QualType Ty) const {
10841   if (Ty->isAnyComplexType())
10842     return ABIArgInfo::getDirect();
10843   uint64_t Size = getContext().getTypeSize(Ty);
10844   if (Size < 64 && Ty->isIntegerType())
10845     return ABIArgInfo::getExtend(Ty);
10846   return DefaultABIInfo::classifyArgumentType(Ty);
10847 }
10848 
10849 void VEABIInfo::computeInfo(CGFunctionInfo &FI) const {
10850   FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
10851   for (auto &Arg : FI.arguments())
10852     Arg.info = classifyArgumentType(Arg.type);
10853 }
10854 
10855 namespace {
10856 class VETargetCodeGenInfo : public TargetCodeGenInfo {
10857 public:
10858   VETargetCodeGenInfo(CodeGenTypes &CGT)
10859       : TargetCodeGenInfo(std::make_unique<VEABIInfo>(CGT)) {}
10860   // VE ABI requires the arguments of variadic and prototype-less functions
10861   // are passed in both registers and memory.
10862   bool isNoProtoCallVariadic(const CallArgList &args,
10863                              const FunctionNoProtoType *fnType) const override {
10864     return true;
10865   }
10866 };
10867 } // end anonymous namespace
10868 
10869 //===----------------------------------------------------------------------===//
10870 // Driver code
10871 //===----------------------------------------------------------------------===//
10872 
10873 bool CodeGenModule::supportsCOMDAT() const {
10874   return getTriple().supportsCOMDAT();
10875 }
10876 
10877 const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
10878   if (TheTargetCodeGenInfo)
10879     return *TheTargetCodeGenInfo;
10880 
10881   // Helper to set the unique_ptr while still keeping the return value.
10882   auto SetCGInfo = [&](TargetCodeGenInfo *P) -> const TargetCodeGenInfo & {
10883     this->TheTargetCodeGenInfo.reset(P);
10884     return *P;
10885   };
10886 
10887   const llvm::Triple &Triple = getTarget().getTriple();
10888   switch (Triple.getArch()) {
10889   default:
10890     return SetCGInfo(new DefaultTargetCodeGenInfo(Types));
10891 
10892   case llvm::Triple::le32:
10893     return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
10894   case llvm::Triple::mips:
10895   case llvm::Triple::mipsel:
10896     if (Triple.getOS() == llvm::Triple::NaCl)
10897       return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
10898     return SetCGInfo(new MIPSTargetCodeGenInfo(Types, true));
10899 
10900   case llvm::Triple::mips64:
10901   case llvm::Triple::mips64el:
10902     return SetCGInfo(new MIPSTargetCodeGenInfo(Types, false));
10903 
10904   case llvm::Triple::avr:
10905     return SetCGInfo(new AVRTargetCodeGenInfo(Types));
10906 
10907   case llvm::Triple::aarch64:
10908   case llvm::Triple::aarch64_32:
10909   case llvm::Triple::aarch64_be: {
10910     AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS;
10911     if (getTarget().getABI() == "darwinpcs")
10912       Kind = AArch64ABIInfo::DarwinPCS;
10913     else if (Triple.isOSWindows())
10914       return SetCGInfo(
10915           new WindowsAArch64TargetCodeGenInfo(Types, AArch64ABIInfo::Win64));
10916 
10917     return SetCGInfo(new AArch64TargetCodeGenInfo(Types, Kind));
10918   }
10919 
10920   case llvm::Triple::wasm32:
10921   case llvm::Triple::wasm64: {
10922     WebAssemblyABIInfo::ABIKind Kind = WebAssemblyABIInfo::MVP;
10923     if (getTarget().getABI() == "experimental-mv")
10924       Kind = WebAssemblyABIInfo::ExperimentalMV;
10925     return SetCGInfo(new WebAssemblyTargetCodeGenInfo(Types, Kind));
10926   }
10927 
10928   case llvm::Triple::arm:
10929   case llvm::Triple::armeb:
10930   case llvm::Triple::thumb:
10931   case llvm::Triple::thumbeb: {
10932     if (Triple.getOS() == llvm::Triple::Win32) {
10933       return SetCGInfo(
10934           new WindowsARMTargetCodeGenInfo(Types, ARMABIInfo::AAPCS_VFP));
10935     }
10936 
10937     ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
10938     StringRef ABIStr = getTarget().getABI();
10939     if (ABIStr == "apcs-gnu")
10940       Kind = ARMABIInfo::APCS;
10941     else if (ABIStr == "aapcs16")
10942       Kind = ARMABIInfo::AAPCS16_VFP;
10943     else if (CodeGenOpts.FloatABI == "hard" ||
10944              (CodeGenOpts.FloatABI != "soft" &&
10945               (Triple.getEnvironment() == llvm::Triple::GNUEABIHF ||
10946                Triple.getEnvironment() == llvm::Triple::MuslEABIHF ||
10947                Triple.getEnvironment() == llvm::Triple::EABIHF)))
10948       Kind = ARMABIInfo::AAPCS_VFP;
10949 
10950     return SetCGInfo(new ARMTargetCodeGenInfo(Types, Kind));
10951   }
10952 
10953   case llvm::Triple::ppc: {
10954     if (Triple.isOSAIX())
10955       return SetCGInfo(new AIXTargetCodeGenInfo(Types, /*Is64Bit*/ false));
10956 
10957     bool IsSoftFloat =
10958         CodeGenOpts.FloatABI == "soft" || getTarget().hasFeature("spe");
10959     bool RetSmallStructInRegABI =
10960         PPC32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
10961     return SetCGInfo(
10962         new PPC32TargetCodeGenInfo(Types, IsSoftFloat, RetSmallStructInRegABI));
10963   }
10964   case llvm::Triple::ppc64:
10965     if (Triple.isOSAIX())
10966       return SetCGInfo(new AIXTargetCodeGenInfo(Types, /*Is64Bit*/ true));
10967 
10968     if (Triple.isOSBinFormatELF()) {
10969       PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1;
10970       if (getTarget().getABI() == "elfv2")
10971         Kind = PPC64_SVR4_ABIInfo::ELFv2;
10972       bool HasQPX = getTarget().getABI() == "elfv1-qpx";
10973       bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
10974 
10975       return SetCGInfo(new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX,
10976                                                         IsSoftFloat));
10977     }
10978     return SetCGInfo(new PPC64TargetCodeGenInfo(Types));
10979   case llvm::Triple::ppc64le: {
10980     assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
10981     PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2;
10982     if (getTarget().getABI() == "elfv1" || getTarget().getABI() == "elfv1-qpx")
10983       Kind = PPC64_SVR4_ABIInfo::ELFv1;
10984     bool HasQPX = getTarget().getABI() == "elfv1-qpx";
10985     bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
10986 
10987     return SetCGInfo(new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX,
10988                                                       IsSoftFloat));
10989   }
10990 
10991   case llvm::Triple::nvptx:
10992   case llvm::Triple::nvptx64:
10993     return SetCGInfo(new NVPTXTargetCodeGenInfo(Types));
10994 
10995   case llvm::Triple::msp430:
10996     return SetCGInfo(new MSP430TargetCodeGenInfo(Types));
10997 
10998   case llvm::Triple::riscv32:
10999   case llvm::Triple::riscv64: {
11000     StringRef ABIStr = getTarget().getABI();
11001     unsigned XLen = getTarget().getPointerWidth(0);
11002     unsigned ABIFLen = 0;
11003     if (ABIStr.endswith("f"))
11004       ABIFLen = 32;
11005     else if (ABIStr.endswith("d"))
11006       ABIFLen = 64;
11007     return SetCGInfo(new RISCVTargetCodeGenInfo(Types, XLen, ABIFLen));
11008   }
11009 
11010   case llvm::Triple::systemz: {
11011     bool SoftFloat = CodeGenOpts.FloatABI == "soft";
11012     bool HasVector = !SoftFloat && getTarget().getABI() == "vector";
11013     return SetCGInfo(new SystemZTargetCodeGenInfo(Types, HasVector, SoftFloat));
11014   }
11015 
11016   case llvm::Triple::tce:
11017   case llvm::Triple::tcele:
11018     return SetCGInfo(new TCETargetCodeGenInfo(Types));
11019 
11020   case llvm::Triple::x86: {
11021     bool IsDarwinVectorABI = Triple.isOSDarwin();
11022     bool RetSmallStructInRegABI =
11023         X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
11024     bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
11025 
11026     if (Triple.getOS() == llvm::Triple::Win32) {
11027       return SetCGInfo(new WinX86_32TargetCodeGenInfo(
11028           Types, IsDarwinVectorABI, RetSmallStructInRegABI,
11029           IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters));
11030     } else {
11031       return SetCGInfo(new X86_32TargetCodeGenInfo(
11032           Types, IsDarwinVectorABI, RetSmallStructInRegABI,
11033           IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters,
11034           CodeGenOpts.FloatABI == "soft"));
11035     }
11036   }
11037 
11038   case llvm::Triple::x86_64: {
11039     StringRef ABI = getTarget().getABI();
11040     X86AVXABILevel AVXLevel =
11041         (ABI == "avx512"
11042              ? X86AVXABILevel::AVX512
11043              : ABI == "avx" ? X86AVXABILevel::AVX : X86AVXABILevel::None);
11044 
11045     switch (Triple.getOS()) {
11046     case llvm::Triple::Win32:
11047       return SetCGInfo(new WinX86_64TargetCodeGenInfo(Types, AVXLevel));
11048     default:
11049       return SetCGInfo(new X86_64TargetCodeGenInfo(Types, AVXLevel));
11050     }
11051   }
11052   case llvm::Triple::hexagon:
11053     return SetCGInfo(new HexagonTargetCodeGenInfo(Types));
11054   case llvm::Triple::lanai:
11055     return SetCGInfo(new LanaiTargetCodeGenInfo(Types));
11056   case llvm::Triple::r600:
11057     return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
11058   case llvm::Triple::amdgcn:
11059     return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
11060   case llvm::Triple::sparc:
11061     return SetCGInfo(new SparcV8TargetCodeGenInfo(Types));
11062   case llvm::Triple::sparcv9:
11063     return SetCGInfo(new SparcV9TargetCodeGenInfo(Types));
11064   case llvm::Triple::xcore:
11065     return SetCGInfo(new XCoreTargetCodeGenInfo(Types));
11066   case llvm::Triple::arc:
11067     return SetCGInfo(new ARCTargetCodeGenInfo(Types));
11068   case llvm::Triple::spir:
11069   case llvm::Triple::spir64:
11070     return SetCGInfo(new SPIRTargetCodeGenInfo(Types));
11071   case llvm::Triple::ve:
11072     return SetCGInfo(new VETargetCodeGenInfo(Types));
11073   }
11074 }
11075 
11076 /// Create an OpenCL kernel for an enqueued block.
11077 ///
11078 /// The kernel has the same function type as the block invoke function. Its
11079 /// name is the name of the block invoke function postfixed with "_kernel".
11080 /// It simply calls the block invoke function then returns.
11081 llvm::Function *
11082 TargetCodeGenInfo::createEnqueuedBlockKernel(CodeGenFunction &CGF,
11083                                              llvm::Function *Invoke,
11084                                              llvm::Value *BlockLiteral) const {
11085   auto *InvokeFT = Invoke->getFunctionType();
11086   llvm::SmallVector<llvm::Type *, 2> ArgTys;
11087   for (auto &P : InvokeFT->params())
11088     ArgTys.push_back(P);
11089   auto &C = CGF.getLLVMContext();
11090   std::string Name = Invoke->getName().str() + "_kernel";
11091   auto *FT = llvm::FunctionType::get(llvm::Type::getVoidTy(C), ArgTys, false);
11092   auto *F = llvm::Function::Create(FT, llvm::GlobalValue::InternalLinkage, Name,
11093                                    &CGF.CGM.getModule());
11094   auto IP = CGF.Builder.saveIP();
11095   auto *BB = llvm::BasicBlock::Create(C, "entry", F);
11096   auto &Builder = CGF.Builder;
11097   Builder.SetInsertPoint(BB);
11098   llvm::SmallVector<llvm::Value *, 2> Args;
11099   for (auto &A : F->args())
11100     Args.push_back(&A);
11101   Builder.CreateCall(Invoke, Args);
11102   Builder.CreateRetVoid();
11103   Builder.restoreIP(IP);
11104   return F;
11105 }
11106 
11107 /// Create an OpenCL kernel for an enqueued block.
11108 ///
11109 /// The type of the first argument (the block literal) is the struct type
11110 /// of the block literal instead of a pointer type. The first argument
11111 /// (block literal) is passed directly by value to the kernel. The kernel
11112 /// allocates the same type of struct on stack and stores the block literal
11113 /// to it and passes its pointer to the block invoke function. The kernel
11114 /// has "enqueued-block" function attribute and kernel argument metadata.
11115 llvm::Function *AMDGPUTargetCodeGenInfo::createEnqueuedBlockKernel(
11116     CodeGenFunction &CGF, llvm::Function *Invoke,
11117     llvm::Value *BlockLiteral) const {
11118   auto &Builder = CGF.Builder;
11119   auto &C = CGF.getLLVMContext();
11120 
11121   auto *BlockTy = BlockLiteral->getType()->getPointerElementType();
11122   auto *InvokeFT = Invoke->getFunctionType();
11123   llvm::SmallVector<llvm::Type *, 2> ArgTys;
11124   llvm::SmallVector<llvm::Metadata *, 8> AddressQuals;
11125   llvm::SmallVector<llvm::Metadata *, 8> AccessQuals;
11126   llvm::SmallVector<llvm::Metadata *, 8> ArgTypeNames;
11127   llvm::SmallVector<llvm::Metadata *, 8> ArgBaseTypeNames;
11128   llvm::SmallVector<llvm::Metadata *, 8> ArgTypeQuals;
11129   llvm::SmallVector<llvm::Metadata *, 8> ArgNames;
11130 
11131   ArgTys.push_back(BlockTy);
11132   ArgTypeNames.push_back(llvm::MDString::get(C, "__block_literal"));
11133   AddressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(0)));
11134   ArgBaseTypeNames.push_back(llvm::MDString::get(C, "__block_literal"));
11135   ArgTypeQuals.push_back(llvm::MDString::get(C, ""));
11136   AccessQuals.push_back(llvm::MDString::get(C, "none"));
11137   ArgNames.push_back(llvm::MDString::get(C, "block_literal"));
11138   for (unsigned I = 1, E = InvokeFT->getNumParams(); I < E; ++I) {
11139     ArgTys.push_back(InvokeFT->getParamType(I));
11140     ArgTypeNames.push_back(llvm::MDString::get(C, "void*"));
11141     AddressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(3)));
11142     AccessQuals.push_back(llvm::MDString::get(C, "none"));
11143     ArgBaseTypeNames.push_back(llvm::MDString::get(C, "void*"));
11144     ArgTypeQuals.push_back(llvm::MDString::get(C, ""));
11145     ArgNames.push_back(
11146         llvm::MDString::get(C, (Twine("local_arg") + Twine(I)).str()));
11147   }
11148   std::string Name = Invoke->getName().str() + "_kernel";
11149   auto *FT = llvm::FunctionType::get(llvm::Type::getVoidTy(C), ArgTys, false);
11150   auto *F = llvm::Function::Create(FT, llvm::GlobalValue::InternalLinkage, Name,
11151                                    &CGF.CGM.getModule());
11152   F->addFnAttr("enqueued-block");
11153   auto IP = CGF.Builder.saveIP();
11154   auto *BB = llvm::BasicBlock::Create(C, "entry", F);
11155   Builder.SetInsertPoint(BB);
11156   const auto BlockAlign = CGF.CGM.getDataLayout().getPrefTypeAlign(BlockTy);
11157   auto *BlockPtr = Builder.CreateAlloca(BlockTy, nullptr);
11158   BlockPtr->setAlignment(BlockAlign);
11159   Builder.CreateAlignedStore(F->arg_begin(), BlockPtr, BlockAlign);
11160   auto *Cast = Builder.CreatePointerCast(BlockPtr, InvokeFT->getParamType(0));
11161   llvm::SmallVector<llvm::Value *, 2> Args;
11162   Args.push_back(Cast);
11163   for (auto I = F->arg_begin() + 1, E = F->arg_end(); I != E; ++I)
11164     Args.push_back(I);
11165   Builder.CreateCall(Invoke, Args);
11166   Builder.CreateRetVoid();
11167   Builder.restoreIP(IP);
11168 
11169   F->setMetadata("kernel_arg_addr_space", llvm::MDNode::get(C, AddressQuals));
11170   F->setMetadata("kernel_arg_access_qual", llvm::MDNode::get(C, AccessQuals));
11171   F->setMetadata("kernel_arg_type", llvm::MDNode::get(C, ArgTypeNames));
11172   F->setMetadata("kernel_arg_base_type",
11173                  llvm::MDNode::get(C, ArgBaseTypeNames));
11174   F->setMetadata("kernel_arg_type_qual", llvm::MDNode::get(C, ArgTypeQuals));
11175   if (CGF.CGM.getCodeGenOpts().EmitOpenCLArgMetadata)
11176     F->setMetadata("kernel_arg_name", llvm::MDNode::get(C, ArgNames));
11177 
11178   return F;
11179 }
11180