1 //===---- TargetInfo.cpp - Encapsulate target details -----------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // These classes wrap the information about a call or function
10 // definition used to handle ABI compliancy.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "TargetInfo.h"
15 #include "ABIInfo.h"
16 #include "CGBlocks.h"
17 #include "CGCXXABI.h"
18 #include "CGValue.h"
19 #include "CodeGenFunction.h"
20 #include "clang/AST/Attr.h"
21 #include "clang/AST/RecordLayout.h"
22 #include "clang/Basic/CodeGenOptions.h"
23 #include "clang/Basic/DiagnosticFrontend.h"
24 #include "clang/Basic/Builtins.h"
25 #include "clang/CodeGen/CGFunctionInfo.h"
26 #include "clang/CodeGen/SwiftCallingConv.h"
27 #include "llvm/ADT/SmallBitVector.h"
28 #include "llvm/ADT/StringExtras.h"
29 #include "llvm/ADT/StringSwitch.h"
30 #include "llvm/ADT/Triple.h"
31 #include "llvm/ADT/Twine.h"
32 #include "llvm/IR/DataLayout.h"
33 #include "llvm/IR/IntrinsicsNVPTX.h"
34 #include "llvm/IR/IntrinsicsS390.h"
35 #include "llvm/IR/Type.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include <algorithm> // std::sort
38 
39 using namespace clang;
40 using namespace CodeGen;
41 
42 // Helper for coercing an aggregate argument or return value into an integer
43 // array of the same size (including padding) and alignment.  This alternate
44 // coercion happens only for the RenderScript ABI and can be removed after
45 // runtimes that rely on it are no longer supported.
46 //
47 // RenderScript assumes that the size of the argument / return value in the IR
48 // is the same as the size of the corresponding qualified type. This helper
49 // coerces the aggregate type into an array of the same size (including
50 // padding).  This coercion is used in lieu of expansion of struct members or
51 // other canonical coercions that return a coerced-type of larger size.
52 //
53 // Ty          - The argument / return value type
54 // Context     - The associated ASTContext
55 // LLVMContext - The associated LLVMContext
56 static ABIArgInfo coerceToIntArray(QualType Ty,
57                                    ASTContext &Context,
58                                    llvm::LLVMContext &LLVMContext) {
59   // Alignment and Size are measured in bits.
60   const uint64_t Size = Context.getTypeSize(Ty);
61   const uint64_t Alignment = Context.getTypeAlign(Ty);
62   llvm::Type *IntType = llvm::Type::getIntNTy(LLVMContext, Alignment);
63   const uint64_t NumElements = (Size + Alignment - 1) / Alignment;
64   return ABIArgInfo::getDirect(llvm::ArrayType::get(IntType, NumElements));
65 }
66 
67 static void AssignToArrayRange(CodeGen::CGBuilderTy &Builder,
68                                llvm::Value *Array,
69                                llvm::Value *Value,
70                                unsigned FirstIndex,
71                                unsigned LastIndex) {
72   // Alternatively, we could emit this as a loop in the source.
73   for (unsigned I = FirstIndex; I <= LastIndex; ++I) {
74     llvm::Value *Cell =
75         Builder.CreateConstInBoundsGEP1_32(Builder.getInt8Ty(), Array, I);
76     Builder.CreateAlignedStore(Value, Cell, CharUnits::One());
77   }
78 }
79 
80 static bool isAggregateTypeForABI(QualType T) {
81   return !CodeGenFunction::hasScalarEvaluationKind(T) ||
82          T->isMemberFunctionPointerType();
83 }
84 
85 ABIArgInfo ABIInfo::getNaturalAlignIndirect(QualType Ty, bool ByVal,
86                                             bool Realign,
87                                             llvm::Type *Padding) const {
88   return ABIArgInfo::getIndirect(getContext().getTypeAlignInChars(Ty), ByVal,
89                                  Realign, Padding);
90 }
91 
92 ABIArgInfo
93 ABIInfo::getNaturalAlignIndirectInReg(QualType Ty, bool Realign) const {
94   return ABIArgInfo::getIndirectInReg(getContext().getTypeAlignInChars(Ty),
95                                       /*ByVal*/ false, Realign);
96 }
97 
98 Address ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
99                              QualType Ty) const {
100   return Address::invalid();
101 }
102 
103 bool ABIInfo::isPromotableIntegerTypeForABI(QualType Ty) const {
104   if (Ty->isPromotableIntegerType())
105     return true;
106 
107   if (const auto *EIT = Ty->getAs<ExtIntType>())
108     if (EIT->getNumBits() < getContext().getTypeSize(getContext().IntTy))
109       return true;
110 
111   return false;
112 }
113 
114 ABIInfo::~ABIInfo() {}
115 
116 /// Does the given lowering require more than the given number of
117 /// registers when expanded?
118 ///
119 /// This is intended to be the basis of a reasonable basic implementation
120 /// of should{Pass,Return}IndirectlyForSwift.
121 ///
122 /// For most targets, a limit of four total registers is reasonable; this
123 /// limits the amount of code required in order to move around the value
124 /// in case it wasn't produced immediately prior to the call by the caller
125 /// (or wasn't produced in exactly the right registers) or isn't used
126 /// immediately within the callee.  But some targets may need to further
127 /// limit the register count due to an inability to support that many
128 /// return registers.
129 static bool occupiesMoreThan(CodeGenTypes &cgt,
130                              ArrayRef<llvm::Type*> scalarTypes,
131                              unsigned maxAllRegisters) {
132   unsigned intCount = 0, fpCount = 0;
133   for (llvm::Type *type : scalarTypes) {
134     if (type->isPointerTy()) {
135       intCount++;
136     } else if (auto intTy = dyn_cast<llvm::IntegerType>(type)) {
137       auto ptrWidth = cgt.getTarget().getPointerWidth(0);
138       intCount += (intTy->getBitWidth() + ptrWidth - 1) / ptrWidth;
139     } else {
140       assert(type->isVectorTy() || type->isFloatingPointTy());
141       fpCount++;
142     }
143   }
144 
145   return (intCount + fpCount > maxAllRegisters);
146 }
147 
148 bool SwiftABIInfo::isLegalVectorTypeForSwift(CharUnits vectorSize,
149                                              llvm::Type *eltTy,
150                                              unsigned numElts) const {
151   // The default implementation of this assumes that the target guarantees
152   // 128-bit SIMD support but nothing more.
153   return (vectorSize.getQuantity() > 8 && vectorSize.getQuantity() <= 16);
154 }
155 
156 static CGCXXABI::RecordArgABI getRecordArgABI(const RecordType *RT,
157                                               CGCXXABI &CXXABI) {
158   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
159   if (!RD) {
160     if (!RT->getDecl()->canPassInRegisters())
161       return CGCXXABI::RAA_Indirect;
162     return CGCXXABI::RAA_Default;
163   }
164   return CXXABI.getRecordArgABI(RD);
165 }
166 
167 static CGCXXABI::RecordArgABI getRecordArgABI(QualType T,
168                                               CGCXXABI &CXXABI) {
169   const RecordType *RT = T->getAs<RecordType>();
170   if (!RT)
171     return CGCXXABI::RAA_Default;
172   return getRecordArgABI(RT, CXXABI);
173 }
174 
175 static bool classifyReturnType(const CGCXXABI &CXXABI, CGFunctionInfo &FI,
176                                const ABIInfo &Info) {
177   QualType Ty = FI.getReturnType();
178 
179   if (const auto *RT = Ty->getAs<RecordType>())
180     if (!isa<CXXRecordDecl>(RT->getDecl()) &&
181         !RT->getDecl()->canPassInRegisters()) {
182       FI.getReturnInfo() = Info.getNaturalAlignIndirect(Ty);
183       return true;
184     }
185 
186   return CXXABI.classifyReturnType(FI);
187 }
188 
189 /// Pass transparent unions as if they were the type of the first element. Sema
190 /// should ensure that all elements of the union have the same "machine type".
191 static QualType useFirstFieldIfTransparentUnion(QualType Ty) {
192   if (const RecordType *UT = Ty->getAsUnionType()) {
193     const RecordDecl *UD = UT->getDecl();
194     if (UD->hasAttr<TransparentUnionAttr>()) {
195       assert(!UD->field_empty() && "sema created an empty transparent union");
196       return UD->field_begin()->getType();
197     }
198   }
199   return Ty;
200 }
201 
202 CGCXXABI &ABIInfo::getCXXABI() const {
203   return CGT.getCXXABI();
204 }
205 
206 ASTContext &ABIInfo::getContext() const {
207   return CGT.getContext();
208 }
209 
210 llvm::LLVMContext &ABIInfo::getVMContext() const {
211   return CGT.getLLVMContext();
212 }
213 
214 const llvm::DataLayout &ABIInfo::getDataLayout() const {
215   return CGT.getDataLayout();
216 }
217 
218 const TargetInfo &ABIInfo::getTarget() const {
219   return CGT.getTarget();
220 }
221 
222 const CodeGenOptions &ABIInfo::getCodeGenOpts() const {
223   return CGT.getCodeGenOpts();
224 }
225 
226 bool ABIInfo::isAndroid() const { return getTarget().getTriple().isAndroid(); }
227 
228 bool ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
229   return false;
230 }
231 
232 bool ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
233                                                 uint64_t Members) const {
234   return false;
235 }
236 
237 LLVM_DUMP_METHOD void ABIArgInfo::dump() const {
238   raw_ostream &OS = llvm::errs();
239   OS << "(ABIArgInfo Kind=";
240   switch (TheKind) {
241   case Direct:
242     OS << "Direct Type=";
243     if (llvm::Type *Ty = getCoerceToType())
244       Ty->print(OS);
245     else
246       OS << "null";
247     break;
248   case Extend:
249     OS << "Extend";
250     break;
251   case Ignore:
252     OS << "Ignore";
253     break;
254   case InAlloca:
255     OS << "InAlloca Offset=" << getInAllocaFieldIndex();
256     break;
257   case Indirect:
258     OS << "Indirect Align=" << getIndirectAlign().getQuantity()
259        << " ByVal=" << getIndirectByVal()
260        << " Realign=" << getIndirectRealign();
261     break;
262   case IndirectAliased:
263     OS << "Indirect Align=" << getIndirectAlign().getQuantity()
264        << " AadrSpace=" << getIndirectAddrSpace()
265        << " Realign=" << getIndirectRealign();
266     break;
267   case Expand:
268     OS << "Expand";
269     break;
270   case CoerceAndExpand:
271     OS << "CoerceAndExpand Type=";
272     getCoerceAndExpandType()->print(OS);
273     break;
274   }
275   OS << ")\n";
276 }
277 
278 // Dynamically round a pointer up to a multiple of the given alignment.
279 static llvm::Value *emitRoundPointerUpToAlignment(CodeGenFunction &CGF,
280                                                   llvm::Value *Ptr,
281                                                   CharUnits Align) {
282   llvm::Value *PtrAsInt = Ptr;
283   // OverflowArgArea = (OverflowArgArea + Align - 1) & -Align;
284   PtrAsInt = CGF.Builder.CreatePtrToInt(PtrAsInt, CGF.IntPtrTy);
285   PtrAsInt = CGF.Builder.CreateAdd(PtrAsInt,
286         llvm::ConstantInt::get(CGF.IntPtrTy, Align.getQuantity() - 1));
287   PtrAsInt = CGF.Builder.CreateAnd(PtrAsInt,
288            llvm::ConstantInt::get(CGF.IntPtrTy, -Align.getQuantity()));
289   PtrAsInt = CGF.Builder.CreateIntToPtr(PtrAsInt,
290                                         Ptr->getType(),
291                                         Ptr->getName() + ".aligned");
292   return PtrAsInt;
293 }
294 
295 /// Emit va_arg for a platform using the common void* representation,
296 /// where arguments are simply emitted in an array of slots on the stack.
297 ///
298 /// This version implements the core direct-value passing rules.
299 ///
300 /// \param SlotSize - The size and alignment of a stack slot.
301 ///   Each argument will be allocated to a multiple of this number of
302 ///   slots, and all the slots will be aligned to this value.
303 /// \param AllowHigherAlign - The slot alignment is not a cap;
304 ///   an argument type with an alignment greater than the slot size
305 ///   will be emitted on a higher-alignment address, potentially
306 ///   leaving one or more empty slots behind as padding.  If this
307 ///   is false, the returned address might be less-aligned than
308 ///   DirectAlign.
309 static Address emitVoidPtrDirectVAArg(CodeGenFunction &CGF,
310                                       Address VAListAddr,
311                                       llvm::Type *DirectTy,
312                                       CharUnits DirectSize,
313                                       CharUnits DirectAlign,
314                                       CharUnits SlotSize,
315                                       bool AllowHigherAlign) {
316   // Cast the element type to i8* if necessary.  Some platforms define
317   // va_list as a struct containing an i8* instead of just an i8*.
318   if (VAListAddr.getElementType() != CGF.Int8PtrTy)
319     VAListAddr = CGF.Builder.CreateElementBitCast(VAListAddr, CGF.Int8PtrTy);
320 
321   llvm::Value *Ptr = CGF.Builder.CreateLoad(VAListAddr, "argp.cur");
322 
323   // If the CC aligns values higher than the slot size, do so if needed.
324   Address Addr = Address::invalid();
325   if (AllowHigherAlign && DirectAlign > SlotSize) {
326     Addr = Address(emitRoundPointerUpToAlignment(CGF, Ptr, DirectAlign),
327                                                  DirectAlign);
328   } else {
329     Addr = Address(Ptr, SlotSize);
330   }
331 
332   // Advance the pointer past the argument, then store that back.
333   CharUnits FullDirectSize = DirectSize.alignTo(SlotSize);
334   Address NextPtr =
335       CGF.Builder.CreateConstInBoundsByteGEP(Addr, FullDirectSize, "argp.next");
336   CGF.Builder.CreateStore(NextPtr.getPointer(), VAListAddr);
337 
338   // If the argument is smaller than a slot, and this is a big-endian
339   // target, the argument will be right-adjusted in its slot.
340   if (DirectSize < SlotSize && CGF.CGM.getDataLayout().isBigEndian() &&
341       !DirectTy->isStructTy()) {
342     Addr = CGF.Builder.CreateConstInBoundsByteGEP(Addr, SlotSize - DirectSize);
343   }
344 
345   Addr = CGF.Builder.CreateElementBitCast(Addr, DirectTy);
346   return Addr;
347 }
348 
349 /// Emit va_arg for a platform using the common void* representation,
350 /// where arguments are simply emitted in an array of slots on the stack.
351 ///
352 /// \param IsIndirect - Values of this type are passed indirectly.
353 /// \param ValueInfo - The size and alignment of this type, generally
354 ///   computed with getContext().getTypeInfoInChars(ValueTy).
355 /// \param SlotSizeAndAlign - The size and alignment of a stack slot.
356 ///   Each argument will be allocated to a multiple of this number of
357 ///   slots, and all the slots will be aligned to this value.
358 /// \param AllowHigherAlign - The slot alignment is not a cap;
359 ///   an argument type with an alignment greater than the slot size
360 ///   will be emitted on a higher-alignment address, potentially
361 ///   leaving one or more empty slots behind as padding.
362 static Address emitVoidPtrVAArg(CodeGenFunction &CGF, Address VAListAddr,
363                                 QualType ValueTy, bool IsIndirect,
364                                 TypeInfoChars ValueInfo,
365                                 CharUnits SlotSizeAndAlign,
366                                 bool AllowHigherAlign) {
367   // The size and alignment of the value that was passed directly.
368   CharUnits DirectSize, DirectAlign;
369   if (IsIndirect) {
370     DirectSize = CGF.getPointerSize();
371     DirectAlign = CGF.getPointerAlign();
372   } else {
373     DirectSize = ValueInfo.Width;
374     DirectAlign = ValueInfo.Align;
375   }
376 
377   // Cast the address we've calculated to the right type.
378   llvm::Type *DirectTy = CGF.ConvertTypeForMem(ValueTy);
379   if (IsIndirect)
380     DirectTy = DirectTy->getPointerTo(0);
381 
382   Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, DirectTy,
383                                         DirectSize, DirectAlign,
384                                         SlotSizeAndAlign,
385                                         AllowHigherAlign);
386 
387   if (IsIndirect) {
388     Addr = Address(CGF.Builder.CreateLoad(Addr), ValueInfo.Align);
389   }
390 
391   return Addr;
392 
393 }
394 
395 static Address emitMergePHI(CodeGenFunction &CGF,
396                             Address Addr1, llvm::BasicBlock *Block1,
397                             Address Addr2, llvm::BasicBlock *Block2,
398                             const llvm::Twine &Name = "") {
399   assert(Addr1.getType() == Addr2.getType());
400   llvm::PHINode *PHI = CGF.Builder.CreatePHI(Addr1.getType(), 2, Name);
401   PHI->addIncoming(Addr1.getPointer(), Block1);
402   PHI->addIncoming(Addr2.getPointer(), Block2);
403   CharUnits Align = std::min(Addr1.getAlignment(), Addr2.getAlignment());
404   return Address(PHI, Align);
405 }
406 
407 TargetCodeGenInfo::~TargetCodeGenInfo() = default;
408 
409 // If someone can figure out a general rule for this, that would be great.
410 // It's probably just doomed to be platform-dependent, though.
411 unsigned TargetCodeGenInfo::getSizeOfUnwindException() const {
412   // Verified for:
413   //   x86-64     FreeBSD, Linux, Darwin
414   //   x86-32     FreeBSD, Linux, Darwin
415   //   PowerPC    Linux, Darwin
416   //   ARM        Darwin (*not* EABI)
417   //   AArch64    Linux
418   return 32;
419 }
420 
421 bool TargetCodeGenInfo::isNoProtoCallVariadic(const CallArgList &args,
422                                      const FunctionNoProtoType *fnType) const {
423   // The following conventions are known to require this to be false:
424   //   x86_stdcall
425   //   MIPS
426   // For everything else, we just prefer false unless we opt out.
427   return false;
428 }
429 
430 void
431 TargetCodeGenInfo::getDependentLibraryOption(llvm::StringRef Lib,
432                                              llvm::SmallString<24> &Opt) const {
433   // This assumes the user is passing a library name like "rt" instead of a
434   // filename like "librt.a/so", and that they don't care whether it's static or
435   // dynamic.
436   Opt = "-l";
437   Opt += Lib;
438 }
439 
440 unsigned TargetCodeGenInfo::getOpenCLKernelCallingConv() const {
441   // OpenCL kernels are called via an explicit runtime API with arguments
442   // set with clSetKernelArg(), not as normal sub-functions.
443   // Return SPIR_KERNEL by default as the kernel calling convention to
444   // ensure the fingerprint is fixed such way that each OpenCL argument
445   // gets one matching argument in the produced kernel function argument
446   // list to enable feasible implementation of clSetKernelArg() with
447   // aggregates etc. In case we would use the default C calling conv here,
448   // clSetKernelArg() might break depending on the target-specific
449   // conventions; different targets might split structs passed as values
450   // to multiple function arguments etc.
451   return llvm::CallingConv::SPIR_KERNEL;
452 }
453 
454 llvm::Constant *TargetCodeGenInfo::getNullPointer(const CodeGen::CodeGenModule &CGM,
455     llvm::PointerType *T, QualType QT) const {
456   return llvm::ConstantPointerNull::get(T);
457 }
458 
459 LangAS TargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM,
460                                                    const VarDecl *D) const {
461   assert(!CGM.getLangOpts().OpenCL &&
462          !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) &&
463          "Address space agnostic languages only");
464   return D ? D->getType().getAddressSpace() : LangAS::Default;
465 }
466 
467 llvm::Value *TargetCodeGenInfo::performAddrSpaceCast(
468     CodeGen::CodeGenFunction &CGF, llvm::Value *Src, LangAS SrcAddr,
469     LangAS DestAddr, llvm::Type *DestTy, bool isNonNull) const {
470   // Since target may map different address spaces in AST to the same address
471   // space, an address space conversion may end up as a bitcast.
472   if (auto *C = dyn_cast<llvm::Constant>(Src))
473     return performAddrSpaceCast(CGF.CGM, C, SrcAddr, DestAddr, DestTy);
474   // Try to preserve the source's name to make IR more readable.
475   return CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
476       Src, DestTy, Src->hasName() ? Src->getName() + ".ascast" : "");
477 }
478 
479 llvm::Constant *
480 TargetCodeGenInfo::performAddrSpaceCast(CodeGenModule &CGM, llvm::Constant *Src,
481                                         LangAS SrcAddr, LangAS DestAddr,
482                                         llvm::Type *DestTy) const {
483   // Since target may map different address spaces in AST to the same address
484   // space, an address space conversion may end up as a bitcast.
485   return llvm::ConstantExpr::getPointerCast(Src, DestTy);
486 }
487 
488 llvm::SyncScope::ID
489 TargetCodeGenInfo::getLLVMSyncScopeID(const LangOptions &LangOpts,
490                                       SyncScope Scope,
491                                       llvm::AtomicOrdering Ordering,
492                                       llvm::LLVMContext &Ctx) const {
493   return Ctx.getOrInsertSyncScopeID(""); /* default sync scope */
494 }
495 
496 static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays);
497 
498 /// isEmptyField - Return true iff a the field is "empty", that is it
499 /// is an unnamed bit-field or an (array of) empty record(s).
500 static bool isEmptyField(ASTContext &Context, const FieldDecl *FD,
501                          bool AllowArrays) {
502   if (FD->isUnnamedBitfield())
503     return true;
504 
505   QualType FT = FD->getType();
506 
507   // Constant arrays of empty records count as empty, strip them off.
508   // Constant arrays of zero length always count as empty.
509   bool WasArray = false;
510   if (AllowArrays)
511     while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
512       if (AT->getSize() == 0)
513         return true;
514       FT = AT->getElementType();
515       // The [[no_unique_address]] special case below does not apply to
516       // arrays of C++ empty records, so we need to remember this fact.
517       WasArray = true;
518     }
519 
520   const RecordType *RT = FT->getAs<RecordType>();
521   if (!RT)
522     return false;
523 
524   // C++ record fields are never empty, at least in the Itanium ABI.
525   //
526   // FIXME: We should use a predicate for whether this behavior is true in the
527   // current ABI.
528   //
529   // The exception to the above rule are fields marked with the
530   // [[no_unique_address]] attribute (since C++20).  Those do count as empty
531   // according to the Itanium ABI.  The exception applies only to records,
532   // not arrays of records, so we must also check whether we stripped off an
533   // array type above.
534   if (isa<CXXRecordDecl>(RT->getDecl()) &&
535       (WasArray || !FD->hasAttr<NoUniqueAddressAttr>()))
536     return false;
537 
538   return isEmptyRecord(Context, FT, AllowArrays);
539 }
540 
541 /// isEmptyRecord - Return true iff a structure contains only empty
542 /// fields. Note that a structure with a flexible array member is not
543 /// considered empty.
544 static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) {
545   const RecordType *RT = T->getAs<RecordType>();
546   if (!RT)
547     return false;
548   const RecordDecl *RD = RT->getDecl();
549   if (RD->hasFlexibleArrayMember())
550     return false;
551 
552   // If this is a C++ record, check the bases first.
553   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
554     for (const auto &I : CXXRD->bases())
555       if (!isEmptyRecord(Context, I.getType(), true))
556         return false;
557 
558   for (const auto *I : RD->fields())
559     if (!isEmptyField(Context, I, AllowArrays))
560       return false;
561   return true;
562 }
563 
564 /// isSingleElementStruct - Determine if a structure is a "single
565 /// element struct", i.e. it has exactly one non-empty field or
566 /// exactly one field which is itself a single element
567 /// struct. Structures with flexible array members are never
568 /// considered single element structs.
569 ///
570 /// \return The field declaration for the single non-empty field, if
571 /// it exists.
572 static const Type *isSingleElementStruct(QualType T, ASTContext &Context) {
573   const RecordType *RT = T->getAs<RecordType>();
574   if (!RT)
575     return nullptr;
576 
577   const RecordDecl *RD = RT->getDecl();
578   if (RD->hasFlexibleArrayMember())
579     return nullptr;
580 
581   const Type *Found = nullptr;
582 
583   // If this is a C++ record, check the bases first.
584   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
585     for (const auto &I : CXXRD->bases()) {
586       // Ignore empty records.
587       if (isEmptyRecord(Context, I.getType(), true))
588         continue;
589 
590       // If we already found an element then this isn't a single-element struct.
591       if (Found)
592         return nullptr;
593 
594       // If this is non-empty and not a single element struct, the composite
595       // cannot be a single element struct.
596       Found = isSingleElementStruct(I.getType(), Context);
597       if (!Found)
598         return nullptr;
599     }
600   }
601 
602   // Check for single element.
603   for (const auto *FD : RD->fields()) {
604     QualType FT = FD->getType();
605 
606     // Ignore empty fields.
607     if (isEmptyField(Context, FD, true))
608       continue;
609 
610     // If we already found an element then this isn't a single-element
611     // struct.
612     if (Found)
613       return nullptr;
614 
615     // Treat single element arrays as the element.
616     while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
617       if (AT->getSize().getZExtValue() != 1)
618         break;
619       FT = AT->getElementType();
620     }
621 
622     if (!isAggregateTypeForABI(FT)) {
623       Found = FT.getTypePtr();
624     } else {
625       Found = isSingleElementStruct(FT, Context);
626       if (!Found)
627         return nullptr;
628     }
629   }
630 
631   // We don't consider a struct a single-element struct if it has
632   // padding beyond the element type.
633   if (Found && Context.getTypeSize(Found) != Context.getTypeSize(T))
634     return nullptr;
635 
636   return Found;
637 }
638 
639 namespace {
640 Address EmitVAArgInstr(CodeGenFunction &CGF, Address VAListAddr, QualType Ty,
641                        const ABIArgInfo &AI) {
642   // This default implementation defers to the llvm backend's va_arg
643   // instruction. It can handle only passing arguments directly
644   // (typically only handled in the backend for primitive types), or
645   // aggregates passed indirectly by pointer (NOTE: if the "byval"
646   // flag has ABI impact in the callee, this implementation cannot
647   // work.)
648 
649   // Only a few cases are covered here at the moment -- those needed
650   // by the default abi.
651   llvm::Value *Val;
652 
653   if (AI.isIndirect()) {
654     assert(!AI.getPaddingType() &&
655            "Unexpected PaddingType seen in arginfo in generic VAArg emitter!");
656     assert(
657         !AI.getIndirectRealign() &&
658         "Unexpected IndirectRealign seen in arginfo in generic VAArg emitter!");
659 
660     auto TyInfo = CGF.getContext().getTypeInfoInChars(Ty);
661     CharUnits TyAlignForABI = TyInfo.Align;
662 
663     llvm::Type *BaseTy =
664         llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
665     llvm::Value *Addr =
666         CGF.Builder.CreateVAArg(VAListAddr.getPointer(), BaseTy);
667     return Address(Addr, TyAlignForABI);
668   } else {
669     assert((AI.isDirect() || AI.isExtend()) &&
670            "Unexpected ArgInfo Kind in generic VAArg emitter!");
671 
672     assert(!AI.getInReg() &&
673            "Unexpected InReg seen in arginfo in generic VAArg emitter!");
674     assert(!AI.getPaddingType() &&
675            "Unexpected PaddingType seen in arginfo in generic VAArg emitter!");
676     assert(!AI.getDirectOffset() &&
677            "Unexpected DirectOffset seen in arginfo in generic VAArg emitter!");
678     assert(!AI.getCoerceToType() &&
679            "Unexpected CoerceToType seen in arginfo in generic VAArg emitter!");
680 
681     Address Temp = CGF.CreateMemTemp(Ty, "varet");
682     Val = CGF.Builder.CreateVAArg(VAListAddr.getPointer(), CGF.ConvertType(Ty));
683     CGF.Builder.CreateStore(Val, Temp);
684     return Temp;
685   }
686 }
687 
688 /// DefaultABIInfo - The default implementation for ABI specific
689 /// details. This implementation provides information which results in
690 /// self-consistent and sensible LLVM IR generation, but does not
691 /// conform to any particular ABI.
692 class DefaultABIInfo : public ABIInfo {
693 public:
694   DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
695 
696   ABIArgInfo classifyReturnType(QualType RetTy) const;
697   ABIArgInfo classifyArgumentType(QualType RetTy) const;
698 
699   void computeInfo(CGFunctionInfo &FI) const override {
700     if (!getCXXABI().classifyReturnType(FI))
701       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
702     for (auto &I : FI.arguments())
703       I.info = classifyArgumentType(I.type);
704   }
705 
706   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
707                     QualType Ty) const override {
708     return EmitVAArgInstr(CGF, VAListAddr, Ty, classifyArgumentType(Ty));
709   }
710 };
711 
712 class DefaultTargetCodeGenInfo : public TargetCodeGenInfo {
713 public:
714   DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
715       : TargetCodeGenInfo(std::make_unique<DefaultABIInfo>(CGT)) {}
716 };
717 
718 ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const {
719   Ty = useFirstFieldIfTransparentUnion(Ty);
720 
721   if (isAggregateTypeForABI(Ty)) {
722     // Records with non-trivial destructors/copy-constructors should not be
723     // passed by value.
724     if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
725       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
726 
727     return getNaturalAlignIndirect(Ty);
728   }
729 
730   // Treat an enum type as its underlying type.
731   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
732     Ty = EnumTy->getDecl()->getIntegerType();
733 
734   ASTContext &Context = getContext();
735   if (const auto *EIT = Ty->getAs<ExtIntType>())
736     if (EIT->getNumBits() >
737         Context.getTypeSize(Context.getTargetInfo().hasInt128Type()
738                                 ? Context.Int128Ty
739                                 : Context.LongLongTy))
740       return getNaturalAlignIndirect(Ty);
741 
742   return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
743                                             : ABIArgInfo::getDirect());
744 }
745 
746 ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const {
747   if (RetTy->isVoidType())
748     return ABIArgInfo::getIgnore();
749 
750   if (isAggregateTypeForABI(RetTy))
751     return getNaturalAlignIndirect(RetTy);
752 
753   // Treat an enum type as its underlying type.
754   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
755     RetTy = EnumTy->getDecl()->getIntegerType();
756 
757   if (const auto *EIT = RetTy->getAs<ExtIntType>())
758     if (EIT->getNumBits() >
759         getContext().getTypeSize(getContext().getTargetInfo().hasInt128Type()
760                                      ? getContext().Int128Ty
761                                      : getContext().LongLongTy))
762       return getNaturalAlignIndirect(RetTy);
763 
764   return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
765                                                : ABIArgInfo::getDirect());
766 }
767 
768 //===----------------------------------------------------------------------===//
769 // WebAssembly ABI Implementation
770 //
771 // This is a very simple ABI that relies a lot on DefaultABIInfo.
772 //===----------------------------------------------------------------------===//
773 
774 class WebAssemblyABIInfo final : public SwiftABIInfo {
775 public:
776   enum ABIKind {
777     MVP = 0,
778     ExperimentalMV = 1,
779   };
780 
781 private:
782   DefaultABIInfo defaultInfo;
783   ABIKind Kind;
784 
785 public:
786   explicit WebAssemblyABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind)
787       : SwiftABIInfo(CGT), defaultInfo(CGT), Kind(Kind) {}
788 
789 private:
790   ABIArgInfo classifyReturnType(QualType RetTy) const;
791   ABIArgInfo classifyArgumentType(QualType Ty) const;
792 
793   // DefaultABIInfo's classifyReturnType and classifyArgumentType are
794   // non-virtual, but computeInfo and EmitVAArg are virtual, so we
795   // overload them.
796   void computeInfo(CGFunctionInfo &FI) const override {
797     if (!getCXXABI().classifyReturnType(FI))
798       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
799     for (auto &Arg : FI.arguments())
800       Arg.info = classifyArgumentType(Arg.type);
801   }
802 
803   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
804                     QualType Ty) const override;
805 
806   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
807                                     bool asReturnValue) const override {
808     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
809   }
810 
811   bool isSwiftErrorInRegister() const override {
812     return false;
813   }
814 };
815 
816 class WebAssemblyTargetCodeGenInfo final : public TargetCodeGenInfo {
817 public:
818   explicit WebAssemblyTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
819                                         WebAssemblyABIInfo::ABIKind K)
820       : TargetCodeGenInfo(std::make_unique<WebAssemblyABIInfo>(CGT, K)) {}
821 
822   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
823                            CodeGen::CodeGenModule &CGM) const override {
824     TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
825     if (const auto *FD = dyn_cast_or_null<FunctionDecl>(D)) {
826       if (const auto *Attr = FD->getAttr<WebAssemblyImportModuleAttr>()) {
827         llvm::Function *Fn = cast<llvm::Function>(GV);
828         llvm::AttrBuilder B;
829         B.addAttribute("wasm-import-module", Attr->getImportModule());
830         Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
831       }
832       if (const auto *Attr = FD->getAttr<WebAssemblyImportNameAttr>()) {
833         llvm::Function *Fn = cast<llvm::Function>(GV);
834         llvm::AttrBuilder B;
835         B.addAttribute("wasm-import-name", Attr->getImportName());
836         Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
837       }
838       if (const auto *Attr = FD->getAttr<WebAssemblyExportNameAttr>()) {
839         llvm::Function *Fn = cast<llvm::Function>(GV);
840         llvm::AttrBuilder B;
841         B.addAttribute("wasm-export-name", Attr->getExportName());
842         Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
843       }
844     }
845 
846     if (auto *FD = dyn_cast_or_null<FunctionDecl>(D)) {
847       llvm::Function *Fn = cast<llvm::Function>(GV);
848       if (!FD->doesThisDeclarationHaveABody() && !FD->hasPrototype())
849         Fn->addFnAttr("no-prototype");
850     }
851   }
852 };
853 
854 /// Classify argument of given type \p Ty.
855 ABIArgInfo WebAssemblyABIInfo::classifyArgumentType(QualType Ty) const {
856   Ty = useFirstFieldIfTransparentUnion(Ty);
857 
858   if (isAggregateTypeForABI(Ty)) {
859     // Records with non-trivial destructors/copy-constructors should not be
860     // passed by value.
861     if (auto RAA = getRecordArgABI(Ty, getCXXABI()))
862       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
863     // Ignore empty structs/unions.
864     if (isEmptyRecord(getContext(), Ty, true))
865       return ABIArgInfo::getIgnore();
866     // Lower single-element structs to just pass a regular value. TODO: We
867     // could do reasonable-size multiple-element structs too, using getExpand(),
868     // though watch out for things like bitfields.
869     if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
870       return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
871     // For the experimental multivalue ABI, fully expand all other aggregates
872     if (Kind == ABIKind::ExperimentalMV) {
873       const RecordType *RT = Ty->getAs<RecordType>();
874       assert(RT);
875       bool HasBitField = false;
876       for (auto *Field : RT->getDecl()->fields()) {
877         if (Field->isBitField()) {
878           HasBitField = true;
879           break;
880         }
881       }
882       if (!HasBitField)
883         return ABIArgInfo::getExpand();
884     }
885   }
886 
887   // Otherwise just do the default thing.
888   return defaultInfo.classifyArgumentType(Ty);
889 }
890 
891 ABIArgInfo WebAssemblyABIInfo::classifyReturnType(QualType RetTy) const {
892   if (isAggregateTypeForABI(RetTy)) {
893     // Records with non-trivial destructors/copy-constructors should not be
894     // returned by value.
895     if (!getRecordArgABI(RetTy, getCXXABI())) {
896       // Ignore empty structs/unions.
897       if (isEmptyRecord(getContext(), RetTy, true))
898         return ABIArgInfo::getIgnore();
899       // Lower single-element structs to just return a regular value. TODO: We
900       // could do reasonable-size multiple-element structs too, using
901       // ABIArgInfo::getDirect().
902       if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
903         return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
904       // For the experimental multivalue ABI, return all other aggregates
905       if (Kind == ABIKind::ExperimentalMV)
906         return ABIArgInfo::getDirect();
907     }
908   }
909 
910   // Otherwise just do the default thing.
911   return defaultInfo.classifyReturnType(RetTy);
912 }
913 
914 Address WebAssemblyABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
915                                       QualType Ty) const {
916   bool IsIndirect = isAggregateTypeForABI(Ty) &&
917                     !isEmptyRecord(getContext(), Ty, true) &&
918                     !isSingleElementStruct(Ty, getContext());
919   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
920                           getContext().getTypeInfoInChars(Ty),
921                           CharUnits::fromQuantity(4),
922                           /*AllowHigherAlign=*/true);
923 }
924 
925 //===----------------------------------------------------------------------===//
926 // le32/PNaCl bitcode ABI Implementation
927 //
928 // This is a simplified version of the x86_32 ABI.  Arguments and return values
929 // are always passed on the stack.
930 //===----------------------------------------------------------------------===//
931 
932 class PNaClABIInfo : public ABIInfo {
933  public:
934   PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
935 
936   ABIArgInfo classifyReturnType(QualType RetTy) const;
937   ABIArgInfo classifyArgumentType(QualType RetTy) const;
938 
939   void computeInfo(CGFunctionInfo &FI) const override;
940   Address EmitVAArg(CodeGenFunction &CGF,
941                     Address VAListAddr, QualType Ty) const override;
942 };
943 
944 class PNaClTargetCodeGenInfo : public TargetCodeGenInfo {
945  public:
946    PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
947        : TargetCodeGenInfo(std::make_unique<PNaClABIInfo>(CGT)) {}
948 };
949 
950 void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const {
951   if (!getCXXABI().classifyReturnType(FI))
952     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
953 
954   for (auto &I : FI.arguments())
955     I.info = classifyArgumentType(I.type);
956 }
957 
958 Address PNaClABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
959                                 QualType Ty) const {
960   // The PNaCL ABI is a bit odd, in that varargs don't use normal
961   // function classification. Structs get passed directly for varargs
962   // functions, through a rewriting transform in
963   // pnacl-llvm/lib/Transforms/NaCl/ExpandVarArgs.cpp, which allows
964   // this target to actually support a va_arg instructions with an
965   // aggregate type, unlike other targets.
966   return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
967 }
968 
969 /// Classify argument of given type \p Ty.
970 ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const {
971   if (isAggregateTypeForABI(Ty)) {
972     if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
973       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
974     return getNaturalAlignIndirect(Ty);
975   } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
976     // Treat an enum type as its underlying type.
977     Ty = EnumTy->getDecl()->getIntegerType();
978   } else if (Ty->isFloatingType()) {
979     // Floating-point types don't go inreg.
980     return ABIArgInfo::getDirect();
981   } else if (const auto *EIT = Ty->getAs<ExtIntType>()) {
982     // Treat extended integers as integers if <=64, otherwise pass indirectly.
983     if (EIT->getNumBits() > 64)
984       return getNaturalAlignIndirect(Ty);
985     return ABIArgInfo::getDirect();
986   }
987 
988   return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
989                                             : ABIArgInfo::getDirect());
990 }
991 
992 ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const {
993   if (RetTy->isVoidType())
994     return ABIArgInfo::getIgnore();
995 
996   // In the PNaCl ABI we always return records/structures on the stack.
997   if (isAggregateTypeForABI(RetTy))
998     return getNaturalAlignIndirect(RetTy);
999 
1000   // Treat extended integers as integers if <=64, otherwise pass indirectly.
1001   if (const auto *EIT = RetTy->getAs<ExtIntType>()) {
1002     if (EIT->getNumBits() > 64)
1003       return getNaturalAlignIndirect(RetTy);
1004     return ABIArgInfo::getDirect();
1005   }
1006 
1007   // Treat an enum type as its underlying type.
1008   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
1009     RetTy = EnumTy->getDecl()->getIntegerType();
1010 
1011   return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
1012                                                : ABIArgInfo::getDirect());
1013 }
1014 
1015 /// IsX86_MMXType - Return true if this is an MMX type.
1016 bool IsX86_MMXType(llvm::Type *IRType) {
1017   // Return true if the type is an MMX type <2 x i32>, <4 x i16>, or <8 x i8>.
1018   return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 &&
1019     cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() &&
1020     IRType->getScalarSizeInBits() != 64;
1021 }
1022 
1023 static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
1024                                           StringRef Constraint,
1025                                           llvm::Type* Ty) {
1026   bool IsMMXCons = llvm::StringSwitch<bool>(Constraint)
1027                      .Cases("y", "&y", "^Ym", true)
1028                      .Default(false);
1029   if (IsMMXCons && Ty->isVectorTy()) {
1030     if (cast<llvm::VectorType>(Ty)->getPrimitiveSizeInBits().getFixedSize() !=
1031         64) {
1032       // Invalid MMX constraint
1033       return nullptr;
1034     }
1035 
1036     return llvm::Type::getX86_MMXTy(CGF.getLLVMContext());
1037   }
1038 
1039   // No operation needed
1040   return Ty;
1041 }
1042 
1043 /// Returns true if this type can be passed in SSE registers with the
1044 /// X86_VectorCall calling convention. Shared between x86_32 and x86_64.
1045 static bool isX86VectorTypeForVectorCall(ASTContext &Context, QualType Ty) {
1046   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
1047     if (BT->isFloatingPoint() && BT->getKind() != BuiltinType::Half) {
1048       if (BT->getKind() == BuiltinType::LongDouble) {
1049         if (&Context.getTargetInfo().getLongDoubleFormat() ==
1050             &llvm::APFloat::x87DoubleExtended())
1051           return false;
1052       }
1053       return true;
1054     }
1055   } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
1056     // vectorcall can pass XMM, YMM, and ZMM vectors. We don't pass SSE1 MMX
1057     // registers specially.
1058     unsigned VecSize = Context.getTypeSize(VT);
1059     if (VecSize == 128 || VecSize == 256 || VecSize == 512)
1060       return true;
1061   }
1062   return false;
1063 }
1064 
1065 /// Returns true if this aggregate is small enough to be passed in SSE registers
1066 /// in the X86_VectorCall calling convention. Shared between x86_32 and x86_64.
1067 static bool isX86VectorCallAggregateSmallEnough(uint64_t NumMembers) {
1068   return NumMembers <= 4;
1069 }
1070 
1071 /// Returns a Homogeneous Vector Aggregate ABIArgInfo, used in X86.
1072 static ABIArgInfo getDirectX86Hva(llvm::Type* T = nullptr) {
1073   auto AI = ABIArgInfo::getDirect(T);
1074   AI.setInReg(true);
1075   AI.setCanBeFlattened(false);
1076   return AI;
1077 }
1078 
1079 //===----------------------------------------------------------------------===//
1080 // X86-32 ABI Implementation
1081 //===----------------------------------------------------------------------===//
1082 
1083 /// Similar to llvm::CCState, but for Clang.
1084 struct CCState {
1085   CCState(CGFunctionInfo &FI)
1086       : IsPreassigned(FI.arg_size()), CC(FI.getCallingConvention()) {}
1087 
1088   llvm::SmallBitVector IsPreassigned;
1089   unsigned CC = CallingConv::CC_C;
1090   unsigned FreeRegs = 0;
1091   unsigned FreeSSERegs = 0;
1092 };
1093 
1094 /// X86_32ABIInfo - The X86-32 ABI information.
1095 class X86_32ABIInfo : public SwiftABIInfo {
1096   enum Class {
1097     Integer,
1098     Float
1099   };
1100 
1101   static const unsigned MinABIStackAlignInBytes = 4;
1102 
1103   bool IsDarwinVectorABI;
1104   bool IsRetSmallStructInRegABI;
1105   bool IsWin32StructABI;
1106   bool IsSoftFloatABI;
1107   bool IsMCUABI;
1108   unsigned DefaultNumRegisterParameters;
1109 
1110   static bool isRegisterSize(unsigned Size) {
1111     return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
1112   }
1113 
1114   bool isHomogeneousAggregateBaseType(QualType Ty) const override {
1115     // FIXME: Assumes vectorcall is in use.
1116     return isX86VectorTypeForVectorCall(getContext(), Ty);
1117   }
1118 
1119   bool isHomogeneousAggregateSmallEnough(const Type *Ty,
1120                                          uint64_t NumMembers) const override {
1121     // FIXME: Assumes vectorcall is in use.
1122     return isX86VectorCallAggregateSmallEnough(NumMembers);
1123   }
1124 
1125   bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context) const;
1126 
1127   /// getIndirectResult - Give a source type \arg Ty, return a suitable result
1128   /// such that the argument will be passed in memory.
1129   ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
1130 
1131   ABIArgInfo getIndirectReturnResult(QualType Ty, CCState &State) const;
1132 
1133   /// Return the alignment to use for the given type on the stack.
1134   unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const;
1135 
1136   Class classify(QualType Ty) const;
1137   ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const;
1138   ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
1139 
1140   /// Updates the number of available free registers, returns
1141   /// true if any registers were allocated.
1142   bool updateFreeRegs(QualType Ty, CCState &State) const;
1143 
1144   bool shouldAggregateUseDirect(QualType Ty, CCState &State, bool &InReg,
1145                                 bool &NeedsPadding) const;
1146   bool shouldPrimitiveUseInReg(QualType Ty, CCState &State) const;
1147 
1148   bool canExpandIndirectArgument(QualType Ty) const;
1149 
1150   /// Rewrite the function info so that all memory arguments use
1151   /// inalloca.
1152   void rewriteWithInAlloca(CGFunctionInfo &FI) const;
1153 
1154   void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
1155                            CharUnits &StackOffset, ABIArgInfo &Info,
1156                            QualType Type) const;
1157   void runVectorCallFirstPass(CGFunctionInfo &FI, CCState &State) const;
1158 
1159 public:
1160 
1161   void computeInfo(CGFunctionInfo &FI) const override;
1162   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
1163                     QualType Ty) const override;
1164 
1165   X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
1166                 bool RetSmallStructInRegABI, bool Win32StructABI,
1167                 unsigned NumRegisterParameters, bool SoftFloatABI)
1168     : SwiftABIInfo(CGT), IsDarwinVectorABI(DarwinVectorABI),
1169       IsRetSmallStructInRegABI(RetSmallStructInRegABI),
1170       IsWin32StructABI(Win32StructABI),
1171       IsSoftFloatABI(SoftFloatABI),
1172       IsMCUABI(CGT.getTarget().getTriple().isOSIAMCU()),
1173       DefaultNumRegisterParameters(NumRegisterParameters) {}
1174 
1175   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
1176                                     bool asReturnValue) const override {
1177     // LLVM's x86-32 lowering currently only assigns up to three
1178     // integer registers and three fp registers.  Oddly, it'll use up to
1179     // four vector registers for vectors, but those can overlap with the
1180     // scalar registers.
1181     return occupiesMoreThan(CGT, scalars, /*total*/ 3);
1182   }
1183 
1184   bool isSwiftErrorInRegister() const override {
1185     // x86-32 lowering does not support passing swifterror in a register.
1186     return false;
1187   }
1188 };
1189 
1190 class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
1191 public:
1192   X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
1193                           bool RetSmallStructInRegABI, bool Win32StructABI,
1194                           unsigned NumRegisterParameters, bool SoftFloatABI)
1195       : TargetCodeGenInfo(std::make_unique<X86_32ABIInfo>(
1196             CGT, DarwinVectorABI, RetSmallStructInRegABI, Win32StructABI,
1197             NumRegisterParameters, SoftFloatABI)) {}
1198 
1199   static bool isStructReturnInRegABI(
1200       const llvm::Triple &Triple, const CodeGenOptions &Opts);
1201 
1202   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
1203                            CodeGen::CodeGenModule &CGM) const override;
1204 
1205   int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
1206     // Darwin uses different dwarf register numbers for EH.
1207     if (CGM.getTarget().getTriple().isOSDarwin()) return 5;
1208     return 4;
1209   }
1210 
1211   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
1212                                llvm::Value *Address) const override;
1213 
1214   llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
1215                                   StringRef Constraint,
1216                                   llvm::Type* Ty) const override {
1217     return X86AdjustInlineAsmType(CGF, Constraint, Ty);
1218   }
1219 
1220   void addReturnRegisterOutputs(CodeGenFunction &CGF, LValue ReturnValue,
1221                                 std::string &Constraints,
1222                                 std::vector<llvm::Type *> &ResultRegTypes,
1223                                 std::vector<llvm::Type *> &ResultTruncRegTypes,
1224                                 std::vector<LValue> &ResultRegDests,
1225                                 std::string &AsmString,
1226                                 unsigned NumOutputs) const override;
1227 
1228   llvm::Constant *
1229   getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
1230     unsigned Sig = (0xeb << 0) |  // jmp rel8
1231                    (0x06 << 8) |  //           .+0x08
1232                    ('v' << 16) |
1233                    ('2' << 24);
1234     return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
1235   }
1236 
1237   StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
1238     return "movl\t%ebp, %ebp"
1239            "\t\t// marker for objc_retainAutoreleaseReturnValue";
1240   }
1241 };
1242 
1243 }
1244 
1245 /// Rewrite input constraint references after adding some output constraints.
1246 /// In the case where there is one output and one input and we add one output,
1247 /// we need to replace all operand references greater than or equal to 1:
1248 ///     mov $0, $1
1249 ///     mov eax, $1
1250 /// The result will be:
1251 ///     mov $0, $2
1252 ///     mov eax, $2
1253 static void rewriteInputConstraintReferences(unsigned FirstIn,
1254                                              unsigned NumNewOuts,
1255                                              std::string &AsmString) {
1256   std::string Buf;
1257   llvm::raw_string_ostream OS(Buf);
1258   size_t Pos = 0;
1259   while (Pos < AsmString.size()) {
1260     size_t DollarStart = AsmString.find('$', Pos);
1261     if (DollarStart == std::string::npos)
1262       DollarStart = AsmString.size();
1263     size_t DollarEnd = AsmString.find_first_not_of('$', DollarStart);
1264     if (DollarEnd == std::string::npos)
1265       DollarEnd = AsmString.size();
1266     OS << StringRef(&AsmString[Pos], DollarEnd - Pos);
1267     Pos = DollarEnd;
1268     size_t NumDollars = DollarEnd - DollarStart;
1269     if (NumDollars % 2 != 0 && Pos < AsmString.size()) {
1270       // We have an operand reference.
1271       size_t DigitStart = Pos;
1272       if (AsmString[DigitStart] == '{') {
1273         OS << '{';
1274         ++DigitStart;
1275       }
1276       size_t DigitEnd = AsmString.find_first_not_of("0123456789", DigitStart);
1277       if (DigitEnd == std::string::npos)
1278         DigitEnd = AsmString.size();
1279       StringRef OperandStr(&AsmString[DigitStart], DigitEnd - DigitStart);
1280       unsigned OperandIndex;
1281       if (!OperandStr.getAsInteger(10, OperandIndex)) {
1282         if (OperandIndex >= FirstIn)
1283           OperandIndex += NumNewOuts;
1284         OS << OperandIndex;
1285       } else {
1286         OS << OperandStr;
1287       }
1288       Pos = DigitEnd;
1289     }
1290   }
1291   AsmString = std::move(OS.str());
1292 }
1293 
1294 /// Add output constraints for EAX:EDX because they are return registers.
1295 void X86_32TargetCodeGenInfo::addReturnRegisterOutputs(
1296     CodeGenFunction &CGF, LValue ReturnSlot, std::string &Constraints,
1297     std::vector<llvm::Type *> &ResultRegTypes,
1298     std::vector<llvm::Type *> &ResultTruncRegTypes,
1299     std::vector<LValue> &ResultRegDests, std::string &AsmString,
1300     unsigned NumOutputs) const {
1301   uint64_t RetWidth = CGF.getContext().getTypeSize(ReturnSlot.getType());
1302 
1303   // Use the EAX constraint if the width is 32 or smaller and EAX:EDX if it is
1304   // larger.
1305   if (!Constraints.empty())
1306     Constraints += ',';
1307   if (RetWidth <= 32) {
1308     Constraints += "={eax}";
1309     ResultRegTypes.push_back(CGF.Int32Ty);
1310   } else {
1311     // Use the 'A' constraint for EAX:EDX.
1312     Constraints += "=A";
1313     ResultRegTypes.push_back(CGF.Int64Ty);
1314   }
1315 
1316   // Truncate EAX or EAX:EDX to an integer of the appropriate size.
1317   llvm::Type *CoerceTy = llvm::IntegerType::get(CGF.getLLVMContext(), RetWidth);
1318   ResultTruncRegTypes.push_back(CoerceTy);
1319 
1320   // Coerce the integer by bitcasting the return slot pointer.
1321   ReturnSlot.setAddress(CGF.Builder.CreateBitCast(ReturnSlot.getAddress(CGF),
1322                                                   CoerceTy->getPointerTo()));
1323   ResultRegDests.push_back(ReturnSlot);
1324 
1325   rewriteInputConstraintReferences(NumOutputs, 1, AsmString);
1326 }
1327 
1328 /// shouldReturnTypeInRegister - Determine if the given type should be
1329 /// returned in a register (for the Darwin and MCU ABI).
1330 bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
1331                                                ASTContext &Context) const {
1332   uint64_t Size = Context.getTypeSize(Ty);
1333 
1334   // For i386, type must be register sized.
1335   // For the MCU ABI, it only needs to be <= 8-byte
1336   if ((IsMCUABI && Size > 64) || (!IsMCUABI && !isRegisterSize(Size)))
1337    return false;
1338 
1339   if (Ty->isVectorType()) {
1340     // 64- and 128- bit vectors inside structures are not returned in
1341     // registers.
1342     if (Size == 64 || Size == 128)
1343       return false;
1344 
1345     return true;
1346   }
1347 
1348   // If this is a builtin, pointer, enum, complex type, member pointer, or
1349   // member function pointer it is ok.
1350   if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() ||
1351       Ty->isAnyComplexType() || Ty->isEnumeralType() ||
1352       Ty->isBlockPointerType() || Ty->isMemberPointerType())
1353     return true;
1354 
1355   // Arrays are treated like records.
1356   if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
1357     return shouldReturnTypeInRegister(AT->getElementType(), Context);
1358 
1359   // Otherwise, it must be a record type.
1360   const RecordType *RT = Ty->getAs<RecordType>();
1361   if (!RT) return false;
1362 
1363   // FIXME: Traverse bases here too.
1364 
1365   // Structure types are passed in register if all fields would be
1366   // passed in a register.
1367   for (const auto *FD : RT->getDecl()->fields()) {
1368     // Empty fields are ignored.
1369     if (isEmptyField(Context, FD, true))
1370       continue;
1371 
1372     // Check fields recursively.
1373     if (!shouldReturnTypeInRegister(FD->getType(), Context))
1374       return false;
1375   }
1376   return true;
1377 }
1378 
1379 static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
1380   // Treat complex types as the element type.
1381   if (const ComplexType *CTy = Ty->getAs<ComplexType>())
1382     Ty = CTy->getElementType();
1383 
1384   // Check for a type which we know has a simple scalar argument-passing
1385   // convention without any padding.  (We're specifically looking for 32
1386   // and 64-bit integer and integer-equivalents, float, and double.)
1387   if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() &&
1388       !Ty->isEnumeralType() && !Ty->isBlockPointerType())
1389     return false;
1390 
1391   uint64_t Size = Context.getTypeSize(Ty);
1392   return Size == 32 || Size == 64;
1393 }
1394 
1395 static bool addFieldSizes(ASTContext &Context, const RecordDecl *RD,
1396                           uint64_t &Size) {
1397   for (const auto *FD : RD->fields()) {
1398     // Scalar arguments on the stack get 4 byte alignment on x86. If the
1399     // argument is smaller than 32-bits, expanding the struct will create
1400     // alignment padding.
1401     if (!is32Or64BitBasicType(FD->getType(), Context))
1402       return false;
1403 
1404     // FIXME: Reject bit-fields wholesale; there are two problems, we don't know
1405     // how to expand them yet, and the predicate for telling if a bitfield still
1406     // counts as "basic" is more complicated than what we were doing previously.
1407     if (FD->isBitField())
1408       return false;
1409 
1410     Size += Context.getTypeSize(FD->getType());
1411   }
1412   return true;
1413 }
1414 
1415 static bool addBaseAndFieldSizes(ASTContext &Context, const CXXRecordDecl *RD,
1416                                  uint64_t &Size) {
1417   // Don't do this if there are any non-empty bases.
1418   for (const CXXBaseSpecifier &Base : RD->bases()) {
1419     if (!addBaseAndFieldSizes(Context, Base.getType()->getAsCXXRecordDecl(),
1420                               Size))
1421       return false;
1422   }
1423   if (!addFieldSizes(Context, RD, Size))
1424     return false;
1425   return true;
1426 }
1427 
1428 /// Test whether an argument type which is to be passed indirectly (on the
1429 /// stack) would have the equivalent layout if it was expanded into separate
1430 /// arguments. If so, we prefer to do the latter to avoid inhibiting
1431 /// optimizations.
1432 bool X86_32ABIInfo::canExpandIndirectArgument(QualType Ty) const {
1433   // We can only expand structure types.
1434   const RecordType *RT = Ty->getAs<RecordType>();
1435   if (!RT)
1436     return false;
1437   const RecordDecl *RD = RT->getDecl();
1438   uint64_t Size = 0;
1439   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
1440     if (!IsWin32StructABI) {
1441       // On non-Windows, we have to conservatively match our old bitcode
1442       // prototypes in order to be ABI-compatible at the bitcode level.
1443       if (!CXXRD->isCLike())
1444         return false;
1445     } else {
1446       // Don't do this for dynamic classes.
1447       if (CXXRD->isDynamicClass())
1448         return false;
1449     }
1450     if (!addBaseAndFieldSizes(getContext(), CXXRD, Size))
1451       return false;
1452   } else {
1453     if (!addFieldSizes(getContext(), RD, Size))
1454       return false;
1455   }
1456 
1457   // We can do this if there was no alignment padding.
1458   return Size == getContext().getTypeSize(Ty);
1459 }
1460 
1461 ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(QualType RetTy, CCState &State) const {
1462   // If the return value is indirect, then the hidden argument is consuming one
1463   // integer register.
1464   if (State.FreeRegs) {
1465     --State.FreeRegs;
1466     if (!IsMCUABI)
1467       return getNaturalAlignIndirectInReg(RetTy);
1468   }
1469   return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
1470 }
1471 
1472 ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy,
1473                                              CCState &State) const {
1474   if (RetTy->isVoidType())
1475     return ABIArgInfo::getIgnore();
1476 
1477   const Type *Base = nullptr;
1478   uint64_t NumElts = 0;
1479   if ((State.CC == llvm::CallingConv::X86_VectorCall ||
1480        State.CC == llvm::CallingConv::X86_RegCall) &&
1481       isHomogeneousAggregate(RetTy, Base, NumElts)) {
1482     // The LLVM struct type for such an aggregate should lower properly.
1483     return ABIArgInfo::getDirect();
1484   }
1485 
1486   if (const VectorType *VT = RetTy->getAs<VectorType>()) {
1487     // On Darwin, some vectors are returned in registers.
1488     if (IsDarwinVectorABI) {
1489       uint64_t Size = getContext().getTypeSize(RetTy);
1490 
1491       // 128-bit vectors are a special case; they are returned in
1492       // registers and we need to make sure to pick a type the LLVM
1493       // backend will like.
1494       if (Size == 128)
1495         return ABIArgInfo::getDirect(llvm::FixedVectorType::get(
1496             llvm::Type::getInt64Ty(getVMContext()), 2));
1497 
1498       // Always return in register if it fits in a general purpose
1499       // register, or if it is 64 bits and has a single element.
1500       if ((Size == 8 || Size == 16 || Size == 32) ||
1501           (Size == 64 && VT->getNumElements() == 1))
1502         return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
1503                                                             Size));
1504 
1505       return getIndirectReturnResult(RetTy, State);
1506     }
1507 
1508     return ABIArgInfo::getDirect();
1509   }
1510 
1511   if (isAggregateTypeForABI(RetTy)) {
1512     if (const RecordType *RT = RetTy->getAs<RecordType>()) {
1513       // Structures with flexible arrays are always indirect.
1514       if (RT->getDecl()->hasFlexibleArrayMember())
1515         return getIndirectReturnResult(RetTy, State);
1516     }
1517 
1518     // If specified, structs and unions are always indirect.
1519     if (!IsRetSmallStructInRegABI && !RetTy->isAnyComplexType())
1520       return getIndirectReturnResult(RetTy, State);
1521 
1522     // Ignore empty structs/unions.
1523     if (isEmptyRecord(getContext(), RetTy, true))
1524       return ABIArgInfo::getIgnore();
1525 
1526     // Small structures which are register sized are generally returned
1527     // in a register.
1528     if (shouldReturnTypeInRegister(RetTy, getContext())) {
1529       uint64_t Size = getContext().getTypeSize(RetTy);
1530 
1531       // As a special-case, if the struct is a "single-element" struct, and
1532       // the field is of type "float" or "double", return it in a
1533       // floating-point register. (MSVC does not apply this special case.)
1534       // We apply a similar transformation for pointer types to improve the
1535       // quality of the generated IR.
1536       if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
1537         if ((!IsWin32StructABI && SeltTy->isRealFloatingType())
1538             || SeltTy->hasPointerRepresentation())
1539           return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
1540 
1541       // FIXME: We should be able to narrow this integer in cases with dead
1542       // padding.
1543       return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
1544     }
1545 
1546     return getIndirectReturnResult(RetTy, State);
1547   }
1548 
1549   // Treat an enum type as its underlying type.
1550   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
1551     RetTy = EnumTy->getDecl()->getIntegerType();
1552 
1553   if (const auto *EIT = RetTy->getAs<ExtIntType>())
1554     if (EIT->getNumBits() > 64)
1555       return getIndirectReturnResult(RetTy, State);
1556 
1557   return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
1558                                                : ABIArgInfo::getDirect());
1559 }
1560 
1561 static bool isSIMDVectorType(ASTContext &Context, QualType Ty) {
1562   return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128;
1563 }
1564 
1565 static bool isRecordWithSIMDVectorType(ASTContext &Context, QualType Ty) {
1566   const RecordType *RT = Ty->getAs<RecordType>();
1567   if (!RT)
1568     return 0;
1569   const RecordDecl *RD = RT->getDecl();
1570 
1571   // If this is a C++ record, check the bases first.
1572   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
1573     for (const auto &I : CXXRD->bases())
1574       if (!isRecordWithSIMDVectorType(Context, I.getType()))
1575         return false;
1576 
1577   for (const auto *i : RD->fields()) {
1578     QualType FT = i->getType();
1579 
1580     if (isSIMDVectorType(Context, FT))
1581       return true;
1582 
1583     if (isRecordWithSIMDVectorType(Context, FT))
1584       return true;
1585   }
1586 
1587   return false;
1588 }
1589 
1590 unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
1591                                                  unsigned Align) const {
1592   // Otherwise, if the alignment is less than or equal to the minimum ABI
1593   // alignment, just use the default; the backend will handle this.
1594   if (Align <= MinABIStackAlignInBytes)
1595     return 0; // Use default alignment.
1596 
1597   // On non-Darwin, the stack type alignment is always 4.
1598   if (!IsDarwinVectorABI) {
1599     // Set explicit alignment, since we may need to realign the top.
1600     return MinABIStackAlignInBytes;
1601   }
1602 
1603   // Otherwise, if the type contains an SSE vector type, the alignment is 16.
1604   if (Align >= 16 && (isSIMDVectorType(getContext(), Ty) ||
1605                       isRecordWithSIMDVectorType(getContext(), Ty)))
1606     return 16;
1607 
1608   return MinABIStackAlignInBytes;
1609 }
1610 
1611 ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal,
1612                                             CCState &State) const {
1613   if (!ByVal) {
1614     if (State.FreeRegs) {
1615       --State.FreeRegs; // Non-byval indirects just use one pointer.
1616       if (!IsMCUABI)
1617         return getNaturalAlignIndirectInReg(Ty);
1618     }
1619     return getNaturalAlignIndirect(Ty, false);
1620   }
1621 
1622   // Compute the byval alignment.
1623   unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
1624   unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign);
1625   if (StackAlign == 0)
1626     return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true);
1627 
1628   // If the stack alignment is less than the type alignment, realign the
1629   // argument.
1630   bool Realign = TypeAlign > StackAlign;
1631   return ABIArgInfo::getIndirect(CharUnits::fromQuantity(StackAlign),
1632                                  /*ByVal=*/true, Realign);
1633 }
1634 
1635 X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const {
1636   const Type *T = isSingleElementStruct(Ty, getContext());
1637   if (!T)
1638     T = Ty.getTypePtr();
1639 
1640   if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
1641     BuiltinType::Kind K = BT->getKind();
1642     if (K == BuiltinType::Float || K == BuiltinType::Double)
1643       return Float;
1644   }
1645   return Integer;
1646 }
1647 
1648 bool X86_32ABIInfo::updateFreeRegs(QualType Ty, CCState &State) const {
1649   if (!IsSoftFloatABI) {
1650     Class C = classify(Ty);
1651     if (C == Float)
1652       return false;
1653   }
1654 
1655   unsigned Size = getContext().getTypeSize(Ty);
1656   unsigned SizeInRegs = (Size + 31) / 32;
1657 
1658   if (SizeInRegs == 0)
1659     return false;
1660 
1661   if (!IsMCUABI) {
1662     if (SizeInRegs > State.FreeRegs) {
1663       State.FreeRegs = 0;
1664       return false;
1665     }
1666   } else {
1667     // The MCU psABI allows passing parameters in-reg even if there are
1668     // earlier parameters that are passed on the stack. Also,
1669     // it does not allow passing >8-byte structs in-register,
1670     // even if there are 3 free registers available.
1671     if (SizeInRegs > State.FreeRegs || SizeInRegs > 2)
1672       return false;
1673   }
1674 
1675   State.FreeRegs -= SizeInRegs;
1676   return true;
1677 }
1678 
1679 bool X86_32ABIInfo::shouldAggregateUseDirect(QualType Ty, CCState &State,
1680                                              bool &InReg,
1681                                              bool &NeedsPadding) const {
1682   // On Windows, aggregates other than HFAs are never passed in registers, and
1683   // they do not consume register slots. Homogenous floating-point aggregates
1684   // (HFAs) have already been dealt with at this point.
1685   if (IsWin32StructABI && isAggregateTypeForABI(Ty))
1686     return false;
1687 
1688   NeedsPadding = false;
1689   InReg = !IsMCUABI;
1690 
1691   if (!updateFreeRegs(Ty, State))
1692     return false;
1693 
1694   if (IsMCUABI)
1695     return true;
1696 
1697   if (State.CC == llvm::CallingConv::X86_FastCall ||
1698       State.CC == llvm::CallingConv::X86_VectorCall ||
1699       State.CC == llvm::CallingConv::X86_RegCall) {
1700     if (getContext().getTypeSize(Ty) <= 32 && State.FreeRegs)
1701       NeedsPadding = true;
1702 
1703     return false;
1704   }
1705 
1706   return true;
1707 }
1708 
1709 bool X86_32ABIInfo::shouldPrimitiveUseInReg(QualType Ty, CCState &State) const {
1710   if (!updateFreeRegs(Ty, State))
1711     return false;
1712 
1713   if (IsMCUABI)
1714     return false;
1715 
1716   if (State.CC == llvm::CallingConv::X86_FastCall ||
1717       State.CC == llvm::CallingConv::X86_VectorCall ||
1718       State.CC == llvm::CallingConv::X86_RegCall) {
1719     if (getContext().getTypeSize(Ty) > 32)
1720       return false;
1721 
1722     return (Ty->isIntegralOrEnumerationType() || Ty->isPointerType() ||
1723         Ty->isReferenceType());
1724   }
1725 
1726   return true;
1727 }
1728 
1729 void X86_32ABIInfo::runVectorCallFirstPass(CGFunctionInfo &FI, CCState &State) const {
1730   // Vectorcall x86 works subtly different than in x64, so the format is
1731   // a bit different than the x64 version.  First, all vector types (not HVAs)
1732   // are assigned, with the first 6 ending up in the [XYZ]MM0-5 registers.
1733   // This differs from the x64 implementation, where the first 6 by INDEX get
1734   // registers.
1735   // In the second pass over the arguments, HVAs are passed in the remaining
1736   // vector registers if possible, or indirectly by address. The address will be
1737   // passed in ECX/EDX if available. Any other arguments are passed according to
1738   // the usual fastcall rules.
1739   MutableArrayRef<CGFunctionInfoArgInfo> Args = FI.arguments();
1740   for (int I = 0, E = Args.size(); I < E; ++I) {
1741     const Type *Base = nullptr;
1742     uint64_t NumElts = 0;
1743     const QualType &Ty = Args[I].type;
1744     if ((Ty->isVectorType() || Ty->isBuiltinType()) &&
1745         isHomogeneousAggregate(Ty, Base, NumElts)) {
1746       if (State.FreeSSERegs >= NumElts) {
1747         State.FreeSSERegs -= NumElts;
1748         Args[I].info = ABIArgInfo::getDirectInReg();
1749         State.IsPreassigned.set(I);
1750       }
1751     }
1752   }
1753 }
1754 
1755 ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
1756                                                CCState &State) const {
1757   // FIXME: Set alignment on indirect arguments.
1758   bool IsFastCall = State.CC == llvm::CallingConv::X86_FastCall;
1759   bool IsRegCall = State.CC == llvm::CallingConv::X86_RegCall;
1760   bool IsVectorCall = State.CC == llvm::CallingConv::X86_VectorCall;
1761 
1762   Ty = useFirstFieldIfTransparentUnion(Ty);
1763   TypeInfo TI = getContext().getTypeInfo(Ty);
1764 
1765   // Check with the C++ ABI first.
1766   const RecordType *RT = Ty->getAs<RecordType>();
1767   if (RT) {
1768     CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
1769     if (RAA == CGCXXABI::RAA_Indirect) {
1770       return getIndirectResult(Ty, false, State);
1771     } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
1772       // The field index doesn't matter, we'll fix it up later.
1773       return ABIArgInfo::getInAlloca(/*FieldIndex=*/0);
1774     }
1775   }
1776 
1777   // Regcall uses the concept of a homogenous vector aggregate, similar
1778   // to other targets.
1779   const Type *Base = nullptr;
1780   uint64_t NumElts = 0;
1781   if ((IsRegCall || IsVectorCall) &&
1782       isHomogeneousAggregate(Ty, Base, NumElts)) {
1783     if (State.FreeSSERegs >= NumElts) {
1784       State.FreeSSERegs -= NumElts;
1785 
1786       // Vectorcall passes HVAs directly and does not flatten them, but regcall
1787       // does.
1788       if (IsVectorCall)
1789         return getDirectX86Hva();
1790 
1791       if (Ty->isBuiltinType() || Ty->isVectorType())
1792         return ABIArgInfo::getDirect();
1793       return ABIArgInfo::getExpand();
1794     }
1795     return getIndirectResult(Ty, /*ByVal=*/false, State);
1796   }
1797 
1798   if (isAggregateTypeForABI(Ty)) {
1799     // Structures with flexible arrays are always indirect.
1800     // FIXME: This should not be byval!
1801     if (RT && RT->getDecl()->hasFlexibleArrayMember())
1802       return getIndirectResult(Ty, true, State);
1803 
1804     // Ignore empty structs/unions on non-Windows.
1805     if (!IsWin32StructABI && isEmptyRecord(getContext(), Ty, true))
1806       return ABIArgInfo::getIgnore();
1807 
1808     llvm::LLVMContext &LLVMContext = getVMContext();
1809     llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
1810     bool NeedsPadding = false;
1811     bool InReg;
1812     if (shouldAggregateUseDirect(Ty, State, InReg, NeedsPadding)) {
1813       unsigned SizeInRegs = (TI.Width + 31) / 32;
1814       SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32);
1815       llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
1816       if (InReg)
1817         return ABIArgInfo::getDirectInReg(Result);
1818       else
1819         return ABIArgInfo::getDirect(Result);
1820     }
1821     llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : nullptr;
1822 
1823     // Pass over-aligned aggregates on Windows indirectly. This behavior was
1824     // added in MSVC 2015.
1825     if (IsWin32StructABI && TI.AlignIsRequired && TI.Align > 32)
1826       return getIndirectResult(Ty, /*ByVal=*/false, State);
1827 
1828     // Expand small (<= 128-bit) record types when we know that the stack layout
1829     // of those arguments will match the struct. This is important because the
1830     // LLVM backend isn't smart enough to remove byval, which inhibits many
1831     // optimizations.
1832     // Don't do this for the MCU if there are still free integer registers
1833     // (see X86_64 ABI for full explanation).
1834     if (TI.Width <= 4 * 32 && (!IsMCUABI || State.FreeRegs == 0) &&
1835         canExpandIndirectArgument(Ty))
1836       return ABIArgInfo::getExpandWithPadding(
1837           IsFastCall || IsVectorCall || IsRegCall, PaddingType);
1838 
1839     return getIndirectResult(Ty, true, State);
1840   }
1841 
1842   if (const VectorType *VT = Ty->getAs<VectorType>()) {
1843     // On Windows, vectors are passed directly if registers are available, or
1844     // indirectly if not. This avoids the need to align argument memory. Pass
1845     // user-defined vector types larger than 512 bits indirectly for simplicity.
1846     if (IsWin32StructABI) {
1847       if (TI.Width <= 512 && State.FreeSSERegs > 0) {
1848         --State.FreeSSERegs;
1849         return ABIArgInfo::getDirectInReg();
1850       }
1851       return getIndirectResult(Ty, /*ByVal=*/false, State);
1852     }
1853 
1854     // On Darwin, some vectors are passed in memory, we handle this by passing
1855     // it as an i8/i16/i32/i64.
1856     if (IsDarwinVectorABI) {
1857       if ((TI.Width == 8 || TI.Width == 16 || TI.Width == 32) ||
1858           (TI.Width == 64 && VT->getNumElements() == 1))
1859         return ABIArgInfo::getDirect(
1860             llvm::IntegerType::get(getVMContext(), TI.Width));
1861     }
1862 
1863     if (IsX86_MMXType(CGT.ConvertType(Ty)))
1864       return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64));
1865 
1866     return ABIArgInfo::getDirect();
1867   }
1868 
1869 
1870   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1871     Ty = EnumTy->getDecl()->getIntegerType();
1872 
1873   bool InReg = shouldPrimitiveUseInReg(Ty, State);
1874 
1875   if (isPromotableIntegerTypeForABI(Ty)) {
1876     if (InReg)
1877       return ABIArgInfo::getExtendInReg(Ty);
1878     return ABIArgInfo::getExtend(Ty);
1879   }
1880 
1881   if (const auto * EIT = Ty->getAs<ExtIntType>()) {
1882     if (EIT->getNumBits() <= 64) {
1883       if (InReg)
1884         return ABIArgInfo::getDirectInReg();
1885       return ABIArgInfo::getDirect();
1886     }
1887     return getIndirectResult(Ty, /*ByVal=*/false, State);
1888   }
1889 
1890   if (InReg)
1891     return ABIArgInfo::getDirectInReg();
1892   return ABIArgInfo::getDirect();
1893 }
1894 
1895 void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const {
1896   CCState State(FI);
1897   if (IsMCUABI)
1898     State.FreeRegs = 3;
1899   else if (State.CC == llvm::CallingConv::X86_FastCall) {
1900     State.FreeRegs = 2;
1901     State.FreeSSERegs = 3;
1902   } else if (State.CC == llvm::CallingConv::X86_VectorCall) {
1903     State.FreeRegs = 2;
1904     State.FreeSSERegs = 6;
1905   } else if (FI.getHasRegParm())
1906     State.FreeRegs = FI.getRegParm();
1907   else if (State.CC == llvm::CallingConv::X86_RegCall) {
1908     State.FreeRegs = 5;
1909     State.FreeSSERegs = 8;
1910   } else if (IsWin32StructABI) {
1911     // Since MSVC 2015, the first three SSE vectors have been passed in
1912     // registers. The rest are passed indirectly.
1913     State.FreeRegs = DefaultNumRegisterParameters;
1914     State.FreeSSERegs = 3;
1915   } else
1916     State.FreeRegs = DefaultNumRegisterParameters;
1917 
1918   if (!::classifyReturnType(getCXXABI(), FI, *this)) {
1919     FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), State);
1920   } else if (FI.getReturnInfo().isIndirect()) {
1921     // The C++ ABI is not aware of register usage, so we have to check if the
1922     // return value was sret and put it in a register ourselves if appropriate.
1923     if (State.FreeRegs) {
1924       --State.FreeRegs;  // The sret parameter consumes a register.
1925       if (!IsMCUABI)
1926         FI.getReturnInfo().setInReg(true);
1927     }
1928   }
1929 
1930   // The chain argument effectively gives us another free register.
1931   if (FI.isChainCall())
1932     ++State.FreeRegs;
1933 
1934   // For vectorcall, do a first pass over the arguments, assigning FP and vector
1935   // arguments to XMM registers as available.
1936   if (State.CC == llvm::CallingConv::X86_VectorCall)
1937     runVectorCallFirstPass(FI, State);
1938 
1939   bool UsedInAlloca = false;
1940   MutableArrayRef<CGFunctionInfoArgInfo> Args = FI.arguments();
1941   for (int I = 0, E = Args.size(); I < E; ++I) {
1942     // Skip arguments that have already been assigned.
1943     if (State.IsPreassigned.test(I))
1944       continue;
1945 
1946     Args[I].info = classifyArgumentType(Args[I].type, State);
1947     UsedInAlloca |= (Args[I].info.getKind() == ABIArgInfo::InAlloca);
1948   }
1949 
1950   // If we needed to use inalloca for any argument, do a second pass and rewrite
1951   // all the memory arguments to use inalloca.
1952   if (UsedInAlloca)
1953     rewriteWithInAlloca(FI);
1954 }
1955 
1956 void
1957 X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
1958                                    CharUnits &StackOffset, ABIArgInfo &Info,
1959                                    QualType Type) const {
1960   // Arguments are always 4-byte-aligned.
1961   CharUnits WordSize = CharUnits::fromQuantity(4);
1962   assert(StackOffset.isMultipleOf(WordSize) && "unaligned inalloca struct");
1963 
1964   // sret pointers and indirect things will require an extra pointer
1965   // indirection, unless they are byval. Most things are byval, and will not
1966   // require this indirection.
1967   bool IsIndirect = false;
1968   if (Info.isIndirect() && !Info.getIndirectByVal())
1969     IsIndirect = true;
1970   Info = ABIArgInfo::getInAlloca(FrameFields.size(), IsIndirect);
1971   llvm::Type *LLTy = CGT.ConvertTypeForMem(Type);
1972   if (IsIndirect)
1973     LLTy = LLTy->getPointerTo(0);
1974   FrameFields.push_back(LLTy);
1975   StackOffset += IsIndirect ? WordSize : getContext().getTypeSizeInChars(Type);
1976 
1977   // Insert padding bytes to respect alignment.
1978   CharUnits FieldEnd = StackOffset;
1979   StackOffset = FieldEnd.alignTo(WordSize);
1980   if (StackOffset != FieldEnd) {
1981     CharUnits NumBytes = StackOffset - FieldEnd;
1982     llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext());
1983     Ty = llvm::ArrayType::get(Ty, NumBytes.getQuantity());
1984     FrameFields.push_back(Ty);
1985   }
1986 }
1987 
1988 static bool isArgInAlloca(const ABIArgInfo &Info) {
1989   // Leave ignored and inreg arguments alone.
1990   switch (Info.getKind()) {
1991   case ABIArgInfo::InAlloca:
1992     return true;
1993   case ABIArgInfo::Ignore:
1994   case ABIArgInfo::IndirectAliased:
1995     return false;
1996   case ABIArgInfo::Indirect:
1997   case ABIArgInfo::Direct:
1998   case ABIArgInfo::Extend:
1999     return !Info.getInReg();
2000   case ABIArgInfo::Expand:
2001   case ABIArgInfo::CoerceAndExpand:
2002     // These are aggregate types which are never passed in registers when
2003     // inalloca is involved.
2004     return true;
2005   }
2006   llvm_unreachable("invalid enum");
2007 }
2008 
2009 void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const {
2010   assert(IsWin32StructABI && "inalloca only supported on win32");
2011 
2012   // Build a packed struct type for all of the arguments in memory.
2013   SmallVector<llvm::Type *, 6> FrameFields;
2014 
2015   // The stack alignment is always 4.
2016   CharUnits StackAlign = CharUnits::fromQuantity(4);
2017 
2018   CharUnits StackOffset;
2019   CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end();
2020 
2021   // Put 'this' into the struct before 'sret', if necessary.
2022   bool IsThisCall =
2023       FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall;
2024   ABIArgInfo &Ret = FI.getReturnInfo();
2025   if (Ret.isIndirect() && Ret.isSRetAfterThis() && !IsThisCall &&
2026       isArgInAlloca(I->info)) {
2027     addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
2028     ++I;
2029   }
2030 
2031   // Put the sret parameter into the inalloca struct if it's in memory.
2032   if (Ret.isIndirect() && !Ret.getInReg()) {
2033     addFieldToArgStruct(FrameFields, StackOffset, Ret, FI.getReturnType());
2034     // On Windows, the hidden sret parameter is always returned in eax.
2035     Ret.setInAllocaSRet(IsWin32StructABI);
2036   }
2037 
2038   // Skip the 'this' parameter in ecx.
2039   if (IsThisCall)
2040     ++I;
2041 
2042   // Put arguments passed in memory into the struct.
2043   for (; I != E; ++I) {
2044     if (isArgInAlloca(I->info))
2045       addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
2046   }
2047 
2048   FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields,
2049                                         /*isPacked=*/true),
2050                   StackAlign);
2051 }
2052 
2053 Address X86_32ABIInfo::EmitVAArg(CodeGenFunction &CGF,
2054                                  Address VAListAddr, QualType Ty) const {
2055 
2056   auto TypeInfo = getContext().getTypeInfoInChars(Ty);
2057 
2058   // x86-32 changes the alignment of certain arguments on the stack.
2059   //
2060   // Just messing with TypeInfo like this works because we never pass
2061   // anything indirectly.
2062   TypeInfo.Align = CharUnits::fromQuantity(
2063                 getTypeStackAlignInBytes(Ty, TypeInfo.Align.getQuantity()));
2064 
2065   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
2066                           TypeInfo, CharUnits::fromQuantity(4),
2067                           /*AllowHigherAlign*/ true);
2068 }
2069 
2070 bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
2071     const llvm::Triple &Triple, const CodeGenOptions &Opts) {
2072   assert(Triple.getArch() == llvm::Triple::x86);
2073 
2074   switch (Opts.getStructReturnConvention()) {
2075   case CodeGenOptions::SRCK_Default:
2076     break;
2077   case CodeGenOptions::SRCK_OnStack:  // -fpcc-struct-return
2078     return false;
2079   case CodeGenOptions::SRCK_InRegs:  // -freg-struct-return
2080     return true;
2081   }
2082 
2083   if (Triple.isOSDarwin() || Triple.isOSIAMCU())
2084     return true;
2085 
2086   switch (Triple.getOS()) {
2087   case llvm::Triple::DragonFly:
2088   case llvm::Triple::FreeBSD:
2089   case llvm::Triple::OpenBSD:
2090   case llvm::Triple::Win32:
2091     return true;
2092   default:
2093     return false;
2094   }
2095 }
2096 
2097 static void addX86InterruptAttrs(const FunctionDecl *FD, llvm::GlobalValue *GV,
2098                                  CodeGen::CodeGenModule &CGM) {
2099   if (!FD->hasAttr<AnyX86InterruptAttr>())
2100     return;
2101 
2102   llvm::Function *Fn = cast<llvm::Function>(GV);
2103   Fn->setCallingConv(llvm::CallingConv::X86_INTR);
2104   if (FD->getNumParams() == 0)
2105     return;
2106 
2107   auto PtrTy = cast<PointerType>(FD->getParamDecl(0)->getType());
2108   llvm::Type *ByValTy = CGM.getTypes().ConvertType(PtrTy->getPointeeType());
2109   llvm::Attribute NewAttr = llvm::Attribute::getWithByValType(
2110     Fn->getContext(), ByValTy);
2111   Fn->addParamAttr(0, NewAttr);
2112 }
2113 
2114 void X86_32TargetCodeGenInfo::setTargetAttributes(
2115     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
2116   if (GV->isDeclaration())
2117     return;
2118   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2119     if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
2120       llvm::Function *Fn = cast<llvm::Function>(GV);
2121       Fn->addFnAttr("stackrealign");
2122     }
2123 
2124     addX86InterruptAttrs(FD, GV, CGM);
2125   }
2126 }
2127 
2128 bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
2129                                                CodeGen::CodeGenFunction &CGF,
2130                                                llvm::Value *Address) const {
2131   CodeGen::CGBuilderTy &Builder = CGF.Builder;
2132 
2133   llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
2134 
2135   // 0-7 are the eight integer registers;  the order is different
2136   //   on Darwin (for EH), but the range is the same.
2137   // 8 is %eip.
2138   AssignToArrayRange(Builder, Address, Four8, 0, 8);
2139 
2140   if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
2141     // 12-16 are st(0..4).  Not sure why we stop at 4.
2142     // These have size 16, which is sizeof(long double) on
2143     // platforms with 8-byte alignment for that type.
2144     llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
2145     AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
2146 
2147   } else {
2148     // 9 is %eflags, which doesn't get a size on Darwin for some
2149     // reason.
2150     Builder.CreateAlignedStore(
2151         Four8, Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, Address, 9),
2152                                CharUnits::One());
2153 
2154     // 11-16 are st(0..5).  Not sure why we stop at 5.
2155     // These have size 12, which is sizeof(long double) on
2156     // platforms with 4-byte alignment for that type.
2157     llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
2158     AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
2159   }
2160 
2161   return false;
2162 }
2163 
2164 //===----------------------------------------------------------------------===//
2165 // X86-64 ABI Implementation
2166 //===----------------------------------------------------------------------===//
2167 
2168 
2169 namespace {
2170 /// The AVX ABI level for X86 targets.
2171 enum class X86AVXABILevel {
2172   None,
2173   AVX,
2174   AVX512
2175 };
2176 
2177 /// \p returns the size in bits of the largest (native) vector for \p AVXLevel.
2178 static unsigned getNativeVectorSizeForAVXABI(X86AVXABILevel AVXLevel) {
2179   switch (AVXLevel) {
2180   case X86AVXABILevel::AVX512:
2181     return 512;
2182   case X86AVXABILevel::AVX:
2183     return 256;
2184   case X86AVXABILevel::None:
2185     return 128;
2186   }
2187   llvm_unreachable("Unknown AVXLevel");
2188 }
2189 
2190 /// X86_64ABIInfo - The X86_64 ABI information.
2191 class X86_64ABIInfo : public SwiftABIInfo {
2192   enum Class {
2193     Integer = 0,
2194     SSE,
2195     SSEUp,
2196     X87,
2197     X87Up,
2198     ComplexX87,
2199     NoClass,
2200     Memory
2201   };
2202 
2203   /// merge - Implement the X86_64 ABI merging algorithm.
2204   ///
2205   /// Merge an accumulating classification \arg Accum with a field
2206   /// classification \arg Field.
2207   ///
2208   /// \param Accum - The accumulating classification. This should
2209   /// always be either NoClass or the result of a previous merge
2210   /// call. In addition, this should never be Memory (the caller
2211   /// should just return Memory for the aggregate).
2212   static Class merge(Class Accum, Class Field);
2213 
2214   /// postMerge - Implement the X86_64 ABI post merging algorithm.
2215   ///
2216   /// Post merger cleanup, reduces a malformed Hi and Lo pair to
2217   /// final MEMORY or SSE classes when necessary.
2218   ///
2219   /// \param AggregateSize - The size of the current aggregate in
2220   /// the classification process.
2221   ///
2222   /// \param Lo - The classification for the parts of the type
2223   /// residing in the low word of the containing object.
2224   ///
2225   /// \param Hi - The classification for the parts of the type
2226   /// residing in the higher words of the containing object.
2227   ///
2228   void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
2229 
2230   /// classify - Determine the x86_64 register classes in which the
2231   /// given type T should be passed.
2232   ///
2233   /// \param Lo - The classification for the parts of the type
2234   /// residing in the low word of the containing object.
2235   ///
2236   /// \param Hi - The classification for the parts of the type
2237   /// residing in the high word of the containing object.
2238   ///
2239   /// \param OffsetBase - The bit offset of this type in the
2240   /// containing object.  Some parameters are classified different
2241   /// depending on whether they straddle an eightbyte boundary.
2242   ///
2243   /// \param isNamedArg - Whether the argument in question is a "named"
2244   /// argument, as used in AMD64-ABI 3.5.7.
2245   ///
2246   /// If a word is unused its result will be NoClass; if a type should
2247   /// be passed in Memory then at least the classification of \arg Lo
2248   /// will be Memory.
2249   ///
2250   /// The \arg Lo class will be NoClass iff the argument is ignored.
2251   ///
2252   /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
2253   /// also be ComplexX87.
2254   void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi,
2255                 bool isNamedArg) const;
2256 
2257   llvm::Type *GetByteVectorType(QualType Ty) const;
2258   llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
2259                                  unsigned IROffset, QualType SourceTy,
2260                                  unsigned SourceOffset) const;
2261   llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
2262                                      unsigned IROffset, QualType SourceTy,
2263                                      unsigned SourceOffset) const;
2264 
2265   /// getIndirectResult - Give a source type \arg Ty, return a suitable result
2266   /// such that the argument will be returned in memory.
2267   ABIArgInfo getIndirectReturnResult(QualType Ty) const;
2268 
2269   /// getIndirectResult - Give a source type \arg Ty, return a suitable result
2270   /// such that the argument will be passed in memory.
2271   ///
2272   /// \param freeIntRegs - The number of free integer registers remaining
2273   /// available.
2274   ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
2275 
2276   ABIArgInfo classifyReturnType(QualType RetTy) const;
2277 
2278   ABIArgInfo classifyArgumentType(QualType Ty, unsigned freeIntRegs,
2279                                   unsigned &neededInt, unsigned &neededSSE,
2280                                   bool isNamedArg) const;
2281 
2282   ABIArgInfo classifyRegCallStructType(QualType Ty, unsigned &NeededInt,
2283                                        unsigned &NeededSSE) const;
2284 
2285   ABIArgInfo classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
2286                                            unsigned &NeededSSE) const;
2287 
2288   bool IsIllegalVectorType(QualType Ty) const;
2289 
2290   /// The 0.98 ABI revision clarified a lot of ambiguities,
2291   /// unfortunately in ways that were not always consistent with
2292   /// certain previous compilers.  In particular, platforms which
2293   /// required strict binary compatibility with older versions of GCC
2294   /// may need to exempt themselves.
2295   bool honorsRevision0_98() const {
2296     return !getTarget().getTriple().isOSDarwin();
2297   }
2298 
2299   /// GCC classifies <1 x long long> as SSE but some platform ABIs choose to
2300   /// classify it as INTEGER (for compatibility with older clang compilers).
2301   bool classifyIntegerMMXAsSSE() const {
2302     // Clang <= 3.8 did not do this.
2303     if (getContext().getLangOpts().getClangABICompat() <=
2304         LangOptions::ClangABI::Ver3_8)
2305       return false;
2306 
2307     const llvm::Triple &Triple = getTarget().getTriple();
2308     if (Triple.isOSDarwin() || Triple.getOS() == llvm::Triple::PS4)
2309       return false;
2310     if (Triple.isOSFreeBSD() && Triple.getOSMajorVersion() >= 10)
2311       return false;
2312     return true;
2313   }
2314 
2315   // GCC classifies vectors of __int128 as memory.
2316   bool passInt128VectorsInMem() const {
2317     // Clang <= 9.0 did not do this.
2318     if (getContext().getLangOpts().getClangABICompat() <=
2319         LangOptions::ClangABI::Ver9)
2320       return false;
2321 
2322     const llvm::Triple &T = getTarget().getTriple();
2323     return T.isOSLinux() || T.isOSNetBSD();
2324   }
2325 
2326   X86AVXABILevel AVXLevel;
2327   // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
2328   // 64-bit hardware.
2329   bool Has64BitPointers;
2330 
2331 public:
2332   X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) :
2333       SwiftABIInfo(CGT), AVXLevel(AVXLevel),
2334       Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {
2335   }
2336 
2337   bool isPassedUsingAVXType(QualType type) const {
2338     unsigned neededInt, neededSSE;
2339     // The freeIntRegs argument doesn't matter here.
2340     ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE,
2341                                            /*isNamedArg*/true);
2342     if (info.isDirect()) {
2343       llvm::Type *ty = info.getCoerceToType();
2344       if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
2345         return vectorTy->getPrimitiveSizeInBits().getFixedSize() > 128;
2346     }
2347     return false;
2348   }
2349 
2350   void computeInfo(CGFunctionInfo &FI) const override;
2351 
2352   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
2353                     QualType Ty) const override;
2354   Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
2355                       QualType Ty) const override;
2356 
2357   bool has64BitPointers() const {
2358     return Has64BitPointers;
2359   }
2360 
2361   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
2362                                     bool asReturnValue) const override {
2363     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
2364   }
2365   bool isSwiftErrorInRegister() const override {
2366     return true;
2367   }
2368 };
2369 
2370 /// WinX86_64ABIInfo - The Windows X86_64 ABI information.
2371 class WinX86_64ABIInfo : public SwiftABIInfo {
2372 public:
2373   WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
2374       : SwiftABIInfo(CGT), AVXLevel(AVXLevel),
2375         IsMingw64(getTarget().getTriple().isWindowsGNUEnvironment()) {}
2376 
2377   void computeInfo(CGFunctionInfo &FI) const override;
2378 
2379   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
2380                     QualType Ty) const override;
2381 
2382   bool isHomogeneousAggregateBaseType(QualType Ty) const override {
2383     // FIXME: Assumes vectorcall is in use.
2384     return isX86VectorTypeForVectorCall(getContext(), Ty);
2385   }
2386 
2387   bool isHomogeneousAggregateSmallEnough(const Type *Ty,
2388                                          uint64_t NumMembers) const override {
2389     // FIXME: Assumes vectorcall is in use.
2390     return isX86VectorCallAggregateSmallEnough(NumMembers);
2391   }
2392 
2393   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type *> scalars,
2394                                     bool asReturnValue) const override {
2395     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
2396   }
2397 
2398   bool isSwiftErrorInRegister() const override {
2399     return true;
2400   }
2401 
2402 private:
2403   ABIArgInfo classify(QualType Ty, unsigned &FreeSSERegs, bool IsReturnType,
2404                       bool IsVectorCall, bool IsRegCall) const;
2405   ABIArgInfo reclassifyHvaArgForVectorCall(QualType Ty, unsigned &FreeSSERegs,
2406                                            const ABIArgInfo &current) const;
2407 
2408   X86AVXABILevel AVXLevel;
2409 
2410   bool IsMingw64;
2411 };
2412 
2413 class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2414 public:
2415   X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
2416       : TargetCodeGenInfo(std::make_unique<X86_64ABIInfo>(CGT, AVXLevel)) {}
2417 
2418   const X86_64ABIInfo &getABIInfo() const {
2419     return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
2420   }
2421 
2422   /// Disable tail call on x86-64. The epilogue code before the tail jump blocks
2423   /// autoreleaseRV/retainRV and autoreleaseRV/unsafeClaimRV optimizations.
2424   bool markARCOptimizedReturnCallsAsNoTail() const override { return true; }
2425 
2426   int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
2427     return 7;
2428   }
2429 
2430   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2431                                llvm::Value *Address) const override {
2432     llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
2433 
2434     // 0-15 are the 16 integer registers.
2435     // 16 is %rip.
2436     AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
2437     return false;
2438   }
2439 
2440   llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
2441                                   StringRef Constraint,
2442                                   llvm::Type* Ty) const override {
2443     return X86AdjustInlineAsmType(CGF, Constraint, Ty);
2444   }
2445 
2446   bool isNoProtoCallVariadic(const CallArgList &args,
2447                              const FunctionNoProtoType *fnType) const override {
2448     // The default CC on x86-64 sets %al to the number of SSA
2449     // registers used, and GCC sets this when calling an unprototyped
2450     // function, so we override the default behavior.  However, don't do
2451     // that when AVX types are involved: the ABI explicitly states it is
2452     // undefined, and it doesn't work in practice because of how the ABI
2453     // defines varargs anyway.
2454     if (fnType->getCallConv() == CC_C) {
2455       bool HasAVXType = false;
2456       for (CallArgList::const_iterator
2457              it = args.begin(), ie = args.end(); it != ie; ++it) {
2458         if (getABIInfo().isPassedUsingAVXType(it->Ty)) {
2459           HasAVXType = true;
2460           break;
2461         }
2462       }
2463 
2464       if (!HasAVXType)
2465         return true;
2466     }
2467 
2468     return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
2469   }
2470 
2471   llvm::Constant *
2472   getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
2473     unsigned Sig = (0xeb << 0) | // jmp rel8
2474                    (0x06 << 8) | //           .+0x08
2475                    ('v' << 16) |
2476                    ('2' << 24);
2477     return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
2478   }
2479 
2480   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2481                            CodeGen::CodeGenModule &CGM) const override {
2482     if (GV->isDeclaration())
2483       return;
2484     if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2485       if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
2486         llvm::Function *Fn = cast<llvm::Function>(GV);
2487         Fn->addFnAttr("stackrealign");
2488       }
2489 
2490       addX86InterruptAttrs(FD, GV, CGM);
2491     }
2492   }
2493 
2494   void checkFunctionCallABI(CodeGenModule &CGM, SourceLocation CallLoc,
2495                             const FunctionDecl *Caller,
2496                             const FunctionDecl *Callee,
2497                             const CallArgList &Args) const override;
2498 };
2499 
2500 static void initFeatureMaps(const ASTContext &Ctx,
2501                             llvm::StringMap<bool> &CallerMap,
2502                             const FunctionDecl *Caller,
2503                             llvm::StringMap<bool> &CalleeMap,
2504                             const FunctionDecl *Callee) {
2505   if (CalleeMap.empty() && CallerMap.empty()) {
2506     // The caller is potentially nullptr in the case where the call isn't in a
2507     // function.  In this case, the getFunctionFeatureMap ensures we just get
2508     // the TU level setting (since it cannot be modified by 'target'..
2509     Ctx.getFunctionFeatureMap(CallerMap, Caller);
2510     Ctx.getFunctionFeatureMap(CalleeMap, Callee);
2511   }
2512 }
2513 
2514 static bool checkAVXParamFeature(DiagnosticsEngine &Diag,
2515                                  SourceLocation CallLoc,
2516                                  const llvm::StringMap<bool> &CallerMap,
2517                                  const llvm::StringMap<bool> &CalleeMap,
2518                                  QualType Ty, StringRef Feature,
2519                                  bool IsArgument) {
2520   bool CallerHasFeat = CallerMap.lookup(Feature);
2521   bool CalleeHasFeat = CalleeMap.lookup(Feature);
2522   if (!CallerHasFeat && !CalleeHasFeat)
2523     return Diag.Report(CallLoc, diag::warn_avx_calling_convention)
2524            << IsArgument << Ty << Feature;
2525 
2526   // Mixing calling conventions here is very clearly an error.
2527   if (!CallerHasFeat || !CalleeHasFeat)
2528     return Diag.Report(CallLoc, diag::err_avx_calling_convention)
2529            << IsArgument << Ty << Feature;
2530 
2531   // Else, both caller and callee have the required feature, so there is no need
2532   // to diagnose.
2533   return false;
2534 }
2535 
2536 static bool checkAVXParam(DiagnosticsEngine &Diag, ASTContext &Ctx,
2537                           SourceLocation CallLoc,
2538                           const llvm::StringMap<bool> &CallerMap,
2539                           const llvm::StringMap<bool> &CalleeMap, QualType Ty,
2540                           bool IsArgument) {
2541   uint64_t Size = Ctx.getTypeSize(Ty);
2542   if (Size > 256)
2543     return checkAVXParamFeature(Diag, CallLoc, CallerMap, CalleeMap, Ty,
2544                                 "avx512f", IsArgument);
2545 
2546   if (Size > 128)
2547     return checkAVXParamFeature(Diag, CallLoc, CallerMap, CalleeMap, Ty, "avx",
2548                                 IsArgument);
2549 
2550   return false;
2551 }
2552 
2553 void X86_64TargetCodeGenInfo::checkFunctionCallABI(
2554     CodeGenModule &CGM, SourceLocation CallLoc, const FunctionDecl *Caller,
2555     const FunctionDecl *Callee, const CallArgList &Args) const {
2556   llvm::StringMap<bool> CallerMap;
2557   llvm::StringMap<bool> CalleeMap;
2558   unsigned ArgIndex = 0;
2559 
2560   // We need to loop through the actual call arguments rather than the the
2561   // function's parameters, in case this variadic.
2562   for (const CallArg &Arg : Args) {
2563     // The "avx" feature changes how vectors >128 in size are passed. "avx512f"
2564     // additionally changes how vectors >256 in size are passed. Like GCC, we
2565     // warn when a function is called with an argument where this will change.
2566     // Unlike GCC, we also error when it is an obvious ABI mismatch, that is,
2567     // the caller and callee features are mismatched.
2568     // Unfortunately, we cannot do this diagnostic in SEMA, since the callee can
2569     // change its ABI with attribute-target after this call.
2570     if (Arg.getType()->isVectorType() &&
2571         CGM.getContext().getTypeSize(Arg.getType()) > 128) {
2572       initFeatureMaps(CGM.getContext(), CallerMap, Caller, CalleeMap, Callee);
2573       QualType Ty = Arg.getType();
2574       // The CallArg seems to have desugared the type already, so for clearer
2575       // diagnostics, replace it with the type in the FunctionDecl if possible.
2576       if (ArgIndex < Callee->getNumParams())
2577         Ty = Callee->getParamDecl(ArgIndex)->getType();
2578 
2579       if (checkAVXParam(CGM.getDiags(), CGM.getContext(), CallLoc, CallerMap,
2580                         CalleeMap, Ty, /*IsArgument*/ true))
2581         return;
2582     }
2583     ++ArgIndex;
2584   }
2585 
2586   // Check return always, as we don't have a good way of knowing in codegen
2587   // whether this value is used, tail-called, etc.
2588   if (Callee->getReturnType()->isVectorType() &&
2589       CGM.getContext().getTypeSize(Callee->getReturnType()) > 128) {
2590     initFeatureMaps(CGM.getContext(), CallerMap, Caller, CalleeMap, Callee);
2591     checkAVXParam(CGM.getDiags(), CGM.getContext(), CallLoc, CallerMap,
2592                   CalleeMap, Callee->getReturnType(),
2593                   /*IsArgument*/ false);
2594   }
2595 }
2596 
2597 static std::string qualifyWindowsLibrary(llvm::StringRef Lib) {
2598   // If the argument does not end in .lib, automatically add the suffix.
2599   // If the argument contains a space, enclose it in quotes.
2600   // This matches the behavior of MSVC.
2601   bool Quote = (Lib.find(' ') != StringRef::npos);
2602   std::string ArgStr = Quote ? "\"" : "";
2603   ArgStr += Lib;
2604   if (!Lib.endswith_lower(".lib") && !Lib.endswith_lower(".a"))
2605     ArgStr += ".lib";
2606   ArgStr += Quote ? "\"" : "";
2607   return ArgStr;
2608 }
2609 
2610 class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
2611 public:
2612   WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
2613         bool DarwinVectorABI, bool RetSmallStructInRegABI, bool Win32StructABI,
2614         unsigned NumRegisterParameters)
2615     : X86_32TargetCodeGenInfo(CGT, DarwinVectorABI, RetSmallStructInRegABI,
2616         Win32StructABI, NumRegisterParameters, false) {}
2617 
2618   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2619                            CodeGen::CodeGenModule &CGM) const override;
2620 
2621   void getDependentLibraryOption(llvm::StringRef Lib,
2622                                  llvm::SmallString<24> &Opt) const override {
2623     Opt = "/DEFAULTLIB:";
2624     Opt += qualifyWindowsLibrary(Lib);
2625   }
2626 
2627   void getDetectMismatchOption(llvm::StringRef Name,
2628                                llvm::StringRef Value,
2629                                llvm::SmallString<32> &Opt) const override {
2630     Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
2631   }
2632 };
2633 
2634 static void addStackProbeTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2635                                           CodeGen::CodeGenModule &CGM) {
2636   if (llvm::Function *Fn = dyn_cast_or_null<llvm::Function>(GV)) {
2637 
2638     if (CGM.getCodeGenOpts().StackProbeSize != 4096)
2639       Fn->addFnAttr("stack-probe-size",
2640                     llvm::utostr(CGM.getCodeGenOpts().StackProbeSize));
2641     if (CGM.getCodeGenOpts().NoStackArgProbe)
2642       Fn->addFnAttr("no-stack-arg-probe");
2643   }
2644 }
2645 
2646 void WinX86_32TargetCodeGenInfo::setTargetAttributes(
2647     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
2648   X86_32TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
2649   if (GV->isDeclaration())
2650     return;
2651   addStackProbeTargetAttributes(D, GV, CGM);
2652 }
2653 
2654 class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2655 public:
2656   WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
2657                              X86AVXABILevel AVXLevel)
2658       : TargetCodeGenInfo(std::make_unique<WinX86_64ABIInfo>(CGT, AVXLevel)) {}
2659 
2660   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2661                            CodeGen::CodeGenModule &CGM) const override;
2662 
2663   int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
2664     return 7;
2665   }
2666 
2667   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2668                                llvm::Value *Address) const override {
2669     llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
2670 
2671     // 0-15 are the 16 integer registers.
2672     // 16 is %rip.
2673     AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
2674     return false;
2675   }
2676 
2677   void getDependentLibraryOption(llvm::StringRef Lib,
2678                                  llvm::SmallString<24> &Opt) const override {
2679     Opt = "/DEFAULTLIB:";
2680     Opt += qualifyWindowsLibrary(Lib);
2681   }
2682 
2683   void getDetectMismatchOption(llvm::StringRef Name,
2684                                llvm::StringRef Value,
2685                                llvm::SmallString<32> &Opt) const override {
2686     Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
2687   }
2688 };
2689 
2690 void WinX86_64TargetCodeGenInfo::setTargetAttributes(
2691     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
2692   TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
2693   if (GV->isDeclaration())
2694     return;
2695   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2696     if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
2697       llvm::Function *Fn = cast<llvm::Function>(GV);
2698       Fn->addFnAttr("stackrealign");
2699     }
2700 
2701     addX86InterruptAttrs(FD, GV, CGM);
2702   }
2703 
2704   addStackProbeTargetAttributes(D, GV, CGM);
2705 }
2706 }
2707 
2708 void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
2709                               Class &Hi) const {
2710   // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
2711   //
2712   // (a) If one of the classes is Memory, the whole argument is passed in
2713   //     memory.
2714   //
2715   // (b) If X87UP is not preceded by X87, the whole argument is passed in
2716   //     memory.
2717   //
2718   // (c) If the size of the aggregate exceeds two eightbytes and the first
2719   //     eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
2720   //     argument is passed in memory. NOTE: This is necessary to keep the
2721   //     ABI working for processors that don't support the __m256 type.
2722   //
2723   // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
2724   //
2725   // Some of these are enforced by the merging logic.  Others can arise
2726   // only with unions; for example:
2727   //   union { _Complex double; unsigned; }
2728   //
2729   // Note that clauses (b) and (c) were added in 0.98.
2730   //
2731   if (Hi == Memory)
2732     Lo = Memory;
2733   if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
2734     Lo = Memory;
2735   if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
2736     Lo = Memory;
2737   if (Hi == SSEUp && Lo != SSE)
2738     Hi = SSE;
2739 }
2740 
2741 X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
2742   // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
2743   // classified recursively so that always two fields are
2744   // considered. The resulting class is calculated according to
2745   // the classes of the fields in the eightbyte:
2746   //
2747   // (a) If both classes are equal, this is the resulting class.
2748   //
2749   // (b) If one of the classes is NO_CLASS, the resulting class is
2750   // the other class.
2751   //
2752   // (c) If one of the classes is MEMORY, the result is the MEMORY
2753   // class.
2754   //
2755   // (d) If one of the classes is INTEGER, the result is the
2756   // INTEGER.
2757   //
2758   // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
2759   // MEMORY is used as class.
2760   //
2761   // (f) Otherwise class SSE is used.
2762 
2763   // Accum should never be memory (we should have returned) or
2764   // ComplexX87 (because this cannot be passed in a structure).
2765   assert((Accum != Memory && Accum != ComplexX87) &&
2766          "Invalid accumulated classification during merge.");
2767   if (Accum == Field || Field == NoClass)
2768     return Accum;
2769   if (Field == Memory)
2770     return Memory;
2771   if (Accum == NoClass)
2772     return Field;
2773   if (Accum == Integer || Field == Integer)
2774     return Integer;
2775   if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
2776       Accum == X87 || Accum == X87Up)
2777     return Memory;
2778   return SSE;
2779 }
2780 
2781 void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
2782                              Class &Lo, Class &Hi, bool isNamedArg) const {
2783   // FIXME: This code can be simplified by introducing a simple value class for
2784   // Class pairs with appropriate constructor methods for the various
2785   // situations.
2786 
2787   // FIXME: Some of the split computations are wrong; unaligned vectors
2788   // shouldn't be passed in registers for example, so there is no chance they
2789   // can straddle an eightbyte. Verify & simplify.
2790 
2791   Lo = Hi = NoClass;
2792 
2793   Class &Current = OffsetBase < 64 ? Lo : Hi;
2794   Current = Memory;
2795 
2796   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
2797     BuiltinType::Kind k = BT->getKind();
2798 
2799     if (k == BuiltinType::Void) {
2800       Current = NoClass;
2801     } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
2802       Lo = Integer;
2803       Hi = Integer;
2804     } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
2805       Current = Integer;
2806     } else if (k == BuiltinType::Float || k == BuiltinType::Double) {
2807       Current = SSE;
2808     } else if (k == BuiltinType::LongDouble) {
2809       const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
2810       if (LDF == &llvm::APFloat::IEEEquad()) {
2811         Lo = SSE;
2812         Hi = SSEUp;
2813       } else if (LDF == &llvm::APFloat::x87DoubleExtended()) {
2814         Lo = X87;
2815         Hi = X87Up;
2816       } else if (LDF == &llvm::APFloat::IEEEdouble()) {
2817         Current = SSE;
2818       } else
2819         llvm_unreachable("unexpected long double representation!");
2820     }
2821     // FIXME: _Decimal32 and _Decimal64 are SSE.
2822     // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
2823     return;
2824   }
2825 
2826   if (const EnumType *ET = Ty->getAs<EnumType>()) {
2827     // Classify the underlying integer type.
2828     classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
2829     return;
2830   }
2831 
2832   if (Ty->hasPointerRepresentation()) {
2833     Current = Integer;
2834     return;
2835   }
2836 
2837   if (Ty->isMemberPointerType()) {
2838     if (Ty->isMemberFunctionPointerType()) {
2839       if (Has64BitPointers) {
2840         // If Has64BitPointers, this is an {i64, i64}, so classify both
2841         // Lo and Hi now.
2842         Lo = Hi = Integer;
2843       } else {
2844         // Otherwise, with 32-bit pointers, this is an {i32, i32}. If that
2845         // straddles an eightbyte boundary, Hi should be classified as well.
2846         uint64_t EB_FuncPtr = (OffsetBase) / 64;
2847         uint64_t EB_ThisAdj = (OffsetBase + 64 - 1) / 64;
2848         if (EB_FuncPtr != EB_ThisAdj) {
2849           Lo = Hi = Integer;
2850         } else {
2851           Current = Integer;
2852         }
2853       }
2854     } else {
2855       Current = Integer;
2856     }
2857     return;
2858   }
2859 
2860   if (const VectorType *VT = Ty->getAs<VectorType>()) {
2861     uint64_t Size = getContext().getTypeSize(VT);
2862     if (Size == 1 || Size == 8 || Size == 16 || Size == 32) {
2863       // gcc passes the following as integer:
2864       // 4 bytes - <4 x char>, <2 x short>, <1 x int>, <1 x float>
2865       // 2 bytes - <2 x char>, <1 x short>
2866       // 1 byte  - <1 x char>
2867       Current = Integer;
2868 
2869       // If this type crosses an eightbyte boundary, it should be
2870       // split.
2871       uint64_t EB_Lo = (OffsetBase) / 64;
2872       uint64_t EB_Hi = (OffsetBase + Size - 1) / 64;
2873       if (EB_Lo != EB_Hi)
2874         Hi = Lo;
2875     } else if (Size == 64) {
2876       QualType ElementType = VT->getElementType();
2877 
2878       // gcc passes <1 x double> in memory. :(
2879       if (ElementType->isSpecificBuiltinType(BuiltinType::Double))
2880         return;
2881 
2882       // gcc passes <1 x long long> as SSE but clang used to unconditionally
2883       // pass them as integer.  For platforms where clang is the de facto
2884       // platform compiler, we must continue to use integer.
2885       if (!classifyIntegerMMXAsSSE() &&
2886           (ElementType->isSpecificBuiltinType(BuiltinType::LongLong) ||
2887            ElementType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
2888            ElementType->isSpecificBuiltinType(BuiltinType::Long) ||
2889            ElementType->isSpecificBuiltinType(BuiltinType::ULong)))
2890         Current = Integer;
2891       else
2892         Current = SSE;
2893 
2894       // If this type crosses an eightbyte boundary, it should be
2895       // split.
2896       if (OffsetBase && OffsetBase != 64)
2897         Hi = Lo;
2898     } else if (Size == 128 ||
2899                (isNamedArg && Size <= getNativeVectorSizeForAVXABI(AVXLevel))) {
2900       QualType ElementType = VT->getElementType();
2901 
2902       // gcc passes 256 and 512 bit <X x __int128> vectors in memory. :(
2903       if (passInt128VectorsInMem() && Size != 128 &&
2904           (ElementType->isSpecificBuiltinType(BuiltinType::Int128) ||
2905            ElementType->isSpecificBuiltinType(BuiltinType::UInt128)))
2906         return;
2907 
2908       // Arguments of 256-bits are split into four eightbyte chunks. The
2909       // least significant one belongs to class SSE and all the others to class
2910       // SSEUP. The original Lo and Hi design considers that types can't be
2911       // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
2912       // This design isn't correct for 256-bits, but since there're no cases
2913       // where the upper parts would need to be inspected, avoid adding
2914       // complexity and just consider Hi to match the 64-256 part.
2915       //
2916       // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
2917       // registers if they are "named", i.e. not part of the "..." of a
2918       // variadic function.
2919       //
2920       // Similarly, per 3.2.3. of the AVX512 draft, 512-bits ("named") args are
2921       // split into eight eightbyte chunks, one SSE and seven SSEUP.
2922       Lo = SSE;
2923       Hi = SSEUp;
2924     }
2925     return;
2926   }
2927 
2928   if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
2929     QualType ET = getContext().getCanonicalType(CT->getElementType());
2930 
2931     uint64_t Size = getContext().getTypeSize(Ty);
2932     if (ET->isIntegralOrEnumerationType()) {
2933       if (Size <= 64)
2934         Current = Integer;
2935       else if (Size <= 128)
2936         Lo = Hi = Integer;
2937     } else if (ET == getContext().FloatTy) {
2938       Current = SSE;
2939     } else if (ET == getContext().DoubleTy) {
2940       Lo = Hi = SSE;
2941     } else if (ET == getContext().LongDoubleTy) {
2942       const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
2943       if (LDF == &llvm::APFloat::IEEEquad())
2944         Current = Memory;
2945       else if (LDF == &llvm::APFloat::x87DoubleExtended())
2946         Current = ComplexX87;
2947       else if (LDF == &llvm::APFloat::IEEEdouble())
2948         Lo = Hi = SSE;
2949       else
2950         llvm_unreachable("unexpected long double representation!");
2951     }
2952 
2953     // If this complex type crosses an eightbyte boundary then it
2954     // should be split.
2955     uint64_t EB_Real = (OffsetBase) / 64;
2956     uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
2957     if (Hi == NoClass && EB_Real != EB_Imag)
2958       Hi = Lo;
2959 
2960     return;
2961   }
2962 
2963   if (const auto *EITy = Ty->getAs<ExtIntType>()) {
2964     if (EITy->getNumBits() <= 64)
2965       Current = Integer;
2966     else if (EITy->getNumBits() <= 128)
2967       Lo = Hi = Integer;
2968     // Larger values need to get passed in memory.
2969     return;
2970   }
2971 
2972   if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
2973     // Arrays are treated like structures.
2974 
2975     uint64_t Size = getContext().getTypeSize(Ty);
2976 
2977     // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
2978     // than eight eightbytes, ..., it has class MEMORY.
2979     if (Size > 512)
2980       return;
2981 
2982     // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
2983     // fields, it has class MEMORY.
2984     //
2985     // Only need to check alignment of array base.
2986     if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
2987       return;
2988 
2989     // Otherwise implement simplified merge. We could be smarter about
2990     // this, but it isn't worth it and would be harder to verify.
2991     Current = NoClass;
2992     uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
2993     uint64_t ArraySize = AT->getSize().getZExtValue();
2994 
2995     // The only case a 256-bit wide vector could be used is when the array
2996     // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2997     // to work for sizes wider than 128, early check and fallback to memory.
2998     //
2999     if (Size > 128 &&
3000         (Size != EltSize || Size > getNativeVectorSizeForAVXABI(AVXLevel)))
3001       return;
3002 
3003     for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
3004       Class FieldLo, FieldHi;
3005       classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
3006       Lo = merge(Lo, FieldLo);
3007       Hi = merge(Hi, FieldHi);
3008       if (Lo == Memory || Hi == Memory)
3009         break;
3010     }
3011 
3012     postMerge(Size, Lo, Hi);
3013     assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
3014     return;
3015   }
3016 
3017   if (const RecordType *RT = Ty->getAs<RecordType>()) {
3018     uint64_t Size = getContext().getTypeSize(Ty);
3019 
3020     // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
3021     // than eight eightbytes, ..., it has class MEMORY.
3022     if (Size > 512)
3023       return;
3024 
3025     // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
3026     // copy constructor or a non-trivial destructor, it is passed by invisible
3027     // reference.
3028     if (getRecordArgABI(RT, getCXXABI()))
3029       return;
3030 
3031     const RecordDecl *RD = RT->getDecl();
3032 
3033     // Assume variable sized types are passed in memory.
3034     if (RD->hasFlexibleArrayMember())
3035       return;
3036 
3037     const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
3038 
3039     // Reset Lo class, this will be recomputed.
3040     Current = NoClass;
3041 
3042     // If this is a C++ record, classify the bases first.
3043     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3044       for (const auto &I : CXXRD->bases()) {
3045         assert(!I.isVirtual() && !I.getType()->isDependentType() &&
3046                "Unexpected base class!");
3047         const auto *Base =
3048             cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
3049 
3050         // Classify this field.
3051         //
3052         // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
3053         // single eightbyte, each is classified separately. Each eightbyte gets
3054         // initialized to class NO_CLASS.
3055         Class FieldLo, FieldHi;
3056         uint64_t Offset =
3057           OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
3058         classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg);
3059         Lo = merge(Lo, FieldLo);
3060         Hi = merge(Hi, FieldHi);
3061         if (Lo == Memory || Hi == Memory) {
3062           postMerge(Size, Lo, Hi);
3063           return;
3064         }
3065       }
3066     }
3067 
3068     // Classify the fields one at a time, merging the results.
3069     unsigned idx = 0;
3070     bool UseClang11Compat = getContext().getLangOpts().getClangABICompat() <=
3071                                 LangOptions::ClangABI::Ver11 ||
3072                             getContext().getTargetInfo().getTriple().isPS4();
3073     bool IsUnion = RT->isUnionType() && !UseClang11Compat;
3074 
3075     for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
3076            i != e; ++i, ++idx) {
3077       uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
3078       bool BitField = i->isBitField();
3079 
3080       // Ignore padding bit-fields.
3081       if (BitField && i->isUnnamedBitfield())
3082         continue;
3083 
3084       // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
3085       // eight eightbytes, or it contains unaligned fields, it has class MEMORY.
3086       //
3087       // The only case a 256-bit or a 512-bit wide vector could be used is when
3088       // the struct contains a single 256-bit or 512-bit element. Early check
3089       // and fallback to memory.
3090       //
3091       // FIXME: Extended the Lo and Hi logic properly to work for size wider
3092       // than 128.
3093       if (Size > 128 &&
3094           ((!IsUnion && Size != getContext().getTypeSize(i->getType())) ||
3095            Size > getNativeVectorSizeForAVXABI(AVXLevel))) {
3096         Lo = Memory;
3097         postMerge(Size, Lo, Hi);
3098         return;
3099       }
3100       // Note, skip this test for bit-fields, see below.
3101       if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
3102         Lo = Memory;
3103         postMerge(Size, Lo, Hi);
3104         return;
3105       }
3106 
3107       // Classify this field.
3108       //
3109       // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
3110       // exceeds a single eightbyte, each is classified
3111       // separately. Each eightbyte gets initialized to class
3112       // NO_CLASS.
3113       Class FieldLo, FieldHi;
3114 
3115       // Bit-fields require special handling, they do not force the
3116       // structure to be passed in memory even if unaligned, and
3117       // therefore they can straddle an eightbyte.
3118       if (BitField) {
3119         assert(!i->isUnnamedBitfield());
3120         uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
3121         uint64_t Size = i->getBitWidthValue(getContext());
3122 
3123         uint64_t EB_Lo = Offset / 64;
3124         uint64_t EB_Hi = (Offset + Size - 1) / 64;
3125 
3126         if (EB_Lo) {
3127           assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
3128           FieldLo = NoClass;
3129           FieldHi = Integer;
3130         } else {
3131           FieldLo = Integer;
3132           FieldHi = EB_Hi ? Integer : NoClass;
3133         }
3134       } else
3135         classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
3136       Lo = merge(Lo, FieldLo);
3137       Hi = merge(Hi, FieldHi);
3138       if (Lo == Memory || Hi == Memory)
3139         break;
3140     }
3141 
3142     postMerge(Size, Lo, Hi);
3143   }
3144 }
3145 
3146 ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
3147   // If this is a scalar LLVM value then assume LLVM will pass it in the right
3148   // place naturally.
3149   if (!isAggregateTypeForABI(Ty)) {
3150     // Treat an enum type as its underlying type.
3151     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3152       Ty = EnumTy->getDecl()->getIntegerType();
3153 
3154     if (Ty->isExtIntType())
3155       return getNaturalAlignIndirect(Ty);
3156 
3157     return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
3158                                               : ABIArgInfo::getDirect());
3159   }
3160 
3161   return getNaturalAlignIndirect(Ty);
3162 }
3163 
3164 bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
3165   if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
3166     uint64_t Size = getContext().getTypeSize(VecTy);
3167     unsigned LargestVector = getNativeVectorSizeForAVXABI(AVXLevel);
3168     if (Size <= 64 || Size > LargestVector)
3169       return true;
3170     QualType EltTy = VecTy->getElementType();
3171     if (passInt128VectorsInMem() &&
3172         (EltTy->isSpecificBuiltinType(BuiltinType::Int128) ||
3173          EltTy->isSpecificBuiltinType(BuiltinType::UInt128)))
3174       return true;
3175   }
3176 
3177   return false;
3178 }
3179 
3180 ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
3181                                             unsigned freeIntRegs) const {
3182   // If this is a scalar LLVM value then assume LLVM will pass it in the right
3183   // place naturally.
3184   //
3185   // This assumption is optimistic, as there could be free registers available
3186   // when we need to pass this argument in memory, and LLVM could try to pass
3187   // the argument in the free register. This does not seem to happen currently,
3188   // but this code would be much safer if we could mark the argument with
3189   // 'onstack'. See PR12193.
3190   if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty) &&
3191       !Ty->isExtIntType()) {
3192     // Treat an enum type as its underlying type.
3193     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3194       Ty = EnumTy->getDecl()->getIntegerType();
3195 
3196     return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
3197                                               : ABIArgInfo::getDirect());
3198   }
3199 
3200   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
3201     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
3202 
3203   // Compute the byval alignment. We specify the alignment of the byval in all
3204   // cases so that the mid-level optimizer knows the alignment of the byval.
3205   unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
3206 
3207   // Attempt to avoid passing indirect results using byval when possible. This
3208   // is important for good codegen.
3209   //
3210   // We do this by coercing the value into a scalar type which the backend can
3211   // handle naturally (i.e., without using byval).
3212   //
3213   // For simplicity, we currently only do this when we have exhausted all of the
3214   // free integer registers. Doing this when there are free integer registers
3215   // would require more care, as we would have to ensure that the coerced value
3216   // did not claim the unused register. That would require either reording the
3217   // arguments to the function (so that any subsequent inreg values came first),
3218   // or only doing this optimization when there were no following arguments that
3219   // might be inreg.
3220   //
3221   // We currently expect it to be rare (particularly in well written code) for
3222   // arguments to be passed on the stack when there are still free integer
3223   // registers available (this would typically imply large structs being passed
3224   // by value), so this seems like a fair tradeoff for now.
3225   //
3226   // We can revisit this if the backend grows support for 'onstack' parameter
3227   // attributes. See PR12193.
3228   if (freeIntRegs == 0) {
3229     uint64_t Size = getContext().getTypeSize(Ty);
3230 
3231     // If this type fits in an eightbyte, coerce it into the matching integral
3232     // type, which will end up on the stack (with alignment 8).
3233     if (Align == 8 && Size <= 64)
3234       return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
3235                                                           Size));
3236   }
3237 
3238   return ABIArgInfo::getIndirect(CharUnits::fromQuantity(Align));
3239 }
3240 
3241 /// The ABI specifies that a value should be passed in a full vector XMM/YMM
3242 /// register. Pick an LLVM IR type that will be passed as a vector register.
3243 llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
3244   // Wrapper structs/arrays that only contain vectors are passed just like
3245   // vectors; strip them off if present.
3246   if (const Type *InnerTy = isSingleElementStruct(Ty, getContext()))
3247     Ty = QualType(InnerTy, 0);
3248 
3249   llvm::Type *IRType = CGT.ConvertType(Ty);
3250   if (isa<llvm::VectorType>(IRType)) {
3251     // Don't pass vXi128 vectors in their native type, the backend can't
3252     // legalize them.
3253     if (passInt128VectorsInMem() &&
3254         cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy(128)) {
3255       // Use a vXi64 vector.
3256       uint64_t Size = getContext().getTypeSize(Ty);
3257       return llvm::FixedVectorType::get(llvm::Type::getInt64Ty(getVMContext()),
3258                                         Size / 64);
3259     }
3260 
3261     return IRType;
3262   }
3263 
3264   if (IRType->getTypeID() == llvm::Type::FP128TyID)
3265     return IRType;
3266 
3267   // We couldn't find the preferred IR vector type for 'Ty'.
3268   uint64_t Size = getContext().getTypeSize(Ty);
3269   assert((Size == 128 || Size == 256 || Size == 512) && "Invalid type found!");
3270 
3271 
3272   // Return a LLVM IR vector type based on the size of 'Ty'.
3273   return llvm::FixedVectorType::get(llvm::Type::getDoubleTy(getVMContext()),
3274                                     Size / 64);
3275 }
3276 
3277 /// BitsContainNoUserData - Return true if the specified [start,end) bit range
3278 /// is known to either be off the end of the specified type or being in
3279 /// alignment padding.  The user type specified is known to be at most 128 bits
3280 /// in size, and have passed through X86_64ABIInfo::classify with a successful
3281 /// classification that put one of the two halves in the INTEGER class.
3282 ///
3283 /// It is conservatively correct to return false.
3284 static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
3285                                   unsigned EndBit, ASTContext &Context) {
3286   // If the bytes being queried are off the end of the type, there is no user
3287   // data hiding here.  This handles analysis of builtins, vectors and other
3288   // types that don't contain interesting padding.
3289   unsigned TySize = (unsigned)Context.getTypeSize(Ty);
3290   if (TySize <= StartBit)
3291     return true;
3292 
3293   if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
3294     unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
3295     unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
3296 
3297     // Check each element to see if the element overlaps with the queried range.
3298     for (unsigned i = 0; i != NumElts; ++i) {
3299       // If the element is after the span we care about, then we're done..
3300       unsigned EltOffset = i*EltSize;
3301       if (EltOffset >= EndBit) break;
3302 
3303       unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
3304       if (!BitsContainNoUserData(AT->getElementType(), EltStart,
3305                                  EndBit-EltOffset, Context))
3306         return false;
3307     }
3308     // If it overlaps no elements, then it is safe to process as padding.
3309     return true;
3310   }
3311 
3312   if (const RecordType *RT = Ty->getAs<RecordType>()) {
3313     const RecordDecl *RD = RT->getDecl();
3314     const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
3315 
3316     // If this is a C++ record, check the bases first.
3317     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3318       for (const auto &I : CXXRD->bases()) {
3319         assert(!I.isVirtual() && !I.getType()->isDependentType() &&
3320                "Unexpected base class!");
3321         const auto *Base =
3322             cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
3323 
3324         // If the base is after the span we care about, ignore it.
3325         unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
3326         if (BaseOffset >= EndBit) continue;
3327 
3328         unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
3329         if (!BitsContainNoUserData(I.getType(), BaseStart,
3330                                    EndBit-BaseOffset, Context))
3331           return false;
3332       }
3333     }
3334 
3335     // Verify that no field has data that overlaps the region of interest.  Yes
3336     // this could be sped up a lot by being smarter about queried fields,
3337     // however we're only looking at structs up to 16 bytes, so we don't care
3338     // much.
3339     unsigned idx = 0;
3340     for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
3341          i != e; ++i, ++idx) {
3342       unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
3343 
3344       // If we found a field after the region we care about, then we're done.
3345       if (FieldOffset >= EndBit) break;
3346 
3347       unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
3348       if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
3349                                  Context))
3350         return false;
3351     }
3352 
3353     // If nothing in this record overlapped the area of interest, then we're
3354     // clean.
3355     return true;
3356   }
3357 
3358   return false;
3359 }
3360 
3361 /// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a
3362 /// float member at the specified offset.  For example, {int,{float}} has a
3363 /// float at offset 4.  It is conservatively correct for this routine to return
3364 /// false.
3365 static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset,
3366                                   const llvm::DataLayout &TD) {
3367   // Base case if we find a float.
3368   if (IROffset == 0 && IRType->isFloatTy())
3369     return true;
3370 
3371   // If this is a struct, recurse into the field at the specified offset.
3372   if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
3373     const llvm::StructLayout *SL = TD.getStructLayout(STy);
3374     unsigned Elt = SL->getElementContainingOffset(IROffset);
3375     IROffset -= SL->getElementOffset(Elt);
3376     return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD);
3377   }
3378 
3379   // If this is an array, recurse into the field at the specified offset.
3380   if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
3381     llvm::Type *EltTy = ATy->getElementType();
3382     unsigned EltSize = TD.getTypeAllocSize(EltTy);
3383     IROffset -= IROffset/EltSize*EltSize;
3384     return ContainsFloatAtOffset(EltTy, IROffset, TD);
3385   }
3386 
3387   return false;
3388 }
3389 
3390 
3391 /// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
3392 /// low 8 bytes of an XMM register, corresponding to the SSE class.
3393 llvm::Type *X86_64ABIInfo::
3394 GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
3395                    QualType SourceTy, unsigned SourceOffset) const {
3396   // The only three choices we have are either double, <2 x float>, or float. We
3397   // pass as float if the last 4 bytes is just padding.  This happens for
3398   // structs that contain 3 floats.
3399   if (BitsContainNoUserData(SourceTy, SourceOffset*8+32,
3400                             SourceOffset*8+64, getContext()))
3401     return llvm::Type::getFloatTy(getVMContext());
3402 
3403   // We want to pass as <2 x float> if the LLVM IR type contains a float at
3404   // offset+0 and offset+4.  Walk the LLVM IR type to find out if this is the
3405   // case.
3406   if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) &&
3407       ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout()))
3408     return llvm::FixedVectorType::get(llvm::Type::getFloatTy(getVMContext()),
3409                                       2);
3410 
3411   return llvm::Type::getDoubleTy(getVMContext());
3412 }
3413 
3414 
3415 /// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
3416 /// an 8-byte GPR.  This means that we either have a scalar or we are talking
3417 /// about the high or low part of an up-to-16-byte struct.  This routine picks
3418 /// the best LLVM IR type to represent this, which may be i64 or may be anything
3419 /// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
3420 /// etc).
3421 ///
3422 /// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
3423 /// the source type.  IROffset is an offset in bytes into the LLVM IR type that
3424 /// the 8-byte value references.  PrefType may be null.
3425 ///
3426 /// SourceTy is the source-level type for the entire argument.  SourceOffset is
3427 /// an offset into this that we're processing (which is always either 0 or 8).
3428 ///
3429 llvm::Type *X86_64ABIInfo::
3430 GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
3431                        QualType SourceTy, unsigned SourceOffset) const {
3432   // If we're dealing with an un-offset LLVM IR type, then it means that we're
3433   // returning an 8-byte unit starting with it.  See if we can safely use it.
3434   if (IROffset == 0) {
3435     // Pointers and int64's always fill the 8-byte unit.
3436     if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
3437         IRType->isIntegerTy(64))
3438       return IRType;
3439 
3440     // If we have a 1/2/4-byte integer, we can use it only if the rest of the
3441     // goodness in the source type is just tail padding.  This is allowed to
3442     // kick in for struct {double,int} on the int, but not on
3443     // struct{double,int,int} because we wouldn't return the second int.  We
3444     // have to do this analysis on the source type because we can't depend on
3445     // unions being lowered a specific way etc.
3446     if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
3447         IRType->isIntegerTy(32) ||
3448         (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
3449       unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
3450           cast<llvm::IntegerType>(IRType)->getBitWidth();
3451 
3452       if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
3453                                 SourceOffset*8+64, getContext()))
3454         return IRType;
3455     }
3456   }
3457 
3458   if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
3459     // If this is a struct, recurse into the field at the specified offset.
3460     const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
3461     if (IROffset < SL->getSizeInBytes()) {
3462       unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
3463       IROffset -= SL->getElementOffset(FieldIdx);
3464 
3465       return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
3466                                     SourceTy, SourceOffset);
3467     }
3468   }
3469 
3470   if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
3471     llvm::Type *EltTy = ATy->getElementType();
3472     unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
3473     unsigned EltOffset = IROffset/EltSize*EltSize;
3474     return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
3475                                   SourceOffset);
3476   }
3477 
3478   // Okay, we don't have any better idea of what to pass, so we pass this in an
3479   // integer register that isn't too big to fit the rest of the struct.
3480   unsigned TySizeInBytes =
3481     (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
3482 
3483   assert(TySizeInBytes != SourceOffset && "Empty field?");
3484 
3485   // It is always safe to classify this as an integer type up to i64 that
3486   // isn't larger than the structure.
3487   return llvm::IntegerType::get(getVMContext(),
3488                                 std::min(TySizeInBytes-SourceOffset, 8U)*8);
3489 }
3490 
3491 
3492 /// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
3493 /// be used as elements of a two register pair to pass or return, return a
3494 /// first class aggregate to represent them.  For example, if the low part of
3495 /// a by-value argument should be passed as i32* and the high part as float,
3496 /// return {i32*, float}.
3497 static llvm::Type *
3498 GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
3499                            const llvm::DataLayout &TD) {
3500   // In order to correctly satisfy the ABI, we need to the high part to start
3501   // at offset 8.  If the high and low parts we inferred are both 4-byte types
3502   // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
3503   // the second element at offset 8.  Check for this:
3504   unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
3505   unsigned HiAlign = TD.getABITypeAlignment(Hi);
3506   unsigned HiStart = llvm::alignTo(LoSize, HiAlign);
3507   assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
3508 
3509   // To handle this, we have to increase the size of the low part so that the
3510   // second element will start at an 8 byte offset.  We can't increase the size
3511   // of the second element because it might make us access off the end of the
3512   // struct.
3513   if (HiStart != 8) {
3514     // There are usually two sorts of types the ABI generation code can produce
3515     // for the low part of a pair that aren't 8 bytes in size: float or
3516     // i8/i16/i32.  This can also include pointers when they are 32-bit (X32 and
3517     // NaCl).
3518     // Promote these to a larger type.
3519     if (Lo->isFloatTy())
3520       Lo = llvm::Type::getDoubleTy(Lo->getContext());
3521     else {
3522       assert((Lo->isIntegerTy() || Lo->isPointerTy())
3523              && "Invalid/unknown lo type");
3524       Lo = llvm::Type::getInt64Ty(Lo->getContext());
3525     }
3526   }
3527 
3528   llvm::StructType *Result = llvm::StructType::get(Lo, Hi);
3529 
3530   // Verify that the second element is at an 8-byte offset.
3531   assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
3532          "Invalid x86-64 argument pair!");
3533   return Result;
3534 }
3535 
3536 ABIArgInfo X86_64ABIInfo::
3537 classifyReturnType(QualType RetTy) const {
3538   // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
3539   // classification algorithm.
3540   X86_64ABIInfo::Class Lo, Hi;
3541   classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
3542 
3543   // Check some invariants.
3544   assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
3545   assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
3546 
3547   llvm::Type *ResType = nullptr;
3548   switch (Lo) {
3549   case NoClass:
3550     if (Hi == NoClass)
3551       return ABIArgInfo::getIgnore();
3552     // If the low part is just padding, it takes no register, leave ResType
3553     // null.
3554     assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3555            "Unknown missing lo part");
3556     break;
3557 
3558   case SSEUp:
3559   case X87Up:
3560     llvm_unreachable("Invalid classification for lo word.");
3561 
3562     // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
3563     // hidden argument.
3564   case Memory:
3565     return getIndirectReturnResult(RetTy);
3566 
3567     // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
3568     // available register of the sequence %rax, %rdx is used.
3569   case Integer:
3570     ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
3571 
3572     // If we have a sign or zero extended integer, make sure to return Extend
3573     // so that the parameter gets the right LLVM IR attributes.
3574     if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3575       // Treat an enum type as its underlying type.
3576       if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
3577         RetTy = EnumTy->getDecl()->getIntegerType();
3578 
3579       if (RetTy->isIntegralOrEnumerationType() &&
3580           isPromotableIntegerTypeForABI(RetTy))
3581         return ABIArgInfo::getExtend(RetTy);
3582     }
3583     break;
3584 
3585     // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
3586     // available SSE register of the sequence %xmm0, %xmm1 is used.
3587   case SSE:
3588     ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
3589     break;
3590 
3591     // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
3592     // returned on the X87 stack in %st0 as 80-bit x87 number.
3593   case X87:
3594     ResType = llvm::Type::getX86_FP80Ty(getVMContext());
3595     break;
3596 
3597     // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
3598     // part of the value is returned in %st0 and the imaginary part in
3599     // %st1.
3600   case ComplexX87:
3601     assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
3602     ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
3603                                     llvm::Type::getX86_FP80Ty(getVMContext()));
3604     break;
3605   }
3606 
3607   llvm::Type *HighPart = nullptr;
3608   switch (Hi) {
3609     // Memory was handled previously and X87 should
3610     // never occur as a hi class.
3611   case Memory:
3612   case X87:
3613     llvm_unreachable("Invalid classification for hi word.");
3614 
3615   case ComplexX87: // Previously handled.
3616   case NoClass:
3617     break;
3618 
3619   case Integer:
3620     HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
3621     if (Lo == NoClass)  // Return HighPart at offset 8 in memory.
3622       return ABIArgInfo::getDirect(HighPart, 8);
3623     break;
3624   case SSE:
3625     HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
3626     if (Lo == NoClass)  // Return HighPart at offset 8 in memory.
3627       return ABIArgInfo::getDirect(HighPart, 8);
3628     break;
3629 
3630     // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
3631     // is passed in the next available eightbyte chunk if the last used
3632     // vector register.
3633     //
3634     // SSEUP should always be preceded by SSE, just widen.
3635   case SSEUp:
3636     assert(Lo == SSE && "Unexpected SSEUp classification.");
3637     ResType = GetByteVectorType(RetTy);
3638     break;
3639 
3640     // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
3641     // returned together with the previous X87 value in %st0.
3642   case X87Up:
3643     // If X87Up is preceded by X87, we don't need to do
3644     // anything. However, in some cases with unions it may not be
3645     // preceded by X87. In such situations we follow gcc and pass the
3646     // extra bits in an SSE reg.
3647     if (Lo != X87) {
3648       HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
3649       if (Lo == NoClass)  // Return HighPart at offset 8 in memory.
3650         return ABIArgInfo::getDirect(HighPart, 8);
3651     }
3652     break;
3653   }
3654 
3655   // If a high part was specified, merge it together with the low part.  It is
3656   // known to pass in the high eightbyte of the result.  We do this by forming a
3657   // first class struct aggregate with the high and low part: {low, high}
3658   if (HighPart)
3659     ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
3660 
3661   return ABIArgInfo::getDirect(ResType);
3662 }
3663 
3664 ABIArgInfo X86_64ABIInfo::classifyArgumentType(
3665   QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE,
3666   bool isNamedArg)
3667   const
3668 {
3669   Ty = useFirstFieldIfTransparentUnion(Ty);
3670 
3671   X86_64ABIInfo::Class Lo, Hi;
3672   classify(Ty, 0, Lo, Hi, isNamedArg);
3673 
3674   // Check some invariants.
3675   // FIXME: Enforce these by construction.
3676   assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
3677   assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
3678 
3679   neededInt = 0;
3680   neededSSE = 0;
3681   llvm::Type *ResType = nullptr;
3682   switch (Lo) {
3683   case NoClass:
3684     if (Hi == NoClass)
3685       return ABIArgInfo::getIgnore();
3686     // If the low part is just padding, it takes no register, leave ResType
3687     // null.
3688     assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3689            "Unknown missing lo part");
3690     break;
3691 
3692     // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
3693     // on the stack.
3694   case Memory:
3695 
3696     // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
3697     // COMPLEX_X87, it is passed in memory.
3698   case X87:
3699   case ComplexX87:
3700     if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect)
3701       ++neededInt;
3702     return getIndirectResult(Ty, freeIntRegs);
3703 
3704   case SSEUp:
3705   case X87Up:
3706     llvm_unreachable("Invalid classification for lo word.");
3707 
3708     // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
3709     // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
3710     // and %r9 is used.
3711   case Integer:
3712     ++neededInt;
3713 
3714     // Pick an 8-byte type based on the preferred type.
3715     ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
3716 
3717     // If we have a sign or zero extended integer, make sure to return Extend
3718     // so that the parameter gets the right LLVM IR attributes.
3719     if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3720       // Treat an enum type as its underlying type.
3721       if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3722         Ty = EnumTy->getDecl()->getIntegerType();
3723 
3724       if (Ty->isIntegralOrEnumerationType() &&
3725           isPromotableIntegerTypeForABI(Ty))
3726         return ABIArgInfo::getExtend(Ty);
3727     }
3728 
3729     break;
3730 
3731     // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
3732     // available SSE register is used, the registers are taken in the
3733     // order from %xmm0 to %xmm7.
3734   case SSE: {
3735     llvm::Type *IRType = CGT.ConvertType(Ty);
3736     ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
3737     ++neededSSE;
3738     break;
3739   }
3740   }
3741 
3742   llvm::Type *HighPart = nullptr;
3743   switch (Hi) {
3744     // Memory was handled previously, ComplexX87 and X87 should
3745     // never occur as hi classes, and X87Up must be preceded by X87,
3746     // which is passed in memory.
3747   case Memory:
3748   case X87:
3749   case ComplexX87:
3750     llvm_unreachable("Invalid classification for hi word.");
3751 
3752   case NoClass: break;
3753 
3754   case Integer:
3755     ++neededInt;
3756     // Pick an 8-byte type based on the preferred type.
3757     HighPart = GetINTEGERTypeAtOffset(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     break;
3762 
3763     // X87Up generally doesn't occur here (long double is passed in
3764     // memory), except in situations involving unions.
3765   case X87Up:
3766   case SSE:
3767     HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
3768 
3769     if (Lo == NoClass)  // Pass HighPart at offset 8 in memory.
3770       return ABIArgInfo::getDirect(HighPart, 8);
3771 
3772     ++neededSSE;
3773     break;
3774 
3775     // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
3776     // eightbyte is passed in the upper half of the last used SSE
3777     // register.  This only happens when 128-bit vectors are passed.
3778   case SSEUp:
3779     assert(Lo == SSE && "Unexpected SSEUp classification");
3780     ResType = GetByteVectorType(Ty);
3781     break;
3782   }
3783 
3784   // If a high part was specified, merge it together with the low part.  It is
3785   // known to pass in the high eightbyte of the result.  We do this by forming a
3786   // first class struct aggregate with the high and low part: {low, high}
3787   if (HighPart)
3788     ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
3789 
3790   return ABIArgInfo::getDirect(ResType);
3791 }
3792 
3793 ABIArgInfo
3794 X86_64ABIInfo::classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
3795                                              unsigned &NeededSSE) const {
3796   auto RT = Ty->getAs<RecordType>();
3797   assert(RT && "classifyRegCallStructType only valid with struct types");
3798 
3799   if (RT->getDecl()->hasFlexibleArrayMember())
3800     return getIndirectReturnResult(Ty);
3801 
3802   // Sum up bases
3803   if (auto CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
3804     if (CXXRD->isDynamicClass()) {
3805       NeededInt = NeededSSE = 0;
3806       return getIndirectReturnResult(Ty);
3807     }
3808 
3809     for (const auto &I : CXXRD->bases())
3810       if (classifyRegCallStructTypeImpl(I.getType(), NeededInt, NeededSSE)
3811               .isIndirect()) {
3812         NeededInt = NeededSSE = 0;
3813         return getIndirectReturnResult(Ty);
3814       }
3815   }
3816 
3817   // Sum up members
3818   for (const auto *FD : RT->getDecl()->fields()) {
3819     if (FD->getType()->isRecordType() && !FD->getType()->isUnionType()) {
3820       if (classifyRegCallStructTypeImpl(FD->getType(), NeededInt, NeededSSE)
3821               .isIndirect()) {
3822         NeededInt = NeededSSE = 0;
3823         return getIndirectReturnResult(Ty);
3824       }
3825     } else {
3826       unsigned LocalNeededInt, LocalNeededSSE;
3827       if (classifyArgumentType(FD->getType(), UINT_MAX, LocalNeededInt,
3828                                LocalNeededSSE, true)
3829               .isIndirect()) {
3830         NeededInt = NeededSSE = 0;
3831         return getIndirectReturnResult(Ty);
3832       }
3833       NeededInt += LocalNeededInt;
3834       NeededSSE += LocalNeededSSE;
3835     }
3836   }
3837 
3838   return ABIArgInfo::getDirect();
3839 }
3840 
3841 ABIArgInfo X86_64ABIInfo::classifyRegCallStructType(QualType Ty,
3842                                                     unsigned &NeededInt,
3843                                                     unsigned &NeededSSE) const {
3844 
3845   NeededInt = 0;
3846   NeededSSE = 0;
3847 
3848   return classifyRegCallStructTypeImpl(Ty, NeededInt, NeededSSE);
3849 }
3850 
3851 void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
3852 
3853   const unsigned CallingConv = FI.getCallingConvention();
3854   // It is possible to force Win64 calling convention on any x86_64 target by
3855   // using __attribute__((ms_abi)). In such case to correctly emit Win64
3856   // compatible code delegate this call to WinX86_64ABIInfo::computeInfo.
3857   if (CallingConv == llvm::CallingConv::Win64) {
3858     WinX86_64ABIInfo Win64ABIInfo(CGT, AVXLevel);
3859     Win64ABIInfo.computeInfo(FI);
3860     return;
3861   }
3862 
3863   bool IsRegCall = CallingConv == llvm::CallingConv::X86_RegCall;
3864 
3865   // Keep track of the number of assigned registers.
3866   unsigned FreeIntRegs = IsRegCall ? 11 : 6;
3867   unsigned FreeSSERegs = IsRegCall ? 16 : 8;
3868   unsigned NeededInt, NeededSSE;
3869 
3870   if (!::classifyReturnType(getCXXABI(), FI, *this)) {
3871     if (IsRegCall && FI.getReturnType()->getTypePtr()->isRecordType() &&
3872         !FI.getReturnType()->getTypePtr()->isUnionType()) {
3873       FI.getReturnInfo() =
3874           classifyRegCallStructType(FI.getReturnType(), NeededInt, NeededSSE);
3875       if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
3876         FreeIntRegs -= NeededInt;
3877         FreeSSERegs -= NeededSSE;
3878       } else {
3879         FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType());
3880       }
3881     } else if (IsRegCall && FI.getReturnType()->getAs<ComplexType>() &&
3882                getContext().getCanonicalType(FI.getReturnType()
3883                                                  ->getAs<ComplexType>()
3884                                                  ->getElementType()) ==
3885                    getContext().LongDoubleTy)
3886       // Complex Long Double Type is passed in Memory when Regcall
3887       // calling convention is used.
3888       FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType());
3889     else
3890       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
3891   }
3892 
3893   // If the return value is indirect, then the hidden argument is consuming one
3894   // integer register.
3895   if (FI.getReturnInfo().isIndirect())
3896     --FreeIntRegs;
3897 
3898   // The chain argument effectively gives us another free register.
3899   if (FI.isChainCall())
3900     ++FreeIntRegs;
3901 
3902   unsigned NumRequiredArgs = FI.getNumRequiredArgs();
3903   // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
3904   // get assigned (in left-to-right order) for passing as follows...
3905   unsigned ArgNo = 0;
3906   for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
3907        it != ie; ++it, ++ArgNo) {
3908     bool IsNamedArg = ArgNo < NumRequiredArgs;
3909 
3910     if (IsRegCall && it->type->isStructureOrClassType())
3911       it->info = classifyRegCallStructType(it->type, NeededInt, NeededSSE);
3912     else
3913       it->info = classifyArgumentType(it->type, FreeIntRegs, NeededInt,
3914                                       NeededSSE, IsNamedArg);
3915 
3916     // AMD64-ABI 3.2.3p3: If there are no registers available for any
3917     // eightbyte of an argument, the whole argument is passed on the
3918     // stack. If registers have already been assigned for some
3919     // eightbytes of such an argument, the assignments get reverted.
3920     if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
3921       FreeIntRegs -= NeededInt;
3922       FreeSSERegs -= NeededSSE;
3923     } else {
3924       it->info = getIndirectResult(it->type, FreeIntRegs);
3925     }
3926   }
3927 }
3928 
3929 static Address EmitX86_64VAArgFromMemory(CodeGenFunction &CGF,
3930                                          Address VAListAddr, QualType Ty) {
3931   Address overflow_arg_area_p =
3932       CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_p");
3933   llvm::Value *overflow_arg_area =
3934     CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
3935 
3936   // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
3937   // byte boundary if alignment needed by type exceeds 8 byte boundary.
3938   // It isn't stated explicitly in the standard, but in practice we use
3939   // alignment greater than 16 where necessary.
3940   CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
3941   if (Align > CharUnits::fromQuantity(8)) {
3942     overflow_arg_area = emitRoundPointerUpToAlignment(CGF, overflow_arg_area,
3943                                                       Align);
3944   }
3945 
3946   // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
3947   llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
3948   llvm::Value *Res =
3949     CGF.Builder.CreateBitCast(overflow_arg_area,
3950                               llvm::PointerType::getUnqual(LTy));
3951 
3952   // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
3953   // l->overflow_arg_area + sizeof(type).
3954   // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
3955   // an 8 byte boundary.
3956 
3957   uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
3958   llvm::Value *Offset =
3959       llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7)  & ~7);
3960   overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
3961                                             "overflow_arg_area.next");
3962   CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
3963 
3964   // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
3965   return Address(Res, Align);
3966 }
3967 
3968 Address X86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3969                                  QualType Ty) const {
3970   // Assume that va_list type is correct; should be pointer to LLVM type:
3971   // struct {
3972   //   i32 gp_offset;
3973   //   i32 fp_offset;
3974   //   i8* overflow_arg_area;
3975   //   i8* reg_save_area;
3976   // };
3977   unsigned neededInt, neededSSE;
3978 
3979   Ty = getContext().getCanonicalType(Ty);
3980   ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
3981                                        /*isNamedArg*/false);
3982 
3983   // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
3984   // in the registers. If not go to step 7.
3985   if (!neededInt && !neededSSE)
3986     return EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
3987 
3988   // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
3989   // general purpose registers needed to pass type and num_fp to hold
3990   // the number of floating point registers needed.
3991 
3992   // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
3993   // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
3994   // l->fp_offset > 304 - num_fp * 16 go to step 7.
3995   //
3996   // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
3997   // register save space).
3998 
3999   llvm::Value *InRegs = nullptr;
4000   Address gp_offset_p = Address::invalid(), fp_offset_p = Address::invalid();
4001   llvm::Value *gp_offset = nullptr, *fp_offset = nullptr;
4002   if (neededInt) {
4003     gp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "gp_offset_p");
4004     gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
4005     InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
4006     InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
4007   }
4008 
4009   if (neededSSE) {
4010     fp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 1, "fp_offset_p");
4011     fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
4012     llvm::Value *FitsInFP =
4013       llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
4014     FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
4015     InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
4016   }
4017 
4018   llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
4019   llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
4020   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
4021   CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
4022 
4023   // Emit code to load the value if it was passed in registers.
4024 
4025   CGF.EmitBlock(InRegBlock);
4026 
4027   // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
4028   // an offset of l->gp_offset and/or l->fp_offset. This may require
4029   // copying to a temporary location in case the parameter is passed
4030   // in different register classes or requires an alignment greater
4031   // than 8 for general purpose registers and 16 for XMM registers.
4032   //
4033   // FIXME: This really results in shameful code when we end up needing to
4034   // collect arguments from different places; often what should result in a
4035   // simple assembling of a structure from scattered addresses has many more
4036   // loads than necessary. Can we clean this up?
4037   llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
4038   llvm::Value *RegSaveArea = CGF.Builder.CreateLoad(
4039       CGF.Builder.CreateStructGEP(VAListAddr, 3), "reg_save_area");
4040 
4041   Address RegAddr = Address::invalid();
4042   if (neededInt && neededSSE) {
4043     // FIXME: Cleanup.
4044     assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
4045     llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
4046     Address Tmp = CGF.CreateMemTemp(Ty);
4047     Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
4048     assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
4049     llvm::Type *TyLo = ST->getElementType(0);
4050     llvm::Type *TyHi = ST->getElementType(1);
4051     assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
4052            "Unexpected ABI info for mixed regs");
4053     llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
4054     llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
4055     llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegSaveArea, gp_offset);
4056     llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegSaveArea, fp_offset);
4057     llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr;
4058     llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr;
4059 
4060     // Copy the first element.
4061     // FIXME: Our choice of alignment here and below is probably pessimistic.
4062     llvm::Value *V = CGF.Builder.CreateAlignedLoad(
4063         TyLo, CGF.Builder.CreateBitCast(RegLoAddr, PTyLo),
4064         CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyLo)));
4065     CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
4066 
4067     // Copy the second element.
4068     V = CGF.Builder.CreateAlignedLoad(
4069         TyHi, CGF.Builder.CreateBitCast(RegHiAddr, PTyHi),
4070         CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyHi)));
4071     CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
4072 
4073     RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
4074   } else if (neededInt) {
4075     RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, gp_offset),
4076                       CharUnits::fromQuantity(8));
4077     RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
4078 
4079     // Copy to a temporary if necessary to ensure the appropriate alignment.
4080     auto TInfo = getContext().getTypeInfoInChars(Ty);
4081     uint64_t TySize = TInfo.Width.getQuantity();
4082     CharUnits TyAlign = TInfo.Align;
4083 
4084     // Copy into a temporary if the type is more aligned than the
4085     // register save area.
4086     if (TyAlign.getQuantity() > 8) {
4087       Address Tmp = CGF.CreateMemTemp(Ty);
4088       CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, false);
4089       RegAddr = Tmp;
4090     }
4091 
4092   } else if (neededSSE == 1) {
4093     RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
4094                       CharUnits::fromQuantity(16));
4095     RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
4096   } else {
4097     assert(neededSSE == 2 && "Invalid number of needed registers!");
4098     // SSE registers are spaced 16 bytes apart in the register save
4099     // area, we need to collect the two eightbytes together.
4100     // The ABI isn't explicit about this, but it seems reasonable
4101     // to assume that the slots are 16-byte aligned, since the stack is
4102     // naturally 16-byte aligned and the prologue is expected to store
4103     // all the SSE registers to the RSA.
4104     Address RegAddrLo = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
4105                                 CharUnits::fromQuantity(16));
4106     Address RegAddrHi =
4107       CGF.Builder.CreateConstInBoundsByteGEP(RegAddrLo,
4108                                              CharUnits::fromQuantity(16));
4109     llvm::Type *ST = AI.canHaveCoerceToType()
4110                          ? AI.getCoerceToType()
4111                          : llvm::StructType::get(CGF.DoubleTy, CGF.DoubleTy);
4112     llvm::Value *V;
4113     Address Tmp = CGF.CreateMemTemp(Ty);
4114     Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
4115     V = CGF.Builder.CreateLoad(CGF.Builder.CreateElementBitCast(
4116         RegAddrLo, ST->getStructElementType(0)));
4117     CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
4118     V = CGF.Builder.CreateLoad(CGF.Builder.CreateElementBitCast(
4119         RegAddrHi, ST->getStructElementType(1)));
4120     CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
4121 
4122     RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
4123   }
4124 
4125   // AMD64-ABI 3.5.7p5: Step 5. Set:
4126   // l->gp_offset = l->gp_offset + num_gp * 8
4127   // l->fp_offset = l->fp_offset + num_fp * 16.
4128   if (neededInt) {
4129     llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
4130     CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
4131                             gp_offset_p);
4132   }
4133   if (neededSSE) {
4134     llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
4135     CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
4136                             fp_offset_p);
4137   }
4138   CGF.EmitBranch(ContBlock);
4139 
4140   // Emit code to load the value if it was passed in memory.
4141 
4142   CGF.EmitBlock(InMemBlock);
4143   Address MemAddr = EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
4144 
4145   // Return the appropriate result.
4146 
4147   CGF.EmitBlock(ContBlock);
4148   Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, MemAddr, InMemBlock,
4149                                  "vaarg.addr");
4150   return ResAddr;
4151 }
4152 
4153 Address X86_64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
4154                                    QualType Ty) const {
4155   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
4156                           CGF.getContext().getTypeInfoInChars(Ty),
4157                           CharUnits::fromQuantity(8),
4158                           /*allowHigherAlign*/ false);
4159 }
4160 
4161 ABIArgInfo WinX86_64ABIInfo::reclassifyHvaArgForVectorCall(
4162     QualType Ty, unsigned &FreeSSERegs, const ABIArgInfo &current) const {
4163   const Type *Base = nullptr;
4164   uint64_t NumElts = 0;
4165 
4166   if (!Ty->isBuiltinType() && !Ty->isVectorType() &&
4167       isHomogeneousAggregate(Ty, Base, NumElts) && FreeSSERegs >= NumElts) {
4168     FreeSSERegs -= NumElts;
4169     return getDirectX86Hva();
4170   }
4171   return current;
4172 }
4173 
4174 ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, unsigned &FreeSSERegs,
4175                                       bool IsReturnType, bool IsVectorCall,
4176                                       bool IsRegCall) const {
4177 
4178   if (Ty->isVoidType())
4179     return ABIArgInfo::getIgnore();
4180 
4181   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4182     Ty = EnumTy->getDecl()->getIntegerType();
4183 
4184   TypeInfo Info = getContext().getTypeInfo(Ty);
4185   uint64_t Width = Info.Width;
4186   CharUnits Align = getContext().toCharUnitsFromBits(Info.Align);
4187 
4188   const RecordType *RT = Ty->getAs<RecordType>();
4189   if (RT) {
4190     if (!IsReturnType) {
4191       if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
4192         return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
4193     }
4194 
4195     if (RT->getDecl()->hasFlexibleArrayMember())
4196       return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
4197 
4198   }
4199 
4200   const Type *Base = nullptr;
4201   uint64_t NumElts = 0;
4202   // vectorcall adds the concept of a homogenous vector aggregate, similar to
4203   // other targets.
4204   if ((IsVectorCall || IsRegCall) &&
4205       isHomogeneousAggregate(Ty, Base, NumElts)) {
4206     if (IsRegCall) {
4207       if (FreeSSERegs >= NumElts) {
4208         FreeSSERegs -= NumElts;
4209         if (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())
4210           return ABIArgInfo::getDirect();
4211         return ABIArgInfo::getExpand();
4212       }
4213       return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
4214     } else if (IsVectorCall) {
4215       if (FreeSSERegs >= NumElts &&
4216           (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())) {
4217         FreeSSERegs -= NumElts;
4218         return ABIArgInfo::getDirect();
4219       } else if (IsReturnType) {
4220         return ABIArgInfo::getExpand();
4221       } else if (!Ty->isBuiltinType() && !Ty->isVectorType()) {
4222         // HVAs are delayed and reclassified in the 2nd step.
4223         return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
4224       }
4225     }
4226   }
4227 
4228   if (Ty->isMemberPointerType()) {
4229     // If the member pointer is represented by an LLVM int or ptr, pass it
4230     // directly.
4231     llvm::Type *LLTy = CGT.ConvertType(Ty);
4232     if (LLTy->isPointerTy() || LLTy->isIntegerTy())
4233       return ABIArgInfo::getDirect();
4234   }
4235 
4236   if (RT || Ty->isAnyComplexType() || Ty->isMemberPointerType()) {
4237     // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
4238     // not 1, 2, 4, or 8 bytes, must be passed by reference."
4239     if (Width > 64 || !llvm::isPowerOf2_64(Width))
4240       return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
4241 
4242     // Otherwise, coerce it to a small integer.
4243     return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Width));
4244   }
4245 
4246   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4247     switch (BT->getKind()) {
4248     case BuiltinType::Bool:
4249       // Bool type is always extended to the ABI, other builtin types are not
4250       // extended.
4251       return ABIArgInfo::getExtend(Ty);
4252 
4253     case BuiltinType::LongDouble:
4254       // Mingw64 GCC uses the old 80 bit extended precision floating point
4255       // unit. It passes them indirectly through memory.
4256       if (IsMingw64) {
4257         const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
4258         if (LDF == &llvm::APFloat::x87DoubleExtended())
4259           return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
4260       }
4261       break;
4262 
4263     case BuiltinType::Int128:
4264     case BuiltinType::UInt128:
4265       // If it's a parameter type, the normal ABI rule is that arguments larger
4266       // than 8 bytes are passed indirectly. GCC follows it. We follow it too,
4267       // even though it isn't particularly efficient.
4268       if (!IsReturnType)
4269         return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
4270 
4271       // Mingw64 GCC returns i128 in XMM0. Coerce to v2i64 to handle that.
4272       // Clang matches them for compatibility.
4273       return ABIArgInfo::getDirect(llvm::FixedVectorType::get(
4274           llvm::Type::getInt64Ty(getVMContext()), 2));
4275 
4276     default:
4277       break;
4278     }
4279   }
4280 
4281   if (Ty->isExtIntType()) {
4282     // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
4283     // not 1, 2, 4, or 8 bytes, must be passed by reference."
4284     // However, non-power-of-two _ExtInts will be passed as 1,2,4 or 8 bytes
4285     // anyway as long is it fits in them, so we don't have to check the power of
4286     // 2.
4287     if (Width <= 64)
4288       return ABIArgInfo::getDirect();
4289     return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
4290   }
4291 
4292   return ABIArgInfo::getDirect();
4293 }
4294 
4295 void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
4296   const unsigned CC = FI.getCallingConvention();
4297   bool IsVectorCall = CC == llvm::CallingConv::X86_VectorCall;
4298   bool IsRegCall = CC == llvm::CallingConv::X86_RegCall;
4299 
4300   // If __attribute__((sysv_abi)) is in use, use the SysV argument
4301   // classification rules.
4302   if (CC == llvm::CallingConv::X86_64_SysV) {
4303     X86_64ABIInfo SysVABIInfo(CGT, AVXLevel);
4304     SysVABIInfo.computeInfo(FI);
4305     return;
4306   }
4307 
4308   unsigned FreeSSERegs = 0;
4309   if (IsVectorCall) {
4310     // We can use up to 4 SSE return registers with vectorcall.
4311     FreeSSERegs = 4;
4312   } else if (IsRegCall) {
4313     // RegCall gives us 16 SSE registers.
4314     FreeSSERegs = 16;
4315   }
4316 
4317   if (!getCXXABI().classifyReturnType(FI))
4318     FI.getReturnInfo() = classify(FI.getReturnType(), FreeSSERegs, true,
4319                                   IsVectorCall, IsRegCall);
4320 
4321   if (IsVectorCall) {
4322     // We can use up to 6 SSE register parameters with vectorcall.
4323     FreeSSERegs = 6;
4324   } else if (IsRegCall) {
4325     // RegCall gives us 16 SSE registers, we can reuse the return registers.
4326     FreeSSERegs = 16;
4327   }
4328 
4329   unsigned ArgNum = 0;
4330   unsigned ZeroSSERegs = 0;
4331   for (auto &I : FI.arguments()) {
4332     // Vectorcall in x64 only permits the first 6 arguments to be passed as
4333     // XMM/YMM registers. After the sixth argument, pretend no vector
4334     // registers are left.
4335     unsigned *MaybeFreeSSERegs =
4336         (IsVectorCall && ArgNum >= 6) ? &ZeroSSERegs : &FreeSSERegs;
4337     I.info =
4338         classify(I.type, *MaybeFreeSSERegs, false, IsVectorCall, IsRegCall);
4339     ++ArgNum;
4340   }
4341 
4342   if (IsVectorCall) {
4343     // For vectorcall, assign aggregate HVAs to any free vector registers in a
4344     // second pass.
4345     for (auto &I : FI.arguments())
4346       I.info = reclassifyHvaArgForVectorCall(I.type, FreeSSERegs, I.info);
4347   }
4348 }
4349 
4350 Address WinX86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4351                                     QualType Ty) const {
4352 
4353   bool IsIndirect = false;
4354 
4355   // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
4356   // not 1, 2, 4, or 8 bytes, must be passed by reference."
4357   if (isAggregateTypeForABI(Ty) || Ty->isMemberPointerType()) {
4358     uint64_t Width = getContext().getTypeSize(Ty);
4359     IsIndirect = Width > 64 || !llvm::isPowerOf2_64(Width);
4360   }
4361 
4362   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
4363                           CGF.getContext().getTypeInfoInChars(Ty),
4364                           CharUnits::fromQuantity(8),
4365                           /*allowHigherAlign*/ false);
4366 }
4367 
4368 static bool PPC_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4369                                         llvm::Value *Address, bool Is64Bit,
4370                                         bool IsAIX) {
4371   // This is calculated from the LLVM and GCC tables and verified
4372   // against gcc output.  AFAIK all PPC ABIs use the same encoding.
4373 
4374   CodeGen::CGBuilderTy &Builder = CGF.Builder;
4375 
4376   llvm::IntegerType *i8 = CGF.Int8Ty;
4377   llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
4378   llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
4379   llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
4380 
4381   // 0-31: r0-31, the 4-byte or 8-byte general-purpose registers
4382   AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 0, 31);
4383 
4384   // 32-63: fp0-31, the 8-byte floating-point registers
4385   AssignToArrayRange(Builder, Address, Eight8, 32, 63);
4386 
4387   // 64-67 are various 4-byte or 8-byte special-purpose registers:
4388   // 64: mq
4389   // 65: lr
4390   // 66: ctr
4391   // 67: ap
4392   AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 64, 67);
4393 
4394   // 68-76 are various 4-byte special-purpose registers:
4395   // 68-75 cr0-7
4396   // 76: xer
4397   AssignToArrayRange(Builder, Address, Four8, 68, 76);
4398 
4399   // 77-108: v0-31, the 16-byte vector registers
4400   AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
4401 
4402   // 109: vrsave
4403   // 110: vscr
4404   AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 109, 110);
4405 
4406   // AIX does not utilize the rest of the registers.
4407   if (IsAIX)
4408     return false;
4409 
4410   // 111: spe_acc
4411   // 112: spefscr
4412   // 113: sfp
4413   AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 111, 113);
4414 
4415   if (!Is64Bit)
4416     return false;
4417 
4418   // TODO: Need to verify if these registers are used on 64 bit AIX with Power8
4419   // or above CPU.
4420   // 64-bit only registers:
4421   // 114: tfhar
4422   // 115: tfiar
4423   // 116: texasr
4424   AssignToArrayRange(Builder, Address, Eight8, 114, 116);
4425 
4426   return false;
4427 }
4428 
4429 // AIX
4430 namespace {
4431 /// AIXABIInfo - The AIX XCOFF ABI information.
4432 class AIXABIInfo : public ABIInfo {
4433   const bool Is64Bit;
4434   const unsigned PtrByteSize;
4435   CharUnits getParamTypeAlignment(QualType Ty) const;
4436 
4437 public:
4438   AIXABIInfo(CodeGen::CodeGenTypes &CGT, bool Is64Bit)
4439       : ABIInfo(CGT), Is64Bit(Is64Bit), PtrByteSize(Is64Bit ? 8 : 4) {}
4440 
4441   bool isPromotableTypeForABI(QualType Ty) const;
4442 
4443   ABIArgInfo classifyReturnType(QualType RetTy) const;
4444   ABIArgInfo classifyArgumentType(QualType Ty) const;
4445 
4446   void computeInfo(CGFunctionInfo &FI) const override {
4447     if (!getCXXABI().classifyReturnType(FI))
4448       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
4449 
4450     for (auto &I : FI.arguments())
4451       I.info = classifyArgumentType(I.type);
4452   }
4453 
4454   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4455                     QualType Ty) const override;
4456 };
4457 
4458 class AIXTargetCodeGenInfo : public TargetCodeGenInfo {
4459   const bool Is64Bit;
4460 
4461 public:
4462   AIXTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool Is64Bit)
4463       : TargetCodeGenInfo(std::make_unique<AIXABIInfo>(CGT, Is64Bit)),
4464         Is64Bit(Is64Bit) {}
4465   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4466     return 1; // r1 is the dedicated stack pointer
4467   }
4468 
4469   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4470                                llvm::Value *Address) const override;
4471 };
4472 } // namespace
4473 
4474 // Return true if the ABI requires Ty to be passed sign- or zero-
4475 // extended to 32/64 bits.
4476 bool AIXABIInfo::isPromotableTypeForABI(QualType Ty) const {
4477   // Treat an enum type as its underlying type.
4478   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4479     Ty = EnumTy->getDecl()->getIntegerType();
4480 
4481   // Promotable integer types are required to be promoted by the ABI.
4482   if (Ty->isPromotableIntegerType())
4483     return true;
4484 
4485   if (!Is64Bit)
4486     return false;
4487 
4488   // For 64 bit mode, in addition to the usual promotable integer types, we also
4489   // need to extend all 32-bit types, since the ABI requires promotion to 64
4490   // bits.
4491   if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
4492     switch (BT->getKind()) {
4493     case BuiltinType::Int:
4494     case BuiltinType::UInt:
4495       return true;
4496     default:
4497       break;
4498     }
4499 
4500   return false;
4501 }
4502 
4503 ABIArgInfo AIXABIInfo::classifyReturnType(QualType RetTy) const {
4504   if (RetTy->isAnyComplexType())
4505     return ABIArgInfo::getDirect();
4506 
4507   if (RetTy->isVectorType())
4508     return ABIArgInfo::getDirect();
4509 
4510   if (RetTy->isVoidType())
4511     return ABIArgInfo::getIgnore();
4512 
4513   if (isAggregateTypeForABI(RetTy))
4514     return getNaturalAlignIndirect(RetTy);
4515 
4516   return (isPromotableTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
4517                                         : ABIArgInfo::getDirect());
4518 }
4519 
4520 ABIArgInfo AIXABIInfo::classifyArgumentType(QualType Ty) const {
4521   Ty = useFirstFieldIfTransparentUnion(Ty);
4522 
4523   if (Ty->isAnyComplexType())
4524     return ABIArgInfo::getDirect();
4525 
4526   if (Ty->isVectorType())
4527     return ABIArgInfo::getDirect();
4528 
4529   if (isAggregateTypeForABI(Ty)) {
4530     // Records with non-trivial destructors/copy-constructors should not be
4531     // passed by value.
4532     if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
4533       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
4534 
4535     CharUnits CCAlign = getParamTypeAlignment(Ty);
4536     CharUnits TyAlign = getContext().getTypeAlignInChars(Ty);
4537 
4538     return ABIArgInfo::getIndirect(CCAlign, /*ByVal*/ true,
4539                                    /*Realign*/ TyAlign > CCAlign);
4540   }
4541 
4542   return (isPromotableTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
4543                                      : ABIArgInfo::getDirect());
4544 }
4545 
4546 CharUnits AIXABIInfo::getParamTypeAlignment(QualType Ty) const {
4547   // Complex types are passed just like their elements.
4548   if (const ComplexType *CTy = Ty->getAs<ComplexType>())
4549     Ty = CTy->getElementType();
4550 
4551   if (Ty->isVectorType())
4552     return CharUnits::fromQuantity(16);
4553 
4554   // If the structure contains a vector type, the alignment is 16.
4555   if (isRecordWithSIMDVectorType(getContext(), Ty))
4556     return CharUnits::fromQuantity(16);
4557 
4558   return CharUnits::fromQuantity(PtrByteSize);
4559 }
4560 
4561 Address AIXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4562                               QualType Ty) const {
4563   if (Ty->isAnyComplexType())
4564     llvm::report_fatal_error("complex type is not supported on AIX yet");
4565 
4566   auto TypeInfo = getContext().getTypeInfoInChars(Ty);
4567   TypeInfo.Align = getParamTypeAlignment(Ty);
4568 
4569   CharUnits SlotSize = CharUnits::fromQuantity(PtrByteSize);
4570 
4571   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false, TypeInfo,
4572                           SlotSize, /*AllowHigher*/ true);
4573 }
4574 
4575 bool AIXTargetCodeGenInfo::initDwarfEHRegSizeTable(
4576     CodeGen::CodeGenFunction &CGF, llvm::Value *Address) const {
4577   return PPC_initDwarfEHRegSizeTable(CGF, Address, Is64Bit, /*IsAIX*/ true);
4578 }
4579 
4580 // PowerPC-32
4581 namespace {
4582 /// PPC32_SVR4_ABIInfo - The 32-bit PowerPC ELF (SVR4) ABI information.
4583 class PPC32_SVR4_ABIInfo : public DefaultABIInfo {
4584   bool IsSoftFloatABI;
4585   bool IsRetSmallStructInRegABI;
4586 
4587   CharUnits getParamTypeAlignment(QualType Ty) const;
4588 
4589 public:
4590   PPC32_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, bool SoftFloatABI,
4591                      bool RetSmallStructInRegABI)
4592       : DefaultABIInfo(CGT), IsSoftFloatABI(SoftFloatABI),
4593         IsRetSmallStructInRegABI(RetSmallStructInRegABI) {}
4594 
4595   ABIArgInfo classifyReturnType(QualType RetTy) const;
4596 
4597   void computeInfo(CGFunctionInfo &FI) const override {
4598     if (!getCXXABI().classifyReturnType(FI))
4599       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
4600     for (auto &I : FI.arguments())
4601       I.info = classifyArgumentType(I.type);
4602   }
4603 
4604   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4605                     QualType Ty) const override;
4606 };
4607 
4608 class PPC32TargetCodeGenInfo : public TargetCodeGenInfo {
4609 public:
4610   PPC32TargetCodeGenInfo(CodeGenTypes &CGT, bool SoftFloatABI,
4611                          bool RetSmallStructInRegABI)
4612       : TargetCodeGenInfo(std::make_unique<PPC32_SVR4_ABIInfo>(
4613             CGT, SoftFloatABI, RetSmallStructInRegABI)) {}
4614 
4615   static bool isStructReturnInRegABI(const llvm::Triple &Triple,
4616                                      const CodeGenOptions &Opts);
4617 
4618   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4619     // This is recovered from gcc output.
4620     return 1; // r1 is the dedicated stack pointer
4621   }
4622 
4623   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4624                                llvm::Value *Address) const override;
4625 };
4626 }
4627 
4628 CharUnits PPC32_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const {
4629   // Complex types are passed just like their elements.
4630   if (const ComplexType *CTy = Ty->getAs<ComplexType>())
4631     Ty = CTy->getElementType();
4632 
4633   if (Ty->isVectorType())
4634     return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16
4635                                                                        : 4);
4636 
4637   // For single-element float/vector structs, we consider the whole type
4638   // to have the same alignment requirements as its single element.
4639   const Type *AlignTy = nullptr;
4640   if (const Type *EltType = isSingleElementStruct(Ty, getContext())) {
4641     const BuiltinType *BT = EltType->getAs<BuiltinType>();
4642     if ((EltType->isVectorType() && getContext().getTypeSize(EltType) == 128) ||
4643         (BT && BT->isFloatingPoint()))
4644       AlignTy = EltType;
4645   }
4646 
4647   if (AlignTy)
4648     return CharUnits::fromQuantity(AlignTy->isVectorType() ? 16 : 4);
4649   return CharUnits::fromQuantity(4);
4650 }
4651 
4652 ABIArgInfo PPC32_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
4653   uint64_t Size;
4654 
4655   // -msvr4-struct-return puts small aggregates in GPR3 and GPR4.
4656   if (isAggregateTypeForABI(RetTy) && IsRetSmallStructInRegABI &&
4657       (Size = getContext().getTypeSize(RetTy)) <= 64) {
4658     // System V ABI (1995), page 3-22, specified:
4659     // > A structure or union whose size is less than or equal to 8 bytes
4660     // > shall be returned in r3 and r4, as if it were first stored in the
4661     // > 8-byte aligned memory area and then the low addressed word were
4662     // > loaded into r3 and the high-addressed word into r4.  Bits beyond
4663     // > the last member of the structure or union are not defined.
4664     //
4665     // GCC for big-endian PPC32 inserts the pad before the first member,
4666     // not "beyond the last member" of the struct.  To stay compatible
4667     // with GCC, we coerce the struct to an integer of the same size.
4668     // LLVM will extend it and return i32 in r3, or i64 in r3:r4.
4669     if (Size == 0)
4670       return ABIArgInfo::getIgnore();
4671     else {
4672       llvm::Type *CoerceTy = llvm::Type::getIntNTy(getVMContext(), Size);
4673       return ABIArgInfo::getDirect(CoerceTy);
4674     }
4675   }
4676 
4677   return DefaultABIInfo::classifyReturnType(RetTy);
4678 }
4679 
4680 // TODO: this implementation is now likely redundant with
4681 // DefaultABIInfo::EmitVAArg.
4682 Address PPC32_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAList,
4683                                       QualType Ty) const {
4684   if (getTarget().getTriple().isOSDarwin()) {
4685     auto TI = getContext().getTypeInfoInChars(Ty);
4686     TI.Align = getParamTypeAlignment(Ty);
4687 
4688     CharUnits SlotSize = CharUnits::fromQuantity(4);
4689     return emitVoidPtrVAArg(CGF, VAList, Ty,
4690                             classifyArgumentType(Ty).isIndirect(), TI, SlotSize,
4691                             /*AllowHigherAlign=*/true);
4692   }
4693 
4694   const unsigned OverflowLimit = 8;
4695   if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
4696     // TODO: Implement this. For now ignore.
4697     (void)CTy;
4698     return Address::invalid(); // FIXME?
4699   }
4700 
4701   // struct __va_list_tag {
4702   //   unsigned char gpr;
4703   //   unsigned char fpr;
4704   //   unsigned short reserved;
4705   //   void *overflow_arg_area;
4706   //   void *reg_save_area;
4707   // };
4708 
4709   bool isI64 = Ty->isIntegerType() && getContext().getTypeSize(Ty) == 64;
4710   bool isInt = !Ty->isFloatingType();
4711   bool isF64 = Ty->isFloatingType() && getContext().getTypeSize(Ty) == 64;
4712 
4713   // All aggregates are passed indirectly?  That doesn't seem consistent
4714   // with the argument-lowering code.
4715   bool isIndirect = isAggregateTypeForABI(Ty);
4716 
4717   CGBuilderTy &Builder = CGF.Builder;
4718 
4719   // The calling convention either uses 1-2 GPRs or 1 FPR.
4720   Address NumRegsAddr = Address::invalid();
4721   if (isInt || IsSoftFloatABI) {
4722     NumRegsAddr = Builder.CreateStructGEP(VAList, 0, "gpr");
4723   } else {
4724     NumRegsAddr = Builder.CreateStructGEP(VAList, 1, "fpr");
4725   }
4726 
4727   llvm::Value *NumRegs = Builder.CreateLoad(NumRegsAddr, "numUsedRegs");
4728 
4729   // "Align" the register count when TY is i64.
4730   if (isI64 || (isF64 && IsSoftFloatABI)) {
4731     NumRegs = Builder.CreateAdd(NumRegs, Builder.getInt8(1));
4732     NumRegs = Builder.CreateAnd(NumRegs, Builder.getInt8((uint8_t) ~1U));
4733   }
4734 
4735   llvm::Value *CC =
4736       Builder.CreateICmpULT(NumRegs, Builder.getInt8(OverflowLimit), "cond");
4737 
4738   llvm::BasicBlock *UsingRegs = CGF.createBasicBlock("using_regs");
4739   llvm::BasicBlock *UsingOverflow = CGF.createBasicBlock("using_overflow");
4740   llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
4741 
4742   Builder.CreateCondBr(CC, UsingRegs, UsingOverflow);
4743 
4744   llvm::Type *DirectTy = CGF.ConvertType(Ty);
4745   if (isIndirect) DirectTy = DirectTy->getPointerTo(0);
4746 
4747   // Case 1: consume registers.
4748   Address RegAddr = Address::invalid();
4749   {
4750     CGF.EmitBlock(UsingRegs);
4751 
4752     Address RegSaveAreaPtr = Builder.CreateStructGEP(VAList, 4);
4753     RegAddr = Address(Builder.CreateLoad(RegSaveAreaPtr),
4754                       CharUnits::fromQuantity(8));
4755     assert(RegAddr.getElementType() == CGF.Int8Ty);
4756 
4757     // Floating-point registers start after the general-purpose registers.
4758     if (!(isInt || IsSoftFloatABI)) {
4759       RegAddr = Builder.CreateConstInBoundsByteGEP(RegAddr,
4760                                                    CharUnits::fromQuantity(32));
4761     }
4762 
4763     // Get the address of the saved value by scaling the number of
4764     // registers we've used by the number of
4765     CharUnits RegSize = CharUnits::fromQuantity((isInt || IsSoftFloatABI) ? 4 : 8);
4766     llvm::Value *RegOffset =
4767       Builder.CreateMul(NumRegs, Builder.getInt8(RegSize.getQuantity()));
4768     RegAddr = Address(Builder.CreateInBoundsGEP(CGF.Int8Ty,
4769                                             RegAddr.getPointer(), RegOffset),
4770                       RegAddr.getAlignment().alignmentOfArrayElement(RegSize));
4771     RegAddr = Builder.CreateElementBitCast(RegAddr, DirectTy);
4772 
4773     // Increase the used-register count.
4774     NumRegs =
4775       Builder.CreateAdd(NumRegs,
4776                         Builder.getInt8((isI64 || (isF64 && IsSoftFloatABI)) ? 2 : 1));
4777     Builder.CreateStore(NumRegs, NumRegsAddr);
4778 
4779     CGF.EmitBranch(Cont);
4780   }
4781 
4782   // Case 2: consume space in the overflow area.
4783   Address MemAddr = Address::invalid();
4784   {
4785     CGF.EmitBlock(UsingOverflow);
4786 
4787     Builder.CreateStore(Builder.getInt8(OverflowLimit), NumRegsAddr);
4788 
4789     // Everything in the overflow area is rounded up to a size of at least 4.
4790     CharUnits OverflowAreaAlign = CharUnits::fromQuantity(4);
4791 
4792     CharUnits Size;
4793     if (!isIndirect) {
4794       auto TypeInfo = CGF.getContext().getTypeInfoInChars(Ty);
4795       Size = TypeInfo.Width.alignTo(OverflowAreaAlign);
4796     } else {
4797       Size = CGF.getPointerSize();
4798     }
4799 
4800     Address OverflowAreaAddr = Builder.CreateStructGEP(VAList, 3);
4801     Address OverflowArea(Builder.CreateLoad(OverflowAreaAddr, "argp.cur"),
4802                          OverflowAreaAlign);
4803     // Round up address of argument to alignment
4804     CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
4805     if (Align > OverflowAreaAlign) {
4806       llvm::Value *Ptr = OverflowArea.getPointer();
4807       OverflowArea = Address(emitRoundPointerUpToAlignment(CGF, Ptr, Align),
4808                                                            Align);
4809     }
4810 
4811     MemAddr = Builder.CreateElementBitCast(OverflowArea, DirectTy);
4812 
4813     // Increase the overflow area.
4814     OverflowArea = Builder.CreateConstInBoundsByteGEP(OverflowArea, Size);
4815     Builder.CreateStore(OverflowArea.getPointer(), OverflowAreaAddr);
4816     CGF.EmitBranch(Cont);
4817   }
4818 
4819   CGF.EmitBlock(Cont);
4820 
4821   // Merge the cases with a phi.
4822   Address Result = emitMergePHI(CGF, RegAddr, UsingRegs, MemAddr, UsingOverflow,
4823                                 "vaarg.addr");
4824 
4825   // Load the pointer if the argument was passed indirectly.
4826   if (isIndirect) {
4827     Result = Address(Builder.CreateLoad(Result, "aggr"),
4828                      getContext().getTypeAlignInChars(Ty));
4829   }
4830 
4831   return Result;
4832 }
4833 
4834 bool PPC32TargetCodeGenInfo::isStructReturnInRegABI(
4835     const llvm::Triple &Triple, const CodeGenOptions &Opts) {
4836   assert(Triple.isPPC32());
4837 
4838   switch (Opts.getStructReturnConvention()) {
4839   case CodeGenOptions::SRCK_Default:
4840     break;
4841   case CodeGenOptions::SRCK_OnStack: // -maix-struct-return
4842     return false;
4843   case CodeGenOptions::SRCK_InRegs: // -msvr4-struct-return
4844     return true;
4845   }
4846 
4847   if (Triple.isOSBinFormatELF() && !Triple.isOSLinux())
4848     return true;
4849 
4850   return false;
4851 }
4852 
4853 bool
4854 PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4855                                                 llvm::Value *Address) const {
4856   return PPC_initDwarfEHRegSizeTable(CGF, Address, /*Is64Bit*/ false,
4857                                      /*IsAIX*/ false);
4858 }
4859 
4860 // PowerPC-64
4861 
4862 namespace {
4863 /// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
4864 class PPC64_SVR4_ABIInfo : public SwiftABIInfo {
4865 public:
4866   enum ABIKind {
4867     ELFv1 = 0,
4868     ELFv2
4869   };
4870 
4871 private:
4872   static const unsigned GPRBits = 64;
4873   ABIKind Kind;
4874   bool IsSoftFloatABI;
4875 
4876 public:
4877   PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind,
4878                      bool SoftFloatABI)
4879       : SwiftABIInfo(CGT), Kind(Kind), IsSoftFloatABI(SoftFloatABI) {}
4880 
4881   bool isPromotableTypeForABI(QualType Ty) const;
4882   CharUnits getParamTypeAlignment(QualType Ty) const;
4883 
4884   ABIArgInfo classifyReturnType(QualType RetTy) const;
4885   ABIArgInfo classifyArgumentType(QualType Ty) const;
4886 
4887   bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4888   bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4889                                          uint64_t Members) const override;
4890 
4891   // TODO: We can add more logic to computeInfo to improve performance.
4892   // Example: For aggregate arguments that fit in a register, we could
4893   // use getDirectInReg (as is done below for structs containing a single
4894   // floating-point value) to avoid pushing them to memory on function
4895   // entry.  This would require changing the logic in PPCISelLowering
4896   // when lowering the parameters in the caller and args in the callee.
4897   void computeInfo(CGFunctionInfo &FI) const override {
4898     if (!getCXXABI().classifyReturnType(FI))
4899       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
4900     for (auto &I : FI.arguments()) {
4901       // We rely on the default argument classification for the most part.
4902       // One exception:  An aggregate containing a single floating-point
4903       // or vector item must be passed in a register if one is available.
4904       const Type *T = isSingleElementStruct(I.type, getContext());
4905       if (T) {
4906         const BuiltinType *BT = T->getAs<BuiltinType>();
4907         if ((T->isVectorType() && getContext().getTypeSize(T) == 128) ||
4908             (BT && BT->isFloatingPoint())) {
4909           QualType QT(T, 0);
4910           I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
4911           continue;
4912         }
4913       }
4914       I.info = classifyArgumentType(I.type);
4915     }
4916   }
4917 
4918   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4919                     QualType Ty) const override;
4920 
4921   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
4922                                     bool asReturnValue) const override {
4923     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
4924   }
4925 
4926   bool isSwiftErrorInRegister() const override {
4927     return false;
4928   }
4929 };
4930 
4931 class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
4932 
4933 public:
4934   PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT,
4935                                PPC64_SVR4_ABIInfo::ABIKind Kind,
4936                                bool SoftFloatABI)
4937       : TargetCodeGenInfo(
4938             std::make_unique<PPC64_SVR4_ABIInfo>(CGT, Kind, SoftFloatABI)) {}
4939 
4940   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4941     // This is recovered from gcc output.
4942     return 1; // r1 is the dedicated stack pointer
4943   }
4944 
4945   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4946                                llvm::Value *Address) const override;
4947 };
4948 
4949 class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
4950 public:
4951   PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
4952 
4953   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4954     // This is recovered from gcc output.
4955     return 1; // r1 is the dedicated stack pointer
4956   }
4957 
4958   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4959                                llvm::Value *Address) const override;
4960 };
4961 
4962 }
4963 
4964 // Return true if the ABI requires Ty to be passed sign- or zero-
4965 // extended to 64 bits.
4966 bool
4967 PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
4968   // Treat an enum type as its underlying type.
4969   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4970     Ty = EnumTy->getDecl()->getIntegerType();
4971 
4972   // Promotable integer types are required to be promoted by the ABI.
4973   if (isPromotableIntegerTypeForABI(Ty))
4974     return true;
4975 
4976   // In addition to the usual promotable integer types, we also need to
4977   // extend all 32-bit types, since the ABI requires promotion to 64 bits.
4978   if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
4979     switch (BT->getKind()) {
4980     case BuiltinType::Int:
4981     case BuiltinType::UInt:
4982       return true;
4983     default:
4984       break;
4985     }
4986 
4987   if (const auto *EIT = Ty->getAs<ExtIntType>())
4988     if (EIT->getNumBits() < 64)
4989       return true;
4990 
4991   return false;
4992 }
4993 
4994 /// isAlignedParamType - Determine whether a type requires 16-byte or
4995 /// higher alignment in the parameter area.  Always returns at least 8.
4996 CharUnits PPC64_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const {
4997   // Complex types are passed just like their elements.
4998   if (const ComplexType *CTy = Ty->getAs<ComplexType>())
4999     Ty = CTy->getElementType();
5000 
5001   // Only vector types of size 16 bytes need alignment (larger types are
5002   // passed via reference, smaller types are not aligned).
5003   if (Ty->isVectorType()) {
5004     return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16 : 8);
5005   } else if (Ty->isRealFloatingType() &&
5006              &getContext().getFloatTypeSemantics(Ty) ==
5007                  &llvm::APFloat::IEEEquad()) {
5008     // According to ABI document section 'Optional Save Areas': If extended
5009     // precision floating-point values in IEEE BINARY 128 QUADRUPLE PRECISION
5010     // format are supported, map them to a single quadword, quadword aligned.
5011     return CharUnits::fromQuantity(16);
5012   }
5013 
5014   // For single-element float/vector structs, we consider the whole type
5015   // to have the same alignment requirements as its single element.
5016   const Type *AlignAsType = nullptr;
5017   const Type *EltType = isSingleElementStruct(Ty, getContext());
5018   if (EltType) {
5019     const BuiltinType *BT = EltType->getAs<BuiltinType>();
5020     if ((EltType->isVectorType() && getContext().getTypeSize(EltType) == 128) ||
5021         (BT && BT->isFloatingPoint()))
5022       AlignAsType = EltType;
5023   }
5024 
5025   // Likewise for ELFv2 homogeneous aggregates.
5026   const Type *Base = nullptr;
5027   uint64_t Members = 0;
5028   if (!AlignAsType && Kind == ELFv2 &&
5029       isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members))
5030     AlignAsType = Base;
5031 
5032   // With special case aggregates, only vector base types need alignment.
5033   if (AlignAsType) {
5034     return CharUnits::fromQuantity(AlignAsType->isVectorType() ? 16 : 8);
5035   }
5036 
5037   // Otherwise, we only need alignment for any aggregate type that
5038   // has an alignment requirement of >= 16 bytes.
5039   if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128) {
5040     return CharUnits::fromQuantity(16);
5041   }
5042 
5043   return CharUnits::fromQuantity(8);
5044 }
5045 
5046 /// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous
5047 /// aggregate.  Base is set to the base element type, and Members is set
5048 /// to the number of base elements.
5049 bool ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base,
5050                                      uint64_t &Members) const {
5051   if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
5052     uint64_t NElements = AT->getSize().getZExtValue();
5053     if (NElements == 0)
5054       return false;
5055     if (!isHomogeneousAggregate(AT->getElementType(), Base, Members))
5056       return false;
5057     Members *= NElements;
5058   } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
5059     const RecordDecl *RD = RT->getDecl();
5060     if (RD->hasFlexibleArrayMember())
5061       return false;
5062 
5063     Members = 0;
5064 
5065     // If this is a C++ record, check the properties of the record such as
5066     // bases and ABI specific restrictions
5067     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
5068       if (!getCXXABI().isPermittedToBeHomogeneousAggregate(CXXRD))
5069         return false;
5070 
5071       for (const auto &I : CXXRD->bases()) {
5072         // Ignore empty records.
5073         if (isEmptyRecord(getContext(), I.getType(), true))
5074           continue;
5075 
5076         uint64_t FldMembers;
5077         if (!isHomogeneousAggregate(I.getType(), Base, FldMembers))
5078           return false;
5079 
5080         Members += FldMembers;
5081       }
5082     }
5083 
5084     for (const auto *FD : RD->fields()) {
5085       // Ignore (non-zero arrays of) empty records.
5086       QualType FT = FD->getType();
5087       while (const ConstantArrayType *AT =
5088              getContext().getAsConstantArrayType(FT)) {
5089         if (AT->getSize().getZExtValue() == 0)
5090           return false;
5091         FT = AT->getElementType();
5092       }
5093       if (isEmptyRecord(getContext(), FT, true))
5094         continue;
5095 
5096       // For compatibility with GCC, ignore empty bitfields in C++ mode.
5097       if (getContext().getLangOpts().CPlusPlus &&
5098           FD->isZeroLengthBitField(getContext()))
5099         continue;
5100 
5101       uint64_t FldMembers;
5102       if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers))
5103         return false;
5104 
5105       Members = (RD->isUnion() ?
5106                  std::max(Members, FldMembers) : Members + FldMembers);
5107     }
5108 
5109     if (!Base)
5110       return false;
5111 
5112     // Ensure there is no padding.
5113     if (getContext().getTypeSize(Base) * Members !=
5114         getContext().getTypeSize(Ty))
5115       return false;
5116   } else {
5117     Members = 1;
5118     if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
5119       Members = 2;
5120       Ty = CT->getElementType();
5121     }
5122 
5123     // Most ABIs only support float, double, and some vector type widths.
5124     if (!isHomogeneousAggregateBaseType(Ty))
5125       return false;
5126 
5127     // The base type must be the same for all members.  Types that
5128     // agree in both total size and mode (float vs. vector) are
5129     // treated as being equivalent here.
5130     const Type *TyPtr = Ty.getTypePtr();
5131     if (!Base) {
5132       Base = TyPtr;
5133       // If it's a non-power-of-2 vector, its size is already a power-of-2,
5134       // so make sure to widen it explicitly.
5135       if (const VectorType *VT = Base->getAs<VectorType>()) {
5136         QualType EltTy = VT->getElementType();
5137         unsigned NumElements =
5138             getContext().getTypeSize(VT) / getContext().getTypeSize(EltTy);
5139         Base = getContext()
5140                    .getVectorType(EltTy, NumElements, VT->getVectorKind())
5141                    .getTypePtr();
5142       }
5143     }
5144 
5145     if (Base->isVectorType() != TyPtr->isVectorType() ||
5146         getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr))
5147       return false;
5148   }
5149   return Members > 0 && isHomogeneousAggregateSmallEnough(Base, Members);
5150 }
5151 
5152 bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
5153   // Homogeneous aggregates for ELFv2 must have base types of float,
5154   // double, long double, or 128-bit vectors.
5155   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
5156     if (BT->getKind() == BuiltinType::Float ||
5157         BT->getKind() == BuiltinType::Double ||
5158         BT->getKind() == BuiltinType::LongDouble ||
5159         (getContext().getTargetInfo().hasFloat128Type() &&
5160           (BT->getKind() == BuiltinType::Float128))) {
5161       if (IsSoftFloatABI)
5162         return false;
5163       return true;
5164     }
5165   }
5166   if (const VectorType *VT = Ty->getAs<VectorType>()) {
5167     if (getContext().getTypeSize(VT) == 128)
5168       return true;
5169   }
5170   return false;
5171 }
5172 
5173 bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateSmallEnough(
5174     const Type *Base, uint64_t Members) const {
5175   // Vector and fp128 types require one register, other floating point types
5176   // require one or two registers depending on their size.
5177   uint32_t NumRegs =
5178       ((getContext().getTargetInfo().hasFloat128Type() &&
5179           Base->isFloat128Type()) ||
5180         Base->isVectorType()) ? 1
5181                               : (getContext().getTypeSize(Base) + 63) / 64;
5182 
5183   // Homogeneous Aggregates may occupy at most 8 registers.
5184   return Members * NumRegs <= 8;
5185 }
5186 
5187 ABIArgInfo
5188 PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
5189   Ty = useFirstFieldIfTransparentUnion(Ty);
5190 
5191   if (Ty->isAnyComplexType())
5192     return ABIArgInfo::getDirect();
5193 
5194   // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes)
5195   // or via reference (larger than 16 bytes).
5196   if (Ty->isVectorType()) {
5197     uint64_t Size = getContext().getTypeSize(Ty);
5198     if (Size > 128)
5199       return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
5200     else if (Size < 128) {
5201       llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
5202       return ABIArgInfo::getDirect(CoerceTy);
5203     }
5204   }
5205 
5206   if (const auto *EIT = Ty->getAs<ExtIntType>())
5207     if (EIT->getNumBits() > 128)
5208       return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
5209 
5210   if (isAggregateTypeForABI(Ty)) {
5211     if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
5212       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
5213 
5214     uint64_t ABIAlign = getParamTypeAlignment(Ty).getQuantity();
5215     uint64_t TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity();
5216 
5217     // ELFv2 homogeneous aggregates are passed as array types.
5218     const Type *Base = nullptr;
5219     uint64_t Members = 0;
5220     if (Kind == ELFv2 &&
5221         isHomogeneousAggregate(Ty, Base, Members)) {
5222       llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
5223       llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
5224       return ABIArgInfo::getDirect(CoerceTy);
5225     }
5226 
5227     // If an aggregate may end up fully in registers, we do not
5228     // use the ByVal method, but pass the aggregate as array.
5229     // This is usually beneficial since we avoid forcing the
5230     // back-end to store the argument to memory.
5231     uint64_t Bits = getContext().getTypeSize(Ty);
5232     if (Bits > 0 && Bits <= 8 * GPRBits) {
5233       llvm::Type *CoerceTy;
5234 
5235       // Types up to 8 bytes are passed as integer type (which will be
5236       // properly aligned in the argument save area doubleword).
5237       if (Bits <= GPRBits)
5238         CoerceTy =
5239             llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
5240       // Larger types are passed as arrays, with the base type selected
5241       // according to the required alignment in the save area.
5242       else {
5243         uint64_t RegBits = ABIAlign * 8;
5244         uint64_t NumRegs = llvm::alignTo(Bits, RegBits) / RegBits;
5245         llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits);
5246         CoerceTy = llvm::ArrayType::get(RegTy, NumRegs);
5247       }
5248 
5249       return ABIArgInfo::getDirect(CoerceTy);
5250     }
5251 
5252     // All other aggregates are passed ByVal.
5253     return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
5254                                    /*ByVal=*/true,
5255                                    /*Realign=*/TyAlign > ABIAlign);
5256   }
5257 
5258   return (isPromotableTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
5259                                      : ABIArgInfo::getDirect());
5260 }
5261 
5262 ABIArgInfo
5263 PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
5264   if (RetTy->isVoidType())
5265     return ABIArgInfo::getIgnore();
5266 
5267   if (RetTy->isAnyComplexType())
5268     return ABIArgInfo::getDirect();
5269 
5270   // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes)
5271   // or via reference (larger than 16 bytes).
5272   if (RetTy->isVectorType()) {
5273     uint64_t Size = getContext().getTypeSize(RetTy);
5274     if (Size > 128)
5275       return getNaturalAlignIndirect(RetTy);
5276     else if (Size < 128) {
5277       llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
5278       return ABIArgInfo::getDirect(CoerceTy);
5279     }
5280   }
5281 
5282   if (const auto *EIT = RetTy->getAs<ExtIntType>())
5283     if (EIT->getNumBits() > 128)
5284       return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
5285 
5286   if (isAggregateTypeForABI(RetTy)) {
5287     // ELFv2 homogeneous aggregates are returned as array types.
5288     const Type *Base = nullptr;
5289     uint64_t Members = 0;
5290     if (Kind == ELFv2 &&
5291         isHomogeneousAggregate(RetTy, Base, Members)) {
5292       llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
5293       llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
5294       return ABIArgInfo::getDirect(CoerceTy);
5295     }
5296 
5297     // ELFv2 small aggregates are returned in up to two registers.
5298     uint64_t Bits = getContext().getTypeSize(RetTy);
5299     if (Kind == ELFv2 && Bits <= 2 * GPRBits) {
5300       if (Bits == 0)
5301         return ABIArgInfo::getIgnore();
5302 
5303       llvm::Type *CoerceTy;
5304       if (Bits > GPRBits) {
5305         CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits);
5306         CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy);
5307       } else
5308         CoerceTy =
5309             llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
5310       return ABIArgInfo::getDirect(CoerceTy);
5311     }
5312 
5313     // All other aggregates are returned indirectly.
5314     return getNaturalAlignIndirect(RetTy);
5315   }
5316 
5317   return (isPromotableTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
5318                                         : ABIArgInfo::getDirect());
5319 }
5320 
5321 // Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
5322 Address PPC64_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5323                                       QualType Ty) const {
5324   auto TypeInfo = getContext().getTypeInfoInChars(Ty);
5325   TypeInfo.Align = getParamTypeAlignment(Ty);
5326 
5327   CharUnits SlotSize = CharUnits::fromQuantity(8);
5328 
5329   // If we have a complex type and the base type is smaller than 8 bytes,
5330   // the ABI calls for the real and imaginary parts to be right-adjusted
5331   // in separate doublewords.  However, Clang expects us to produce a
5332   // pointer to a structure with the two parts packed tightly.  So generate
5333   // loads of the real and imaginary parts relative to the va_list pointer,
5334   // and store them to a temporary structure.
5335   if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
5336     CharUnits EltSize = TypeInfo.Width / 2;
5337     if (EltSize < SlotSize) {
5338       Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, CGF.Int8Ty,
5339                                             SlotSize * 2, SlotSize,
5340                                             SlotSize, /*AllowHigher*/ true);
5341 
5342       Address RealAddr = Addr;
5343       Address ImagAddr = RealAddr;
5344       if (CGF.CGM.getDataLayout().isBigEndian()) {
5345         RealAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr,
5346                                                           SlotSize - EltSize);
5347         ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(ImagAddr,
5348                                                       2 * SlotSize - EltSize);
5349       } else {
5350         ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, SlotSize);
5351       }
5352 
5353       llvm::Type *EltTy = CGF.ConvertTypeForMem(CTy->getElementType());
5354       RealAddr = CGF.Builder.CreateElementBitCast(RealAddr, EltTy);
5355       ImagAddr = CGF.Builder.CreateElementBitCast(ImagAddr, EltTy);
5356       llvm::Value *Real = CGF.Builder.CreateLoad(RealAddr, ".vareal");
5357       llvm::Value *Imag = CGF.Builder.CreateLoad(ImagAddr, ".vaimag");
5358 
5359       Address Temp = CGF.CreateMemTemp(Ty, "vacplx");
5360       CGF.EmitStoreOfComplex({Real, Imag}, CGF.MakeAddrLValue(Temp, Ty),
5361                              /*init*/ true);
5362       return Temp;
5363     }
5364   }
5365 
5366   // Otherwise, just use the general rule.
5367   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
5368                           TypeInfo, SlotSize, /*AllowHigher*/ true);
5369 }
5370 
5371 bool
5372 PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
5373   CodeGen::CodeGenFunction &CGF,
5374   llvm::Value *Address) const {
5375   return PPC_initDwarfEHRegSizeTable(CGF, Address, /*Is64Bit*/ true,
5376                                      /*IsAIX*/ false);
5377 }
5378 
5379 bool
5380 PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
5381                                                 llvm::Value *Address) const {
5382   return PPC_initDwarfEHRegSizeTable(CGF, Address, /*Is64Bit*/ true,
5383                                      /*IsAIX*/ false);
5384 }
5385 
5386 //===----------------------------------------------------------------------===//
5387 // AArch64 ABI Implementation
5388 //===----------------------------------------------------------------------===//
5389 
5390 namespace {
5391 
5392 class AArch64ABIInfo : public SwiftABIInfo {
5393 public:
5394   enum ABIKind {
5395     AAPCS = 0,
5396     DarwinPCS,
5397     Win64
5398   };
5399 
5400 private:
5401   ABIKind Kind;
5402 
5403 public:
5404   AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind)
5405     : SwiftABIInfo(CGT), Kind(Kind) {}
5406 
5407 private:
5408   ABIKind getABIKind() const { return Kind; }
5409   bool isDarwinPCS() const { return Kind == DarwinPCS; }
5410 
5411   ABIArgInfo classifyReturnType(QualType RetTy, bool IsVariadic) const;
5412   ABIArgInfo classifyArgumentType(QualType RetTy) const;
5413   ABIArgInfo coerceIllegalVector(QualType Ty) const;
5414   bool isHomogeneousAggregateBaseType(QualType Ty) const override;
5415   bool isHomogeneousAggregateSmallEnough(const Type *Ty,
5416                                          uint64_t Members) const override;
5417 
5418   bool isIllegalVectorType(QualType Ty) const;
5419 
5420   void computeInfo(CGFunctionInfo &FI) const override {
5421     if (!::classifyReturnType(getCXXABI(), FI, *this))
5422       FI.getReturnInfo() =
5423           classifyReturnType(FI.getReturnType(), FI.isVariadic());
5424 
5425     for (auto &it : FI.arguments())
5426       it.info = classifyArgumentType(it.type);
5427   }
5428 
5429   Address EmitDarwinVAArg(Address VAListAddr, QualType Ty,
5430                           CodeGenFunction &CGF) const;
5431 
5432   Address EmitAAPCSVAArg(Address VAListAddr, QualType Ty,
5433                          CodeGenFunction &CGF) const;
5434 
5435   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5436                     QualType Ty) const override {
5437     llvm::Type *BaseTy = CGF.ConvertType(Ty);
5438     if (isa<llvm::ScalableVectorType>(BaseTy))
5439       llvm::report_fatal_error("Passing SVE types to variadic functions is "
5440                                "currently not supported");
5441 
5442     return Kind == Win64 ? EmitMSVAArg(CGF, VAListAddr, Ty)
5443                          : isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF)
5444                                          : EmitAAPCSVAArg(VAListAddr, Ty, CGF);
5445   }
5446 
5447   Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
5448                       QualType Ty) const override;
5449 
5450   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
5451                                     bool asReturnValue) const override {
5452     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
5453   }
5454   bool isSwiftErrorInRegister() const override {
5455     return true;
5456   }
5457 
5458   bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy,
5459                                  unsigned elts) const override;
5460 
5461   bool allowBFloatArgsAndRet() const override {
5462     return getTarget().hasBFloat16Type();
5463   }
5464 };
5465 
5466 class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
5467 public:
5468   AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind)
5469       : TargetCodeGenInfo(std::make_unique<AArch64ABIInfo>(CGT, Kind)) {}
5470 
5471   StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
5472     return "mov\tfp, fp\t\t// marker for objc_retainAutoreleaseReturnValue";
5473   }
5474 
5475   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
5476     return 31;
5477   }
5478 
5479   bool doesReturnSlotInterfereWithArgs() const override { return false; }
5480 
5481   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5482                            CodeGen::CodeGenModule &CGM) const override {
5483     const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
5484     if (!FD)
5485       return;
5486 
5487     const auto *TA = FD->getAttr<TargetAttr>();
5488     if (TA == nullptr)
5489       return;
5490 
5491     ParsedTargetAttr Attr = TA->parse();
5492     if (Attr.BranchProtection.empty())
5493       return;
5494 
5495     TargetInfo::BranchProtectionInfo BPI;
5496     StringRef Error;
5497     (void)CGM.getTarget().validateBranchProtection(Attr.BranchProtection,
5498                                                    BPI, Error);
5499     assert(Error.empty());
5500 
5501     auto *Fn = cast<llvm::Function>(GV);
5502     static const char *SignReturnAddrStr[] = {"none", "non-leaf", "all"};
5503     Fn->addFnAttr("sign-return-address", SignReturnAddrStr[static_cast<int>(BPI.SignReturnAddr)]);
5504 
5505     if (BPI.SignReturnAddr != LangOptions::SignReturnAddressScopeKind::None) {
5506       Fn->addFnAttr("sign-return-address-key",
5507                     BPI.SignKey == LangOptions::SignReturnAddressKeyKind::AKey
5508                         ? "a_key"
5509                         : "b_key");
5510     }
5511 
5512     Fn->addFnAttr("branch-target-enforcement",
5513                   BPI.BranchTargetEnforcement ? "true" : "false");
5514   }
5515 };
5516 
5517 class WindowsAArch64TargetCodeGenInfo : public AArch64TargetCodeGenInfo {
5518 public:
5519   WindowsAArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind K)
5520       : AArch64TargetCodeGenInfo(CGT, K) {}
5521 
5522   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5523                            CodeGen::CodeGenModule &CGM) const override;
5524 
5525   void getDependentLibraryOption(llvm::StringRef Lib,
5526                                  llvm::SmallString<24> &Opt) const override {
5527     Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib);
5528   }
5529 
5530   void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value,
5531                                llvm::SmallString<32> &Opt) const override {
5532     Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
5533   }
5534 };
5535 
5536 void WindowsAArch64TargetCodeGenInfo::setTargetAttributes(
5537     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
5538   AArch64TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
5539   if (GV->isDeclaration())
5540     return;
5541   addStackProbeTargetAttributes(D, GV, CGM);
5542 }
5543 }
5544 
5545 ABIArgInfo AArch64ABIInfo::coerceIllegalVector(QualType Ty) const {
5546   assert(Ty->isVectorType() && "expected vector type!");
5547 
5548   const auto *VT = Ty->castAs<VectorType>();
5549   if (VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector) {
5550     assert(VT->getElementType()->isBuiltinType() && "expected builtin type!");
5551     assert(VT->getElementType()->castAs<BuiltinType>()->getKind() ==
5552                BuiltinType::UChar &&
5553            "unexpected builtin type for SVE predicate!");
5554     return ABIArgInfo::getDirect(llvm::ScalableVectorType::get(
5555         llvm::Type::getInt1Ty(getVMContext()), 16));
5556   }
5557 
5558   if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector) {
5559     assert(VT->getElementType()->isBuiltinType() && "expected builtin type!");
5560 
5561     const auto *BT = VT->getElementType()->castAs<BuiltinType>();
5562     llvm::ScalableVectorType *ResType = nullptr;
5563     switch (BT->getKind()) {
5564     default:
5565       llvm_unreachable("unexpected builtin type for SVE vector!");
5566     case BuiltinType::SChar:
5567     case BuiltinType::UChar:
5568       ResType = llvm::ScalableVectorType::get(
5569           llvm::Type::getInt8Ty(getVMContext()), 16);
5570       break;
5571     case BuiltinType::Short:
5572     case BuiltinType::UShort:
5573       ResType = llvm::ScalableVectorType::get(
5574           llvm::Type::getInt16Ty(getVMContext()), 8);
5575       break;
5576     case BuiltinType::Int:
5577     case BuiltinType::UInt:
5578       ResType = llvm::ScalableVectorType::get(
5579           llvm::Type::getInt32Ty(getVMContext()), 4);
5580       break;
5581     case BuiltinType::Long:
5582     case BuiltinType::ULong:
5583       ResType = llvm::ScalableVectorType::get(
5584           llvm::Type::getInt64Ty(getVMContext()), 2);
5585       break;
5586     case BuiltinType::Half:
5587       ResType = llvm::ScalableVectorType::get(
5588           llvm::Type::getHalfTy(getVMContext()), 8);
5589       break;
5590     case BuiltinType::Float:
5591       ResType = llvm::ScalableVectorType::get(
5592           llvm::Type::getFloatTy(getVMContext()), 4);
5593       break;
5594     case BuiltinType::Double:
5595       ResType = llvm::ScalableVectorType::get(
5596           llvm::Type::getDoubleTy(getVMContext()), 2);
5597       break;
5598     case BuiltinType::BFloat16:
5599       ResType = llvm::ScalableVectorType::get(
5600           llvm::Type::getBFloatTy(getVMContext()), 8);
5601       break;
5602     }
5603     return ABIArgInfo::getDirect(ResType);
5604   }
5605 
5606   uint64_t Size = getContext().getTypeSize(Ty);
5607   // Android promotes <2 x i8> to i16, not i32
5608   if (isAndroid() && (Size <= 16)) {
5609     llvm::Type *ResType = llvm::Type::getInt16Ty(getVMContext());
5610     return ABIArgInfo::getDirect(ResType);
5611   }
5612   if (Size <= 32) {
5613     llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext());
5614     return ABIArgInfo::getDirect(ResType);
5615   }
5616   if (Size == 64) {
5617     auto *ResType =
5618         llvm::FixedVectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2);
5619     return ABIArgInfo::getDirect(ResType);
5620   }
5621   if (Size == 128) {
5622     auto *ResType =
5623         llvm::FixedVectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4);
5624     return ABIArgInfo::getDirect(ResType);
5625   }
5626   return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
5627 }
5628 
5629 ABIArgInfo AArch64ABIInfo::classifyArgumentType(QualType Ty) const {
5630   Ty = useFirstFieldIfTransparentUnion(Ty);
5631 
5632   // Handle illegal vector types here.
5633   if (isIllegalVectorType(Ty))
5634     return coerceIllegalVector(Ty);
5635 
5636   if (!isAggregateTypeForABI(Ty)) {
5637     // Treat an enum type as its underlying type.
5638     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5639       Ty = EnumTy->getDecl()->getIntegerType();
5640 
5641     if (const auto *EIT = Ty->getAs<ExtIntType>())
5642       if (EIT->getNumBits() > 128)
5643         return getNaturalAlignIndirect(Ty);
5644 
5645     return (isPromotableIntegerTypeForABI(Ty) && isDarwinPCS()
5646                 ? ABIArgInfo::getExtend(Ty)
5647                 : ABIArgInfo::getDirect());
5648   }
5649 
5650   // Structures with either a non-trivial destructor or a non-trivial
5651   // copy constructor are always indirect.
5652   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
5653     return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA ==
5654                                      CGCXXABI::RAA_DirectInMemory);
5655   }
5656 
5657   // Empty records are always ignored on Darwin, but actually passed in C++ mode
5658   // elsewhere for GNU compatibility.
5659   uint64_t Size = getContext().getTypeSize(Ty);
5660   bool IsEmpty = isEmptyRecord(getContext(), Ty, true);
5661   if (IsEmpty || Size == 0) {
5662     if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS())
5663       return ABIArgInfo::getIgnore();
5664 
5665     // GNU C mode. The only argument that gets ignored is an empty one with size
5666     // 0.
5667     if (IsEmpty && Size == 0)
5668       return ABIArgInfo::getIgnore();
5669     return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
5670   }
5671 
5672   // Homogeneous Floating-point Aggregates (HFAs) need to be expanded.
5673   const Type *Base = nullptr;
5674   uint64_t Members = 0;
5675   if (isHomogeneousAggregate(Ty, Base, Members)) {
5676     return ABIArgInfo::getDirect(
5677         llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members));
5678   }
5679 
5680   // Aggregates <= 16 bytes are passed directly in registers or on the stack.
5681   if (Size <= 128) {
5682     // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
5683     // same size and alignment.
5684     if (getTarget().isRenderScriptTarget()) {
5685       return coerceToIntArray(Ty, getContext(), getVMContext());
5686     }
5687     unsigned Alignment;
5688     if (Kind == AArch64ABIInfo::AAPCS) {
5689       Alignment = getContext().getTypeUnadjustedAlign(Ty);
5690       Alignment = Alignment < 128 ? 64 : 128;
5691     } else {
5692       Alignment = std::max(getContext().getTypeAlign(Ty),
5693                            (unsigned)getTarget().getPointerWidth(0));
5694     }
5695     Size = llvm::alignTo(Size, Alignment);
5696 
5697     // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
5698     // For aggregates with 16-byte alignment, we use i128.
5699     llvm::Type *BaseTy = llvm::Type::getIntNTy(getVMContext(), Alignment);
5700     return ABIArgInfo::getDirect(
5701         Size == Alignment ? BaseTy
5702                           : llvm::ArrayType::get(BaseTy, Size / Alignment));
5703   }
5704 
5705   return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
5706 }
5707 
5708 ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy,
5709                                               bool IsVariadic) const {
5710   if (RetTy->isVoidType())
5711     return ABIArgInfo::getIgnore();
5712 
5713   if (const auto *VT = RetTy->getAs<VectorType>()) {
5714     if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector ||
5715         VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector)
5716       return coerceIllegalVector(RetTy);
5717   }
5718 
5719   // Large vector types should be returned via memory.
5720   if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
5721     return getNaturalAlignIndirect(RetTy);
5722 
5723   if (!isAggregateTypeForABI(RetTy)) {
5724     // Treat an enum type as its underlying type.
5725     if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5726       RetTy = EnumTy->getDecl()->getIntegerType();
5727 
5728     if (const auto *EIT = RetTy->getAs<ExtIntType>())
5729       if (EIT->getNumBits() > 128)
5730         return getNaturalAlignIndirect(RetTy);
5731 
5732     return (isPromotableIntegerTypeForABI(RetTy) && isDarwinPCS()
5733                 ? ABIArgInfo::getExtend(RetTy)
5734                 : ABIArgInfo::getDirect());
5735   }
5736 
5737   uint64_t Size = getContext().getTypeSize(RetTy);
5738   if (isEmptyRecord(getContext(), RetTy, true) || Size == 0)
5739     return ABIArgInfo::getIgnore();
5740 
5741   const Type *Base = nullptr;
5742   uint64_t Members = 0;
5743   if (isHomogeneousAggregate(RetTy, Base, Members) &&
5744       !(getTarget().getTriple().getArch() == llvm::Triple::aarch64_32 &&
5745         IsVariadic))
5746     // Homogeneous Floating-point Aggregates (HFAs) are returned directly.
5747     return ABIArgInfo::getDirect();
5748 
5749   // Aggregates <= 16 bytes are returned directly in registers or on the stack.
5750   if (Size <= 128) {
5751     // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
5752     // same size and alignment.
5753     if (getTarget().isRenderScriptTarget()) {
5754       return coerceToIntArray(RetTy, getContext(), getVMContext());
5755     }
5756     unsigned Alignment = getContext().getTypeAlign(RetTy);
5757     Size = llvm::alignTo(Size, 64); // round up to multiple of 8 bytes
5758 
5759     // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
5760     // For aggregates with 16-byte alignment, we use i128.
5761     if (Alignment < 128 && Size == 128) {
5762       llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
5763       return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
5764     }
5765     return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
5766   }
5767 
5768   return getNaturalAlignIndirect(RetTy);
5769 }
5770 
5771 /// isIllegalVectorType - check whether the vector type is legal for AArch64.
5772 bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const {
5773   if (const VectorType *VT = Ty->getAs<VectorType>()) {
5774     // Check whether VT is a fixed-length SVE vector. These types are
5775     // represented as scalable vectors in function args/return and must be
5776     // coerced from fixed vectors.
5777     if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector ||
5778         VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector)
5779       return true;
5780 
5781     // Check whether VT is legal.
5782     unsigned NumElements = VT->getNumElements();
5783     uint64_t Size = getContext().getTypeSize(VT);
5784     // NumElements should be power of 2.
5785     if (!llvm::isPowerOf2_32(NumElements))
5786       return true;
5787 
5788     // arm64_32 has to be compatible with the ARM logic here, which allows huge
5789     // vectors for some reason.
5790     llvm::Triple Triple = getTarget().getTriple();
5791     if (Triple.getArch() == llvm::Triple::aarch64_32 &&
5792         Triple.isOSBinFormatMachO())
5793       return Size <= 32;
5794 
5795     return Size != 64 && (Size != 128 || NumElements == 1);
5796   }
5797   return false;
5798 }
5799 
5800 bool AArch64ABIInfo::isLegalVectorTypeForSwift(CharUnits totalSize,
5801                                                llvm::Type *eltTy,
5802                                                unsigned elts) const {
5803   if (!llvm::isPowerOf2_32(elts))
5804     return false;
5805   if (totalSize.getQuantity() != 8 &&
5806       (totalSize.getQuantity() != 16 || elts == 1))
5807     return false;
5808   return true;
5809 }
5810 
5811 bool AArch64ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
5812   // Homogeneous aggregates for AAPCS64 must have base types of a floating
5813   // point type or a short-vector type. This is the same as the 32-bit ABI,
5814   // but with the difference that any floating-point type is allowed,
5815   // including __fp16.
5816   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
5817     if (BT->isFloatingPoint())
5818       return true;
5819   } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
5820     unsigned VecSize = getContext().getTypeSize(VT);
5821     if (VecSize == 64 || VecSize == 128)
5822       return true;
5823   }
5824   return false;
5825 }
5826 
5827 bool AArch64ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
5828                                                        uint64_t Members) const {
5829   return Members <= 4;
5830 }
5831 
5832 Address AArch64ABIInfo::EmitAAPCSVAArg(Address VAListAddr,
5833                                             QualType Ty,
5834                                             CodeGenFunction &CGF) const {
5835   ABIArgInfo AI = classifyArgumentType(Ty);
5836   bool IsIndirect = AI.isIndirect();
5837 
5838   llvm::Type *BaseTy = CGF.ConvertType(Ty);
5839   if (IsIndirect)
5840     BaseTy = llvm::PointerType::getUnqual(BaseTy);
5841   else if (AI.getCoerceToType())
5842     BaseTy = AI.getCoerceToType();
5843 
5844   unsigned NumRegs = 1;
5845   if (llvm::ArrayType *ArrTy = dyn_cast<llvm::ArrayType>(BaseTy)) {
5846     BaseTy = ArrTy->getElementType();
5847     NumRegs = ArrTy->getNumElements();
5848   }
5849   bool IsFPR = BaseTy->isFloatingPointTy() || BaseTy->isVectorTy();
5850 
5851   // The AArch64 va_list type and handling is specified in the Procedure Call
5852   // Standard, section B.4:
5853   //
5854   // struct {
5855   //   void *__stack;
5856   //   void *__gr_top;
5857   //   void *__vr_top;
5858   //   int __gr_offs;
5859   //   int __vr_offs;
5860   // };
5861 
5862   llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
5863   llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
5864   llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
5865   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
5866 
5867   CharUnits TySize = getContext().getTypeSizeInChars(Ty);
5868   CharUnits TyAlign = getContext().getTypeUnadjustedAlignInChars(Ty);
5869 
5870   Address reg_offs_p = Address::invalid();
5871   llvm::Value *reg_offs = nullptr;
5872   int reg_top_index;
5873   int RegSize = IsIndirect ? 8 : TySize.getQuantity();
5874   if (!IsFPR) {
5875     // 3 is the field number of __gr_offs
5876     reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 3, "gr_offs_p");
5877     reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
5878     reg_top_index = 1; // field number for __gr_top
5879     RegSize = llvm::alignTo(RegSize, 8);
5880   } else {
5881     // 4 is the field number of __vr_offs.
5882     reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 4, "vr_offs_p");
5883     reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
5884     reg_top_index = 2; // field number for __vr_top
5885     RegSize = 16 * NumRegs;
5886   }
5887 
5888   //=======================================
5889   // Find out where argument was passed
5890   //=======================================
5891 
5892   // If reg_offs >= 0 we're already using the stack for this type of
5893   // argument. We don't want to keep updating reg_offs (in case it overflows,
5894   // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
5895   // whatever they get).
5896   llvm::Value *UsingStack = nullptr;
5897   UsingStack = CGF.Builder.CreateICmpSGE(
5898       reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0));
5899 
5900   CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
5901 
5902   // Otherwise, at least some kind of argument could go in these registers, the
5903   // question is whether this particular type is too big.
5904   CGF.EmitBlock(MaybeRegBlock);
5905 
5906   // Integer arguments may need to correct register alignment (for example a
5907   // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
5908   // align __gr_offs to calculate the potential address.
5909   if (!IsFPR && !IsIndirect && TyAlign.getQuantity() > 8) {
5910     int Align = TyAlign.getQuantity();
5911 
5912     reg_offs = CGF.Builder.CreateAdd(
5913         reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
5914         "align_regoffs");
5915     reg_offs = CGF.Builder.CreateAnd(
5916         reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align),
5917         "aligned_regoffs");
5918   }
5919 
5920   // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
5921   // The fact that this is done unconditionally reflects the fact that
5922   // allocating an argument to the stack also uses up all the remaining
5923   // registers of the appropriate kind.
5924   llvm::Value *NewOffset = nullptr;
5925   NewOffset = CGF.Builder.CreateAdd(
5926       reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs");
5927   CGF.Builder.CreateStore(NewOffset, reg_offs_p);
5928 
5929   // Now we're in a position to decide whether this argument really was in
5930   // registers or not.
5931   llvm::Value *InRegs = nullptr;
5932   InRegs = CGF.Builder.CreateICmpSLE(
5933       NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg");
5934 
5935   CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
5936 
5937   //=======================================
5938   // Argument was in registers
5939   //=======================================
5940 
5941   // Now we emit the code for if the argument was originally passed in
5942   // registers. First start the appropriate block:
5943   CGF.EmitBlock(InRegBlock);
5944 
5945   llvm::Value *reg_top = nullptr;
5946   Address reg_top_p =
5947       CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index, "reg_top_p");
5948   reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
5949   Address BaseAddr(CGF.Builder.CreateInBoundsGEP(reg_top, reg_offs),
5950                    CharUnits::fromQuantity(IsFPR ? 16 : 8));
5951   Address RegAddr = Address::invalid();
5952   llvm::Type *MemTy = CGF.ConvertTypeForMem(Ty);
5953 
5954   if (IsIndirect) {
5955     // If it's been passed indirectly (actually a struct), whatever we find from
5956     // stored registers or on the stack will actually be a struct **.
5957     MemTy = llvm::PointerType::getUnqual(MemTy);
5958   }
5959 
5960   const Type *Base = nullptr;
5961   uint64_t NumMembers = 0;
5962   bool IsHFA = isHomogeneousAggregate(Ty, Base, NumMembers);
5963   if (IsHFA && NumMembers > 1) {
5964     // Homogeneous aggregates passed in registers will have their elements split
5965     // and stored 16-bytes apart regardless of size (they're notionally in qN,
5966     // qN+1, ...). We reload and store into a temporary local variable
5967     // contiguously.
5968     assert(!IsIndirect && "Homogeneous aggregates should be passed directly");
5969     auto BaseTyInfo = getContext().getTypeInfoInChars(QualType(Base, 0));
5970     llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
5971     llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
5972     Address Tmp = CGF.CreateTempAlloca(HFATy,
5973                                        std::max(TyAlign, BaseTyInfo.Align));
5974 
5975     // On big-endian platforms, the value will be right-aligned in its slot.
5976     int Offset = 0;
5977     if (CGF.CGM.getDataLayout().isBigEndian() &&
5978         BaseTyInfo.Width.getQuantity() < 16)
5979       Offset = 16 - BaseTyInfo.Width.getQuantity();
5980 
5981     for (unsigned i = 0; i < NumMembers; ++i) {
5982       CharUnits BaseOffset = CharUnits::fromQuantity(16 * i + Offset);
5983       Address LoadAddr =
5984         CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, BaseOffset);
5985       LoadAddr = CGF.Builder.CreateElementBitCast(LoadAddr, BaseTy);
5986 
5987       Address StoreAddr = CGF.Builder.CreateConstArrayGEP(Tmp, i);
5988 
5989       llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
5990       CGF.Builder.CreateStore(Elem, StoreAddr);
5991     }
5992 
5993     RegAddr = CGF.Builder.CreateElementBitCast(Tmp, MemTy);
5994   } else {
5995     // Otherwise the object is contiguous in memory.
5996 
5997     // It might be right-aligned in its slot.
5998     CharUnits SlotSize = BaseAddr.getAlignment();
5999     if (CGF.CGM.getDataLayout().isBigEndian() && !IsIndirect &&
6000         (IsHFA || !isAggregateTypeForABI(Ty)) &&
6001         TySize < SlotSize) {
6002       CharUnits Offset = SlotSize - TySize;
6003       BaseAddr = CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, Offset);
6004     }
6005 
6006     RegAddr = CGF.Builder.CreateElementBitCast(BaseAddr, MemTy);
6007   }
6008 
6009   CGF.EmitBranch(ContBlock);
6010 
6011   //=======================================
6012   // Argument was on the stack
6013   //=======================================
6014   CGF.EmitBlock(OnStackBlock);
6015 
6016   Address stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "stack_p");
6017   llvm::Value *OnStackPtr = CGF.Builder.CreateLoad(stack_p, "stack");
6018 
6019   // Again, stack arguments may need realignment. In this case both integer and
6020   // floating-point ones might be affected.
6021   if (!IsIndirect && TyAlign.getQuantity() > 8) {
6022     int Align = TyAlign.getQuantity();
6023 
6024     OnStackPtr = CGF.Builder.CreatePtrToInt(OnStackPtr, CGF.Int64Ty);
6025 
6026     OnStackPtr = CGF.Builder.CreateAdd(
6027         OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
6028         "align_stack");
6029     OnStackPtr = CGF.Builder.CreateAnd(
6030         OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, -Align),
6031         "align_stack");
6032 
6033     OnStackPtr = CGF.Builder.CreateIntToPtr(OnStackPtr, CGF.Int8PtrTy);
6034   }
6035   Address OnStackAddr(OnStackPtr,
6036                       std::max(CharUnits::fromQuantity(8), TyAlign));
6037 
6038   // All stack slots are multiples of 8 bytes.
6039   CharUnits StackSlotSize = CharUnits::fromQuantity(8);
6040   CharUnits StackSize;
6041   if (IsIndirect)
6042     StackSize = StackSlotSize;
6043   else
6044     StackSize = TySize.alignTo(StackSlotSize);
6045 
6046   llvm::Value *StackSizeC = CGF.Builder.getSize(StackSize);
6047   llvm::Value *NewStack =
6048       CGF.Builder.CreateInBoundsGEP(OnStackPtr, StackSizeC, "new_stack");
6049 
6050   // Write the new value of __stack for the next call to va_arg
6051   CGF.Builder.CreateStore(NewStack, stack_p);
6052 
6053   if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) &&
6054       TySize < StackSlotSize) {
6055     CharUnits Offset = StackSlotSize - TySize;
6056     OnStackAddr = CGF.Builder.CreateConstInBoundsByteGEP(OnStackAddr, Offset);
6057   }
6058 
6059   OnStackAddr = CGF.Builder.CreateElementBitCast(OnStackAddr, MemTy);
6060 
6061   CGF.EmitBranch(ContBlock);
6062 
6063   //=======================================
6064   // Tidy up
6065   //=======================================
6066   CGF.EmitBlock(ContBlock);
6067 
6068   Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
6069                                  OnStackAddr, OnStackBlock, "vaargs.addr");
6070 
6071   if (IsIndirect)
6072     return Address(CGF.Builder.CreateLoad(ResAddr, "vaarg.addr"),
6073                    TyAlign);
6074 
6075   return ResAddr;
6076 }
6077 
6078 Address AArch64ABIInfo::EmitDarwinVAArg(Address VAListAddr, QualType Ty,
6079                                         CodeGenFunction &CGF) const {
6080   // The backend's lowering doesn't support va_arg for aggregates or
6081   // illegal vector types.  Lower VAArg here for these cases and use
6082   // the LLVM va_arg instruction for everything else.
6083   if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty))
6084     return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
6085 
6086   uint64_t PointerSize = getTarget().getPointerWidth(0) / 8;
6087   CharUnits SlotSize = CharUnits::fromQuantity(PointerSize);
6088 
6089   // Empty records are ignored for parameter passing purposes.
6090   if (isEmptyRecord(getContext(), Ty, true)) {
6091     Address Addr(CGF.Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
6092     Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
6093     return Addr;
6094   }
6095 
6096   // The size of the actual thing passed, which might end up just
6097   // being a pointer for indirect types.
6098   auto TyInfo = getContext().getTypeInfoInChars(Ty);
6099 
6100   // Arguments bigger than 16 bytes which aren't homogeneous
6101   // aggregates should be passed indirectly.
6102   bool IsIndirect = false;
6103   if (TyInfo.Width.getQuantity() > 16) {
6104     const Type *Base = nullptr;
6105     uint64_t Members = 0;
6106     IsIndirect = !isHomogeneousAggregate(Ty, Base, Members);
6107   }
6108 
6109   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
6110                           TyInfo, SlotSize, /*AllowHigherAlign*/ true);
6111 }
6112 
6113 Address AArch64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
6114                                     QualType Ty) const {
6115   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
6116                           CGF.getContext().getTypeInfoInChars(Ty),
6117                           CharUnits::fromQuantity(8),
6118                           /*allowHigherAlign*/ false);
6119 }
6120 
6121 //===----------------------------------------------------------------------===//
6122 // ARM ABI Implementation
6123 //===----------------------------------------------------------------------===//
6124 
6125 namespace {
6126 
6127 class ARMABIInfo : public SwiftABIInfo {
6128 public:
6129   enum ABIKind {
6130     APCS = 0,
6131     AAPCS = 1,
6132     AAPCS_VFP = 2,
6133     AAPCS16_VFP = 3,
6134   };
6135 
6136 private:
6137   ABIKind Kind;
6138   bool IsFloatABISoftFP;
6139 
6140 public:
6141   ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind)
6142       : SwiftABIInfo(CGT), Kind(_Kind) {
6143     setCCs();
6144     IsFloatABISoftFP = CGT.getCodeGenOpts().FloatABI == "softfp" ||
6145         CGT.getCodeGenOpts().FloatABI == ""; // default
6146   }
6147 
6148   bool isEABI() const {
6149     switch (getTarget().getTriple().getEnvironment()) {
6150     case llvm::Triple::Android:
6151     case llvm::Triple::EABI:
6152     case llvm::Triple::EABIHF:
6153     case llvm::Triple::GNUEABI:
6154     case llvm::Triple::GNUEABIHF:
6155     case llvm::Triple::MuslEABI:
6156     case llvm::Triple::MuslEABIHF:
6157       return true;
6158     default:
6159       return false;
6160     }
6161   }
6162 
6163   bool isEABIHF() const {
6164     switch (getTarget().getTriple().getEnvironment()) {
6165     case llvm::Triple::EABIHF:
6166     case llvm::Triple::GNUEABIHF:
6167     case llvm::Triple::MuslEABIHF:
6168       return true;
6169     default:
6170       return false;
6171     }
6172   }
6173 
6174   ABIKind getABIKind() const { return Kind; }
6175 
6176   bool allowBFloatArgsAndRet() const override {
6177     return !IsFloatABISoftFP && getTarget().hasBFloat16Type();
6178   }
6179 
6180 private:
6181   ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic,
6182                                 unsigned functionCallConv) const;
6183   ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic,
6184                                   unsigned functionCallConv) const;
6185   ABIArgInfo classifyHomogeneousAggregate(QualType Ty, const Type *Base,
6186                                           uint64_t Members) const;
6187   ABIArgInfo coerceIllegalVector(QualType Ty) const;
6188   bool isIllegalVectorType(QualType Ty) const;
6189   bool containsAnyFP16Vectors(QualType Ty) const;
6190 
6191   bool isHomogeneousAggregateBaseType(QualType Ty) const override;
6192   bool isHomogeneousAggregateSmallEnough(const Type *Ty,
6193                                          uint64_t Members) const override;
6194 
6195   bool isEffectivelyAAPCS_VFP(unsigned callConvention, bool acceptHalf) const;
6196 
6197   void computeInfo(CGFunctionInfo &FI) const override;
6198 
6199   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6200                     QualType Ty) const override;
6201 
6202   llvm::CallingConv::ID getLLVMDefaultCC() const;
6203   llvm::CallingConv::ID getABIDefaultCC() const;
6204   void setCCs();
6205 
6206   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
6207                                     bool asReturnValue) const override {
6208     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
6209   }
6210   bool isSwiftErrorInRegister() const override {
6211     return true;
6212   }
6213   bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy,
6214                                  unsigned elts) const override;
6215 };
6216 
6217 class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
6218 public:
6219   ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
6220       : TargetCodeGenInfo(std::make_unique<ARMABIInfo>(CGT, K)) {}
6221 
6222   const ARMABIInfo &getABIInfo() const {
6223     return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
6224   }
6225 
6226   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
6227     return 13;
6228   }
6229 
6230   StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
6231     return "mov\tr7, r7\t\t// marker for objc_retainAutoreleaseReturnValue";
6232   }
6233 
6234   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
6235                                llvm::Value *Address) const override {
6236     llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
6237 
6238     // 0-15 are the 16 integer registers.
6239     AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
6240     return false;
6241   }
6242 
6243   unsigned getSizeOfUnwindException() const override {
6244     if (getABIInfo().isEABI()) return 88;
6245     return TargetCodeGenInfo::getSizeOfUnwindException();
6246   }
6247 
6248   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
6249                            CodeGen::CodeGenModule &CGM) const override {
6250     if (GV->isDeclaration())
6251       return;
6252     const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
6253     if (!FD)
6254       return;
6255 
6256     const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
6257     if (!Attr)
6258       return;
6259 
6260     const char *Kind;
6261     switch (Attr->getInterrupt()) {
6262     case ARMInterruptAttr::Generic: Kind = ""; break;
6263     case ARMInterruptAttr::IRQ:     Kind = "IRQ"; break;
6264     case ARMInterruptAttr::FIQ:     Kind = "FIQ"; break;
6265     case ARMInterruptAttr::SWI:     Kind = "SWI"; break;
6266     case ARMInterruptAttr::ABORT:   Kind = "ABORT"; break;
6267     case ARMInterruptAttr::UNDEF:   Kind = "UNDEF"; break;
6268     }
6269 
6270     llvm::Function *Fn = cast<llvm::Function>(GV);
6271 
6272     Fn->addFnAttr("interrupt", Kind);
6273 
6274     ARMABIInfo::ABIKind ABI = cast<ARMABIInfo>(getABIInfo()).getABIKind();
6275     if (ABI == ARMABIInfo::APCS)
6276       return;
6277 
6278     // AAPCS guarantees that sp will be 8-byte aligned on any public interface,
6279     // however this is not necessarily true on taking any interrupt. Instruct
6280     // the backend to perform a realignment as part of the function prologue.
6281     llvm::AttrBuilder B;
6282     B.addStackAlignmentAttr(8);
6283     Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
6284   }
6285 };
6286 
6287 class WindowsARMTargetCodeGenInfo : public ARMTargetCodeGenInfo {
6288 public:
6289   WindowsARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
6290       : ARMTargetCodeGenInfo(CGT, K) {}
6291 
6292   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
6293                            CodeGen::CodeGenModule &CGM) const override;
6294 
6295   void getDependentLibraryOption(llvm::StringRef Lib,
6296                                  llvm::SmallString<24> &Opt) const override {
6297     Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib);
6298   }
6299 
6300   void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value,
6301                                llvm::SmallString<32> &Opt) const override {
6302     Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
6303   }
6304 };
6305 
6306 void WindowsARMTargetCodeGenInfo::setTargetAttributes(
6307     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
6308   ARMTargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
6309   if (GV->isDeclaration())
6310     return;
6311   addStackProbeTargetAttributes(D, GV, CGM);
6312 }
6313 }
6314 
6315 void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
6316   if (!::classifyReturnType(getCXXABI(), FI, *this))
6317     FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), FI.isVariadic(),
6318                                             FI.getCallingConvention());
6319 
6320   for (auto &I : FI.arguments())
6321     I.info = classifyArgumentType(I.type, FI.isVariadic(),
6322                                   FI.getCallingConvention());
6323 
6324 
6325   // Always honor user-specified calling convention.
6326   if (FI.getCallingConvention() != llvm::CallingConv::C)
6327     return;
6328 
6329   llvm::CallingConv::ID cc = getRuntimeCC();
6330   if (cc != llvm::CallingConv::C)
6331     FI.setEffectiveCallingConvention(cc);
6332 }
6333 
6334 /// Return the default calling convention that LLVM will use.
6335 llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
6336   // The default calling convention that LLVM will infer.
6337   if (isEABIHF() || getTarget().getTriple().isWatchABI())
6338     return llvm::CallingConv::ARM_AAPCS_VFP;
6339   else if (isEABI())
6340     return llvm::CallingConv::ARM_AAPCS;
6341   else
6342     return llvm::CallingConv::ARM_APCS;
6343 }
6344 
6345 /// Return the calling convention that our ABI would like us to use
6346 /// as the C calling convention.
6347 llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
6348   switch (getABIKind()) {
6349   case APCS: return llvm::CallingConv::ARM_APCS;
6350   case AAPCS: return llvm::CallingConv::ARM_AAPCS;
6351   case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
6352   case AAPCS16_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
6353   }
6354   llvm_unreachable("bad ABI kind");
6355 }
6356 
6357 void ARMABIInfo::setCCs() {
6358   assert(getRuntimeCC() == llvm::CallingConv::C);
6359 
6360   // Don't muddy up the IR with a ton of explicit annotations if
6361   // they'd just match what LLVM will infer from the triple.
6362   llvm::CallingConv::ID abiCC = getABIDefaultCC();
6363   if (abiCC != getLLVMDefaultCC())
6364     RuntimeCC = abiCC;
6365 }
6366 
6367 ABIArgInfo ARMABIInfo::coerceIllegalVector(QualType Ty) const {
6368   uint64_t Size = getContext().getTypeSize(Ty);
6369   if (Size <= 32) {
6370     llvm::Type *ResType =
6371         llvm::Type::getInt32Ty(getVMContext());
6372     return ABIArgInfo::getDirect(ResType);
6373   }
6374   if (Size == 64 || Size == 128) {
6375     auto *ResType = llvm::FixedVectorType::get(
6376         llvm::Type::getInt32Ty(getVMContext()), Size / 32);
6377     return ABIArgInfo::getDirect(ResType);
6378   }
6379   return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
6380 }
6381 
6382 ABIArgInfo ARMABIInfo::classifyHomogeneousAggregate(QualType Ty,
6383                                                     const Type *Base,
6384                                                     uint64_t Members) const {
6385   assert(Base && "Base class should be set for homogeneous aggregate");
6386   // Base can be a floating-point or a vector.
6387   if (const VectorType *VT = Base->getAs<VectorType>()) {
6388     // FP16 vectors should be converted to integer vectors
6389     if (!getTarget().hasLegalHalfType() && containsAnyFP16Vectors(Ty)) {
6390       uint64_t Size = getContext().getTypeSize(VT);
6391       auto *NewVecTy = llvm::FixedVectorType::get(
6392           llvm::Type::getInt32Ty(getVMContext()), Size / 32);
6393       llvm::Type *Ty = llvm::ArrayType::get(NewVecTy, Members);
6394       return ABIArgInfo::getDirect(Ty, 0, nullptr, false);
6395     }
6396   }
6397   return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
6398 }
6399 
6400 ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty, bool isVariadic,
6401                                             unsigned functionCallConv) const {
6402   // 6.1.2.1 The following argument types are VFP CPRCs:
6403   //   A single-precision floating-point type (including promoted
6404   //   half-precision types); A double-precision floating-point type;
6405   //   A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
6406   //   with a Base Type of a single- or double-precision floating-point type,
6407   //   64-bit containerized vectors or 128-bit containerized vectors with one
6408   //   to four Elements.
6409   // Variadic functions should always marshal to the base standard.
6410   bool IsAAPCS_VFP =
6411       !isVariadic && isEffectivelyAAPCS_VFP(functionCallConv, /* AAPCS16 */ false);
6412 
6413   Ty = useFirstFieldIfTransparentUnion(Ty);
6414 
6415   // Handle illegal vector types here.
6416   if (isIllegalVectorType(Ty))
6417     return coerceIllegalVector(Ty);
6418 
6419   if (!isAggregateTypeForABI(Ty)) {
6420     // Treat an enum type as its underlying type.
6421     if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
6422       Ty = EnumTy->getDecl()->getIntegerType();
6423     }
6424 
6425     if (const auto *EIT = Ty->getAs<ExtIntType>())
6426       if (EIT->getNumBits() > 64)
6427         return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
6428 
6429     return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
6430                                               : ABIArgInfo::getDirect());
6431   }
6432 
6433   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
6434     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
6435   }
6436 
6437   // Ignore empty records.
6438   if (isEmptyRecord(getContext(), Ty, true))
6439     return ABIArgInfo::getIgnore();
6440 
6441   if (IsAAPCS_VFP) {
6442     // Homogeneous Aggregates need to be expanded when we can fit the aggregate
6443     // into VFP registers.
6444     const Type *Base = nullptr;
6445     uint64_t Members = 0;
6446     if (isHomogeneousAggregate(Ty, Base, Members))
6447       return classifyHomogeneousAggregate(Ty, Base, Members);
6448   } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
6449     // WatchOS does have homogeneous aggregates. Note that we intentionally use
6450     // this convention even for a variadic function: the backend will use GPRs
6451     // if needed.
6452     const Type *Base = nullptr;
6453     uint64_t Members = 0;
6454     if (isHomogeneousAggregate(Ty, Base, Members)) {
6455       assert(Base && Members <= 4 && "unexpected homogeneous aggregate");
6456       llvm::Type *Ty =
6457         llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members);
6458       return ABIArgInfo::getDirect(Ty, 0, nullptr, false);
6459     }
6460   }
6461 
6462   if (getABIKind() == ARMABIInfo::AAPCS16_VFP &&
6463       getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(16)) {
6464     // WatchOS is adopting the 64-bit AAPCS rule on composite types: if they're
6465     // bigger than 128-bits, they get placed in space allocated by the caller,
6466     // and a pointer is passed.
6467     return ABIArgInfo::getIndirect(
6468         CharUnits::fromQuantity(getContext().getTypeAlign(Ty) / 8), false);
6469   }
6470 
6471   // Support byval for ARM.
6472   // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
6473   // most 8-byte. We realign the indirect argument if type alignment is bigger
6474   // than ABI alignment.
6475   uint64_t ABIAlign = 4;
6476   uint64_t TyAlign;
6477   if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
6478       getABIKind() == ARMABIInfo::AAPCS) {
6479     TyAlign = getContext().getTypeUnadjustedAlignInChars(Ty).getQuantity();
6480     ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
6481   } else {
6482     TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity();
6483   }
6484   if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
6485     assert(getABIKind() != ARMABIInfo::AAPCS16_VFP && "unexpected byval");
6486     return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
6487                                    /*ByVal=*/true,
6488                                    /*Realign=*/TyAlign > ABIAlign);
6489   }
6490 
6491   // On RenderScript, coerce Aggregates <= 64 bytes to an integer array of
6492   // same size and alignment.
6493   if (getTarget().isRenderScriptTarget()) {
6494     return coerceToIntArray(Ty, getContext(), getVMContext());
6495   }
6496 
6497   // Otherwise, pass by coercing to a structure of the appropriate size.
6498   llvm::Type* ElemTy;
6499   unsigned SizeRegs;
6500   // FIXME: Try to match the types of the arguments more accurately where
6501   // we can.
6502   if (TyAlign <= 4) {
6503     ElemTy = llvm::Type::getInt32Ty(getVMContext());
6504     SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
6505   } else {
6506     ElemTy = llvm::Type::getInt64Ty(getVMContext());
6507     SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
6508   }
6509 
6510   return ABIArgInfo::getDirect(llvm::ArrayType::get(ElemTy, SizeRegs));
6511 }
6512 
6513 static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
6514                               llvm::LLVMContext &VMContext) {
6515   // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
6516   // is called integer-like if its size is less than or equal to one word, and
6517   // the offset of each of its addressable sub-fields is zero.
6518 
6519   uint64_t Size = Context.getTypeSize(Ty);
6520 
6521   // Check that the type fits in a word.
6522   if (Size > 32)
6523     return false;
6524 
6525   // FIXME: Handle vector types!
6526   if (Ty->isVectorType())
6527     return false;
6528 
6529   // Float types are never treated as "integer like".
6530   if (Ty->isRealFloatingType())
6531     return false;
6532 
6533   // If this is a builtin or pointer type then it is ok.
6534   if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
6535     return true;
6536 
6537   // Small complex integer types are "integer like".
6538   if (const ComplexType *CT = Ty->getAs<ComplexType>())
6539     return isIntegerLikeType(CT->getElementType(), Context, VMContext);
6540 
6541   // Single element and zero sized arrays should be allowed, by the definition
6542   // above, but they are not.
6543 
6544   // Otherwise, it must be a record type.
6545   const RecordType *RT = Ty->getAs<RecordType>();
6546   if (!RT) return false;
6547 
6548   // Ignore records with flexible arrays.
6549   const RecordDecl *RD = RT->getDecl();
6550   if (RD->hasFlexibleArrayMember())
6551     return false;
6552 
6553   // Check that all sub-fields are at offset 0, and are themselves "integer
6554   // like".
6555   const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
6556 
6557   bool HadField = false;
6558   unsigned idx = 0;
6559   for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
6560        i != e; ++i, ++idx) {
6561     const FieldDecl *FD = *i;
6562 
6563     // Bit-fields are not addressable, we only need to verify they are "integer
6564     // like". We still have to disallow a subsequent non-bitfield, for example:
6565     //   struct { int : 0; int x }
6566     // is non-integer like according to gcc.
6567     if (FD->isBitField()) {
6568       if (!RD->isUnion())
6569         HadField = true;
6570 
6571       if (!isIntegerLikeType(FD->getType(), Context, VMContext))
6572         return false;
6573 
6574       continue;
6575     }
6576 
6577     // Check if this field is at offset 0.
6578     if (Layout.getFieldOffset(idx) != 0)
6579       return false;
6580 
6581     if (!isIntegerLikeType(FD->getType(), Context, VMContext))
6582       return false;
6583 
6584     // Only allow at most one field in a structure. This doesn't match the
6585     // wording above, but follows gcc in situations with a field following an
6586     // empty structure.
6587     if (!RD->isUnion()) {
6588       if (HadField)
6589         return false;
6590 
6591       HadField = true;
6592     }
6593   }
6594 
6595   return true;
6596 }
6597 
6598 ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy, bool isVariadic,
6599                                           unsigned functionCallConv) const {
6600 
6601   // Variadic functions should always marshal to the base standard.
6602   bool IsAAPCS_VFP =
6603       !isVariadic && isEffectivelyAAPCS_VFP(functionCallConv, /* AAPCS16 */ true);
6604 
6605   if (RetTy->isVoidType())
6606     return ABIArgInfo::getIgnore();
6607 
6608   if (const VectorType *VT = RetTy->getAs<VectorType>()) {
6609     // Large vector types should be returned via memory.
6610     if (getContext().getTypeSize(RetTy) > 128)
6611       return getNaturalAlignIndirect(RetTy);
6612     // TODO: FP16/BF16 vectors should be converted to integer vectors
6613     // This check is similar  to isIllegalVectorType - refactor?
6614     if ((!getTarget().hasLegalHalfType() &&
6615         (VT->getElementType()->isFloat16Type() ||
6616          VT->getElementType()->isHalfType())) ||
6617         (IsFloatABISoftFP &&
6618          VT->getElementType()->isBFloat16Type()))
6619       return coerceIllegalVector(RetTy);
6620   }
6621 
6622   if (!isAggregateTypeForABI(RetTy)) {
6623     // Treat an enum type as its underlying type.
6624     if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6625       RetTy = EnumTy->getDecl()->getIntegerType();
6626 
6627     if (const auto *EIT = RetTy->getAs<ExtIntType>())
6628       if (EIT->getNumBits() > 64)
6629         return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
6630 
6631     return isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
6632                                                 : ABIArgInfo::getDirect();
6633   }
6634 
6635   // Are we following APCS?
6636   if (getABIKind() == APCS) {
6637     if (isEmptyRecord(getContext(), RetTy, false))
6638       return ABIArgInfo::getIgnore();
6639 
6640     // Complex types are all returned as packed integers.
6641     //
6642     // FIXME: Consider using 2 x vector types if the back end handles them
6643     // correctly.
6644     if (RetTy->isAnyComplexType())
6645       return ABIArgInfo::getDirect(llvm::IntegerType::get(
6646           getVMContext(), getContext().getTypeSize(RetTy)));
6647 
6648     // Integer like structures are returned in r0.
6649     if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
6650       // Return in the smallest viable integer type.
6651       uint64_t Size = getContext().getTypeSize(RetTy);
6652       if (Size <= 8)
6653         return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6654       if (Size <= 16)
6655         return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6656       return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6657     }
6658 
6659     // Otherwise return in memory.
6660     return getNaturalAlignIndirect(RetTy);
6661   }
6662 
6663   // Otherwise this is an AAPCS variant.
6664 
6665   if (isEmptyRecord(getContext(), RetTy, true))
6666     return ABIArgInfo::getIgnore();
6667 
6668   // Check for homogeneous aggregates with AAPCS-VFP.
6669   if (IsAAPCS_VFP) {
6670     const Type *Base = nullptr;
6671     uint64_t Members = 0;
6672     if (isHomogeneousAggregate(RetTy, Base, Members))
6673       return classifyHomogeneousAggregate(RetTy, Base, Members);
6674   }
6675 
6676   // Aggregates <= 4 bytes are returned in r0; other aggregates
6677   // are returned indirectly.
6678   uint64_t Size = getContext().getTypeSize(RetTy);
6679   if (Size <= 32) {
6680     // On RenderScript, coerce Aggregates <= 4 bytes to an integer array of
6681     // same size and alignment.
6682     if (getTarget().isRenderScriptTarget()) {
6683       return coerceToIntArray(RetTy, getContext(), getVMContext());
6684     }
6685     if (getDataLayout().isBigEndian())
6686       // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4)
6687       return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6688 
6689     // Return in the smallest viable integer type.
6690     if (Size <= 8)
6691       return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6692     if (Size <= 16)
6693       return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6694     return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6695   } else if (Size <= 128 && getABIKind() == AAPCS16_VFP) {
6696     llvm::Type *Int32Ty = llvm::Type::getInt32Ty(getVMContext());
6697     llvm::Type *CoerceTy =
6698         llvm::ArrayType::get(Int32Ty, llvm::alignTo(Size, 32) / 32);
6699     return ABIArgInfo::getDirect(CoerceTy);
6700   }
6701 
6702   return getNaturalAlignIndirect(RetTy);
6703 }
6704 
6705 /// isIllegalVector - check whether Ty is an illegal vector type.
6706 bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
6707   if (const VectorType *VT = Ty->getAs<VectorType> ()) {
6708     // On targets that don't support half, fp16 or bfloat, they are expanded
6709     // into float, and we don't want the ABI to depend on whether or not they
6710     // are supported in hardware. Thus return false to coerce vectors of these
6711     // types into integer vectors.
6712     // We do not depend on hasLegalHalfType for bfloat as it is a
6713     // separate IR type.
6714     if ((!getTarget().hasLegalHalfType() &&
6715         (VT->getElementType()->isFloat16Type() ||
6716          VT->getElementType()->isHalfType())) ||
6717         (IsFloatABISoftFP &&
6718          VT->getElementType()->isBFloat16Type()))
6719       return true;
6720     if (isAndroid()) {
6721       // Android shipped using Clang 3.1, which supported a slightly different
6722       // vector ABI. The primary differences were that 3-element vector types
6723       // were legal, and so were sub 32-bit vectors (i.e. <2 x i8>). This path
6724       // accepts that legacy behavior for Android only.
6725       // Check whether VT is legal.
6726       unsigned NumElements = VT->getNumElements();
6727       // NumElements should be power of 2 or equal to 3.
6728       if (!llvm::isPowerOf2_32(NumElements) && NumElements != 3)
6729         return true;
6730     } else {
6731       // Check whether VT is legal.
6732       unsigned NumElements = VT->getNumElements();
6733       uint64_t Size = getContext().getTypeSize(VT);
6734       // NumElements should be power of 2.
6735       if (!llvm::isPowerOf2_32(NumElements))
6736         return true;
6737       // Size should be greater than 32 bits.
6738       return Size <= 32;
6739     }
6740   }
6741   return false;
6742 }
6743 
6744 /// Return true if a type contains any 16-bit floating point vectors
6745 bool ARMABIInfo::containsAnyFP16Vectors(QualType Ty) const {
6746   if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
6747     uint64_t NElements = AT->getSize().getZExtValue();
6748     if (NElements == 0)
6749       return false;
6750     return containsAnyFP16Vectors(AT->getElementType());
6751   } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
6752     const RecordDecl *RD = RT->getDecl();
6753 
6754     // If this is a C++ record, check the bases first.
6755     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
6756       if (llvm::any_of(CXXRD->bases(), [this](const CXXBaseSpecifier &B) {
6757             return containsAnyFP16Vectors(B.getType());
6758           }))
6759         return true;
6760 
6761     if (llvm::any_of(RD->fields(), [this](FieldDecl *FD) {
6762           return FD && containsAnyFP16Vectors(FD->getType());
6763         }))
6764       return true;
6765 
6766     return false;
6767   } else {
6768     if (const VectorType *VT = Ty->getAs<VectorType>())
6769       return (VT->getElementType()->isFloat16Type() ||
6770               VT->getElementType()->isBFloat16Type() ||
6771               VT->getElementType()->isHalfType());
6772     return false;
6773   }
6774 }
6775 
6776 bool ARMABIInfo::isLegalVectorTypeForSwift(CharUnits vectorSize,
6777                                            llvm::Type *eltTy,
6778                                            unsigned numElts) const {
6779   if (!llvm::isPowerOf2_32(numElts))
6780     return false;
6781   unsigned size = getDataLayout().getTypeStoreSizeInBits(eltTy);
6782   if (size > 64)
6783     return false;
6784   if (vectorSize.getQuantity() != 8 &&
6785       (vectorSize.getQuantity() != 16 || numElts == 1))
6786     return false;
6787   return true;
6788 }
6789 
6790 bool ARMABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
6791   // Homogeneous aggregates for AAPCS-VFP must have base types of float,
6792   // double, or 64-bit or 128-bit vectors.
6793   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
6794     if (BT->getKind() == BuiltinType::Float ||
6795         BT->getKind() == BuiltinType::Double ||
6796         BT->getKind() == BuiltinType::LongDouble)
6797       return true;
6798   } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
6799     unsigned VecSize = getContext().getTypeSize(VT);
6800     if (VecSize == 64 || VecSize == 128)
6801       return true;
6802   }
6803   return false;
6804 }
6805 
6806 bool ARMABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
6807                                                    uint64_t Members) const {
6808   return Members <= 4;
6809 }
6810 
6811 bool ARMABIInfo::isEffectivelyAAPCS_VFP(unsigned callConvention,
6812                                         bool acceptHalf) const {
6813   // Give precedence to user-specified calling conventions.
6814   if (callConvention != llvm::CallingConv::C)
6815     return (callConvention == llvm::CallingConv::ARM_AAPCS_VFP);
6816   else
6817     return (getABIKind() == AAPCS_VFP) ||
6818            (acceptHalf && (getABIKind() == AAPCS16_VFP));
6819 }
6820 
6821 Address ARMABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6822                               QualType Ty) const {
6823   CharUnits SlotSize = CharUnits::fromQuantity(4);
6824 
6825   // Empty records are ignored for parameter passing purposes.
6826   if (isEmptyRecord(getContext(), Ty, true)) {
6827     Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize);
6828     Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
6829     return Addr;
6830   }
6831 
6832   CharUnits TySize = getContext().getTypeSizeInChars(Ty);
6833   CharUnits TyAlignForABI = getContext().getTypeUnadjustedAlignInChars(Ty);
6834 
6835   // Use indirect if size of the illegal vector is bigger than 16 bytes.
6836   bool IsIndirect = false;
6837   const Type *Base = nullptr;
6838   uint64_t Members = 0;
6839   if (TySize > CharUnits::fromQuantity(16) && isIllegalVectorType(Ty)) {
6840     IsIndirect = true;
6841 
6842   // ARMv7k passes structs bigger than 16 bytes indirectly, in space
6843   // allocated by the caller.
6844   } else if (TySize > CharUnits::fromQuantity(16) &&
6845              getABIKind() == ARMABIInfo::AAPCS16_VFP &&
6846              !isHomogeneousAggregate(Ty, Base, Members)) {
6847     IsIndirect = true;
6848 
6849   // Otherwise, bound the type's ABI alignment.
6850   // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
6851   // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
6852   // Our callers should be prepared to handle an under-aligned address.
6853   } else if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
6854              getABIKind() == ARMABIInfo::AAPCS) {
6855     TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
6856     TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(8));
6857   } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
6858     // ARMv7k allows type alignment up to 16 bytes.
6859     TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
6860     TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(16));
6861   } else {
6862     TyAlignForABI = CharUnits::fromQuantity(4);
6863   }
6864 
6865   TypeInfoChars TyInfo(TySize, TyAlignForABI, false);
6866   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TyInfo,
6867                           SlotSize, /*AllowHigherAlign*/ true);
6868 }
6869 
6870 //===----------------------------------------------------------------------===//
6871 // NVPTX ABI Implementation
6872 //===----------------------------------------------------------------------===//
6873 
6874 namespace {
6875 
6876 class NVPTXTargetCodeGenInfo;
6877 
6878 class NVPTXABIInfo : public ABIInfo {
6879   NVPTXTargetCodeGenInfo &CGInfo;
6880 
6881 public:
6882   NVPTXABIInfo(CodeGenTypes &CGT, NVPTXTargetCodeGenInfo &Info)
6883       : ABIInfo(CGT), CGInfo(Info) {}
6884 
6885   ABIArgInfo classifyReturnType(QualType RetTy) const;
6886   ABIArgInfo classifyArgumentType(QualType Ty) const;
6887 
6888   void computeInfo(CGFunctionInfo &FI) const override;
6889   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6890                     QualType Ty) const override;
6891   bool isUnsupportedType(QualType T) const;
6892   ABIArgInfo coerceToIntArrayWithLimit(QualType Ty, unsigned MaxSize) const;
6893 };
6894 
6895 class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
6896 public:
6897   NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
6898       : TargetCodeGenInfo(std::make_unique<NVPTXABIInfo>(CGT, *this)) {}
6899 
6900   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
6901                            CodeGen::CodeGenModule &M) const override;
6902   bool shouldEmitStaticExternCAliases() const override;
6903 
6904   llvm::Type *getCUDADeviceBuiltinSurfaceDeviceType() const override {
6905     // On the device side, surface reference is represented as an object handle
6906     // in 64-bit integer.
6907     return llvm::Type::getInt64Ty(getABIInfo().getVMContext());
6908   }
6909 
6910   llvm::Type *getCUDADeviceBuiltinTextureDeviceType() const override {
6911     // On the device side, texture reference is represented as an object handle
6912     // in 64-bit integer.
6913     return llvm::Type::getInt64Ty(getABIInfo().getVMContext());
6914   }
6915 
6916   bool emitCUDADeviceBuiltinSurfaceDeviceCopy(CodeGenFunction &CGF, LValue Dst,
6917                                               LValue Src) const override {
6918     emitBuiltinSurfTexDeviceCopy(CGF, Dst, Src);
6919     return true;
6920   }
6921 
6922   bool emitCUDADeviceBuiltinTextureDeviceCopy(CodeGenFunction &CGF, LValue Dst,
6923                                               LValue Src) const override {
6924     emitBuiltinSurfTexDeviceCopy(CGF, Dst, Src);
6925     return true;
6926   }
6927 
6928 private:
6929   // Adds a NamedMDNode with GV, Name, and Operand as operands, and adds the
6930   // resulting MDNode to the nvvm.annotations MDNode.
6931   static void addNVVMMetadata(llvm::GlobalValue *GV, StringRef Name,
6932                               int Operand);
6933 
6934   static void emitBuiltinSurfTexDeviceCopy(CodeGenFunction &CGF, LValue Dst,
6935                                            LValue Src) {
6936     llvm::Value *Handle = nullptr;
6937     llvm::Constant *C =
6938         llvm::dyn_cast<llvm::Constant>(Src.getAddress(CGF).getPointer());
6939     // Lookup `addrspacecast` through the constant pointer if any.
6940     if (auto *ASC = llvm::dyn_cast_or_null<llvm::AddrSpaceCastOperator>(C))
6941       C = llvm::cast<llvm::Constant>(ASC->getPointerOperand());
6942     if (auto *GV = llvm::dyn_cast_or_null<llvm::GlobalVariable>(C)) {
6943       // Load the handle from the specific global variable using
6944       // `nvvm.texsurf.handle.internal` intrinsic.
6945       Handle = CGF.EmitRuntimeCall(
6946           CGF.CGM.getIntrinsic(llvm::Intrinsic::nvvm_texsurf_handle_internal,
6947                                {GV->getType()}),
6948           {GV}, "texsurf_handle");
6949     } else
6950       Handle = CGF.EmitLoadOfScalar(Src, SourceLocation());
6951     CGF.EmitStoreOfScalar(Handle, Dst);
6952   }
6953 };
6954 
6955 /// Checks if the type is unsupported directly by the current target.
6956 bool NVPTXABIInfo::isUnsupportedType(QualType T) const {
6957   ASTContext &Context = getContext();
6958   if (!Context.getTargetInfo().hasFloat16Type() && T->isFloat16Type())
6959     return true;
6960   if (!Context.getTargetInfo().hasFloat128Type() &&
6961       (T->isFloat128Type() ||
6962        (T->isRealFloatingType() && Context.getTypeSize(T) == 128)))
6963     return true;
6964   if (const auto *EIT = T->getAs<ExtIntType>())
6965     return EIT->getNumBits() >
6966            (Context.getTargetInfo().hasInt128Type() ? 128U : 64U);
6967   if (!Context.getTargetInfo().hasInt128Type() && T->isIntegerType() &&
6968       Context.getTypeSize(T) > 64U)
6969     return true;
6970   if (const auto *AT = T->getAsArrayTypeUnsafe())
6971     return isUnsupportedType(AT->getElementType());
6972   const auto *RT = T->getAs<RecordType>();
6973   if (!RT)
6974     return false;
6975   const RecordDecl *RD = RT->getDecl();
6976 
6977   // If this is a C++ record, check the bases first.
6978   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
6979     for (const CXXBaseSpecifier &I : CXXRD->bases())
6980       if (isUnsupportedType(I.getType()))
6981         return true;
6982 
6983   for (const FieldDecl *I : RD->fields())
6984     if (isUnsupportedType(I->getType()))
6985       return true;
6986   return false;
6987 }
6988 
6989 /// Coerce the given type into an array with maximum allowed size of elements.
6990 ABIArgInfo NVPTXABIInfo::coerceToIntArrayWithLimit(QualType Ty,
6991                                                    unsigned MaxSize) const {
6992   // Alignment and Size are measured in bits.
6993   const uint64_t Size = getContext().getTypeSize(Ty);
6994   const uint64_t Alignment = getContext().getTypeAlign(Ty);
6995   const unsigned Div = std::min<unsigned>(MaxSize, Alignment);
6996   llvm::Type *IntType = llvm::Type::getIntNTy(getVMContext(), Div);
6997   const uint64_t NumElements = (Size + Div - 1) / Div;
6998   return ABIArgInfo::getDirect(llvm::ArrayType::get(IntType, NumElements));
6999 }
7000 
7001 ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
7002   if (RetTy->isVoidType())
7003     return ABIArgInfo::getIgnore();
7004 
7005   if (getContext().getLangOpts().OpenMP &&
7006       getContext().getLangOpts().OpenMPIsDevice && isUnsupportedType(RetTy))
7007     return coerceToIntArrayWithLimit(RetTy, 64);
7008 
7009   // note: this is different from default ABI
7010   if (!RetTy->isScalarType())
7011     return ABIArgInfo::getDirect();
7012 
7013   // Treat an enum type as its underlying type.
7014   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
7015     RetTy = EnumTy->getDecl()->getIntegerType();
7016 
7017   return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
7018                                                : ABIArgInfo::getDirect());
7019 }
7020 
7021 ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
7022   // Treat an enum type as its underlying type.
7023   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7024     Ty = EnumTy->getDecl()->getIntegerType();
7025 
7026   // Return aggregates type as indirect by value
7027   if (isAggregateTypeForABI(Ty)) {
7028     // Under CUDA device compilation, tex/surf builtin types are replaced with
7029     // object types and passed directly.
7030     if (getContext().getLangOpts().CUDAIsDevice) {
7031       if (Ty->isCUDADeviceBuiltinSurfaceType())
7032         return ABIArgInfo::getDirect(
7033             CGInfo.getCUDADeviceBuiltinSurfaceDeviceType());
7034       if (Ty->isCUDADeviceBuiltinTextureType())
7035         return ABIArgInfo::getDirect(
7036             CGInfo.getCUDADeviceBuiltinTextureDeviceType());
7037     }
7038     return getNaturalAlignIndirect(Ty, /* byval */ true);
7039   }
7040 
7041   if (const auto *EIT = Ty->getAs<ExtIntType>()) {
7042     if ((EIT->getNumBits() > 128) ||
7043         (!getContext().getTargetInfo().hasInt128Type() &&
7044          EIT->getNumBits() > 64))
7045       return getNaturalAlignIndirect(Ty, /* byval */ true);
7046   }
7047 
7048   return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
7049                                             : ABIArgInfo::getDirect());
7050 }
7051 
7052 void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
7053   if (!getCXXABI().classifyReturnType(FI))
7054     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7055   for (auto &I : FI.arguments())
7056     I.info = classifyArgumentType(I.type);
7057 
7058   // Always honor user-specified calling convention.
7059   if (FI.getCallingConvention() != llvm::CallingConv::C)
7060     return;
7061 
7062   FI.setEffectiveCallingConvention(getRuntimeCC());
7063 }
7064 
7065 Address NVPTXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7066                                 QualType Ty) const {
7067   llvm_unreachable("NVPTX does not support varargs");
7068 }
7069 
7070 void NVPTXTargetCodeGenInfo::setTargetAttributes(
7071     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
7072   if (GV->isDeclaration())
7073     return;
7074   const VarDecl *VD = dyn_cast_or_null<VarDecl>(D);
7075   if (VD) {
7076     if (M.getLangOpts().CUDA) {
7077       if (VD->getType()->isCUDADeviceBuiltinSurfaceType())
7078         addNVVMMetadata(GV, "surface", 1);
7079       else if (VD->getType()->isCUDADeviceBuiltinTextureType())
7080         addNVVMMetadata(GV, "texture", 1);
7081       return;
7082     }
7083   }
7084 
7085   const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
7086   if (!FD) return;
7087 
7088   llvm::Function *F = cast<llvm::Function>(GV);
7089 
7090   // Perform special handling in OpenCL mode
7091   if (M.getLangOpts().OpenCL) {
7092     // Use OpenCL function attributes to check for kernel functions
7093     // By default, all functions are device functions
7094     if (FD->hasAttr<OpenCLKernelAttr>()) {
7095       // OpenCL __kernel functions get kernel metadata
7096       // Create !{<func-ref>, metadata !"kernel", i32 1} node
7097       addNVVMMetadata(F, "kernel", 1);
7098       // And kernel functions are not subject to inlining
7099       F->addFnAttr(llvm::Attribute::NoInline);
7100     }
7101   }
7102 
7103   // Perform special handling in CUDA mode.
7104   if (M.getLangOpts().CUDA) {
7105     // CUDA __global__ functions get a kernel metadata entry.  Since
7106     // __global__ functions cannot be called from the device, we do not
7107     // need to set the noinline attribute.
7108     if (FD->hasAttr<CUDAGlobalAttr>()) {
7109       // Create !{<func-ref>, metadata !"kernel", i32 1} node
7110       addNVVMMetadata(F, "kernel", 1);
7111     }
7112     if (CUDALaunchBoundsAttr *Attr = FD->getAttr<CUDALaunchBoundsAttr>()) {
7113       // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node
7114       llvm::APSInt MaxThreads(32);
7115       MaxThreads = Attr->getMaxThreads()->EvaluateKnownConstInt(M.getContext());
7116       if (MaxThreads > 0)
7117         addNVVMMetadata(F, "maxntidx", MaxThreads.getExtValue());
7118 
7119       // min blocks is an optional argument for CUDALaunchBoundsAttr. If it was
7120       // not specified in __launch_bounds__ or if the user specified a 0 value,
7121       // we don't have to add a PTX directive.
7122       if (Attr->getMinBlocks()) {
7123         llvm::APSInt MinBlocks(32);
7124         MinBlocks = Attr->getMinBlocks()->EvaluateKnownConstInt(M.getContext());
7125         if (MinBlocks > 0)
7126           // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node
7127           addNVVMMetadata(F, "minctasm", MinBlocks.getExtValue());
7128       }
7129     }
7130   }
7131 }
7132 
7133 void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::GlobalValue *GV,
7134                                              StringRef Name, int Operand) {
7135   llvm::Module *M = GV->getParent();
7136   llvm::LLVMContext &Ctx = M->getContext();
7137 
7138   // Get "nvvm.annotations" metadata node
7139   llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
7140 
7141   llvm::Metadata *MDVals[] = {
7142       llvm::ConstantAsMetadata::get(GV), llvm::MDString::get(Ctx, Name),
7143       llvm::ConstantAsMetadata::get(
7144           llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand))};
7145   // Append metadata to nvvm.annotations
7146   MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
7147 }
7148 
7149 bool NVPTXTargetCodeGenInfo::shouldEmitStaticExternCAliases() const {
7150   return false;
7151 }
7152 }
7153 
7154 //===----------------------------------------------------------------------===//
7155 // SystemZ ABI Implementation
7156 //===----------------------------------------------------------------------===//
7157 
7158 namespace {
7159 
7160 class SystemZABIInfo : public SwiftABIInfo {
7161   bool HasVector;
7162   bool IsSoftFloatABI;
7163 
7164 public:
7165   SystemZABIInfo(CodeGenTypes &CGT, bool HV, bool SF)
7166     : SwiftABIInfo(CGT), HasVector(HV), IsSoftFloatABI(SF) {}
7167 
7168   bool isPromotableIntegerTypeForABI(QualType Ty) const;
7169   bool isCompoundType(QualType Ty) const;
7170   bool isVectorArgumentType(QualType Ty) const;
7171   bool isFPArgumentType(QualType Ty) const;
7172   QualType GetSingleElementType(QualType Ty) const;
7173 
7174   ABIArgInfo classifyReturnType(QualType RetTy) const;
7175   ABIArgInfo classifyArgumentType(QualType ArgTy) const;
7176 
7177   void computeInfo(CGFunctionInfo &FI) const override {
7178     if (!getCXXABI().classifyReturnType(FI))
7179       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7180     for (auto &I : FI.arguments())
7181       I.info = classifyArgumentType(I.type);
7182   }
7183 
7184   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7185                     QualType Ty) const override;
7186 
7187   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
7188                                     bool asReturnValue) const override {
7189     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
7190   }
7191   bool isSwiftErrorInRegister() const override {
7192     return false;
7193   }
7194 };
7195 
7196 class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
7197 public:
7198   SystemZTargetCodeGenInfo(CodeGenTypes &CGT, bool HasVector, bool SoftFloatABI)
7199       : TargetCodeGenInfo(
7200             std::make_unique<SystemZABIInfo>(CGT, HasVector, SoftFloatABI)) {}
7201 
7202   llvm::Value *testFPKind(llvm::Value *V, unsigned BuiltinID,
7203                           CGBuilderTy &Builder,
7204                           CodeGenModule &CGM) const override {
7205     assert(V->getType()->isFloatingPointTy() && "V should have an FP type.");
7206     // Only use TDC in constrained FP mode.
7207     if (!Builder.getIsFPConstrained())
7208       return nullptr;
7209 
7210     llvm::Type *Ty = V->getType();
7211     if (Ty->isFloatTy() || Ty->isDoubleTy() || Ty->isFP128Ty()) {
7212       llvm::Module &M = CGM.getModule();
7213       auto &Ctx = M.getContext();
7214       llvm::Function *TDCFunc =
7215           llvm::Intrinsic::getDeclaration(&M, llvm::Intrinsic::s390_tdc, Ty);
7216       unsigned TDCBits = 0;
7217       switch (BuiltinID) {
7218       case Builtin::BI__builtin_isnan:
7219         TDCBits = 0xf;
7220         break;
7221       default:
7222         break;
7223       }
7224       if (TDCBits)
7225         return Builder.CreateCall(
7226             TDCFunc,
7227             {V, llvm::ConstantInt::get(llvm::Type::getInt64Ty(Ctx), TDCBits)});
7228     }
7229     return nullptr;
7230   }
7231 };
7232 }
7233 
7234 bool SystemZABIInfo::isPromotableIntegerTypeForABI(QualType Ty) const {
7235   // Treat an enum type as its underlying type.
7236   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7237     Ty = EnumTy->getDecl()->getIntegerType();
7238 
7239   // Promotable integer types are required to be promoted by the ABI.
7240   if (ABIInfo::isPromotableIntegerTypeForABI(Ty))
7241     return true;
7242 
7243   if (const auto *EIT = Ty->getAs<ExtIntType>())
7244     if (EIT->getNumBits() < 64)
7245       return true;
7246 
7247   // 32-bit values must also be promoted.
7248   if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
7249     switch (BT->getKind()) {
7250     case BuiltinType::Int:
7251     case BuiltinType::UInt:
7252       return true;
7253     default:
7254       return false;
7255     }
7256   return false;
7257 }
7258 
7259 bool SystemZABIInfo::isCompoundType(QualType Ty) const {
7260   return (Ty->isAnyComplexType() ||
7261           Ty->isVectorType() ||
7262           isAggregateTypeForABI(Ty));
7263 }
7264 
7265 bool SystemZABIInfo::isVectorArgumentType(QualType Ty) const {
7266   return (HasVector &&
7267           Ty->isVectorType() &&
7268           getContext().getTypeSize(Ty) <= 128);
7269 }
7270 
7271 bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
7272   if (IsSoftFloatABI)
7273     return false;
7274 
7275   if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
7276     switch (BT->getKind()) {
7277     case BuiltinType::Float:
7278     case BuiltinType::Double:
7279       return true;
7280     default:
7281       return false;
7282     }
7283 
7284   return false;
7285 }
7286 
7287 QualType SystemZABIInfo::GetSingleElementType(QualType Ty) const {
7288   const RecordType *RT = Ty->getAs<RecordType>();
7289 
7290   if (RT && RT->isStructureOrClassType()) {
7291     const RecordDecl *RD = RT->getDecl();
7292     QualType Found;
7293 
7294     // If this is a C++ record, check the bases first.
7295     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
7296       for (const auto &I : CXXRD->bases()) {
7297         QualType Base = I.getType();
7298 
7299         // Empty bases don't affect things either way.
7300         if (isEmptyRecord(getContext(), Base, true))
7301           continue;
7302 
7303         if (!Found.isNull())
7304           return Ty;
7305         Found = GetSingleElementType(Base);
7306       }
7307 
7308     // Check the fields.
7309     for (const auto *FD : RD->fields()) {
7310       // For compatibility with GCC, ignore empty bitfields in C++ mode.
7311       // Unlike isSingleElementStruct(), empty structure and array fields
7312       // do count.  So do anonymous bitfields that aren't zero-sized.
7313       if (getContext().getLangOpts().CPlusPlus &&
7314           FD->isZeroLengthBitField(getContext()))
7315         continue;
7316       // Like isSingleElementStruct(), ignore C++20 empty data members.
7317       if (FD->hasAttr<NoUniqueAddressAttr>() &&
7318           isEmptyRecord(getContext(), FD->getType(), true))
7319         continue;
7320 
7321       // Unlike isSingleElementStruct(), arrays do not count.
7322       // Nested structures still do though.
7323       if (!Found.isNull())
7324         return Ty;
7325       Found = GetSingleElementType(FD->getType());
7326     }
7327 
7328     // Unlike isSingleElementStruct(), trailing padding is allowed.
7329     // An 8-byte aligned struct s { float f; } is passed as a double.
7330     if (!Found.isNull())
7331       return Found;
7332   }
7333 
7334   return Ty;
7335 }
7336 
7337 Address SystemZABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7338                                   QualType Ty) const {
7339   // Assume that va_list type is correct; should be pointer to LLVM type:
7340   // struct {
7341   //   i64 __gpr;
7342   //   i64 __fpr;
7343   //   i8 *__overflow_arg_area;
7344   //   i8 *__reg_save_area;
7345   // };
7346 
7347   // Every non-vector argument occupies 8 bytes and is passed by preference
7348   // in either GPRs or FPRs.  Vector arguments occupy 8 or 16 bytes and are
7349   // always passed on the stack.
7350   Ty = getContext().getCanonicalType(Ty);
7351   auto TyInfo = getContext().getTypeInfoInChars(Ty);
7352   llvm::Type *ArgTy = CGF.ConvertTypeForMem(Ty);
7353   llvm::Type *DirectTy = ArgTy;
7354   ABIArgInfo AI = classifyArgumentType(Ty);
7355   bool IsIndirect = AI.isIndirect();
7356   bool InFPRs = false;
7357   bool IsVector = false;
7358   CharUnits UnpaddedSize;
7359   CharUnits DirectAlign;
7360   if (IsIndirect) {
7361     DirectTy = llvm::PointerType::getUnqual(DirectTy);
7362     UnpaddedSize = DirectAlign = CharUnits::fromQuantity(8);
7363   } else {
7364     if (AI.getCoerceToType())
7365       ArgTy = AI.getCoerceToType();
7366     InFPRs = (!IsSoftFloatABI && (ArgTy->isFloatTy() || ArgTy->isDoubleTy()));
7367     IsVector = ArgTy->isVectorTy();
7368     UnpaddedSize = TyInfo.Width;
7369     DirectAlign = TyInfo.Align;
7370   }
7371   CharUnits PaddedSize = CharUnits::fromQuantity(8);
7372   if (IsVector && UnpaddedSize > PaddedSize)
7373     PaddedSize = CharUnits::fromQuantity(16);
7374   assert((UnpaddedSize <= PaddedSize) && "Invalid argument size.");
7375 
7376   CharUnits Padding = (PaddedSize - UnpaddedSize);
7377 
7378   llvm::Type *IndexTy = CGF.Int64Ty;
7379   llvm::Value *PaddedSizeV =
7380     llvm::ConstantInt::get(IndexTy, PaddedSize.getQuantity());
7381 
7382   if (IsVector) {
7383     // Work out the address of a vector argument on the stack.
7384     // Vector arguments are always passed in the high bits of a
7385     // single (8 byte) or double (16 byte) stack slot.
7386     Address OverflowArgAreaPtr =
7387         CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr");
7388     Address OverflowArgArea =
7389       Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
7390               TyInfo.Align);
7391     Address MemAddr =
7392       CGF.Builder.CreateElementBitCast(OverflowArgArea, DirectTy, "mem_addr");
7393 
7394     // Update overflow_arg_area_ptr pointer
7395     llvm::Value *NewOverflowArgArea =
7396       CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
7397                             "overflow_arg_area");
7398     CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
7399 
7400     return MemAddr;
7401   }
7402 
7403   assert(PaddedSize.getQuantity() == 8);
7404 
7405   unsigned MaxRegs, RegCountField, RegSaveIndex;
7406   CharUnits RegPadding;
7407   if (InFPRs) {
7408     MaxRegs = 4; // Maximum of 4 FPR arguments
7409     RegCountField = 1; // __fpr
7410     RegSaveIndex = 16; // save offset for f0
7411     RegPadding = CharUnits(); // floats are passed in the high bits of an FPR
7412   } else {
7413     MaxRegs = 5; // Maximum of 5 GPR arguments
7414     RegCountField = 0; // __gpr
7415     RegSaveIndex = 2; // save offset for r2
7416     RegPadding = Padding; // values are passed in the low bits of a GPR
7417   }
7418 
7419   Address RegCountPtr =
7420       CGF.Builder.CreateStructGEP(VAListAddr, RegCountField, "reg_count_ptr");
7421   llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
7422   llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
7423   llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
7424                                                  "fits_in_regs");
7425 
7426   llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
7427   llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
7428   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
7429   CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
7430 
7431   // Emit code to load the value if it was passed in registers.
7432   CGF.EmitBlock(InRegBlock);
7433 
7434   // Work out the address of an argument register.
7435   llvm::Value *ScaledRegCount =
7436     CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
7437   llvm::Value *RegBase =
7438     llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize.getQuantity()
7439                                       + RegPadding.getQuantity());
7440   llvm::Value *RegOffset =
7441     CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
7442   Address RegSaveAreaPtr =
7443       CGF.Builder.CreateStructGEP(VAListAddr, 3, "reg_save_area_ptr");
7444   llvm::Value *RegSaveArea =
7445     CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
7446   Address RawRegAddr(CGF.Builder.CreateGEP(RegSaveArea, RegOffset,
7447                                            "raw_reg_addr"),
7448                      PaddedSize);
7449   Address RegAddr =
7450     CGF.Builder.CreateElementBitCast(RawRegAddr, DirectTy, "reg_addr");
7451 
7452   // Update the register count
7453   llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
7454   llvm::Value *NewRegCount =
7455     CGF.Builder.CreateAdd(RegCount, One, "reg_count");
7456   CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
7457   CGF.EmitBranch(ContBlock);
7458 
7459   // Emit code to load the value if it was passed in memory.
7460   CGF.EmitBlock(InMemBlock);
7461 
7462   // Work out the address of a stack argument.
7463   Address OverflowArgAreaPtr =
7464       CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr");
7465   Address OverflowArgArea =
7466     Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
7467             PaddedSize);
7468   Address RawMemAddr =
7469     CGF.Builder.CreateConstByteGEP(OverflowArgArea, Padding, "raw_mem_addr");
7470   Address MemAddr =
7471     CGF.Builder.CreateElementBitCast(RawMemAddr, DirectTy, "mem_addr");
7472 
7473   // Update overflow_arg_area_ptr pointer
7474   llvm::Value *NewOverflowArgArea =
7475     CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
7476                           "overflow_arg_area");
7477   CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
7478   CGF.EmitBranch(ContBlock);
7479 
7480   // Return the appropriate result.
7481   CGF.EmitBlock(ContBlock);
7482   Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
7483                                  MemAddr, InMemBlock, "va_arg.addr");
7484 
7485   if (IsIndirect)
7486     ResAddr = Address(CGF.Builder.CreateLoad(ResAddr, "indirect_arg"),
7487                       TyInfo.Align);
7488 
7489   return ResAddr;
7490 }
7491 
7492 ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
7493   if (RetTy->isVoidType())
7494     return ABIArgInfo::getIgnore();
7495   if (isVectorArgumentType(RetTy))
7496     return ABIArgInfo::getDirect();
7497   if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
7498     return getNaturalAlignIndirect(RetTy);
7499   return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
7500                                                : ABIArgInfo::getDirect());
7501 }
7502 
7503 ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
7504   // Handle the generic C++ ABI.
7505   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
7506     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
7507 
7508   // Integers and enums are extended to full register width.
7509   if (isPromotableIntegerTypeForABI(Ty))
7510     return ABIArgInfo::getExtend(Ty);
7511 
7512   // Handle vector types and vector-like structure types.  Note that
7513   // as opposed to float-like structure types, we do not allow any
7514   // padding for vector-like structures, so verify the sizes match.
7515   uint64_t Size = getContext().getTypeSize(Ty);
7516   QualType SingleElementTy = GetSingleElementType(Ty);
7517   if (isVectorArgumentType(SingleElementTy) &&
7518       getContext().getTypeSize(SingleElementTy) == Size)
7519     return ABIArgInfo::getDirect(CGT.ConvertType(SingleElementTy));
7520 
7521   // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
7522   if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
7523     return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
7524 
7525   // Handle small structures.
7526   if (const RecordType *RT = Ty->getAs<RecordType>()) {
7527     // Structures with flexible arrays have variable length, so really
7528     // fail the size test above.
7529     const RecordDecl *RD = RT->getDecl();
7530     if (RD->hasFlexibleArrayMember())
7531       return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
7532 
7533     // The structure is passed as an unextended integer, a float, or a double.
7534     llvm::Type *PassTy;
7535     if (isFPArgumentType(SingleElementTy)) {
7536       assert(Size == 32 || Size == 64);
7537       if (Size == 32)
7538         PassTy = llvm::Type::getFloatTy(getVMContext());
7539       else
7540         PassTy = llvm::Type::getDoubleTy(getVMContext());
7541     } else
7542       PassTy = llvm::IntegerType::get(getVMContext(), Size);
7543     return ABIArgInfo::getDirect(PassTy);
7544   }
7545 
7546   // Non-structure compounds are passed indirectly.
7547   if (isCompoundType(Ty))
7548     return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
7549 
7550   return ABIArgInfo::getDirect(nullptr);
7551 }
7552 
7553 //===----------------------------------------------------------------------===//
7554 // MSP430 ABI Implementation
7555 //===----------------------------------------------------------------------===//
7556 
7557 namespace {
7558 
7559 class MSP430ABIInfo : public DefaultABIInfo {
7560   static ABIArgInfo complexArgInfo() {
7561     ABIArgInfo Info = ABIArgInfo::getDirect();
7562     Info.setCanBeFlattened(false);
7563     return Info;
7564   }
7565 
7566 public:
7567   MSP430ABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
7568 
7569   ABIArgInfo classifyReturnType(QualType RetTy) const {
7570     if (RetTy->isAnyComplexType())
7571       return complexArgInfo();
7572 
7573     return DefaultABIInfo::classifyReturnType(RetTy);
7574   }
7575 
7576   ABIArgInfo classifyArgumentType(QualType RetTy) const {
7577     if (RetTy->isAnyComplexType())
7578       return complexArgInfo();
7579 
7580     return DefaultABIInfo::classifyArgumentType(RetTy);
7581   }
7582 
7583   // Just copy the original implementations because
7584   // DefaultABIInfo::classify{Return,Argument}Type() are not virtual
7585   void computeInfo(CGFunctionInfo &FI) const override {
7586     if (!getCXXABI().classifyReturnType(FI))
7587       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7588     for (auto &I : FI.arguments())
7589       I.info = classifyArgumentType(I.type);
7590   }
7591 
7592   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7593                     QualType Ty) const override {
7594     return EmitVAArgInstr(CGF, VAListAddr, Ty, classifyArgumentType(Ty));
7595   }
7596 };
7597 
7598 class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
7599 public:
7600   MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
7601       : TargetCodeGenInfo(std::make_unique<MSP430ABIInfo>(CGT)) {}
7602   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
7603                            CodeGen::CodeGenModule &M) const override;
7604 };
7605 
7606 }
7607 
7608 void MSP430TargetCodeGenInfo::setTargetAttributes(
7609     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
7610   if (GV->isDeclaration())
7611     return;
7612   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
7613     const auto *InterruptAttr = FD->getAttr<MSP430InterruptAttr>();
7614     if (!InterruptAttr)
7615       return;
7616 
7617     // Handle 'interrupt' attribute:
7618     llvm::Function *F = cast<llvm::Function>(GV);
7619 
7620     // Step 1: Set ISR calling convention.
7621     F->setCallingConv(llvm::CallingConv::MSP430_INTR);
7622 
7623     // Step 2: Add attributes goodness.
7624     F->addFnAttr(llvm::Attribute::NoInline);
7625     F->addFnAttr("interrupt", llvm::utostr(InterruptAttr->getNumber()));
7626   }
7627 }
7628 
7629 //===----------------------------------------------------------------------===//
7630 // MIPS ABI Implementation.  This works for both little-endian and
7631 // big-endian variants.
7632 //===----------------------------------------------------------------------===//
7633 
7634 namespace {
7635 class MipsABIInfo : public ABIInfo {
7636   bool IsO32;
7637   unsigned MinABIStackAlignInBytes, StackAlignInBytes;
7638   void CoerceToIntArgs(uint64_t TySize,
7639                        SmallVectorImpl<llvm::Type *> &ArgList) const;
7640   llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
7641   llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
7642   llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
7643 public:
7644   MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
7645     ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
7646     StackAlignInBytes(IsO32 ? 8 : 16) {}
7647 
7648   ABIArgInfo classifyReturnType(QualType RetTy) const;
7649   ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
7650   void computeInfo(CGFunctionInfo &FI) const override;
7651   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7652                     QualType Ty) const override;
7653   ABIArgInfo extendType(QualType Ty) const;
7654 };
7655 
7656 class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
7657   unsigned SizeOfUnwindException;
7658 public:
7659   MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
7660       : TargetCodeGenInfo(std::make_unique<MipsABIInfo>(CGT, IsO32)),
7661         SizeOfUnwindException(IsO32 ? 24 : 32) {}
7662 
7663   int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
7664     return 29;
7665   }
7666 
7667   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
7668                            CodeGen::CodeGenModule &CGM) const override {
7669     const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
7670     if (!FD) return;
7671     llvm::Function *Fn = cast<llvm::Function>(GV);
7672 
7673     if (FD->hasAttr<MipsLongCallAttr>())
7674       Fn->addFnAttr("long-call");
7675     else if (FD->hasAttr<MipsShortCallAttr>())
7676       Fn->addFnAttr("short-call");
7677 
7678     // Other attributes do not have a meaning for declarations.
7679     if (GV->isDeclaration())
7680       return;
7681 
7682     if (FD->hasAttr<Mips16Attr>()) {
7683       Fn->addFnAttr("mips16");
7684     }
7685     else if (FD->hasAttr<NoMips16Attr>()) {
7686       Fn->addFnAttr("nomips16");
7687     }
7688 
7689     if (FD->hasAttr<MicroMipsAttr>())
7690       Fn->addFnAttr("micromips");
7691     else if (FD->hasAttr<NoMicroMipsAttr>())
7692       Fn->addFnAttr("nomicromips");
7693 
7694     const MipsInterruptAttr *Attr = FD->getAttr<MipsInterruptAttr>();
7695     if (!Attr)
7696       return;
7697 
7698     const char *Kind;
7699     switch (Attr->getInterrupt()) {
7700     case MipsInterruptAttr::eic:     Kind = "eic"; break;
7701     case MipsInterruptAttr::sw0:     Kind = "sw0"; break;
7702     case MipsInterruptAttr::sw1:     Kind = "sw1"; break;
7703     case MipsInterruptAttr::hw0:     Kind = "hw0"; break;
7704     case MipsInterruptAttr::hw1:     Kind = "hw1"; break;
7705     case MipsInterruptAttr::hw2:     Kind = "hw2"; break;
7706     case MipsInterruptAttr::hw3:     Kind = "hw3"; break;
7707     case MipsInterruptAttr::hw4:     Kind = "hw4"; break;
7708     case MipsInterruptAttr::hw5:     Kind = "hw5"; break;
7709     }
7710 
7711     Fn->addFnAttr("interrupt", Kind);
7712 
7713   }
7714 
7715   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
7716                                llvm::Value *Address) const override;
7717 
7718   unsigned getSizeOfUnwindException() const override {
7719     return SizeOfUnwindException;
7720   }
7721 };
7722 }
7723 
7724 void MipsABIInfo::CoerceToIntArgs(
7725     uint64_t TySize, SmallVectorImpl<llvm::Type *> &ArgList) const {
7726   llvm::IntegerType *IntTy =
7727     llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
7728 
7729   // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
7730   for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
7731     ArgList.push_back(IntTy);
7732 
7733   // If necessary, add one more integer type to ArgList.
7734   unsigned R = TySize % (MinABIStackAlignInBytes * 8);
7735 
7736   if (R)
7737     ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
7738 }
7739 
7740 // In N32/64, an aligned double precision floating point field is passed in
7741 // a register.
7742 llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
7743   SmallVector<llvm::Type*, 8> ArgList, IntArgList;
7744 
7745   if (IsO32) {
7746     CoerceToIntArgs(TySize, ArgList);
7747     return llvm::StructType::get(getVMContext(), ArgList);
7748   }
7749 
7750   if (Ty->isComplexType())
7751     return CGT.ConvertType(Ty);
7752 
7753   const RecordType *RT = Ty->getAs<RecordType>();
7754 
7755   // Unions/vectors are passed in integer registers.
7756   if (!RT || !RT->isStructureOrClassType()) {
7757     CoerceToIntArgs(TySize, ArgList);
7758     return llvm::StructType::get(getVMContext(), ArgList);
7759   }
7760 
7761   const RecordDecl *RD = RT->getDecl();
7762   const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
7763   assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
7764 
7765   uint64_t LastOffset = 0;
7766   unsigned idx = 0;
7767   llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
7768 
7769   // Iterate over fields in the struct/class and check if there are any aligned
7770   // double fields.
7771   for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
7772        i != e; ++i, ++idx) {
7773     const QualType Ty = i->getType();
7774     const BuiltinType *BT = Ty->getAs<BuiltinType>();
7775 
7776     if (!BT || BT->getKind() != BuiltinType::Double)
7777       continue;
7778 
7779     uint64_t Offset = Layout.getFieldOffset(idx);
7780     if (Offset % 64) // Ignore doubles that are not aligned.
7781       continue;
7782 
7783     // Add ((Offset - LastOffset) / 64) args of type i64.
7784     for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
7785       ArgList.push_back(I64);
7786 
7787     // Add double type.
7788     ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
7789     LastOffset = Offset + 64;
7790   }
7791 
7792   CoerceToIntArgs(TySize - LastOffset, IntArgList);
7793   ArgList.append(IntArgList.begin(), IntArgList.end());
7794 
7795   return llvm::StructType::get(getVMContext(), ArgList);
7796 }
7797 
7798 llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
7799                                         uint64_t Offset) const {
7800   if (OrigOffset + MinABIStackAlignInBytes > Offset)
7801     return nullptr;
7802 
7803   return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
7804 }
7805 
7806 ABIArgInfo
7807 MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
7808   Ty = useFirstFieldIfTransparentUnion(Ty);
7809 
7810   uint64_t OrigOffset = Offset;
7811   uint64_t TySize = getContext().getTypeSize(Ty);
7812   uint64_t Align = getContext().getTypeAlign(Ty) / 8;
7813 
7814   Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
7815                    (uint64_t)StackAlignInBytes);
7816   unsigned CurrOffset = llvm::alignTo(Offset, Align);
7817   Offset = CurrOffset + llvm::alignTo(TySize, Align * 8) / 8;
7818 
7819   if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
7820     // Ignore empty aggregates.
7821     if (TySize == 0)
7822       return ABIArgInfo::getIgnore();
7823 
7824     if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
7825       Offset = OrigOffset + MinABIStackAlignInBytes;
7826       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
7827     }
7828 
7829     // If we have reached here, aggregates are passed directly by coercing to
7830     // another structure type. Padding is inserted if the offset of the
7831     // aggregate is unaligned.
7832     ABIArgInfo ArgInfo =
7833         ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
7834                               getPaddingType(OrigOffset, CurrOffset));
7835     ArgInfo.setInReg(true);
7836     return ArgInfo;
7837   }
7838 
7839   // Treat an enum type as its underlying type.
7840   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7841     Ty = EnumTy->getDecl()->getIntegerType();
7842 
7843   // Make sure we pass indirectly things that are too large.
7844   if (const auto *EIT = Ty->getAs<ExtIntType>())
7845     if (EIT->getNumBits() > 128 ||
7846         (EIT->getNumBits() > 64 &&
7847          !getContext().getTargetInfo().hasInt128Type()))
7848       return getNaturalAlignIndirect(Ty);
7849 
7850   // All integral types are promoted to the GPR width.
7851   if (Ty->isIntegralOrEnumerationType())
7852     return extendType(Ty);
7853 
7854   return ABIArgInfo::getDirect(
7855       nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset));
7856 }
7857 
7858 llvm::Type*
7859 MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
7860   const RecordType *RT = RetTy->getAs<RecordType>();
7861   SmallVector<llvm::Type*, 8> RTList;
7862 
7863   if (RT && RT->isStructureOrClassType()) {
7864     const RecordDecl *RD = RT->getDecl();
7865     const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
7866     unsigned FieldCnt = Layout.getFieldCount();
7867 
7868     // N32/64 returns struct/classes in floating point registers if the
7869     // following conditions are met:
7870     // 1. The size of the struct/class is no larger than 128-bit.
7871     // 2. The struct/class has one or two fields all of which are floating
7872     //    point types.
7873     // 3. The offset of the first field is zero (this follows what gcc does).
7874     //
7875     // Any other composite results are returned in integer registers.
7876     //
7877     if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
7878       RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
7879       for (; b != e; ++b) {
7880         const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
7881 
7882         if (!BT || !BT->isFloatingPoint())
7883           break;
7884 
7885         RTList.push_back(CGT.ConvertType(b->getType()));
7886       }
7887 
7888       if (b == e)
7889         return llvm::StructType::get(getVMContext(), RTList,
7890                                      RD->hasAttr<PackedAttr>());
7891 
7892       RTList.clear();
7893     }
7894   }
7895 
7896   CoerceToIntArgs(Size, RTList);
7897   return llvm::StructType::get(getVMContext(), RTList);
7898 }
7899 
7900 ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
7901   uint64_t Size = getContext().getTypeSize(RetTy);
7902 
7903   if (RetTy->isVoidType())
7904     return ABIArgInfo::getIgnore();
7905 
7906   // O32 doesn't treat zero-sized structs differently from other structs.
7907   // However, N32/N64 ignores zero sized return values.
7908   if (!IsO32 && Size == 0)
7909     return ABIArgInfo::getIgnore();
7910 
7911   if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
7912     if (Size <= 128) {
7913       if (RetTy->isAnyComplexType())
7914         return ABIArgInfo::getDirect();
7915 
7916       // O32 returns integer vectors in registers and N32/N64 returns all small
7917       // aggregates in registers.
7918       if (!IsO32 ||
7919           (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) {
7920         ABIArgInfo ArgInfo =
7921             ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
7922         ArgInfo.setInReg(true);
7923         return ArgInfo;
7924       }
7925     }
7926 
7927     return getNaturalAlignIndirect(RetTy);
7928   }
7929 
7930   // Treat an enum type as its underlying type.
7931   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
7932     RetTy = EnumTy->getDecl()->getIntegerType();
7933 
7934   // Make sure we pass indirectly things that are too large.
7935   if (const auto *EIT = RetTy->getAs<ExtIntType>())
7936     if (EIT->getNumBits() > 128 ||
7937         (EIT->getNumBits() > 64 &&
7938          !getContext().getTargetInfo().hasInt128Type()))
7939       return getNaturalAlignIndirect(RetTy);
7940 
7941   if (isPromotableIntegerTypeForABI(RetTy))
7942     return ABIArgInfo::getExtend(RetTy);
7943 
7944   if ((RetTy->isUnsignedIntegerOrEnumerationType() ||
7945       RetTy->isSignedIntegerOrEnumerationType()) && Size == 32 && !IsO32)
7946     return ABIArgInfo::getSignExtend(RetTy);
7947 
7948   return ABIArgInfo::getDirect();
7949 }
7950 
7951 void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
7952   ABIArgInfo &RetInfo = FI.getReturnInfo();
7953   if (!getCXXABI().classifyReturnType(FI))
7954     RetInfo = classifyReturnType(FI.getReturnType());
7955 
7956   // Check if a pointer to an aggregate is passed as a hidden argument.
7957   uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
7958 
7959   for (auto &I : FI.arguments())
7960     I.info = classifyArgumentType(I.type, Offset);
7961 }
7962 
7963 Address MipsABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7964                                QualType OrigTy) const {
7965   QualType Ty = OrigTy;
7966 
7967   // Integer arguments are promoted to 32-bit on O32 and 64-bit on N32/N64.
7968   // Pointers are also promoted in the same way but this only matters for N32.
7969   unsigned SlotSizeInBits = IsO32 ? 32 : 64;
7970   unsigned PtrWidth = getTarget().getPointerWidth(0);
7971   bool DidPromote = false;
7972   if ((Ty->isIntegerType() &&
7973           getContext().getIntWidth(Ty) < SlotSizeInBits) ||
7974       (Ty->isPointerType() && PtrWidth < SlotSizeInBits)) {
7975     DidPromote = true;
7976     Ty = getContext().getIntTypeForBitwidth(SlotSizeInBits,
7977                                             Ty->isSignedIntegerType());
7978   }
7979 
7980   auto TyInfo = getContext().getTypeInfoInChars(Ty);
7981 
7982   // The alignment of things in the argument area is never larger than
7983   // StackAlignInBytes.
7984   TyInfo.Align =
7985     std::min(TyInfo.Align, CharUnits::fromQuantity(StackAlignInBytes));
7986 
7987   // MinABIStackAlignInBytes is the size of argument slots on the stack.
7988   CharUnits ArgSlotSize = CharUnits::fromQuantity(MinABIStackAlignInBytes);
7989 
7990   Address Addr = emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
7991                           TyInfo, ArgSlotSize, /*AllowHigherAlign*/ true);
7992 
7993 
7994   // If there was a promotion, "unpromote" into a temporary.
7995   // TODO: can we just use a pointer into a subset of the original slot?
7996   if (DidPromote) {
7997     Address Temp = CGF.CreateMemTemp(OrigTy, "vaarg.promotion-temp");
7998     llvm::Value *Promoted = CGF.Builder.CreateLoad(Addr);
7999 
8000     // Truncate down to the right width.
8001     llvm::Type *IntTy = (OrigTy->isIntegerType() ? Temp.getElementType()
8002                                                  : CGF.IntPtrTy);
8003     llvm::Value *V = CGF.Builder.CreateTrunc(Promoted, IntTy);
8004     if (OrigTy->isPointerType())
8005       V = CGF.Builder.CreateIntToPtr(V, Temp.getElementType());
8006 
8007     CGF.Builder.CreateStore(V, Temp);
8008     Addr = Temp;
8009   }
8010 
8011   return Addr;
8012 }
8013 
8014 ABIArgInfo MipsABIInfo::extendType(QualType Ty) const {
8015   int TySize = getContext().getTypeSize(Ty);
8016 
8017   // MIPS64 ABI requires unsigned 32 bit integers to be sign extended.
8018   if (Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
8019     return ABIArgInfo::getSignExtend(Ty);
8020 
8021   return ABIArgInfo::getExtend(Ty);
8022 }
8023 
8024 bool
8025 MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
8026                                                llvm::Value *Address) const {
8027   // This information comes from gcc's implementation, which seems to
8028   // as canonical as it gets.
8029 
8030   // Everything on MIPS is 4 bytes.  Double-precision FP registers
8031   // are aliased to pairs of single-precision FP registers.
8032   llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
8033 
8034   // 0-31 are the general purpose registers, $0 - $31.
8035   // 32-63 are the floating-point registers, $f0 - $f31.
8036   // 64 and 65 are the multiply/divide registers, $hi and $lo.
8037   // 66 is the (notional, I think) register for signal-handler return.
8038   AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
8039 
8040   // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
8041   // They are one bit wide and ignored here.
8042 
8043   // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
8044   // (coprocessor 1 is the FP unit)
8045   // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
8046   // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
8047   // 176-181 are the DSP accumulator registers.
8048   AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
8049   return false;
8050 }
8051 
8052 //===----------------------------------------------------------------------===//
8053 // AVR ABI Implementation.
8054 //===----------------------------------------------------------------------===//
8055 
8056 namespace {
8057 class AVRTargetCodeGenInfo : public TargetCodeGenInfo {
8058 public:
8059   AVRTargetCodeGenInfo(CodeGenTypes &CGT)
8060       : TargetCodeGenInfo(std::make_unique<DefaultABIInfo>(CGT)) {}
8061 
8062   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
8063                            CodeGen::CodeGenModule &CGM) const override {
8064     if (GV->isDeclaration())
8065       return;
8066     const auto *FD = dyn_cast_or_null<FunctionDecl>(D);
8067     if (!FD) return;
8068     auto *Fn = cast<llvm::Function>(GV);
8069 
8070     if (FD->getAttr<AVRInterruptAttr>())
8071       Fn->addFnAttr("interrupt");
8072 
8073     if (FD->getAttr<AVRSignalAttr>())
8074       Fn->addFnAttr("signal");
8075   }
8076 };
8077 }
8078 
8079 //===----------------------------------------------------------------------===//
8080 // TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
8081 // Currently subclassed only to implement custom OpenCL C function attribute
8082 // handling.
8083 //===----------------------------------------------------------------------===//
8084 
8085 namespace {
8086 
8087 class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
8088 public:
8089   TCETargetCodeGenInfo(CodeGenTypes &CGT)
8090     : DefaultTargetCodeGenInfo(CGT) {}
8091 
8092   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
8093                            CodeGen::CodeGenModule &M) const override;
8094 };
8095 
8096 void TCETargetCodeGenInfo::setTargetAttributes(
8097     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
8098   if (GV->isDeclaration())
8099     return;
8100   const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
8101   if (!FD) return;
8102 
8103   llvm::Function *F = cast<llvm::Function>(GV);
8104 
8105   if (M.getLangOpts().OpenCL) {
8106     if (FD->hasAttr<OpenCLKernelAttr>()) {
8107       // OpenCL C Kernel functions are not subject to inlining
8108       F->addFnAttr(llvm::Attribute::NoInline);
8109       const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
8110       if (Attr) {
8111         // Convert the reqd_work_group_size() attributes to metadata.
8112         llvm::LLVMContext &Context = F->getContext();
8113         llvm::NamedMDNode *OpenCLMetadata =
8114             M.getModule().getOrInsertNamedMetadata(
8115                 "opencl.kernel_wg_size_info");
8116 
8117         SmallVector<llvm::Metadata *, 5> Operands;
8118         Operands.push_back(llvm::ConstantAsMetadata::get(F));
8119 
8120         Operands.push_back(
8121             llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
8122                 M.Int32Ty, llvm::APInt(32, Attr->getXDim()))));
8123         Operands.push_back(
8124             llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
8125                 M.Int32Ty, llvm::APInt(32, Attr->getYDim()))));
8126         Operands.push_back(
8127             llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
8128                 M.Int32Ty, llvm::APInt(32, Attr->getZDim()))));
8129 
8130         // Add a boolean constant operand for "required" (true) or "hint"
8131         // (false) for implementing the work_group_size_hint attr later.
8132         // Currently always true as the hint is not yet implemented.
8133         Operands.push_back(
8134             llvm::ConstantAsMetadata::get(llvm::ConstantInt::getTrue(Context)));
8135         OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
8136       }
8137     }
8138   }
8139 }
8140 
8141 }
8142 
8143 //===----------------------------------------------------------------------===//
8144 // Hexagon ABI Implementation
8145 //===----------------------------------------------------------------------===//
8146 
8147 namespace {
8148 
8149 class HexagonABIInfo : public DefaultABIInfo {
8150 public:
8151   HexagonABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
8152 
8153 private:
8154   ABIArgInfo classifyReturnType(QualType RetTy) const;
8155   ABIArgInfo classifyArgumentType(QualType RetTy) const;
8156   ABIArgInfo classifyArgumentType(QualType RetTy, unsigned *RegsLeft) const;
8157 
8158   void computeInfo(CGFunctionInfo &FI) const override;
8159 
8160   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8161                     QualType Ty) const override;
8162   Address EmitVAArgFromMemory(CodeGenFunction &CFG, Address VAListAddr,
8163                               QualType Ty) const;
8164   Address EmitVAArgForHexagon(CodeGenFunction &CFG, Address VAListAddr,
8165                               QualType Ty) const;
8166   Address EmitVAArgForHexagonLinux(CodeGenFunction &CFG, Address VAListAddr,
8167                                    QualType Ty) const;
8168 };
8169 
8170 class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
8171 public:
8172   HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
8173       : TargetCodeGenInfo(std::make_unique<HexagonABIInfo>(CGT)) {}
8174 
8175   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
8176     return 29;
8177   }
8178 
8179   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
8180                            CodeGen::CodeGenModule &GCM) const override {
8181     if (GV->isDeclaration())
8182       return;
8183     const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
8184     if (!FD)
8185       return;
8186   }
8187 };
8188 
8189 } // namespace
8190 
8191 void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
8192   unsigned RegsLeft = 6;
8193   if (!getCXXABI().classifyReturnType(FI))
8194     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
8195   for (auto &I : FI.arguments())
8196     I.info = classifyArgumentType(I.type, &RegsLeft);
8197 }
8198 
8199 static bool HexagonAdjustRegsLeft(uint64_t Size, unsigned *RegsLeft) {
8200   assert(Size <= 64 && "Not expecting to pass arguments larger than 64 bits"
8201                        " through registers");
8202 
8203   if (*RegsLeft == 0)
8204     return false;
8205 
8206   if (Size <= 32) {
8207     (*RegsLeft)--;
8208     return true;
8209   }
8210 
8211   if (2 <= (*RegsLeft & (~1U))) {
8212     *RegsLeft = (*RegsLeft & (~1U)) - 2;
8213     return true;
8214   }
8215 
8216   // Next available register was r5 but candidate was greater than 32-bits so it
8217   // has to go on the stack. However we still consume r5
8218   if (*RegsLeft == 1)
8219     *RegsLeft = 0;
8220 
8221   return false;
8222 }
8223 
8224 ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty,
8225                                                 unsigned *RegsLeft) const {
8226   if (!isAggregateTypeForABI(Ty)) {
8227     // Treat an enum type as its underlying type.
8228     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
8229       Ty = EnumTy->getDecl()->getIntegerType();
8230 
8231     uint64_t Size = getContext().getTypeSize(Ty);
8232     if (Size <= 64)
8233       HexagonAdjustRegsLeft(Size, RegsLeft);
8234 
8235     if (Size > 64 && Ty->isExtIntType())
8236       return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
8237 
8238     return isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
8239                                              : ABIArgInfo::getDirect();
8240   }
8241 
8242   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
8243     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
8244 
8245   // Ignore empty records.
8246   if (isEmptyRecord(getContext(), Ty, true))
8247     return ABIArgInfo::getIgnore();
8248 
8249   uint64_t Size = getContext().getTypeSize(Ty);
8250   unsigned Align = getContext().getTypeAlign(Ty);
8251 
8252   if (Size > 64)
8253     return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
8254 
8255   if (HexagonAdjustRegsLeft(Size, RegsLeft))
8256     Align = Size <= 32 ? 32 : 64;
8257   if (Size <= Align) {
8258     // Pass in the smallest viable integer type.
8259     if (!llvm::isPowerOf2_64(Size))
8260       Size = llvm::NextPowerOf2(Size);
8261     return ABIArgInfo::getDirect(llvm::Type::getIntNTy(getVMContext(), Size));
8262   }
8263   return DefaultABIInfo::classifyArgumentType(Ty);
8264 }
8265 
8266 ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
8267   if (RetTy->isVoidType())
8268     return ABIArgInfo::getIgnore();
8269 
8270   const TargetInfo &T = CGT.getTarget();
8271   uint64_t Size = getContext().getTypeSize(RetTy);
8272 
8273   if (RetTy->getAs<VectorType>()) {
8274     // HVX vectors are returned in vector registers or register pairs.
8275     if (T.hasFeature("hvx")) {
8276       assert(T.hasFeature("hvx-length64b") || T.hasFeature("hvx-length128b"));
8277       uint64_t VecSize = T.hasFeature("hvx-length64b") ? 64*8 : 128*8;
8278       if (Size == VecSize || Size == 2*VecSize)
8279         return ABIArgInfo::getDirectInReg();
8280     }
8281     // Large vector types should be returned via memory.
8282     if (Size > 64)
8283       return getNaturalAlignIndirect(RetTy);
8284   }
8285 
8286   if (!isAggregateTypeForABI(RetTy)) {
8287     // Treat an enum type as its underlying type.
8288     if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
8289       RetTy = EnumTy->getDecl()->getIntegerType();
8290 
8291     if (Size > 64 && RetTy->isExtIntType())
8292       return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
8293 
8294     return isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
8295                                                 : ABIArgInfo::getDirect();
8296   }
8297 
8298   if (isEmptyRecord(getContext(), RetTy, true))
8299     return ABIArgInfo::getIgnore();
8300 
8301   // Aggregates <= 8 bytes are returned in registers, other aggregates
8302   // are returned indirectly.
8303   if (Size <= 64) {
8304     // Return in the smallest viable integer type.
8305     if (!llvm::isPowerOf2_64(Size))
8306       Size = llvm::NextPowerOf2(Size);
8307     return ABIArgInfo::getDirect(llvm::Type::getIntNTy(getVMContext(), Size));
8308   }
8309   return getNaturalAlignIndirect(RetTy, /*ByVal=*/true);
8310 }
8311 
8312 Address HexagonABIInfo::EmitVAArgFromMemory(CodeGenFunction &CGF,
8313                                             Address VAListAddr,
8314                                             QualType Ty) const {
8315   // Load the overflow area pointer.
8316   Address __overflow_area_pointer_p =
8317       CGF.Builder.CreateStructGEP(VAListAddr, 2, "__overflow_area_pointer_p");
8318   llvm::Value *__overflow_area_pointer = CGF.Builder.CreateLoad(
8319       __overflow_area_pointer_p, "__overflow_area_pointer");
8320 
8321   uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8;
8322   if (Align > 4) {
8323     // Alignment should be a power of 2.
8324     assert((Align & (Align - 1)) == 0 && "Alignment is not power of 2!");
8325 
8326     // overflow_arg_area = (overflow_arg_area + align - 1) & -align;
8327     llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int64Ty, Align - 1);
8328 
8329     // Add offset to the current pointer to access the argument.
8330     __overflow_area_pointer =
8331         CGF.Builder.CreateGEP(__overflow_area_pointer, Offset);
8332     llvm::Value *AsInt =
8333         CGF.Builder.CreatePtrToInt(__overflow_area_pointer, CGF.Int32Ty);
8334 
8335     // Create a mask which should be "AND"ed
8336     // with (overflow_arg_area + align - 1)
8337     llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int32Ty, -(int)Align);
8338     __overflow_area_pointer = CGF.Builder.CreateIntToPtr(
8339         CGF.Builder.CreateAnd(AsInt, Mask), __overflow_area_pointer->getType(),
8340         "__overflow_area_pointer.align");
8341   }
8342 
8343   // Get the type of the argument from memory and bitcast
8344   // overflow area pointer to the argument type.
8345   llvm::Type *PTy = CGF.ConvertTypeForMem(Ty);
8346   Address AddrTyped = CGF.Builder.CreateBitCast(
8347       Address(__overflow_area_pointer, CharUnits::fromQuantity(Align)),
8348       llvm::PointerType::getUnqual(PTy));
8349 
8350   // Round up to the minimum stack alignment for varargs which is 4 bytes.
8351   uint64_t Offset = llvm::alignTo(CGF.getContext().getTypeSize(Ty) / 8, 4);
8352 
8353   __overflow_area_pointer = CGF.Builder.CreateGEP(
8354       __overflow_area_pointer, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
8355       "__overflow_area_pointer.next");
8356   CGF.Builder.CreateStore(__overflow_area_pointer, __overflow_area_pointer_p);
8357 
8358   return AddrTyped;
8359 }
8360 
8361 Address HexagonABIInfo::EmitVAArgForHexagon(CodeGenFunction &CGF,
8362                                             Address VAListAddr,
8363                                             QualType Ty) const {
8364   // FIXME: Need to handle alignment
8365   llvm::Type *BP = CGF.Int8PtrTy;
8366   llvm::Type *BPP = CGF.Int8PtrPtrTy;
8367   CGBuilderTy &Builder = CGF.Builder;
8368   Address VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
8369   llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
8370   // Handle address alignment for type alignment > 32 bits
8371   uint64_t TyAlign = CGF.getContext().getTypeAlign(Ty) / 8;
8372   if (TyAlign > 4) {
8373     assert((TyAlign & (TyAlign - 1)) == 0 && "Alignment is not power of 2!");
8374     llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int32Ty);
8375     AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt32(TyAlign - 1));
8376     AddrAsInt = Builder.CreateAnd(AddrAsInt, Builder.getInt32(~(TyAlign - 1)));
8377     Addr = Builder.CreateIntToPtr(AddrAsInt, BP);
8378   }
8379   llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
8380   Address AddrTyped = Builder.CreateBitCast(
8381       Address(Addr, CharUnits::fromQuantity(TyAlign)), PTy);
8382 
8383   uint64_t Offset = llvm::alignTo(CGF.getContext().getTypeSize(Ty) / 8, 4);
8384   llvm::Value *NextAddr = Builder.CreateGEP(
8385       Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset), "ap.next");
8386   Builder.CreateStore(NextAddr, VAListAddrAsBPP);
8387 
8388   return AddrTyped;
8389 }
8390 
8391 Address HexagonABIInfo::EmitVAArgForHexagonLinux(CodeGenFunction &CGF,
8392                                                  Address VAListAddr,
8393                                                  QualType Ty) const {
8394   int ArgSize = CGF.getContext().getTypeSize(Ty) / 8;
8395 
8396   if (ArgSize > 8)
8397     return EmitVAArgFromMemory(CGF, VAListAddr, Ty);
8398 
8399   // Here we have check if the argument is in register area or
8400   // in overflow area.
8401   // If the saved register area pointer + argsize rounded up to alignment >
8402   // saved register area end pointer, argument is in overflow area.
8403   unsigned RegsLeft = 6;
8404   Ty = CGF.getContext().getCanonicalType(Ty);
8405   (void)classifyArgumentType(Ty, &RegsLeft);
8406 
8407   llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
8408   llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
8409   llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
8410   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
8411 
8412   // Get rounded size of the argument.GCC does not allow vararg of
8413   // size < 4 bytes. We follow the same logic here.
8414   ArgSize = (CGF.getContext().getTypeSize(Ty) <= 32) ? 4 : 8;
8415   int ArgAlign = (CGF.getContext().getTypeSize(Ty) <= 32) ? 4 : 8;
8416 
8417   // Argument may be in saved register area
8418   CGF.EmitBlock(MaybeRegBlock);
8419 
8420   // Load the current saved register area pointer.
8421   Address __current_saved_reg_area_pointer_p = CGF.Builder.CreateStructGEP(
8422       VAListAddr, 0, "__current_saved_reg_area_pointer_p");
8423   llvm::Value *__current_saved_reg_area_pointer = CGF.Builder.CreateLoad(
8424       __current_saved_reg_area_pointer_p, "__current_saved_reg_area_pointer");
8425 
8426   // Load the saved register area end pointer.
8427   Address __saved_reg_area_end_pointer_p = CGF.Builder.CreateStructGEP(
8428       VAListAddr, 1, "__saved_reg_area_end_pointer_p");
8429   llvm::Value *__saved_reg_area_end_pointer = CGF.Builder.CreateLoad(
8430       __saved_reg_area_end_pointer_p, "__saved_reg_area_end_pointer");
8431 
8432   // If the size of argument is > 4 bytes, check if the stack
8433   // location is aligned to 8 bytes
8434   if (ArgAlign > 4) {
8435 
8436     llvm::Value *__current_saved_reg_area_pointer_int =
8437         CGF.Builder.CreatePtrToInt(__current_saved_reg_area_pointer,
8438                                    CGF.Int32Ty);
8439 
8440     __current_saved_reg_area_pointer_int = CGF.Builder.CreateAdd(
8441         __current_saved_reg_area_pointer_int,
8442         llvm::ConstantInt::get(CGF.Int32Ty, (ArgAlign - 1)),
8443         "align_current_saved_reg_area_pointer");
8444 
8445     __current_saved_reg_area_pointer_int =
8446         CGF.Builder.CreateAnd(__current_saved_reg_area_pointer_int,
8447                               llvm::ConstantInt::get(CGF.Int32Ty, -ArgAlign),
8448                               "align_current_saved_reg_area_pointer");
8449 
8450     __current_saved_reg_area_pointer =
8451         CGF.Builder.CreateIntToPtr(__current_saved_reg_area_pointer_int,
8452                                    __current_saved_reg_area_pointer->getType(),
8453                                    "align_current_saved_reg_area_pointer");
8454   }
8455 
8456   llvm::Value *__new_saved_reg_area_pointer =
8457       CGF.Builder.CreateGEP(__current_saved_reg_area_pointer,
8458                             llvm::ConstantInt::get(CGF.Int32Ty, ArgSize),
8459                             "__new_saved_reg_area_pointer");
8460 
8461   llvm::Value *UsingStack = 0;
8462   UsingStack = CGF.Builder.CreateICmpSGT(__new_saved_reg_area_pointer,
8463                                          __saved_reg_area_end_pointer);
8464 
8465   CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, InRegBlock);
8466 
8467   // Argument in saved register area
8468   // Implement the block where argument is in register saved area
8469   CGF.EmitBlock(InRegBlock);
8470 
8471   llvm::Type *PTy = CGF.ConvertType(Ty);
8472   llvm::Value *__saved_reg_area_p = CGF.Builder.CreateBitCast(
8473       __current_saved_reg_area_pointer, llvm::PointerType::getUnqual(PTy));
8474 
8475   CGF.Builder.CreateStore(__new_saved_reg_area_pointer,
8476                           __current_saved_reg_area_pointer_p);
8477 
8478   CGF.EmitBranch(ContBlock);
8479 
8480   // Argument in overflow area
8481   // Implement the block where the argument is in overflow area.
8482   CGF.EmitBlock(OnStackBlock);
8483 
8484   // Load the overflow area pointer
8485   Address __overflow_area_pointer_p =
8486       CGF.Builder.CreateStructGEP(VAListAddr, 2, "__overflow_area_pointer_p");
8487   llvm::Value *__overflow_area_pointer = CGF.Builder.CreateLoad(
8488       __overflow_area_pointer_p, "__overflow_area_pointer");
8489 
8490   // Align the overflow area pointer according to the alignment of the argument
8491   if (ArgAlign > 4) {
8492     llvm::Value *__overflow_area_pointer_int =
8493         CGF.Builder.CreatePtrToInt(__overflow_area_pointer, CGF.Int32Ty);
8494 
8495     __overflow_area_pointer_int =
8496         CGF.Builder.CreateAdd(__overflow_area_pointer_int,
8497                               llvm::ConstantInt::get(CGF.Int32Ty, ArgAlign - 1),
8498                               "align_overflow_area_pointer");
8499 
8500     __overflow_area_pointer_int =
8501         CGF.Builder.CreateAnd(__overflow_area_pointer_int,
8502                               llvm::ConstantInt::get(CGF.Int32Ty, -ArgAlign),
8503                               "align_overflow_area_pointer");
8504 
8505     __overflow_area_pointer = CGF.Builder.CreateIntToPtr(
8506         __overflow_area_pointer_int, __overflow_area_pointer->getType(),
8507         "align_overflow_area_pointer");
8508   }
8509 
8510   // Get the pointer for next argument in overflow area and store it
8511   // to overflow area pointer.
8512   llvm::Value *__new_overflow_area_pointer = CGF.Builder.CreateGEP(
8513       __overflow_area_pointer, llvm::ConstantInt::get(CGF.Int32Ty, ArgSize),
8514       "__overflow_area_pointer.next");
8515 
8516   CGF.Builder.CreateStore(__new_overflow_area_pointer,
8517                           __overflow_area_pointer_p);
8518 
8519   CGF.Builder.CreateStore(__new_overflow_area_pointer,
8520                           __current_saved_reg_area_pointer_p);
8521 
8522   // Bitcast the overflow area pointer to the type of argument.
8523   llvm::Type *OverflowPTy = CGF.ConvertTypeForMem(Ty);
8524   llvm::Value *__overflow_area_p = CGF.Builder.CreateBitCast(
8525       __overflow_area_pointer, llvm::PointerType::getUnqual(OverflowPTy));
8526 
8527   CGF.EmitBranch(ContBlock);
8528 
8529   // Get the correct pointer to load the variable argument
8530   // Implement the ContBlock
8531   CGF.EmitBlock(ContBlock);
8532 
8533   llvm::Type *MemPTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
8534   llvm::PHINode *ArgAddr = CGF.Builder.CreatePHI(MemPTy, 2, "vaarg.addr");
8535   ArgAddr->addIncoming(__saved_reg_area_p, InRegBlock);
8536   ArgAddr->addIncoming(__overflow_area_p, OnStackBlock);
8537 
8538   return Address(ArgAddr, CharUnits::fromQuantity(ArgAlign));
8539 }
8540 
8541 Address HexagonABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8542                                   QualType Ty) const {
8543 
8544   if (getTarget().getTriple().isMusl())
8545     return EmitVAArgForHexagonLinux(CGF, VAListAddr, Ty);
8546 
8547   return EmitVAArgForHexagon(CGF, VAListAddr, Ty);
8548 }
8549 
8550 //===----------------------------------------------------------------------===//
8551 // Lanai ABI Implementation
8552 //===----------------------------------------------------------------------===//
8553 
8554 namespace {
8555 class LanaiABIInfo : public DefaultABIInfo {
8556 public:
8557   LanaiABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
8558 
8559   bool shouldUseInReg(QualType Ty, CCState &State) const;
8560 
8561   void computeInfo(CGFunctionInfo &FI) const override {
8562     CCState State(FI);
8563     // Lanai uses 4 registers to pass arguments unless the function has the
8564     // regparm attribute set.
8565     if (FI.getHasRegParm()) {
8566       State.FreeRegs = FI.getRegParm();
8567     } else {
8568       State.FreeRegs = 4;
8569     }
8570 
8571     if (!getCXXABI().classifyReturnType(FI))
8572       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
8573     for (auto &I : FI.arguments())
8574       I.info = classifyArgumentType(I.type, State);
8575   }
8576 
8577   ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
8578   ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
8579 };
8580 } // end anonymous namespace
8581 
8582 bool LanaiABIInfo::shouldUseInReg(QualType Ty, CCState &State) const {
8583   unsigned Size = getContext().getTypeSize(Ty);
8584   unsigned SizeInRegs = llvm::alignTo(Size, 32U) / 32U;
8585 
8586   if (SizeInRegs == 0)
8587     return false;
8588 
8589   if (SizeInRegs > State.FreeRegs) {
8590     State.FreeRegs = 0;
8591     return false;
8592   }
8593 
8594   State.FreeRegs -= SizeInRegs;
8595 
8596   return true;
8597 }
8598 
8599 ABIArgInfo LanaiABIInfo::getIndirectResult(QualType Ty, bool ByVal,
8600                                            CCState &State) const {
8601   if (!ByVal) {
8602     if (State.FreeRegs) {
8603       --State.FreeRegs; // Non-byval indirects just use one pointer.
8604       return getNaturalAlignIndirectInReg(Ty);
8605     }
8606     return getNaturalAlignIndirect(Ty, false);
8607   }
8608 
8609   // Compute the byval alignment.
8610   const unsigned MinABIStackAlignInBytes = 4;
8611   unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
8612   return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true,
8613                                  /*Realign=*/TypeAlign >
8614                                      MinABIStackAlignInBytes);
8615 }
8616 
8617 ABIArgInfo LanaiABIInfo::classifyArgumentType(QualType Ty,
8618                                               CCState &State) const {
8619   // Check with the C++ ABI first.
8620   const RecordType *RT = Ty->getAs<RecordType>();
8621   if (RT) {
8622     CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
8623     if (RAA == CGCXXABI::RAA_Indirect) {
8624       return getIndirectResult(Ty, /*ByVal=*/false, State);
8625     } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
8626       return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
8627     }
8628   }
8629 
8630   if (isAggregateTypeForABI(Ty)) {
8631     // Structures with flexible arrays are always indirect.
8632     if (RT && RT->getDecl()->hasFlexibleArrayMember())
8633       return getIndirectResult(Ty, /*ByVal=*/true, State);
8634 
8635     // Ignore empty structs/unions.
8636     if (isEmptyRecord(getContext(), Ty, true))
8637       return ABIArgInfo::getIgnore();
8638 
8639     llvm::LLVMContext &LLVMContext = getVMContext();
8640     unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
8641     if (SizeInRegs <= State.FreeRegs) {
8642       llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
8643       SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32);
8644       llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
8645       State.FreeRegs -= SizeInRegs;
8646       return ABIArgInfo::getDirectInReg(Result);
8647     } else {
8648       State.FreeRegs = 0;
8649     }
8650     return getIndirectResult(Ty, true, State);
8651   }
8652 
8653   // Treat an enum type as its underlying type.
8654   if (const auto *EnumTy = Ty->getAs<EnumType>())
8655     Ty = EnumTy->getDecl()->getIntegerType();
8656 
8657   bool InReg = shouldUseInReg(Ty, State);
8658 
8659   // Don't pass >64 bit integers in registers.
8660   if (const auto *EIT = Ty->getAs<ExtIntType>())
8661     if (EIT->getNumBits() > 64)
8662       return getIndirectResult(Ty, /*ByVal=*/true, State);
8663 
8664   if (isPromotableIntegerTypeForABI(Ty)) {
8665     if (InReg)
8666       return ABIArgInfo::getDirectInReg();
8667     return ABIArgInfo::getExtend(Ty);
8668   }
8669   if (InReg)
8670     return ABIArgInfo::getDirectInReg();
8671   return ABIArgInfo::getDirect();
8672 }
8673 
8674 namespace {
8675 class LanaiTargetCodeGenInfo : public TargetCodeGenInfo {
8676 public:
8677   LanaiTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
8678       : TargetCodeGenInfo(std::make_unique<LanaiABIInfo>(CGT)) {}
8679 };
8680 }
8681 
8682 //===----------------------------------------------------------------------===//
8683 // AMDGPU ABI Implementation
8684 //===----------------------------------------------------------------------===//
8685 
8686 namespace {
8687 
8688 class AMDGPUABIInfo final : public DefaultABIInfo {
8689 private:
8690   static const unsigned MaxNumRegsForArgsRet = 16;
8691 
8692   unsigned numRegsForType(QualType Ty) const;
8693 
8694   bool isHomogeneousAggregateBaseType(QualType Ty) const override;
8695   bool isHomogeneousAggregateSmallEnough(const Type *Base,
8696                                          uint64_t Members) const override;
8697 
8698   // Coerce HIP scalar pointer arguments from generic pointers to global ones.
8699   llvm::Type *coerceKernelArgumentType(llvm::Type *Ty, unsigned FromAS,
8700                                        unsigned ToAS) const {
8701     // Single value types.
8702     if (Ty->isPointerTy() && Ty->getPointerAddressSpace() == FromAS)
8703       return llvm::PointerType::get(
8704           cast<llvm::PointerType>(Ty)->getElementType(), ToAS);
8705     return Ty;
8706   }
8707 
8708 public:
8709   explicit AMDGPUABIInfo(CodeGen::CodeGenTypes &CGT) :
8710     DefaultABIInfo(CGT) {}
8711 
8712   ABIArgInfo classifyReturnType(QualType RetTy) const;
8713   ABIArgInfo classifyKernelArgumentType(QualType Ty) const;
8714   ABIArgInfo classifyArgumentType(QualType Ty, unsigned &NumRegsLeft) const;
8715 
8716   void computeInfo(CGFunctionInfo &FI) const override;
8717   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8718                     QualType Ty) const override;
8719 };
8720 
8721 bool AMDGPUABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
8722   return true;
8723 }
8724 
8725 bool AMDGPUABIInfo::isHomogeneousAggregateSmallEnough(
8726   const Type *Base, uint64_t Members) const {
8727   uint32_t NumRegs = (getContext().getTypeSize(Base) + 31) / 32;
8728 
8729   // Homogeneous Aggregates may occupy at most 16 registers.
8730   return Members * NumRegs <= MaxNumRegsForArgsRet;
8731 }
8732 
8733 /// Estimate number of registers the type will use when passed in registers.
8734 unsigned AMDGPUABIInfo::numRegsForType(QualType Ty) const {
8735   unsigned NumRegs = 0;
8736 
8737   if (const VectorType *VT = Ty->getAs<VectorType>()) {
8738     // Compute from the number of elements. The reported size is based on the
8739     // in-memory size, which includes the padding 4th element for 3-vectors.
8740     QualType EltTy = VT->getElementType();
8741     unsigned EltSize = getContext().getTypeSize(EltTy);
8742 
8743     // 16-bit element vectors should be passed as packed.
8744     if (EltSize == 16)
8745       return (VT->getNumElements() + 1) / 2;
8746 
8747     unsigned EltNumRegs = (EltSize + 31) / 32;
8748     return EltNumRegs * VT->getNumElements();
8749   }
8750 
8751   if (const RecordType *RT = Ty->getAs<RecordType>()) {
8752     const RecordDecl *RD = RT->getDecl();
8753     assert(!RD->hasFlexibleArrayMember());
8754 
8755     for (const FieldDecl *Field : RD->fields()) {
8756       QualType FieldTy = Field->getType();
8757       NumRegs += numRegsForType(FieldTy);
8758     }
8759 
8760     return NumRegs;
8761   }
8762 
8763   return (getContext().getTypeSize(Ty) + 31) / 32;
8764 }
8765 
8766 void AMDGPUABIInfo::computeInfo(CGFunctionInfo &FI) const {
8767   llvm::CallingConv::ID CC = FI.getCallingConvention();
8768 
8769   if (!getCXXABI().classifyReturnType(FI))
8770     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
8771 
8772   unsigned NumRegsLeft = MaxNumRegsForArgsRet;
8773   for (auto &Arg : FI.arguments()) {
8774     if (CC == llvm::CallingConv::AMDGPU_KERNEL) {
8775       Arg.info = classifyKernelArgumentType(Arg.type);
8776     } else {
8777       Arg.info = classifyArgumentType(Arg.type, NumRegsLeft);
8778     }
8779   }
8780 }
8781 
8782 Address AMDGPUABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8783                                  QualType Ty) const {
8784   llvm_unreachable("AMDGPU does not support varargs");
8785 }
8786 
8787 ABIArgInfo AMDGPUABIInfo::classifyReturnType(QualType RetTy) const {
8788   if (isAggregateTypeForABI(RetTy)) {
8789     // Records with non-trivial destructors/copy-constructors should not be
8790     // returned by value.
8791     if (!getRecordArgABI(RetTy, getCXXABI())) {
8792       // Ignore empty structs/unions.
8793       if (isEmptyRecord(getContext(), RetTy, true))
8794         return ABIArgInfo::getIgnore();
8795 
8796       // Lower single-element structs to just return a regular value.
8797       if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
8798         return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
8799 
8800       if (const RecordType *RT = RetTy->getAs<RecordType>()) {
8801         const RecordDecl *RD = RT->getDecl();
8802         if (RD->hasFlexibleArrayMember())
8803           return DefaultABIInfo::classifyReturnType(RetTy);
8804       }
8805 
8806       // Pack aggregates <= 4 bytes into single VGPR or pair.
8807       uint64_t Size = getContext().getTypeSize(RetTy);
8808       if (Size <= 16)
8809         return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
8810 
8811       if (Size <= 32)
8812         return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
8813 
8814       if (Size <= 64) {
8815         llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext());
8816         return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2));
8817       }
8818 
8819       if (numRegsForType(RetTy) <= MaxNumRegsForArgsRet)
8820         return ABIArgInfo::getDirect();
8821     }
8822   }
8823 
8824   // Otherwise just do the default thing.
8825   return DefaultABIInfo::classifyReturnType(RetTy);
8826 }
8827 
8828 /// For kernels all parameters are really passed in a special buffer. It doesn't
8829 /// make sense to pass anything byval, so everything must be direct.
8830 ABIArgInfo AMDGPUABIInfo::classifyKernelArgumentType(QualType Ty) const {
8831   Ty = useFirstFieldIfTransparentUnion(Ty);
8832 
8833   // TODO: Can we omit empty structs?
8834 
8835   if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
8836     Ty = QualType(SeltTy, 0);
8837 
8838   llvm::Type *OrigLTy = CGT.ConvertType(Ty);
8839   llvm::Type *LTy = OrigLTy;
8840   if (getContext().getLangOpts().HIP) {
8841     LTy = coerceKernelArgumentType(
8842         OrigLTy, /*FromAS=*/getContext().getTargetAddressSpace(LangAS::Default),
8843         /*ToAS=*/getContext().getTargetAddressSpace(LangAS::cuda_device));
8844   }
8845 
8846   // FIXME: Should also use this for OpenCL, but it requires addressing the
8847   // problem of kernels being called.
8848   //
8849   // FIXME: This doesn't apply the optimization of coercing pointers in structs
8850   // to global address space when using byref. This would require implementing a
8851   // new kind of coercion of the in-memory type when for indirect arguments.
8852   if (!getContext().getLangOpts().OpenCL && LTy == OrigLTy &&
8853       isAggregateTypeForABI(Ty)) {
8854     return ABIArgInfo::getIndirectAliased(
8855         getContext().getTypeAlignInChars(Ty),
8856         getContext().getTargetAddressSpace(LangAS::opencl_constant),
8857         false /*Realign*/, nullptr /*Padding*/);
8858   }
8859 
8860   // If we set CanBeFlattened to true, CodeGen will expand the struct to its
8861   // individual elements, which confuses the Clover OpenCL backend; therefore we
8862   // have to set it to false here. Other args of getDirect() are just defaults.
8863   return ABIArgInfo::getDirect(LTy, 0, nullptr, false);
8864 }
8865 
8866 ABIArgInfo AMDGPUABIInfo::classifyArgumentType(QualType Ty,
8867                                                unsigned &NumRegsLeft) const {
8868   assert(NumRegsLeft <= MaxNumRegsForArgsRet && "register estimate underflow");
8869 
8870   Ty = useFirstFieldIfTransparentUnion(Ty);
8871 
8872   if (isAggregateTypeForABI(Ty)) {
8873     // Records with non-trivial destructors/copy-constructors should not be
8874     // passed by value.
8875     if (auto RAA = getRecordArgABI(Ty, getCXXABI()))
8876       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
8877 
8878     // Ignore empty structs/unions.
8879     if (isEmptyRecord(getContext(), Ty, true))
8880       return ABIArgInfo::getIgnore();
8881 
8882     // Lower single-element structs to just pass a regular value. TODO: We
8883     // could do reasonable-size multiple-element structs too, using getExpand(),
8884     // though watch out for things like bitfields.
8885     if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
8886       return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
8887 
8888     if (const RecordType *RT = Ty->getAs<RecordType>()) {
8889       const RecordDecl *RD = RT->getDecl();
8890       if (RD->hasFlexibleArrayMember())
8891         return DefaultABIInfo::classifyArgumentType(Ty);
8892     }
8893 
8894     // Pack aggregates <= 8 bytes into single VGPR or pair.
8895     uint64_t Size = getContext().getTypeSize(Ty);
8896     if (Size <= 64) {
8897       unsigned NumRegs = (Size + 31) / 32;
8898       NumRegsLeft -= std::min(NumRegsLeft, NumRegs);
8899 
8900       if (Size <= 16)
8901         return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
8902 
8903       if (Size <= 32)
8904         return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
8905 
8906       // XXX: Should this be i64 instead, and should the limit increase?
8907       llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext());
8908       return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2));
8909     }
8910 
8911     if (NumRegsLeft > 0) {
8912       unsigned NumRegs = numRegsForType(Ty);
8913       if (NumRegsLeft >= NumRegs) {
8914         NumRegsLeft -= NumRegs;
8915         return ABIArgInfo::getDirect();
8916       }
8917     }
8918   }
8919 
8920   // Otherwise just do the default thing.
8921   ABIArgInfo ArgInfo = DefaultABIInfo::classifyArgumentType(Ty);
8922   if (!ArgInfo.isIndirect()) {
8923     unsigned NumRegs = numRegsForType(Ty);
8924     NumRegsLeft -= std::min(NumRegs, NumRegsLeft);
8925   }
8926 
8927   return ArgInfo;
8928 }
8929 
8930 class AMDGPUTargetCodeGenInfo : public TargetCodeGenInfo {
8931 public:
8932   AMDGPUTargetCodeGenInfo(CodeGenTypes &CGT)
8933       : TargetCodeGenInfo(std::make_unique<AMDGPUABIInfo>(CGT)) {}
8934   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
8935                            CodeGen::CodeGenModule &M) const override;
8936   unsigned getOpenCLKernelCallingConv() const override;
8937 
8938   llvm::Constant *getNullPointer(const CodeGen::CodeGenModule &CGM,
8939       llvm::PointerType *T, QualType QT) const override;
8940 
8941   LangAS getASTAllocaAddressSpace() const override {
8942     return getLangASFromTargetAS(
8943         getABIInfo().getDataLayout().getAllocaAddrSpace());
8944   }
8945   LangAS getGlobalVarAddressSpace(CodeGenModule &CGM,
8946                                   const VarDecl *D) const override;
8947   llvm::SyncScope::ID getLLVMSyncScopeID(const LangOptions &LangOpts,
8948                                          SyncScope Scope,
8949                                          llvm::AtomicOrdering Ordering,
8950                                          llvm::LLVMContext &Ctx) const override;
8951   llvm::Function *
8952   createEnqueuedBlockKernel(CodeGenFunction &CGF,
8953                             llvm::Function *BlockInvokeFunc,
8954                             llvm::Value *BlockLiteral) const override;
8955   bool shouldEmitStaticExternCAliases() const override;
8956   void setCUDAKernelCallingConvention(const FunctionType *&FT) const override;
8957 };
8958 }
8959 
8960 static bool requiresAMDGPUProtectedVisibility(const Decl *D,
8961                                               llvm::GlobalValue *GV) {
8962   if (GV->getVisibility() != llvm::GlobalValue::HiddenVisibility)
8963     return false;
8964 
8965   return D->hasAttr<OpenCLKernelAttr>() ||
8966          (isa<FunctionDecl>(D) && D->hasAttr<CUDAGlobalAttr>()) ||
8967          (isa<VarDecl>(D) &&
8968           (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>() ||
8969            cast<VarDecl>(D)->getType()->isCUDADeviceBuiltinSurfaceType() ||
8970            cast<VarDecl>(D)->getType()->isCUDADeviceBuiltinTextureType()));
8971 }
8972 
8973 void AMDGPUTargetCodeGenInfo::setTargetAttributes(
8974     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
8975   if (requiresAMDGPUProtectedVisibility(D, GV)) {
8976     GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
8977     GV->setDSOLocal(true);
8978   }
8979 
8980   if (GV->isDeclaration())
8981     return;
8982   const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
8983   if (!FD)
8984     return;
8985 
8986   llvm::Function *F = cast<llvm::Function>(GV);
8987 
8988   const auto *ReqdWGS = M.getLangOpts().OpenCL ?
8989     FD->getAttr<ReqdWorkGroupSizeAttr>() : nullptr;
8990 
8991 
8992   const bool IsOpenCLKernel = M.getLangOpts().OpenCL &&
8993                               FD->hasAttr<OpenCLKernelAttr>();
8994   const bool IsHIPKernel = M.getLangOpts().HIP &&
8995                            FD->hasAttr<CUDAGlobalAttr>();
8996   if ((IsOpenCLKernel || IsHIPKernel) &&
8997       (M.getTriple().getOS() == llvm::Triple::AMDHSA))
8998     F->addFnAttr("amdgpu-implicitarg-num-bytes", "56");
8999 
9000   if (IsHIPKernel)
9001     F->addFnAttr("uniform-work-group-size", "true");
9002 
9003 
9004   const auto *FlatWGS = FD->getAttr<AMDGPUFlatWorkGroupSizeAttr>();
9005   if (ReqdWGS || FlatWGS) {
9006     unsigned Min = 0;
9007     unsigned Max = 0;
9008     if (FlatWGS) {
9009       Min = FlatWGS->getMin()
9010                 ->EvaluateKnownConstInt(M.getContext())
9011                 .getExtValue();
9012       Max = FlatWGS->getMax()
9013                 ->EvaluateKnownConstInt(M.getContext())
9014                 .getExtValue();
9015     }
9016     if (ReqdWGS && Min == 0 && Max == 0)
9017       Min = Max = ReqdWGS->getXDim() * ReqdWGS->getYDim() * ReqdWGS->getZDim();
9018 
9019     if (Min != 0) {
9020       assert(Min <= Max && "Min must be less than or equal Max");
9021 
9022       std::string AttrVal = llvm::utostr(Min) + "," + llvm::utostr(Max);
9023       F->addFnAttr("amdgpu-flat-work-group-size", AttrVal);
9024     } else
9025       assert(Max == 0 && "Max must be zero");
9026   } else if (IsOpenCLKernel || IsHIPKernel) {
9027     // By default, restrict the maximum size to a value specified by
9028     // --gpu-max-threads-per-block=n or its default value for HIP.
9029     const unsigned OpenCLDefaultMaxWorkGroupSize = 256;
9030     const unsigned DefaultMaxWorkGroupSize =
9031         IsOpenCLKernel ? OpenCLDefaultMaxWorkGroupSize
9032                        : M.getLangOpts().GPUMaxThreadsPerBlock;
9033     std::string AttrVal =
9034         std::string("1,") + llvm::utostr(DefaultMaxWorkGroupSize);
9035     F->addFnAttr("amdgpu-flat-work-group-size", AttrVal);
9036   }
9037 
9038   if (const auto *Attr = FD->getAttr<AMDGPUWavesPerEUAttr>()) {
9039     unsigned Min =
9040         Attr->getMin()->EvaluateKnownConstInt(M.getContext()).getExtValue();
9041     unsigned Max = Attr->getMax() ? Attr->getMax()
9042                                         ->EvaluateKnownConstInt(M.getContext())
9043                                         .getExtValue()
9044                                   : 0;
9045 
9046     if (Min != 0) {
9047       assert((Max == 0 || Min <= Max) && "Min must be less than or equal Max");
9048 
9049       std::string AttrVal = llvm::utostr(Min);
9050       if (Max != 0)
9051         AttrVal = AttrVal + "," + llvm::utostr(Max);
9052       F->addFnAttr("amdgpu-waves-per-eu", AttrVal);
9053     } else
9054       assert(Max == 0 && "Max must be zero");
9055   }
9056 
9057   if (const auto *Attr = FD->getAttr<AMDGPUNumSGPRAttr>()) {
9058     unsigned NumSGPR = Attr->getNumSGPR();
9059 
9060     if (NumSGPR != 0)
9061       F->addFnAttr("amdgpu-num-sgpr", llvm::utostr(NumSGPR));
9062   }
9063 
9064   if (const auto *Attr = FD->getAttr<AMDGPUNumVGPRAttr>()) {
9065     uint32_t NumVGPR = Attr->getNumVGPR();
9066 
9067     if (NumVGPR != 0)
9068       F->addFnAttr("amdgpu-num-vgpr", llvm::utostr(NumVGPR));
9069   }
9070 
9071   if (M.getContext().getTargetInfo().allowAMDGPUUnsafeFPAtomics())
9072     F->addFnAttr("amdgpu-unsafe-fp-atomics", "true");
9073 }
9074 
9075 unsigned AMDGPUTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
9076   return llvm::CallingConv::AMDGPU_KERNEL;
9077 }
9078 
9079 // Currently LLVM assumes null pointers always have value 0,
9080 // which results in incorrectly transformed IR. Therefore, instead of
9081 // emitting null pointers in private and local address spaces, a null
9082 // pointer in generic address space is emitted which is casted to a
9083 // pointer in local or private address space.
9084 llvm::Constant *AMDGPUTargetCodeGenInfo::getNullPointer(
9085     const CodeGen::CodeGenModule &CGM, llvm::PointerType *PT,
9086     QualType QT) const {
9087   if (CGM.getContext().getTargetNullPointerValue(QT) == 0)
9088     return llvm::ConstantPointerNull::get(PT);
9089 
9090   auto &Ctx = CGM.getContext();
9091   auto NPT = llvm::PointerType::get(PT->getElementType(),
9092       Ctx.getTargetAddressSpace(LangAS::opencl_generic));
9093   return llvm::ConstantExpr::getAddrSpaceCast(
9094       llvm::ConstantPointerNull::get(NPT), PT);
9095 }
9096 
9097 LangAS
9098 AMDGPUTargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM,
9099                                                   const VarDecl *D) const {
9100   assert(!CGM.getLangOpts().OpenCL &&
9101          !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) &&
9102          "Address space agnostic languages only");
9103   LangAS DefaultGlobalAS = getLangASFromTargetAS(
9104       CGM.getContext().getTargetAddressSpace(LangAS::opencl_global));
9105   if (!D)
9106     return DefaultGlobalAS;
9107 
9108   LangAS AddrSpace = D->getType().getAddressSpace();
9109   assert(AddrSpace == LangAS::Default || isTargetAddressSpace(AddrSpace));
9110   if (AddrSpace != LangAS::Default)
9111     return AddrSpace;
9112 
9113   if (CGM.isTypeConstant(D->getType(), false)) {
9114     if (auto ConstAS = CGM.getTarget().getConstantAddressSpace())
9115       return ConstAS.getValue();
9116   }
9117   return DefaultGlobalAS;
9118 }
9119 
9120 llvm::SyncScope::ID
9121 AMDGPUTargetCodeGenInfo::getLLVMSyncScopeID(const LangOptions &LangOpts,
9122                                             SyncScope Scope,
9123                                             llvm::AtomicOrdering Ordering,
9124                                             llvm::LLVMContext &Ctx) const {
9125   std::string Name;
9126   switch (Scope) {
9127   case SyncScope::OpenCLWorkGroup:
9128     Name = "workgroup";
9129     break;
9130   case SyncScope::OpenCLDevice:
9131     Name = "agent";
9132     break;
9133   case SyncScope::OpenCLAllSVMDevices:
9134     Name = "";
9135     break;
9136   case SyncScope::OpenCLSubGroup:
9137     Name = "wavefront";
9138   }
9139 
9140   if (Ordering != llvm::AtomicOrdering::SequentiallyConsistent) {
9141     if (!Name.empty())
9142       Name = Twine(Twine(Name) + Twine("-")).str();
9143 
9144     Name = Twine(Twine(Name) + Twine("one-as")).str();
9145   }
9146 
9147   return Ctx.getOrInsertSyncScopeID(Name);
9148 }
9149 
9150 bool AMDGPUTargetCodeGenInfo::shouldEmitStaticExternCAliases() const {
9151   return false;
9152 }
9153 
9154 void AMDGPUTargetCodeGenInfo::setCUDAKernelCallingConvention(
9155     const FunctionType *&FT) const {
9156   FT = getABIInfo().getContext().adjustFunctionType(
9157       FT, FT->getExtInfo().withCallingConv(CC_OpenCLKernel));
9158 }
9159 
9160 //===----------------------------------------------------------------------===//
9161 // SPARC v8 ABI Implementation.
9162 // Based on the SPARC Compliance Definition version 2.4.1.
9163 //
9164 // Ensures that complex values are passed in registers.
9165 //
9166 namespace {
9167 class SparcV8ABIInfo : public DefaultABIInfo {
9168 public:
9169   SparcV8ABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
9170 
9171 private:
9172   ABIArgInfo classifyReturnType(QualType RetTy) const;
9173   void computeInfo(CGFunctionInfo &FI) const override;
9174 };
9175 } // end anonymous namespace
9176 
9177 
9178 ABIArgInfo
9179 SparcV8ABIInfo::classifyReturnType(QualType Ty) const {
9180   if (Ty->isAnyComplexType()) {
9181     return ABIArgInfo::getDirect();
9182   }
9183   else {
9184     return DefaultABIInfo::classifyReturnType(Ty);
9185   }
9186 }
9187 
9188 void SparcV8ABIInfo::computeInfo(CGFunctionInfo &FI) const {
9189 
9190   FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
9191   for (auto &Arg : FI.arguments())
9192     Arg.info = classifyArgumentType(Arg.type);
9193 }
9194 
9195 namespace {
9196 class SparcV8TargetCodeGenInfo : public TargetCodeGenInfo {
9197 public:
9198   SparcV8TargetCodeGenInfo(CodeGenTypes &CGT)
9199       : TargetCodeGenInfo(std::make_unique<SparcV8ABIInfo>(CGT)) {}
9200 };
9201 } // end anonymous namespace
9202 
9203 //===----------------------------------------------------------------------===//
9204 // SPARC v9 ABI Implementation.
9205 // Based on the SPARC Compliance Definition version 2.4.1.
9206 //
9207 // Function arguments a mapped to a nominal "parameter array" and promoted to
9208 // registers depending on their type. Each argument occupies 8 or 16 bytes in
9209 // the array, structs larger than 16 bytes are passed indirectly.
9210 //
9211 // One case requires special care:
9212 //
9213 //   struct mixed {
9214 //     int i;
9215 //     float f;
9216 //   };
9217 //
9218 // When a struct mixed is passed by value, it only occupies 8 bytes in the
9219 // parameter array, but the int is passed in an integer register, and the float
9220 // is passed in a floating point register. This is represented as two arguments
9221 // with the LLVM IR inreg attribute:
9222 //
9223 //   declare void f(i32 inreg %i, float inreg %f)
9224 //
9225 // The code generator will only allocate 4 bytes from the parameter array for
9226 // the inreg arguments. All other arguments are allocated a multiple of 8
9227 // bytes.
9228 //
9229 namespace {
9230 class SparcV9ABIInfo : public ABIInfo {
9231 public:
9232   SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
9233 
9234 private:
9235   ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
9236   void computeInfo(CGFunctionInfo &FI) const override;
9237   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9238                     QualType Ty) const override;
9239 
9240   // Coercion type builder for structs passed in registers. The coercion type
9241   // serves two purposes:
9242   //
9243   // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
9244   //    in registers.
9245   // 2. Expose aligned floating point elements as first-level elements, so the
9246   //    code generator knows to pass them in floating point registers.
9247   //
9248   // We also compute the InReg flag which indicates that the struct contains
9249   // aligned 32-bit floats.
9250   //
9251   struct CoerceBuilder {
9252     llvm::LLVMContext &Context;
9253     const llvm::DataLayout &DL;
9254     SmallVector<llvm::Type*, 8> Elems;
9255     uint64_t Size;
9256     bool InReg;
9257 
9258     CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
9259       : Context(c), DL(dl), Size(0), InReg(false) {}
9260 
9261     // Pad Elems with integers until Size is ToSize.
9262     void pad(uint64_t ToSize) {
9263       assert(ToSize >= Size && "Cannot remove elements");
9264       if (ToSize == Size)
9265         return;
9266 
9267       // Finish the current 64-bit word.
9268       uint64_t Aligned = llvm::alignTo(Size, 64);
9269       if (Aligned > Size && Aligned <= ToSize) {
9270         Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
9271         Size = Aligned;
9272       }
9273 
9274       // Add whole 64-bit words.
9275       while (Size + 64 <= ToSize) {
9276         Elems.push_back(llvm::Type::getInt64Ty(Context));
9277         Size += 64;
9278       }
9279 
9280       // Final in-word padding.
9281       if (Size < ToSize) {
9282         Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
9283         Size = ToSize;
9284       }
9285     }
9286 
9287     // Add a floating point element at Offset.
9288     void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
9289       // Unaligned floats are treated as integers.
9290       if (Offset % Bits)
9291         return;
9292       // The InReg flag is only required if there are any floats < 64 bits.
9293       if (Bits < 64)
9294         InReg = true;
9295       pad(Offset);
9296       Elems.push_back(Ty);
9297       Size = Offset + Bits;
9298     }
9299 
9300     // Add a struct type to the coercion type, starting at Offset (in bits).
9301     void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
9302       const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
9303       for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
9304         llvm::Type *ElemTy = StrTy->getElementType(i);
9305         uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
9306         switch (ElemTy->getTypeID()) {
9307         case llvm::Type::StructTyID:
9308           addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
9309           break;
9310         case llvm::Type::FloatTyID:
9311           addFloat(ElemOffset, ElemTy, 32);
9312           break;
9313         case llvm::Type::DoubleTyID:
9314           addFloat(ElemOffset, ElemTy, 64);
9315           break;
9316         case llvm::Type::FP128TyID:
9317           addFloat(ElemOffset, ElemTy, 128);
9318           break;
9319         case llvm::Type::PointerTyID:
9320           if (ElemOffset % 64 == 0) {
9321             pad(ElemOffset);
9322             Elems.push_back(ElemTy);
9323             Size += 64;
9324           }
9325           break;
9326         default:
9327           break;
9328         }
9329       }
9330     }
9331 
9332     // Check if Ty is a usable substitute for the coercion type.
9333     bool isUsableType(llvm::StructType *Ty) const {
9334       return llvm::makeArrayRef(Elems) == Ty->elements();
9335     }
9336 
9337     // Get the coercion type as a literal struct type.
9338     llvm::Type *getType() const {
9339       if (Elems.size() == 1)
9340         return Elems.front();
9341       else
9342         return llvm::StructType::get(Context, Elems);
9343     }
9344   };
9345 };
9346 } // end anonymous namespace
9347 
9348 ABIArgInfo
9349 SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
9350   if (Ty->isVoidType())
9351     return ABIArgInfo::getIgnore();
9352 
9353   uint64_t Size = getContext().getTypeSize(Ty);
9354 
9355   // Anything too big to fit in registers is passed with an explicit indirect
9356   // pointer / sret pointer.
9357   if (Size > SizeLimit)
9358     return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
9359 
9360   // Treat an enum type as its underlying type.
9361   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
9362     Ty = EnumTy->getDecl()->getIntegerType();
9363 
9364   // Integer types smaller than a register are extended.
9365   if (Size < 64 && Ty->isIntegerType())
9366     return ABIArgInfo::getExtend(Ty);
9367 
9368   if (const auto *EIT = Ty->getAs<ExtIntType>())
9369     if (EIT->getNumBits() < 64)
9370       return ABIArgInfo::getExtend(Ty);
9371 
9372   // Other non-aggregates go in registers.
9373   if (!isAggregateTypeForABI(Ty))
9374     return ABIArgInfo::getDirect();
9375 
9376   // If a C++ object has either a non-trivial copy constructor or a non-trivial
9377   // destructor, it is passed with an explicit indirect pointer / sret pointer.
9378   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
9379     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
9380 
9381   // This is a small aggregate type that should be passed in registers.
9382   // Build a coercion type from the LLVM struct type.
9383   llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
9384   if (!StrTy)
9385     return ABIArgInfo::getDirect();
9386 
9387   CoerceBuilder CB(getVMContext(), getDataLayout());
9388   CB.addStruct(0, StrTy);
9389   CB.pad(llvm::alignTo(CB.DL.getTypeSizeInBits(StrTy), 64));
9390 
9391   // Try to use the original type for coercion.
9392   llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
9393 
9394   if (CB.InReg)
9395     return ABIArgInfo::getDirectInReg(CoerceTy);
9396   else
9397     return ABIArgInfo::getDirect(CoerceTy);
9398 }
9399 
9400 Address SparcV9ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9401                                   QualType Ty) const {
9402   ABIArgInfo AI = classifyType(Ty, 16 * 8);
9403   llvm::Type *ArgTy = CGT.ConvertType(Ty);
9404   if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
9405     AI.setCoerceToType(ArgTy);
9406 
9407   CharUnits SlotSize = CharUnits::fromQuantity(8);
9408 
9409   CGBuilderTy &Builder = CGF.Builder;
9410   Address Addr(Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
9411   llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
9412 
9413   auto TypeInfo = getContext().getTypeInfoInChars(Ty);
9414 
9415   Address ArgAddr = Address::invalid();
9416   CharUnits Stride;
9417   switch (AI.getKind()) {
9418   case ABIArgInfo::Expand:
9419   case ABIArgInfo::CoerceAndExpand:
9420   case ABIArgInfo::InAlloca:
9421     llvm_unreachable("Unsupported ABI kind for va_arg");
9422 
9423   case ABIArgInfo::Extend: {
9424     Stride = SlotSize;
9425     CharUnits Offset = SlotSize - TypeInfo.Width;
9426     ArgAddr = Builder.CreateConstInBoundsByteGEP(Addr, Offset, "extend");
9427     break;
9428   }
9429 
9430   case ABIArgInfo::Direct: {
9431     auto AllocSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
9432     Stride = CharUnits::fromQuantity(AllocSize).alignTo(SlotSize);
9433     ArgAddr = Addr;
9434     break;
9435   }
9436 
9437   case ABIArgInfo::Indirect:
9438   case ABIArgInfo::IndirectAliased:
9439     Stride = SlotSize;
9440     ArgAddr = Builder.CreateElementBitCast(Addr, ArgPtrTy, "indirect");
9441     ArgAddr = Address(Builder.CreateLoad(ArgAddr, "indirect.arg"),
9442                       TypeInfo.Align);
9443     break;
9444 
9445   case ABIArgInfo::Ignore:
9446     return Address(llvm::UndefValue::get(ArgPtrTy), TypeInfo.Align);
9447   }
9448 
9449   // Update VAList.
9450   Address NextPtr = Builder.CreateConstInBoundsByteGEP(Addr, Stride, "ap.next");
9451   Builder.CreateStore(NextPtr.getPointer(), VAListAddr);
9452 
9453   return Builder.CreateBitCast(ArgAddr, ArgPtrTy, "arg.addr");
9454 }
9455 
9456 void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
9457   FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
9458   for (auto &I : FI.arguments())
9459     I.info = classifyType(I.type, 16 * 8);
9460 }
9461 
9462 namespace {
9463 class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
9464 public:
9465   SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
9466       : TargetCodeGenInfo(std::make_unique<SparcV9ABIInfo>(CGT)) {}
9467 
9468   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
9469     return 14;
9470   }
9471 
9472   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
9473                                llvm::Value *Address) const override;
9474 };
9475 } // end anonymous namespace
9476 
9477 bool
9478 SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
9479                                                 llvm::Value *Address) const {
9480   // This is calculated from the LLVM and GCC tables and verified
9481   // against gcc output.  AFAIK all ABIs use the same encoding.
9482 
9483   CodeGen::CGBuilderTy &Builder = CGF.Builder;
9484 
9485   llvm::IntegerType *i8 = CGF.Int8Ty;
9486   llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
9487   llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
9488 
9489   // 0-31: the 8-byte general-purpose registers
9490   AssignToArrayRange(Builder, Address, Eight8, 0, 31);
9491 
9492   // 32-63: f0-31, the 4-byte floating-point registers
9493   AssignToArrayRange(Builder, Address, Four8, 32, 63);
9494 
9495   //   Y   = 64
9496   //   PSR = 65
9497   //   WIM = 66
9498   //   TBR = 67
9499   //   PC  = 68
9500   //   NPC = 69
9501   //   FSR = 70
9502   //   CSR = 71
9503   AssignToArrayRange(Builder, Address, Eight8, 64, 71);
9504 
9505   // 72-87: d0-15, the 8-byte floating-point registers
9506   AssignToArrayRange(Builder, Address, Eight8, 72, 87);
9507 
9508   return false;
9509 }
9510 
9511 // ARC ABI implementation.
9512 namespace {
9513 
9514 class ARCABIInfo : public DefaultABIInfo {
9515 public:
9516   using DefaultABIInfo::DefaultABIInfo;
9517 
9518 private:
9519   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9520                     QualType Ty) const override;
9521 
9522   void updateState(const ABIArgInfo &Info, QualType Ty, CCState &State) const {
9523     if (!State.FreeRegs)
9524       return;
9525     if (Info.isIndirect() && Info.getInReg())
9526       State.FreeRegs--;
9527     else if (Info.isDirect() && Info.getInReg()) {
9528       unsigned sz = (getContext().getTypeSize(Ty) + 31) / 32;
9529       if (sz < State.FreeRegs)
9530         State.FreeRegs -= sz;
9531       else
9532         State.FreeRegs = 0;
9533     }
9534   }
9535 
9536   void computeInfo(CGFunctionInfo &FI) const override {
9537     CCState State(FI);
9538     // ARC uses 8 registers to pass arguments.
9539     State.FreeRegs = 8;
9540 
9541     if (!getCXXABI().classifyReturnType(FI))
9542       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
9543     updateState(FI.getReturnInfo(), FI.getReturnType(), State);
9544     for (auto &I : FI.arguments()) {
9545       I.info = classifyArgumentType(I.type, State.FreeRegs);
9546       updateState(I.info, I.type, State);
9547     }
9548   }
9549 
9550   ABIArgInfo getIndirectByRef(QualType Ty, bool HasFreeRegs) const;
9551   ABIArgInfo getIndirectByValue(QualType Ty) const;
9552   ABIArgInfo classifyArgumentType(QualType Ty, uint8_t FreeRegs) const;
9553   ABIArgInfo classifyReturnType(QualType RetTy) const;
9554 };
9555 
9556 class ARCTargetCodeGenInfo : public TargetCodeGenInfo {
9557 public:
9558   ARCTargetCodeGenInfo(CodeGenTypes &CGT)
9559       : TargetCodeGenInfo(std::make_unique<ARCABIInfo>(CGT)) {}
9560 };
9561 
9562 
9563 ABIArgInfo ARCABIInfo::getIndirectByRef(QualType Ty, bool HasFreeRegs) const {
9564   return HasFreeRegs ? getNaturalAlignIndirectInReg(Ty) :
9565                        getNaturalAlignIndirect(Ty, false);
9566 }
9567 
9568 ABIArgInfo ARCABIInfo::getIndirectByValue(QualType Ty) const {
9569   // Compute the byval alignment.
9570   const unsigned MinABIStackAlignInBytes = 4;
9571   unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
9572   return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true,
9573                                  TypeAlign > MinABIStackAlignInBytes);
9574 }
9575 
9576 Address ARCABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9577                               QualType Ty) const {
9578   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
9579                           getContext().getTypeInfoInChars(Ty),
9580                           CharUnits::fromQuantity(4), true);
9581 }
9582 
9583 ABIArgInfo ARCABIInfo::classifyArgumentType(QualType Ty,
9584                                             uint8_t FreeRegs) const {
9585   // Handle the generic C++ ABI.
9586   const RecordType *RT = Ty->getAs<RecordType>();
9587   if (RT) {
9588     CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
9589     if (RAA == CGCXXABI::RAA_Indirect)
9590       return getIndirectByRef(Ty, FreeRegs > 0);
9591 
9592     if (RAA == CGCXXABI::RAA_DirectInMemory)
9593       return getIndirectByValue(Ty);
9594   }
9595 
9596   // Treat an enum type as its underlying type.
9597   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
9598     Ty = EnumTy->getDecl()->getIntegerType();
9599 
9600   auto SizeInRegs = llvm::alignTo(getContext().getTypeSize(Ty), 32) / 32;
9601 
9602   if (isAggregateTypeForABI(Ty)) {
9603     // Structures with flexible arrays are always indirect.
9604     if (RT && RT->getDecl()->hasFlexibleArrayMember())
9605       return getIndirectByValue(Ty);
9606 
9607     // Ignore empty structs/unions.
9608     if (isEmptyRecord(getContext(), Ty, true))
9609       return ABIArgInfo::getIgnore();
9610 
9611     llvm::LLVMContext &LLVMContext = getVMContext();
9612 
9613     llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
9614     SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32);
9615     llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
9616 
9617     return FreeRegs >= SizeInRegs ?
9618         ABIArgInfo::getDirectInReg(Result) :
9619         ABIArgInfo::getDirect(Result, 0, nullptr, false);
9620   }
9621 
9622   if (const auto *EIT = Ty->getAs<ExtIntType>())
9623     if (EIT->getNumBits() > 64)
9624       return getIndirectByValue(Ty);
9625 
9626   return isPromotableIntegerTypeForABI(Ty)
9627              ? (FreeRegs >= SizeInRegs ? ABIArgInfo::getExtendInReg(Ty)
9628                                        : ABIArgInfo::getExtend(Ty))
9629              : (FreeRegs >= SizeInRegs ? ABIArgInfo::getDirectInReg()
9630                                        : ABIArgInfo::getDirect());
9631 }
9632 
9633 ABIArgInfo ARCABIInfo::classifyReturnType(QualType RetTy) const {
9634   if (RetTy->isAnyComplexType())
9635     return ABIArgInfo::getDirectInReg();
9636 
9637   // Arguments of size > 4 registers are indirect.
9638   auto RetSize = llvm::alignTo(getContext().getTypeSize(RetTy), 32) / 32;
9639   if (RetSize > 4)
9640     return getIndirectByRef(RetTy, /*HasFreeRegs*/ true);
9641 
9642   return DefaultABIInfo::classifyReturnType(RetTy);
9643 }
9644 
9645 } // End anonymous namespace.
9646 
9647 //===----------------------------------------------------------------------===//
9648 // XCore ABI Implementation
9649 //===----------------------------------------------------------------------===//
9650 
9651 namespace {
9652 
9653 /// A SmallStringEnc instance is used to build up the TypeString by passing
9654 /// it by reference between functions that append to it.
9655 typedef llvm::SmallString<128> SmallStringEnc;
9656 
9657 /// TypeStringCache caches the meta encodings of Types.
9658 ///
9659 /// The reason for caching TypeStrings is two fold:
9660 ///   1. To cache a type's encoding for later uses;
9661 ///   2. As a means to break recursive member type inclusion.
9662 ///
9663 /// A cache Entry can have a Status of:
9664 ///   NonRecursive:   The type encoding is not recursive;
9665 ///   Recursive:      The type encoding is recursive;
9666 ///   Incomplete:     An incomplete TypeString;
9667 ///   IncompleteUsed: An incomplete TypeString that has been used in a
9668 ///                   Recursive type encoding.
9669 ///
9670 /// A NonRecursive entry will have all of its sub-members expanded as fully
9671 /// as possible. Whilst it may contain types which are recursive, the type
9672 /// itself is not recursive and thus its encoding may be safely used whenever
9673 /// the type is encountered.
9674 ///
9675 /// A Recursive entry will have all of its sub-members expanded as fully as
9676 /// possible. The type itself is recursive and it may contain other types which
9677 /// are recursive. The Recursive encoding must not be used during the expansion
9678 /// of a recursive type's recursive branch. For simplicity the code uses
9679 /// IncompleteCount to reject all usage of Recursive encodings for member types.
9680 ///
9681 /// An Incomplete entry is always a RecordType and only encodes its
9682 /// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and
9683 /// are placed into the cache during type expansion as a means to identify and
9684 /// handle recursive inclusion of types as sub-members. If there is recursion
9685 /// the entry becomes IncompleteUsed.
9686 ///
9687 /// During the expansion of a RecordType's members:
9688 ///
9689 ///   If the cache contains a NonRecursive encoding for the member type, the
9690 ///   cached encoding is used;
9691 ///
9692 ///   If the cache contains a Recursive encoding for the member type, the
9693 ///   cached encoding is 'Swapped' out, as it may be incorrect, and...
9694 ///
9695 ///   If the member is a RecordType, an Incomplete encoding is placed into the
9696 ///   cache to break potential recursive inclusion of itself as a sub-member;
9697 ///
9698 ///   Once a member RecordType has been expanded, its temporary incomplete
9699 ///   entry is removed from the cache. If a Recursive encoding was swapped out
9700 ///   it is swapped back in;
9701 ///
9702 ///   If an incomplete entry is used to expand a sub-member, the incomplete
9703 ///   entry is marked as IncompleteUsed. The cache keeps count of how many
9704 ///   IncompleteUsed entries it currently contains in IncompleteUsedCount;
9705 ///
9706 ///   If a member's encoding is found to be a NonRecursive or Recursive viz:
9707 ///   IncompleteUsedCount==0, the member's encoding is added to the cache.
9708 ///   Else the member is part of a recursive type and thus the recursion has
9709 ///   been exited too soon for the encoding to be correct for the member.
9710 ///
9711 class TypeStringCache {
9712   enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed};
9713   struct Entry {
9714     std::string Str;     // The encoded TypeString for the type.
9715     enum Status State;   // Information about the encoding in 'Str'.
9716     std::string Swapped; // A temporary place holder for a Recursive encoding
9717                          // during the expansion of RecordType's members.
9718   };
9719   std::map<const IdentifierInfo *, struct Entry> Map;
9720   unsigned IncompleteCount;     // Number of Incomplete entries in the Map.
9721   unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map.
9722 public:
9723   TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {}
9724   void addIncomplete(const IdentifierInfo *ID, std::string StubEnc);
9725   bool removeIncomplete(const IdentifierInfo *ID);
9726   void addIfComplete(const IdentifierInfo *ID, StringRef Str,
9727                      bool IsRecursive);
9728   StringRef lookupStr(const IdentifierInfo *ID);
9729 };
9730 
9731 /// TypeString encodings for enum & union fields must be order.
9732 /// FieldEncoding is a helper for this ordering process.
9733 class FieldEncoding {
9734   bool HasName;
9735   std::string Enc;
9736 public:
9737   FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {}
9738   StringRef str() { return Enc; }
9739   bool operator<(const FieldEncoding &rhs) const {
9740     if (HasName != rhs.HasName) return HasName;
9741     return Enc < rhs.Enc;
9742   }
9743 };
9744 
9745 class XCoreABIInfo : public DefaultABIInfo {
9746 public:
9747   XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
9748   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9749                     QualType Ty) const override;
9750 };
9751 
9752 class XCoreTargetCodeGenInfo : public TargetCodeGenInfo {
9753   mutable TypeStringCache TSC;
9754   void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
9755                     const CodeGen::CodeGenModule &M) const;
9756 
9757 public:
9758   XCoreTargetCodeGenInfo(CodeGenTypes &CGT)
9759       : TargetCodeGenInfo(std::make_unique<XCoreABIInfo>(CGT)) {}
9760   void emitTargetMetadata(CodeGen::CodeGenModule &CGM,
9761                           const llvm::MapVector<GlobalDecl, StringRef>
9762                               &MangledDeclNames) const override;
9763 };
9764 
9765 } // End anonymous namespace.
9766 
9767 // TODO: this implementation is likely now redundant with the default
9768 // EmitVAArg.
9769 Address XCoreABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9770                                 QualType Ty) const {
9771   CGBuilderTy &Builder = CGF.Builder;
9772 
9773   // Get the VAList.
9774   CharUnits SlotSize = CharUnits::fromQuantity(4);
9775   Address AP(Builder.CreateLoad(VAListAddr), SlotSize);
9776 
9777   // Handle the argument.
9778   ABIArgInfo AI = classifyArgumentType(Ty);
9779   CharUnits TypeAlign = getContext().getTypeAlignInChars(Ty);
9780   llvm::Type *ArgTy = CGT.ConvertType(Ty);
9781   if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
9782     AI.setCoerceToType(ArgTy);
9783   llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
9784 
9785   Address Val = Address::invalid();
9786   CharUnits ArgSize = CharUnits::Zero();
9787   switch (AI.getKind()) {
9788   case ABIArgInfo::Expand:
9789   case ABIArgInfo::CoerceAndExpand:
9790   case ABIArgInfo::InAlloca:
9791     llvm_unreachable("Unsupported ABI kind for va_arg");
9792   case ABIArgInfo::Ignore:
9793     Val = Address(llvm::UndefValue::get(ArgPtrTy), TypeAlign);
9794     ArgSize = CharUnits::Zero();
9795     break;
9796   case ABIArgInfo::Extend:
9797   case ABIArgInfo::Direct:
9798     Val = Builder.CreateBitCast(AP, ArgPtrTy);
9799     ArgSize = CharUnits::fromQuantity(
9800                        getDataLayout().getTypeAllocSize(AI.getCoerceToType()));
9801     ArgSize = ArgSize.alignTo(SlotSize);
9802     break;
9803   case ABIArgInfo::Indirect:
9804   case ABIArgInfo::IndirectAliased:
9805     Val = Builder.CreateElementBitCast(AP, ArgPtrTy);
9806     Val = Address(Builder.CreateLoad(Val), TypeAlign);
9807     ArgSize = SlotSize;
9808     break;
9809   }
9810 
9811   // Increment the VAList.
9812   if (!ArgSize.isZero()) {
9813     Address APN = Builder.CreateConstInBoundsByteGEP(AP, ArgSize);
9814     Builder.CreateStore(APN.getPointer(), VAListAddr);
9815   }
9816 
9817   return Val;
9818 }
9819 
9820 /// During the expansion of a RecordType, an incomplete TypeString is placed
9821 /// into the cache as a means to identify and break recursion.
9822 /// If there is a Recursive encoding in the cache, it is swapped out and will
9823 /// be reinserted by removeIncomplete().
9824 /// All other types of encoding should have been used rather than arriving here.
9825 void TypeStringCache::addIncomplete(const IdentifierInfo *ID,
9826                                     std::string StubEnc) {
9827   if (!ID)
9828     return;
9829   Entry &E = Map[ID];
9830   assert( (E.Str.empty() || E.State == Recursive) &&
9831          "Incorrectly use of addIncomplete");
9832   assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()");
9833   E.Swapped.swap(E.Str); // swap out the Recursive
9834   E.Str.swap(StubEnc);
9835   E.State = Incomplete;
9836   ++IncompleteCount;
9837 }
9838 
9839 /// Once the RecordType has been expanded, the temporary incomplete TypeString
9840 /// must be removed from the cache.
9841 /// If a Recursive was swapped out by addIncomplete(), it will be replaced.
9842 /// Returns true if the RecordType was defined recursively.
9843 bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) {
9844   if (!ID)
9845     return false;
9846   auto I = Map.find(ID);
9847   assert(I != Map.end() && "Entry not present");
9848   Entry &E = I->second;
9849   assert( (E.State == Incomplete ||
9850            E.State == IncompleteUsed) &&
9851          "Entry must be an incomplete type");
9852   bool IsRecursive = false;
9853   if (E.State == IncompleteUsed) {
9854     // We made use of our Incomplete encoding, thus we are recursive.
9855     IsRecursive = true;
9856     --IncompleteUsedCount;
9857   }
9858   if (E.Swapped.empty())
9859     Map.erase(I);
9860   else {
9861     // Swap the Recursive back.
9862     E.Swapped.swap(E.Str);
9863     E.Swapped.clear();
9864     E.State = Recursive;
9865   }
9866   --IncompleteCount;
9867   return IsRecursive;
9868 }
9869 
9870 /// Add the encoded TypeString to the cache only if it is NonRecursive or
9871 /// Recursive (viz: all sub-members were expanded as fully as possible).
9872 void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str,
9873                                     bool IsRecursive) {
9874   if (!ID || IncompleteUsedCount)
9875     return; // No key or it is is an incomplete sub-type so don't add.
9876   Entry &E = Map[ID];
9877   if (IsRecursive && !E.Str.empty()) {
9878     assert(E.State==Recursive && E.Str.size() == Str.size() &&
9879            "This is not the same Recursive entry");
9880     // The parent container was not recursive after all, so we could have used
9881     // this Recursive sub-member entry after all, but we assumed the worse when
9882     // we started viz: IncompleteCount!=0.
9883     return;
9884   }
9885   assert(E.Str.empty() && "Entry already present");
9886   E.Str = Str.str();
9887   E.State = IsRecursive? Recursive : NonRecursive;
9888 }
9889 
9890 /// Return a cached TypeString encoding for the ID. If there isn't one, or we
9891 /// are recursively expanding a type (IncompleteCount != 0) and the cached
9892 /// encoding is Recursive, return an empty StringRef.
9893 StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) {
9894   if (!ID)
9895     return StringRef();   // We have no key.
9896   auto I = Map.find(ID);
9897   if (I == Map.end())
9898     return StringRef();   // We have no encoding.
9899   Entry &E = I->second;
9900   if (E.State == Recursive && IncompleteCount)
9901     return StringRef();   // We don't use Recursive encodings for member types.
9902 
9903   if (E.State == Incomplete) {
9904     // The incomplete type is being used to break out of recursion.
9905     E.State = IncompleteUsed;
9906     ++IncompleteUsedCount;
9907   }
9908   return E.Str;
9909 }
9910 
9911 /// The XCore ABI includes a type information section that communicates symbol
9912 /// type information to the linker. The linker uses this information to verify
9913 /// safety/correctness of things such as array bound and pointers et al.
9914 /// The ABI only requires C (and XC) language modules to emit TypeStrings.
9915 /// This type information (TypeString) is emitted into meta data for all global
9916 /// symbols: definitions, declarations, functions & variables.
9917 ///
9918 /// The TypeString carries type, qualifier, name, size & value details.
9919 /// Please see 'Tools Development Guide' section 2.16.2 for format details:
9920 /// https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf
9921 /// The output is tested by test/CodeGen/xcore-stringtype.c.
9922 ///
9923 static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
9924                           const CodeGen::CodeGenModule &CGM,
9925                           TypeStringCache &TSC);
9926 
9927 /// XCore uses emitTargetMD to emit TypeString metadata for global symbols.
9928 void XCoreTargetCodeGenInfo::emitTargetMD(
9929     const Decl *D, llvm::GlobalValue *GV,
9930     const CodeGen::CodeGenModule &CGM) const {
9931   SmallStringEnc Enc;
9932   if (getTypeString(Enc, D, CGM, TSC)) {
9933     llvm::LLVMContext &Ctx = CGM.getModule().getContext();
9934     llvm::Metadata *MDVals[] = {llvm::ConstantAsMetadata::get(GV),
9935                                 llvm::MDString::get(Ctx, Enc.str())};
9936     llvm::NamedMDNode *MD =
9937       CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings");
9938     MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
9939   }
9940 }
9941 
9942 void XCoreTargetCodeGenInfo::emitTargetMetadata(
9943     CodeGen::CodeGenModule &CGM,
9944     const llvm::MapVector<GlobalDecl, StringRef> &MangledDeclNames) const {
9945   // Warning, new MangledDeclNames may be appended within this loop.
9946   // We rely on MapVector insertions adding new elements to the end
9947   // of the container.
9948   for (unsigned I = 0; I != MangledDeclNames.size(); ++I) {
9949     auto Val = *(MangledDeclNames.begin() + I);
9950     llvm::GlobalValue *GV = CGM.GetGlobalValue(Val.second);
9951     if (GV) {
9952       const Decl *D = Val.first.getDecl()->getMostRecentDecl();
9953       emitTargetMD(D, GV, CGM);
9954     }
9955   }
9956 }
9957 //===----------------------------------------------------------------------===//
9958 // SPIR ABI Implementation
9959 //===----------------------------------------------------------------------===//
9960 
9961 namespace {
9962 class SPIRABIInfo : public DefaultABIInfo {
9963 public:
9964   SPIRABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) { setCCs(); }
9965 
9966 private:
9967   void setCCs();
9968 };
9969 } // end anonymous namespace
9970 namespace {
9971 class SPIRTargetCodeGenInfo : public TargetCodeGenInfo {
9972 public:
9973   SPIRTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
9974       : TargetCodeGenInfo(std::make_unique<SPIRABIInfo>(CGT)) {}
9975   unsigned getOpenCLKernelCallingConv() const override;
9976 };
9977 
9978 } // End anonymous namespace.
9979 void SPIRABIInfo::setCCs() {
9980   assert(getRuntimeCC() == llvm::CallingConv::C);
9981   RuntimeCC = llvm::CallingConv::SPIR_FUNC;
9982 }
9983 
9984 namespace clang {
9985 namespace CodeGen {
9986 void computeSPIRKernelABIInfo(CodeGenModule &CGM, CGFunctionInfo &FI) {
9987   DefaultABIInfo SPIRABI(CGM.getTypes());
9988   SPIRABI.computeInfo(FI);
9989 }
9990 }
9991 }
9992 
9993 unsigned SPIRTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
9994   return llvm::CallingConv::SPIR_KERNEL;
9995 }
9996 
9997 static bool appendType(SmallStringEnc &Enc, QualType QType,
9998                        const CodeGen::CodeGenModule &CGM,
9999                        TypeStringCache &TSC);
10000 
10001 /// Helper function for appendRecordType().
10002 /// Builds a SmallVector containing the encoded field types in declaration
10003 /// order.
10004 static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE,
10005                              const RecordDecl *RD,
10006                              const CodeGen::CodeGenModule &CGM,
10007                              TypeStringCache &TSC) {
10008   for (const auto *Field : RD->fields()) {
10009     SmallStringEnc Enc;
10010     Enc += "m(";
10011     Enc += Field->getName();
10012     Enc += "){";
10013     if (Field->isBitField()) {
10014       Enc += "b(";
10015       llvm::raw_svector_ostream OS(Enc);
10016       OS << Field->getBitWidthValue(CGM.getContext());
10017       Enc += ':';
10018     }
10019     if (!appendType(Enc, Field->getType(), CGM, TSC))
10020       return false;
10021     if (Field->isBitField())
10022       Enc += ')';
10023     Enc += '}';
10024     FE.emplace_back(!Field->getName().empty(), Enc);
10025   }
10026   return true;
10027 }
10028 
10029 /// Appends structure and union types to Enc and adds encoding to cache.
10030 /// Recursively calls appendType (via extractFieldType) for each field.
10031 /// Union types have their fields ordered according to the ABI.
10032 static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT,
10033                              const CodeGen::CodeGenModule &CGM,
10034                              TypeStringCache &TSC, const IdentifierInfo *ID) {
10035   // Append the cached TypeString if we have one.
10036   StringRef TypeString = TSC.lookupStr(ID);
10037   if (!TypeString.empty()) {
10038     Enc += TypeString;
10039     return true;
10040   }
10041 
10042   // Start to emit an incomplete TypeString.
10043   size_t Start = Enc.size();
10044   Enc += (RT->isUnionType()? 'u' : 's');
10045   Enc += '(';
10046   if (ID)
10047     Enc += ID->getName();
10048   Enc += "){";
10049 
10050   // We collect all encoded fields and order as necessary.
10051   bool IsRecursive = false;
10052   const RecordDecl *RD = RT->getDecl()->getDefinition();
10053   if (RD && !RD->field_empty()) {
10054     // An incomplete TypeString stub is placed in the cache for this RecordType
10055     // so that recursive calls to this RecordType will use it whilst building a
10056     // complete TypeString for this RecordType.
10057     SmallVector<FieldEncoding, 16> FE;
10058     std::string StubEnc(Enc.substr(Start).str());
10059     StubEnc += '}';  // StubEnc now holds a valid incomplete TypeString.
10060     TSC.addIncomplete(ID, std::move(StubEnc));
10061     if (!extractFieldType(FE, RD, CGM, TSC)) {
10062       (void) TSC.removeIncomplete(ID);
10063       return false;
10064     }
10065     IsRecursive = TSC.removeIncomplete(ID);
10066     // The ABI requires unions to be sorted but not structures.
10067     // See FieldEncoding::operator< for sort algorithm.
10068     if (RT->isUnionType())
10069       llvm::sort(FE);
10070     // We can now complete the TypeString.
10071     unsigned E = FE.size();
10072     for (unsigned I = 0; I != E; ++I) {
10073       if (I)
10074         Enc += ',';
10075       Enc += FE[I].str();
10076     }
10077   }
10078   Enc += '}';
10079   TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive);
10080   return true;
10081 }
10082 
10083 /// Appends enum types to Enc and adds the encoding to the cache.
10084 static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET,
10085                            TypeStringCache &TSC,
10086                            const IdentifierInfo *ID) {
10087   // Append the cached TypeString if we have one.
10088   StringRef TypeString = TSC.lookupStr(ID);
10089   if (!TypeString.empty()) {
10090     Enc += TypeString;
10091     return true;
10092   }
10093 
10094   size_t Start = Enc.size();
10095   Enc += "e(";
10096   if (ID)
10097     Enc += ID->getName();
10098   Enc += "){";
10099 
10100   // We collect all encoded enumerations and order them alphanumerically.
10101   if (const EnumDecl *ED = ET->getDecl()->getDefinition()) {
10102     SmallVector<FieldEncoding, 16> FE;
10103     for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E;
10104          ++I) {
10105       SmallStringEnc EnumEnc;
10106       EnumEnc += "m(";
10107       EnumEnc += I->getName();
10108       EnumEnc += "){";
10109       I->getInitVal().toString(EnumEnc);
10110       EnumEnc += '}';
10111       FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc));
10112     }
10113     llvm::sort(FE);
10114     unsigned E = FE.size();
10115     for (unsigned I = 0; I != E; ++I) {
10116       if (I)
10117         Enc += ',';
10118       Enc += FE[I].str();
10119     }
10120   }
10121   Enc += '}';
10122   TSC.addIfComplete(ID, Enc.substr(Start), false);
10123   return true;
10124 }
10125 
10126 /// Appends type's qualifier to Enc.
10127 /// This is done prior to appending the type's encoding.
10128 static void appendQualifier(SmallStringEnc &Enc, QualType QT) {
10129   // Qualifiers are emitted in alphabetical order.
10130   static const char *const Table[]={"","c:","r:","cr:","v:","cv:","rv:","crv:"};
10131   int Lookup = 0;
10132   if (QT.isConstQualified())
10133     Lookup += 1<<0;
10134   if (QT.isRestrictQualified())
10135     Lookup += 1<<1;
10136   if (QT.isVolatileQualified())
10137     Lookup += 1<<2;
10138   Enc += Table[Lookup];
10139 }
10140 
10141 /// Appends built-in types to Enc.
10142 static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) {
10143   const char *EncType;
10144   switch (BT->getKind()) {
10145     case BuiltinType::Void:
10146       EncType = "0";
10147       break;
10148     case BuiltinType::Bool:
10149       EncType = "b";
10150       break;
10151     case BuiltinType::Char_U:
10152       EncType = "uc";
10153       break;
10154     case BuiltinType::UChar:
10155       EncType = "uc";
10156       break;
10157     case BuiltinType::SChar:
10158       EncType = "sc";
10159       break;
10160     case BuiltinType::UShort:
10161       EncType = "us";
10162       break;
10163     case BuiltinType::Short:
10164       EncType = "ss";
10165       break;
10166     case BuiltinType::UInt:
10167       EncType = "ui";
10168       break;
10169     case BuiltinType::Int:
10170       EncType = "si";
10171       break;
10172     case BuiltinType::ULong:
10173       EncType = "ul";
10174       break;
10175     case BuiltinType::Long:
10176       EncType = "sl";
10177       break;
10178     case BuiltinType::ULongLong:
10179       EncType = "ull";
10180       break;
10181     case BuiltinType::LongLong:
10182       EncType = "sll";
10183       break;
10184     case BuiltinType::Float:
10185       EncType = "ft";
10186       break;
10187     case BuiltinType::Double:
10188       EncType = "d";
10189       break;
10190     case BuiltinType::LongDouble:
10191       EncType = "ld";
10192       break;
10193     default:
10194       return false;
10195   }
10196   Enc += EncType;
10197   return true;
10198 }
10199 
10200 /// Appends a pointer encoding to Enc before calling appendType for the pointee.
10201 static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT,
10202                               const CodeGen::CodeGenModule &CGM,
10203                               TypeStringCache &TSC) {
10204   Enc += "p(";
10205   if (!appendType(Enc, PT->getPointeeType(), CGM, TSC))
10206     return false;
10207   Enc += ')';
10208   return true;
10209 }
10210 
10211 /// Appends array encoding to Enc before calling appendType for the element.
10212 static bool appendArrayType(SmallStringEnc &Enc, QualType QT,
10213                             const ArrayType *AT,
10214                             const CodeGen::CodeGenModule &CGM,
10215                             TypeStringCache &TSC, StringRef NoSizeEnc) {
10216   if (AT->getSizeModifier() != ArrayType::Normal)
10217     return false;
10218   Enc += "a(";
10219   if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
10220     CAT->getSize().toStringUnsigned(Enc);
10221   else
10222     Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "".
10223   Enc += ':';
10224   // The Qualifiers should be attached to the type rather than the array.
10225   appendQualifier(Enc, QT);
10226   if (!appendType(Enc, AT->getElementType(), CGM, TSC))
10227     return false;
10228   Enc += ')';
10229   return true;
10230 }
10231 
10232 /// Appends a function encoding to Enc, calling appendType for the return type
10233 /// and the arguments.
10234 static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT,
10235                              const CodeGen::CodeGenModule &CGM,
10236                              TypeStringCache &TSC) {
10237   Enc += "f{";
10238   if (!appendType(Enc, FT->getReturnType(), CGM, TSC))
10239     return false;
10240   Enc += "}(";
10241   if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) {
10242     // N.B. we are only interested in the adjusted param types.
10243     auto I = FPT->param_type_begin();
10244     auto E = FPT->param_type_end();
10245     if (I != E) {
10246       do {
10247         if (!appendType(Enc, *I, CGM, TSC))
10248           return false;
10249         ++I;
10250         if (I != E)
10251           Enc += ',';
10252       } while (I != E);
10253       if (FPT->isVariadic())
10254         Enc += ",va";
10255     } else {
10256       if (FPT->isVariadic())
10257         Enc += "va";
10258       else
10259         Enc += '0';
10260     }
10261   }
10262   Enc += ')';
10263   return true;
10264 }
10265 
10266 /// Handles the type's qualifier before dispatching a call to handle specific
10267 /// type encodings.
10268 static bool appendType(SmallStringEnc &Enc, QualType QType,
10269                        const CodeGen::CodeGenModule &CGM,
10270                        TypeStringCache &TSC) {
10271 
10272   QualType QT = QType.getCanonicalType();
10273 
10274   if (const ArrayType *AT = QT->getAsArrayTypeUnsafe())
10275     // The Qualifiers should be attached to the type rather than the array.
10276     // Thus we don't call appendQualifier() here.
10277     return appendArrayType(Enc, QT, AT, CGM, TSC, "");
10278 
10279   appendQualifier(Enc, QT);
10280 
10281   if (const BuiltinType *BT = QT->getAs<BuiltinType>())
10282     return appendBuiltinType(Enc, BT);
10283 
10284   if (const PointerType *PT = QT->getAs<PointerType>())
10285     return appendPointerType(Enc, PT, CGM, TSC);
10286 
10287   if (const EnumType *ET = QT->getAs<EnumType>())
10288     return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier());
10289 
10290   if (const RecordType *RT = QT->getAsStructureType())
10291     return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
10292 
10293   if (const RecordType *RT = QT->getAsUnionType())
10294     return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
10295 
10296   if (const FunctionType *FT = QT->getAs<FunctionType>())
10297     return appendFunctionType(Enc, FT, CGM, TSC);
10298 
10299   return false;
10300 }
10301 
10302 static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
10303                           const CodeGen::CodeGenModule &CGM,
10304                           TypeStringCache &TSC) {
10305   if (!D)
10306     return false;
10307 
10308   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
10309     if (FD->getLanguageLinkage() != CLanguageLinkage)
10310       return false;
10311     return appendType(Enc, FD->getType(), CGM, TSC);
10312   }
10313 
10314   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
10315     if (VD->getLanguageLinkage() != CLanguageLinkage)
10316       return false;
10317     QualType QT = VD->getType().getCanonicalType();
10318     if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) {
10319       // Global ArrayTypes are given a size of '*' if the size is unknown.
10320       // The Qualifiers should be attached to the type rather than the array.
10321       // Thus we don't call appendQualifier() here.
10322       return appendArrayType(Enc, QT, AT, CGM, TSC, "*");
10323     }
10324     return appendType(Enc, QT, CGM, TSC);
10325   }
10326   return false;
10327 }
10328 
10329 //===----------------------------------------------------------------------===//
10330 // RISCV ABI Implementation
10331 //===----------------------------------------------------------------------===//
10332 
10333 namespace {
10334 class RISCVABIInfo : public DefaultABIInfo {
10335 private:
10336   // Size of the integer ('x') registers in bits.
10337   unsigned XLen;
10338   // Size of the floating point ('f') registers in bits. Note that the target
10339   // ISA might have a wider FLen than the selected ABI (e.g. an RV32IF target
10340   // with soft float ABI has FLen==0).
10341   unsigned FLen;
10342   static const int NumArgGPRs = 8;
10343   static const int NumArgFPRs = 8;
10344   bool detectFPCCEligibleStructHelper(QualType Ty, CharUnits CurOff,
10345                                       llvm::Type *&Field1Ty,
10346                                       CharUnits &Field1Off,
10347                                       llvm::Type *&Field2Ty,
10348                                       CharUnits &Field2Off) const;
10349 
10350 public:
10351   RISCVABIInfo(CodeGen::CodeGenTypes &CGT, unsigned XLen, unsigned FLen)
10352       : DefaultABIInfo(CGT), XLen(XLen), FLen(FLen) {}
10353 
10354   // DefaultABIInfo's classifyReturnType and classifyArgumentType are
10355   // non-virtual, but computeInfo is virtual, so we overload it.
10356   void computeInfo(CGFunctionInfo &FI) const override;
10357 
10358   ABIArgInfo classifyArgumentType(QualType Ty, bool IsFixed, int &ArgGPRsLeft,
10359                                   int &ArgFPRsLeft) const;
10360   ABIArgInfo classifyReturnType(QualType RetTy) const;
10361 
10362   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
10363                     QualType Ty) const override;
10364 
10365   ABIArgInfo extendType(QualType Ty) const;
10366 
10367   bool detectFPCCEligibleStruct(QualType Ty, llvm::Type *&Field1Ty,
10368                                 CharUnits &Field1Off, llvm::Type *&Field2Ty,
10369                                 CharUnits &Field2Off, int &NeededArgGPRs,
10370                                 int &NeededArgFPRs) const;
10371   ABIArgInfo coerceAndExpandFPCCEligibleStruct(llvm::Type *Field1Ty,
10372                                                CharUnits Field1Off,
10373                                                llvm::Type *Field2Ty,
10374                                                CharUnits Field2Off) const;
10375 };
10376 } // end anonymous namespace
10377 
10378 void RISCVABIInfo::computeInfo(CGFunctionInfo &FI) const {
10379   QualType RetTy = FI.getReturnType();
10380   if (!getCXXABI().classifyReturnType(FI))
10381     FI.getReturnInfo() = classifyReturnType(RetTy);
10382 
10383   // IsRetIndirect is true if classifyArgumentType indicated the value should
10384   // be passed indirect, or if the type size is a scalar greater than 2*XLen
10385   // and not a complex type with elements <= FLen. e.g. fp128 is passed direct
10386   // in LLVM IR, relying on the backend lowering code to rewrite the argument
10387   // list and pass indirectly on RV32.
10388   bool IsRetIndirect = FI.getReturnInfo().getKind() == ABIArgInfo::Indirect;
10389   if (!IsRetIndirect && RetTy->isScalarType() &&
10390       getContext().getTypeSize(RetTy) > (2 * XLen)) {
10391     if (RetTy->isComplexType() && FLen) {
10392       QualType EltTy = RetTy->castAs<ComplexType>()->getElementType();
10393       IsRetIndirect = getContext().getTypeSize(EltTy) > FLen;
10394     } else {
10395       // This is a normal scalar > 2*XLen, such as fp128 on RV32.
10396       IsRetIndirect = true;
10397     }
10398   }
10399 
10400   // We must track the number of GPRs used in order to conform to the RISC-V
10401   // ABI, as integer scalars passed in registers should have signext/zeroext
10402   // when promoted, but are anyext if passed on the stack. As GPR usage is
10403   // different for variadic arguments, we must also track whether we are
10404   // examining a vararg or not.
10405   int ArgGPRsLeft = IsRetIndirect ? NumArgGPRs - 1 : NumArgGPRs;
10406   int ArgFPRsLeft = FLen ? NumArgFPRs : 0;
10407   int NumFixedArgs = FI.getNumRequiredArgs();
10408 
10409   int ArgNum = 0;
10410   for (auto &ArgInfo : FI.arguments()) {
10411     bool IsFixed = ArgNum < NumFixedArgs;
10412     ArgInfo.info =
10413         classifyArgumentType(ArgInfo.type, IsFixed, ArgGPRsLeft, ArgFPRsLeft);
10414     ArgNum++;
10415   }
10416 }
10417 
10418 // Returns true if the struct is a potential candidate for the floating point
10419 // calling convention. If this function returns true, the caller is
10420 // responsible for checking that if there is only a single field then that
10421 // field is a float.
10422 bool RISCVABIInfo::detectFPCCEligibleStructHelper(QualType Ty, CharUnits CurOff,
10423                                                   llvm::Type *&Field1Ty,
10424                                                   CharUnits &Field1Off,
10425                                                   llvm::Type *&Field2Ty,
10426                                                   CharUnits &Field2Off) const {
10427   bool IsInt = Ty->isIntegralOrEnumerationType();
10428   bool IsFloat = Ty->isRealFloatingType();
10429 
10430   if (IsInt || IsFloat) {
10431     uint64_t Size = getContext().getTypeSize(Ty);
10432     if (IsInt && Size > XLen)
10433       return false;
10434     // Can't be eligible if larger than the FP registers. Half precision isn't
10435     // currently supported on RISC-V and the ABI hasn't been confirmed, so
10436     // default to the integer ABI in that case.
10437     if (IsFloat && (Size > FLen || Size < 32))
10438       return false;
10439     // Can't be eligible if an integer type was already found (int+int pairs
10440     // are not eligible).
10441     if (IsInt && Field1Ty && Field1Ty->isIntegerTy())
10442       return false;
10443     if (!Field1Ty) {
10444       Field1Ty = CGT.ConvertType(Ty);
10445       Field1Off = CurOff;
10446       return true;
10447     }
10448     if (!Field2Ty) {
10449       Field2Ty = CGT.ConvertType(Ty);
10450       Field2Off = CurOff;
10451       return true;
10452     }
10453     return false;
10454   }
10455 
10456   if (auto CTy = Ty->getAs<ComplexType>()) {
10457     if (Field1Ty)
10458       return false;
10459     QualType EltTy = CTy->getElementType();
10460     if (getContext().getTypeSize(EltTy) > FLen)
10461       return false;
10462     Field1Ty = CGT.ConvertType(EltTy);
10463     Field1Off = CurOff;
10464     Field2Ty = Field1Ty;
10465     Field2Off = Field1Off + getContext().getTypeSizeInChars(EltTy);
10466     return true;
10467   }
10468 
10469   if (const ConstantArrayType *ATy = getContext().getAsConstantArrayType(Ty)) {
10470     uint64_t ArraySize = ATy->getSize().getZExtValue();
10471     QualType EltTy = ATy->getElementType();
10472     CharUnits EltSize = getContext().getTypeSizeInChars(EltTy);
10473     for (uint64_t i = 0; i < ArraySize; ++i) {
10474       bool Ret = detectFPCCEligibleStructHelper(EltTy, CurOff, Field1Ty,
10475                                                 Field1Off, Field2Ty, Field2Off);
10476       if (!Ret)
10477         return false;
10478       CurOff += EltSize;
10479     }
10480     return true;
10481   }
10482 
10483   if (const auto *RTy = Ty->getAs<RecordType>()) {
10484     // Structures with either a non-trivial destructor or a non-trivial
10485     // copy constructor are not eligible for the FP calling convention.
10486     if (getRecordArgABI(Ty, CGT.getCXXABI()))
10487       return false;
10488     if (isEmptyRecord(getContext(), Ty, true))
10489       return true;
10490     const RecordDecl *RD = RTy->getDecl();
10491     // Unions aren't eligible unless they're empty (which is caught above).
10492     if (RD->isUnion())
10493       return false;
10494     int ZeroWidthBitFieldCount = 0;
10495     for (const FieldDecl *FD : RD->fields()) {
10496       const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
10497       uint64_t FieldOffInBits = Layout.getFieldOffset(FD->getFieldIndex());
10498       QualType QTy = FD->getType();
10499       if (FD->isBitField()) {
10500         unsigned BitWidth = FD->getBitWidthValue(getContext());
10501         // Allow a bitfield with a type greater than XLen as long as the
10502         // bitwidth is XLen or less.
10503         if (getContext().getTypeSize(QTy) > XLen && BitWidth <= XLen)
10504           QTy = getContext().getIntTypeForBitwidth(XLen, false);
10505         if (BitWidth == 0) {
10506           ZeroWidthBitFieldCount++;
10507           continue;
10508         }
10509       }
10510 
10511       bool Ret = detectFPCCEligibleStructHelper(
10512           QTy, CurOff + getContext().toCharUnitsFromBits(FieldOffInBits),
10513           Field1Ty, Field1Off, Field2Ty, Field2Off);
10514       if (!Ret)
10515         return false;
10516 
10517       // As a quirk of the ABI, zero-width bitfields aren't ignored for fp+fp
10518       // or int+fp structs, but are ignored for a struct with an fp field and
10519       // any number of zero-width bitfields.
10520       if (Field2Ty && ZeroWidthBitFieldCount > 0)
10521         return false;
10522     }
10523     return Field1Ty != nullptr;
10524   }
10525 
10526   return false;
10527 }
10528 
10529 // Determine if a struct is eligible for passing according to the floating
10530 // point calling convention (i.e., when flattened it contains a single fp
10531 // value, fp+fp, or int+fp of appropriate size). If so, NeededArgFPRs and
10532 // NeededArgGPRs are incremented appropriately.
10533 bool RISCVABIInfo::detectFPCCEligibleStruct(QualType Ty, llvm::Type *&Field1Ty,
10534                                             CharUnits &Field1Off,
10535                                             llvm::Type *&Field2Ty,
10536                                             CharUnits &Field2Off,
10537                                             int &NeededArgGPRs,
10538                                             int &NeededArgFPRs) const {
10539   Field1Ty = nullptr;
10540   Field2Ty = nullptr;
10541   NeededArgGPRs = 0;
10542   NeededArgFPRs = 0;
10543   bool IsCandidate = detectFPCCEligibleStructHelper(
10544       Ty, CharUnits::Zero(), Field1Ty, Field1Off, Field2Ty, Field2Off);
10545   // Not really a candidate if we have a single int but no float.
10546   if (Field1Ty && !Field2Ty && !Field1Ty->isFloatingPointTy())
10547     return false;
10548   if (!IsCandidate)
10549     return false;
10550   if (Field1Ty && Field1Ty->isFloatingPointTy())
10551     NeededArgFPRs++;
10552   else if (Field1Ty)
10553     NeededArgGPRs++;
10554   if (Field2Ty && Field2Ty->isFloatingPointTy())
10555     NeededArgFPRs++;
10556   else if (Field2Ty)
10557     NeededArgGPRs++;
10558   return true;
10559 }
10560 
10561 // Call getCoerceAndExpand for the two-element flattened struct described by
10562 // Field1Ty, Field1Off, Field2Ty, Field2Off. This method will create an
10563 // appropriate coerceToType and unpaddedCoerceToType.
10564 ABIArgInfo RISCVABIInfo::coerceAndExpandFPCCEligibleStruct(
10565     llvm::Type *Field1Ty, CharUnits Field1Off, llvm::Type *Field2Ty,
10566     CharUnits Field2Off) const {
10567   SmallVector<llvm::Type *, 3> CoerceElts;
10568   SmallVector<llvm::Type *, 2> UnpaddedCoerceElts;
10569   if (!Field1Off.isZero())
10570     CoerceElts.push_back(llvm::ArrayType::get(
10571         llvm::Type::getInt8Ty(getVMContext()), Field1Off.getQuantity()));
10572 
10573   CoerceElts.push_back(Field1Ty);
10574   UnpaddedCoerceElts.push_back(Field1Ty);
10575 
10576   if (!Field2Ty) {
10577     return ABIArgInfo::getCoerceAndExpand(
10578         llvm::StructType::get(getVMContext(), CoerceElts, !Field1Off.isZero()),
10579         UnpaddedCoerceElts[0]);
10580   }
10581 
10582   CharUnits Field2Align =
10583       CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(Field2Ty));
10584   CharUnits Field1End = Field1Off +
10585       CharUnits::fromQuantity(getDataLayout().getTypeStoreSize(Field1Ty));
10586   CharUnits Field2OffNoPadNoPack = Field1End.alignTo(Field2Align);
10587 
10588   CharUnits Padding = CharUnits::Zero();
10589   if (Field2Off > Field2OffNoPadNoPack)
10590     Padding = Field2Off - Field2OffNoPadNoPack;
10591   else if (Field2Off != Field2Align && Field2Off > Field1End)
10592     Padding = Field2Off - Field1End;
10593 
10594   bool IsPacked = !Field2Off.isMultipleOf(Field2Align);
10595 
10596   if (!Padding.isZero())
10597     CoerceElts.push_back(llvm::ArrayType::get(
10598         llvm::Type::getInt8Ty(getVMContext()), Padding.getQuantity()));
10599 
10600   CoerceElts.push_back(Field2Ty);
10601   UnpaddedCoerceElts.push_back(Field2Ty);
10602 
10603   auto CoerceToType =
10604       llvm::StructType::get(getVMContext(), CoerceElts, IsPacked);
10605   auto UnpaddedCoerceToType =
10606       llvm::StructType::get(getVMContext(), UnpaddedCoerceElts, IsPacked);
10607 
10608   return ABIArgInfo::getCoerceAndExpand(CoerceToType, UnpaddedCoerceToType);
10609 }
10610 
10611 ABIArgInfo RISCVABIInfo::classifyArgumentType(QualType Ty, bool IsFixed,
10612                                               int &ArgGPRsLeft,
10613                                               int &ArgFPRsLeft) const {
10614   assert(ArgGPRsLeft <= NumArgGPRs && "Arg GPR tracking underflow");
10615   Ty = useFirstFieldIfTransparentUnion(Ty);
10616 
10617   // Structures with either a non-trivial destructor or a non-trivial
10618   // copy constructor are always passed indirectly.
10619   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
10620     if (ArgGPRsLeft)
10621       ArgGPRsLeft -= 1;
10622     return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA ==
10623                                            CGCXXABI::RAA_DirectInMemory);
10624   }
10625 
10626   // Ignore empty structs/unions.
10627   if (isEmptyRecord(getContext(), Ty, true))
10628     return ABIArgInfo::getIgnore();
10629 
10630   uint64_t Size = getContext().getTypeSize(Ty);
10631 
10632   // Pass floating point values via FPRs if possible.
10633   if (IsFixed && Ty->isFloatingType() && !Ty->isComplexType() &&
10634       FLen >= Size && ArgFPRsLeft) {
10635     ArgFPRsLeft--;
10636     return ABIArgInfo::getDirect();
10637   }
10638 
10639   // Complex types for the hard float ABI must be passed direct rather than
10640   // using CoerceAndExpand.
10641   if (IsFixed && Ty->isComplexType() && FLen && ArgFPRsLeft >= 2) {
10642     QualType EltTy = Ty->castAs<ComplexType>()->getElementType();
10643     if (getContext().getTypeSize(EltTy) <= FLen) {
10644       ArgFPRsLeft -= 2;
10645       return ABIArgInfo::getDirect();
10646     }
10647   }
10648 
10649   if (IsFixed && FLen && Ty->isStructureOrClassType()) {
10650     llvm::Type *Field1Ty = nullptr;
10651     llvm::Type *Field2Ty = nullptr;
10652     CharUnits Field1Off = CharUnits::Zero();
10653     CharUnits Field2Off = CharUnits::Zero();
10654     int NeededArgGPRs;
10655     int NeededArgFPRs;
10656     bool IsCandidate =
10657         detectFPCCEligibleStruct(Ty, Field1Ty, Field1Off, Field2Ty, Field2Off,
10658                                  NeededArgGPRs, NeededArgFPRs);
10659     if (IsCandidate && NeededArgGPRs <= ArgGPRsLeft &&
10660         NeededArgFPRs <= ArgFPRsLeft) {
10661       ArgGPRsLeft -= NeededArgGPRs;
10662       ArgFPRsLeft -= NeededArgFPRs;
10663       return coerceAndExpandFPCCEligibleStruct(Field1Ty, Field1Off, Field2Ty,
10664                                                Field2Off);
10665     }
10666   }
10667 
10668   uint64_t NeededAlign = getContext().getTypeAlign(Ty);
10669   bool MustUseStack = false;
10670   // Determine the number of GPRs needed to pass the current argument
10671   // according to the ABI. 2*XLen-aligned varargs are passed in "aligned"
10672   // register pairs, so may consume 3 registers.
10673   int NeededArgGPRs = 1;
10674   if (!IsFixed && NeededAlign == 2 * XLen)
10675     NeededArgGPRs = 2 + (ArgGPRsLeft % 2);
10676   else if (Size > XLen && Size <= 2 * XLen)
10677     NeededArgGPRs = 2;
10678 
10679   if (NeededArgGPRs > ArgGPRsLeft) {
10680     MustUseStack = true;
10681     NeededArgGPRs = ArgGPRsLeft;
10682   }
10683 
10684   ArgGPRsLeft -= NeededArgGPRs;
10685 
10686   if (!isAggregateTypeForABI(Ty) && !Ty->isVectorType()) {
10687     // Treat an enum type as its underlying type.
10688     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
10689       Ty = EnumTy->getDecl()->getIntegerType();
10690 
10691     // All integral types are promoted to XLen width, unless passed on the
10692     // stack.
10693     if (Size < XLen && Ty->isIntegralOrEnumerationType() && !MustUseStack) {
10694       return extendType(Ty);
10695     }
10696 
10697     if (const auto *EIT = Ty->getAs<ExtIntType>()) {
10698       if (EIT->getNumBits() < XLen && !MustUseStack)
10699         return extendType(Ty);
10700       if (EIT->getNumBits() > 128 ||
10701           (!getContext().getTargetInfo().hasInt128Type() &&
10702            EIT->getNumBits() > 64))
10703         return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
10704     }
10705 
10706     return ABIArgInfo::getDirect();
10707   }
10708 
10709   // Aggregates which are <= 2*XLen will be passed in registers if possible,
10710   // so coerce to integers.
10711   if (Size <= 2 * XLen) {
10712     unsigned Alignment = getContext().getTypeAlign(Ty);
10713 
10714     // Use a single XLen int if possible, 2*XLen if 2*XLen alignment is
10715     // required, and a 2-element XLen array if only XLen alignment is required.
10716     if (Size <= XLen) {
10717       return ABIArgInfo::getDirect(
10718           llvm::IntegerType::get(getVMContext(), XLen));
10719     } else if (Alignment == 2 * XLen) {
10720       return ABIArgInfo::getDirect(
10721           llvm::IntegerType::get(getVMContext(), 2 * XLen));
10722     } else {
10723       return ABIArgInfo::getDirect(llvm::ArrayType::get(
10724           llvm::IntegerType::get(getVMContext(), XLen), 2));
10725     }
10726   }
10727   return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
10728 }
10729 
10730 ABIArgInfo RISCVABIInfo::classifyReturnType(QualType RetTy) const {
10731   if (RetTy->isVoidType())
10732     return ABIArgInfo::getIgnore();
10733 
10734   int ArgGPRsLeft = 2;
10735   int ArgFPRsLeft = FLen ? 2 : 0;
10736 
10737   // The rules for return and argument types are the same, so defer to
10738   // classifyArgumentType.
10739   return classifyArgumentType(RetTy, /*IsFixed=*/true, ArgGPRsLeft,
10740                               ArgFPRsLeft);
10741 }
10742 
10743 Address RISCVABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
10744                                 QualType Ty) const {
10745   CharUnits SlotSize = CharUnits::fromQuantity(XLen / 8);
10746 
10747   // Empty records are ignored for parameter passing purposes.
10748   if (isEmptyRecord(getContext(), Ty, true)) {
10749     Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize);
10750     Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
10751     return Addr;
10752   }
10753 
10754   auto TInfo = getContext().getTypeInfoInChars(Ty);
10755 
10756   // Arguments bigger than 2*Xlen bytes are passed indirectly.
10757   bool IsIndirect = TInfo.Width > 2 * SlotSize;
10758 
10759   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TInfo,
10760                           SlotSize, /*AllowHigherAlign=*/true);
10761 }
10762 
10763 ABIArgInfo RISCVABIInfo::extendType(QualType Ty) const {
10764   int TySize = getContext().getTypeSize(Ty);
10765   // RV64 ABI requires unsigned 32 bit integers to be sign extended.
10766   if (XLen == 64 && Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
10767     return ABIArgInfo::getSignExtend(Ty);
10768   return ABIArgInfo::getExtend(Ty);
10769 }
10770 
10771 namespace {
10772 class RISCVTargetCodeGenInfo : public TargetCodeGenInfo {
10773 public:
10774   RISCVTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, unsigned XLen,
10775                          unsigned FLen)
10776       : TargetCodeGenInfo(std::make_unique<RISCVABIInfo>(CGT, XLen, FLen)) {}
10777 
10778   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
10779                            CodeGen::CodeGenModule &CGM) const override {
10780     const auto *FD = dyn_cast_or_null<FunctionDecl>(D);
10781     if (!FD) return;
10782 
10783     const auto *Attr = FD->getAttr<RISCVInterruptAttr>();
10784     if (!Attr)
10785       return;
10786 
10787     const char *Kind;
10788     switch (Attr->getInterrupt()) {
10789     case RISCVInterruptAttr::user: Kind = "user"; break;
10790     case RISCVInterruptAttr::supervisor: Kind = "supervisor"; break;
10791     case RISCVInterruptAttr::machine: Kind = "machine"; break;
10792     }
10793 
10794     auto *Fn = cast<llvm::Function>(GV);
10795 
10796     Fn->addFnAttr("interrupt", Kind);
10797   }
10798 };
10799 } // namespace
10800 
10801 //===----------------------------------------------------------------------===//
10802 // VE ABI Implementation.
10803 //
10804 namespace {
10805 class VEABIInfo : public DefaultABIInfo {
10806 public:
10807   VEABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
10808 
10809 private:
10810   ABIArgInfo classifyReturnType(QualType RetTy) const;
10811   ABIArgInfo classifyArgumentType(QualType RetTy) const;
10812   void computeInfo(CGFunctionInfo &FI) const override;
10813 };
10814 } // end anonymous namespace
10815 
10816 ABIArgInfo VEABIInfo::classifyReturnType(QualType Ty) const {
10817   if (Ty->isAnyComplexType())
10818     return ABIArgInfo::getDirect();
10819   uint64_t Size = getContext().getTypeSize(Ty);
10820   if (Size < 64 && Ty->isIntegerType())
10821     return ABIArgInfo::getExtend(Ty);
10822   return DefaultABIInfo::classifyReturnType(Ty);
10823 }
10824 
10825 ABIArgInfo VEABIInfo::classifyArgumentType(QualType Ty) const {
10826   if (Ty->isAnyComplexType())
10827     return ABIArgInfo::getDirect();
10828   uint64_t Size = getContext().getTypeSize(Ty);
10829   if (Size < 64 && Ty->isIntegerType())
10830     return ABIArgInfo::getExtend(Ty);
10831   return DefaultABIInfo::classifyArgumentType(Ty);
10832 }
10833 
10834 void VEABIInfo::computeInfo(CGFunctionInfo &FI) const {
10835   FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
10836   for (auto &Arg : FI.arguments())
10837     Arg.info = classifyArgumentType(Arg.type);
10838 }
10839 
10840 namespace {
10841 class VETargetCodeGenInfo : public TargetCodeGenInfo {
10842 public:
10843   VETargetCodeGenInfo(CodeGenTypes &CGT)
10844       : TargetCodeGenInfo(std::make_unique<VEABIInfo>(CGT)) {}
10845   // VE ABI requires the arguments of variadic and prototype-less functions
10846   // are passed in both registers and memory.
10847   bool isNoProtoCallVariadic(const CallArgList &args,
10848                              const FunctionNoProtoType *fnType) const override {
10849     return true;
10850   }
10851 };
10852 } // end anonymous namespace
10853 
10854 //===----------------------------------------------------------------------===//
10855 // Driver code
10856 //===----------------------------------------------------------------------===//
10857 
10858 bool CodeGenModule::supportsCOMDAT() const {
10859   return getTriple().supportsCOMDAT();
10860 }
10861 
10862 const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
10863   if (TheTargetCodeGenInfo)
10864     return *TheTargetCodeGenInfo;
10865 
10866   // Helper to set the unique_ptr while still keeping the return value.
10867   auto SetCGInfo = [&](TargetCodeGenInfo *P) -> const TargetCodeGenInfo & {
10868     this->TheTargetCodeGenInfo.reset(P);
10869     return *P;
10870   };
10871 
10872   const llvm::Triple &Triple = getTarget().getTriple();
10873   switch (Triple.getArch()) {
10874   default:
10875     return SetCGInfo(new DefaultTargetCodeGenInfo(Types));
10876 
10877   case llvm::Triple::le32:
10878     return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
10879   case llvm::Triple::mips:
10880   case llvm::Triple::mipsel:
10881     if (Triple.getOS() == llvm::Triple::NaCl)
10882       return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
10883     return SetCGInfo(new MIPSTargetCodeGenInfo(Types, true));
10884 
10885   case llvm::Triple::mips64:
10886   case llvm::Triple::mips64el:
10887     return SetCGInfo(new MIPSTargetCodeGenInfo(Types, false));
10888 
10889   case llvm::Triple::avr:
10890     return SetCGInfo(new AVRTargetCodeGenInfo(Types));
10891 
10892   case llvm::Triple::aarch64:
10893   case llvm::Triple::aarch64_32:
10894   case llvm::Triple::aarch64_be: {
10895     AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS;
10896     if (getTarget().getABI() == "darwinpcs")
10897       Kind = AArch64ABIInfo::DarwinPCS;
10898     else if (Triple.isOSWindows())
10899       return SetCGInfo(
10900           new WindowsAArch64TargetCodeGenInfo(Types, AArch64ABIInfo::Win64));
10901 
10902     return SetCGInfo(new AArch64TargetCodeGenInfo(Types, Kind));
10903   }
10904 
10905   case llvm::Triple::wasm32:
10906   case llvm::Triple::wasm64: {
10907     WebAssemblyABIInfo::ABIKind Kind = WebAssemblyABIInfo::MVP;
10908     if (getTarget().getABI() == "experimental-mv")
10909       Kind = WebAssemblyABIInfo::ExperimentalMV;
10910     return SetCGInfo(new WebAssemblyTargetCodeGenInfo(Types, Kind));
10911   }
10912 
10913   case llvm::Triple::arm:
10914   case llvm::Triple::armeb:
10915   case llvm::Triple::thumb:
10916   case llvm::Triple::thumbeb: {
10917     if (Triple.getOS() == llvm::Triple::Win32) {
10918       return SetCGInfo(
10919           new WindowsARMTargetCodeGenInfo(Types, ARMABIInfo::AAPCS_VFP));
10920     }
10921 
10922     ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
10923     StringRef ABIStr = getTarget().getABI();
10924     if (ABIStr == "apcs-gnu")
10925       Kind = ARMABIInfo::APCS;
10926     else if (ABIStr == "aapcs16")
10927       Kind = ARMABIInfo::AAPCS16_VFP;
10928     else if (CodeGenOpts.FloatABI == "hard" ||
10929              (CodeGenOpts.FloatABI != "soft" &&
10930               (Triple.getEnvironment() == llvm::Triple::GNUEABIHF ||
10931                Triple.getEnvironment() == llvm::Triple::MuslEABIHF ||
10932                Triple.getEnvironment() == llvm::Triple::EABIHF)))
10933       Kind = ARMABIInfo::AAPCS_VFP;
10934 
10935     return SetCGInfo(new ARMTargetCodeGenInfo(Types, Kind));
10936   }
10937 
10938   case llvm::Triple::ppc: {
10939     if (Triple.isOSAIX())
10940       return SetCGInfo(new AIXTargetCodeGenInfo(Types, /*Is64Bit*/ false));
10941 
10942     bool IsSoftFloat =
10943         CodeGenOpts.FloatABI == "soft" || getTarget().hasFeature("spe");
10944     bool RetSmallStructInRegABI =
10945         PPC32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
10946     return SetCGInfo(
10947         new PPC32TargetCodeGenInfo(Types, IsSoftFloat, RetSmallStructInRegABI));
10948   }
10949   case llvm::Triple::ppcle: {
10950     bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
10951     bool RetSmallStructInRegABI =
10952         PPC32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
10953     return SetCGInfo(
10954         new PPC32TargetCodeGenInfo(Types, IsSoftFloat, RetSmallStructInRegABI));
10955   }
10956   case llvm::Triple::ppc64:
10957     if (Triple.isOSAIX())
10958       return SetCGInfo(new AIXTargetCodeGenInfo(Types, /*Is64Bit*/ true));
10959 
10960     if (Triple.isOSBinFormatELF()) {
10961       PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1;
10962       if (getTarget().getABI() == "elfv2")
10963         Kind = PPC64_SVR4_ABIInfo::ELFv2;
10964       bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
10965 
10966       return SetCGInfo(
10967           new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, IsSoftFloat));
10968     }
10969     return SetCGInfo(new PPC64TargetCodeGenInfo(Types));
10970   case llvm::Triple::ppc64le: {
10971     assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
10972     PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2;
10973     if (getTarget().getABI() == "elfv1")
10974       Kind = PPC64_SVR4_ABIInfo::ELFv1;
10975     bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
10976 
10977     return SetCGInfo(
10978         new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, IsSoftFloat));
10979   }
10980 
10981   case llvm::Triple::nvptx:
10982   case llvm::Triple::nvptx64:
10983     return SetCGInfo(new NVPTXTargetCodeGenInfo(Types));
10984 
10985   case llvm::Triple::msp430:
10986     return SetCGInfo(new MSP430TargetCodeGenInfo(Types));
10987 
10988   case llvm::Triple::riscv32:
10989   case llvm::Triple::riscv64: {
10990     StringRef ABIStr = getTarget().getABI();
10991     unsigned XLen = getTarget().getPointerWidth(0);
10992     unsigned ABIFLen = 0;
10993     if (ABIStr.endswith("f"))
10994       ABIFLen = 32;
10995     else if (ABIStr.endswith("d"))
10996       ABIFLen = 64;
10997     return SetCGInfo(new RISCVTargetCodeGenInfo(Types, XLen, ABIFLen));
10998   }
10999 
11000   case llvm::Triple::systemz: {
11001     bool SoftFloat = CodeGenOpts.FloatABI == "soft";
11002     bool HasVector = !SoftFloat && getTarget().getABI() == "vector";
11003     return SetCGInfo(new SystemZTargetCodeGenInfo(Types, HasVector, SoftFloat));
11004   }
11005 
11006   case llvm::Triple::tce:
11007   case llvm::Triple::tcele:
11008     return SetCGInfo(new TCETargetCodeGenInfo(Types));
11009 
11010   case llvm::Triple::x86: {
11011     bool IsDarwinVectorABI = Triple.isOSDarwin();
11012     bool RetSmallStructInRegABI =
11013         X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
11014     bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
11015 
11016     if (Triple.getOS() == llvm::Triple::Win32) {
11017       return SetCGInfo(new WinX86_32TargetCodeGenInfo(
11018           Types, IsDarwinVectorABI, RetSmallStructInRegABI,
11019           IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters));
11020     } else {
11021       return SetCGInfo(new X86_32TargetCodeGenInfo(
11022           Types, IsDarwinVectorABI, RetSmallStructInRegABI,
11023           IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters,
11024           CodeGenOpts.FloatABI == "soft"));
11025     }
11026   }
11027 
11028   case llvm::Triple::x86_64: {
11029     StringRef ABI = getTarget().getABI();
11030     X86AVXABILevel AVXLevel =
11031         (ABI == "avx512"
11032              ? X86AVXABILevel::AVX512
11033              : ABI == "avx" ? X86AVXABILevel::AVX : X86AVXABILevel::None);
11034 
11035     switch (Triple.getOS()) {
11036     case llvm::Triple::Win32:
11037       return SetCGInfo(new WinX86_64TargetCodeGenInfo(Types, AVXLevel));
11038     default:
11039       return SetCGInfo(new X86_64TargetCodeGenInfo(Types, AVXLevel));
11040     }
11041   }
11042   case llvm::Triple::hexagon:
11043     return SetCGInfo(new HexagonTargetCodeGenInfo(Types));
11044   case llvm::Triple::lanai:
11045     return SetCGInfo(new LanaiTargetCodeGenInfo(Types));
11046   case llvm::Triple::r600:
11047     return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
11048   case llvm::Triple::amdgcn:
11049     return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
11050   case llvm::Triple::sparc:
11051     return SetCGInfo(new SparcV8TargetCodeGenInfo(Types));
11052   case llvm::Triple::sparcv9:
11053     return SetCGInfo(new SparcV9TargetCodeGenInfo(Types));
11054   case llvm::Triple::xcore:
11055     return SetCGInfo(new XCoreTargetCodeGenInfo(Types));
11056   case llvm::Triple::arc:
11057     return SetCGInfo(new ARCTargetCodeGenInfo(Types));
11058   case llvm::Triple::spir:
11059   case llvm::Triple::spir64:
11060     return SetCGInfo(new SPIRTargetCodeGenInfo(Types));
11061   case llvm::Triple::ve:
11062     return SetCGInfo(new VETargetCodeGenInfo(Types));
11063   }
11064 }
11065 
11066 /// Create an OpenCL kernel for an enqueued block.
11067 ///
11068 /// The kernel has the same function type as the block invoke function. Its
11069 /// name is the name of the block invoke function postfixed with "_kernel".
11070 /// It simply calls the block invoke function then returns.
11071 llvm::Function *
11072 TargetCodeGenInfo::createEnqueuedBlockKernel(CodeGenFunction &CGF,
11073                                              llvm::Function *Invoke,
11074                                              llvm::Value *BlockLiteral) const {
11075   auto *InvokeFT = Invoke->getFunctionType();
11076   llvm::SmallVector<llvm::Type *, 2> ArgTys;
11077   for (auto &P : InvokeFT->params())
11078     ArgTys.push_back(P);
11079   auto &C = CGF.getLLVMContext();
11080   std::string Name = Invoke->getName().str() + "_kernel";
11081   auto *FT = llvm::FunctionType::get(llvm::Type::getVoidTy(C), ArgTys, false);
11082   auto *F = llvm::Function::Create(FT, llvm::GlobalValue::InternalLinkage, Name,
11083                                    &CGF.CGM.getModule());
11084   auto IP = CGF.Builder.saveIP();
11085   auto *BB = llvm::BasicBlock::Create(C, "entry", F);
11086   auto &Builder = CGF.Builder;
11087   Builder.SetInsertPoint(BB);
11088   llvm::SmallVector<llvm::Value *, 2> Args;
11089   for (auto &A : F->args())
11090     Args.push_back(&A);
11091   llvm::CallInst *call = Builder.CreateCall(Invoke, Args);
11092   call->setCallingConv(Invoke->getCallingConv());
11093   Builder.CreateRetVoid();
11094   Builder.restoreIP(IP);
11095   return F;
11096 }
11097 
11098 /// Create an OpenCL kernel for an enqueued block.
11099 ///
11100 /// The type of the first argument (the block literal) is the struct type
11101 /// of the block literal instead of a pointer type. The first argument
11102 /// (block literal) is passed directly by value to the kernel. The kernel
11103 /// allocates the same type of struct on stack and stores the block literal
11104 /// to it and passes its pointer to the block invoke function. The kernel
11105 /// has "enqueued-block" function attribute and kernel argument metadata.
11106 llvm::Function *AMDGPUTargetCodeGenInfo::createEnqueuedBlockKernel(
11107     CodeGenFunction &CGF, llvm::Function *Invoke,
11108     llvm::Value *BlockLiteral) const {
11109   auto &Builder = CGF.Builder;
11110   auto &C = CGF.getLLVMContext();
11111 
11112   auto *BlockTy = BlockLiteral->getType()->getPointerElementType();
11113   auto *InvokeFT = Invoke->getFunctionType();
11114   llvm::SmallVector<llvm::Type *, 2> ArgTys;
11115   llvm::SmallVector<llvm::Metadata *, 8> AddressQuals;
11116   llvm::SmallVector<llvm::Metadata *, 8> AccessQuals;
11117   llvm::SmallVector<llvm::Metadata *, 8> ArgTypeNames;
11118   llvm::SmallVector<llvm::Metadata *, 8> ArgBaseTypeNames;
11119   llvm::SmallVector<llvm::Metadata *, 8> ArgTypeQuals;
11120   llvm::SmallVector<llvm::Metadata *, 8> ArgNames;
11121 
11122   ArgTys.push_back(BlockTy);
11123   ArgTypeNames.push_back(llvm::MDString::get(C, "__block_literal"));
11124   AddressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(0)));
11125   ArgBaseTypeNames.push_back(llvm::MDString::get(C, "__block_literal"));
11126   ArgTypeQuals.push_back(llvm::MDString::get(C, ""));
11127   AccessQuals.push_back(llvm::MDString::get(C, "none"));
11128   ArgNames.push_back(llvm::MDString::get(C, "block_literal"));
11129   for (unsigned I = 1, E = InvokeFT->getNumParams(); I < E; ++I) {
11130     ArgTys.push_back(InvokeFT->getParamType(I));
11131     ArgTypeNames.push_back(llvm::MDString::get(C, "void*"));
11132     AddressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(3)));
11133     AccessQuals.push_back(llvm::MDString::get(C, "none"));
11134     ArgBaseTypeNames.push_back(llvm::MDString::get(C, "void*"));
11135     ArgTypeQuals.push_back(llvm::MDString::get(C, ""));
11136     ArgNames.push_back(
11137         llvm::MDString::get(C, (Twine("local_arg") + Twine(I)).str()));
11138   }
11139   std::string Name = Invoke->getName().str() + "_kernel";
11140   auto *FT = llvm::FunctionType::get(llvm::Type::getVoidTy(C), ArgTys, false);
11141   auto *F = llvm::Function::Create(FT, llvm::GlobalValue::InternalLinkage, Name,
11142                                    &CGF.CGM.getModule());
11143   F->addFnAttr("enqueued-block");
11144   auto IP = CGF.Builder.saveIP();
11145   auto *BB = llvm::BasicBlock::Create(C, "entry", F);
11146   Builder.SetInsertPoint(BB);
11147   const auto BlockAlign = CGF.CGM.getDataLayout().getPrefTypeAlign(BlockTy);
11148   auto *BlockPtr = Builder.CreateAlloca(BlockTy, nullptr);
11149   BlockPtr->setAlignment(BlockAlign);
11150   Builder.CreateAlignedStore(F->arg_begin(), BlockPtr, BlockAlign);
11151   auto *Cast = Builder.CreatePointerCast(BlockPtr, InvokeFT->getParamType(0));
11152   llvm::SmallVector<llvm::Value *, 2> Args;
11153   Args.push_back(Cast);
11154   for (auto I = F->arg_begin() + 1, E = F->arg_end(); I != E; ++I)
11155     Args.push_back(I);
11156   llvm::CallInst *call = Builder.CreateCall(Invoke, Args);
11157   call->setCallingConv(Invoke->getCallingConv());
11158   Builder.CreateRetVoid();
11159   Builder.restoreIP(IP);
11160 
11161   F->setMetadata("kernel_arg_addr_space", llvm::MDNode::get(C, AddressQuals));
11162   F->setMetadata("kernel_arg_access_qual", llvm::MDNode::get(C, AccessQuals));
11163   F->setMetadata("kernel_arg_type", llvm::MDNode::get(C, ArgTypeNames));
11164   F->setMetadata("kernel_arg_base_type",
11165                  llvm::MDNode::get(C, ArgBaseTypeNames));
11166   F->setMetadata("kernel_arg_type_qual", llvm::MDNode::get(C, ArgTypeQuals));
11167   if (CGF.CGM.getCodeGenOpts().EmitOpenCLArgMetadata)
11168     F->setMetadata("kernel_arg_name", llvm::MDNode::get(C, ArgNames));
11169 
11170   return F;
11171 }
11172