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   if (Ty->isVectorType())
4567     llvm::report_fatal_error(
4568         "vector types are not yet supported for variadic functions on AIX");
4569 
4570   auto TypeInfo = getContext().getTypeInfoInChars(Ty);
4571   TypeInfo.Align = getParamTypeAlignment(Ty);
4572 
4573   CharUnits SlotSize = CharUnits::fromQuantity(PtrByteSize);
4574 
4575   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false, TypeInfo,
4576                           SlotSize, /*AllowHigher*/ true);
4577 }
4578 
4579 bool AIXTargetCodeGenInfo::initDwarfEHRegSizeTable(
4580     CodeGen::CodeGenFunction &CGF, llvm::Value *Address) const {
4581   return PPC_initDwarfEHRegSizeTable(CGF, Address, Is64Bit, /*IsAIX*/ true);
4582 }
4583 
4584 // PowerPC-32
4585 namespace {
4586 /// PPC32_SVR4_ABIInfo - The 32-bit PowerPC ELF (SVR4) ABI information.
4587 class PPC32_SVR4_ABIInfo : public DefaultABIInfo {
4588   bool IsSoftFloatABI;
4589   bool IsRetSmallStructInRegABI;
4590 
4591   CharUnits getParamTypeAlignment(QualType Ty) const;
4592 
4593 public:
4594   PPC32_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, bool SoftFloatABI,
4595                      bool RetSmallStructInRegABI)
4596       : DefaultABIInfo(CGT), IsSoftFloatABI(SoftFloatABI),
4597         IsRetSmallStructInRegABI(RetSmallStructInRegABI) {}
4598 
4599   ABIArgInfo classifyReturnType(QualType RetTy) const;
4600 
4601   void computeInfo(CGFunctionInfo &FI) const override {
4602     if (!getCXXABI().classifyReturnType(FI))
4603       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
4604     for (auto &I : FI.arguments())
4605       I.info = classifyArgumentType(I.type);
4606   }
4607 
4608   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4609                     QualType Ty) const override;
4610 };
4611 
4612 class PPC32TargetCodeGenInfo : public TargetCodeGenInfo {
4613 public:
4614   PPC32TargetCodeGenInfo(CodeGenTypes &CGT, bool SoftFloatABI,
4615                          bool RetSmallStructInRegABI)
4616       : TargetCodeGenInfo(std::make_unique<PPC32_SVR4_ABIInfo>(
4617             CGT, SoftFloatABI, RetSmallStructInRegABI)) {}
4618 
4619   static bool isStructReturnInRegABI(const llvm::Triple &Triple,
4620                                      const CodeGenOptions &Opts);
4621 
4622   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4623     // This is recovered from gcc output.
4624     return 1; // r1 is the dedicated stack pointer
4625   }
4626 
4627   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4628                                llvm::Value *Address) const override;
4629 };
4630 }
4631 
4632 CharUnits PPC32_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const {
4633   // Complex types are passed just like their elements.
4634   if (const ComplexType *CTy = Ty->getAs<ComplexType>())
4635     Ty = CTy->getElementType();
4636 
4637   if (Ty->isVectorType())
4638     return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16
4639                                                                        : 4);
4640 
4641   // For single-element float/vector structs, we consider the whole type
4642   // to have the same alignment requirements as its single element.
4643   const Type *AlignTy = nullptr;
4644   if (const Type *EltType = isSingleElementStruct(Ty, getContext())) {
4645     const BuiltinType *BT = EltType->getAs<BuiltinType>();
4646     if ((EltType->isVectorType() && getContext().getTypeSize(EltType) == 128) ||
4647         (BT && BT->isFloatingPoint()))
4648       AlignTy = EltType;
4649   }
4650 
4651   if (AlignTy)
4652     return CharUnits::fromQuantity(AlignTy->isVectorType() ? 16 : 4);
4653   return CharUnits::fromQuantity(4);
4654 }
4655 
4656 ABIArgInfo PPC32_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
4657   uint64_t Size;
4658 
4659   // -msvr4-struct-return puts small aggregates in GPR3 and GPR4.
4660   if (isAggregateTypeForABI(RetTy) && IsRetSmallStructInRegABI &&
4661       (Size = getContext().getTypeSize(RetTy)) <= 64) {
4662     // System V ABI (1995), page 3-22, specified:
4663     // > A structure or union whose size is less than or equal to 8 bytes
4664     // > shall be returned in r3 and r4, as if it were first stored in the
4665     // > 8-byte aligned memory area and then the low addressed word were
4666     // > loaded into r3 and the high-addressed word into r4.  Bits beyond
4667     // > the last member of the structure or union are not defined.
4668     //
4669     // GCC for big-endian PPC32 inserts the pad before the first member,
4670     // not "beyond the last member" of the struct.  To stay compatible
4671     // with GCC, we coerce the struct to an integer of the same size.
4672     // LLVM will extend it and return i32 in r3, or i64 in r3:r4.
4673     if (Size == 0)
4674       return ABIArgInfo::getIgnore();
4675     else {
4676       llvm::Type *CoerceTy = llvm::Type::getIntNTy(getVMContext(), Size);
4677       return ABIArgInfo::getDirect(CoerceTy);
4678     }
4679   }
4680 
4681   return DefaultABIInfo::classifyReturnType(RetTy);
4682 }
4683 
4684 // TODO: this implementation is now likely redundant with
4685 // DefaultABIInfo::EmitVAArg.
4686 Address PPC32_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAList,
4687                                       QualType Ty) const {
4688   if (getTarget().getTriple().isOSDarwin()) {
4689     auto TI = getContext().getTypeInfoInChars(Ty);
4690     TI.Align = getParamTypeAlignment(Ty);
4691 
4692     CharUnits SlotSize = CharUnits::fromQuantity(4);
4693     return emitVoidPtrVAArg(CGF, VAList, Ty,
4694                             classifyArgumentType(Ty).isIndirect(), TI, SlotSize,
4695                             /*AllowHigherAlign=*/true);
4696   }
4697 
4698   const unsigned OverflowLimit = 8;
4699   if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
4700     // TODO: Implement this. For now ignore.
4701     (void)CTy;
4702     return Address::invalid(); // FIXME?
4703   }
4704 
4705   // struct __va_list_tag {
4706   //   unsigned char gpr;
4707   //   unsigned char fpr;
4708   //   unsigned short reserved;
4709   //   void *overflow_arg_area;
4710   //   void *reg_save_area;
4711   // };
4712 
4713   bool isI64 = Ty->isIntegerType() && getContext().getTypeSize(Ty) == 64;
4714   bool isInt = !Ty->isFloatingType();
4715   bool isF64 = Ty->isFloatingType() && getContext().getTypeSize(Ty) == 64;
4716 
4717   // All aggregates are passed indirectly?  That doesn't seem consistent
4718   // with the argument-lowering code.
4719   bool isIndirect = isAggregateTypeForABI(Ty);
4720 
4721   CGBuilderTy &Builder = CGF.Builder;
4722 
4723   // The calling convention either uses 1-2 GPRs or 1 FPR.
4724   Address NumRegsAddr = Address::invalid();
4725   if (isInt || IsSoftFloatABI) {
4726     NumRegsAddr = Builder.CreateStructGEP(VAList, 0, "gpr");
4727   } else {
4728     NumRegsAddr = Builder.CreateStructGEP(VAList, 1, "fpr");
4729   }
4730 
4731   llvm::Value *NumRegs = Builder.CreateLoad(NumRegsAddr, "numUsedRegs");
4732 
4733   // "Align" the register count when TY is i64.
4734   if (isI64 || (isF64 && IsSoftFloatABI)) {
4735     NumRegs = Builder.CreateAdd(NumRegs, Builder.getInt8(1));
4736     NumRegs = Builder.CreateAnd(NumRegs, Builder.getInt8((uint8_t) ~1U));
4737   }
4738 
4739   llvm::Value *CC =
4740       Builder.CreateICmpULT(NumRegs, Builder.getInt8(OverflowLimit), "cond");
4741 
4742   llvm::BasicBlock *UsingRegs = CGF.createBasicBlock("using_regs");
4743   llvm::BasicBlock *UsingOverflow = CGF.createBasicBlock("using_overflow");
4744   llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
4745 
4746   Builder.CreateCondBr(CC, UsingRegs, UsingOverflow);
4747 
4748   llvm::Type *DirectTy = CGF.ConvertType(Ty);
4749   if (isIndirect) DirectTy = DirectTy->getPointerTo(0);
4750 
4751   // Case 1: consume registers.
4752   Address RegAddr = Address::invalid();
4753   {
4754     CGF.EmitBlock(UsingRegs);
4755 
4756     Address RegSaveAreaPtr = Builder.CreateStructGEP(VAList, 4);
4757     RegAddr = Address(Builder.CreateLoad(RegSaveAreaPtr),
4758                       CharUnits::fromQuantity(8));
4759     assert(RegAddr.getElementType() == CGF.Int8Ty);
4760 
4761     // Floating-point registers start after the general-purpose registers.
4762     if (!(isInt || IsSoftFloatABI)) {
4763       RegAddr = Builder.CreateConstInBoundsByteGEP(RegAddr,
4764                                                    CharUnits::fromQuantity(32));
4765     }
4766 
4767     // Get the address of the saved value by scaling the number of
4768     // registers we've used by the number of
4769     CharUnits RegSize = CharUnits::fromQuantity((isInt || IsSoftFloatABI) ? 4 : 8);
4770     llvm::Value *RegOffset =
4771       Builder.CreateMul(NumRegs, Builder.getInt8(RegSize.getQuantity()));
4772     RegAddr = Address(Builder.CreateInBoundsGEP(CGF.Int8Ty,
4773                                             RegAddr.getPointer(), RegOffset),
4774                       RegAddr.getAlignment().alignmentOfArrayElement(RegSize));
4775     RegAddr = Builder.CreateElementBitCast(RegAddr, DirectTy);
4776 
4777     // Increase the used-register count.
4778     NumRegs =
4779       Builder.CreateAdd(NumRegs,
4780                         Builder.getInt8((isI64 || (isF64 && IsSoftFloatABI)) ? 2 : 1));
4781     Builder.CreateStore(NumRegs, NumRegsAddr);
4782 
4783     CGF.EmitBranch(Cont);
4784   }
4785 
4786   // Case 2: consume space in the overflow area.
4787   Address MemAddr = Address::invalid();
4788   {
4789     CGF.EmitBlock(UsingOverflow);
4790 
4791     Builder.CreateStore(Builder.getInt8(OverflowLimit), NumRegsAddr);
4792 
4793     // Everything in the overflow area is rounded up to a size of at least 4.
4794     CharUnits OverflowAreaAlign = CharUnits::fromQuantity(4);
4795 
4796     CharUnits Size;
4797     if (!isIndirect) {
4798       auto TypeInfo = CGF.getContext().getTypeInfoInChars(Ty);
4799       Size = TypeInfo.Width.alignTo(OverflowAreaAlign);
4800     } else {
4801       Size = CGF.getPointerSize();
4802     }
4803 
4804     Address OverflowAreaAddr = Builder.CreateStructGEP(VAList, 3);
4805     Address OverflowArea(Builder.CreateLoad(OverflowAreaAddr, "argp.cur"),
4806                          OverflowAreaAlign);
4807     // Round up address of argument to alignment
4808     CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
4809     if (Align > OverflowAreaAlign) {
4810       llvm::Value *Ptr = OverflowArea.getPointer();
4811       OverflowArea = Address(emitRoundPointerUpToAlignment(CGF, Ptr, Align),
4812                                                            Align);
4813     }
4814 
4815     MemAddr = Builder.CreateElementBitCast(OverflowArea, DirectTy);
4816 
4817     // Increase the overflow area.
4818     OverflowArea = Builder.CreateConstInBoundsByteGEP(OverflowArea, Size);
4819     Builder.CreateStore(OverflowArea.getPointer(), OverflowAreaAddr);
4820     CGF.EmitBranch(Cont);
4821   }
4822 
4823   CGF.EmitBlock(Cont);
4824 
4825   // Merge the cases with a phi.
4826   Address Result = emitMergePHI(CGF, RegAddr, UsingRegs, MemAddr, UsingOverflow,
4827                                 "vaarg.addr");
4828 
4829   // Load the pointer if the argument was passed indirectly.
4830   if (isIndirect) {
4831     Result = Address(Builder.CreateLoad(Result, "aggr"),
4832                      getContext().getTypeAlignInChars(Ty));
4833   }
4834 
4835   return Result;
4836 }
4837 
4838 bool PPC32TargetCodeGenInfo::isStructReturnInRegABI(
4839     const llvm::Triple &Triple, const CodeGenOptions &Opts) {
4840   assert(Triple.isPPC32());
4841 
4842   switch (Opts.getStructReturnConvention()) {
4843   case CodeGenOptions::SRCK_Default:
4844     break;
4845   case CodeGenOptions::SRCK_OnStack: // -maix-struct-return
4846     return false;
4847   case CodeGenOptions::SRCK_InRegs: // -msvr4-struct-return
4848     return true;
4849   }
4850 
4851   if (Triple.isOSBinFormatELF() && !Triple.isOSLinux())
4852     return true;
4853 
4854   return false;
4855 }
4856 
4857 bool
4858 PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4859                                                 llvm::Value *Address) const {
4860   return PPC_initDwarfEHRegSizeTable(CGF, Address, /*Is64Bit*/ false,
4861                                      /*IsAIX*/ false);
4862 }
4863 
4864 // PowerPC-64
4865 
4866 namespace {
4867 /// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
4868 class PPC64_SVR4_ABIInfo : public SwiftABIInfo {
4869 public:
4870   enum ABIKind {
4871     ELFv1 = 0,
4872     ELFv2
4873   };
4874 
4875 private:
4876   static const unsigned GPRBits = 64;
4877   ABIKind Kind;
4878   bool IsSoftFloatABI;
4879 
4880 public:
4881   PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind,
4882                      bool SoftFloatABI)
4883       : SwiftABIInfo(CGT), Kind(Kind), IsSoftFloatABI(SoftFloatABI) {}
4884 
4885   bool isPromotableTypeForABI(QualType Ty) const;
4886   CharUnits getParamTypeAlignment(QualType Ty) const;
4887 
4888   ABIArgInfo classifyReturnType(QualType RetTy) const;
4889   ABIArgInfo classifyArgumentType(QualType Ty) const;
4890 
4891   bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4892   bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4893                                          uint64_t Members) const override;
4894 
4895   // TODO: We can add more logic to computeInfo to improve performance.
4896   // Example: For aggregate arguments that fit in a register, we could
4897   // use getDirectInReg (as is done below for structs containing a single
4898   // floating-point value) to avoid pushing them to memory on function
4899   // entry.  This would require changing the logic in PPCISelLowering
4900   // when lowering the parameters in the caller and args in the callee.
4901   void computeInfo(CGFunctionInfo &FI) const override {
4902     if (!getCXXABI().classifyReturnType(FI))
4903       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
4904     for (auto &I : FI.arguments()) {
4905       // We rely on the default argument classification for the most part.
4906       // One exception:  An aggregate containing a single floating-point
4907       // or vector item must be passed in a register if one is available.
4908       const Type *T = isSingleElementStruct(I.type, getContext());
4909       if (T) {
4910         const BuiltinType *BT = T->getAs<BuiltinType>();
4911         if ((T->isVectorType() && getContext().getTypeSize(T) == 128) ||
4912             (BT && BT->isFloatingPoint())) {
4913           QualType QT(T, 0);
4914           I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
4915           continue;
4916         }
4917       }
4918       I.info = classifyArgumentType(I.type);
4919     }
4920   }
4921 
4922   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4923                     QualType Ty) const override;
4924 
4925   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
4926                                     bool asReturnValue) const override {
4927     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
4928   }
4929 
4930   bool isSwiftErrorInRegister() const override {
4931     return false;
4932   }
4933 };
4934 
4935 class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
4936 
4937 public:
4938   PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT,
4939                                PPC64_SVR4_ABIInfo::ABIKind Kind,
4940                                bool SoftFloatABI)
4941       : TargetCodeGenInfo(
4942             std::make_unique<PPC64_SVR4_ABIInfo>(CGT, Kind, SoftFloatABI)) {}
4943 
4944   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4945     // This is recovered from gcc output.
4946     return 1; // r1 is the dedicated stack pointer
4947   }
4948 
4949   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4950                                llvm::Value *Address) const override;
4951 };
4952 
4953 class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
4954 public:
4955   PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
4956 
4957   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4958     // This is recovered from gcc output.
4959     return 1; // r1 is the dedicated stack pointer
4960   }
4961 
4962   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4963                                llvm::Value *Address) const override;
4964 };
4965 
4966 }
4967 
4968 // Return true if the ABI requires Ty to be passed sign- or zero-
4969 // extended to 64 bits.
4970 bool
4971 PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
4972   // Treat an enum type as its underlying type.
4973   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4974     Ty = EnumTy->getDecl()->getIntegerType();
4975 
4976   // Promotable integer types are required to be promoted by the ABI.
4977   if (isPromotableIntegerTypeForABI(Ty))
4978     return true;
4979 
4980   // In addition to the usual promotable integer types, we also need to
4981   // extend all 32-bit types, since the ABI requires promotion to 64 bits.
4982   if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
4983     switch (BT->getKind()) {
4984     case BuiltinType::Int:
4985     case BuiltinType::UInt:
4986       return true;
4987     default:
4988       break;
4989     }
4990 
4991   if (const auto *EIT = Ty->getAs<ExtIntType>())
4992     if (EIT->getNumBits() < 64)
4993       return true;
4994 
4995   return false;
4996 }
4997 
4998 /// isAlignedParamType - Determine whether a type requires 16-byte or
4999 /// higher alignment in the parameter area.  Always returns at least 8.
5000 CharUnits PPC64_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const {
5001   // Complex types are passed just like their elements.
5002   if (const ComplexType *CTy = Ty->getAs<ComplexType>())
5003     Ty = CTy->getElementType();
5004 
5005   // Only vector types of size 16 bytes need alignment (larger types are
5006   // passed via reference, smaller types are not aligned).
5007   if (Ty->isVectorType()) {
5008     return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16 : 8);
5009   } else if (Ty->isRealFloatingType() &&
5010              &getContext().getFloatTypeSemantics(Ty) ==
5011                  &llvm::APFloat::IEEEquad()) {
5012     // According to ABI document section 'Optional Save Areas': If extended
5013     // precision floating-point values in IEEE BINARY 128 QUADRUPLE PRECISION
5014     // format are supported, map them to a single quadword, quadword aligned.
5015     return CharUnits::fromQuantity(16);
5016   }
5017 
5018   // For single-element float/vector structs, we consider the whole type
5019   // to have the same alignment requirements as its single element.
5020   const Type *AlignAsType = nullptr;
5021   const Type *EltType = isSingleElementStruct(Ty, getContext());
5022   if (EltType) {
5023     const BuiltinType *BT = EltType->getAs<BuiltinType>();
5024     if ((EltType->isVectorType() && getContext().getTypeSize(EltType) == 128) ||
5025         (BT && BT->isFloatingPoint()))
5026       AlignAsType = EltType;
5027   }
5028 
5029   // Likewise for ELFv2 homogeneous aggregates.
5030   const Type *Base = nullptr;
5031   uint64_t Members = 0;
5032   if (!AlignAsType && Kind == ELFv2 &&
5033       isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members))
5034     AlignAsType = Base;
5035 
5036   // With special case aggregates, only vector base types need alignment.
5037   if (AlignAsType) {
5038     return CharUnits::fromQuantity(AlignAsType->isVectorType() ? 16 : 8);
5039   }
5040 
5041   // Otherwise, we only need alignment for any aggregate type that
5042   // has an alignment requirement of >= 16 bytes.
5043   if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128) {
5044     return CharUnits::fromQuantity(16);
5045   }
5046 
5047   return CharUnits::fromQuantity(8);
5048 }
5049 
5050 /// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous
5051 /// aggregate.  Base is set to the base element type, and Members is set
5052 /// to the number of base elements.
5053 bool ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base,
5054                                      uint64_t &Members) const {
5055   if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
5056     uint64_t NElements = AT->getSize().getZExtValue();
5057     if (NElements == 0)
5058       return false;
5059     if (!isHomogeneousAggregate(AT->getElementType(), Base, Members))
5060       return false;
5061     Members *= NElements;
5062   } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
5063     const RecordDecl *RD = RT->getDecl();
5064     if (RD->hasFlexibleArrayMember())
5065       return false;
5066 
5067     Members = 0;
5068 
5069     // If this is a C++ record, check the properties of the record such as
5070     // bases and ABI specific restrictions
5071     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
5072       if (!getCXXABI().isPermittedToBeHomogeneousAggregate(CXXRD))
5073         return false;
5074 
5075       for (const auto &I : CXXRD->bases()) {
5076         // Ignore empty records.
5077         if (isEmptyRecord(getContext(), I.getType(), true))
5078           continue;
5079 
5080         uint64_t FldMembers;
5081         if (!isHomogeneousAggregate(I.getType(), Base, FldMembers))
5082           return false;
5083 
5084         Members += FldMembers;
5085       }
5086     }
5087 
5088     for (const auto *FD : RD->fields()) {
5089       // Ignore (non-zero arrays of) empty records.
5090       QualType FT = FD->getType();
5091       while (const ConstantArrayType *AT =
5092              getContext().getAsConstantArrayType(FT)) {
5093         if (AT->getSize().getZExtValue() == 0)
5094           return false;
5095         FT = AT->getElementType();
5096       }
5097       if (isEmptyRecord(getContext(), FT, true))
5098         continue;
5099 
5100       // For compatibility with GCC, ignore empty bitfields in C++ mode.
5101       if (getContext().getLangOpts().CPlusPlus &&
5102           FD->isZeroLengthBitField(getContext()))
5103         continue;
5104 
5105       uint64_t FldMembers;
5106       if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers))
5107         return false;
5108 
5109       Members = (RD->isUnion() ?
5110                  std::max(Members, FldMembers) : Members + FldMembers);
5111     }
5112 
5113     if (!Base)
5114       return false;
5115 
5116     // Ensure there is no padding.
5117     if (getContext().getTypeSize(Base) * Members !=
5118         getContext().getTypeSize(Ty))
5119       return false;
5120   } else {
5121     Members = 1;
5122     if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
5123       Members = 2;
5124       Ty = CT->getElementType();
5125     }
5126 
5127     // Most ABIs only support float, double, and some vector type widths.
5128     if (!isHomogeneousAggregateBaseType(Ty))
5129       return false;
5130 
5131     // The base type must be the same for all members.  Types that
5132     // agree in both total size and mode (float vs. vector) are
5133     // treated as being equivalent here.
5134     const Type *TyPtr = Ty.getTypePtr();
5135     if (!Base) {
5136       Base = TyPtr;
5137       // If it's a non-power-of-2 vector, its size is already a power-of-2,
5138       // so make sure to widen it explicitly.
5139       if (const VectorType *VT = Base->getAs<VectorType>()) {
5140         QualType EltTy = VT->getElementType();
5141         unsigned NumElements =
5142             getContext().getTypeSize(VT) / getContext().getTypeSize(EltTy);
5143         Base = getContext()
5144                    .getVectorType(EltTy, NumElements, VT->getVectorKind())
5145                    .getTypePtr();
5146       }
5147     }
5148 
5149     if (Base->isVectorType() != TyPtr->isVectorType() ||
5150         getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr))
5151       return false;
5152   }
5153   return Members > 0 && isHomogeneousAggregateSmallEnough(Base, Members);
5154 }
5155 
5156 bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
5157   // Homogeneous aggregates for ELFv2 must have base types of float,
5158   // double, long double, or 128-bit vectors.
5159   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
5160     if (BT->getKind() == BuiltinType::Float ||
5161         BT->getKind() == BuiltinType::Double ||
5162         BT->getKind() == BuiltinType::LongDouble ||
5163         (getContext().getTargetInfo().hasFloat128Type() &&
5164           (BT->getKind() == BuiltinType::Float128))) {
5165       if (IsSoftFloatABI)
5166         return false;
5167       return true;
5168     }
5169   }
5170   if (const VectorType *VT = Ty->getAs<VectorType>()) {
5171     if (getContext().getTypeSize(VT) == 128)
5172       return true;
5173   }
5174   return false;
5175 }
5176 
5177 bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateSmallEnough(
5178     const Type *Base, uint64_t Members) const {
5179   // Vector and fp128 types require one register, other floating point types
5180   // require one or two registers depending on their size.
5181   uint32_t NumRegs =
5182       ((getContext().getTargetInfo().hasFloat128Type() &&
5183           Base->isFloat128Type()) ||
5184         Base->isVectorType()) ? 1
5185                               : (getContext().getTypeSize(Base) + 63) / 64;
5186 
5187   // Homogeneous Aggregates may occupy at most 8 registers.
5188   return Members * NumRegs <= 8;
5189 }
5190 
5191 ABIArgInfo
5192 PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
5193   Ty = useFirstFieldIfTransparentUnion(Ty);
5194 
5195   if (Ty->isAnyComplexType())
5196     return ABIArgInfo::getDirect();
5197 
5198   // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes)
5199   // or via reference (larger than 16 bytes).
5200   if (Ty->isVectorType()) {
5201     uint64_t Size = getContext().getTypeSize(Ty);
5202     if (Size > 128)
5203       return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
5204     else if (Size < 128) {
5205       llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
5206       return ABIArgInfo::getDirect(CoerceTy);
5207     }
5208   }
5209 
5210   if (const auto *EIT = Ty->getAs<ExtIntType>())
5211     if (EIT->getNumBits() > 128)
5212       return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
5213 
5214   if (isAggregateTypeForABI(Ty)) {
5215     if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
5216       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
5217 
5218     uint64_t ABIAlign = getParamTypeAlignment(Ty).getQuantity();
5219     uint64_t TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity();
5220 
5221     // ELFv2 homogeneous aggregates are passed as array types.
5222     const Type *Base = nullptr;
5223     uint64_t Members = 0;
5224     if (Kind == ELFv2 &&
5225         isHomogeneousAggregate(Ty, Base, Members)) {
5226       llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
5227       llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
5228       return ABIArgInfo::getDirect(CoerceTy);
5229     }
5230 
5231     // If an aggregate may end up fully in registers, we do not
5232     // use the ByVal method, but pass the aggregate as array.
5233     // This is usually beneficial since we avoid forcing the
5234     // back-end to store the argument to memory.
5235     uint64_t Bits = getContext().getTypeSize(Ty);
5236     if (Bits > 0 && Bits <= 8 * GPRBits) {
5237       llvm::Type *CoerceTy;
5238 
5239       // Types up to 8 bytes are passed as integer type (which will be
5240       // properly aligned in the argument save area doubleword).
5241       if (Bits <= GPRBits)
5242         CoerceTy =
5243             llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
5244       // Larger types are passed as arrays, with the base type selected
5245       // according to the required alignment in the save area.
5246       else {
5247         uint64_t RegBits = ABIAlign * 8;
5248         uint64_t NumRegs = llvm::alignTo(Bits, RegBits) / RegBits;
5249         llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits);
5250         CoerceTy = llvm::ArrayType::get(RegTy, NumRegs);
5251       }
5252 
5253       return ABIArgInfo::getDirect(CoerceTy);
5254     }
5255 
5256     // All other aggregates are passed ByVal.
5257     return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
5258                                    /*ByVal=*/true,
5259                                    /*Realign=*/TyAlign > ABIAlign);
5260   }
5261 
5262   return (isPromotableTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
5263                                      : ABIArgInfo::getDirect());
5264 }
5265 
5266 ABIArgInfo
5267 PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
5268   if (RetTy->isVoidType())
5269     return ABIArgInfo::getIgnore();
5270 
5271   if (RetTy->isAnyComplexType())
5272     return ABIArgInfo::getDirect();
5273 
5274   // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes)
5275   // or via reference (larger than 16 bytes).
5276   if (RetTy->isVectorType()) {
5277     uint64_t Size = getContext().getTypeSize(RetTy);
5278     if (Size > 128)
5279       return getNaturalAlignIndirect(RetTy);
5280     else if (Size < 128) {
5281       llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
5282       return ABIArgInfo::getDirect(CoerceTy);
5283     }
5284   }
5285 
5286   if (const auto *EIT = RetTy->getAs<ExtIntType>())
5287     if (EIT->getNumBits() > 128)
5288       return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
5289 
5290   if (isAggregateTypeForABI(RetTy)) {
5291     // ELFv2 homogeneous aggregates are returned as array types.
5292     const Type *Base = nullptr;
5293     uint64_t Members = 0;
5294     if (Kind == ELFv2 &&
5295         isHomogeneousAggregate(RetTy, Base, Members)) {
5296       llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
5297       llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
5298       return ABIArgInfo::getDirect(CoerceTy);
5299     }
5300 
5301     // ELFv2 small aggregates are returned in up to two registers.
5302     uint64_t Bits = getContext().getTypeSize(RetTy);
5303     if (Kind == ELFv2 && Bits <= 2 * GPRBits) {
5304       if (Bits == 0)
5305         return ABIArgInfo::getIgnore();
5306 
5307       llvm::Type *CoerceTy;
5308       if (Bits > GPRBits) {
5309         CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits);
5310         CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy);
5311       } else
5312         CoerceTy =
5313             llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
5314       return ABIArgInfo::getDirect(CoerceTy);
5315     }
5316 
5317     // All other aggregates are returned indirectly.
5318     return getNaturalAlignIndirect(RetTy);
5319   }
5320 
5321   return (isPromotableTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
5322                                         : ABIArgInfo::getDirect());
5323 }
5324 
5325 // Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
5326 Address PPC64_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5327                                       QualType Ty) const {
5328   auto TypeInfo = getContext().getTypeInfoInChars(Ty);
5329   TypeInfo.Align = getParamTypeAlignment(Ty);
5330 
5331   CharUnits SlotSize = CharUnits::fromQuantity(8);
5332 
5333   // If we have a complex type and the base type is smaller than 8 bytes,
5334   // the ABI calls for the real and imaginary parts to be right-adjusted
5335   // in separate doublewords.  However, Clang expects us to produce a
5336   // pointer to a structure with the two parts packed tightly.  So generate
5337   // loads of the real and imaginary parts relative to the va_list pointer,
5338   // and store them to a temporary structure.
5339   if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
5340     CharUnits EltSize = TypeInfo.Width / 2;
5341     if (EltSize < SlotSize) {
5342       Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, CGF.Int8Ty,
5343                                             SlotSize * 2, SlotSize,
5344                                             SlotSize, /*AllowHigher*/ true);
5345 
5346       Address RealAddr = Addr;
5347       Address ImagAddr = RealAddr;
5348       if (CGF.CGM.getDataLayout().isBigEndian()) {
5349         RealAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr,
5350                                                           SlotSize - EltSize);
5351         ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(ImagAddr,
5352                                                       2 * SlotSize - EltSize);
5353       } else {
5354         ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, SlotSize);
5355       }
5356 
5357       llvm::Type *EltTy = CGF.ConvertTypeForMem(CTy->getElementType());
5358       RealAddr = CGF.Builder.CreateElementBitCast(RealAddr, EltTy);
5359       ImagAddr = CGF.Builder.CreateElementBitCast(ImagAddr, EltTy);
5360       llvm::Value *Real = CGF.Builder.CreateLoad(RealAddr, ".vareal");
5361       llvm::Value *Imag = CGF.Builder.CreateLoad(ImagAddr, ".vaimag");
5362 
5363       Address Temp = CGF.CreateMemTemp(Ty, "vacplx");
5364       CGF.EmitStoreOfComplex({Real, Imag}, CGF.MakeAddrLValue(Temp, Ty),
5365                              /*init*/ true);
5366       return Temp;
5367     }
5368   }
5369 
5370   // Otherwise, just use the general rule.
5371   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
5372                           TypeInfo, SlotSize, /*AllowHigher*/ true);
5373 }
5374 
5375 bool
5376 PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
5377   CodeGen::CodeGenFunction &CGF,
5378   llvm::Value *Address) const {
5379   return PPC_initDwarfEHRegSizeTable(CGF, Address, /*Is64Bit*/ true,
5380                                      /*IsAIX*/ false);
5381 }
5382 
5383 bool
5384 PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
5385                                                 llvm::Value *Address) const {
5386   return PPC_initDwarfEHRegSizeTable(CGF, Address, /*Is64Bit*/ true,
5387                                      /*IsAIX*/ false);
5388 }
5389 
5390 //===----------------------------------------------------------------------===//
5391 // AArch64 ABI Implementation
5392 //===----------------------------------------------------------------------===//
5393 
5394 namespace {
5395 
5396 class AArch64ABIInfo : public SwiftABIInfo {
5397 public:
5398   enum ABIKind {
5399     AAPCS = 0,
5400     DarwinPCS,
5401     Win64
5402   };
5403 
5404 private:
5405   ABIKind Kind;
5406 
5407 public:
5408   AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind)
5409     : SwiftABIInfo(CGT), Kind(Kind) {}
5410 
5411 private:
5412   ABIKind getABIKind() const { return Kind; }
5413   bool isDarwinPCS() const { return Kind == DarwinPCS; }
5414 
5415   ABIArgInfo classifyReturnType(QualType RetTy, bool IsVariadic) const;
5416   ABIArgInfo classifyArgumentType(QualType RetTy) const;
5417   ABIArgInfo coerceIllegalVector(QualType Ty) const;
5418   bool isHomogeneousAggregateBaseType(QualType Ty) const override;
5419   bool isHomogeneousAggregateSmallEnough(const Type *Ty,
5420                                          uint64_t Members) const override;
5421 
5422   bool isIllegalVectorType(QualType Ty) const;
5423 
5424   void computeInfo(CGFunctionInfo &FI) const override {
5425     if (!::classifyReturnType(getCXXABI(), FI, *this))
5426       FI.getReturnInfo() =
5427           classifyReturnType(FI.getReturnType(), FI.isVariadic());
5428 
5429     for (auto &it : FI.arguments())
5430       it.info = classifyArgumentType(it.type);
5431   }
5432 
5433   Address EmitDarwinVAArg(Address VAListAddr, QualType Ty,
5434                           CodeGenFunction &CGF) const;
5435 
5436   Address EmitAAPCSVAArg(Address VAListAddr, QualType Ty,
5437                          CodeGenFunction &CGF) const;
5438 
5439   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5440                     QualType Ty) const override {
5441     llvm::Type *BaseTy = CGF.ConvertType(Ty);
5442     if (isa<llvm::ScalableVectorType>(BaseTy))
5443       llvm::report_fatal_error("Passing SVE types to variadic functions is "
5444                                "currently not supported");
5445 
5446     return Kind == Win64 ? EmitMSVAArg(CGF, VAListAddr, Ty)
5447                          : isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF)
5448                                          : EmitAAPCSVAArg(VAListAddr, Ty, CGF);
5449   }
5450 
5451   Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
5452                       QualType Ty) const override;
5453 
5454   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
5455                                     bool asReturnValue) const override {
5456     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
5457   }
5458   bool isSwiftErrorInRegister() const override {
5459     return true;
5460   }
5461 
5462   bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy,
5463                                  unsigned elts) const override;
5464 
5465   bool allowBFloatArgsAndRet() const override {
5466     return getTarget().hasBFloat16Type();
5467   }
5468 };
5469 
5470 class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
5471 public:
5472   AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind)
5473       : TargetCodeGenInfo(std::make_unique<AArch64ABIInfo>(CGT, Kind)) {}
5474 
5475   StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
5476     return "mov\tfp, fp\t\t// marker for objc_retainAutoreleaseReturnValue";
5477   }
5478 
5479   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
5480     return 31;
5481   }
5482 
5483   bool doesReturnSlotInterfereWithArgs() const override { return false; }
5484 
5485   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5486                            CodeGen::CodeGenModule &CGM) const override {
5487     const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
5488     if (!FD)
5489       return;
5490 
5491     const auto *TA = FD->getAttr<TargetAttr>();
5492     if (TA == nullptr)
5493       return;
5494 
5495     ParsedTargetAttr Attr = TA->parse();
5496     if (Attr.BranchProtection.empty())
5497       return;
5498 
5499     TargetInfo::BranchProtectionInfo BPI;
5500     StringRef Error;
5501     (void)CGM.getTarget().validateBranchProtection(Attr.BranchProtection,
5502                                                    BPI, Error);
5503     assert(Error.empty());
5504 
5505     auto *Fn = cast<llvm::Function>(GV);
5506     static const char *SignReturnAddrStr[] = {"none", "non-leaf", "all"};
5507     Fn->addFnAttr("sign-return-address", SignReturnAddrStr[static_cast<int>(BPI.SignReturnAddr)]);
5508 
5509     if (BPI.SignReturnAddr != LangOptions::SignReturnAddressScopeKind::None) {
5510       Fn->addFnAttr("sign-return-address-key",
5511                     BPI.SignKey == LangOptions::SignReturnAddressKeyKind::AKey
5512                         ? "a_key"
5513                         : "b_key");
5514     }
5515 
5516     Fn->addFnAttr("branch-target-enforcement",
5517                   BPI.BranchTargetEnforcement ? "true" : "false");
5518   }
5519 };
5520 
5521 class WindowsAArch64TargetCodeGenInfo : public AArch64TargetCodeGenInfo {
5522 public:
5523   WindowsAArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind K)
5524       : AArch64TargetCodeGenInfo(CGT, K) {}
5525 
5526   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5527                            CodeGen::CodeGenModule &CGM) const override;
5528 
5529   void getDependentLibraryOption(llvm::StringRef Lib,
5530                                  llvm::SmallString<24> &Opt) const override {
5531     Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib);
5532   }
5533 
5534   void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value,
5535                                llvm::SmallString<32> &Opt) const override {
5536     Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
5537   }
5538 };
5539 
5540 void WindowsAArch64TargetCodeGenInfo::setTargetAttributes(
5541     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
5542   AArch64TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
5543   if (GV->isDeclaration())
5544     return;
5545   addStackProbeTargetAttributes(D, GV, CGM);
5546 }
5547 }
5548 
5549 ABIArgInfo AArch64ABIInfo::coerceIllegalVector(QualType Ty) const {
5550   assert(Ty->isVectorType() && "expected vector type!");
5551 
5552   const auto *VT = Ty->castAs<VectorType>();
5553   if (VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector) {
5554     assert(VT->getElementType()->isBuiltinType() && "expected builtin type!");
5555     assert(VT->getElementType()->castAs<BuiltinType>()->getKind() ==
5556                BuiltinType::UChar &&
5557            "unexpected builtin type for SVE predicate!");
5558     return ABIArgInfo::getDirect(llvm::ScalableVectorType::get(
5559         llvm::Type::getInt1Ty(getVMContext()), 16));
5560   }
5561 
5562   if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector) {
5563     assert(VT->getElementType()->isBuiltinType() && "expected builtin type!");
5564 
5565     const auto *BT = VT->getElementType()->castAs<BuiltinType>();
5566     llvm::ScalableVectorType *ResType = nullptr;
5567     switch (BT->getKind()) {
5568     default:
5569       llvm_unreachable("unexpected builtin type for SVE vector!");
5570     case BuiltinType::SChar:
5571     case BuiltinType::UChar:
5572       ResType = llvm::ScalableVectorType::get(
5573           llvm::Type::getInt8Ty(getVMContext()), 16);
5574       break;
5575     case BuiltinType::Short:
5576     case BuiltinType::UShort:
5577       ResType = llvm::ScalableVectorType::get(
5578           llvm::Type::getInt16Ty(getVMContext()), 8);
5579       break;
5580     case BuiltinType::Int:
5581     case BuiltinType::UInt:
5582       ResType = llvm::ScalableVectorType::get(
5583           llvm::Type::getInt32Ty(getVMContext()), 4);
5584       break;
5585     case BuiltinType::Long:
5586     case BuiltinType::ULong:
5587       ResType = llvm::ScalableVectorType::get(
5588           llvm::Type::getInt64Ty(getVMContext()), 2);
5589       break;
5590     case BuiltinType::Half:
5591       ResType = llvm::ScalableVectorType::get(
5592           llvm::Type::getHalfTy(getVMContext()), 8);
5593       break;
5594     case BuiltinType::Float:
5595       ResType = llvm::ScalableVectorType::get(
5596           llvm::Type::getFloatTy(getVMContext()), 4);
5597       break;
5598     case BuiltinType::Double:
5599       ResType = llvm::ScalableVectorType::get(
5600           llvm::Type::getDoubleTy(getVMContext()), 2);
5601       break;
5602     case BuiltinType::BFloat16:
5603       ResType = llvm::ScalableVectorType::get(
5604           llvm::Type::getBFloatTy(getVMContext()), 8);
5605       break;
5606     }
5607     return ABIArgInfo::getDirect(ResType);
5608   }
5609 
5610   uint64_t Size = getContext().getTypeSize(Ty);
5611   // Android promotes <2 x i8> to i16, not i32
5612   if (isAndroid() && (Size <= 16)) {
5613     llvm::Type *ResType = llvm::Type::getInt16Ty(getVMContext());
5614     return ABIArgInfo::getDirect(ResType);
5615   }
5616   if (Size <= 32) {
5617     llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext());
5618     return ABIArgInfo::getDirect(ResType);
5619   }
5620   if (Size == 64) {
5621     auto *ResType =
5622         llvm::FixedVectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2);
5623     return ABIArgInfo::getDirect(ResType);
5624   }
5625   if (Size == 128) {
5626     auto *ResType =
5627         llvm::FixedVectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4);
5628     return ABIArgInfo::getDirect(ResType);
5629   }
5630   return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
5631 }
5632 
5633 ABIArgInfo AArch64ABIInfo::classifyArgumentType(QualType Ty) const {
5634   Ty = useFirstFieldIfTransparentUnion(Ty);
5635 
5636   // Handle illegal vector types here.
5637   if (isIllegalVectorType(Ty))
5638     return coerceIllegalVector(Ty);
5639 
5640   if (!isAggregateTypeForABI(Ty)) {
5641     // Treat an enum type as its underlying type.
5642     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5643       Ty = EnumTy->getDecl()->getIntegerType();
5644 
5645     if (const auto *EIT = Ty->getAs<ExtIntType>())
5646       if (EIT->getNumBits() > 128)
5647         return getNaturalAlignIndirect(Ty);
5648 
5649     return (isPromotableIntegerTypeForABI(Ty) && isDarwinPCS()
5650                 ? ABIArgInfo::getExtend(Ty)
5651                 : ABIArgInfo::getDirect());
5652   }
5653 
5654   // Structures with either a non-trivial destructor or a non-trivial
5655   // copy constructor are always indirect.
5656   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
5657     return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA ==
5658                                      CGCXXABI::RAA_DirectInMemory);
5659   }
5660 
5661   // Empty records are always ignored on Darwin, but actually passed in C++ mode
5662   // elsewhere for GNU compatibility.
5663   uint64_t Size = getContext().getTypeSize(Ty);
5664   bool IsEmpty = isEmptyRecord(getContext(), Ty, true);
5665   if (IsEmpty || Size == 0) {
5666     if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS())
5667       return ABIArgInfo::getIgnore();
5668 
5669     // GNU C mode. The only argument that gets ignored is an empty one with size
5670     // 0.
5671     if (IsEmpty && Size == 0)
5672       return ABIArgInfo::getIgnore();
5673     return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
5674   }
5675 
5676   // Homogeneous Floating-point Aggregates (HFAs) need to be expanded.
5677   const Type *Base = nullptr;
5678   uint64_t Members = 0;
5679   if (isHomogeneousAggregate(Ty, Base, Members)) {
5680     return ABIArgInfo::getDirect(
5681         llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members));
5682   }
5683 
5684   // Aggregates <= 16 bytes are passed directly in registers or on the stack.
5685   if (Size <= 128) {
5686     // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
5687     // same size and alignment.
5688     if (getTarget().isRenderScriptTarget()) {
5689       return coerceToIntArray(Ty, getContext(), getVMContext());
5690     }
5691     unsigned Alignment;
5692     if (Kind == AArch64ABIInfo::AAPCS) {
5693       Alignment = getContext().getTypeUnadjustedAlign(Ty);
5694       Alignment = Alignment < 128 ? 64 : 128;
5695     } else {
5696       Alignment = std::max(getContext().getTypeAlign(Ty),
5697                            (unsigned)getTarget().getPointerWidth(0));
5698     }
5699     Size = llvm::alignTo(Size, Alignment);
5700 
5701     // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
5702     // For aggregates with 16-byte alignment, we use i128.
5703     llvm::Type *BaseTy = llvm::Type::getIntNTy(getVMContext(), Alignment);
5704     return ABIArgInfo::getDirect(
5705         Size == Alignment ? BaseTy
5706                           : llvm::ArrayType::get(BaseTy, Size / Alignment));
5707   }
5708 
5709   return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
5710 }
5711 
5712 ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy,
5713                                               bool IsVariadic) const {
5714   if (RetTy->isVoidType())
5715     return ABIArgInfo::getIgnore();
5716 
5717   if (const auto *VT = RetTy->getAs<VectorType>()) {
5718     if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector ||
5719         VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector)
5720       return coerceIllegalVector(RetTy);
5721   }
5722 
5723   // Large vector types should be returned via memory.
5724   if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
5725     return getNaturalAlignIndirect(RetTy);
5726 
5727   if (!isAggregateTypeForABI(RetTy)) {
5728     // Treat an enum type as its underlying type.
5729     if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5730       RetTy = EnumTy->getDecl()->getIntegerType();
5731 
5732     if (const auto *EIT = RetTy->getAs<ExtIntType>())
5733       if (EIT->getNumBits() > 128)
5734         return getNaturalAlignIndirect(RetTy);
5735 
5736     return (isPromotableIntegerTypeForABI(RetTy) && isDarwinPCS()
5737                 ? ABIArgInfo::getExtend(RetTy)
5738                 : ABIArgInfo::getDirect());
5739   }
5740 
5741   uint64_t Size = getContext().getTypeSize(RetTy);
5742   if (isEmptyRecord(getContext(), RetTy, true) || Size == 0)
5743     return ABIArgInfo::getIgnore();
5744 
5745   const Type *Base = nullptr;
5746   uint64_t Members = 0;
5747   if (isHomogeneousAggregate(RetTy, Base, Members) &&
5748       !(getTarget().getTriple().getArch() == llvm::Triple::aarch64_32 &&
5749         IsVariadic))
5750     // Homogeneous Floating-point Aggregates (HFAs) are returned directly.
5751     return ABIArgInfo::getDirect();
5752 
5753   // Aggregates <= 16 bytes are returned directly in registers or on the stack.
5754   if (Size <= 128) {
5755     // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
5756     // same size and alignment.
5757     if (getTarget().isRenderScriptTarget()) {
5758       return coerceToIntArray(RetTy, getContext(), getVMContext());
5759     }
5760     unsigned Alignment = getContext().getTypeAlign(RetTy);
5761     Size = llvm::alignTo(Size, 64); // round up to multiple of 8 bytes
5762 
5763     // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
5764     // For aggregates with 16-byte alignment, we use i128.
5765     if (Alignment < 128 && Size == 128) {
5766       llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
5767       return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
5768     }
5769     return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
5770   }
5771 
5772   return getNaturalAlignIndirect(RetTy);
5773 }
5774 
5775 /// isIllegalVectorType - check whether the vector type is legal for AArch64.
5776 bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const {
5777   if (const VectorType *VT = Ty->getAs<VectorType>()) {
5778     // Check whether VT is a fixed-length SVE vector. These types are
5779     // represented as scalable vectors in function args/return and must be
5780     // coerced from fixed vectors.
5781     if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector ||
5782         VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector)
5783       return true;
5784 
5785     // Check whether VT is legal.
5786     unsigned NumElements = VT->getNumElements();
5787     uint64_t Size = getContext().getTypeSize(VT);
5788     // NumElements should be power of 2.
5789     if (!llvm::isPowerOf2_32(NumElements))
5790       return true;
5791 
5792     // arm64_32 has to be compatible with the ARM logic here, which allows huge
5793     // vectors for some reason.
5794     llvm::Triple Triple = getTarget().getTriple();
5795     if (Triple.getArch() == llvm::Triple::aarch64_32 &&
5796         Triple.isOSBinFormatMachO())
5797       return Size <= 32;
5798 
5799     return Size != 64 && (Size != 128 || NumElements == 1);
5800   }
5801   return false;
5802 }
5803 
5804 bool AArch64ABIInfo::isLegalVectorTypeForSwift(CharUnits totalSize,
5805                                                llvm::Type *eltTy,
5806                                                unsigned elts) const {
5807   if (!llvm::isPowerOf2_32(elts))
5808     return false;
5809   if (totalSize.getQuantity() != 8 &&
5810       (totalSize.getQuantity() != 16 || elts == 1))
5811     return false;
5812   return true;
5813 }
5814 
5815 bool AArch64ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
5816   // Homogeneous aggregates for AAPCS64 must have base types of a floating
5817   // point type or a short-vector type. This is the same as the 32-bit ABI,
5818   // but with the difference that any floating-point type is allowed,
5819   // including __fp16.
5820   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
5821     if (BT->isFloatingPoint())
5822       return true;
5823   } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
5824     unsigned VecSize = getContext().getTypeSize(VT);
5825     if (VecSize == 64 || VecSize == 128)
5826       return true;
5827   }
5828   return false;
5829 }
5830 
5831 bool AArch64ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
5832                                                        uint64_t Members) const {
5833   return Members <= 4;
5834 }
5835 
5836 Address AArch64ABIInfo::EmitAAPCSVAArg(Address VAListAddr,
5837                                             QualType Ty,
5838                                             CodeGenFunction &CGF) const {
5839   ABIArgInfo AI = classifyArgumentType(Ty);
5840   bool IsIndirect = AI.isIndirect();
5841 
5842   llvm::Type *BaseTy = CGF.ConvertType(Ty);
5843   if (IsIndirect)
5844     BaseTy = llvm::PointerType::getUnqual(BaseTy);
5845   else if (AI.getCoerceToType())
5846     BaseTy = AI.getCoerceToType();
5847 
5848   unsigned NumRegs = 1;
5849   if (llvm::ArrayType *ArrTy = dyn_cast<llvm::ArrayType>(BaseTy)) {
5850     BaseTy = ArrTy->getElementType();
5851     NumRegs = ArrTy->getNumElements();
5852   }
5853   bool IsFPR = BaseTy->isFloatingPointTy() || BaseTy->isVectorTy();
5854 
5855   // The AArch64 va_list type and handling is specified in the Procedure Call
5856   // Standard, section B.4:
5857   //
5858   // struct {
5859   //   void *__stack;
5860   //   void *__gr_top;
5861   //   void *__vr_top;
5862   //   int __gr_offs;
5863   //   int __vr_offs;
5864   // };
5865 
5866   llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
5867   llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
5868   llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
5869   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
5870 
5871   CharUnits TySize = getContext().getTypeSizeInChars(Ty);
5872   CharUnits TyAlign = getContext().getTypeUnadjustedAlignInChars(Ty);
5873 
5874   Address reg_offs_p = Address::invalid();
5875   llvm::Value *reg_offs = nullptr;
5876   int reg_top_index;
5877   int RegSize = IsIndirect ? 8 : TySize.getQuantity();
5878   if (!IsFPR) {
5879     // 3 is the field number of __gr_offs
5880     reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 3, "gr_offs_p");
5881     reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
5882     reg_top_index = 1; // field number for __gr_top
5883     RegSize = llvm::alignTo(RegSize, 8);
5884   } else {
5885     // 4 is the field number of __vr_offs.
5886     reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 4, "vr_offs_p");
5887     reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
5888     reg_top_index = 2; // field number for __vr_top
5889     RegSize = 16 * NumRegs;
5890   }
5891 
5892   //=======================================
5893   // Find out where argument was passed
5894   //=======================================
5895 
5896   // If reg_offs >= 0 we're already using the stack for this type of
5897   // argument. We don't want to keep updating reg_offs (in case it overflows,
5898   // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
5899   // whatever they get).
5900   llvm::Value *UsingStack = nullptr;
5901   UsingStack = CGF.Builder.CreateICmpSGE(
5902       reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0));
5903 
5904   CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
5905 
5906   // Otherwise, at least some kind of argument could go in these registers, the
5907   // question is whether this particular type is too big.
5908   CGF.EmitBlock(MaybeRegBlock);
5909 
5910   // Integer arguments may need to correct register alignment (for example a
5911   // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
5912   // align __gr_offs to calculate the potential address.
5913   if (!IsFPR && !IsIndirect && TyAlign.getQuantity() > 8) {
5914     int Align = TyAlign.getQuantity();
5915 
5916     reg_offs = CGF.Builder.CreateAdd(
5917         reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
5918         "align_regoffs");
5919     reg_offs = CGF.Builder.CreateAnd(
5920         reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align),
5921         "aligned_regoffs");
5922   }
5923 
5924   // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
5925   // The fact that this is done unconditionally reflects the fact that
5926   // allocating an argument to the stack also uses up all the remaining
5927   // registers of the appropriate kind.
5928   llvm::Value *NewOffset = nullptr;
5929   NewOffset = CGF.Builder.CreateAdd(
5930       reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs");
5931   CGF.Builder.CreateStore(NewOffset, reg_offs_p);
5932 
5933   // Now we're in a position to decide whether this argument really was in
5934   // registers or not.
5935   llvm::Value *InRegs = nullptr;
5936   InRegs = CGF.Builder.CreateICmpSLE(
5937       NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg");
5938 
5939   CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
5940 
5941   //=======================================
5942   // Argument was in registers
5943   //=======================================
5944 
5945   // Now we emit the code for if the argument was originally passed in
5946   // registers. First start the appropriate block:
5947   CGF.EmitBlock(InRegBlock);
5948 
5949   llvm::Value *reg_top = nullptr;
5950   Address reg_top_p =
5951       CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index, "reg_top_p");
5952   reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
5953   Address BaseAddr(CGF.Builder.CreateInBoundsGEP(reg_top, reg_offs),
5954                    CharUnits::fromQuantity(IsFPR ? 16 : 8));
5955   Address RegAddr = Address::invalid();
5956   llvm::Type *MemTy = CGF.ConvertTypeForMem(Ty);
5957 
5958   if (IsIndirect) {
5959     // If it's been passed indirectly (actually a struct), whatever we find from
5960     // stored registers or on the stack will actually be a struct **.
5961     MemTy = llvm::PointerType::getUnqual(MemTy);
5962   }
5963 
5964   const Type *Base = nullptr;
5965   uint64_t NumMembers = 0;
5966   bool IsHFA = isHomogeneousAggregate(Ty, Base, NumMembers);
5967   if (IsHFA && NumMembers > 1) {
5968     // Homogeneous aggregates passed in registers will have their elements split
5969     // and stored 16-bytes apart regardless of size (they're notionally in qN,
5970     // qN+1, ...). We reload and store into a temporary local variable
5971     // contiguously.
5972     assert(!IsIndirect && "Homogeneous aggregates should be passed directly");
5973     auto BaseTyInfo = getContext().getTypeInfoInChars(QualType(Base, 0));
5974     llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
5975     llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
5976     Address Tmp = CGF.CreateTempAlloca(HFATy,
5977                                        std::max(TyAlign, BaseTyInfo.Align));
5978 
5979     // On big-endian platforms, the value will be right-aligned in its slot.
5980     int Offset = 0;
5981     if (CGF.CGM.getDataLayout().isBigEndian() &&
5982         BaseTyInfo.Width.getQuantity() < 16)
5983       Offset = 16 - BaseTyInfo.Width.getQuantity();
5984 
5985     for (unsigned i = 0; i < NumMembers; ++i) {
5986       CharUnits BaseOffset = CharUnits::fromQuantity(16 * i + Offset);
5987       Address LoadAddr =
5988         CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, BaseOffset);
5989       LoadAddr = CGF.Builder.CreateElementBitCast(LoadAddr, BaseTy);
5990 
5991       Address StoreAddr = CGF.Builder.CreateConstArrayGEP(Tmp, i);
5992 
5993       llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
5994       CGF.Builder.CreateStore(Elem, StoreAddr);
5995     }
5996 
5997     RegAddr = CGF.Builder.CreateElementBitCast(Tmp, MemTy);
5998   } else {
5999     // Otherwise the object is contiguous in memory.
6000 
6001     // It might be right-aligned in its slot.
6002     CharUnits SlotSize = BaseAddr.getAlignment();
6003     if (CGF.CGM.getDataLayout().isBigEndian() && !IsIndirect &&
6004         (IsHFA || !isAggregateTypeForABI(Ty)) &&
6005         TySize < SlotSize) {
6006       CharUnits Offset = SlotSize - TySize;
6007       BaseAddr = CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, Offset);
6008     }
6009 
6010     RegAddr = CGF.Builder.CreateElementBitCast(BaseAddr, MemTy);
6011   }
6012 
6013   CGF.EmitBranch(ContBlock);
6014 
6015   //=======================================
6016   // Argument was on the stack
6017   //=======================================
6018   CGF.EmitBlock(OnStackBlock);
6019 
6020   Address stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "stack_p");
6021   llvm::Value *OnStackPtr = CGF.Builder.CreateLoad(stack_p, "stack");
6022 
6023   // Again, stack arguments may need realignment. In this case both integer and
6024   // floating-point ones might be affected.
6025   if (!IsIndirect && TyAlign.getQuantity() > 8) {
6026     int Align = TyAlign.getQuantity();
6027 
6028     OnStackPtr = CGF.Builder.CreatePtrToInt(OnStackPtr, CGF.Int64Ty);
6029 
6030     OnStackPtr = CGF.Builder.CreateAdd(
6031         OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
6032         "align_stack");
6033     OnStackPtr = CGF.Builder.CreateAnd(
6034         OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, -Align),
6035         "align_stack");
6036 
6037     OnStackPtr = CGF.Builder.CreateIntToPtr(OnStackPtr, CGF.Int8PtrTy);
6038   }
6039   Address OnStackAddr(OnStackPtr,
6040                       std::max(CharUnits::fromQuantity(8), TyAlign));
6041 
6042   // All stack slots are multiples of 8 bytes.
6043   CharUnits StackSlotSize = CharUnits::fromQuantity(8);
6044   CharUnits StackSize;
6045   if (IsIndirect)
6046     StackSize = StackSlotSize;
6047   else
6048     StackSize = TySize.alignTo(StackSlotSize);
6049 
6050   llvm::Value *StackSizeC = CGF.Builder.getSize(StackSize);
6051   llvm::Value *NewStack =
6052       CGF.Builder.CreateInBoundsGEP(OnStackPtr, StackSizeC, "new_stack");
6053 
6054   // Write the new value of __stack for the next call to va_arg
6055   CGF.Builder.CreateStore(NewStack, stack_p);
6056 
6057   if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) &&
6058       TySize < StackSlotSize) {
6059     CharUnits Offset = StackSlotSize - TySize;
6060     OnStackAddr = CGF.Builder.CreateConstInBoundsByteGEP(OnStackAddr, Offset);
6061   }
6062 
6063   OnStackAddr = CGF.Builder.CreateElementBitCast(OnStackAddr, MemTy);
6064 
6065   CGF.EmitBranch(ContBlock);
6066 
6067   //=======================================
6068   // Tidy up
6069   //=======================================
6070   CGF.EmitBlock(ContBlock);
6071 
6072   Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
6073                                  OnStackAddr, OnStackBlock, "vaargs.addr");
6074 
6075   if (IsIndirect)
6076     return Address(CGF.Builder.CreateLoad(ResAddr, "vaarg.addr"),
6077                    TyAlign);
6078 
6079   return ResAddr;
6080 }
6081 
6082 Address AArch64ABIInfo::EmitDarwinVAArg(Address VAListAddr, QualType Ty,
6083                                         CodeGenFunction &CGF) const {
6084   // The backend's lowering doesn't support va_arg for aggregates or
6085   // illegal vector types.  Lower VAArg here for these cases and use
6086   // the LLVM va_arg instruction for everything else.
6087   if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty))
6088     return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
6089 
6090   uint64_t PointerSize = getTarget().getPointerWidth(0) / 8;
6091   CharUnits SlotSize = CharUnits::fromQuantity(PointerSize);
6092 
6093   // Empty records are ignored for parameter passing purposes.
6094   if (isEmptyRecord(getContext(), Ty, true)) {
6095     Address Addr(CGF.Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
6096     Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
6097     return Addr;
6098   }
6099 
6100   // The size of the actual thing passed, which might end up just
6101   // being a pointer for indirect types.
6102   auto TyInfo = getContext().getTypeInfoInChars(Ty);
6103 
6104   // Arguments bigger than 16 bytes which aren't homogeneous
6105   // aggregates should be passed indirectly.
6106   bool IsIndirect = false;
6107   if (TyInfo.Width.getQuantity() > 16) {
6108     const Type *Base = nullptr;
6109     uint64_t Members = 0;
6110     IsIndirect = !isHomogeneousAggregate(Ty, Base, Members);
6111   }
6112 
6113   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
6114                           TyInfo, SlotSize, /*AllowHigherAlign*/ true);
6115 }
6116 
6117 Address AArch64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
6118                                     QualType Ty) const {
6119   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
6120                           CGF.getContext().getTypeInfoInChars(Ty),
6121                           CharUnits::fromQuantity(8),
6122                           /*allowHigherAlign*/ false);
6123 }
6124 
6125 //===----------------------------------------------------------------------===//
6126 // ARM ABI Implementation
6127 //===----------------------------------------------------------------------===//
6128 
6129 namespace {
6130 
6131 class ARMABIInfo : public SwiftABIInfo {
6132 public:
6133   enum ABIKind {
6134     APCS = 0,
6135     AAPCS = 1,
6136     AAPCS_VFP = 2,
6137     AAPCS16_VFP = 3,
6138   };
6139 
6140 private:
6141   ABIKind Kind;
6142   bool IsFloatABISoftFP;
6143 
6144 public:
6145   ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind)
6146       : SwiftABIInfo(CGT), Kind(_Kind) {
6147     setCCs();
6148     IsFloatABISoftFP = CGT.getCodeGenOpts().FloatABI == "softfp" ||
6149         CGT.getCodeGenOpts().FloatABI == ""; // default
6150   }
6151 
6152   bool isEABI() const {
6153     switch (getTarget().getTriple().getEnvironment()) {
6154     case llvm::Triple::Android:
6155     case llvm::Triple::EABI:
6156     case llvm::Triple::EABIHF:
6157     case llvm::Triple::GNUEABI:
6158     case llvm::Triple::GNUEABIHF:
6159     case llvm::Triple::MuslEABI:
6160     case llvm::Triple::MuslEABIHF:
6161       return true;
6162     default:
6163       return false;
6164     }
6165   }
6166 
6167   bool isEABIHF() const {
6168     switch (getTarget().getTriple().getEnvironment()) {
6169     case llvm::Triple::EABIHF:
6170     case llvm::Triple::GNUEABIHF:
6171     case llvm::Triple::MuslEABIHF:
6172       return true;
6173     default:
6174       return false;
6175     }
6176   }
6177 
6178   ABIKind getABIKind() const { return Kind; }
6179 
6180   bool allowBFloatArgsAndRet() const override {
6181     return !IsFloatABISoftFP && getTarget().hasBFloat16Type();
6182   }
6183 
6184 private:
6185   ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic,
6186                                 unsigned functionCallConv) const;
6187   ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic,
6188                                   unsigned functionCallConv) const;
6189   ABIArgInfo classifyHomogeneousAggregate(QualType Ty, const Type *Base,
6190                                           uint64_t Members) const;
6191   ABIArgInfo coerceIllegalVector(QualType Ty) const;
6192   bool isIllegalVectorType(QualType Ty) const;
6193   bool containsAnyFP16Vectors(QualType Ty) const;
6194 
6195   bool isHomogeneousAggregateBaseType(QualType Ty) const override;
6196   bool isHomogeneousAggregateSmallEnough(const Type *Ty,
6197                                          uint64_t Members) const override;
6198 
6199   bool isEffectivelyAAPCS_VFP(unsigned callConvention, bool acceptHalf) const;
6200 
6201   void computeInfo(CGFunctionInfo &FI) const override;
6202 
6203   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6204                     QualType Ty) const override;
6205 
6206   llvm::CallingConv::ID getLLVMDefaultCC() const;
6207   llvm::CallingConv::ID getABIDefaultCC() const;
6208   void setCCs();
6209 
6210   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
6211                                     bool asReturnValue) const override {
6212     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
6213   }
6214   bool isSwiftErrorInRegister() const override {
6215     return true;
6216   }
6217   bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy,
6218                                  unsigned elts) const override;
6219 };
6220 
6221 class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
6222 public:
6223   ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
6224       : TargetCodeGenInfo(std::make_unique<ARMABIInfo>(CGT, K)) {}
6225 
6226   const ARMABIInfo &getABIInfo() const {
6227     return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
6228   }
6229 
6230   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
6231     return 13;
6232   }
6233 
6234   StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
6235     return "mov\tr7, r7\t\t// marker for objc_retainAutoreleaseReturnValue";
6236   }
6237 
6238   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
6239                                llvm::Value *Address) const override {
6240     llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
6241 
6242     // 0-15 are the 16 integer registers.
6243     AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
6244     return false;
6245   }
6246 
6247   unsigned getSizeOfUnwindException() const override {
6248     if (getABIInfo().isEABI()) return 88;
6249     return TargetCodeGenInfo::getSizeOfUnwindException();
6250   }
6251 
6252   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
6253                            CodeGen::CodeGenModule &CGM) const override {
6254     if (GV->isDeclaration())
6255       return;
6256     const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
6257     if (!FD)
6258       return;
6259 
6260     const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
6261     if (!Attr)
6262       return;
6263 
6264     const char *Kind;
6265     switch (Attr->getInterrupt()) {
6266     case ARMInterruptAttr::Generic: Kind = ""; break;
6267     case ARMInterruptAttr::IRQ:     Kind = "IRQ"; break;
6268     case ARMInterruptAttr::FIQ:     Kind = "FIQ"; break;
6269     case ARMInterruptAttr::SWI:     Kind = "SWI"; break;
6270     case ARMInterruptAttr::ABORT:   Kind = "ABORT"; break;
6271     case ARMInterruptAttr::UNDEF:   Kind = "UNDEF"; break;
6272     }
6273 
6274     llvm::Function *Fn = cast<llvm::Function>(GV);
6275 
6276     Fn->addFnAttr("interrupt", Kind);
6277 
6278     ARMABIInfo::ABIKind ABI = cast<ARMABIInfo>(getABIInfo()).getABIKind();
6279     if (ABI == ARMABIInfo::APCS)
6280       return;
6281 
6282     // AAPCS guarantees that sp will be 8-byte aligned on any public interface,
6283     // however this is not necessarily true on taking any interrupt. Instruct
6284     // the backend to perform a realignment as part of the function prologue.
6285     llvm::AttrBuilder B;
6286     B.addStackAlignmentAttr(8);
6287     Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
6288   }
6289 };
6290 
6291 class WindowsARMTargetCodeGenInfo : public ARMTargetCodeGenInfo {
6292 public:
6293   WindowsARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
6294       : ARMTargetCodeGenInfo(CGT, K) {}
6295 
6296   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
6297                            CodeGen::CodeGenModule &CGM) const override;
6298 
6299   void getDependentLibraryOption(llvm::StringRef Lib,
6300                                  llvm::SmallString<24> &Opt) const override {
6301     Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib);
6302   }
6303 
6304   void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value,
6305                                llvm::SmallString<32> &Opt) const override {
6306     Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
6307   }
6308 };
6309 
6310 void WindowsARMTargetCodeGenInfo::setTargetAttributes(
6311     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
6312   ARMTargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
6313   if (GV->isDeclaration())
6314     return;
6315   addStackProbeTargetAttributes(D, GV, CGM);
6316 }
6317 }
6318 
6319 void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
6320   if (!::classifyReturnType(getCXXABI(), FI, *this))
6321     FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), FI.isVariadic(),
6322                                             FI.getCallingConvention());
6323 
6324   for (auto &I : FI.arguments())
6325     I.info = classifyArgumentType(I.type, FI.isVariadic(),
6326                                   FI.getCallingConvention());
6327 
6328 
6329   // Always honor user-specified calling convention.
6330   if (FI.getCallingConvention() != llvm::CallingConv::C)
6331     return;
6332 
6333   llvm::CallingConv::ID cc = getRuntimeCC();
6334   if (cc != llvm::CallingConv::C)
6335     FI.setEffectiveCallingConvention(cc);
6336 }
6337 
6338 /// Return the default calling convention that LLVM will use.
6339 llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
6340   // The default calling convention that LLVM will infer.
6341   if (isEABIHF() || getTarget().getTriple().isWatchABI())
6342     return llvm::CallingConv::ARM_AAPCS_VFP;
6343   else if (isEABI())
6344     return llvm::CallingConv::ARM_AAPCS;
6345   else
6346     return llvm::CallingConv::ARM_APCS;
6347 }
6348 
6349 /// Return the calling convention that our ABI would like us to use
6350 /// as the C calling convention.
6351 llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
6352   switch (getABIKind()) {
6353   case APCS: return llvm::CallingConv::ARM_APCS;
6354   case AAPCS: return llvm::CallingConv::ARM_AAPCS;
6355   case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
6356   case AAPCS16_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
6357   }
6358   llvm_unreachable("bad ABI kind");
6359 }
6360 
6361 void ARMABIInfo::setCCs() {
6362   assert(getRuntimeCC() == llvm::CallingConv::C);
6363 
6364   // Don't muddy up the IR with a ton of explicit annotations if
6365   // they'd just match what LLVM will infer from the triple.
6366   llvm::CallingConv::ID abiCC = getABIDefaultCC();
6367   if (abiCC != getLLVMDefaultCC())
6368     RuntimeCC = abiCC;
6369 }
6370 
6371 ABIArgInfo ARMABIInfo::coerceIllegalVector(QualType Ty) const {
6372   uint64_t Size = getContext().getTypeSize(Ty);
6373   if (Size <= 32) {
6374     llvm::Type *ResType =
6375         llvm::Type::getInt32Ty(getVMContext());
6376     return ABIArgInfo::getDirect(ResType);
6377   }
6378   if (Size == 64 || Size == 128) {
6379     auto *ResType = llvm::FixedVectorType::get(
6380         llvm::Type::getInt32Ty(getVMContext()), Size / 32);
6381     return ABIArgInfo::getDirect(ResType);
6382   }
6383   return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
6384 }
6385 
6386 ABIArgInfo ARMABIInfo::classifyHomogeneousAggregate(QualType Ty,
6387                                                     const Type *Base,
6388                                                     uint64_t Members) const {
6389   assert(Base && "Base class should be set for homogeneous aggregate");
6390   // Base can be a floating-point or a vector.
6391   if (const VectorType *VT = Base->getAs<VectorType>()) {
6392     // FP16 vectors should be converted to integer vectors
6393     if (!getTarget().hasLegalHalfType() && containsAnyFP16Vectors(Ty)) {
6394       uint64_t Size = getContext().getTypeSize(VT);
6395       auto *NewVecTy = llvm::FixedVectorType::get(
6396           llvm::Type::getInt32Ty(getVMContext()), Size / 32);
6397       llvm::Type *Ty = llvm::ArrayType::get(NewVecTy, Members);
6398       return ABIArgInfo::getDirect(Ty, 0, nullptr, false);
6399     }
6400   }
6401   return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
6402 }
6403 
6404 ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty, bool isVariadic,
6405                                             unsigned functionCallConv) const {
6406   // 6.1.2.1 The following argument types are VFP CPRCs:
6407   //   A single-precision floating-point type (including promoted
6408   //   half-precision types); A double-precision floating-point type;
6409   //   A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
6410   //   with a Base Type of a single- or double-precision floating-point type,
6411   //   64-bit containerized vectors or 128-bit containerized vectors with one
6412   //   to four Elements.
6413   // Variadic functions should always marshal to the base standard.
6414   bool IsAAPCS_VFP =
6415       !isVariadic && isEffectivelyAAPCS_VFP(functionCallConv, /* AAPCS16 */ false);
6416 
6417   Ty = useFirstFieldIfTransparentUnion(Ty);
6418 
6419   // Handle illegal vector types here.
6420   if (isIllegalVectorType(Ty))
6421     return coerceIllegalVector(Ty);
6422 
6423   if (!isAggregateTypeForABI(Ty)) {
6424     // Treat an enum type as its underlying type.
6425     if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
6426       Ty = EnumTy->getDecl()->getIntegerType();
6427     }
6428 
6429     if (const auto *EIT = Ty->getAs<ExtIntType>())
6430       if (EIT->getNumBits() > 64)
6431         return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
6432 
6433     return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
6434                                               : ABIArgInfo::getDirect());
6435   }
6436 
6437   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
6438     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
6439   }
6440 
6441   // Ignore empty records.
6442   if (isEmptyRecord(getContext(), Ty, true))
6443     return ABIArgInfo::getIgnore();
6444 
6445   if (IsAAPCS_VFP) {
6446     // Homogeneous Aggregates need to be expanded when we can fit the aggregate
6447     // into VFP registers.
6448     const Type *Base = nullptr;
6449     uint64_t Members = 0;
6450     if (isHomogeneousAggregate(Ty, Base, Members))
6451       return classifyHomogeneousAggregate(Ty, Base, Members);
6452   } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
6453     // WatchOS does have homogeneous aggregates. Note that we intentionally use
6454     // this convention even for a variadic function: the backend will use GPRs
6455     // if needed.
6456     const Type *Base = nullptr;
6457     uint64_t Members = 0;
6458     if (isHomogeneousAggregate(Ty, Base, Members)) {
6459       assert(Base && Members <= 4 && "unexpected homogeneous aggregate");
6460       llvm::Type *Ty =
6461         llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members);
6462       return ABIArgInfo::getDirect(Ty, 0, nullptr, false);
6463     }
6464   }
6465 
6466   if (getABIKind() == ARMABIInfo::AAPCS16_VFP &&
6467       getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(16)) {
6468     // WatchOS is adopting the 64-bit AAPCS rule on composite types: if they're
6469     // bigger than 128-bits, they get placed in space allocated by the caller,
6470     // and a pointer is passed.
6471     return ABIArgInfo::getIndirect(
6472         CharUnits::fromQuantity(getContext().getTypeAlign(Ty) / 8), false);
6473   }
6474 
6475   // Support byval for ARM.
6476   // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
6477   // most 8-byte. We realign the indirect argument if type alignment is bigger
6478   // than ABI alignment.
6479   uint64_t ABIAlign = 4;
6480   uint64_t TyAlign;
6481   if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
6482       getABIKind() == ARMABIInfo::AAPCS) {
6483     TyAlign = getContext().getTypeUnadjustedAlignInChars(Ty).getQuantity();
6484     ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
6485   } else {
6486     TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity();
6487   }
6488   if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
6489     assert(getABIKind() != ARMABIInfo::AAPCS16_VFP && "unexpected byval");
6490     return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
6491                                    /*ByVal=*/true,
6492                                    /*Realign=*/TyAlign > ABIAlign);
6493   }
6494 
6495   // On RenderScript, coerce Aggregates <= 64 bytes to an integer array of
6496   // same size and alignment.
6497   if (getTarget().isRenderScriptTarget()) {
6498     return coerceToIntArray(Ty, getContext(), getVMContext());
6499   }
6500 
6501   // Otherwise, pass by coercing to a structure of the appropriate size.
6502   llvm::Type* ElemTy;
6503   unsigned SizeRegs;
6504   // FIXME: Try to match the types of the arguments more accurately where
6505   // we can.
6506   if (TyAlign <= 4) {
6507     ElemTy = llvm::Type::getInt32Ty(getVMContext());
6508     SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
6509   } else {
6510     ElemTy = llvm::Type::getInt64Ty(getVMContext());
6511     SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
6512   }
6513 
6514   return ABIArgInfo::getDirect(llvm::ArrayType::get(ElemTy, SizeRegs));
6515 }
6516 
6517 static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
6518                               llvm::LLVMContext &VMContext) {
6519   // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
6520   // is called integer-like if its size is less than or equal to one word, and
6521   // the offset of each of its addressable sub-fields is zero.
6522 
6523   uint64_t Size = Context.getTypeSize(Ty);
6524 
6525   // Check that the type fits in a word.
6526   if (Size > 32)
6527     return false;
6528 
6529   // FIXME: Handle vector types!
6530   if (Ty->isVectorType())
6531     return false;
6532 
6533   // Float types are never treated as "integer like".
6534   if (Ty->isRealFloatingType())
6535     return false;
6536 
6537   // If this is a builtin or pointer type then it is ok.
6538   if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
6539     return true;
6540 
6541   // Small complex integer types are "integer like".
6542   if (const ComplexType *CT = Ty->getAs<ComplexType>())
6543     return isIntegerLikeType(CT->getElementType(), Context, VMContext);
6544 
6545   // Single element and zero sized arrays should be allowed, by the definition
6546   // above, but they are not.
6547 
6548   // Otherwise, it must be a record type.
6549   const RecordType *RT = Ty->getAs<RecordType>();
6550   if (!RT) return false;
6551 
6552   // Ignore records with flexible arrays.
6553   const RecordDecl *RD = RT->getDecl();
6554   if (RD->hasFlexibleArrayMember())
6555     return false;
6556 
6557   // Check that all sub-fields are at offset 0, and are themselves "integer
6558   // like".
6559   const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
6560 
6561   bool HadField = false;
6562   unsigned idx = 0;
6563   for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
6564        i != e; ++i, ++idx) {
6565     const FieldDecl *FD = *i;
6566 
6567     // Bit-fields are not addressable, we only need to verify they are "integer
6568     // like". We still have to disallow a subsequent non-bitfield, for example:
6569     //   struct { int : 0; int x }
6570     // is non-integer like according to gcc.
6571     if (FD->isBitField()) {
6572       if (!RD->isUnion())
6573         HadField = true;
6574 
6575       if (!isIntegerLikeType(FD->getType(), Context, VMContext))
6576         return false;
6577 
6578       continue;
6579     }
6580 
6581     // Check if this field is at offset 0.
6582     if (Layout.getFieldOffset(idx) != 0)
6583       return false;
6584 
6585     if (!isIntegerLikeType(FD->getType(), Context, VMContext))
6586       return false;
6587 
6588     // Only allow at most one field in a structure. This doesn't match the
6589     // wording above, but follows gcc in situations with a field following an
6590     // empty structure.
6591     if (!RD->isUnion()) {
6592       if (HadField)
6593         return false;
6594 
6595       HadField = true;
6596     }
6597   }
6598 
6599   return true;
6600 }
6601 
6602 ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy, bool isVariadic,
6603                                           unsigned functionCallConv) const {
6604 
6605   // Variadic functions should always marshal to the base standard.
6606   bool IsAAPCS_VFP =
6607       !isVariadic && isEffectivelyAAPCS_VFP(functionCallConv, /* AAPCS16 */ true);
6608 
6609   if (RetTy->isVoidType())
6610     return ABIArgInfo::getIgnore();
6611 
6612   if (const VectorType *VT = RetTy->getAs<VectorType>()) {
6613     // Large vector types should be returned via memory.
6614     if (getContext().getTypeSize(RetTy) > 128)
6615       return getNaturalAlignIndirect(RetTy);
6616     // TODO: FP16/BF16 vectors should be converted to integer vectors
6617     // This check is similar  to isIllegalVectorType - refactor?
6618     if ((!getTarget().hasLegalHalfType() &&
6619         (VT->getElementType()->isFloat16Type() ||
6620          VT->getElementType()->isHalfType())) ||
6621         (IsFloatABISoftFP &&
6622          VT->getElementType()->isBFloat16Type()))
6623       return coerceIllegalVector(RetTy);
6624   }
6625 
6626   if (!isAggregateTypeForABI(RetTy)) {
6627     // Treat an enum type as its underlying type.
6628     if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6629       RetTy = EnumTy->getDecl()->getIntegerType();
6630 
6631     if (const auto *EIT = RetTy->getAs<ExtIntType>())
6632       if (EIT->getNumBits() > 64)
6633         return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
6634 
6635     return isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
6636                                                 : ABIArgInfo::getDirect();
6637   }
6638 
6639   // Are we following APCS?
6640   if (getABIKind() == APCS) {
6641     if (isEmptyRecord(getContext(), RetTy, false))
6642       return ABIArgInfo::getIgnore();
6643 
6644     // Complex types are all returned as packed integers.
6645     //
6646     // FIXME: Consider using 2 x vector types if the back end handles them
6647     // correctly.
6648     if (RetTy->isAnyComplexType())
6649       return ABIArgInfo::getDirect(llvm::IntegerType::get(
6650           getVMContext(), getContext().getTypeSize(RetTy)));
6651 
6652     // Integer like structures are returned in r0.
6653     if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
6654       // Return in the smallest viable integer type.
6655       uint64_t Size = getContext().getTypeSize(RetTy);
6656       if (Size <= 8)
6657         return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6658       if (Size <= 16)
6659         return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6660       return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6661     }
6662 
6663     // Otherwise return in memory.
6664     return getNaturalAlignIndirect(RetTy);
6665   }
6666 
6667   // Otherwise this is an AAPCS variant.
6668 
6669   if (isEmptyRecord(getContext(), RetTy, true))
6670     return ABIArgInfo::getIgnore();
6671 
6672   // Check for homogeneous aggregates with AAPCS-VFP.
6673   if (IsAAPCS_VFP) {
6674     const Type *Base = nullptr;
6675     uint64_t Members = 0;
6676     if (isHomogeneousAggregate(RetTy, Base, Members))
6677       return classifyHomogeneousAggregate(RetTy, Base, Members);
6678   }
6679 
6680   // Aggregates <= 4 bytes are returned in r0; other aggregates
6681   // are returned indirectly.
6682   uint64_t Size = getContext().getTypeSize(RetTy);
6683   if (Size <= 32) {
6684     // On RenderScript, coerce Aggregates <= 4 bytes to an integer array of
6685     // same size and alignment.
6686     if (getTarget().isRenderScriptTarget()) {
6687       return coerceToIntArray(RetTy, getContext(), getVMContext());
6688     }
6689     if (getDataLayout().isBigEndian())
6690       // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4)
6691       return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6692 
6693     // Return in the smallest viable integer type.
6694     if (Size <= 8)
6695       return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6696     if (Size <= 16)
6697       return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6698     return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6699   } else if (Size <= 128 && getABIKind() == AAPCS16_VFP) {
6700     llvm::Type *Int32Ty = llvm::Type::getInt32Ty(getVMContext());
6701     llvm::Type *CoerceTy =
6702         llvm::ArrayType::get(Int32Ty, llvm::alignTo(Size, 32) / 32);
6703     return ABIArgInfo::getDirect(CoerceTy);
6704   }
6705 
6706   return getNaturalAlignIndirect(RetTy);
6707 }
6708 
6709 /// isIllegalVector - check whether Ty is an illegal vector type.
6710 bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
6711   if (const VectorType *VT = Ty->getAs<VectorType> ()) {
6712     // On targets that don't support half, fp16 or bfloat, they are expanded
6713     // into float, and we don't want the ABI to depend on whether or not they
6714     // are supported in hardware. Thus return false to coerce vectors of these
6715     // types into integer vectors.
6716     // We do not depend on hasLegalHalfType for bfloat as it is a
6717     // separate IR type.
6718     if ((!getTarget().hasLegalHalfType() &&
6719         (VT->getElementType()->isFloat16Type() ||
6720          VT->getElementType()->isHalfType())) ||
6721         (IsFloatABISoftFP &&
6722          VT->getElementType()->isBFloat16Type()))
6723       return true;
6724     if (isAndroid()) {
6725       // Android shipped using Clang 3.1, which supported a slightly different
6726       // vector ABI. The primary differences were that 3-element vector types
6727       // were legal, and so were sub 32-bit vectors (i.e. <2 x i8>). This path
6728       // accepts that legacy behavior for Android only.
6729       // Check whether VT is legal.
6730       unsigned NumElements = VT->getNumElements();
6731       // NumElements should be power of 2 or equal to 3.
6732       if (!llvm::isPowerOf2_32(NumElements) && NumElements != 3)
6733         return true;
6734     } else {
6735       // Check whether VT is legal.
6736       unsigned NumElements = VT->getNumElements();
6737       uint64_t Size = getContext().getTypeSize(VT);
6738       // NumElements should be power of 2.
6739       if (!llvm::isPowerOf2_32(NumElements))
6740         return true;
6741       // Size should be greater than 32 bits.
6742       return Size <= 32;
6743     }
6744   }
6745   return false;
6746 }
6747 
6748 /// Return true if a type contains any 16-bit floating point vectors
6749 bool ARMABIInfo::containsAnyFP16Vectors(QualType Ty) const {
6750   if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
6751     uint64_t NElements = AT->getSize().getZExtValue();
6752     if (NElements == 0)
6753       return false;
6754     return containsAnyFP16Vectors(AT->getElementType());
6755   } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
6756     const RecordDecl *RD = RT->getDecl();
6757 
6758     // If this is a C++ record, check the bases first.
6759     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
6760       if (llvm::any_of(CXXRD->bases(), [this](const CXXBaseSpecifier &B) {
6761             return containsAnyFP16Vectors(B.getType());
6762           }))
6763         return true;
6764 
6765     if (llvm::any_of(RD->fields(), [this](FieldDecl *FD) {
6766           return FD && containsAnyFP16Vectors(FD->getType());
6767         }))
6768       return true;
6769 
6770     return false;
6771   } else {
6772     if (const VectorType *VT = Ty->getAs<VectorType>())
6773       return (VT->getElementType()->isFloat16Type() ||
6774               VT->getElementType()->isBFloat16Type() ||
6775               VT->getElementType()->isHalfType());
6776     return false;
6777   }
6778 }
6779 
6780 bool ARMABIInfo::isLegalVectorTypeForSwift(CharUnits vectorSize,
6781                                            llvm::Type *eltTy,
6782                                            unsigned numElts) const {
6783   if (!llvm::isPowerOf2_32(numElts))
6784     return false;
6785   unsigned size = getDataLayout().getTypeStoreSizeInBits(eltTy);
6786   if (size > 64)
6787     return false;
6788   if (vectorSize.getQuantity() != 8 &&
6789       (vectorSize.getQuantity() != 16 || numElts == 1))
6790     return false;
6791   return true;
6792 }
6793 
6794 bool ARMABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
6795   // Homogeneous aggregates for AAPCS-VFP must have base types of float,
6796   // double, or 64-bit or 128-bit vectors.
6797   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
6798     if (BT->getKind() == BuiltinType::Float ||
6799         BT->getKind() == BuiltinType::Double ||
6800         BT->getKind() == BuiltinType::LongDouble)
6801       return true;
6802   } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
6803     unsigned VecSize = getContext().getTypeSize(VT);
6804     if (VecSize == 64 || VecSize == 128)
6805       return true;
6806   }
6807   return false;
6808 }
6809 
6810 bool ARMABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
6811                                                    uint64_t Members) const {
6812   return Members <= 4;
6813 }
6814 
6815 bool ARMABIInfo::isEffectivelyAAPCS_VFP(unsigned callConvention,
6816                                         bool acceptHalf) const {
6817   // Give precedence to user-specified calling conventions.
6818   if (callConvention != llvm::CallingConv::C)
6819     return (callConvention == llvm::CallingConv::ARM_AAPCS_VFP);
6820   else
6821     return (getABIKind() == AAPCS_VFP) ||
6822            (acceptHalf && (getABIKind() == AAPCS16_VFP));
6823 }
6824 
6825 Address ARMABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6826                               QualType Ty) const {
6827   CharUnits SlotSize = CharUnits::fromQuantity(4);
6828 
6829   // Empty records are ignored for parameter passing purposes.
6830   if (isEmptyRecord(getContext(), Ty, true)) {
6831     Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize);
6832     Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
6833     return Addr;
6834   }
6835 
6836   CharUnits TySize = getContext().getTypeSizeInChars(Ty);
6837   CharUnits TyAlignForABI = getContext().getTypeUnadjustedAlignInChars(Ty);
6838 
6839   // Use indirect if size of the illegal vector is bigger than 16 bytes.
6840   bool IsIndirect = false;
6841   const Type *Base = nullptr;
6842   uint64_t Members = 0;
6843   if (TySize > CharUnits::fromQuantity(16) && isIllegalVectorType(Ty)) {
6844     IsIndirect = true;
6845 
6846   // ARMv7k passes structs bigger than 16 bytes indirectly, in space
6847   // allocated by the caller.
6848   } else if (TySize > CharUnits::fromQuantity(16) &&
6849              getABIKind() == ARMABIInfo::AAPCS16_VFP &&
6850              !isHomogeneousAggregate(Ty, Base, Members)) {
6851     IsIndirect = true;
6852 
6853   // Otherwise, bound the type's ABI alignment.
6854   // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
6855   // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
6856   // Our callers should be prepared to handle an under-aligned address.
6857   } else if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
6858              getABIKind() == ARMABIInfo::AAPCS) {
6859     TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
6860     TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(8));
6861   } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
6862     // ARMv7k allows type alignment up to 16 bytes.
6863     TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
6864     TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(16));
6865   } else {
6866     TyAlignForABI = CharUnits::fromQuantity(4);
6867   }
6868 
6869   TypeInfoChars TyInfo(TySize, TyAlignForABI, false);
6870   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TyInfo,
6871                           SlotSize, /*AllowHigherAlign*/ true);
6872 }
6873 
6874 //===----------------------------------------------------------------------===//
6875 // NVPTX ABI Implementation
6876 //===----------------------------------------------------------------------===//
6877 
6878 namespace {
6879 
6880 class NVPTXTargetCodeGenInfo;
6881 
6882 class NVPTXABIInfo : public ABIInfo {
6883   NVPTXTargetCodeGenInfo &CGInfo;
6884 
6885 public:
6886   NVPTXABIInfo(CodeGenTypes &CGT, NVPTXTargetCodeGenInfo &Info)
6887       : ABIInfo(CGT), CGInfo(Info) {}
6888 
6889   ABIArgInfo classifyReturnType(QualType RetTy) const;
6890   ABIArgInfo classifyArgumentType(QualType Ty) const;
6891 
6892   void computeInfo(CGFunctionInfo &FI) const override;
6893   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6894                     QualType Ty) const override;
6895   bool isUnsupportedType(QualType T) const;
6896   ABIArgInfo coerceToIntArrayWithLimit(QualType Ty, unsigned MaxSize) const;
6897 };
6898 
6899 class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
6900 public:
6901   NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
6902       : TargetCodeGenInfo(std::make_unique<NVPTXABIInfo>(CGT, *this)) {}
6903 
6904   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
6905                            CodeGen::CodeGenModule &M) const override;
6906   bool shouldEmitStaticExternCAliases() const override;
6907 
6908   llvm::Type *getCUDADeviceBuiltinSurfaceDeviceType() const override {
6909     // On the device side, surface reference is represented as an object handle
6910     // in 64-bit integer.
6911     return llvm::Type::getInt64Ty(getABIInfo().getVMContext());
6912   }
6913 
6914   llvm::Type *getCUDADeviceBuiltinTextureDeviceType() const override {
6915     // On the device side, texture reference is represented as an object handle
6916     // in 64-bit integer.
6917     return llvm::Type::getInt64Ty(getABIInfo().getVMContext());
6918   }
6919 
6920   bool emitCUDADeviceBuiltinSurfaceDeviceCopy(CodeGenFunction &CGF, LValue Dst,
6921                                               LValue Src) const override {
6922     emitBuiltinSurfTexDeviceCopy(CGF, Dst, Src);
6923     return true;
6924   }
6925 
6926   bool emitCUDADeviceBuiltinTextureDeviceCopy(CodeGenFunction &CGF, LValue Dst,
6927                                               LValue Src) const override {
6928     emitBuiltinSurfTexDeviceCopy(CGF, Dst, Src);
6929     return true;
6930   }
6931 
6932 private:
6933   // Adds a NamedMDNode with GV, Name, and Operand as operands, and adds the
6934   // resulting MDNode to the nvvm.annotations MDNode.
6935   static void addNVVMMetadata(llvm::GlobalValue *GV, StringRef Name,
6936                               int Operand);
6937 
6938   static void emitBuiltinSurfTexDeviceCopy(CodeGenFunction &CGF, LValue Dst,
6939                                            LValue Src) {
6940     llvm::Value *Handle = nullptr;
6941     llvm::Constant *C =
6942         llvm::dyn_cast<llvm::Constant>(Src.getAddress(CGF).getPointer());
6943     // Lookup `addrspacecast` through the constant pointer if any.
6944     if (auto *ASC = llvm::dyn_cast_or_null<llvm::AddrSpaceCastOperator>(C))
6945       C = llvm::cast<llvm::Constant>(ASC->getPointerOperand());
6946     if (auto *GV = llvm::dyn_cast_or_null<llvm::GlobalVariable>(C)) {
6947       // Load the handle from the specific global variable using
6948       // `nvvm.texsurf.handle.internal` intrinsic.
6949       Handle = CGF.EmitRuntimeCall(
6950           CGF.CGM.getIntrinsic(llvm::Intrinsic::nvvm_texsurf_handle_internal,
6951                                {GV->getType()}),
6952           {GV}, "texsurf_handle");
6953     } else
6954       Handle = CGF.EmitLoadOfScalar(Src, SourceLocation());
6955     CGF.EmitStoreOfScalar(Handle, Dst);
6956   }
6957 };
6958 
6959 /// Checks if the type is unsupported directly by the current target.
6960 bool NVPTXABIInfo::isUnsupportedType(QualType T) const {
6961   ASTContext &Context = getContext();
6962   if (!Context.getTargetInfo().hasFloat16Type() && T->isFloat16Type())
6963     return true;
6964   if (!Context.getTargetInfo().hasFloat128Type() &&
6965       (T->isFloat128Type() ||
6966        (T->isRealFloatingType() && Context.getTypeSize(T) == 128)))
6967     return true;
6968   if (const auto *EIT = T->getAs<ExtIntType>())
6969     return EIT->getNumBits() >
6970            (Context.getTargetInfo().hasInt128Type() ? 128U : 64U);
6971   if (!Context.getTargetInfo().hasInt128Type() && T->isIntegerType() &&
6972       Context.getTypeSize(T) > 64U)
6973     return true;
6974   if (const auto *AT = T->getAsArrayTypeUnsafe())
6975     return isUnsupportedType(AT->getElementType());
6976   const auto *RT = T->getAs<RecordType>();
6977   if (!RT)
6978     return false;
6979   const RecordDecl *RD = RT->getDecl();
6980 
6981   // If this is a C++ record, check the bases first.
6982   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
6983     for (const CXXBaseSpecifier &I : CXXRD->bases())
6984       if (isUnsupportedType(I.getType()))
6985         return true;
6986 
6987   for (const FieldDecl *I : RD->fields())
6988     if (isUnsupportedType(I->getType()))
6989       return true;
6990   return false;
6991 }
6992 
6993 /// Coerce the given type into an array with maximum allowed size of elements.
6994 ABIArgInfo NVPTXABIInfo::coerceToIntArrayWithLimit(QualType Ty,
6995                                                    unsigned MaxSize) const {
6996   // Alignment and Size are measured in bits.
6997   const uint64_t Size = getContext().getTypeSize(Ty);
6998   const uint64_t Alignment = getContext().getTypeAlign(Ty);
6999   const unsigned Div = std::min<unsigned>(MaxSize, Alignment);
7000   llvm::Type *IntType = llvm::Type::getIntNTy(getVMContext(), Div);
7001   const uint64_t NumElements = (Size + Div - 1) / Div;
7002   return ABIArgInfo::getDirect(llvm::ArrayType::get(IntType, NumElements));
7003 }
7004 
7005 ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
7006   if (RetTy->isVoidType())
7007     return ABIArgInfo::getIgnore();
7008 
7009   if (getContext().getLangOpts().OpenMP &&
7010       getContext().getLangOpts().OpenMPIsDevice && isUnsupportedType(RetTy))
7011     return coerceToIntArrayWithLimit(RetTy, 64);
7012 
7013   // note: this is different from default ABI
7014   if (!RetTy->isScalarType())
7015     return ABIArgInfo::getDirect();
7016 
7017   // Treat an enum type as its underlying type.
7018   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
7019     RetTy = EnumTy->getDecl()->getIntegerType();
7020 
7021   return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
7022                                                : ABIArgInfo::getDirect());
7023 }
7024 
7025 ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
7026   // Treat an enum type as its underlying type.
7027   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7028     Ty = EnumTy->getDecl()->getIntegerType();
7029 
7030   // Return aggregates type as indirect by value
7031   if (isAggregateTypeForABI(Ty)) {
7032     // Under CUDA device compilation, tex/surf builtin types are replaced with
7033     // object types and passed directly.
7034     if (getContext().getLangOpts().CUDAIsDevice) {
7035       if (Ty->isCUDADeviceBuiltinSurfaceType())
7036         return ABIArgInfo::getDirect(
7037             CGInfo.getCUDADeviceBuiltinSurfaceDeviceType());
7038       if (Ty->isCUDADeviceBuiltinTextureType())
7039         return ABIArgInfo::getDirect(
7040             CGInfo.getCUDADeviceBuiltinTextureDeviceType());
7041     }
7042     return getNaturalAlignIndirect(Ty, /* byval */ true);
7043   }
7044 
7045   if (const auto *EIT = Ty->getAs<ExtIntType>()) {
7046     if ((EIT->getNumBits() > 128) ||
7047         (!getContext().getTargetInfo().hasInt128Type() &&
7048          EIT->getNumBits() > 64))
7049       return getNaturalAlignIndirect(Ty, /* byval */ true);
7050   }
7051 
7052   return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
7053                                             : ABIArgInfo::getDirect());
7054 }
7055 
7056 void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
7057   if (!getCXXABI().classifyReturnType(FI))
7058     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7059   for (auto &I : FI.arguments())
7060     I.info = classifyArgumentType(I.type);
7061 
7062   // Always honor user-specified calling convention.
7063   if (FI.getCallingConvention() != llvm::CallingConv::C)
7064     return;
7065 
7066   FI.setEffectiveCallingConvention(getRuntimeCC());
7067 }
7068 
7069 Address NVPTXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7070                                 QualType Ty) const {
7071   llvm_unreachable("NVPTX does not support varargs");
7072 }
7073 
7074 void NVPTXTargetCodeGenInfo::setTargetAttributes(
7075     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
7076   if (GV->isDeclaration())
7077     return;
7078   const VarDecl *VD = dyn_cast_or_null<VarDecl>(D);
7079   if (VD) {
7080     if (M.getLangOpts().CUDA) {
7081       if (VD->getType()->isCUDADeviceBuiltinSurfaceType())
7082         addNVVMMetadata(GV, "surface", 1);
7083       else if (VD->getType()->isCUDADeviceBuiltinTextureType())
7084         addNVVMMetadata(GV, "texture", 1);
7085       return;
7086     }
7087   }
7088 
7089   const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
7090   if (!FD) return;
7091 
7092   llvm::Function *F = cast<llvm::Function>(GV);
7093 
7094   // Perform special handling in OpenCL mode
7095   if (M.getLangOpts().OpenCL) {
7096     // Use OpenCL function attributes to check for kernel functions
7097     // By default, all functions are device functions
7098     if (FD->hasAttr<OpenCLKernelAttr>()) {
7099       // OpenCL __kernel functions get kernel metadata
7100       // Create !{<func-ref>, metadata !"kernel", i32 1} node
7101       addNVVMMetadata(F, "kernel", 1);
7102       // And kernel functions are not subject to inlining
7103       F->addFnAttr(llvm::Attribute::NoInline);
7104     }
7105   }
7106 
7107   // Perform special handling in CUDA mode.
7108   if (M.getLangOpts().CUDA) {
7109     // CUDA __global__ functions get a kernel metadata entry.  Since
7110     // __global__ functions cannot be called from the device, we do not
7111     // need to set the noinline attribute.
7112     if (FD->hasAttr<CUDAGlobalAttr>()) {
7113       // Create !{<func-ref>, metadata !"kernel", i32 1} node
7114       addNVVMMetadata(F, "kernel", 1);
7115     }
7116     if (CUDALaunchBoundsAttr *Attr = FD->getAttr<CUDALaunchBoundsAttr>()) {
7117       // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node
7118       llvm::APSInt MaxThreads(32);
7119       MaxThreads = Attr->getMaxThreads()->EvaluateKnownConstInt(M.getContext());
7120       if (MaxThreads > 0)
7121         addNVVMMetadata(F, "maxntidx", MaxThreads.getExtValue());
7122 
7123       // min blocks is an optional argument for CUDALaunchBoundsAttr. If it was
7124       // not specified in __launch_bounds__ or if the user specified a 0 value,
7125       // we don't have to add a PTX directive.
7126       if (Attr->getMinBlocks()) {
7127         llvm::APSInt MinBlocks(32);
7128         MinBlocks = Attr->getMinBlocks()->EvaluateKnownConstInt(M.getContext());
7129         if (MinBlocks > 0)
7130           // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node
7131           addNVVMMetadata(F, "minctasm", MinBlocks.getExtValue());
7132       }
7133     }
7134   }
7135 }
7136 
7137 void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::GlobalValue *GV,
7138                                              StringRef Name, int Operand) {
7139   llvm::Module *M = GV->getParent();
7140   llvm::LLVMContext &Ctx = M->getContext();
7141 
7142   // Get "nvvm.annotations" metadata node
7143   llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
7144 
7145   llvm::Metadata *MDVals[] = {
7146       llvm::ConstantAsMetadata::get(GV), llvm::MDString::get(Ctx, Name),
7147       llvm::ConstantAsMetadata::get(
7148           llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand))};
7149   // Append metadata to nvvm.annotations
7150   MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
7151 }
7152 
7153 bool NVPTXTargetCodeGenInfo::shouldEmitStaticExternCAliases() const {
7154   return false;
7155 }
7156 }
7157 
7158 //===----------------------------------------------------------------------===//
7159 // SystemZ ABI Implementation
7160 //===----------------------------------------------------------------------===//
7161 
7162 namespace {
7163 
7164 class SystemZABIInfo : public SwiftABIInfo {
7165   bool HasVector;
7166   bool IsSoftFloatABI;
7167 
7168 public:
7169   SystemZABIInfo(CodeGenTypes &CGT, bool HV, bool SF)
7170     : SwiftABIInfo(CGT), HasVector(HV), IsSoftFloatABI(SF) {}
7171 
7172   bool isPromotableIntegerTypeForABI(QualType Ty) const;
7173   bool isCompoundType(QualType Ty) const;
7174   bool isVectorArgumentType(QualType Ty) const;
7175   bool isFPArgumentType(QualType Ty) const;
7176   QualType GetSingleElementType(QualType Ty) const;
7177 
7178   ABIArgInfo classifyReturnType(QualType RetTy) const;
7179   ABIArgInfo classifyArgumentType(QualType ArgTy) const;
7180 
7181   void computeInfo(CGFunctionInfo &FI) const override {
7182     if (!getCXXABI().classifyReturnType(FI))
7183       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7184     for (auto &I : FI.arguments())
7185       I.info = classifyArgumentType(I.type);
7186   }
7187 
7188   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7189                     QualType Ty) const override;
7190 
7191   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
7192                                     bool asReturnValue) const override {
7193     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
7194   }
7195   bool isSwiftErrorInRegister() const override {
7196     return false;
7197   }
7198 };
7199 
7200 class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
7201 public:
7202   SystemZTargetCodeGenInfo(CodeGenTypes &CGT, bool HasVector, bool SoftFloatABI)
7203       : TargetCodeGenInfo(
7204             std::make_unique<SystemZABIInfo>(CGT, HasVector, SoftFloatABI)) {}
7205 
7206   llvm::Value *testFPKind(llvm::Value *V, unsigned BuiltinID,
7207                           CGBuilderTy &Builder,
7208                           CodeGenModule &CGM) const override {
7209     assert(V->getType()->isFloatingPointTy() && "V should have an FP type.");
7210     // Only use TDC in constrained FP mode.
7211     if (!Builder.getIsFPConstrained())
7212       return nullptr;
7213 
7214     llvm::Type *Ty = V->getType();
7215     if (Ty->isFloatTy() || Ty->isDoubleTy() || Ty->isFP128Ty()) {
7216       llvm::Module &M = CGM.getModule();
7217       auto &Ctx = M.getContext();
7218       llvm::Function *TDCFunc =
7219           llvm::Intrinsic::getDeclaration(&M, llvm::Intrinsic::s390_tdc, Ty);
7220       unsigned TDCBits = 0;
7221       switch (BuiltinID) {
7222       case Builtin::BI__builtin_isnan:
7223         TDCBits = 0xf;
7224         break;
7225       default:
7226         break;
7227       }
7228       if (TDCBits)
7229         return Builder.CreateCall(
7230             TDCFunc,
7231             {V, llvm::ConstantInt::get(llvm::Type::getInt64Ty(Ctx), TDCBits)});
7232     }
7233     return nullptr;
7234   }
7235 };
7236 }
7237 
7238 bool SystemZABIInfo::isPromotableIntegerTypeForABI(QualType Ty) const {
7239   // Treat an enum type as its underlying type.
7240   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7241     Ty = EnumTy->getDecl()->getIntegerType();
7242 
7243   // Promotable integer types are required to be promoted by the ABI.
7244   if (ABIInfo::isPromotableIntegerTypeForABI(Ty))
7245     return true;
7246 
7247   if (const auto *EIT = Ty->getAs<ExtIntType>())
7248     if (EIT->getNumBits() < 64)
7249       return true;
7250 
7251   // 32-bit values must also be promoted.
7252   if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
7253     switch (BT->getKind()) {
7254     case BuiltinType::Int:
7255     case BuiltinType::UInt:
7256       return true;
7257     default:
7258       return false;
7259     }
7260   return false;
7261 }
7262 
7263 bool SystemZABIInfo::isCompoundType(QualType Ty) const {
7264   return (Ty->isAnyComplexType() ||
7265           Ty->isVectorType() ||
7266           isAggregateTypeForABI(Ty));
7267 }
7268 
7269 bool SystemZABIInfo::isVectorArgumentType(QualType Ty) const {
7270   return (HasVector &&
7271           Ty->isVectorType() &&
7272           getContext().getTypeSize(Ty) <= 128);
7273 }
7274 
7275 bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
7276   if (IsSoftFloatABI)
7277     return false;
7278 
7279   if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
7280     switch (BT->getKind()) {
7281     case BuiltinType::Float:
7282     case BuiltinType::Double:
7283       return true;
7284     default:
7285       return false;
7286     }
7287 
7288   return false;
7289 }
7290 
7291 QualType SystemZABIInfo::GetSingleElementType(QualType Ty) const {
7292   const RecordType *RT = Ty->getAs<RecordType>();
7293 
7294   if (RT && RT->isStructureOrClassType()) {
7295     const RecordDecl *RD = RT->getDecl();
7296     QualType Found;
7297 
7298     // If this is a C++ record, check the bases first.
7299     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
7300       for (const auto &I : CXXRD->bases()) {
7301         QualType Base = I.getType();
7302 
7303         // Empty bases don't affect things either way.
7304         if (isEmptyRecord(getContext(), Base, true))
7305           continue;
7306 
7307         if (!Found.isNull())
7308           return Ty;
7309         Found = GetSingleElementType(Base);
7310       }
7311 
7312     // Check the fields.
7313     for (const auto *FD : RD->fields()) {
7314       // For compatibility with GCC, ignore empty bitfields in C++ mode.
7315       // Unlike isSingleElementStruct(), empty structure and array fields
7316       // do count.  So do anonymous bitfields that aren't zero-sized.
7317       if (getContext().getLangOpts().CPlusPlus &&
7318           FD->isZeroLengthBitField(getContext()))
7319         continue;
7320       // Like isSingleElementStruct(), ignore C++20 empty data members.
7321       if (FD->hasAttr<NoUniqueAddressAttr>() &&
7322           isEmptyRecord(getContext(), FD->getType(), true))
7323         continue;
7324 
7325       // Unlike isSingleElementStruct(), arrays do not count.
7326       // Nested structures still do though.
7327       if (!Found.isNull())
7328         return Ty;
7329       Found = GetSingleElementType(FD->getType());
7330     }
7331 
7332     // Unlike isSingleElementStruct(), trailing padding is allowed.
7333     // An 8-byte aligned struct s { float f; } is passed as a double.
7334     if (!Found.isNull())
7335       return Found;
7336   }
7337 
7338   return Ty;
7339 }
7340 
7341 Address SystemZABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7342                                   QualType Ty) const {
7343   // Assume that va_list type is correct; should be pointer to LLVM type:
7344   // struct {
7345   //   i64 __gpr;
7346   //   i64 __fpr;
7347   //   i8 *__overflow_arg_area;
7348   //   i8 *__reg_save_area;
7349   // };
7350 
7351   // Every non-vector argument occupies 8 bytes and is passed by preference
7352   // in either GPRs or FPRs.  Vector arguments occupy 8 or 16 bytes and are
7353   // always passed on the stack.
7354   Ty = getContext().getCanonicalType(Ty);
7355   auto TyInfo = getContext().getTypeInfoInChars(Ty);
7356   llvm::Type *ArgTy = CGF.ConvertTypeForMem(Ty);
7357   llvm::Type *DirectTy = ArgTy;
7358   ABIArgInfo AI = classifyArgumentType(Ty);
7359   bool IsIndirect = AI.isIndirect();
7360   bool InFPRs = false;
7361   bool IsVector = false;
7362   CharUnits UnpaddedSize;
7363   CharUnits DirectAlign;
7364   if (IsIndirect) {
7365     DirectTy = llvm::PointerType::getUnqual(DirectTy);
7366     UnpaddedSize = DirectAlign = CharUnits::fromQuantity(8);
7367   } else {
7368     if (AI.getCoerceToType())
7369       ArgTy = AI.getCoerceToType();
7370     InFPRs = (!IsSoftFloatABI && (ArgTy->isFloatTy() || ArgTy->isDoubleTy()));
7371     IsVector = ArgTy->isVectorTy();
7372     UnpaddedSize = TyInfo.Width;
7373     DirectAlign = TyInfo.Align;
7374   }
7375   CharUnits PaddedSize = CharUnits::fromQuantity(8);
7376   if (IsVector && UnpaddedSize > PaddedSize)
7377     PaddedSize = CharUnits::fromQuantity(16);
7378   assert((UnpaddedSize <= PaddedSize) && "Invalid argument size.");
7379 
7380   CharUnits Padding = (PaddedSize - UnpaddedSize);
7381 
7382   llvm::Type *IndexTy = CGF.Int64Ty;
7383   llvm::Value *PaddedSizeV =
7384     llvm::ConstantInt::get(IndexTy, PaddedSize.getQuantity());
7385 
7386   if (IsVector) {
7387     // Work out the address of a vector argument on the stack.
7388     // Vector arguments are always passed in the high bits of a
7389     // single (8 byte) or double (16 byte) stack slot.
7390     Address OverflowArgAreaPtr =
7391         CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr");
7392     Address OverflowArgArea =
7393       Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
7394               TyInfo.Align);
7395     Address MemAddr =
7396       CGF.Builder.CreateElementBitCast(OverflowArgArea, DirectTy, "mem_addr");
7397 
7398     // Update overflow_arg_area_ptr pointer
7399     llvm::Value *NewOverflowArgArea =
7400       CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
7401                             "overflow_arg_area");
7402     CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
7403 
7404     return MemAddr;
7405   }
7406 
7407   assert(PaddedSize.getQuantity() == 8);
7408 
7409   unsigned MaxRegs, RegCountField, RegSaveIndex;
7410   CharUnits RegPadding;
7411   if (InFPRs) {
7412     MaxRegs = 4; // Maximum of 4 FPR arguments
7413     RegCountField = 1; // __fpr
7414     RegSaveIndex = 16; // save offset for f0
7415     RegPadding = CharUnits(); // floats are passed in the high bits of an FPR
7416   } else {
7417     MaxRegs = 5; // Maximum of 5 GPR arguments
7418     RegCountField = 0; // __gpr
7419     RegSaveIndex = 2; // save offset for r2
7420     RegPadding = Padding; // values are passed in the low bits of a GPR
7421   }
7422 
7423   Address RegCountPtr =
7424       CGF.Builder.CreateStructGEP(VAListAddr, RegCountField, "reg_count_ptr");
7425   llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
7426   llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
7427   llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
7428                                                  "fits_in_regs");
7429 
7430   llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
7431   llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
7432   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
7433   CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
7434 
7435   // Emit code to load the value if it was passed in registers.
7436   CGF.EmitBlock(InRegBlock);
7437 
7438   // Work out the address of an argument register.
7439   llvm::Value *ScaledRegCount =
7440     CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
7441   llvm::Value *RegBase =
7442     llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize.getQuantity()
7443                                       + RegPadding.getQuantity());
7444   llvm::Value *RegOffset =
7445     CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
7446   Address RegSaveAreaPtr =
7447       CGF.Builder.CreateStructGEP(VAListAddr, 3, "reg_save_area_ptr");
7448   llvm::Value *RegSaveArea =
7449     CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
7450   Address RawRegAddr(CGF.Builder.CreateGEP(RegSaveArea, RegOffset,
7451                                            "raw_reg_addr"),
7452                      PaddedSize);
7453   Address RegAddr =
7454     CGF.Builder.CreateElementBitCast(RawRegAddr, DirectTy, "reg_addr");
7455 
7456   // Update the register count
7457   llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
7458   llvm::Value *NewRegCount =
7459     CGF.Builder.CreateAdd(RegCount, One, "reg_count");
7460   CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
7461   CGF.EmitBranch(ContBlock);
7462 
7463   // Emit code to load the value if it was passed in memory.
7464   CGF.EmitBlock(InMemBlock);
7465 
7466   // Work out the address of a stack argument.
7467   Address OverflowArgAreaPtr =
7468       CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr");
7469   Address OverflowArgArea =
7470     Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
7471             PaddedSize);
7472   Address RawMemAddr =
7473     CGF.Builder.CreateConstByteGEP(OverflowArgArea, Padding, "raw_mem_addr");
7474   Address MemAddr =
7475     CGF.Builder.CreateElementBitCast(RawMemAddr, DirectTy, "mem_addr");
7476 
7477   // Update overflow_arg_area_ptr pointer
7478   llvm::Value *NewOverflowArgArea =
7479     CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
7480                           "overflow_arg_area");
7481   CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
7482   CGF.EmitBranch(ContBlock);
7483 
7484   // Return the appropriate result.
7485   CGF.EmitBlock(ContBlock);
7486   Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
7487                                  MemAddr, InMemBlock, "va_arg.addr");
7488 
7489   if (IsIndirect)
7490     ResAddr = Address(CGF.Builder.CreateLoad(ResAddr, "indirect_arg"),
7491                       TyInfo.Align);
7492 
7493   return ResAddr;
7494 }
7495 
7496 ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
7497   if (RetTy->isVoidType())
7498     return ABIArgInfo::getIgnore();
7499   if (isVectorArgumentType(RetTy))
7500     return ABIArgInfo::getDirect();
7501   if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
7502     return getNaturalAlignIndirect(RetTy);
7503   return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
7504                                                : ABIArgInfo::getDirect());
7505 }
7506 
7507 ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
7508   // Handle the generic C++ ABI.
7509   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
7510     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
7511 
7512   // Integers and enums are extended to full register width.
7513   if (isPromotableIntegerTypeForABI(Ty))
7514     return ABIArgInfo::getExtend(Ty);
7515 
7516   // Handle vector types and vector-like structure types.  Note that
7517   // as opposed to float-like structure types, we do not allow any
7518   // padding for vector-like structures, so verify the sizes match.
7519   uint64_t Size = getContext().getTypeSize(Ty);
7520   QualType SingleElementTy = GetSingleElementType(Ty);
7521   if (isVectorArgumentType(SingleElementTy) &&
7522       getContext().getTypeSize(SingleElementTy) == Size)
7523     return ABIArgInfo::getDirect(CGT.ConvertType(SingleElementTy));
7524 
7525   // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
7526   if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
7527     return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
7528 
7529   // Handle small structures.
7530   if (const RecordType *RT = Ty->getAs<RecordType>()) {
7531     // Structures with flexible arrays have variable length, so really
7532     // fail the size test above.
7533     const RecordDecl *RD = RT->getDecl();
7534     if (RD->hasFlexibleArrayMember())
7535       return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
7536 
7537     // The structure is passed as an unextended integer, a float, or a double.
7538     llvm::Type *PassTy;
7539     if (isFPArgumentType(SingleElementTy)) {
7540       assert(Size == 32 || Size == 64);
7541       if (Size == 32)
7542         PassTy = llvm::Type::getFloatTy(getVMContext());
7543       else
7544         PassTy = llvm::Type::getDoubleTy(getVMContext());
7545     } else
7546       PassTy = llvm::IntegerType::get(getVMContext(), Size);
7547     return ABIArgInfo::getDirect(PassTy);
7548   }
7549 
7550   // Non-structure compounds are passed indirectly.
7551   if (isCompoundType(Ty))
7552     return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
7553 
7554   return ABIArgInfo::getDirect(nullptr);
7555 }
7556 
7557 //===----------------------------------------------------------------------===//
7558 // MSP430 ABI Implementation
7559 //===----------------------------------------------------------------------===//
7560 
7561 namespace {
7562 
7563 class MSP430ABIInfo : public DefaultABIInfo {
7564   static ABIArgInfo complexArgInfo() {
7565     ABIArgInfo Info = ABIArgInfo::getDirect();
7566     Info.setCanBeFlattened(false);
7567     return Info;
7568   }
7569 
7570 public:
7571   MSP430ABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
7572 
7573   ABIArgInfo classifyReturnType(QualType RetTy) const {
7574     if (RetTy->isAnyComplexType())
7575       return complexArgInfo();
7576 
7577     return DefaultABIInfo::classifyReturnType(RetTy);
7578   }
7579 
7580   ABIArgInfo classifyArgumentType(QualType RetTy) const {
7581     if (RetTy->isAnyComplexType())
7582       return complexArgInfo();
7583 
7584     return DefaultABIInfo::classifyArgumentType(RetTy);
7585   }
7586 
7587   // Just copy the original implementations because
7588   // DefaultABIInfo::classify{Return,Argument}Type() are not virtual
7589   void computeInfo(CGFunctionInfo &FI) const override {
7590     if (!getCXXABI().classifyReturnType(FI))
7591       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7592     for (auto &I : FI.arguments())
7593       I.info = classifyArgumentType(I.type);
7594   }
7595 
7596   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7597                     QualType Ty) const override {
7598     return EmitVAArgInstr(CGF, VAListAddr, Ty, classifyArgumentType(Ty));
7599   }
7600 };
7601 
7602 class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
7603 public:
7604   MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
7605       : TargetCodeGenInfo(std::make_unique<MSP430ABIInfo>(CGT)) {}
7606   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
7607                            CodeGen::CodeGenModule &M) const override;
7608 };
7609 
7610 }
7611 
7612 void MSP430TargetCodeGenInfo::setTargetAttributes(
7613     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
7614   if (GV->isDeclaration())
7615     return;
7616   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
7617     const auto *InterruptAttr = FD->getAttr<MSP430InterruptAttr>();
7618     if (!InterruptAttr)
7619       return;
7620 
7621     // Handle 'interrupt' attribute:
7622     llvm::Function *F = cast<llvm::Function>(GV);
7623 
7624     // Step 1: Set ISR calling convention.
7625     F->setCallingConv(llvm::CallingConv::MSP430_INTR);
7626 
7627     // Step 2: Add attributes goodness.
7628     F->addFnAttr(llvm::Attribute::NoInline);
7629     F->addFnAttr("interrupt", llvm::utostr(InterruptAttr->getNumber()));
7630   }
7631 }
7632 
7633 //===----------------------------------------------------------------------===//
7634 // MIPS ABI Implementation.  This works for both little-endian and
7635 // big-endian variants.
7636 //===----------------------------------------------------------------------===//
7637 
7638 namespace {
7639 class MipsABIInfo : public ABIInfo {
7640   bool IsO32;
7641   unsigned MinABIStackAlignInBytes, StackAlignInBytes;
7642   void CoerceToIntArgs(uint64_t TySize,
7643                        SmallVectorImpl<llvm::Type *> &ArgList) const;
7644   llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
7645   llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
7646   llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
7647 public:
7648   MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
7649     ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
7650     StackAlignInBytes(IsO32 ? 8 : 16) {}
7651 
7652   ABIArgInfo classifyReturnType(QualType RetTy) const;
7653   ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
7654   void computeInfo(CGFunctionInfo &FI) const override;
7655   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7656                     QualType Ty) const override;
7657   ABIArgInfo extendType(QualType Ty) const;
7658 };
7659 
7660 class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
7661   unsigned SizeOfUnwindException;
7662 public:
7663   MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
7664       : TargetCodeGenInfo(std::make_unique<MipsABIInfo>(CGT, IsO32)),
7665         SizeOfUnwindException(IsO32 ? 24 : 32) {}
7666 
7667   int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
7668     return 29;
7669   }
7670 
7671   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
7672                            CodeGen::CodeGenModule &CGM) const override {
7673     const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
7674     if (!FD) return;
7675     llvm::Function *Fn = cast<llvm::Function>(GV);
7676 
7677     if (FD->hasAttr<MipsLongCallAttr>())
7678       Fn->addFnAttr("long-call");
7679     else if (FD->hasAttr<MipsShortCallAttr>())
7680       Fn->addFnAttr("short-call");
7681 
7682     // Other attributes do not have a meaning for declarations.
7683     if (GV->isDeclaration())
7684       return;
7685 
7686     if (FD->hasAttr<Mips16Attr>()) {
7687       Fn->addFnAttr("mips16");
7688     }
7689     else if (FD->hasAttr<NoMips16Attr>()) {
7690       Fn->addFnAttr("nomips16");
7691     }
7692 
7693     if (FD->hasAttr<MicroMipsAttr>())
7694       Fn->addFnAttr("micromips");
7695     else if (FD->hasAttr<NoMicroMipsAttr>())
7696       Fn->addFnAttr("nomicromips");
7697 
7698     const MipsInterruptAttr *Attr = FD->getAttr<MipsInterruptAttr>();
7699     if (!Attr)
7700       return;
7701 
7702     const char *Kind;
7703     switch (Attr->getInterrupt()) {
7704     case MipsInterruptAttr::eic:     Kind = "eic"; break;
7705     case MipsInterruptAttr::sw0:     Kind = "sw0"; break;
7706     case MipsInterruptAttr::sw1:     Kind = "sw1"; break;
7707     case MipsInterruptAttr::hw0:     Kind = "hw0"; break;
7708     case MipsInterruptAttr::hw1:     Kind = "hw1"; break;
7709     case MipsInterruptAttr::hw2:     Kind = "hw2"; break;
7710     case MipsInterruptAttr::hw3:     Kind = "hw3"; break;
7711     case MipsInterruptAttr::hw4:     Kind = "hw4"; break;
7712     case MipsInterruptAttr::hw5:     Kind = "hw5"; break;
7713     }
7714 
7715     Fn->addFnAttr("interrupt", Kind);
7716 
7717   }
7718 
7719   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
7720                                llvm::Value *Address) const override;
7721 
7722   unsigned getSizeOfUnwindException() const override {
7723     return SizeOfUnwindException;
7724   }
7725 };
7726 }
7727 
7728 void MipsABIInfo::CoerceToIntArgs(
7729     uint64_t TySize, SmallVectorImpl<llvm::Type *> &ArgList) const {
7730   llvm::IntegerType *IntTy =
7731     llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
7732 
7733   // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
7734   for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
7735     ArgList.push_back(IntTy);
7736 
7737   // If necessary, add one more integer type to ArgList.
7738   unsigned R = TySize % (MinABIStackAlignInBytes * 8);
7739 
7740   if (R)
7741     ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
7742 }
7743 
7744 // In N32/64, an aligned double precision floating point field is passed in
7745 // a register.
7746 llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
7747   SmallVector<llvm::Type*, 8> ArgList, IntArgList;
7748 
7749   if (IsO32) {
7750     CoerceToIntArgs(TySize, ArgList);
7751     return llvm::StructType::get(getVMContext(), ArgList);
7752   }
7753 
7754   if (Ty->isComplexType())
7755     return CGT.ConvertType(Ty);
7756 
7757   const RecordType *RT = Ty->getAs<RecordType>();
7758 
7759   // Unions/vectors are passed in integer registers.
7760   if (!RT || !RT->isStructureOrClassType()) {
7761     CoerceToIntArgs(TySize, ArgList);
7762     return llvm::StructType::get(getVMContext(), ArgList);
7763   }
7764 
7765   const RecordDecl *RD = RT->getDecl();
7766   const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
7767   assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
7768 
7769   uint64_t LastOffset = 0;
7770   unsigned idx = 0;
7771   llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
7772 
7773   // Iterate over fields in the struct/class and check if there are any aligned
7774   // double fields.
7775   for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
7776        i != e; ++i, ++idx) {
7777     const QualType Ty = i->getType();
7778     const BuiltinType *BT = Ty->getAs<BuiltinType>();
7779 
7780     if (!BT || BT->getKind() != BuiltinType::Double)
7781       continue;
7782 
7783     uint64_t Offset = Layout.getFieldOffset(idx);
7784     if (Offset % 64) // Ignore doubles that are not aligned.
7785       continue;
7786 
7787     // Add ((Offset - LastOffset) / 64) args of type i64.
7788     for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
7789       ArgList.push_back(I64);
7790 
7791     // Add double type.
7792     ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
7793     LastOffset = Offset + 64;
7794   }
7795 
7796   CoerceToIntArgs(TySize - LastOffset, IntArgList);
7797   ArgList.append(IntArgList.begin(), IntArgList.end());
7798 
7799   return llvm::StructType::get(getVMContext(), ArgList);
7800 }
7801 
7802 llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
7803                                         uint64_t Offset) const {
7804   if (OrigOffset + MinABIStackAlignInBytes > Offset)
7805     return nullptr;
7806 
7807   return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
7808 }
7809 
7810 ABIArgInfo
7811 MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
7812   Ty = useFirstFieldIfTransparentUnion(Ty);
7813 
7814   uint64_t OrigOffset = Offset;
7815   uint64_t TySize = getContext().getTypeSize(Ty);
7816   uint64_t Align = getContext().getTypeAlign(Ty) / 8;
7817 
7818   Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
7819                    (uint64_t)StackAlignInBytes);
7820   unsigned CurrOffset = llvm::alignTo(Offset, Align);
7821   Offset = CurrOffset + llvm::alignTo(TySize, Align * 8) / 8;
7822 
7823   if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
7824     // Ignore empty aggregates.
7825     if (TySize == 0)
7826       return ABIArgInfo::getIgnore();
7827 
7828     if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
7829       Offset = OrigOffset + MinABIStackAlignInBytes;
7830       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
7831     }
7832 
7833     // If we have reached here, aggregates are passed directly by coercing to
7834     // another structure type. Padding is inserted if the offset of the
7835     // aggregate is unaligned.
7836     ABIArgInfo ArgInfo =
7837         ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
7838                               getPaddingType(OrigOffset, CurrOffset));
7839     ArgInfo.setInReg(true);
7840     return ArgInfo;
7841   }
7842 
7843   // Treat an enum type as its underlying type.
7844   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7845     Ty = EnumTy->getDecl()->getIntegerType();
7846 
7847   // Make sure we pass indirectly things that are too large.
7848   if (const auto *EIT = Ty->getAs<ExtIntType>())
7849     if (EIT->getNumBits() > 128 ||
7850         (EIT->getNumBits() > 64 &&
7851          !getContext().getTargetInfo().hasInt128Type()))
7852       return getNaturalAlignIndirect(Ty);
7853 
7854   // All integral types are promoted to the GPR width.
7855   if (Ty->isIntegralOrEnumerationType())
7856     return extendType(Ty);
7857 
7858   return ABIArgInfo::getDirect(
7859       nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset));
7860 }
7861 
7862 llvm::Type*
7863 MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
7864   const RecordType *RT = RetTy->getAs<RecordType>();
7865   SmallVector<llvm::Type*, 8> RTList;
7866 
7867   if (RT && RT->isStructureOrClassType()) {
7868     const RecordDecl *RD = RT->getDecl();
7869     const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
7870     unsigned FieldCnt = Layout.getFieldCount();
7871 
7872     // N32/64 returns struct/classes in floating point registers if the
7873     // following conditions are met:
7874     // 1. The size of the struct/class is no larger than 128-bit.
7875     // 2. The struct/class has one or two fields all of which are floating
7876     //    point types.
7877     // 3. The offset of the first field is zero (this follows what gcc does).
7878     //
7879     // Any other composite results are returned in integer registers.
7880     //
7881     if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
7882       RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
7883       for (; b != e; ++b) {
7884         const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
7885 
7886         if (!BT || !BT->isFloatingPoint())
7887           break;
7888 
7889         RTList.push_back(CGT.ConvertType(b->getType()));
7890       }
7891 
7892       if (b == e)
7893         return llvm::StructType::get(getVMContext(), RTList,
7894                                      RD->hasAttr<PackedAttr>());
7895 
7896       RTList.clear();
7897     }
7898   }
7899 
7900   CoerceToIntArgs(Size, RTList);
7901   return llvm::StructType::get(getVMContext(), RTList);
7902 }
7903 
7904 ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
7905   uint64_t Size = getContext().getTypeSize(RetTy);
7906 
7907   if (RetTy->isVoidType())
7908     return ABIArgInfo::getIgnore();
7909 
7910   // O32 doesn't treat zero-sized structs differently from other structs.
7911   // However, N32/N64 ignores zero sized return values.
7912   if (!IsO32 && Size == 0)
7913     return ABIArgInfo::getIgnore();
7914 
7915   if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
7916     if (Size <= 128) {
7917       if (RetTy->isAnyComplexType())
7918         return ABIArgInfo::getDirect();
7919 
7920       // O32 returns integer vectors in registers and N32/N64 returns all small
7921       // aggregates in registers.
7922       if (!IsO32 ||
7923           (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) {
7924         ABIArgInfo ArgInfo =
7925             ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
7926         ArgInfo.setInReg(true);
7927         return ArgInfo;
7928       }
7929     }
7930 
7931     return getNaturalAlignIndirect(RetTy);
7932   }
7933 
7934   // Treat an enum type as its underlying type.
7935   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
7936     RetTy = EnumTy->getDecl()->getIntegerType();
7937 
7938   // Make sure we pass indirectly things that are too large.
7939   if (const auto *EIT = RetTy->getAs<ExtIntType>())
7940     if (EIT->getNumBits() > 128 ||
7941         (EIT->getNumBits() > 64 &&
7942          !getContext().getTargetInfo().hasInt128Type()))
7943       return getNaturalAlignIndirect(RetTy);
7944 
7945   if (isPromotableIntegerTypeForABI(RetTy))
7946     return ABIArgInfo::getExtend(RetTy);
7947 
7948   if ((RetTy->isUnsignedIntegerOrEnumerationType() ||
7949       RetTy->isSignedIntegerOrEnumerationType()) && Size == 32 && !IsO32)
7950     return ABIArgInfo::getSignExtend(RetTy);
7951 
7952   return ABIArgInfo::getDirect();
7953 }
7954 
7955 void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
7956   ABIArgInfo &RetInfo = FI.getReturnInfo();
7957   if (!getCXXABI().classifyReturnType(FI))
7958     RetInfo = classifyReturnType(FI.getReturnType());
7959 
7960   // Check if a pointer to an aggregate is passed as a hidden argument.
7961   uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
7962 
7963   for (auto &I : FI.arguments())
7964     I.info = classifyArgumentType(I.type, Offset);
7965 }
7966 
7967 Address MipsABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7968                                QualType OrigTy) const {
7969   QualType Ty = OrigTy;
7970 
7971   // Integer arguments are promoted to 32-bit on O32 and 64-bit on N32/N64.
7972   // Pointers are also promoted in the same way but this only matters for N32.
7973   unsigned SlotSizeInBits = IsO32 ? 32 : 64;
7974   unsigned PtrWidth = getTarget().getPointerWidth(0);
7975   bool DidPromote = false;
7976   if ((Ty->isIntegerType() &&
7977           getContext().getIntWidth(Ty) < SlotSizeInBits) ||
7978       (Ty->isPointerType() && PtrWidth < SlotSizeInBits)) {
7979     DidPromote = true;
7980     Ty = getContext().getIntTypeForBitwidth(SlotSizeInBits,
7981                                             Ty->isSignedIntegerType());
7982   }
7983 
7984   auto TyInfo = getContext().getTypeInfoInChars(Ty);
7985 
7986   // The alignment of things in the argument area is never larger than
7987   // StackAlignInBytes.
7988   TyInfo.Align =
7989     std::min(TyInfo.Align, CharUnits::fromQuantity(StackAlignInBytes));
7990 
7991   // MinABIStackAlignInBytes is the size of argument slots on the stack.
7992   CharUnits ArgSlotSize = CharUnits::fromQuantity(MinABIStackAlignInBytes);
7993 
7994   Address Addr = emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
7995                           TyInfo, ArgSlotSize, /*AllowHigherAlign*/ true);
7996 
7997 
7998   // If there was a promotion, "unpromote" into a temporary.
7999   // TODO: can we just use a pointer into a subset of the original slot?
8000   if (DidPromote) {
8001     Address Temp = CGF.CreateMemTemp(OrigTy, "vaarg.promotion-temp");
8002     llvm::Value *Promoted = CGF.Builder.CreateLoad(Addr);
8003 
8004     // Truncate down to the right width.
8005     llvm::Type *IntTy = (OrigTy->isIntegerType() ? Temp.getElementType()
8006                                                  : CGF.IntPtrTy);
8007     llvm::Value *V = CGF.Builder.CreateTrunc(Promoted, IntTy);
8008     if (OrigTy->isPointerType())
8009       V = CGF.Builder.CreateIntToPtr(V, Temp.getElementType());
8010 
8011     CGF.Builder.CreateStore(V, Temp);
8012     Addr = Temp;
8013   }
8014 
8015   return Addr;
8016 }
8017 
8018 ABIArgInfo MipsABIInfo::extendType(QualType Ty) const {
8019   int TySize = getContext().getTypeSize(Ty);
8020 
8021   // MIPS64 ABI requires unsigned 32 bit integers to be sign extended.
8022   if (Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
8023     return ABIArgInfo::getSignExtend(Ty);
8024 
8025   return ABIArgInfo::getExtend(Ty);
8026 }
8027 
8028 bool
8029 MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
8030                                                llvm::Value *Address) const {
8031   // This information comes from gcc's implementation, which seems to
8032   // as canonical as it gets.
8033 
8034   // Everything on MIPS is 4 bytes.  Double-precision FP registers
8035   // are aliased to pairs of single-precision FP registers.
8036   llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
8037 
8038   // 0-31 are the general purpose registers, $0 - $31.
8039   // 32-63 are the floating-point registers, $f0 - $f31.
8040   // 64 and 65 are the multiply/divide registers, $hi and $lo.
8041   // 66 is the (notional, I think) register for signal-handler return.
8042   AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
8043 
8044   // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
8045   // They are one bit wide and ignored here.
8046 
8047   // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
8048   // (coprocessor 1 is the FP unit)
8049   // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
8050   // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
8051   // 176-181 are the DSP accumulator registers.
8052   AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
8053   return false;
8054 }
8055 
8056 //===----------------------------------------------------------------------===//
8057 // AVR ABI Implementation.
8058 //===----------------------------------------------------------------------===//
8059 
8060 namespace {
8061 class AVRTargetCodeGenInfo : public TargetCodeGenInfo {
8062 public:
8063   AVRTargetCodeGenInfo(CodeGenTypes &CGT)
8064       : TargetCodeGenInfo(std::make_unique<DefaultABIInfo>(CGT)) {}
8065 
8066   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
8067                            CodeGen::CodeGenModule &CGM) const override {
8068     if (GV->isDeclaration())
8069       return;
8070     const auto *FD = dyn_cast_or_null<FunctionDecl>(D);
8071     if (!FD) return;
8072     auto *Fn = cast<llvm::Function>(GV);
8073 
8074     if (FD->getAttr<AVRInterruptAttr>())
8075       Fn->addFnAttr("interrupt");
8076 
8077     if (FD->getAttr<AVRSignalAttr>())
8078       Fn->addFnAttr("signal");
8079   }
8080 };
8081 }
8082 
8083 //===----------------------------------------------------------------------===//
8084 // TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
8085 // Currently subclassed only to implement custom OpenCL C function attribute
8086 // handling.
8087 //===----------------------------------------------------------------------===//
8088 
8089 namespace {
8090 
8091 class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
8092 public:
8093   TCETargetCodeGenInfo(CodeGenTypes &CGT)
8094     : DefaultTargetCodeGenInfo(CGT) {}
8095 
8096   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
8097                            CodeGen::CodeGenModule &M) const override;
8098 };
8099 
8100 void TCETargetCodeGenInfo::setTargetAttributes(
8101     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
8102   if (GV->isDeclaration())
8103     return;
8104   const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
8105   if (!FD) return;
8106 
8107   llvm::Function *F = cast<llvm::Function>(GV);
8108 
8109   if (M.getLangOpts().OpenCL) {
8110     if (FD->hasAttr<OpenCLKernelAttr>()) {
8111       // OpenCL C Kernel functions are not subject to inlining
8112       F->addFnAttr(llvm::Attribute::NoInline);
8113       const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
8114       if (Attr) {
8115         // Convert the reqd_work_group_size() attributes to metadata.
8116         llvm::LLVMContext &Context = F->getContext();
8117         llvm::NamedMDNode *OpenCLMetadata =
8118             M.getModule().getOrInsertNamedMetadata(
8119                 "opencl.kernel_wg_size_info");
8120 
8121         SmallVector<llvm::Metadata *, 5> Operands;
8122         Operands.push_back(llvm::ConstantAsMetadata::get(F));
8123 
8124         Operands.push_back(
8125             llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
8126                 M.Int32Ty, llvm::APInt(32, Attr->getXDim()))));
8127         Operands.push_back(
8128             llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
8129                 M.Int32Ty, llvm::APInt(32, Attr->getYDim()))));
8130         Operands.push_back(
8131             llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
8132                 M.Int32Ty, llvm::APInt(32, Attr->getZDim()))));
8133 
8134         // Add a boolean constant operand for "required" (true) or "hint"
8135         // (false) for implementing the work_group_size_hint attr later.
8136         // Currently always true as the hint is not yet implemented.
8137         Operands.push_back(
8138             llvm::ConstantAsMetadata::get(llvm::ConstantInt::getTrue(Context)));
8139         OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
8140       }
8141     }
8142   }
8143 }
8144 
8145 }
8146 
8147 //===----------------------------------------------------------------------===//
8148 // Hexagon ABI Implementation
8149 //===----------------------------------------------------------------------===//
8150 
8151 namespace {
8152 
8153 class HexagonABIInfo : public DefaultABIInfo {
8154 public:
8155   HexagonABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
8156 
8157 private:
8158   ABIArgInfo classifyReturnType(QualType RetTy) const;
8159   ABIArgInfo classifyArgumentType(QualType RetTy) const;
8160   ABIArgInfo classifyArgumentType(QualType RetTy, unsigned *RegsLeft) const;
8161 
8162   void computeInfo(CGFunctionInfo &FI) const override;
8163 
8164   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8165                     QualType Ty) const override;
8166   Address EmitVAArgFromMemory(CodeGenFunction &CFG, Address VAListAddr,
8167                               QualType Ty) const;
8168   Address EmitVAArgForHexagon(CodeGenFunction &CFG, Address VAListAddr,
8169                               QualType Ty) const;
8170   Address EmitVAArgForHexagonLinux(CodeGenFunction &CFG, Address VAListAddr,
8171                                    QualType Ty) const;
8172 };
8173 
8174 class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
8175 public:
8176   HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
8177       : TargetCodeGenInfo(std::make_unique<HexagonABIInfo>(CGT)) {}
8178 
8179   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
8180     return 29;
8181   }
8182 
8183   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
8184                            CodeGen::CodeGenModule &GCM) const override {
8185     if (GV->isDeclaration())
8186       return;
8187     const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
8188     if (!FD)
8189       return;
8190   }
8191 };
8192 
8193 } // namespace
8194 
8195 void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
8196   unsigned RegsLeft = 6;
8197   if (!getCXXABI().classifyReturnType(FI))
8198     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
8199   for (auto &I : FI.arguments())
8200     I.info = classifyArgumentType(I.type, &RegsLeft);
8201 }
8202 
8203 static bool HexagonAdjustRegsLeft(uint64_t Size, unsigned *RegsLeft) {
8204   assert(Size <= 64 && "Not expecting to pass arguments larger than 64 bits"
8205                        " through registers");
8206 
8207   if (*RegsLeft == 0)
8208     return false;
8209 
8210   if (Size <= 32) {
8211     (*RegsLeft)--;
8212     return true;
8213   }
8214 
8215   if (2 <= (*RegsLeft & (~1U))) {
8216     *RegsLeft = (*RegsLeft & (~1U)) - 2;
8217     return true;
8218   }
8219 
8220   // Next available register was r5 but candidate was greater than 32-bits so it
8221   // has to go on the stack. However we still consume r5
8222   if (*RegsLeft == 1)
8223     *RegsLeft = 0;
8224 
8225   return false;
8226 }
8227 
8228 ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty,
8229                                                 unsigned *RegsLeft) const {
8230   if (!isAggregateTypeForABI(Ty)) {
8231     // Treat an enum type as its underlying type.
8232     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
8233       Ty = EnumTy->getDecl()->getIntegerType();
8234 
8235     uint64_t Size = getContext().getTypeSize(Ty);
8236     if (Size <= 64)
8237       HexagonAdjustRegsLeft(Size, RegsLeft);
8238 
8239     if (Size > 64 && Ty->isExtIntType())
8240       return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
8241 
8242     return isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
8243                                              : ABIArgInfo::getDirect();
8244   }
8245 
8246   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
8247     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
8248 
8249   // Ignore empty records.
8250   if (isEmptyRecord(getContext(), Ty, true))
8251     return ABIArgInfo::getIgnore();
8252 
8253   uint64_t Size = getContext().getTypeSize(Ty);
8254   unsigned Align = getContext().getTypeAlign(Ty);
8255 
8256   if (Size > 64)
8257     return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
8258 
8259   if (HexagonAdjustRegsLeft(Size, RegsLeft))
8260     Align = Size <= 32 ? 32 : 64;
8261   if (Size <= Align) {
8262     // Pass in the smallest viable integer type.
8263     if (!llvm::isPowerOf2_64(Size))
8264       Size = llvm::NextPowerOf2(Size);
8265     return ABIArgInfo::getDirect(llvm::Type::getIntNTy(getVMContext(), Size));
8266   }
8267   return DefaultABIInfo::classifyArgumentType(Ty);
8268 }
8269 
8270 ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
8271   if (RetTy->isVoidType())
8272     return ABIArgInfo::getIgnore();
8273 
8274   const TargetInfo &T = CGT.getTarget();
8275   uint64_t Size = getContext().getTypeSize(RetTy);
8276 
8277   if (RetTy->getAs<VectorType>()) {
8278     // HVX vectors are returned in vector registers or register pairs.
8279     if (T.hasFeature("hvx")) {
8280       assert(T.hasFeature("hvx-length64b") || T.hasFeature("hvx-length128b"));
8281       uint64_t VecSize = T.hasFeature("hvx-length64b") ? 64*8 : 128*8;
8282       if (Size == VecSize || Size == 2*VecSize)
8283         return ABIArgInfo::getDirectInReg();
8284     }
8285     // Large vector types should be returned via memory.
8286     if (Size > 64)
8287       return getNaturalAlignIndirect(RetTy);
8288   }
8289 
8290   if (!isAggregateTypeForABI(RetTy)) {
8291     // Treat an enum type as its underlying type.
8292     if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
8293       RetTy = EnumTy->getDecl()->getIntegerType();
8294 
8295     if (Size > 64 && RetTy->isExtIntType())
8296       return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
8297 
8298     return isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
8299                                                 : ABIArgInfo::getDirect();
8300   }
8301 
8302   if (isEmptyRecord(getContext(), RetTy, true))
8303     return ABIArgInfo::getIgnore();
8304 
8305   // Aggregates <= 8 bytes are returned in registers, other aggregates
8306   // are returned indirectly.
8307   if (Size <= 64) {
8308     // Return in the smallest viable integer type.
8309     if (!llvm::isPowerOf2_64(Size))
8310       Size = llvm::NextPowerOf2(Size);
8311     return ABIArgInfo::getDirect(llvm::Type::getIntNTy(getVMContext(), Size));
8312   }
8313   return getNaturalAlignIndirect(RetTy, /*ByVal=*/true);
8314 }
8315 
8316 Address HexagonABIInfo::EmitVAArgFromMemory(CodeGenFunction &CGF,
8317                                             Address VAListAddr,
8318                                             QualType Ty) const {
8319   // Load the overflow area pointer.
8320   Address __overflow_area_pointer_p =
8321       CGF.Builder.CreateStructGEP(VAListAddr, 2, "__overflow_area_pointer_p");
8322   llvm::Value *__overflow_area_pointer = CGF.Builder.CreateLoad(
8323       __overflow_area_pointer_p, "__overflow_area_pointer");
8324 
8325   uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8;
8326   if (Align > 4) {
8327     // Alignment should be a power of 2.
8328     assert((Align & (Align - 1)) == 0 && "Alignment is not power of 2!");
8329 
8330     // overflow_arg_area = (overflow_arg_area + align - 1) & -align;
8331     llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int64Ty, Align - 1);
8332 
8333     // Add offset to the current pointer to access the argument.
8334     __overflow_area_pointer =
8335         CGF.Builder.CreateGEP(__overflow_area_pointer, Offset);
8336     llvm::Value *AsInt =
8337         CGF.Builder.CreatePtrToInt(__overflow_area_pointer, CGF.Int32Ty);
8338 
8339     // Create a mask which should be "AND"ed
8340     // with (overflow_arg_area + align - 1)
8341     llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int32Ty, -(int)Align);
8342     __overflow_area_pointer = CGF.Builder.CreateIntToPtr(
8343         CGF.Builder.CreateAnd(AsInt, Mask), __overflow_area_pointer->getType(),
8344         "__overflow_area_pointer.align");
8345   }
8346 
8347   // Get the type of the argument from memory and bitcast
8348   // overflow area pointer to the argument type.
8349   llvm::Type *PTy = CGF.ConvertTypeForMem(Ty);
8350   Address AddrTyped = CGF.Builder.CreateBitCast(
8351       Address(__overflow_area_pointer, CharUnits::fromQuantity(Align)),
8352       llvm::PointerType::getUnqual(PTy));
8353 
8354   // Round up to the minimum stack alignment for varargs which is 4 bytes.
8355   uint64_t Offset = llvm::alignTo(CGF.getContext().getTypeSize(Ty) / 8, 4);
8356 
8357   __overflow_area_pointer = CGF.Builder.CreateGEP(
8358       __overflow_area_pointer, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
8359       "__overflow_area_pointer.next");
8360   CGF.Builder.CreateStore(__overflow_area_pointer, __overflow_area_pointer_p);
8361 
8362   return AddrTyped;
8363 }
8364 
8365 Address HexagonABIInfo::EmitVAArgForHexagon(CodeGenFunction &CGF,
8366                                             Address VAListAddr,
8367                                             QualType Ty) const {
8368   // FIXME: Need to handle alignment
8369   llvm::Type *BP = CGF.Int8PtrTy;
8370   llvm::Type *BPP = CGF.Int8PtrPtrTy;
8371   CGBuilderTy &Builder = CGF.Builder;
8372   Address VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
8373   llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
8374   // Handle address alignment for type alignment > 32 bits
8375   uint64_t TyAlign = CGF.getContext().getTypeAlign(Ty) / 8;
8376   if (TyAlign > 4) {
8377     assert((TyAlign & (TyAlign - 1)) == 0 && "Alignment is not power of 2!");
8378     llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int32Ty);
8379     AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt32(TyAlign - 1));
8380     AddrAsInt = Builder.CreateAnd(AddrAsInt, Builder.getInt32(~(TyAlign - 1)));
8381     Addr = Builder.CreateIntToPtr(AddrAsInt, BP);
8382   }
8383   llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
8384   Address AddrTyped = Builder.CreateBitCast(
8385       Address(Addr, CharUnits::fromQuantity(TyAlign)), PTy);
8386 
8387   uint64_t Offset = llvm::alignTo(CGF.getContext().getTypeSize(Ty) / 8, 4);
8388   llvm::Value *NextAddr = Builder.CreateGEP(
8389       Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset), "ap.next");
8390   Builder.CreateStore(NextAddr, VAListAddrAsBPP);
8391 
8392   return AddrTyped;
8393 }
8394 
8395 Address HexagonABIInfo::EmitVAArgForHexagonLinux(CodeGenFunction &CGF,
8396                                                  Address VAListAddr,
8397                                                  QualType Ty) const {
8398   int ArgSize = CGF.getContext().getTypeSize(Ty) / 8;
8399 
8400   if (ArgSize > 8)
8401     return EmitVAArgFromMemory(CGF, VAListAddr, Ty);
8402 
8403   // Here we have check if the argument is in register area or
8404   // in overflow area.
8405   // If the saved register area pointer + argsize rounded up to alignment >
8406   // saved register area end pointer, argument is in overflow area.
8407   unsigned RegsLeft = 6;
8408   Ty = CGF.getContext().getCanonicalType(Ty);
8409   (void)classifyArgumentType(Ty, &RegsLeft);
8410 
8411   llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
8412   llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
8413   llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
8414   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
8415 
8416   // Get rounded size of the argument.GCC does not allow vararg of
8417   // size < 4 bytes. We follow the same logic here.
8418   ArgSize = (CGF.getContext().getTypeSize(Ty) <= 32) ? 4 : 8;
8419   int ArgAlign = (CGF.getContext().getTypeSize(Ty) <= 32) ? 4 : 8;
8420 
8421   // Argument may be in saved register area
8422   CGF.EmitBlock(MaybeRegBlock);
8423 
8424   // Load the current saved register area pointer.
8425   Address __current_saved_reg_area_pointer_p = CGF.Builder.CreateStructGEP(
8426       VAListAddr, 0, "__current_saved_reg_area_pointer_p");
8427   llvm::Value *__current_saved_reg_area_pointer = CGF.Builder.CreateLoad(
8428       __current_saved_reg_area_pointer_p, "__current_saved_reg_area_pointer");
8429 
8430   // Load the saved register area end pointer.
8431   Address __saved_reg_area_end_pointer_p = CGF.Builder.CreateStructGEP(
8432       VAListAddr, 1, "__saved_reg_area_end_pointer_p");
8433   llvm::Value *__saved_reg_area_end_pointer = CGF.Builder.CreateLoad(
8434       __saved_reg_area_end_pointer_p, "__saved_reg_area_end_pointer");
8435 
8436   // If the size of argument is > 4 bytes, check if the stack
8437   // location is aligned to 8 bytes
8438   if (ArgAlign > 4) {
8439 
8440     llvm::Value *__current_saved_reg_area_pointer_int =
8441         CGF.Builder.CreatePtrToInt(__current_saved_reg_area_pointer,
8442                                    CGF.Int32Ty);
8443 
8444     __current_saved_reg_area_pointer_int = CGF.Builder.CreateAdd(
8445         __current_saved_reg_area_pointer_int,
8446         llvm::ConstantInt::get(CGF.Int32Ty, (ArgAlign - 1)),
8447         "align_current_saved_reg_area_pointer");
8448 
8449     __current_saved_reg_area_pointer_int =
8450         CGF.Builder.CreateAnd(__current_saved_reg_area_pointer_int,
8451                               llvm::ConstantInt::get(CGF.Int32Ty, -ArgAlign),
8452                               "align_current_saved_reg_area_pointer");
8453 
8454     __current_saved_reg_area_pointer =
8455         CGF.Builder.CreateIntToPtr(__current_saved_reg_area_pointer_int,
8456                                    __current_saved_reg_area_pointer->getType(),
8457                                    "align_current_saved_reg_area_pointer");
8458   }
8459 
8460   llvm::Value *__new_saved_reg_area_pointer =
8461       CGF.Builder.CreateGEP(__current_saved_reg_area_pointer,
8462                             llvm::ConstantInt::get(CGF.Int32Ty, ArgSize),
8463                             "__new_saved_reg_area_pointer");
8464 
8465   llvm::Value *UsingStack = 0;
8466   UsingStack = CGF.Builder.CreateICmpSGT(__new_saved_reg_area_pointer,
8467                                          __saved_reg_area_end_pointer);
8468 
8469   CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, InRegBlock);
8470 
8471   // Argument in saved register area
8472   // Implement the block where argument is in register saved area
8473   CGF.EmitBlock(InRegBlock);
8474 
8475   llvm::Type *PTy = CGF.ConvertType(Ty);
8476   llvm::Value *__saved_reg_area_p = CGF.Builder.CreateBitCast(
8477       __current_saved_reg_area_pointer, llvm::PointerType::getUnqual(PTy));
8478 
8479   CGF.Builder.CreateStore(__new_saved_reg_area_pointer,
8480                           __current_saved_reg_area_pointer_p);
8481 
8482   CGF.EmitBranch(ContBlock);
8483 
8484   // Argument in overflow area
8485   // Implement the block where the argument is in overflow area.
8486   CGF.EmitBlock(OnStackBlock);
8487 
8488   // Load the overflow area pointer
8489   Address __overflow_area_pointer_p =
8490       CGF.Builder.CreateStructGEP(VAListAddr, 2, "__overflow_area_pointer_p");
8491   llvm::Value *__overflow_area_pointer = CGF.Builder.CreateLoad(
8492       __overflow_area_pointer_p, "__overflow_area_pointer");
8493 
8494   // Align the overflow area pointer according to the alignment of the argument
8495   if (ArgAlign > 4) {
8496     llvm::Value *__overflow_area_pointer_int =
8497         CGF.Builder.CreatePtrToInt(__overflow_area_pointer, CGF.Int32Ty);
8498 
8499     __overflow_area_pointer_int =
8500         CGF.Builder.CreateAdd(__overflow_area_pointer_int,
8501                               llvm::ConstantInt::get(CGF.Int32Ty, ArgAlign - 1),
8502                               "align_overflow_area_pointer");
8503 
8504     __overflow_area_pointer_int =
8505         CGF.Builder.CreateAnd(__overflow_area_pointer_int,
8506                               llvm::ConstantInt::get(CGF.Int32Ty, -ArgAlign),
8507                               "align_overflow_area_pointer");
8508 
8509     __overflow_area_pointer = CGF.Builder.CreateIntToPtr(
8510         __overflow_area_pointer_int, __overflow_area_pointer->getType(),
8511         "align_overflow_area_pointer");
8512   }
8513 
8514   // Get the pointer for next argument in overflow area and store it
8515   // to overflow area pointer.
8516   llvm::Value *__new_overflow_area_pointer = CGF.Builder.CreateGEP(
8517       __overflow_area_pointer, llvm::ConstantInt::get(CGF.Int32Ty, ArgSize),
8518       "__overflow_area_pointer.next");
8519 
8520   CGF.Builder.CreateStore(__new_overflow_area_pointer,
8521                           __overflow_area_pointer_p);
8522 
8523   CGF.Builder.CreateStore(__new_overflow_area_pointer,
8524                           __current_saved_reg_area_pointer_p);
8525 
8526   // Bitcast the overflow area pointer to the type of argument.
8527   llvm::Type *OverflowPTy = CGF.ConvertTypeForMem(Ty);
8528   llvm::Value *__overflow_area_p = CGF.Builder.CreateBitCast(
8529       __overflow_area_pointer, llvm::PointerType::getUnqual(OverflowPTy));
8530 
8531   CGF.EmitBranch(ContBlock);
8532 
8533   // Get the correct pointer to load the variable argument
8534   // Implement the ContBlock
8535   CGF.EmitBlock(ContBlock);
8536 
8537   llvm::Type *MemPTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
8538   llvm::PHINode *ArgAddr = CGF.Builder.CreatePHI(MemPTy, 2, "vaarg.addr");
8539   ArgAddr->addIncoming(__saved_reg_area_p, InRegBlock);
8540   ArgAddr->addIncoming(__overflow_area_p, OnStackBlock);
8541 
8542   return Address(ArgAddr, CharUnits::fromQuantity(ArgAlign));
8543 }
8544 
8545 Address HexagonABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8546                                   QualType Ty) const {
8547 
8548   if (getTarget().getTriple().isMusl())
8549     return EmitVAArgForHexagonLinux(CGF, VAListAddr, Ty);
8550 
8551   return EmitVAArgForHexagon(CGF, VAListAddr, Ty);
8552 }
8553 
8554 //===----------------------------------------------------------------------===//
8555 // Lanai ABI Implementation
8556 //===----------------------------------------------------------------------===//
8557 
8558 namespace {
8559 class LanaiABIInfo : public DefaultABIInfo {
8560 public:
8561   LanaiABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
8562 
8563   bool shouldUseInReg(QualType Ty, CCState &State) const;
8564 
8565   void computeInfo(CGFunctionInfo &FI) const override {
8566     CCState State(FI);
8567     // Lanai uses 4 registers to pass arguments unless the function has the
8568     // regparm attribute set.
8569     if (FI.getHasRegParm()) {
8570       State.FreeRegs = FI.getRegParm();
8571     } else {
8572       State.FreeRegs = 4;
8573     }
8574 
8575     if (!getCXXABI().classifyReturnType(FI))
8576       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
8577     for (auto &I : FI.arguments())
8578       I.info = classifyArgumentType(I.type, State);
8579   }
8580 
8581   ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
8582   ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
8583 };
8584 } // end anonymous namespace
8585 
8586 bool LanaiABIInfo::shouldUseInReg(QualType Ty, CCState &State) const {
8587   unsigned Size = getContext().getTypeSize(Ty);
8588   unsigned SizeInRegs = llvm::alignTo(Size, 32U) / 32U;
8589 
8590   if (SizeInRegs == 0)
8591     return false;
8592 
8593   if (SizeInRegs > State.FreeRegs) {
8594     State.FreeRegs = 0;
8595     return false;
8596   }
8597 
8598   State.FreeRegs -= SizeInRegs;
8599 
8600   return true;
8601 }
8602 
8603 ABIArgInfo LanaiABIInfo::getIndirectResult(QualType Ty, bool ByVal,
8604                                            CCState &State) const {
8605   if (!ByVal) {
8606     if (State.FreeRegs) {
8607       --State.FreeRegs; // Non-byval indirects just use one pointer.
8608       return getNaturalAlignIndirectInReg(Ty);
8609     }
8610     return getNaturalAlignIndirect(Ty, false);
8611   }
8612 
8613   // Compute the byval alignment.
8614   const unsigned MinABIStackAlignInBytes = 4;
8615   unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
8616   return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true,
8617                                  /*Realign=*/TypeAlign >
8618                                      MinABIStackAlignInBytes);
8619 }
8620 
8621 ABIArgInfo LanaiABIInfo::classifyArgumentType(QualType Ty,
8622                                               CCState &State) const {
8623   // Check with the C++ ABI first.
8624   const RecordType *RT = Ty->getAs<RecordType>();
8625   if (RT) {
8626     CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
8627     if (RAA == CGCXXABI::RAA_Indirect) {
8628       return getIndirectResult(Ty, /*ByVal=*/false, State);
8629     } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
8630       return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
8631     }
8632   }
8633 
8634   if (isAggregateTypeForABI(Ty)) {
8635     // Structures with flexible arrays are always indirect.
8636     if (RT && RT->getDecl()->hasFlexibleArrayMember())
8637       return getIndirectResult(Ty, /*ByVal=*/true, State);
8638 
8639     // Ignore empty structs/unions.
8640     if (isEmptyRecord(getContext(), Ty, true))
8641       return ABIArgInfo::getIgnore();
8642 
8643     llvm::LLVMContext &LLVMContext = getVMContext();
8644     unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
8645     if (SizeInRegs <= State.FreeRegs) {
8646       llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
8647       SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32);
8648       llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
8649       State.FreeRegs -= SizeInRegs;
8650       return ABIArgInfo::getDirectInReg(Result);
8651     } else {
8652       State.FreeRegs = 0;
8653     }
8654     return getIndirectResult(Ty, true, State);
8655   }
8656 
8657   // Treat an enum type as its underlying type.
8658   if (const auto *EnumTy = Ty->getAs<EnumType>())
8659     Ty = EnumTy->getDecl()->getIntegerType();
8660 
8661   bool InReg = shouldUseInReg(Ty, State);
8662 
8663   // Don't pass >64 bit integers in registers.
8664   if (const auto *EIT = Ty->getAs<ExtIntType>())
8665     if (EIT->getNumBits() > 64)
8666       return getIndirectResult(Ty, /*ByVal=*/true, State);
8667 
8668   if (isPromotableIntegerTypeForABI(Ty)) {
8669     if (InReg)
8670       return ABIArgInfo::getDirectInReg();
8671     return ABIArgInfo::getExtend(Ty);
8672   }
8673   if (InReg)
8674     return ABIArgInfo::getDirectInReg();
8675   return ABIArgInfo::getDirect();
8676 }
8677 
8678 namespace {
8679 class LanaiTargetCodeGenInfo : public TargetCodeGenInfo {
8680 public:
8681   LanaiTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
8682       : TargetCodeGenInfo(std::make_unique<LanaiABIInfo>(CGT)) {}
8683 };
8684 }
8685 
8686 //===----------------------------------------------------------------------===//
8687 // AMDGPU ABI Implementation
8688 //===----------------------------------------------------------------------===//
8689 
8690 namespace {
8691 
8692 class AMDGPUABIInfo final : public DefaultABIInfo {
8693 private:
8694   static const unsigned MaxNumRegsForArgsRet = 16;
8695 
8696   unsigned numRegsForType(QualType Ty) const;
8697 
8698   bool isHomogeneousAggregateBaseType(QualType Ty) const override;
8699   bool isHomogeneousAggregateSmallEnough(const Type *Base,
8700                                          uint64_t Members) const override;
8701 
8702   // Coerce HIP scalar pointer arguments from generic pointers to global ones.
8703   llvm::Type *coerceKernelArgumentType(llvm::Type *Ty, unsigned FromAS,
8704                                        unsigned ToAS) const {
8705     // Single value types.
8706     if (Ty->isPointerTy() && Ty->getPointerAddressSpace() == FromAS)
8707       return llvm::PointerType::get(
8708           cast<llvm::PointerType>(Ty)->getElementType(), ToAS);
8709     return Ty;
8710   }
8711 
8712 public:
8713   explicit AMDGPUABIInfo(CodeGen::CodeGenTypes &CGT) :
8714     DefaultABIInfo(CGT) {}
8715 
8716   ABIArgInfo classifyReturnType(QualType RetTy) const;
8717   ABIArgInfo classifyKernelArgumentType(QualType Ty) const;
8718   ABIArgInfo classifyArgumentType(QualType Ty, unsigned &NumRegsLeft) const;
8719 
8720   void computeInfo(CGFunctionInfo &FI) const override;
8721   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8722                     QualType Ty) const override;
8723 };
8724 
8725 bool AMDGPUABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
8726   return true;
8727 }
8728 
8729 bool AMDGPUABIInfo::isHomogeneousAggregateSmallEnough(
8730   const Type *Base, uint64_t Members) const {
8731   uint32_t NumRegs = (getContext().getTypeSize(Base) + 31) / 32;
8732 
8733   // Homogeneous Aggregates may occupy at most 16 registers.
8734   return Members * NumRegs <= MaxNumRegsForArgsRet;
8735 }
8736 
8737 /// Estimate number of registers the type will use when passed in registers.
8738 unsigned AMDGPUABIInfo::numRegsForType(QualType Ty) const {
8739   unsigned NumRegs = 0;
8740 
8741   if (const VectorType *VT = Ty->getAs<VectorType>()) {
8742     // Compute from the number of elements. The reported size is based on the
8743     // in-memory size, which includes the padding 4th element for 3-vectors.
8744     QualType EltTy = VT->getElementType();
8745     unsigned EltSize = getContext().getTypeSize(EltTy);
8746 
8747     // 16-bit element vectors should be passed as packed.
8748     if (EltSize == 16)
8749       return (VT->getNumElements() + 1) / 2;
8750 
8751     unsigned EltNumRegs = (EltSize + 31) / 32;
8752     return EltNumRegs * VT->getNumElements();
8753   }
8754 
8755   if (const RecordType *RT = Ty->getAs<RecordType>()) {
8756     const RecordDecl *RD = RT->getDecl();
8757     assert(!RD->hasFlexibleArrayMember());
8758 
8759     for (const FieldDecl *Field : RD->fields()) {
8760       QualType FieldTy = Field->getType();
8761       NumRegs += numRegsForType(FieldTy);
8762     }
8763 
8764     return NumRegs;
8765   }
8766 
8767   return (getContext().getTypeSize(Ty) + 31) / 32;
8768 }
8769 
8770 void AMDGPUABIInfo::computeInfo(CGFunctionInfo &FI) const {
8771   llvm::CallingConv::ID CC = FI.getCallingConvention();
8772 
8773   if (!getCXXABI().classifyReturnType(FI))
8774     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
8775 
8776   unsigned NumRegsLeft = MaxNumRegsForArgsRet;
8777   for (auto &Arg : FI.arguments()) {
8778     if (CC == llvm::CallingConv::AMDGPU_KERNEL) {
8779       Arg.info = classifyKernelArgumentType(Arg.type);
8780     } else {
8781       Arg.info = classifyArgumentType(Arg.type, NumRegsLeft);
8782     }
8783   }
8784 }
8785 
8786 Address AMDGPUABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8787                                  QualType Ty) const {
8788   llvm_unreachable("AMDGPU does not support varargs");
8789 }
8790 
8791 ABIArgInfo AMDGPUABIInfo::classifyReturnType(QualType RetTy) const {
8792   if (isAggregateTypeForABI(RetTy)) {
8793     // Records with non-trivial destructors/copy-constructors should not be
8794     // returned by value.
8795     if (!getRecordArgABI(RetTy, getCXXABI())) {
8796       // Ignore empty structs/unions.
8797       if (isEmptyRecord(getContext(), RetTy, true))
8798         return ABIArgInfo::getIgnore();
8799 
8800       // Lower single-element structs to just return a regular value.
8801       if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
8802         return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
8803 
8804       if (const RecordType *RT = RetTy->getAs<RecordType>()) {
8805         const RecordDecl *RD = RT->getDecl();
8806         if (RD->hasFlexibleArrayMember())
8807           return DefaultABIInfo::classifyReturnType(RetTy);
8808       }
8809 
8810       // Pack aggregates <= 4 bytes into single VGPR or pair.
8811       uint64_t Size = getContext().getTypeSize(RetTy);
8812       if (Size <= 16)
8813         return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
8814 
8815       if (Size <= 32)
8816         return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
8817 
8818       if (Size <= 64) {
8819         llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext());
8820         return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2));
8821       }
8822 
8823       if (numRegsForType(RetTy) <= MaxNumRegsForArgsRet)
8824         return ABIArgInfo::getDirect();
8825     }
8826   }
8827 
8828   // Otherwise just do the default thing.
8829   return DefaultABIInfo::classifyReturnType(RetTy);
8830 }
8831 
8832 /// For kernels all parameters are really passed in a special buffer. It doesn't
8833 /// make sense to pass anything byval, so everything must be direct.
8834 ABIArgInfo AMDGPUABIInfo::classifyKernelArgumentType(QualType Ty) const {
8835   Ty = useFirstFieldIfTransparentUnion(Ty);
8836 
8837   // TODO: Can we omit empty structs?
8838 
8839   if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
8840     Ty = QualType(SeltTy, 0);
8841 
8842   llvm::Type *OrigLTy = CGT.ConvertType(Ty);
8843   llvm::Type *LTy = OrigLTy;
8844   if (getContext().getLangOpts().HIP) {
8845     LTy = coerceKernelArgumentType(
8846         OrigLTy, /*FromAS=*/getContext().getTargetAddressSpace(LangAS::Default),
8847         /*ToAS=*/getContext().getTargetAddressSpace(LangAS::cuda_device));
8848   }
8849 
8850   // FIXME: Should also use this for OpenCL, but it requires addressing the
8851   // problem of kernels being called.
8852   //
8853   // FIXME: This doesn't apply the optimization of coercing pointers in structs
8854   // to global address space when using byref. This would require implementing a
8855   // new kind of coercion of the in-memory type when for indirect arguments.
8856   if (!getContext().getLangOpts().OpenCL && LTy == OrigLTy &&
8857       isAggregateTypeForABI(Ty)) {
8858     return ABIArgInfo::getIndirectAliased(
8859         getContext().getTypeAlignInChars(Ty),
8860         getContext().getTargetAddressSpace(LangAS::opencl_constant),
8861         false /*Realign*/, nullptr /*Padding*/);
8862   }
8863 
8864   // If we set CanBeFlattened to true, CodeGen will expand the struct to its
8865   // individual elements, which confuses the Clover OpenCL backend; therefore we
8866   // have to set it to false here. Other args of getDirect() are just defaults.
8867   return ABIArgInfo::getDirect(LTy, 0, nullptr, false);
8868 }
8869 
8870 ABIArgInfo AMDGPUABIInfo::classifyArgumentType(QualType Ty,
8871                                                unsigned &NumRegsLeft) const {
8872   assert(NumRegsLeft <= MaxNumRegsForArgsRet && "register estimate underflow");
8873 
8874   Ty = useFirstFieldIfTransparentUnion(Ty);
8875 
8876   if (isAggregateTypeForABI(Ty)) {
8877     // Records with non-trivial destructors/copy-constructors should not be
8878     // passed by value.
8879     if (auto RAA = getRecordArgABI(Ty, getCXXABI()))
8880       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
8881 
8882     // Ignore empty structs/unions.
8883     if (isEmptyRecord(getContext(), Ty, true))
8884       return ABIArgInfo::getIgnore();
8885 
8886     // Lower single-element structs to just pass a regular value. TODO: We
8887     // could do reasonable-size multiple-element structs too, using getExpand(),
8888     // though watch out for things like bitfields.
8889     if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
8890       return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
8891 
8892     if (const RecordType *RT = Ty->getAs<RecordType>()) {
8893       const RecordDecl *RD = RT->getDecl();
8894       if (RD->hasFlexibleArrayMember())
8895         return DefaultABIInfo::classifyArgumentType(Ty);
8896     }
8897 
8898     // Pack aggregates <= 8 bytes into single VGPR or pair.
8899     uint64_t Size = getContext().getTypeSize(Ty);
8900     if (Size <= 64) {
8901       unsigned NumRegs = (Size + 31) / 32;
8902       NumRegsLeft -= std::min(NumRegsLeft, NumRegs);
8903 
8904       if (Size <= 16)
8905         return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
8906 
8907       if (Size <= 32)
8908         return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
8909 
8910       // XXX: Should this be i64 instead, and should the limit increase?
8911       llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext());
8912       return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2));
8913     }
8914 
8915     if (NumRegsLeft > 0) {
8916       unsigned NumRegs = numRegsForType(Ty);
8917       if (NumRegsLeft >= NumRegs) {
8918         NumRegsLeft -= NumRegs;
8919         return ABIArgInfo::getDirect();
8920       }
8921     }
8922   }
8923 
8924   // Otherwise just do the default thing.
8925   ABIArgInfo ArgInfo = DefaultABIInfo::classifyArgumentType(Ty);
8926   if (!ArgInfo.isIndirect()) {
8927     unsigned NumRegs = numRegsForType(Ty);
8928     NumRegsLeft -= std::min(NumRegs, NumRegsLeft);
8929   }
8930 
8931   return ArgInfo;
8932 }
8933 
8934 class AMDGPUTargetCodeGenInfo : public TargetCodeGenInfo {
8935 public:
8936   AMDGPUTargetCodeGenInfo(CodeGenTypes &CGT)
8937       : TargetCodeGenInfo(std::make_unique<AMDGPUABIInfo>(CGT)) {}
8938   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
8939                            CodeGen::CodeGenModule &M) const override;
8940   unsigned getOpenCLKernelCallingConv() const override;
8941 
8942   llvm::Constant *getNullPointer(const CodeGen::CodeGenModule &CGM,
8943       llvm::PointerType *T, QualType QT) const override;
8944 
8945   LangAS getASTAllocaAddressSpace() const override {
8946     return getLangASFromTargetAS(
8947         getABIInfo().getDataLayout().getAllocaAddrSpace());
8948   }
8949   LangAS getGlobalVarAddressSpace(CodeGenModule &CGM,
8950                                   const VarDecl *D) const override;
8951   llvm::SyncScope::ID getLLVMSyncScopeID(const LangOptions &LangOpts,
8952                                          SyncScope Scope,
8953                                          llvm::AtomicOrdering Ordering,
8954                                          llvm::LLVMContext &Ctx) const override;
8955   llvm::Function *
8956   createEnqueuedBlockKernel(CodeGenFunction &CGF,
8957                             llvm::Function *BlockInvokeFunc,
8958                             llvm::Value *BlockLiteral) const override;
8959   bool shouldEmitStaticExternCAliases() const override;
8960   void setCUDAKernelCallingConvention(const FunctionType *&FT) const override;
8961 };
8962 }
8963 
8964 static bool requiresAMDGPUProtectedVisibility(const Decl *D,
8965                                               llvm::GlobalValue *GV) {
8966   if (GV->getVisibility() != llvm::GlobalValue::HiddenVisibility)
8967     return false;
8968 
8969   return D->hasAttr<OpenCLKernelAttr>() ||
8970          (isa<FunctionDecl>(D) && D->hasAttr<CUDAGlobalAttr>()) ||
8971          (isa<VarDecl>(D) &&
8972           (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>() ||
8973            cast<VarDecl>(D)->getType()->isCUDADeviceBuiltinSurfaceType() ||
8974            cast<VarDecl>(D)->getType()->isCUDADeviceBuiltinTextureType()));
8975 }
8976 
8977 void AMDGPUTargetCodeGenInfo::setTargetAttributes(
8978     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
8979   if (requiresAMDGPUProtectedVisibility(D, GV)) {
8980     GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
8981     GV->setDSOLocal(true);
8982   }
8983 
8984   if (GV->isDeclaration())
8985     return;
8986   const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
8987   if (!FD)
8988     return;
8989 
8990   llvm::Function *F = cast<llvm::Function>(GV);
8991 
8992   const auto *ReqdWGS = M.getLangOpts().OpenCL ?
8993     FD->getAttr<ReqdWorkGroupSizeAttr>() : nullptr;
8994 
8995 
8996   const bool IsOpenCLKernel = M.getLangOpts().OpenCL &&
8997                               FD->hasAttr<OpenCLKernelAttr>();
8998   const bool IsHIPKernel = M.getLangOpts().HIP &&
8999                            FD->hasAttr<CUDAGlobalAttr>();
9000   if ((IsOpenCLKernel || IsHIPKernel) &&
9001       (M.getTriple().getOS() == llvm::Triple::AMDHSA))
9002     F->addFnAttr("amdgpu-implicitarg-num-bytes", "56");
9003 
9004   if (IsHIPKernel)
9005     F->addFnAttr("uniform-work-group-size", "true");
9006 
9007 
9008   const auto *FlatWGS = FD->getAttr<AMDGPUFlatWorkGroupSizeAttr>();
9009   if (ReqdWGS || FlatWGS) {
9010     unsigned Min = 0;
9011     unsigned Max = 0;
9012     if (FlatWGS) {
9013       Min = FlatWGS->getMin()
9014                 ->EvaluateKnownConstInt(M.getContext())
9015                 .getExtValue();
9016       Max = FlatWGS->getMax()
9017                 ->EvaluateKnownConstInt(M.getContext())
9018                 .getExtValue();
9019     }
9020     if (ReqdWGS && Min == 0 && Max == 0)
9021       Min = Max = ReqdWGS->getXDim() * ReqdWGS->getYDim() * ReqdWGS->getZDim();
9022 
9023     if (Min != 0) {
9024       assert(Min <= Max && "Min must be less than or equal Max");
9025 
9026       std::string AttrVal = llvm::utostr(Min) + "," + llvm::utostr(Max);
9027       F->addFnAttr("amdgpu-flat-work-group-size", AttrVal);
9028     } else
9029       assert(Max == 0 && "Max must be zero");
9030   } else if (IsOpenCLKernel || IsHIPKernel) {
9031     // By default, restrict the maximum size to a value specified by
9032     // --gpu-max-threads-per-block=n or its default value for HIP.
9033     const unsigned OpenCLDefaultMaxWorkGroupSize = 256;
9034     const unsigned DefaultMaxWorkGroupSize =
9035         IsOpenCLKernel ? OpenCLDefaultMaxWorkGroupSize
9036                        : M.getLangOpts().GPUMaxThreadsPerBlock;
9037     std::string AttrVal =
9038         std::string("1,") + llvm::utostr(DefaultMaxWorkGroupSize);
9039     F->addFnAttr("amdgpu-flat-work-group-size", AttrVal);
9040   }
9041 
9042   if (const auto *Attr = FD->getAttr<AMDGPUWavesPerEUAttr>()) {
9043     unsigned Min =
9044         Attr->getMin()->EvaluateKnownConstInt(M.getContext()).getExtValue();
9045     unsigned Max = Attr->getMax() ? Attr->getMax()
9046                                         ->EvaluateKnownConstInt(M.getContext())
9047                                         .getExtValue()
9048                                   : 0;
9049 
9050     if (Min != 0) {
9051       assert((Max == 0 || Min <= Max) && "Min must be less than or equal Max");
9052 
9053       std::string AttrVal = llvm::utostr(Min);
9054       if (Max != 0)
9055         AttrVal = AttrVal + "," + llvm::utostr(Max);
9056       F->addFnAttr("amdgpu-waves-per-eu", AttrVal);
9057     } else
9058       assert(Max == 0 && "Max must be zero");
9059   }
9060 
9061   if (const auto *Attr = FD->getAttr<AMDGPUNumSGPRAttr>()) {
9062     unsigned NumSGPR = Attr->getNumSGPR();
9063 
9064     if (NumSGPR != 0)
9065       F->addFnAttr("amdgpu-num-sgpr", llvm::utostr(NumSGPR));
9066   }
9067 
9068   if (const auto *Attr = FD->getAttr<AMDGPUNumVGPRAttr>()) {
9069     uint32_t NumVGPR = Attr->getNumVGPR();
9070 
9071     if (NumVGPR != 0)
9072       F->addFnAttr("amdgpu-num-vgpr", llvm::utostr(NumVGPR));
9073   }
9074 
9075   if (M.getContext().getTargetInfo().allowAMDGPUUnsafeFPAtomics())
9076     F->addFnAttr("amdgpu-unsafe-fp-atomics", "true");
9077 }
9078 
9079 unsigned AMDGPUTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
9080   return llvm::CallingConv::AMDGPU_KERNEL;
9081 }
9082 
9083 // Currently LLVM assumes null pointers always have value 0,
9084 // which results in incorrectly transformed IR. Therefore, instead of
9085 // emitting null pointers in private and local address spaces, a null
9086 // pointer in generic address space is emitted which is casted to a
9087 // pointer in local or private address space.
9088 llvm::Constant *AMDGPUTargetCodeGenInfo::getNullPointer(
9089     const CodeGen::CodeGenModule &CGM, llvm::PointerType *PT,
9090     QualType QT) const {
9091   if (CGM.getContext().getTargetNullPointerValue(QT) == 0)
9092     return llvm::ConstantPointerNull::get(PT);
9093 
9094   auto &Ctx = CGM.getContext();
9095   auto NPT = llvm::PointerType::get(PT->getElementType(),
9096       Ctx.getTargetAddressSpace(LangAS::opencl_generic));
9097   return llvm::ConstantExpr::getAddrSpaceCast(
9098       llvm::ConstantPointerNull::get(NPT), PT);
9099 }
9100 
9101 LangAS
9102 AMDGPUTargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM,
9103                                                   const VarDecl *D) const {
9104   assert(!CGM.getLangOpts().OpenCL &&
9105          !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) &&
9106          "Address space agnostic languages only");
9107   LangAS DefaultGlobalAS = getLangASFromTargetAS(
9108       CGM.getContext().getTargetAddressSpace(LangAS::opencl_global));
9109   if (!D)
9110     return DefaultGlobalAS;
9111 
9112   LangAS AddrSpace = D->getType().getAddressSpace();
9113   assert(AddrSpace == LangAS::Default || isTargetAddressSpace(AddrSpace));
9114   if (AddrSpace != LangAS::Default)
9115     return AddrSpace;
9116 
9117   if (CGM.isTypeConstant(D->getType(), false)) {
9118     if (auto ConstAS = CGM.getTarget().getConstantAddressSpace())
9119       return ConstAS.getValue();
9120   }
9121   return DefaultGlobalAS;
9122 }
9123 
9124 llvm::SyncScope::ID
9125 AMDGPUTargetCodeGenInfo::getLLVMSyncScopeID(const LangOptions &LangOpts,
9126                                             SyncScope Scope,
9127                                             llvm::AtomicOrdering Ordering,
9128                                             llvm::LLVMContext &Ctx) const {
9129   std::string Name;
9130   switch (Scope) {
9131   case SyncScope::OpenCLWorkGroup:
9132     Name = "workgroup";
9133     break;
9134   case SyncScope::OpenCLDevice:
9135     Name = "agent";
9136     break;
9137   case SyncScope::OpenCLAllSVMDevices:
9138     Name = "";
9139     break;
9140   case SyncScope::OpenCLSubGroup:
9141     Name = "wavefront";
9142   }
9143 
9144   if (Ordering != llvm::AtomicOrdering::SequentiallyConsistent) {
9145     if (!Name.empty())
9146       Name = Twine(Twine(Name) + Twine("-")).str();
9147 
9148     Name = Twine(Twine(Name) + Twine("one-as")).str();
9149   }
9150 
9151   return Ctx.getOrInsertSyncScopeID(Name);
9152 }
9153 
9154 bool AMDGPUTargetCodeGenInfo::shouldEmitStaticExternCAliases() const {
9155   return false;
9156 }
9157 
9158 void AMDGPUTargetCodeGenInfo::setCUDAKernelCallingConvention(
9159     const FunctionType *&FT) const {
9160   FT = getABIInfo().getContext().adjustFunctionType(
9161       FT, FT->getExtInfo().withCallingConv(CC_OpenCLKernel));
9162 }
9163 
9164 //===----------------------------------------------------------------------===//
9165 // SPARC v8 ABI Implementation.
9166 // Based on the SPARC Compliance Definition version 2.4.1.
9167 //
9168 // Ensures that complex values are passed in registers.
9169 //
9170 namespace {
9171 class SparcV8ABIInfo : public DefaultABIInfo {
9172 public:
9173   SparcV8ABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
9174 
9175 private:
9176   ABIArgInfo classifyReturnType(QualType RetTy) const;
9177   void computeInfo(CGFunctionInfo &FI) const override;
9178 };
9179 } // end anonymous namespace
9180 
9181 
9182 ABIArgInfo
9183 SparcV8ABIInfo::classifyReturnType(QualType Ty) const {
9184   if (Ty->isAnyComplexType()) {
9185     return ABIArgInfo::getDirect();
9186   }
9187   else {
9188     return DefaultABIInfo::classifyReturnType(Ty);
9189   }
9190 }
9191 
9192 void SparcV8ABIInfo::computeInfo(CGFunctionInfo &FI) const {
9193 
9194   FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
9195   for (auto &Arg : FI.arguments())
9196     Arg.info = classifyArgumentType(Arg.type);
9197 }
9198 
9199 namespace {
9200 class SparcV8TargetCodeGenInfo : public TargetCodeGenInfo {
9201 public:
9202   SparcV8TargetCodeGenInfo(CodeGenTypes &CGT)
9203       : TargetCodeGenInfo(std::make_unique<SparcV8ABIInfo>(CGT)) {}
9204 };
9205 } // end anonymous namespace
9206 
9207 //===----------------------------------------------------------------------===//
9208 // SPARC v9 ABI Implementation.
9209 // Based on the SPARC Compliance Definition version 2.4.1.
9210 //
9211 // Function arguments a mapped to a nominal "parameter array" and promoted to
9212 // registers depending on their type. Each argument occupies 8 or 16 bytes in
9213 // the array, structs larger than 16 bytes are passed indirectly.
9214 //
9215 // One case requires special care:
9216 //
9217 //   struct mixed {
9218 //     int i;
9219 //     float f;
9220 //   };
9221 //
9222 // When a struct mixed is passed by value, it only occupies 8 bytes in the
9223 // parameter array, but the int is passed in an integer register, and the float
9224 // is passed in a floating point register. This is represented as two arguments
9225 // with the LLVM IR inreg attribute:
9226 //
9227 //   declare void f(i32 inreg %i, float inreg %f)
9228 //
9229 // The code generator will only allocate 4 bytes from the parameter array for
9230 // the inreg arguments. All other arguments are allocated a multiple of 8
9231 // bytes.
9232 //
9233 namespace {
9234 class SparcV9ABIInfo : public ABIInfo {
9235 public:
9236   SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
9237 
9238 private:
9239   ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
9240   void computeInfo(CGFunctionInfo &FI) const override;
9241   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9242                     QualType Ty) const override;
9243 
9244   // Coercion type builder for structs passed in registers. The coercion type
9245   // serves two purposes:
9246   //
9247   // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
9248   //    in registers.
9249   // 2. Expose aligned floating point elements as first-level elements, so the
9250   //    code generator knows to pass them in floating point registers.
9251   //
9252   // We also compute the InReg flag which indicates that the struct contains
9253   // aligned 32-bit floats.
9254   //
9255   struct CoerceBuilder {
9256     llvm::LLVMContext &Context;
9257     const llvm::DataLayout &DL;
9258     SmallVector<llvm::Type*, 8> Elems;
9259     uint64_t Size;
9260     bool InReg;
9261 
9262     CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
9263       : Context(c), DL(dl), Size(0), InReg(false) {}
9264 
9265     // Pad Elems with integers until Size is ToSize.
9266     void pad(uint64_t ToSize) {
9267       assert(ToSize >= Size && "Cannot remove elements");
9268       if (ToSize == Size)
9269         return;
9270 
9271       // Finish the current 64-bit word.
9272       uint64_t Aligned = llvm::alignTo(Size, 64);
9273       if (Aligned > Size && Aligned <= ToSize) {
9274         Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
9275         Size = Aligned;
9276       }
9277 
9278       // Add whole 64-bit words.
9279       while (Size + 64 <= ToSize) {
9280         Elems.push_back(llvm::Type::getInt64Ty(Context));
9281         Size += 64;
9282       }
9283 
9284       // Final in-word padding.
9285       if (Size < ToSize) {
9286         Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
9287         Size = ToSize;
9288       }
9289     }
9290 
9291     // Add a floating point element at Offset.
9292     void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
9293       // Unaligned floats are treated as integers.
9294       if (Offset % Bits)
9295         return;
9296       // The InReg flag is only required if there are any floats < 64 bits.
9297       if (Bits < 64)
9298         InReg = true;
9299       pad(Offset);
9300       Elems.push_back(Ty);
9301       Size = Offset + Bits;
9302     }
9303 
9304     // Add a struct type to the coercion type, starting at Offset (in bits).
9305     void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
9306       const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
9307       for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
9308         llvm::Type *ElemTy = StrTy->getElementType(i);
9309         uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
9310         switch (ElemTy->getTypeID()) {
9311         case llvm::Type::StructTyID:
9312           addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
9313           break;
9314         case llvm::Type::FloatTyID:
9315           addFloat(ElemOffset, ElemTy, 32);
9316           break;
9317         case llvm::Type::DoubleTyID:
9318           addFloat(ElemOffset, ElemTy, 64);
9319           break;
9320         case llvm::Type::FP128TyID:
9321           addFloat(ElemOffset, ElemTy, 128);
9322           break;
9323         case llvm::Type::PointerTyID:
9324           if (ElemOffset % 64 == 0) {
9325             pad(ElemOffset);
9326             Elems.push_back(ElemTy);
9327             Size += 64;
9328           }
9329           break;
9330         default:
9331           break;
9332         }
9333       }
9334     }
9335 
9336     // Check if Ty is a usable substitute for the coercion type.
9337     bool isUsableType(llvm::StructType *Ty) const {
9338       return llvm::makeArrayRef(Elems) == Ty->elements();
9339     }
9340 
9341     // Get the coercion type as a literal struct type.
9342     llvm::Type *getType() const {
9343       if (Elems.size() == 1)
9344         return Elems.front();
9345       else
9346         return llvm::StructType::get(Context, Elems);
9347     }
9348   };
9349 };
9350 } // end anonymous namespace
9351 
9352 ABIArgInfo
9353 SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
9354   if (Ty->isVoidType())
9355     return ABIArgInfo::getIgnore();
9356 
9357   uint64_t Size = getContext().getTypeSize(Ty);
9358 
9359   // Anything too big to fit in registers is passed with an explicit indirect
9360   // pointer / sret pointer.
9361   if (Size > SizeLimit)
9362     return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
9363 
9364   // Treat an enum type as its underlying type.
9365   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
9366     Ty = EnumTy->getDecl()->getIntegerType();
9367 
9368   // Integer types smaller than a register are extended.
9369   if (Size < 64 && Ty->isIntegerType())
9370     return ABIArgInfo::getExtend(Ty);
9371 
9372   if (const auto *EIT = Ty->getAs<ExtIntType>())
9373     if (EIT->getNumBits() < 64)
9374       return ABIArgInfo::getExtend(Ty);
9375 
9376   // Other non-aggregates go in registers.
9377   if (!isAggregateTypeForABI(Ty))
9378     return ABIArgInfo::getDirect();
9379 
9380   // If a C++ object has either a non-trivial copy constructor or a non-trivial
9381   // destructor, it is passed with an explicit indirect pointer / sret pointer.
9382   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
9383     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
9384 
9385   // This is a small aggregate type that should be passed in registers.
9386   // Build a coercion type from the LLVM struct type.
9387   llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
9388   if (!StrTy)
9389     return ABIArgInfo::getDirect();
9390 
9391   CoerceBuilder CB(getVMContext(), getDataLayout());
9392   CB.addStruct(0, StrTy);
9393   CB.pad(llvm::alignTo(CB.DL.getTypeSizeInBits(StrTy), 64));
9394 
9395   // Try to use the original type for coercion.
9396   llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
9397 
9398   if (CB.InReg)
9399     return ABIArgInfo::getDirectInReg(CoerceTy);
9400   else
9401     return ABIArgInfo::getDirect(CoerceTy);
9402 }
9403 
9404 Address SparcV9ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9405                                   QualType Ty) const {
9406   ABIArgInfo AI = classifyType(Ty, 16 * 8);
9407   llvm::Type *ArgTy = CGT.ConvertType(Ty);
9408   if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
9409     AI.setCoerceToType(ArgTy);
9410 
9411   CharUnits SlotSize = CharUnits::fromQuantity(8);
9412 
9413   CGBuilderTy &Builder = CGF.Builder;
9414   Address Addr(Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
9415   llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
9416 
9417   auto TypeInfo = getContext().getTypeInfoInChars(Ty);
9418 
9419   Address ArgAddr = Address::invalid();
9420   CharUnits Stride;
9421   switch (AI.getKind()) {
9422   case ABIArgInfo::Expand:
9423   case ABIArgInfo::CoerceAndExpand:
9424   case ABIArgInfo::InAlloca:
9425     llvm_unreachable("Unsupported ABI kind for va_arg");
9426 
9427   case ABIArgInfo::Extend: {
9428     Stride = SlotSize;
9429     CharUnits Offset = SlotSize - TypeInfo.Width;
9430     ArgAddr = Builder.CreateConstInBoundsByteGEP(Addr, Offset, "extend");
9431     break;
9432   }
9433 
9434   case ABIArgInfo::Direct: {
9435     auto AllocSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
9436     Stride = CharUnits::fromQuantity(AllocSize).alignTo(SlotSize);
9437     ArgAddr = Addr;
9438     break;
9439   }
9440 
9441   case ABIArgInfo::Indirect:
9442   case ABIArgInfo::IndirectAliased:
9443     Stride = SlotSize;
9444     ArgAddr = Builder.CreateElementBitCast(Addr, ArgPtrTy, "indirect");
9445     ArgAddr = Address(Builder.CreateLoad(ArgAddr, "indirect.arg"),
9446                       TypeInfo.Align);
9447     break;
9448 
9449   case ABIArgInfo::Ignore:
9450     return Address(llvm::UndefValue::get(ArgPtrTy), TypeInfo.Align);
9451   }
9452 
9453   // Update VAList.
9454   Address NextPtr = Builder.CreateConstInBoundsByteGEP(Addr, Stride, "ap.next");
9455   Builder.CreateStore(NextPtr.getPointer(), VAListAddr);
9456 
9457   return Builder.CreateBitCast(ArgAddr, ArgPtrTy, "arg.addr");
9458 }
9459 
9460 void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
9461   FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
9462   for (auto &I : FI.arguments())
9463     I.info = classifyType(I.type, 16 * 8);
9464 }
9465 
9466 namespace {
9467 class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
9468 public:
9469   SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
9470       : TargetCodeGenInfo(std::make_unique<SparcV9ABIInfo>(CGT)) {}
9471 
9472   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
9473     return 14;
9474   }
9475 
9476   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
9477                                llvm::Value *Address) const override;
9478 };
9479 } // end anonymous namespace
9480 
9481 bool
9482 SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
9483                                                 llvm::Value *Address) const {
9484   // This is calculated from the LLVM and GCC tables and verified
9485   // against gcc output.  AFAIK all ABIs use the same encoding.
9486 
9487   CodeGen::CGBuilderTy &Builder = CGF.Builder;
9488 
9489   llvm::IntegerType *i8 = CGF.Int8Ty;
9490   llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
9491   llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
9492 
9493   // 0-31: the 8-byte general-purpose registers
9494   AssignToArrayRange(Builder, Address, Eight8, 0, 31);
9495 
9496   // 32-63: f0-31, the 4-byte floating-point registers
9497   AssignToArrayRange(Builder, Address, Four8, 32, 63);
9498 
9499   //   Y   = 64
9500   //   PSR = 65
9501   //   WIM = 66
9502   //   TBR = 67
9503   //   PC  = 68
9504   //   NPC = 69
9505   //   FSR = 70
9506   //   CSR = 71
9507   AssignToArrayRange(Builder, Address, Eight8, 64, 71);
9508 
9509   // 72-87: d0-15, the 8-byte floating-point registers
9510   AssignToArrayRange(Builder, Address, Eight8, 72, 87);
9511 
9512   return false;
9513 }
9514 
9515 // ARC ABI implementation.
9516 namespace {
9517 
9518 class ARCABIInfo : public DefaultABIInfo {
9519 public:
9520   using DefaultABIInfo::DefaultABIInfo;
9521 
9522 private:
9523   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9524                     QualType Ty) const override;
9525 
9526   void updateState(const ABIArgInfo &Info, QualType Ty, CCState &State) const {
9527     if (!State.FreeRegs)
9528       return;
9529     if (Info.isIndirect() && Info.getInReg())
9530       State.FreeRegs--;
9531     else if (Info.isDirect() && Info.getInReg()) {
9532       unsigned sz = (getContext().getTypeSize(Ty) + 31) / 32;
9533       if (sz < State.FreeRegs)
9534         State.FreeRegs -= sz;
9535       else
9536         State.FreeRegs = 0;
9537     }
9538   }
9539 
9540   void computeInfo(CGFunctionInfo &FI) const override {
9541     CCState State(FI);
9542     // ARC uses 8 registers to pass arguments.
9543     State.FreeRegs = 8;
9544 
9545     if (!getCXXABI().classifyReturnType(FI))
9546       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
9547     updateState(FI.getReturnInfo(), FI.getReturnType(), State);
9548     for (auto &I : FI.arguments()) {
9549       I.info = classifyArgumentType(I.type, State.FreeRegs);
9550       updateState(I.info, I.type, State);
9551     }
9552   }
9553 
9554   ABIArgInfo getIndirectByRef(QualType Ty, bool HasFreeRegs) const;
9555   ABIArgInfo getIndirectByValue(QualType Ty) const;
9556   ABIArgInfo classifyArgumentType(QualType Ty, uint8_t FreeRegs) const;
9557   ABIArgInfo classifyReturnType(QualType RetTy) const;
9558 };
9559 
9560 class ARCTargetCodeGenInfo : public TargetCodeGenInfo {
9561 public:
9562   ARCTargetCodeGenInfo(CodeGenTypes &CGT)
9563       : TargetCodeGenInfo(std::make_unique<ARCABIInfo>(CGT)) {}
9564 };
9565 
9566 
9567 ABIArgInfo ARCABIInfo::getIndirectByRef(QualType Ty, bool HasFreeRegs) const {
9568   return HasFreeRegs ? getNaturalAlignIndirectInReg(Ty) :
9569                        getNaturalAlignIndirect(Ty, false);
9570 }
9571 
9572 ABIArgInfo ARCABIInfo::getIndirectByValue(QualType Ty) const {
9573   // Compute the byval alignment.
9574   const unsigned MinABIStackAlignInBytes = 4;
9575   unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
9576   return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true,
9577                                  TypeAlign > MinABIStackAlignInBytes);
9578 }
9579 
9580 Address ARCABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9581                               QualType Ty) const {
9582   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
9583                           getContext().getTypeInfoInChars(Ty),
9584                           CharUnits::fromQuantity(4), true);
9585 }
9586 
9587 ABIArgInfo ARCABIInfo::classifyArgumentType(QualType Ty,
9588                                             uint8_t FreeRegs) const {
9589   // Handle the generic C++ ABI.
9590   const RecordType *RT = Ty->getAs<RecordType>();
9591   if (RT) {
9592     CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
9593     if (RAA == CGCXXABI::RAA_Indirect)
9594       return getIndirectByRef(Ty, FreeRegs > 0);
9595 
9596     if (RAA == CGCXXABI::RAA_DirectInMemory)
9597       return getIndirectByValue(Ty);
9598   }
9599 
9600   // Treat an enum type as its underlying type.
9601   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
9602     Ty = EnumTy->getDecl()->getIntegerType();
9603 
9604   auto SizeInRegs = llvm::alignTo(getContext().getTypeSize(Ty), 32) / 32;
9605 
9606   if (isAggregateTypeForABI(Ty)) {
9607     // Structures with flexible arrays are always indirect.
9608     if (RT && RT->getDecl()->hasFlexibleArrayMember())
9609       return getIndirectByValue(Ty);
9610 
9611     // Ignore empty structs/unions.
9612     if (isEmptyRecord(getContext(), Ty, true))
9613       return ABIArgInfo::getIgnore();
9614 
9615     llvm::LLVMContext &LLVMContext = getVMContext();
9616 
9617     llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
9618     SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32);
9619     llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
9620 
9621     return FreeRegs >= SizeInRegs ?
9622         ABIArgInfo::getDirectInReg(Result) :
9623         ABIArgInfo::getDirect(Result, 0, nullptr, false);
9624   }
9625 
9626   if (const auto *EIT = Ty->getAs<ExtIntType>())
9627     if (EIT->getNumBits() > 64)
9628       return getIndirectByValue(Ty);
9629 
9630   return isPromotableIntegerTypeForABI(Ty)
9631              ? (FreeRegs >= SizeInRegs ? ABIArgInfo::getExtendInReg(Ty)
9632                                        : ABIArgInfo::getExtend(Ty))
9633              : (FreeRegs >= SizeInRegs ? ABIArgInfo::getDirectInReg()
9634                                        : ABIArgInfo::getDirect());
9635 }
9636 
9637 ABIArgInfo ARCABIInfo::classifyReturnType(QualType RetTy) const {
9638   if (RetTy->isAnyComplexType())
9639     return ABIArgInfo::getDirectInReg();
9640 
9641   // Arguments of size > 4 registers are indirect.
9642   auto RetSize = llvm::alignTo(getContext().getTypeSize(RetTy), 32) / 32;
9643   if (RetSize > 4)
9644     return getIndirectByRef(RetTy, /*HasFreeRegs*/ true);
9645 
9646   return DefaultABIInfo::classifyReturnType(RetTy);
9647 }
9648 
9649 } // End anonymous namespace.
9650 
9651 //===----------------------------------------------------------------------===//
9652 // XCore ABI Implementation
9653 //===----------------------------------------------------------------------===//
9654 
9655 namespace {
9656 
9657 /// A SmallStringEnc instance is used to build up the TypeString by passing
9658 /// it by reference between functions that append to it.
9659 typedef llvm::SmallString<128> SmallStringEnc;
9660 
9661 /// TypeStringCache caches the meta encodings of Types.
9662 ///
9663 /// The reason for caching TypeStrings is two fold:
9664 ///   1. To cache a type's encoding for later uses;
9665 ///   2. As a means to break recursive member type inclusion.
9666 ///
9667 /// A cache Entry can have a Status of:
9668 ///   NonRecursive:   The type encoding is not recursive;
9669 ///   Recursive:      The type encoding is recursive;
9670 ///   Incomplete:     An incomplete TypeString;
9671 ///   IncompleteUsed: An incomplete TypeString that has been used in a
9672 ///                   Recursive type encoding.
9673 ///
9674 /// A NonRecursive entry will have all of its sub-members expanded as fully
9675 /// as possible. Whilst it may contain types which are recursive, the type
9676 /// itself is not recursive and thus its encoding may be safely used whenever
9677 /// the type is encountered.
9678 ///
9679 /// A Recursive entry will have all of its sub-members expanded as fully as
9680 /// possible. The type itself is recursive and it may contain other types which
9681 /// are recursive. The Recursive encoding must not be used during the expansion
9682 /// of a recursive type's recursive branch. For simplicity the code uses
9683 /// IncompleteCount to reject all usage of Recursive encodings for member types.
9684 ///
9685 /// An Incomplete entry is always a RecordType and only encodes its
9686 /// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and
9687 /// are placed into the cache during type expansion as a means to identify and
9688 /// handle recursive inclusion of types as sub-members. If there is recursion
9689 /// the entry becomes IncompleteUsed.
9690 ///
9691 /// During the expansion of a RecordType's members:
9692 ///
9693 ///   If the cache contains a NonRecursive encoding for the member type, the
9694 ///   cached encoding is used;
9695 ///
9696 ///   If the cache contains a Recursive encoding for the member type, the
9697 ///   cached encoding is 'Swapped' out, as it may be incorrect, and...
9698 ///
9699 ///   If the member is a RecordType, an Incomplete encoding is placed into the
9700 ///   cache to break potential recursive inclusion of itself as a sub-member;
9701 ///
9702 ///   Once a member RecordType has been expanded, its temporary incomplete
9703 ///   entry is removed from the cache. If a Recursive encoding was swapped out
9704 ///   it is swapped back in;
9705 ///
9706 ///   If an incomplete entry is used to expand a sub-member, the incomplete
9707 ///   entry is marked as IncompleteUsed. The cache keeps count of how many
9708 ///   IncompleteUsed entries it currently contains in IncompleteUsedCount;
9709 ///
9710 ///   If a member's encoding is found to be a NonRecursive or Recursive viz:
9711 ///   IncompleteUsedCount==0, the member's encoding is added to the cache.
9712 ///   Else the member is part of a recursive type and thus the recursion has
9713 ///   been exited too soon for the encoding to be correct for the member.
9714 ///
9715 class TypeStringCache {
9716   enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed};
9717   struct Entry {
9718     std::string Str;     // The encoded TypeString for the type.
9719     enum Status State;   // Information about the encoding in 'Str'.
9720     std::string Swapped; // A temporary place holder for a Recursive encoding
9721                          // during the expansion of RecordType's members.
9722   };
9723   std::map<const IdentifierInfo *, struct Entry> Map;
9724   unsigned IncompleteCount;     // Number of Incomplete entries in the Map.
9725   unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map.
9726 public:
9727   TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {}
9728   void addIncomplete(const IdentifierInfo *ID, std::string StubEnc);
9729   bool removeIncomplete(const IdentifierInfo *ID);
9730   void addIfComplete(const IdentifierInfo *ID, StringRef Str,
9731                      bool IsRecursive);
9732   StringRef lookupStr(const IdentifierInfo *ID);
9733 };
9734 
9735 /// TypeString encodings for enum & union fields must be order.
9736 /// FieldEncoding is a helper for this ordering process.
9737 class FieldEncoding {
9738   bool HasName;
9739   std::string Enc;
9740 public:
9741   FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {}
9742   StringRef str() { return Enc; }
9743   bool operator<(const FieldEncoding &rhs) const {
9744     if (HasName != rhs.HasName) return HasName;
9745     return Enc < rhs.Enc;
9746   }
9747 };
9748 
9749 class XCoreABIInfo : public DefaultABIInfo {
9750 public:
9751   XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
9752   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9753                     QualType Ty) const override;
9754 };
9755 
9756 class XCoreTargetCodeGenInfo : public TargetCodeGenInfo {
9757   mutable TypeStringCache TSC;
9758   void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
9759                     const CodeGen::CodeGenModule &M) const;
9760 
9761 public:
9762   XCoreTargetCodeGenInfo(CodeGenTypes &CGT)
9763       : TargetCodeGenInfo(std::make_unique<XCoreABIInfo>(CGT)) {}
9764   void emitTargetMetadata(CodeGen::CodeGenModule &CGM,
9765                           const llvm::MapVector<GlobalDecl, StringRef>
9766                               &MangledDeclNames) const override;
9767 };
9768 
9769 } // End anonymous namespace.
9770 
9771 // TODO: this implementation is likely now redundant with the default
9772 // EmitVAArg.
9773 Address XCoreABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9774                                 QualType Ty) const {
9775   CGBuilderTy &Builder = CGF.Builder;
9776 
9777   // Get the VAList.
9778   CharUnits SlotSize = CharUnits::fromQuantity(4);
9779   Address AP(Builder.CreateLoad(VAListAddr), SlotSize);
9780 
9781   // Handle the argument.
9782   ABIArgInfo AI = classifyArgumentType(Ty);
9783   CharUnits TypeAlign = getContext().getTypeAlignInChars(Ty);
9784   llvm::Type *ArgTy = CGT.ConvertType(Ty);
9785   if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
9786     AI.setCoerceToType(ArgTy);
9787   llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
9788 
9789   Address Val = Address::invalid();
9790   CharUnits ArgSize = CharUnits::Zero();
9791   switch (AI.getKind()) {
9792   case ABIArgInfo::Expand:
9793   case ABIArgInfo::CoerceAndExpand:
9794   case ABIArgInfo::InAlloca:
9795     llvm_unreachable("Unsupported ABI kind for va_arg");
9796   case ABIArgInfo::Ignore:
9797     Val = Address(llvm::UndefValue::get(ArgPtrTy), TypeAlign);
9798     ArgSize = CharUnits::Zero();
9799     break;
9800   case ABIArgInfo::Extend:
9801   case ABIArgInfo::Direct:
9802     Val = Builder.CreateBitCast(AP, ArgPtrTy);
9803     ArgSize = CharUnits::fromQuantity(
9804                        getDataLayout().getTypeAllocSize(AI.getCoerceToType()));
9805     ArgSize = ArgSize.alignTo(SlotSize);
9806     break;
9807   case ABIArgInfo::Indirect:
9808   case ABIArgInfo::IndirectAliased:
9809     Val = Builder.CreateElementBitCast(AP, ArgPtrTy);
9810     Val = Address(Builder.CreateLoad(Val), TypeAlign);
9811     ArgSize = SlotSize;
9812     break;
9813   }
9814 
9815   // Increment the VAList.
9816   if (!ArgSize.isZero()) {
9817     Address APN = Builder.CreateConstInBoundsByteGEP(AP, ArgSize);
9818     Builder.CreateStore(APN.getPointer(), VAListAddr);
9819   }
9820 
9821   return Val;
9822 }
9823 
9824 /// During the expansion of a RecordType, an incomplete TypeString is placed
9825 /// into the cache as a means to identify and break recursion.
9826 /// If there is a Recursive encoding in the cache, it is swapped out and will
9827 /// be reinserted by removeIncomplete().
9828 /// All other types of encoding should have been used rather than arriving here.
9829 void TypeStringCache::addIncomplete(const IdentifierInfo *ID,
9830                                     std::string StubEnc) {
9831   if (!ID)
9832     return;
9833   Entry &E = Map[ID];
9834   assert( (E.Str.empty() || E.State == Recursive) &&
9835          "Incorrectly use of addIncomplete");
9836   assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()");
9837   E.Swapped.swap(E.Str); // swap out the Recursive
9838   E.Str.swap(StubEnc);
9839   E.State = Incomplete;
9840   ++IncompleteCount;
9841 }
9842 
9843 /// Once the RecordType has been expanded, the temporary incomplete TypeString
9844 /// must be removed from the cache.
9845 /// If a Recursive was swapped out by addIncomplete(), it will be replaced.
9846 /// Returns true if the RecordType was defined recursively.
9847 bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) {
9848   if (!ID)
9849     return false;
9850   auto I = Map.find(ID);
9851   assert(I != Map.end() && "Entry not present");
9852   Entry &E = I->second;
9853   assert( (E.State == Incomplete ||
9854            E.State == IncompleteUsed) &&
9855          "Entry must be an incomplete type");
9856   bool IsRecursive = false;
9857   if (E.State == IncompleteUsed) {
9858     // We made use of our Incomplete encoding, thus we are recursive.
9859     IsRecursive = true;
9860     --IncompleteUsedCount;
9861   }
9862   if (E.Swapped.empty())
9863     Map.erase(I);
9864   else {
9865     // Swap the Recursive back.
9866     E.Swapped.swap(E.Str);
9867     E.Swapped.clear();
9868     E.State = Recursive;
9869   }
9870   --IncompleteCount;
9871   return IsRecursive;
9872 }
9873 
9874 /// Add the encoded TypeString to the cache only if it is NonRecursive or
9875 /// Recursive (viz: all sub-members were expanded as fully as possible).
9876 void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str,
9877                                     bool IsRecursive) {
9878   if (!ID || IncompleteUsedCount)
9879     return; // No key or it is is an incomplete sub-type so don't add.
9880   Entry &E = Map[ID];
9881   if (IsRecursive && !E.Str.empty()) {
9882     assert(E.State==Recursive && E.Str.size() == Str.size() &&
9883            "This is not the same Recursive entry");
9884     // The parent container was not recursive after all, so we could have used
9885     // this Recursive sub-member entry after all, but we assumed the worse when
9886     // we started viz: IncompleteCount!=0.
9887     return;
9888   }
9889   assert(E.Str.empty() && "Entry already present");
9890   E.Str = Str.str();
9891   E.State = IsRecursive? Recursive : NonRecursive;
9892 }
9893 
9894 /// Return a cached TypeString encoding for the ID. If there isn't one, or we
9895 /// are recursively expanding a type (IncompleteCount != 0) and the cached
9896 /// encoding is Recursive, return an empty StringRef.
9897 StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) {
9898   if (!ID)
9899     return StringRef();   // We have no key.
9900   auto I = Map.find(ID);
9901   if (I == Map.end())
9902     return StringRef();   // We have no encoding.
9903   Entry &E = I->second;
9904   if (E.State == Recursive && IncompleteCount)
9905     return StringRef();   // We don't use Recursive encodings for member types.
9906 
9907   if (E.State == Incomplete) {
9908     // The incomplete type is being used to break out of recursion.
9909     E.State = IncompleteUsed;
9910     ++IncompleteUsedCount;
9911   }
9912   return E.Str;
9913 }
9914 
9915 /// The XCore ABI includes a type information section that communicates symbol
9916 /// type information to the linker. The linker uses this information to verify
9917 /// safety/correctness of things such as array bound and pointers et al.
9918 /// The ABI only requires C (and XC) language modules to emit TypeStrings.
9919 /// This type information (TypeString) is emitted into meta data for all global
9920 /// symbols: definitions, declarations, functions & variables.
9921 ///
9922 /// The TypeString carries type, qualifier, name, size & value details.
9923 /// Please see 'Tools Development Guide' section 2.16.2 for format details:
9924 /// https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf
9925 /// The output is tested by test/CodeGen/xcore-stringtype.c.
9926 ///
9927 static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
9928                           const CodeGen::CodeGenModule &CGM,
9929                           TypeStringCache &TSC);
9930 
9931 /// XCore uses emitTargetMD to emit TypeString metadata for global symbols.
9932 void XCoreTargetCodeGenInfo::emitTargetMD(
9933     const Decl *D, llvm::GlobalValue *GV,
9934     const CodeGen::CodeGenModule &CGM) const {
9935   SmallStringEnc Enc;
9936   if (getTypeString(Enc, D, CGM, TSC)) {
9937     llvm::LLVMContext &Ctx = CGM.getModule().getContext();
9938     llvm::Metadata *MDVals[] = {llvm::ConstantAsMetadata::get(GV),
9939                                 llvm::MDString::get(Ctx, Enc.str())};
9940     llvm::NamedMDNode *MD =
9941       CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings");
9942     MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
9943   }
9944 }
9945 
9946 void XCoreTargetCodeGenInfo::emitTargetMetadata(
9947     CodeGen::CodeGenModule &CGM,
9948     const llvm::MapVector<GlobalDecl, StringRef> &MangledDeclNames) const {
9949   // Warning, new MangledDeclNames may be appended within this loop.
9950   // We rely on MapVector insertions adding new elements to the end
9951   // of the container.
9952   for (unsigned I = 0; I != MangledDeclNames.size(); ++I) {
9953     auto Val = *(MangledDeclNames.begin() + I);
9954     llvm::GlobalValue *GV = CGM.GetGlobalValue(Val.second);
9955     if (GV) {
9956       const Decl *D = Val.first.getDecl()->getMostRecentDecl();
9957       emitTargetMD(D, GV, CGM);
9958     }
9959   }
9960 }
9961 //===----------------------------------------------------------------------===//
9962 // SPIR ABI Implementation
9963 //===----------------------------------------------------------------------===//
9964 
9965 namespace {
9966 class SPIRABIInfo : public DefaultABIInfo {
9967 public:
9968   SPIRABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) { setCCs(); }
9969 
9970 private:
9971   void setCCs();
9972 };
9973 } // end anonymous namespace
9974 namespace {
9975 class SPIRTargetCodeGenInfo : public TargetCodeGenInfo {
9976 public:
9977   SPIRTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
9978       : TargetCodeGenInfo(std::make_unique<SPIRABIInfo>(CGT)) {}
9979   unsigned getOpenCLKernelCallingConv() const override;
9980 };
9981 
9982 } // End anonymous namespace.
9983 void SPIRABIInfo::setCCs() {
9984   assert(getRuntimeCC() == llvm::CallingConv::C);
9985   RuntimeCC = llvm::CallingConv::SPIR_FUNC;
9986 }
9987 
9988 namespace clang {
9989 namespace CodeGen {
9990 void computeSPIRKernelABIInfo(CodeGenModule &CGM, CGFunctionInfo &FI) {
9991   DefaultABIInfo SPIRABI(CGM.getTypes());
9992   SPIRABI.computeInfo(FI);
9993 }
9994 }
9995 }
9996 
9997 unsigned SPIRTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
9998   return llvm::CallingConv::SPIR_KERNEL;
9999 }
10000 
10001 static bool appendType(SmallStringEnc &Enc, QualType QType,
10002                        const CodeGen::CodeGenModule &CGM,
10003                        TypeStringCache &TSC);
10004 
10005 /// Helper function for appendRecordType().
10006 /// Builds a SmallVector containing the encoded field types in declaration
10007 /// order.
10008 static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE,
10009                              const RecordDecl *RD,
10010                              const CodeGen::CodeGenModule &CGM,
10011                              TypeStringCache &TSC) {
10012   for (const auto *Field : RD->fields()) {
10013     SmallStringEnc Enc;
10014     Enc += "m(";
10015     Enc += Field->getName();
10016     Enc += "){";
10017     if (Field->isBitField()) {
10018       Enc += "b(";
10019       llvm::raw_svector_ostream OS(Enc);
10020       OS << Field->getBitWidthValue(CGM.getContext());
10021       Enc += ':';
10022     }
10023     if (!appendType(Enc, Field->getType(), CGM, TSC))
10024       return false;
10025     if (Field->isBitField())
10026       Enc += ')';
10027     Enc += '}';
10028     FE.emplace_back(!Field->getName().empty(), Enc);
10029   }
10030   return true;
10031 }
10032 
10033 /// Appends structure and union types to Enc and adds encoding to cache.
10034 /// Recursively calls appendType (via extractFieldType) for each field.
10035 /// Union types have their fields ordered according to the ABI.
10036 static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT,
10037                              const CodeGen::CodeGenModule &CGM,
10038                              TypeStringCache &TSC, const IdentifierInfo *ID) {
10039   // Append the cached TypeString if we have one.
10040   StringRef TypeString = TSC.lookupStr(ID);
10041   if (!TypeString.empty()) {
10042     Enc += TypeString;
10043     return true;
10044   }
10045 
10046   // Start to emit an incomplete TypeString.
10047   size_t Start = Enc.size();
10048   Enc += (RT->isUnionType()? 'u' : 's');
10049   Enc += '(';
10050   if (ID)
10051     Enc += ID->getName();
10052   Enc += "){";
10053 
10054   // We collect all encoded fields and order as necessary.
10055   bool IsRecursive = false;
10056   const RecordDecl *RD = RT->getDecl()->getDefinition();
10057   if (RD && !RD->field_empty()) {
10058     // An incomplete TypeString stub is placed in the cache for this RecordType
10059     // so that recursive calls to this RecordType will use it whilst building a
10060     // complete TypeString for this RecordType.
10061     SmallVector<FieldEncoding, 16> FE;
10062     std::string StubEnc(Enc.substr(Start).str());
10063     StubEnc += '}';  // StubEnc now holds a valid incomplete TypeString.
10064     TSC.addIncomplete(ID, std::move(StubEnc));
10065     if (!extractFieldType(FE, RD, CGM, TSC)) {
10066       (void) TSC.removeIncomplete(ID);
10067       return false;
10068     }
10069     IsRecursive = TSC.removeIncomplete(ID);
10070     // The ABI requires unions to be sorted but not structures.
10071     // See FieldEncoding::operator< for sort algorithm.
10072     if (RT->isUnionType())
10073       llvm::sort(FE);
10074     // We can now complete the TypeString.
10075     unsigned E = FE.size();
10076     for (unsigned I = 0; I != E; ++I) {
10077       if (I)
10078         Enc += ',';
10079       Enc += FE[I].str();
10080     }
10081   }
10082   Enc += '}';
10083   TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive);
10084   return true;
10085 }
10086 
10087 /// Appends enum types to Enc and adds the encoding to the cache.
10088 static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET,
10089                            TypeStringCache &TSC,
10090                            const IdentifierInfo *ID) {
10091   // Append the cached TypeString if we have one.
10092   StringRef TypeString = TSC.lookupStr(ID);
10093   if (!TypeString.empty()) {
10094     Enc += TypeString;
10095     return true;
10096   }
10097 
10098   size_t Start = Enc.size();
10099   Enc += "e(";
10100   if (ID)
10101     Enc += ID->getName();
10102   Enc += "){";
10103 
10104   // We collect all encoded enumerations and order them alphanumerically.
10105   if (const EnumDecl *ED = ET->getDecl()->getDefinition()) {
10106     SmallVector<FieldEncoding, 16> FE;
10107     for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E;
10108          ++I) {
10109       SmallStringEnc EnumEnc;
10110       EnumEnc += "m(";
10111       EnumEnc += I->getName();
10112       EnumEnc += "){";
10113       I->getInitVal().toString(EnumEnc);
10114       EnumEnc += '}';
10115       FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc));
10116     }
10117     llvm::sort(FE);
10118     unsigned E = FE.size();
10119     for (unsigned I = 0; I != E; ++I) {
10120       if (I)
10121         Enc += ',';
10122       Enc += FE[I].str();
10123     }
10124   }
10125   Enc += '}';
10126   TSC.addIfComplete(ID, Enc.substr(Start), false);
10127   return true;
10128 }
10129 
10130 /// Appends type's qualifier to Enc.
10131 /// This is done prior to appending the type's encoding.
10132 static void appendQualifier(SmallStringEnc &Enc, QualType QT) {
10133   // Qualifiers are emitted in alphabetical order.
10134   static const char *const Table[]={"","c:","r:","cr:","v:","cv:","rv:","crv:"};
10135   int Lookup = 0;
10136   if (QT.isConstQualified())
10137     Lookup += 1<<0;
10138   if (QT.isRestrictQualified())
10139     Lookup += 1<<1;
10140   if (QT.isVolatileQualified())
10141     Lookup += 1<<2;
10142   Enc += Table[Lookup];
10143 }
10144 
10145 /// Appends built-in types to Enc.
10146 static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) {
10147   const char *EncType;
10148   switch (BT->getKind()) {
10149     case BuiltinType::Void:
10150       EncType = "0";
10151       break;
10152     case BuiltinType::Bool:
10153       EncType = "b";
10154       break;
10155     case BuiltinType::Char_U:
10156       EncType = "uc";
10157       break;
10158     case BuiltinType::UChar:
10159       EncType = "uc";
10160       break;
10161     case BuiltinType::SChar:
10162       EncType = "sc";
10163       break;
10164     case BuiltinType::UShort:
10165       EncType = "us";
10166       break;
10167     case BuiltinType::Short:
10168       EncType = "ss";
10169       break;
10170     case BuiltinType::UInt:
10171       EncType = "ui";
10172       break;
10173     case BuiltinType::Int:
10174       EncType = "si";
10175       break;
10176     case BuiltinType::ULong:
10177       EncType = "ul";
10178       break;
10179     case BuiltinType::Long:
10180       EncType = "sl";
10181       break;
10182     case BuiltinType::ULongLong:
10183       EncType = "ull";
10184       break;
10185     case BuiltinType::LongLong:
10186       EncType = "sll";
10187       break;
10188     case BuiltinType::Float:
10189       EncType = "ft";
10190       break;
10191     case BuiltinType::Double:
10192       EncType = "d";
10193       break;
10194     case BuiltinType::LongDouble:
10195       EncType = "ld";
10196       break;
10197     default:
10198       return false;
10199   }
10200   Enc += EncType;
10201   return true;
10202 }
10203 
10204 /// Appends a pointer encoding to Enc before calling appendType for the pointee.
10205 static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT,
10206                               const CodeGen::CodeGenModule &CGM,
10207                               TypeStringCache &TSC) {
10208   Enc += "p(";
10209   if (!appendType(Enc, PT->getPointeeType(), CGM, TSC))
10210     return false;
10211   Enc += ')';
10212   return true;
10213 }
10214 
10215 /// Appends array encoding to Enc before calling appendType for the element.
10216 static bool appendArrayType(SmallStringEnc &Enc, QualType QT,
10217                             const ArrayType *AT,
10218                             const CodeGen::CodeGenModule &CGM,
10219                             TypeStringCache &TSC, StringRef NoSizeEnc) {
10220   if (AT->getSizeModifier() != ArrayType::Normal)
10221     return false;
10222   Enc += "a(";
10223   if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
10224     CAT->getSize().toStringUnsigned(Enc);
10225   else
10226     Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "".
10227   Enc += ':';
10228   // The Qualifiers should be attached to the type rather than the array.
10229   appendQualifier(Enc, QT);
10230   if (!appendType(Enc, AT->getElementType(), CGM, TSC))
10231     return false;
10232   Enc += ')';
10233   return true;
10234 }
10235 
10236 /// Appends a function encoding to Enc, calling appendType for the return type
10237 /// and the arguments.
10238 static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT,
10239                              const CodeGen::CodeGenModule &CGM,
10240                              TypeStringCache &TSC) {
10241   Enc += "f{";
10242   if (!appendType(Enc, FT->getReturnType(), CGM, TSC))
10243     return false;
10244   Enc += "}(";
10245   if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) {
10246     // N.B. we are only interested in the adjusted param types.
10247     auto I = FPT->param_type_begin();
10248     auto E = FPT->param_type_end();
10249     if (I != E) {
10250       do {
10251         if (!appendType(Enc, *I, CGM, TSC))
10252           return false;
10253         ++I;
10254         if (I != E)
10255           Enc += ',';
10256       } while (I != E);
10257       if (FPT->isVariadic())
10258         Enc += ",va";
10259     } else {
10260       if (FPT->isVariadic())
10261         Enc += "va";
10262       else
10263         Enc += '0';
10264     }
10265   }
10266   Enc += ')';
10267   return true;
10268 }
10269 
10270 /// Handles the type's qualifier before dispatching a call to handle specific
10271 /// type encodings.
10272 static bool appendType(SmallStringEnc &Enc, QualType QType,
10273                        const CodeGen::CodeGenModule &CGM,
10274                        TypeStringCache &TSC) {
10275 
10276   QualType QT = QType.getCanonicalType();
10277 
10278   if (const ArrayType *AT = QT->getAsArrayTypeUnsafe())
10279     // The Qualifiers should be attached to the type rather than the array.
10280     // Thus we don't call appendQualifier() here.
10281     return appendArrayType(Enc, QT, AT, CGM, TSC, "");
10282 
10283   appendQualifier(Enc, QT);
10284 
10285   if (const BuiltinType *BT = QT->getAs<BuiltinType>())
10286     return appendBuiltinType(Enc, BT);
10287 
10288   if (const PointerType *PT = QT->getAs<PointerType>())
10289     return appendPointerType(Enc, PT, CGM, TSC);
10290 
10291   if (const EnumType *ET = QT->getAs<EnumType>())
10292     return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier());
10293 
10294   if (const RecordType *RT = QT->getAsStructureType())
10295     return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
10296 
10297   if (const RecordType *RT = QT->getAsUnionType())
10298     return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
10299 
10300   if (const FunctionType *FT = QT->getAs<FunctionType>())
10301     return appendFunctionType(Enc, FT, CGM, TSC);
10302 
10303   return false;
10304 }
10305 
10306 static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
10307                           const CodeGen::CodeGenModule &CGM,
10308                           TypeStringCache &TSC) {
10309   if (!D)
10310     return false;
10311 
10312   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
10313     if (FD->getLanguageLinkage() != CLanguageLinkage)
10314       return false;
10315     return appendType(Enc, FD->getType(), CGM, TSC);
10316   }
10317 
10318   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
10319     if (VD->getLanguageLinkage() != CLanguageLinkage)
10320       return false;
10321     QualType QT = VD->getType().getCanonicalType();
10322     if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) {
10323       // Global ArrayTypes are given a size of '*' if the size is unknown.
10324       // The Qualifiers should be attached to the type rather than the array.
10325       // Thus we don't call appendQualifier() here.
10326       return appendArrayType(Enc, QT, AT, CGM, TSC, "*");
10327     }
10328     return appendType(Enc, QT, CGM, TSC);
10329   }
10330   return false;
10331 }
10332 
10333 //===----------------------------------------------------------------------===//
10334 // RISCV ABI Implementation
10335 //===----------------------------------------------------------------------===//
10336 
10337 namespace {
10338 class RISCVABIInfo : public DefaultABIInfo {
10339 private:
10340   // Size of the integer ('x') registers in bits.
10341   unsigned XLen;
10342   // Size of the floating point ('f') registers in bits. Note that the target
10343   // ISA might have a wider FLen than the selected ABI (e.g. an RV32IF target
10344   // with soft float ABI has FLen==0).
10345   unsigned FLen;
10346   static const int NumArgGPRs = 8;
10347   static const int NumArgFPRs = 8;
10348   bool detectFPCCEligibleStructHelper(QualType Ty, CharUnits CurOff,
10349                                       llvm::Type *&Field1Ty,
10350                                       CharUnits &Field1Off,
10351                                       llvm::Type *&Field2Ty,
10352                                       CharUnits &Field2Off) const;
10353 
10354 public:
10355   RISCVABIInfo(CodeGen::CodeGenTypes &CGT, unsigned XLen, unsigned FLen)
10356       : DefaultABIInfo(CGT), XLen(XLen), FLen(FLen) {}
10357 
10358   // DefaultABIInfo's classifyReturnType and classifyArgumentType are
10359   // non-virtual, but computeInfo is virtual, so we overload it.
10360   void computeInfo(CGFunctionInfo &FI) const override;
10361 
10362   ABIArgInfo classifyArgumentType(QualType Ty, bool IsFixed, int &ArgGPRsLeft,
10363                                   int &ArgFPRsLeft) const;
10364   ABIArgInfo classifyReturnType(QualType RetTy) const;
10365 
10366   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
10367                     QualType Ty) const override;
10368 
10369   ABIArgInfo extendType(QualType Ty) const;
10370 
10371   bool detectFPCCEligibleStruct(QualType Ty, llvm::Type *&Field1Ty,
10372                                 CharUnits &Field1Off, llvm::Type *&Field2Ty,
10373                                 CharUnits &Field2Off, int &NeededArgGPRs,
10374                                 int &NeededArgFPRs) const;
10375   ABIArgInfo coerceAndExpandFPCCEligibleStruct(llvm::Type *Field1Ty,
10376                                                CharUnits Field1Off,
10377                                                llvm::Type *Field2Ty,
10378                                                CharUnits Field2Off) const;
10379 };
10380 } // end anonymous namespace
10381 
10382 void RISCVABIInfo::computeInfo(CGFunctionInfo &FI) const {
10383   QualType RetTy = FI.getReturnType();
10384   if (!getCXXABI().classifyReturnType(FI))
10385     FI.getReturnInfo() = classifyReturnType(RetTy);
10386 
10387   // IsRetIndirect is true if classifyArgumentType indicated the value should
10388   // be passed indirect, or if the type size is a scalar greater than 2*XLen
10389   // and not a complex type with elements <= FLen. e.g. fp128 is passed direct
10390   // in LLVM IR, relying on the backend lowering code to rewrite the argument
10391   // list and pass indirectly on RV32.
10392   bool IsRetIndirect = FI.getReturnInfo().getKind() == ABIArgInfo::Indirect;
10393   if (!IsRetIndirect && RetTy->isScalarType() &&
10394       getContext().getTypeSize(RetTy) > (2 * XLen)) {
10395     if (RetTy->isComplexType() && FLen) {
10396       QualType EltTy = RetTy->castAs<ComplexType>()->getElementType();
10397       IsRetIndirect = getContext().getTypeSize(EltTy) > FLen;
10398     } else {
10399       // This is a normal scalar > 2*XLen, such as fp128 on RV32.
10400       IsRetIndirect = true;
10401     }
10402   }
10403 
10404   // We must track the number of GPRs used in order to conform to the RISC-V
10405   // ABI, as integer scalars passed in registers should have signext/zeroext
10406   // when promoted, but are anyext if passed on the stack. As GPR usage is
10407   // different for variadic arguments, we must also track whether we are
10408   // examining a vararg or not.
10409   int ArgGPRsLeft = IsRetIndirect ? NumArgGPRs - 1 : NumArgGPRs;
10410   int ArgFPRsLeft = FLen ? NumArgFPRs : 0;
10411   int NumFixedArgs = FI.getNumRequiredArgs();
10412 
10413   int ArgNum = 0;
10414   for (auto &ArgInfo : FI.arguments()) {
10415     bool IsFixed = ArgNum < NumFixedArgs;
10416     ArgInfo.info =
10417         classifyArgumentType(ArgInfo.type, IsFixed, ArgGPRsLeft, ArgFPRsLeft);
10418     ArgNum++;
10419   }
10420 }
10421 
10422 // Returns true if the struct is a potential candidate for the floating point
10423 // calling convention. If this function returns true, the caller is
10424 // responsible for checking that if there is only a single field then that
10425 // field is a float.
10426 bool RISCVABIInfo::detectFPCCEligibleStructHelper(QualType Ty, CharUnits CurOff,
10427                                                   llvm::Type *&Field1Ty,
10428                                                   CharUnits &Field1Off,
10429                                                   llvm::Type *&Field2Ty,
10430                                                   CharUnits &Field2Off) const {
10431   bool IsInt = Ty->isIntegralOrEnumerationType();
10432   bool IsFloat = Ty->isRealFloatingType();
10433 
10434   if (IsInt || IsFloat) {
10435     uint64_t Size = getContext().getTypeSize(Ty);
10436     if (IsInt && Size > XLen)
10437       return false;
10438     // Can't be eligible if larger than the FP registers. Half precision isn't
10439     // currently supported on RISC-V and the ABI hasn't been confirmed, so
10440     // default to the integer ABI in that case.
10441     if (IsFloat && (Size > FLen || Size < 32))
10442       return false;
10443     // Can't be eligible if an integer type was already found (int+int pairs
10444     // are not eligible).
10445     if (IsInt && Field1Ty && Field1Ty->isIntegerTy())
10446       return false;
10447     if (!Field1Ty) {
10448       Field1Ty = CGT.ConvertType(Ty);
10449       Field1Off = CurOff;
10450       return true;
10451     }
10452     if (!Field2Ty) {
10453       Field2Ty = CGT.ConvertType(Ty);
10454       Field2Off = CurOff;
10455       return true;
10456     }
10457     return false;
10458   }
10459 
10460   if (auto CTy = Ty->getAs<ComplexType>()) {
10461     if (Field1Ty)
10462       return false;
10463     QualType EltTy = CTy->getElementType();
10464     if (getContext().getTypeSize(EltTy) > FLen)
10465       return false;
10466     Field1Ty = CGT.ConvertType(EltTy);
10467     Field1Off = CurOff;
10468     Field2Ty = Field1Ty;
10469     Field2Off = Field1Off + getContext().getTypeSizeInChars(EltTy);
10470     return true;
10471   }
10472 
10473   if (const ConstantArrayType *ATy = getContext().getAsConstantArrayType(Ty)) {
10474     uint64_t ArraySize = ATy->getSize().getZExtValue();
10475     QualType EltTy = ATy->getElementType();
10476     CharUnits EltSize = getContext().getTypeSizeInChars(EltTy);
10477     for (uint64_t i = 0; i < ArraySize; ++i) {
10478       bool Ret = detectFPCCEligibleStructHelper(EltTy, CurOff, Field1Ty,
10479                                                 Field1Off, Field2Ty, Field2Off);
10480       if (!Ret)
10481         return false;
10482       CurOff += EltSize;
10483     }
10484     return true;
10485   }
10486 
10487   if (const auto *RTy = Ty->getAs<RecordType>()) {
10488     // Structures with either a non-trivial destructor or a non-trivial
10489     // copy constructor are not eligible for the FP calling convention.
10490     if (getRecordArgABI(Ty, CGT.getCXXABI()))
10491       return false;
10492     if (isEmptyRecord(getContext(), Ty, true))
10493       return true;
10494     const RecordDecl *RD = RTy->getDecl();
10495     // Unions aren't eligible unless they're empty (which is caught above).
10496     if (RD->isUnion())
10497       return false;
10498     int ZeroWidthBitFieldCount = 0;
10499     for (const FieldDecl *FD : RD->fields()) {
10500       const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
10501       uint64_t FieldOffInBits = Layout.getFieldOffset(FD->getFieldIndex());
10502       QualType QTy = FD->getType();
10503       if (FD->isBitField()) {
10504         unsigned BitWidth = FD->getBitWidthValue(getContext());
10505         // Allow a bitfield with a type greater than XLen as long as the
10506         // bitwidth is XLen or less.
10507         if (getContext().getTypeSize(QTy) > XLen && BitWidth <= XLen)
10508           QTy = getContext().getIntTypeForBitwidth(XLen, false);
10509         if (BitWidth == 0) {
10510           ZeroWidthBitFieldCount++;
10511           continue;
10512         }
10513       }
10514 
10515       bool Ret = detectFPCCEligibleStructHelper(
10516           QTy, CurOff + getContext().toCharUnitsFromBits(FieldOffInBits),
10517           Field1Ty, Field1Off, Field2Ty, Field2Off);
10518       if (!Ret)
10519         return false;
10520 
10521       // As a quirk of the ABI, zero-width bitfields aren't ignored for fp+fp
10522       // or int+fp structs, but are ignored for a struct with an fp field and
10523       // any number of zero-width bitfields.
10524       if (Field2Ty && ZeroWidthBitFieldCount > 0)
10525         return false;
10526     }
10527     return Field1Ty != nullptr;
10528   }
10529 
10530   return false;
10531 }
10532 
10533 // Determine if a struct is eligible for passing according to the floating
10534 // point calling convention (i.e., when flattened it contains a single fp
10535 // value, fp+fp, or int+fp of appropriate size). If so, NeededArgFPRs and
10536 // NeededArgGPRs are incremented appropriately.
10537 bool RISCVABIInfo::detectFPCCEligibleStruct(QualType Ty, llvm::Type *&Field1Ty,
10538                                             CharUnits &Field1Off,
10539                                             llvm::Type *&Field2Ty,
10540                                             CharUnits &Field2Off,
10541                                             int &NeededArgGPRs,
10542                                             int &NeededArgFPRs) const {
10543   Field1Ty = nullptr;
10544   Field2Ty = nullptr;
10545   NeededArgGPRs = 0;
10546   NeededArgFPRs = 0;
10547   bool IsCandidate = detectFPCCEligibleStructHelper(
10548       Ty, CharUnits::Zero(), Field1Ty, Field1Off, Field2Ty, Field2Off);
10549   // Not really a candidate if we have a single int but no float.
10550   if (Field1Ty && !Field2Ty && !Field1Ty->isFloatingPointTy())
10551     return false;
10552   if (!IsCandidate)
10553     return false;
10554   if (Field1Ty && Field1Ty->isFloatingPointTy())
10555     NeededArgFPRs++;
10556   else if (Field1Ty)
10557     NeededArgGPRs++;
10558   if (Field2Ty && Field2Ty->isFloatingPointTy())
10559     NeededArgFPRs++;
10560   else if (Field2Ty)
10561     NeededArgGPRs++;
10562   return true;
10563 }
10564 
10565 // Call getCoerceAndExpand for the two-element flattened struct described by
10566 // Field1Ty, Field1Off, Field2Ty, Field2Off. This method will create an
10567 // appropriate coerceToType and unpaddedCoerceToType.
10568 ABIArgInfo RISCVABIInfo::coerceAndExpandFPCCEligibleStruct(
10569     llvm::Type *Field1Ty, CharUnits Field1Off, llvm::Type *Field2Ty,
10570     CharUnits Field2Off) const {
10571   SmallVector<llvm::Type *, 3> CoerceElts;
10572   SmallVector<llvm::Type *, 2> UnpaddedCoerceElts;
10573   if (!Field1Off.isZero())
10574     CoerceElts.push_back(llvm::ArrayType::get(
10575         llvm::Type::getInt8Ty(getVMContext()), Field1Off.getQuantity()));
10576 
10577   CoerceElts.push_back(Field1Ty);
10578   UnpaddedCoerceElts.push_back(Field1Ty);
10579 
10580   if (!Field2Ty) {
10581     return ABIArgInfo::getCoerceAndExpand(
10582         llvm::StructType::get(getVMContext(), CoerceElts, !Field1Off.isZero()),
10583         UnpaddedCoerceElts[0]);
10584   }
10585 
10586   CharUnits Field2Align =
10587       CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(Field2Ty));
10588   CharUnits Field1End = Field1Off +
10589       CharUnits::fromQuantity(getDataLayout().getTypeStoreSize(Field1Ty));
10590   CharUnits Field2OffNoPadNoPack = Field1End.alignTo(Field2Align);
10591 
10592   CharUnits Padding = CharUnits::Zero();
10593   if (Field2Off > Field2OffNoPadNoPack)
10594     Padding = Field2Off - Field2OffNoPadNoPack;
10595   else if (Field2Off != Field2Align && Field2Off > Field1End)
10596     Padding = Field2Off - Field1End;
10597 
10598   bool IsPacked = !Field2Off.isMultipleOf(Field2Align);
10599 
10600   if (!Padding.isZero())
10601     CoerceElts.push_back(llvm::ArrayType::get(
10602         llvm::Type::getInt8Ty(getVMContext()), Padding.getQuantity()));
10603 
10604   CoerceElts.push_back(Field2Ty);
10605   UnpaddedCoerceElts.push_back(Field2Ty);
10606 
10607   auto CoerceToType =
10608       llvm::StructType::get(getVMContext(), CoerceElts, IsPacked);
10609   auto UnpaddedCoerceToType =
10610       llvm::StructType::get(getVMContext(), UnpaddedCoerceElts, IsPacked);
10611 
10612   return ABIArgInfo::getCoerceAndExpand(CoerceToType, UnpaddedCoerceToType);
10613 }
10614 
10615 ABIArgInfo RISCVABIInfo::classifyArgumentType(QualType Ty, bool IsFixed,
10616                                               int &ArgGPRsLeft,
10617                                               int &ArgFPRsLeft) const {
10618   assert(ArgGPRsLeft <= NumArgGPRs && "Arg GPR tracking underflow");
10619   Ty = useFirstFieldIfTransparentUnion(Ty);
10620 
10621   // Structures with either a non-trivial destructor or a non-trivial
10622   // copy constructor are always passed indirectly.
10623   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
10624     if (ArgGPRsLeft)
10625       ArgGPRsLeft -= 1;
10626     return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA ==
10627                                            CGCXXABI::RAA_DirectInMemory);
10628   }
10629 
10630   // Ignore empty structs/unions.
10631   if (isEmptyRecord(getContext(), Ty, true))
10632     return ABIArgInfo::getIgnore();
10633 
10634   uint64_t Size = getContext().getTypeSize(Ty);
10635 
10636   // Pass floating point values via FPRs if possible.
10637   if (IsFixed && Ty->isFloatingType() && !Ty->isComplexType() &&
10638       FLen >= Size && ArgFPRsLeft) {
10639     ArgFPRsLeft--;
10640     return ABIArgInfo::getDirect();
10641   }
10642 
10643   // Complex types for the hard float ABI must be passed direct rather than
10644   // using CoerceAndExpand.
10645   if (IsFixed && Ty->isComplexType() && FLen && ArgFPRsLeft >= 2) {
10646     QualType EltTy = Ty->castAs<ComplexType>()->getElementType();
10647     if (getContext().getTypeSize(EltTy) <= FLen) {
10648       ArgFPRsLeft -= 2;
10649       return ABIArgInfo::getDirect();
10650     }
10651   }
10652 
10653   if (IsFixed && FLen && Ty->isStructureOrClassType()) {
10654     llvm::Type *Field1Ty = nullptr;
10655     llvm::Type *Field2Ty = nullptr;
10656     CharUnits Field1Off = CharUnits::Zero();
10657     CharUnits Field2Off = CharUnits::Zero();
10658     int NeededArgGPRs;
10659     int NeededArgFPRs;
10660     bool IsCandidate =
10661         detectFPCCEligibleStruct(Ty, Field1Ty, Field1Off, Field2Ty, Field2Off,
10662                                  NeededArgGPRs, NeededArgFPRs);
10663     if (IsCandidate && NeededArgGPRs <= ArgGPRsLeft &&
10664         NeededArgFPRs <= ArgFPRsLeft) {
10665       ArgGPRsLeft -= NeededArgGPRs;
10666       ArgFPRsLeft -= NeededArgFPRs;
10667       return coerceAndExpandFPCCEligibleStruct(Field1Ty, Field1Off, Field2Ty,
10668                                                Field2Off);
10669     }
10670   }
10671 
10672   uint64_t NeededAlign = getContext().getTypeAlign(Ty);
10673   bool MustUseStack = false;
10674   // Determine the number of GPRs needed to pass the current argument
10675   // according to the ABI. 2*XLen-aligned varargs are passed in "aligned"
10676   // register pairs, so may consume 3 registers.
10677   int NeededArgGPRs = 1;
10678   if (!IsFixed && NeededAlign == 2 * XLen)
10679     NeededArgGPRs = 2 + (ArgGPRsLeft % 2);
10680   else if (Size > XLen && Size <= 2 * XLen)
10681     NeededArgGPRs = 2;
10682 
10683   if (NeededArgGPRs > ArgGPRsLeft) {
10684     MustUseStack = true;
10685     NeededArgGPRs = ArgGPRsLeft;
10686   }
10687 
10688   ArgGPRsLeft -= NeededArgGPRs;
10689 
10690   if (!isAggregateTypeForABI(Ty) && !Ty->isVectorType()) {
10691     // Treat an enum type as its underlying type.
10692     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
10693       Ty = EnumTy->getDecl()->getIntegerType();
10694 
10695     // All integral types are promoted to XLen width, unless passed on the
10696     // stack.
10697     if (Size < XLen && Ty->isIntegralOrEnumerationType() && !MustUseStack) {
10698       return extendType(Ty);
10699     }
10700 
10701     if (const auto *EIT = Ty->getAs<ExtIntType>()) {
10702       if (EIT->getNumBits() < XLen && !MustUseStack)
10703         return extendType(Ty);
10704       if (EIT->getNumBits() > 128 ||
10705           (!getContext().getTargetInfo().hasInt128Type() &&
10706            EIT->getNumBits() > 64))
10707         return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
10708     }
10709 
10710     return ABIArgInfo::getDirect();
10711   }
10712 
10713   // Aggregates which are <= 2*XLen will be passed in registers if possible,
10714   // so coerce to integers.
10715   if (Size <= 2 * XLen) {
10716     unsigned Alignment = getContext().getTypeAlign(Ty);
10717 
10718     // Use a single XLen int if possible, 2*XLen if 2*XLen alignment is
10719     // required, and a 2-element XLen array if only XLen alignment is required.
10720     if (Size <= XLen) {
10721       return ABIArgInfo::getDirect(
10722           llvm::IntegerType::get(getVMContext(), XLen));
10723     } else if (Alignment == 2 * XLen) {
10724       return ABIArgInfo::getDirect(
10725           llvm::IntegerType::get(getVMContext(), 2 * XLen));
10726     } else {
10727       return ABIArgInfo::getDirect(llvm::ArrayType::get(
10728           llvm::IntegerType::get(getVMContext(), XLen), 2));
10729     }
10730   }
10731   return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
10732 }
10733 
10734 ABIArgInfo RISCVABIInfo::classifyReturnType(QualType RetTy) const {
10735   if (RetTy->isVoidType())
10736     return ABIArgInfo::getIgnore();
10737 
10738   int ArgGPRsLeft = 2;
10739   int ArgFPRsLeft = FLen ? 2 : 0;
10740 
10741   // The rules for return and argument types are the same, so defer to
10742   // classifyArgumentType.
10743   return classifyArgumentType(RetTy, /*IsFixed=*/true, ArgGPRsLeft,
10744                               ArgFPRsLeft);
10745 }
10746 
10747 Address RISCVABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
10748                                 QualType Ty) const {
10749   CharUnits SlotSize = CharUnits::fromQuantity(XLen / 8);
10750 
10751   // Empty records are ignored for parameter passing purposes.
10752   if (isEmptyRecord(getContext(), Ty, true)) {
10753     Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize);
10754     Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
10755     return Addr;
10756   }
10757 
10758   auto TInfo = getContext().getTypeInfoInChars(Ty);
10759 
10760   // Arguments bigger than 2*Xlen bytes are passed indirectly.
10761   bool IsIndirect = TInfo.Width > 2 * SlotSize;
10762 
10763   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TInfo,
10764                           SlotSize, /*AllowHigherAlign=*/true);
10765 }
10766 
10767 ABIArgInfo RISCVABIInfo::extendType(QualType Ty) const {
10768   int TySize = getContext().getTypeSize(Ty);
10769   // RV64 ABI requires unsigned 32 bit integers to be sign extended.
10770   if (XLen == 64 && Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
10771     return ABIArgInfo::getSignExtend(Ty);
10772   return ABIArgInfo::getExtend(Ty);
10773 }
10774 
10775 namespace {
10776 class RISCVTargetCodeGenInfo : public TargetCodeGenInfo {
10777 public:
10778   RISCVTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, unsigned XLen,
10779                          unsigned FLen)
10780       : TargetCodeGenInfo(std::make_unique<RISCVABIInfo>(CGT, XLen, FLen)) {}
10781 
10782   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
10783                            CodeGen::CodeGenModule &CGM) const override {
10784     const auto *FD = dyn_cast_or_null<FunctionDecl>(D);
10785     if (!FD) return;
10786 
10787     const auto *Attr = FD->getAttr<RISCVInterruptAttr>();
10788     if (!Attr)
10789       return;
10790 
10791     const char *Kind;
10792     switch (Attr->getInterrupt()) {
10793     case RISCVInterruptAttr::user: Kind = "user"; break;
10794     case RISCVInterruptAttr::supervisor: Kind = "supervisor"; break;
10795     case RISCVInterruptAttr::machine: Kind = "machine"; break;
10796     }
10797 
10798     auto *Fn = cast<llvm::Function>(GV);
10799 
10800     Fn->addFnAttr("interrupt", Kind);
10801   }
10802 };
10803 } // namespace
10804 
10805 //===----------------------------------------------------------------------===//
10806 // VE ABI Implementation.
10807 //
10808 namespace {
10809 class VEABIInfo : public DefaultABIInfo {
10810 public:
10811   VEABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
10812 
10813 private:
10814   ABIArgInfo classifyReturnType(QualType RetTy) const;
10815   ABIArgInfo classifyArgumentType(QualType RetTy) const;
10816   void computeInfo(CGFunctionInfo &FI) const override;
10817 };
10818 } // end anonymous namespace
10819 
10820 ABIArgInfo VEABIInfo::classifyReturnType(QualType Ty) const {
10821   if (Ty->isAnyComplexType())
10822     return ABIArgInfo::getDirect();
10823   uint64_t Size = getContext().getTypeSize(Ty);
10824   if (Size < 64 && Ty->isIntegerType())
10825     return ABIArgInfo::getExtend(Ty);
10826   return DefaultABIInfo::classifyReturnType(Ty);
10827 }
10828 
10829 ABIArgInfo VEABIInfo::classifyArgumentType(QualType Ty) const {
10830   if (Ty->isAnyComplexType())
10831     return ABIArgInfo::getDirect();
10832   uint64_t Size = getContext().getTypeSize(Ty);
10833   if (Size < 64 && Ty->isIntegerType())
10834     return ABIArgInfo::getExtend(Ty);
10835   return DefaultABIInfo::classifyArgumentType(Ty);
10836 }
10837 
10838 void VEABIInfo::computeInfo(CGFunctionInfo &FI) const {
10839   FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
10840   for (auto &Arg : FI.arguments())
10841     Arg.info = classifyArgumentType(Arg.type);
10842 }
10843 
10844 namespace {
10845 class VETargetCodeGenInfo : public TargetCodeGenInfo {
10846 public:
10847   VETargetCodeGenInfo(CodeGenTypes &CGT)
10848       : TargetCodeGenInfo(std::make_unique<VEABIInfo>(CGT)) {}
10849   // VE ABI requires the arguments of variadic and prototype-less functions
10850   // are passed in both registers and memory.
10851   bool isNoProtoCallVariadic(const CallArgList &args,
10852                              const FunctionNoProtoType *fnType) const override {
10853     return true;
10854   }
10855 };
10856 } // end anonymous namespace
10857 
10858 //===----------------------------------------------------------------------===//
10859 // Driver code
10860 //===----------------------------------------------------------------------===//
10861 
10862 bool CodeGenModule::supportsCOMDAT() const {
10863   return getTriple().supportsCOMDAT();
10864 }
10865 
10866 const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
10867   if (TheTargetCodeGenInfo)
10868     return *TheTargetCodeGenInfo;
10869 
10870   // Helper to set the unique_ptr while still keeping the return value.
10871   auto SetCGInfo = [&](TargetCodeGenInfo *P) -> const TargetCodeGenInfo & {
10872     this->TheTargetCodeGenInfo.reset(P);
10873     return *P;
10874   };
10875 
10876   const llvm::Triple &Triple = getTarget().getTriple();
10877   switch (Triple.getArch()) {
10878   default:
10879     return SetCGInfo(new DefaultTargetCodeGenInfo(Types));
10880 
10881   case llvm::Triple::le32:
10882     return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
10883   case llvm::Triple::mips:
10884   case llvm::Triple::mipsel:
10885     if (Triple.getOS() == llvm::Triple::NaCl)
10886       return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
10887     return SetCGInfo(new MIPSTargetCodeGenInfo(Types, true));
10888 
10889   case llvm::Triple::mips64:
10890   case llvm::Triple::mips64el:
10891     return SetCGInfo(new MIPSTargetCodeGenInfo(Types, false));
10892 
10893   case llvm::Triple::avr:
10894     return SetCGInfo(new AVRTargetCodeGenInfo(Types));
10895 
10896   case llvm::Triple::aarch64:
10897   case llvm::Triple::aarch64_32:
10898   case llvm::Triple::aarch64_be: {
10899     AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS;
10900     if (getTarget().getABI() == "darwinpcs")
10901       Kind = AArch64ABIInfo::DarwinPCS;
10902     else if (Triple.isOSWindows())
10903       return SetCGInfo(
10904           new WindowsAArch64TargetCodeGenInfo(Types, AArch64ABIInfo::Win64));
10905 
10906     return SetCGInfo(new AArch64TargetCodeGenInfo(Types, Kind));
10907   }
10908 
10909   case llvm::Triple::wasm32:
10910   case llvm::Triple::wasm64: {
10911     WebAssemblyABIInfo::ABIKind Kind = WebAssemblyABIInfo::MVP;
10912     if (getTarget().getABI() == "experimental-mv")
10913       Kind = WebAssemblyABIInfo::ExperimentalMV;
10914     return SetCGInfo(new WebAssemblyTargetCodeGenInfo(Types, Kind));
10915   }
10916 
10917   case llvm::Triple::arm:
10918   case llvm::Triple::armeb:
10919   case llvm::Triple::thumb:
10920   case llvm::Triple::thumbeb: {
10921     if (Triple.getOS() == llvm::Triple::Win32) {
10922       return SetCGInfo(
10923           new WindowsARMTargetCodeGenInfo(Types, ARMABIInfo::AAPCS_VFP));
10924     }
10925 
10926     ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
10927     StringRef ABIStr = getTarget().getABI();
10928     if (ABIStr == "apcs-gnu")
10929       Kind = ARMABIInfo::APCS;
10930     else if (ABIStr == "aapcs16")
10931       Kind = ARMABIInfo::AAPCS16_VFP;
10932     else if (CodeGenOpts.FloatABI == "hard" ||
10933              (CodeGenOpts.FloatABI != "soft" &&
10934               (Triple.getEnvironment() == llvm::Triple::GNUEABIHF ||
10935                Triple.getEnvironment() == llvm::Triple::MuslEABIHF ||
10936                Triple.getEnvironment() == llvm::Triple::EABIHF)))
10937       Kind = ARMABIInfo::AAPCS_VFP;
10938 
10939     return SetCGInfo(new ARMTargetCodeGenInfo(Types, Kind));
10940   }
10941 
10942   case llvm::Triple::ppc: {
10943     if (Triple.isOSAIX())
10944       return SetCGInfo(new AIXTargetCodeGenInfo(Types, /*Is64Bit*/ false));
10945 
10946     bool IsSoftFloat =
10947         CodeGenOpts.FloatABI == "soft" || getTarget().hasFeature("spe");
10948     bool RetSmallStructInRegABI =
10949         PPC32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
10950     return SetCGInfo(
10951         new PPC32TargetCodeGenInfo(Types, IsSoftFloat, RetSmallStructInRegABI));
10952   }
10953   case llvm::Triple::ppcle: {
10954     bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
10955     bool RetSmallStructInRegABI =
10956         PPC32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
10957     return SetCGInfo(
10958         new PPC32TargetCodeGenInfo(Types, IsSoftFloat, RetSmallStructInRegABI));
10959   }
10960   case llvm::Triple::ppc64:
10961     if (Triple.isOSAIX())
10962       return SetCGInfo(new AIXTargetCodeGenInfo(Types, /*Is64Bit*/ true));
10963 
10964     if (Triple.isOSBinFormatELF()) {
10965       PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1;
10966       if (getTarget().getABI() == "elfv2")
10967         Kind = PPC64_SVR4_ABIInfo::ELFv2;
10968       bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
10969 
10970       return SetCGInfo(
10971           new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, IsSoftFloat));
10972     }
10973     return SetCGInfo(new PPC64TargetCodeGenInfo(Types));
10974   case llvm::Triple::ppc64le: {
10975     assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
10976     PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2;
10977     if (getTarget().getABI() == "elfv1")
10978       Kind = PPC64_SVR4_ABIInfo::ELFv1;
10979     bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
10980 
10981     return SetCGInfo(
10982         new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, IsSoftFloat));
10983   }
10984 
10985   case llvm::Triple::nvptx:
10986   case llvm::Triple::nvptx64:
10987     return SetCGInfo(new NVPTXTargetCodeGenInfo(Types));
10988 
10989   case llvm::Triple::msp430:
10990     return SetCGInfo(new MSP430TargetCodeGenInfo(Types));
10991 
10992   case llvm::Triple::riscv32:
10993   case llvm::Triple::riscv64: {
10994     StringRef ABIStr = getTarget().getABI();
10995     unsigned XLen = getTarget().getPointerWidth(0);
10996     unsigned ABIFLen = 0;
10997     if (ABIStr.endswith("f"))
10998       ABIFLen = 32;
10999     else if (ABIStr.endswith("d"))
11000       ABIFLen = 64;
11001     return SetCGInfo(new RISCVTargetCodeGenInfo(Types, XLen, ABIFLen));
11002   }
11003 
11004   case llvm::Triple::systemz: {
11005     bool SoftFloat = CodeGenOpts.FloatABI == "soft";
11006     bool HasVector = !SoftFloat && getTarget().getABI() == "vector";
11007     return SetCGInfo(new SystemZTargetCodeGenInfo(Types, HasVector, SoftFloat));
11008   }
11009 
11010   case llvm::Triple::tce:
11011   case llvm::Triple::tcele:
11012     return SetCGInfo(new TCETargetCodeGenInfo(Types));
11013 
11014   case llvm::Triple::x86: {
11015     bool IsDarwinVectorABI = Triple.isOSDarwin();
11016     bool RetSmallStructInRegABI =
11017         X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
11018     bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
11019 
11020     if (Triple.getOS() == llvm::Triple::Win32) {
11021       return SetCGInfo(new WinX86_32TargetCodeGenInfo(
11022           Types, IsDarwinVectorABI, RetSmallStructInRegABI,
11023           IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters));
11024     } else {
11025       return SetCGInfo(new X86_32TargetCodeGenInfo(
11026           Types, IsDarwinVectorABI, RetSmallStructInRegABI,
11027           IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters,
11028           CodeGenOpts.FloatABI == "soft"));
11029     }
11030   }
11031 
11032   case llvm::Triple::x86_64: {
11033     StringRef ABI = getTarget().getABI();
11034     X86AVXABILevel AVXLevel =
11035         (ABI == "avx512"
11036              ? X86AVXABILevel::AVX512
11037              : ABI == "avx" ? X86AVXABILevel::AVX : X86AVXABILevel::None);
11038 
11039     switch (Triple.getOS()) {
11040     case llvm::Triple::Win32:
11041       return SetCGInfo(new WinX86_64TargetCodeGenInfo(Types, AVXLevel));
11042     default:
11043       return SetCGInfo(new X86_64TargetCodeGenInfo(Types, AVXLevel));
11044     }
11045   }
11046   case llvm::Triple::hexagon:
11047     return SetCGInfo(new HexagonTargetCodeGenInfo(Types));
11048   case llvm::Triple::lanai:
11049     return SetCGInfo(new LanaiTargetCodeGenInfo(Types));
11050   case llvm::Triple::r600:
11051     return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
11052   case llvm::Triple::amdgcn:
11053     return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
11054   case llvm::Triple::sparc:
11055     return SetCGInfo(new SparcV8TargetCodeGenInfo(Types));
11056   case llvm::Triple::sparcv9:
11057     return SetCGInfo(new SparcV9TargetCodeGenInfo(Types));
11058   case llvm::Triple::xcore:
11059     return SetCGInfo(new XCoreTargetCodeGenInfo(Types));
11060   case llvm::Triple::arc:
11061     return SetCGInfo(new ARCTargetCodeGenInfo(Types));
11062   case llvm::Triple::spir:
11063   case llvm::Triple::spir64:
11064     return SetCGInfo(new SPIRTargetCodeGenInfo(Types));
11065   case llvm::Triple::ve:
11066     return SetCGInfo(new VETargetCodeGenInfo(Types));
11067   }
11068 }
11069 
11070 /// Create an OpenCL kernel for an enqueued block.
11071 ///
11072 /// The kernel has the same function type as the block invoke function. Its
11073 /// name is the name of the block invoke function postfixed with "_kernel".
11074 /// It simply calls the block invoke function then returns.
11075 llvm::Function *
11076 TargetCodeGenInfo::createEnqueuedBlockKernel(CodeGenFunction &CGF,
11077                                              llvm::Function *Invoke,
11078                                              llvm::Value *BlockLiteral) const {
11079   auto *InvokeFT = Invoke->getFunctionType();
11080   llvm::SmallVector<llvm::Type *, 2> ArgTys;
11081   for (auto &P : InvokeFT->params())
11082     ArgTys.push_back(P);
11083   auto &C = CGF.getLLVMContext();
11084   std::string Name = Invoke->getName().str() + "_kernel";
11085   auto *FT = llvm::FunctionType::get(llvm::Type::getVoidTy(C), ArgTys, false);
11086   auto *F = llvm::Function::Create(FT, llvm::GlobalValue::InternalLinkage, Name,
11087                                    &CGF.CGM.getModule());
11088   auto IP = CGF.Builder.saveIP();
11089   auto *BB = llvm::BasicBlock::Create(C, "entry", F);
11090   auto &Builder = CGF.Builder;
11091   Builder.SetInsertPoint(BB);
11092   llvm::SmallVector<llvm::Value *, 2> Args;
11093   for (auto &A : F->args())
11094     Args.push_back(&A);
11095   llvm::CallInst *call = Builder.CreateCall(Invoke, Args);
11096   call->setCallingConv(Invoke->getCallingConv());
11097   Builder.CreateRetVoid();
11098   Builder.restoreIP(IP);
11099   return F;
11100 }
11101 
11102 /// Create an OpenCL kernel for an enqueued block.
11103 ///
11104 /// The type of the first argument (the block literal) is the struct type
11105 /// of the block literal instead of a pointer type. The first argument
11106 /// (block literal) is passed directly by value to the kernel. The kernel
11107 /// allocates the same type of struct on stack and stores the block literal
11108 /// to it and passes its pointer to the block invoke function. The kernel
11109 /// has "enqueued-block" function attribute and kernel argument metadata.
11110 llvm::Function *AMDGPUTargetCodeGenInfo::createEnqueuedBlockKernel(
11111     CodeGenFunction &CGF, llvm::Function *Invoke,
11112     llvm::Value *BlockLiteral) const {
11113   auto &Builder = CGF.Builder;
11114   auto &C = CGF.getLLVMContext();
11115 
11116   auto *BlockTy = BlockLiteral->getType()->getPointerElementType();
11117   auto *InvokeFT = Invoke->getFunctionType();
11118   llvm::SmallVector<llvm::Type *, 2> ArgTys;
11119   llvm::SmallVector<llvm::Metadata *, 8> AddressQuals;
11120   llvm::SmallVector<llvm::Metadata *, 8> AccessQuals;
11121   llvm::SmallVector<llvm::Metadata *, 8> ArgTypeNames;
11122   llvm::SmallVector<llvm::Metadata *, 8> ArgBaseTypeNames;
11123   llvm::SmallVector<llvm::Metadata *, 8> ArgTypeQuals;
11124   llvm::SmallVector<llvm::Metadata *, 8> ArgNames;
11125 
11126   ArgTys.push_back(BlockTy);
11127   ArgTypeNames.push_back(llvm::MDString::get(C, "__block_literal"));
11128   AddressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(0)));
11129   ArgBaseTypeNames.push_back(llvm::MDString::get(C, "__block_literal"));
11130   ArgTypeQuals.push_back(llvm::MDString::get(C, ""));
11131   AccessQuals.push_back(llvm::MDString::get(C, "none"));
11132   ArgNames.push_back(llvm::MDString::get(C, "block_literal"));
11133   for (unsigned I = 1, E = InvokeFT->getNumParams(); I < E; ++I) {
11134     ArgTys.push_back(InvokeFT->getParamType(I));
11135     ArgTypeNames.push_back(llvm::MDString::get(C, "void*"));
11136     AddressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(3)));
11137     AccessQuals.push_back(llvm::MDString::get(C, "none"));
11138     ArgBaseTypeNames.push_back(llvm::MDString::get(C, "void*"));
11139     ArgTypeQuals.push_back(llvm::MDString::get(C, ""));
11140     ArgNames.push_back(
11141         llvm::MDString::get(C, (Twine("local_arg") + Twine(I)).str()));
11142   }
11143   std::string Name = Invoke->getName().str() + "_kernel";
11144   auto *FT = llvm::FunctionType::get(llvm::Type::getVoidTy(C), ArgTys, false);
11145   auto *F = llvm::Function::Create(FT, llvm::GlobalValue::InternalLinkage, Name,
11146                                    &CGF.CGM.getModule());
11147   F->addFnAttr("enqueued-block");
11148   auto IP = CGF.Builder.saveIP();
11149   auto *BB = llvm::BasicBlock::Create(C, "entry", F);
11150   Builder.SetInsertPoint(BB);
11151   const auto BlockAlign = CGF.CGM.getDataLayout().getPrefTypeAlign(BlockTy);
11152   auto *BlockPtr = Builder.CreateAlloca(BlockTy, nullptr);
11153   BlockPtr->setAlignment(BlockAlign);
11154   Builder.CreateAlignedStore(F->arg_begin(), BlockPtr, BlockAlign);
11155   auto *Cast = Builder.CreatePointerCast(BlockPtr, InvokeFT->getParamType(0));
11156   llvm::SmallVector<llvm::Value *, 2> Args;
11157   Args.push_back(Cast);
11158   for (auto I = F->arg_begin() + 1, E = F->arg_end(); I != E; ++I)
11159     Args.push_back(I);
11160   llvm::CallInst *call = Builder.CreateCall(Invoke, Args);
11161   call->setCallingConv(Invoke->getCallingConv());
11162   Builder.CreateRetVoid();
11163   Builder.restoreIP(IP);
11164 
11165   F->setMetadata("kernel_arg_addr_space", llvm::MDNode::get(C, AddressQuals));
11166   F->setMetadata("kernel_arg_access_qual", llvm::MDNode::get(C, AccessQuals));
11167   F->setMetadata("kernel_arg_type", llvm::MDNode::get(C, ArgTypeNames));
11168   F->setMetadata("kernel_arg_base_type",
11169                  llvm::MDNode::get(C, ArgBaseTypeNames));
11170   F->setMetadata("kernel_arg_type_qual", llvm::MDNode::get(C, ArgTypeQuals));
11171   if (CGF.CGM.getCodeGenOpts().EmitOpenCLArgMetadata)
11172     F->setMetadata("kernel_arg_name", llvm::MDNode::get(C, ArgNames));
11173 
11174   return F;
11175 }
11176