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 static llvm::Type *getVAListElementType(CodeGenFunction &CGF) {
104   return CGF.ConvertTypeForMem(
105       CGF.getContext().getBuiltinVaListType()->getPointeeType());
106 }
107 
108 bool ABIInfo::isPromotableIntegerTypeForABI(QualType Ty) const {
109   if (Ty->isPromotableIntegerType())
110     return true;
111 
112   if (const auto *EIT = Ty->getAs<BitIntType>())
113     if (EIT->getNumBits() < getContext().getTypeSize(getContext().IntTy))
114       return true;
115 
116   return false;
117 }
118 
119 ABIInfo::~ABIInfo() {}
120 
121 /// Does the given lowering require more than the given number of
122 /// registers when expanded?
123 ///
124 /// This is intended to be the basis of a reasonable basic implementation
125 /// of should{Pass,Return}IndirectlyForSwift.
126 ///
127 /// For most targets, a limit of four total registers is reasonable; this
128 /// limits the amount of code required in order to move around the value
129 /// in case it wasn't produced immediately prior to the call by the caller
130 /// (or wasn't produced in exactly the right registers) or isn't used
131 /// immediately within the callee.  But some targets may need to further
132 /// limit the register count due to an inability to support that many
133 /// return registers.
134 static bool occupiesMoreThan(CodeGenTypes &cgt,
135                              ArrayRef<llvm::Type*> scalarTypes,
136                              unsigned maxAllRegisters) {
137   unsigned intCount = 0, fpCount = 0;
138   for (llvm::Type *type : scalarTypes) {
139     if (type->isPointerTy()) {
140       intCount++;
141     } else if (auto intTy = dyn_cast<llvm::IntegerType>(type)) {
142       auto ptrWidth = cgt.getTarget().getPointerWidth(0);
143       intCount += (intTy->getBitWidth() + ptrWidth - 1) / ptrWidth;
144     } else {
145       assert(type->isVectorTy() || type->isFloatingPointTy());
146       fpCount++;
147     }
148   }
149 
150   return (intCount + fpCount > maxAllRegisters);
151 }
152 
153 bool SwiftABIInfo::isLegalVectorTypeForSwift(CharUnits vectorSize,
154                                              llvm::Type *eltTy,
155                                              unsigned numElts) const {
156   // The default implementation of this assumes that the target guarantees
157   // 128-bit SIMD support but nothing more.
158   return (vectorSize.getQuantity() > 8 && vectorSize.getQuantity() <= 16);
159 }
160 
161 static CGCXXABI::RecordArgABI getRecordArgABI(const RecordType *RT,
162                                               CGCXXABI &CXXABI) {
163   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
164   if (!RD) {
165     if (!RT->getDecl()->canPassInRegisters())
166       return CGCXXABI::RAA_Indirect;
167     return CGCXXABI::RAA_Default;
168   }
169   return CXXABI.getRecordArgABI(RD);
170 }
171 
172 static CGCXXABI::RecordArgABI getRecordArgABI(QualType T,
173                                               CGCXXABI &CXXABI) {
174   const RecordType *RT = T->getAs<RecordType>();
175   if (!RT)
176     return CGCXXABI::RAA_Default;
177   return getRecordArgABI(RT, CXXABI);
178 }
179 
180 static bool classifyReturnType(const CGCXXABI &CXXABI, CGFunctionInfo &FI,
181                                const ABIInfo &Info) {
182   QualType Ty = FI.getReturnType();
183 
184   if (const auto *RT = Ty->getAs<RecordType>())
185     if (!isa<CXXRecordDecl>(RT->getDecl()) &&
186         !RT->getDecl()->canPassInRegisters()) {
187       FI.getReturnInfo() = Info.getNaturalAlignIndirect(Ty);
188       return true;
189     }
190 
191   return CXXABI.classifyReturnType(FI);
192 }
193 
194 /// Pass transparent unions as if they were the type of the first element. Sema
195 /// should ensure that all elements of the union have the same "machine type".
196 static QualType useFirstFieldIfTransparentUnion(QualType Ty) {
197   if (const RecordType *UT = Ty->getAsUnionType()) {
198     const RecordDecl *UD = UT->getDecl();
199     if (UD->hasAttr<TransparentUnionAttr>()) {
200       assert(!UD->field_empty() && "sema created an empty transparent union");
201       return UD->field_begin()->getType();
202     }
203   }
204   return Ty;
205 }
206 
207 CGCXXABI &ABIInfo::getCXXABI() const {
208   return CGT.getCXXABI();
209 }
210 
211 ASTContext &ABIInfo::getContext() const {
212   return CGT.getContext();
213 }
214 
215 llvm::LLVMContext &ABIInfo::getVMContext() const {
216   return CGT.getLLVMContext();
217 }
218 
219 const llvm::DataLayout &ABIInfo::getDataLayout() const {
220   return CGT.getDataLayout();
221 }
222 
223 const TargetInfo &ABIInfo::getTarget() const {
224   return CGT.getTarget();
225 }
226 
227 const CodeGenOptions &ABIInfo::getCodeGenOpts() const {
228   return CGT.getCodeGenOpts();
229 }
230 
231 bool ABIInfo::isAndroid() const { return getTarget().getTriple().isAndroid(); }
232 
233 bool ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
234   return false;
235 }
236 
237 bool ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
238                                                 uint64_t Members) const {
239   return false;
240 }
241 
242 LLVM_DUMP_METHOD void ABIArgInfo::dump() const {
243   raw_ostream &OS = llvm::errs();
244   OS << "(ABIArgInfo Kind=";
245   switch (TheKind) {
246   case Direct:
247     OS << "Direct Type=";
248     if (llvm::Type *Ty = getCoerceToType())
249       Ty->print(OS);
250     else
251       OS << "null";
252     break;
253   case Extend:
254     OS << "Extend";
255     break;
256   case Ignore:
257     OS << "Ignore";
258     break;
259   case InAlloca:
260     OS << "InAlloca Offset=" << getInAllocaFieldIndex();
261     break;
262   case Indirect:
263     OS << "Indirect Align=" << getIndirectAlign().getQuantity()
264        << " ByVal=" << getIndirectByVal()
265        << " Realign=" << getIndirectRealign();
266     break;
267   case IndirectAliased:
268     OS << "Indirect Align=" << getIndirectAlign().getQuantity()
269        << " AadrSpace=" << getIndirectAddrSpace()
270        << " Realign=" << getIndirectRealign();
271     break;
272   case Expand:
273     OS << "Expand";
274     break;
275   case CoerceAndExpand:
276     OS << "CoerceAndExpand Type=";
277     getCoerceAndExpandType()->print(OS);
278     break;
279   }
280   OS << ")\n";
281 }
282 
283 // Dynamically round a pointer up to a multiple of the given alignment.
284 static llvm::Value *emitRoundPointerUpToAlignment(CodeGenFunction &CGF,
285                                                   llvm::Value *Ptr,
286                                                   CharUnits Align) {
287   llvm::Value *PtrAsInt = Ptr;
288   // OverflowArgArea = (OverflowArgArea + Align - 1) & -Align;
289   PtrAsInt = CGF.Builder.CreatePtrToInt(PtrAsInt, CGF.IntPtrTy);
290   PtrAsInt = CGF.Builder.CreateAdd(PtrAsInt,
291         llvm::ConstantInt::get(CGF.IntPtrTy, Align.getQuantity() - 1));
292   PtrAsInt = CGF.Builder.CreateAnd(PtrAsInt,
293            llvm::ConstantInt::get(CGF.IntPtrTy, -Align.getQuantity()));
294   PtrAsInt = CGF.Builder.CreateIntToPtr(PtrAsInt,
295                                         Ptr->getType(),
296                                         Ptr->getName() + ".aligned");
297   return PtrAsInt;
298 }
299 
300 /// Emit va_arg for a platform using the common void* representation,
301 /// where arguments are simply emitted in an array of slots on the stack.
302 ///
303 /// This version implements the core direct-value passing rules.
304 ///
305 /// \param SlotSize - The size and alignment of a stack slot.
306 ///   Each argument will be allocated to a multiple of this number of
307 ///   slots, and all the slots will be aligned to this value.
308 /// \param AllowHigherAlign - The slot alignment is not a cap;
309 ///   an argument type with an alignment greater than the slot size
310 ///   will be emitted on a higher-alignment address, potentially
311 ///   leaving one or more empty slots behind as padding.  If this
312 ///   is false, the returned address might be less-aligned than
313 ///   DirectAlign.
314 static Address emitVoidPtrDirectVAArg(CodeGenFunction &CGF,
315                                       Address VAListAddr,
316                                       llvm::Type *DirectTy,
317                                       CharUnits DirectSize,
318                                       CharUnits DirectAlign,
319                                       CharUnits SlotSize,
320                                       bool AllowHigherAlign) {
321   // Cast the element type to i8* if necessary.  Some platforms define
322   // va_list as a struct containing an i8* instead of just an i8*.
323   if (VAListAddr.getElementType() != CGF.Int8PtrTy)
324     VAListAddr = CGF.Builder.CreateElementBitCast(VAListAddr, CGF.Int8PtrTy);
325 
326   llvm::Value *Ptr = CGF.Builder.CreateLoad(VAListAddr, "argp.cur");
327 
328   // If the CC aligns values higher than the slot size, do so if needed.
329   Address Addr = Address::invalid();
330   if (AllowHigherAlign && DirectAlign > SlotSize) {
331     Addr = Address(emitRoundPointerUpToAlignment(CGF, Ptr, DirectAlign),
332                    CGF.Int8Ty, DirectAlign);
333   } else {
334     Addr = Address(Ptr, CGF.Int8Ty, SlotSize);
335   }
336 
337   // Advance the pointer past the argument, then store that back.
338   CharUnits FullDirectSize = DirectSize.alignTo(SlotSize);
339   Address NextPtr =
340       CGF.Builder.CreateConstInBoundsByteGEP(Addr, FullDirectSize, "argp.next");
341   CGF.Builder.CreateStore(NextPtr.getPointer(), VAListAddr);
342 
343   // If the argument is smaller than a slot, and this is a big-endian
344   // target, the argument will be right-adjusted in its slot.
345   if (DirectSize < SlotSize && CGF.CGM.getDataLayout().isBigEndian() &&
346       !DirectTy->isStructTy()) {
347     Addr = CGF.Builder.CreateConstInBoundsByteGEP(Addr, SlotSize - DirectSize);
348   }
349 
350   Addr = CGF.Builder.CreateElementBitCast(Addr, DirectTy);
351   return Addr;
352 }
353 
354 /// Emit va_arg for a platform using the common void* representation,
355 /// where arguments are simply emitted in an array of slots on the stack.
356 ///
357 /// \param IsIndirect - Values of this type are passed indirectly.
358 /// \param ValueInfo - The size and alignment of this type, generally
359 ///   computed with getContext().getTypeInfoInChars(ValueTy).
360 /// \param SlotSizeAndAlign - The size and alignment of a stack slot.
361 ///   Each argument will be allocated to a multiple of this number of
362 ///   slots, and all the slots will be aligned to this value.
363 /// \param AllowHigherAlign - The slot alignment is not a cap;
364 ///   an argument type with an alignment greater than the slot size
365 ///   will be emitted on a higher-alignment address, potentially
366 ///   leaving one or more empty slots behind as padding.
367 static Address emitVoidPtrVAArg(CodeGenFunction &CGF, Address VAListAddr,
368                                 QualType ValueTy, bool IsIndirect,
369                                 TypeInfoChars ValueInfo,
370                                 CharUnits SlotSizeAndAlign,
371                                 bool AllowHigherAlign) {
372   // The size and alignment of the value that was passed directly.
373   CharUnits DirectSize, DirectAlign;
374   if (IsIndirect) {
375     DirectSize = CGF.getPointerSize();
376     DirectAlign = CGF.getPointerAlign();
377   } else {
378     DirectSize = ValueInfo.Width;
379     DirectAlign = ValueInfo.Align;
380   }
381 
382   // Cast the address we've calculated to the right type.
383   llvm::Type *DirectTy = CGF.ConvertTypeForMem(ValueTy), *ElementTy = DirectTy;
384   if (IsIndirect)
385     DirectTy = DirectTy->getPointerTo(0);
386 
387   Address Addr =
388       emitVoidPtrDirectVAArg(CGF, VAListAddr, DirectTy, DirectSize, DirectAlign,
389                              SlotSizeAndAlign, AllowHigherAlign);
390 
391   if (IsIndirect) {
392     Addr = Address(CGF.Builder.CreateLoad(Addr), ElementTy, ValueInfo.Align);
393   }
394 
395   return Addr;
396 }
397 
398 static Address complexTempStructure(CodeGenFunction &CGF, Address VAListAddr,
399                                     QualType Ty, CharUnits SlotSize,
400                                     CharUnits EltSize, const ComplexType *CTy) {
401   Address Addr =
402       emitVoidPtrDirectVAArg(CGF, VAListAddr, CGF.Int8Ty, SlotSize * 2,
403                              SlotSize, SlotSize, /*AllowHigher*/ true);
404 
405   Address RealAddr = Addr;
406   Address ImagAddr = RealAddr;
407   if (CGF.CGM.getDataLayout().isBigEndian()) {
408     RealAddr =
409         CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, SlotSize - EltSize);
410     ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(ImagAddr,
411                                                       2 * SlotSize - EltSize);
412   } else {
413     ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, SlotSize);
414   }
415 
416   llvm::Type *EltTy = CGF.ConvertTypeForMem(CTy->getElementType());
417   RealAddr = CGF.Builder.CreateElementBitCast(RealAddr, EltTy);
418   ImagAddr = CGF.Builder.CreateElementBitCast(ImagAddr, EltTy);
419   llvm::Value *Real = CGF.Builder.CreateLoad(RealAddr, ".vareal");
420   llvm::Value *Imag = CGF.Builder.CreateLoad(ImagAddr, ".vaimag");
421 
422   Address Temp = CGF.CreateMemTemp(Ty, "vacplx");
423   CGF.EmitStoreOfComplex({Real, Imag}, CGF.MakeAddrLValue(Temp, Ty),
424                          /*init*/ true);
425   return Temp;
426 }
427 
428 static Address emitMergePHI(CodeGenFunction &CGF,
429                             Address Addr1, llvm::BasicBlock *Block1,
430                             Address Addr2, llvm::BasicBlock *Block2,
431                             const llvm::Twine &Name = "") {
432   assert(Addr1.getType() == Addr2.getType());
433   llvm::PHINode *PHI = CGF.Builder.CreatePHI(Addr1.getType(), 2, Name);
434   PHI->addIncoming(Addr1.getPointer(), Block1);
435   PHI->addIncoming(Addr2.getPointer(), Block2);
436   CharUnits Align = std::min(Addr1.getAlignment(), Addr2.getAlignment());
437   return Address(PHI, Addr1.getElementType(), Align);
438 }
439 
440 TargetCodeGenInfo::~TargetCodeGenInfo() = default;
441 
442 // If someone can figure out a general rule for this, that would be great.
443 // It's probably just doomed to be platform-dependent, though.
444 unsigned TargetCodeGenInfo::getSizeOfUnwindException() const {
445   // Verified for:
446   //   x86-64     FreeBSD, Linux, Darwin
447   //   x86-32     FreeBSD, Linux, Darwin
448   //   PowerPC    Linux, Darwin
449   //   ARM        Darwin (*not* EABI)
450   //   AArch64    Linux
451   return 32;
452 }
453 
454 bool TargetCodeGenInfo::isNoProtoCallVariadic(const CallArgList &args,
455                                      const FunctionNoProtoType *fnType) const {
456   // The following conventions are known to require this to be false:
457   //   x86_stdcall
458   //   MIPS
459   // For everything else, we just prefer false unless we opt out.
460   return false;
461 }
462 
463 void
464 TargetCodeGenInfo::getDependentLibraryOption(llvm::StringRef Lib,
465                                              llvm::SmallString<24> &Opt) const {
466   // This assumes the user is passing a library name like "rt" instead of a
467   // filename like "librt.a/so", and that they don't care whether it's static or
468   // dynamic.
469   Opt = "-l";
470   Opt += Lib;
471 }
472 
473 unsigned TargetCodeGenInfo::getOpenCLKernelCallingConv() const {
474   // OpenCL kernels are called via an explicit runtime API with arguments
475   // set with clSetKernelArg(), not as normal sub-functions.
476   // Return SPIR_KERNEL by default as the kernel calling convention to
477   // ensure the fingerprint is fixed such way that each OpenCL argument
478   // gets one matching argument in the produced kernel function argument
479   // list to enable feasible implementation of clSetKernelArg() with
480   // aggregates etc. In case we would use the default C calling conv here,
481   // clSetKernelArg() might break depending on the target-specific
482   // conventions; different targets might split structs passed as values
483   // to multiple function arguments etc.
484   return llvm::CallingConv::SPIR_KERNEL;
485 }
486 
487 llvm::Constant *TargetCodeGenInfo::getNullPointer(const CodeGen::CodeGenModule &CGM,
488     llvm::PointerType *T, QualType QT) const {
489   return llvm::ConstantPointerNull::get(T);
490 }
491 
492 LangAS TargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM,
493                                                    const VarDecl *D) const {
494   assert(!CGM.getLangOpts().OpenCL &&
495          !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) &&
496          "Address space agnostic languages only");
497   return D ? D->getType().getAddressSpace() : LangAS::Default;
498 }
499 
500 llvm::Value *TargetCodeGenInfo::performAddrSpaceCast(
501     CodeGen::CodeGenFunction &CGF, llvm::Value *Src, LangAS SrcAddr,
502     LangAS DestAddr, llvm::Type *DestTy, bool isNonNull) const {
503   // Since target may map different address spaces in AST to the same address
504   // space, an address space conversion may end up as a bitcast.
505   if (auto *C = dyn_cast<llvm::Constant>(Src))
506     return performAddrSpaceCast(CGF.CGM, C, SrcAddr, DestAddr, DestTy);
507   // Try to preserve the source's name to make IR more readable.
508   return CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
509       Src, DestTy, Src->hasName() ? Src->getName() + ".ascast" : "");
510 }
511 
512 llvm::Constant *
513 TargetCodeGenInfo::performAddrSpaceCast(CodeGenModule &CGM, llvm::Constant *Src,
514                                         LangAS SrcAddr, LangAS DestAddr,
515                                         llvm::Type *DestTy) const {
516   // Since target may map different address spaces in AST to the same address
517   // space, an address space conversion may end up as a bitcast.
518   return llvm::ConstantExpr::getPointerCast(Src, DestTy);
519 }
520 
521 llvm::SyncScope::ID
522 TargetCodeGenInfo::getLLVMSyncScopeID(const LangOptions &LangOpts,
523                                       SyncScope Scope,
524                                       llvm::AtomicOrdering Ordering,
525                                       llvm::LLVMContext &Ctx) const {
526   return Ctx.getOrInsertSyncScopeID(""); /* default sync scope */
527 }
528 
529 static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays);
530 
531 /// isEmptyField - Return true iff a the field is "empty", that is it
532 /// is an unnamed bit-field or an (array of) empty record(s).
533 static bool isEmptyField(ASTContext &Context, const FieldDecl *FD,
534                          bool AllowArrays) {
535   if (FD->isUnnamedBitfield())
536     return true;
537 
538   QualType FT = FD->getType();
539 
540   // Constant arrays of empty records count as empty, strip them off.
541   // Constant arrays of zero length always count as empty.
542   bool WasArray = false;
543   if (AllowArrays)
544     while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
545       if (AT->getSize() == 0)
546         return true;
547       FT = AT->getElementType();
548       // The [[no_unique_address]] special case below does not apply to
549       // arrays of C++ empty records, so we need to remember this fact.
550       WasArray = true;
551     }
552 
553   const RecordType *RT = FT->getAs<RecordType>();
554   if (!RT)
555     return false;
556 
557   // C++ record fields are never empty, at least in the Itanium ABI.
558   //
559   // FIXME: We should use a predicate for whether this behavior is true in the
560   // current ABI.
561   //
562   // The exception to the above rule are fields marked with the
563   // [[no_unique_address]] attribute (since C++20).  Those do count as empty
564   // according to the Itanium ABI.  The exception applies only to records,
565   // not arrays of records, so we must also check whether we stripped off an
566   // array type above.
567   if (isa<CXXRecordDecl>(RT->getDecl()) &&
568       (WasArray || !FD->hasAttr<NoUniqueAddressAttr>()))
569     return false;
570 
571   return isEmptyRecord(Context, FT, AllowArrays);
572 }
573 
574 /// isEmptyRecord - Return true iff a structure contains only empty
575 /// fields. Note that a structure with a flexible array member is not
576 /// considered empty.
577 static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) {
578   const RecordType *RT = T->getAs<RecordType>();
579   if (!RT)
580     return false;
581   const RecordDecl *RD = RT->getDecl();
582   if (RD->hasFlexibleArrayMember())
583     return false;
584 
585   // If this is a C++ record, check the bases first.
586   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
587     for (const auto &I : CXXRD->bases())
588       if (!isEmptyRecord(Context, I.getType(), true))
589         return false;
590 
591   for (const auto *I : RD->fields())
592     if (!isEmptyField(Context, I, AllowArrays))
593       return false;
594   return true;
595 }
596 
597 /// isSingleElementStruct - Determine if a structure is a "single
598 /// element struct", i.e. it has exactly one non-empty field or
599 /// exactly one field which is itself a single element
600 /// struct. Structures with flexible array members are never
601 /// considered single element structs.
602 ///
603 /// \return The field declaration for the single non-empty field, if
604 /// it exists.
605 static const Type *isSingleElementStruct(QualType T, ASTContext &Context) {
606   const RecordType *RT = T->getAs<RecordType>();
607   if (!RT)
608     return nullptr;
609 
610   const RecordDecl *RD = RT->getDecl();
611   if (RD->hasFlexibleArrayMember())
612     return nullptr;
613 
614   const Type *Found = nullptr;
615 
616   // If this is a C++ record, check the bases first.
617   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
618     for (const auto &I : CXXRD->bases()) {
619       // Ignore empty records.
620       if (isEmptyRecord(Context, I.getType(), true))
621         continue;
622 
623       // If we already found an element then this isn't a single-element struct.
624       if (Found)
625         return nullptr;
626 
627       // If this is non-empty and not a single element struct, the composite
628       // cannot be a single element struct.
629       Found = isSingleElementStruct(I.getType(), Context);
630       if (!Found)
631         return nullptr;
632     }
633   }
634 
635   // Check for single element.
636   for (const auto *FD : RD->fields()) {
637     QualType FT = FD->getType();
638 
639     // Ignore empty fields.
640     if (isEmptyField(Context, FD, true))
641       continue;
642 
643     // If we already found an element then this isn't a single-element
644     // struct.
645     if (Found)
646       return nullptr;
647 
648     // Treat single element arrays as the element.
649     while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
650       if (AT->getSize().getZExtValue() != 1)
651         break;
652       FT = AT->getElementType();
653     }
654 
655     if (!isAggregateTypeForABI(FT)) {
656       Found = FT.getTypePtr();
657     } else {
658       Found = isSingleElementStruct(FT, Context);
659       if (!Found)
660         return nullptr;
661     }
662   }
663 
664   // We don't consider a struct a single-element struct if it has
665   // padding beyond the element type.
666   if (Found && Context.getTypeSize(Found) != Context.getTypeSize(T))
667     return nullptr;
668 
669   return Found;
670 }
671 
672 namespace {
673 Address EmitVAArgInstr(CodeGenFunction &CGF, Address VAListAddr, QualType Ty,
674                        const ABIArgInfo &AI) {
675   // This default implementation defers to the llvm backend's va_arg
676   // instruction. It can handle only passing arguments directly
677   // (typically only handled in the backend for primitive types), or
678   // aggregates passed indirectly by pointer (NOTE: if the "byval"
679   // flag has ABI impact in the callee, this implementation cannot
680   // work.)
681 
682   // Only a few cases are covered here at the moment -- those needed
683   // by the default abi.
684   llvm::Value *Val;
685 
686   if (AI.isIndirect()) {
687     assert(!AI.getPaddingType() &&
688            "Unexpected PaddingType seen in arginfo in generic VAArg emitter!");
689     assert(
690         !AI.getIndirectRealign() &&
691         "Unexpected IndirectRealign seen in arginfo in generic VAArg emitter!");
692 
693     auto TyInfo = CGF.getContext().getTypeInfoInChars(Ty);
694     CharUnits TyAlignForABI = TyInfo.Align;
695 
696     llvm::Type *ElementTy = CGF.ConvertTypeForMem(Ty);
697     llvm::Type *BaseTy = llvm::PointerType::getUnqual(ElementTy);
698     llvm::Value *Addr =
699         CGF.Builder.CreateVAArg(VAListAddr.getPointer(), BaseTy);
700     return Address(Addr, ElementTy, TyAlignForABI);
701   } else {
702     assert((AI.isDirect() || AI.isExtend()) &&
703            "Unexpected ArgInfo Kind in generic VAArg emitter!");
704 
705     assert(!AI.getInReg() &&
706            "Unexpected InReg seen in arginfo in generic VAArg emitter!");
707     assert(!AI.getPaddingType() &&
708            "Unexpected PaddingType seen in arginfo in generic VAArg emitter!");
709     assert(!AI.getDirectOffset() &&
710            "Unexpected DirectOffset seen in arginfo in generic VAArg emitter!");
711     assert(!AI.getCoerceToType() &&
712            "Unexpected CoerceToType seen in arginfo in generic VAArg emitter!");
713 
714     Address Temp = CGF.CreateMemTemp(Ty, "varet");
715     Val = CGF.Builder.CreateVAArg(VAListAddr.getPointer(),
716                                   CGF.ConvertTypeForMem(Ty));
717     CGF.Builder.CreateStore(Val, Temp);
718     return Temp;
719   }
720 }
721 
722 /// DefaultABIInfo - The default implementation for ABI specific
723 /// details. This implementation provides information which results in
724 /// self-consistent and sensible LLVM IR generation, but does not
725 /// conform to any particular ABI.
726 class DefaultABIInfo : public ABIInfo {
727 public:
728   DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
729 
730   ABIArgInfo classifyReturnType(QualType RetTy) const;
731   ABIArgInfo classifyArgumentType(QualType RetTy) const;
732 
733   void computeInfo(CGFunctionInfo &FI) const override {
734     if (!getCXXABI().classifyReturnType(FI))
735       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
736     for (auto &I : FI.arguments())
737       I.info = classifyArgumentType(I.type);
738   }
739 
740   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
741                     QualType Ty) const override {
742     return EmitVAArgInstr(CGF, VAListAddr, Ty, classifyArgumentType(Ty));
743   }
744 };
745 
746 class DefaultTargetCodeGenInfo : public TargetCodeGenInfo {
747 public:
748   DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
749       : TargetCodeGenInfo(std::make_unique<DefaultABIInfo>(CGT)) {}
750 };
751 
752 ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const {
753   Ty = useFirstFieldIfTransparentUnion(Ty);
754 
755   if (isAggregateTypeForABI(Ty)) {
756     // Records with non-trivial destructors/copy-constructors should not be
757     // passed by value.
758     if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
759       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
760 
761     return getNaturalAlignIndirect(Ty);
762   }
763 
764   // Treat an enum type as its underlying type.
765   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
766     Ty = EnumTy->getDecl()->getIntegerType();
767 
768   ASTContext &Context = getContext();
769   if (const auto *EIT = Ty->getAs<BitIntType>())
770     if (EIT->getNumBits() >
771         Context.getTypeSize(Context.getTargetInfo().hasInt128Type()
772                                 ? Context.Int128Ty
773                                 : Context.LongLongTy))
774       return getNaturalAlignIndirect(Ty);
775 
776   return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
777                                             : ABIArgInfo::getDirect());
778 }
779 
780 ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const {
781   if (RetTy->isVoidType())
782     return ABIArgInfo::getIgnore();
783 
784   if (isAggregateTypeForABI(RetTy))
785     return getNaturalAlignIndirect(RetTy);
786 
787   // Treat an enum type as its underlying type.
788   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
789     RetTy = EnumTy->getDecl()->getIntegerType();
790 
791   if (const auto *EIT = RetTy->getAs<BitIntType>())
792     if (EIT->getNumBits() >
793         getContext().getTypeSize(getContext().getTargetInfo().hasInt128Type()
794                                      ? getContext().Int128Ty
795                                      : getContext().LongLongTy))
796       return getNaturalAlignIndirect(RetTy);
797 
798   return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
799                                                : ABIArgInfo::getDirect());
800 }
801 
802 //===----------------------------------------------------------------------===//
803 // WebAssembly ABI Implementation
804 //
805 // This is a very simple ABI that relies a lot on DefaultABIInfo.
806 //===----------------------------------------------------------------------===//
807 
808 class WebAssemblyABIInfo final : public SwiftABIInfo {
809 public:
810   enum ABIKind {
811     MVP = 0,
812     ExperimentalMV = 1,
813   };
814 
815 private:
816   DefaultABIInfo defaultInfo;
817   ABIKind Kind;
818 
819 public:
820   explicit WebAssemblyABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind)
821       : SwiftABIInfo(CGT), defaultInfo(CGT), Kind(Kind) {}
822 
823 private:
824   ABIArgInfo classifyReturnType(QualType RetTy) const;
825   ABIArgInfo classifyArgumentType(QualType Ty) const;
826 
827   // DefaultABIInfo's classifyReturnType and classifyArgumentType are
828   // non-virtual, but computeInfo and EmitVAArg are virtual, so we
829   // overload them.
830   void computeInfo(CGFunctionInfo &FI) const override {
831     if (!getCXXABI().classifyReturnType(FI))
832       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
833     for (auto &Arg : FI.arguments())
834       Arg.info = classifyArgumentType(Arg.type);
835   }
836 
837   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
838                     QualType Ty) const override;
839 
840   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
841                                     bool asReturnValue) const override {
842     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
843   }
844 
845   bool isSwiftErrorInRegister() const override {
846     return false;
847   }
848 };
849 
850 class WebAssemblyTargetCodeGenInfo final : public TargetCodeGenInfo {
851 public:
852   explicit WebAssemblyTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
853                                         WebAssemblyABIInfo::ABIKind K)
854       : TargetCodeGenInfo(std::make_unique<WebAssemblyABIInfo>(CGT, K)) {}
855 
856   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
857                            CodeGen::CodeGenModule &CGM) const override {
858     TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
859     if (const auto *FD = dyn_cast_or_null<FunctionDecl>(D)) {
860       if (const auto *Attr = FD->getAttr<WebAssemblyImportModuleAttr>()) {
861         llvm::Function *Fn = cast<llvm::Function>(GV);
862         llvm::AttrBuilder B(GV->getContext());
863         B.addAttribute("wasm-import-module", Attr->getImportModule());
864         Fn->addFnAttrs(B);
865       }
866       if (const auto *Attr = FD->getAttr<WebAssemblyImportNameAttr>()) {
867         llvm::Function *Fn = cast<llvm::Function>(GV);
868         llvm::AttrBuilder B(GV->getContext());
869         B.addAttribute("wasm-import-name", Attr->getImportName());
870         Fn->addFnAttrs(B);
871       }
872       if (const auto *Attr = FD->getAttr<WebAssemblyExportNameAttr>()) {
873         llvm::Function *Fn = cast<llvm::Function>(GV);
874         llvm::AttrBuilder B(GV->getContext());
875         B.addAttribute("wasm-export-name", Attr->getExportName());
876         Fn->addFnAttrs(B);
877       }
878     }
879 
880     if (auto *FD = dyn_cast_or_null<FunctionDecl>(D)) {
881       llvm::Function *Fn = cast<llvm::Function>(GV);
882       if (!FD->doesThisDeclarationHaveABody() && !FD->hasPrototype())
883         Fn->addFnAttr("no-prototype");
884     }
885   }
886 };
887 
888 /// Classify argument of given type \p Ty.
889 ABIArgInfo WebAssemblyABIInfo::classifyArgumentType(QualType Ty) const {
890   Ty = useFirstFieldIfTransparentUnion(Ty);
891 
892   if (isAggregateTypeForABI(Ty)) {
893     // Records with non-trivial destructors/copy-constructors should not be
894     // passed by value.
895     if (auto RAA = getRecordArgABI(Ty, getCXXABI()))
896       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
897     // Ignore empty structs/unions.
898     if (isEmptyRecord(getContext(), Ty, true))
899       return ABIArgInfo::getIgnore();
900     // Lower single-element structs to just pass a regular value. TODO: We
901     // could do reasonable-size multiple-element structs too, using getExpand(),
902     // though watch out for things like bitfields.
903     if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
904       return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
905     // For the experimental multivalue ABI, fully expand all other aggregates
906     if (Kind == ABIKind::ExperimentalMV) {
907       const RecordType *RT = Ty->getAs<RecordType>();
908       assert(RT);
909       bool HasBitField = false;
910       for (auto *Field : RT->getDecl()->fields()) {
911         if (Field->isBitField()) {
912           HasBitField = true;
913           break;
914         }
915       }
916       if (!HasBitField)
917         return ABIArgInfo::getExpand();
918     }
919   }
920 
921   // Otherwise just do the default thing.
922   return defaultInfo.classifyArgumentType(Ty);
923 }
924 
925 ABIArgInfo WebAssemblyABIInfo::classifyReturnType(QualType RetTy) const {
926   if (isAggregateTypeForABI(RetTy)) {
927     // Records with non-trivial destructors/copy-constructors should not be
928     // returned by value.
929     if (!getRecordArgABI(RetTy, getCXXABI())) {
930       // Ignore empty structs/unions.
931       if (isEmptyRecord(getContext(), RetTy, true))
932         return ABIArgInfo::getIgnore();
933       // Lower single-element structs to just return a regular value. TODO: We
934       // could do reasonable-size multiple-element structs too, using
935       // ABIArgInfo::getDirect().
936       if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
937         return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
938       // For the experimental multivalue ABI, return all other aggregates
939       if (Kind == ABIKind::ExperimentalMV)
940         return ABIArgInfo::getDirect();
941     }
942   }
943 
944   // Otherwise just do the default thing.
945   return defaultInfo.classifyReturnType(RetTy);
946 }
947 
948 Address WebAssemblyABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
949                                       QualType Ty) const {
950   bool IsIndirect = isAggregateTypeForABI(Ty) &&
951                     !isEmptyRecord(getContext(), Ty, true) &&
952                     !isSingleElementStruct(Ty, getContext());
953   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
954                           getContext().getTypeInfoInChars(Ty),
955                           CharUnits::fromQuantity(4),
956                           /*AllowHigherAlign=*/true);
957 }
958 
959 //===----------------------------------------------------------------------===//
960 // le32/PNaCl bitcode ABI Implementation
961 //
962 // This is a simplified version of the x86_32 ABI.  Arguments and return values
963 // are always passed on the stack.
964 //===----------------------------------------------------------------------===//
965 
966 class PNaClABIInfo : public ABIInfo {
967  public:
968   PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
969 
970   ABIArgInfo classifyReturnType(QualType RetTy) const;
971   ABIArgInfo classifyArgumentType(QualType RetTy) const;
972 
973   void computeInfo(CGFunctionInfo &FI) const override;
974   Address EmitVAArg(CodeGenFunction &CGF,
975                     Address VAListAddr, QualType Ty) const override;
976 };
977 
978 class PNaClTargetCodeGenInfo : public TargetCodeGenInfo {
979  public:
980    PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
981        : TargetCodeGenInfo(std::make_unique<PNaClABIInfo>(CGT)) {}
982 };
983 
984 void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const {
985   if (!getCXXABI().classifyReturnType(FI))
986     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
987 
988   for (auto &I : FI.arguments())
989     I.info = classifyArgumentType(I.type);
990 }
991 
992 Address PNaClABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
993                                 QualType Ty) const {
994   // The PNaCL ABI is a bit odd, in that varargs don't use normal
995   // function classification. Structs get passed directly for varargs
996   // functions, through a rewriting transform in
997   // pnacl-llvm/lib/Transforms/NaCl/ExpandVarArgs.cpp, which allows
998   // this target to actually support a va_arg instructions with an
999   // aggregate type, unlike other targets.
1000   return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
1001 }
1002 
1003 /// Classify argument of given type \p Ty.
1004 ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const {
1005   if (isAggregateTypeForABI(Ty)) {
1006     if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
1007       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
1008     return getNaturalAlignIndirect(Ty);
1009   } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
1010     // Treat an enum type as its underlying type.
1011     Ty = EnumTy->getDecl()->getIntegerType();
1012   } else if (Ty->isFloatingType()) {
1013     // Floating-point types don't go inreg.
1014     return ABIArgInfo::getDirect();
1015   } else if (const auto *EIT = Ty->getAs<BitIntType>()) {
1016     // Treat bit-precise integers as integers if <= 64, otherwise pass
1017     // indirectly.
1018     if (EIT->getNumBits() > 64)
1019       return getNaturalAlignIndirect(Ty);
1020     return ABIArgInfo::getDirect();
1021   }
1022 
1023   return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
1024                                             : ABIArgInfo::getDirect());
1025 }
1026 
1027 ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const {
1028   if (RetTy->isVoidType())
1029     return ABIArgInfo::getIgnore();
1030 
1031   // In the PNaCl ABI we always return records/structures on the stack.
1032   if (isAggregateTypeForABI(RetTy))
1033     return getNaturalAlignIndirect(RetTy);
1034 
1035   // Treat bit-precise integers as integers if <= 64, otherwise pass indirectly.
1036   if (const auto *EIT = RetTy->getAs<BitIntType>()) {
1037     if (EIT->getNumBits() > 64)
1038       return getNaturalAlignIndirect(RetTy);
1039     return ABIArgInfo::getDirect();
1040   }
1041 
1042   // Treat an enum type as its underlying type.
1043   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
1044     RetTy = EnumTy->getDecl()->getIntegerType();
1045 
1046   return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
1047                                                : ABIArgInfo::getDirect());
1048 }
1049 
1050 /// IsX86_MMXType - Return true if this is an MMX type.
1051 bool IsX86_MMXType(llvm::Type *IRType) {
1052   // Return true if the type is an MMX type <2 x i32>, <4 x i16>, or <8 x i8>.
1053   return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 &&
1054     cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() &&
1055     IRType->getScalarSizeInBits() != 64;
1056 }
1057 
1058 static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
1059                                           StringRef Constraint,
1060                                           llvm::Type* Ty) {
1061   bool IsMMXCons = llvm::StringSwitch<bool>(Constraint)
1062                      .Cases("y", "&y", "^Ym", true)
1063                      .Default(false);
1064   if (IsMMXCons && Ty->isVectorTy()) {
1065     if (cast<llvm::VectorType>(Ty)->getPrimitiveSizeInBits().getFixedSize() !=
1066         64) {
1067       // Invalid MMX constraint
1068       return nullptr;
1069     }
1070 
1071     return llvm::Type::getX86_MMXTy(CGF.getLLVMContext());
1072   }
1073 
1074   // No operation needed
1075   return Ty;
1076 }
1077 
1078 /// Returns true if this type can be passed in SSE registers with the
1079 /// X86_VectorCall calling convention. Shared between x86_32 and x86_64.
1080 static bool isX86VectorTypeForVectorCall(ASTContext &Context, QualType Ty) {
1081   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
1082     if (BT->isFloatingPoint() && BT->getKind() != BuiltinType::Half) {
1083       if (BT->getKind() == BuiltinType::LongDouble) {
1084         if (&Context.getTargetInfo().getLongDoubleFormat() ==
1085             &llvm::APFloat::x87DoubleExtended())
1086           return false;
1087       }
1088       return true;
1089     }
1090   } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
1091     // vectorcall can pass XMM, YMM, and ZMM vectors. We don't pass SSE1 MMX
1092     // registers specially.
1093     unsigned VecSize = Context.getTypeSize(VT);
1094     if (VecSize == 128 || VecSize == 256 || VecSize == 512)
1095       return true;
1096   }
1097   return false;
1098 }
1099 
1100 /// Returns true if this aggregate is small enough to be passed in SSE registers
1101 /// in the X86_VectorCall calling convention. Shared between x86_32 and x86_64.
1102 static bool isX86VectorCallAggregateSmallEnough(uint64_t NumMembers) {
1103   return NumMembers <= 4;
1104 }
1105 
1106 /// Returns a Homogeneous Vector Aggregate ABIArgInfo, used in X86.
1107 static ABIArgInfo getDirectX86Hva(llvm::Type* T = nullptr) {
1108   auto AI = ABIArgInfo::getDirect(T);
1109   AI.setInReg(true);
1110   AI.setCanBeFlattened(false);
1111   return AI;
1112 }
1113 
1114 //===----------------------------------------------------------------------===//
1115 // X86-32 ABI Implementation
1116 //===----------------------------------------------------------------------===//
1117 
1118 /// Similar to llvm::CCState, but for Clang.
1119 struct CCState {
1120   CCState(CGFunctionInfo &FI)
1121       : IsPreassigned(FI.arg_size()), CC(FI.getCallingConvention()) {}
1122 
1123   llvm::SmallBitVector IsPreassigned;
1124   unsigned CC = CallingConv::CC_C;
1125   unsigned FreeRegs = 0;
1126   unsigned FreeSSERegs = 0;
1127 };
1128 
1129 /// X86_32ABIInfo - The X86-32 ABI information.
1130 class X86_32ABIInfo : public SwiftABIInfo {
1131   enum Class {
1132     Integer,
1133     Float
1134   };
1135 
1136   static const unsigned MinABIStackAlignInBytes = 4;
1137 
1138   bool IsDarwinVectorABI;
1139   bool IsRetSmallStructInRegABI;
1140   bool IsWin32StructABI;
1141   bool IsSoftFloatABI;
1142   bool IsMCUABI;
1143   bool IsLinuxABI;
1144   unsigned DefaultNumRegisterParameters;
1145 
1146   static bool isRegisterSize(unsigned Size) {
1147     return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
1148   }
1149 
1150   bool isHomogeneousAggregateBaseType(QualType Ty) const override {
1151     // FIXME: Assumes vectorcall is in use.
1152     return isX86VectorTypeForVectorCall(getContext(), Ty);
1153   }
1154 
1155   bool isHomogeneousAggregateSmallEnough(const Type *Ty,
1156                                          uint64_t NumMembers) const override {
1157     // FIXME: Assumes vectorcall is in use.
1158     return isX86VectorCallAggregateSmallEnough(NumMembers);
1159   }
1160 
1161   bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context) const;
1162 
1163   /// getIndirectResult - Give a source type \arg Ty, return a suitable result
1164   /// such that the argument will be passed in memory.
1165   ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
1166 
1167   ABIArgInfo getIndirectReturnResult(QualType Ty, CCState &State) const;
1168 
1169   /// Return the alignment to use for the given type on the stack.
1170   unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const;
1171 
1172   Class classify(QualType Ty) const;
1173   ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const;
1174   ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
1175 
1176   /// Updates the number of available free registers, returns
1177   /// true if any registers were allocated.
1178   bool updateFreeRegs(QualType Ty, CCState &State) const;
1179 
1180   bool shouldAggregateUseDirect(QualType Ty, CCState &State, bool &InReg,
1181                                 bool &NeedsPadding) const;
1182   bool shouldPrimitiveUseInReg(QualType Ty, CCState &State) const;
1183 
1184   bool canExpandIndirectArgument(QualType Ty) const;
1185 
1186   /// Rewrite the function info so that all memory arguments use
1187   /// inalloca.
1188   void rewriteWithInAlloca(CGFunctionInfo &FI) const;
1189 
1190   void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
1191                            CharUnits &StackOffset, ABIArgInfo &Info,
1192                            QualType Type) const;
1193   void runVectorCallFirstPass(CGFunctionInfo &FI, CCState &State) const;
1194 
1195 public:
1196 
1197   void computeInfo(CGFunctionInfo &FI) const override;
1198   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
1199                     QualType Ty) const override;
1200 
1201   X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
1202                 bool RetSmallStructInRegABI, bool Win32StructABI,
1203                 unsigned NumRegisterParameters, bool SoftFloatABI)
1204     : SwiftABIInfo(CGT), IsDarwinVectorABI(DarwinVectorABI),
1205       IsRetSmallStructInRegABI(RetSmallStructInRegABI),
1206       IsWin32StructABI(Win32StructABI), IsSoftFloatABI(SoftFloatABI),
1207       IsMCUABI(CGT.getTarget().getTriple().isOSIAMCU()),
1208       IsLinuxABI(CGT.getTarget().getTriple().isOSLinux() ||
1209                  CGT.getTarget().getTriple().isOSCygMing()),
1210       DefaultNumRegisterParameters(NumRegisterParameters) {}
1211 
1212   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
1213                                     bool asReturnValue) const override {
1214     // LLVM's x86-32 lowering currently only assigns up to three
1215     // integer registers and three fp registers.  Oddly, it'll use up to
1216     // four vector registers for vectors, but those can overlap with the
1217     // scalar registers.
1218     return occupiesMoreThan(CGT, scalars, /*total*/ 3);
1219   }
1220 
1221   bool isSwiftErrorInRegister() const override {
1222     // x86-32 lowering does not support passing swifterror in a register.
1223     return false;
1224   }
1225 };
1226 
1227 class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
1228 public:
1229   X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
1230                           bool RetSmallStructInRegABI, bool Win32StructABI,
1231                           unsigned NumRegisterParameters, bool SoftFloatABI)
1232       : TargetCodeGenInfo(std::make_unique<X86_32ABIInfo>(
1233             CGT, DarwinVectorABI, RetSmallStructInRegABI, Win32StructABI,
1234             NumRegisterParameters, SoftFloatABI)) {}
1235 
1236   static bool isStructReturnInRegABI(
1237       const llvm::Triple &Triple, const CodeGenOptions &Opts);
1238 
1239   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
1240                            CodeGen::CodeGenModule &CGM) const override;
1241 
1242   int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
1243     // Darwin uses different dwarf register numbers for EH.
1244     if (CGM.getTarget().getTriple().isOSDarwin()) return 5;
1245     return 4;
1246   }
1247 
1248   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
1249                                llvm::Value *Address) const override;
1250 
1251   llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
1252                                   StringRef Constraint,
1253                                   llvm::Type* Ty) const override {
1254     return X86AdjustInlineAsmType(CGF, Constraint, Ty);
1255   }
1256 
1257   void addReturnRegisterOutputs(CodeGenFunction &CGF, LValue ReturnValue,
1258                                 std::string &Constraints,
1259                                 std::vector<llvm::Type *> &ResultRegTypes,
1260                                 std::vector<llvm::Type *> &ResultTruncRegTypes,
1261                                 std::vector<LValue> &ResultRegDests,
1262                                 std::string &AsmString,
1263                                 unsigned NumOutputs) const override;
1264 
1265   llvm::Constant *
1266   getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
1267     unsigned Sig = (0xeb << 0) |  // jmp rel8
1268                    (0x06 << 8) |  //           .+0x08
1269                    ('v' << 16) |
1270                    ('2' << 24);
1271     return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
1272   }
1273 
1274   StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
1275     return "movl\t%ebp, %ebp"
1276            "\t\t// marker for objc_retainAutoreleaseReturnValue";
1277   }
1278 };
1279 
1280 }
1281 
1282 /// Rewrite input constraint references after adding some output constraints.
1283 /// In the case where there is one output and one input and we add one output,
1284 /// we need to replace all operand references greater than or equal to 1:
1285 ///     mov $0, $1
1286 ///     mov eax, $1
1287 /// The result will be:
1288 ///     mov $0, $2
1289 ///     mov eax, $2
1290 static void rewriteInputConstraintReferences(unsigned FirstIn,
1291                                              unsigned NumNewOuts,
1292                                              std::string &AsmString) {
1293   std::string Buf;
1294   llvm::raw_string_ostream OS(Buf);
1295   size_t Pos = 0;
1296   while (Pos < AsmString.size()) {
1297     size_t DollarStart = AsmString.find('$', Pos);
1298     if (DollarStart == std::string::npos)
1299       DollarStart = AsmString.size();
1300     size_t DollarEnd = AsmString.find_first_not_of('$', DollarStart);
1301     if (DollarEnd == std::string::npos)
1302       DollarEnd = AsmString.size();
1303     OS << StringRef(&AsmString[Pos], DollarEnd - Pos);
1304     Pos = DollarEnd;
1305     size_t NumDollars = DollarEnd - DollarStart;
1306     if (NumDollars % 2 != 0 && Pos < AsmString.size()) {
1307       // We have an operand reference.
1308       size_t DigitStart = Pos;
1309       if (AsmString[DigitStart] == '{') {
1310         OS << '{';
1311         ++DigitStart;
1312       }
1313       size_t DigitEnd = AsmString.find_first_not_of("0123456789", DigitStart);
1314       if (DigitEnd == std::string::npos)
1315         DigitEnd = AsmString.size();
1316       StringRef OperandStr(&AsmString[DigitStart], DigitEnd - DigitStart);
1317       unsigned OperandIndex;
1318       if (!OperandStr.getAsInteger(10, OperandIndex)) {
1319         if (OperandIndex >= FirstIn)
1320           OperandIndex += NumNewOuts;
1321         OS << OperandIndex;
1322       } else {
1323         OS << OperandStr;
1324       }
1325       Pos = DigitEnd;
1326     }
1327   }
1328   AsmString = std::move(OS.str());
1329 }
1330 
1331 /// Add output constraints for EAX:EDX because they are return registers.
1332 void X86_32TargetCodeGenInfo::addReturnRegisterOutputs(
1333     CodeGenFunction &CGF, LValue ReturnSlot, std::string &Constraints,
1334     std::vector<llvm::Type *> &ResultRegTypes,
1335     std::vector<llvm::Type *> &ResultTruncRegTypes,
1336     std::vector<LValue> &ResultRegDests, std::string &AsmString,
1337     unsigned NumOutputs) const {
1338   uint64_t RetWidth = CGF.getContext().getTypeSize(ReturnSlot.getType());
1339 
1340   // Use the EAX constraint if the width is 32 or smaller and EAX:EDX if it is
1341   // larger.
1342   if (!Constraints.empty())
1343     Constraints += ',';
1344   if (RetWidth <= 32) {
1345     Constraints += "={eax}";
1346     ResultRegTypes.push_back(CGF.Int32Ty);
1347   } else {
1348     // Use the 'A' constraint for EAX:EDX.
1349     Constraints += "=A";
1350     ResultRegTypes.push_back(CGF.Int64Ty);
1351   }
1352 
1353   // Truncate EAX or EAX:EDX to an integer of the appropriate size.
1354   llvm::Type *CoerceTy = llvm::IntegerType::get(CGF.getLLVMContext(), RetWidth);
1355   ResultTruncRegTypes.push_back(CoerceTy);
1356 
1357   // Coerce the integer by bitcasting the return slot pointer.
1358   ReturnSlot.setAddress(
1359       CGF.Builder.CreateElementBitCast(ReturnSlot.getAddress(CGF), CoerceTy));
1360   ResultRegDests.push_back(ReturnSlot);
1361 
1362   rewriteInputConstraintReferences(NumOutputs, 1, AsmString);
1363 }
1364 
1365 /// shouldReturnTypeInRegister - Determine if the given type should be
1366 /// returned in a register (for the Darwin and MCU ABI).
1367 bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
1368                                                ASTContext &Context) const {
1369   uint64_t Size = Context.getTypeSize(Ty);
1370 
1371   // For i386, type must be register sized.
1372   // For the MCU ABI, it only needs to be <= 8-byte
1373   if ((IsMCUABI && Size > 64) || (!IsMCUABI && !isRegisterSize(Size)))
1374    return false;
1375 
1376   if (Ty->isVectorType()) {
1377     // 64- and 128- bit vectors inside structures are not returned in
1378     // registers.
1379     if (Size == 64 || Size == 128)
1380       return false;
1381 
1382     return true;
1383   }
1384 
1385   // If this is a builtin, pointer, enum, complex type, member pointer, or
1386   // member function pointer it is ok.
1387   if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() ||
1388       Ty->isAnyComplexType() || Ty->isEnumeralType() ||
1389       Ty->isBlockPointerType() || Ty->isMemberPointerType())
1390     return true;
1391 
1392   // Arrays are treated like records.
1393   if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
1394     return shouldReturnTypeInRegister(AT->getElementType(), Context);
1395 
1396   // Otherwise, it must be a record type.
1397   const RecordType *RT = Ty->getAs<RecordType>();
1398   if (!RT) return false;
1399 
1400   // FIXME: Traverse bases here too.
1401 
1402   // Structure types are passed in register if all fields would be
1403   // passed in a register.
1404   for (const auto *FD : RT->getDecl()->fields()) {
1405     // Empty fields are ignored.
1406     if (isEmptyField(Context, FD, true))
1407       continue;
1408 
1409     // Check fields recursively.
1410     if (!shouldReturnTypeInRegister(FD->getType(), Context))
1411       return false;
1412   }
1413   return true;
1414 }
1415 
1416 static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
1417   // Treat complex types as the element type.
1418   if (const ComplexType *CTy = Ty->getAs<ComplexType>())
1419     Ty = CTy->getElementType();
1420 
1421   // Check for a type which we know has a simple scalar argument-passing
1422   // convention without any padding.  (We're specifically looking for 32
1423   // and 64-bit integer and integer-equivalents, float, and double.)
1424   if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() &&
1425       !Ty->isEnumeralType() && !Ty->isBlockPointerType())
1426     return false;
1427 
1428   uint64_t Size = Context.getTypeSize(Ty);
1429   return Size == 32 || Size == 64;
1430 }
1431 
1432 static bool addFieldSizes(ASTContext &Context, const RecordDecl *RD,
1433                           uint64_t &Size) {
1434   for (const auto *FD : RD->fields()) {
1435     // Scalar arguments on the stack get 4 byte alignment on x86. If the
1436     // argument is smaller than 32-bits, expanding the struct will create
1437     // alignment padding.
1438     if (!is32Or64BitBasicType(FD->getType(), Context))
1439       return false;
1440 
1441     // FIXME: Reject bit-fields wholesale; there are two problems, we don't know
1442     // how to expand them yet, and the predicate for telling if a bitfield still
1443     // counts as "basic" is more complicated than what we were doing previously.
1444     if (FD->isBitField())
1445       return false;
1446 
1447     Size += Context.getTypeSize(FD->getType());
1448   }
1449   return true;
1450 }
1451 
1452 static bool addBaseAndFieldSizes(ASTContext &Context, const CXXRecordDecl *RD,
1453                                  uint64_t &Size) {
1454   // Don't do this if there are any non-empty bases.
1455   for (const CXXBaseSpecifier &Base : RD->bases()) {
1456     if (!addBaseAndFieldSizes(Context, Base.getType()->getAsCXXRecordDecl(),
1457                               Size))
1458       return false;
1459   }
1460   if (!addFieldSizes(Context, RD, Size))
1461     return false;
1462   return true;
1463 }
1464 
1465 /// Test whether an argument type which is to be passed indirectly (on the
1466 /// stack) would have the equivalent layout if it was expanded into separate
1467 /// arguments. If so, we prefer to do the latter to avoid inhibiting
1468 /// optimizations.
1469 bool X86_32ABIInfo::canExpandIndirectArgument(QualType Ty) const {
1470   // We can only expand structure types.
1471   const RecordType *RT = Ty->getAs<RecordType>();
1472   if (!RT)
1473     return false;
1474   const RecordDecl *RD = RT->getDecl();
1475   uint64_t Size = 0;
1476   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
1477     if (!IsWin32StructABI) {
1478       // On non-Windows, we have to conservatively match our old bitcode
1479       // prototypes in order to be ABI-compatible at the bitcode level.
1480       if (!CXXRD->isCLike())
1481         return false;
1482     } else {
1483       // Don't do this for dynamic classes.
1484       if (CXXRD->isDynamicClass())
1485         return false;
1486     }
1487     if (!addBaseAndFieldSizes(getContext(), CXXRD, Size))
1488       return false;
1489   } else {
1490     if (!addFieldSizes(getContext(), RD, Size))
1491       return false;
1492   }
1493 
1494   // We can do this if there was no alignment padding.
1495   return Size == getContext().getTypeSize(Ty);
1496 }
1497 
1498 ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(QualType RetTy, CCState &State) const {
1499   // If the return value is indirect, then the hidden argument is consuming one
1500   // integer register.
1501   if (State.FreeRegs) {
1502     --State.FreeRegs;
1503     if (!IsMCUABI)
1504       return getNaturalAlignIndirectInReg(RetTy);
1505   }
1506   return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
1507 }
1508 
1509 ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy,
1510                                              CCState &State) const {
1511   if (RetTy->isVoidType())
1512     return ABIArgInfo::getIgnore();
1513 
1514   const Type *Base = nullptr;
1515   uint64_t NumElts = 0;
1516   if ((State.CC == llvm::CallingConv::X86_VectorCall ||
1517        State.CC == llvm::CallingConv::X86_RegCall) &&
1518       isHomogeneousAggregate(RetTy, Base, NumElts)) {
1519     // The LLVM struct type for such an aggregate should lower properly.
1520     return ABIArgInfo::getDirect();
1521   }
1522 
1523   if (const VectorType *VT = RetTy->getAs<VectorType>()) {
1524     // On Darwin, some vectors are returned in registers.
1525     if (IsDarwinVectorABI) {
1526       uint64_t Size = getContext().getTypeSize(RetTy);
1527 
1528       // 128-bit vectors are a special case; they are returned in
1529       // registers and we need to make sure to pick a type the LLVM
1530       // backend will like.
1531       if (Size == 128)
1532         return ABIArgInfo::getDirect(llvm::FixedVectorType::get(
1533             llvm::Type::getInt64Ty(getVMContext()), 2));
1534 
1535       // Always return in register if it fits in a general purpose
1536       // register, or if it is 64 bits and has a single element.
1537       if ((Size == 8 || Size == 16 || Size == 32) ||
1538           (Size == 64 && VT->getNumElements() == 1))
1539         return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
1540                                                             Size));
1541 
1542       return getIndirectReturnResult(RetTy, State);
1543     }
1544 
1545     return ABIArgInfo::getDirect();
1546   }
1547 
1548   if (isAggregateTypeForABI(RetTy)) {
1549     if (const RecordType *RT = RetTy->getAs<RecordType>()) {
1550       // Structures with flexible arrays are always indirect.
1551       if (RT->getDecl()->hasFlexibleArrayMember())
1552         return getIndirectReturnResult(RetTy, State);
1553     }
1554 
1555     // If specified, structs and unions are always indirect.
1556     if (!IsRetSmallStructInRegABI && !RetTy->isAnyComplexType())
1557       return getIndirectReturnResult(RetTy, State);
1558 
1559     // Ignore empty structs/unions.
1560     if (isEmptyRecord(getContext(), RetTy, true))
1561       return ABIArgInfo::getIgnore();
1562 
1563     // Return complex of _Float16 as <2 x half> so the backend will use xmm0.
1564     if (const ComplexType *CT = RetTy->getAs<ComplexType>()) {
1565       QualType ET = getContext().getCanonicalType(CT->getElementType());
1566       if (ET->isFloat16Type())
1567         return ABIArgInfo::getDirect(llvm::FixedVectorType::get(
1568             llvm::Type::getHalfTy(getVMContext()), 2));
1569     }
1570 
1571     // Small structures which are register sized are generally returned
1572     // in a register.
1573     if (shouldReturnTypeInRegister(RetTy, getContext())) {
1574       uint64_t Size = getContext().getTypeSize(RetTy);
1575 
1576       // As a special-case, if the struct is a "single-element" struct, and
1577       // the field is of type "float" or "double", return it in a
1578       // floating-point register. (MSVC does not apply this special case.)
1579       // We apply a similar transformation for pointer types to improve the
1580       // quality of the generated IR.
1581       if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
1582         if ((!IsWin32StructABI && SeltTy->isRealFloatingType())
1583             || SeltTy->hasPointerRepresentation())
1584           return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
1585 
1586       // FIXME: We should be able to narrow this integer in cases with dead
1587       // padding.
1588       return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
1589     }
1590 
1591     return getIndirectReturnResult(RetTy, State);
1592   }
1593 
1594   // Treat an enum type as its underlying type.
1595   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
1596     RetTy = EnumTy->getDecl()->getIntegerType();
1597 
1598   if (const auto *EIT = RetTy->getAs<BitIntType>())
1599     if (EIT->getNumBits() > 64)
1600       return getIndirectReturnResult(RetTy, State);
1601 
1602   return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
1603                                                : ABIArgInfo::getDirect());
1604 }
1605 
1606 static bool isSIMDVectorType(ASTContext &Context, QualType Ty) {
1607   return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128;
1608 }
1609 
1610 static bool isRecordWithSIMDVectorType(ASTContext &Context, QualType Ty) {
1611   const RecordType *RT = Ty->getAs<RecordType>();
1612   if (!RT)
1613     return false;
1614   const RecordDecl *RD = RT->getDecl();
1615 
1616   // If this is a C++ record, check the bases first.
1617   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
1618     for (const auto &I : CXXRD->bases())
1619       if (!isRecordWithSIMDVectorType(Context, I.getType()))
1620         return false;
1621 
1622   for (const auto *i : RD->fields()) {
1623     QualType FT = i->getType();
1624 
1625     if (isSIMDVectorType(Context, FT))
1626       return true;
1627 
1628     if (isRecordWithSIMDVectorType(Context, FT))
1629       return true;
1630   }
1631 
1632   return false;
1633 }
1634 
1635 unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
1636                                                  unsigned Align) const {
1637   // Otherwise, if the alignment is less than or equal to the minimum ABI
1638   // alignment, just use the default; the backend will handle this.
1639   if (Align <= MinABIStackAlignInBytes)
1640     return 0; // Use default alignment.
1641 
1642   if (IsLinuxABI) {
1643     // Exclude other System V OS (e.g Darwin, PS4 and FreeBSD) since we don't
1644     // want to spend any effort dealing with the ramifications of ABI breaks.
1645     //
1646     // If the vector type is __m128/__m256/__m512, return the default alignment.
1647     if (Ty->isVectorType() && (Align == 16 || Align == 32 || Align == 64))
1648       return Align;
1649   }
1650   // On non-Darwin, the stack type alignment is always 4.
1651   if (!IsDarwinVectorABI) {
1652     // Set explicit alignment, since we may need to realign the top.
1653     return MinABIStackAlignInBytes;
1654   }
1655 
1656   // Otherwise, if the type contains an SSE vector type, the alignment is 16.
1657   if (Align >= 16 && (isSIMDVectorType(getContext(), Ty) ||
1658                       isRecordWithSIMDVectorType(getContext(), Ty)))
1659     return 16;
1660 
1661   return MinABIStackAlignInBytes;
1662 }
1663 
1664 ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal,
1665                                             CCState &State) const {
1666   if (!ByVal) {
1667     if (State.FreeRegs) {
1668       --State.FreeRegs; // Non-byval indirects just use one pointer.
1669       if (!IsMCUABI)
1670         return getNaturalAlignIndirectInReg(Ty);
1671     }
1672     return getNaturalAlignIndirect(Ty, false);
1673   }
1674 
1675   // Compute the byval alignment.
1676   unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
1677   unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign);
1678   if (StackAlign == 0)
1679     return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true);
1680 
1681   // If the stack alignment is less than the type alignment, realign the
1682   // argument.
1683   bool Realign = TypeAlign > StackAlign;
1684   return ABIArgInfo::getIndirect(CharUnits::fromQuantity(StackAlign),
1685                                  /*ByVal=*/true, Realign);
1686 }
1687 
1688 X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const {
1689   const Type *T = isSingleElementStruct(Ty, getContext());
1690   if (!T)
1691     T = Ty.getTypePtr();
1692 
1693   if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
1694     BuiltinType::Kind K = BT->getKind();
1695     if (K == BuiltinType::Float || K == BuiltinType::Double)
1696       return Float;
1697   }
1698   return Integer;
1699 }
1700 
1701 bool X86_32ABIInfo::updateFreeRegs(QualType Ty, CCState &State) const {
1702   if (!IsSoftFloatABI) {
1703     Class C = classify(Ty);
1704     if (C == Float)
1705       return false;
1706   }
1707 
1708   unsigned Size = getContext().getTypeSize(Ty);
1709   unsigned SizeInRegs = (Size + 31) / 32;
1710 
1711   if (SizeInRegs == 0)
1712     return false;
1713 
1714   if (!IsMCUABI) {
1715     if (SizeInRegs > State.FreeRegs) {
1716       State.FreeRegs = 0;
1717       return false;
1718     }
1719   } else {
1720     // The MCU psABI allows passing parameters in-reg even if there are
1721     // earlier parameters that are passed on the stack. Also,
1722     // it does not allow passing >8-byte structs in-register,
1723     // even if there are 3 free registers available.
1724     if (SizeInRegs > State.FreeRegs || SizeInRegs > 2)
1725       return false;
1726   }
1727 
1728   State.FreeRegs -= SizeInRegs;
1729   return true;
1730 }
1731 
1732 bool X86_32ABIInfo::shouldAggregateUseDirect(QualType Ty, CCState &State,
1733                                              bool &InReg,
1734                                              bool &NeedsPadding) const {
1735   // On Windows, aggregates other than HFAs are never passed in registers, and
1736   // they do not consume register slots. Homogenous floating-point aggregates
1737   // (HFAs) have already been dealt with at this point.
1738   if (IsWin32StructABI && isAggregateTypeForABI(Ty))
1739     return false;
1740 
1741   NeedsPadding = false;
1742   InReg = !IsMCUABI;
1743 
1744   if (!updateFreeRegs(Ty, State))
1745     return false;
1746 
1747   if (IsMCUABI)
1748     return true;
1749 
1750   if (State.CC == llvm::CallingConv::X86_FastCall ||
1751       State.CC == llvm::CallingConv::X86_VectorCall ||
1752       State.CC == llvm::CallingConv::X86_RegCall) {
1753     if (getContext().getTypeSize(Ty) <= 32 && State.FreeRegs)
1754       NeedsPadding = true;
1755 
1756     return false;
1757   }
1758 
1759   return true;
1760 }
1761 
1762 bool X86_32ABIInfo::shouldPrimitiveUseInReg(QualType Ty, CCState &State) const {
1763   if (!updateFreeRegs(Ty, State))
1764     return false;
1765 
1766   if (IsMCUABI)
1767     return false;
1768 
1769   if (State.CC == llvm::CallingConv::X86_FastCall ||
1770       State.CC == llvm::CallingConv::X86_VectorCall ||
1771       State.CC == llvm::CallingConv::X86_RegCall) {
1772     if (getContext().getTypeSize(Ty) > 32)
1773       return false;
1774 
1775     return (Ty->isIntegralOrEnumerationType() || Ty->isPointerType() ||
1776         Ty->isReferenceType());
1777   }
1778 
1779   return true;
1780 }
1781 
1782 void X86_32ABIInfo::runVectorCallFirstPass(CGFunctionInfo &FI, CCState &State) const {
1783   // Vectorcall x86 works subtly different than in x64, so the format is
1784   // a bit different than the x64 version.  First, all vector types (not HVAs)
1785   // are assigned, with the first 6 ending up in the [XYZ]MM0-5 registers.
1786   // This differs from the x64 implementation, where the first 6 by INDEX get
1787   // registers.
1788   // In the second pass over the arguments, HVAs are passed in the remaining
1789   // vector registers if possible, or indirectly by address. The address will be
1790   // passed in ECX/EDX if available. Any other arguments are passed according to
1791   // the usual fastcall rules.
1792   MutableArrayRef<CGFunctionInfoArgInfo> Args = FI.arguments();
1793   for (int I = 0, E = Args.size(); I < E; ++I) {
1794     const Type *Base = nullptr;
1795     uint64_t NumElts = 0;
1796     const QualType &Ty = Args[I].type;
1797     if ((Ty->isVectorType() || Ty->isBuiltinType()) &&
1798         isHomogeneousAggregate(Ty, Base, NumElts)) {
1799       if (State.FreeSSERegs >= NumElts) {
1800         State.FreeSSERegs -= NumElts;
1801         Args[I].info = ABIArgInfo::getDirectInReg();
1802         State.IsPreassigned.set(I);
1803       }
1804     }
1805   }
1806 }
1807 
1808 ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
1809                                                CCState &State) const {
1810   // FIXME: Set alignment on indirect arguments.
1811   bool IsFastCall = State.CC == llvm::CallingConv::X86_FastCall;
1812   bool IsRegCall = State.CC == llvm::CallingConv::X86_RegCall;
1813   bool IsVectorCall = State.CC == llvm::CallingConv::X86_VectorCall;
1814 
1815   Ty = useFirstFieldIfTransparentUnion(Ty);
1816   TypeInfo TI = getContext().getTypeInfo(Ty);
1817 
1818   // Check with the C++ ABI first.
1819   const RecordType *RT = Ty->getAs<RecordType>();
1820   if (RT) {
1821     CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
1822     if (RAA == CGCXXABI::RAA_Indirect) {
1823       return getIndirectResult(Ty, false, State);
1824     } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
1825       // The field index doesn't matter, we'll fix it up later.
1826       return ABIArgInfo::getInAlloca(/*FieldIndex=*/0);
1827     }
1828   }
1829 
1830   // Regcall uses the concept of a homogenous vector aggregate, similar
1831   // to other targets.
1832   const Type *Base = nullptr;
1833   uint64_t NumElts = 0;
1834   if ((IsRegCall || IsVectorCall) &&
1835       isHomogeneousAggregate(Ty, Base, NumElts)) {
1836     if (State.FreeSSERegs >= NumElts) {
1837       State.FreeSSERegs -= NumElts;
1838 
1839       // Vectorcall passes HVAs directly and does not flatten them, but regcall
1840       // does.
1841       if (IsVectorCall)
1842         return getDirectX86Hva();
1843 
1844       if (Ty->isBuiltinType() || Ty->isVectorType())
1845         return ABIArgInfo::getDirect();
1846       return ABIArgInfo::getExpand();
1847     }
1848     return getIndirectResult(Ty, /*ByVal=*/false, State);
1849   }
1850 
1851   if (isAggregateTypeForABI(Ty)) {
1852     // Structures with flexible arrays are always indirect.
1853     // FIXME: This should not be byval!
1854     if (RT && RT->getDecl()->hasFlexibleArrayMember())
1855       return getIndirectResult(Ty, true, State);
1856 
1857     // Ignore empty structs/unions on non-Windows.
1858     if (!IsWin32StructABI && isEmptyRecord(getContext(), Ty, true))
1859       return ABIArgInfo::getIgnore();
1860 
1861     llvm::LLVMContext &LLVMContext = getVMContext();
1862     llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
1863     bool NeedsPadding = false;
1864     bool InReg;
1865     if (shouldAggregateUseDirect(Ty, State, InReg, NeedsPadding)) {
1866       unsigned SizeInRegs = (TI.Width + 31) / 32;
1867       SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32);
1868       llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
1869       if (InReg)
1870         return ABIArgInfo::getDirectInReg(Result);
1871       else
1872         return ABIArgInfo::getDirect(Result);
1873     }
1874     llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : nullptr;
1875 
1876     // Pass over-aligned aggregates on Windows indirectly. This behavior was
1877     // added in MSVC 2015.
1878     if (IsWin32StructABI && TI.isAlignRequired() && TI.Align > 32)
1879       return getIndirectResult(Ty, /*ByVal=*/false, State);
1880 
1881     // Expand small (<= 128-bit) record types when we know that the stack layout
1882     // of those arguments will match the struct. This is important because the
1883     // LLVM backend isn't smart enough to remove byval, which inhibits many
1884     // optimizations.
1885     // Don't do this for the MCU if there are still free integer registers
1886     // (see X86_64 ABI for full explanation).
1887     if (TI.Width <= 4 * 32 && (!IsMCUABI || State.FreeRegs == 0) &&
1888         canExpandIndirectArgument(Ty))
1889       return ABIArgInfo::getExpandWithPadding(
1890           IsFastCall || IsVectorCall || IsRegCall, PaddingType);
1891 
1892     return getIndirectResult(Ty, true, State);
1893   }
1894 
1895   if (const VectorType *VT = Ty->getAs<VectorType>()) {
1896     // On Windows, vectors are passed directly if registers are available, or
1897     // indirectly if not. This avoids the need to align argument memory. Pass
1898     // user-defined vector types larger than 512 bits indirectly for simplicity.
1899     if (IsWin32StructABI) {
1900       if (TI.Width <= 512 && State.FreeSSERegs > 0) {
1901         --State.FreeSSERegs;
1902         return ABIArgInfo::getDirectInReg();
1903       }
1904       return getIndirectResult(Ty, /*ByVal=*/false, State);
1905     }
1906 
1907     // On Darwin, some vectors are passed in memory, we handle this by passing
1908     // it as an i8/i16/i32/i64.
1909     if (IsDarwinVectorABI) {
1910       if ((TI.Width == 8 || TI.Width == 16 || TI.Width == 32) ||
1911           (TI.Width == 64 && VT->getNumElements() == 1))
1912         return ABIArgInfo::getDirect(
1913             llvm::IntegerType::get(getVMContext(), TI.Width));
1914     }
1915 
1916     if (IsX86_MMXType(CGT.ConvertType(Ty)))
1917       return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64));
1918 
1919     return ABIArgInfo::getDirect();
1920   }
1921 
1922 
1923   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1924     Ty = EnumTy->getDecl()->getIntegerType();
1925 
1926   bool InReg = shouldPrimitiveUseInReg(Ty, State);
1927 
1928   if (isPromotableIntegerTypeForABI(Ty)) {
1929     if (InReg)
1930       return ABIArgInfo::getExtendInReg(Ty);
1931     return ABIArgInfo::getExtend(Ty);
1932   }
1933 
1934   if (const auto *EIT = Ty->getAs<BitIntType>()) {
1935     if (EIT->getNumBits() <= 64) {
1936       if (InReg)
1937         return ABIArgInfo::getDirectInReg();
1938       return ABIArgInfo::getDirect();
1939     }
1940     return getIndirectResult(Ty, /*ByVal=*/false, State);
1941   }
1942 
1943   if (InReg)
1944     return ABIArgInfo::getDirectInReg();
1945   return ABIArgInfo::getDirect();
1946 }
1947 
1948 void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const {
1949   CCState State(FI);
1950   if (IsMCUABI)
1951     State.FreeRegs = 3;
1952   else if (State.CC == llvm::CallingConv::X86_FastCall) {
1953     State.FreeRegs = 2;
1954     State.FreeSSERegs = 3;
1955   } else if (State.CC == llvm::CallingConv::X86_VectorCall) {
1956     State.FreeRegs = 2;
1957     State.FreeSSERegs = 6;
1958   } else if (FI.getHasRegParm())
1959     State.FreeRegs = FI.getRegParm();
1960   else if (State.CC == llvm::CallingConv::X86_RegCall) {
1961     State.FreeRegs = 5;
1962     State.FreeSSERegs = 8;
1963   } else if (IsWin32StructABI) {
1964     // Since MSVC 2015, the first three SSE vectors have been passed in
1965     // registers. The rest are passed indirectly.
1966     State.FreeRegs = DefaultNumRegisterParameters;
1967     State.FreeSSERegs = 3;
1968   } else
1969     State.FreeRegs = DefaultNumRegisterParameters;
1970 
1971   if (!::classifyReturnType(getCXXABI(), FI, *this)) {
1972     FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), State);
1973   } else if (FI.getReturnInfo().isIndirect()) {
1974     // The C++ ABI is not aware of register usage, so we have to check if the
1975     // return value was sret and put it in a register ourselves if appropriate.
1976     if (State.FreeRegs) {
1977       --State.FreeRegs;  // The sret parameter consumes a register.
1978       if (!IsMCUABI)
1979         FI.getReturnInfo().setInReg(true);
1980     }
1981   }
1982 
1983   // The chain argument effectively gives us another free register.
1984   if (FI.isChainCall())
1985     ++State.FreeRegs;
1986 
1987   // For vectorcall, do a first pass over the arguments, assigning FP and vector
1988   // arguments to XMM registers as available.
1989   if (State.CC == llvm::CallingConv::X86_VectorCall)
1990     runVectorCallFirstPass(FI, State);
1991 
1992   bool UsedInAlloca = false;
1993   MutableArrayRef<CGFunctionInfoArgInfo> Args = FI.arguments();
1994   for (int I = 0, E = Args.size(); I < E; ++I) {
1995     // Skip arguments that have already been assigned.
1996     if (State.IsPreassigned.test(I))
1997       continue;
1998 
1999     Args[I].info = classifyArgumentType(Args[I].type, State);
2000     UsedInAlloca |= (Args[I].info.getKind() == ABIArgInfo::InAlloca);
2001   }
2002 
2003   // If we needed to use inalloca for any argument, do a second pass and rewrite
2004   // all the memory arguments to use inalloca.
2005   if (UsedInAlloca)
2006     rewriteWithInAlloca(FI);
2007 }
2008 
2009 void
2010 X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
2011                                    CharUnits &StackOffset, ABIArgInfo &Info,
2012                                    QualType Type) const {
2013   // Arguments are always 4-byte-aligned.
2014   CharUnits WordSize = CharUnits::fromQuantity(4);
2015   assert(StackOffset.isMultipleOf(WordSize) && "unaligned inalloca struct");
2016 
2017   // sret pointers and indirect things will require an extra pointer
2018   // indirection, unless they are byval. Most things are byval, and will not
2019   // require this indirection.
2020   bool IsIndirect = false;
2021   if (Info.isIndirect() && !Info.getIndirectByVal())
2022     IsIndirect = true;
2023   Info = ABIArgInfo::getInAlloca(FrameFields.size(), IsIndirect);
2024   llvm::Type *LLTy = CGT.ConvertTypeForMem(Type);
2025   if (IsIndirect)
2026     LLTy = LLTy->getPointerTo(0);
2027   FrameFields.push_back(LLTy);
2028   StackOffset += IsIndirect ? WordSize : getContext().getTypeSizeInChars(Type);
2029 
2030   // Insert padding bytes to respect alignment.
2031   CharUnits FieldEnd = StackOffset;
2032   StackOffset = FieldEnd.alignTo(WordSize);
2033   if (StackOffset != FieldEnd) {
2034     CharUnits NumBytes = StackOffset - FieldEnd;
2035     llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext());
2036     Ty = llvm::ArrayType::get(Ty, NumBytes.getQuantity());
2037     FrameFields.push_back(Ty);
2038   }
2039 }
2040 
2041 static bool isArgInAlloca(const ABIArgInfo &Info) {
2042   // Leave ignored and inreg arguments alone.
2043   switch (Info.getKind()) {
2044   case ABIArgInfo::InAlloca:
2045     return true;
2046   case ABIArgInfo::Ignore:
2047   case ABIArgInfo::IndirectAliased:
2048     return false;
2049   case ABIArgInfo::Indirect:
2050   case ABIArgInfo::Direct:
2051   case ABIArgInfo::Extend:
2052     return !Info.getInReg();
2053   case ABIArgInfo::Expand:
2054   case ABIArgInfo::CoerceAndExpand:
2055     // These are aggregate types which are never passed in registers when
2056     // inalloca is involved.
2057     return true;
2058   }
2059   llvm_unreachable("invalid enum");
2060 }
2061 
2062 void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const {
2063   assert(IsWin32StructABI && "inalloca only supported on win32");
2064 
2065   // Build a packed struct type for all of the arguments in memory.
2066   SmallVector<llvm::Type *, 6> FrameFields;
2067 
2068   // The stack alignment is always 4.
2069   CharUnits StackAlign = CharUnits::fromQuantity(4);
2070 
2071   CharUnits StackOffset;
2072   CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end();
2073 
2074   // Put 'this' into the struct before 'sret', if necessary.
2075   bool IsThisCall =
2076       FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall;
2077   ABIArgInfo &Ret = FI.getReturnInfo();
2078   if (Ret.isIndirect() && Ret.isSRetAfterThis() && !IsThisCall &&
2079       isArgInAlloca(I->info)) {
2080     addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
2081     ++I;
2082   }
2083 
2084   // Put the sret parameter into the inalloca struct if it's in memory.
2085   if (Ret.isIndirect() && !Ret.getInReg()) {
2086     addFieldToArgStruct(FrameFields, StackOffset, Ret, FI.getReturnType());
2087     // On Windows, the hidden sret parameter is always returned in eax.
2088     Ret.setInAllocaSRet(IsWin32StructABI);
2089   }
2090 
2091   // Skip the 'this' parameter in ecx.
2092   if (IsThisCall)
2093     ++I;
2094 
2095   // Put arguments passed in memory into the struct.
2096   for (; I != E; ++I) {
2097     if (isArgInAlloca(I->info))
2098       addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
2099   }
2100 
2101   FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields,
2102                                         /*isPacked=*/true),
2103                   StackAlign);
2104 }
2105 
2106 Address X86_32ABIInfo::EmitVAArg(CodeGenFunction &CGF,
2107                                  Address VAListAddr, QualType Ty) const {
2108 
2109   auto TypeInfo = getContext().getTypeInfoInChars(Ty);
2110 
2111   // x86-32 changes the alignment of certain arguments on the stack.
2112   //
2113   // Just messing with TypeInfo like this works because we never pass
2114   // anything indirectly.
2115   TypeInfo.Align = CharUnits::fromQuantity(
2116                 getTypeStackAlignInBytes(Ty, TypeInfo.Align.getQuantity()));
2117 
2118   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
2119                           TypeInfo, CharUnits::fromQuantity(4),
2120                           /*AllowHigherAlign*/ true);
2121 }
2122 
2123 bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
2124     const llvm::Triple &Triple, const CodeGenOptions &Opts) {
2125   assert(Triple.getArch() == llvm::Triple::x86);
2126 
2127   switch (Opts.getStructReturnConvention()) {
2128   case CodeGenOptions::SRCK_Default:
2129     break;
2130   case CodeGenOptions::SRCK_OnStack:  // -fpcc-struct-return
2131     return false;
2132   case CodeGenOptions::SRCK_InRegs:  // -freg-struct-return
2133     return true;
2134   }
2135 
2136   if (Triple.isOSDarwin() || Triple.isOSIAMCU())
2137     return true;
2138 
2139   switch (Triple.getOS()) {
2140   case llvm::Triple::DragonFly:
2141   case llvm::Triple::FreeBSD:
2142   case llvm::Triple::OpenBSD:
2143   case llvm::Triple::Win32:
2144     return true;
2145   default:
2146     return false;
2147   }
2148 }
2149 
2150 static void addX86InterruptAttrs(const FunctionDecl *FD, llvm::GlobalValue *GV,
2151                                  CodeGen::CodeGenModule &CGM) {
2152   if (!FD->hasAttr<AnyX86InterruptAttr>())
2153     return;
2154 
2155   llvm::Function *Fn = cast<llvm::Function>(GV);
2156   Fn->setCallingConv(llvm::CallingConv::X86_INTR);
2157   if (FD->getNumParams() == 0)
2158     return;
2159 
2160   auto PtrTy = cast<PointerType>(FD->getParamDecl(0)->getType());
2161   llvm::Type *ByValTy = CGM.getTypes().ConvertType(PtrTy->getPointeeType());
2162   llvm::Attribute NewAttr = llvm::Attribute::getWithByValType(
2163     Fn->getContext(), ByValTy);
2164   Fn->addParamAttr(0, NewAttr);
2165 }
2166 
2167 void X86_32TargetCodeGenInfo::setTargetAttributes(
2168     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
2169   if (GV->isDeclaration())
2170     return;
2171   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2172     if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
2173       llvm::Function *Fn = cast<llvm::Function>(GV);
2174       Fn->addFnAttr("stackrealign");
2175     }
2176 
2177     addX86InterruptAttrs(FD, GV, CGM);
2178   }
2179 }
2180 
2181 bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
2182                                                CodeGen::CodeGenFunction &CGF,
2183                                                llvm::Value *Address) const {
2184   CodeGen::CGBuilderTy &Builder = CGF.Builder;
2185 
2186   llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
2187 
2188   // 0-7 are the eight integer registers;  the order is different
2189   //   on Darwin (for EH), but the range is the same.
2190   // 8 is %eip.
2191   AssignToArrayRange(Builder, Address, Four8, 0, 8);
2192 
2193   if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
2194     // 12-16 are st(0..4).  Not sure why we stop at 4.
2195     // These have size 16, which is sizeof(long double) on
2196     // platforms with 8-byte alignment for that type.
2197     llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
2198     AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
2199 
2200   } else {
2201     // 9 is %eflags, which doesn't get a size on Darwin for some
2202     // reason.
2203     Builder.CreateAlignedStore(
2204         Four8, Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, Address, 9),
2205                                CharUnits::One());
2206 
2207     // 11-16 are st(0..5).  Not sure why we stop at 5.
2208     // These have size 12, which is sizeof(long double) on
2209     // platforms with 4-byte alignment for that type.
2210     llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
2211     AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
2212   }
2213 
2214   return false;
2215 }
2216 
2217 //===----------------------------------------------------------------------===//
2218 // X86-64 ABI Implementation
2219 //===----------------------------------------------------------------------===//
2220 
2221 
2222 namespace {
2223 /// The AVX ABI level for X86 targets.
2224 enum class X86AVXABILevel {
2225   None,
2226   AVX,
2227   AVX512
2228 };
2229 
2230 /// \p returns the size in bits of the largest (native) vector for \p AVXLevel.
2231 static unsigned getNativeVectorSizeForAVXABI(X86AVXABILevel AVXLevel) {
2232   switch (AVXLevel) {
2233   case X86AVXABILevel::AVX512:
2234     return 512;
2235   case X86AVXABILevel::AVX:
2236     return 256;
2237   case X86AVXABILevel::None:
2238     return 128;
2239   }
2240   llvm_unreachable("Unknown AVXLevel");
2241 }
2242 
2243 /// X86_64ABIInfo - The X86_64 ABI information.
2244 class X86_64ABIInfo : public SwiftABIInfo {
2245   enum Class {
2246     Integer = 0,
2247     SSE,
2248     SSEUp,
2249     X87,
2250     X87Up,
2251     ComplexX87,
2252     NoClass,
2253     Memory
2254   };
2255 
2256   /// merge - Implement the X86_64 ABI merging algorithm.
2257   ///
2258   /// Merge an accumulating classification \arg Accum with a field
2259   /// classification \arg Field.
2260   ///
2261   /// \param Accum - The accumulating classification. This should
2262   /// always be either NoClass or the result of a previous merge
2263   /// call. In addition, this should never be Memory (the caller
2264   /// should just return Memory for the aggregate).
2265   static Class merge(Class Accum, Class Field);
2266 
2267   /// postMerge - Implement the X86_64 ABI post merging algorithm.
2268   ///
2269   /// Post merger cleanup, reduces a malformed Hi and Lo pair to
2270   /// final MEMORY or SSE classes when necessary.
2271   ///
2272   /// \param AggregateSize - The size of the current aggregate in
2273   /// the classification process.
2274   ///
2275   /// \param Lo - The classification for the parts of the type
2276   /// residing in the low word of the containing object.
2277   ///
2278   /// \param Hi - The classification for the parts of the type
2279   /// residing in the higher words of the containing object.
2280   ///
2281   void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
2282 
2283   /// classify - Determine the x86_64 register classes in which the
2284   /// given type T should be passed.
2285   ///
2286   /// \param Lo - The classification for the parts of the type
2287   /// residing in the low word of the containing object.
2288   ///
2289   /// \param Hi - The classification for the parts of the type
2290   /// residing in the high word of the containing object.
2291   ///
2292   /// \param OffsetBase - The bit offset of this type in the
2293   /// containing object.  Some parameters are classified different
2294   /// depending on whether they straddle an eightbyte boundary.
2295   ///
2296   /// \param isNamedArg - Whether the argument in question is a "named"
2297   /// argument, as used in AMD64-ABI 3.5.7.
2298   ///
2299   /// If a word is unused its result will be NoClass; if a type should
2300   /// be passed in Memory then at least the classification of \arg Lo
2301   /// will be Memory.
2302   ///
2303   /// The \arg Lo class will be NoClass iff the argument is ignored.
2304   ///
2305   /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
2306   /// also be ComplexX87.
2307   void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi,
2308                 bool isNamedArg) const;
2309 
2310   llvm::Type *GetByteVectorType(QualType Ty) const;
2311   llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
2312                                  unsigned IROffset, QualType SourceTy,
2313                                  unsigned SourceOffset) const;
2314   llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
2315                                      unsigned IROffset, QualType SourceTy,
2316                                      unsigned SourceOffset) const;
2317 
2318   /// getIndirectResult - Give a source type \arg Ty, return a suitable result
2319   /// such that the argument will be returned in memory.
2320   ABIArgInfo getIndirectReturnResult(QualType Ty) const;
2321 
2322   /// getIndirectResult - Give a source type \arg Ty, return a suitable result
2323   /// such that the argument will be passed in memory.
2324   ///
2325   /// \param freeIntRegs - The number of free integer registers remaining
2326   /// available.
2327   ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
2328 
2329   ABIArgInfo classifyReturnType(QualType RetTy) const;
2330 
2331   ABIArgInfo classifyArgumentType(QualType Ty, unsigned freeIntRegs,
2332                                   unsigned &neededInt, unsigned &neededSSE,
2333                                   bool isNamedArg) const;
2334 
2335   ABIArgInfo classifyRegCallStructType(QualType Ty, unsigned &NeededInt,
2336                                        unsigned &NeededSSE) const;
2337 
2338   ABIArgInfo classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
2339                                            unsigned &NeededSSE) const;
2340 
2341   bool IsIllegalVectorType(QualType Ty) const;
2342 
2343   /// The 0.98 ABI revision clarified a lot of ambiguities,
2344   /// unfortunately in ways that were not always consistent with
2345   /// certain previous compilers.  In particular, platforms which
2346   /// required strict binary compatibility with older versions of GCC
2347   /// may need to exempt themselves.
2348   bool honorsRevision0_98() const {
2349     return !getTarget().getTriple().isOSDarwin();
2350   }
2351 
2352   /// GCC classifies <1 x long long> as SSE but some platform ABIs choose to
2353   /// classify it as INTEGER (for compatibility with older clang compilers).
2354   bool classifyIntegerMMXAsSSE() const {
2355     // Clang <= 3.8 did not do this.
2356     if (getContext().getLangOpts().getClangABICompat() <=
2357         LangOptions::ClangABI::Ver3_8)
2358       return false;
2359 
2360     const llvm::Triple &Triple = getTarget().getTriple();
2361     if (Triple.isOSDarwin() || Triple.getOS() == llvm::Triple::PS4)
2362       return false;
2363     if (Triple.isOSFreeBSD() && Triple.getOSMajorVersion() >= 10)
2364       return false;
2365     return true;
2366   }
2367 
2368   // GCC classifies vectors of __int128 as memory.
2369   bool passInt128VectorsInMem() const {
2370     // Clang <= 9.0 did not do this.
2371     if (getContext().getLangOpts().getClangABICompat() <=
2372         LangOptions::ClangABI::Ver9)
2373       return false;
2374 
2375     const llvm::Triple &T = getTarget().getTriple();
2376     return T.isOSLinux() || T.isOSNetBSD();
2377   }
2378 
2379   X86AVXABILevel AVXLevel;
2380   // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
2381   // 64-bit hardware.
2382   bool Has64BitPointers;
2383 
2384 public:
2385   X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) :
2386       SwiftABIInfo(CGT), AVXLevel(AVXLevel),
2387       Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {
2388   }
2389 
2390   bool isPassedUsingAVXType(QualType type) const {
2391     unsigned neededInt, neededSSE;
2392     // The freeIntRegs argument doesn't matter here.
2393     ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE,
2394                                            /*isNamedArg*/true);
2395     if (info.isDirect()) {
2396       llvm::Type *ty = info.getCoerceToType();
2397       if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
2398         return vectorTy->getPrimitiveSizeInBits().getFixedSize() > 128;
2399     }
2400     return false;
2401   }
2402 
2403   void computeInfo(CGFunctionInfo &FI) const override;
2404 
2405   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
2406                     QualType Ty) const override;
2407   Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
2408                       QualType Ty) const override;
2409 
2410   bool has64BitPointers() const {
2411     return Has64BitPointers;
2412   }
2413 
2414   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
2415                                     bool asReturnValue) const override {
2416     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
2417   }
2418   bool isSwiftErrorInRegister() const override {
2419     return true;
2420   }
2421 };
2422 
2423 /// WinX86_64ABIInfo - The Windows X86_64 ABI information.
2424 class WinX86_64ABIInfo : public SwiftABIInfo {
2425 public:
2426   WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
2427       : SwiftABIInfo(CGT), AVXLevel(AVXLevel),
2428         IsMingw64(getTarget().getTriple().isWindowsGNUEnvironment()) {}
2429 
2430   void computeInfo(CGFunctionInfo &FI) const override;
2431 
2432   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
2433                     QualType Ty) const override;
2434 
2435   bool isHomogeneousAggregateBaseType(QualType Ty) const override {
2436     // FIXME: Assumes vectorcall is in use.
2437     return isX86VectorTypeForVectorCall(getContext(), Ty);
2438   }
2439 
2440   bool isHomogeneousAggregateSmallEnough(const Type *Ty,
2441                                          uint64_t NumMembers) const override {
2442     // FIXME: Assumes vectorcall is in use.
2443     return isX86VectorCallAggregateSmallEnough(NumMembers);
2444   }
2445 
2446   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type *> scalars,
2447                                     bool asReturnValue) const override {
2448     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
2449   }
2450 
2451   bool isSwiftErrorInRegister() const override {
2452     return true;
2453   }
2454 
2455 private:
2456   ABIArgInfo classify(QualType Ty, unsigned &FreeSSERegs, bool IsReturnType,
2457                       bool IsVectorCall, bool IsRegCall) const;
2458   ABIArgInfo reclassifyHvaArgForVectorCall(QualType Ty, unsigned &FreeSSERegs,
2459                                            const ABIArgInfo &current) const;
2460 
2461   X86AVXABILevel AVXLevel;
2462 
2463   bool IsMingw64;
2464 };
2465 
2466 class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2467 public:
2468   X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
2469       : TargetCodeGenInfo(std::make_unique<X86_64ABIInfo>(CGT, AVXLevel)) {}
2470 
2471   const X86_64ABIInfo &getABIInfo() const {
2472     return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
2473   }
2474 
2475   /// Disable tail call on x86-64. The epilogue code before the tail jump blocks
2476   /// autoreleaseRV/retainRV and autoreleaseRV/unsafeClaimRV optimizations.
2477   bool markARCOptimizedReturnCallsAsNoTail() const override { return true; }
2478 
2479   int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
2480     return 7;
2481   }
2482 
2483   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2484                                llvm::Value *Address) const override {
2485     llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
2486 
2487     // 0-15 are the 16 integer registers.
2488     // 16 is %rip.
2489     AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
2490     return false;
2491   }
2492 
2493   llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
2494                                   StringRef Constraint,
2495                                   llvm::Type* Ty) const override {
2496     return X86AdjustInlineAsmType(CGF, Constraint, Ty);
2497   }
2498 
2499   bool isNoProtoCallVariadic(const CallArgList &args,
2500                              const FunctionNoProtoType *fnType) const override {
2501     // The default CC on x86-64 sets %al to the number of SSA
2502     // registers used, and GCC sets this when calling an unprototyped
2503     // function, so we override the default behavior.  However, don't do
2504     // that when AVX types are involved: the ABI explicitly states it is
2505     // undefined, and it doesn't work in practice because of how the ABI
2506     // defines varargs anyway.
2507     if (fnType->getCallConv() == CC_C) {
2508       bool HasAVXType = false;
2509       for (CallArgList::const_iterator
2510              it = args.begin(), ie = args.end(); it != ie; ++it) {
2511         if (getABIInfo().isPassedUsingAVXType(it->Ty)) {
2512           HasAVXType = true;
2513           break;
2514         }
2515       }
2516 
2517       if (!HasAVXType)
2518         return true;
2519     }
2520 
2521     return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
2522   }
2523 
2524   llvm::Constant *
2525   getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
2526     unsigned Sig = (0xeb << 0) | // jmp rel8
2527                    (0x06 << 8) | //           .+0x08
2528                    ('v' << 16) |
2529                    ('2' << 24);
2530     return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
2531   }
2532 
2533   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2534                            CodeGen::CodeGenModule &CGM) const override {
2535     if (GV->isDeclaration())
2536       return;
2537     if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2538       if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
2539         llvm::Function *Fn = cast<llvm::Function>(GV);
2540         Fn->addFnAttr("stackrealign");
2541       }
2542 
2543       addX86InterruptAttrs(FD, GV, CGM);
2544     }
2545   }
2546 
2547   void checkFunctionCallABI(CodeGenModule &CGM, SourceLocation CallLoc,
2548                             const FunctionDecl *Caller,
2549                             const FunctionDecl *Callee,
2550                             const CallArgList &Args) const override;
2551 };
2552 
2553 static void initFeatureMaps(const ASTContext &Ctx,
2554                             llvm::StringMap<bool> &CallerMap,
2555                             const FunctionDecl *Caller,
2556                             llvm::StringMap<bool> &CalleeMap,
2557                             const FunctionDecl *Callee) {
2558   if (CalleeMap.empty() && CallerMap.empty()) {
2559     // The caller is potentially nullptr in the case where the call isn't in a
2560     // function.  In this case, the getFunctionFeatureMap ensures we just get
2561     // the TU level setting (since it cannot be modified by 'target'..
2562     Ctx.getFunctionFeatureMap(CallerMap, Caller);
2563     Ctx.getFunctionFeatureMap(CalleeMap, Callee);
2564   }
2565 }
2566 
2567 static bool checkAVXParamFeature(DiagnosticsEngine &Diag,
2568                                  SourceLocation CallLoc,
2569                                  const llvm::StringMap<bool> &CallerMap,
2570                                  const llvm::StringMap<bool> &CalleeMap,
2571                                  QualType Ty, StringRef Feature,
2572                                  bool IsArgument) {
2573   bool CallerHasFeat = CallerMap.lookup(Feature);
2574   bool CalleeHasFeat = CalleeMap.lookup(Feature);
2575   if (!CallerHasFeat && !CalleeHasFeat)
2576     return Diag.Report(CallLoc, diag::warn_avx_calling_convention)
2577            << IsArgument << Ty << Feature;
2578 
2579   // Mixing calling conventions here is very clearly an error.
2580   if (!CallerHasFeat || !CalleeHasFeat)
2581     return Diag.Report(CallLoc, diag::err_avx_calling_convention)
2582            << IsArgument << Ty << Feature;
2583 
2584   // Else, both caller and callee have the required feature, so there is no need
2585   // to diagnose.
2586   return false;
2587 }
2588 
2589 static bool checkAVXParam(DiagnosticsEngine &Diag, ASTContext &Ctx,
2590                           SourceLocation CallLoc,
2591                           const llvm::StringMap<bool> &CallerMap,
2592                           const llvm::StringMap<bool> &CalleeMap, QualType Ty,
2593                           bool IsArgument) {
2594   uint64_t Size = Ctx.getTypeSize(Ty);
2595   if (Size > 256)
2596     return checkAVXParamFeature(Diag, CallLoc, CallerMap, CalleeMap, Ty,
2597                                 "avx512f", IsArgument);
2598 
2599   if (Size > 128)
2600     return checkAVXParamFeature(Diag, CallLoc, CallerMap, CalleeMap, Ty, "avx",
2601                                 IsArgument);
2602 
2603   return false;
2604 }
2605 
2606 void X86_64TargetCodeGenInfo::checkFunctionCallABI(
2607     CodeGenModule &CGM, SourceLocation CallLoc, const FunctionDecl *Caller,
2608     const FunctionDecl *Callee, const CallArgList &Args) const {
2609   llvm::StringMap<bool> CallerMap;
2610   llvm::StringMap<bool> CalleeMap;
2611   unsigned ArgIndex = 0;
2612 
2613   // We need to loop through the actual call arguments rather than the the
2614   // function's parameters, in case this variadic.
2615   for (const CallArg &Arg : Args) {
2616     // The "avx" feature changes how vectors >128 in size are passed. "avx512f"
2617     // additionally changes how vectors >256 in size are passed. Like GCC, we
2618     // warn when a function is called with an argument where this will change.
2619     // Unlike GCC, we also error when it is an obvious ABI mismatch, that is,
2620     // the caller and callee features are mismatched.
2621     // Unfortunately, we cannot do this diagnostic in SEMA, since the callee can
2622     // change its ABI with attribute-target after this call.
2623     if (Arg.getType()->isVectorType() &&
2624         CGM.getContext().getTypeSize(Arg.getType()) > 128) {
2625       initFeatureMaps(CGM.getContext(), CallerMap, Caller, CalleeMap, Callee);
2626       QualType Ty = Arg.getType();
2627       // The CallArg seems to have desugared the type already, so for clearer
2628       // diagnostics, replace it with the type in the FunctionDecl if possible.
2629       if (ArgIndex < Callee->getNumParams())
2630         Ty = Callee->getParamDecl(ArgIndex)->getType();
2631 
2632       if (checkAVXParam(CGM.getDiags(), CGM.getContext(), CallLoc, CallerMap,
2633                         CalleeMap, Ty, /*IsArgument*/ true))
2634         return;
2635     }
2636     ++ArgIndex;
2637   }
2638 
2639   // Check return always, as we don't have a good way of knowing in codegen
2640   // whether this value is used, tail-called, etc.
2641   if (Callee->getReturnType()->isVectorType() &&
2642       CGM.getContext().getTypeSize(Callee->getReturnType()) > 128) {
2643     initFeatureMaps(CGM.getContext(), CallerMap, Caller, CalleeMap, Callee);
2644     checkAVXParam(CGM.getDiags(), CGM.getContext(), CallLoc, CallerMap,
2645                   CalleeMap, Callee->getReturnType(),
2646                   /*IsArgument*/ false);
2647   }
2648 }
2649 
2650 static std::string qualifyWindowsLibrary(llvm::StringRef Lib) {
2651   // If the argument does not end in .lib, automatically add the suffix.
2652   // If the argument contains a space, enclose it in quotes.
2653   // This matches the behavior of MSVC.
2654   bool Quote = Lib.contains(' ');
2655   std::string ArgStr = Quote ? "\"" : "";
2656   ArgStr += Lib;
2657   if (!Lib.endswith_insensitive(".lib") && !Lib.endswith_insensitive(".a"))
2658     ArgStr += ".lib";
2659   ArgStr += Quote ? "\"" : "";
2660   return ArgStr;
2661 }
2662 
2663 class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
2664 public:
2665   WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
2666         bool DarwinVectorABI, bool RetSmallStructInRegABI, bool Win32StructABI,
2667         unsigned NumRegisterParameters)
2668     : X86_32TargetCodeGenInfo(CGT, DarwinVectorABI, RetSmallStructInRegABI,
2669         Win32StructABI, NumRegisterParameters, false) {}
2670 
2671   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2672                            CodeGen::CodeGenModule &CGM) const override;
2673 
2674   void getDependentLibraryOption(llvm::StringRef Lib,
2675                                  llvm::SmallString<24> &Opt) const override {
2676     Opt = "/DEFAULTLIB:";
2677     Opt += qualifyWindowsLibrary(Lib);
2678   }
2679 
2680   void getDetectMismatchOption(llvm::StringRef Name,
2681                                llvm::StringRef Value,
2682                                llvm::SmallString<32> &Opt) const override {
2683     Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
2684   }
2685 };
2686 
2687 static void addStackProbeTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2688                                           CodeGen::CodeGenModule &CGM) {
2689   if (llvm::Function *Fn = dyn_cast_or_null<llvm::Function>(GV)) {
2690 
2691     if (CGM.getCodeGenOpts().StackProbeSize != 4096)
2692       Fn->addFnAttr("stack-probe-size",
2693                     llvm::utostr(CGM.getCodeGenOpts().StackProbeSize));
2694     if (CGM.getCodeGenOpts().NoStackArgProbe)
2695       Fn->addFnAttr("no-stack-arg-probe");
2696   }
2697 }
2698 
2699 void WinX86_32TargetCodeGenInfo::setTargetAttributes(
2700     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
2701   X86_32TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
2702   if (GV->isDeclaration())
2703     return;
2704   addStackProbeTargetAttributes(D, GV, CGM);
2705 }
2706 
2707 class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2708 public:
2709   WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
2710                              X86AVXABILevel AVXLevel)
2711       : TargetCodeGenInfo(std::make_unique<WinX86_64ABIInfo>(CGT, AVXLevel)) {}
2712 
2713   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2714                            CodeGen::CodeGenModule &CGM) const override;
2715 
2716   int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
2717     return 7;
2718   }
2719 
2720   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2721                                llvm::Value *Address) const override {
2722     llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
2723 
2724     // 0-15 are the 16 integer registers.
2725     // 16 is %rip.
2726     AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
2727     return false;
2728   }
2729 
2730   void getDependentLibraryOption(llvm::StringRef Lib,
2731                                  llvm::SmallString<24> &Opt) const override {
2732     Opt = "/DEFAULTLIB:";
2733     Opt += qualifyWindowsLibrary(Lib);
2734   }
2735 
2736   void getDetectMismatchOption(llvm::StringRef Name,
2737                                llvm::StringRef Value,
2738                                llvm::SmallString<32> &Opt) const override {
2739     Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
2740   }
2741 };
2742 
2743 void WinX86_64TargetCodeGenInfo::setTargetAttributes(
2744     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
2745   TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
2746   if (GV->isDeclaration())
2747     return;
2748   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2749     if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
2750       llvm::Function *Fn = cast<llvm::Function>(GV);
2751       Fn->addFnAttr("stackrealign");
2752     }
2753 
2754     addX86InterruptAttrs(FD, GV, CGM);
2755   }
2756 
2757   addStackProbeTargetAttributes(D, GV, CGM);
2758 }
2759 }
2760 
2761 void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
2762                               Class &Hi) const {
2763   // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
2764   //
2765   // (a) If one of the classes is Memory, the whole argument is passed in
2766   //     memory.
2767   //
2768   // (b) If X87UP is not preceded by X87, the whole argument is passed in
2769   //     memory.
2770   //
2771   // (c) If the size of the aggregate exceeds two eightbytes and the first
2772   //     eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
2773   //     argument is passed in memory. NOTE: This is necessary to keep the
2774   //     ABI working for processors that don't support the __m256 type.
2775   //
2776   // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
2777   //
2778   // Some of these are enforced by the merging logic.  Others can arise
2779   // only with unions; for example:
2780   //   union { _Complex double; unsigned; }
2781   //
2782   // Note that clauses (b) and (c) were added in 0.98.
2783   //
2784   if (Hi == Memory)
2785     Lo = Memory;
2786   if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
2787     Lo = Memory;
2788   if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
2789     Lo = Memory;
2790   if (Hi == SSEUp && Lo != SSE)
2791     Hi = SSE;
2792 }
2793 
2794 X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
2795   // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
2796   // classified recursively so that always two fields are
2797   // considered. The resulting class is calculated according to
2798   // the classes of the fields in the eightbyte:
2799   //
2800   // (a) If both classes are equal, this is the resulting class.
2801   //
2802   // (b) If one of the classes is NO_CLASS, the resulting class is
2803   // the other class.
2804   //
2805   // (c) If one of the classes is MEMORY, the result is the MEMORY
2806   // class.
2807   //
2808   // (d) If one of the classes is INTEGER, the result is the
2809   // INTEGER.
2810   //
2811   // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
2812   // MEMORY is used as class.
2813   //
2814   // (f) Otherwise class SSE is used.
2815 
2816   // Accum should never be memory (we should have returned) or
2817   // ComplexX87 (because this cannot be passed in a structure).
2818   assert((Accum != Memory && Accum != ComplexX87) &&
2819          "Invalid accumulated classification during merge.");
2820   if (Accum == Field || Field == NoClass)
2821     return Accum;
2822   if (Field == Memory)
2823     return Memory;
2824   if (Accum == NoClass)
2825     return Field;
2826   if (Accum == Integer || Field == Integer)
2827     return Integer;
2828   if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
2829       Accum == X87 || Accum == X87Up)
2830     return Memory;
2831   return SSE;
2832 }
2833 
2834 void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
2835                              Class &Lo, Class &Hi, bool isNamedArg) const {
2836   // FIXME: This code can be simplified by introducing a simple value class for
2837   // Class pairs with appropriate constructor methods for the various
2838   // situations.
2839 
2840   // FIXME: Some of the split computations are wrong; unaligned vectors
2841   // shouldn't be passed in registers for example, so there is no chance they
2842   // can straddle an eightbyte. Verify & simplify.
2843 
2844   Lo = Hi = NoClass;
2845 
2846   Class &Current = OffsetBase < 64 ? Lo : Hi;
2847   Current = Memory;
2848 
2849   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
2850     BuiltinType::Kind k = BT->getKind();
2851 
2852     if (k == BuiltinType::Void) {
2853       Current = NoClass;
2854     } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
2855       Lo = Integer;
2856       Hi = Integer;
2857     } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
2858       Current = Integer;
2859     } else if (k == BuiltinType::Float || k == BuiltinType::Double ||
2860                k == BuiltinType::Float16) {
2861       Current = SSE;
2862     } else if (k == BuiltinType::LongDouble) {
2863       const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
2864       if (LDF == &llvm::APFloat::IEEEquad()) {
2865         Lo = SSE;
2866         Hi = SSEUp;
2867       } else if (LDF == &llvm::APFloat::x87DoubleExtended()) {
2868         Lo = X87;
2869         Hi = X87Up;
2870       } else if (LDF == &llvm::APFloat::IEEEdouble()) {
2871         Current = SSE;
2872       } else
2873         llvm_unreachable("unexpected long double representation!");
2874     }
2875     // FIXME: _Decimal32 and _Decimal64 are SSE.
2876     // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
2877     return;
2878   }
2879 
2880   if (const EnumType *ET = Ty->getAs<EnumType>()) {
2881     // Classify the underlying integer type.
2882     classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
2883     return;
2884   }
2885 
2886   if (Ty->hasPointerRepresentation()) {
2887     Current = Integer;
2888     return;
2889   }
2890 
2891   if (Ty->isMemberPointerType()) {
2892     if (Ty->isMemberFunctionPointerType()) {
2893       if (Has64BitPointers) {
2894         // If Has64BitPointers, this is an {i64, i64}, so classify both
2895         // Lo and Hi now.
2896         Lo = Hi = Integer;
2897       } else {
2898         // Otherwise, with 32-bit pointers, this is an {i32, i32}. If that
2899         // straddles an eightbyte boundary, Hi should be classified as well.
2900         uint64_t EB_FuncPtr = (OffsetBase) / 64;
2901         uint64_t EB_ThisAdj = (OffsetBase + 64 - 1) / 64;
2902         if (EB_FuncPtr != EB_ThisAdj) {
2903           Lo = Hi = Integer;
2904         } else {
2905           Current = Integer;
2906         }
2907       }
2908     } else {
2909       Current = Integer;
2910     }
2911     return;
2912   }
2913 
2914   if (const VectorType *VT = Ty->getAs<VectorType>()) {
2915     uint64_t Size = getContext().getTypeSize(VT);
2916     if (Size == 1 || Size == 8 || Size == 16 || Size == 32) {
2917       // gcc passes the following as integer:
2918       // 4 bytes - <4 x char>, <2 x short>, <1 x int>, <1 x float>
2919       // 2 bytes - <2 x char>, <1 x short>
2920       // 1 byte  - <1 x char>
2921       Current = Integer;
2922 
2923       // If this type crosses an eightbyte boundary, it should be
2924       // split.
2925       uint64_t EB_Lo = (OffsetBase) / 64;
2926       uint64_t EB_Hi = (OffsetBase + Size - 1) / 64;
2927       if (EB_Lo != EB_Hi)
2928         Hi = Lo;
2929     } else if (Size == 64) {
2930       QualType ElementType = VT->getElementType();
2931 
2932       // gcc passes <1 x double> in memory. :(
2933       if (ElementType->isSpecificBuiltinType(BuiltinType::Double))
2934         return;
2935 
2936       // gcc passes <1 x long long> as SSE but clang used to unconditionally
2937       // pass them as integer.  For platforms where clang is the de facto
2938       // platform compiler, we must continue to use integer.
2939       if (!classifyIntegerMMXAsSSE() &&
2940           (ElementType->isSpecificBuiltinType(BuiltinType::LongLong) ||
2941            ElementType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
2942            ElementType->isSpecificBuiltinType(BuiltinType::Long) ||
2943            ElementType->isSpecificBuiltinType(BuiltinType::ULong)))
2944         Current = Integer;
2945       else
2946         Current = SSE;
2947 
2948       // If this type crosses an eightbyte boundary, it should be
2949       // split.
2950       if (OffsetBase && OffsetBase != 64)
2951         Hi = Lo;
2952     } else if (Size == 128 ||
2953                (isNamedArg && Size <= getNativeVectorSizeForAVXABI(AVXLevel))) {
2954       QualType ElementType = VT->getElementType();
2955 
2956       // gcc passes 256 and 512 bit <X x __int128> vectors in memory. :(
2957       if (passInt128VectorsInMem() && Size != 128 &&
2958           (ElementType->isSpecificBuiltinType(BuiltinType::Int128) ||
2959            ElementType->isSpecificBuiltinType(BuiltinType::UInt128)))
2960         return;
2961 
2962       // Arguments of 256-bits are split into four eightbyte chunks. The
2963       // least significant one belongs to class SSE and all the others to class
2964       // SSEUP. The original Lo and Hi design considers that types can't be
2965       // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
2966       // This design isn't correct for 256-bits, but since there're no cases
2967       // where the upper parts would need to be inspected, avoid adding
2968       // complexity and just consider Hi to match the 64-256 part.
2969       //
2970       // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
2971       // registers if they are "named", i.e. not part of the "..." of a
2972       // variadic function.
2973       //
2974       // Similarly, per 3.2.3. of the AVX512 draft, 512-bits ("named") args are
2975       // split into eight eightbyte chunks, one SSE and seven SSEUP.
2976       Lo = SSE;
2977       Hi = SSEUp;
2978     }
2979     return;
2980   }
2981 
2982   if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
2983     QualType ET = getContext().getCanonicalType(CT->getElementType());
2984 
2985     uint64_t Size = getContext().getTypeSize(Ty);
2986     if (ET->isIntegralOrEnumerationType()) {
2987       if (Size <= 64)
2988         Current = Integer;
2989       else if (Size <= 128)
2990         Lo = Hi = Integer;
2991     } else if (ET->isFloat16Type() || ET == getContext().FloatTy) {
2992       Current = SSE;
2993     } else if (ET == getContext().DoubleTy) {
2994       Lo = Hi = SSE;
2995     } else if (ET == getContext().LongDoubleTy) {
2996       const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
2997       if (LDF == &llvm::APFloat::IEEEquad())
2998         Current = Memory;
2999       else if (LDF == &llvm::APFloat::x87DoubleExtended())
3000         Current = ComplexX87;
3001       else if (LDF == &llvm::APFloat::IEEEdouble())
3002         Lo = Hi = SSE;
3003       else
3004         llvm_unreachable("unexpected long double representation!");
3005     }
3006 
3007     // If this complex type crosses an eightbyte boundary then it
3008     // should be split.
3009     uint64_t EB_Real = (OffsetBase) / 64;
3010     uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
3011     if (Hi == NoClass && EB_Real != EB_Imag)
3012       Hi = Lo;
3013 
3014     return;
3015   }
3016 
3017   if (const auto *EITy = Ty->getAs<BitIntType>()) {
3018     if (EITy->getNumBits() <= 64)
3019       Current = Integer;
3020     else if (EITy->getNumBits() <= 128)
3021       Lo = Hi = Integer;
3022     // Larger values need to get passed in memory.
3023     return;
3024   }
3025 
3026   if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
3027     // Arrays are treated like structures.
3028 
3029     uint64_t Size = getContext().getTypeSize(Ty);
3030 
3031     // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
3032     // than eight eightbytes, ..., it has class MEMORY.
3033     if (Size > 512)
3034       return;
3035 
3036     // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
3037     // fields, it has class MEMORY.
3038     //
3039     // Only need to check alignment of array base.
3040     if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
3041       return;
3042 
3043     // Otherwise implement simplified merge. We could be smarter about
3044     // this, but it isn't worth it and would be harder to verify.
3045     Current = NoClass;
3046     uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
3047     uint64_t ArraySize = AT->getSize().getZExtValue();
3048 
3049     // The only case a 256-bit wide vector could be used is when the array
3050     // contains a single 256-bit element. Since Lo and Hi logic isn't extended
3051     // to work for sizes wider than 128, early check and fallback to memory.
3052     //
3053     if (Size > 128 &&
3054         (Size != EltSize || Size > getNativeVectorSizeForAVXABI(AVXLevel)))
3055       return;
3056 
3057     for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
3058       Class FieldLo, FieldHi;
3059       classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
3060       Lo = merge(Lo, FieldLo);
3061       Hi = merge(Hi, FieldHi);
3062       if (Lo == Memory || Hi == Memory)
3063         break;
3064     }
3065 
3066     postMerge(Size, Lo, Hi);
3067     assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
3068     return;
3069   }
3070 
3071   if (const RecordType *RT = Ty->getAs<RecordType>()) {
3072     uint64_t Size = getContext().getTypeSize(Ty);
3073 
3074     // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
3075     // than eight eightbytes, ..., it has class MEMORY.
3076     if (Size > 512)
3077       return;
3078 
3079     // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
3080     // copy constructor or a non-trivial destructor, it is passed by invisible
3081     // reference.
3082     if (getRecordArgABI(RT, getCXXABI()))
3083       return;
3084 
3085     const RecordDecl *RD = RT->getDecl();
3086 
3087     // Assume variable sized types are passed in memory.
3088     if (RD->hasFlexibleArrayMember())
3089       return;
3090 
3091     const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
3092 
3093     // Reset Lo class, this will be recomputed.
3094     Current = NoClass;
3095 
3096     // If this is a C++ record, classify the bases first.
3097     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3098       for (const auto &I : CXXRD->bases()) {
3099         assert(!I.isVirtual() && !I.getType()->isDependentType() &&
3100                "Unexpected base class!");
3101         const auto *Base =
3102             cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
3103 
3104         // Classify this field.
3105         //
3106         // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
3107         // single eightbyte, each is classified separately. Each eightbyte gets
3108         // initialized to class NO_CLASS.
3109         Class FieldLo, FieldHi;
3110         uint64_t Offset =
3111           OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
3112         classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg);
3113         Lo = merge(Lo, FieldLo);
3114         Hi = merge(Hi, FieldHi);
3115         if (Lo == Memory || Hi == Memory) {
3116           postMerge(Size, Lo, Hi);
3117           return;
3118         }
3119       }
3120     }
3121 
3122     // Classify the fields one at a time, merging the results.
3123     unsigned idx = 0;
3124     bool UseClang11Compat = getContext().getLangOpts().getClangABICompat() <=
3125                                 LangOptions::ClangABI::Ver11 ||
3126                             getContext().getTargetInfo().getTriple().isPS4();
3127     bool IsUnion = RT->isUnionType() && !UseClang11Compat;
3128 
3129     for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
3130            i != e; ++i, ++idx) {
3131       uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
3132       bool BitField = i->isBitField();
3133 
3134       // Ignore padding bit-fields.
3135       if (BitField && i->isUnnamedBitfield())
3136         continue;
3137 
3138       // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
3139       // eight eightbytes, or it contains unaligned fields, it has class MEMORY.
3140       //
3141       // The only case a 256-bit or a 512-bit wide vector could be used is when
3142       // the struct contains a single 256-bit or 512-bit element. Early check
3143       // and fallback to memory.
3144       //
3145       // FIXME: Extended the Lo and Hi logic properly to work for size wider
3146       // than 128.
3147       if (Size > 128 &&
3148           ((!IsUnion && Size != getContext().getTypeSize(i->getType())) ||
3149            Size > getNativeVectorSizeForAVXABI(AVXLevel))) {
3150         Lo = Memory;
3151         postMerge(Size, Lo, Hi);
3152         return;
3153       }
3154       // Note, skip this test for bit-fields, see below.
3155       if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
3156         Lo = Memory;
3157         postMerge(Size, Lo, Hi);
3158         return;
3159       }
3160 
3161       // Classify this field.
3162       //
3163       // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
3164       // exceeds a single eightbyte, each is classified
3165       // separately. Each eightbyte gets initialized to class
3166       // NO_CLASS.
3167       Class FieldLo, FieldHi;
3168 
3169       // Bit-fields require special handling, they do not force the
3170       // structure to be passed in memory even if unaligned, and
3171       // therefore they can straddle an eightbyte.
3172       if (BitField) {
3173         assert(!i->isUnnamedBitfield());
3174         uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
3175         uint64_t Size = i->getBitWidthValue(getContext());
3176 
3177         uint64_t EB_Lo = Offset / 64;
3178         uint64_t EB_Hi = (Offset + Size - 1) / 64;
3179 
3180         if (EB_Lo) {
3181           assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
3182           FieldLo = NoClass;
3183           FieldHi = Integer;
3184         } else {
3185           FieldLo = Integer;
3186           FieldHi = EB_Hi ? Integer : NoClass;
3187         }
3188       } else
3189         classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
3190       Lo = merge(Lo, FieldLo);
3191       Hi = merge(Hi, FieldHi);
3192       if (Lo == Memory || Hi == Memory)
3193         break;
3194     }
3195 
3196     postMerge(Size, Lo, Hi);
3197   }
3198 }
3199 
3200 ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
3201   // If this is a scalar LLVM value then assume LLVM will pass it in the right
3202   // place naturally.
3203   if (!isAggregateTypeForABI(Ty)) {
3204     // Treat an enum type as its underlying type.
3205     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3206       Ty = EnumTy->getDecl()->getIntegerType();
3207 
3208     if (Ty->isBitIntType())
3209       return getNaturalAlignIndirect(Ty);
3210 
3211     return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
3212                                               : ABIArgInfo::getDirect());
3213   }
3214 
3215   return getNaturalAlignIndirect(Ty);
3216 }
3217 
3218 bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
3219   if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
3220     uint64_t Size = getContext().getTypeSize(VecTy);
3221     unsigned LargestVector = getNativeVectorSizeForAVXABI(AVXLevel);
3222     if (Size <= 64 || Size > LargestVector)
3223       return true;
3224     QualType EltTy = VecTy->getElementType();
3225     if (passInt128VectorsInMem() &&
3226         (EltTy->isSpecificBuiltinType(BuiltinType::Int128) ||
3227          EltTy->isSpecificBuiltinType(BuiltinType::UInt128)))
3228       return true;
3229   }
3230 
3231   return false;
3232 }
3233 
3234 ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
3235                                             unsigned freeIntRegs) const {
3236   // If this is a scalar LLVM value then assume LLVM will pass it in the right
3237   // place naturally.
3238   //
3239   // This assumption is optimistic, as there could be free registers available
3240   // when we need to pass this argument in memory, and LLVM could try to pass
3241   // the argument in the free register. This does not seem to happen currently,
3242   // but this code would be much safer if we could mark the argument with
3243   // 'onstack'. See PR12193.
3244   if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty) &&
3245       !Ty->isBitIntType()) {
3246     // Treat an enum type as its underlying type.
3247     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3248       Ty = EnumTy->getDecl()->getIntegerType();
3249 
3250     return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
3251                                               : ABIArgInfo::getDirect());
3252   }
3253 
3254   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
3255     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
3256 
3257   // Compute the byval alignment. We specify the alignment of the byval in all
3258   // cases so that the mid-level optimizer knows the alignment of the byval.
3259   unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
3260 
3261   // Attempt to avoid passing indirect results using byval when possible. This
3262   // is important for good codegen.
3263   //
3264   // We do this by coercing the value into a scalar type which the backend can
3265   // handle naturally (i.e., without using byval).
3266   //
3267   // For simplicity, we currently only do this when we have exhausted all of the
3268   // free integer registers. Doing this when there are free integer registers
3269   // would require more care, as we would have to ensure that the coerced value
3270   // did not claim the unused register. That would require either reording the
3271   // arguments to the function (so that any subsequent inreg values came first),
3272   // or only doing this optimization when there were no following arguments that
3273   // might be inreg.
3274   //
3275   // We currently expect it to be rare (particularly in well written code) for
3276   // arguments to be passed on the stack when there are still free integer
3277   // registers available (this would typically imply large structs being passed
3278   // by value), so this seems like a fair tradeoff for now.
3279   //
3280   // We can revisit this if the backend grows support for 'onstack' parameter
3281   // attributes. See PR12193.
3282   if (freeIntRegs == 0) {
3283     uint64_t Size = getContext().getTypeSize(Ty);
3284 
3285     // If this type fits in an eightbyte, coerce it into the matching integral
3286     // type, which will end up on the stack (with alignment 8).
3287     if (Align == 8 && Size <= 64)
3288       return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
3289                                                           Size));
3290   }
3291 
3292   return ABIArgInfo::getIndirect(CharUnits::fromQuantity(Align));
3293 }
3294 
3295 /// The ABI specifies that a value should be passed in a full vector XMM/YMM
3296 /// register. Pick an LLVM IR type that will be passed as a vector register.
3297 llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
3298   // Wrapper structs/arrays that only contain vectors are passed just like
3299   // vectors; strip them off if present.
3300   if (const Type *InnerTy = isSingleElementStruct(Ty, getContext()))
3301     Ty = QualType(InnerTy, 0);
3302 
3303   llvm::Type *IRType = CGT.ConvertType(Ty);
3304   if (isa<llvm::VectorType>(IRType)) {
3305     // Don't pass vXi128 vectors in their native type, the backend can't
3306     // legalize them.
3307     if (passInt128VectorsInMem() &&
3308         cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy(128)) {
3309       // Use a vXi64 vector.
3310       uint64_t Size = getContext().getTypeSize(Ty);
3311       return llvm::FixedVectorType::get(llvm::Type::getInt64Ty(getVMContext()),
3312                                         Size / 64);
3313     }
3314 
3315     return IRType;
3316   }
3317 
3318   if (IRType->getTypeID() == llvm::Type::FP128TyID)
3319     return IRType;
3320 
3321   // We couldn't find the preferred IR vector type for 'Ty'.
3322   uint64_t Size = getContext().getTypeSize(Ty);
3323   assert((Size == 128 || Size == 256 || Size == 512) && "Invalid type found!");
3324 
3325 
3326   // Return a LLVM IR vector type based on the size of 'Ty'.
3327   return llvm::FixedVectorType::get(llvm::Type::getDoubleTy(getVMContext()),
3328                                     Size / 64);
3329 }
3330 
3331 /// BitsContainNoUserData - Return true if the specified [start,end) bit range
3332 /// is known to either be off the end of the specified type or being in
3333 /// alignment padding.  The user type specified is known to be at most 128 bits
3334 /// in size, and have passed through X86_64ABIInfo::classify with a successful
3335 /// classification that put one of the two halves in the INTEGER class.
3336 ///
3337 /// It is conservatively correct to return false.
3338 static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
3339                                   unsigned EndBit, ASTContext &Context) {
3340   // If the bytes being queried are off the end of the type, there is no user
3341   // data hiding here.  This handles analysis of builtins, vectors and other
3342   // types that don't contain interesting padding.
3343   unsigned TySize = (unsigned)Context.getTypeSize(Ty);
3344   if (TySize <= StartBit)
3345     return true;
3346 
3347   if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
3348     unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
3349     unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
3350 
3351     // Check each element to see if the element overlaps with the queried range.
3352     for (unsigned i = 0; i != NumElts; ++i) {
3353       // If the element is after the span we care about, then we're done..
3354       unsigned EltOffset = i*EltSize;
3355       if (EltOffset >= EndBit) break;
3356 
3357       unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
3358       if (!BitsContainNoUserData(AT->getElementType(), EltStart,
3359                                  EndBit-EltOffset, Context))
3360         return false;
3361     }
3362     // If it overlaps no elements, then it is safe to process as padding.
3363     return true;
3364   }
3365 
3366   if (const RecordType *RT = Ty->getAs<RecordType>()) {
3367     const RecordDecl *RD = RT->getDecl();
3368     const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
3369 
3370     // If this is a C++ record, check the bases first.
3371     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3372       for (const auto &I : CXXRD->bases()) {
3373         assert(!I.isVirtual() && !I.getType()->isDependentType() &&
3374                "Unexpected base class!");
3375         const auto *Base =
3376             cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
3377 
3378         // If the base is after the span we care about, ignore it.
3379         unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
3380         if (BaseOffset >= EndBit) continue;
3381 
3382         unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
3383         if (!BitsContainNoUserData(I.getType(), BaseStart,
3384                                    EndBit-BaseOffset, Context))
3385           return false;
3386       }
3387     }
3388 
3389     // Verify that no field has data that overlaps the region of interest.  Yes
3390     // this could be sped up a lot by being smarter about queried fields,
3391     // however we're only looking at structs up to 16 bytes, so we don't care
3392     // much.
3393     unsigned idx = 0;
3394     for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
3395          i != e; ++i, ++idx) {
3396       unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
3397 
3398       // If we found a field after the region we care about, then we're done.
3399       if (FieldOffset >= EndBit) break;
3400 
3401       unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
3402       if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
3403                                  Context))
3404         return false;
3405     }
3406 
3407     // If nothing in this record overlapped the area of interest, then we're
3408     // clean.
3409     return true;
3410   }
3411 
3412   return false;
3413 }
3414 
3415 /// getFPTypeAtOffset - Return a floating point type at the specified offset.
3416 static llvm::Type *getFPTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
3417                                      const llvm::DataLayout &TD) {
3418   if (IROffset == 0 && IRType->isFloatingPointTy())
3419     return IRType;
3420 
3421   // If this is a struct, recurse into the field at the specified offset.
3422   if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
3423     if (!STy->getNumContainedTypes())
3424       return nullptr;
3425 
3426     const llvm::StructLayout *SL = TD.getStructLayout(STy);
3427     unsigned Elt = SL->getElementContainingOffset(IROffset);
3428     IROffset -= SL->getElementOffset(Elt);
3429     return getFPTypeAtOffset(STy->getElementType(Elt), IROffset, TD);
3430   }
3431 
3432   // If this is an array, recurse into the field at the specified offset.
3433   if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
3434     llvm::Type *EltTy = ATy->getElementType();
3435     unsigned EltSize = TD.getTypeAllocSize(EltTy);
3436     IROffset -= IROffset / EltSize * EltSize;
3437     return getFPTypeAtOffset(EltTy, IROffset, TD);
3438   }
3439 
3440   return nullptr;
3441 }
3442 
3443 /// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
3444 /// low 8 bytes of an XMM register, corresponding to the SSE class.
3445 llvm::Type *X86_64ABIInfo::
3446 GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
3447                    QualType SourceTy, unsigned SourceOffset) const {
3448   const llvm::DataLayout &TD = getDataLayout();
3449   unsigned SourceSize =
3450       (unsigned)getContext().getTypeSize(SourceTy) / 8 - SourceOffset;
3451   llvm::Type *T0 = getFPTypeAtOffset(IRType, IROffset, TD);
3452   if (!T0 || T0->isDoubleTy())
3453     return llvm::Type::getDoubleTy(getVMContext());
3454 
3455   // Get the adjacent FP type.
3456   llvm::Type *T1 = nullptr;
3457   unsigned T0Size = TD.getTypeAllocSize(T0);
3458   if (SourceSize > T0Size)
3459       T1 = getFPTypeAtOffset(IRType, IROffset + T0Size, TD);
3460   if (T1 == nullptr) {
3461     // Check if IRType is a half + float. float type will be in IROffset+4 due
3462     // to its alignment.
3463     if (T0->isHalfTy() && SourceSize > 4)
3464       T1 = getFPTypeAtOffset(IRType, IROffset + 4, TD);
3465     // If we can't get a second FP type, return a simple half or float.
3466     // avx512fp16-abi.c:pr51813_2 shows it works to return float for
3467     // {float, i8} too.
3468     if (T1 == nullptr)
3469       return T0;
3470   }
3471 
3472   if (T0->isFloatTy() && T1->isFloatTy())
3473     return llvm::FixedVectorType::get(T0, 2);
3474 
3475   if (T0->isHalfTy() && T1->isHalfTy()) {
3476     llvm::Type *T2 = nullptr;
3477     if (SourceSize > 4)
3478       T2 = getFPTypeAtOffset(IRType, IROffset + 4, TD);
3479     if (T2 == nullptr)
3480       return llvm::FixedVectorType::get(T0, 2);
3481     return llvm::FixedVectorType::get(T0, 4);
3482   }
3483 
3484   if (T0->isHalfTy() || T1->isHalfTy())
3485     return llvm::FixedVectorType::get(llvm::Type::getHalfTy(getVMContext()), 4);
3486 
3487   return llvm::Type::getDoubleTy(getVMContext());
3488 }
3489 
3490 
3491 /// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
3492 /// an 8-byte GPR.  This means that we either have a scalar or we are talking
3493 /// about the high or low part of an up-to-16-byte struct.  This routine picks
3494 /// the best LLVM IR type to represent this, which may be i64 or may be anything
3495 /// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
3496 /// etc).
3497 ///
3498 /// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
3499 /// the source type.  IROffset is an offset in bytes into the LLVM IR type that
3500 /// the 8-byte value references.  PrefType may be null.
3501 ///
3502 /// SourceTy is the source-level type for the entire argument.  SourceOffset is
3503 /// an offset into this that we're processing (which is always either 0 or 8).
3504 ///
3505 llvm::Type *X86_64ABIInfo::
3506 GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
3507                        QualType SourceTy, unsigned SourceOffset) const {
3508   // If we're dealing with an un-offset LLVM IR type, then it means that we're
3509   // returning an 8-byte unit starting with it.  See if we can safely use it.
3510   if (IROffset == 0) {
3511     // Pointers and int64's always fill the 8-byte unit.
3512     if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
3513         IRType->isIntegerTy(64))
3514       return IRType;
3515 
3516     // If we have a 1/2/4-byte integer, we can use it only if the rest of the
3517     // goodness in the source type is just tail padding.  This is allowed to
3518     // kick in for struct {double,int} on the int, but not on
3519     // struct{double,int,int} because we wouldn't return the second int.  We
3520     // have to do this analysis on the source type because we can't depend on
3521     // unions being lowered a specific way etc.
3522     if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
3523         IRType->isIntegerTy(32) ||
3524         (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
3525       unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
3526           cast<llvm::IntegerType>(IRType)->getBitWidth();
3527 
3528       if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
3529                                 SourceOffset*8+64, getContext()))
3530         return IRType;
3531     }
3532   }
3533 
3534   if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
3535     // If this is a struct, recurse into the field at the specified offset.
3536     const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
3537     if (IROffset < SL->getSizeInBytes()) {
3538       unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
3539       IROffset -= SL->getElementOffset(FieldIdx);
3540 
3541       return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
3542                                     SourceTy, SourceOffset);
3543     }
3544   }
3545 
3546   if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
3547     llvm::Type *EltTy = ATy->getElementType();
3548     unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
3549     unsigned EltOffset = IROffset/EltSize*EltSize;
3550     return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
3551                                   SourceOffset);
3552   }
3553 
3554   // Okay, we don't have any better idea of what to pass, so we pass this in an
3555   // integer register that isn't too big to fit the rest of the struct.
3556   unsigned TySizeInBytes =
3557     (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
3558 
3559   assert(TySizeInBytes != SourceOffset && "Empty field?");
3560 
3561   // It is always safe to classify this as an integer type up to i64 that
3562   // isn't larger than the structure.
3563   return llvm::IntegerType::get(getVMContext(),
3564                                 std::min(TySizeInBytes-SourceOffset, 8U)*8);
3565 }
3566 
3567 
3568 /// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
3569 /// be used as elements of a two register pair to pass or return, return a
3570 /// first class aggregate to represent them.  For example, if the low part of
3571 /// a by-value argument should be passed as i32* and the high part as float,
3572 /// return {i32*, float}.
3573 static llvm::Type *
3574 GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
3575                            const llvm::DataLayout &TD) {
3576   // In order to correctly satisfy the ABI, we need to the high part to start
3577   // at offset 8.  If the high and low parts we inferred are both 4-byte types
3578   // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
3579   // the second element at offset 8.  Check for this:
3580   unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
3581   unsigned HiAlign = TD.getABITypeAlignment(Hi);
3582   unsigned HiStart = llvm::alignTo(LoSize, HiAlign);
3583   assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
3584 
3585   // To handle this, we have to increase the size of the low part so that the
3586   // second element will start at an 8 byte offset.  We can't increase the size
3587   // of the second element because it might make us access off the end of the
3588   // struct.
3589   if (HiStart != 8) {
3590     // There are usually two sorts of types the ABI generation code can produce
3591     // for the low part of a pair that aren't 8 bytes in size: half, float or
3592     // i8/i16/i32.  This can also include pointers when they are 32-bit (X32 and
3593     // NaCl).
3594     // Promote these to a larger type.
3595     if (Lo->isHalfTy() || Lo->isFloatTy())
3596       Lo = llvm::Type::getDoubleTy(Lo->getContext());
3597     else {
3598       assert((Lo->isIntegerTy() || Lo->isPointerTy())
3599              && "Invalid/unknown lo type");
3600       Lo = llvm::Type::getInt64Ty(Lo->getContext());
3601     }
3602   }
3603 
3604   llvm::StructType *Result = llvm::StructType::get(Lo, Hi);
3605 
3606   // Verify that the second element is at an 8-byte offset.
3607   assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
3608          "Invalid x86-64 argument pair!");
3609   return Result;
3610 }
3611 
3612 ABIArgInfo X86_64ABIInfo::
3613 classifyReturnType(QualType RetTy) const {
3614   // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
3615   // classification algorithm.
3616   X86_64ABIInfo::Class Lo, Hi;
3617   classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
3618 
3619   // Check some invariants.
3620   assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
3621   assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
3622 
3623   llvm::Type *ResType = nullptr;
3624   switch (Lo) {
3625   case NoClass:
3626     if (Hi == NoClass)
3627       return ABIArgInfo::getIgnore();
3628     // If the low part is just padding, it takes no register, leave ResType
3629     // null.
3630     assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3631            "Unknown missing lo part");
3632     break;
3633 
3634   case SSEUp:
3635   case X87Up:
3636     llvm_unreachable("Invalid classification for lo word.");
3637 
3638     // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
3639     // hidden argument.
3640   case Memory:
3641     return getIndirectReturnResult(RetTy);
3642 
3643     // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
3644     // available register of the sequence %rax, %rdx is used.
3645   case Integer:
3646     ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
3647 
3648     // If we have a sign or zero extended integer, make sure to return Extend
3649     // so that the parameter gets the right LLVM IR attributes.
3650     if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3651       // Treat an enum type as its underlying type.
3652       if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
3653         RetTy = EnumTy->getDecl()->getIntegerType();
3654 
3655       if (RetTy->isIntegralOrEnumerationType() &&
3656           isPromotableIntegerTypeForABI(RetTy))
3657         return ABIArgInfo::getExtend(RetTy);
3658     }
3659     break;
3660 
3661     // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
3662     // available SSE register of the sequence %xmm0, %xmm1 is used.
3663   case SSE:
3664     ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
3665     break;
3666 
3667     // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
3668     // returned on the X87 stack in %st0 as 80-bit x87 number.
3669   case X87:
3670     ResType = llvm::Type::getX86_FP80Ty(getVMContext());
3671     break;
3672 
3673     // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
3674     // part of the value is returned in %st0 and the imaginary part in
3675     // %st1.
3676   case ComplexX87:
3677     assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
3678     ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
3679                                     llvm::Type::getX86_FP80Ty(getVMContext()));
3680     break;
3681   }
3682 
3683   llvm::Type *HighPart = nullptr;
3684   switch (Hi) {
3685     // Memory was handled previously and X87 should
3686     // never occur as a hi class.
3687   case Memory:
3688   case X87:
3689     llvm_unreachable("Invalid classification for hi word.");
3690 
3691   case ComplexX87: // Previously handled.
3692   case NoClass:
3693     break;
3694 
3695   case Integer:
3696     HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
3697     if (Lo == NoClass)  // Return HighPart at offset 8 in memory.
3698       return ABIArgInfo::getDirect(HighPart, 8);
3699     break;
3700   case SSE:
3701     HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
3702     if (Lo == NoClass)  // Return HighPart at offset 8 in memory.
3703       return ABIArgInfo::getDirect(HighPart, 8);
3704     break;
3705 
3706     // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
3707     // is passed in the next available eightbyte chunk if the last used
3708     // vector register.
3709     //
3710     // SSEUP should always be preceded by SSE, just widen.
3711   case SSEUp:
3712     assert(Lo == SSE && "Unexpected SSEUp classification.");
3713     ResType = GetByteVectorType(RetTy);
3714     break;
3715 
3716     // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
3717     // returned together with the previous X87 value in %st0.
3718   case X87Up:
3719     // If X87Up is preceded by X87, we don't need to do
3720     // anything. However, in some cases with unions it may not be
3721     // preceded by X87. In such situations we follow gcc and pass the
3722     // extra bits in an SSE reg.
3723     if (Lo != X87) {
3724       HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
3725       if (Lo == NoClass)  // Return HighPart at offset 8 in memory.
3726         return ABIArgInfo::getDirect(HighPart, 8);
3727     }
3728     break;
3729   }
3730 
3731   // If a high part was specified, merge it together with the low part.  It is
3732   // known to pass in the high eightbyte of the result.  We do this by forming a
3733   // first class struct aggregate with the high and low part: {low, high}
3734   if (HighPart)
3735     ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
3736 
3737   return ABIArgInfo::getDirect(ResType);
3738 }
3739 
3740 ABIArgInfo X86_64ABIInfo::classifyArgumentType(
3741   QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE,
3742   bool isNamedArg)
3743   const
3744 {
3745   Ty = useFirstFieldIfTransparentUnion(Ty);
3746 
3747   X86_64ABIInfo::Class Lo, Hi;
3748   classify(Ty, 0, Lo, Hi, isNamedArg);
3749 
3750   // Check some invariants.
3751   // FIXME: Enforce these by construction.
3752   assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
3753   assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
3754 
3755   neededInt = 0;
3756   neededSSE = 0;
3757   llvm::Type *ResType = nullptr;
3758   switch (Lo) {
3759   case NoClass:
3760     if (Hi == NoClass)
3761       return ABIArgInfo::getIgnore();
3762     // If the low part is just padding, it takes no register, leave ResType
3763     // null.
3764     assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3765            "Unknown missing lo part");
3766     break;
3767 
3768     // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
3769     // on the stack.
3770   case Memory:
3771 
3772     // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
3773     // COMPLEX_X87, it is passed in memory.
3774   case X87:
3775   case ComplexX87:
3776     if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect)
3777       ++neededInt;
3778     return getIndirectResult(Ty, freeIntRegs);
3779 
3780   case SSEUp:
3781   case X87Up:
3782     llvm_unreachable("Invalid classification for lo word.");
3783 
3784     // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
3785     // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
3786     // and %r9 is used.
3787   case Integer:
3788     ++neededInt;
3789 
3790     // Pick an 8-byte type based on the preferred type.
3791     ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
3792 
3793     // If we have a sign or zero extended integer, make sure to return Extend
3794     // so that the parameter gets the right LLVM IR attributes.
3795     if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3796       // Treat an enum type as its underlying type.
3797       if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3798         Ty = EnumTy->getDecl()->getIntegerType();
3799 
3800       if (Ty->isIntegralOrEnumerationType() &&
3801           isPromotableIntegerTypeForABI(Ty))
3802         return ABIArgInfo::getExtend(Ty);
3803     }
3804 
3805     break;
3806 
3807     // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
3808     // available SSE register is used, the registers are taken in the
3809     // order from %xmm0 to %xmm7.
3810   case SSE: {
3811     llvm::Type *IRType = CGT.ConvertType(Ty);
3812     ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
3813     ++neededSSE;
3814     break;
3815   }
3816   }
3817 
3818   llvm::Type *HighPart = nullptr;
3819   switch (Hi) {
3820     // Memory was handled previously, ComplexX87 and X87 should
3821     // never occur as hi classes, and X87Up must be preceded by X87,
3822     // which is passed in memory.
3823   case Memory:
3824   case X87:
3825   case ComplexX87:
3826     llvm_unreachable("Invalid classification for hi word.");
3827 
3828   case NoClass: break;
3829 
3830   case Integer:
3831     ++neededInt;
3832     // Pick an 8-byte type based on the preferred type.
3833     HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
3834 
3835     if (Lo == NoClass)  // Pass HighPart at offset 8 in memory.
3836       return ABIArgInfo::getDirect(HighPart, 8);
3837     break;
3838 
3839     // X87Up generally doesn't occur here (long double is passed in
3840     // memory), except in situations involving unions.
3841   case X87Up:
3842   case SSE:
3843     HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
3844 
3845     if (Lo == NoClass)  // Pass HighPart at offset 8 in memory.
3846       return ABIArgInfo::getDirect(HighPart, 8);
3847 
3848     ++neededSSE;
3849     break;
3850 
3851     // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
3852     // eightbyte is passed in the upper half of the last used SSE
3853     // register.  This only happens when 128-bit vectors are passed.
3854   case SSEUp:
3855     assert(Lo == SSE && "Unexpected SSEUp classification");
3856     ResType = GetByteVectorType(Ty);
3857     break;
3858   }
3859 
3860   // If a high part was specified, merge it together with the low part.  It is
3861   // known to pass in the high eightbyte of the result.  We do this by forming a
3862   // first class struct aggregate with the high and low part: {low, high}
3863   if (HighPart)
3864     ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
3865 
3866   return ABIArgInfo::getDirect(ResType);
3867 }
3868 
3869 ABIArgInfo
3870 X86_64ABIInfo::classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
3871                                              unsigned &NeededSSE) const {
3872   auto RT = Ty->getAs<RecordType>();
3873   assert(RT && "classifyRegCallStructType only valid with struct types");
3874 
3875   if (RT->getDecl()->hasFlexibleArrayMember())
3876     return getIndirectReturnResult(Ty);
3877 
3878   // Sum up bases
3879   if (auto CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
3880     if (CXXRD->isDynamicClass()) {
3881       NeededInt = NeededSSE = 0;
3882       return getIndirectReturnResult(Ty);
3883     }
3884 
3885     for (const auto &I : CXXRD->bases())
3886       if (classifyRegCallStructTypeImpl(I.getType(), NeededInt, NeededSSE)
3887               .isIndirect()) {
3888         NeededInt = NeededSSE = 0;
3889         return getIndirectReturnResult(Ty);
3890       }
3891   }
3892 
3893   // Sum up members
3894   for (const auto *FD : RT->getDecl()->fields()) {
3895     if (FD->getType()->isRecordType() && !FD->getType()->isUnionType()) {
3896       if (classifyRegCallStructTypeImpl(FD->getType(), NeededInt, NeededSSE)
3897               .isIndirect()) {
3898         NeededInt = NeededSSE = 0;
3899         return getIndirectReturnResult(Ty);
3900       }
3901     } else {
3902       unsigned LocalNeededInt, LocalNeededSSE;
3903       if (classifyArgumentType(FD->getType(), UINT_MAX, LocalNeededInt,
3904                                LocalNeededSSE, true)
3905               .isIndirect()) {
3906         NeededInt = NeededSSE = 0;
3907         return getIndirectReturnResult(Ty);
3908       }
3909       NeededInt += LocalNeededInt;
3910       NeededSSE += LocalNeededSSE;
3911     }
3912   }
3913 
3914   return ABIArgInfo::getDirect();
3915 }
3916 
3917 ABIArgInfo X86_64ABIInfo::classifyRegCallStructType(QualType Ty,
3918                                                     unsigned &NeededInt,
3919                                                     unsigned &NeededSSE) const {
3920 
3921   NeededInt = 0;
3922   NeededSSE = 0;
3923 
3924   return classifyRegCallStructTypeImpl(Ty, NeededInt, NeededSSE);
3925 }
3926 
3927 void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
3928 
3929   const unsigned CallingConv = FI.getCallingConvention();
3930   // It is possible to force Win64 calling convention on any x86_64 target by
3931   // using __attribute__((ms_abi)). In such case to correctly emit Win64
3932   // compatible code delegate this call to WinX86_64ABIInfo::computeInfo.
3933   if (CallingConv == llvm::CallingConv::Win64) {
3934     WinX86_64ABIInfo Win64ABIInfo(CGT, AVXLevel);
3935     Win64ABIInfo.computeInfo(FI);
3936     return;
3937   }
3938 
3939   bool IsRegCall = CallingConv == llvm::CallingConv::X86_RegCall;
3940 
3941   // Keep track of the number of assigned registers.
3942   unsigned FreeIntRegs = IsRegCall ? 11 : 6;
3943   unsigned FreeSSERegs = IsRegCall ? 16 : 8;
3944   unsigned NeededInt, NeededSSE;
3945 
3946   if (!::classifyReturnType(getCXXABI(), FI, *this)) {
3947     if (IsRegCall && FI.getReturnType()->getTypePtr()->isRecordType() &&
3948         !FI.getReturnType()->getTypePtr()->isUnionType()) {
3949       FI.getReturnInfo() =
3950           classifyRegCallStructType(FI.getReturnType(), NeededInt, NeededSSE);
3951       if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
3952         FreeIntRegs -= NeededInt;
3953         FreeSSERegs -= NeededSSE;
3954       } else {
3955         FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType());
3956       }
3957     } else if (IsRegCall && FI.getReturnType()->getAs<ComplexType>() &&
3958                getContext().getCanonicalType(FI.getReturnType()
3959                                                  ->getAs<ComplexType>()
3960                                                  ->getElementType()) ==
3961                    getContext().LongDoubleTy)
3962       // Complex Long Double Type is passed in Memory when Regcall
3963       // calling convention is used.
3964       FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType());
3965     else
3966       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
3967   }
3968 
3969   // If the return value is indirect, then the hidden argument is consuming one
3970   // integer register.
3971   if (FI.getReturnInfo().isIndirect())
3972     --FreeIntRegs;
3973 
3974   // The chain argument effectively gives us another free register.
3975   if (FI.isChainCall())
3976     ++FreeIntRegs;
3977 
3978   unsigned NumRequiredArgs = FI.getNumRequiredArgs();
3979   // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
3980   // get assigned (in left-to-right order) for passing as follows...
3981   unsigned ArgNo = 0;
3982   for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
3983        it != ie; ++it, ++ArgNo) {
3984     bool IsNamedArg = ArgNo < NumRequiredArgs;
3985 
3986     if (IsRegCall && it->type->isStructureOrClassType())
3987       it->info = classifyRegCallStructType(it->type, NeededInt, NeededSSE);
3988     else
3989       it->info = classifyArgumentType(it->type, FreeIntRegs, NeededInt,
3990                                       NeededSSE, IsNamedArg);
3991 
3992     // AMD64-ABI 3.2.3p3: If there are no registers available for any
3993     // eightbyte of an argument, the whole argument is passed on the
3994     // stack. If registers have already been assigned for some
3995     // eightbytes of such an argument, the assignments get reverted.
3996     if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
3997       FreeIntRegs -= NeededInt;
3998       FreeSSERegs -= NeededSSE;
3999     } else {
4000       it->info = getIndirectResult(it->type, FreeIntRegs);
4001     }
4002   }
4003 }
4004 
4005 static Address EmitX86_64VAArgFromMemory(CodeGenFunction &CGF,
4006                                          Address VAListAddr, QualType Ty) {
4007   Address overflow_arg_area_p =
4008       CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_p");
4009   llvm::Value *overflow_arg_area =
4010     CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
4011 
4012   // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
4013   // byte boundary if alignment needed by type exceeds 8 byte boundary.
4014   // It isn't stated explicitly in the standard, but in practice we use
4015   // alignment greater than 16 where necessary.
4016   CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
4017   if (Align > CharUnits::fromQuantity(8)) {
4018     overflow_arg_area = emitRoundPointerUpToAlignment(CGF, overflow_arg_area,
4019                                                       Align);
4020   }
4021 
4022   // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
4023   llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
4024   llvm::Value *Res =
4025     CGF.Builder.CreateBitCast(overflow_arg_area,
4026                               llvm::PointerType::getUnqual(LTy));
4027 
4028   // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
4029   // l->overflow_arg_area + sizeof(type).
4030   // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
4031   // an 8 byte boundary.
4032 
4033   uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
4034   llvm::Value *Offset =
4035       llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7)  & ~7);
4036   overflow_arg_area = CGF.Builder.CreateGEP(CGF.Int8Ty, overflow_arg_area,
4037                                             Offset, "overflow_arg_area.next");
4038   CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
4039 
4040   // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
4041   return Address(Res, LTy, Align);
4042 }
4043 
4044 Address X86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4045                                  QualType Ty) const {
4046   // Assume that va_list type is correct; should be pointer to LLVM type:
4047   // struct {
4048   //   i32 gp_offset;
4049   //   i32 fp_offset;
4050   //   i8* overflow_arg_area;
4051   //   i8* reg_save_area;
4052   // };
4053   unsigned neededInt, neededSSE;
4054 
4055   Ty = getContext().getCanonicalType(Ty);
4056   ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
4057                                        /*isNamedArg*/false);
4058 
4059   // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
4060   // in the registers. If not go to step 7.
4061   if (!neededInt && !neededSSE)
4062     return EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
4063 
4064   // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
4065   // general purpose registers needed to pass type and num_fp to hold
4066   // the number of floating point registers needed.
4067 
4068   // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
4069   // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
4070   // l->fp_offset > 304 - num_fp * 16 go to step 7.
4071   //
4072   // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
4073   // register save space).
4074 
4075   llvm::Value *InRegs = nullptr;
4076   Address gp_offset_p = Address::invalid(), fp_offset_p = Address::invalid();
4077   llvm::Value *gp_offset = nullptr, *fp_offset = nullptr;
4078   if (neededInt) {
4079     gp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "gp_offset_p");
4080     gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
4081     InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
4082     InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
4083   }
4084 
4085   if (neededSSE) {
4086     fp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 1, "fp_offset_p");
4087     fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
4088     llvm::Value *FitsInFP =
4089       llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
4090     FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
4091     InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
4092   }
4093 
4094   llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
4095   llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
4096   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
4097   CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
4098 
4099   // Emit code to load the value if it was passed in registers.
4100 
4101   CGF.EmitBlock(InRegBlock);
4102 
4103   // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
4104   // an offset of l->gp_offset and/or l->fp_offset. This may require
4105   // copying to a temporary location in case the parameter is passed
4106   // in different register classes or requires an alignment greater
4107   // than 8 for general purpose registers and 16 for XMM registers.
4108   //
4109   // FIXME: This really results in shameful code when we end up needing to
4110   // collect arguments from different places; often what should result in a
4111   // simple assembling of a structure from scattered addresses has many more
4112   // loads than necessary. Can we clean this up?
4113   llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
4114   llvm::Value *RegSaveArea = CGF.Builder.CreateLoad(
4115       CGF.Builder.CreateStructGEP(VAListAddr, 3), "reg_save_area");
4116 
4117   Address RegAddr = Address::invalid();
4118   if (neededInt && neededSSE) {
4119     // FIXME: Cleanup.
4120     assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
4121     llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
4122     Address Tmp = CGF.CreateMemTemp(Ty);
4123     Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
4124     assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
4125     llvm::Type *TyLo = ST->getElementType(0);
4126     llvm::Type *TyHi = ST->getElementType(1);
4127     assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
4128            "Unexpected ABI info for mixed regs");
4129     llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
4130     llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
4131     llvm::Value *GPAddr =
4132         CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, gp_offset);
4133     llvm::Value *FPAddr =
4134         CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, fp_offset);
4135     llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr;
4136     llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr;
4137 
4138     // Copy the first element.
4139     // FIXME: Our choice of alignment here and below is probably pessimistic.
4140     llvm::Value *V = CGF.Builder.CreateAlignedLoad(
4141         TyLo, CGF.Builder.CreateBitCast(RegLoAddr, PTyLo),
4142         CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyLo)));
4143     CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
4144 
4145     // Copy the second element.
4146     V = CGF.Builder.CreateAlignedLoad(
4147         TyHi, CGF.Builder.CreateBitCast(RegHiAddr, PTyHi),
4148         CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyHi)));
4149     CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
4150 
4151     RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
4152   } else if (neededInt) {
4153     RegAddr = Address(CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, gp_offset),
4154                       CGF.Int8Ty, CharUnits::fromQuantity(8));
4155     RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
4156 
4157     // Copy to a temporary if necessary to ensure the appropriate alignment.
4158     auto TInfo = getContext().getTypeInfoInChars(Ty);
4159     uint64_t TySize = TInfo.Width.getQuantity();
4160     CharUnits TyAlign = TInfo.Align;
4161 
4162     // Copy into a temporary if the type is more aligned than the
4163     // register save area.
4164     if (TyAlign.getQuantity() > 8) {
4165       Address Tmp = CGF.CreateMemTemp(Ty);
4166       CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, false);
4167       RegAddr = Tmp;
4168     }
4169 
4170   } else if (neededSSE == 1) {
4171     RegAddr = Address(CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, fp_offset),
4172                       CGF.Int8Ty, CharUnits::fromQuantity(16));
4173     RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
4174   } else {
4175     assert(neededSSE == 2 && "Invalid number of needed registers!");
4176     // SSE registers are spaced 16 bytes apart in the register save
4177     // area, we need to collect the two eightbytes together.
4178     // The ABI isn't explicit about this, but it seems reasonable
4179     // to assume that the slots are 16-byte aligned, since the stack is
4180     // naturally 16-byte aligned and the prologue is expected to store
4181     // all the SSE registers to the RSA.
4182     Address RegAddrLo = Address(CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea,
4183                                                       fp_offset),
4184                                 CGF.Int8Ty, CharUnits::fromQuantity(16));
4185     Address RegAddrHi =
4186       CGF.Builder.CreateConstInBoundsByteGEP(RegAddrLo,
4187                                              CharUnits::fromQuantity(16));
4188     llvm::Type *ST = AI.canHaveCoerceToType()
4189                          ? AI.getCoerceToType()
4190                          : llvm::StructType::get(CGF.DoubleTy, CGF.DoubleTy);
4191     llvm::Value *V;
4192     Address Tmp = CGF.CreateMemTemp(Ty);
4193     Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
4194     V = CGF.Builder.CreateLoad(CGF.Builder.CreateElementBitCast(
4195         RegAddrLo, ST->getStructElementType(0)));
4196     CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
4197     V = CGF.Builder.CreateLoad(CGF.Builder.CreateElementBitCast(
4198         RegAddrHi, ST->getStructElementType(1)));
4199     CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
4200 
4201     RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
4202   }
4203 
4204   // AMD64-ABI 3.5.7p5: Step 5. Set:
4205   // l->gp_offset = l->gp_offset + num_gp * 8
4206   // l->fp_offset = l->fp_offset + num_fp * 16.
4207   if (neededInt) {
4208     llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
4209     CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
4210                             gp_offset_p);
4211   }
4212   if (neededSSE) {
4213     llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
4214     CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
4215                             fp_offset_p);
4216   }
4217   CGF.EmitBranch(ContBlock);
4218 
4219   // Emit code to load the value if it was passed in memory.
4220 
4221   CGF.EmitBlock(InMemBlock);
4222   Address MemAddr = EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
4223 
4224   // Return the appropriate result.
4225 
4226   CGF.EmitBlock(ContBlock);
4227   Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, MemAddr, InMemBlock,
4228                                  "vaarg.addr");
4229   return ResAddr;
4230 }
4231 
4232 Address X86_64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
4233                                    QualType Ty) const {
4234   // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
4235   // not 1, 2, 4, or 8 bytes, must be passed by reference."
4236   uint64_t Width = getContext().getTypeSize(Ty);
4237   bool IsIndirect = Width > 64 || !llvm::isPowerOf2_64(Width);
4238 
4239   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
4240                           CGF.getContext().getTypeInfoInChars(Ty),
4241                           CharUnits::fromQuantity(8),
4242                           /*allowHigherAlign*/ false);
4243 }
4244 
4245 ABIArgInfo WinX86_64ABIInfo::reclassifyHvaArgForVectorCall(
4246     QualType Ty, unsigned &FreeSSERegs, const ABIArgInfo &current) const {
4247   const Type *Base = nullptr;
4248   uint64_t NumElts = 0;
4249 
4250   if (!Ty->isBuiltinType() && !Ty->isVectorType() &&
4251       isHomogeneousAggregate(Ty, Base, NumElts) && FreeSSERegs >= NumElts) {
4252     FreeSSERegs -= NumElts;
4253     return getDirectX86Hva();
4254   }
4255   return current;
4256 }
4257 
4258 ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, unsigned &FreeSSERegs,
4259                                       bool IsReturnType, bool IsVectorCall,
4260                                       bool IsRegCall) const {
4261 
4262   if (Ty->isVoidType())
4263     return ABIArgInfo::getIgnore();
4264 
4265   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4266     Ty = EnumTy->getDecl()->getIntegerType();
4267 
4268   TypeInfo Info = getContext().getTypeInfo(Ty);
4269   uint64_t Width = Info.Width;
4270   CharUnits Align = getContext().toCharUnitsFromBits(Info.Align);
4271 
4272   const RecordType *RT = Ty->getAs<RecordType>();
4273   if (RT) {
4274     if (!IsReturnType) {
4275       if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
4276         return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
4277     }
4278 
4279     if (RT->getDecl()->hasFlexibleArrayMember())
4280       return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
4281 
4282   }
4283 
4284   const Type *Base = nullptr;
4285   uint64_t NumElts = 0;
4286   // vectorcall adds the concept of a homogenous vector aggregate, similar to
4287   // other targets.
4288   if ((IsVectorCall || IsRegCall) &&
4289       isHomogeneousAggregate(Ty, Base, NumElts)) {
4290     if (IsRegCall) {
4291       if (FreeSSERegs >= NumElts) {
4292         FreeSSERegs -= NumElts;
4293         if (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())
4294           return ABIArgInfo::getDirect();
4295         return ABIArgInfo::getExpand();
4296       }
4297       return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
4298     } else if (IsVectorCall) {
4299       if (FreeSSERegs >= NumElts &&
4300           (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())) {
4301         FreeSSERegs -= NumElts;
4302         return ABIArgInfo::getDirect();
4303       } else if (IsReturnType) {
4304         return ABIArgInfo::getExpand();
4305       } else if (!Ty->isBuiltinType() && !Ty->isVectorType()) {
4306         // HVAs are delayed and reclassified in the 2nd step.
4307         return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
4308       }
4309     }
4310   }
4311 
4312   if (Ty->isMemberPointerType()) {
4313     // If the member pointer is represented by an LLVM int or ptr, pass it
4314     // directly.
4315     llvm::Type *LLTy = CGT.ConvertType(Ty);
4316     if (LLTy->isPointerTy() || LLTy->isIntegerTy())
4317       return ABIArgInfo::getDirect();
4318   }
4319 
4320   if (RT || Ty->isAnyComplexType() || Ty->isMemberPointerType()) {
4321     // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
4322     // not 1, 2, 4, or 8 bytes, must be passed by reference."
4323     if (Width > 64 || !llvm::isPowerOf2_64(Width))
4324       return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
4325 
4326     // Otherwise, coerce it to a small integer.
4327     return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Width));
4328   }
4329 
4330   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4331     switch (BT->getKind()) {
4332     case BuiltinType::Bool:
4333       // Bool type is always extended to the ABI, other builtin types are not
4334       // extended.
4335       return ABIArgInfo::getExtend(Ty);
4336 
4337     case BuiltinType::LongDouble:
4338       // Mingw64 GCC uses the old 80 bit extended precision floating point
4339       // unit. It passes them indirectly through memory.
4340       if (IsMingw64) {
4341         const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
4342         if (LDF == &llvm::APFloat::x87DoubleExtended())
4343           return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
4344       }
4345       break;
4346 
4347     case BuiltinType::Int128:
4348     case BuiltinType::UInt128:
4349       // If it's a parameter type, the normal ABI rule is that arguments larger
4350       // than 8 bytes are passed indirectly. GCC follows it. We follow it too,
4351       // even though it isn't particularly efficient.
4352       if (!IsReturnType)
4353         return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
4354 
4355       // Mingw64 GCC returns i128 in XMM0. Coerce to v2i64 to handle that.
4356       // Clang matches them for compatibility.
4357       return ABIArgInfo::getDirect(llvm::FixedVectorType::get(
4358           llvm::Type::getInt64Ty(getVMContext()), 2));
4359 
4360     default:
4361       break;
4362     }
4363   }
4364 
4365   if (Ty->isBitIntType()) {
4366     // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
4367     // not 1, 2, 4, or 8 bytes, must be passed by reference."
4368     // However, non-power-of-two bit-precise integers will be passed as 1, 2, 4,
4369     // or 8 bytes anyway as long is it fits in them, so we don't have to check
4370     // the power of 2.
4371     if (Width <= 64)
4372       return ABIArgInfo::getDirect();
4373     return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
4374   }
4375 
4376   return ABIArgInfo::getDirect();
4377 }
4378 
4379 void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
4380   const unsigned CC = FI.getCallingConvention();
4381   bool IsVectorCall = CC == llvm::CallingConv::X86_VectorCall;
4382   bool IsRegCall = CC == llvm::CallingConv::X86_RegCall;
4383 
4384   // If __attribute__((sysv_abi)) is in use, use the SysV argument
4385   // classification rules.
4386   if (CC == llvm::CallingConv::X86_64_SysV) {
4387     X86_64ABIInfo SysVABIInfo(CGT, AVXLevel);
4388     SysVABIInfo.computeInfo(FI);
4389     return;
4390   }
4391 
4392   unsigned FreeSSERegs = 0;
4393   if (IsVectorCall) {
4394     // We can use up to 4 SSE return registers with vectorcall.
4395     FreeSSERegs = 4;
4396   } else if (IsRegCall) {
4397     // RegCall gives us 16 SSE registers.
4398     FreeSSERegs = 16;
4399   }
4400 
4401   if (!getCXXABI().classifyReturnType(FI))
4402     FI.getReturnInfo() = classify(FI.getReturnType(), FreeSSERegs, true,
4403                                   IsVectorCall, IsRegCall);
4404 
4405   if (IsVectorCall) {
4406     // We can use up to 6 SSE register parameters with vectorcall.
4407     FreeSSERegs = 6;
4408   } else if (IsRegCall) {
4409     // RegCall gives us 16 SSE registers, we can reuse the return registers.
4410     FreeSSERegs = 16;
4411   }
4412 
4413   unsigned ArgNum = 0;
4414   unsigned ZeroSSERegs = 0;
4415   for (auto &I : FI.arguments()) {
4416     // Vectorcall in x64 only permits the first 6 arguments to be passed as
4417     // XMM/YMM registers. After the sixth argument, pretend no vector
4418     // registers are left.
4419     unsigned *MaybeFreeSSERegs =
4420         (IsVectorCall && ArgNum >= 6) ? &ZeroSSERegs : &FreeSSERegs;
4421     I.info =
4422         classify(I.type, *MaybeFreeSSERegs, false, IsVectorCall, IsRegCall);
4423     ++ArgNum;
4424   }
4425 
4426   if (IsVectorCall) {
4427     // For vectorcall, assign aggregate HVAs to any free vector registers in a
4428     // second pass.
4429     for (auto &I : FI.arguments())
4430       I.info = reclassifyHvaArgForVectorCall(I.type, FreeSSERegs, I.info);
4431   }
4432 }
4433 
4434 Address WinX86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4435                                     QualType Ty) const {
4436   // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
4437   // not 1, 2, 4, or 8 bytes, must be passed by reference."
4438   uint64_t Width = getContext().getTypeSize(Ty);
4439   bool IsIndirect = Width > 64 || !llvm::isPowerOf2_64(Width);
4440 
4441   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
4442                           CGF.getContext().getTypeInfoInChars(Ty),
4443                           CharUnits::fromQuantity(8),
4444                           /*allowHigherAlign*/ false);
4445 }
4446 
4447 static bool PPC_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4448                                         llvm::Value *Address, bool Is64Bit,
4449                                         bool IsAIX) {
4450   // This is calculated from the LLVM and GCC tables and verified
4451   // against gcc output.  AFAIK all PPC ABIs use the same encoding.
4452 
4453   CodeGen::CGBuilderTy &Builder = CGF.Builder;
4454 
4455   llvm::IntegerType *i8 = CGF.Int8Ty;
4456   llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
4457   llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
4458   llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
4459 
4460   // 0-31: r0-31, the 4-byte or 8-byte general-purpose registers
4461   AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 0, 31);
4462 
4463   // 32-63: fp0-31, the 8-byte floating-point registers
4464   AssignToArrayRange(Builder, Address, Eight8, 32, 63);
4465 
4466   // 64-67 are various 4-byte or 8-byte special-purpose registers:
4467   // 64: mq
4468   // 65: lr
4469   // 66: ctr
4470   // 67: ap
4471   AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 64, 67);
4472 
4473   // 68-76 are various 4-byte special-purpose registers:
4474   // 68-75 cr0-7
4475   // 76: xer
4476   AssignToArrayRange(Builder, Address, Four8, 68, 76);
4477 
4478   // 77-108: v0-31, the 16-byte vector registers
4479   AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
4480 
4481   // 109: vrsave
4482   // 110: vscr
4483   AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 109, 110);
4484 
4485   // AIX does not utilize the rest of the registers.
4486   if (IsAIX)
4487     return false;
4488 
4489   // 111: spe_acc
4490   // 112: spefscr
4491   // 113: sfp
4492   AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 111, 113);
4493 
4494   if (!Is64Bit)
4495     return false;
4496 
4497   // TODO: Need to verify if these registers are used on 64 bit AIX with Power8
4498   // or above CPU.
4499   // 64-bit only registers:
4500   // 114: tfhar
4501   // 115: tfiar
4502   // 116: texasr
4503   AssignToArrayRange(Builder, Address, Eight8, 114, 116);
4504 
4505   return false;
4506 }
4507 
4508 // AIX
4509 namespace {
4510 /// AIXABIInfo - The AIX XCOFF ABI information.
4511 class AIXABIInfo : public ABIInfo {
4512   const bool Is64Bit;
4513   const unsigned PtrByteSize;
4514   CharUnits getParamTypeAlignment(QualType Ty) const;
4515 
4516 public:
4517   AIXABIInfo(CodeGen::CodeGenTypes &CGT, bool Is64Bit)
4518       : ABIInfo(CGT), Is64Bit(Is64Bit), PtrByteSize(Is64Bit ? 8 : 4) {}
4519 
4520   bool isPromotableTypeForABI(QualType Ty) const;
4521 
4522   ABIArgInfo classifyReturnType(QualType RetTy) const;
4523   ABIArgInfo classifyArgumentType(QualType Ty) const;
4524 
4525   void computeInfo(CGFunctionInfo &FI) const override {
4526     if (!getCXXABI().classifyReturnType(FI))
4527       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
4528 
4529     for (auto &I : FI.arguments())
4530       I.info = classifyArgumentType(I.type);
4531   }
4532 
4533   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4534                     QualType Ty) const override;
4535 };
4536 
4537 class AIXTargetCodeGenInfo : public TargetCodeGenInfo {
4538   const bool Is64Bit;
4539 
4540 public:
4541   AIXTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool Is64Bit)
4542       : TargetCodeGenInfo(std::make_unique<AIXABIInfo>(CGT, Is64Bit)),
4543         Is64Bit(Is64Bit) {}
4544   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4545     return 1; // r1 is the dedicated stack pointer
4546   }
4547 
4548   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4549                                llvm::Value *Address) const override;
4550 };
4551 } // namespace
4552 
4553 // Return true if the ABI requires Ty to be passed sign- or zero-
4554 // extended to 32/64 bits.
4555 bool AIXABIInfo::isPromotableTypeForABI(QualType Ty) const {
4556   // Treat an enum type as its underlying type.
4557   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4558     Ty = EnumTy->getDecl()->getIntegerType();
4559 
4560   // Promotable integer types are required to be promoted by the ABI.
4561   if (Ty->isPromotableIntegerType())
4562     return true;
4563 
4564   if (!Is64Bit)
4565     return false;
4566 
4567   // For 64 bit mode, in addition to the usual promotable integer types, we also
4568   // need to extend all 32-bit types, since the ABI requires promotion to 64
4569   // bits.
4570   if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
4571     switch (BT->getKind()) {
4572     case BuiltinType::Int:
4573     case BuiltinType::UInt:
4574       return true;
4575     default:
4576       break;
4577     }
4578 
4579   return false;
4580 }
4581 
4582 ABIArgInfo AIXABIInfo::classifyReturnType(QualType RetTy) const {
4583   if (RetTy->isAnyComplexType())
4584     return ABIArgInfo::getDirect();
4585 
4586   if (RetTy->isVectorType())
4587     return ABIArgInfo::getDirect();
4588 
4589   if (RetTy->isVoidType())
4590     return ABIArgInfo::getIgnore();
4591 
4592   if (isAggregateTypeForABI(RetTy))
4593     return getNaturalAlignIndirect(RetTy);
4594 
4595   return (isPromotableTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
4596                                         : ABIArgInfo::getDirect());
4597 }
4598 
4599 ABIArgInfo AIXABIInfo::classifyArgumentType(QualType Ty) const {
4600   Ty = useFirstFieldIfTransparentUnion(Ty);
4601 
4602   if (Ty->isAnyComplexType())
4603     return ABIArgInfo::getDirect();
4604 
4605   if (Ty->isVectorType())
4606     return ABIArgInfo::getDirect();
4607 
4608   if (isAggregateTypeForABI(Ty)) {
4609     // Records with non-trivial destructors/copy-constructors should not be
4610     // passed by value.
4611     if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
4612       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
4613 
4614     CharUnits CCAlign = getParamTypeAlignment(Ty);
4615     CharUnits TyAlign = getContext().getTypeAlignInChars(Ty);
4616 
4617     return ABIArgInfo::getIndirect(CCAlign, /*ByVal*/ true,
4618                                    /*Realign*/ TyAlign > CCAlign);
4619   }
4620 
4621   return (isPromotableTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
4622                                      : ABIArgInfo::getDirect());
4623 }
4624 
4625 CharUnits AIXABIInfo::getParamTypeAlignment(QualType Ty) const {
4626   // Complex types are passed just like their elements.
4627   if (const ComplexType *CTy = Ty->getAs<ComplexType>())
4628     Ty = CTy->getElementType();
4629 
4630   if (Ty->isVectorType())
4631     return CharUnits::fromQuantity(16);
4632 
4633   // If the structure contains a vector type, the alignment is 16.
4634   if (isRecordWithSIMDVectorType(getContext(), Ty))
4635     return CharUnits::fromQuantity(16);
4636 
4637   return CharUnits::fromQuantity(PtrByteSize);
4638 }
4639 
4640 Address AIXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4641                               QualType Ty) const {
4642 
4643   auto TypeInfo = getContext().getTypeInfoInChars(Ty);
4644   TypeInfo.Align = getParamTypeAlignment(Ty);
4645 
4646   CharUnits SlotSize = CharUnits::fromQuantity(PtrByteSize);
4647 
4648   // If we have a complex type and the base type is smaller than the register
4649   // size, the ABI calls for the real and imaginary parts to be right-adjusted
4650   // in separate words in 32bit mode or doublewords in 64bit mode. However,
4651   // Clang expects us to produce a pointer to a structure with the two parts
4652   // packed tightly. So generate loads of the real and imaginary parts relative
4653   // to the va_list pointer, and store them to a temporary structure. We do the
4654   // same as the PPC64ABI here.
4655   if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
4656     CharUnits EltSize = TypeInfo.Width / 2;
4657     if (EltSize < SlotSize)
4658       return complexTempStructure(CGF, VAListAddr, Ty, SlotSize, EltSize, CTy);
4659   }
4660 
4661   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false, TypeInfo,
4662                           SlotSize, /*AllowHigher*/ true);
4663 }
4664 
4665 bool AIXTargetCodeGenInfo::initDwarfEHRegSizeTable(
4666     CodeGen::CodeGenFunction &CGF, llvm::Value *Address) const {
4667   return PPC_initDwarfEHRegSizeTable(CGF, Address, Is64Bit, /*IsAIX*/ true);
4668 }
4669 
4670 // PowerPC-32
4671 namespace {
4672 /// PPC32_SVR4_ABIInfo - The 32-bit PowerPC ELF (SVR4) ABI information.
4673 class PPC32_SVR4_ABIInfo : public DefaultABIInfo {
4674   bool IsSoftFloatABI;
4675   bool IsRetSmallStructInRegABI;
4676 
4677   CharUnits getParamTypeAlignment(QualType Ty) const;
4678 
4679 public:
4680   PPC32_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, bool SoftFloatABI,
4681                      bool RetSmallStructInRegABI)
4682       : DefaultABIInfo(CGT), IsSoftFloatABI(SoftFloatABI),
4683         IsRetSmallStructInRegABI(RetSmallStructInRegABI) {}
4684 
4685   ABIArgInfo classifyReturnType(QualType RetTy) const;
4686 
4687   void computeInfo(CGFunctionInfo &FI) const override {
4688     if (!getCXXABI().classifyReturnType(FI))
4689       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
4690     for (auto &I : FI.arguments())
4691       I.info = classifyArgumentType(I.type);
4692   }
4693 
4694   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4695                     QualType Ty) const override;
4696 };
4697 
4698 class PPC32TargetCodeGenInfo : public TargetCodeGenInfo {
4699 public:
4700   PPC32TargetCodeGenInfo(CodeGenTypes &CGT, bool SoftFloatABI,
4701                          bool RetSmallStructInRegABI)
4702       : TargetCodeGenInfo(std::make_unique<PPC32_SVR4_ABIInfo>(
4703             CGT, SoftFloatABI, RetSmallStructInRegABI)) {}
4704 
4705   static bool isStructReturnInRegABI(const llvm::Triple &Triple,
4706                                      const CodeGenOptions &Opts);
4707 
4708   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4709     // This is recovered from gcc output.
4710     return 1; // r1 is the dedicated stack pointer
4711   }
4712 
4713   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4714                                llvm::Value *Address) const override;
4715 };
4716 }
4717 
4718 CharUnits PPC32_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const {
4719   // Complex types are passed just like their elements.
4720   if (const ComplexType *CTy = Ty->getAs<ComplexType>())
4721     Ty = CTy->getElementType();
4722 
4723   if (Ty->isVectorType())
4724     return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16
4725                                                                        : 4);
4726 
4727   // For single-element float/vector structs, we consider the whole type
4728   // to have the same alignment requirements as its single element.
4729   const Type *AlignTy = nullptr;
4730   if (const Type *EltType = isSingleElementStruct(Ty, getContext())) {
4731     const BuiltinType *BT = EltType->getAs<BuiltinType>();
4732     if ((EltType->isVectorType() && getContext().getTypeSize(EltType) == 128) ||
4733         (BT && BT->isFloatingPoint()))
4734       AlignTy = EltType;
4735   }
4736 
4737   if (AlignTy)
4738     return CharUnits::fromQuantity(AlignTy->isVectorType() ? 16 : 4);
4739   return CharUnits::fromQuantity(4);
4740 }
4741 
4742 ABIArgInfo PPC32_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
4743   uint64_t Size;
4744 
4745   // -msvr4-struct-return puts small aggregates in GPR3 and GPR4.
4746   if (isAggregateTypeForABI(RetTy) && IsRetSmallStructInRegABI &&
4747       (Size = getContext().getTypeSize(RetTy)) <= 64) {
4748     // System V ABI (1995), page 3-22, specified:
4749     // > A structure or union whose size is less than or equal to 8 bytes
4750     // > shall be returned in r3 and r4, as if it were first stored in the
4751     // > 8-byte aligned memory area and then the low addressed word were
4752     // > loaded into r3 and the high-addressed word into r4.  Bits beyond
4753     // > the last member of the structure or union are not defined.
4754     //
4755     // GCC for big-endian PPC32 inserts the pad before the first member,
4756     // not "beyond the last member" of the struct.  To stay compatible
4757     // with GCC, we coerce the struct to an integer of the same size.
4758     // LLVM will extend it and return i32 in r3, or i64 in r3:r4.
4759     if (Size == 0)
4760       return ABIArgInfo::getIgnore();
4761     else {
4762       llvm::Type *CoerceTy = llvm::Type::getIntNTy(getVMContext(), Size);
4763       return ABIArgInfo::getDirect(CoerceTy);
4764     }
4765   }
4766 
4767   return DefaultABIInfo::classifyReturnType(RetTy);
4768 }
4769 
4770 // TODO: this implementation is now likely redundant with
4771 // DefaultABIInfo::EmitVAArg.
4772 Address PPC32_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAList,
4773                                       QualType Ty) const {
4774   if (getTarget().getTriple().isOSDarwin()) {
4775     auto TI = getContext().getTypeInfoInChars(Ty);
4776     TI.Align = getParamTypeAlignment(Ty);
4777 
4778     CharUnits SlotSize = CharUnits::fromQuantity(4);
4779     return emitVoidPtrVAArg(CGF, VAList, Ty,
4780                             classifyArgumentType(Ty).isIndirect(), TI, SlotSize,
4781                             /*AllowHigherAlign=*/true);
4782   }
4783 
4784   const unsigned OverflowLimit = 8;
4785   if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
4786     // TODO: Implement this. For now ignore.
4787     (void)CTy;
4788     return Address::invalid(); // FIXME?
4789   }
4790 
4791   // struct __va_list_tag {
4792   //   unsigned char gpr;
4793   //   unsigned char fpr;
4794   //   unsigned short reserved;
4795   //   void *overflow_arg_area;
4796   //   void *reg_save_area;
4797   // };
4798 
4799   bool isI64 = Ty->isIntegerType() && getContext().getTypeSize(Ty) == 64;
4800   bool isInt = !Ty->isFloatingType();
4801   bool isF64 = Ty->isFloatingType() && getContext().getTypeSize(Ty) == 64;
4802 
4803   // All aggregates are passed indirectly?  That doesn't seem consistent
4804   // with the argument-lowering code.
4805   bool isIndirect = isAggregateTypeForABI(Ty);
4806 
4807   CGBuilderTy &Builder = CGF.Builder;
4808 
4809   // The calling convention either uses 1-2 GPRs or 1 FPR.
4810   Address NumRegsAddr = Address::invalid();
4811   if (isInt || IsSoftFloatABI) {
4812     NumRegsAddr = Builder.CreateStructGEP(VAList, 0, "gpr");
4813   } else {
4814     NumRegsAddr = Builder.CreateStructGEP(VAList, 1, "fpr");
4815   }
4816 
4817   llvm::Value *NumRegs = Builder.CreateLoad(NumRegsAddr, "numUsedRegs");
4818 
4819   // "Align" the register count when TY is i64.
4820   if (isI64 || (isF64 && IsSoftFloatABI)) {
4821     NumRegs = Builder.CreateAdd(NumRegs, Builder.getInt8(1));
4822     NumRegs = Builder.CreateAnd(NumRegs, Builder.getInt8((uint8_t) ~1U));
4823   }
4824 
4825   llvm::Value *CC =
4826       Builder.CreateICmpULT(NumRegs, Builder.getInt8(OverflowLimit), "cond");
4827 
4828   llvm::BasicBlock *UsingRegs = CGF.createBasicBlock("using_regs");
4829   llvm::BasicBlock *UsingOverflow = CGF.createBasicBlock("using_overflow");
4830   llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
4831 
4832   Builder.CreateCondBr(CC, UsingRegs, UsingOverflow);
4833 
4834   llvm::Type *DirectTy = CGF.ConvertType(Ty), *ElementTy = DirectTy;
4835   if (isIndirect) DirectTy = DirectTy->getPointerTo(0);
4836 
4837   // Case 1: consume registers.
4838   Address RegAddr = Address::invalid();
4839   {
4840     CGF.EmitBlock(UsingRegs);
4841 
4842     Address RegSaveAreaPtr = Builder.CreateStructGEP(VAList, 4);
4843     RegAddr = Address(Builder.CreateLoad(RegSaveAreaPtr), CGF.Int8Ty,
4844                       CharUnits::fromQuantity(8));
4845     assert(RegAddr.getElementType() == CGF.Int8Ty);
4846 
4847     // Floating-point registers start after the general-purpose registers.
4848     if (!(isInt || IsSoftFloatABI)) {
4849       RegAddr = Builder.CreateConstInBoundsByteGEP(RegAddr,
4850                                                    CharUnits::fromQuantity(32));
4851     }
4852 
4853     // Get the address of the saved value by scaling the number of
4854     // registers we've used by the number of
4855     CharUnits RegSize = CharUnits::fromQuantity((isInt || IsSoftFloatABI) ? 4 : 8);
4856     llvm::Value *RegOffset =
4857         Builder.CreateMul(NumRegs, Builder.getInt8(RegSize.getQuantity()));
4858     RegAddr = Address(
4859         Builder.CreateInBoundsGEP(CGF.Int8Ty, RegAddr.getPointer(), RegOffset),
4860         CGF.Int8Ty, RegAddr.getAlignment().alignmentOfArrayElement(RegSize));
4861     RegAddr = Builder.CreateElementBitCast(RegAddr, DirectTy);
4862 
4863     // Increase the used-register count.
4864     NumRegs =
4865       Builder.CreateAdd(NumRegs,
4866                         Builder.getInt8((isI64 || (isF64 && IsSoftFloatABI)) ? 2 : 1));
4867     Builder.CreateStore(NumRegs, NumRegsAddr);
4868 
4869     CGF.EmitBranch(Cont);
4870   }
4871 
4872   // Case 2: consume space in the overflow area.
4873   Address MemAddr = Address::invalid();
4874   {
4875     CGF.EmitBlock(UsingOverflow);
4876 
4877     Builder.CreateStore(Builder.getInt8(OverflowLimit), NumRegsAddr);
4878 
4879     // Everything in the overflow area is rounded up to a size of at least 4.
4880     CharUnits OverflowAreaAlign = CharUnits::fromQuantity(4);
4881 
4882     CharUnits Size;
4883     if (!isIndirect) {
4884       auto TypeInfo = CGF.getContext().getTypeInfoInChars(Ty);
4885       Size = TypeInfo.Width.alignTo(OverflowAreaAlign);
4886     } else {
4887       Size = CGF.getPointerSize();
4888     }
4889 
4890     Address OverflowAreaAddr = Builder.CreateStructGEP(VAList, 3);
4891     Address OverflowArea =
4892         Address(Builder.CreateLoad(OverflowAreaAddr, "argp.cur"), CGF.Int8Ty,
4893                 OverflowAreaAlign);
4894     // Round up address of argument to alignment
4895     CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
4896     if (Align > OverflowAreaAlign) {
4897       llvm::Value *Ptr = OverflowArea.getPointer();
4898       OverflowArea = Address(emitRoundPointerUpToAlignment(CGF, Ptr, Align),
4899                              OverflowArea.getElementType(), Align);
4900     }
4901 
4902     MemAddr = Builder.CreateElementBitCast(OverflowArea, DirectTy);
4903 
4904     // Increase the overflow area.
4905     OverflowArea = Builder.CreateConstInBoundsByteGEP(OverflowArea, Size);
4906     Builder.CreateStore(OverflowArea.getPointer(), OverflowAreaAddr);
4907     CGF.EmitBranch(Cont);
4908   }
4909 
4910   CGF.EmitBlock(Cont);
4911 
4912   // Merge the cases with a phi.
4913   Address Result = emitMergePHI(CGF, RegAddr, UsingRegs, MemAddr, UsingOverflow,
4914                                 "vaarg.addr");
4915 
4916   // Load the pointer if the argument was passed indirectly.
4917   if (isIndirect) {
4918     Result = Address(Builder.CreateLoad(Result, "aggr"), ElementTy,
4919                      getContext().getTypeAlignInChars(Ty));
4920   }
4921 
4922   return Result;
4923 }
4924 
4925 bool PPC32TargetCodeGenInfo::isStructReturnInRegABI(
4926     const llvm::Triple &Triple, const CodeGenOptions &Opts) {
4927   assert(Triple.isPPC32());
4928 
4929   switch (Opts.getStructReturnConvention()) {
4930   case CodeGenOptions::SRCK_Default:
4931     break;
4932   case CodeGenOptions::SRCK_OnStack: // -maix-struct-return
4933     return false;
4934   case CodeGenOptions::SRCK_InRegs: // -msvr4-struct-return
4935     return true;
4936   }
4937 
4938   if (Triple.isOSBinFormatELF() && !Triple.isOSLinux())
4939     return true;
4940 
4941   return false;
4942 }
4943 
4944 bool
4945 PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4946                                                 llvm::Value *Address) const {
4947   return PPC_initDwarfEHRegSizeTable(CGF, Address, /*Is64Bit*/ false,
4948                                      /*IsAIX*/ false);
4949 }
4950 
4951 // PowerPC-64
4952 
4953 namespace {
4954 /// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
4955 class PPC64_SVR4_ABIInfo : public SwiftABIInfo {
4956 public:
4957   enum ABIKind {
4958     ELFv1 = 0,
4959     ELFv2
4960   };
4961 
4962 private:
4963   static const unsigned GPRBits = 64;
4964   ABIKind Kind;
4965   bool IsSoftFloatABI;
4966 
4967 public:
4968   PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind,
4969                      bool SoftFloatABI)
4970       : SwiftABIInfo(CGT), Kind(Kind), IsSoftFloatABI(SoftFloatABI) {}
4971 
4972   bool isPromotableTypeForABI(QualType Ty) const;
4973   CharUnits getParamTypeAlignment(QualType Ty) const;
4974 
4975   ABIArgInfo classifyReturnType(QualType RetTy) const;
4976   ABIArgInfo classifyArgumentType(QualType Ty) const;
4977 
4978   bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4979   bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4980                                          uint64_t Members) const override;
4981 
4982   // TODO: We can add more logic to computeInfo to improve performance.
4983   // Example: For aggregate arguments that fit in a register, we could
4984   // use getDirectInReg (as is done below for structs containing a single
4985   // floating-point value) to avoid pushing them to memory on function
4986   // entry.  This would require changing the logic in PPCISelLowering
4987   // when lowering the parameters in the caller and args in the callee.
4988   void computeInfo(CGFunctionInfo &FI) const override {
4989     if (!getCXXABI().classifyReturnType(FI))
4990       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
4991     for (auto &I : FI.arguments()) {
4992       // We rely on the default argument classification for the most part.
4993       // One exception:  An aggregate containing a single floating-point
4994       // or vector item must be passed in a register if one is available.
4995       const Type *T = isSingleElementStruct(I.type, getContext());
4996       if (T) {
4997         const BuiltinType *BT = T->getAs<BuiltinType>();
4998         if ((T->isVectorType() && getContext().getTypeSize(T) == 128) ||
4999             (BT && BT->isFloatingPoint())) {
5000           QualType QT(T, 0);
5001           I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
5002           continue;
5003         }
5004       }
5005       I.info = classifyArgumentType(I.type);
5006     }
5007   }
5008 
5009   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5010                     QualType Ty) const override;
5011 
5012   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
5013                                     bool asReturnValue) const override {
5014     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
5015   }
5016 
5017   bool isSwiftErrorInRegister() const override {
5018     return false;
5019   }
5020 };
5021 
5022 class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
5023 
5024 public:
5025   PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT,
5026                                PPC64_SVR4_ABIInfo::ABIKind Kind,
5027                                bool SoftFloatABI)
5028       : TargetCodeGenInfo(
5029             std::make_unique<PPC64_SVR4_ABIInfo>(CGT, Kind, SoftFloatABI)) {}
5030 
5031   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
5032     // This is recovered from gcc output.
5033     return 1; // r1 is the dedicated stack pointer
5034   }
5035 
5036   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
5037                                llvm::Value *Address) const override;
5038 };
5039 
5040 class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
5041 public:
5042   PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
5043 
5044   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
5045     // This is recovered from gcc output.
5046     return 1; // r1 is the dedicated stack pointer
5047   }
5048 
5049   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
5050                                llvm::Value *Address) const override;
5051 };
5052 
5053 }
5054 
5055 // Return true if the ABI requires Ty to be passed sign- or zero-
5056 // extended to 64 bits.
5057 bool
5058 PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
5059   // Treat an enum type as its underlying type.
5060   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5061     Ty = EnumTy->getDecl()->getIntegerType();
5062 
5063   // Promotable integer types are required to be promoted by the ABI.
5064   if (isPromotableIntegerTypeForABI(Ty))
5065     return true;
5066 
5067   // In addition to the usual promotable integer types, we also need to
5068   // extend all 32-bit types, since the ABI requires promotion to 64 bits.
5069   if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
5070     switch (BT->getKind()) {
5071     case BuiltinType::Int:
5072     case BuiltinType::UInt:
5073       return true;
5074     default:
5075       break;
5076     }
5077 
5078   if (const auto *EIT = Ty->getAs<BitIntType>())
5079     if (EIT->getNumBits() < 64)
5080       return true;
5081 
5082   return false;
5083 }
5084 
5085 /// isAlignedParamType - Determine whether a type requires 16-byte or
5086 /// higher alignment in the parameter area.  Always returns at least 8.
5087 CharUnits PPC64_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const {
5088   // Complex types are passed just like their elements.
5089   if (const ComplexType *CTy = Ty->getAs<ComplexType>())
5090     Ty = CTy->getElementType();
5091 
5092   auto FloatUsesVector = [this](QualType Ty){
5093     return Ty->isRealFloatingType() && &getContext().getFloatTypeSemantics(
5094                                            Ty) == &llvm::APFloat::IEEEquad();
5095   };
5096 
5097   // Only vector types of size 16 bytes need alignment (larger types are
5098   // passed via reference, smaller types are not aligned).
5099   if (Ty->isVectorType()) {
5100     return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16 : 8);
5101   } else if (FloatUsesVector(Ty)) {
5102     // According to ABI document section 'Optional Save Areas': If extended
5103     // precision floating-point values in IEEE BINARY 128 QUADRUPLE PRECISION
5104     // format are supported, map them to a single quadword, quadword aligned.
5105     return CharUnits::fromQuantity(16);
5106   }
5107 
5108   // For single-element float/vector structs, we consider the whole type
5109   // to have the same alignment requirements as its single element.
5110   const Type *AlignAsType = nullptr;
5111   const Type *EltType = isSingleElementStruct(Ty, getContext());
5112   if (EltType) {
5113     const BuiltinType *BT = EltType->getAs<BuiltinType>();
5114     if ((EltType->isVectorType() && getContext().getTypeSize(EltType) == 128) ||
5115         (BT && BT->isFloatingPoint()))
5116       AlignAsType = EltType;
5117   }
5118 
5119   // Likewise for ELFv2 homogeneous aggregates.
5120   const Type *Base = nullptr;
5121   uint64_t Members = 0;
5122   if (!AlignAsType && Kind == ELFv2 &&
5123       isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members))
5124     AlignAsType = Base;
5125 
5126   // With special case aggregates, only vector base types need alignment.
5127   if (AlignAsType) {
5128     bool UsesVector = AlignAsType->isVectorType() ||
5129                       FloatUsesVector(QualType(AlignAsType, 0));
5130     return CharUnits::fromQuantity(UsesVector ? 16 : 8);
5131   }
5132 
5133   // Otherwise, we only need alignment for any aggregate type that
5134   // has an alignment requirement of >= 16 bytes.
5135   if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128) {
5136     return CharUnits::fromQuantity(16);
5137   }
5138 
5139   return CharUnits::fromQuantity(8);
5140 }
5141 
5142 /// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous
5143 /// aggregate.  Base is set to the base element type, and Members is set
5144 /// to the number of base elements.
5145 bool ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base,
5146                                      uint64_t &Members) const {
5147   if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
5148     uint64_t NElements = AT->getSize().getZExtValue();
5149     if (NElements == 0)
5150       return false;
5151     if (!isHomogeneousAggregate(AT->getElementType(), Base, Members))
5152       return false;
5153     Members *= NElements;
5154   } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
5155     const RecordDecl *RD = RT->getDecl();
5156     if (RD->hasFlexibleArrayMember())
5157       return false;
5158 
5159     Members = 0;
5160 
5161     // If this is a C++ record, check the properties of the record such as
5162     // bases and ABI specific restrictions
5163     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
5164       if (!getCXXABI().isPermittedToBeHomogeneousAggregate(CXXRD))
5165         return false;
5166 
5167       for (const auto &I : CXXRD->bases()) {
5168         // Ignore empty records.
5169         if (isEmptyRecord(getContext(), I.getType(), true))
5170           continue;
5171 
5172         uint64_t FldMembers;
5173         if (!isHomogeneousAggregate(I.getType(), Base, FldMembers))
5174           return false;
5175 
5176         Members += FldMembers;
5177       }
5178     }
5179 
5180     for (const auto *FD : RD->fields()) {
5181       // Ignore (non-zero arrays of) empty records.
5182       QualType FT = FD->getType();
5183       while (const ConstantArrayType *AT =
5184              getContext().getAsConstantArrayType(FT)) {
5185         if (AT->getSize().getZExtValue() == 0)
5186           return false;
5187         FT = AT->getElementType();
5188       }
5189       if (isEmptyRecord(getContext(), FT, true))
5190         continue;
5191 
5192       // For compatibility with GCC, ignore empty bitfields in C++ mode.
5193       if (getContext().getLangOpts().CPlusPlus &&
5194           FD->isZeroLengthBitField(getContext()))
5195         continue;
5196 
5197       uint64_t FldMembers;
5198       if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers))
5199         return false;
5200 
5201       Members = (RD->isUnion() ?
5202                  std::max(Members, FldMembers) : Members + FldMembers);
5203     }
5204 
5205     if (!Base)
5206       return false;
5207 
5208     // Ensure there is no padding.
5209     if (getContext().getTypeSize(Base) * Members !=
5210         getContext().getTypeSize(Ty))
5211       return false;
5212   } else {
5213     Members = 1;
5214     if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
5215       Members = 2;
5216       Ty = CT->getElementType();
5217     }
5218 
5219     // Most ABIs only support float, double, and some vector type widths.
5220     if (!isHomogeneousAggregateBaseType(Ty))
5221       return false;
5222 
5223     // The base type must be the same for all members.  Types that
5224     // agree in both total size and mode (float vs. vector) are
5225     // treated as being equivalent here.
5226     const Type *TyPtr = Ty.getTypePtr();
5227     if (!Base) {
5228       Base = TyPtr;
5229       // If it's a non-power-of-2 vector, its size is already a power-of-2,
5230       // so make sure to widen it explicitly.
5231       if (const VectorType *VT = Base->getAs<VectorType>()) {
5232         QualType EltTy = VT->getElementType();
5233         unsigned NumElements =
5234             getContext().getTypeSize(VT) / getContext().getTypeSize(EltTy);
5235         Base = getContext()
5236                    .getVectorType(EltTy, NumElements, VT->getVectorKind())
5237                    .getTypePtr();
5238       }
5239     }
5240 
5241     if (Base->isVectorType() != TyPtr->isVectorType() ||
5242         getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr))
5243       return false;
5244   }
5245   return Members > 0 && isHomogeneousAggregateSmallEnough(Base, Members);
5246 }
5247 
5248 bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
5249   // Homogeneous aggregates for ELFv2 must have base types of float,
5250   // double, long double, or 128-bit vectors.
5251   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
5252     if (BT->getKind() == BuiltinType::Float ||
5253         BT->getKind() == BuiltinType::Double ||
5254         BT->getKind() == BuiltinType::LongDouble ||
5255         BT->getKind() == BuiltinType::Ibm128 ||
5256         (getContext().getTargetInfo().hasFloat128Type() &&
5257          (BT->getKind() == BuiltinType::Float128))) {
5258       if (IsSoftFloatABI)
5259         return false;
5260       return true;
5261     }
5262   }
5263   if (const VectorType *VT = Ty->getAs<VectorType>()) {
5264     if (getContext().getTypeSize(VT) == 128)
5265       return true;
5266   }
5267   return false;
5268 }
5269 
5270 bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateSmallEnough(
5271     const Type *Base, uint64_t Members) const {
5272   // Vector and fp128 types require one register, other floating point types
5273   // require one or two registers depending on their size.
5274   uint32_t NumRegs =
5275       ((getContext().getTargetInfo().hasFloat128Type() &&
5276           Base->isFloat128Type()) ||
5277         Base->isVectorType()) ? 1
5278                               : (getContext().getTypeSize(Base) + 63) / 64;
5279 
5280   // Homogeneous Aggregates may occupy at most 8 registers.
5281   return Members * NumRegs <= 8;
5282 }
5283 
5284 ABIArgInfo
5285 PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
5286   Ty = useFirstFieldIfTransparentUnion(Ty);
5287 
5288   if (Ty->isAnyComplexType())
5289     return ABIArgInfo::getDirect();
5290 
5291   // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes)
5292   // or via reference (larger than 16 bytes).
5293   if (Ty->isVectorType()) {
5294     uint64_t Size = getContext().getTypeSize(Ty);
5295     if (Size > 128)
5296       return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
5297     else if (Size < 128) {
5298       llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
5299       return ABIArgInfo::getDirect(CoerceTy);
5300     }
5301   }
5302 
5303   if (const auto *EIT = Ty->getAs<BitIntType>())
5304     if (EIT->getNumBits() > 128)
5305       return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
5306 
5307   if (isAggregateTypeForABI(Ty)) {
5308     if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
5309       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
5310 
5311     uint64_t ABIAlign = getParamTypeAlignment(Ty).getQuantity();
5312     uint64_t TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity();
5313 
5314     // ELFv2 homogeneous aggregates are passed as array types.
5315     const Type *Base = nullptr;
5316     uint64_t Members = 0;
5317     if (Kind == ELFv2 &&
5318         isHomogeneousAggregate(Ty, Base, Members)) {
5319       llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
5320       llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
5321       return ABIArgInfo::getDirect(CoerceTy);
5322     }
5323 
5324     // If an aggregate may end up fully in registers, we do not
5325     // use the ByVal method, but pass the aggregate as array.
5326     // This is usually beneficial since we avoid forcing the
5327     // back-end to store the argument to memory.
5328     uint64_t Bits = getContext().getTypeSize(Ty);
5329     if (Bits > 0 && Bits <= 8 * GPRBits) {
5330       llvm::Type *CoerceTy;
5331 
5332       // Types up to 8 bytes are passed as integer type (which will be
5333       // properly aligned in the argument save area doubleword).
5334       if (Bits <= GPRBits)
5335         CoerceTy =
5336             llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
5337       // Larger types are passed as arrays, with the base type selected
5338       // according to the required alignment in the save area.
5339       else {
5340         uint64_t RegBits = ABIAlign * 8;
5341         uint64_t NumRegs = llvm::alignTo(Bits, RegBits) / RegBits;
5342         llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits);
5343         CoerceTy = llvm::ArrayType::get(RegTy, NumRegs);
5344       }
5345 
5346       return ABIArgInfo::getDirect(CoerceTy);
5347     }
5348 
5349     // All other aggregates are passed ByVal.
5350     return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
5351                                    /*ByVal=*/true,
5352                                    /*Realign=*/TyAlign > ABIAlign);
5353   }
5354 
5355   return (isPromotableTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
5356                                      : ABIArgInfo::getDirect());
5357 }
5358 
5359 ABIArgInfo
5360 PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
5361   if (RetTy->isVoidType())
5362     return ABIArgInfo::getIgnore();
5363 
5364   if (RetTy->isAnyComplexType())
5365     return ABIArgInfo::getDirect();
5366 
5367   // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes)
5368   // or via reference (larger than 16 bytes).
5369   if (RetTy->isVectorType()) {
5370     uint64_t Size = getContext().getTypeSize(RetTy);
5371     if (Size > 128)
5372       return getNaturalAlignIndirect(RetTy);
5373     else if (Size < 128) {
5374       llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
5375       return ABIArgInfo::getDirect(CoerceTy);
5376     }
5377   }
5378 
5379   if (const auto *EIT = RetTy->getAs<BitIntType>())
5380     if (EIT->getNumBits() > 128)
5381       return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
5382 
5383   if (isAggregateTypeForABI(RetTy)) {
5384     // ELFv2 homogeneous aggregates are returned as array types.
5385     const Type *Base = nullptr;
5386     uint64_t Members = 0;
5387     if (Kind == ELFv2 &&
5388         isHomogeneousAggregate(RetTy, Base, Members)) {
5389       llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
5390       llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
5391       return ABIArgInfo::getDirect(CoerceTy);
5392     }
5393 
5394     // ELFv2 small aggregates are returned in up to two registers.
5395     uint64_t Bits = getContext().getTypeSize(RetTy);
5396     if (Kind == ELFv2 && Bits <= 2 * GPRBits) {
5397       if (Bits == 0)
5398         return ABIArgInfo::getIgnore();
5399 
5400       llvm::Type *CoerceTy;
5401       if (Bits > GPRBits) {
5402         CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits);
5403         CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy);
5404       } else
5405         CoerceTy =
5406             llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
5407       return ABIArgInfo::getDirect(CoerceTy);
5408     }
5409 
5410     // All other aggregates are returned indirectly.
5411     return getNaturalAlignIndirect(RetTy);
5412   }
5413 
5414   return (isPromotableTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
5415                                         : ABIArgInfo::getDirect());
5416 }
5417 
5418 // Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
5419 Address PPC64_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5420                                       QualType Ty) const {
5421   auto TypeInfo = getContext().getTypeInfoInChars(Ty);
5422   TypeInfo.Align = getParamTypeAlignment(Ty);
5423 
5424   CharUnits SlotSize = CharUnits::fromQuantity(8);
5425 
5426   // If we have a complex type and the base type is smaller than 8 bytes,
5427   // the ABI calls for the real and imaginary parts to be right-adjusted
5428   // in separate doublewords.  However, Clang expects us to produce a
5429   // pointer to a structure with the two parts packed tightly.  So generate
5430   // loads of the real and imaginary parts relative to the va_list pointer,
5431   // and store them to a temporary structure.
5432   if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
5433     CharUnits EltSize = TypeInfo.Width / 2;
5434     if (EltSize < SlotSize)
5435       return complexTempStructure(CGF, VAListAddr, Ty, SlotSize, EltSize, CTy);
5436   }
5437 
5438   // Otherwise, just use the general rule.
5439   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
5440                           TypeInfo, SlotSize, /*AllowHigher*/ true);
5441 }
5442 
5443 bool
5444 PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
5445   CodeGen::CodeGenFunction &CGF,
5446   llvm::Value *Address) const {
5447   return PPC_initDwarfEHRegSizeTable(CGF, Address, /*Is64Bit*/ true,
5448                                      /*IsAIX*/ false);
5449 }
5450 
5451 bool
5452 PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
5453                                                 llvm::Value *Address) const {
5454   return PPC_initDwarfEHRegSizeTable(CGF, Address, /*Is64Bit*/ true,
5455                                      /*IsAIX*/ false);
5456 }
5457 
5458 //===----------------------------------------------------------------------===//
5459 // AArch64 ABI Implementation
5460 //===----------------------------------------------------------------------===//
5461 
5462 namespace {
5463 
5464 class AArch64ABIInfo : public SwiftABIInfo {
5465 public:
5466   enum ABIKind {
5467     AAPCS = 0,
5468     DarwinPCS,
5469     Win64
5470   };
5471 
5472 private:
5473   ABIKind Kind;
5474 
5475 public:
5476   AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind)
5477     : SwiftABIInfo(CGT), Kind(Kind) {}
5478 
5479 private:
5480   ABIKind getABIKind() const { return Kind; }
5481   bool isDarwinPCS() const { return Kind == DarwinPCS; }
5482 
5483   ABIArgInfo classifyReturnType(QualType RetTy, bool IsVariadic) const;
5484   ABIArgInfo classifyArgumentType(QualType RetTy, bool IsVariadic,
5485                                   unsigned CallingConvention) const;
5486   ABIArgInfo coerceIllegalVector(QualType Ty) const;
5487   bool isHomogeneousAggregateBaseType(QualType Ty) const override;
5488   bool isHomogeneousAggregateSmallEnough(const Type *Ty,
5489                                          uint64_t Members) const override;
5490 
5491   bool isIllegalVectorType(QualType Ty) const;
5492 
5493   void computeInfo(CGFunctionInfo &FI) const override {
5494     if (!::classifyReturnType(getCXXABI(), FI, *this))
5495       FI.getReturnInfo() =
5496           classifyReturnType(FI.getReturnType(), FI.isVariadic());
5497 
5498     for (auto &it : FI.arguments())
5499       it.info = classifyArgumentType(it.type, FI.isVariadic(),
5500                                      FI.getCallingConvention());
5501   }
5502 
5503   Address EmitDarwinVAArg(Address VAListAddr, QualType Ty,
5504                           CodeGenFunction &CGF) const;
5505 
5506   Address EmitAAPCSVAArg(Address VAListAddr, QualType Ty,
5507                          CodeGenFunction &CGF) const;
5508 
5509   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5510                     QualType Ty) const override {
5511     llvm::Type *BaseTy = CGF.ConvertType(Ty);
5512     if (isa<llvm::ScalableVectorType>(BaseTy))
5513       llvm::report_fatal_error("Passing SVE types to variadic functions is "
5514                                "currently not supported");
5515 
5516     return Kind == Win64 ? EmitMSVAArg(CGF, VAListAddr, Ty)
5517                          : isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF)
5518                                          : EmitAAPCSVAArg(VAListAddr, Ty, CGF);
5519   }
5520 
5521   Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
5522                       QualType Ty) const override;
5523 
5524   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
5525                                     bool asReturnValue) const override {
5526     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
5527   }
5528   bool isSwiftErrorInRegister() const override {
5529     return true;
5530   }
5531 
5532   bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy,
5533                                  unsigned elts) const override;
5534 
5535   bool allowBFloatArgsAndRet() const override {
5536     return getTarget().hasBFloat16Type();
5537   }
5538 };
5539 
5540 class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
5541 public:
5542   AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind)
5543       : TargetCodeGenInfo(std::make_unique<AArch64ABIInfo>(CGT, Kind)) {}
5544 
5545   StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
5546     return "mov\tfp, fp\t\t// marker for objc_retainAutoreleaseReturnValue";
5547   }
5548 
5549   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
5550     return 31;
5551   }
5552 
5553   bool doesReturnSlotInterfereWithArgs() const override { return false; }
5554 
5555   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5556                            CodeGen::CodeGenModule &CGM) const override {
5557     const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
5558     if (!FD)
5559       return;
5560 
5561     const auto *TA = FD->getAttr<TargetAttr>();
5562     if (TA == nullptr)
5563       return;
5564 
5565     ParsedTargetAttr Attr = TA->parse();
5566     if (Attr.BranchProtection.empty())
5567       return;
5568 
5569     TargetInfo::BranchProtectionInfo BPI;
5570     StringRef Error;
5571     (void)CGM.getTarget().validateBranchProtection(
5572         Attr.BranchProtection, Attr.Architecture, BPI, Error);
5573     assert(Error.empty());
5574 
5575     auto *Fn = cast<llvm::Function>(GV);
5576     static const char *SignReturnAddrStr[] = {"none", "non-leaf", "all"};
5577     Fn->addFnAttr("sign-return-address", SignReturnAddrStr[static_cast<int>(BPI.SignReturnAddr)]);
5578 
5579     if (BPI.SignReturnAddr != LangOptions::SignReturnAddressScopeKind::None) {
5580       Fn->addFnAttr("sign-return-address-key",
5581                     BPI.SignKey == LangOptions::SignReturnAddressKeyKind::AKey
5582                         ? "a_key"
5583                         : "b_key");
5584     }
5585 
5586     Fn->addFnAttr("branch-target-enforcement",
5587                   BPI.BranchTargetEnforcement ? "true" : "false");
5588   }
5589 
5590   bool isScalarizableAsmOperand(CodeGen::CodeGenFunction &CGF,
5591                                 llvm::Type *Ty) const override {
5592     if (CGF.getTarget().hasFeature("ls64")) {
5593       auto *ST = dyn_cast<llvm::StructType>(Ty);
5594       if (ST && ST->getNumElements() == 1) {
5595         auto *AT = dyn_cast<llvm::ArrayType>(ST->getElementType(0));
5596         if (AT && AT->getNumElements() == 8 &&
5597             AT->getElementType()->isIntegerTy(64))
5598           return true;
5599       }
5600     }
5601     return TargetCodeGenInfo::isScalarizableAsmOperand(CGF, Ty);
5602   }
5603 };
5604 
5605 class WindowsAArch64TargetCodeGenInfo : public AArch64TargetCodeGenInfo {
5606 public:
5607   WindowsAArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind K)
5608       : AArch64TargetCodeGenInfo(CGT, K) {}
5609 
5610   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5611                            CodeGen::CodeGenModule &CGM) const override;
5612 
5613   void getDependentLibraryOption(llvm::StringRef Lib,
5614                                  llvm::SmallString<24> &Opt) const override {
5615     Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib);
5616   }
5617 
5618   void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value,
5619                                llvm::SmallString<32> &Opt) const override {
5620     Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
5621   }
5622 };
5623 
5624 void WindowsAArch64TargetCodeGenInfo::setTargetAttributes(
5625     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
5626   AArch64TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
5627   if (GV->isDeclaration())
5628     return;
5629   addStackProbeTargetAttributes(D, GV, CGM);
5630 }
5631 }
5632 
5633 ABIArgInfo AArch64ABIInfo::coerceIllegalVector(QualType Ty) const {
5634   assert(Ty->isVectorType() && "expected vector type!");
5635 
5636   const auto *VT = Ty->castAs<VectorType>();
5637   if (VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector) {
5638     assert(VT->getElementType()->isBuiltinType() && "expected builtin type!");
5639     assert(VT->getElementType()->castAs<BuiltinType>()->getKind() ==
5640                BuiltinType::UChar &&
5641            "unexpected builtin type for SVE predicate!");
5642     return ABIArgInfo::getDirect(llvm::ScalableVectorType::get(
5643         llvm::Type::getInt1Ty(getVMContext()), 16));
5644   }
5645 
5646   if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector) {
5647     assert(VT->getElementType()->isBuiltinType() && "expected builtin type!");
5648 
5649     const auto *BT = VT->getElementType()->castAs<BuiltinType>();
5650     llvm::ScalableVectorType *ResType = nullptr;
5651     switch (BT->getKind()) {
5652     default:
5653       llvm_unreachable("unexpected builtin type for SVE vector!");
5654     case BuiltinType::SChar:
5655     case BuiltinType::UChar:
5656       ResType = llvm::ScalableVectorType::get(
5657           llvm::Type::getInt8Ty(getVMContext()), 16);
5658       break;
5659     case BuiltinType::Short:
5660     case BuiltinType::UShort:
5661       ResType = llvm::ScalableVectorType::get(
5662           llvm::Type::getInt16Ty(getVMContext()), 8);
5663       break;
5664     case BuiltinType::Int:
5665     case BuiltinType::UInt:
5666       ResType = llvm::ScalableVectorType::get(
5667           llvm::Type::getInt32Ty(getVMContext()), 4);
5668       break;
5669     case BuiltinType::Long:
5670     case BuiltinType::ULong:
5671       ResType = llvm::ScalableVectorType::get(
5672           llvm::Type::getInt64Ty(getVMContext()), 2);
5673       break;
5674     case BuiltinType::Half:
5675       ResType = llvm::ScalableVectorType::get(
5676           llvm::Type::getHalfTy(getVMContext()), 8);
5677       break;
5678     case BuiltinType::Float:
5679       ResType = llvm::ScalableVectorType::get(
5680           llvm::Type::getFloatTy(getVMContext()), 4);
5681       break;
5682     case BuiltinType::Double:
5683       ResType = llvm::ScalableVectorType::get(
5684           llvm::Type::getDoubleTy(getVMContext()), 2);
5685       break;
5686     case BuiltinType::BFloat16:
5687       ResType = llvm::ScalableVectorType::get(
5688           llvm::Type::getBFloatTy(getVMContext()), 8);
5689       break;
5690     }
5691     return ABIArgInfo::getDirect(ResType);
5692   }
5693 
5694   uint64_t Size = getContext().getTypeSize(Ty);
5695   // Android promotes <2 x i8> to i16, not i32
5696   if (isAndroid() && (Size <= 16)) {
5697     llvm::Type *ResType = llvm::Type::getInt16Ty(getVMContext());
5698     return ABIArgInfo::getDirect(ResType);
5699   }
5700   if (Size <= 32) {
5701     llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext());
5702     return ABIArgInfo::getDirect(ResType);
5703   }
5704   if (Size == 64) {
5705     auto *ResType =
5706         llvm::FixedVectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2);
5707     return ABIArgInfo::getDirect(ResType);
5708   }
5709   if (Size == 128) {
5710     auto *ResType =
5711         llvm::FixedVectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4);
5712     return ABIArgInfo::getDirect(ResType);
5713   }
5714   return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
5715 }
5716 
5717 ABIArgInfo
5718 AArch64ABIInfo::classifyArgumentType(QualType Ty, bool IsVariadic,
5719                                      unsigned CallingConvention) const {
5720   Ty = useFirstFieldIfTransparentUnion(Ty);
5721 
5722   // Handle illegal vector types here.
5723   if (isIllegalVectorType(Ty))
5724     return coerceIllegalVector(Ty);
5725 
5726   if (!isAggregateTypeForABI(Ty)) {
5727     // Treat an enum type as its underlying type.
5728     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5729       Ty = EnumTy->getDecl()->getIntegerType();
5730 
5731     if (const auto *EIT = Ty->getAs<BitIntType>())
5732       if (EIT->getNumBits() > 128)
5733         return getNaturalAlignIndirect(Ty);
5734 
5735     return (isPromotableIntegerTypeForABI(Ty) && isDarwinPCS()
5736                 ? ABIArgInfo::getExtend(Ty)
5737                 : ABIArgInfo::getDirect());
5738   }
5739 
5740   // Structures with either a non-trivial destructor or a non-trivial
5741   // copy constructor are always indirect.
5742   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
5743     return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA ==
5744                                      CGCXXABI::RAA_DirectInMemory);
5745   }
5746 
5747   // Empty records are always ignored on Darwin, but actually passed in C++ mode
5748   // elsewhere for GNU compatibility.
5749   uint64_t Size = getContext().getTypeSize(Ty);
5750   bool IsEmpty = isEmptyRecord(getContext(), Ty, true);
5751   if (IsEmpty || Size == 0) {
5752     if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS())
5753       return ABIArgInfo::getIgnore();
5754 
5755     // GNU C mode. The only argument that gets ignored is an empty one with size
5756     // 0.
5757     if (IsEmpty && Size == 0)
5758       return ABIArgInfo::getIgnore();
5759     return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
5760   }
5761 
5762   // Homogeneous Floating-point Aggregates (HFAs) need to be expanded.
5763   const Type *Base = nullptr;
5764   uint64_t Members = 0;
5765   bool IsWin64 = Kind == Win64 || CallingConvention == llvm::CallingConv::Win64;
5766   bool IsWinVariadic = IsWin64 && IsVariadic;
5767   // In variadic functions on Windows, all composite types are treated alike,
5768   // no special handling of HFAs/HVAs.
5769   if (!IsWinVariadic && isHomogeneousAggregate(Ty, Base, Members)) {
5770     if (Kind != AArch64ABIInfo::AAPCS)
5771       return ABIArgInfo::getDirect(
5772           llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members));
5773 
5774     // For alignment adjusted HFAs, cap the argument alignment to 16, leave it
5775     // default otherwise.
5776     unsigned Align =
5777         getContext().getTypeUnadjustedAlignInChars(Ty).getQuantity();
5778     unsigned BaseAlign = getContext().getTypeAlignInChars(Base).getQuantity();
5779     Align = (Align > BaseAlign && Align >= 16) ? 16 : 0;
5780     return ABIArgInfo::getDirect(
5781         llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members), 0,
5782         nullptr, true, Align);
5783   }
5784 
5785   // Aggregates <= 16 bytes are passed directly in registers or on the stack.
5786   if (Size <= 128) {
5787     // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
5788     // same size and alignment.
5789     if (getTarget().isRenderScriptTarget()) {
5790       return coerceToIntArray(Ty, getContext(), getVMContext());
5791     }
5792     unsigned Alignment;
5793     if (Kind == AArch64ABIInfo::AAPCS) {
5794       Alignment = getContext().getTypeUnadjustedAlign(Ty);
5795       Alignment = Alignment < 128 ? 64 : 128;
5796     } else {
5797       Alignment = std::max(getContext().getTypeAlign(Ty),
5798                            (unsigned)getTarget().getPointerWidth(0));
5799     }
5800     Size = llvm::alignTo(Size, Alignment);
5801 
5802     // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
5803     // For aggregates with 16-byte alignment, we use i128.
5804     llvm::Type *BaseTy = llvm::Type::getIntNTy(getVMContext(), Alignment);
5805     return ABIArgInfo::getDirect(
5806         Size == Alignment ? BaseTy
5807                           : llvm::ArrayType::get(BaseTy, Size / Alignment));
5808   }
5809 
5810   return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
5811 }
5812 
5813 ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy,
5814                                               bool IsVariadic) const {
5815   if (RetTy->isVoidType())
5816     return ABIArgInfo::getIgnore();
5817 
5818   if (const auto *VT = RetTy->getAs<VectorType>()) {
5819     if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector ||
5820         VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector)
5821       return coerceIllegalVector(RetTy);
5822   }
5823 
5824   // Large vector types should be returned via memory.
5825   if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
5826     return getNaturalAlignIndirect(RetTy);
5827 
5828   if (!isAggregateTypeForABI(RetTy)) {
5829     // Treat an enum type as its underlying type.
5830     if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5831       RetTy = EnumTy->getDecl()->getIntegerType();
5832 
5833     if (const auto *EIT = RetTy->getAs<BitIntType>())
5834       if (EIT->getNumBits() > 128)
5835         return getNaturalAlignIndirect(RetTy);
5836 
5837     return (isPromotableIntegerTypeForABI(RetTy) && isDarwinPCS()
5838                 ? ABIArgInfo::getExtend(RetTy)
5839                 : ABIArgInfo::getDirect());
5840   }
5841 
5842   uint64_t Size = getContext().getTypeSize(RetTy);
5843   if (isEmptyRecord(getContext(), RetTy, true) || Size == 0)
5844     return ABIArgInfo::getIgnore();
5845 
5846   const Type *Base = nullptr;
5847   uint64_t Members = 0;
5848   if (isHomogeneousAggregate(RetTy, Base, Members) &&
5849       !(getTarget().getTriple().getArch() == llvm::Triple::aarch64_32 &&
5850         IsVariadic))
5851     // Homogeneous Floating-point Aggregates (HFAs) are returned directly.
5852     return ABIArgInfo::getDirect();
5853 
5854   // Aggregates <= 16 bytes are returned directly in registers or on the stack.
5855   if (Size <= 128) {
5856     // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
5857     // same size and alignment.
5858     if (getTarget().isRenderScriptTarget()) {
5859       return coerceToIntArray(RetTy, getContext(), getVMContext());
5860     }
5861 
5862     if (Size <= 64 && getDataLayout().isLittleEndian()) {
5863       // Composite types are returned in lower bits of a 64-bit register for LE,
5864       // and in higher bits for BE. However, integer types are always returned
5865       // in lower bits for both LE and BE, and they are not rounded up to
5866       // 64-bits. We can skip rounding up of composite types for LE, but not for
5867       // BE, otherwise composite types will be indistinguishable from integer
5868       // types.
5869       return ABIArgInfo::getDirect(
5870           llvm::IntegerType::get(getVMContext(), Size));
5871     }
5872 
5873     unsigned Alignment = getContext().getTypeAlign(RetTy);
5874     Size = llvm::alignTo(Size, 64); // round up to multiple of 8 bytes
5875 
5876     // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
5877     // For aggregates with 16-byte alignment, we use i128.
5878     if (Alignment < 128 && Size == 128) {
5879       llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
5880       return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
5881     }
5882     return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
5883   }
5884 
5885   return getNaturalAlignIndirect(RetTy);
5886 }
5887 
5888 /// isIllegalVectorType - check whether the vector type is legal for AArch64.
5889 bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const {
5890   if (const VectorType *VT = Ty->getAs<VectorType>()) {
5891     // Check whether VT is a fixed-length SVE vector. These types are
5892     // represented as scalable vectors in function args/return and must be
5893     // coerced from fixed vectors.
5894     if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector ||
5895         VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector)
5896       return true;
5897 
5898     // Check whether VT is legal.
5899     unsigned NumElements = VT->getNumElements();
5900     uint64_t Size = getContext().getTypeSize(VT);
5901     // NumElements should be power of 2.
5902     if (!llvm::isPowerOf2_32(NumElements))
5903       return true;
5904 
5905     // arm64_32 has to be compatible with the ARM logic here, which allows huge
5906     // vectors for some reason.
5907     llvm::Triple Triple = getTarget().getTriple();
5908     if (Triple.getArch() == llvm::Triple::aarch64_32 &&
5909         Triple.isOSBinFormatMachO())
5910       return Size <= 32;
5911 
5912     return Size != 64 && (Size != 128 || NumElements == 1);
5913   }
5914   return false;
5915 }
5916 
5917 bool AArch64ABIInfo::isLegalVectorTypeForSwift(CharUnits totalSize,
5918                                                llvm::Type *eltTy,
5919                                                unsigned elts) const {
5920   if (!llvm::isPowerOf2_32(elts))
5921     return false;
5922   if (totalSize.getQuantity() != 8 &&
5923       (totalSize.getQuantity() != 16 || elts == 1))
5924     return false;
5925   return true;
5926 }
5927 
5928 bool AArch64ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
5929   // Homogeneous aggregates for AAPCS64 must have base types of a floating
5930   // point type or a short-vector type. This is the same as the 32-bit ABI,
5931   // but with the difference that any floating-point type is allowed,
5932   // including __fp16.
5933   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
5934     if (BT->isFloatingPoint())
5935       return true;
5936   } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
5937     unsigned VecSize = getContext().getTypeSize(VT);
5938     if (VecSize == 64 || VecSize == 128)
5939       return true;
5940   }
5941   return false;
5942 }
5943 
5944 bool AArch64ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
5945                                                        uint64_t Members) const {
5946   return Members <= 4;
5947 }
5948 
5949 Address AArch64ABIInfo::EmitAAPCSVAArg(Address VAListAddr, QualType Ty,
5950                                        CodeGenFunction &CGF) const {
5951   ABIArgInfo AI = classifyArgumentType(Ty, /*IsVariadic=*/true,
5952                                        CGF.CurFnInfo->getCallingConvention());
5953   bool IsIndirect = AI.isIndirect();
5954 
5955   llvm::Type *BaseTy = CGF.ConvertType(Ty);
5956   if (IsIndirect)
5957     BaseTy = llvm::PointerType::getUnqual(BaseTy);
5958   else if (AI.getCoerceToType())
5959     BaseTy = AI.getCoerceToType();
5960 
5961   unsigned NumRegs = 1;
5962   if (llvm::ArrayType *ArrTy = dyn_cast<llvm::ArrayType>(BaseTy)) {
5963     BaseTy = ArrTy->getElementType();
5964     NumRegs = ArrTy->getNumElements();
5965   }
5966   bool IsFPR = BaseTy->isFloatingPointTy() || BaseTy->isVectorTy();
5967 
5968   // The AArch64 va_list type and handling is specified in the Procedure Call
5969   // Standard, section B.4:
5970   //
5971   // struct {
5972   //   void *__stack;
5973   //   void *__gr_top;
5974   //   void *__vr_top;
5975   //   int __gr_offs;
5976   //   int __vr_offs;
5977   // };
5978 
5979   llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
5980   llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
5981   llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
5982   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
5983 
5984   CharUnits TySize = getContext().getTypeSizeInChars(Ty);
5985   CharUnits TyAlign = getContext().getTypeUnadjustedAlignInChars(Ty);
5986 
5987   Address reg_offs_p = Address::invalid();
5988   llvm::Value *reg_offs = nullptr;
5989   int reg_top_index;
5990   int RegSize = IsIndirect ? 8 : TySize.getQuantity();
5991   if (!IsFPR) {
5992     // 3 is the field number of __gr_offs
5993     reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 3, "gr_offs_p");
5994     reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
5995     reg_top_index = 1; // field number for __gr_top
5996     RegSize = llvm::alignTo(RegSize, 8);
5997   } else {
5998     // 4 is the field number of __vr_offs.
5999     reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 4, "vr_offs_p");
6000     reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
6001     reg_top_index = 2; // field number for __vr_top
6002     RegSize = 16 * NumRegs;
6003   }
6004 
6005   //=======================================
6006   // Find out where argument was passed
6007   //=======================================
6008 
6009   // If reg_offs >= 0 we're already using the stack for this type of
6010   // argument. We don't want to keep updating reg_offs (in case it overflows,
6011   // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
6012   // whatever they get).
6013   llvm::Value *UsingStack = nullptr;
6014   UsingStack = CGF.Builder.CreateICmpSGE(
6015       reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0));
6016 
6017   CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
6018 
6019   // Otherwise, at least some kind of argument could go in these registers, the
6020   // question is whether this particular type is too big.
6021   CGF.EmitBlock(MaybeRegBlock);
6022 
6023   // Integer arguments may need to correct register alignment (for example a
6024   // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
6025   // align __gr_offs to calculate the potential address.
6026   if (!IsFPR && !IsIndirect && TyAlign.getQuantity() > 8) {
6027     int Align = TyAlign.getQuantity();
6028 
6029     reg_offs = CGF.Builder.CreateAdd(
6030         reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
6031         "align_regoffs");
6032     reg_offs = CGF.Builder.CreateAnd(
6033         reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align),
6034         "aligned_regoffs");
6035   }
6036 
6037   // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
6038   // The fact that this is done unconditionally reflects the fact that
6039   // allocating an argument to the stack also uses up all the remaining
6040   // registers of the appropriate kind.
6041   llvm::Value *NewOffset = nullptr;
6042   NewOffset = CGF.Builder.CreateAdd(
6043       reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs");
6044   CGF.Builder.CreateStore(NewOffset, reg_offs_p);
6045 
6046   // Now we're in a position to decide whether this argument really was in
6047   // registers or not.
6048   llvm::Value *InRegs = nullptr;
6049   InRegs = CGF.Builder.CreateICmpSLE(
6050       NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg");
6051 
6052   CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
6053 
6054   //=======================================
6055   // Argument was in registers
6056   //=======================================
6057 
6058   // Now we emit the code for if the argument was originally passed in
6059   // registers. First start the appropriate block:
6060   CGF.EmitBlock(InRegBlock);
6061 
6062   llvm::Value *reg_top = nullptr;
6063   Address reg_top_p =
6064       CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index, "reg_top_p");
6065   reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
6066   Address BaseAddr(CGF.Builder.CreateInBoundsGEP(CGF.Int8Ty, reg_top, reg_offs),
6067                    CGF.Int8Ty, CharUnits::fromQuantity(IsFPR ? 16 : 8));
6068   Address RegAddr = Address::invalid();
6069   llvm::Type *MemTy = CGF.ConvertTypeForMem(Ty), *ElementTy = MemTy;
6070 
6071   if (IsIndirect) {
6072     // If it's been passed indirectly (actually a struct), whatever we find from
6073     // stored registers or on the stack will actually be a struct **.
6074     MemTy = llvm::PointerType::getUnqual(MemTy);
6075   }
6076 
6077   const Type *Base = nullptr;
6078   uint64_t NumMembers = 0;
6079   bool IsHFA = isHomogeneousAggregate(Ty, Base, NumMembers);
6080   if (IsHFA && NumMembers > 1) {
6081     // Homogeneous aggregates passed in registers will have their elements split
6082     // and stored 16-bytes apart regardless of size (they're notionally in qN,
6083     // qN+1, ...). We reload and store into a temporary local variable
6084     // contiguously.
6085     assert(!IsIndirect && "Homogeneous aggregates should be passed directly");
6086     auto BaseTyInfo = getContext().getTypeInfoInChars(QualType(Base, 0));
6087     llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
6088     llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
6089     Address Tmp = CGF.CreateTempAlloca(HFATy,
6090                                        std::max(TyAlign, BaseTyInfo.Align));
6091 
6092     // On big-endian platforms, the value will be right-aligned in its slot.
6093     int Offset = 0;
6094     if (CGF.CGM.getDataLayout().isBigEndian() &&
6095         BaseTyInfo.Width.getQuantity() < 16)
6096       Offset = 16 - BaseTyInfo.Width.getQuantity();
6097 
6098     for (unsigned i = 0; i < NumMembers; ++i) {
6099       CharUnits BaseOffset = CharUnits::fromQuantity(16 * i + Offset);
6100       Address LoadAddr =
6101         CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, BaseOffset);
6102       LoadAddr = CGF.Builder.CreateElementBitCast(LoadAddr, BaseTy);
6103 
6104       Address StoreAddr = CGF.Builder.CreateConstArrayGEP(Tmp, i);
6105 
6106       llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
6107       CGF.Builder.CreateStore(Elem, StoreAddr);
6108     }
6109 
6110     RegAddr = CGF.Builder.CreateElementBitCast(Tmp, MemTy);
6111   } else {
6112     // Otherwise the object is contiguous in memory.
6113 
6114     // It might be right-aligned in its slot.
6115     CharUnits SlotSize = BaseAddr.getAlignment();
6116     if (CGF.CGM.getDataLayout().isBigEndian() && !IsIndirect &&
6117         (IsHFA || !isAggregateTypeForABI(Ty)) &&
6118         TySize < SlotSize) {
6119       CharUnits Offset = SlotSize - TySize;
6120       BaseAddr = CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, Offset);
6121     }
6122 
6123     RegAddr = CGF.Builder.CreateElementBitCast(BaseAddr, MemTy);
6124   }
6125 
6126   CGF.EmitBranch(ContBlock);
6127 
6128   //=======================================
6129   // Argument was on the stack
6130   //=======================================
6131   CGF.EmitBlock(OnStackBlock);
6132 
6133   Address stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "stack_p");
6134   llvm::Value *OnStackPtr = CGF.Builder.CreateLoad(stack_p, "stack");
6135 
6136   // Again, stack arguments may need realignment. In this case both integer and
6137   // floating-point ones might be affected.
6138   if (!IsIndirect && TyAlign.getQuantity() > 8) {
6139     int Align = TyAlign.getQuantity();
6140 
6141     OnStackPtr = CGF.Builder.CreatePtrToInt(OnStackPtr, CGF.Int64Ty);
6142 
6143     OnStackPtr = CGF.Builder.CreateAdd(
6144         OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
6145         "align_stack");
6146     OnStackPtr = CGF.Builder.CreateAnd(
6147         OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, -Align),
6148         "align_stack");
6149 
6150     OnStackPtr = CGF.Builder.CreateIntToPtr(OnStackPtr, CGF.Int8PtrTy);
6151   }
6152   Address OnStackAddr = Address(OnStackPtr, CGF.Int8Ty,
6153                                 std::max(CharUnits::fromQuantity(8), TyAlign));
6154 
6155   // All stack slots are multiples of 8 bytes.
6156   CharUnits StackSlotSize = CharUnits::fromQuantity(8);
6157   CharUnits StackSize;
6158   if (IsIndirect)
6159     StackSize = StackSlotSize;
6160   else
6161     StackSize = TySize.alignTo(StackSlotSize);
6162 
6163   llvm::Value *StackSizeC = CGF.Builder.getSize(StackSize);
6164   llvm::Value *NewStack = CGF.Builder.CreateInBoundsGEP(
6165       CGF.Int8Ty, OnStackPtr, StackSizeC, "new_stack");
6166 
6167   // Write the new value of __stack for the next call to va_arg
6168   CGF.Builder.CreateStore(NewStack, stack_p);
6169 
6170   if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) &&
6171       TySize < StackSlotSize) {
6172     CharUnits Offset = StackSlotSize - TySize;
6173     OnStackAddr = CGF.Builder.CreateConstInBoundsByteGEP(OnStackAddr, Offset);
6174   }
6175 
6176   OnStackAddr = CGF.Builder.CreateElementBitCast(OnStackAddr, MemTy);
6177 
6178   CGF.EmitBranch(ContBlock);
6179 
6180   //=======================================
6181   // Tidy up
6182   //=======================================
6183   CGF.EmitBlock(ContBlock);
6184 
6185   Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, OnStackAddr,
6186                                  OnStackBlock, "vaargs.addr");
6187 
6188   if (IsIndirect)
6189     return Address(CGF.Builder.CreateLoad(ResAddr, "vaarg.addr"), ElementTy,
6190                    TyAlign);
6191 
6192   return ResAddr;
6193 }
6194 
6195 Address AArch64ABIInfo::EmitDarwinVAArg(Address VAListAddr, QualType Ty,
6196                                         CodeGenFunction &CGF) const {
6197   // The backend's lowering doesn't support va_arg for aggregates or
6198   // illegal vector types.  Lower VAArg here for these cases and use
6199   // the LLVM va_arg instruction for everything else.
6200   if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty))
6201     return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
6202 
6203   uint64_t PointerSize = getTarget().getPointerWidth(0) / 8;
6204   CharUnits SlotSize = CharUnits::fromQuantity(PointerSize);
6205 
6206   // Empty records are ignored for parameter passing purposes.
6207   if (isEmptyRecord(getContext(), Ty, true)) {
6208     Address Addr = Address(CGF.Builder.CreateLoad(VAListAddr, "ap.cur"),
6209                            getVAListElementType(CGF), SlotSize);
6210     Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
6211     return Addr;
6212   }
6213 
6214   // The size of the actual thing passed, which might end up just
6215   // being a pointer for indirect types.
6216   auto TyInfo = getContext().getTypeInfoInChars(Ty);
6217 
6218   // Arguments bigger than 16 bytes which aren't homogeneous
6219   // aggregates should be passed indirectly.
6220   bool IsIndirect = false;
6221   if (TyInfo.Width.getQuantity() > 16) {
6222     const Type *Base = nullptr;
6223     uint64_t Members = 0;
6224     IsIndirect = !isHomogeneousAggregate(Ty, Base, Members);
6225   }
6226 
6227   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
6228                           TyInfo, SlotSize, /*AllowHigherAlign*/ true);
6229 }
6230 
6231 Address AArch64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
6232                                     QualType Ty) const {
6233   bool IsIndirect = false;
6234 
6235   // Composites larger than 16 bytes are passed by reference.
6236   if (isAggregateTypeForABI(Ty) && getContext().getTypeSize(Ty) > 128)
6237     IsIndirect = true;
6238 
6239   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
6240                           CGF.getContext().getTypeInfoInChars(Ty),
6241                           CharUnits::fromQuantity(8),
6242                           /*allowHigherAlign*/ false);
6243 }
6244 
6245 //===----------------------------------------------------------------------===//
6246 // ARM ABI Implementation
6247 //===----------------------------------------------------------------------===//
6248 
6249 namespace {
6250 
6251 class ARMABIInfo : public SwiftABIInfo {
6252 public:
6253   enum ABIKind {
6254     APCS = 0,
6255     AAPCS = 1,
6256     AAPCS_VFP = 2,
6257     AAPCS16_VFP = 3,
6258   };
6259 
6260 private:
6261   ABIKind Kind;
6262   bool IsFloatABISoftFP;
6263 
6264 public:
6265   ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind)
6266       : SwiftABIInfo(CGT), Kind(_Kind) {
6267     setCCs();
6268     IsFloatABISoftFP = CGT.getCodeGenOpts().FloatABI == "softfp" ||
6269         CGT.getCodeGenOpts().FloatABI == ""; // default
6270   }
6271 
6272   bool isEABI() const {
6273     switch (getTarget().getTriple().getEnvironment()) {
6274     case llvm::Triple::Android:
6275     case llvm::Triple::EABI:
6276     case llvm::Triple::EABIHF:
6277     case llvm::Triple::GNUEABI:
6278     case llvm::Triple::GNUEABIHF:
6279     case llvm::Triple::MuslEABI:
6280     case llvm::Triple::MuslEABIHF:
6281       return true;
6282     default:
6283       return false;
6284     }
6285   }
6286 
6287   bool isEABIHF() const {
6288     switch (getTarget().getTriple().getEnvironment()) {
6289     case llvm::Triple::EABIHF:
6290     case llvm::Triple::GNUEABIHF:
6291     case llvm::Triple::MuslEABIHF:
6292       return true;
6293     default:
6294       return false;
6295     }
6296   }
6297 
6298   ABIKind getABIKind() const { return Kind; }
6299 
6300   bool allowBFloatArgsAndRet() const override {
6301     return !IsFloatABISoftFP && getTarget().hasBFloat16Type();
6302   }
6303 
6304 private:
6305   ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic,
6306                                 unsigned functionCallConv) const;
6307   ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic,
6308                                   unsigned functionCallConv) const;
6309   ABIArgInfo classifyHomogeneousAggregate(QualType Ty, const Type *Base,
6310                                           uint64_t Members) const;
6311   ABIArgInfo coerceIllegalVector(QualType Ty) const;
6312   bool isIllegalVectorType(QualType Ty) const;
6313   bool containsAnyFP16Vectors(QualType Ty) const;
6314 
6315   bool isHomogeneousAggregateBaseType(QualType Ty) const override;
6316   bool isHomogeneousAggregateSmallEnough(const Type *Ty,
6317                                          uint64_t Members) const override;
6318 
6319   bool isEffectivelyAAPCS_VFP(unsigned callConvention, bool acceptHalf) const;
6320 
6321   void computeInfo(CGFunctionInfo &FI) const override;
6322 
6323   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6324                     QualType Ty) const override;
6325 
6326   llvm::CallingConv::ID getLLVMDefaultCC() const;
6327   llvm::CallingConv::ID getABIDefaultCC() const;
6328   void setCCs();
6329 
6330   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
6331                                     bool asReturnValue) const override {
6332     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
6333   }
6334   bool isSwiftErrorInRegister() const override {
6335     return true;
6336   }
6337   bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy,
6338                                  unsigned elts) const override;
6339 };
6340 
6341 class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
6342 public:
6343   ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
6344       : TargetCodeGenInfo(std::make_unique<ARMABIInfo>(CGT, K)) {}
6345 
6346   const ARMABIInfo &getABIInfo() const {
6347     return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
6348   }
6349 
6350   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
6351     return 13;
6352   }
6353 
6354   StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
6355     return "mov\tr7, r7\t\t// marker for objc_retainAutoreleaseReturnValue";
6356   }
6357 
6358   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
6359                                llvm::Value *Address) const override {
6360     llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
6361 
6362     // 0-15 are the 16 integer registers.
6363     AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
6364     return false;
6365   }
6366 
6367   unsigned getSizeOfUnwindException() const override {
6368     if (getABIInfo().isEABI()) return 88;
6369     return TargetCodeGenInfo::getSizeOfUnwindException();
6370   }
6371 
6372   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
6373                            CodeGen::CodeGenModule &CGM) const override {
6374     if (GV->isDeclaration())
6375       return;
6376     const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
6377     if (!FD)
6378       return;
6379     auto *Fn = cast<llvm::Function>(GV);
6380 
6381     if (const auto *TA = FD->getAttr<TargetAttr>()) {
6382       ParsedTargetAttr Attr = TA->parse();
6383       if (!Attr.BranchProtection.empty()) {
6384         TargetInfo::BranchProtectionInfo BPI;
6385         StringRef DiagMsg;
6386         StringRef Arch = Attr.Architecture.empty()
6387                              ? CGM.getTarget().getTargetOpts().CPU
6388                              : Attr.Architecture;
6389         if (!CGM.getTarget().validateBranchProtection(Attr.BranchProtection,
6390                                                       Arch, BPI, DiagMsg)) {
6391           CGM.getDiags().Report(
6392               D->getLocation(),
6393               diag::warn_target_unsupported_branch_protection_attribute)
6394               << Arch;
6395         } else {
6396           static const char *SignReturnAddrStr[] = {"none", "non-leaf", "all"};
6397           assert(static_cast<unsigned>(BPI.SignReturnAddr) <= 2 &&
6398                  "Unexpected SignReturnAddressScopeKind");
6399           Fn->addFnAttr(
6400               "sign-return-address",
6401               SignReturnAddrStr[static_cast<int>(BPI.SignReturnAddr)]);
6402 
6403           Fn->addFnAttr("branch-target-enforcement",
6404                         BPI.BranchTargetEnforcement ? "true" : "false");
6405         }
6406       } else if (CGM.getLangOpts().BranchTargetEnforcement ||
6407                  CGM.getLangOpts().hasSignReturnAddress()) {
6408         // If the Branch Protection attribute is missing, validate the target
6409         // Architecture attribute against Branch Protection command line
6410         // settings.
6411         if (!CGM.getTarget().isBranchProtectionSupportedArch(Attr.Architecture))
6412           CGM.getDiags().Report(
6413               D->getLocation(),
6414               diag::warn_target_unsupported_branch_protection_attribute)
6415               << Attr.Architecture;
6416       }
6417     }
6418 
6419     const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
6420     if (!Attr)
6421       return;
6422 
6423     const char *Kind;
6424     switch (Attr->getInterrupt()) {
6425     case ARMInterruptAttr::Generic: Kind = ""; break;
6426     case ARMInterruptAttr::IRQ:     Kind = "IRQ"; break;
6427     case ARMInterruptAttr::FIQ:     Kind = "FIQ"; break;
6428     case ARMInterruptAttr::SWI:     Kind = "SWI"; break;
6429     case ARMInterruptAttr::ABORT:   Kind = "ABORT"; break;
6430     case ARMInterruptAttr::UNDEF:   Kind = "UNDEF"; break;
6431     }
6432 
6433     Fn->addFnAttr("interrupt", Kind);
6434 
6435     ARMABIInfo::ABIKind ABI = cast<ARMABIInfo>(getABIInfo()).getABIKind();
6436     if (ABI == ARMABIInfo::APCS)
6437       return;
6438 
6439     // AAPCS guarantees that sp will be 8-byte aligned on any public interface,
6440     // however this is not necessarily true on taking any interrupt. Instruct
6441     // the backend to perform a realignment as part of the function prologue.
6442     llvm::AttrBuilder B(Fn->getContext());
6443     B.addStackAlignmentAttr(8);
6444     Fn->addFnAttrs(B);
6445   }
6446 };
6447 
6448 class WindowsARMTargetCodeGenInfo : public ARMTargetCodeGenInfo {
6449 public:
6450   WindowsARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
6451       : ARMTargetCodeGenInfo(CGT, K) {}
6452 
6453   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
6454                            CodeGen::CodeGenModule &CGM) const override;
6455 
6456   void getDependentLibraryOption(llvm::StringRef Lib,
6457                                  llvm::SmallString<24> &Opt) const override {
6458     Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib);
6459   }
6460 
6461   void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value,
6462                                llvm::SmallString<32> &Opt) const override {
6463     Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
6464   }
6465 };
6466 
6467 void WindowsARMTargetCodeGenInfo::setTargetAttributes(
6468     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
6469   ARMTargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
6470   if (GV->isDeclaration())
6471     return;
6472   addStackProbeTargetAttributes(D, GV, CGM);
6473 }
6474 }
6475 
6476 void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
6477   if (!::classifyReturnType(getCXXABI(), FI, *this))
6478     FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), FI.isVariadic(),
6479                                             FI.getCallingConvention());
6480 
6481   for (auto &I : FI.arguments())
6482     I.info = classifyArgumentType(I.type, FI.isVariadic(),
6483                                   FI.getCallingConvention());
6484 
6485 
6486   // Always honor user-specified calling convention.
6487   if (FI.getCallingConvention() != llvm::CallingConv::C)
6488     return;
6489 
6490   llvm::CallingConv::ID cc = getRuntimeCC();
6491   if (cc != llvm::CallingConv::C)
6492     FI.setEffectiveCallingConvention(cc);
6493 }
6494 
6495 /// Return the default calling convention that LLVM will use.
6496 llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
6497   // The default calling convention that LLVM will infer.
6498   if (isEABIHF() || getTarget().getTriple().isWatchABI())
6499     return llvm::CallingConv::ARM_AAPCS_VFP;
6500   else if (isEABI())
6501     return llvm::CallingConv::ARM_AAPCS;
6502   else
6503     return llvm::CallingConv::ARM_APCS;
6504 }
6505 
6506 /// Return the calling convention that our ABI would like us to use
6507 /// as the C calling convention.
6508 llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
6509   switch (getABIKind()) {
6510   case APCS: return llvm::CallingConv::ARM_APCS;
6511   case AAPCS: return llvm::CallingConv::ARM_AAPCS;
6512   case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
6513   case AAPCS16_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
6514   }
6515   llvm_unreachable("bad ABI kind");
6516 }
6517 
6518 void ARMABIInfo::setCCs() {
6519   assert(getRuntimeCC() == llvm::CallingConv::C);
6520 
6521   // Don't muddy up the IR with a ton of explicit annotations if
6522   // they'd just match what LLVM will infer from the triple.
6523   llvm::CallingConv::ID abiCC = getABIDefaultCC();
6524   if (abiCC != getLLVMDefaultCC())
6525     RuntimeCC = abiCC;
6526 }
6527 
6528 ABIArgInfo ARMABIInfo::coerceIllegalVector(QualType Ty) const {
6529   uint64_t Size = getContext().getTypeSize(Ty);
6530   if (Size <= 32) {
6531     llvm::Type *ResType =
6532         llvm::Type::getInt32Ty(getVMContext());
6533     return ABIArgInfo::getDirect(ResType);
6534   }
6535   if (Size == 64 || Size == 128) {
6536     auto *ResType = llvm::FixedVectorType::get(
6537         llvm::Type::getInt32Ty(getVMContext()), Size / 32);
6538     return ABIArgInfo::getDirect(ResType);
6539   }
6540   return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
6541 }
6542 
6543 ABIArgInfo ARMABIInfo::classifyHomogeneousAggregate(QualType Ty,
6544                                                     const Type *Base,
6545                                                     uint64_t Members) const {
6546   assert(Base && "Base class should be set for homogeneous aggregate");
6547   // Base can be a floating-point or a vector.
6548   if (const VectorType *VT = Base->getAs<VectorType>()) {
6549     // FP16 vectors should be converted to integer vectors
6550     if (!getTarget().hasLegalHalfType() && containsAnyFP16Vectors(Ty)) {
6551       uint64_t Size = getContext().getTypeSize(VT);
6552       auto *NewVecTy = llvm::FixedVectorType::get(
6553           llvm::Type::getInt32Ty(getVMContext()), Size / 32);
6554       llvm::Type *Ty = llvm::ArrayType::get(NewVecTy, Members);
6555       return ABIArgInfo::getDirect(Ty, 0, nullptr, false);
6556     }
6557   }
6558   unsigned Align = 0;
6559   if (getABIKind() == ARMABIInfo::AAPCS ||
6560       getABIKind() == ARMABIInfo::AAPCS_VFP) {
6561     // For alignment adjusted HFAs, cap the argument alignment to 8, leave it
6562     // default otherwise.
6563     Align = getContext().getTypeUnadjustedAlignInChars(Ty).getQuantity();
6564     unsigned BaseAlign = getContext().getTypeAlignInChars(Base).getQuantity();
6565     Align = (Align > BaseAlign && Align >= 8) ? 8 : 0;
6566   }
6567   return ABIArgInfo::getDirect(nullptr, 0, nullptr, false, Align);
6568 }
6569 
6570 ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty, bool isVariadic,
6571                                             unsigned functionCallConv) const {
6572   // 6.1.2.1 The following argument types are VFP CPRCs:
6573   //   A single-precision floating-point type (including promoted
6574   //   half-precision types); A double-precision floating-point type;
6575   //   A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
6576   //   with a Base Type of a single- or double-precision floating-point type,
6577   //   64-bit containerized vectors or 128-bit containerized vectors with one
6578   //   to four Elements.
6579   // Variadic functions should always marshal to the base standard.
6580   bool IsAAPCS_VFP =
6581       !isVariadic && isEffectivelyAAPCS_VFP(functionCallConv, /* AAPCS16 */ false);
6582 
6583   Ty = useFirstFieldIfTransparentUnion(Ty);
6584 
6585   // Handle illegal vector types here.
6586   if (isIllegalVectorType(Ty))
6587     return coerceIllegalVector(Ty);
6588 
6589   if (!isAggregateTypeForABI(Ty)) {
6590     // Treat an enum type as its underlying type.
6591     if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
6592       Ty = EnumTy->getDecl()->getIntegerType();
6593     }
6594 
6595     if (const auto *EIT = Ty->getAs<BitIntType>())
6596       if (EIT->getNumBits() > 64)
6597         return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
6598 
6599     return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
6600                                               : ABIArgInfo::getDirect());
6601   }
6602 
6603   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
6604     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
6605   }
6606 
6607   // Ignore empty records.
6608   if (isEmptyRecord(getContext(), Ty, true))
6609     return ABIArgInfo::getIgnore();
6610 
6611   if (IsAAPCS_VFP) {
6612     // Homogeneous Aggregates need to be expanded when we can fit the aggregate
6613     // into VFP registers.
6614     const Type *Base = nullptr;
6615     uint64_t Members = 0;
6616     if (isHomogeneousAggregate(Ty, Base, Members))
6617       return classifyHomogeneousAggregate(Ty, Base, Members);
6618   } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
6619     // WatchOS does have homogeneous aggregates. Note that we intentionally use
6620     // this convention even for a variadic function: the backend will use GPRs
6621     // if needed.
6622     const Type *Base = nullptr;
6623     uint64_t Members = 0;
6624     if (isHomogeneousAggregate(Ty, Base, Members)) {
6625       assert(Base && Members <= 4 && "unexpected homogeneous aggregate");
6626       llvm::Type *Ty =
6627         llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members);
6628       return ABIArgInfo::getDirect(Ty, 0, nullptr, false);
6629     }
6630   }
6631 
6632   if (getABIKind() == ARMABIInfo::AAPCS16_VFP &&
6633       getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(16)) {
6634     // WatchOS is adopting the 64-bit AAPCS rule on composite types: if they're
6635     // bigger than 128-bits, they get placed in space allocated by the caller,
6636     // and a pointer is passed.
6637     return ABIArgInfo::getIndirect(
6638         CharUnits::fromQuantity(getContext().getTypeAlign(Ty) / 8), false);
6639   }
6640 
6641   // Support byval for ARM.
6642   // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
6643   // most 8-byte. We realign the indirect argument if type alignment is bigger
6644   // than ABI alignment.
6645   uint64_t ABIAlign = 4;
6646   uint64_t TyAlign;
6647   if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
6648       getABIKind() == ARMABIInfo::AAPCS) {
6649     TyAlign = getContext().getTypeUnadjustedAlignInChars(Ty).getQuantity();
6650     ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
6651   } else {
6652     TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity();
6653   }
6654   if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
6655     assert(getABIKind() != ARMABIInfo::AAPCS16_VFP && "unexpected byval");
6656     return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
6657                                    /*ByVal=*/true,
6658                                    /*Realign=*/TyAlign > ABIAlign);
6659   }
6660 
6661   // On RenderScript, coerce Aggregates <= 64 bytes to an integer array of
6662   // same size and alignment.
6663   if (getTarget().isRenderScriptTarget()) {
6664     return coerceToIntArray(Ty, getContext(), getVMContext());
6665   }
6666 
6667   // Otherwise, pass by coercing to a structure of the appropriate size.
6668   llvm::Type* ElemTy;
6669   unsigned SizeRegs;
6670   // FIXME: Try to match the types of the arguments more accurately where
6671   // we can.
6672   if (TyAlign <= 4) {
6673     ElemTy = llvm::Type::getInt32Ty(getVMContext());
6674     SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
6675   } else {
6676     ElemTy = llvm::Type::getInt64Ty(getVMContext());
6677     SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
6678   }
6679 
6680   return ABIArgInfo::getDirect(llvm::ArrayType::get(ElemTy, SizeRegs));
6681 }
6682 
6683 static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
6684                               llvm::LLVMContext &VMContext) {
6685   // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
6686   // is called integer-like if its size is less than or equal to one word, and
6687   // the offset of each of its addressable sub-fields is zero.
6688 
6689   uint64_t Size = Context.getTypeSize(Ty);
6690 
6691   // Check that the type fits in a word.
6692   if (Size > 32)
6693     return false;
6694 
6695   // FIXME: Handle vector types!
6696   if (Ty->isVectorType())
6697     return false;
6698 
6699   // Float types are never treated as "integer like".
6700   if (Ty->isRealFloatingType())
6701     return false;
6702 
6703   // If this is a builtin or pointer type then it is ok.
6704   if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
6705     return true;
6706 
6707   // Small complex integer types are "integer like".
6708   if (const ComplexType *CT = Ty->getAs<ComplexType>())
6709     return isIntegerLikeType(CT->getElementType(), Context, VMContext);
6710 
6711   // Single element and zero sized arrays should be allowed, by the definition
6712   // above, but they are not.
6713 
6714   // Otherwise, it must be a record type.
6715   const RecordType *RT = Ty->getAs<RecordType>();
6716   if (!RT) return false;
6717 
6718   // Ignore records with flexible arrays.
6719   const RecordDecl *RD = RT->getDecl();
6720   if (RD->hasFlexibleArrayMember())
6721     return false;
6722 
6723   // Check that all sub-fields are at offset 0, and are themselves "integer
6724   // like".
6725   const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
6726 
6727   bool HadField = false;
6728   unsigned idx = 0;
6729   for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
6730        i != e; ++i, ++idx) {
6731     const FieldDecl *FD = *i;
6732 
6733     // Bit-fields are not addressable, we only need to verify they are "integer
6734     // like". We still have to disallow a subsequent non-bitfield, for example:
6735     //   struct { int : 0; int x }
6736     // is non-integer like according to gcc.
6737     if (FD->isBitField()) {
6738       if (!RD->isUnion())
6739         HadField = true;
6740 
6741       if (!isIntegerLikeType(FD->getType(), Context, VMContext))
6742         return false;
6743 
6744       continue;
6745     }
6746 
6747     // Check if this field is at offset 0.
6748     if (Layout.getFieldOffset(idx) != 0)
6749       return false;
6750 
6751     if (!isIntegerLikeType(FD->getType(), Context, VMContext))
6752       return false;
6753 
6754     // Only allow at most one field in a structure. This doesn't match the
6755     // wording above, but follows gcc in situations with a field following an
6756     // empty structure.
6757     if (!RD->isUnion()) {
6758       if (HadField)
6759         return false;
6760 
6761       HadField = true;
6762     }
6763   }
6764 
6765   return true;
6766 }
6767 
6768 ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy, bool isVariadic,
6769                                           unsigned functionCallConv) const {
6770 
6771   // Variadic functions should always marshal to the base standard.
6772   bool IsAAPCS_VFP =
6773       !isVariadic && isEffectivelyAAPCS_VFP(functionCallConv, /* AAPCS16 */ true);
6774 
6775   if (RetTy->isVoidType())
6776     return ABIArgInfo::getIgnore();
6777 
6778   if (const VectorType *VT = RetTy->getAs<VectorType>()) {
6779     // Large vector types should be returned via memory.
6780     if (getContext().getTypeSize(RetTy) > 128)
6781       return getNaturalAlignIndirect(RetTy);
6782     // TODO: FP16/BF16 vectors should be converted to integer vectors
6783     // This check is similar  to isIllegalVectorType - refactor?
6784     if ((!getTarget().hasLegalHalfType() &&
6785         (VT->getElementType()->isFloat16Type() ||
6786          VT->getElementType()->isHalfType())) ||
6787         (IsFloatABISoftFP &&
6788          VT->getElementType()->isBFloat16Type()))
6789       return coerceIllegalVector(RetTy);
6790   }
6791 
6792   if (!isAggregateTypeForABI(RetTy)) {
6793     // Treat an enum type as its underlying type.
6794     if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6795       RetTy = EnumTy->getDecl()->getIntegerType();
6796 
6797     if (const auto *EIT = RetTy->getAs<BitIntType>())
6798       if (EIT->getNumBits() > 64)
6799         return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
6800 
6801     return isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
6802                                                 : ABIArgInfo::getDirect();
6803   }
6804 
6805   // Are we following APCS?
6806   if (getABIKind() == APCS) {
6807     if (isEmptyRecord(getContext(), RetTy, false))
6808       return ABIArgInfo::getIgnore();
6809 
6810     // Complex types are all returned as packed integers.
6811     //
6812     // FIXME: Consider using 2 x vector types if the back end handles them
6813     // correctly.
6814     if (RetTy->isAnyComplexType())
6815       return ABIArgInfo::getDirect(llvm::IntegerType::get(
6816           getVMContext(), getContext().getTypeSize(RetTy)));
6817 
6818     // Integer like structures are returned in r0.
6819     if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
6820       // Return in the smallest viable integer type.
6821       uint64_t Size = getContext().getTypeSize(RetTy);
6822       if (Size <= 8)
6823         return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6824       if (Size <= 16)
6825         return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6826       return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6827     }
6828 
6829     // Otherwise return in memory.
6830     return getNaturalAlignIndirect(RetTy);
6831   }
6832 
6833   // Otherwise this is an AAPCS variant.
6834 
6835   if (isEmptyRecord(getContext(), RetTy, true))
6836     return ABIArgInfo::getIgnore();
6837 
6838   // Check for homogeneous aggregates with AAPCS-VFP.
6839   if (IsAAPCS_VFP) {
6840     const Type *Base = nullptr;
6841     uint64_t Members = 0;
6842     if (isHomogeneousAggregate(RetTy, Base, Members))
6843       return classifyHomogeneousAggregate(RetTy, Base, Members);
6844   }
6845 
6846   // Aggregates <= 4 bytes are returned in r0; other aggregates
6847   // are returned indirectly.
6848   uint64_t Size = getContext().getTypeSize(RetTy);
6849   if (Size <= 32) {
6850     // On RenderScript, coerce Aggregates <= 4 bytes to an integer array of
6851     // same size and alignment.
6852     if (getTarget().isRenderScriptTarget()) {
6853       return coerceToIntArray(RetTy, getContext(), getVMContext());
6854     }
6855     if (getDataLayout().isBigEndian())
6856       // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4)
6857       return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6858 
6859     // Return in the smallest viable integer type.
6860     if (Size <= 8)
6861       return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6862     if (Size <= 16)
6863       return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6864     return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6865   } else if (Size <= 128 && getABIKind() == AAPCS16_VFP) {
6866     llvm::Type *Int32Ty = llvm::Type::getInt32Ty(getVMContext());
6867     llvm::Type *CoerceTy =
6868         llvm::ArrayType::get(Int32Ty, llvm::alignTo(Size, 32) / 32);
6869     return ABIArgInfo::getDirect(CoerceTy);
6870   }
6871 
6872   return getNaturalAlignIndirect(RetTy);
6873 }
6874 
6875 /// isIllegalVector - check whether Ty is an illegal vector type.
6876 bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
6877   if (const VectorType *VT = Ty->getAs<VectorType> ()) {
6878     // On targets that don't support half, fp16 or bfloat, they are expanded
6879     // into float, and we don't want the ABI to depend on whether or not they
6880     // are supported in hardware. Thus return false to coerce vectors of these
6881     // types into integer vectors.
6882     // We do not depend on hasLegalHalfType for bfloat as it is a
6883     // separate IR type.
6884     if ((!getTarget().hasLegalHalfType() &&
6885         (VT->getElementType()->isFloat16Type() ||
6886          VT->getElementType()->isHalfType())) ||
6887         (IsFloatABISoftFP &&
6888          VT->getElementType()->isBFloat16Type()))
6889       return true;
6890     if (isAndroid()) {
6891       // Android shipped using Clang 3.1, which supported a slightly different
6892       // vector ABI. The primary differences were that 3-element vector types
6893       // were legal, and so were sub 32-bit vectors (i.e. <2 x i8>). This path
6894       // accepts that legacy behavior for Android only.
6895       // Check whether VT is legal.
6896       unsigned NumElements = VT->getNumElements();
6897       // NumElements should be power of 2 or equal to 3.
6898       if (!llvm::isPowerOf2_32(NumElements) && NumElements != 3)
6899         return true;
6900     } else {
6901       // Check whether VT is legal.
6902       unsigned NumElements = VT->getNumElements();
6903       uint64_t Size = getContext().getTypeSize(VT);
6904       // NumElements should be power of 2.
6905       if (!llvm::isPowerOf2_32(NumElements))
6906         return true;
6907       // Size should be greater than 32 bits.
6908       return Size <= 32;
6909     }
6910   }
6911   return false;
6912 }
6913 
6914 /// Return true if a type contains any 16-bit floating point vectors
6915 bool ARMABIInfo::containsAnyFP16Vectors(QualType Ty) const {
6916   if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
6917     uint64_t NElements = AT->getSize().getZExtValue();
6918     if (NElements == 0)
6919       return false;
6920     return containsAnyFP16Vectors(AT->getElementType());
6921   } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
6922     const RecordDecl *RD = RT->getDecl();
6923 
6924     // If this is a C++ record, check the bases first.
6925     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
6926       if (llvm::any_of(CXXRD->bases(), [this](const CXXBaseSpecifier &B) {
6927             return containsAnyFP16Vectors(B.getType());
6928           }))
6929         return true;
6930 
6931     if (llvm::any_of(RD->fields(), [this](FieldDecl *FD) {
6932           return FD && containsAnyFP16Vectors(FD->getType());
6933         }))
6934       return true;
6935 
6936     return false;
6937   } else {
6938     if (const VectorType *VT = Ty->getAs<VectorType>())
6939       return (VT->getElementType()->isFloat16Type() ||
6940               VT->getElementType()->isBFloat16Type() ||
6941               VT->getElementType()->isHalfType());
6942     return false;
6943   }
6944 }
6945 
6946 bool ARMABIInfo::isLegalVectorTypeForSwift(CharUnits vectorSize,
6947                                            llvm::Type *eltTy,
6948                                            unsigned numElts) const {
6949   if (!llvm::isPowerOf2_32(numElts))
6950     return false;
6951   unsigned size = getDataLayout().getTypeStoreSizeInBits(eltTy);
6952   if (size > 64)
6953     return false;
6954   if (vectorSize.getQuantity() != 8 &&
6955       (vectorSize.getQuantity() != 16 || numElts == 1))
6956     return false;
6957   return true;
6958 }
6959 
6960 bool ARMABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
6961   // Homogeneous aggregates for AAPCS-VFP must have base types of float,
6962   // double, or 64-bit or 128-bit vectors.
6963   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
6964     if (BT->getKind() == BuiltinType::Float ||
6965         BT->getKind() == BuiltinType::Double ||
6966         BT->getKind() == BuiltinType::LongDouble)
6967       return true;
6968   } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
6969     unsigned VecSize = getContext().getTypeSize(VT);
6970     if (VecSize == 64 || VecSize == 128)
6971       return true;
6972   }
6973   return false;
6974 }
6975 
6976 bool ARMABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
6977                                                    uint64_t Members) const {
6978   return Members <= 4;
6979 }
6980 
6981 bool ARMABIInfo::isEffectivelyAAPCS_VFP(unsigned callConvention,
6982                                         bool acceptHalf) const {
6983   // Give precedence to user-specified calling conventions.
6984   if (callConvention != llvm::CallingConv::C)
6985     return (callConvention == llvm::CallingConv::ARM_AAPCS_VFP);
6986   else
6987     return (getABIKind() == AAPCS_VFP) ||
6988            (acceptHalf && (getABIKind() == AAPCS16_VFP));
6989 }
6990 
6991 Address ARMABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6992                               QualType Ty) const {
6993   CharUnits SlotSize = CharUnits::fromQuantity(4);
6994 
6995   // Empty records are ignored for parameter passing purposes.
6996   if (isEmptyRecord(getContext(), Ty, true)) {
6997     Address Addr = Address(CGF.Builder.CreateLoad(VAListAddr),
6998                            getVAListElementType(CGF), SlotSize);
6999     Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
7000     return Addr;
7001   }
7002 
7003   CharUnits TySize = getContext().getTypeSizeInChars(Ty);
7004   CharUnits TyAlignForABI = getContext().getTypeUnadjustedAlignInChars(Ty);
7005 
7006   // Use indirect if size of the illegal vector is bigger than 16 bytes.
7007   bool IsIndirect = false;
7008   const Type *Base = nullptr;
7009   uint64_t Members = 0;
7010   if (TySize > CharUnits::fromQuantity(16) && isIllegalVectorType(Ty)) {
7011     IsIndirect = true;
7012 
7013   // ARMv7k passes structs bigger than 16 bytes indirectly, in space
7014   // allocated by the caller.
7015   } else if (TySize > CharUnits::fromQuantity(16) &&
7016              getABIKind() == ARMABIInfo::AAPCS16_VFP &&
7017              !isHomogeneousAggregate(Ty, Base, Members)) {
7018     IsIndirect = true;
7019 
7020   // Otherwise, bound the type's ABI alignment.
7021   // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
7022   // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
7023   // Our callers should be prepared to handle an under-aligned address.
7024   } else if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
7025              getABIKind() == ARMABIInfo::AAPCS) {
7026     TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
7027     TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(8));
7028   } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
7029     // ARMv7k allows type alignment up to 16 bytes.
7030     TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
7031     TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(16));
7032   } else {
7033     TyAlignForABI = CharUnits::fromQuantity(4);
7034   }
7035 
7036   TypeInfoChars TyInfo(TySize, TyAlignForABI, AlignRequirementKind::None);
7037   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TyInfo,
7038                           SlotSize, /*AllowHigherAlign*/ true);
7039 }
7040 
7041 //===----------------------------------------------------------------------===//
7042 // NVPTX ABI Implementation
7043 //===----------------------------------------------------------------------===//
7044 
7045 namespace {
7046 
7047 class NVPTXTargetCodeGenInfo;
7048 
7049 class NVPTXABIInfo : public ABIInfo {
7050   NVPTXTargetCodeGenInfo &CGInfo;
7051 
7052 public:
7053   NVPTXABIInfo(CodeGenTypes &CGT, NVPTXTargetCodeGenInfo &Info)
7054       : ABIInfo(CGT), CGInfo(Info) {}
7055 
7056   ABIArgInfo classifyReturnType(QualType RetTy) const;
7057   ABIArgInfo classifyArgumentType(QualType Ty) const;
7058 
7059   void computeInfo(CGFunctionInfo &FI) const override;
7060   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7061                     QualType Ty) const override;
7062   bool isUnsupportedType(QualType T) const;
7063   ABIArgInfo coerceToIntArrayWithLimit(QualType Ty, unsigned MaxSize) const;
7064 };
7065 
7066 class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
7067 public:
7068   NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
7069       : TargetCodeGenInfo(std::make_unique<NVPTXABIInfo>(CGT, *this)) {}
7070 
7071   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
7072                            CodeGen::CodeGenModule &M) const override;
7073   bool shouldEmitStaticExternCAliases() const override;
7074 
7075   llvm::Type *getCUDADeviceBuiltinSurfaceDeviceType() const override {
7076     // On the device side, surface reference is represented as an object handle
7077     // in 64-bit integer.
7078     return llvm::Type::getInt64Ty(getABIInfo().getVMContext());
7079   }
7080 
7081   llvm::Type *getCUDADeviceBuiltinTextureDeviceType() const override {
7082     // On the device side, texture reference is represented as an object handle
7083     // in 64-bit integer.
7084     return llvm::Type::getInt64Ty(getABIInfo().getVMContext());
7085   }
7086 
7087   bool emitCUDADeviceBuiltinSurfaceDeviceCopy(CodeGenFunction &CGF, LValue Dst,
7088                                               LValue Src) const override {
7089     emitBuiltinSurfTexDeviceCopy(CGF, Dst, Src);
7090     return true;
7091   }
7092 
7093   bool emitCUDADeviceBuiltinTextureDeviceCopy(CodeGenFunction &CGF, LValue Dst,
7094                                               LValue Src) const override {
7095     emitBuiltinSurfTexDeviceCopy(CGF, Dst, Src);
7096     return true;
7097   }
7098 
7099 private:
7100   // Adds a NamedMDNode with GV, Name, and Operand as operands, and adds the
7101   // resulting MDNode to the nvvm.annotations MDNode.
7102   static void addNVVMMetadata(llvm::GlobalValue *GV, StringRef Name,
7103                               int Operand);
7104 
7105   static void emitBuiltinSurfTexDeviceCopy(CodeGenFunction &CGF, LValue Dst,
7106                                            LValue Src) {
7107     llvm::Value *Handle = nullptr;
7108     llvm::Constant *C =
7109         llvm::dyn_cast<llvm::Constant>(Src.getAddress(CGF).getPointer());
7110     // Lookup `addrspacecast` through the constant pointer if any.
7111     if (auto *ASC = llvm::dyn_cast_or_null<llvm::AddrSpaceCastOperator>(C))
7112       C = llvm::cast<llvm::Constant>(ASC->getPointerOperand());
7113     if (auto *GV = llvm::dyn_cast_or_null<llvm::GlobalVariable>(C)) {
7114       // Load the handle from the specific global variable using
7115       // `nvvm.texsurf.handle.internal` intrinsic.
7116       Handle = CGF.EmitRuntimeCall(
7117           CGF.CGM.getIntrinsic(llvm::Intrinsic::nvvm_texsurf_handle_internal,
7118                                {GV->getType()}),
7119           {GV}, "texsurf_handle");
7120     } else
7121       Handle = CGF.EmitLoadOfScalar(Src, SourceLocation());
7122     CGF.EmitStoreOfScalar(Handle, Dst);
7123   }
7124 };
7125 
7126 /// Checks if the type is unsupported directly by the current target.
7127 bool NVPTXABIInfo::isUnsupportedType(QualType T) const {
7128   ASTContext &Context = getContext();
7129   if (!Context.getTargetInfo().hasFloat16Type() && T->isFloat16Type())
7130     return true;
7131   if (!Context.getTargetInfo().hasFloat128Type() &&
7132       (T->isFloat128Type() ||
7133        (T->isRealFloatingType() && Context.getTypeSize(T) == 128)))
7134     return true;
7135   if (const auto *EIT = T->getAs<BitIntType>())
7136     return EIT->getNumBits() >
7137            (Context.getTargetInfo().hasInt128Type() ? 128U : 64U);
7138   if (!Context.getTargetInfo().hasInt128Type() && T->isIntegerType() &&
7139       Context.getTypeSize(T) > 64U)
7140     return true;
7141   if (const auto *AT = T->getAsArrayTypeUnsafe())
7142     return isUnsupportedType(AT->getElementType());
7143   const auto *RT = T->getAs<RecordType>();
7144   if (!RT)
7145     return false;
7146   const RecordDecl *RD = RT->getDecl();
7147 
7148   // If this is a C++ record, check the bases first.
7149   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
7150     for (const CXXBaseSpecifier &I : CXXRD->bases())
7151       if (isUnsupportedType(I.getType()))
7152         return true;
7153 
7154   for (const FieldDecl *I : RD->fields())
7155     if (isUnsupportedType(I->getType()))
7156       return true;
7157   return false;
7158 }
7159 
7160 /// Coerce the given type into an array with maximum allowed size of elements.
7161 ABIArgInfo NVPTXABIInfo::coerceToIntArrayWithLimit(QualType Ty,
7162                                                    unsigned MaxSize) const {
7163   // Alignment and Size are measured in bits.
7164   const uint64_t Size = getContext().getTypeSize(Ty);
7165   const uint64_t Alignment = getContext().getTypeAlign(Ty);
7166   const unsigned Div = std::min<unsigned>(MaxSize, Alignment);
7167   llvm::Type *IntType = llvm::Type::getIntNTy(getVMContext(), Div);
7168   const uint64_t NumElements = (Size + Div - 1) / Div;
7169   return ABIArgInfo::getDirect(llvm::ArrayType::get(IntType, NumElements));
7170 }
7171 
7172 ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
7173   if (RetTy->isVoidType())
7174     return ABIArgInfo::getIgnore();
7175 
7176   if (getContext().getLangOpts().OpenMP &&
7177       getContext().getLangOpts().OpenMPIsDevice && isUnsupportedType(RetTy))
7178     return coerceToIntArrayWithLimit(RetTy, 64);
7179 
7180   // note: this is different from default ABI
7181   if (!RetTy->isScalarType())
7182     return ABIArgInfo::getDirect();
7183 
7184   // Treat an enum type as its underlying type.
7185   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
7186     RetTy = EnumTy->getDecl()->getIntegerType();
7187 
7188   return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
7189                                                : ABIArgInfo::getDirect());
7190 }
7191 
7192 ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
7193   // Treat an enum type as its underlying type.
7194   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7195     Ty = EnumTy->getDecl()->getIntegerType();
7196 
7197   // Return aggregates type as indirect by value
7198   if (isAggregateTypeForABI(Ty)) {
7199     // Under CUDA device compilation, tex/surf builtin types are replaced with
7200     // object types and passed directly.
7201     if (getContext().getLangOpts().CUDAIsDevice) {
7202       if (Ty->isCUDADeviceBuiltinSurfaceType())
7203         return ABIArgInfo::getDirect(
7204             CGInfo.getCUDADeviceBuiltinSurfaceDeviceType());
7205       if (Ty->isCUDADeviceBuiltinTextureType())
7206         return ABIArgInfo::getDirect(
7207             CGInfo.getCUDADeviceBuiltinTextureDeviceType());
7208     }
7209     return getNaturalAlignIndirect(Ty, /* byval */ true);
7210   }
7211 
7212   if (const auto *EIT = Ty->getAs<BitIntType>()) {
7213     if ((EIT->getNumBits() > 128) ||
7214         (!getContext().getTargetInfo().hasInt128Type() &&
7215          EIT->getNumBits() > 64))
7216       return getNaturalAlignIndirect(Ty, /* byval */ true);
7217   }
7218 
7219   return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
7220                                             : ABIArgInfo::getDirect());
7221 }
7222 
7223 void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
7224   if (!getCXXABI().classifyReturnType(FI))
7225     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7226   for (auto &I : FI.arguments())
7227     I.info = classifyArgumentType(I.type);
7228 
7229   // Always honor user-specified calling convention.
7230   if (FI.getCallingConvention() != llvm::CallingConv::C)
7231     return;
7232 
7233   FI.setEffectiveCallingConvention(getRuntimeCC());
7234 }
7235 
7236 Address NVPTXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7237                                 QualType Ty) const {
7238   llvm_unreachable("NVPTX does not support varargs");
7239 }
7240 
7241 void NVPTXTargetCodeGenInfo::setTargetAttributes(
7242     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
7243   if (GV->isDeclaration())
7244     return;
7245   const VarDecl *VD = dyn_cast_or_null<VarDecl>(D);
7246   if (VD) {
7247     if (M.getLangOpts().CUDA) {
7248       if (VD->getType()->isCUDADeviceBuiltinSurfaceType())
7249         addNVVMMetadata(GV, "surface", 1);
7250       else if (VD->getType()->isCUDADeviceBuiltinTextureType())
7251         addNVVMMetadata(GV, "texture", 1);
7252       return;
7253     }
7254   }
7255 
7256   const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
7257   if (!FD) return;
7258 
7259   llvm::Function *F = cast<llvm::Function>(GV);
7260 
7261   // Perform special handling in OpenCL mode
7262   if (M.getLangOpts().OpenCL) {
7263     // Use OpenCL function attributes to check for kernel functions
7264     // By default, all functions are device functions
7265     if (FD->hasAttr<OpenCLKernelAttr>()) {
7266       // OpenCL __kernel functions get kernel metadata
7267       // Create !{<func-ref>, metadata !"kernel", i32 1} node
7268       addNVVMMetadata(F, "kernel", 1);
7269       // And kernel functions are not subject to inlining
7270       F->addFnAttr(llvm::Attribute::NoInline);
7271     }
7272   }
7273 
7274   // Perform special handling in CUDA mode.
7275   if (M.getLangOpts().CUDA) {
7276     // CUDA __global__ functions get a kernel metadata entry.  Since
7277     // __global__ functions cannot be called from the device, we do not
7278     // need to set the noinline attribute.
7279     if (FD->hasAttr<CUDAGlobalAttr>()) {
7280       // Create !{<func-ref>, metadata !"kernel", i32 1} node
7281       addNVVMMetadata(F, "kernel", 1);
7282     }
7283     if (CUDALaunchBoundsAttr *Attr = FD->getAttr<CUDALaunchBoundsAttr>()) {
7284       // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node
7285       llvm::APSInt MaxThreads(32);
7286       MaxThreads = Attr->getMaxThreads()->EvaluateKnownConstInt(M.getContext());
7287       if (MaxThreads > 0)
7288         addNVVMMetadata(F, "maxntidx", MaxThreads.getExtValue());
7289 
7290       // min blocks is an optional argument for CUDALaunchBoundsAttr. If it was
7291       // not specified in __launch_bounds__ or if the user specified a 0 value,
7292       // we don't have to add a PTX directive.
7293       if (Attr->getMinBlocks()) {
7294         llvm::APSInt MinBlocks(32);
7295         MinBlocks = Attr->getMinBlocks()->EvaluateKnownConstInt(M.getContext());
7296         if (MinBlocks > 0)
7297           // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node
7298           addNVVMMetadata(F, "minctasm", MinBlocks.getExtValue());
7299       }
7300     }
7301   }
7302 }
7303 
7304 void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::GlobalValue *GV,
7305                                              StringRef Name, int Operand) {
7306   llvm::Module *M = GV->getParent();
7307   llvm::LLVMContext &Ctx = M->getContext();
7308 
7309   // Get "nvvm.annotations" metadata node
7310   llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
7311 
7312   llvm::Metadata *MDVals[] = {
7313       llvm::ConstantAsMetadata::get(GV), llvm::MDString::get(Ctx, Name),
7314       llvm::ConstantAsMetadata::get(
7315           llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand))};
7316   // Append metadata to nvvm.annotations
7317   MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
7318 }
7319 
7320 bool NVPTXTargetCodeGenInfo::shouldEmitStaticExternCAliases() const {
7321   return false;
7322 }
7323 }
7324 
7325 //===----------------------------------------------------------------------===//
7326 // SystemZ ABI Implementation
7327 //===----------------------------------------------------------------------===//
7328 
7329 namespace {
7330 
7331 class SystemZABIInfo : public SwiftABIInfo {
7332   bool HasVector;
7333   bool IsSoftFloatABI;
7334 
7335 public:
7336   SystemZABIInfo(CodeGenTypes &CGT, bool HV, bool SF)
7337     : SwiftABIInfo(CGT), HasVector(HV), IsSoftFloatABI(SF) {}
7338 
7339   bool isPromotableIntegerTypeForABI(QualType Ty) const;
7340   bool isCompoundType(QualType Ty) const;
7341   bool isVectorArgumentType(QualType Ty) const;
7342   bool isFPArgumentType(QualType Ty) const;
7343   QualType GetSingleElementType(QualType Ty) const;
7344 
7345   ABIArgInfo classifyReturnType(QualType RetTy) const;
7346   ABIArgInfo classifyArgumentType(QualType ArgTy) const;
7347 
7348   void computeInfo(CGFunctionInfo &FI) const override {
7349     if (!getCXXABI().classifyReturnType(FI))
7350       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7351     for (auto &I : FI.arguments())
7352       I.info = classifyArgumentType(I.type);
7353   }
7354 
7355   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7356                     QualType Ty) const override;
7357 
7358   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
7359                                     bool asReturnValue) const override {
7360     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
7361   }
7362   bool isSwiftErrorInRegister() const override {
7363     return false;
7364   }
7365 };
7366 
7367 class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
7368 public:
7369   SystemZTargetCodeGenInfo(CodeGenTypes &CGT, bool HasVector, bool SoftFloatABI)
7370       : TargetCodeGenInfo(
7371             std::make_unique<SystemZABIInfo>(CGT, HasVector, SoftFloatABI)) {}
7372 
7373   llvm::Value *testFPKind(llvm::Value *V, unsigned BuiltinID,
7374                           CGBuilderTy &Builder,
7375                           CodeGenModule &CGM) const override {
7376     assert(V->getType()->isFloatingPointTy() && "V should have an FP type.");
7377     // Only use TDC in constrained FP mode.
7378     if (!Builder.getIsFPConstrained())
7379       return nullptr;
7380 
7381     llvm::Type *Ty = V->getType();
7382     if (Ty->isFloatTy() || Ty->isDoubleTy() || Ty->isFP128Ty()) {
7383       llvm::Module &M = CGM.getModule();
7384       auto &Ctx = M.getContext();
7385       llvm::Function *TDCFunc =
7386           llvm::Intrinsic::getDeclaration(&M, llvm::Intrinsic::s390_tdc, Ty);
7387       unsigned TDCBits = 0;
7388       switch (BuiltinID) {
7389       case Builtin::BI__builtin_isnan:
7390         TDCBits = 0xf;
7391         break;
7392       case Builtin::BIfinite:
7393       case Builtin::BI__finite:
7394       case Builtin::BIfinitef:
7395       case Builtin::BI__finitef:
7396       case Builtin::BIfinitel:
7397       case Builtin::BI__finitel:
7398       case Builtin::BI__builtin_isfinite:
7399         TDCBits = 0xfc0;
7400         break;
7401       case Builtin::BI__builtin_isinf:
7402         TDCBits = 0x30;
7403         break;
7404       default:
7405         break;
7406       }
7407       if (TDCBits)
7408         return Builder.CreateCall(
7409             TDCFunc,
7410             {V, llvm::ConstantInt::get(llvm::Type::getInt64Ty(Ctx), TDCBits)});
7411     }
7412     return nullptr;
7413   }
7414 };
7415 }
7416 
7417 bool SystemZABIInfo::isPromotableIntegerTypeForABI(QualType Ty) const {
7418   // Treat an enum type as its underlying type.
7419   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7420     Ty = EnumTy->getDecl()->getIntegerType();
7421 
7422   // Promotable integer types are required to be promoted by the ABI.
7423   if (ABIInfo::isPromotableIntegerTypeForABI(Ty))
7424     return true;
7425 
7426   if (const auto *EIT = Ty->getAs<BitIntType>())
7427     if (EIT->getNumBits() < 64)
7428       return true;
7429 
7430   // 32-bit values must also be promoted.
7431   if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
7432     switch (BT->getKind()) {
7433     case BuiltinType::Int:
7434     case BuiltinType::UInt:
7435       return true;
7436     default:
7437       return false;
7438     }
7439   return false;
7440 }
7441 
7442 bool SystemZABIInfo::isCompoundType(QualType Ty) const {
7443   return (Ty->isAnyComplexType() ||
7444           Ty->isVectorType() ||
7445           isAggregateTypeForABI(Ty));
7446 }
7447 
7448 bool SystemZABIInfo::isVectorArgumentType(QualType Ty) const {
7449   return (HasVector &&
7450           Ty->isVectorType() &&
7451           getContext().getTypeSize(Ty) <= 128);
7452 }
7453 
7454 bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
7455   if (IsSoftFloatABI)
7456     return false;
7457 
7458   if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
7459     switch (BT->getKind()) {
7460     case BuiltinType::Float:
7461     case BuiltinType::Double:
7462       return true;
7463     default:
7464       return false;
7465     }
7466 
7467   return false;
7468 }
7469 
7470 QualType SystemZABIInfo::GetSingleElementType(QualType Ty) const {
7471   const RecordType *RT = Ty->getAs<RecordType>();
7472 
7473   if (RT && RT->isStructureOrClassType()) {
7474     const RecordDecl *RD = RT->getDecl();
7475     QualType Found;
7476 
7477     // If this is a C++ record, check the bases first.
7478     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
7479       for (const auto &I : CXXRD->bases()) {
7480         QualType Base = I.getType();
7481 
7482         // Empty bases don't affect things either way.
7483         if (isEmptyRecord(getContext(), Base, true))
7484           continue;
7485 
7486         if (!Found.isNull())
7487           return Ty;
7488         Found = GetSingleElementType(Base);
7489       }
7490 
7491     // Check the fields.
7492     for (const auto *FD : RD->fields()) {
7493       // For compatibility with GCC, ignore empty bitfields in C++ mode.
7494       // Unlike isSingleElementStruct(), empty structure and array fields
7495       // do count.  So do anonymous bitfields that aren't zero-sized.
7496       if (getContext().getLangOpts().CPlusPlus &&
7497           FD->isZeroLengthBitField(getContext()))
7498         continue;
7499       // Like isSingleElementStruct(), ignore C++20 empty data members.
7500       if (FD->hasAttr<NoUniqueAddressAttr>() &&
7501           isEmptyRecord(getContext(), FD->getType(), true))
7502         continue;
7503 
7504       // Unlike isSingleElementStruct(), arrays do not count.
7505       // Nested structures still do though.
7506       if (!Found.isNull())
7507         return Ty;
7508       Found = GetSingleElementType(FD->getType());
7509     }
7510 
7511     // Unlike isSingleElementStruct(), trailing padding is allowed.
7512     // An 8-byte aligned struct s { float f; } is passed as a double.
7513     if (!Found.isNull())
7514       return Found;
7515   }
7516 
7517   return Ty;
7518 }
7519 
7520 Address SystemZABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7521                                   QualType Ty) const {
7522   // Assume that va_list type is correct; should be pointer to LLVM type:
7523   // struct {
7524   //   i64 __gpr;
7525   //   i64 __fpr;
7526   //   i8 *__overflow_arg_area;
7527   //   i8 *__reg_save_area;
7528   // };
7529 
7530   // Every non-vector argument occupies 8 bytes and is passed by preference
7531   // in either GPRs or FPRs.  Vector arguments occupy 8 or 16 bytes and are
7532   // always passed on the stack.
7533   Ty = getContext().getCanonicalType(Ty);
7534   auto TyInfo = getContext().getTypeInfoInChars(Ty);
7535   llvm::Type *ArgTy = CGF.ConvertTypeForMem(Ty);
7536   llvm::Type *DirectTy = ArgTy;
7537   ABIArgInfo AI = classifyArgumentType(Ty);
7538   bool IsIndirect = AI.isIndirect();
7539   bool InFPRs = false;
7540   bool IsVector = false;
7541   CharUnits UnpaddedSize;
7542   CharUnits DirectAlign;
7543   if (IsIndirect) {
7544     DirectTy = llvm::PointerType::getUnqual(DirectTy);
7545     UnpaddedSize = DirectAlign = CharUnits::fromQuantity(8);
7546   } else {
7547     if (AI.getCoerceToType())
7548       ArgTy = AI.getCoerceToType();
7549     InFPRs = (!IsSoftFloatABI && (ArgTy->isFloatTy() || ArgTy->isDoubleTy()));
7550     IsVector = ArgTy->isVectorTy();
7551     UnpaddedSize = TyInfo.Width;
7552     DirectAlign = TyInfo.Align;
7553   }
7554   CharUnits PaddedSize = CharUnits::fromQuantity(8);
7555   if (IsVector && UnpaddedSize > PaddedSize)
7556     PaddedSize = CharUnits::fromQuantity(16);
7557   assert((UnpaddedSize <= PaddedSize) && "Invalid argument size.");
7558 
7559   CharUnits Padding = (PaddedSize - UnpaddedSize);
7560 
7561   llvm::Type *IndexTy = CGF.Int64Ty;
7562   llvm::Value *PaddedSizeV =
7563     llvm::ConstantInt::get(IndexTy, PaddedSize.getQuantity());
7564 
7565   if (IsVector) {
7566     // Work out the address of a vector argument on the stack.
7567     // Vector arguments are always passed in the high bits of a
7568     // single (8 byte) or double (16 byte) stack slot.
7569     Address OverflowArgAreaPtr =
7570         CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr");
7571     Address OverflowArgArea =
7572         Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
7573                 CGF.Int8Ty, TyInfo.Align);
7574     Address MemAddr =
7575         CGF.Builder.CreateElementBitCast(OverflowArgArea, DirectTy, "mem_addr");
7576 
7577     // Update overflow_arg_area_ptr pointer
7578     llvm::Value *NewOverflowArgArea = CGF.Builder.CreateGEP(
7579         OverflowArgArea.getElementType(), OverflowArgArea.getPointer(),
7580         PaddedSizeV, "overflow_arg_area");
7581     CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
7582 
7583     return MemAddr;
7584   }
7585 
7586   assert(PaddedSize.getQuantity() == 8);
7587 
7588   unsigned MaxRegs, RegCountField, RegSaveIndex;
7589   CharUnits RegPadding;
7590   if (InFPRs) {
7591     MaxRegs = 4; // Maximum of 4 FPR arguments
7592     RegCountField = 1; // __fpr
7593     RegSaveIndex = 16; // save offset for f0
7594     RegPadding = CharUnits(); // floats are passed in the high bits of an FPR
7595   } else {
7596     MaxRegs = 5; // Maximum of 5 GPR arguments
7597     RegCountField = 0; // __gpr
7598     RegSaveIndex = 2; // save offset for r2
7599     RegPadding = Padding; // values are passed in the low bits of a GPR
7600   }
7601 
7602   Address RegCountPtr =
7603       CGF.Builder.CreateStructGEP(VAListAddr, RegCountField, "reg_count_ptr");
7604   llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
7605   llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
7606   llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
7607                                                  "fits_in_regs");
7608 
7609   llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
7610   llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
7611   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
7612   CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
7613 
7614   // Emit code to load the value if it was passed in registers.
7615   CGF.EmitBlock(InRegBlock);
7616 
7617   // Work out the address of an argument register.
7618   llvm::Value *ScaledRegCount =
7619     CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
7620   llvm::Value *RegBase =
7621     llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize.getQuantity()
7622                                       + RegPadding.getQuantity());
7623   llvm::Value *RegOffset =
7624     CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
7625   Address RegSaveAreaPtr =
7626       CGF.Builder.CreateStructGEP(VAListAddr, 3, "reg_save_area_ptr");
7627   llvm::Value *RegSaveArea =
7628       CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
7629   Address RawRegAddr(
7630       CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, RegOffset, "raw_reg_addr"),
7631       CGF.Int8Ty, PaddedSize);
7632   Address RegAddr =
7633       CGF.Builder.CreateElementBitCast(RawRegAddr, DirectTy, "reg_addr");
7634 
7635   // Update the register count
7636   llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
7637   llvm::Value *NewRegCount =
7638     CGF.Builder.CreateAdd(RegCount, One, "reg_count");
7639   CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
7640   CGF.EmitBranch(ContBlock);
7641 
7642   // Emit code to load the value if it was passed in memory.
7643   CGF.EmitBlock(InMemBlock);
7644 
7645   // Work out the address of a stack argument.
7646   Address OverflowArgAreaPtr =
7647       CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr");
7648   Address OverflowArgArea =
7649       Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
7650               CGF.Int8Ty, PaddedSize);
7651   Address RawMemAddr =
7652       CGF.Builder.CreateConstByteGEP(OverflowArgArea, Padding, "raw_mem_addr");
7653   Address MemAddr =
7654     CGF.Builder.CreateElementBitCast(RawMemAddr, DirectTy, "mem_addr");
7655 
7656   // Update overflow_arg_area_ptr pointer
7657   llvm::Value *NewOverflowArgArea =
7658     CGF.Builder.CreateGEP(OverflowArgArea.getElementType(),
7659                           OverflowArgArea.getPointer(), PaddedSizeV,
7660                           "overflow_arg_area");
7661   CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
7662   CGF.EmitBranch(ContBlock);
7663 
7664   // Return the appropriate result.
7665   CGF.EmitBlock(ContBlock);
7666   Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, MemAddr, InMemBlock,
7667                                  "va_arg.addr");
7668 
7669   if (IsIndirect)
7670     ResAddr = Address(CGF.Builder.CreateLoad(ResAddr, "indirect_arg"), ArgTy,
7671                       TyInfo.Align);
7672 
7673   return ResAddr;
7674 }
7675 
7676 ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
7677   if (RetTy->isVoidType())
7678     return ABIArgInfo::getIgnore();
7679   if (isVectorArgumentType(RetTy))
7680     return ABIArgInfo::getDirect();
7681   if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
7682     return getNaturalAlignIndirect(RetTy);
7683   return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
7684                                                : ABIArgInfo::getDirect());
7685 }
7686 
7687 ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
7688   // Handle the generic C++ ABI.
7689   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
7690     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
7691 
7692   // Integers and enums are extended to full register width.
7693   if (isPromotableIntegerTypeForABI(Ty))
7694     return ABIArgInfo::getExtend(Ty);
7695 
7696   // Handle vector types and vector-like structure types.  Note that
7697   // as opposed to float-like structure types, we do not allow any
7698   // padding for vector-like structures, so verify the sizes match.
7699   uint64_t Size = getContext().getTypeSize(Ty);
7700   QualType SingleElementTy = GetSingleElementType(Ty);
7701   if (isVectorArgumentType(SingleElementTy) &&
7702       getContext().getTypeSize(SingleElementTy) == Size)
7703     return ABIArgInfo::getDirect(CGT.ConvertType(SingleElementTy));
7704 
7705   // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
7706   if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
7707     return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
7708 
7709   // Handle small structures.
7710   if (const RecordType *RT = Ty->getAs<RecordType>()) {
7711     // Structures with flexible arrays have variable length, so really
7712     // fail the size test above.
7713     const RecordDecl *RD = RT->getDecl();
7714     if (RD->hasFlexibleArrayMember())
7715       return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
7716 
7717     // The structure is passed as an unextended integer, a float, or a double.
7718     llvm::Type *PassTy;
7719     if (isFPArgumentType(SingleElementTy)) {
7720       assert(Size == 32 || Size == 64);
7721       if (Size == 32)
7722         PassTy = llvm::Type::getFloatTy(getVMContext());
7723       else
7724         PassTy = llvm::Type::getDoubleTy(getVMContext());
7725     } else
7726       PassTy = llvm::IntegerType::get(getVMContext(), Size);
7727     return ABIArgInfo::getDirect(PassTy);
7728   }
7729 
7730   // Non-structure compounds are passed indirectly.
7731   if (isCompoundType(Ty))
7732     return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
7733 
7734   return ABIArgInfo::getDirect(nullptr);
7735 }
7736 
7737 //===----------------------------------------------------------------------===//
7738 // MSP430 ABI Implementation
7739 //===----------------------------------------------------------------------===//
7740 
7741 namespace {
7742 
7743 class MSP430ABIInfo : public DefaultABIInfo {
7744   static ABIArgInfo complexArgInfo() {
7745     ABIArgInfo Info = ABIArgInfo::getDirect();
7746     Info.setCanBeFlattened(false);
7747     return Info;
7748   }
7749 
7750 public:
7751   MSP430ABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
7752 
7753   ABIArgInfo classifyReturnType(QualType RetTy) const {
7754     if (RetTy->isAnyComplexType())
7755       return complexArgInfo();
7756 
7757     return DefaultABIInfo::classifyReturnType(RetTy);
7758   }
7759 
7760   ABIArgInfo classifyArgumentType(QualType RetTy) const {
7761     if (RetTy->isAnyComplexType())
7762       return complexArgInfo();
7763 
7764     return DefaultABIInfo::classifyArgumentType(RetTy);
7765   }
7766 
7767   // Just copy the original implementations because
7768   // DefaultABIInfo::classify{Return,Argument}Type() are not virtual
7769   void computeInfo(CGFunctionInfo &FI) const override {
7770     if (!getCXXABI().classifyReturnType(FI))
7771       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7772     for (auto &I : FI.arguments())
7773       I.info = classifyArgumentType(I.type);
7774   }
7775 
7776   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7777                     QualType Ty) const override {
7778     return EmitVAArgInstr(CGF, VAListAddr, Ty, classifyArgumentType(Ty));
7779   }
7780 };
7781 
7782 class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
7783 public:
7784   MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
7785       : TargetCodeGenInfo(std::make_unique<MSP430ABIInfo>(CGT)) {}
7786   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
7787                            CodeGen::CodeGenModule &M) const override;
7788 };
7789 
7790 }
7791 
7792 void MSP430TargetCodeGenInfo::setTargetAttributes(
7793     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
7794   if (GV->isDeclaration())
7795     return;
7796   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
7797     const auto *InterruptAttr = FD->getAttr<MSP430InterruptAttr>();
7798     if (!InterruptAttr)
7799       return;
7800 
7801     // Handle 'interrupt' attribute:
7802     llvm::Function *F = cast<llvm::Function>(GV);
7803 
7804     // Step 1: Set ISR calling convention.
7805     F->setCallingConv(llvm::CallingConv::MSP430_INTR);
7806 
7807     // Step 2: Add attributes goodness.
7808     F->addFnAttr(llvm::Attribute::NoInline);
7809     F->addFnAttr("interrupt", llvm::utostr(InterruptAttr->getNumber()));
7810   }
7811 }
7812 
7813 //===----------------------------------------------------------------------===//
7814 // MIPS ABI Implementation.  This works for both little-endian and
7815 // big-endian variants.
7816 //===----------------------------------------------------------------------===//
7817 
7818 namespace {
7819 class MipsABIInfo : public ABIInfo {
7820   bool IsO32;
7821   unsigned MinABIStackAlignInBytes, StackAlignInBytes;
7822   void CoerceToIntArgs(uint64_t TySize,
7823                        SmallVectorImpl<llvm::Type *> &ArgList) const;
7824   llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
7825   llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
7826   llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
7827 public:
7828   MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
7829     ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
7830     StackAlignInBytes(IsO32 ? 8 : 16) {}
7831 
7832   ABIArgInfo classifyReturnType(QualType RetTy) const;
7833   ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
7834   void computeInfo(CGFunctionInfo &FI) const override;
7835   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7836                     QualType Ty) const override;
7837   ABIArgInfo extendType(QualType Ty) const;
7838 };
7839 
7840 class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
7841   unsigned SizeOfUnwindException;
7842 public:
7843   MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
7844       : TargetCodeGenInfo(std::make_unique<MipsABIInfo>(CGT, IsO32)),
7845         SizeOfUnwindException(IsO32 ? 24 : 32) {}
7846 
7847   int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
7848     return 29;
7849   }
7850 
7851   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
7852                            CodeGen::CodeGenModule &CGM) const override {
7853     const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
7854     if (!FD) return;
7855     llvm::Function *Fn = cast<llvm::Function>(GV);
7856 
7857     if (FD->hasAttr<MipsLongCallAttr>())
7858       Fn->addFnAttr("long-call");
7859     else if (FD->hasAttr<MipsShortCallAttr>())
7860       Fn->addFnAttr("short-call");
7861 
7862     // Other attributes do not have a meaning for declarations.
7863     if (GV->isDeclaration())
7864       return;
7865 
7866     if (FD->hasAttr<Mips16Attr>()) {
7867       Fn->addFnAttr("mips16");
7868     }
7869     else if (FD->hasAttr<NoMips16Attr>()) {
7870       Fn->addFnAttr("nomips16");
7871     }
7872 
7873     if (FD->hasAttr<MicroMipsAttr>())
7874       Fn->addFnAttr("micromips");
7875     else if (FD->hasAttr<NoMicroMipsAttr>())
7876       Fn->addFnAttr("nomicromips");
7877 
7878     const MipsInterruptAttr *Attr = FD->getAttr<MipsInterruptAttr>();
7879     if (!Attr)
7880       return;
7881 
7882     const char *Kind;
7883     switch (Attr->getInterrupt()) {
7884     case MipsInterruptAttr::eic:     Kind = "eic"; break;
7885     case MipsInterruptAttr::sw0:     Kind = "sw0"; break;
7886     case MipsInterruptAttr::sw1:     Kind = "sw1"; break;
7887     case MipsInterruptAttr::hw0:     Kind = "hw0"; break;
7888     case MipsInterruptAttr::hw1:     Kind = "hw1"; break;
7889     case MipsInterruptAttr::hw2:     Kind = "hw2"; break;
7890     case MipsInterruptAttr::hw3:     Kind = "hw3"; break;
7891     case MipsInterruptAttr::hw4:     Kind = "hw4"; break;
7892     case MipsInterruptAttr::hw5:     Kind = "hw5"; break;
7893     }
7894 
7895     Fn->addFnAttr("interrupt", Kind);
7896 
7897   }
7898 
7899   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
7900                                llvm::Value *Address) const override;
7901 
7902   unsigned getSizeOfUnwindException() const override {
7903     return SizeOfUnwindException;
7904   }
7905 };
7906 }
7907 
7908 void MipsABIInfo::CoerceToIntArgs(
7909     uint64_t TySize, SmallVectorImpl<llvm::Type *> &ArgList) const {
7910   llvm::IntegerType *IntTy =
7911     llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
7912 
7913   // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
7914   for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
7915     ArgList.push_back(IntTy);
7916 
7917   // If necessary, add one more integer type to ArgList.
7918   unsigned R = TySize % (MinABIStackAlignInBytes * 8);
7919 
7920   if (R)
7921     ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
7922 }
7923 
7924 // In N32/64, an aligned double precision floating point field is passed in
7925 // a register.
7926 llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
7927   SmallVector<llvm::Type*, 8> ArgList, IntArgList;
7928 
7929   if (IsO32) {
7930     CoerceToIntArgs(TySize, ArgList);
7931     return llvm::StructType::get(getVMContext(), ArgList);
7932   }
7933 
7934   if (Ty->isComplexType())
7935     return CGT.ConvertType(Ty);
7936 
7937   const RecordType *RT = Ty->getAs<RecordType>();
7938 
7939   // Unions/vectors are passed in integer registers.
7940   if (!RT || !RT->isStructureOrClassType()) {
7941     CoerceToIntArgs(TySize, ArgList);
7942     return llvm::StructType::get(getVMContext(), ArgList);
7943   }
7944 
7945   const RecordDecl *RD = RT->getDecl();
7946   const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
7947   assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
7948 
7949   uint64_t LastOffset = 0;
7950   unsigned idx = 0;
7951   llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
7952 
7953   // Iterate over fields in the struct/class and check if there are any aligned
7954   // double fields.
7955   for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
7956        i != e; ++i, ++idx) {
7957     const QualType Ty = i->getType();
7958     const BuiltinType *BT = Ty->getAs<BuiltinType>();
7959 
7960     if (!BT || BT->getKind() != BuiltinType::Double)
7961       continue;
7962 
7963     uint64_t Offset = Layout.getFieldOffset(idx);
7964     if (Offset % 64) // Ignore doubles that are not aligned.
7965       continue;
7966 
7967     // Add ((Offset - LastOffset) / 64) args of type i64.
7968     for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
7969       ArgList.push_back(I64);
7970 
7971     // Add double type.
7972     ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
7973     LastOffset = Offset + 64;
7974   }
7975 
7976   CoerceToIntArgs(TySize - LastOffset, IntArgList);
7977   ArgList.append(IntArgList.begin(), IntArgList.end());
7978 
7979   return llvm::StructType::get(getVMContext(), ArgList);
7980 }
7981 
7982 llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
7983                                         uint64_t Offset) const {
7984   if (OrigOffset + MinABIStackAlignInBytes > Offset)
7985     return nullptr;
7986 
7987   return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
7988 }
7989 
7990 ABIArgInfo
7991 MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
7992   Ty = useFirstFieldIfTransparentUnion(Ty);
7993 
7994   uint64_t OrigOffset = Offset;
7995   uint64_t TySize = getContext().getTypeSize(Ty);
7996   uint64_t Align = getContext().getTypeAlign(Ty) / 8;
7997 
7998   Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
7999                    (uint64_t)StackAlignInBytes);
8000   unsigned CurrOffset = llvm::alignTo(Offset, Align);
8001   Offset = CurrOffset + llvm::alignTo(TySize, Align * 8) / 8;
8002 
8003   if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
8004     // Ignore empty aggregates.
8005     if (TySize == 0)
8006       return ABIArgInfo::getIgnore();
8007 
8008     if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
8009       Offset = OrigOffset + MinABIStackAlignInBytes;
8010       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
8011     }
8012 
8013     // If we have reached here, aggregates are passed directly by coercing to
8014     // another structure type. Padding is inserted if the offset of the
8015     // aggregate is unaligned.
8016     ABIArgInfo ArgInfo =
8017         ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
8018                               getPaddingType(OrigOffset, CurrOffset));
8019     ArgInfo.setInReg(true);
8020     return ArgInfo;
8021   }
8022 
8023   // Treat an enum type as its underlying type.
8024   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
8025     Ty = EnumTy->getDecl()->getIntegerType();
8026 
8027   // Make sure we pass indirectly things that are too large.
8028   if (const auto *EIT = Ty->getAs<BitIntType>())
8029     if (EIT->getNumBits() > 128 ||
8030         (EIT->getNumBits() > 64 &&
8031          !getContext().getTargetInfo().hasInt128Type()))
8032       return getNaturalAlignIndirect(Ty);
8033 
8034   // All integral types are promoted to the GPR width.
8035   if (Ty->isIntegralOrEnumerationType())
8036     return extendType(Ty);
8037 
8038   return ABIArgInfo::getDirect(
8039       nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset));
8040 }
8041 
8042 llvm::Type*
8043 MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
8044   const RecordType *RT = RetTy->getAs<RecordType>();
8045   SmallVector<llvm::Type*, 8> RTList;
8046 
8047   if (RT && RT->isStructureOrClassType()) {
8048     const RecordDecl *RD = RT->getDecl();
8049     const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
8050     unsigned FieldCnt = Layout.getFieldCount();
8051 
8052     // N32/64 returns struct/classes in floating point registers if the
8053     // following conditions are met:
8054     // 1. The size of the struct/class is no larger than 128-bit.
8055     // 2. The struct/class has one or two fields all of which are floating
8056     //    point types.
8057     // 3. The offset of the first field is zero (this follows what gcc does).
8058     //
8059     // Any other composite results are returned in integer registers.
8060     //
8061     if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
8062       RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
8063       for (; b != e; ++b) {
8064         const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
8065 
8066         if (!BT || !BT->isFloatingPoint())
8067           break;
8068 
8069         RTList.push_back(CGT.ConvertType(b->getType()));
8070       }
8071 
8072       if (b == e)
8073         return llvm::StructType::get(getVMContext(), RTList,
8074                                      RD->hasAttr<PackedAttr>());
8075 
8076       RTList.clear();
8077     }
8078   }
8079 
8080   CoerceToIntArgs(Size, RTList);
8081   return llvm::StructType::get(getVMContext(), RTList);
8082 }
8083 
8084 ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
8085   uint64_t Size = getContext().getTypeSize(RetTy);
8086 
8087   if (RetTy->isVoidType())
8088     return ABIArgInfo::getIgnore();
8089 
8090   // O32 doesn't treat zero-sized structs differently from other structs.
8091   // However, N32/N64 ignores zero sized return values.
8092   if (!IsO32 && Size == 0)
8093     return ABIArgInfo::getIgnore();
8094 
8095   if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
8096     if (Size <= 128) {
8097       if (RetTy->isAnyComplexType())
8098         return ABIArgInfo::getDirect();
8099 
8100       // O32 returns integer vectors in registers and N32/N64 returns all small
8101       // aggregates in registers.
8102       if (!IsO32 ||
8103           (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) {
8104         ABIArgInfo ArgInfo =
8105             ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
8106         ArgInfo.setInReg(true);
8107         return ArgInfo;
8108       }
8109     }
8110 
8111     return getNaturalAlignIndirect(RetTy);
8112   }
8113 
8114   // Treat an enum type as its underlying type.
8115   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
8116     RetTy = EnumTy->getDecl()->getIntegerType();
8117 
8118   // Make sure we pass indirectly things that are too large.
8119   if (const auto *EIT = RetTy->getAs<BitIntType>())
8120     if (EIT->getNumBits() > 128 ||
8121         (EIT->getNumBits() > 64 &&
8122          !getContext().getTargetInfo().hasInt128Type()))
8123       return getNaturalAlignIndirect(RetTy);
8124 
8125   if (isPromotableIntegerTypeForABI(RetTy))
8126     return ABIArgInfo::getExtend(RetTy);
8127 
8128   if ((RetTy->isUnsignedIntegerOrEnumerationType() ||
8129       RetTy->isSignedIntegerOrEnumerationType()) && Size == 32 && !IsO32)
8130     return ABIArgInfo::getSignExtend(RetTy);
8131 
8132   return ABIArgInfo::getDirect();
8133 }
8134 
8135 void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
8136   ABIArgInfo &RetInfo = FI.getReturnInfo();
8137   if (!getCXXABI().classifyReturnType(FI))
8138     RetInfo = classifyReturnType(FI.getReturnType());
8139 
8140   // Check if a pointer to an aggregate is passed as a hidden argument.
8141   uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
8142 
8143   for (auto &I : FI.arguments())
8144     I.info = classifyArgumentType(I.type, Offset);
8145 }
8146 
8147 Address MipsABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8148                                QualType OrigTy) const {
8149   QualType Ty = OrigTy;
8150 
8151   // Integer arguments are promoted to 32-bit on O32 and 64-bit on N32/N64.
8152   // Pointers are also promoted in the same way but this only matters for N32.
8153   unsigned SlotSizeInBits = IsO32 ? 32 : 64;
8154   unsigned PtrWidth = getTarget().getPointerWidth(0);
8155   bool DidPromote = false;
8156   if ((Ty->isIntegerType() &&
8157           getContext().getIntWidth(Ty) < SlotSizeInBits) ||
8158       (Ty->isPointerType() && PtrWidth < SlotSizeInBits)) {
8159     DidPromote = true;
8160     Ty = getContext().getIntTypeForBitwidth(SlotSizeInBits,
8161                                             Ty->isSignedIntegerType());
8162   }
8163 
8164   auto TyInfo = getContext().getTypeInfoInChars(Ty);
8165 
8166   // The alignment of things in the argument area is never larger than
8167   // StackAlignInBytes.
8168   TyInfo.Align =
8169     std::min(TyInfo.Align, CharUnits::fromQuantity(StackAlignInBytes));
8170 
8171   // MinABIStackAlignInBytes is the size of argument slots on the stack.
8172   CharUnits ArgSlotSize = CharUnits::fromQuantity(MinABIStackAlignInBytes);
8173 
8174   Address Addr = emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
8175                           TyInfo, ArgSlotSize, /*AllowHigherAlign*/ true);
8176 
8177 
8178   // If there was a promotion, "unpromote" into a temporary.
8179   // TODO: can we just use a pointer into a subset of the original slot?
8180   if (DidPromote) {
8181     Address Temp = CGF.CreateMemTemp(OrigTy, "vaarg.promotion-temp");
8182     llvm::Value *Promoted = CGF.Builder.CreateLoad(Addr);
8183 
8184     // Truncate down to the right width.
8185     llvm::Type *IntTy = (OrigTy->isIntegerType() ? Temp.getElementType()
8186                                                  : CGF.IntPtrTy);
8187     llvm::Value *V = CGF.Builder.CreateTrunc(Promoted, IntTy);
8188     if (OrigTy->isPointerType())
8189       V = CGF.Builder.CreateIntToPtr(V, Temp.getElementType());
8190 
8191     CGF.Builder.CreateStore(V, Temp);
8192     Addr = Temp;
8193   }
8194 
8195   return Addr;
8196 }
8197 
8198 ABIArgInfo MipsABIInfo::extendType(QualType Ty) const {
8199   int TySize = getContext().getTypeSize(Ty);
8200 
8201   // MIPS64 ABI requires unsigned 32 bit integers to be sign extended.
8202   if (Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
8203     return ABIArgInfo::getSignExtend(Ty);
8204 
8205   return ABIArgInfo::getExtend(Ty);
8206 }
8207 
8208 bool
8209 MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
8210                                                llvm::Value *Address) const {
8211   // This information comes from gcc's implementation, which seems to
8212   // as canonical as it gets.
8213 
8214   // Everything on MIPS is 4 bytes.  Double-precision FP registers
8215   // are aliased to pairs of single-precision FP registers.
8216   llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
8217 
8218   // 0-31 are the general purpose registers, $0 - $31.
8219   // 32-63 are the floating-point registers, $f0 - $f31.
8220   // 64 and 65 are the multiply/divide registers, $hi and $lo.
8221   // 66 is the (notional, I think) register for signal-handler return.
8222   AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
8223 
8224   // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
8225   // They are one bit wide and ignored here.
8226 
8227   // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
8228   // (coprocessor 1 is the FP unit)
8229   // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
8230   // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
8231   // 176-181 are the DSP accumulator registers.
8232   AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
8233   return false;
8234 }
8235 
8236 //===----------------------------------------------------------------------===//
8237 // M68k ABI Implementation
8238 //===----------------------------------------------------------------------===//
8239 
8240 namespace {
8241 
8242 class M68kTargetCodeGenInfo : public TargetCodeGenInfo {
8243 public:
8244   M68kTargetCodeGenInfo(CodeGenTypes &CGT)
8245       : TargetCodeGenInfo(std::make_unique<DefaultABIInfo>(CGT)) {}
8246   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
8247                            CodeGen::CodeGenModule &M) const override;
8248 };
8249 
8250 } // namespace
8251 
8252 void M68kTargetCodeGenInfo::setTargetAttributes(
8253     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
8254   if (const auto *FD = dyn_cast_or_null<FunctionDecl>(D)) {
8255     if (const auto *attr = FD->getAttr<M68kInterruptAttr>()) {
8256       // Handle 'interrupt' attribute:
8257       llvm::Function *F = cast<llvm::Function>(GV);
8258 
8259       // Step 1: Set ISR calling convention.
8260       F->setCallingConv(llvm::CallingConv::M68k_INTR);
8261 
8262       // Step 2: Add attributes goodness.
8263       F->addFnAttr(llvm::Attribute::NoInline);
8264 
8265       // Step 3: Emit ISR vector alias.
8266       unsigned Num = attr->getNumber() / 2;
8267       llvm::GlobalAlias::create(llvm::Function::ExternalLinkage,
8268                                 "__isr_" + Twine(Num), F);
8269     }
8270   }
8271 }
8272 
8273 //===----------------------------------------------------------------------===//
8274 // AVR ABI Implementation. Documented at
8275 // https://gcc.gnu.org/wiki/avr-gcc#Calling_Convention
8276 // https://gcc.gnu.org/wiki/avr-gcc#Reduced_Tiny
8277 //===----------------------------------------------------------------------===//
8278 
8279 namespace {
8280 class AVRABIInfo : public DefaultABIInfo {
8281 public:
8282   AVRABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
8283 
8284   ABIArgInfo classifyReturnType(QualType Ty) const {
8285     // A return struct with size less than or equal to 8 bytes is returned
8286     // directly via registers R18-R25.
8287     if (isAggregateTypeForABI(Ty) && getContext().getTypeSize(Ty) <= 64)
8288       return ABIArgInfo::getDirect();
8289     else
8290       return DefaultABIInfo::classifyReturnType(Ty);
8291   }
8292 
8293   // Just copy the original implementation of DefaultABIInfo::computeInfo(),
8294   // since DefaultABIInfo::classify{Return,Argument}Type() are not virtual.
8295   void computeInfo(CGFunctionInfo &FI) const override {
8296     if (!getCXXABI().classifyReturnType(FI))
8297       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
8298     for (auto &I : FI.arguments())
8299       I.info = classifyArgumentType(I.type);
8300   }
8301 };
8302 
8303 class AVRTargetCodeGenInfo : public TargetCodeGenInfo {
8304 public:
8305   AVRTargetCodeGenInfo(CodeGenTypes &CGT)
8306       : TargetCodeGenInfo(std::make_unique<AVRABIInfo>(CGT)) {}
8307 
8308   LangAS getGlobalVarAddressSpace(CodeGenModule &CGM,
8309                                   const VarDecl *D) const override {
8310     // Check if global/static variable is defined in address space
8311     // 1~6 (__flash, __flash1, __flash2, __flash3, __flash4, __flash5)
8312     // but not constant.
8313     if (D) {
8314       LangAS AS = D->getType().getAddressSpace();
8315       if (isTargetAddressSpace(AS) && 1 <= toTargetAddressSpace(AS) &&
8316           toTargetAddressSpace(AS) <= 6 && !D->getType().isConstQualified())
8317         CGM.getDiags().Report(D->getLocation(),
8318                               diag::err_verify_nonconst_addrspace)
8319             << "__flash*";
8320     }
8321     return TargetCodeGenInfo::getGlobalVarAddressSpace(CGM, D);
8322   }
8323 
8324   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
8325                            CodeGen::CodeGenModule &CGM) const override {
8326     if (GV->isDeclaration())
8327       return;
8328     const auto *FD = dyn_cast_or_null<FunctionDecl>(D);
8329     if (!FD) return;
8330     auto *Fn = cast<llvm::Function>(GV);
8331 
8332     if (FD->getAttr<AVRInterruptAttr>())
8333       Fn->addFnAttr("interrupt");
8334 
8335     if (FD->getAttr<AVRSignalAttr>())
8336       Fn->addFnAttr("signal");
8337   }
8338 };
8339 }
8340 
8341 //===----------------------------------------------------------------------===//
8342 // TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
8343 // Currently subclassed only to implement custom OpenCL C function attribute
8344 // handling.
8345 //===----------------------------------------------------------------------===//
8346 
8347 namespace {
8348 
8349 class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
8350 public:
8351   TCETargetCodeGenInfo(CodeGenTypes &CGT)
8352     : DefaultTargetCodeGenInfo(CGT) {}
8353 
8354   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
8355                            CodeGen::CodeGenModule &M) const override;
8356 };
8357 
8358 void TCETargetCodeGenInfo::setTargetAttributes(
8359     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
8360   if (GV->isDeclaration())
8361     return;
8362   const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
8363   if (!FD) return;
8364 
8365   llvm::Function *F = cast<llvm::Function>(GV);
8366 
8367   if (M.getLangOpts().OpenCL) {
8368     if (FD->hasAttr<OpenCLKernelAttr>()) {
8369       // OpenCL C Kernel functions are not subject to inlining
8370       F->addFnAttr(llvm::Attribute::NoInline);
8371       const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
8372       if (Attr) {
8373         // Convert the reqd_work_group_size() attributes to metadata.
8374         llvm::LLVMContext &Context = F->getContext();
8375         llvm::NamedMDNode *OpenCLMetadata =
8376             M.getModule().getOrInsertNamedMetadata(
8377                 "opencl.kernel_wg_size_info");
8378 
8379         SmallVector<llvm::Metadata *, 5> Operands;
8380         Operands.push_back(llvm::ConstantAsMetadata::get(F));
8381 
8382         Operands.push_back(
8383             llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
8384                 M.Int32Ty, llvm::APInt(32, Attr->getXDim()))));
8385         Operands.push_back(
8386             llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
8387                 M.Int32Ty, llvm::APInt(32, Attr->getYDim()))));
8388         Operands.push_back(
8389             llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
8390                 M.Int32Ty, llvm::APInt(32, Attr->getZDim()))));
8391 
8392         // Add a boolean constant operand for "required" (true) or "hint"
8393         // (false) for implementing the work_group_size_hint attr later.
8394         // Currently always true as the hint is not yet implemented.
8395         Operands.push_back(
8396             llvm::ConstantAsMetadata::get(llvm::ConstantInt::getTrue(Context)));
8397         OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
8398       }
8399     }
8400   }
8401 }
8402 
8403 }
8404 
8405 //===----------------------------------------------------------------------===//
8406 // Hexagon ABI Implementation
8407 //===----------------------------------------------------------------------===//
8408 
8409 namespace {
8410 
8411 class HexagonABIInfo : public DefaultABIInfo {
8412 public:
8413   HexagonABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
8414 
8415 private:
8416   ABIArgInfo classifyReturnType(QualType RetTy) const;
8417   ABIArgInfo classifyArgumentType(QualType RetTy) const;
8418   ABIArgInfo classifyArgumentType(QualType RetTy, unsigned *RegsLeft) const;
8419 
8420   void computeInfo(CGFunctionInfo &FI) const override;
8421 
8422   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8423                     QualType Ty) const override;
8424   Address EmitVAArgFromMemory(CodeGenFunction &CFG, Address VAListAddr,
8425                               QualType Ty) const;
8426   Address EmitVAArgForHexagon(CodeGenFunction &CFG, Address VAListAddr,
8427                               QualType Ty) const;
8428   Address EmitVAArgForHexagonLinux(CodeGenFunction &CFG, Address VAListAddr,
8429                                    QualType Ty) const;
8430 };
8431 
8432 class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
8433 public:
8434   HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
8435       : TargetCodeGenInfo(std::make_unique<HexagonABIInfo>(CGT)) {}
8436 
8437   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
8438     return 29;
8439   }
8440 
8441   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
8442                            CodeGen::CodeGenModule &GCM) const override {
8443     if (GV->isDeclaration())
8444       return;
8445     const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
8446     if (!FD)
8447       return;
8448   }
8449 };
8450 
8451 } // namespace
8452 
8453 void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
8454   unsigned RegsLeft = 6;
8455   if (!getCXXABI().classifyReturnType(FI))
8456     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
8457   for (auto &I : FI.arguments())
8458     I.info = classifyArgumentType(I.type, &RegsLeft);
8459 }
8460 
8461 static bool HexagonAdjustRegsLeft(uint64_t Size, unsigned *RegsLeft) {
8462   assert(Size <= 64 && "Not expecting to pass arguments larger than 64 bits"
8463                        " through registers");
8464 
8465   if (*RegsLeft == 0)
8466     return false;
8467 
8468   if (Size <= 32) {
8469     (*RegsLeft)--;
8470     return true;
8471   }
8472 
8473   if (2 <= (*RegsLeft & (~1U))) {
8474     *RegsLeft = (*RegsLeft & (~1U)) - 2;
8475     return true;
8476   }
8477 
8478   // Next available register was r5 but candidate was greater than 32-bits so it
8479   // has to go on the stack. However we still consume r5
8480   if (*RegsLeft == 1)
8481     *RegsLeft = 0;
8482 
8483   return false;
8484 }
8485 
8486 ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty,
8487                                                 unsigned *RegsLeft) const {
8488   if (!isAggregateTypeForABI(Ty)) {
8489     // Treat an enum type as its underlying type.
8490     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
8491       Ty = EnumTy->getDecl()->getIntegerType();
8492 
8493     uint64_t Size = getContext().getTypeSize(Ty);
8494     if (Size <= 64)
8495       HexagonAdjustRegsLeft(Size, RegsLeft);
8496 
8497     if (Size > 64 && Ty->isBitIntType())
8498       return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
8499 
8500     return isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
8501                                              : ABIArgInfo::getDirect();
8502   }
8503 
8504   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
8505     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
8506 
8507   // Ignore empty records.
8508   if (isEmptyRecord(getContext(), Ty, true))
8509     return ABIArgInfo::getIgnore();
8510 
8511   uint64_t Size = getContext().getTypeSize(Ty);
8512   unsigned Align = getContext().getTypeAlign(Ty);
8513 
8514   if (Size > 64)
8515     return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
8516 
8517   if (HexagonAdjustRegsLeft(Size, RegsLeft))
8518     Align = Size <= 32 ? 32 : 64;
8519   if (Size <= Align) {
8520     // Pass in the smallest viable integer type.
8521     if (!llvm::isPowerOf2_64(Size))
8522       Size = llvm::NextPowerOf2(Size);
8523     return ABIArgInfo::getDirect(llvm::Type::getIntNTy(getVMContext(), Size));
8524   }
8525   return DefaultABIInfo::classifyArgumentType(Ty);
8526 }
8527 
8528 ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
8529   if (RetTy->isVoidType())
8530     return ABIArgInfo::getIgnore();
8531 
8532   const TargetInfo &T = CGT.getTarget();
8533   uint64_t Size = getContext().getTypeSize(RetTy);
8534 
8535   if (RetTy->getAs<VectorType>()) {
8536     // HVX vectors are returned in vector registers or register pairs.
8537     if (T.hasFeature("hvx")) {
8538       assert(T.hasFeature("hvx-length64b") || T.hasFeature("hvx-length128b"));
8539       uint64_t VecSize = T.hasFeature("hvx-length64b") ? 64*8 : 128*8;
8540       if (Size == VecSize || Size == 2*VecSize)
8541         return ABIArgInfo::getDirectInReg();
8542     }
8543     // Large vector types should be returned via memory.
8544     if (Size > 64)
8545       return getNaturalAlignIndirect(RetTy);
8546   }
8547 
8548   if (!isAggregateTypeForABI(RetTy)) {
8549     // Treat an enum type as its underlying type.
8550     if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
8551       RetTy = EnumTy->getDecl()->getIntegerType();
8552 
8553     if (Size > 64 && RetTy->isBitIntType())
8554       return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
8555 
8556     return isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
8557                                                 : ABIArgInfo::getDirect();
8558   }
8559 
8560   if (isEmptyRecord(getContext(), RetTy, true))
8561     return ABIArgInfo::getIgnore();
8562 
8563   // Aggregates <= 8 bytes are returned in registers, other aggregates
8564   // are returned indirectly.
8565   if (Size <= 64) {
8566     // Return in the smallest viable integer type.
8567     if (!llvm::isPowerOf2_64(Size))
8568       Size = llvm::NextPowerOf2(Size);
8569     return ABIArgInfo::getDirect(llvm::Type::getIntNTy(getVMContext(), Size));
8570   }
8571   return getNaturalAlignIndirect(RetTy, /*ByVal=*/true);
8572 }
8573 
8574 Address HexagonABIInfo::EmitVAArgFromMemory(CodeGenFunction &CGF,
8575                                             Address VAListAddr,
8576                                             QualType Ty) const {
8577   // Load the overflow area pointer.
8578   Address __overflow_area_pointer_p =
8579       CGF.Builder.CreateStructGEP(VAListAddr, 2, "__overflow_area_pointer_p");
8580   llvm::Value *__overflow_area_pointer = CGF.Builder.CreateLoad(
8581       __overflow_area_pointer_p, "__overflow_area_pointer");
8582 
8583   uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8;
8584   if (Align > 4) {
8585     // Alignment should be a power of 2.
8586     assert((Align & (Align - 1)) == 0 && "Alignment is not power of 2!");
8587 
8588     // overflow_arg_area = (overflow_arg_area + align - 1) & -align;
8589     llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int64Ty, Align - 1);
8590 
8591     // Add offset to the current pointer to access the argument.
8592     __overflow_area_pointer =
8593         CGF.Builder.CreateGEP(CGF.Int8Ty, __overflow_area_pointer, Offset);
8594     llvm::Value *AsInt =
8595         CGF.Builder.CreatePtrToInt(__overflow_area_pointer, CGF.Int32Ty);
8596 
8597     // Create a mask which should be "AND"ed
8598     // with (overflow_arg_area + align - 1)
8599     llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int32Ty, -(int)Align);
8600     __overflow_area_pointer = CGF.Builder.CreateIntToPtr(
8601         CGF.Builder.CreateAnd(AsInt, Mask), __overflow_area_pointer->getType(),
8602         "__overflow_area_pointer.align");
8603   }
8604 
8605   // Get the type of the argument from memory and bitcast
8606   // overflow area pointer to the argument type.
8607   llvm::Type *PTy = CGF.ConvertTypeForMem(Ty);
8608   Address AddrTyped = CGF.Builder.CreateElementBitCast(
8609       Address(__overflow_area_pointer, CGF.Int8Ty,
8610               CharUnits::fromQuantity(Align)),
8611       PTy);
8612 
8613   // Round up to the minimum stack alignment for varargs which is 4 bytes.
8614   uint64_t Offset = llvm::alignTo(CGF.getContext().getTypeSize(Ty) / 8, 4);
8615 
8616   __overflow_area_pointer = CGF.Builder.CreateGEP(
8617       CGF.Int8Ty, __overflow_area_pointer,
8618       llvm::ConstantInt::get(CGF.Int32Ty, Offset),
8619       "__overflow_area_pointer.next");
8620   CGF.Builder.CreateStore(__overflow_area_pointer, __overflow_area_pointer_p);
8621 
8622   return AddrTyped;
8623 }
8624 
8625 Address HexagonABIInfo::EmitVAArgForHexagon(CodeGenFunction &CGF,
8626                                             Address VAListAddr,
8627                                             QualType Ty) const {
8628   // FIXME: Need to handle alignment
8629   llvm::Type *BP = CGF.Int8PtrTy;
8630   CGBuilderTy &Builder = CGF.Builder;
8631   Address VAListAddrAsBPP = Builder.CreateElementBitCast(VAListAddr, BP, "ap");
8632   llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
8633   // Handle address alignment for type alignment > 32 bits
8634   uint64_t TyAlign = CGF.getContext().getTypeAlign(Ty) / 8;
8635   if (TyAlign > 4) {
8636     assert((TyAlign & (TyAlign - 1)) == 0 && "Alignment is not power of 2!");
8637     llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int32Ty);
8638     AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt32(TyAlign - 1));
8639     AddrAsInt = Builder.CreateAnd(AddrAsInt, Builder.getInt32(~(TyAlign - 1)));
8640     Addr = Builder.CreateIntToPtr(AddrAsInt, BP);
8641   }
8642   Address AddrTyped = Builder.CreateElementBitCast(
8643       Address(Addr, CGF.Int8Ty, CharUnits::fromQuantity(TyAlign)),
8644       CGF.ConvertType(Ty));
8645 
8646   uint64_t Offset = llvm::alignTo(CGF.getContext().getTypeSize(Ty) / 8, 4);
8647   llvm::Value *NextAddr = Builder.CreateGEP(
8648       CGF.Int8Ty, Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset), "ap.next");
8649   Builder.CreateStore(NextAddr, VAListAddrAsBPP);
8650 
8651   return AddrTyped;
8652 }
8653 
8654 Address HexagonABIInfo::EmitVAArgForHexagonLinux(CodeGenFunction &CGF,
8655                                                  Address VAListAddr,
8656                                                  QualType Ty) const {
8657   int ArgSize = CGF.getContext().getTypeSize(Ty) / 8;
8658 
8659   if (ArgSize > 8)
8660     return EmitVAArgFromMemory(CGF, VAListAddr, Ty);
8661 
8662   // Here we have check if the argument is in register area or
8663   // in overflow area.
8664   // If the saved register area pointer + argsize rounded up to alignment >
8665   // saved register area end pointer, argument is in overflow area.
8666   unsigned RegsLeft = 6;
8667   Ty = CGF.getContext().getCanonicalType(Ty);
8668   (void)classifyArgumentType(Ty, &RegsLeft);
8669 
8670   llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
8671   llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
8672   llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
8673   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
8674 
8675   // Get rounded size of the argument.GCC does not allow vararg of
8676   // size < 4 bytes. We follow the same logic here.
8677   ArgSize = (CGF.getContext().getTypeSize(Ty) <= 32) ? 4 : 8;
8678   int ArgAlign = (CGF.getContext().getTypeSize(Ty) <= 32) ? 4 : 8;
8679 
8680   // Argument may be in saved register area
8681   CGF.EmitBlock(MaybeRegBlock);
8682 
8683   // Load the current saved register area pointer.
8684   Address __current_saved_reg_area_pointer_p = CGF.Builder.CreateStructGEP(
8685       VAListAddr, 0, "__current_saved_reg_area_pointer_p");
8686   llvm::Value *__current_saved_reg_area_pointer = CGF.Builder.CreateLoad(
8687       __current_saved_reg_area_pointer_p, "__current_saved_reg_area_pointer");
8688 
8689   // Load the saved register area end pointer.
8690   Address __saved_reg_area_end_pointer_p = CGF.Builder.CreateStructGEP(
8691       VAListAddr, 1, "__saved_reg_area_end_pointer_p");
8692   llvm::Value *__saved_reg_area_end_pointer = CGF.Builder.CreateLoad(
8693       __saved_reg_area_end_pointer_p, "__saved_reg_area_end_pointer");
8694 
8695   // If the size of argument is > 4 bytes, check if the stack
8696   // location is aligned to 8 bytes
8697   if (ArgAlign > 4) {
8698 
8699     llvm::Value *__current_saved_reg_area_pointer_int =
8700         CGF.Builder.CreatePtrToInt(__current_saved_reg_area_pointer,
8701                                    CGF.Int32Ty);
8702 
8703     __current_saved_reg_area_pointer_int = CGF.Builder.CreateAdd(
8704         __current_saved_reg_area_pointer_int,
8705         llvm::ConstantInt::get(CGF.Int32Ty, (ArgAlign - 1)),
8706         "align_current_saved_reg_area_pointer");
8707 
8708     __current_saved_reg_area_pointer_int =
8709         CGF.Builder.CreateAnd(__current_saved_reg_area_pointer_int,
8710                               llvm::ConstantInt::get(CGF.Int32Ty, -ArgAlign),
8711                               "align_current_saved_reg_area_pointer");
8712 
8713     __current_saved_reg_area_pointer =
8714         CGF.Builder.CreateIntToPtr(__current_saved_reg_area_pointer_int,
8715                                    __current_saved_reg_area_pointer->getType(),
8716                                    "align_current_saved_reg_area_pointer");
8717   }
8718 
8719   llvm::Value *__new_saved_reg_area_pointer =
8720       CGF.Builder.CreateGEP(CGF.Int8Ty, __current_saved_reg_area_pointer,
8721                             llvm::ConstantInt::get(CGF.Int32Ty, ArgSize),
8722                             "__new_saved_reg_area_pointer");
8723 
8724   llvm::Value *UsingStack = nullptr;
8725   UsingStack = CGF.Builder.CreateICmpSGT(__new_saved_reg_area_pointer,
8726                                          __saved_reg_area_end_pointer);
8727 
8728   CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, InRegBlock);
8729 
8730   // Argument in saved register area
8731   // Implement the block where argument is in register saved area
8732   CGF.EmitBlock(InRegBlock);
8733 
8734   llvm::Type *PTy = CGF.ConvertType(Ty);
8735   llvm::Value *__saved_reg_area_p = CGF.Builder.CreateBitCast(
8736       __current_saved_reg_area_pointer, llvm::PointerType::getUnqual(PTy));
8737 
8738   CGF.Builder.CreateStore(__new_saved_reg_area_pointer,
8739                           __current_saved_reg_area_pointer_p);
8740 
8741   CGF.EmitBranch(ContBlock);
8742 
8743   // Argument in overflow area
8744   // Implement the block where the argument is in overflow area.
8745   CGF.EmitBlock(OnStackBlock);
8746 
8747   // Load the overflow area pointer
8748   Address __overflow_area_pointer_p =
8749       CGF.Builder.CreateStructGEP(VAListAddr, 2, "__overflow_area_pointer_p");
8750   llvm::Value *__overflow_area_pointer = CGF.Builder.CreateLoad(
8751       __overflow_area_pointer_p, "__overflow_area_pointer");
8752 
8753   // Align the overflow area pointer according to the alignment of the argument
8754   if (ArgAlign > 4) {
8755     llvm::Value *__overflow_area_pointer_int =
8756         CGF.Builder.CreatePtrToInt(__overflow_area_pointer, CGF.Int32Ty);
8757 
8758     __overflow_area_pointer_int =
8759         CGF.Builder.CreateAdd(__overflow_area_pointer_int,
8760                               llvm::ConstantInt::get(CGF.Int32Ty, ArgAlign - 1),
8761                               "align_overflow_area_pointer");
8762 
8763     __overflow_area_pointer_int =
8764         CGF.Builder.CreateAnd(__overflow_area_pointer_int,
8765                               llvm::ConstantInt::get(CGF.Int32Ty, -ArgAlign),
8766                               "align_overflow_area_pointer");
8767 
8768     __overflow_area_pointer = CGF.Builder.CreateIntToPtr(
8769         __overflow_area_pointer_int, __overflow_area_pointer->getType(),
8770         "align_overflow_area_pointer");
8771   }
8772 
8773   // Get the pointer for next argument in overflow area and store it
8774   // to overflow area pointer.
8775   llvm::Value *__new_overflow_area_pointer = CGF.Builder.CreateGEP(
8776       CGF.Int8Ty, __overflow_area_pointer,
8777       llvm::ConstantInt::get(CGF.Int32Ty, ArgSize),
8778       "__overflow_area_pointer.next");
8779 
8780   CGF.Builder.CreateStore(__new_overflow_area_pointer,
8781                           __overflow_area_pointer_p);
8782 
8783   CGF.Builder.CreateStore(__new_overflow_area_pointer,
8784                           __current_saved_reg_area_pointer_p);
8785 
8786   // Bitcast the overflow area pointer to the type of argument.
8787   llvm::Type *OverflowPTy = CGF.ConvertTypeForMem(Ty);
8788   llvm::Value *__overflow_area_p = CGF.Builder.CreateBitCast(
8789       __overflow_area_pointer, llvm::PointerType::getUnqual(OverflowPTy));
8790 
8791   CGF.EmitBranch(ContBlock);
8792 
8793   // Get the correct pointer to load the variable argument
8794   // Implement the ContBlock
8795   CGF.EmitBlock(ContBlock);
8796 
8797   llvm::Type *MemTy = CGF.ConvertTypeForMem(Ty);
8798   llvm::Type *MemPTy = llvm::PointerType::getUnqual(MemTy);
8799   llvm::PHINode *ArgAddr = CGF.Builder.CreatePHI(MemPTy, 2, "vaarg.addr");
8800   ArgAddr->addIncoming(__saved_reg_area_p, InRegBlock);
8801   ArgAddr->addIncoming(__overflow_area_p, OnStackBlock);
8802 
8803   return Address(ArgAddr, MemTy, CharUnits::fromQuantity(ArgAlign));
8804 }
8805 
8806 Address HexagonABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8807                                   QualType Ty) const {
8808 
8809   if (getTarget().getTriple().isMusl())
8810     return EmitVAArgForHexagonLinux(CGF, VAListAddr, Ty);
8811 
8812   return EmitVAArgForHexagon(CGF, VAListAddr, Ty);
8813 }
8814 
8815 //===----------------------------------------------------------------------===//
8816 // Lanai ABI Implementation
8817 //===----------------------------------------------------------------------===//
8818 
8819 namespace {
8820 class LanaiABIInfo : public DefaultABIInfo {
8821 public:
8822   LanaiABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
8823 
8824   bool shouldUseInReg(QualType Ty, CCState &State) const;
8825 
8826   void computeInfo(CGFunctionInfo &FI) const override {
8827     CCState State(FI);
8828     // Lanai uses 4 registers to pass arguments unless the function has the
8829     // regparm attribute set.
8830     if (FI.getHasRegParm()) {
8831       State.FreeRegs = FI.getRegParm();
8832     } else {
8833       State.FreeRegs = 4;
8834     }
8835 
8836     if (!getCXXABI().classifyReturnType(FI))
8837       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
8838     for (auto &I : FI.arguments())
8839       I.info = classifyArgumentType(I.type, State);
8840   }
8841 
8842   ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
8843   ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
8844 };
8845 } // end anonymous namespace
8846 
8847 bool LanaiABIInfo::shouldUseInReg(QualType Ty, CCState &State) const {
8848   unsigned Size = getContext().getTypeSize(Ty);
8849   unsigned SizeInRegs = llvm::alignTo(Size, 32U) / 32U;
8850 
8851   if (SizeInRegs == 0)
8852     return false;
8853 
8854   if (SizeInRegs > State.FreeRegs) {
8855     State.FreeRegs = 0;
8856     return false;
8857   }
8858 
8859   State.FreeRegs -= SizeInRegs;
8860 
8861   return true;
8862 }
8863 
8864 ABIArgInfo LanaiABIInfo::getIndirectResult(QualType Ty, bool ByVal,
8865                                            CCState &State) const {
8866   if (!ByVal) {
8867     if (State.FreeRegs) {
8868       --State.FreeRegs; // Non-byval indirects just use one pointer.
8869       return getNaturalAlignIndirectInReg(Ty);
8870     }
8871     return getNaturalAlignIndirect(Ty, false);
8872   }
8873 
8874   // Compute the byval alignment.
8875   const unsigned MinABIStackAlignInBytes = 4;
8876   unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
8877   return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true,
8878                                  /*Realign=*/TypeAlign >
8879                                      MinABIStackAlignInBytes);
8880 }
8881 
8882 ABIArgInfo LanaiABIInfo::classifyArgumentType(QualType Ty,
8883                                               CCState &State) const {
8884   // Check with the C++ ABI first.
8885   const RecordType *RT = Ty->getAs<RecordType>();
8886   if (RT) {
8887     CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
8888     if (RAA == CGCXXABI::RAA_Indirect) {
8889       return getIndirectResult(Ty, /*ByVal=*/false, State);
8890     } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
8891       return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
8892     }
8893   }
8894 
8895   if (isAggregateTypeForABI(Ty)) {
8896     // Structures with flexible arrays are always indirect.
8897     if (RT && RT->getDecl()->hasFlexibleArrayMember())
8898       return getIndirectResult(Ty, /*ByVal=*/true, State);
8899 
8900     // Ignore empty structs/unions.
8901     if (isEmptyRecord(getContext(), Ty, true))
8902       return ABIArgInfo::getIgnore();
8903 
8904     llvm::LLVMContext &LLVMContext = getVMContext();
8905     unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
8906     if (SizeInRegs <= State.FreeRegs) {
8907       llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
8908       SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32);
8909       llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
8910       State.FreeRegs -= SizeInRegs;
8911       return ABIArgInfo::getDirectInReg(Result);
8912     } else {
8913       State.FreeRegs = 0;
8914     }
8915     return getIndirectResult(Ty, true, State);
8916   }
8917 
8918   // Treat an enum type as its underlying type.
8919   if (const auto *EnumTy = Ty->getAs<EnumType>())
8920     Ty = EnumTy->getDecl()->getIntegerType();
8921 
8922   bool InReg = shouldUseInReg(Ty, State);
8923 
8924   // Don't pass >64 bit integers in registers.
8925   if (const auto *EIT = Ty->getAs<BitIntType>())
8926     if (EIT->getNumBits() > 64)
8927       return getIndirectResult(Ty, /*ByVal=*/true, State);
8928 
8929   if (isPromotableIntegerTypeForABI(Ty)) {
8930     if (InReg)
8931       return ABIArgInfo::getDirectInReg();
8932     return ABIArgInfo::getExtend(Ty);
8933   }
8934   if (InReg)
8935     return ABIArgInfo::getDirectInReg();
8936   return ABIArgInfo::getDirect();
8937 }
8938 
8939 namespace {
8940 class LanaiTargetCodeGenInfo : public TargetCodeGenInfo {
8941 public:
8942   LanaiTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
8943       : TargetCodeGenInfo(std::make_unique<LanaiABIInfo>(CGT)) {}
8944 };
8945 }
8946 
8947 //===----------------------------------------------------------------------===//
8948 // AMDGPU ABI Implementation
8949 //===----------------------------------------------------------------------===//
8950 
8951 namespace {
8952 
8953 class AMDGPUABIInfo final : public DefaultABIInfo {
8954 private:
8955   static const unsigned MaxNumRegsForArgsRet = 16;
8956 
8957   unsigned numRegsForType(QualType Ty) const;
8958 
8959   bool isHomogeneousAggregateBaseType(QualType Ty) const override;
8960   bool isHomogeneousAggregateSmallEnough(const Type *Base,
8961                                          uint64_t Members) const override;
8962 
8963   // Coerce HIP scalar pointer arguments from generic pointers to global ones.
8964   llvm::Type *coerceKernelArgumentType(llvm::Type *Ty, unsigned FromAS,
8965                                        unsigned ToAS) const {
8966     // Single value types.
8967     auto *PtrTy = llvm::dyn_cast<llvm::PointerType>(Ty);
8968     if (PtrTy && PtrTy->getAddressSpace() == FromAS)
8969       return llvm::PointerType::getWithSamePointeeType(PtrTy, ToAS);
8970     return Ty;
8971   }
8972 
8973 public:
8974   explicit AMDGPUABIInfo(CodeGen::CodeGenTypes &CGT) :
8975     DefaultABIInfo(CGT) {}
8976 
8977   ABIArgInfo classifyReturnType(QualType RetTy) const;
8978   ABIArgInfo classifyKernelArgumentType(QualType Ty) const;
8979   ABIArgInfo classifyArgumentType(QualType Ty, unsigned &NumRegsLeft) const;
8980 
8981   void computeInfo(CGFunctionInfo &FI) const override;
8982   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8983                     QualType Ty) const override;
8984 };
8985 
8986 bool AMDGPUABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
8987   return true;
8988 }
8989 
8990 bool AMDGPUABIInfo::isHomogeneousAggregateSmallEnough(
8991   const Type *Base, uint64_t Members) const {
8992   uint32_t NumRegs = (getContext().getTypeSize(Base) + 31) / 32;
8993 
8994   // Homogeneous Aggregates may occupy at most 16 registers.
8995   return Members * NumRegs <= MaxNumRegsForArgsRet;
8996 }
8997 
8998 /// Estimate number of registers the type will use when passed in registers.
8999 unsigned AMDGPUABIInfo::numRegsForType(QualType Ty) const {
9000   unsigned NumRegs = 0;
9001 
9002   if (const VectorType *VT = Ty->getAs<VectorType>()) {
9003     // Compute from the number of elements. The reported size is based on the
9004     // in-memory size, which includes the padding 4th element for 3-vectors.
9005     QualType EltTy = VT->getElementType();
9006     unsigned EltSize = getContext().getTypeSize(EltTy);
9007 
9008     // 16-bit element vectors should be passed as packed.
9009     if (EltSize == 16)
9010       return (VT->getNumElements() + 1) / 2;
9011 
9012     unsigned EltNumRegs = (EltSize + 31) / 32;
9013     return EltNumRegs * VT->getNumElements();
9014   }
9015 
9016   if (const RecordType *RT = Ty->getAs<RecordType>()) {
9017     const RecordDecl *RD = RT->getDecl();
9018     assert(!RD->hasFlexibleArrayMember());
9019 
9020     for (const FieldDecl *Field : RD->fields()) {
9021       QualType FieldTy = Field->getType();
9022       NumRegs += numRegsForType(FieldTy);
9023     }
9024 
9025     return NumRegs;
9026   }
9027 
9028   return (getContext().getTypeSize(Ty) + 31) / 32;
9029 }
9030 
9031 void AMDGPUABIInfo::computeInfo(CGFunctionInfo &FI) const {
9032   llvm::CallingConv::ID CC = FI.getCallingConvention();
9033 
9034   if (!getCXXABI().classifyReturnType(FI))
9035     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
9036 
9037   unsigned NumRegsLeft = MaxNumRegsForArgsRet;
9038   for (auto &Arg : FI.arguments()) {
9039     if (CC == llvm::CallingConv::AMDGPU_KERNEL) {
9040       Arg.info = classifyKernelArgumentType(Arg.type);
9041     } else {
9042       Arg.info = classifyArgumentType(Arg.type, NumRegsLeft);
9043     }
9044   }
9045 }
9046 
9047 Address AMDGPUABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9048                                  QualType Ty) const {
9049   llvm_unreachable("AMDGPU does not support varargs");
9050 }
9051 
9052 ABIArgInfo AMDGPUABIInfo::classifyReturnType(QualType RetTy) const {
9053   if (isAggregateTypeForABI(RetTy)) {
9054     // Records with non-trivial destructors/copy-constructors should not be
9055     // returned by value.
9056     if (!getRecordArgABI(RetTy, getCXXABI())) {
9057       // Ignore empty structs/unions.
9058       if (isEmptyRecord(getContext(), RetTy, true))
9059         return ABIArgInfo::getIgnore();
9060 
9061       // Lower single-element structs to just return a regular value.
9062       if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
9063         return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
9064 
9065       if (const RecordType *RT = RetTy->getAs<RecordType>()) {
9066         const RecordDecl *RD = RT->getDecl();
9067         if (RD->hasFlexibleArrayMember())
9068           return DefaultABIInfo::classifyReturnType(RetTy);
9069       }
9070 
9071       // Pack aggregates <= 4 bytes into single VGPR or pair.
9072       uint64_t Size = getContext().getTypeSize(RetTy);
9073       if (Size <= 16)
9074         return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
9075 
9076       if (Size <= 32)
9077         return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
9078 
9079       if (Size <= 64) {
9080         llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext());
9081         return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2));
9082       }
9083 
9084       if (numRegsForType(RetTy) <= MaxNumRegsForArgsRet)
9085         return ABIArgInfo::getDirect();
9086     }
9087   }
9088 
9089   // Otherwise just do the default thing.
9090   return DefaultABIInfo::classifyReturnType(RetTy);
9091 }
9092 
9093 /// For kernels all parameters are really passed in a special buffer. It doesn't
9094 /// make sense to pass anything byval, so everything must be direct.
9095 ABIArgInfo AMDGPUABIInfo::classifyKernelArgumentType(QualType Ty) const {
9096   Ty = useFirstFieldIfTransparentUnion(Ty);
9097 
9098   // TODO: Can we omit empty structs?
9099 
9100   if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
9101     Ty = QualType(SeltTy, 0);
9102 
9103   llvm::Type *OrigLTy = CGT.ConvertType(Ty);
9104   llvm::Type *LTy = OrigLTy;
9105   if (getContext().getLangOpts().HIP) {
9106     LTy = coerceKernelArgumentType(
9107         OrigLTy, /*FromAS=*/getContext().getTargetAddressSpace(LangAS::Default),
9108         /*ToAS=*/getContext().getTargetAddressSpace(LangAS::cuda_device));
9109   }
9110 
9111   // FIXME: Should also use this for OpenCL, but it requires addressing the
9112   // problem of kernels being called.
9113   //
9114   // FIXME: This doesn't apply the optimization of coercing pointers in structs
9115   // to global address space when using byref. This would require implementing a
9116   // new kind of coercion of the in-memory type when for indirect arguments.
9117   if (!getContext().getLangOpts().OpenCL && LTy == OrigLTy &&
9118       isAggregateTypeForABI(Ty)) {
9119     return ABIArgInfo::getIndirectAliased(
9120         getContext().getTypeAlignInChars(Ty),
9121         getContext().getTargetAddressSpace(LangAS::opencl_constant),
9122         false /*Realign*/, nullptr /*Padding*/);
9123   }
9124 
9125   // If we set CanBeFlattened to true, CodeGen will expand the struct to its
9126   // individual elements, which confuses the Clover OpenCL backend; therefore we
9127   // have to set it to false here. Other args of getDirect() are just defaults.
9128   return ABIArgInfo::getDirect(LTy, 0, nullptr, false);
9129 }
9130 
9131 ABIArgInfo AMDGPUABIInfo::classifyArgumentType(QualType Ty,
9132                                                unsigned &NumRegsLeft) const {
9133   assert(NumRegsLeft <= MaxNumRegsForArgsRet && "register estimate underflow");
9134 
9135   Ty = useFirstFieldIfTransparentUnion(Ty);
9136 
9137   if (isAggregateTypeForABI(Ty)) {
9138     // Records with non-trivial destructors/copy-constructors should not be
9139     // passed by value.
9140     if (auto RAA = getRecordArgABI(Ty, getCXXABI()))
9141       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
9142 
9143     // Ignore empty structs/unions.
9144     if (isEmptyRecord(getContext(), Ty, true))
9145       return ABIArgInfo::getIgnore();
9146 
9147     // Lower single-element structs to just pass a regular value. TODO: We
9148     // could do reasonable-size multiple-element structs too, using getExpand(),
9149     // though watch out for things like bitfields.
9150     if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
9151       return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
9152 
9153     if (const RecordType *RT = Ty->getAs<RecordType>()) {
9154       const RecordDecl *RD = RT->getDecl();
9155       if (RD->hasFlexibleArrayMember())
9156         return DefaultABIInfo::classifyArgumentType(Ty);
9157     }
9158 
9159     // Pack aggregates <= 8 bytes into single VGPR or pair.
9160     uint64_t Size = getContext().getTypeSize(Ty);
9161     if (Size <= 64) {
9162       unsigned NumRegs = (Size + 31) / 32;
9163       NumRegsLeft -= std::min(NumRegsLeft, NumRegs);
9164 
9165       if (Size <= 16)
9166         return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
9167 
9168       if (Size <= 32)
9169         return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
9170 
9171       // XXX: Should this be i64 instead, and should the limit increase?
9172       llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext());
9173       return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2));
9174     }
9175 
9176     if (NumRegsLeft > 0) {
9177       unsigned NumRegs = numRegsForType(Ty);
9178       if (NumRegsLeft >= NumRegs) {
9179         NumRegsLeft -= NumRegs;
9180         return ABIArgInfo::getDirect();
9181       }
9182     }
9183   }
9184 
9185   // Otherwise just do the default thing.
9186   ABIArgInfo ArgInfo = DefaultABIInfo::classifyArgumentType(Ty);
9187   if (!ArgInfo.isIndirect()) {
9188     unsigned NumRegs = numRegsForType(Ty);
9189     NumRegsLeft -= std::min(NumRegs, NumRegsLeft);
9190   }
9191 
9192   return ArgInfo;
9193 }
9194 
9195 class AMDGPUTargetCodeGenInfo : public TargetCodeGenInfo {
9196 public:
9197   AMDGPUTargetCodeGenInfo(CodeGenTypes &CGT)
9198       : TargetCodeGenInfo(std::make_unique<AMDGPUABIInfo>(CGT)) {}
9199 
9200   void setFunctionDeclAttributes(const FunctionDecl *FD, llvm::Function *F,
9201                                  CodeGenModule &CGM) const;
9202 
9203   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
9204                            CodeGen::CodeGenModule &M) const override;
9205   unsigned getOpenCLKernelCallingConv() const override;
9206 
9207   llvm::Constant *getNullPointer(const CodeGen::CodeGenModule &CGM,
9208       llvm::PointerType *T, QualType QT) const override;
9209 
9210   LangAS getASTAllocaAddressSpace() const override {
9211     return getLangASFromTargetAS(
9212         getABIInfo().getDataLayout().getAllocaAddrSpace());
9213   }
9214   LangAS getGlobalVarAddressSpace(CodeGenModule &CGM,
9215                                   const VarDecl *D) const override;
9216   llvm::SyncScope::ID getLLVMSyncScopeID(const LangOptions &LangOpts,
9217                                          SyncScope Scope,
9218                                          llvm::AtomicOrdering Ordering,
9219                                          llvm::LLVMContext &Ctx) const override;
9220   llvm::Function *
9221   createEnqueuedBlockKernel(CodeGenFunction &CGF,
9222                             llvm::Function *BlockInvokeFunc,
9223                             llvm::Type *BlockTy) const override;
9224   bool shouldEmitStaticExternCAliases() const override;
9225   void setCUDAKernelCallingConvention(const FunctionType *&FT) const override;
9226 };
9227 }
9228 
9229 static bool requiresAMDGPUProtectedVisibility(const Decl *D,
9230                                               llvm::GlobalValue *GV) {
9231   if (GV->getVisibility() != llvm::GlobalValue::HiddenVisibility)
9232     return false;
9233 
9234   return D->hasAttr<OpenCLKernelAttr>() ||
9235          (isa<FunctionDecl>(D) && D->hasAttr<CUDAGlobalAttr>()) ||
9236          (isa<VarDecl>(D) &&
9237           (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>() ||
9238            cast<VarDecl>(D)->getType()->isCUDADeviceBuiltinSurfaceType() ||
9239            cast<VarDecl>(D)->getType()->isCUDADeviceBuiltinTextureType()));
9240 }
9241 
9242 void AMDGPUTargetCodeGenInfo::setFunctionDeclAttributes(
9243     const FunctionDecl *FD, llvm::Function *F, CodeGenModule &M) const {
9244   const auto *ReqdWGS =
9245       M.getLangOpts().OpenCL ? FD->getAttr<ReqdWorkGroupSizeAttr>() : nullptr;
9246   const bool IsOpenCLKernel =
9247       M.getLangOpts().OpenCL && FD->hasAttr<OpenCLKernelAttr>();
9248   const bool IsHIPKernel = M.getLangOpts().HIP && FD->hasAttr<CUDAGlobalAttr>();
9249 
9250   const auto *FlatWGS = FD->getAttr<AMDGPUFlatWorkGroupSizeAttr>();
9251   if (ReqdWGS || FlatWGS) {
9252     unsigned Min = 0;
9253     unsigned Max = 0;
9254     if (FlatWGS) {
9255       Min = FlatWGS->getMin()
9256                 ->EvaluateKnownConstInt(M.getContext())
9257                 .getExtValue();
9258       Max = FlatWGS->getMax()
9259                 ->EvaluateKnownConstInt(M.getContext())
9260                 .getExtValue();
9261     }
9262     if (ReqdWGS && Min == 0 && Max == 0)
9263       Min = Max = ReqdWGS->getXDim() * ReqdWGS->getYDim() * ReqdWGS->getZDim();
9264 
9265     if (Min != 0) {
9266       assert(Min <= Max && "Min must be less than or equal Max");
9267 
9268       std::string AttrVal = llvm::utostr(Min) + "," + llvm::utostr(Max);
9269       F->addFnAttr("amdgpu-flat-work-group-size", AttrVal);
9270     } else
9271       assert(Max == 0 && "Max must be zero");
9272   } else if (IsOpenCLKernel || IsHIPKernel) {
9273     // By default, restrict the maximum size to a value specified by
9274     // --gpu-max-threads-per-block=n or its default value for HIP.
9275     const unsigned OpenCLDefaultMaxWorkGroupSize = 256;
9276     const unsigned DefaultMaxWorkGroupSize =
9277         IsOpenCLKernel ? OpenCLDefaultMaxWorkGroupSize
9278                        : M.getLangOpts().GPUMaxThreadsPerBlock;
9279     std::string AttrVal =
9280         std::string("1,") + llvm::utostr(DefaultMaxWorkGroupSize);
9281     F->addFnAttr("amdgpu-flat-work-group-size", AttrVal);
9282   }
9283 
9284   if (const auto *Attr = FD->getAttr<AMDGPUWavesPerEUAttr>()) {
9285     unsigned Min =
9286         Attr->getMin()->EvaluateKnownConstInt(M.getContext()).getExtValue();
9287     unsigned Max = Attr->getMax() ? Attr->getMax()
9288                                         ->EvaluateKnownConstInt(M.getContext())
9289                                         .getExtValue()
9290                                   : 0;
9291 
9292     if (Min != 0) {
9293       assert((Max == 0 || Min <= Max) && "Min must be less than or equal Max");
9294 
9295       std::string AttrVal = llvm::utostr(Min);
9296       if (Max != 0)
9297         AttrVal = AttrVal + "," + llvm::utostr(Max);
9298       F->addFnAttr("amdgpu-waves-per-eu", AttrVal);
9299     } else
9300       assert(Max == 0 && "Max must be zero");
9301   }
9302 
9303   if (const auto *Attr = FD->getAttr<AMDGPUNumSGPRAttr>()) {
9304     unsigned NumSGPR = Attr->getNumSGPR();
9305 
9306     if (NumSGPR != 0)
9307       F->addFnAttr("amdgpu-num-sgpr", llvm::utostr(NumSGPR));
9308   }
9309 
9310   if (const auto *Attr = FD->getAttr<AMDGPUNumVGPRAttr>()) {
9311     uint32_t NumVGPR = Attr->getNumVGPR();
9312 
9313     if (NumVGPR != 0)
9314       F->addFnAttr("amdgpu-num-vgpr", llvm::utostr(NumVGPR));
9315   }
9316 }
9317 
9318 void AMDGPUTargetCodeGenInfo::setTargetAttributes(
9319     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
9320   if (requiresAMDGPUProtectedVisibility(D, GV)) {
9321     GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
9322     GV->setDSOLocal(true);
9323   }
9324 
9325   if (GV->isDeclaration())
9326     return;
9327 
9328   llvm::Function *F = dyn_cast<llvm::Function>(GV);
9329   if (!F)
9330     return;
9331 
9332   const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
9333   if (FD)
9334     setFunctionDeclAttributes(FD, F, M);
9335 
9336   const bool IsHIPKernel =
9337       M.getLangOpts().HIP && FD && FD->hasAttr<CUDAGlobalAttr>();
9338 
9339   if (IsHIPKernel)
9340     F->addFnAttr("uniform-work-group-size", "true");
9341 
9342   if (M.getContext().getTargetInfo().allowAMDGPUUnsafeFPAtomics())
9343     F->addFnAttr("amdgpu-unsafe-fp-atomics", "true");
9344 
9345   if (!getABIInfo().getCodeGenOpts().EmitIEEENaNCompliantInsts)
9346     F->addFnAttr("amdgpu-ieee", "false");
9347 }
9348 
9349 unsigned AMDGPUTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
9350   return llvm::CallingConv::AMDGPU_KERNEL;
9351 }
9352 
9353 // Currently LLVM assumes null pointers always have value 0,
9354 // which results in incorrectly transformed IR. Therefore, instead of
9355 // emitting null pointers in private and local address spaces, a null
9356 // pointer in generic address space is emitted which is casted to a
9357 // pointer in local or private address space.
9358 llvm::Constant *AMDGPUTargetCodeGenInfo::getNullPointer(
9359     const CodeGen::CodeGenModule &CGM, llvm::PointerType *PT,
9360     QualType QT) const {
9361   if (CGM.getContext().getTargetNullPointerValue(QT) == 0)
9362     return llvm::ConstantPointerNull::get(PT);
9363 
9364   auto &Ctx = CGM.getContext();
9365   auto NPT = llvm::PointerType::getWithSamePointeeType(
9366       PT, Ctx.getTargetAddressSpace(LangAS::opencl_generic));
9367   return llvm::ConstantExpr::getAddrSpaceCast(
9368       llvm::ConstantPointerNull::get(NPT), PT);
9369 }
9370 
9371 LangAS
9372 AMDGPUTargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM,
9373                                                   const VarDecl *D) const {
9374   assert(!CGM.getLangOpts().OpenCL &&
9375          !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) &&
9376          "Address space agnostic languages only");
9377   LangAS DefaultGlobalAS = getLangASFromTargetAS(
9378       CGM.getContext().getTargetAddressSpace(LangAS::opencl_global));
9379   if (!D)
9380     return DefaultGlobalAS;
9381 
9382   LangAS AddrSpace = D->getType().getAddressSpace();
9383   assert(AddrSpace == LangAS::Default || isTargetAddressSpace(AddrSpace));
9384   if (AddrSpace != LangAS::Default)
9385     return AddrSpace;
9386 
9387   // Only promote to address space 4 if VarDecl has constant initialization.
9388   if (CGM.isTypeConstant(D->getType(), false) &&
9389       D->hasConstantInitialization()) {
9390     if (auto ConstAS = CGM.getTarget().getConstantAddressSpace())
9391       return ConstAS.getValue();
9392   }
9393   return DefaultGlobalAS;
9394 }
9395 
9396 llvm::SyncScope::ID
9397 AMDGPUTargetCodeGenInfo::getLLVMSyncScopeID(const LangOptions &LangOpts,
9398                                             SyncScope Scope,
9399                                             llvm::AtomicOrdering Ordering,
9400                                             llvm::LLVMContext &Ctx) const {
9401   std::string Name;
9402   switch (Scope) {
9403   case SyncScope::HIPSingleThread:
9404     Name = "singlethread";
9405     break;
9406   case SyncScope::HIPWavefront:
9407   case SyncScope::OpenCLSubGroup:
9408     Name = "wavefront";
9409     break;
9410   case SyncScope::HIPWorkgroup:
9411   case SyncScope::OpenCLWorkGroup:
9412     Name = "workgroup";
9413     break;
9414   case SyncScope::HIPAgent:
9415   case SyncScope::OpenCLDevice:
9416     Name = "agent";
9417     break;
9418   case SyncScope::HIPSystem:
9419   case SyncScope::OpenCLAllSVMDevices:
9420     Name = "";
9421     break;
9422   }
9423 
9424   if (Ordering != llvm::AtomicOrdering::SequentiallyConsistent) {
9425     if (!Name.empty())
9426       Name = Twine(Twine(Name) + Twine("-")).str();
9427 
9428     Name = Twine(Twine(Name) + Twine("one-as")).str();
9429   }
9430 
9431   return Ctx.getOrInsertSyncScopeID(Name);
9432 }
9433 
9434 bool AMDGPUTargetCodeGenInfo::shouldEmitStaticExternCAliases() const {
9435   return false;
9436 }
9437 
9438 void AMDGPUTargetCodeGenInfo::setCUDAKernelCallingConvention(
9439     const FunctionType *&FT) const {
9440   FT = getABIInfo().getContext().adjustFunctionType(
9441       FT, FT->getExtInfo().withCallingConv(CC_OpenCLKernel));
9442 }
9443 
9444 //===----------------------------------------------------------------------===//
9445 // SPARC v8 ABI Implementation.
9446 // Based on the SPARC Compliance Definition version 2.4.1.
9447 //
9448 // Ensures that complex values are passed in registers.
9449 //
9450 namespace {
9451 class SparcV8ABIInfo : public DefaultABIInfo {
9452 public:
9453   SparcV8ABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
9454 
9455 private:
9456   ABIArgInfo classifyReturnType(QualType RetTy) const;
9457   void computeInfo(CGFunctionInfo &FI) const override;
9458 };
9459 } // end anonymous namespace
9460 
9461 
9462 ABIArgInfo
9463 SparcV8ABIInfo::classifyReturnType(QualType Ty) const {
9464   if (Ty->isAnyComplexType()) {
9465     return ABIArgInfo::getDirect();
9466   }
9467   else {
9468     return DefaultABIInfo::classifyReturnType(Ty);
9469   }
9470 }
9471 
9472 void SparcV8ABIInfo::computeInfo(CGFunctionInfo &FI) const {
9473 
9474   FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
9475   for (auto &Arg : FI.arguments())
9476     Arg.info = classifyArgumentType(Arg.type);
9477 }
9478 
9479 namespace {
9480 class SparcV8TargetCodeGenInfo : public TargetCodeGenInfo {
9481 public:
9482   SparcV8TargetCodeGenInfo(CodeGenTypes &CGT)
9483       : TargetCodeGenInfo(std::make_unique<SparcV8ABIInfo>(CGT)) {}
9484 
9485   llvm::Value *decodeReturnAddress(CodeGen::CodeGenFunction &CGF,
9486                                    llvm::Value *Address) const override {
9487     int Offset;
9488     if (isAggregateTypeForABI(CGF.CurFnInfo->getReturnType()))
9489       Offset = 12;
9490     else
9491       Offset = 8;
9492     return CGF.Builder.CreateGEP(CGF.Int8Ty, Address,
9493                                  llvm::ConstantInt::get(CGF.Int32Ty, Offset));
9494   }
9495 
9496   llvm::Value *encodeReturnAddress(CodeGen::CodeGenFunction &CGF,
9497                                    llvm::Value *Address) const override {
9498     int Offset;
9499     if (isAggregateTypeForABI(CGF.CurFnInfo->getReturnType()))
9500       Offset = -12;
9501     else
9502       Offset = -8;
9503     return CGF.Builder.CreateGEP(CGF.Int8Ty, Address,
9504                                  llvm::ConstantInt::get(CGF.Int32Ty, Offset));
9505   }
9506 };
9507 } // end anonymous namespace
9508 
9509 //===----------------------------------------------------------------------===//
9510 // SPARC v9 ABI Implementation.
9511 // Based on the SPARC Compliance Definition version 2.4.1.
9512 //
9513 // Function arguments a mapped to a nominal "parameter array" and promoted to
9514 // registers depending on their type. Each argument occupies 8 or 16 bytes in
9515 // the array, structs larger than 16 bytes are passed indirectly.
9516 //
9517 // One case requires special care:
9518 //
9519 //   struct mixed {
9520 //     int i;
9521 //     float f;
9522 //   };
9523 //
9524 // When a struct mixed is passed by value, it only occupies 8 bytes in the
9525 // parameter array, but the int is passed in an integer register, and the float
9526 // is passed in a floating point register. This is represented as two arguments
9527 // with the LLVM IR inreg attribute:
9528 //
9529 //   declare void f(i32 inreg %i, float inreg %f)
9530 //
9531 // The code generator will only allocate 4 bytes from the parameter array for
9532 // the inreg arguments. All other arguments are allocated a multiple of 8
9533 // bytes.
9534 //
9535 namespace {
9536 class SparcV9ABIInfo : public ABIInfo {
9537 public:
9538   SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
9539 
9540 private:
9541   ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
9542   void computeInfo(CGFunctionInfo &FI) const override;
9543   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9544                     QualType Ty) const override;
9545 
9546   // Coercion type builder for structs passed in registers. The coercion type
9547   // serves two purposes:
9548   //
9549   // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
9550   //    in registers.
9551   // 2. Expose aligned floating point elements as first-level elements, so the
9552   //    code generator knows to pass them in floating point registers.
9553   //
9554   // We also compute the InReg flag which indicates that the struct contains
9555   // aligned 32-bit floats.
9556   //
9557   struct CoerceBuilder {
9558     llvm::LLVMContext &Context;
9559     const llvm::DataLayout &DL;
9560     SmallVector<llvm::Type*, 8> Elems;
9561     uint64_t Size;
9562     bool InReg;
9563 
9564     CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
9565       : Context(c), DL(dl), Size(0), InReg(false) {}
9566 
9567     // Pad Elems with integers until Size is ToSize.
9568     void pad(uint64_t ToSize) {
9569       assert(ToSize >= Size && "Cannot remove elements");
9570       if (ToSize == Size)
9571         return;
9572 
9573       // Finish the current 64-bit word.
9574       uint64_t Aligned = llvm::alignTo(Size, 64);
9575       if (Aligned > Size && Aligned <= ToSize) {
9576         Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
9577         Size = Aligned;
9578       }
9579 
9580       // Add whole 64-bit words.
9581       while (Size + 64 <= ToSize) {
9582         Elems.push_back(llvm::Type::getInt64Ty(Context));
9583         Size += 64;
9584       }
9585 
9586       // Final in-word padding.
9587       if (Size < ToSize) {
9588         Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
9589         Size = ToSize;
9590       }
9591     }
9592 
9593     // Add a floating point element at Offset.
9594     void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
9595       // Unaligned floats are treated as integers.
9596       if (Offset % Bits)
9597         return;
9598       // The InReg flag is only required if there are any floats < 64 bits.
9599       if (Bits < 64)
9600         InReg = true;
9601       pad(Offset);
9602       Elems.push_back(Ty);
9603       Size = Offset + Bits;
9604     }
9605 
9606     // Add a struct type to the coercion type, starting at Offset (in bits).
9607     void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
9608       const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
9609       for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
9610         llvm::Type *ElemTy = StrTy->getElementType(i);
9611         uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
9612         switch (ElemTy->getTypeID()) {
9613         case llvm::Type::StructTyID:
9614           addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
9615           break;
9616         case llvm::Type::FloatTyID:
9617           addFloat(ElemOffset, ElemTy, 32);
9618           break;
9619         case llvm::Type::DoubleTyID:
9620           addFloat(ElemOffset, ElemTy, 64);
9621           break;
9622         case llvm::Type::FP128TyID:
9623           addFloat(ElemOffset, ElemTy, 128);
9624           break;
9625         case llvm::Type::PointerTyID:
9626           if (ElemOffset % 64 == 0) {
9627             pad(ElemOffset);
9628             Elems.push_back(ElemTy);
9629             Size += 64;
9630           }
9631           break;
9632         default:
9633           break;
9634         }
9635       }
9636     }
9637 
9638     // Check if Ty is a usable substitute for the coercion type.
9639     bool isUsableType(llvm::StructType *Ty) const {
9640       return llvm::makeArrayRef(Elems) == Ty->elements();
9641     }
9642 
9643     // Get the coercion type as a literal struct type.
9644     llvm::Type *getType() const {
9645       if (Elems.size() == 1)
9646         return Elems.front();
9647       else
9648         return llvm::StructType::get(Context, Elems);
9649     }
9650   };
9651 };
9652 } // end anonymous namespace
9653 
9654 ABIArgInfo
9655 SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
9656   if (Ty->isVoidType())
9657     return ABIArgInfo::getIgnore();
9658 
9659   uint64_t Size = getContext().getTypeSize(Ty);
9660 
9661   // Anything too big to fit in registers is passed with an explicit indirect
9662   // pointer / sret pointer.
9663   if (Size > SizeLimit)
9664     return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
9665 
9666   // Treat an enum type as its underlying type.
9667   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
9668     Ty = EnumTy->getDecl()->getIntegerType();
9669 
9670   // Integer types smaller than a register are extended.
9671   if (Size < 64 && Ty->isIntegerType())
9672     return ABIArgInfo::getExtend(Ty);
9673 
9674   if (const auto *EIT = Ty->getAs<BitIntType>())
9675     if (EIT->getNumBits() < 64)
9676       return ABIArgInfo::getExtend(Ty);
9677 
9678   // Other non-aggregates go in registers.
9679   if (!isAggregateTypeForABI(Ty))
9680     return ABIArgInfo::getDirect();
9681 
9682   // If a C++ object has either a non-trivial copy constructor or a non-trivial
9683   // destructor, it is passed with an explicit indirect pointer / sret pointer.
9684   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
9685     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
9686 
9687   // This is a small aggregate type that should be passed in registers.
9688   // Build a coercion type from the LLVM struct type.
9689   llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
9690   if (!StrTy)
9691     return ABIArgInfo::getDirect();
9692 
9693   CoerceBuilder CB(getVMContext(), getDataLayout());
9694   CB.addStruct(0, StrTy);
9695   CB.pad(llvm::alignTo(CB.DL.getTypeSizeInBits(StrTy), 64));
9696 
9697   // Try to use the original type for coercion.
9698   llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
9699 
9700   if (CB.InReg)
9701     return ABIArgInfo::getDirectInReg(CoerceTy);
9702   else
9703     return ABIArgInfo::getDirect(CoerceTy);
9704 }
9705 
9706 Address SparcV9ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9707                                   QualType Ty) const {
9708   ABIArgInfo AI = classifyType(Ty, 16 * 8);
9709   llvm::Type *ArgTy = CGT.ConvertType(Ty);
9710   if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
9711     AI.setCoerceToType(ArgTy);
9712 
9713   CharUnits SlotSize = CharUnits::fromQuantity(8);
9714 
9715   CGBuilderTy &Builder = CGF.Builder;
9716   Address Addr = Address(Builder.CreateLoad(VAListAddr, "ap.cur"),
9717                          getVAListElementType(CGF), SlotSize);
9718   llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
9719 
9720   auto TypeInfo = getContext().getTypeInfoInChars(Ty);
9721 
9722   Address ArgAddr = Address::invalid();
9723   CharUnits Stride;
9724   switch (AI.getKind()) {
9725   case ABIArgInfo::Expand:
9726   case ABIArgInfo::CoerceAndExpand:
9727   case ABIArgInfo::InAlloca:
9728     llvm_unreachable("Unsupported ABI kind for va_arg");
9729 
9730   case ABIArgInfo::Extend: {
9731     Stride = SlotSize;
9732     CharUnits Offset = SlotSize - TypeInfo.Width;
9733     ArgAddr = Builder.CreateConstInBoundsByteGEP(Addr, Offset, "extend");
9734     break;
9735   }
9736 
9737   case ABIArgInfo::Direct: {
9738     auto AllocSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
9739     Stride = CharUnits::fromQuantity(AllocSize).alignTo(SlotSize);
9740     ArgAddr = Addr;
9741     break;
9742   }
9743 
9744   case ABIArgInfo::Indirect:
9745   case ABIArgInfo::IndirectAliased:
9746     Stride = SlotSize;
9747     ArgAddr = Builder.CreateElementBitCast(Addr, ArgPtrTy, "indirect");
9748     ArgAddr = Address(Builder.CreateLoad(ArgAddr, "indirect.arg"), ArgTy,
9749                       TypeInfo.Align);
9750     break;
9751 
9752   case ABIArgInfo::Ignore:
9753     return Address(llvm::UndefValue::get(ArgPtrTy), ArgTy, TypeInfo.Align);
9754   }
9755 
9756   // Update VAList.
9757   Address NextPtr = Builder.CreateConstInBoundsByteGEP(Addr, Stride, "ap.next");
9758   Builder.CreateStore(NextPtr.getPointer(), VAListAddr);
9759 
9760   return Builder.CreateElementBitCast(ArgAddr, ArgTy, "arg.addr");
9761 }
9762 
9763 void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
9764   FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
9765   for (auto &I : FI.arguments())
9766     I.info = classifyType(I.type, 16 * 8);
9767 }
9768 
9769 namespace {
9770 class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
9771 public:
9772   SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
9773       : TargetCodeGenInfo(std::make_unique<SparcV9ABIInfo>(CGT)) {}
9774 
9775   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
9776     return 14;
9777   }
9778 
9779   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
9780                                llvm::Value *Address) const override;
9781 
9782   llvm::Value *decodeReturnAddress(CodeGen::CodeGenFunction &CGF,
9783                                    llvm::Value *Address) const override {
9784     return CGF.Builder.CreateGEP(CGF.Int8Ty, Address,
9785                                  llvm::ConstantInt::get(CGF.Int32Ty, 8));
9786   }
9787 
9788   llvm::Value *encodeReturnAddress(CodeGen::CodeGenFunction &CGF,
9789                                    llvm::Value *Address) const override {
9790     return CGF.Builder.CreateGEP(CGF.Int8Ty, Address,
9791                                  llvm::ConstantInt::get(CGF.Int32Ty, -8));
9792   }
9793 };
9794 } // end anonymous namespace
9795 
9796 bool
9797 SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
9798                                                 llvm::Value *Address) const {
9799   // This is calculated from the LLVM and GCC tables and verified
9800   // against gcc output.  AFAIK all ABIs use the same encoding.
9801 
9802   CodeGen::CGBuilderTy &Builder = CGF.Builder;
9803 
9804   llvm::IntegerType *i8 = CGF.Int8Ty;
9805   llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
9806   llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
9807 
9808   // 0-31: the 8-byte general-purpose registers
9809   AssignToArrayRange(Builder, Address, Eight8, 0, 31);
9810 
9811   // 32-63: f0-31, the 4-byte floating-point registers
9812   AssignToArrayRange(Builder, Address, Four8, 32, 63);
9813 
9814   //   Y   = 64
9815   //   PSR = 65
9816   //   WIM = 66
9817   //   TBR = 67
9818   //   PC  = 68
9819   //   NPC = 69
9820   //   FSR = 70
9821   //   CSR = 71
9822   AssignToArrayRange(Builder, Address, Eight8, 64, 71);
9823 
9824   // 72-87: d0-15, the 8-byte floating-point registers
9825   AssignToArrayRange(Builder, Address, Eight8, 72, 87);
9826 
9827   return false;
9828 }
9829 
9830 // ARC ABI implementation.
9831 namespace {
9832 
9833 class ARCABIInfo : public DefaultABIInfo {
9834 public:
9835   using DefaultABIInfo::DefaultABIInfo;
9836 
9837 private:
9838   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9839                     QualType Ty) const override;
9840 
9841   void updateState(const ABIArgInfo &Info, QualType Ty, CCState &State) const {
9842     if (!State.FreeRegs)
9843       return;
9844     if (Info.isIndirect() && Info.getInReg())
9845       State.FreeRegs--;
9846     else if (Info.isDirect() && Info.getInReg()) {
9847       unsigned sz = (getContext().getTypeSize(Ty) + 31) / 32;
9848       if (sz < State.FreeRegs)
9849         State.FreeRegs -= sz;
9850       else
9851         State.FreeRegs = 0;
9852     }
9853   }
9854 
9855   void computeInfo(CGFunctionInfo &FI) const override {
9856     CCState State(FI);
9857     // ARC uses 8 registers to pass arguments.
9858     State.FreeRegs = 8;
9859 
9860     if (!getCXXABI().classifyReturnType(FI))
9861       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
9862     updateState(FI.getReturnInfo(), FI.getReturnType(), State);
9863     for (auto &I : FI.arguments()) {
9864       I.info = classifyArgumentType(I.type, State.FreeRegs);
9865       updateState(I.info, I.type, State);
9866     }
9867   }
9868 
9869   ABIArgInfo getIndirectByRef(QualType Ty, bool HasFreeRegs) const;
9870   ABIArgInfo getIndirectByValue(QualType Ty) const;
9871   ABIArgInfo classifyArgumentType(QualType Ty, uint8_t FreeRegs) const;
9872   ABIArgInfo classifyReturnType(QualType RetTy) const;
9873 };
9874 
9875 class ARCTargetCodeGenInfo : public TargetCodeGenInfo {
9876 public:
9877   ARCTargetCodeGenInfo(CodeGenTypes &CGT)
9878       : TargetCodeGenInfo(std::make_unique<ARCABIInfo>(CGT)) {}
9879 };
9880 
9881 
9882 ABIArgInfo ARCABIInfo::getIndirectByRef(QualType Ty, bool HasFreeRegs) const {
9883   return HasFreeRegs ? getNaturalAlignIndirectInReg(Ty) :
9884                        getNaturalAlignIndirect(Ty, false);
9885 }
9886 
9887 ABIArgInfo ARCABIInfo::getIndirectByValue(QualType Ty) const {
9888   // Compute the byval alignment.
9889   const unsigned MinABIStackAlignInBytes = 4;
9890   unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
9891   return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true,
9892                                  TypeAlign > MinABIStackAlignInBytes);
9893 }
9894 
9895 Address ARCABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9896                               QualType Ty) const {
9897   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
9898                           getContext().getTypeInfoInChars(Ty),
9899                           CharUnits::fromQuantity(4), true);
9900 }
9901 
9902 ABIArgInfo ARCABIInfo::classifyArgumentType(QualType Ty,
9903                                             uint8_t FreeRegs) const {
9904   // Handle the generic C++ ABI.
9905   const RecordType *RT = Ty->getAs<RecordType>();
9906   if (RT) {
9907     CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
9908     if (RAA == CGCXXABI::RAA_Indirect)
9909       return getIndirectByRef(Ty, FreeRegs > 0);
9910 
9911     if (RAA == CGCXXABI::RAA_DirectInMemory)
9912       return getIndirectByValue(Ty);
9913   }
9914 
9915   // Treat an enum type as its underlying type.
9916   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
9917     Ty = EnumTy->getDecl()->getIntegerType();
9918 
9919   auto SizeInRegs = llvm::alignTo(getContext().getTypeSize(Ty), 32) / 32;
9920 
9921   if (isAggregateTypeForABI(Ty)) {
9922     // Structures with flexible arrays are always indirect.
9923     if (RT && RT->getDecl()->hasFlexibleArrayMember())
9924       return getIndirectByValue(Ty);
9925 
9926     // Ignore empty structs/unions.
9927     if (isEmptyRecord(getContext(), Ty, true))
9928       return ABIArgInfo::getIgnore();
9929 
9930     llvm::LLVMContext &LLVMContext = getVMContext();
9931 
9932     llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
9933     SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32);
9934     llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
9935 
9936     return FreeRegs >= SizeInRegs ?
9937         ABIArgInfo::getDirectInReg(Result) :
9938         ABIArgInfo::getDirect(Result, 0, nullptr, false);
9939   }
9940 
9941   if (const auto *EIT = Ty->getAs<BitIntType>())
9942     if (EIT->getNumBits() > 64)
9943       return getIndirectByValue(Ty);
9944 
9945   return isPromotableIntegerTypeForABI(Ty)
9946              ? (FreeRegs >= SizeInRegs ? ABIArgInfo::getExtendInReg(Ty)
9947                                        : ABIArgInfo::getExtend(Ty))
9948              : (FreeRegs >= SizeInRegs ? ABIArgInfo::getDirectInReg()
9949                                        : ABIArgInfo::getDirect());
9950 }
9951 
9952 ABIArgInfo ARCABIInfo::classifyReturnType(QualType RetTy) const {
9953   if (RetTy->isAnyComplexType())
9954     return ABIArgInfo::getDirectInReg();
9955 
9956   // Arguments of size > 4 registers are indirect.
9957   auto RetSize = llvm::alignTo(getContext().getTypeSize(RetTy), 32) / 32;
9958   if (RetSize > 4)
9959     return getIndirectByRef(RetTy, /*HasFreeRegs*/ true);
9960 
9961   return DefaultABIInfo::classifyReturnType(RetTy);
9962 }
9963 
9964 } // End anonymous namespace.
9965 
9966 //===----------------------------------------------------------------------===//
9967 // XCore ABI Implementation
9968 //===----------------------------------------------------------------------===//
9969 
9970 namespace {
9971 
9972 /// A SmallStringEnc instance is used to build up the TypeString by passing
9973 /// it by reference between functions that append to it.
9974 typedef llvm::SmallString<128> SmallStringEnc;
9975 
9976 /// TypeStringCache caches the meta encodings of Types.
9977 ///
9978 /// The reason for caching TypeStrings is two fold:
9979 ///   1. To cache a type's encoding for later uses;
9980 ///   2. As a means to break recursive member type inclusion.
9981 ///
9982 /// A cache Entry can have a Status of:
9983 ///   NonRecursive:   The type encoding is not recursive;
9984 ///   Recursive:      The type encoding is recursive;
9985 ///   Incomplete:     An incomplete TypeString;
9986 ///   IncompleteUsed: An incomplete TypeString that has been used in a
9987 ///                   Recursive type encoding.
9988 ///
9989 /// A NonRecursive entry will have all of its sub-members expanded as fully
9990 /// as possible. Whilst it may contain types which are recursive, the type
9991 /// itself is not recursive and thus its encoding may be safely used whenever
9992 /// the type is encountered.
9993 ///
9994 /// A Recursive entry will have all of its sub-members expanded as fully as
9995 /// possible. The type itself is recursive and it may contain other types which
9996 /// are recursive. The Recursive encoding must not be used during the expansion
9997 /// of a recursive type's recursive branch. For simplicity the code uses
9998 /// IncompleteCount to reject all usage of Recursive encodings for member types.
9999 ///
10000 /// An Incomplete entry is always a RecordType and only encodes its
10001 /// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and
10002 /// are placed into the cache during type expansion as a means to identify and
10003 /// handle recursive inclusion of types as sub-members. If there is recursion
10004 /// the entry becomes IncompleteUsed.
10005 ///
10006 /// During the expansion of a RecordType's members:
10007 ///
10008 ///   If the cache contains a NonRecursive encoding for the member type, the
10009 ///   cached encoding is used;
10010 ///
10011 ///   If the cache contains a Recursive encoding for the member type, the
10012 ///   cached encoding is 'Swapped' out, as it may be incorrect, and...
10013 ///
10014 ///   If the member is a RecordType, an Incomplete encoding is placed into the
10015 ///   cache to break potential recursive inclusion of itself as a sub-member;
10016 ///
10017 ///   Once a member RecordType has been expanded, its temporary incomplete
10018 ///   entry is removed from the cache. If a Recursive encoding was swapped out
10019 ///   it is swapped back in;
10020 ///
10021 ///   If an incomplete entry is used to expand a sub-member, the incomplete
10022 ///   entry is marked as IncompleteUsed. The cache keeps count of how many
10023 ///   IncompleteUsed entries it currently contains in IncompleteUsedCount;
10024 ///
10025 ///   If a member's encoding is found to be a NonRecursive or Recursive viz:
10026 ///   IncompleteUsedCount==0, the member's encoding is added to the cache.
10027 ///   Else the member is part of a recursive type and thus the recursion has
10028 ///   been exited too soon for the encoding to be correct for the member.
10029 ///
10030 class TypeStringCache {
10031   enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed};
10032   struct Entry {
10033     std::string Str;     // The encoded TypeString for the type.
10034     enum Status State;   // Information about the encoding in 'Str'.
10035     std::string Swapped; // A temporary place holder for a Recursive encoding
10036                          // during the expansion of RecordType's members.
10037   };
10038   std::map<const IdentifierInfo *, struct Entry> Map;
10039   unsigned IncompleteCount;     // Number of Incomplete entries in the Map.
10040   unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map.
10041 public:
10042   TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {}
10043   void addIncomplete(const IdentifierInfo *ID, std::string StubEnc);
10044   bool removeIncomplete(const IdentifierInfo *ID);
10045   void addIfComplete(const IdentifierInfo *ID, StringRef Str,
10046                      bool IsRecursive);
10047   StringRef lookupStr(const IdentifierInfo *ID);
10048 };
10049 
10050 /// TypeString encodings for enum & union fields must be order.
10051 /// FieldEncoding is a helper for this ordering process.
10052 class FieldEncoding {
10053   bool HasName;
10054   std::string Enc;
10055 public:
10056   FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {}
10057   StringRef str() { return Enc; }
10058   bool operator<(const FieldEncoding &rhs) const {
10059     if (HasName != rhs.HasName) return HasName;
10060     return Enc < rhs.Enc;
10061   }
10062 };
10063 
10064 class XCoreABIInfo : public DefaultABIInfo {
10065 public:
10066   XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
10067   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
10068                     QualType Ty) const override;
10069 };
10070 
10071 class XCoreTargetCodeGenInfo : public TargetCodeGenInfo {
10072   mutable TypeStringCache TSC;
10073   void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
10074                     const CodeGen::CodeGenModule &M) const;
10075 
10076 public:
10077   XCoreTargetCodeGenInfo(CodeGenTypes &CGT)
10078       : TargetCodeGenInfo(std::make_unique<XCoreABIInfo>(CGT)) {}
10079   void emitTargetMetadata(CodeGen::CodeGenModule &CGM,
10080                           const llvm::MapVector<GlobalDecl, StringRef>
10081                               &MangledDeclNames) const override;
10082 };
10083 
10084 } // End anonymous namespace.
10085 
10086 // TODO: this implementation is likely now redundant with the default
10087 // EmitVAArg.
10088 Address XCoreABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
10089                                 QualType Ty) const {
10090   CGBuilderTy &Builder = CGF.Builder;
10091 
10092   // Get the VAList.
10093   CharUnits SlotSize = CharUnits::fromQuantity(4);
10094   Address AP = Address(Builder.CreateLoad(VAListAddr),
10095                        getVAListElementType(CGF), SlotSize);
10096 
10097   // Handle the argument.
10098   ABIArgInfo AI = classifyArgumentType(Ty);
10099   CharUnits TypeAlign = getContext().getTypeAlignInChars(Ty);
10100   llvm::Type *ArgTy = CGT.ConvertType(Ty);
10101   if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
10102     AI.setCoerceToType(ArgTy);
10103   llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
10104 
10105   Address Val = Address::invalid();
10106   CharUnits ArgSize = CharUnits::Zero();
10107   switch (AI.getKind()) {
10108   case ABIArgInfo::Expand:
10109   case ABIArgInfo::CoerceAndExpand:
10110   case ABIArgInfo::InAlloca:
10111     llvm_unreachable("Unsupported ABI kind for va_arg");
10112   case ABIArgInfo::Ignore:
10113     Val = Address(llvm::UndefValue::get(ArgPtrTy), ArgTy, TypeAlign);
10114     ArgSize = CharUnits::Zero();
10115     break;
10116   case ABIArgInfo::Extend:
10117   case ABIArgInfo::Direct:
10118     Val = Builder.CreateElementBitCast(AP, ArgTy);
10119     ArgSize = CharUnits::fromQuantity(
10120         getDataLayout().getTypeAllocSize(AI.getCoerceToType()));
10121     ArgSize = ArgSize.alignTo(SlotSize);
10122     break;
10123   case ABIArgInfo::Indirect:
10124   case ABIArgInfo::IndirectAliased:
10125     Val = Builder.CreateElementBitCast(AP, ArgPtrTy);
10126     Val = Address(Builder.CreateLoad(Val), ArgTy, TypeAlign);
10127     ArgSize = SlotSize;
10128     break;
10129   }
10130 
10131   // Increment the VAList.
10132   if (!ArgSize.isZero()) {
10133     Address APN = Builder.CreateConstInBoundsByteGEP(AP, ArgSize);
10134     Builder.CreateStore(APN.getPointer(), VAListAddr);
10135   }
10136 
10137   return Val;
10138 }
10139 
10140 /// During the expansion of a RecordType, an incomplete TypeString is placed
10141 /// into the cache as a means to identify and break recursion.
10142 /// If there is a Recursive encoding in the cache, it is swapped out and will
10143 /// be reinserted by removeIncomplete().
10144 /// All other types of encoding should have been used rather than arriving here.
10145 void TypeStringCache::addIncomplete(const IdentifierInfo *ID,
10146                                     std::string StubEnc) {
10147   if (!ID)
10148     return;
10149   Entry &E = Map[ID];
10150   assert( (E.Str.empty() || E.State == Recursive) &&
10151          "Incorrectly use of addIncomplete");
10152   assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()");
10153   E.Swapped.swap(E.Str); // swap out the Recursive
10154   E.Str.swap(StubEnc);
10155   E.State = Incomplete;
10156   ++IncompleteCount;
10157 }
10158 
10159 /// Once the RecordType has been expanded, the temporary incomplete TypeString
10160 /// must be removed from the cache.
10161 /// If a Recursive was swapped out by addIncomplete(), it will be replaced.
10162 /// Returns true if the RecordType was defined recursively.
10163 bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) {
10164   if (!ID)
10165     return false;
10166   auto I = Map.find(ID);
10167   assert(I != Map.end() && "Entry not present");
10168   Entry &E = I->second;
10169   assert( (E.State == Incomplete ||
10170            E.State == IncompleteUsed) &&
10171          "Entry must be an incomplete type");
10172   bool IsRecursive = false;
10173   if (E.State == IncompleteUsed) {
10174     // We made use of our Incomplete encoding, thus we are recursive.
10175     IsRecursive = true;
10176     --IncompleteUsedCount;
10177   }
10178   if (E.Swapped.empty())
10179     Map.erase(I);
10180   else {
10181     // Swap the Recursive back.
10182     E.Swapped.swap(E.Str);
10183     E.Swapped.clear();
10184     E.State = Recursive;
10185   }
10186   --IncompleteCount;
10187   return IsRecursive;
10188 }
10189 
10190 /// Add the encoded TypeString to the cache only if it is NonRecursive or
10191 /// Recursive (viz: all sub-members were expanded as fully as possible).
10192 void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str,
10193                                     bool IsRecursive) {
10194   if (!ID || IncompleteUsedCount)
10195     return; // No key or it is is an incomplete sub-type so don't add.
10196   Entry &E = Map[ID];
10197   if (IsRecursive && !E.Str.empty()) {
10198     assert(E.State==Recursive && E.Str.size() == Str.size() &&
10199            "This is not the same Recursive entry");
10200     // The parent container was not recursive after all, so we could have used
10201     // this Recursive sub-member entry after all, but we assumed the worse when
10202     // we started viz: IncompleteCount!=0.
10203     return;
10204   }
10205   assert(E.Str.empty() && "Entry already present");
10206   E.Str = Str.str();
10207   E.State = IsRecursive? Recursive : NonRecursive;
10208 }
10209 
10210 /// Return a cached TypeString encoding for the ID. If there isn't one, or we
10211 /// are recursively expanding a type (IncompleteCount != 0) and the cached
10212 /// encoding is Recursive, return an empty StringRef.
10213 StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) {
10214   if (!ID)
10215     return StringRef();   // We have no key.
10216   auto I = Map.find(ID);
10217   if (I == Map.end())
10218     return StringRef();   // We have no encoding.
10219   Entry &E = I->second;
10220   if (E.State == Recursive && IncompleteCount)
10221     return StringRef();   // We don't use Recursive encodings for member types.
10222 
10223   if (E.State == Incomplete) {
10224     // The incomplete type is being used to break out of recursion.
10225     E.State = IncompleteUsed;
10226     ++IncompleteUsedCount;
10227   }
10228   return E.Str;
10229 }
10230 
10231 /// The XCore ABI includes a type information section that communicates symbol
10232 /// type information to the linker. The linker uses this information to verify
10233 /// safety/correctness of things such as array bound and pointers et al.
10234 /// The ABI only requires C (and XC) language modules to emit TypeStrings.
10235 /// This type information (TypeString) is emitted into meta data for all global
10236 /// symbols: definitions, declarations, functions & variables.
10237 ///
10238 /// The TypeString carries type, qualifier, name, size & value details.
10239 /// Please see 'Tools Development Guide' section 2.16.2 for format details:
10240 /// https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf
10241 /// The output is tested by test/CodeGen/xcore-stringtype.c.
10242 ///
10243 static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
10244                           const CodeGen::CodeGenModule &CGM,
10245                           TypeStringCache &TSC);
10246 
10247 /// XCore uses emitTargetMD to emit TypeString metadata for global symbols.
10248 void XCoreTargetCodeGenInfo::emitTargetMD(
10249     const Decl *D, llvm::GlobalValue *GV,
10250     const CodeGen::CodeGenModule &CGM) const {
10251   SmallStringEnc Enc;
10252   if (getTypeString(Enc, D, CGM, TSC)) {
10253     llvm::LLVMContext &Ctx = CGM.getModule().getContext();
10254     llvm::Metadata *MDVals[] = {llvm::ConstantAsMetadata::get(GV),
10255                                 llvm::MDString::get(Ctx, Enc.str())};
10256     llvm::NamedMDNode *MD =
10257       CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings");
10258     MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
10259   }
10260 }
10261 
10262 void XCoreTargetCodeGenInfo::emitTargetMetadata(
10263     CodeGen::CodeGenModule &CGM,
10264     const llvm::MapVector<GlobalDecl, StringRef> &MangledDeclNames) const {
10265   // Warning, new MangledDeclNames may be appended within this loop.
10266   // We rely on MapVector insertions adding new elements to the end
10267   // of the container.
10268   for (unsigned I = 0; I != MangledDeclNames.size(); ++I) {
10269     auto Val = *(MangledDeclNames.begin() + I);
10270     llvm::GlobalValue *GV = CGM.GetGlobalValue(Val.second);
10271     if (GV) {
10272       const Decl *D = Val.first.getDecl()->getMostRecentDecl();
10273       emitTargetMD(D, GV, CGM);
10274     }
10275   }
10276 }
10277 
10278 //===----------------------------------------------------------------------===//
10279 // Base ABI and target codegen info implementation common between SPIR and
10280 // SPIR-V.
10281 //===----------------------------------------------------------------------===//
10282 
10283 namespace {
10284 class CommonSPIRABIInfo : public DefaultABIInfo {
10285 public:
10286   CommonSPIRABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) { setCCs(); }
10287 
10288 private:
10289   void setCCs();
10290 };
10291 
10292 class SPIRVABIInfo : public CommonSPIRABIInfo {
10293 public:
10294   SPIRVABIInfo(CodeGenTypes &CGT) : CommonSPIRABIInfo(CGT) {}
10295   void computeInfo(CGFunctionInfo &FI) const override;
10296 
10297 private:
10298   ABIArgInfo classifyKernelArgumentType(QualType Ty) const;
10299 };
10300 } // end anonymous namespace
10301 namespace {
10302 class CommonSPIRTargetCodeGenInfo : public TargetCodeGenInfo {
10303 public:
10304   CommonSPIRTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
10305       : TargetCodeGenInfo(std::make_unique<CommonSPIRABIInfo>(CGT)) {}
10306   CommonSPIRTargetCodeGenInfo(std::unique_ptr<ABIInfo> ABIInfo)
10307       : TargetCodeGenInfo(std::move(ABIInfo)) {}
10308 
10309   LangAS getASTAllocaAddressSpace() const override {
10310     return getLangASFromTargetAS(
10311         getABIInfo().getDataLayout().getAllocaAddrSpace());
10312   }
10313 
10314   unsigned getOpenCLKernelCallingConv() const override;
10315 };
10316 class SPIRVTargetCodeGenInfo : public CommonSPIRTargetCodeGenInfo {
10317 public:
10318   SPIRVTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
10319       : CommonSPIRTargetCodeGenInfo(std::make_unique<SPIRVABIInfo>(CGT)) {}
10320   void setCUDAKernelCallingConvention(const FunctionType *&FT) const override;
10321 };
10322 } // End anonymous namespace.
10323 
10324 void CommonSPIRABIInfo::setCCs() {
10325   assert(getRuntimeCC() == llvm::CallingConv::C);
10326   RuntimeCC = llvm::CallingConv::SPIR_FUNC;
10327 }
10328 
10329 ABIArgInfo SPIRVABIInfo::classifyKernelArgumentType(QualType Ty) const {
10330   if (getContext().getLangOpts().CUDAIsDevice) {
10331     // Coerce pointer arguments with default address space to CrossWorkGroup
10332     // pointers for HIPSPV/CUDASPV. When the language mode is HIP/CUDA, the
10333     // SPIRTargetInfo maps cuda_device to SPIR-V's CrossWorkGroup address space.
10334     llvm::Type *LTy = CGT.ConvertType(Ty);
10335     auto DefaultAS = getContext().getTargetAddressSpace(LangAS::Default);
10336     auto GlobalAS = getContext().getTargetAddressSpace(LangAS::cuda_device);
10337     auto *PtrTy = llvm::dyn_cast<llvm::PointerType>(LTy);
10338     if (PtrTy && PtrTy->getAddressSpace() == DefaultAS) {
10339       LTy = llvm::PointerType::getWithSamePointeeType(PtrTy, GlobalAS);
10340       return ABIArgInfo::getDirect(LTy, 0, nullptr, false);
10341     }
10342   }
10343   return classifyArgumentType(Ty);
10344 }
10345 
10346 void SPIRVABIInfo::computeInfo(CGFunctionInfo &FI) const {
10347   // The logic is same as in DefaultABIInfo with an exception on the kernel
10348   // arguments handling.
10349   llvm::CallingConv::ID CC = FI.getCallingConvention();
10350 
10351   if (!getCXXABI().classifyReturnType(FI))
10352     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
10353 
10354   for (auto &I : FI.arguments()) {
10355     if (CC == llvm::CallingConv::SPIR_KERNEL) {
10356       I.info = classifyKernelArgumentType(I.type);
10357     } else {
10358       I.info = classifyArgumentType(I.type);
10359     }
10360   }
10361 }
10362 
10363 namespace clang {
10364 namespace CodeGen {
10365 void computeSPIRKernelABIInfo(CodeGenModule &CGM, CGFunctionInfo &FI) {
10366   if (CGM.getTarget().getTriple().isSPIRV())
10367     SPIRVABIInfo(CGM.getTypes()).computeInfo(FI);
10368   else
10369     CommonSPIRABIInfo(CGM.getTypes()).computeInfo(FI);
10370 }
10371 }
10372 }
10373 
10374 unsigned CommonSPIRTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
10375   return llvm::CallingConv::SPIR_KERNEL;
10376 }
10377 
10378 void SPIRVTargetCodeGenInfo::setCUDAKernelCallingConvention(
10379     const FunctionType *&FT) const {
10380   // Convert HIP kernels to SPIR-V kernels.
10381   if (getABIInfo().getContext().getLangOpts().HIP) {
10382     FT = getABIInfo().getContext().adjustFunctionType(
10383         FT, FT->getExtInfo().withCallingConv(CC_OpenCLKernel));
10384     return;
10385   }
10386 }
10387 
10388 static bool appendType(SmallStringEnc &Enc, QualType QType,
10389                        const CodeGen::CodeGenModule &CGM,
10390                        TypeStringCache &TSC);
10391 
10392 /// Helper function for appendRecordType().
10393 /// Builds a SmallVector containing the encoded field types in declaration
10394 /// order.
10395 static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE,
10396                              const RecordDecl *RD,
10397                              const CodeGen::CodeGenModule &CGM,
10398                              TypeStringCache &TSC) {
10399   for (const auto *Field : RD->fields()) {
10400     SmallStringEnc Enc;
10401     Enc += "m(";
10402     Enc += Field->getName();
10403     Enc += "){";
10404     if (Field->isBitField()) {
10405       Enc += "b(";
10406       llvm::raw_svector_ostream OS(Enc);
10407       OS << Field->getBitWidthValue(CGM.getContext());
10408       Enc += ':';
10409     }
10410     if (!appendType(Enc, Field->getType(), CGM, TSC))
10411       return false;
10412     if (Field->isBitField())
10413       Enc += ')';
10414     Enc += '}';
10415     FE.emplace_back(!Field->getName().empty(), Enc);
10416   }
10417   return true;
10418 }
10419 
10420 /// Appends structure and union types to Enc and adds encoding to cache.
10421 /// Recursively calls appendType (via extractFieldType) for each field.
10422 /// Union types have their fields ordered according to the ABI.
10423 static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT,
10424                              const CodeGen::CodeGenModule &CGM,
10425                              TypeStringCache &TSC, const IdentifierInfo *ID) {
10426   // Append the cached TypeString if we have one.
10427   StringRef TypeString = TSC.lookupStr(ID);
10428   if (!TypeString.empty()) {
10429     Enc += TypeString;
10430     return true;
10431   }
10432 
10433   // Start to emit an incomplete TypeString.
10434   size_t Start = Enc.size();
10435   Enc += (RT->isUnionType()? 'u' : 's');
10436   Enc += '(';
10437   if (ID)
10438     Enc += ID->getName();
10439   Enc += "){";
10440 
10441   // We collect all encoded fields and order as necessary.
10442   bool IsRecursive = false;
10443   const RecordDecl *RD = RT->getDecl()->getDefinition();
10444   if (RD && !RD->field_empty()) {
10445     // An incomplete TypeString stub is placed in the cache for this RecordType
10446     // so that recursive calls to this RecordType will use it whilst building a
10447     // complete TypeString for this RecordType.
10448     SmallVector<FieldEncoding, 16> FE;
10449     std::string StubEnc(Enc.substr(Start).str());
10450     StubEnc += '}';  // StubEnc now holds a valid incomplete TypeString.
10451     TSC.addIncomplete(ID, std::move(StubEnc));
10452     if (!extractFieldType(FE, RD, CGM, TSC)) {
10453       (void) TSC.removeIncomplete(ID);
10454       return false;
10455     }
10456     IsRecursive = TSC.removeIncomplete(ID);
10457     // The ABI requires unions to be sorted but not structures.
10458     // See FieldEncoding::operator< for sort algorithm.
10459     if (RT->isUnionType())
10460       llvm::sort(FE);
10461     // We can now complete the TypeString.
10462     unsigned E = FE.size();
10463     for (unsigned I = 0; I != E; ++I) {
10464       if (I)
10465         Enc += ',';
10466       Enc += FE[I].str();
10467     }
10468   }
10469   Enc += '}';
10470   TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive);
10471   return true;
10472 }
10473 
10474 /// Appends enum types to Enc and adds the encoding to the cache.
10475 static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET,
10476                            TypeStringCache &TSC,
10477                            const IdentifierInfo *ID) {
10478   // Append the cached TypeString if we have one.
10479   StringRef TypeString = TSC.lookupStr(ID);
10480   if (!TypeString.empty()) {
10481     Enc += TypeString;
10482     return true;
10483   }
10484 
10485   size_t Start = Enc.size();
10486   Enc += "e(";
10487   if (ID)
10488     Enc += ID->getName();
10489   Enc += "){";
10490 
10491   // We collect all encoded enumerations and order them alphanumerically.
10492   if (const EnumDecl *ED = ET->getDecl()->getDefinition()) {
10493     SmallVector<FieldEncoding, 16> FE;
10494     for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E;
10495          ++I) {
10496       SmallStringEnc EnumEnc;
10497       EnumEnc += "m(";
10498       EnumEnc += I->getName();
10499       EnumEnc += "){";
10500       I->getInitVal().toString(EnumEnc);
10501       EnumEnc += '}';
10502       FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc));
10503     }
10504     llvm::sort(FE);
10505     unsigned E = FE.size();
10506     for (unsigned I = 0; I != E; ++I) {
10507       if (I)
10508         Enc += ',';
10509       Enc += FE[I].str();
10510     }
10511   }
10512   Enc += '}';
10513   TSC.addIfComplete(ID, Enc.substr(Start), false);
10514   return true;
10515 }
10516 
10517 /// Appends type's qualifier to Enc.
10518 /// This is done prior to appending the type's encoding.
10519 static void appendQualifier(SmallStringEnc &Enc, QualType QT) {
10520   // Qualifiers are emitted in alphabetical order.
10521   static const char *const Table[]={"","c:","r:","cr:","v:","cv:","rv:","crv:"};
10522   int Lookup = 0;
10523   if (QT.isConstQualified())
10524     Lookup += 1<<0;
10525   if (QT.isRestrictQualified())
10526     Lookup += 1<<1;
10527   if (QT.isVolatileQualified())
10528     Lookup += 1<<2;
10529   Enc += Table[Lookup];
10530 }
10531 
10532 /// Appends built-in types to Enc.
10533 static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) {
10534   const char *EncType;
10535   switch (BT->getKind()) {
10536     case BuiltinType::Void:
10537       EncType = "0";
10538       break;
10539     case BuiltinType::Bool:
10540       EncType = "b";
10541       break;
10542     case BuiltinType::Char_U:
10543       EncType = "uc";
10544       break;
10545     case BuiltinType::UChar:
10546       EncType = "uc";
10547       break;
10548     case BuiltinType::SChar:
10549       EncType = "sc";
10550       break;
10551     case BuiltinType::UShort:
10552       EncType = "us";
10553       break;
10554     case BuiltinType::Short:
10555       EncType = "ss";
10556       break;
10557     case BuiltinType::UInt:
10558       EncType = "ui";
10559       break;
10560     case BuiltinType::Int:
10561       EncType = "si";
10562       break;
10563     case BuiltinType::ULong:
10564       EncType = "ul";
10565       break;
10566     case BuiltinType::Long:
10567       EncType = "sl";
10568       break;
10569     case BuiltinType::ULongLong:
10570       EncType = "ull";
10571       break;
10572     case BuiltinType::LongLong:
10573       EncType = "sll";
10574       break;
10575     case BuiltinType::Float:
10576       EncType = "ft";
10577       break;
10578     case BuiltinType::Double:
10579       EncType = "d";
10580       break;
10581     case BuiltinType::LongDouble:
10582       EncType = "ld";
10583       break;
10584     default:
10585       return false;
10586   }
10587   Enc += EncType;
10588   return true;
10589 }
10590 
10591 /// Appends a pointer encoding to Enc before calling appendType for the pointee.
10592 static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT,
10593                               const CodeGen::CodeGenModule &CGM,
10594                               TypeStringCache &TSC) {
10595   Enc += "p(";
10596   if (!appendType(Enc, PT->getPointeeType(), CGM, TSC))
10597     return false;
10598   Enc += ')';
10599   return true;
10600 }
10601 
10602 /// Appends array encoding to Enc before calling appendType for the element.
10603 static bool appendArrayType(SmallStringEnc &Enc, QualType QT,
10604                             const ArrayType *AT,
10605                             const CodeGen::CodeGenModule &CGM,
10606                             TypeStringCache &TSC, StringRef NoSizeEnc) {
10607   if (AT->getSizeModifier() != ArrayType::Normal)
10608     return false;
10609   Enc += "a(";
10610   if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
10611     CAT->getSize().toStringUnsigned(Enc);
10612   else
10613     Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "".
10614   Enc += ':';
10615   // The Qualifiers should be attached to the type rather than the array.
10616   appendQualifier(Enc, QT);
10617   if (!appendType(Enc, AT->getElementType(), CGM, TSC))
10618     return false;
10619   Enc += ')';
10620   return true;
10621 }
10622 
10623 /// Appends a function encoding to Enc, calling appendType for the return type
10624 /// and the arguments.
10625 static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT,
10626                              const CodeGen::CodeGenModule &CGM,
10627                              TypeStringCache &TSC) {
10628   Enc += "f{";
10629   if (!appendType(Enc, FT->getReturnType(), CGM, TSC))
10630     return false;
10631   Enc += "}(";
10632   if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) {
10633     // N.B. we are only interested in the adjusted param types.
10634     auto I = FPT->param_type_begin();
10635     auto E = FPT->param_type_end();
10636     if (I != E) {
10637       do {
10638         if (!appendType(Enc, *I, CGM, TSC))
10639           return false;
10640         ++I;
10641         if (I != E)
10642           Enc += ',';
10643       } while (I != E);
10644       if (FPT->isVariadic())
10645         Enc += ",va";
10646     } else {
10647       if (FPT->isVariadic())
10648         Enc += "va";
10649       else
10650         Enc += '0';
10651     }
10652   }
10653   Enc += ')';
10654   return true;
10655 }
10656 
10657 /// Handles the type's qualifier before dispatching a call to handle specific
10658 /// type encodings.
10659 static bool appendType(SmallStringEnc &Enc, QualType QType,
10660                        const CodeGen::CodeGenModule &CGM,
10661                        TypeStringCache &TSC) {
10662 
10663   QualType QT = QType.getCanonicalType();
10664 
10665   if (const ArrayType *AT = QT->getAsArrayTypeUnsafe())
10666     // The Qualifiers should be attached to the type rather than the array.
10667     // Thus we don't call appendQualifier() here.
10668     return appendArrayType(Enc, QT, AT, CGM, TSC, "");
10669 
10670   appendQualifier(Enc, QT);
10671 
10672   if (const BuiltinType *BT = QT->getAs<BuiltinType>())
10673     return appendBuiltinType(Enc, BT);
10674 
10675   if (const PointerType *PT = QT->getAs<PointerType>())
10676     return appendPointerType(Enc, PT, CGM, TSC);
10677 
10678   if (const EnumType *ET = QT->getAs<EnumType>())
10679     return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier());
10680 
10681   if (const RecordType *RT = QT->getAsStructureType())
10682     return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
10683 
10684   if (const RecordType *RT = QT->getAsUnionType())
10685     return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
10686 
10687   if (const FunctionType *FT = QT->getAs<FunctionType>())
10688     return appendFunctionType(Enc, FT, CGM, TSC);
10689 
10690   return false;
10691 }
10692 
10693 static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
10694                           const CodeGen::CodeGenModule &CGM,
10695                           TypeStringCache &TSC) {
10696   if (!D)
10697     return false;
10698 
10699   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
10700     if (FD->getLanguageLinkage() != CLanguageLinkage)
10701       return false;
10702     return appendType(Enc, FD->getType(), CGM, TSC);
10703   }
10704 
10705   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
10706     if (VD->getLanguageLinkage() != CLanguageLinkage)
10707       return false;
10708     QualType QT = VD->getType().getCanonicalType();
10709     if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) {
10710       // Global ArrayTypes are given a size of '*' if the size is unknown.
10711       // The Qualifiers should be attached to the type rather than the array.
10712       // Thus we don't call appendQualifier() here.
10713       return appendArrayType(Enc, QT, AT, CGM, TSC, "*");
10714     }
10715     return appendType(Enc, QT, CGM, TSC);
10716   }
10717   return false;
10718 }
10719 
10720 //===----------------------------------------------------------------------===//
10721 // RISCV ABI Implementation
10722 //===----------------------------------------------------------------------===//
10723 
10724 namespace {
10725 class RISCVABIInfo : public DefaultABIInfo {
10726 private:
10727   // Size of the integer ('x') registers in bits.
10728   unsigned XLen;
10729   // Size of the floating point ('f') registers in bits. Note that the target
10730   // ISA might have a wider FLen than the selected ABI (e.g. an RV32IF target
10731   // with soft float ABI has FLen==0).
10732   unsigned FLen;
10733   static const int NumArgGPRs = 8;
10734   static const int NumArgFPRs = 8;
10735   bool detectFPCCEligibleStructHelper(QualType Ty, CharUnits CurOff,
10736                                       llvm::Type *&Field1Ty,
10737                                       CharUnits &Field1Off,
10738                                       llvm::Type *&Field2Ty,
10739                                       CharUnits &Field2Off) const;
10740 
10741 public:
10742   RISCVABIInfo(CodeGen::CodeGenTypes &CGT, unsigned XLen, unsigned FLen)
10743       : DefaultABIInfo(CGT), XLen(XLen), FLen(FLen) {}
10744 
10745   // DefaultABIInfo's classifyReturnType and classifyArgumentType are
10746   // non-virtual, but computeInfo is virtual, so we overload it.
10747   void computeInfo(CGFunctionInfo &FI) const override;
10748 
10749   ABIArgInfo classifyArgumentType(QualType Ty, bool IsFixed, int &ArgGPRsLeft,
10750                                   int &ArgFPRsLeft) const;
10751   ABIArgInfo classifyReturnType(QualType RetTy) const;
10752 
10753   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
10754                     QualType Ty) const override;
10755 
10756   ABIArgInfo extendType(QualType Ty) const;
10757 
10758   bool detectFPCCEligibleStruct(QualType Ty, llvm::Type *&Field1Ty,
10759                                 CharUnits &Field1Off, llvm::Type *&Field2Ty,
10760                                 CharUnits &Field2Off, int &NeededArgGPRs,
10761                                 int &NeededArgFPRs) const;
10762   ABIArgInfo coerceAndExpandFPCCEligibleStruct(llvm::Type *Field1Ty,
10763                                                CharUnits Field1Off,
10764                                                llvm::Type *Field2Ty,
10765                                                CharUnits Field2Off) const;
10766 };
10767 } // end anonymous namespace
10768 
10769 void RISCVABIInfo::computeInfo(CGFunctionInfo &FI) const {
10770   QualType RetTy = FI.getReturnType();
10771   if (!getCXXABI().classifyReturnType(FI))
10772     FI.getReturnInfo() = classifyReturnType(RetTy);
10773 
10774   // IsRetIndirect is true if classifyArgumentType indicated the value should
10775   // be passed indirect, or if the type size is a scalar greater than 2*XLen
10776   // and not a complex type with elements <= FLen. e.g. fp128 is passed direct
10777   // in LLVM IR, relying on the backend lowering code to rewrite the argument
10778   // list and pass indirectly on RV32.
10779   bool IsRetIndirect = FI.getReturnInfo().getKind() == ABIArgInfo::Indirect;
10780   if (!IsRetIndirect && RetTy->isScalarType() &&
10781       getContext().getTypeSize(RetTy) > (2 * XLen)) {
10782     if (RetTy->isComplexType() && FLen) {
10783       QualType EltTy = RetTy->castAs<ComplexType>()->getElementType();
10784       IsRetIndirect = getContext().getTypeSize(EltTy) > FLen;
10785     } else {
10786       // This is a normal scalar > 2*XLen, such as fp128 on RV32.
10787       IsRetIndirect = true;
10788     }
10789   }
10790 
10791   // We must track the number of GPRs used in order to conform to the RISC-V
10792   // ABI, as integer scalars passed in registers should have signext/zeroext
10793   // when promoted, but are anyext if passed on the stack. As GPR usage is
10794   // different for variadic arguments, we must also track whether we are
10795   // examining a vararg or not.
10796   int ArgGPRsLeft = IsRetIndirect ? NumArgGPRs - 1 : NumArgGPRs;
10797   int ArgFPRsLeft = FLen ? NumArgFPRs : 0;
10798   int NumFixedArgs = FI.getNumRequiredArgs();
10799 
10800   int ArgNum = 0;
10801   for (auto &ArgInfo : FI.arguments()) {
10802     bool IsFixed = ArgNum < NumFixedArgs;
10803     ArgInfo.info =
10804         classifyArgumentType(ArgInfo.type, IsFixed, ArgGPRsLeft, ArgFPRsLeft);
10805     ArgNum++;
10806   }
10807 }
10808 
10809 // Returns true if the struct is a potential candidate for the floating point
10810 // calling convention. If this function returns true, the caller is
10811 // responsible for checking that if there is only a single field then that
10812 // field is a float.
10813 bool RISCVABIInfo::detectFPCCEligibleStructHelper(QualType Ty, CharUnits CurOff,
10814                                                   llvm::Type *&Field1Ty,
10815                                                   CharUnits &Field1Off,
10816                                                   llvm::Type *&Field2Ty,
10817                                                   CharUnits &Field2Off) const {
10818   bool IsInt = Ty->isIntegralOrEnumerationType();
10819   bool IsFloat = Ty->isRealFloatingType();
10820 
10821   if (IsInt || IsFloat) {
10822     uint64_t Size = getContext().getTypeSize(Ty);
10823     if (IsInt && Size > XLen)
10824       return false;
10825     // Can't be eligible if larger than the FP registers. Half precision isn't
10826     // currently supported on RISC-V and the ABI hasn't been confirmed, so
10827     // default to the integer ABI in that case.
10828     if (IsFloat && (Size > FLen || Size < 32))
10829       return false;
10830     // Can't be eligible if an integer type was already found (int+int pairs
10831     // are not eligible).
10832     if (IsInt && Field1Ty && Field1Ty->isIntegerTy())
10833       return false;
10834     if (!Field1Ty) {
10835       Field1Ty = CGT.ConvertType(Ty);
10836       Field1Off = CurOff;
10837       return true;
10838     }
10839     if (!Field2Ty) {
10840       Field2Ty = CGT.ConvertType(Ty);
10841       Field2Off = CurOff;
10842       return true;
10843     }
10844     return false;
10845   }
10846 
10847   if (auto CTy = Ty->getAs<ComplexType>()) {
10848     if (Field1Ty)
10849       return false;
10850     QualType EltTy = CTy->getElementType();
10851     if (getContext().getTypeSize(EltTy) > FLen)
10852       return false;
10853     Field1Ty = CGT.ConvertType(EltTy);
10854     Field1Off = CurOff;
10855     Field2Ty = Field1Ty;
10856     Field2Off = Field1Off + getContext().getTypeSizeInChars(EltTy);
10857     return true;
10858   }
10859 
10860   if (const ConstantArrayType *ATy = getContext().getAsConstantArrayType(Ty)) {
10861     uint64_t ArraySize = ATy->getSize().getZExtValue();
10862     QualType EltTy = ATy->getElementType();
10863     CharUnits EltSize = getContext().getTypeSizeInChars(EltTy);
10864     for (uint64_t i = 0; i < ArraySize; ++i) {
10865       bool Ret = detectFPCCEligibleStructHelper(EltTy, CurOff, Field1Ty,
10866                                                 Field1Off, Field2Ty, Field2Off);
10867       if (!Ret)
10868         return false;
10869       CurOff += EltSize;
10870     }
10871     return true;
10872   }
10873 
10874   if (const auto *RTy = Ty->getAs<RecordType>()) {
10875     // Structures with either a non-trivial destructor or a non-trivial
10876     // copy constructor are not eligible for the FP calling convention.
10877     if (getRecordArgABI(Ty, CGT.getCXXABI()))
10878       return false;
10879     if (isEmptyRecord(getContext(), Ty, true))
10880       return true;
10881     const RecordDecl *RD = RTy->getDecl();
10882     // Unions aren't eligible unless they're empty (which is caught above).
10883     if (RD->isUnion())
10884       return false;
10885     int ZeroWidthBitFieldCount = 0;
10886     for (const FieldDecl *FD : RD->fields()) {
10887       const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
10888       uint64_t FieldOffInBits = Layout.getFieldOffset(FD->getFieldIndex());
10889       QualType QTy = FD->getType();
10890       if (FD->isBitField()) {
10891         unsigned BitWidth = FD->getBitWidthValue(getContext());
10892         // Allow a bitfield with a type greater than XLen as long as the
10893         // bitwidth is XLen or less.
10894         if (getContext().getTypeSize(QTy) > XLen && BitWidth <= XLen)
10895           QTy = getContext().getIntTypeForBitwidth(XLen, false);
10896         if (BitWidth == 0) {
10897           ZeroWidthBitFieldCount++;
10898           continue;
10899         }
10900       }
10901 
10902       bool Ret = detectFPCCEligibleStructHelper(
10903           QTy, CurOff + getContext().toCharUnitsFromBits(FieldOffInBits),
10904           Field1Ty, Field1Off, Field2Ty, Field2Off);
10905       if (!Ret)
10906         return false;
10907 
10908       // As a quirk of the ABI, zero-width bitfields aren't ignored for fp+fp
10909       // or int+fp structs, but are ignored for a struct with an fp field and
10910       // any number of zero-width bitfields.
10911       if (Field2Ty && ZeroWidthBitFieldCount > 0)
10912         return false;
10913     }
10914     return Field1Ty != nullptr;
10915   }
10916 
10917   return false;
10918 }
10919 
10920 // Determine if a struct is eligible for passing according to the floating
10921 // point calling convention (i.e., when flattened it contains a single fp
10922 // value, fp+fp, or int+fp of appropriate size). If so, NeededArgFPRs and
10923 // NeededArgGPRs are incremented appropriately.
10924 bool RISCVABIInfo::detectFPCCEligibleStruct(QualType Ty, llvm::Type *&Field1Ty,
10925                                             CharUnits &Field1Off,
10926                                             llvm::Type *&Field2Ty,
10927                                             CharUnits &Field2Off,
10928                                             int &NeededArgGPRs,
10929                                             int &NeededArgFPRs) const {
10930   Field1Ty = nullptr;
10931   Field2Ty = nullptr;
10932   NeededArgGPRs = 0;
10933   NeededArgFPRs = 0;
10934   bool IsCandidate = detectFPCCEligibleStructHelper(
10935       Ty, CharUnits::Zero(), Field1Ty, Field1Off, Field2Ty, Field2Off);
10936   // Not really a candidate if we have a single int but no float.
10937   if (Field1Ty && !Field2Ty && !Field1Ty->isFloatingPointTy())
10938     return false;
10939   if (!IsCandidate)
10940     return false;
10941   if (Field1Ty && Field1Ty->isFloatingPointTy())
10942     NeededArgFPRs++;
10943   else if (Field1Ty)
10944     NeededArgGPRs++;
10945   if (Field2Ty && Field2Ty->isFloatingPointTy())
10946     NeededArgFPRs++;
10947   else if (Field2Ty)
10948     NeededArgGPRs++;
10949   return true;
10950 }
10951 
10952 // Call getCoerceAndExpand for the two-element flattened struct described by
10953 // Field1Ty, Field1Off, Field2Ty, Field2Off. This method will create an
10954 // appropriate coerceToType and unpaddedCoerceToType.
10955 ABIArgInfo RISCVABIInfo::coerceAndExpandFPCCEligibleStruct(
10956     llvm::Type *Field1Ty, CharUnits Field1Off, llvm::Type *Field2Ty,
10957     CharUnits Field2Off) const {
10958   SmallVector<llvm::Type *, 3> CoerceElts;
10959   SmallVector<llvm::Type *, 2> UnpaddedCoerceElts;
10960   if (!Field1Off.isZero())
10961     CoerceElts.push_back(llvm::ArrayType::get(
10962         llvm::Type::getInt8Ty(getVMContext()), Field1Off.getQuantity()));
10963 
10964   CoerceElts.push_back(Field1Ty);
10965   UnpaddedCoerceElts.push_back(Field1Ty);
10966 
10967   if (!Field2Ty) {
10968     return ABIArgInfo::getCoerceAndExpand(
10969         llvm::StructType::get(getVMContext(), CoerceElts, !Field1Off.isZero()),
10970         UnpaddedCoerceElts[0]);
10971   }
10972 
10973   CharUnits Field2Align =
10974       CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(Field2Ty));
10975   CharUnits Field1End = Field1Off +
10976       CharUnits::fromQuantity(getDataLayout().getTypeStoreSize(Field1Ty));
10977   CharUnits Field2OffNoPadNoPack = Field1End.alignTo(Field2Align);
10978 
10979   CharUnits Padding = CharUnits::Zero();
10980   if (Field2Off > Field2OffNoPadNoPack)
10981     Padding = Field2Off - Field2OffNoPadNoPack;
10982   else if (Field2Off != Field2Align && Field2Off > Field1End)
10983     Padding = Field2Off - Field1End;
10984 
10985   bool IsPacked = !Field2Off.isMultipleOf(Field2Align);
10986 
10987   if (!Padding.isZero())
10988     CoerceElts.push_back(llvm::ArrayType::get(
10989         llvm::Type::getInt8Ty(getVMContext()), Padding.getQuantity()));
10990 
10991   CoerceElts.push_back(Field2Ty);
10992   UnpaddedCoerceElts.push_back(Field2Ty);
10993 
10994   auto CoerceToType =
10995       llvm::StructType::get(getVMContext(), CoerceElts, IsPacked);
10996   auto UnpaddedCoerceToType =
10997       llvm::StructType::get(getVMContext(), UnpaddedCoerceElts, IsPacked);
10998 
10999   return ABIArgInfo::getCoerceAndExpand(CoerceToType, UnpaddedCoerceToType);
11000 }
11001 
11002 ABIArgInfo RISCVABIInfo::classifyArgumentType(QualType Ty, bool IsFixed,
11003                                               int &ArgGPRsLeft,
11004                                               int &ArgFPRsLeft) const {
11005   assert(ArgGPRsLeft <= NumArgGPRs && "Arg GPR tracking underflow");
11006   Ty = useFirstFieldIfTransparentUnion(Ty);
11007 
11008   // Structures with either a non-trivial destructor or a non-trivial
11009   // copy constructor are always passed indirectly.
11010   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
11011     if (ArgGPRsLeft)
11012       ArgGPRsLeft -= 1;
11013     return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA ==
11014                                            CGCXXABI::RAA_DirectInMemory);
11015   }
11016 
11017   // Ignore empty structs/unions.
11018   if (isEmptyRecord(getContext(), Ty, true))
11019     return ABIArgInfo::getIgnore();
11020 
11021   uint64_t Size = getContext().getTypeSize(Ty);
11022 
11023   // Pass floating point values via FPRs if possible.
11024   if (IsFixed && Ty->isFloatingType() && !Ty->isComplexType() &&
11025       FLen >= Size && ArgFPRsLeft) {
11026     ArgFPRsLeft--;
11027     return ABIArgInfo::getDirect();
11028   }
11029 
11030   // Complex types for the hard float ABI must be passed direct rather than
11031   // using CoerceAndExpand.
11032   if (IsFixed && Ty->isComplexType() && FLen && ArgFPRsLeft >= 2) {
11033     QualType EltTy = Ty->castAs<ComplexType>()->getElementType();
11034     if (getContext().getTypeSize(EltTy) <= FLen) {
11035       ArgFPRsLeft -= 2;
11036       return ABIArgInfo::getDirect();
11037     }
11038   }
11039 
11040   if (IsFixed && FLen && Ty->isStructureOrClassType()) {
11041     llvm::Type *Field1Ty = nullptr;
11042     llvm::Type *Field2Ty = nullptr;
11043     CharUnits Field1Off = CharUnits::Zero();
11044     CharUnits Field2Off = CharUnits::Zero();
11045     int NeededArgGPRs = 0;
11046     int NeededArgFPRs = 0;
11047     bool IsCandidate =
11048         detectFPCCEligibleStruct(Ty, Field1Ty, Field1Off, Field2Ty, Field2Off,
11049                                  NeededArgGPRs, NeededArgFPRs);
11050     if (IsCandidate && NeededArgGPRs <= ArgGPRsLeft &&
11051         NeededArgFPRs <= ArgFPRsLeft) {
11052       ArgGPRsLeft -= NeededArgGPRs;
11053       ArgFPRsLeft -= NeededArgFPRs;
11054       return coerceAndExpandFPCCEligibleStruct(Field1Ty, Field1Off, Field2Ty,
11055                                                Field2Off);
11056     }
11057   }
11058 
11059   uint64_t NeededAlign = getContext().getTypeAlign(Ty);
11060   bool MustUseStack = false;
11061   // Determine the number of GPRs needed to pass the current argument
11062   // according to the ABI. 2*XLen-aligned varargs are passed in "aligned"
11063   // register pairs, so may consume 3 registers.
11064   int NeededArgGPRs = 1;
11065   if (!IsFixed && NeededAlign == 2 * XLen)
11066     NeededArgGPRs = 2 + (ArgGPRsLeft % 2);
11067   else if (Size > XLen && Size <= 2 * XLen)
11068     NeededArgGPRs = 2;
11069 
11070   if (NeededArgGPRs > ArgGPRsLeft) {
11071     MustUseStack = true;
11072     NeededArgGPRs = ArgGPRsLeft;
11073   }
11074 
11075   ArgGPRsLeft -= NeededArgGPRs;
11076 
11077   if (!isAggregateTypeForABI(Ty) && !Ty->isVectorType()) {
11078     // Treat an enum type as its underlying type.
11079     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
11080       Ty = EnumTy->getDecl()->getIntegerType();
11081 
11082     // All integral types are promoted to XLen width, unless passed on the
11083     // stack.
11084     if (Size < XLen && Ty->isIntegralOrEnumerationType() && !MustUseStack) {
11085       return extendType(Ty);
11086     }
11087 
11088     if (const auto *EIT = Ty->getAs<BitIntType>()) {
11089       if (EIT->getNumBits() < XLen && !MustUseStack)
11090         return extendType(Ty);
11091       if (EIT->getNumBits() > 128 ||
11092           (!getContext().getTargetInfo().hasInt128Type() &&
11093            EIT->getNumBits() > 64))
11094         return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
11095     }
11096 
11097     return ABIArgInfo::getDirect();
11098   }
11099 
11100   // Aggregates which are <= 2*XLen will be passed in registers if possible,
11101   // so coerce to integers.
11102   if (Size <= 2 * XLen) {
11103     unsigned Alignment = getContext().getTypeAlign(Ty);
11104 
11105     // Use a single XLen int if possible, 2*XLen if 2*XLen alignment is
11106     // required, and a 2-element XLen array if only XLen alignment is required.
11107     if (Size <= XLen) {
11108       return ABIArgInfo::getDirect(
11109           llvm::IntegerType::get(getVMContext(), XLen));
11110     } else if (Alignment == 2 * XLen) {
11111       return ABIArgInfo::getDirect(
11112           llvm::IntegerType::get(getVMContext(), 2 * XLen));
11113     } else {
11114       return ABIArgInfo::getDirect(llvm::ArrayType::get(
11115           llvm::IntegerType::get(getVMContext(), XLen), 2));
11116     }
11117   }
11118   return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
11119 }
11120 
11121 ABIArgInfo RISCVABIInfo::classifyReturnType(QualType RetTy) const {
11122   if (RetTy->isVoidType())
11123     return ABIArgInfo::getIgnore();
11124 
11125   int ArgGPRsLeft = 2;
11126   int ArgFPRsLeft = FLen ? 2 : 0;
11127 
11128   // The rules for return and argument types are the same, so defer to
11129   // classifyArgumentType.
11130   return classifyArgumentType(RetTy, /*IsFixed=*/true, ArgGPRsLeft,
11131                               ArgFPRsLeft);
11132 }
11133 
11134 Address RISCVABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
11135                                 QualType Ty) const {
11136   CharUnits SlotSize = CharUnits::fromQuantity(XLen / 8);
11137 
11138   // Empty records are ignored for parameter passing purposes.
11139   if (isEmptyRecord(getContext(), Ty, true)) {
11140     Address Addr = Address(CGF.Builder.CreateLoad(VAListAddr),
11141                            getVAListElementType(CGF), SlotSize);
11142     Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
11143     return Addr;
11144   }
11145 
11146   auto TInfo = getContext().getTypeInfoInChars(Ty);
11147 
11148   // Arguments bigger than 2*Xlen bytes are passed indirectly.
11149   bool IsIndirect = TInfo.Width > 2 * SlotSize;
11150 
11151   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TInfo,
11152                           SlotSize, /*AllowHigherAlign=*/true);
11153 }
11154 
11155 ABIArgInfo RISCVABIInfo::extendType(QualType Ty) const {
11156   int TySize = getContext().getTypeSize(Ty);
11157   // RV64 ABI requires unsigned 32 bit integers to be sign extended.
11158   if (XLen == 64 && Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
11159     return ABIArgInfo::getSignExtend(Ty);
11160   return ABIArgInfo::getExtend(Ty);
11161 }
11162 
11163 namespace {
11164 class RISCVTargetCodeGenInfo : public TargetCodeGenInfo {
11165 public:
11166   RISCVTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, unsigned XLen,
11167                          unsigned FLen)
11168       : TargetCodeGenInfo(std::make_unique<RISCVABIInfo>(CGT, XLen, FLen)) {}
11169 
11170   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
11171                            CodeGen::CodeGenModule &CGM) const override {
11172     const auto *FD = dyn_cast_or_null<FunctionDecl>(D);
11173     if (!FD) return;
11174 
11175     const auto *Attr = FD->getAttr<RISCVInterruptAttr>();
11176     if (!Attr)
11177       return;
11178 
11179     const char *Kind;
11180     switch (Attr->getInterrupt()) {
11181     case RISCVInterruptAttr::user: Kind = "user"; break;
11182     case RISCVInterruptAttr::supervisor: Kind = "supervisor"; break;
11183     case RISCVInterruptAttr::machine: Kind = "machine"; break;
11184     }
11185 
11186     auto *Fn = cast<llvm::Function>(GV);
11187 
11188     Fn->addFnAttr("interrupt", Kind);
11189   }
11190 };
11191 } // namespace
11192 
11193 //===----------------------------------------------------------------------===//
11194 // VE ABI Implementation.
11195 //
11196 namespace {
11197 class VEABIInfo : public DefaultABIInfo {
11198 public:
11199   VEABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
11200 
11201 private:
11202   ABIArgInfo classifyReturnType(QualType RetTy) const;
11203   ABIArgInfo classifyArgumentType(QualType RetTy) const;
11204   void computeInfo(CGFunctionInfo &FI) const override;
11205 };
11206 } // end anonymous namespace
11207 
11208 ABIArgInfo VEABIInfo::classifyReturnType(QualType Ty) const {
11209   if (Ty->isAnyComplexType())
11210     return ABIArgInfo::getDirect();
11211   uint64_t Size = getContext().getTypeSize(Ty);
11212   if (Size < 64 && Ty->isIntegerType())
11213     return ABIArgInfo::getExtend(Ty);
11214   return DefaultABIInfo::classifyReturnType(Ty);
11215 }
11216 
11217 ABIArgInfo VEABIInfo::classifyArgumentType(QualType Ty) const {
11218   if (Ty->isAnyComplexType())
11219     return ABIArgInfo::getDirect();
11220   uint64_t Size = getContext().getTypeSize(Ty);
11221   if (Size < 64 && Ty->isIntegerType())
11222     return ABIArgInfo::getExtend(Ty);
11223   return DefaultABIInfo::classifyArgumentType(Ty);
11224 }
11225 
11226 void VEABIInfo::computeInfo(CGFunctionInfo &FI) const {
11227   FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
11228   for (auto &Arg : FI.arguments())
11229     Arg.info = classifyArgumentType(Arg.type);
11230 }
11231 
11232 namespace {
11233 class VETargetCodeGenInfo : public TargetCodeGenInfo {
11234 public:
11235   VETargetCodeGenInfo(CodeGenTypes &CGT)
11236       : TargetCodeGenInfo(std::make_unique<VEABIInfo>(CGT)) {}
11237   // VE ABI requires the arguments of variadic and prototype-less functions
11238   // are passed in both registers and memory.
11239   bool isNoProtoCallVariadic(const CallArgList &args,
11240                              const FunctionNoProtoType *fnType) const override {
11241     return true;
11242   }
11243 };
11244 } // end anonymous namespace
11245 
11246 //===----------------------------------------------------------------------===//
11247 // Driver code
11248 //===----------------------------------------------------------------------===//
11249 
11250 bool CodeGenModule::supportsCOMDAT() const {
11251   return getTriple().supportsCOMDAT();
11252 }
11253 
11254 const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
11255   if (TheTargetCodeGenInfo)
11256     return *TheTargetCodeGenInfo;
11257 
11258   // Helper to set the unique_ptr while still keeping the return value.
11259   auto SetCGInfo = [&](TargetCodeGenInfo *P) -> const TargetCodeGenInfo & {
11260     this->TheTargetCodeGenInfo.reset(P);
11261     return *P;
11262   };
11263 
11264   const llvm::Triple &Triple = getTarget().getTriple();
11265   switch (Triple.getArch()) {
11266   default:
11267     return SetCGInfo(new DefaultTargetCodeGenInfo(Types));
11268 
11269   case llvm::Triple::le32:
11270     return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
11271   case llvm::Triple::m68k:
11272     return SetCGInfo(new M68kTargetCodeGenInfo(Types));
11273   case llvm::Triple::mips:
11274   case llvm::Triple::mipsel:
11275     if (Triple.getOS() == llvm::Triple::NaCl)
11276       return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
11277     return SetCGInfo(new MIPSTargetCodeGenInfo(Types, true));
11278 
11279   case llvm::Triple::mips64:
11280   case llvm::Triple::mips64el:
11281     return SetCGInfo(new MIPSTargetCodeGenInfo(Types, false));
11282 
11283   case llvm::Triple::avr:
11284     return SetCGInfo(new AVRTargetCodeGenInfo(Types));
11285 
11286   case llvm::Triple::aarch64:
11287   case llvm::Triple::aarch64_32:
11288   case llvm::Triple::aarch64_be: {
11289     AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS;
11290     if (getTarget().getABI() == "darwinpcs")
11291       Kind = AArch64ABIInfo::DarwinPCS;
11292     else if (Triple.isOSWindows())
11293       return SetCGInfo(
11294           new WindowsAArch64TargetCodeGenInfo(Types, AArch64ABIInfo::Win64));
11295 
11296     return SetCGInfo(new AArch64TargetCodeGenInfo(Types, Kind));
11297   }
11298 
11299   case llvm::Triple::wasm32:
11300   case llvm::Triple::wasm64: {
11301     WebAssemblyABIInfo::ABIKind Kind = WebAssemblyABIInfo::MVP;
11302     if (getTarget().getABI() == "experimental-mv")
11303       Kind = WebAssemblyABIInfo::ExperimentalMV;
11304     return SetCGInfo(new WebAssemblyTargetCodeGenInfo(Types, Kind));
11305   }
11306 
11307   case llvm::Triple::arm:
11308   case llvm::Triple::armeb:
11309   case llvm::Triple::thumb:
11310   case llvm::Triple::thumbeb: {
11311     if (Triple.getOS() == llvm::Triple::Win32) {
11312       return SetCGInfo(
11313           new WindowsARMTargetCodeGenInfo(Types, ARMABIInfo::AAPCS_VFP));
11314     }
11315 
11316     ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
11317     StringRef ABIStr = getTarget().getABI();
11318     if (ABIStr == "apcs-gnu")
11319       Kind = ARMABIInfo::APCS;
11320     else if (ABIStr == "aapcs16")
11321       Kind = ARMABIInfo::AAPCS16_VFP;
11322     else if (CodeGenOpts.FloatABI == "hard" ||
11323              (CodeGenOpts.FloatABI != "soft" &&
11324               (Triple.getEnvironment() == llvm::Triple::GNUEABIHF ||
11325                Triple.getEnvironment() == llvm::Triple::MuslEABIHF ||
11326                Triple.getEnvironment() == llvm::Triple::EABIHF)))
11327       Kind = ARMABIInfo::AAPCS_VFP;
11328 
11329     return SetCGInfo(new ARMTargetCodeGenInfo(Types, Kind));
11330   }
11331 
11332   case llvm::Triple::ppc: {
11333     if (Triple.isOSAIX())
11334       return SetCGInfo(new AIXTargetCodeGenInfo(Types, /*Is64Bit*/ false));
11335 
11336     bool IsSoftFloat =
11337         CodeGenOpts.FloatABI == "soft" || getTarget().hasFeature("spe");
11338     bool RetSmallStructInRegABI =
11339         PPC32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
11340     return SetCGInfo(
11341         new PPC32TargetCodeGenInfo(Types, IsSoftFloat, RetSmallStructInRegABI));
11342   }
11343   case llvm::Triple::ppcle: {
11344     bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
11345     bool RetSmallStructInRegABI =
11346         PPC32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
11347     return SetCGInfo(
11348         new PPC32TargetCodeGenInfo(Types, IsSoftFloat, RetSmallStructInRegABI));
11349   }
11350   case llvm::Triple::ppc64:
11351     if (Triple.isOSAIX())
11352       return SetCGInfo(new AIXTargetCodeGenInfo(Types, /*Is64Bit*/ true));
11353 
11354     if (Triple.isOSBinFormatELF()) {
11355       PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1;
11356       if (getTarget().getABI() == "elfv2")
11357         Kind = PPC64_SVR4_ABIInfo::ELFv2;
11358       bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
11359 
11360       return SetCGInfo(
11361           new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, IsSoftFloat));
11362     }
11363     return SetCGInfo(new PPC64TargetCodeGenInfo(Types));
11364   case llvm::Triple::ppc64le: {
11365     assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
11366     PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2;
11367     if (getTarget().getABI() == "elfv1")
11368       Kind = PPC64_SVR4_ABIInfo::ELFv1;
11369     bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
11370 
11371     return SetCGInfo(
11372         new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, IsSoftFloat));
11373   }
11374 
11375   case llvm::Triple::nvptx:
11376   case llvm::Triple::nvptx64:
11377     return SetCGInfo(new NVPTXTargetCodeGenInfo(Types));
11378 
11379   case llvm::Triple::msp430:
11380     return SetCGInfo(new MSP430TargetCodeGenInfo(Types));
11381 
11382   case llvm::Triple::riscv32:
11383   case llvm::Triple::riscv64: {
11384     StringRef ABIStr = getTarget().getABI();
11385     unsigned XLen = getTarget().getPointerWidth(0);
11386     unsigned ABIFLen = 0;
11387     if (ABIStr.endswith("f"))
11388       ABIFLen = 32;
11389     else if (ABIStr.endswith("d"))
11390       ABIFLen = 64;
11391     return SetCGInfo(new RISCVTargetCodeGenInfo(Types, XLen, ABIFLen));
11392   }
11393 
11394   case llvm::Triple::systemz: {
11395     bool SoftFloat = CodeGenOpts.FloatABI == "soft";
11396     bool HasVector = !SoftFloat && getTarget().getABI() == "vector";
11397     return SetCGInfo(new SystemZTargetCodeGenInfo(Types, HasVector, SoftFloat));
11398   }
11399 
11400   case llvm::Triple::tce:
11401   case llvm::Triple::tcele:
11402     return SetCGInfo(new TCETargetCodeGenInfo(Types));
11403 
11404   case llvm::Triple::x86: {
11405     bool IsDarwinVectorABI = Triple.isOSDarwin();
11406     bool RetSmallStructInRegABI =
11407         X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
11408     bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
11409 
11410     if (Triple.getOS() == llvm::Triple::Win32) {
11411       return SetCGInfo(new WinX86_32TargetCodeGenInfo(
11412           Types, IsDarwinVectorABI, RetSmallStructInRegABI,
11413           IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters));
11414     } else {
11415       return SetCGInfo(new X86_32TargetCodeGenInfo(
11416           Types, IsDarwinVectorABI, RetSmallStructInRegABI,
11417           IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters,
11418           CodeGenOpts.FloatABI == "soft"));
11419     }
11420   }
11421 
11422   case llvm::Triple::x86_64: {
11423     StringRef ABI = getTarget().getABI();
11424     X86AVXABILevel AVXLevel =
11425         (ABI == "avx512"
11426              ? X86AVXABILevel::AVX512
11427              : ABI == "avx" ? X86AVXABILevel::AVX : X86AVXABILevel::None);
11428 
11429     switch (Triple.getOS()) {
11430     case llvm::Triple::Win32:
11431       return SetCGInfo(new WinX86_64TargetCodeGenInfo(Types, AVXLevel));
11432     default:
11433       return SetCGInfo(new X86_64TargetCodeGenInfo(Types, AVXLevel));
11434     }
11435   }
11436   case llvm::Triple::hexagon:
11437     return SetCGInfo(new HexagonTargetCodeGenInfo(Types));
11438   case llvm::Triple::lanai:
11439     return SetCGInfo(new LanaiTargetCodeGenInfo(Types));
11440   case llvm::Triple::r600:
11441     return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
11442   case llvm::Triple::amdgcn:
11443     return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
11444   case llvm::Triple::sparc:
11445     return SetCGInfo(new SparcV8TargetCodeGenInfo(Types));
11446   case llvm::Triple::sparcv9:
11447     return SetCGInfo(new SparcV9TargetCodeGenInfo(Types));
11448   case llvm::Triple::xcore:
11449     return SetCGInfo(new XCoreTargetCodeGenInfo(Types));
11450   case llvm::Triple::arc:
11451     return SetCGInfo(new ARCTargetCodeGenInfo(Types));
11452   case llvm::Triple::spir:
11453   case llvm::Triple::spir64:
11454     return SetCGInfo(new CommonSPIRTargetCodeGenInfo(Types));
11455   case llvm::Triple::spirv32:
11456   case llvm::Triple::spirv64:
11457     return SetCGInfo(new SPIRVTargetCodeGenInfo(Types));
11458   case llvm::Triple::ve:
11459     return SetCGInfo(new VETargetCodeGenInfo(Types));
11460   }
11461 }
11462 
11463 /// Create an OpenCL kernel for an enqueued block.
11464 ///
11465 /// The kernel has the same function type as the block invoke function. Its
11466 /// name is the name of the block invoke function postfixed with "_kernel".
11467 /// It simply calls the block invoke function then returns.
11468 llvm::Function *
11469 TargetCodeGenInfo::createEnqueuedBlockKernel(CodeGenFunction &CGF,
11470                                              llvm::Function *Invoke,
11471                                              llvm::Type *BlockTy) const {
11472   auto *InvokeFT = Invoke->getFunctionType();
11473   auto &C = CGF.getLLVMContext();
11474   std::string Name = Invoke->getName().str() + "_kernel";
11475   auto *FT = llvm::FunctionType::get(llvm::Type::getVoidTy(C),
11476                                      InvokeFT->params(), false);
11477   auto *F = llvm::Function::Create(FT, llvm::GlobalValue::ExternalLinkage, Name,
11478                                    &CGF.CGM.getModule());
11479   auto IP = CGF.Builder.saveIP();
11480   auto *BB = llvm::BasicBlock::Create(C, "entry", F);
11481   auto &Builder = CGF.Builder;
11482   Builder.SetInsertPoint(BB);
11483   llvm::SmallVector<llvm::Value *, 2> Args(llvm::make_pointer_range(F->args()));
11484   llvm::CallInst *call = Builder.CreateCall(Invoke, Args);
11485   call->setCallingConv(Invoke->getCallingConv());
11486   Builder.CreateRetVoid();
11487   Builder.restoreIP(IP);
11488   return F;
11489 }
11490 
11491 /// Create an OpenCL kernel for an enqueued block.
11492 ///
11493 /// The type of the first argument (the block literal) is the struct type
11494 /// of the block literal instead of a pointer type. The first argument
11495 /// (block literal) is passed directly by value to the kernel. The kernel
11496 /// allocates the same type of struct on stack and stores the block literal
11497 /// to it and passes its pointer to the block invoke function. The kernel
11498 /// has "enqueued-block" function attribute and kernel argument metadata.
11499 llvm::Function *AMDGPUTargetCodeGenInfo::createEnqueuedBlockKernel(
11500     CodeGenFunction &CGF, llvm::Function *Invoke,
11501     llvm::Type *BlockTy) const {
11502   auto &Builder = CGF.Builder;
11503   auto &C = CGF.getLLVMContext();
11504 
11505   auto *InvokeFT = Invoke->getFunctionType();
11506   llvm::SmallVector<llvm::Type *, 2> ArgTys;
11507   llvm::SmallVector<llvm::Metadata *, 8> AddressQuals;
11508   llvm::SmallVector<llvm::Metadata *, 8> AccessQuals;
11509   llvm::SmallVector<llvm::Metadata *, 8> ArgTypeNames;
11510   llvm::SmallVector<llvm::Metadata *, 8> ArgBaseTypeNames;
11511   llvm::SmallVector<llvm::Metadata *, 8> ArgTypeQuals;
11512   llvm::SmallVector<llvm::Metadata *, 8> ArgNames;
11513 
11514   ArgTys.push_back(BlockTy);
11515   ArgTypeNames.push_back(llvm::MDString::get(C, "__block_literal"));
11516   AddressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(0)));
11517   ArgBaseTypeNames.push_back(llvm::MDString::get(C, "__block_literal"));
11518   ArgTypeQuals.push_back(llvm::MDString::get(C, ""));
11519   AccessQuals.push_back(llvm::MDString::get(C, "none"));
11520   ArgNames.push_back(llvm::MDString::get(C, "block_literal"));
11521   for (unsigned I = 1, E = InvokeFT->getNumParams(); I < E; ++I) {
11522     ArgTys.push_back(InvokeFT->getParamType(I));
11523     ArgTypeNames.push_back(llvm::MDString::get(C, "void*"));
11524     AddressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(3)));
11525     AccessQuals.push_back(llvm::MDString::get(C, "none"));
11526     ArgBaseTypeNames.push_back(llvm::MDString::get(C, "void*"));
11527     ArgTypeQuals.push_back(llvm::MDString::get(C, ""));
11528     ArgNames.push_back(
11529         llvm::MDString::get(C, (Twine("local_arg") + Twine(I)).str()));
11530   }
11531   std::string Name = Invoke->getName().str() + "_kernel";
11532   auto *FT = llvm::FunctionType::get(llvm::Type::getVoidTy(C), ArgTys, false);
11533   auto *F = llvm::Function::Create(FT, llvm::GlobalValue::InternalLinkage, Name,
11534                                    &CGF.CGM.getModule());
11535   F->addFnAttr("enqueued-block");
11536   auto IP = CGF.Builder.saveIP();
11537   auto *BB = llvm::BasicBlock::Create(C, "entry", F);
11538   Builder.SetInsertPoint(BB);
11539   const auto BlockAlign = CGF.CGM.getDataLayout().getPrefTypeAlign(BlockTy);
11540   auto *BlockPtr = Builder.CreateAlloca(BlockTy, nullptr);
11541   BlockPtr->setAlignment(BlockAlign);
11542   Builder.CreateAlignedStore(F->arg_begin(), BlockPtr, BlockAlign);
11543   auto *Cast = Builder.CreatePointerCast(BlockPtr, InvokeFT->getParamType(0));
11544   llvm::SmallVector<llvm::Value *, 2> Args;
11545   Args.push_back(Cast);
11546   for (auto I = F->arg_begin() + 1, E = F->arg_end(); I != E; ++I)
11547     Args.push_back(I);
11548   llvm::CallInst *call = Builder.CreateCall(Invoke, Args);
11549   call->setCallingConv(Invoke->getCallingConv());
11550   Builder.CreateRetVoid();
11551   Builder.restoreIP(IP);
11552 
11553   F->setMetadata("kernel_arg_addr_space", llvm::MDNode::get(C, AddressQuals));
11554   F->setMetadata("kernel_arg_access_qual", llvm::MDNode::get(C, AccessQuals));
11555   F->setMetadata("kernel_arg_type", llvm::MDNode::get(C, ArgTypeNames));
11556   F->setMetadata("kernel_arg_base_type",
11557                  llvm::MDNode::get(C, ArgBaseTypeNames));
11558   F->setMetadata("kernel_arg_type_qual", llvm::MDNode::get(C, ArgTypeQuals));
11559   if (CGF.CGM.getCodeGenOpts().EmitOpenCLArgMetadata)
11560     F->setMetadata("kernel_arg_name", llvm::MDNode::get(C, ArgNames));
11561 
11562   return F;
11563 }
11564