xref: /freebsd/contrib/llvm-project/clang/lib/CodeGen/TargetInfo.cpp (revision ec4deee4e4f2aef1b97d9424f25d04e91fd7dc10)
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/CodeGen/CGFunctionInfo.h"
24 #include "clang/CodeGen/SwiftCallingConv.h"
25 #include "llvm/ADT/SmallBitVector.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/ADT/StringSwitch.h"
28 #include "llvm/ADT/Triple.h"
29 #include "llvm/ADT/Twine.h"
30 #include "llvm/IR/DataLayout.h"
31 #include "llvm/IR/Type.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include <algorithm> // std::sort
34 
35 using namespace clang;
36 using namespace CodeGen;
37 
38 // Helper for coercing an aggregate argument or return value into an integer
39 // array of the same size (including padding) and alignment.  This alternate
40 // coercion happens only for the RenderScript ABI and can be removed after
41 // runtimes that rely on it are no longer supported.
42 //
43 // RenderScript assumes that the size of the argument / return value in the IR
44 // is the same as the size of the corresponding qualified type. This helper
45 // coerces the aggregate type into an array of the same size (including
46 // padding).  This coercion is used in lieu of expansion of struct members or
47 // other canonical coercions that return a coerced-type of larger size.
48 //
49 // Ty          - The argument / return value type
50 // Context     - The associated ASTContext
51 // LLVMContext - The associated LLVMContext
52 static ABIArgInfo coerceToIntArray(QualType Ty,
53                                    ASTContext &Context,
54                                    llvm::LLVMContext &LLVMContext) {
55   // Alignment and Size are measured in bits.
56   const uint64_t Size = Context.getTypeSize(Ty);
57   const uint64_t Alignment = Context.getTypeAlign(Ty);
58   llvm::Type *IntType = llvm::Type::getIntNTy(LLVMContext, Alignment);
59   const uint64_t NumElements = (Size + Alignment - 1) / Alignment;
60   return ABIArgInfo::getDirect(llvm::ArrayType::get(IntType, NumElements));
61 }
62 
63 static void AssignToArrayRange(CodeGen::CGBuilderTy &Builder,
64                                llvm::Value *Array,
65                                llvm::Value *Value,
66                                unsigned FirstIndex,
67                                unsigned LastIndex) {
68   // Alternatively, we could emit this as a loop in the source.
69   for (unsigned I = FirstIndex; I <= LastIndex; ++I) {
70     llvm::Value *Cell =
71         Builder.CreateConstInBoundsGEP1_32(Builder.getInt8Ty(), Array, I);
72     Builder.CreateAlignedStore(Value, Cell, CharUnits::One());
73   }
74 }
75 
76 static bool isAggregateTypeForABI(QualType T) {
77   return !CodeGenFunction::hasScalarEvaluationKind(T) ||
78          T->isMemberFunctionPointerType();
79 }
80 
81 ABIArgInfo
82 ABIInfo::getNaturalAlignIndirect(QualType Ty, bool ByRef, bool Realign,
83                                  llvm::Type *Padding) const {
84   return ABIArgInfo::getIndirect(getContext().getTypeAlignInChars(Ty),
85                                  ByRef, Realign, Padding);
86 }
87 
88 ABIArgInfo
89 ABIInfo::getNaturalAlignIndirectInReg(QualType Ty, bool Realign) const {
90   return ABIArgInfo::getIndirectInReg(getContext().getTypeAlignInChars(Ty),
91                                       /*ByRef*/ false, Realign);
92 }
93 
94 Address ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
95                              QualType Ty) const {
96   return Address::invalid();
97 }
98 
99 ABIInfo::~ABIInfo() {}
100 
101 /// Does the given lowering require more than the given number of
102 /// registers when expanded?
103 ///
104 /// This is intended to be the basis of a reasonable basic implementation
105 /// of should{Pass,Return}IndirectlyForSwift.
106 ///
107 /// For most targets, a limit of four total registers is reasonable; this
108 /// limits the amount of code required in order to move around the value
109 /// in case it wasn't produced immediately prior to the call by the caller
110 /// (or wasn't produced in exactly the right registers) or isn't used
111 /// immediately within the callee.  But some targets may need to further
112 /// limit the register count due to an inability to support that many
113 /// return registers.
114 static bool occupiesMoreThan(CodeGenTypes &cgt,
115                              ArrayRef<llvm::Type*> scalarTypes,
116                              unsigned maxAllRegisters) {
117   unsigned intCount = 0, fpCount = 0;
118   for (llvm::Type *type : scalarTypes) {
119     if (type->isPointerTy()) {
120       intCount++;
121     } else if (auto intTy = dyn_cast<llvm::IntegerType>(type)) {
122       auto ptrWidth = cgt.getTarget().getPointerWidth(0);
123       intCount += (intTy->getBitWidth() + ptrWidth - 1) / ptrWidth;
124     } else {
125       assert(type->isVectorTy() || type->isFloatingPointTy());
126       fpCount++;
127     }
128   }
129 
130   return (intCount + fpCount > maxAllRegisters);
131 }
132 
133 bool SwiftABIInfo::isLegalVectorTypeForSwift(CharUnits vectorSize,
134                                              llvm::Type *eltTy,
135                                              unsigned numElts) const {
136   // The default implementation of this assumes that the target guarantees
137   // 128-bit SIMD support but nothing more.
138   return (vectorSize.getQuantity() > 8 && vectorSize.getQuantity() <= 16);
139 }
140 
141 static CGCXXABI::RecordArgABI getRecordArgABI(const RecordType *RT,
142                                               CGCXXABI &CXXABI) {
143   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
144   if (!RD) {
145     if (!RT->getDecl()->canPassInRegisters())
146       return CGCXXABI::RAA_Indirect;
147     return CGCXXABI::RAA_Default;
148   }
149   return CXXABI.getRecordArgABI(RD);
150 }
151 
152 static CGCXXABI::RecordArgABI getRecordArgABI(QualType T,
153                                               CGCXXABI &CXXABI) {
154   const RecordType *RT = T->getAs<RecordType>();
155   if (!RT)
156     return CGCXXABI::RAA_Default;
157   return getRecordArgABI(RT, CXXABI);
158 }
159 
160 static bool classifyReturnType(const CGCXXABI &CXXABI, CGFunctionInfo &FI,
161                                const ABIInfo &Info) {
162   QualType Ty = FI.getReturnType();
163 
164   if (const auto *RT = Ty->getAs<RecordType>())
165     if (!isa<CXXRecordDecl>(RT->getDecl()) &&
166         !RT->getDecl()->canPassInRegisters()) {
167       FI.getReturnInfo() = Info.getNaturalAlignIndirect(Ty);
168       return true;
169     }
170 
171   return CXXABI.classifyReturnType(FI);
172 }
173 
174 /// Pass transparent unions as if they were the type of the first element. Sema
175 /// should ensure that all elements of the union have the same "machine type".
176 static QualType useFirstFieldIfTransparentUnion(QualType Ty) {
177   if (const RecordType *UT = Ty->getAsUnionType()) {
178     const RecordDecl *UD = UT->getDecl();
179     if (UD->hasAttr<TransparentUnionAttr>()) {
180       assert(!UD->field_empty() && "sema created an empty transparent union");
181       return UD->field_begin()->getType();
182     }
183   }
184   return Ty;
185 }
186 
187 CGCXXABI &ABIInfo::getCXXABI() const {
188   return CGT.getCXXABI();
189 }
190 
191 ASTContext &ABIInfo::getContext() const {
192   return CGT.getContext();
193 }
194 
195 llvm::LLVMContext &ABIInfo::getVMContext() const {
196   return CGT.getLLVMContext();
197 }
198 
199 const llvm::DataLayout &ABIInfo::getDataLayout() const {
200   return CGT.getDataLayout();
201 }
202 
203 const TargetInfo &ABIInfo::getTarget() const {
204   return CGT.getTarget();
205 }
206 
207 const CodeGenOptions &ABIInfo::getCodeGenOpts() const {
208   return CGT.getCodeGenOpts();
209 }
210 
211 bool ABIInfo::isAndroid() const { return getTarget().getTriple().isAndroid(); }
212 
213 bool ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
214   return false;
215 }
216 
217 bool ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
218                                                 uint64_t Members) const {
219   return false;
220 }
221 
222 LLVM_DUMP_METHOD void ABIArgInfo::dump() const {
223   raw_ostream &OS = llvm::errs();
224   OS << "(ABIArgInfo Kind=";
225   switch (TheKind) {
226   case Direct:
227     OS << "Direct Type=";
228     if (llvm::Type *Ty = getCoerceToType())
229       Ty->print(OS);
230     else
231       OS << "null";
232     break;
233   case Extend:
234     OS << "Extend";
235     break;
236   case Ignore:
237     OS << "Ignore";
238     break;
239   case InAlloca:
240     OS << "InAlloca Offset=" << getInAllocaFieldIndex();
241     break;
242   case Indirect:
243     OS << "Indirect Align=" << getIndirectAlign().getQuantity()
244        << " ByVal=" << getIndirectByVal()
245        << " Realign=" << getIndirectRealign();
246     break;
247   case Expand:
248     OS << "Expand";
249     break;
250   case CoerceAndExpand:
251     OS << "CoerceAndExpand Type=";
252     getCoerceAndExpandType()->print(OS);
253     break;
254   }
255   OS << ")\n";
256 }
257 
258 // Dynamically round a pointer up to a multiple of the given alignment.
259 static llvm::Value *emitRoundPointerUpToAlignment(CodeGenFunction &CGF,
260                                                   llvm::Value *Ptr,
261                                                   CharUnits Align) {
262   llvm::Value *PtrAsInt = Ptr;
263   // OverflowArgArea = (OverflowArgArea + Align - 1) & -Align;
264   PtrAsInt = CGF.Builder.CreatePtrToInt(PtrAsInt, CGF.IntPtrTy);
265   PtrAsInt = CGF.Builder.CreateAdd(PtrAsInt,
266         llvm::ConstantInt::get(CGF.IntPtrTy, Align.getQuantity() - 1));
267   PtrAsInt = CGF.Builder.CreateAnd(PtrAsInt,
268            llvm::ConstantInt::get(CGF.IntPtrTy, -Align.getQuantity()));
269   PtrAsInt = CGF.Builder.CreateIntToPtr(PtrAsInt,
270                                         Ptr->getType(),
271                                         Ptr->getName() + ".aligned");
272   return PtrAsInt;
273 }
274 
275 /// Emit va_arg for a platform using the common void* representation,
276 /// where arguments are simply emitted in an array of slots on the stack.
277 ///
278 /// This version implements the core direct-value passing rules.
279 ///
280 /// \param SlotSize - The size and alignment of a stack slot.
281 ///   Each argument will be allocated to a multiple of this number of
282 ///   slots, and all the slots will be aligned to this value.
283 /// \param AllowHigherAlign - The slot alignment is not a cap;
284 ///   an argument type with an alignment greater than the slot size
285 ///   will be emitted on a higher-alignment address, potentially
286 ///   leaving one or more empty slots behind as padding.  If this
287 ///   is false, the returned address might be less-aligned than
288 ///   DirectAlign.
289 static Address emitVoidPtrDirectVAArg(CodeGenFunction &CGF,
290                                       Address VAListAddr,
291                                       llvm::Type *DirectTy,
292                                       CharUnits DirectSize,
293                                       CharUnits DirectAlign,
294                                       CharUnits SlotSize,
295                                       bool AllowHigherAlign) {
296   // Cast the element type to i8* if necessary.  Some platforms define
297   // va_list as a struct containing an i8* instead of just an i8*.
298   if (VAListAddr.getElementType() != CGF.Int8PtrTy)
299     VAListAddr = CGF.Builder.CreateElementBitCast(VAListAddr, CGF.Int8PtrTy);
300 
301   llvm::Value *Ptr = CGF.Builder.CreateLoad(VAListAddr, "argp.cur");
302 
303   // If the CC aligns values higher than the slot size, do so if needed.
304   Address Addr = Address::invalid();
305   if (AllowHigherAlign && DirectAlign > SlotSize) {
306     Addr = Address(emitRoundPointerUpToAlignment(CGF, Ptr, DirectAlign),
307                                                  DirectAlign);
308   } else {
309     Addr = Address(Ptr, SlotSize);
310   }
311 
312   // Advance the pointer past the argument, then store that back.
313   CharUnits FullDirectSize = DirectSize.alignTo(SlotSize);
314   Address NextPtr =
315       CGF.Builder.CreateConstInBoundsByteGEP(Addr, FullDirectSize, "argp.next");
316   CGF.Builder.CreateStore(NextPtr.getPointer(), VAListAddr);
317 
318   // If the argument is smaller than a slot, and this is a big-endian
319   // target, the argument will be right-adjusted in its slot.
320   if (DirectSize < SlotSize && CGF.CGM.getDataLayout().isBigEndian() &&
321       !DirectTy->isStructTy()) {
322     Addr = CGF.Builder.CreateConstInBoundsByteGEP(Addr, SlotSize - DirectSize);
323   }
324 
325   Addr = CGF.Builder.CreateElementBitCast(Addr, DirectTy);
326   return Addr;
327 }
328 
329 /// Emit va_arg for a platform using the common void* representation,
330 /// where arguments are simply emitted in an array of slots on the stack.
331 ///
332 /// \param IsIndirect - Values of this type are passed indirectly.
333 /// \param ValueInfo - The size and alignment of this type, generally
334 ///   computed with getContext().getTypeInfoInChars(ValueTy).
335 /// \param SlotSizeAndAlign - The size and alignment of a stack slot.
336 ///   Each argument will be allocated to a multiple of this number of
337 ///   slots, and all the slots will be aligned to this value.
338 /// \param AllowHigherAlign - The slot alignment is not a cap;
339 ///   an argument type with an alignment greater than the slot size
340 ///   will be emitted on a higher-alignment address, potentially
341 ///   leaving one or more empty slots behind as padding.
342 static Address emitVoidPtrVAArg(CodeGenFunction &CGF, Address VAListAddr,
343                                 QualType ValueTy, bool IsIndirect,
344                                 std::pair<CharUnits, CharUnits> ValueInfo,
345                                 CharUnits SlotSizeAndAlign,
346                                 bool AllowHigherAlign) {
347   // The size and alignment of the value that was passed directly.
348   CharUnits DirectSize, DirectAlign;
349   if (IsIndirect) {
350     DirectSize = CGF.getPointerSize();
351     DirectAlign = CGF.getPointerAlign();
352   } else {
353     DirectSize = ValueInfo.first;
354     DirectAlign = ValueInfo.second;
355   }
356 
357   // Cast the address we've calculated to the right type.
358   llvm::Type *DirectTy = CGF.ConvertTypeForMem(ValueTy);
359   if (IsIndirect)
360     DirectTy = DirectTy->getPointerTo(0);
361 
362   Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, DirectTy,
363                                         DirectSize, DirectAlign,
364                                         SlotSizeAndAlign,
365                                         AllowHigherAlign);
366 
367   if (IsIndirect) {
368     Addr = Address(CGF.Builder.CreateLoad(Addr), ValueInfo.second);
369   }
370 
371   return Addr;
372 
373 }
374 
375 static Address emitMergePHI(CodeGenFunction &CGF,
376                             Address Addr1, llvm::BasicBlock *Block1,
377                             Address Addr2, llvm::BasicBlock *Block2,
378                             const llvm::Twine &Name = "") {
379   assert(Addr1.getType() == Addr2.getType());
380   llvm::PHINode *PHI = CGF.Builder.CreatePHI(Addr1.getType(), 2, Name);
381   PHI->addIncoming(Addr1.getPointer(), Block1);
382   PHI->addIncoming(Addr2.getPointer(), Block2);
383   CharUnits Align = std::min(Addr1.getAlignment(), Addr2.getAlignment());
384   return Address(PHI, Align);
385 }
386 
387 TargetCodeGenInfo::~TargetCodeGenInfo() { delete Info; }
388 
389 // If someone can figure out a general rule for this, that would be great.
390 // It's probably just doomed to be platform-dependent, though.
391 unsigned TargetCodeGenInfo::getSizeOfUnwindException() const {
392   // Verified for:
393   //   x86-64     FreeBSD, Linux, Darwin
394   //   x86-32     FreeBSD, Linux, Darwin
395   //   PowerPC    Linux, Darwin
396   //   ARM        Darwin (*not* EABI)
397   //   AArch64    Linux
398   return 32;
399 }
400 
401 bool TargetCodeGenInfo::isNoProtoCallVariadic(const CallArgList &args,
402                                      const FunctionNoProtoType *fnType) const {
403   // The following conventions are known to require this to be false:
404   //   x86_stdcall
405   //   MIPS
406   // For everything else, we just prefer false unless we opt out.
407   return false;
408 }
409 
410 void
411 TargetCodeGenInfo::getDependentLibraryOption(llvm::StringRef Lib,
412                                              llvm::SmallString<24> &Opt) const {
413   // This assumes the user is passing a library name like "rt" instead of a
414   // filename like "librt.a/so", and that they don't care whether it's static or
415   // dynamic.
416   Opt = "-l";
417   Opt += Lib;
418 }
419 
420 unsigned TargetCodeGenInfo::getOpenCLKernelCallingConv() const {
421   // OpenCL kernels are called via an explicit runtime API with arguments
422   // set with clSetKernelArg(), not as normal sub-functions.
423   // Return SPIR_KERNEL by default as the kernel calling convention to
424   // ensure the fingerprint is fixed such way that each OpenCL argument
425   // gets one matching argument in the produced kernel function argument
426   // list to enable feasible implementation of clSetKernelArg() with
427   // aggregates etc. In case we would use the default C calling conv here,
428   // clSetKernelArg() might break depending on the target-specific
429   // conventions; different targets might split structs passed as values
430   // to multiple function arguments etc.
431   return llvm::CallingConv::SPIR_KERNEL;
432 }
433 
434 llvm::Constant *TargetCodeGenInfo::getNullPointer(const CodeGen::CodeGenModule &CGM,
435     llvm::PointerType *T, QualType QT) const {
436   return llvm::ConstantPointerNull::get(T);
437 }
438 
439 LangAS TargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM,
440                                                    const VarDecl *D) const {
441   assert(!CGM.getLangOpts().OpenCL &&
442          !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) &&
443          "Address space agnostic languages only");
444   return D ? D->getType().getAddressSpace() : LangAS::Default;
445 }
446 
447 llvm::Value *TargetCodeGenInfo::performAddrSpaceCast(
448     CodeGen::CodeGenFunction &CGF, llvm::Value *Src, LangAS SrcAddr,
449     LangAS DestAddr, llvm::Type *DestTy, bool isNonNull) const {
450   // Since target may map different address spaces in AST to the same address
451   // space, an address space conversion may end up as a bitcast.
452   if (auto *C = dyn_cast<llvm::Constant>(Src))
453     return performAddrSpaceCast(CGF.CGM, C, SrcAddr, DestAddr, DestTy);
454   // Try to preserve the source's name to make IR more readable.
455   return CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
456       Src, DestTy, Src->hasName() ? Src->getName() + ".ascast" : "");
457 }
458 
459 llvm::Constant *
460 TargetCodeGenInfo::performAddrSpaceCast(CodeGenModule &CGM, llvm::Constant *Src,
461                                         LangAS SrcAddr, LangAS DestAddr,
462                                         llvm::Type *DestTy) const {
463   // Since target may map different address spaces in AST to the same address
464   // space, an address space conversion may end up as a bitcast.
465   return llvm::ConstantExpr::getPointerCast(Src, DestTy);
466 }
467 
468 llvm::SyncScope::ID
469 TargetCodeGenInfo::getLLVMSyncScopeID(const LangOptions &LangOpts,
470                                       SyncScope Scope,
471                                       llvm::AtomicOrdering Ordering,
472                                       llvm::LLVMContext &Ctx) const {
473   return Ctx.getOrInsertSyncScopeID(""); /* default sync scope */
474 }
475 
476 static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays);
477 
478 /// isEmptyField - Return true iff a the field is "empty", that is it
479 /// is an unnamed bit-field or an (array of) empty record(s).
480 static bool isEmptyField(ASTContext &Context, const FieldDecl *FD,
481                          bool AllowArrays) {
482   if (FD->isUnnamedBitfield())
483     return true;
484 
485   QualType FT = FD->getType();
486 
487   // Constant arrays of empty records count as empty, strip them off.
488   // Constant arrays of zero length always count as empty.
489   if (AllowArrays)
490     while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
491       if (AT->getSize() == 0)
492         return true;
493       FT = AT->getElementType();
494     }
495 
496   const RecordType *RT = FT->getAs<RecordType>();
497   if (!RT)
498     return false;
499 
500   // C++ record fields are never empty, at least in the Itanium ABI.
501   //
502   // FIXME: We should use a predicate for whether this behavior is true in the
503   // current ABI.
504   if (isa<CXXRecordDecl>(RT->getDecl()))
505     return false;
506 
507   return isEmptyRecord(Context, FT, AllowArrays);
508 }
509 
510 /// isEmptyRecord - Return true iff a structure contains only empty
511 /// fields. Note that a structure with a flexible array member is not
512 /// considered empty.
513 static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) {
514   const RecordType *RT = T->getAs<RecordType>();
515   if (!RT)
516     return false;
517   const RecordDecl *RD = RT->getDecl();
518   if (RD->hasFlexibleArrayMember())
519     return false;
520 
521   // If this is a C++ record, check the bases first.
522   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
523     for (const auto &I : CXXRD->bases())
524       if (!isEmptyRecord(Context, I.getType(), true))
525         return false;
526 
527   for (const auto *I : RD->fields())
528     if (!isEmptyField(Context, I, AllowArrays))
529       return false;
530   return true;
531 }
532 
533 /// isSingleElementStruct - Determine if a structure is a "single
534 /// element struct", i.e. it has exactly one non-empty field or
535 /// exactly one field which is itself a single element
536 /// struct. Structures with flexible array members are never
537 /// considered single element structs.
538 ///
539 /// \return The field declaration for the single non-empty field, if
540 /// it exists.
541 static const Type *isSingleElementStruct(QualType T, ASTContext &Context) {
542   const RecordType *RT = T->getAs<RecordType>();
543   if (!RT)
544     return nullptr;
545 
546   const RecordDecl *RD = RT->getDecl();
547   if (RD->hasFlexibleArrayMember())
548     return nullptr;
549 
550   const Type *Found = nullptr;
551 
552   // If this is a C++ record, check the bases first.
553   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
554     for (const auto &I : CXXRD->bases()) {
555       // Ignore empty records.
556       if (isEmptyRecord(Context, I.getType(), true))
557         continue;
558 
559       // If we already found an element then this isn't a single-element struct.
560       if (Found)
561         return nullptr;
562 
563       // If this is non-empty and not a single element struct, the composite
564       // cannot be a single element struct.
565       Found = isSingleElementStruct(I.getType(), Context);
566       if (!Found)
567         return nullptr;
568     }
569   }
570 
571   // Check for single element.
572   for (const auto *FD : RD->fields()) {
573     QualType FT = FD->getType();
574 
575     // Ignore empty fields.
576     if (isEmptyField(Context, FD, true))
577       continue;
578 
579     // If we already found an element then this isn't a single-element
580     // struct.
581     if (Found)
582       return nullptr;
583 
584     // Treat single element arrays as the element.
585     while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
586       if (AT->getSize().getZExtValue() != 1)
587         break;
588       FT = AT->getElementType();
589     }
590 
591     if (!isAggregateTypeForABI(FT)) {
592       Found = FT.getTypePtr();
593     } else {
594       Found = isSingleElementStruct(FT, Context);
595       if (!Found)
596         return nullptr;
597     }
598   }
599 
600   // We don't consider a struct a single-element struct if it has
601   // padding beyond the element type.
602   if (Found && Context.getTypeSize(Found) != Context.getTypeSize(T))
603     return nullptr;
604 
605   return Found;
606 }
607 
608 namespace {
609 Address EmitVAArgInstr(CodeGenFunction &CGF, Address VAListAddr, QualType Ty,
610                        const ABIArgInfo &AI) {
611   // This default implementation defers to the llvm backend's va_arg
612   // instruction. It can handle only passing arguments directly
613   // (typically only handled in the backend for primitive types), or
614   // aggregates passed indirectly by pointer (NOTE: if the "byval"
615   // flag has ABI impact in the callee, this implementation cannot
616   // work.)
617 
618   // Only a few cases are covered here at the moment -- those needed
619   // by the default abi.
620   llvm::Value *Val;
621 
622   if (AI.isIndirect()) {
623     assert(!AI.getPaddingType() &&
624            "Unexpected PaddingType seen in arginfo in generic VAArg emitter!");
625     assert(
626         !AI.getIndirectRealign() &&
627         "Unexpected IndirectRealign seen in arginfo in generic VAArg emitter!");
628 
629     auto TyInfo = CGF.getContext().getTypeInfoInChars(Ty);
630     CharUnits TyAlignForABI = TyInfo.second;
631 
632     llvm::Type *BaseTy =
633         llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
634     llvm::Value *Addr =
635         CGF.Builder.CreateVAArg(VAListAddr.getPointer(), BaseTy);
636     return Address(Addr, TyAlignForABI);
637   } else {
638     assert((AI.isDirect() || AI.isExtend()) &&
639            "Unexpected ArgInfo Kind in generic VAArg emitter!");
640 
641     assert(!AI.getInReg() &&
642            "Unexpected InReg seen in arginfo in generic VAArg emitter!");
643     assert(!AI.getPaddingType() &&
644            "Unexpected PaddingType seen in arginfo in generic VAArg emitter!");
645     assert(!AI.getDirectOffset() &&
646            "Unexpected DirectOffset seen in arginfo in generic VAArg emitter!");
647     assert(!AI.getCoerceToType() &&
648            "Unexpected CoerceToType seen in arginfo in generic VAArg emitter!");
649 
650     Address Temp = CGF.CreateMemTemp(Ty, "varet");
651     Val = CGF.Builder.CreateVAArg(VAListAddr.getPointer(), CGF.ConvertType(Ty));
652     CGF.Builder.CreateStore(Val, Temp);
653     return Temp;
654   }
655 }
656 
657 /// DefaultABIInfo - The default implementation for ABI specific
658 /// details. This implementation provides information which results in
659 /// self-consistent and sensible LLVM IR generation, but does not
660 /// conform to any particular ABI.
661 class DefaultABIInfo : public ABIInfo {
662 public:
663   DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
664 
665   ABIArgInfo classifyReturnType(QualType RetTy) const;
666   ABIArgInfo classifyArgumentType(QualType RetTy) const;
667 
668   void computeInfo(CGFunctionInfo &FI) const override {
669     if (!getCXXABI().classifyReturnType(FI))
670       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
671     for (auto &I : FI.arguments())
672       I.info = classifyArgumentType(I.type);
673   }
674 
675   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
676                     QualType Ty) const override {
677     return EmitVAArgInstr(CGF, VAListAddr, Ty, classifyArgumentType(Ty));
678   }
679 };
680 
681 class DefaultTargetCodeGenInfo : public TargetCodeGenInfo {
682 public:
683   DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
684     : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
685 };
686 
687 ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const {
688   Ty = useFirstFieldIfTransparentUnion(Ty);
689 
690   if (isAggregateTypeForABI(Ty)) {
691     // Records with non-trivial destructors/copy-constructors should not be
692     // passed by value.
693     if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
694       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
695 
696     return getNaturalAlignIndirect(Ty);
697   }
698 
699   // Treat an enum type as its underlying type.
700   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
701     Ty = EnumTy->getDecl()->getIntegerType();
702 
703   return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty)
704                                         : ABIArgInfo::getDirect());
705 }
706 
707 ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const {
708   if (RetTy->isVoidType())
709     return ABIArgInfo::getIgnore();
710 
711   if (isAggregateTypeForABI(RetTy))
712     return getNaturalAlignIndirect(RetTy);
713 
714   // Treat an enum type as its underlying type.
715   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
716     RetTy = EnumTy->getDecl()->getIntegerType();
717 
718   return (RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy)
719                                            : ABIArgInfo::getDirect());
720 }
721 
722 //===----------------------------------------------------------------------===//
723 // WebAssembly ABI Implementation
724 //
725 // This is a very simple ABI that relies a lot on DefaultABIInfo.
726 //===----------------------------------------------------------------------===//
727 
728 class WebAssemblyABIInfo final : public SwiftABIInfo {
729   DefaultABIInfo defaultInfo;
730 
731 public:
732   explicit WebAssemblyABIInfo(CodeGen::CodeGenTypes &CGT)
733       : SwiftABIInfo(CGT), defaultInfo(CGT) {}
734 
735 private:
736   ABIArgInfo classifyReturnType(QualType RetTy) const;
737   ABIArgInfo classifyArgumentType(QualType Ty) const;
738 
739   // DefaultABIInfo's classifyReturnType and classifyArgumentType are
740   // non-virtual, but computeInfo and EmitVAArg are virtual, so we
741   // overload them.
742   void computeInfo(CGFunctionInfo &FI) const override {
743     if (!getCXXABI().classifyReturnType(FI))
744       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
745     for (auto &Arg : FI.arguments())
746       Arg.info = classifyArgumentType(Arg.type);
747   }
748 
749   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
750                     QualType Ty) const override;
751 
752   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
753                                     bool asReturnValue) const override {
754     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
755   }
756 
757   bool isSwiftErrorInRegister() const override {
758     return false;
759   }
760 };
761 
762 class WebAssemblyTargetCodeGenInfo final : public TargetCodeGenInfo {
763 public:
764   explicit WebAssemblyTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
765       : TargetCodeGenInfo(new WebAssemblyABIInfo(CGT)) {}
766 
767   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
768                            CodeGen::CodeGenModule &CGM) const override {
769     TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
770     if (const auto *FD = dyn_cast_or_null<FunctionDecl>(D)) {
771       if (const auto *Attr = FD->getAttr<WebAssemblyImportModuleAttr>()) {
772         llvm::Function *Fn = cast<llvm::Function>(GV);
773         llvm::AttrBuilder B;
774         B.addAttribute("wasm-import-module", Attr->getImportModule());
775         Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
776       }
777       if (const auto *Attr = FD->getAttr<WebAssemblyImportNameAttr>()) {
778         llvm::Function *Fn = cast<llvm::Function>(GV);
779         llvm::AttrBuilder B;
780         B.addAttribute("wasm-import-name", Attr->getImportName());
781         Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
782       }
783       if (const auto *Attr = FD->getAttr<WebAssemblyExportNameAttr>()) {
784         llvm::Function *Fn = cast<llvm::Function>(GV);
785         llvm::AttrBuilder B;
786         B.addAttribute("wasm-export-name", Attr->getExportName());
787         Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
788       }
789     }
790 
791     if (auto *FD = dyn_cast_or_null<FunctionDecl>(D)) {
792       llvm::Function *Fn = cast<llvm::Function>(GV);
793       if (!FD->doesThisDeclarationHaveABody() && !FD->hasPrototype())
794         Fn->addFnAttr("no-prototype");
795     }
796   }
797 };
798 
799 /// Classify argument of given type \p Ty.
800 ABIArgInfo WebAssemblyABIInfo::classifyArgumentType(QualType Ty) const {
801   Ty = useFirstFieldIfTransparentUnion(Ty);
802 
803   if (isAggregateTypeForABI(Ty)) {
804     // Records with non-trivial destructors/copy-constructors should not be
805     // passed by value.
806     if (auto RAA = getRecordArgABI(Ty, getCXXABI()))
807       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
808     // Ignore empty structs/unions.
809     if (isEmptyRecord(getContext(), Ty, true))
810       return ABIArgInfo::getIgnore();
811     // Lower single-element structs to just pass a regular value. TODO: We
812     // could do reasonable-size multiple-element structs too, using getExpand(),
813     // though watch out for things like bitfields.
814     if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
815       return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
816   }
817 
818   // Otherwise just do the default thing.
819   return defaultInfo.classifyArgumentType(Ty);
820 }
821 
822 ABIArgInfo WebAssemblyABIInfo::classifyReturnType(QualType RetTy) const {
823   if (isAggregateTypeForABI(RetTy)) {
824     // Records with non-trivial destructors/copy-constructors should not be
825     // returned by value.
826     if (!getRecordArgABI(RetTy, getCXXABI())) {
827       // Ignore empty structs/unions.
828       if (isEmptyRecord(getContext(), RetTy, true))
829         return ABIArgInfo::getIgnore();
830       // Lower single-element structs to just return a regular value. TODO: We
831       // could do reasonable-size multiple-element structs too, using
832       // ABIArgInfo::getDirect().
833       if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
834         return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
835     }
836   }
837 
838   // Otherwise just do the default thing.
839   return defaultInfo.classifyReturnType(RetTy);
840 }
841 
842 Address WebAssemblyABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
843                                       QualType Ty) const {
844   bool IsIndirect = isAggregateTypeForABI(Ty) &&
845                     !isEmptyRecord(getContext(), Ty, true) &&
846                     !isSingleElementStruct(Ty, getContext());
847   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
848                           getContext().getTypeInfoInChars(Ty),
849                           CharUnits::fromQuantity(4),
850                           /*AllowHigherAlign=*/true);
851 }
852 
853 //===----------------------------------------------------------------------===//
854 // le32/PNaCl bitcode ABI Implementation
855 //
856 // This is a simplified version of the x86_32 ABI.  Arguments and return values
857 // are always passed on the stack.
858 //===----------------------------------------------------------------------===//
859 
860 class PNaClABIInfo : public ABIInfo {
861  public:
862   PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
863 
864   ABIArgInfo classifyReturnType(QualType RetTy) const;
865   ABIArgInfo classifyArgumentType(QualType RetTy) const;
866 
867   void computeInfo(CGFunctionInfo &FI) const override;
868   Address EmitVAArg(CodeGenFunction &CGF,
869                     Address VAListAddr, QualType Ty) const override;
870 };
871 
872 class PNaClTargetCodeGenInfo : public TargetCodeGenInfo {
873  public:
874   PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
875     : TargetCodeGenInfo(new PNaClABIInfo(CGT)) {}
876 };
877 
878 void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const {
879   if (!getCXXABI().classifyReturnType(FI))
880     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
881 
882   for (auto &I : FI.arguments())
883     I.info = classifyArgumentType(I.type);
884 }
885 
886 Address PNaClABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
887                                 QualType Ty) const {
888   // The PNaCL ABI is a bit odd, in that varargs don't use normal
889   // function classification. Structs get passed directly for varargs
890   // functions, through a rewriting transform in
891   // pnacl-llvm/lib/Transforms/NaCl/ExpandVarArgs.cpp, which allows
892   // this target to actually support a va_arg instructions with an
893   // aggregate type, unlike other targets.
894   return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
895 }
896 
897 /// Classify argument of given type \p Ty.
898 ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const {
899   if (isAggregateTypeForABI(Ty)) {
900     if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
901       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
902     return getNaturalAlignIndirect(Ty);
903   } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
904     // Treat an enum type as its underlying type.
905     Ty = EnumTy->getDecl()->getIntegerType();
906   } else if (Ty->isFloatingType()) {
907     // Floating-point types don't go inreg.
908     return ABIArgInfo::getDirect();
909   }
910 
911   return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty)
912                                         : ABIArgInfo::getDirect());
913 }
914 
915 ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const {
916   if (RetTy->isVoidType())
917     return ABIArgInfo::getIgnore();
918 
919   // In the PNaCl ABI we always return records/structures on the stack.
920   if (isAggregateTypeForABI(RetTy))
921     return getNaturalAlignIndirect(RetTy);
922 
923   // Treat an enum type as its underlying type.
924   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
925     RetTy = EnumTy->getDecl()->getIntegerType();
926 
927   return (RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy)
928                                            : ABIArgInfo::getDirect());
929 }
930 
931 /// IsX86_MMXType - Return true if this is an MMX type.
932 bool IsX86_MMXType(llvm::Type *IRType) {
933   // Return true if the type is an MMX type <2 x i32>, <4 x i16>, or <8 x i8>.
934   return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 &&
935     cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() &&
936     IRType->getScalarSizeInBits() != 64;
937 }
938 
939 static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
940                                           StringRef Constraint,
941                                           llvm::Type* Ty) {
942   bool IsMMXCons = llvm::StringSwitch<bool>(Constraint)
943                      .Cases("y", "&y", "^Ym", true)
944                      .Default(false);
945   if (IsMMXCons && Ty->isVectorTy()) {
946     if (cast<llvm::VectorType>(Ty)->getBitWidth() != 64) {
947       // Invalid MMX constraint
948       return nullptr;
949     }
950 
951     return llvm::Type::getX86_MMXTy(CGF.getLLVMContext());
952   }
953 
954   // No operation needed
955   return Ty;
956 }
957 
958 /// Returns true if this type can be passed in SSE registers with the
959 /// X86_VectorCall calling convention. Shared between x86_32 and x86_64.
960 static bool isX86VectorTypeForVectorCall(ASTContext &Context, QualType Ty) {
961   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
962     if (BT->isFloatingPoint() && BT->getKind() != BuiltinType::Half) {
963       if (BT->getKind() == BuiltinType::LongDouble) {
964         if (&Context.getTargetInfo().getLongDoubleFormat() ==
965             &llvm::APFloat::x87DoubleExtended())
966           return false;
967       }
968       return true;
969     }
970   } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
971     // vectorcall can pass XMM, YMM, and ZMM vectors. We don't pass SSE1 MMX
972     // registers specially.
973     unsigned VecSize = Context.getTypeSize(VT);
974     if (VecSize == 128 || VecSize == 256 || VecSize == 512)
975       return true;
976   }
977   return false;
978 }
979 
980 /// Returns true if this aggregate is small enough to be passed in SSE registers
981 /// in the X86_VectorCall calling convention. Shared between x86_32 and x86_64.
982 static bool isX86VectorCallAggregateSmallEnough(uint64_t NumMembers) {
983   return NumMembers <= 4;
984 }
985 
986 /// Returns a Homogeneous Vector Aggregate ABIArgInfo, used in X86.
987 static ABIArgInfo getDirectX86Hva(llvm::Type* T = nullptr) {
988   auto AI = ABIArgInfo::getDirect(T);
989   AI.setInReg(true);
990   AI.setCanBeFlattened(false);
991   return AI;
992 }
993 
994 //===----------------------------------------------------------------------===//
995 // X86-32 ABI Implementation
996 //===----------------------------------------------------------------------===//
997 
998 /// Similar to llvm::CCState, but for Clang.
999 struct CCState {
1000   CCState(CGFunctionInfo &FI)
1001       : IsPreassigned(FI.arg_size()), CC(FI.getCallingConvention()) {}
1002 
1003   llvm::SmallBitVector IsPreassigned;
1004   unsigned CC = CallingConv::CC_C;
1005   unsigned FreeRegs = 0;
1006   unsigned FreeSSERegs = 0;
1007 };
1008 
1009 enum {
1010   // Vectorcall only allows the first 6 parameters to be passed in registers.
1011   VectorcallMaxParamNumAsReg = 6
1012 };
1013 
1014 /// X86_32ABIInfo - The X86-32 ABI information.
1015 class X86_32ABIInfo : public SwiftABIInfo {
1016   enum Class {
1017     Integer,
1018     Float
1019   };
1020 
1021   static const unsigned MinABIStackAlignInBytes = 4;
1022 
1023   bool IsDarwinVectorABI;
1024   bool IsRetSmallStructInRegABI;
1025   bool IsWin32StructABI;
1026   bool IsSoftFloatABI;
1027   bool IsMCUABI;
1028   unsigned DefaultNumRegisterParameters;
1029 
1030   static bool isRegisterSize(unsigned Size) {
1031     return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
1032   }
1033 
1034   bool isHomogeneousAggregateBaseType(QualType Ty) const override {
1035     // FIXME: Assumes vectorcall is in use.
1036     return isX86VectorTypeForVectorCall(getContext(), Ty);
1037   }
1038 
1039   bool isHomogeneousAggregateSmallEnough(const Type *Ty,
1040                                          uint64_t NumMembers) const override {
1041     // FIXME: Assumes vectorcall is in use.
1042     return isX86VectorCallAggregateSmallEnough(NumMembers);
1043   }
1044 
1045   bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context) const;
1046 
1047   /// getIndirectResult - Give a source type \arg Ty, return a suitable result
1048   /// such that the argument will be passed in memory.
1049   ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
1050 
1051   ABIArgInfo getIndirectReturnResult(QualType Ty, CCState &State) const;
1052 
1053   /// Return the alignment to use for the given type on the stack.
1054   unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const;
1055 
1056   Class classify(QualType Ty) const;
1057   ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const;
1058   ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
1059 
1060   /// Updates the number of available free registers, returns
1061   /// true if any registers were allocated.
1062   bool updateFreeRegs(QualType Ty, CCState &State) const;
1063 
1064   bool shouldAggregateUseDirect(QualType Ty, CCState &State, bool &InReg,
1065                                 bool &NeedsPadding) const;
1066   bool shouldPrimitiveUseInReg(QualType Ty, CCState &State) const;
1067 
1068   bool canExpandIndirectArgument(QualType Ty) const;
1069 
1070   /// Rewrite the function info so that all memory arguments use
1071   /// inalloca.
1072   void rewriteWithInAlloca(CGFunctionInfo &FI) const;
1073 
1074   void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
1075                            CharUnits &StackOffset, ABIArgInfo &Info,
1076                            QualType Type) const;
1077   void runVectorCallFirstPass(CGFunctionInfo &FI, CCState &State) const;
1078 
1079 public:
1080 
1081   void computeInfo(CGFunctionInfo &FI) const override;
1082   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
1083                     QualType Ty) const override;
1084 
1085   X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
1086                 bool RetSmallStructInRegABI, bool Win32StructABI,
1087                 unsigned NumRegisterParameters, bool SoftFloatABI)
1088     : SwiftABIInfo(CGT), IsDarwinVectorABI(DarwinVectorABI),
1089       IsRetSmallStructInRegABI(RetSmallStructInRegABI),
1090       IsWin32StructABI(Win32StructABI),
1091       IsSoftFloatABI(SoftFloatABI),
1092       IsMCUABI(CGT.getTarget().getTriple().isOSIAMCU()),
1093       DefaultNumRegisterParameters(NumRegisterParameters) {}
1094 
1095   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
1096                                     bool asReturnValue) const override {
1097     // LLVM's x86-32 lowering currently only assigns up to three
1098     // integer registers and three fp registers.  Oddly, it'll use up to
1099     // four vector registers for vectors, but those can overlap with the
1100     // scalar registers.
1101     return occupiesMoreThan(CGT, scalars, /*total*/ 3);
1102   }
1103 
1104   bool isSwiftErrorInRegister() const override {
1105     // x86-32 lowering does not support passing swifterror in a register.
1106     return false;
1107   }
1108 };
1109 
1110 class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
1111 public:
1112   X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
1113                           bool RetSmallStructInRegABI, bool Win32StructABI,
1114                           unsigned NumRegisterParameters, bool SoftFloatABI)
1115       : TargetCodeGenInfo(new X86_32ABIInfo(
1116             CGT, DarwinVectorABI, RetSmallStructInRegABI, Win32StructABI,
1117             NumRegisterParameters, SoftFloatABI)) {}
1118 
1119   static bool isStructReturnInRegABI(
1120       const llvm::Triple &Triple, const CodeGenOptions &Opts);
1121 
1122   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
1123                            CodeGen::CodeGenModule &CGM) const override;
1124 
1125   int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
1126     // Darwin uses different dwarf register numbers for EH.
1127     if (CGM.getTarget().getTriple().isOSDarwin()) return 5;
1128     return 4;
1129   }
1130 
1131   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
1132                                llvm::Value *Address) const override;
1133 
1134   llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
1135                                   StringRef Constraint,
1136                                   llvm::Type* Ty) const override {
1137     return X86AdjustInlineAsmType(CGF, Constraint, Ty);
1138   }
1139 
1140   void addReturnRegisterOutputs(CodeGenFunction &CGF, LValue ReturnValue,
1141                                 std::string &Constraints,
1142                                 std::vector<llvm::Type *> &ResultRegTypes,
1143                                 std::vector<llvm::Type *> &ResultTruncRegTypes,
1144                                 std::vector<LValue> &ResultRegDests,
1145                                 std::string &AsmString,
1146                                 unsigned NumOutputs) const override;
1147 
1148   llvm::Constant *
1149   getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
1150     unsigned Sig = (0xeb << 0) |  // jmp rel8
1151                    (0x06 << 8) |  //           .+0x08
1152                    ('v' << 16) |
1153                    ('2' << 24);
1154     return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
1155   }
1156 
1157   StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
1158     return "movl\t%ebp, %ebp"
1159            "\t\t// marker for objc_retainAutoreleaseReturnValue";
1160   }
1161 };
1162 
1163 }
1164 
1165 /// Rewrite input constraint references after adding some output constraints.
1166 /// In the case where there is one output and one input and we add one output,
1167 /// we need to replace all operand references greater than or equal to 1:
1168 ///     mov $0, $1
1169 ///     mov eax, $1
1170 /// The result will be:
1171 ///     mov $0, $2
1172 ///     mov eax, $2
1173 static void rewriteInputConstraintReferences(unsigned FirstIn,
1174                                              unsigned NumNewOuts,
1175                                              std::string &AsmString) {
1176   std::string Buf;
1177   llvm::raw_string_ostream OS(Buf);
1178   size_t Pos = 0;
1179   while (Pos < AsmString.size()) {
1180     size_t DollarStart = AsmString.find('$', Pos);
1181     if (DollarStart == std::string::npos)
1182       DollarStart = AsmString.size();
1183     size_t DollarEnd = AsmString.find_first_not_of('$', DollarStart);
1184     if (DollarEnd == std::string::npos)
1185       DollarEnd = AsmString.size();
1186     OS << StringRef(&AsmString[Pos], DollarEnd - Pos);
1187     Pos = DollarEnd;
1188     size_t NumDollars = DollarEnd - DollarStart;
1189     if (NumDollars % 2 != 0 && Pos < AsmString.size()) {
1190       // We have an operand reference.
1191       size_t DigitStart = Pos;
1192       if (AsmString[DigitStart] == '{') {
1193         OS << '{';
1194         ++DigitStart;
1195       }
1196       size_t DigitEnd = AsmString.find_first_not_of("0123456789", DigitStart);
1197       if (DigitEnd == std::string::npos)
1198         DigitEnd = AsmString.size();
1199       StringRef OperandStr(&AsmString[DigitStart], DigitEnd - DigitStart);
1200       unsigned OperandIndex;
1201       if (!OperandStr.getAsInteger(10, OperandIndex)) {
1202         if (OperandIndex >= FirstIn)
1203           OperandIndex += NumNewOuts;
1204         OS << OperandIndex;
1205       } else {
1206         OS << OperandStr;
1207       }
1208       Pos = DigitEnd;
1209     }
1210   }
1211   AsmString = std::move(OS.str());
1212 }
1213 
1214 /// Add output constraints for EAX:EDX because they are return registers.
1215 void X86_32TargetCodeGenInfo::addReturnRegisterOutputs(
1216     CodeGenFunction &CGF, LValue ReturnSlot, std::string &Constraints,
1217     std::vector<llvm::Type *> &ResultRegTypes,
1218     std::vector<llvm::Type *> &ResultTruncRegTypes,
1219     std::vector<LValue> &ResultRegDests, std::string &AsmString,
1220     unsigned NumOutputs) const {
1221   uint64_t RetWidth = CGF.getContext().getTypeSize(ReturnSlot.getType());
1222 
1223   // Use the EAX constraint if the width is 32 or smaller and EAX:EDX if it is
1224   // larger.
1225   if (!Constraints.empty())
1226     Constraints += ',';
1227   if (RetWidth <= 32) {
1228     Constraints += "={eax}";
1229     ResultRegTypes.push_back(CGF.Int32Ty);
1230   } else {
1231     // Use the 'A' constraint for EAX:EDX.
1232     Constraints += "=A";
1233     ResultRegTypes.push_back(CGF.Int64Ty);
1234   }
1235 
1236   // Truncate EAX or EAX:EDX to an integer of the appropriate size.
1237   llvm::Type *CoerceTy = llvm::IntegerType::get(CGF.getLLVMContext(), RetWidth);
1238   ResultTruncRegTypes.push_back(CoerceTy);
1239 
1240   // Coerce the integer by bitcasting the return slot pointer.
1241   ReturnSlot.setAddress(CGF.Builder.CreateBitCast(ReturnSlot.getAddress(CGF),
1242                                                   CoerceTy->getPointerTo()));
1243   ResultRegDests.push_back(ReturnSlot);
1244 
1245   rewriteInputConstraintReferences(NumOutputs, 1, AsmString);
1246 }
1247 
1248 /// shouldReturnTypeInRegister - Determine if the given type should be
1249 /// returned in a register (for the Darwin and MCU ABI).
1250 bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
1251                                                ASTContext &Context) const {
1252   uint64_t Size = Context.getTypeSize(Ty);
1253 
1254   // For i386, type must be register sized.
1255   // For the MCU ABI, it only needs to be <= 8-byte
1256   if ((IsMCUABI && Size > 64) || (!IsMCUABI && !isRegisterSize(Size)))
1257    return false;
1258 
1259   if (Ty->isVectorType()) {
1260     // 64- and 128- bit vectors inside structures are not returned in
1261     // registers.
1262     if (Size == 64 || Size == 128)
1263       return false;
1264 
1265     return true;
1266   }
1267 
1268   // If this is a builtin, pointer, enum, complex type, member pointer, or
1269   // member function pointer it is ok.
1270   if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() ||
1271       Ty->isAnyComplexType() || Ty->isEnumeralType() ||
1272       Ty->isBlockPointerType() || Ty->isMemberPointerType())
1273     return true;
1274 
1275   // Arrays are treated like records.
1276   if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
1277     return shouldReturnTypeInRegister(AT->getElementType(), Context);
1278 
1279   // Otherwise, it must be a record type.
1280   const RecordType *RT = Ty->getAs<RecordType>();
1281   if (!RT) return false;
1282 
1283   // FIXME: Traverse bases here too.
1284 
1285   // Structure types are passed in register if all fields would be
1286   // passed in a register.
1287   for (const auto *FD : RT->getDecl()->fields()) {
1288     // Empty fields are ignored.
1289     if (isEmptyField(Context, FD, true))
1290       continue;
1291 
1292     // Check fields recursively.
1293     if (!shouldReturnTypeInRegister(FD->getType(), Context))
1294       return false;
1295   }
1296   return true;
1297 }
1298 
1299 static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
1300   // Treat complex types as the element type.
1301   if (const ComplexType *CTy = Ty->getAs<ComplexType>())
1302     Ty = CTy->getElementType();
1303 
1304   // Check for a type which we know has a simple scalar argument-passing
1305   // convention without any padding.  (We're specifically looking for 32
1306   // and 64-bit integer and integer-equivalents, float, and double.)
1307   if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() &&
1308       !Ty->isEnumeralType() && !Ty->isBlockPointerType())
1309     return false;
1310 
1311   uint64_t Size = Context.getTypeSize(Ty);
1312   return Size == 32 || Size == 64;
1313 }
1314 
1315 static bool addFieldSizes(ASTContext &Context, const RecordDecl *RD,
1316                           uint64_t &Size) {
1317   for (const auto *FD : RD->fields()) {
1318     // Scalar arguments on the stack get 4 byte alignment on x86. If the
1319     // argument is smaller than 32-bits, expanding the struct will create
1320     // alignment padding.
1321     if (!is32Or64BitBasicType(FD->getType(), Context))
1322       return false;
1323 
1324     // FIXME: Reject bit-fields wholesale; there are two problems, we don't know
1325     // how to expand them yet, and the predicate for telling if a bitfield still
1326     // counts as "basic" is more complicated than what we were doing previously.
1327     if (FD->isBitField())
1328       return false;
1329 
1330     Size += Context.getTypeSize(FD->getType());
1331   }
1332   return true;
1333 }
1334 
1335 static bool addBaseAndFieldSizes(ASTContext &Context, const CXXRecordDecl *RD,
1336                                  uint64_t &Size) {
1337   // Don't do this if there are any non-empty bases.
1338   for (const CXXBaseSpecifier &Base : RD->bases()) {
1339     if (!addBaseAndFieldSizes(Context, Base.getType()->getAsCXXRecordDecl(),
1340                               Size))
1341       return false;
1342   }
1343   if (!addFieldSizes(Context, RD, Size))
1344     return false;
1345   return true;
1346 }
1347 
1348 /// Test whether an argument type which is to be passed indirectly (on the
1349 /// stack) would have the equivalent layout if it was expanded into separate
1350 /// arguments. If so, we prefer to do the latter to avoid inhibiting
1351 /// optimizations.
1352 bool X86_32ABIInfo::canExpandIndirectArgument(QualType Ty) const {
1353   // We can only expand structure types.
1354   const RecordType *RT = Ty->getAs<RecordType>();
1355   if (!RT)
1356     return false;
1357   const RecordDecl *RD = RT->getDecl();
1358   uint64_t Size = 0;
1359   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
1360     if (!IsWin32StructABI) {
1361       // On non-Windows, we have to conservatively match our old bitcode
1362       // prototypes in order to be ABI-compatible at the bitcode level.
1363       if (!CXXRD->isCLike())
1364         return false;
1365     } else {
1366       // Don't do this for dynamic classes.
1367       if (CXXRD->isDynamicClass())
1368         return false;
1369     }
1370     if (!addBaseAndFieldSizes(getContext(), CXXRD, Size))
1371       return false;
1372   } else {
1373     if (!addFieldSizes(getContext(), RD, Size))
1374       return false;
1375   }
1376 
1377   // We can do this if there was no alignment padding.
1378   return Size == getContext().getTypeSize(Ty);
1379 }
1380 
1381 ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(QualType RetTy, CCState &State) const {
1382   // If the return value is indirect, then the hidden argument is consuming one
1383   // integer register.
1384   if (State.FreeRegs) {
1385     --State.FreeRegs;
1386     if (!IsMCUABI)
1387       return getNaturalAlignIndirectInReg(RetTy);
1388   }
1389   return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
1390 }
1391 
1392 ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy,
1393                                              CCState &State) const {
1394   if (RetTy->isVoidType())
1395     return ABIArgInfo::getIgnore();
1396 
1397   const Type *Base = nullptr;
1398   uint64_t NumElts = 0;
1399   if ((State.CC == llvm::CallingConv::X86_VectorCall ||
1400        State.CC == llvm::CallingConv::X86_RegCall) &&
1401       isHomogeneousAggregate(RetTy, Base, NumElts)) {
1402     // The LLVM struct type for such an aggregate should lower properly.
1403     return ABIArgInfo::getDirect();
1404   }
1405 
1406   if (const VectorType *VT = RetTy->getAs<VectorType>()) {
1407     // On Darwin, some vectors are returned in registers.
1408     if (IsDarwinVectorABI) {
1409       uint64_t Size = getContext().getTypeSize(RetTy);
1410 
1411       // 128-bit vectors are a special case; they are returned in
1412       // registers and we need to make sure to pick a type the LLVM
1413       // backend will like.
1414       if (Size == 128)
1415         return ABIArgInfo::getDirect(llvm::VectorType::get(
1416                   llvm::Type::getInt64Ty(getVMContext()), 2));
1417 
1418       // Always return in register if it fits in a general purpose
1419       // register, or if it is 64 bits and has a single element.
1420       if ((Size == 8 || Size == 16 || Size == 32) ||
1421           (Size == 64 && VT->getNumElements() == 1))
1422         return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
1423                                                             Size));
1424 
1425       return getIndirectReturnResult(RetTy, State);
1426     }
1427 
1428     return ABIArgInfo::getDirect();
1429   }
1430 
1431   if (isAggregateTypeForABI(RetTy)) {
1432     if (const RecordType *RT = RetTy->getAs<RecordType>()) {
1433       // Structures with flexible arrays are always indirect.
1434       if (RT->getDecl()->hasFlexibleArrayMember())
1435         return getIndirectReturnResult(RetTy, State);
1436     }
1437 
1438     // If specified, structs and unions are always indirect.
1439     if (!IsRetSmallStructInRegABI && !RetTy->isAnyComplexType())
1440       return getIndirectReturnResult(RetTy, State);
1441 
1442     // Ignore empty structs/unions.
1443     if (isEmptyRecord(getContext(), RetTy, true))
1444       return ABIArgInfo::getIgnore();
1445 
1446     // Small structures which are register sized are generally returned
1447     // in a register.
1448     if (shouldReturnTypeInRegister(RetTy, getContext())) {
1449       uint64_t Size = getContext().getTypeSize(RetTy);
1450 
1451       // As a special-case, if the struct is a "single-element" struct, and
1452       // the field is of type "float" or "double", return it in a
1453       // floating-point register. (MSVC does not apply this special case.)
1454       // We apply a similar transformation for pointer types to improve the
1455       // quality of the generated IR.
1456       if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
1457         if ((!IsWin32StructABI && SeltTy->isRealFloatingType())
1458             || SeltTy->hasPointerRepresentation())
1459           return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
1460 
1461       // FIXME: We should be able to narrow this integer in cases with dead
1462       // padding.
1463       return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
1464     }
1465 
1466     return getIndirectReturnResult(RetTy, State);
1467   }
1468 
1469   // Treat an enum type as its underlying type.
1470   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
1471     RetTy = EnumTy->getDecl()->getIntegerType();
1472 
1473   return (RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy)
1474                                            : ABIArgInfo::getDirect());
1475 }
1476 
1477 static bool isSSEVectorType(ASTContext &Context, QualType Ty) {
1478   return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128;
1479 }
1480 
1481 static bool isRecordWithSSEVectorType(ASTContext &Context, QualType Ty) {
1482   const RecordType *RT = Ty->getAs<RecordType>();
1483   if (!RT)
1484     return 0;
1485   const RecordDecl *RD = RT->getDecl();
1486 
1487   // If this is a C++ record, check the bases first.
1488   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
1489     for (const auto &I : CXXRD->bases())
1490       if (!isRecordWithSSEVectorType(Context, I.getType()))
1491         return false;
1492 
1493   for (const auto *i : RD->fields()) {
1494     QualType FT = i->getType();
1495 
1496     if (isSSEVectorType(Context, FT))
1497       return true;
1498 
1499     if (isRecordWithSSEVectorType(Context, FT))
1500       return true;
1501   }
1502 
1503   return false;
1504 }
1505 
1506 unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
1507                                                  unsigned Align) const {
1508   // Otherwise, if the alignment is less than or equal to the minimum ABI
1509   // alignment, just use the default; the backend will handle this.
1510   if (Align <= MinABIStackAlignInBytes)
1511     return 0; // Use default alignment.
1512 
1513   // On non-Darwin, the stack type alignment is always 4.
1514   if (!IsDarwinVectorABI) {
1515     // Set explicit alignment, since we may need to realign the top.
1516     return MinABIStackAlignInBytes;
1517   }
1518 
1519   // Otherwise, if the type contains an SSE vector type, the alignment is 16.
1520   if (Align >= 16 && (isSSEVectorType(getContext(), Ty) ||
1521                       isRecordWithSSEVectorType(getContext(), Ty)))
1522     return 16;
1523 
1524   return MinABIStackAlignInBytes;
1525 }
1526 
1527 ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal,
1528                                             CCState &State) const {
1529   if (!ByVal) {
1530     if (State.FreeRegs) {
1531       --State.FreeRegs; // Non-byval indirects just use one pointer.
1532       if (!IsMCUABI)
1533         return getNaturalAlignIndirectInReg(Ty);
1534     }
1535     return getNaturalAlignIndirect(Ty, false);
1536   }
1537 
1538   // Compute the byval alignment.
1539   unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
1540   unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign);
1541   if (StackAlign == 0)
1542     return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true);
1543 
1544   // If the stack alignment is less than the type alignment, realign the
1545   // argument.
1546   bool Realign = TypeAlign > StackAlign;
1547   return ABIArgInfo::getIndirect(CharUnits::fromQuantity(StackAlign),
1548                                  /*ByVal=*/true, Realign);
1549 }
1550 
1551 X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const {
1552   const Type *T = isSingleElementStruct(Ty, getContext());
1553   if (!T)
1554     T = Ty.getTypePtr();
1555 
1556   if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
1557     BuiltinType::Kind K = BT->getKind();
1558     if (K == BuiltinType::Float || K == BuiltinType::Double)
1559       return Float;
1560   }
1561   return Integer;
1562 }
1563 
1564 bool X86_32ABIInfo::updateFreeRegs(QualType Ty, CCState &State) const {
1565   if (!IsSoftFloatABI) {
1566     Class C = classify(Ty);
1567     if (C == Float)
1568       return false;
1569   }
1570 
1571   unsigned Size = getContext().getTypeSize(Ty);
1572   unsigned SizeInRegs = (Size + 31) / 32;
1573 
1574   if (SizeInRegs == 0)
1575     return false;
1576 
1577   if (!IsMCUABI) {
1578     if (SizeInRegs > State.FreeRegs) {
1579       State.FreeRegs = 0;
1580       return false;
1581     }
1582   } else {
1583     // The MCU psABI allows passing parameters in-reg even if there are
1584     // earlier parameters that are passed on the stack. Also,
1585     // it does not allow passing >8-byte structs in-register,
1586     // even if there are 3 free registers available.
1587     if (SizeInRegs > State.FreeRegs || SizeInRegs > 2)
1588       return false;
1589   }
1590 
1591   State.FreeRegs -= SizeInRegs;
1592   return true;
1593 }
1594 
1595 bool X86_32ABIInfo::shouldAggregateUseDirect(QualType Ty, CCState &State,
1596                                              bool &InReg,
1597                                              bool &NeedsPadding) const {
1598   // On Windows, aggregates other than HFAs are never passed in registers, and
1599   // they do not consume register slots. Homogenous floating-point aggregates
1600   // (HFAs) have already been dealt with at this point.
1601   if (IsWin32StructABI && isAggregateTypeForABI(Ty))
1602     return false;
1603 
1604   NeedsPadding = false;
1605   InReg = !IsMCUABI;
1606 
1607   if (!updateFreeRegs(Ty, State))
1608     return false;
1609 
1610   if (IsMCUABI)
1611     return true;
1612 
1613   if (State.CC == llvm::CallingConv::X86_FastCall ||
1614       State.CC == llvm::CallingConv::X86_VectorCall ||
1615       State.CC == llvm::CallingConv::X86_RegCall) {
1616     if (getContext().getTypeSize(Ty) <= 32 && State.FreeRegs)
1617       NeedsPadding = true;
1618 
1619     return false;
1620   }
1621 
1622   return true;
1623 }
1624 
1625 bool X86_32ABIInfo::shouldPrimitiveUseInReg(QualType Ty, CCState &State) const {
1626   if (!updateFreeRegs(Ty, State))
1627     return false;
1628 
1629   if (IsMCUABI)
1630     return false;
1631 
1632   if (State.CC == llvm::CallingConv::X86_FastCall ||
1633       State.CC == llvm::CallingConv::X86_VectorCall ||
1634       State.CC == llvm::CallingConv::X86_RegCall) {
1635     if (getContext().getTypeSize(Ty) > 32)
1636       return false;
1637 
1638     return (Ty->isIntegralOrEnumerationType() || Ty->isPointerType() ||
1639         Ty->isReferenceType());
1640   }
1641 
1642   return true;
1643 }
1644 
1645 void X86_32ABIInfo::runVectorCallFirstPass(CGFunctionInfo &FI, CCState &State) const {
1646   // Vectorcall x86 works subtly different than in x64, so the format is
1647   // a bit different than the x64 version.  First, all vector types (not HVAs)
1648   // are assigned, with the first 6 ending up in the [XYZ]MM0-5 registers.
1649   // This differs from the x64 implementation, where the first 6 by INDEX get
1650   // registers.
1651   // In the second pass over the arguments, HVAs are passed in the remaining
1652   // vector registers if possible, or indirectly by address. The address will be
1653   // passed in ECX/EDX if available. Any other arguments are passed according to
1654   // the usual fastcall rules.
1655   MutableArrayRef<CGFunctionInfoArgInfo> Args = FI.arguments();
1656   for (int I = 0, E = Args.size(); I < E; ++I) {
1657     const Type *Base = nullptr;
1658     uint64_t NumElts = 0;
1659     const QualType &Ty = Args[I].type;
1660     if ((Ty->isVectorType() || Ty->isBuiltinType()) &&
1661         isHomogeneousAggregate(Ty, Base, NumElts)) {
1662       if (State.FreeSSERegs >= NumElts) {
1663         State.FreeSSERegs -= NumElts;
1664         Args[I].info = ABIArgInfo::getDirect();
1665         State.IsPreassigned.set(I);
1666       }
1667     }
1668   }
1669 }
1670 
1671 ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
1672                                                CCState &State) const {
1673   // FIXME: Set alignment on indirect arguments.
1674   bool IsFastCall = State.CC == llvm::CallingConv::X86_FastCall;
1675   bool IsRegCall = State.CC == llvm::CallingConv::X86_RegCall;
1676   bool IsVectorCall = State.CC == llvm::CallingConv::X86_VectorCall;
1677 
1678   Ty = useFirstFieldIfTransparentUnion(Ty);
1679 
1680   // Check with the C++ ABI first.
1681   const RecordType *RT = Ty->getAs<RecordType>();
1682   if (RT) {
1683     CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
1684     if (RAA == CGCXXABI::RAA_Indirect) {
1685       return getIndirectResult(Ty, false, State);
1686     } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
1687       // The field index doesn't matter, we'll fix it up later.
1688       return ABIArgInfo::getInAlloca(/*FieldIndex=*/0);
1689     }
1690   }
1691 
1692   // Regcall uses the concept of a homogenous vector aggregate, similar
1693   // to other targets.
1694   const Type *Base = nullptr;
1695   uint64_t NumElts = 0;
1696   if ((IsRegCall || IsVectorCall) &&
1697       isHomogeneousAggregate(Ty, Base, NumElts)) {
1698     if (State.FreeSSERegs >= NumElts) {
1699       State.FreeSSERegs -= NumElts;
1700 
1701       // Vectorcall passes HVAs directly and does not flatten them, but regcall
1702       // does.
1703       if (IsVectorCall)
1704         return getDirectX86Hva();
1705 
1706       if (Ty->isBuiltinType() || Ty->isVectorType())
1707         return ABIArgInfo::getDirect();
1708       return ABIArgInfo::getExpand();
1709     }
1710     return getIndirectResult(Ty, /*ByVal=*/false, State);
1711   }
1712 
1713   if (isAggregateTypeForABI(Ty)) {
1714     // Structures with flexible arrays are always indirect.
1715     // FIXME: This should not be byval!
1716     if (RT && RT->getDecl()->hasFlexibleArrayMember())
1717       return getIndirectResult(Ty, true, State);
1718 
1719     // Ignore empty structs/unions on non-Windows.
1720     if (!IsWin32StructABI && isEmptyRecord(getContext(), Ty, true))
1721       return ABIArgInfo::getIgnore();
1722 
1723     llvm::LLVMContext &LLVMContext = getVMContext();
1724     llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
1725     bool NeedsPadding = false;
1726     bool InReg;
1727     if (shouldAggregateUseDirect(Ty, State, InReg, NeedsPadding)) {
1728       unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
1729       SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32);
1730       llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
1731       if (InReg)
1732         return ABIArgInfo::getDirectInReg(Result);
1733       else
1734         return ABIArgInfo::getDirect(Result);
1735     }
1736     llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : nullptr;
1737 
1738     // Expand small (<= 128-bit) record types when we know that the stack layout
1739     // of those arguments will match the struct. This is important because the
1740     // LLVM backend isn't smart enough to remove byval, which inhibits many
1741     // optimizations.
1742     // Don't do this for the MCU if there are still free integer registers
1743     // (see X86_64 ABI for full explanation).
1744     if (getContext().getTypeSize(Ty) <= 4 * 32 &&
1745         (!IsMCUABI || State.FreeRegs == 0) && canExpandIndirectArgument(Ty))
1746       return ABIArgInfo::getExpandWithPadding(
1747           IsFastCall || IsVectorCall || IsRegCall, PaddingType);
1748 
1749     return getIndirectResult(Ty, true, State);
1750   }
1751 
1752   if (const VectorType *VT = Ty->getAs<VectorType>()) {
1753     // On Darwin, some vectors are passed in memory, we handle this by passing
1754     // it as an i8/i16/i32/i64.
1755     if (IsDarwinVectorABI) {
1756       uint64_t Size = getContext().getTypeSize(Ty);
1757       if ((Size == 8 || Size == 16 || Size == 32) ||
1758           (Size == 64 && VT->getNumElements() == 1))
1759         return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
1760                                                             Size));
1761     }
1762 
1763     if (IsX86_MMXType(CGT.ConvertType(Ty)))
1764       return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64));
1765 
1766     return ABIArgInfo::getDirect();
1767   }
1768 
1769 
1770   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1771     Ty = EnumTy->getDecl()->getIntegerType();
1772 
1773   bool InReg = shouldPrimitiveUseInReg(Ty, State);
1774 
1775   if (Ty->isPromotableIntegerType()) {
1776     if (InReg)
1777       return ABIArgInfo::getExtendInReg(Ty);
1778     return ABIArgInfo::getExtend(Ty);
1779   }
1780 
1781   if (InReg)
1782     return ABIArgInfo::getDirectInReg();
1783   return ABIArgInfo::getDirect();
1784 }
1785 
1786 void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const {
1787   CCState State(FI);
1788   if (IsMCUABI)
1789     State.FreeRegs = 3;
1790   else if (State.CC == llvm::CallingConv::X86_FastCall)
1791     State.FreeRegs = 2;
1792   else if (State.CC == llvm::CallingConv::X86_VectorCall) {
1793     State.FreeRegs = 2;
1794     State.FreeSSERegs = 6;
1795   } else if (FI.getHasRegParm())
1796     State.FreeRegs = FI.getRegParm();
1797   else if (State.CC == llvm::CallingConv::X86_RegCall) {
1798     State.FreeRegs = 5;
1799     State.FreeSSERegs = 8;
1800   } else
1801     State.FreeRegs = DefaultNumRegisterParameters;
1802 
1803   if (!::classifyReturnType(getCXXABI(), FI, *this)) {
1804     FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), State);
1805   } else if (FI.getReturnInfo().isIndirect()) {
1806     // The C++ ABI is not aware of register usage, so we have to check if the
1807     // return value was sret and put it in a register ourselves if appropriate.
1808     if (State.FreeRegs) {
1809       --State.FreeRegs;  // The sret parameter consumes a register.
1810       if (!IsMCUABI)
1811         FI.getReturnInfo().setInReg(true);
1812     }
1813   }
1814 
1815   // The chain argument effectively gives us another free register.
1816   if (FI.isChainCall())
1817     ++State.FreeRegs;
1818 
1819   // For vectorcall, do a first pass over the arguments, assigning FP and vector
1820   // arguments to XMM registers as available.
1821   if (State.CC == llvm::CallingConv::X86_VectorCall)
1822     runVectorCallFirstPass(FI, State);
1823 
1824   bool UsedInAlloca = false;
1825   MutableArrayRef<CGFunctionInfoArgInfo> Args = FI.arguments();
1826   for (int I = 0, E = Args.size(); I < E; ++I) {
1827     // Skip arguments that have already been assigned.
1828     if (State.IsPreassigned.test(I))
1829       continue;
1830 
1831     Args[I].info = classifyArgumentType(Args[I].type, State);
1832     UsedInAlloca |= (Args[I].info.getKind() == ABIArgInfo::InAlloca);
1833   }
1834 
1835   // If we needed to use inalloca for any argument, do a second pass and rewrite
1836   // all the memory arguments to use inalloca.
1837   if (UsedInAlloca)
1838     rewriteWithInAlloca(FI);
1839 }
1840 
1841 void
1842 X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
1843                                    CharUnits &StackOffset, ABIArgInfo &Info,
1844                                    QualType Type) const {
1845   // Arguments are always 4-byte-aligned.
1846   CharUnits FieldAlign = CharUnits::fromQuantity(4);
1847 
1848   assert(StackOffset.isMultipleOf(FieldAlign) && "unaligned inalloca struct");
1849   Info = ABIArgInfo::getInAlloca(FrameFields.size());
1850   FrameFields.push_back(CGT.ConvertTypeForMem(Type));
1851   StackOffset += getContext().getTypeSizeInChars(Type);
1852 
1853   // Insert padding bytes to respect alignment.
1854   CharUnits FieldEnd = StackOffset;
1855   StackOffset = FieldEnd.alignTo(FieldAlign);
1856   if (StackOffset != FieldEnd) {
1857     CharUnits NumBytes = StackOffset - FieldEnd;
1858     llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext());
1859     Ty = llvm::ArrayType::get(Ty, NumBytes.getQuantity());
1860     FrameFields.push_back(Ty);
1861   }
1862 }
1863 
1864 static bool isArgInAlloca(const ABIArgInfo &Info) {
1865   // Leave ignored and inreg arguments alone.
1866   switch (Info.getKind()) {
1867   case ABIArgInfo::InAlloca:
1868     return true;
1869   case ABIArgInfo::Indirect:
1870     assert(Info.getIndirectByVal());
1871     return true;
1872   case ABIArgInfo::Ignore:
1873     return false;
1874   case ABIArgInfo::Direct:
1875   case ABIArgInfo::Extend:
1876     if (Info.getInReg())
1877       return false;
1878     return true;
1879   case ABIArgInfo::Expand:
1880   case ABIArgInfo::CoerceAndExpand:
1881     // These are aggregate types which are never passed in registers when
1882     // inalloca is involved.
1883     return true;
1884   }
1885   llvm_unreachable("invalid enum");
1886 }
1887 
1888 void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const {
1889   assert(IsWin32StructABI && "inalloca only supported on win32");
1890 
1891   // Build a packed struct type for all of the arguments in memory.
1892   SmallVector<llvm::Type *, 6> FrameFields;
1893 
1894   // The stack alignment is always 4.
1895   CharUnits StackAlign = CharUnits::fromQuantity(4);
1896 
1897   CharUnits StackOffset;
1898   CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end();
1899 
1900   // Put 'this' into the struct before 'sret', if necessary.
1901   bool IsThisCall =
1902       FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall;
1903   ABIArgInfo &Ret = FI.getReturnInfo();
1904   if (Ret.isIndirect() && Ret.isSRetAfterThis() && !IsThisCall &&
1905       isArgInAlloca(I->info)) {
1906     addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
1907     ++I;
1908   }
1909 
1910   // Put the sret parameter into the inalloca struct if it's in memory.
1911   if (Ret.isIndirect() && !Ret.getInReg()) {
1912     CanQualType PtrTy = getContext().getPointerType(FI.getReturnType());
1913     addFieldToArgStruct(FrameFields, StackOffset, Ret, PtrTy);
1914     // On Windows, the hidden sret parameter is always returned in eax.
1915     Ret.setInAllocaSRet(IsWin32StructABI);
1916   }
1917 
1918   // Skip the 'this' parameter in ecx.
1919   if (IsThisCall)
1920     ++I;
1921 
1922   // Put arguments passed in memory into the struct.
1923   for (; I != E; ++I) {
1924     if (isArgInAlloca(I->info))
1925       addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
1926   }
1927 
1928   FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields,
1929                                         /*isPacked=*/true),
1930                   StackAlign);
1931 }
1932 
1933 Address X86_32ABIInfo::EmitVAArg(CodeGenFunction &CGF,
1934                                  Address VAListAddr, QualType Ty) const {
1935 
1936   auto TypeInfo = getContext().getTypeInfoInChars(Ty);
1937 
1938   // x86-32 changes the alignment of certain arguments on the stack.
1939   //
1940   // Just messing with TypeInfo like this works because we never pass
1941   // anything indirectly.
1942   TypeInfo.second = CharUnits::fromQuantity(
1943                 getTypeStackAlignInBytes(Ty, TypeInfo.second.getQuantity()));
1944 
1945   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
1946                           TypeInfo, CharUnits::fromQuantity(4),
1947                           /*AllowHigherAlign*/ true);
1948 }
1949 
1950 bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
1951     const llvm::Triple &Triple, const CodeGenOptions &Opts) {
1952   assert(Triple.getArch() == llvm::Triple::x86);
1953 
1954   switch (Opts.getStructReturnConvention()) {
1955   case CodeGenOptions::SRCK_Default:
1956     break;
1957   case CodeGenOptions::SRCK_OnStack:  // -fpcc-struct-return
1958     return false;
1959   case CodeGenOptions::SRCK_InRegs:  // -freg-struct-return
1960     return true;
1961   }
1962 
1963   if (Triple.isOSDarwin() || Triple.isOSIAMCU())
1964     return true;
1965 
1966   switch (Triple.getOS()) {
1967   case llvm::Triple::DragonFly:
1968   case llvm::Triple::FreeBSD:
1969   case llvm::Triple::OpenBSD:
1970   case llvm::Triple::Win32:
1971     return true;
1972   default:
1973     return false;
1974   }
1975 }
1976 
1977 void X86_32TargetCodeGenInfo::setTargetAttributes(
1978     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
1979   if (GV->isDeclaration())
1980     return;
1981   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
1982     if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
1983       llvm::Function *Fn = cast<llvm::Function>(GV);
1984       Fn->addFnAttr("stackrealign");
1985     }
1986     if (FD->hasAttr<AnyX86InterruptAttr>()) {
1987       llvm::Function *Fn = cast<llvm::Function>(GV);
1988       Fn->setCallingConv(llvm::CallingConv::X86_INTR);
1989     }
1990   }
1991 }
1992 
1993 bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
1994                                                CodeGen::CodeGenFunction &CGF,
1995                                                llvm::Value *Address) const {
1996   CodeGen::CGBuilderTy &Builder = CGF.Builder;
1997 
1998   llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
1999 
2000   // 0-7 are the eight integer registers;  the order is different
2001   //   on Darwin (for EH), but the range is the same.
2002   // 8 is %eip.
2003   AssignToArrayRange(Builder, Address, Four8, 0, 8);
2004 
2005   if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
2006     // 12-16 are st(0..4).  Not sure why we stop at 4.
2007     // These have size 16, which is sizeof(long double) on
2008     // platforms with 8-byte alignment for that type.
2009     llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
2010     AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
2011 
2012   } else {
2013     // 9 is %eflags, which doesn't get a size on Darwin for some
2014     // reason.
2015     Builder.CreateAlignedStore(
2016         Four8, Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, Address, 9),
2017                                CharUnits::One());
2018 
2019     // 11-16 are st(0..5).  Not sure why we stop at 5.
2020     // These have size 12, which is sizeof(long double) on
2021     // platforms with 4-byte alignment for that type.
2022     llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
2023     AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
2024   }
2025 
2026   return false;
2027 }
2028 
2029 //===----------------------------------------------------------------------===//
2030 // X86-64 ABI Implementation
2031 //===----------------------------------------------------------------------===//
2032 
2033 
2034 namespace {
2035 /// The AVX ABI level for X86 targets.
2036 enum class X86AVXABILevel {
2037   None,
2038   AVX,
2039   AVX512
2040 };
2041 
2042 /// \p returns the size in bits of the largest (native) vector for \p AVXLevel.
2043 static unsigned getNativeVectorSizeForAVXABI(X86AVXABILevel AVXLevel) {
2044   switch (AVXLevel) {
2045   case X86AVXABILevel::AVX512:
2046     return 512;
2047   case X86AVXABILevel::AVX:
2048     return 256;
2049   case X86AVXABILevel::None:
2050     return 128;
2051   }
2052   llvm_unreachable("Unknown AVXLevel");
2053 }
2054 
2055 /// X86_64ABIInfo - The X86_64 ABI information.
2056 class X86_64ABIInfo : public SwiftABIInfo {
2057   enum Class {
2058     Integer = 0,
2059     SSE,
2060     SSEUp,
2061     X87,
2062     X87Up,
2063     ComplexX87,
2064     NoClass,
2065     Memory
2066   };
2067 
2068   /// merge - Implement the X86_64 ABI merging algorithm.
2069   ///
2070   /// Merge an accumulating classification \arg Accum with a field
2071   /// classification \arg Field.
2072   ///
2073   /// \param Accum - The accumulating classification. This should
2074   /// always be either NoClass or the result of a previous merge
2075   /// call. In addition, this should never be Memory (the caller
2076   /// should just return Memory for the aggregate).
2077   static Class merge(Class Accum, Class Field);
2078 
2079   /// postMerge - Implement the X86_64 ABI post merging algorithm.
2080   ///
2081   /// Post merger cleanup, reduces a malformed Hi and Lo pair to
2082   /// final MEMORY or SSE classes when necessary.
2083   ///
2084   /// \param AggregateSize - The size of the current aggregate in
2085   /// the classification process.
2086   ///
2087   /// \param Lo - The classification for the parts of the type
2088   /// residing in the low word of the containing object.
2089   ///
2090   /// \param Hi - The classification for the parts of the type
2091   /// residing in the higher words of the containing object.
2092   ///
2093   void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
2094 
2095   /// classify - Determine the x86_64 register classes in which the
2096   /// given type T should be passed.
2097   ///
2098   /// \param Lo - The classification for the parts of the type
2099   /// residing in the low word of the containing object.
2100   ///
2101   /// \param Hi - The classification for the parts of the type
2102   /// residing in the high word of the containing object.
2103   ///
2104   /// \param OffsetBase - The bit offset of this type in the
2105   /// containing object.  Some parameters are classified different
2106   /// depending on whether they straddle an eightbyte boundary.
2107   ///
2108   /// \param isNamedArg - Whether the argument in question is a "named"
2109   /// argument, as used in AMD64-ABI 3.5.7.
2110   ///
2111   /// If a word is unused its result will be NoClass; if a type should
2112   /// be passed in Memory then at least the classification of \arg Lo
2113   /// will be Memory.
2114   ///
2115   /// The \arg Lo class will be NoClass iff the argument is ignored.
2116   ///
2117   /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
2118   /// also be ComplexX87.
2119   void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi,
2120                 bool isNamedArg) const;
2121 
2122   llvm::Type *GetByteVectorType(QualType Ty) const;
2123   llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
2124                                  unsigned IROffset, QualType SourceTy,
2125                                  unsigned SourceOffset) const;
2126   llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
2127                                      unsigned IROffset, QualType SourceTy,
2128                                      unsigned SourceOffset) const;
2129 
2130   /// getIndirectResult - Give a source type \arg Ty, return a suitable result
2131   /// such that the argument will be returned in memory.
2132   ABIArgInfo getIndirectReturnResult(QualType Ty) const;
2133 
2134   /// getIndirectResult - Give a source type \arg Ty, return a suitable result
2135   /// such that the argument will be passed in memory.
2136   ///
2137   /// \param freeIntRegs - The number of free integer registers remaining
2138   /// available.
2139   ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
2140 
2141   ABIArgInfo classifyReturnType(QualType RetTy) const;
2142 
2143   ABIArgInfo classifyArgumentType(QualType Ty, unsigned freeIntRegs,
2144                                   unsigned &neededInt, unsigned &neededSSE,
2145                                   bool isNamedArg) const;
2146 
2147   ABIArgInfo classifyRegCallStructType(QualType Ty, unsigned &NeededInt,
2148                                        unsigned &NeededSSE) const;
2149 
2150   ABIArgInfo classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
2151                                            unsigned &NeededSSE) const;
2152 
2153   bool IsIllegalVectorType(QualType Ty) const;
2154 
2155   /// The 0.98 ABI revision clarified a lot of ambiguities,
2156   /// unfortunately in ways that were not always consistent with
2157   /// certain previous compilers.  In particular, platforms which
2158   /// required strict binary compatibility with older versions of GCC
2159   /// may need to exempt themselves.
2160   bool honorsRevision0_98() const {
2161     return !getTarget().getTriple().isOSDarwin();
2162   }
2163 
2164   /// GCC classifies <1 x long long> as SSE but some platform ABIs choose to
2165   /// classify it as INTEGER (for compatibility with older clang compilers).
2166   bool classifyIntegerMMXAsSSE() const {
2167     // Clang <= 3.8 did not do this.
2168     if (getContext().getLangOpts().getClangABICompat() <=
2169         LangOptions::ClangABI::Ver3_8)
2170       return false;
2171 
2172     const llvm::Triple &Triple = getTarget().getTriple();
2173     if (Triple.isOSDarwin() || Triple.getOS() == llvm::Triple::PS4)
2174       return false;
2175     if (Triple.isOSFreeBSD() && Triple.getOSMajorVersion() >= 10)
2176       return false;
2177     return true;
2178   }
2179 
2180   // GCC classifies vectors of __int128 as memory.
2181   bool passInt128VectorsInMem() const {
2182     // Clang <= 9.0 did not do this.
2183     if (getContext().getLangOpts().getClangABICompat() <=
2184         LangOptions::ClangABI::Ver9)
2185       return false;
2186 
2187     const llvm::Triple &T = getTarget().getTriple();
2188     return T.isOSLinux() || T.isOSNetBSD();
2189   }
2190 
2191   X86AVXABILevel AVXLevel;
2192   // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
2193   // 64-bit hardware.
2194   bool Has64BitPointers;
2195 
2196 public:
2197   X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) :
2198       SwiftABIInfo(CGT), AVXLevel(AVXLevel),
2199       Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {
2200   }
2201 
2202   bool isPassedUsingAVXType(QualType type) const {
2203     unsigned neededInt, neededSSE;
2204     // The freeIntRegs argument doesn't matter here.
2205     ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE,
2206                                            /*isNamedArg*/true);
2207     if (info.isDirect()) {
2208       llvm::Type *ty = info.getCoerceToType();
2209       if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
2210         return (vectorTy->getBitWidth() > 128);
2211     }
2212     return false;
2213   }
2214 
2215   void computeInfo(CGFunctionInfo &FI) const override;
2216 
2217   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
2218                     QualType Ty) const override;
2219   Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
2220                       QualType Ty) const override;
2221 
2222   bool has64BitPointers() const {
2223     return Has64BitPointers;
2224   }
2225 
2226   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
2227                                     bool asReturnValue) const override {
2228     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
2229   }
2230   bool isSwiftErrorInRegister() const override {
2231     return true;
2232   }
2233 };
2234 
2235 /// WinX86_64ABIInfo - The Windows X86_64 ABI information.
2236 class WinX86_64ABIInfo : public SwiftABIInfo {
2237 public:
2238   WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
2239       : SwiftABIInfo(CGT), AVXLevel(AVXLevel),
2240         IsMingw64(getTarget().getTriple().isWindowsGNUEnvironment()) {}
2241 
2242   void computeInfo(CGFunctionInfo &FI) const override;
2243 
2244   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
2245                     QualType Ty) const override;
2246 
2247   bool isHomogeneousAggregateBaseType(QualType Ty) const override {
2248     // FIXME: Assumes vectorcall is in use.
2249     return isX86VectorTypeForVectorCall(getContext(), Ty);
2250   }
2251 
2252   bool isHomogeneousAggregateSmallEnough(const Type *Ty,
2253                                          uint64_t NumMembers) const override {
2254     // FIXME: Assumes vectorcall is in use.
2255     return isX86VectorCallAggregateSmallEnough(NumMembers);
2256   }
2257 
2258   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type *> scalars,
2259                                     bool asReturnValue) const override {
2260     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
2261   }
2262 
2263   bool isSwiftErrorInRegister() const override {
2264     return true;
2265   }
2266 
2267 private:
2268   ABIArgInfo classify(QualType Ty, unsigned &FreeSSERegs, bool IsReturnType,
2269                       bool IsVectorCall, bool IsRegCall) const;
2270   ABIArgInfo reclassifyHvaArgType(QualType Ty, unsigned &FreeSSERegs,
2271                                       const ABIArgInfo &current) const;
2272   void computeVectorCallArgs(CGFunctionInfo &FI, unsigned FreeSSERegs,
2273                              bool IsVectorCall, bool IsRegCall) const;
2274 
2275   X86AVXABILevel AVXLevel;
2276 
2277   bool IsMingw64;
2278 };
2279 
2280 class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2281 public:
2282   X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
2283       : TargetCodeGenInfo(new X86_64ABIInfo(CGT, AVXLevel)) {}
2284 
2285   const X86_64ABIInfo &getABIInfo() const {
2286     return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
2287   }
2288 
2289   /// Disable tail call on x86-64. The epilogue code before the tail jump blocks
2290   /// the autoreleaseRV/retainRV optimization.
2291   bool shouldSuppressTailCallsOfRetainAutoreleasedReturnValue() const override {
2292     return true;
2293   }
2294 
2295   int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
2296     return 7;
2297   }
2298 
2299   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2300                                llvm::Value *Address) const override {
2301     llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
2302 
2303     // 0-15 are the 16 integer registers.
2304     // 16 is %rip.
2305     AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
2306     return false;
2307   }
2308 
2309   llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
2310                                   StringRef Constraint,
2311                                   llvm::Type* Ty) const override {
2312     return X86AdjustInlineAsmType(CGF, Constraint, Ty);
2313   }
2314 
2315   bool isNoProtoCallVariadic(const CallArgList &args,
2316                              const FunctionNoProtoType *fnType) const override {
2317     // The default CC on x86-64 sets %al to the number of SSA
2318     // registers used, and GCC sets this when calling an unprototyped
2319     // function, so we override the default behavior.  However, don't do
2320     // that when AVX types are involved: the ABI explicitly states it is
2321     // undefined, and it doesn't work in practice because of how the ABI
2322     // defines varargs anyway.
2323     if (fnType->getCallConv() == CC_C) {
2324       bool HasAVXType = false;
2325       for (CallArgList::const_iterator
2326              it = args.begin(), ie = args.end(); it != ie; ++it) {
2327         if (getABIInfo().isPassedUsingAVXType(it->Ty)) {
2328           HasAVXType = true;
2329           break;
2330         }
2331       }
2332 
2333       if (!HasAVXType)
2334         return true;
2335     }
2336 
2337     return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
2338   }
2339 
2340   llvm::Constant *
2341   getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
2342     unsigned Sig = (0xeb << 0) | // jmp rel8
2343                    (0x06 << 8) | //           .+0x08
2344                    ('v' << 16) |
2345                    ('2' << 24);
2346     return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
2347   }
2348 
2349   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2350                            CodeGen::CodeGenModule &CGM) const override {
2351     if (GV->isDeclaration())
2352       return;
2353     if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2354       if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
2355         llvm::Function *Fn = cast<llvm::Function>(GV);
2356         Fn->addFnAttr("stackrealign");
2357       }
2358       if (FD->hasAttr<AnyX86InterruptAttr>()) {
2359         llvm::Function *Fn = cast<llvm::Function>(GV);
2360         Fn->setCallingConv(llvm::CallingConv::X86_INTR);
2361       }
2362     }
2363   }
2364 };
2365 
2366 static std::string qualifyWindowsLibrary(llvm::StringRef Lib) {
2367   // If the argument does not end in .lib, automatically add the suffix.
2368   // If the argument contains a space, enclose it in quotes.
2369   // This matches the behavior of MSVC.
2370   bool Quote = (Lib.find(" ") != StringRef::npos);
2371   std::string ArgStr = Quote ? "\"" : "";
2372   ArgStr += Lib;
2373   if (!Lib.endswith_lower(".lib") && !Lib.endswith_lower(".a"))
2374     ArgStr += ".lib";
2375   ArgStr += Quote ? "\"" : "";
2376   return ArgStr;
2377 }
2378 
2379 class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
2380 public:
2381   WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
2382         bool DarwinVectorABI, bool RetSmallStructInRegABI, bool Win32StructABI,
2383         unsigned NumRegisterParameters)
2384     : X86_32TargetCodeGenInfo(CGT, DarwinVectorABI, RetSmallStructInRegABI,
2385         Win32StructABI, NumRegisterParameters, false) {}
2386 
2387   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2388                            CodeGen::CodeGenModule &CGM) const override;
2389 
2390   void getDependentLibraryOption(llvm::StringRef Lib,
2391                                  llvm::SmallString<24> &Opt) const override {
2392     Opt = "/DEFAULTLIB:";
2393     Opt += qualifyWindowsLibrary(Lib);
2394   }
2395 
2396   void getDetectMismatchOption(llvm::StringRef Name,
2397                                llvm::StringRef Value,
2398                                llvm::SmallString<32> &Opt) const override {
2399     Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
2400   }
2401 };
2402 
2403 static void addStackProbeTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2404                                           CodeGen::CodeGenModule &CGM) {
2405   if (llvm::Function *Fn = dyn_cast_or_null<llvm::Function>(GV)) {
2406 
2407     if (CGM.getCodeGenOpts().StackProbeSize != 4096)
2408       Fn->addFnAttr("stack-probe-size",
2409                     llvm::utostr(CGM.getCodeGenOpts().StackProbeSize));
2410     if (CGM.getCodeGenOpts().NoStackArgProbe)
2411       Fn->addFnAttr("no-stack-arg-probe");
2412   }
2413 }
2414 
2415 void WinX86_32TargetCodeGenInfo::setTargetAttributes(
2416     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
2417   X86_32TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
2418   if (GV->isDeclaration())
2419     return;
2420   addStackProbeTargetAttributes(D, GV, CGM);
2421 }
2422 
2423 class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2424 public:
2425   WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
2426                              X86AVXABILevel AVXLevel)
2427       : TargetCodeGenInfo(new WinX86_64ABIInfo(CGT, AVXLevel)) {}
2428 
2429   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2430                            CodeGen::CodeGenModule &CGM) const override;
2431 
2432   int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
2433     return 7;
2434   }
2435 
2436   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2437                                llvm::Value *Address) const override {
2438     llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
2439 
2440     // 0-15 are the 16 integer registers.
2441     // 16 is %rip.
2442     AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
2443     return false;
2444   }
2445 
2446   void getDependentLibraryOption(llvm::StringRef Lib,
2447                                  llvm::SmallString<24> &Opt) const override {
2448     Opt = "/DEFAULTLIB:";
2449     Opt += qualifyWindowsLibrary(Lib);
2450   }
2451 
2452   void getDetectMismatchOption(llvm::StringRef Name,
2453                                llvm::StringRef Value,
2454                                llvm::SmallString<32> &Opt) const override {
2455     Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
2456   }
2457 };
2458 
2459 void WinX86_64TargetCodeGenInfo::setTargetAttributes(
2460     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
2461   TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
2462   if (GV->isDeclaration())
2463     return;
2464   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2465     if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
2466       llvm::Function *Fn = cast<llvm::Function>(GV);
2467       Fn->addFnAttr("stackrealign");
2468     }
2469     if (FD->hasAttr<AnyX86InterruptAttr>()) {
2470       llvm::Function *Fn = cast<llvm::Function>(GV);
2471       Fn->setCallingConv(llvm::CallingConv::X86_INTR);
2472     }
2473   }
2474 
2475   addStackProbeTargetAttributes(D, GV, CGM);
2476 }
2477 }
2478 
2479 void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
2480                               Class &Hi) const {
2481   // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
2482   //
2483   // (a) If one of the classes is Memory, the whole argument is passed in
2484   //     memory.
2485   //
2486   // (b) If X87UP is not preceded by X87, the whole argument is passed in
2487   //     memory.
2488   //
2489   // (c) If the size of the aggregate exceeds two eightbytes and the first
2490   //     eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
2491   //     argument is passed in memory. NOTE: This is necessary to keep the
2492   //     ABI working for processors that don't support the __m256 type.
2493   //
2494   // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
2495   //
2496   // Some of these are enforced by the merging logic.  Others can arise
2497   // only with unions; for example:
2498   //   union { _Complex double; unsigned; }
2499   //
2500   // Note that clauses (b) and (c) were added in 0.98.
2501   //
2502   if (Hi == Memory)
2503     Lo = Memory;
2504   if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
2505     Lo = Memory;
2506   if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
2507     Lo = Memory;
2508   if (Hi == SSEUp && Lo != SSE)
2509     Hi = SSE;
2510 }
2511 
2512 X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
2513   // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
2514   // classified recursively so that always two fields are
2515   // considered. The resulting class is calculated according to
2516   // the classes of the fields in the eightbyte:
2517   //
2518   // (a) If both classes are equal, this is the resulting class.
2519   //
2520   // (b) If one of the classes is NO_CLASS, the resulting class is
2521   // the other class.
2522   //
2523   // (c) If one of the classes is MEMORY, the result is the MEMORY
2524   // class.
2525   //
2526   // (d) If one of the classes is INTEGER, the result is the
2527   // INTEGER.
2528   //
2529   // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
2530   // MEMORY is used as class.
2531   //
2532   // (f) Otherwise class SSE is used.
2533 
2534   // Accum should never be memory (we should have returned) or
2535   // ComplexX87 (because this cannot be passed in a structure).
2536   assert((Accum != Memory && Accum != ComplexX87) &&
2537          "Invalid accumulated classification during merge.");
2538   if (Accum == Field || Field == NoClass)
2539     return Accum;
2540   if (Field == Memory)
2541     return Memory;
2542   if (Accum == NoClass)
2543     return Field;
2544   if (Accum == Integer || Field == Integer)
2545     return Integer;
2546   if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
2547       Accum == X87 || Accum == X87Up)
2548     return Memory;
2549   return SSE;
2550 }
2551 
2552 void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
2553                              Class &Lo, Class &Hi, bool isNamedArg) const {
2554   // FIXME: This code can be simplified by introducing a simple value class for
2555   // Class pairs with appropriate constructor methods for the various
2556   // situations.
2557 
2558   // FIXME: Some of the split computations are wrong; unaligned vectors
2559   // shouldn't be passed in registers for example, so there is no chance they
2560   // can straddle an eightbyte. Verify & simplify.
2561 
2562   Lo = Hi = NoClass;
2563 
2564   Class &Current = OffsetBase < 64 ? Lo : Hi;
2565   Current = Memory;
2566 
2567   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
2568     BuiltinType::Kind k = BT->getKind();
2569 
2570     if (k == BuiltinType::Void) {
2571       Current = NoClass;
2572     } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
2573       Lo = Integer;
2574       Hi = Integer;
2575     } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
2576       Current = Integer;
2577     } else if (k == BuiltinType::Float || k == BuiltinType::Double) {
2578       Current = SSE;
2579     } else if (k == BuiltinType::LongDouble) {
2580       const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
2581       if (LDF == &llvm::APFloat::IEEEquad()) {
2582         Lo = SSE;
2583         Hi = SSEUp;
2584       } else if (LDF == &llvm::APFloat::x87DoubleExtended()) {
2585         Lo = X87;
2586         Hi = X87Up;
2587       } else if (LDF == &llvm::APFloat::IEEEdouble()) {
2588         Current = SSE;
2589       } else
2590         llvm_unreachable("unexpected long double representation!");
2591     }
2592     // FIXME: _Decimal32 and _Decimal64 are SSE.
2593     // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
2594     return;
2595   }
2596 
2597   if (const EnumType *ET = Ty->getAs<EnumType>()) {
2598     // Classify the underlying integer type.
2599     classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
2600     return;
2601   }
2602 
2603   if (Ty->hasPointerRepresentation()) {
2604     Current = Integer;
2605     return;
2606   }
2607 
2608   if (Ty->isMemberPointerType()) {
2609     if (Ty->isMemberFunctionPointerType()) {
2610       if (Has64BitPointers) {
2611         // If Has64BitPointers, this is an {i64, i64}, so classify both
2612         // Lo and Hi now.
2613         Lo = Hi = Integer;
2614       } else {
2615         // Otherwise, with 32-bit pointers, this is an {i32, i32}. If that
2616         // straddles an eightbyte boundary, Hi should be classified as well.
2617         uint64_t EB_FuncPtr = (OffsetBase) / 64;
2618         uint64_t EB_ThisAdj = (OffsetBase + 64 - 1) / 64;
2619         if (EB_FuncPtr != EB_ThisAdj) {
2620           Lo = Hi = Integer;
2621         } else {
2622           Current = Integer;
2623         }
2624       }
2625     } else {
2626       Current = Integer;
2627     }
2628     return;
2629   }
2630 
2631   if (const VectorType *VT = Ty->getAs<VectorType>()) {
2632     uint64_t Size = getContext().getTypeSize(VT);
2633     if (Size == 1 || Size == 8 || Size == 16 || Size == 32) {
2634       // gcc passes the following as integer:
2635       // 4 bytes - <4 x char>, <2 x short>, <1 x int>, <1 x float>
2636       // 2 bytes - <2 x char>, <1 x short>
2637       // 1 byte  - <1 x char>
2638       Current = Integer;
2639 
2640       // If this type crosses an eightbyte boundary, it should be
2641       // split.
2642       uint64_t EB_Lo = (OffsetBase) / 64;
2643       uint64_t EB_Hi = (OffsetBase + Size - 1) / 64;
2644       if (EB_Lo != EB_Hi)
2645         Hi = Lo;
2646     } else if (Size == 64) {
2647       QualType ElementType = VT->getElementType();
2648 
2649       // gcc passes <1 x double> in memory. :(
2650       if (ElementType->isSpecificBuiltinType(BuiltinType::Double))
2651         return;
2652 
2653       // gcc passes <1 x long long> as SSE but clang used to unconditionally
2654       // pass them as integer.  For platforms where clang is the de facto
2655       // platform compiler, we must continue to use integer.
2656       if (!classifyIntegerMMXAsSSE() &&
2657           (ElementType->isSpecificBuiltinType(BuiltinType::LongLong) ||
2658            ElementType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
2659            ElementType->isSpecificBuiltinType(BuiltinType::Long) ||
2660            ElementType->isSpecificBuiltinType(BuiltinType::ULong)))
2661         Current = Integer;
2662       else
2663         Current = SSE;
2664 
2665       // If this type crosses an eightbyte boundary, it should be
2666       // split.
2667       if (OffsetBase && OffsetBase != 64)
2668         Hi = Lo;
2669     } else if (Size == 128 ||
2670                (isNamedArg && Size <= getNativeVectorSizeForAVXABI(AVXLevel))) {
2671       QualType ElementType = VT->getElementType();
2672 
2673       // gcc passes 256 and 512 bit <X x __int128> vectors in memory. :(
2674       if (passInt128VectorsInMem() && Size != 128 &&
2675           (ElementType->isSpecificBuiltinType(BuiltinType::Int128) ||
2676            ElementType->isSpecificBuiltinType(BuiltinType::UInt128)))
2677         return;
2678 
2679       // Arguments of 256-bits are split into four eightbyte chunks. The
2680       // least significant one belongs to class SSE and all the others to class
2681       // SSEUP. The original Lo and Hi design considers that types can't be
2682       // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
2683       // This design isn't correct for 256-bits, but since there're no cases
2684       // where the upper parts would need to be inspected, avoid adding
2685       // complexity and just consider Hi to match the 64-256 part.
2686       //
2687       // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
2688       // registers if they are "named", i.e. not part of the "..." of a
2689       // variadic function.
2690       //
2691       // Similarly, per 3.2.3. of the AVX512 draft, 512-bits ("named") args are
2692       // split into eight eightbyte chunks, one SSE and seven SSEUP.
2693       Lo = SSE;
2694       Hi = SSEUp;
2695     }
2696     return;
2697   }
2698 
2699   if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
2700     QualType ET = getContext().getCanonicalType(CT->getElementType());
2701 
2702     uint64_t Size = getContext().getTypeSize(Ty);
2703     if (ET->isIntegralOrEnumerationType()) {
2704       if (Size <= 64)
2705         Current = Integer;
2706       else if (Size <= 128)
2707         Lo = Hi = Integer;
2708     } else if (ET == getContext().FloatTy) {
2709       Current = SSE;
2710     } else if (ET == getContext().DoubleTy) {
2711       Lo = Hi = SSE;
2712     } else if (ET == getContext().LongDoubleTy) {
2713       const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
2714       if (LDF == &llvm::APFloat::IEEEquad())
2715         Current = Memory;
2716       else if (LDF == &llvm::APFloat::x87DoubleExtended())
2717         Current = ComplexX87;
2718       else if (LDF == &llvm::APFloat::IEEEdouble())
2719         Lo = Hi = SSE;
2720       else
2721         llvm_unreachable("unexpected long double representation!");
2722     }
2723 
2724     // If this complex type crosses an eightbyte boundary then it
2725     // should be split.
2726     uint64_t EB_Real = (OffsetBase) / 64;
2727     uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
2728     if (Hi == NoClass && EB_Real != EB_Imag)
2729       Hi = Lo;
2730 
2731     return;
2732   }
2733 
2734   if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
2735     // Arrays are treated like structures.
2736 
2737     uint64_t Size = getContext().getTypeSize(Ty);
2738 
2739     // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
2740     // than eight eightbytes, ..., it has class MEMORY.
2741     if (Size > 512)
2742       return;
2743 
2744     // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
2745     // fields, it has class MEMORY.
2746     //
2747     // Only need to check alignment of array base.
2748     if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
2749       return;
2750 
2751     // Otherwise implement simplified merge. We could be smarter about
2752     // this, but it isn't worth it and would be harder to verify.
2753     Current = NoClass;
2754     uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
2755     uint64_t ArraySize = AT->getSize().getZExtValue();
2756 
2757     // The only case a 256-bit wide vector could be used is when the array
2758     // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2759     // to work for sizes wider than 128, early check and fallback to memory.
2760     //
2761     if (Size > 128 &&
2762         (Size != EltSize || Size > getNativeVectorSizeForAVXABI(AVXLevel)))
2763       return;
2764 
2765     for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
2766       Class FieldLo, FieldHi;
2767       classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
2768       Lo = merge(Lo, FieldLo);
2769       Hi = merge(Hi, FieldHi);
2770       if (Lo == Memory || Hi == Memory)
2771         break;
2772     }
2773 
2774     postMerge(Size, Lo, Hi);
2775     assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
2776     return;
2777   }
2778 
2779   if (const RecordType *RT = Ty->getAs<RecordType>()) {
2780     uint64_t Size = getContext().getTypeSize(Ty);
2781 
2782     // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
2783     // than eight eightbytes, ..., it has class MEMORY.
2784     if (Size > 512)
2785       return;
2786 
2787     // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
2788     // copy constructor or a non-trivial destructor, it is passed by invisible
2789     // reference.
2790     if (getRecordArgABI(RT, getCXXABI()))
2791       return;
2792 
2793     const RecordDecl *RD = RT->getDecl();
2794 
2795     // Assume variable sized types are passed in memory.
2796     if (RD->hasFlexibleArrayMember())
2797       return;
2798 
2799     const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
2800 
2801     // Reset Lo class, this will be recomputed.
2802     Current = NoClass;
2803 
2804     // If this is a C++ record, classify the bases first.
2805     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
2806       for (const auto &I : CXXRD->bases()) {
2807         assert(!I.isVirtual() && !I.getType()->isDependentType() &&
2808                "Unexpected base class!");
2809         const auto *Base =
2810             cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
2811 
2812         // Classify this field.
2813         //
2814         // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
2815         // single eightbyte, each is classified separately. Each eightbyte gets
2816         // initialized to class NO_CLASS.
2817         Class FieldLo, FieldHi;
2818         uint64_t Offset =
2819           OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
2820         classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg);
2821         Lo = merge(Lo, FieldLo);
2822         Hi = merge(Hi, FieldHi);
2823         if (Lo == Memory || Hi == Memory) {
2824           postMerge(Size, Lo, Hi);
2825           return;
2826         }
2827       }
2828     }
2829 
2830     // Classify the fields one at a time, merging the results.
2831     unsigned idx = 0;
2832     for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
2833            i != e; ++i, ++idx) {
2834       uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
2835       bool BitField = i->isBitField();
2836 
2837       // Ignore padding bit-fields.
2838       if (BitField && i->isUnnamedBitfield())
2839         continue;
2840 
2841       // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
2842       // four eightbytes, or it contains unaligned fields, it has class MEMORY.
2843       //
2844       // The only case a 256-bit wide vector could be used is when the struct
2845       // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2846       // to work for sizes wider than 128, early check and fallback to memory.
2847       //
2848       if (Size > 128 && (Size != getContext().getTypeSize(i->getType()) ||
2849                          Size > getNativeVectorSizeForAVXABI(AVXLevel))) {
2850         Lo = Memory;
2851         postMerge(Size, Lo, Hi);
2852         return;
2853       }
2854       // Note, skip this test for bit-fields, see below.
2855       if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
2856         Lo = Memory;
2857         postMerge(Size, Lo, Hi);
2858         return;
2859       }
2860 
2861       // Classify this field.
2862       //
2863       // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
2864       // exceeds a single eightbyte, each is classified
2865       // separately. Each eightbyte gets initialized to class
2866       // NO_CLASS.
2867       Class FieldLo, FieldHi;
2868 
2869       // Bit-fields require special handling, they do not force the
2870       // structure to be passed in memory even if unaligned, and
2871       // therefore they can straddle an eightbyte.
2872       if (BitField) {
2873         assert(!i->isUnnamedBitfield());
2874         uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
2875         uint64_t Size = i->getBitWidthValue(getContext());
2876 
2877         uint64_t EB_Lo = Offset / 64;
2878         uint64_t EB_Hi = (Offset + Size - 1) / 64;
2879 
2880         if (EB_Lo) {
2881           assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
2882           FieldLo = NoClass;
2883           FieldHi = Integer;
2884         } else {
2885           FieldLo = Integer;
2886           FieldHi = EB_Hi ? Integer : NoClass;
2887         }
2888       } else
2889         classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
2890       Lo = merge(Lo, FieldLo);
2891       Hi = merge(Hi, FieldHi);
2892       if (Lo == Memory || Hi == Memory)
2893         break;
2894     }
2895 
2896     postMerge(Size, Lo, Hi);
2897   }
2898 }
2899 
2900 ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
2901   // If this is a scalar LLVM value then assume LLVM will pass it in the right
2902   // place naturally.
2903   if (!isAggregateTypeForABI(Ty)) {
2904     // Treat an enum type as its underlying type.
2905     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2906       Ty = EnumTy->getDecl()->getIntegerType();
2907 
2908     return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty)
2909                                           : ABIArgInfo::getDirect());
2910   }
2911 
2912   return getNaturalAlignIndirect(Ty);
2913 }
2914 
2915 bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
2916   if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
2917     uint64_t Size = getContext().getTypeSize(VecTy);
2918     unsigned LargestVector = getNativeVectorSizeForAVXABI(AVXLevel);
2919     if (Size <= 64 || Size > LargestVector)
2920       return true;
2921     QualType EltTy = VecTy->getElementType();
2922     if (passInt128VectorsInMem() &&
2923         (EltTy->isSpecificBuiltinType(BuiltinType::Int128) ||
2924          EltTy->isSpecificBuiltinType(BuiltinType::UInt128)))
2925       return true;
2926   }
2927 
2928   return false;
2929 }
2930 
2931 ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
2932                                             unsigned freeIntRegs) const {
2933   // If this is a scalar LLVM value then assume LLVM will pass it in the right
2934   // place naturally.
2935   //
2936   // This assumption is optimistic, as there could be free registers available
2937   // when we need to pass this argument in memory, and LLVM could try to pass
2938   // the argument in the free register. This does not seem to happen currently,
2939   // but this code would be much safer if we could mark the argument with
2940   // 'onstack'. See PR12193.
2941   if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty)) {
2942     // Treat an enum type as its underlying type.
2943     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2944       Ty = EnumTy->getDecl()->getIntegerType();
2945 
2946     return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty)
2947                                           : ABIArgInfo::getDirect());
2948   }
2949 
2950   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
2951     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
2952 
2953   // Compute the byval alignment. We specify the alignment of the byval in all
2954   // cases so that the mid-level optimizer knows the alignment of the byval.
2955   unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
2956 
2957   // Attempt to avoid passing indirect results using byval when possible. This
2958   // is important for good codegen.
2959   //
2960   // We do this by coercing the value into a scalar type which the backend can
2961   // handle naturally (i.e., without using byval).
2962   //
2963   // For simplicity, we currently only do this when we have exhausted all of the
2964   // free integer registers. Doing this when there are free integer registers
2965   // would require more care, as we would have to ensure that the coerced value
2966   // did not claim the unused register. That would require either reording the
2967   // arguments to the function (so that any subsequent inreg values came first),
2968   // or only doing this optimization when there were no following arguments that
2969   // might be inreg.
2970   //
2971   // We currently expect it to be rare (particularly in well written code) for
2972   // arguments to be passed on the stack when there are still free integer
2973   // registers available (this would typically imply large structs being passed
2974   // by value), so this seems like a fair tradeoff for now.
2975   //
2976   // We can revisit this if the backend grows support for 'onstack' parameter
2977   // attributes. See PR12193.
2978   if (freeIntRegs == 0) {
2979     uint64_t Size = getContext().getTypeSize(Ty);
2980 
2981     // If this type fits in an eightbyte, coerce it into the matching integral
2982     // type, which will end up on the stack (with alignment 8).
2983     if (Align == 8 && Size <= 64)
2984       return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2985                                                           Size));
2986   }
2987 
2988   return ABIArgInfo::getIndirect(CharUnits::fromQuantity(Align));
2989 }
2990 
2991 /// The ABI specifies that a value should be passed in a full vector XMM/YMM
2992 /// register. Pick an LLVM IR type that will be passed as a vector register.
2993 llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
2994   // Wrapper structs/arrays that only contain vectors are passed just like
2995   // vectors; strip them off if present.
2996   if (const Type *InnerTy = isSingleElementStruct(Ty, getContext()))
2997     Ty = QualType(InnerTy, 0);
2998 
2999   llvm::Type *IRType = CGT.ConvertType(Ty);
3000   if (isa<llvm::VectorType>(IRType)) {
3001     // Don't pass vXi128 vectors in their native type, the backend can't
3002     // legalize them.
3003     if (passInt128VectorsInMem() &&
3004         IRType->getVectorElementType()->isIntegerTy(128)) {
3005       // Use a vXi64 vector.
3006       uint64_t Size = getContext().getTypeSize(Ty);
3007       return llvm::VectorType::get(llvm::Type::getInt64Ty(getVMContext()),
3008                                    Size / 64);
3009     }
3010 
3011     return IRType;
3012   }
3013 
3014   if (IRType->getTypeID() == llvm::Type::FP128TyID)
3015     return IRType;
3016 
3017   // We couldn't find the preferred IR vector type for 'Ty'.
3018   uint64_t Size = getContext().getTypeSize(Ty);
3019   assert((Size == 128 || Size == 256 || Size == 512) && "Invalid type found!");
3020 
3021 
3022   // Return a LLVM IR vector type based on the size of 'Ty'.
3023   return llvm::VectorType::get(llvm::Type::getDoubleTy(getVMContext()),
3024                                Size / 64);
3025 }
3026 
3027 /// BitsContainNoUserData - Return true if the specified [start,end) bit range
3028 /// is known to either be off the end of the specified type or being in
3029 /// alignment padding.  The user type specified is known to be at most 128 bits
3030 /// in size, and have passed through X86_64ABIInfo::classify with a successful
3031 /// classification that put one of the two halves in the INTEGER class.
3032 ///
3033 /// It is conservatively correct to return false.
3034 static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
3035                                   unsigned EndBit, ASTContext &Context) {
3036   // If the bytes being queried are off the end of the type, there is no user
3037   // data hiding here.  This handles analysis of builtins, vectors and other
3038   // types that don't contain interesting padding.
3039   unsigned TySize = (unsigned)Context.getTypeSize(Ty);
3040   if (TySize <= StartBit)
3041     return true;
3042 
3043   if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
3044     unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
3045     unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
3046 
3047     // Check each element to see if the element overlaps with the queried range.
3048     for (unsigned i = 0; i != NumElts; ++i) {
3049       // If the element is after the span we care about, then we're done..
3050       unsigned EltOffset = i*EltSize;
3051       if (EltOffset >= EndBit) break;
3052 
3053       unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
3054       if (!BitsContainNoUserData(AT->getElementType(), EltStart,
3055                                  EndBit-EltOffset, Context))
3056         return false;
3057     }
3058     // If it overlaps no elements, then it is safe to process as padding.
3059     return true;
3060   }
3061 
3062   if (const RecordType *RT = Ty->getAs<RecordType>()) {
3063     const RecordDecl *RD = RT->getDecl();
3064     const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
3065 
3066     // If this is a C++ record, check the bases first.
3067     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3068       for (const auto &I : CXXRD->bases()) {
3069         assert(!I.isVirtual() && !I.getType()->isDependentType() &&
3070                "Unexpected base class!");
3071         const auto *Base =
3072             cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
3073 
3074         // If the base is after the span we care about, ignore it.
3075         unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
3076         if (BaseOffset >= EndBit) continue;
3077 
3078         unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
3079         if (!BitsContainNoUserData(I.getType(), BaseStart,
3080                                    EndBit-BaseOffset, Context))
3081           return false;
3082       }
3083     }
3084 
3085     // Verify that no field has data that overlaps the region of interest.  Yes
3086     // this could be sped up a lot by being smarter about queried fields,
3087     // however we're only looking at structs up to 16 bytes, so we don't care
3088     // much.
3089     unsigned idx = 0;
3090     for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
3091          i != e; ++i, ++idx) {
3092       unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
3093 
3094       // If we found a field after the region we care about, then we're done.
3095       if (FieldOffset >= EndBit) break;
3096 
3097       unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
3098       if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
3099                                  Context))
3100         return false;
3101     }
3102 
3103     // If nothing in this record overlapped the area of interest, then we're
3104     // clean.
3105     return true;
3106   }
3107 
3108   return false;
3109 }
3110 
3111 /// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a
3112 /// float member at the specified offset.  For example, {int,{float}} has a
3113 /// float at offset 4.  It is conservatively correct for this routine to return
3114 /// false.
3115 static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset,
3116                                   const llvm::DataLayout &TD) {
3117   // Base case if we find a float.
3118   if (IROffset == 0 && IRType->isFloatTy())
3119     return true;
3120 
3121   // If this is a struct, recurse into the field at the specified offset.
3122   if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
3123     const llvm::StructLayout *SL = TD.getStructLayout(STy);
3124     unsigned Elt = SL->getElementContainingOffset(IROffset);
3125     IROffset -= SL->getElementOffset(Elt);
3126     return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD);
3127   }
3128 
3129   // If this is an array, recurse into the field at the specified offset.
3130   if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
3131     llvm::Type *EltTy = ATy->getElementType();
3132     unsigned EltSize = TD.getTypeAllocSize(EltTy);
3133     IROffset -= IROffset/EltSize*EltSize;
3134     return ContainsFloatAtOffset(EltTy, IROffset, TD);
3135   }
3136 
3137   return false;
3138 }
3139 
3140 
3141 /// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
3142 /// low 8 bytes of an XMM register, corresponding to the SSE class.
3143 llvm::Type *X86_64ABIInfo::
3144 GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
3145                    QualType SourceTy, unsigned SourceOffset) const {
3146   // The only three choices we have are either double, <2 x float>, or float. We
3147   // pass as float if the last 4 bytes is just padding.  This happens for
3148   // structs that contain 3 floats.
3149   if (BitsContainNoUserData(SourceTy, SourceOffset*8+32,
3150                             SourceOffset*8+64, getContext()))
3151     return llvm::Type::getFloatTy(getVMContext());
3152 
3153   // We want to pass as <2 x float> if the LLVM IR type contains a float at
3154   // offset+0 and offset+4.  Walk the LLVM IR type to find out if this is the
3155   // case.
3156   if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) &&
3157       ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout()))
3158     return llvm::VectorType::get(llvm::Type::getFloatTy(getVMContext()), 2);
3159 
3160   return llvm::Type::getDoubleTy(getVMContext());
3161 }
3162 
3163 
3164 /// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
3165 /// an 8-byte GPR.  This means that we either have a scalar or we are talking
3166 /// about the high or low part of an up-to-16-byte struct.  This routine picks
3167 /// the best LLVM IR type to represent this, which may be i64 or may be anything
3168 /// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
3169 /// etc).
3170 ///
3171 /// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
3172 /// the source type.  IROffset is an offset in bytes into the LLVM IR type that
3173 /// the 8-byte value references.  PrefType may be null.
3174 ///
3175 /// SourceTy is the source-level type for the entire argument.  SourceOffset is
3176 /// an offset into this that we're processing (which is always either 0 or 8).
3177 ///
3178 llvm::Type *X86_64ABIInfo::
3179 GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
3180                        QualType SourceTy, unsigned SourceOffset) const {
3181   // If we're dealing with an un-offset LLVM IR type, then it means that we're
3182   // returning an 8-byte unit starting with it.  See if we can safely use it.
3183   if (IROffset == 0) {
3184     // Pointers and int64's always fill the 8-byte unit.
3185     if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
3186         IRType->isIntegerTy(64))
3187       return IRType;
3188 
3189     // If we have a 1/2/4-byte integer, we can use it only if the rest of the
3190     // goodness in the source type is just tail padding.  This is allowed to
3191     // kick in for struct {double,int} on the int, but not on
3192     // struct{double,int,int} because we wouldn't return the second int.  We
3193     // have to do this analysis on the source type because we can't depend on
3194     // unions being lowered a specific way etc.
3195     if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
3196         IRType->isIntegerTy(32) ||
3197         (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
3198       unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
3199           cast<llvm::IntegerType>(IRType)->getBitWidth();
3200 
3201       if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
3202                                 SourceOffset*8+64, getContext()))
3203         return IRType;
3204     }
3205   }
3206 
3207   if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
3208     // If this is a struct, recurse into the field at the specified offset.
3209     const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
3210     if (IROffset < SL->getSizeInBytes()) {
3211       unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
3212       IROffset -= SL->getElementOffset(FieldIdx);
3213 
3214       return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
3215                                     SourceTy, SourceOffset);
3216     }
3217   }
3218 
3219   if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
3220     llvm::Type *EltTy = ATy->getElementType();
3221     unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
3222     unsigned EltOffset = IROffset/EltSize*EltSize;
3223     return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
3224                                   SourceOffset);
3225   }
3226 
3227   // Okay, we don't have any better idea of what to pass, so we pass this in an
3228   // integer register that isn't too big to fit the rest of the struct.
3229   unsigned TySizeInBytes =
3230     (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
3231 
3232   assert(TySizeInBytes != SourceOffset && "Empty field?");
3233 
3234   // It is always safe to classify this as an integer type up to i64 that
3235   // isn't larger than the structure.
3236   return llvm::IntegerType::get(getVMContext(),
3237                                 std::min(TySizeInBytes-SourceOffset, 8U)*8);
3238 }
3239 
3240 
3241 /// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
3242 /// be used as elements of a two register pair to pass or return, return a
3243 /// first class aggregate to represent them.  For example, if the low part of
3244 /// a by-value argument should be passed as i32* and the high part as float,
3245 /// return {i32*, float}.
3246 static llvm::Type *
3247 GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
3248                            const llvm::DataLayout &TD) {
3249   // In order to correctly satisfy the ABI, we need to the high part to start
3250   // at offset 8.  If the high and low parts we inferred are both 4-byte types
3251   // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
3252   // the second element at offset 8.  Check for this:
3253   unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
3254   unsigned HiAlign = TD.getABITypeAlignment(Hi);
3255   unsigned HiStart = llvm::alignTo(LoSize, HiAlign);
3256   assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
3257 
3258   // To handle this, we have to increase the size of the low part so that the
3259   // second element will start at an 8 byte offset.  We can't increase the size
3260   // of the second element because it might make us access off the end of the
3261   // struct.
3262   if (HiStart != 8) {
3263     // There are usually two sorts of types the ABI generation code can produce
3264     // for the low part of a pair that aren't 8 bytes in size: float or
3265     // i8/i16/i32.  This can also include pointers when they are 32-bit (X32 and
3266     // NaCl).
3267     // Promote these to a larger type.
3268     if (Lo->isFloatTy())
3269       Lo = llvm::Type::getDoubleTy(Lo->getContext());
3270     else {
3271       assert((Lo->isIntegerTy() || Lo->isPointerTy())
3272              && "Invalid/unknown lo type");
3273       Lo = llvm::Type::getInt64Ty(Lo->getContext());
3274     }
3275   }
3276 
3277   llvm::StructType *Result = llvm::StructType::get(Lo, Hi);
3278 
3279   // Verify that the second element is at an 8-byte offset.
3280   assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
3281          "Invalid x86-64 argument pair!");
3282   return Result;
3283 }
3284 
3285 ABIArgInfo X86_64ABIInfo::
3286 classifyReturnType(QualType RetTy) const {
3287   // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
3288   // classification algorithm.
3289   X86_64ABIInfo::Class Lo, Hi;
3290   classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
3291 
3292   // Check some invariants.
3293   assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
3294   assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
3295 
3296   llvm::Type *ResType = nullptr;
3297   switch (Lo) {
3298   case NoClass:
3299     if (Hi == NoClass)
3300       return ABIArgInfo::getIgnore();
3301     // If the low part is just padding, it takes no register, leave ResType
3302     // null.
3303     assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3304            "Unknown missing lo part");
3305     break;
3306 
3307   case SSEUp:
3308   case X87Up:
3309     llvm_unreachable("Invalid classification for lo word.");
3310 
3311     // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
3312     // hidden argument.
3313   case Memory:
3314     return getIndirectReturnResult(RetTy);
3315 
3316     // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
3317     // available register of the sequence %rax, %rdx is used.
3318   case Integer:
3319     ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
3320 
3321     // If we have a sign or zero extended integer, make sure to return Extend
3322     // so that the parameter gets the right LLVM IR attributes.
3323     if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3324       // Treat an enum type as its underlying type.
3325       if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
3326         RetTy = EnumTy->getDecl()->getIntegerType();
3327 
3328       if (RetTy->isIntegralOrEnumerationType() &&
3329           RetTy->isPromotableIntegerType())
3330         return ABIArgInfo::getExtend(RetTy);
3331     }
3332     break;
3333 
3334     // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
3335     // available SSE register of the sequence %xmm0, %xmm1 is used.
3336   case SSE:
3337     ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
3338     break;
3339 
3340     // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
3341     // returned on the X87 stack in %st0 as 80-bit x87 number.
3342   case X87:
3343     ResType = llvm::Type::getX86_FP80Ty(getVMContext());
3344     break;
3345 
3346     // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
3347     // part of the value is returned in %st0 and the imaginary part in
3348     // %st1.
3349   case ComplexX87:
3350     assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
3351     ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
3352                                     llvm::Type::getX86_FP80Ty(getVMContext()));
3353     break;
3354   }
3355 
3356   llvm::Type *HighPart = nullptr;
3357   switch (Hi) {
3358     // Memory was handled previously and X87 should
3359     // never occur as a hi class.
3360   case Memory:
3361   case X87:
3362     llvm_unreachable("Invalid classification for hi word.");
3363 
3364   case ComplexX87: // Previously handled.
3365   case NoClass:
3366     break;
3367 
3368   case Integer:
3369     HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
3370     if (Lo == NoClass)  // Return HighPart at offset 8 in memory.
3371       return ABIArgInfo::getDirect(HighPart, 8);
3372     break;
3373   case SSE:
3374     HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
3375     if (Lo == NoClass)  // Return HighPart at offset 8 in memory.
3376       return ABIArgInfo::getDirect(HighPart, 8);
3377     break;
3378 
3379     // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
3380     // is passed in the next available eightbyte chunk if the last used
3381     // vector register.
3382     //
3383     // SSEUP should always be preceded by SSE, just widen.
3384   case SSEUp:
3385     assert(Lo == SSE && "Unexpected SSEUp classification.");
3386     ResType = GetByteVectorType(RetTy);
3387     break;
3388 
3389     // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
3390     // returned together with the previous X87 value in %st0.
3391   case X87Up:
3392     // If X87Up is preceded by X87, we don't need to do
3393     // anything. However, in some cases with unions it may not be
3394     // preceded by X87. In such situations we follow gcc and pass the
3395     // extra bits in an SSE reg.
3396     if (Lo != X87) {
3397       HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
3398       if (Lo == NoClass)  // Return HighPart at offset 8 in memory.
3399         return ABIArgInfo::getDirect(HighPart, 8);
3400     }
3401     break;
3402   }
3403 
3404   // If a high part was specified, merge it together with the low part.  It is
3405   // known to pass in the high eightbyte of the result.  We do this by forming a
3406   // first class struct aggregate with the high and low part: {low, high}
3407   if (HighPart)
3408     ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
3409 
3410   return ABIArgInfo::getDirect(ResType);
3411 }
3412 
3413 ABIArgInfo X86_64ABIInfo::classifyArgumentType(
3414   QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE,
3415   bool isNamedArg)
3416   const
3417 {
3418   Ty = useFirstFieldIfTransparentUnion(Ty);
3419 
3420   X86_64ABIInfo::Class Lo, Hi;
3421   classify(Ty, 0, Lo, Hi, isNamedArg);
3422 
3423   // Check some invariants.
3424   // FIXME: Enforce these by construction.
3425   assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
3426   assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
3427 
3428   neededInt = 0;
3429   neededSSE = 0;
3430   llvm::Type *ResType = nullptr;
3431   switch (Lo) {
3432   case NoClass:
3433     if (Hi == NoClass)
3434       return ABIArgInfo::getIgnore();
3435     // If the low part is just padding, it takes no register, leave ResType
3436     // null.
3437     assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3438            "Unknown missing lo part");
3439     break;
3440 
3441     // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
3442     // on the stack.
3443   case Memory:
3444 
3445     // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
3446     // COMPLEX_X87, it is passed in memory.
3447   case X87:
3448   case ComplexX87:
3449     if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect)
3450       ++neededInt;
3451     return getIndirectResult(Ty, freeIntRegs);
3452 
3453   case SSEUp:
3454   case X87Up:
3455     llvm_unreachable("Invalid classification for lo word.");
3456 
3457     // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
3458     // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
3459     // and %r9 is used.
3460   case Integer:
3461     ++neededInt;
3462 
3463     // Pick an 8-byte type based on the preferred type.
3464     ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
3465 
3466     // If we have a sign or zero extended integer, make sure to return Extend
3467     // so that the parameter gets the right LLVM IR attributes.
3468     if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3469       // Treat an enum type as its underlying type.
3470       if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3471         Ty = EnumTy->getDecl()->getIntegerType();
3472 
3473       if (Ty->isIntegralOrEnumerationType() &&
3474           Ty->isPromotableIntegerType())
3475         return ABIArgInfo::getExtend(Ty);
3476     }
3477 
3478     break;
3479 
3480     // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
3481     // available SSE register is used, the registers are taken in the
3482     // order from %xmm0 to %xmm7.
3483   case SSE: {
3484     llvm::Type *IRType = CGT.ConvertType(Ty);
3485     ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
3486     ++neededSSE;
3487     break;
3488   }
3489   }
3490 
3491   llvm::Type *HighPart = nullptr;
3492   switch (Hi) {
3493     // Memory was handled previously, ComplexX87 and X87 should
3494     // never occur as hi classes, and X87Up must be preceded by X87,
3495     // which is passed in memory.
3496   case Memory:
3497   case X87:
3498   case ComplexX87:
3499     llvm_unreachable("Invalid classification for hi word.");
3500 
3501   case NoClass: break;
3502 
3503   case Integer:
3504     ++neededInt;
3505     // Pick an 8-byte type based on the preferred type.
3506     HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
3507 
3508     if (Lo == NoClass)  // Pass HighPart at offset 8 in memory.
3509       return ABIArgInfo::getDirect(HighPart, 8);
3510     break;
3511 
3512     // X87Up generally doesn't occur here (long double is passed in
3513     // memory), except in situations involving unions.
3514   case X87Up:
3515   case SSE:
3516     HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
3517 
3518     if (Lo == NoClass)  // Pass HighPart at offset 8 in memory.
3519       return ABIArgInfo::getDirect(HighPart, 8);
3520 
3521     ++neededSSE;
3522     break;
3523 
3524     // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
3525     // eightbyte is passed in the upper half of the last used SSE
3526     // register.  This only happens when 128-bit vectors are passed.
3527   case SSEUp:
3528     assert(Lo == SSE && "Unexpected SSEUp classification");
3529     ResType = GetByteVectorType(Ty);
3530     break;
3531   }
3532 
3533   // If a high part was specified, merge it together with the low part.  It is
3534   // known to pass in the high eightbyte of the result.  We do this by forming a
3535   // first class struct aggregate with the high and low part: {low, high}
3536   if (HighPart)
3537     ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
3538 
3539   return ABIArgInfo::getDirect(ResType);
3540 }
3541 
3542 ABIArgInfo
3543 X86_64ABIInfo::classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
3544                                              unsigned &NeededSSE) const {
3545   auto RT = Ty->getAs<RecordType>();
3546   assert(RT && "classifyRegCallStructType only valid with struct types");
3547 
3548   if (RT->getDecl()->hasFlexibleArrayMember())
3549     return getIndirectReturnResult(Ty);
3550 
3551   // Sum up bases
3552   if (auto CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
3553     if (CXXRD->isDynamicClass()) {
3554       NeededInt = NeededSSE = 0;
3555       return getIndirectReturnResult(Ty);
3556     }
3557 
3558     for (const auto &I : CXXRD->bases())
3559       if (classifyRegCallStructTypeImpl(I.getType(), NeededInt, NeededSSE)
3560               .isIndirect()) {
3561         NeededInt = NeededSSE = 0;
3562         return getIndirectReturnResult(Ty);
3563       }
3564   }
3565 
3566   // Sum up members
3567   for (const auto *FD : RT->getDecl()->fields()) {
3568     if (FD->getType()->isRecordType() && !FD->getType()->isUnionType()) {
3569       if (classifyRegCallStructTypeImpl(FD->getType(), NeededInt, NeededSSE)
3570               .isIndirect()) {
3571         NeededInt = NeededSSE = 0;
3572         return getIndirectReturnResult(Ty);
3573       }
3574     } else {
3575       unsigned LocalNeededInt, LocalNeededSSE;
3576       if (classifyArgumentType(FD->getType(), UINT_MAX, LocalNeededInt,
3577                                LocalNeededSSE, true)
3578               .isIndirect()) {
3579         NeededInt = NeededSSE = 0;
3580         return getIndirectReturnResult(Ty);
3581       }
3582       NeededInt += LocalNeededInt;
3583       NeededSSE += LocalNeededSSE;
3584     }
3585   }
3586 
3587   return ABIArgInfo::getDirect();
3588 }
3589 
3590 ABIArgInfo X86_64ABIInfo::classifyRegCallStructType(QualType Ty,
3591                                                     unsigned &NeededInt,
3592                                                     unsigned &NeededSSE) const {
3593 
3594   NeededInt = 0;
3595   NeededSSE = 0;
3596 
3597   return classifyRegCallStructTypeImpl(Ty, NeededInt, NeededSSE);
3598 }
3599 
3600 void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
3601 
3602   const unsigned CallingConv = FI.getCallingConvention();
3603   // It is possible to force Win64 calling convention on any x86_64 target by
3604   // using __attribute__((ms_abi)). In such case to correctly emit Win64
3605   // compatible code delegate this call to WinX86_64ABIInfo::computeInfo.
3606   if (CallingConv == llvm::CallingConv::Win64) {
3607     WinX86_64ABIInfo Win64ABIInfo(CGT, AVXLevel);
3608     Win64ABIInfo.computeInfo(FI);
3609     return;
3610   }
3611 
3612   bool IsRegCall = CallingConv == llvm::CallingConv::X86_RegCall;
3613 
3614   // Keep track of the number of assigned registers.
3615   unsigned FreeIntRegs = IsRegCall ? 11 : 6;
3616   unsigned FreeSSERegs = IsRegCall ? 16 : 8;
3617   unsigned NeededInt, NeededSSE;
3618 
3619   if (!::classifyReturnType(getCXXABI(), FI, *this)) {
3620     if (IsRegCall && FI.getReturnType()->getTypePtr()->isRecordType() &&
3621         !FI.getReturnType()->getTypePtr()->isUnionType()) {
3622       FI.getReturnInfo() =
3623           classifyRegCallStructType(FI.getReturnType(), NeededInt, NeededSSE);
3624       if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
3625         FreeIntRegs -= NeededInt;
3626         FreeSSERegs -= NeededSSE;
3627       } else {
3628         FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType());
3629       }
3630     } else if (IsRegCall && FI.getReturnType()->getAs<ComplexType>()) {
3631       // Complex Long Double Type is passed in Memory when Regcall
3632       // calling convention is used.
3633       const ComplexType *CT = FI.getReturnType()->getAs<ComplexType>();
3634       if (getContext().getCanonicalType(CT->getElementType()) ==
3635           getContext().LongDoubleTy)
3636         FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType());
3637     } else
3638       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
3639   }
3640 
3641   // If the return value is indirect, then the hidden argument is consuming one
3642   // integer register.
3643   if (FI.getReturnInfo().isIndirect())
3644     --FreeIntRegs;
3645 
3646   // The chain argument effectively gives us another free register.
3647   if (FI.isChainCall())
3648     ++FreeIntRegs;
3649 
3650   unsigned NumRequiredArgs = FI.getNumRequiredArgs();
3651   // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
3652   // get assigned (in left-to-right order) for passing as follows...
3653   unsigned ArgNo = 0;
3654   for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
3655        it != ie; ++it, ++ArgNo) {
3656     bool IsNamedArg = ArgNo < NumRequiredArgs;
3657 
3658     if (IsRegCall && it->type->isStructureOrClassType())
3659       it->info = classifyRegCallStructType(it->type, NeededInt, NeededSSE);
3660     else
3661       it->info = classifyArgumentType(it->type, FreeIntRegs, NeededInt,
3662                                       NeededSSE, IsNamedArg);
3663 
3664     // AMD64-ABI 3.2.3p3: If there are no registers available for any
3665     // eightbyte of an argument, the whole argument is passed on the
3666     // stack. If registers have already been assigned for some
3667     // eightbytes of such an argument, the assignments get reverted.
3668     if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
3669       FreeIntRegs -= NeededInt;
3670       FreeSSERegs -= NeededSSE;
3671     } else {
3672       it->info = getIndirectResult(it->type, FreeIntRegs);
3673     }
3674   }
3675 }
3676 
3677 static Address EmitX86_64VAArgFromMemory(CodeGenFunction &CGF,
3678                                          Address VAListAddr, QualType Ty) {
3679   Address overflow_arg_area_p =
3680       CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_p");
3681   llvm::Value *overflow_arg_area =
3682     CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
3683 
3684   // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
3685   // byte boundary if alignment needed by type exceeds 8 byte boundary.
3686   // It isn't stated explicitly in the standard, but in practice we use
3687   // alignment greater than 16 where necessary.
3688   CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
3689   if (Align > CharUnits::fromQuantity(8)) {
3690     overflow_arg_area = emitRoundPointerUpToAlignment(CGF, overflow_arg_area,
3691                                                       Align);
3692   }
3693 
3694   // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
3695   llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
3696   llvm::Value *Res =
3697     CGF.Builder.CreateBitCast(overflow_arg_area,
3698                               llvm::PointerType::getUnqual(LTy));
3699 
3700   // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
3701   // l->overflow_arg_area + sizeof(type).
3702   // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
3703   // an 8 byte boundary.
3704 
3705   uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
3706   llvm::Value *Offset =
3707       llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7)  & ~7);
3708   overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
3709                                             "overflow_arg_area.next");
3710   CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
3711 
3712   // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
3713   return Address(Res, Align);
3714 }
3715 
3716 Address X86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3717                                  QualType Ty) const {
3718   // Assume that va_list type is correct; should be pointer to LLVM type:
3719   // struct {
3720   //   i32 gp_offset;
3721   //   i32 fp_offset;
3722   //   i8* overflow_arg_area;
3723   //   i8* reg_save_area;
3724   // };
3725   unsigned neededInt, neededSSE;
3726 
3727   Ty = getContext().getCanonicalType(Ty);
3728   ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
3729                                        /*isNamedArg*/false);
3730 
3731   // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
3732   // in the registers. If not go to step 7.
3733   if (!neededInt && !neededSSE)
3734     return EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
3735 
3736   // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
3737   // general purpose registers needed to pass type and num_fp to hold
3738   // the number of floating point registers needed.
3739 
3740   // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
3741   // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
3742   // l->fp_offset > 304 - num_fp * 16 go to step 7.
3743   //
3744   // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
3745   // register save space).
3746 
3747   llvm::Value *InRegs = nullptr;
3748   Address gp_offset_p = Address::invalid(), fp_offset_p = Address::invalid();
3749   llvm::Value *gp_offset = nullptr, *fp_offset = nullptr;
3750   if (neededInt) {
3751     gp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "gp_offset_p");
3752     gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
3753     InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
3754     InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
3755   }
3756 
3757   if (neededSSE) {
3758     fp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 1, "fp_offset_p");
3759     fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
3760     llvm::Value *FitsInFP =
3761       llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
3762     FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
3763     InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
3764   }
3765 
3766   llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
3767   llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
3768   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
3769   CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
3770 
3771   // Emit code to load the value if it was passed in registers.
3772 
3773   CGF.EmitBlock(InRegBlock);
3774 
3775   // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
3776   // an offset of l->gp_offset and/or l->fp_offset. This may require
3777   // copying to a temporary location in case the parameter is passed
3778   // in different register classes or requires an alignment greater
3779   // than 8 for general purpose registers and 16 for XMM registers.
3780   //
3781   // FIXME: This really results in shameful code when we end up needing to
3782   // collect arguments from different places; often what should result in a
3783   // simple assembling of a structure from scattered addresses has many more
3784   // loads than necessary. Can we clean this up?
3785   llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
3786   llvm::Value *RegSaveArea = CGF.Builder.CreateLoad(
3787       CGF.Builder.CreateStructGEP(VAListAddr, 3), "reg_save_area");
3788 
3789   Address RegAddr = Address::invalid();
3790   if (neededInt && neededSSE) {
3791     // FIXME: Cleanup.
3792     assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
3793     llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
3794     Address Tmp = CGF.CreateMemTemp(Ty);
3795     Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
3796     assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
3797     llvm::Type *TyLo = ST->getElementType(0);
3798     llvm::Type *TyHi = ST->getElementType(1);
3799     assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
3800            "Unexpected ABI info for mixed regs");
3801     llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
3802     llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
3803     llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegSaveArea, gp_offset);
3804     llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegSaveArea, fp_offset);
3805     llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr;
3806     llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr;
3807 
3808     // Copy the first element.
3809     // FIXME: Our choice of alignment here and below is probably pessimistic.
3810     llvm::Value *V = CGF.Builder.CreateAlignedLoad(
3811         TyLo, CGF.Builder.CreateBitCast(RegLoAddr, PTyLo),
3812         CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyLo)));
3813     CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
3814 
3815     // Copy the second element.
3816     V = CGF.Builder.CreateAlignedLoad(
3817         TyHi, CGF.Builder.CreateBitCast(RegHiAddr, PTyHi),
3818         CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyHi)));
3819     CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
3820 
3821     RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
3822   } else if (neededInt) {
3823     RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, gp_offset),
3824                       CharUnits::fromQuantity(8));
3825     RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
3826 
3827     // Copy to a temporary if necessary to ensure the appropriate alignment.
3828     std::pair<CharUnits, CharUnits> SizeAlign =
3829         getContext().getTypeInfoInChars(Ty);
3830     uint64_t TySize = SizeAlign.first.getQuantity();
3831     CharUnits TyAlign = SizeAlign.second;
3832 
3833     // Copy into a temporary if the type is more aligned than the
3834     // register save area.
3835     if (TyAlign.getQuantity() > 8) {
3836       Address Tmp = CGF.CreateMemTemp(Ty);
3837       CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, false);
3838       RegAddr = Tmp;
3839     }
3840 
3841   } else if (neededSSE == 1) {
3842     RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
3843                       CharUnits::fromQuantity(16));
3844     RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
3845   } else {
3846     assert(neededSSE == 2 && "Invalid number of needed registers!");
3847     // SSE registers are spaced 16 bytes apart in the register save
3848     // area, we need to collect the two eightbytes together.
3849     // The ABI isn't explicit about this, but it seems reasonable
3850     // to assume that the slots are 16-byte aligned, since the stack is
3851     // naturally 16-byte aligned and the prologue is expected to store
3852     // all the SSE registers to the RSA.
3853     Address RegAddrLo = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
3854                                 CharUnits::fromQuantity(16));
3855     Address RegAddrHi =
3856       CGF.Builder.CreateConstInBoundsByteGEP(RegAddrLo,
3857                                              CharUnits::fromQuantity(16));
3858     llvm::Type *ST = AI.canHaveCoerceToType()
3859                          ? AI.getCoerceToType()
3860                          : llvm::StructType::get(CGF.DoubleTy, CGF.DoubleTy);
3861     llvm::Value *V;
3862     Address Tmp = CGF.CreateMemTemp(Ty);
3863     Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
3864     V = CGF.Builder.CreateLoad(CGF.Builder.CreateElementBitCast(
3865         RegAddrLo, ST->getStructElementType(0)));
3866     CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
3867     V = CGF.Builder.CreateLoad(CGF.Builder.CreateElementBitCast(
3868         RegAddrHi, ST->getStructElementType(1)));
3869     CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
3870 
3871     RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
3872   }
3873 
3874   // AMD64-ABI 3.5.7p5: Step 5. Set:
3875   // l->gp_offset = l->gp_offset + num_gp * 8
3876   // l->fp_offset = l->fp_offset + num_fp * 16.
3877   if (neededInt) {
3878     llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
3879     CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
3880                             gp_offset_p);
3881   }
3882   if (neededSSE) {
3883     llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
3884     CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
3885                             fp_offset_p);
3886   }
3887   CGF.EmitBranch(ContBlock);
3888 
3889   // Emit code to load the value if it was passed in memory.
3890 
3891   CGF.EmitBlock(InMemBlock);
3892   Address MemAddr = EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
3893 
3894   // Return the appropriate result.
3895 
3896   CGF.EmitBlock(ContBlock);
3897   Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, MemAddr, InMemBlock,
3898                                  "vaarg.addr");
3899   return ResAddr;
3900 }
3901 
3902 Address X86_64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
3903                                    QualType Ty) const {
3904   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
3905                           CGF.getContext().getTypeInfoInChars(Ty),
3906                           CharUnits::fromQuantity(8),
3907                           /*allowHigherAlign*/ false);
3908 }
3909 
3910 ABIArgInfo
3911 WinX86_64ABIInfo::reclassifyHvaArgType(QualType Ty, unsigned &FreeSSERegs,
3912                                     const ABIArgInfo &current) const {
3913   // Assumes vectorCall calling convention.
3914   const Type *Base = nullptr;
3915   uint64_t NumElts = 0;
3916 
3917   if (!Ty->isBuiltinType() && !Ty->isVectorType() &&
3918       isHomogeneousAggregate(Ty, Base, NumElts) && FreeSSERegs >= NumElts) {
3919     FreeSSERegs -= NumElts;
3920     return getDirectX86Hva();
3921   }
3922   return current;
3923 }
3924 
3925 ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, unsigned &FreeSSERegs,
3926                                       bool IsReturnType, bool IsVectorCall,
3927                                       bool IsRegCall) const {
3928 
3929   if (Ty->isVoidType())
3930     return ABIArgInfo::getIgnore();
3931 
3932   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3933     Ty = EnumTy->getDecl()->getIntegerType();
3934 
3935   TypeInfo Info = getContext().getTypeInfo(Ty);
3936   uint64_t Width = Info.Width;
3937   CharUnits Align = getContext().toCharUnitsFromBits(Info.Align);
3938 
3939   const RecordType *RT = Ty->getAs<RecordType>();
3940   if (RT) {
3941     if (!IsReturnType) {
3942       if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
3943         return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
3944     }
3945 
3946     if (RT->getDecl()->hasFlexibleArrayMember())
3947       return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
3948 
3949   }
3950 
3951   const Type *Base = nullptr;
3952   uint64_t NumElts = 0;
3953   // vectorcall adds the concept of a homogenous vector aggregate, similar to
3954   // other targets.
3955   if ((IsVectorCall || IsRegCall) &&
3956       isHomogeneousAggregate(Ty, Base, NumElts)) {
3957     if (IsRegCall) {
3958       if (FreeSSERegs >= NumElts) {
3959         FreeSSERegs -= NumElts;
3960         if (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())
3961           return ABIArgInfo::getDirect();
3962         return ABIArgInfo::getExpand();
3963       }
3964       return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3965     } else if (IsVectorCall) {
3966       if (FreeSSERegs >= NumElts &&
3967           (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())) {
3968         FreeSSERegs -= NumElts;
3969         return ABIArgInfo::getDirect();
3970       } else if (IsReturnType) {
3971         return ABIArgInfo::getExpand();
3972       } else if (!Ty->isBuiltinType() && !Ty->isVectorType()) {
3973         // HVAs are delayed and reclassified in the 2nd step.
3974         return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3975       }
3976     }
3977   }
3978 
3979   if (Ty->isMemberPointerType()) {
3980     // If the member pointer is represented by an LLVM int or ptr, pass it
3981     // directly.
3982     llvm::Type *LLTy = CGT.ConvertType(Ty);
3983     if (LLTy->isPointerTy() || LLTy->isIntegerTy())
3984       return ABIArgInfo::getDirect();
3985   }
3986 
3987   if (RT || Ty->isAnyComplexType() || Ty->isMemberPointerType()) {
3988     // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
3989     // not 1, 2, 4, or 8 bytes, must be passed by reference."
3990     if (Width > 64 || !llvm::isPowerOf2_64(Width))
3991       return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
3992 
3993     // Otherwise, coerce it to a small integer.
3994     return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Width));
3995   }
3996 
3997   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
3998     switch (BT->getKind()) {
3999     case BuiltinType::Bool:
4000       // Bool type is always extended to the ABI, other builtin types are not
4001       // extended.
4002       return ABIArgInfo::getExtend(Ty);
4003 
4004     case BuiltinType::LongDouble:
4005       // Mingw64 GCC uses the old 80 bit extended precision floating point
4006       // unit. It passes them indirectly through memory.
4007       if (IsMingw64) {
4008         const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
4009         if (LDF == &llvm::APFloat::x87DoubleExtended())
4010           return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
4011       }
4012       break;
4013 
4014     case BuiltinType::Int128:
4015     case BuiltinType::UInt128:
4016       // If it's a parameter type, the normal ABI rule is that arguments larger
4017       // than 8 bytes are passed indirectly. GCC follows it. We follow it too,
4018       // even though it isn't particularly efficient.
4019       if (!IsReturnType)
4020         return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
4021 
4022       // Mingw64 GCC returns i128 in XMM0. Coerce to v2i64 to handle that.
4023       // Clang matches them for compatibility.
4024       return ABIArgInfo::getDirect(
4025           llvm::VectorType::get(llvm::Type::getInt64Ty(getVMContext()), 2));
4026 
4027     default:
4028       break;
4029     }
4030   }
4031 
4032   return ABIArgInfo::getDirect();
4033 }
4034 
4035 void WinX86_64ABIInfo::computeVectorCallArgs(CGFunctionInfo &FI,
4036                                              unsigned FreeSSERegs,
4037                                              bool IsVectorCall,
4038                                              bool IsRegCall) const {
4039   unsigned Count = 0;
4040   for (auto &I : FI.arguments()) {
4041     // Vectorcall in x64 only permits the first 6 arguments to be passed
4042     // as XMM/YMM registers.
4043     if (Count < VectorcallMaxParamNumAsReg)
4044       I.info = classify(I.type, FreeSSERegs, false, IsVectorCall, IsRegCall);
4045     else {
4046       // Since these cannot be passed in registers, pretend no registers
4047       // are left.
4048       unsigned ZeroSSERegsAvail = 0;
4049       I.info = classify(I.type, /*FreeSSERegs=*/ZeroSSERegsAvail, false,
4050                         IsVectorCall, IsRegCall);
4051     }
4052     ++Count;
4053   }
4054 
4055   for (auto &I : FI.arguments()) {
4056     I.info = reclassifyHvaArgType(I.type, FreeSSERegs, I.info);
4057   }
4058 }
4059 
4060 void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
4061   const unsigned CC = FI.getCallingConvention();
4062   bool IsVectorCall = CC == llvm::CallingConv::X86_VectorCall;
4063   bool IsRegCall = CC == llvm::CallingConv::X86_RegCall;
4064 
4065   // If __attribute__((sysv_abi)) is in use, use the SysV argument
4066   // classification rules.
4067   if (CC == llvm::CallingConv::X86_64_SysV) {
4068     X86_64ABIInfo SysVABIInfo(CGT, AVXLevel);
4069     SysVABIInfo.computeInfo(FI);
4070     return;
4071   }
4072 
4073   unsigned FreeSSERegs = 0;
4074   if (IsVectorCall) {
4075     // We can use up to 4 SSE return registers with vectorcall.
4076     FreeSSERegs = 4;
4077   } else if (IsRegCall) {
4078     // RegCall gives us 16 SSE registers.
4079     FreeSSERegs = 16;
4080   }
4081 
4082   if (!getCXXABI().classifyReturnType(FI))
4083     FI.getReturnInfo() = classify(FI.getReturnType(), FreeSSERegs, true,
4084                                   IsVectorCall, IsRegCall);
4085 
4086   if (IsVectorCall) {
4087     // We can use up to 6 SSE register parameters with vectorcall.
4088     FreeSSERegs = 6;
4089   } else if (IsRegCall) {
4090     // RegCall gives us 16 SSE registers, we can reuse the return registers.
4091     FreeSSERegs = 16;
4092   }
4093 
4094   if (IsVectorCall) {
4095     computeVectorCallArgs(FI, FreeSSERegs, IsVectorCall, IsRegCall);
4096   } else {
4097     for (auto &I : FI.arguments())
4098       I.info = classify(I.type, FreeSSERegs, false, IsVectorCall, IsRegCall);
4099   }
4100 
4101 }
4102 
4103 Address WinX86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4104                                     QualType Ty) const {
4105 
4106   bool IsIndirect = false;
4107 
4108   // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
4109   // not 1, 2, 4, or 8 bytes, must be passed by reference."
4110   if (isAggregateTypeForABI(Ty) || Ty->isMemberPointerType()) {
4111     uint64_t Width = getContext().getTypeSize(Ty);
4112     IsIndirect = Width > 64 || !llvm::isPowerOf2_64(Width);
4113   }
4114 
4115   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
4116                           CGF.getContext().getTypeInfoInChars(Ty),
4117                           CharUnits::fromQuantity(8),
4118                           /*allowHigherAlign*/ false);
4119 }
4120 
4121 // PowerPC-32
4122 namespace {
4123 /// PPC32_SVR4_ABIInfo - The 32-bit PowerPC ELF (SVR4) ABI information.
4124 class PPC32_SVR4_ABIInfo : public DefaultABIInfo {
4125   bool IsSoftFloatABI;
4126   bool IsRetSmallStructInRegABI;
4127 
4128   CharUnits getParamTypeAlignment(QualType Ty) const;
4129 
4130 public:
4131   PPC32_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, bool SoftFloatABI,
4132                      bool RetSmallStructInRegABI)
4133       : DefaultABIInfo(CGT), IsSoftFloatABI(SoftFloatABI),
4134         IsRetSmallStructInRegABI(RetSmallStructInRegABI) {}
4135 
4136   ABIArgInfo classifyReturnType(QualType RetTy) const;
4137 
4138   void computeInfo(CGFunctionInfo &FI) const override {
4139     if (!getCXXABI().classifyReturnType(FI))
4140       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
4141     for (auto &I : FI.arguments())
4142       I.info = classifyArgumentType(I.type);
4143   }
4144 
4145   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4146                     QualType Ty) const override;
4147 };
4148 
4149 class PPC32TargetCodeGenInfo : public TargetCodeGenInfo {
4150 public:
4151   PPC32TargetCodeGenInfo(CodeGenTypes &CGT, bool SoftFloatABI,
4152                          bool RetSmallStructInRegABI)
4153       : TargetCodeGenInfo(new PPC32_SVR4_ABIInfo(CGT, SoftFloatABI,
4154                                                  RetSmallStructInRegABI)) {}
4155 
4156   static bool isStructReturnInRegABI(const llvm::Triple &Triple,
4157                                      const CodeGenOptions &Opts);
4158 
4159   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4160     // This is recovered from gcc output.
4161     return 1; // r1 is the dedicated stack pointer
4162   }
4163 
4164   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4165                                llvm::Value *Address) const override;
4166 };
4167 }
4168 
4169 CharUnits PPC32_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const {
4170   // Complex types are passed just like their elements
4171   if (const ComplexType *CTy = Ty->getAs<ComplexType>())
4172     Ty = CTy->getElementType();
4173 
4174   if (Ty->isVectorType())
4175     return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16
4176                                                                        : 4);
4177 
4178   // For single-element float/vector structs, we consider the whole type
4179   // to have the same alignment requirements as its single element.
4180   const Type *AlignTy = nullptr;
4181   if (const Type *EltType = isSingleElementStruct(Ty, getContext())) {
4182     const BuiltinType *BT = EltType->getAs<BuiltinType>();
4183     if ((EltType->isVectorType() && getContext().getTypeSize(EltType) == 128) ||
4184         (BT && BT->isFloatingPoint()))
4185       AlignTy = EltType;
4186   }
4187 
4188   if (AlignTy)
4189     return CharUnits::fromQuantity(AlignTy->isVectorType() ? 16 : 4);
4190   return CharUnits::fromQuantity(4);
4191 }
4192 
4193 ABIArgInfo PPC32_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
4194   uint64_t Size;
4195 
4196   // -msvr4-struct-return puts small aggregates in GPR3 and GPR4.
4197   if (isAggregateTypeForABI(RetTy) && IsRetSmallStructInRegABI &&
4198       (Size = getContext().getTypeSize(RetTy)) <= 64) {
4199     // System V ABI (1995), page 3-22, specified:
4200     // > A structure or union whose size is less than or equal to 8 bytes
4201     // > shall be returned in r3 and r4, as if it were first stored in the
4202     // > 8-byte aligned memory area and then the low addressed word were
4203     // > loaded into r3 and the high-addressed word into r4.  Bits beyond
4204     // > the last member of the structure or union are not defined.
4205     //
4206     // GCC for big-endian PPC32 inserts the pad before the first member,
4207     // not "beyond the last member" of the struct.  To stay compatible
4208     // with GCC, we coerce the struct to an integer of the same size.
4209     // LLVM will extend it and return i32 in r3, or i64 in r3:r4.
4210     if (Size == 0)
4211       return ABIArgInfo::getIgnore();
4212     else {
4213       llvm::Type *CoerceTy = llvm::Type::getIntNTy(getVMContext(), Size);
4214       return ABIArgInfo::getDirect(CoerceTy);
4215     }
4216   }
4217 
4218   return DefaultABIInfo::classifyReturnType(RetTy);
4219 }
4220 
4221 // TODO: this implementation is now likely redundant with
4222 // DefaultABIInfo::EmitVAArg.
4223 Address PPC32_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAList,
4224                                       QualType Ty) const {
4225   if (getTarget().getTriple().isOSDarwin()) {
4226     auto TI = getContext().getTypeInfoInChars(Ty);
4227     TI.second = getParamTypeAlignment(Ty);
4228 
4229     CharUnits SlotSize = CharUnits::fromQuantity(4);
4230     return emitVoidPtrVAArg(CGF, VAList, Ty,
4231                             classifyArgumentType(Ty).isIndirect(), TI, SlotSize,
4232                             /*AllowHigherAlign=*/true);
4233   }
4234 
4235   const unsigned OverflowLimit = 8;
4236   if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
4237     // TODO: Implement this. For now ignore.
4238     (void)CTy;
4239     return Address::invalid(); // FIXME?
4240   }
4241 
4242   // struct __va_list_tag {
4243   //   unsigned char gpr;
4244   //   unsigned char fpr;
4245   //   unsigned short reserved;
4246   //   void *overflow_arg_area;
4247   //   void *reg_save_area;
4248   // };
4249 
4250   bool isI64 = Ty->isIntegerType() && getContext().getTypeSize(Ty) == 64;
4251   bool isInt =
4252       Ty->isIntegerType() || Ty->isPointerType() || Ty->isAggregateType();
4253   bool isF64 = Ty->isFloatingType() && getContext().getTypeSize(Ty) == 64;
4254 
4255   // All aggregates are passed indirectly?  That doesn't seem consistent
4256   // with the argument-lowering code.
4257   bool isIndirect = Ty->isAggregateType();
4258 
4259   CGBuilderTy &Builder = CGF.Builder;
4260 
4261   // The calling convention either uses 1-2 GPRs or 1 FPR.
4262   Address NumRegsAddr = Address::invalid();
4263   if (isInt || IsSoftFloatABI) {
4264     NumRegsAddr = Builder.CreateStructGEP(VAList, 0, "gpr");
4265   } else {
4266     NumRegsAddr = Builder.CreateStructGEP(VAList, 1, "fpr");
4267   }
4268 
4269   llvm::Value *NumRegs = Builder.CreateLoad(NumRegsAddr, "numUsedRegs");
4270 
4271   // "Align" the register count when TY is i64.
4272   if (isI64 || (isF64 && IsSoftFloatABI)) {
4273     NumRegs = Builder.CreateAdd(NumRegs, Builder.getInt8(1));
4274     NumRegs = Builder.CreateAnd(NumRegs, Builder.getInt8((uint8_t) ~1U));
4275   }
4276 
4277   llvm::Value *CC =
4278       Builder.CreateICmpULT(NumRegs, Builder.getInt8(OverflowLimit), "cond");
4279 
4280   llvm::BasicBlock *UsingRegs = CGF.createBasicBlock("using_regs");
4281   llvm::BasicBlock *UsingOverflow = CGF.createBasicBlock("using_overflow");
4282   llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
4283 
4284   Builder.CreateCondBr(CC, UsingRegs, UsingOverflow);
4285 
4286   llvm::Type *DirectTy = CGF.ConvertType(Ty);
4287   if (isIndirect) DirectTy = DirectTy->getPointerTo(0);
4288 
4289   // Case 1: consume registers.
4290   Address RegAddr = Address::invalid();
4291   {
4292     CGF.EmitBlock(UsingRegs);
4293 
4294     Address RegSaveAreaPtr = Builder.CreateStructGEP(VAList, 4);
4295     RegAddr = Address(Builder.CreateLoad(RegSaveAreaPtr),
4296                       CharUnits::fromQuantity(8));
4297     assert(RegAddr.getElementType() == CGF.Int8Ty);
4298 
4299     // Floating-point registers start after the general-purpose registers.
4300     if (!(isInt || IsSoftFloatABI)) {
4301       RegAddr = Builder.CreateConstInBoundsByteGEP(RegAddr,
4302                                                    CharUnits::fromQuantity(32));
4303     }
4304 
4305     // Get the address of the saved value by scaling the number of
4306     // registers we've used by the number of
4307     CharUnits RegSize = CharUnits::fromQuantity((isInt || IsSoftFloatABI) ? 4 : 8);
4308     llvm::Value *RegOffset =
4309       Builder.CreateMul(NumRegs, Builder.getInt8(RegSize.getQuantity()));
4310     RegAddr = Address(Builder.CreateInBoundsGEP(CGF.Int8Ty,
4311                                             RegAddr.getPointer(), RegOffset),
4312                       RegAddr.getAlignment().alignmentOfArrayElement(RegSize));
4313     RegAddr = Builder.CreateElementBitCast(RegAddr, DirectTy);
4314 
4315     // Increase the used-register count.
4316     NumRegs =
4317       Builder.CreateAdd(NumRegs,
4318                         Builder.getInt8((isI64 || (isF64 && IsSoftFloatABI)) ? 2 : 1));
4319     Builder.CreateStore(NumRegs, NumRegsAddr);
4320 
4321     CGF.EmitBranch(Cont);
4322   }
4323 
4324   // Case 2: consume space in the overflow area.
4325   Address MemAddr = Address::invalid();
4326   {
4327     CGF.EmitBlock(UsingOverflow);
4328 
4329     Builder.CreateStore(Builder.getInt8(OverflowLimit), NumRegsAddr);
4330 
4331     // Everything in the overflow area is rounded up to a size of at least 4.
4332     CharUnits OverflowAreaAlign = CharUnits::fromQuantity(4);
4333 
4334     CharUnits Size;
4335     if (!isIndirect) {
4336       auto TypeInfo = CGF.getContext().getTypeInfoInChars(Ty);
4337       Size = TypeInfo.first.alignTo(OverflowAreaAlign);
4338     } else {
4339       Size = CGF.getPointerSize();
4340     }
4341 
4342     Address OverflowAreaAddr = Builder.CreateStructGEP(VAList, 3);
4343     Address OverflowArea(Builder.CreateLoad(OverflowAreaAddr, "argp.cur"),
4344                          OverflowAreaAlign);
4345     // Round up address of argument to alignment
4346     CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
4347     if (Align > OverflowAreaAlign) {
4348       llvm::Value *Ptr = OverflowArea.getPointer();
4349       OverflowArea = Address(emitRoundPointerUpToAlignment(CGF, Ptr, Align),
4350                                                            Align);
4351     }
4352 
4353     MemAddr = Builder.CreateElementBitCast(OverflowArea, DirectTy);
4354 
4355     // Increase the overflow area.
4356     OverflowArea = Builder.CreateConstInBoundsByteGEP(OverflowArea, Size);
4357     Builder.CreateStore(OverflowArea.getPointer(), OverflowAreaAddr);
4358     CGF.EmitBranch(Cont);
4359   }
4360 
4361   CGF.EmitBlock(Cont);
4362 
4363   // Merge the cases with a phi.
4364   Address Result = emitMergePHI(CGF, RegAddr, UsingRegs, MemAddr, UsingOverflow,
4365                                 "vaarg.addr");
4366 
4367   // Load the pointer if the argument was passed indirectly.
4368   if (isIndirect) {
4369     Result = Address(Builder.CreateLoad(Result, "aggr"),
4370                      getContext().getTypeAlignInChars(Ty));
4371   }
4372 
4373   return Result;
4374 }
4375 
4376 bool PPC32TargetCodeGenInfo::isStructReturnInRegABI(
4377     const llvm::Triple &Triple, const CodeGenOptions &Opts) {
4378   assert(Triple.getArch() == llvm::Triple::ppc);
4379 
4380   switch (Opts.getStructReturnConvention()) {
4381   case CodeGenOptions::SRCK_Default:
4382     break;
4383   case CodeGenOptions::SRCK_OnStack: // -maix-struct-return
4384     return false;
4385   case CodeGenOptions::SRCK_InRegs: // -msvr4-struct-return
4386     return true;
4387   }
4388 
4389   if (Triple.isOSBinFormatELF() && !Triple.isOSLinux())
4390     return true;
4391 
4392   return false;
4393 }
4394 
4395 bool
4396 PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4397                                                 llvm::Value *Address) const {
4398   // This is calculated from the LLVM and GCC tables and verified
4399   // against gcc output.  AFAIK all ABIs use the same encoding.
4400 
4401   CodeGen::CGBuilderTy &Builder = CGF.Builder;
4402 
4403   llvm::IntegerType *i8 = CGF.Int8Ty;
4404   llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
4405   llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
4406   llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
4407 
4408   // 0-31: r0-31, the 4-byte general-purpose registers
4409   AssignToArrayRange(Builder, Address, Four8, 0, 31);
4410 
4411   // 32-63: fp0-31, the 8-byte floating-point registers
4412   AssignToArrayRange(Builder, Address, Eight8, 32, 63);
4413 
4414   // 64-76 are various 4-byte special-purpose registers:
4415   // 64: mq
4416   // 65: lr
4417   // 66: ctr
4418   // 67: ap
4419   // 68-75 cr0-7
4420   // 76: xer
4421   AssignToArrayRange(Builder, Address, Four8, 64, 76);
4422 
4423   // 77-108: v0-31, the 16-byte vector registers
4424   AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
4425 
4426   // 109: vrsave
4427   // 110: vscr
4428   // 111: spe_acc
4429   // 112: spefscr
4430   // 113: sfp
4431   AssignToArrayRange(Builder, Address, Four8, 109, 113);
4432 
4433   return false;
4434 }
4435 
4436 // PowerPC-64
4437 
4438 namespace {
4439 /// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
4440 class PPC64_SVR4_ABIInfo : public SwiftABIInfo {
4441 public:
4442   enum ABIKind {
4443     ELFv1 = 0,
4444     ELFv2
4445   };
4446 
4447 private:
4448   static const unsigned GPRBits = 64;
4449   ABIKind Kind;
4450   bool HasQPX;
4451   bool IsSoftFloatABI;
4452 
4453   // A vector of float or double will be promoted to <4 x f32> or <4 x f64> and
4454   // will be passed in a QPX register.
4455   bool IsQPXVectorTy(const Type *Ty) const {
4456     if (!HasQPX)
4457       return false;
4458 
4459     if (const VectorType *VT = Ty->getAs<VectorType>()) {
4460       unsigned NumElements = VT->getNumElements();
4461       if (NumElements == 1)
4462         return false;
4463 
4464       if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double)) {
4465         if (getContext().getTypeSize(Ty) <= 256)
4466           return true;
4467       } else if (VT->getElementType()->
4468                    isSpecificBuiltinType(BuiltinType::Float)) {
4469         if (getContext().getTypeSize(Ty) <= 128)
4470           return true;
4471       }
4472     }
4473 
4474     return false;
4475   }
4476 
4477   bool IsQPXVectorTy(QualType Ty) const {
4478     return IsQPXVectorTy(Ty.getTypePtr());
4479   }
4480 
4481 public:
4482   PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind, bool HasQPX,
4483                      bool SoftFloatABI)
4484       : SwiftABIInfo(CGT), Kind(Kind), HasQPX(HasQPX),
4485         IsSoftFloatABI(SoftFloatABI) {}
4486 
4487   bool isPromotableTypeForABI(QualType Ty) const;
4488   CharUnits getParamTypeAlignment(QualType Ty) const;
4489 
4490   ABIArgInfo classifyReturnType(QualType RetTy) const;
4491   ABIArgInfo classifyArgumentType(QualType Ty) const;
4492 
4493   bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4494   bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4495                                          uint64_t Members) const override;
4496 
4497   // TODO: We can add more logic to computeInfo to improve performance.
4498   // Example: For aggregate arguments that fit in a register, we could
4499   // use getDirectInReg (as is done below for structs containing a single
4500   // floating-point value) to avoid pushing them to memory on function
4501   // entry.  This would require changing the logic in PPCISelLowering
4502   // when lowering the parameters in the caller and args in the callee.
4503   void computeInfo(CGFunctionInfo &FI) const override {
4504     if (!getCXXABI().classifyReturnType(FI))
4505       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
4506     for (auto &I : FI.arguments()) {
4507       // We rely on the default argument classification for the most part.
4508       // One exception:  An aggregate containing a single floating-point
4509       // or vector item must be passed in a register if one is available.
4510       const Type *T = isSingleElementStruct(I.type, getContext());
4511       if (T) {
4512         const BuiltinType *BT = T->getAs<BuiltinType>();
4513         if (IsQPXVectorTy(T) ||
4514             (T->isVectorType() && getContext().getTypeSize(T) == 128) ||
4515             (BT && BT->isFloatingPoint())) {
4516           QualType QT(T, 0);
4517           I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
4518           continue;
4519         }
4520       }
4521       I.info = classifyArgumentType(I.type);
4522     }
4523   }
4524 
4525   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4526                     QualType Ty) const override;
4527 
4528   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
4529                                     bool asReturnValue) const override {
4530     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
4531   }
4532 
4533   bool isSwiftErrorInRegister() const override {
4534     return false;
4535   }
4536 };
4537 
4538 class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
4539 
4540 public:
4541   PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT,
4542                                PPC64_SVR4_ABIInfo::ABIKind Kind, bool HasQPX,
4543                                bool SoftFloatABI)
4544       : TargetCodeGenInfo(new PPC64_SVR4_ABIInfo(CGT, Kind, HasQPX,
4545                                                  SoftFloatABI)) {}
4546 
4547   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4548     // This is recovered from gcc output.
4549     return 1; // r1 is the dedicated stack pointer
4550   }
4551 
4552   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4553                                llvm::Value *Address) const override;
4554 };
4555 
4556 class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
4557 public:
4558   PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
4559 
4560   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4561     // This is recovered from gcc output.
4562     return 1; // r1 is the dedicated stack pointer
4563   }
4564 
4565   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4566                                llvm::Value *Address) const override;
4567 };
4568 
4569 }
4570 
4571 // Return true if the ABI requires Ty to be passed sign- or zero-
4572 // extended to 64 bits.
4573 bool
4574 PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
4575   // Treat an enum type as its underlying type.
4576   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4577     Ty = EnumTy->getDecl()->getIntegerType();
4578 
4579   // Promotable integer types are required to be promoted by the ABI.
4580   if (Ty->isPromotableIntegerType())
4581     return true;
4582 
4583   // In addition to the usual promotable integer types, we also need to
4584   // extend all 32-bit types, since the ABI requires promotion to 64 bits.
4585   if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
4586     switch (BT->getKind()) {
4587     case BuiltinType::Int:
4588     case BuiltinType::UInt:
4589       return true;
4590     default:
4591       break;
4592     }
4593 
4594   return false;
4595 }
4596 
4597 /// isAlignedParamType - Determine whether a type requires 16-byte or
4598 /// higher alignment in the parameter area.  Always returns at least 8.
4599 CharUnits PPC64_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const {
4600   // Complex types are passed just like their elements.
4601   if (const ComplexType *CTy = Ty->getAs<ComplexType>())
4602     Ty = CTy->getElementType();
4603 
4604   // Only vector types of size 16 bytes need alignment (larger types are
4605   // passed via reference, smaller types are not aligned).
4606   if (IsQPXVectorTy(Ty)) {
4607     if (getContext().getTypeSize(Ty) > 128)
4608       return CharUnits::fromQuantity(32);
4609 
4610     return CharUnits::fromQuantity(16);
4611   } else if (Ty->isVectorType()) {
4612     return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16 : 8);
4613   }
4614 
4615   // For single-element float/vector structs, we consider the whole type
4616   // to have the same alignment requirements as its single element.
4617   const Type *AlignAsType = nullptr;
4618   const Type *EltType = isSingleElementStruct(Ty, getContext());
4619   if (EltType) {
4620     const BuiltinType *BT = EltType->getAs<BuiltinType>();
4621     if (IsQPXVectorTy(EltType) || (EltType->isVectorType() &&
4622          getContext().getTypeSize(EltType) == 128) ||
4623         (BT && BT->isFloatingPoint()))
4624       AlignAsType = EltType;
4625   }
4626 
4627   // Likewise for ELFv2 homogeneous aggregates.
4628   const Type *Base = nullptr;
4629   uint64_t Members = 0;
4630   if (!AlignAsType && Kind == ELFv2 &&
4631       isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members))
4632     AlignAsType = Base;
4633 
4634   // With special case aggregates, only vector base types need alignment.
4635   if (AlignAsType && IsQPXVectorTy(AlignAsType)) {
4636     if (getContext().getTypeSize(AlignAsType) > 128)
4637       return CharUnits::fromQuantity(32);
4638 
4639     return CharUnits::fromQuantity(16);
4640   } else if (AlignAsType) {
4641     return CharUnits::fromQuantity(AlignAsType->isVectorType() ? 16 : 8);
4642   }
4643 
4644   // Otherwise, we only need alignment for any aggregate type that
4645   // has an alignment requirement of >= 16 bytes.
4646   if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128) {
4647     if (HasQPX && getContext().getTypeAlign(Ty) >= 256)
4648       return CharUnits::fromQuantity(32);
4649     return CharUnits::fromQuantity(16);
4650   }
4651 
4652   return CharUnits::fromQuantity(8);
4653 }
4654 
4655 /// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous
4656 /// aggregate.  Base is set to the base element type, and Members is set
4657 /// to the number of base elements.
4658 bool ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base,
4659                                      uint64_t &Members) const {
4660   if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
4661     uint64_t NElements = AT->getSize().getZExtValue();
4662     if (NElements == 0)
4663       return false;
4664     if (!isHomogeneousAggregate(AT->getElementType(), Base, Members))
4665       return false;
4666     Members *= NElements;
4667   } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
4668     const RecordDecl *RD = RT->getDecl();
4669     if (RD->hasFlexibleArrayMember())
4670       return false;
4671 
4672     Members = 0;
4673 
4674     // If this is a C++ record, check the bases first.
4675     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
4676       for (const auto &I : CXXRD->bases()) {
4677         // Ignore empty records.
4678         if (isEmptyRecord(getContext(), I.getType(), true))
4679           continue;
4680 
4681         uint64_t FldMembers;
4682         if (!isHomogeneousAggregate(I.getType(), Base, FldMembers))
4683           return false;
4684 
4685         Members += FldMembers;
4686       }
4687     }
4688 
4689     for (const auto *FD : RD->fields()) {
4690       // Ignore (non-zero arrays of) empty records.
4691       QualType FT = FD->getType();
4692       while (const ConstantArrayType *AT =
4693              getContext().getAsConstantArrayType(FT)) {
4694         if (AT->getSize().getZExtValue() == 0)
4695           return false;
4696         FT = AT->getElementType();
4697       }
4698       if (isEmptyRecord(getContext(), FT, true))
4699         continue;
4700 
4701       // For compatibility with GCC, ignore empty bitfields in C++ mode.
4702       if (getContext().getLangOpts().CPlusPlus &&
4703           FD->isZeroLengthBitField(getContext()))
4704         continue;
4705 
4706       uint64_t FldMembers;
4707       if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers))
4708         return false;
4709 
4710       Members = (RD->isUnion() ?
4711                  std::max(Members, FldMembers) : Members + FldMembers);
4712     }
4713 
4714     if (!Base)
4715       return false;
4716 
4717     // Ensure there is no padding.
4718     if (getContext().getTypeSize(Base) * Members !=
4719         getContext().getTypeSize(Ty))
4720       return false;
4721   } else {
4722     Members = 1;
4723     if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
4724       Members = 2;
4725       Ty = CT->getElementType();
4726     }
4727 
4728     // Most ABIs only support float, double, and some vector type widths.
4729     if (!isHomogeneousAggregateBaseType(Ty))
4730       return false;
4731 
4732     // The base type must be the same for all members.  Types that
4733     // agree in both total size and mode (float vs. vector) are
4734     // treated as being equivalent here.
4735     const Type *TyPtr = Ty.getTypePtr();
4736     if (!Base) {
4737       Base = TyPtr;
4738       // If it's a non-power-of-2 vector, its size is already a power-of-2,
4739       // so make sure to widen it explicitly.
4740       if (const VectorType *VT = Base->getAs<VectorType>()) {
4741         QualType EltTy = VT->getElementType();
4742         unsigned NumElements =
4743             getContext().getTypeSize(VT) / getContext().getTypeSize(EltTy);
4744         Base = getContext()
4745                    .getVectorType(EltTy, NumElements, VT->getVectorKind())
4746                    .getTypePtr();
4747       }
4748     }
4749 
4750     if (Base->isVectorType() != TyPtr->isVectorType() ||
4751         getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr))
4752       return false;
4753   }
4754   return Members > 0 && isHomogeneousAggregateSmallEnough(Base, Members);
4755 }
4756 
4757 bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
4758   // Homogeneous aggregates for ELFv2 must have base types of float,
4759   // double, long double, or 128-bit vectors.
4760   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4761     if (BT->getKind() == BuiltinType::Float ||
4762         BT->getKind() == BuiltinType::Double ||
4763         BT->getKind() == BuiltinType::LongDouble ||
4764         (getContext().getTargetInfo().hasFloat128Type() &&
4765           (BT->getKind() == BuiltinType::Float128))) {
4766       if (IsSoftFloatABI)
4767         return false;
4768       return true;
4769     }
4770   }
4771   if (const VectorType *VT = Ty->getAs<VectorType>()) {
4772     if (getContext().getTypeSize(VT) == 128 || IsQPXVectorTy(Ty))
4773       return true;
4774   }
4775   return false;
4776 }
4777 
4778 bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateSmallEnough(
4779     const Type *Base, uint64_t Members) const {
4780   // Vector and fp128 types require one register, other floating point types
4781   // require one or two registers depending on their size.
4782   uint32_t NumRegs =
4783       ((getContext().getTargetInfo().hasFloat128Type() &&
4784           Base->isFloat128Type()) ||
4785         Base->isVectorType()) ? 1
4786                               : (getContext().getTypeSize(Base) + 63) / 64;
4787 
4788   // Homogeneous Aggregates may occupy at most 8 registers.
4789   return Members * NumRegs <= 8;
4790 }
4791 
4792 ABIArgInfo
4793 PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
4794   Ty = useFirstFieldIfTransparentUnion(Ty);
4795 
4796   if (Ty->isAnyComplexType())
4797     return ABIArgInfo::getDirect();
4798 
4799   // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes)
4800   // or via reference (larger than 16 bytes).
4801   if (Ty->isVectorType() && !IsQPXVectorTy(Ty)) {
4802     uint64_t Size = getContext().getTypeSize(Ty);
4803     if (Size > 128)
4804       return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
4805     else if (Size < 128) {
4806       llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
4807       return ABIArgInfo::getDirect(CoerceTy);
4808     }
4809   }
4810 
4811   if (isAggregateTypeForABI(Ty)) {
4812     if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
4813       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
4814 
4815     uint64_t ABIAlign = getParamTypeAlignment(Ty).getQuantity();
4816     uint64_t TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity();
4817 
4818     // ELFv2 homogeneous aggregates are passed as array types.
4819     const Type *Base = nullptr;
4820     uint64_t Members = 0;
4821     if (Kind == ELFv2 &&
4822         isHomogeneousAggregate(Ty, Base, Members)) {
4823       llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
4824       llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
4825       return ABIArgInfo::getDirect(CoerceTy);
4826     }
4827 
4828     // If an aggregate may end up fully in registers, we do not
4829     // use the ByVal method, but pass the aggregate as array.
4830     // This is usually beneficial since we avoid forcing the
4831     // back-end to store the argument to memory.
4832     uint64_t Bits = getContext().getTypeSize(Ty);
4833     if (Bits > 0 && Bits <= 8 * GPRBits) {
4834       llvm::Type *CoerceTy;
4835 
4836       // Types up to 8 bytes are passed as integer type (which will be
4837       // properly aligned in the argument save area doubleword).
4838       if (Bits <= GPRBits)
4839         CoerceTy =
4840             llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
4841       // Larger types are passed as arrays, with the base type selected
4842       // according to the required alignment in the save area.
4843       else {
4844         uint64_t RegBits = ABIAlign * 8;
4845         uint64_t NumRegs = llvm::alignTo(Bits, RegBits) / RegBits;
4846         llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits);
4847         CoerceTy = llvm::ArrayType::get(RegTy, NumRegs);
4848       }
4849 
4850       return ABIArgInfo::getDirect(CoerceTy);
4851     }
4852 
4853     // All other aggregates are passed ByVal.
4854     return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
4855                                    /*ByVal=*/true,
4856                                    /*Realign=*/TyAlign > ABIAlign);
4857   }
4858 
4859   return (isPromotableTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
4860                                      : ABIArgInfo::getDirect());
4861 }
4862 
4863 ABIArgInfo
4864 PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
4865   if (RetTy->isVoidType())
4866     return ABIArgInfo::getIgnore();
4867 
4868   if (RetTy->isAnyComplexType())
4869     return ABIArgInfo::getDirect();
4870 
4871   // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes)
4872   // or via reference (larger than 16 bytes).
4873   if (RetTy->isVectorType() && !IsQPXVectorTy(RetTy)) {
4874     uint64_t Size = getContext().getTypeSize(RetTy);
4875     if (Size > 128)
4876       return getNaturalAlignIndirect(RetTy);
4877     else if (Size < 128) {
4878       llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
4879       return ABIArgInfo::getDirect(CoerceTy);
4880     }
4881   }
4882 
4883   if (isAggregateTypeForABI(RetTy)) {
4884     // ELFv2 homogeneous aggregates are returned as array types.
4885     const Type *Base = nullptr;
4886     uint64_t Members = 0;
4887     if (Kind == ELFv2 &&
4888         isHomogeneousAggregate(RetTy, Base, Members)) {
4889       llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
4890       llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
4891       return ABIArgInfo::getDirect(CoerceTy);
4892     }
4893 
4894     // ELFv2 small aggregates are returned in up to two registers.
4895     uint64_t Bits = getContext().getTypeSize(RetTy);
4896     if (Kind == ELFv2 && Bits <= 2 * GPRBits) {
4897       if (Bits == 0)
4898         return ABIArgInfo::getIgnore();
4899 
4900       llvm::Type *CoerceTy;
4901       if (Bits > GPRBits) {
4902         CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits);
4903         CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy);
4904       } else
4905         CoerceTy =
4906             llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
4907       return ABIArgInfo::getDirect(CoerceTy);
4908     }
4909 
4910     // All other aggregates are returned indirectly.
4911     return getNaturalAlignIndirect(RetTy);
4912   }
4913 
4914   return (isPromotableTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
4915                                         : ABIArgInfo::getDirect());
4916 }
4917 
4918 // Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
4919 Address PPC64_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4920                                       QualType Ty) const {
4921   auto TypeInfo = getContext().getTypeInfoInChars(Ty);
4922   TypeInfo.second = getParamTypeAlignment(Ty);
4923 
4924   CharUnits SlotSize = CharUnits::fromQuantity(8);
4925 
4926   // If we have a complex type and the base type is smaller than 8 bytes,
4927   // the ABI calls for the real and imaginary parts to be right-adjusted
4928   // in separate doublewords.  However, Clang expects us to produce a
4929   // pointer to a structure with the two parts packed tightly.  So generate
4930   // loads of the real and imaginary parts relative to the va_list pointer,
4931   // and store them to a temporary structure.
4932   if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
4933     CharUnits EltSize = TypeInfo.first / 2;
4934     if (EltSize < SlotSize) {
4935       Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, CGF.Int8Ty,
4936                                             SlotSize * 2, SlotSize,
4937                                             SlotSize, /*AllowHigher*/ true);
4938 
4939       Address RealAddr = Addr;
4940       Address ImagAddr = RealAddr;
4941       if (CGF.CGM.getDataLayout().isBigEndian()) {
4942         RealAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr,
4943                                                           SlotSize - EltSize);
4944         ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(ImagAddr,
4945                                                       2 * SlotSize - EltSize);
4946       } else {
4947         ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, SlotSize);
4948       }
4949 
4950       llvm::Type *EltTy = CGF.ConvertTypeForMem(CTy->getElementType());
4951       RealAddr = CGF.Builder.CreateElementBitCast(RealAddr, EltTy);
4952       ImagAddr = CGF.Builder.CreateElementBitCast(ImagAddr, EltTy);
4953       llvm::Value *Real = CGF.Builder.CreateLoad(RealAddr, ".vareal");
4954       llvm::Value *Imag = CGF.Builder.CreateLoad(ImagAddr, ".vaimag");
4955 
4956       Address Temp = CGF.CreateMemTemp(Ty, "vacplx");
4957       CGF.EmitStoreOfComplex({Real, Imag}, CGF.MakeAddrLValue(Temp, Ty),
4958                              /*init*/ true);
4959       return Temp;
4960     }
4961   }
4962 
4963   // Otherwise, just use the general rule.
4964   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
4965                           TypeInfo, SlotSize, /*AllowHigher*/ true);
4966 }
4967 
4968 static bool
4969 PPC64_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4970                               llvm::Value *Address) {
4971   // This is calculated from the LLVM and GCC tables and verified
4972   // against gcc output.  AFAIK all ABIs use the same encoding.
4973 
4974   CodeGen::CGBuilderTy &Builder = CGF.Builder;
4975 
4976   llvm::IntegerType *i8 = CGF.Int8Ty;
4977   llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
4978   llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
4979   llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
4980 
4981   // 0-31: r0-31, the 8-byte general-purpose registers
4982   AssignToArrayRange(Builder, Address, Eight8, 0, 31);
4983 
4984   // 32-63: fp0-31, the 8-byte floating-point registers
4985   AssignToArrayRange(Builder, Address, Eight8, 32, 63);
4986 
4987   // 64-67 are various 8-byte special-purpose registers:
4988   // 64: mq
4989   // 65: lr
4990   // 66: ctr
4991   // 67: ap
4992   AssignToArrayRange(Builder, Address, Eight8, 64, 67);
4993 
4994   // 68-76 are various 4-byte special-purpose registers:
4995   // 68-75 cr0-7
4996   // 76: xer
4997   AssignToArrayRange(Builder, Address, Four8, 68, 76);
4998 
4999   // 77-108: v0-31, the 16-byte vector registers
5000   AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
5001 
5002   // 109: vrsave
5003   // 110: vscr
5004   // 111: spe_acc
5005   // 112: spefscr
5006   // 113: sfp
5007   // 114: tfhar
5008   // 115: tfiar
5009   // 116: texasr
5010   AssignToArrayRange(Builder, Address, Eight8, 109, 116);
5011 
5012   return false;
5013 }
5014 
5015 bool
5016 PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
5017   CodeGen::CodeGenFunction &CGF,
5018   llvm::Value *Address) const {
5019 
5020   return PPC64_initDwarfEHRegSizeTable(CGF, Address);
5021 }
5022 
5023 bool
5024 PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
5025                                                 llvm::Value *Address) const {
5026 
5027   return PPC64_initDwarfEHRegSizeTable(CGF, Address);
5028 }
5029 
5030 //===----------------------------------------------------------------------===//
5031 // AArch64 ABI Implementation
5032 //===----------------------------------------------------------------------===//
5033 
5034 namespace {
5035 
5036 class AArch64ABIInfo : public SwiftABIInfo {
5037 public:
5038   enum ABIKind {
5039     AAPCS = 0,
5040     DarwinPCS,
5041     Win64
5042   };
5043 
5044 private:
5045   ABIKind Kind;
5046 
5047 public:
5048   AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind)
5049     : SwiftABIInfo(CGT), Kind(Kind) {}
5050 
5051 private:
5052   ABIKind getABIKind() const { return Kind; }
5053   bool isDarwinPCS() const { return Kind == DarwinPCS; }
5054 
5055   ABIArgInfo classifyReturnType(QualType RetTy, bool IsVariadic) const;
5056   ABIArgInfo classifyArgumentType(QualType RetTy) const;
5057   bool isHomogeneousAggregateBaseType(QualType Ty) const override;
5058   bool isHomogeneousAggregateSmallEnough(const Type *Ty,
5059                                          uint64_t Members) const override;
5060 
5061   bool isIllegalVectorType(QualType Ty) const;
5062 
5063   void computeInfo(CGFunctionInfo &FI) const override {
5064     if (!::classifyReturnType(getCXXABI(), FI, *this))
5065       FI.getReturnInfo() =
5066           classifyReturnType(FI.getReturnType(), FI.isVariadic());
5067 
5068     for (auto &it : FI.arguments())
5069       it.info = classifyArgumentType(it.type);
5070   }
5071 
5072   Address EmitDarwinVAArg(Address VAListAddr, QualType Ty,
5073                           CodeGenFunction &CGF) const;
5074 
5075   Address EmitAAPCSVAArg(Address VAListAddr, QualType Ty,
5076                          CodeGenFunction &CGF) const;
5077 
5078   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5079                     QualType Ty) const override {
5080     return Kind == Win64 ? EmitMSVAArg(CGF, VAListAddr, Ty)
5081                          : isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF)
5082                                          : EmitAAPCSVAArg(VAListAddr, Ty, CGF);
5083   }
5084 
5085   Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
5086                       QualType Ty) const override;
5087 
5088   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
5089                                     bool asReturnValue) const override {
5090     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
5091   }
5092   bool isSwiftErrorInRegister() const override {
5093     return true;
5094   }
5095 
5096   bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy,
5097                                  unsigned elts) const override;
5098 };
5099 
5100 class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
5101 public:
5102   AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind)
5103       : TargetCodeGenInfo(new AArch64ABIInfo(CGT, Kind)) {}
5104 
5105   StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
5106     return "mov\tfp, fp\t\t// marker for objc_retainAutoreleaseReturnValue";
5107   }
5108 
5109   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
5110     return 31;
5111   }
5112 
5113   bool doesReturnSlotInterfereWithArgs() const override { return false; }
5114 
5115   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5116                            CodeGen::CodeGenModule &CGM) const override {
5117     const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
5118     if (!FD)
5119       return;
5120 
5121     CodeGenOptions::SignReturnAddressScope Scope = CGM.getCodeGenOpts().getSignReturnAddress();
5122     CodeGenOptions::SignReturnAddressKeyValue Key = CGM.getCodeGenOpts().getSignReturnAddressKey();
5123     bool BranchTargetEnforcement = CGM.getCodeGenOpts().BranchTargetEnforcement;
5124     if (const auto *TA = FD->getAttr<TargetAttr>()) {
5125       ParsedTargetAttr Attr = TA->parse();
5126       if (!Attr.BranchProtection.empty()) {
5127         TargetInfo::BranchProtectionInfo BPI;
5128         StringRef Error;
5129         (void)CGM.getTarget().validateBranchProtection(Attr.BranchProtection,
5130                                                        BPI, Error);
5131         assert(Error.empty());
5132         Scope = BPI.SignReturnAddr;
5133         Key = BPI.SignKey;
5134         BranchTargetEnforcement = BPI.BranchTargetEnforcement;
5135       }
5136     }
5137 
5138     auto *Fn = cast<llvm::Function>(GV);
5139     if (Scope != CodeGenOptions::SignReturnAddressScope::None) {
5140       Fn->addFnAttr("sign-return-address",
5141                     Scope == CodeGenOptions::SignReturnAddressScope::All
5142                         ? "all"
5143                         : "non-leaf");
5144 
5145       Fn->addFnAttr("sign-return-address-key",
5146                     Key == CodeGenOptions::SignReturnAddressKeyValue::AKey
5147                         ? "a_key"
5148                         : "b_key");
5149     }
5150 
5151     if (BranchTargetEnforcement)
5152       Fn->addFnAttr("branch-target-enforcement");
5153   }
5154 };
5155 
5156 class WindowsAArch64TargetCodeGenInfo : public AArch64TargetCodeGenInfo {
5157 public:
5158   WindowsAArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind K)
5159       : AArch64TargetCodeGenInfo(CGT, K) {}
5160 
5161   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5162                            CodeGen::CodeGenModule &CGM) const override;
5163 
5164   void getDependentLibraryOption(llvm::StringRef Lib,
5165                                  llvm::SmallString<24> &Opt) const override {
5166     Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib);
5167   }
5168 
5169   void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value,
5170                                llvm::SmallString<32> &Opt) const override {
5171     Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
5172   }
5173 };
5174 
5175 void WindowsAArch64TargetCodeGenInfo::setTargetAttributes(
5176     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
5177   AArch64TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
5178   if (GV->isDeclaration())
5179     return;
5180   addStackProbeTargetAttributes(D, GV, CGM);
5181 }
5182 }
5183 
5184 ABIArgInfo AArch64ABIInfo::classifyArgumentType(QualType Ty) const {
5185   Ty = useFirstFieldIfTransparentUnion(Ty);
5186 
5187   // Handle illegal vector types here.
5188   if (isIllegalVectorType(Ty)) {
5189     uint64_t Size = getContext().getTypeSize(Ty);
5190     // Android promotes <2 x i8> to i16, not i32
5191     if (isAndroid() && (Size <= 16)) {
5192       llvm::Type *ResType = llvm::Type::getInt16Ty(getVMContext());
5193       return ABIArgInfo::getDirect(ResType);
5194     }
5195     if (Size <= 32) {
5196       llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext());
5197       return ABIArgInfo::getDirect(ResType);
5198     }
5199     if (Size == 64) {
5200       llvm::Type *ResType =
5201           llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2);
5202       return ABIArgInfo::getDirect(ResType);
5203     }
5204     if (Size == 128) {
5205       llvm::Type *ResType =
5206           llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4);
5207       return ABIArgInfo::getDirect(ResType);
5208     }
5209     return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
5210   }
5211 
5212   if (!isAggregateTypeForABI(Ty)) {
5213     // Treat an enum type as its underlying type.
5214     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5215       Ty = EnumTy->getDecl()->getIntegerType();
5216 
5217     return (Ty->isPromotableIntegerType() && isDarwinPCS()
5218                 ? ABIArgInfo::getExtend(Ty)
5219                 : ABIArgInfo::getDirect());
5220   }
5221 
5222   // Structures with either a non-trivial destructor or a non-trivial
5223   // copy constructor are always indirect.
5224   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
5225     return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA ==
5226                                      CGCXXABI::RAA_DirectInMemory);
5227   }
5228 
5229   // Empty records are always ignored on Darwin, but actually passed in C++ mode
5230   // elsewhere for GNU compatibility.
5231   uint64_t Size = getContext().getTypeSize(Ty);
5232   bool IsEmpty = isEmptyRecord(getContext(), Ty, true);
5233   if (IsEmpty || Size == 0) {
5234     if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS())
5235       return ABIArgInfo::getIgnore();
5236 
5237     // GNU C mode. The only argument that gets ignored is an empty one with size
5238     // 0.
5239     if (IsEmpty && Size == 0)
5240       return ABIArgInfo::getIgnore();
5241     return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
5242   }
5243 
5244   // Homogeneous Floating-point Aggregates (HFAs) need to be expanded.
5245   const Type *Base = nullptr;
5246   uint64_t Members = 0;
5247   if (isHomogeneousAggregate(Ty, Base, Members)) {
5248     return ABIArgInfo::getDirect(
5249         llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members));
5250   }
5251 
5252   // Aggregates <= 16 bytes are passed directly in registers or on the stack.
5253   if (Size <= 128) {
5254     // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
5255     // same size and alignment.
5256     if (getTarget().isRenderScriptTarget()) {
5257       return coerceToIntArray(Ty, getContext(), getVMContext());
5258     }
5259     unsigned Alignment;
5260     if (Kind == AArch64ABIInfo::AAPCS) {
5261       Alignment = getContext().getTypeUnadjustedAlign(Ty);
5262       Alignment = Alignment < 128 ? 64 : 128;
5263     } else {
5264       Alignment = std::max(getContext().getTypeAlign(Ty),
5265                            (unsigned)getTarget().getPointerWidth(0));
5266     }
5267     Size = llvm::alignTo(Size, Alignment);
5268 
5269     // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
5270     // For aggregates with 16-byte alignment, we use i128.
5271     llvm::Type *BaseTy = llvm::Type::getIntNTy(getVMContext(), Alignment);
5272     return ABIArgInfo::getDirect(
5273         Size == Alignment ? BaseTy
5274                           : llvm::ArrayType::get(BaseTy, Size / Alignment));
5275   }
5276 
5277   return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
5278 }
5279 
5280 ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy,
5281                                               bool IsVariadic) const {
5282   if (RetTy->isVoidType())
5283     return ABIArgInfo::getIgnore();
5284 
5285   // Large vector types should be returned via memory.
5286   if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
5287     return getNaturalAlignIndirect(RetTy);
5288 
5289   if (!isAggregateTypeForABI(RetTy)) {
5290     // Treat an enum type as its underlying type.
5291     if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5292       RetTy = EnumTy->getDecl()->getIntegerType();
5293 
5294     return (RetTy->isPromotableIntegerType() && isDarwinPCS()
5295                 ? ABIArgInfo::getExtend(RetTy)
5296                 : ABIArgInfo::getDirect());
5297   }
5298 
5299   uint64_t Size = getContext().getTypeSize(RetTy);
5300   if (isEmptyRecord(getContext(), RetTy, true) || Size == 0)
5301     return ABIArgInfo::getIgnore();
5302 
5303   const Type *Base = nullptr;
5304   uint64_t Members = 0;
5305   if (isHomogeneousAggregate(RetTy, Base, Members) &&
5306       !(getTarget().getTriple().getArch() == llvm::Triple::aarch64_32 &&
5307         IsVariadic))
5308     // Homogeneous Floating-point Aggregates (HFAs) are returned directly.
5309     return ABIArgInfo::getDirect();
5310 
5311   // Aggregates <= 16 bytes are returned directly in registers or on the stack.
5312   if (Size <= 128) {
5313     // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
5314     // same size and alignment.
5315     if (getTarget().isRenderScriptTarget()) {
5316       return coerceToIntArray(RetTy, getContext(), getVMContext());
5317     }
5318     unsigned Alignment = getContext().getTypeAlign(RetTy);
5319     Size = llvm::alignTo(Size, 64); // round up to multiple of 8 bytes
5320 
5321     // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
5322     // For aggregates with 16-byte alignment, we use i128.
5323     if (Alignment < 128 && Size == 128) {
5324       llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
5325       return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
5326     }
5327     return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
5328   }
5329 
5330   return getNaturalAlignIndirect(RetTy);
5331 }
5332 
5333 /// isIllegalVectorType - check whether the vector type is legal for AArch64.
5334 bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const {
5335   if (const VectorType *VT = Ty->getAs<VectorType>()) {
5336     // Check whether VT is legal.
5337     unsigned NumElements = VT->getNumElements();
5338     uint64_t Size = getContext().getTypeSize(VT);
5339     // NumElements should be power of 2.
5340     if (!llvm::isPowerOf2_32(NumElements))
5341       return true;
5342 
5343     // arm64_32 has to be compatible with the ARM logic here, which allows huge
5344     // vectors for some reason.
5345     llvm::Triple Triple = getTarget().getTriple();
5346     if (Triple.getArch() == llvm::Triple::aarch64_32 &&
5347         Triple.isOSBinFormatMachO())
5348       return Size <= 32;
5349 
5350     return Size != 64 && (Size != 128 || NumElements == 1);
5351   }
5352   return false;
5353 }
5354 
5355 bool AArch64ABIInfo::isLegalVectorTypeForSwift(CharUnits totalSize,
5356                                                llvm::Type *eltTy,
5357                                                unsigned elts) const {
5358   if (!llvm::isPowerOf2_32(elts))
5359     return false;
5360   if (totalSize.getQuantity() != 8 &&
5361       (totalSize.getQuantity() != 16 || elts == 1))
5362     return false;
5363   return true;
5364 }
5365 
5366 bool AArch64ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
5367   // Homogeneous aggregates for AAPCS64 must have base types of a floating
5368   // point type or a short-vector type. This is the same as the 32-bit ABI,
5369   // but with the difference that any floating-point type is allowed,
5370   // including __fp16.
5371   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
5372     if (BT->isFloatingPoint())
5373       return true;
5374   } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
5375     unsigned VecSize = getContext().getTypeSize(VT);
5376     if (VecSize == 64 || VecSize == 128)
5377       return true;
5378   }
5379   return false;
5380 }
5381 
5382 bool AArch64ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
5383                                                        uint64_t Members) const {
5384   return Members <= 4;
5385 }
5386 
5387 Address AArch64ABIInfo::EmitAAPCSVAArg(Address VAListAddr,
5388                                             QualType Ty,
5389                                             CodeGenFunction &CGF) const {
5390   ABIArgInfo AI = classifyArgumentType(Ty);
5391   bool IsIndirect = AI.isIndirect();
5392 
5393   llvm::Type *BaseTy = CGF.ConvertType(Ty);
5394   if (IsIndirect)
5395     BaseTy = llvm::PointerType::getUnqual(BaseTy);
5396   else if (AI.getCoerceToType())
5397     BaseTy = AI.getCoerceToType();
5398 
5399   unsigned NumRegs = 1;
5400   if (llvm::ArrayType *ArrTy = dyn_cast<llvm::ArrayType>(BaseTy)) {
5401     BaseTy = ArrTy->getElementType();
5402     NumRegs = ArrTy->getNumElements();
5403   }
5404   bool IsFPR = BaseTy->isFloatingPointTy() || BaseTy->isVectorTy();
5405 
5406   // The AArch64 va_list type and handling is specified in the Procedure Call
5407   // Standard, section B.4:
5408   //
5409   // struct {
5410   //   void *__stack;
5411   //   void *__gr_top;
5412   //   void *__vr_top;
5413   //   int __gr_offs;
5414   //   int __vr_offs;
5415   // };
5416 
5417   llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
5418   llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
5419   llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
5420   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
5421 
5422   CharUnits TySize = getContext().getTypeSizeInChars(Ty);
5423   CharUnits TyAlign = getContext().getTypeUnadjustedAlignInChars(Ty);
5424 
5425   Address reg_offs_p = Address::invalid();
5426   llvm::Value *reg_offs = nullptr;
5427   int reg_top_index;
5428   int RegSize = IsIndirect ? 8 : TySize.getQuantity();
5429   if (!IsFPR) {
5430     // 3 is the field number of __gr_offs
5431     reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 3, "gr_offs_p");
5432     reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
5433     reg_top_index = 1; // field number for __gr_top
5434     RegSize = llvm::alignTo(RegSize, 8);
5435   } else {
5436     // 4 is the field number of __vr_offs.
5437     reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 4, "vr_offs_p");
5438     reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
5439     reg_top_index = 2; // field number for __vr_top
5440     RegSize = 16 * NumRegs;
5441   }
5442 
5443   //=======================================
5444   // Find out where argument was passed
5445   //=======================================
5446 
5447   // If reg_offs >= 0 we're already using the stack for this type of
5448   // argument. We don't want to keep updating reg_offs (in case it overflows,
5449   // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
5450   // whatever they get).
5451   llvm::Value *UsingStack = nullptr;
5452   UsingStack = CGF.Builder.CreateICmpSGE(
5453       reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0));
5454 
5455   CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
5456 
5457   // Otherwise, at least some kind of argument could go in these registers, the
5458   // question is whether this particular type is too big.
5459   CGF.EmitBlock(MaybeRegBlock);
5460 
5461   // Integer arguments may need to correct register alignment (for example a
5462   // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
5463   // align __gr_offs to calculate the potential address.
5464   if (!IsFPR && !IsIndirect && TyAlign.getQuantity() > 8) {
5465     int Align = TyAlign.getQuantity();
5466 
5467     reg_offs = CGF.Builder.CreateAdd(
5468         reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
5469         "align_regoffs");
5470     reg_offs = CGF.Builder.CreateAnd(
5471         reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align),
5472         "aligned_regoffs");
5473   }
5474 
5475   // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
5476   // The fact that this is done unconditionally reflects the fact that
5477   // allocating an argument to the stack also uses up all the remaining
5478   // registers of the appropriate kind.
5479   llvm::Value *NewOffset = nullptr;
5480   NewOffset = CGF.Builder.CreateAdd(
5481       reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs");
5482   CGF.Builder.CreateStore(NewOffset, reg_offs_p);
5483 
5484   // Now we're in a position to decide whether this argument really was in
5485   // registers or not.
5486   llvm::Value *InRegs = nullptr;
5487   InRegs = CGF.Builder.CreateICmpSLE(
5488       NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg");
5489 
5490   CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
5491 
5492   //=======================================
5493   // Argument was in registers
5494   //=======================================
5495 
5496   // Now we emit the code for if the argument was originally passed in
5497   // registers. First start the appropriate block:
5498   CGF.EmitBlock(InRegBlock);
5499 
5500   llvm::Value *reg_top = nullptr;
5501   Address reg_top_p =
5502       CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index, "reg_top_p");
5503   reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
5504   Address BaseAddr(CGF.Builder.CreateInBoundsGEP(reg_top, reg_offs),
5505                    CharUnits::fromQuantity(IsFPR ? 16 : 8));
5506   Address RegAddr = Address::invalid();
5507   llvm::Type *MemTy = CGF.ConvertTypeForMem(Ty);
5508 
5509   if (IsIndirect) {
5510     // If it's been passed indirectly (actually a struct), whatever we find from
5511     // stored registers or on the stack will actually be a struct **.
5512     MemTy = llvm::PointerType::getUnqual(MemTy);
5513   }
5514 
5515   const Type *Base = nullptr;
5516   uint64_t NumMembers = 0;
5517   bool IsHFA = isHomogeneousAggregate(Ty, Base, NumMembers);
5518   if (IsHFA && NumMembers > 1) {
5519     // Homogeneous aggregates passed in registers will have their elements split
5520     // and stored 16-bytes apart regardless of size (they're notionally in qN,
5521     // qN+1, ...). We reload and store into a temporary local variable
5522     // contiguously.
5523     assert(!IsIndirect && "Homogeneous aggregates should be passed directly");
5524     auto BaseTyInfo = getContext().getTypeInfoInChars(QualType(Base, 0));
5525     llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
5526     llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
5527     Address Tmp = CGF.CreateTempAlloca(HFATy,
5528                                        std::max(TyAlign, BaseTyInfo.second));
5529 
5530     // On big-endian platforms, the value will be right-aligned in its slot.
5531     int Offset = 0;
5532     if (CGF.CGM.getDataLayout().isBigEndian() &&
5533         BaseTyInfo.first.getQuantity() < 16)
5534       Offset = 16 - BaseTyInfo.first.getQuantity();
5535 
5536     for (unsigned i = 0; i < NumMembers; ++i) {
5537       CharUnits BaseOffset = CharUnits::fromQuantity(16 * i + Offset);
5538       Address LoadAddr =
5539         CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, BaseOffset);
5540       LoadAddr = CGF.Builder.CreateElementBitCast(LoadAddr, BaseTy);
5541 
5542       Address StoreAddr = CGF.Builder.CreateConstArrayGEP(Tmp, i);
5543 
5544       llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
5545       CGF.Builder.CreateStore(Elem, StoreAddr);
5546     }
5547 
5548     RegAddr = CGF.Builder.CreateElementBitCast(Tmp, MemTy);
5549   } else {
5550     // Otherwise the object is contiguous in memory.
5551 
5552     // It might be right-aligned in its slot.
5553     CharUnits SlotSize = BaseAddr.getAlignment();
5554     if (CGF.CGM.getDataLayout().isBigEndian() && !IsIndirect &&
5555         (IsHFA || !isAggregateTypeForABI(Ty)) &&
5556         TySize < SlotSize) {
5557       CharUnits Offset = SlotSize - TySize;
5558       BaseAddr = CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, Offset);
5559     }
5560 
5561     RegAddr = CGF.Builder.CreateElementBitCast(BaseAddr, MemTy);
5562   }
5563 
5564   CGF.EmitBranch(ContBlock);
5565 
5566   //=======================================
5567   // Argument was on the stack
5568   //=======================================
5569   CGF.EmitBlock(OnStackBlock);
5570 
5571   Address stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "stack_p");
5572   llvm::Value *OnStackPtr = CGF.Builder.CreateLoad(stack_p, "stack");
5573 
5574   // Again, stack arguments may need realignment. In this case both integer and
5575   // floating-point ones might be affected.
5576   if (!IsIndirect && TyAlign.getQuantity() > 8) {
5577     int Align = TyAlign.getQuantity();
5578 
5579     OnStackPtr = CGF.Builder.CreatePtrToInt(OnStackPtr, CGF.Int64Ty);
5580 
5581     OnStackPtr = CGF.Builder.CreateAdd(
5582         OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
5583         "align_stack");
5584     OnStackPtr = CGF.Builder.CreateAnd(
5585         OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, -Align),
5586         "align_stack");
5587 
5588     OnStackPtr = CGF.Builder.CreateIntToPtr(OnStackPtr, CGF.Int8PtrTy);
5589   }
5590   Address OnStackAddr(OnStackPtr,
5591                       std::max(CharUnits::fromQuantity(8), TyAlign));
5592 
5593   // All stack slots are multiples of 8 bytes.
5594   CharUnits StackSlotSize = CharUnits::fromQuantity(8);
5595   CharUnits StackSize;
5596   if (IsIndirect)
5597     StackSize = StackSlotSize;
5598   else
5599     StackSize = TySize.alignTo(StackSlotSize);
5600 
5601   llvm::Value *StackSizeC = CGF.Builder.getSize(StackSize);
5602   llvm::Value *NewStack =
5603       CGF.Builder.CreateInBoundsGEP(OnStackPtr, StackSizeC, "new_stack");
5604 
5605   // Write the new value of __stack for the next call to va_arg
5606   CGF.Builder.CreateStore(NewStack, stack_p);
5607 
5608   if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) &&
5609       TySize < StackSlotSize) {
5610     CharUnits Offset = StackSlotSize - TySize;
5611     OnStackAddr = CGF.Builder.CreateConstInBoundsByteGEP(OnStackAddr, Offset);
5612   }
5613 
5614   OnStackAddr = CGF.Builder.CreateElementBitCast(OnStackAddr, MemTy);
5615 
5616   CGF.EmitBranch(ContBlock);
5617 
5618   //=======================================
5619   // Tidy up
5620   //=======================================
5621   CGF.EmitBlock(ContBlock);
5622 
5623   Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
5624                                  OnStackAddr, OnStackBlock, "vaargs.addr");
5625 
5626   if (IsIndirect)
5627     return Address(CGF.Builder.CreateLoad(ResAddr, "vaarg.addr"),
5628                    TyAlign);
5629 
5630   return ResAddr;
5631 }
5632 
5633 Address AArch64ABIInfo::EmitDarwinVAArg(Address VAListAddr, QualType Ty,
5634                                         CodeGenFunction &CGF) const {
5635   // The backend's lowering doesn't support va_arg for aggregates or
5636   // illegal vector types.  Lower VAArg here for these cases and use
5637   // the LLVM va_arg instruction for everything else.
5638   if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty))
5639     return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
5640 
5641   uint64_t PointerSize = getTarget().getPointerWidth(0) / 8;
5642   CharUnits SlotSize = CharUnits::fromQuantity(PointerSize);
5643 
5644   // Empty records are ignored for parameter passing purposes.
5645   if (isEmptyRecord(getContext(), Ty, true)) {
5646     Address Addr(CGF.Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
5647     Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
5648     return Addr;
5649   }
5650 
5651   // The size of the actual thing passed, which might end up just
5652   // being a pointer for indirect types.
5653   auto TyInfo = getContext().getTypeInfoInChars(Ty);
5654 
5655   // Arguments bigger than 16 bytes which aren't homogeneous
5656   // aggregates should be passed indirectly.
5657   bool IsIndirect = false;
5658   if (TyInfo.first.getQuantity() > 16) {
5659     const Type *Base = nullptr;
5660     uint64_t Members = 0;
5661     IsIndirect = !isHomogeneousAggregate(Ty, Base, Members);
5662   }
5663 
5664   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
5665                           TyInfo, SlotSize, /*AllowHigherAlign*/ true);
5666 }
5667 
5668 Address AArch64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
5669                                     QualType Ty) const {
5670   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
5671                           CGF.getContext().getTypeInfoInChars(Ty),
5672                           CharUnits::fromQuantity(8),
5673                           /*allowHigherAlign*/ false);
5674 }
5675 
5676 //===----------------------------------------------------------------------===//
5677 // ARM ABI Implementation
5678 //===----------------------------------------------------------------------===//
5679 
5680 namespace {
5681 
5682 class ARMABIInfo : public SwiftABIInfo {
5683 public:
5684   enum ABIKind {
5685     APCS = 0,
5686     AAPCS = 1,
5687     AAPCS_VFP = 2,
5688     AAPCS16_VFP = 3,
5689   };
5690 
5691 private:
5692   ABIKind Kind;
5693 
5694 public:
5695   ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind)
5696       : SwiftABIInfo(CGT), Kind(_Kind) {
5697     setCCs();
5698   }
5699 
5700   bool isEABI() const {
5701     switch (getTarget().getTriple().getEnvironment()) {
5702     case llvm::Triple::Android:
5703     case llvm::Triple::EABI:
5704     case llvm::Triple::EABIHF:
5705     case llvm::Triple::GNUEABI:
5706     case llvm::Triple::GNUEABIHF:
5707     case llvm::Triple::MuslEABI:
5708     case llvm::Triple::MuslEABIHF:
5709       return true;
5710     default:
5711       return false;
5712     }
5713   }
5714 
5715   bool isEABIHF() const {
5716     switch (getTarget().getTriple().getEnvironment()) {
5717     case llvm::Triple::EABIHF:
5718     case llvm::Triple::GNUEABIHF:
5719     case llvm::Triple::MuslEABIHF:
5720       return true;
5721     default:
5722       return false;
5723     }
5724   }
5725 
5726   ABIKind getABIKind() const { return Kind; }
5727 
5728 private:
5729   ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic,
5730                                 unsigned functionCallConv) const;
5731   ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic,
5732                                   unsigned functionCallConv) const;
5733   ABIArgInfo classifyHomogeneousAggregate(QualType Ty, const Type *Base,
5734                                           uint64_t Members) const;
5735   ABIArgInfo coerceIllegalVector(QualType Ty) const;
5736   bool isIllegalVectorType(QualType Ty) const;
5737   bool containsAnyFP16Vectors(QualType Ty) const;
5738 
5739   bool isHomogeneousAggregateBaseType(QualType Ty) const override;
5740   bool isHomogeneousAggregateSmallEnough(const Type *Ty,
5741                                          uint64_t Members) const override;
5742 
5743   bool isEffectivelyAAPCS_VFP(unsigned callConvention, bool acceptHalf) const;
5744 
5745   void computeInfo(CGFunctionInfo &FI) const override;
5746 
5747   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5748                     QualType Ty) const override;
5749 
5750   llvm::CallingConv::ID getLLVMDefaultCC() const;
5751   llvm::CallingConv::ID getABIDefaultCC() const;
5752   void setCCs();
5753 
5754   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
5755                                     bool asReturnValue) const override {
5756     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
5757   }
5758   bool isSwiftErrorInRegister() const override {
5759     return true;
5760   }
5761   bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy,
5762                                  unsigned elts) const override;
5763 };
5764 
5765 class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
5766 public:
5767   ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
5768     :TargetCodeGenInfo(new ARMABIInfo(CGT, K)) {}
5769 
5770   const ARMABIInfo &getABIInfo() const {
5771     return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
5772   }
5773 
5774   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
5775     return 13;
5776   }
5777 
5778   StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
5779     return "mov\tr7, r7\t\t// marker for objc_retainAutoreleaseReturnValue";
5780   }
5781 
5782   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
5783                                llvm::Value *Address) const override {
5784     llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
5785 
5786     // 0-15 are the 16 integer registers.
5787     AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
5788     return false;
5789   }
5790 
5791   unsigned getSizeOfUnwindException() const override {
5792     if (getABIInfo().isEABI()) return 88;
5793     return TargetCodeGenInfo::getSizeOfUnwindException();
5794   }
5795 
5796   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5797                            CodeGen::CodeGenModule &CGM) const override {
5798     if (GV->isDeclaration())
5799       return;
5800     const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
5801     if (!FD)
5802       return;
5803 
5804     const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
5805     if (!Attr)
5806       return;
5807 
5808     const char *Kind;
5809     switch (Attr->getInterrupt()) {
5810     case ARMInterruptAttr::Generic: Kind = ""; break;
5811     case ARMInterruptAttr::IRQ:     Kind = "IRQ"; break;
5812     case ARMInterruptAttr::FIQ:     Kind = "FIQ"; break;
5813     case ARMInterruptAttr::SWI:     Kind = "SWI"; break;
5814     case ARMInterruptAttr::ABORT:   Kind = "ABORT"; break;
5815     case ARMInterruptAttr::UNDEF:   Kind = "UNDEF"; break;
5816     }
5817 
5818     llvm::Function *Fn = cast<llvm::Function>(GV);
5819 
5820     Fn->addFnAttr("interrupt", Kind);
5821 
5822     ARMABIInfo::ABIKind ABI = cast<ARMABIInfo>(getABIInfo()).getABIKind();
5823     if (ABI == ARMABIInfo::APCS)
5824       return;
5825 
5826     // AAPCS guarantees that sp will be 8-byte aligned on any public interface,
5827     // however this is not necessarily true on taking any interrupt. Instruct
5828     // the backend to perform a realignment as part of the function prologue.
5829     llvm::AttrBuilder B;
5830     B.addStackAlignmentAttr(8);
5831     Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
5832   }
5833 };
5834 
5835 class WindowsARMTargetCodeGenInfo : public ARMTargetCodeGenInfo {
5836 public:
5837   WindowsARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
5838       : ARMTargetCodeGenInfo(CGT, K) {}
5839 
5840   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5841                            CodeGen::CodeGenModule &CGM) const override;
5842 
5843   void getDependentLibraryOption(llvm::StringRef Lib,
5844                                  llvm::SmallString<24> &Opt) const override {
5845     Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib);
5846   }
5847 
5848   void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value,
5849                                llvm::SmallString<32> &Opt) const override {
5850     Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
5851   }
5852 };
5853 
5854 void WindowsARMTargetCodeGenInfo::setTargetAttributes(
5855     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
5856   ARMTargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
5857   if (GV->isDeclaration())
5858     return;
5859   addStackProbeTargetAttributes(D, GV, CGM);
5860 }
5861 }
5862 
5863 void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
5864   if (!::classifyReturnType(getCXXABI(), FI, *this))
5865     FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), FI.isVariadic(),
5866                                             FI.getCallingConvention());
5867 
5868   for (auto &I : FI.arguments())
5869     I.info = classifyArgumentType(I.type, FI.isVariadic(),
5870                                   FI.getCallingConvention());
5871 
5872 
5873   // Always honor user-specified calling convention.
5874   if (FI.getCallingConvention() != llvm::CallingConv::C)
5875     return;
5876 
5877   llvm::CallingConv::ID cc = getRuntimeCC();
5878   if (cc != llvm::CallingConv::C)
5879     FI.setEffectiveCallingConvention(cc);
5880 }
5881 
5882 /// Return the default calling convention that LLVM will use.
5883 llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
5884   // The default calling convention that LLVM will infer.
5885   if (isEABIHF() || getTarget().getTriple().isWatchABI())
5886     return llvm::CallingConv::ARM_AAPCS_VFP;
5887   else if (isEABI())
5888     return llvm::CallingConv::ARM_AAPCS;
5889   else
5890     return llvm::CallingConv::ARM_APCS;
5891 }
5892 
5893 /// Return the calling convention that our ABI would like us to use
5894 /// as the C calling convention.
5895 llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
5896   switch (getABIKind()) {
5897   case APCS: return llvm::CallingConv::ARM_APCS;
5898   case AAPCS: return llvm::CallingConv::ARM_AAPCS;
5899   case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
5900   case AAPCS16_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
5901   }
5902   llvm_unreachable("bad ABI kind");
5903 }
5904 
5905 void ARMABIInfo::setCCs() {
5906   assert(getRuntimeCC() == llvm::CallingConv::C);
5907 
5908   // Don't muddy up the IR with a ton of explicit annotations if
5909   // they'd just match what LLVM will infer from the triple.
5910   llvm::CallingConv::ID abiCC = getABIDefaultCC();
5911   if (abiCC != getLLVMDefaultCC())
5912     RuntimeCC = abiCC;
5913 }
5914 
5915 ABIArgInfo ARMABIInfo::coerceIllegalVector(QualType Ty) const {
5916   uint64_t Size = getContext().getTypeSize(Ty);
5917   if (Size <= 32) {
5918     llvm::Type *ResType =
5919         llvm::Type::getInt32Ty(getVMContext());
5920     return ABIArgInfo::getDirect(ResType);
5921   }
5922   if (Size == 64 || Size == 128) {
5923     llvm::Type *ResType = llvm::VectorType::get(
5924         llvm::Type::getInt32Ty(getVMContext()), Size / 32);
5925     return ABIArgInfo::getDirect(ResType);
5926   }
5927   return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
5928 }
5929 
5930 ABIArgInfo ARMABIInfo::classifyHomogeneousAggregate(QualType Ty,
5931                                                     const Type *Base,
5932                                                     uint64_t Members) const {
5933   assert(Base && "Base class should be set for homogeneous aggregate");
5934   // Base can be a floating-point or a vector.
5935   if (const VectorType *VT = Base->getAs<VectorType>()) {
5936     // FP16 vectors should be converted to integer vectors
5937     if (!getTarget().hasLegalHalfType() && containsAnyFP16Vectors(Ty)) {
5938       uint64_t Size = getContext().getTypeSize(VT);
5939       llvm::Type *NewVecTy = llvm::VectorType::get(
5940           llvm::Type::getInt32Ty(getVMContext()), Size / 32);
5941       llvm::Type *Ty = llvm::ArrayType::get(NewVecTy, Members);
5942       return ABIArgInfo::getDirect(Ty, 0, nullptr, false);
5943     }
5944   }
5945   return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
5946 }
5947 
5948 ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty, bool isVariadic,
5949                                             unsigned functionCallConv) const {
5950   // 6.1.2.1 The following argument types are VFP CPRCs:
5951   //   A single-precision floating-point type (including promoted
5952   //   half-precision types); A double-precision floating-point type;
5953   //   A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
5954   //   with a Base Type of a single- or double-precision floating-point type,
5955   //   64-bit containerized vectors or 128-bit containerized vectors with one
5956   //   to four Elements.
5957   // Variadic functions should always marshal to the base standard.
5958   bool IsAAPCS_VFP =
5959       !isVariadic && isEffectivelyAAPCS_VFP(functionCallConv, /* AAPCS16 */ false);
5960 
5961   Ty = useFirstFieldIfTransparentUnion(Ty);
5962 
5963   // Handle illegal vector types here.
5964   if (isIllegalVectorType(Ty))
5965     return coerceIllegalVector(Ty);
5966 
5967   // _Float16 and __fp16 get passed as if it were an int or float, but with
5968   // the top 16 bits unspecified. This is not done for OpenCL as it handles the
5969   // half type natively, and does not need to interwork with AAPCS code.
5970   if ((Ty->isFloat16Type() || Ty->isHalfType()) &&
5971       !getContext().getLangOpts().NativeHalfArgsAndReturns) {
5972     llvm::Type *ResType = IsAAPCS_VFP ?
5973       llvm::Type::getFloatTy(getVMContext()) :
5974       llvm::Type::getInt32Ty(getVMContext());
5975     return ABIArgInfo::getDirect(ResType);
5976   }
5977 
5978   if (!isAggregateTypeForABI(Ty)) {
5979     // Treat an enum type as its underlying type.
5980     if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
5981       Ty = EnumTy->getDecl()->getIntegerType();
5982     }
5983 
5984     return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty)
5985                                           : ABIArgInfo::getDirect());
5986   }
5987 
5988   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
5989     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
5990   }
5991 
5992   // Ignore empty records.
5993   if (isEmptyRecord(getContext(), Ty, true))
5994     return ABIArgInfo::getIgnore();
5995 
5996   if (IsAAPCS_VFP) {
5997     // Homogeneous Aggregates need to be expanded when we can fit the aggregate
5998     // into VFP registers.
5999     const Type *Base = nullptr;
6000     uint64_t Members = 0;
6001     if (isHomogeneousAggregate(Ty, Base, Members))
6002       return classifyHomogeneousAggregate(Ty, Base, Members);
6003   } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
6004     // WatchOS does have homogeneous aggregates. Note that we intentionally use
6005     // this convention even for a variadic function: the backend will use GPRs
6006     // if needed.
6007     const Type *Base = nullptr;
6008     uint64_t Members = 0;
6009     if (isHomogeneousAggregate(Ty, Base, Members)) {
6010       assert(Base && Members <= 4 && "unexpected homogeneous aggregate");
6011       llvm::Type *Ty =
6012         llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members);
6013       return ABIArgInfo::getDirect(Ty, 0, nullptr, false);
6014     }
6015   }
6016 
6017   if (getABIKind() == ARMABIInfo::AAPCS16_VFP &&
6018       getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(16)) {
6019     // WatchOS is adopting the 64-bit AAPCS rule on composite types: if they're
6020     // bigger than 128-bits, they get placed in space allocated by the caller,
6021     // and a pointer is passed.
6022     return ABIArgInfo::getIndirect(
6023         CharUnits::fromQuantity(getContext().getTypeAlign(Ty) / 8), false);
6024   }
6025 
6026   // Support byval for ARM.
6027   // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
6028   // most 8-byte. We realign the indirect argument if type alignment is bigger
6029   // than ABI alignment.
6030   uint64_t ABIAlign = 4;
6031   uint64_t TyAlign;
6032   if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
6033       getABIKind() == ARMABIInfo::AAPCS) {
6034     TyAlign = getContext().getTypeUnadjustedAlignInChars(Ty).getQuantity();
6035     ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
6036   } else {
6037     TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity();
6038   }
6039   if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
6040     assert(getABIKind() != ARMABIInfo::AAPCS16_VFP && "unexpected byval");
6041     return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
6042                                    /*ByVal=*/true,
6043                                    /*Realign=*/TyAlign > ABIAlign);
6044   }
6045 
6046   // On RenderScript, coerce Aggregates <= 64 bytes to an integer array of
6047   // same size and alignment.
6048   if (getTarget().isRenderScriptTarget()) {
6049     return coerceToIntArray(Ty, getContext(), getVMContext());
6050   }
6051 
6052   // Otherwise, pass by coercing to a structure of the appropriate size.
6053   llvm::Type* ElemTy;
6054   unsigned SizeRegs;
6055   // FIXME: Try to match the types of the arguments more accurately where
6056   // we can.
6057   if (TyAlign <= 4) {
6058     ElemTy = llvm::Type::getInt32Ty(getVMContext());
6059     SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
6060   } else {
6061     ElemTy = llvm::Type::getInt64Ty(getVMContext());
6062     SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
6063   }
6064 
6065   return ABIArgInfo::getDirect(llvm::ArrayType::get(ElemTy, SizeRegs));
6066 }
6067 
6068 static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
6069                               llvm::LLVMContext &VMContext) {
6070   // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
6071   // is called integer-like if its size is less than or equal to one word, and
6072   // the offset of each of its addressable sub-fields is zero.
6073 
6074   uint64_t Size = Context.getTypeSize(Ty);
6075 
6076   // Check that the type fits in a word.
6077   if (Size > 32)
6078     return false;
6079 
6080   // FIXME: Handle vector types!
6081   if (Ty->isVectorType())
6082     return false;
6083 
6084   // Float types are never treated as "integer like".
6085   if (Ty->isRealFloatingType())
6086     return false;
6087 
6088   // If this is a builtin or pointer type then it is ok.
6089   if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
6090     return true;
6091 
6092   // Small complex integer types are "integer like".
6093   if (const ComplexType *CT = Ty->getAs<ComplexType>())
6094     return isIntegerLikeType(CT->getElementType(), Context, VMContext);
6095 
6096   // Single element and zero sized arrays should be allowed, by the definition
6097   // above, but they are not.
6098 
6099   // Otherwise, it must be a record type.
6100   const RecordType *RT = Ty->getAs<RecordType>();
6101   if (!RT) return false;
6102 
6103   // Ignore records with flexible arrays.
6104   const RecordDecl *RD = RT->getDecl();
6105   if (RD->hasFlexibleArrayMember())
6106     return false;
6107 
6108   // Check that all sub-fields are at offset 0, and are themselves "integer
6109   // like".
6110   const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
6111 
6112   bool HadField = false;
6113   unsigned idx = 0;
6114   for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
6115        i != e; ++i, ++idx) {
6116     const FieldDecl *FD = *i;
6117 
6118     // Bit-fields are not addressable, we only need to verify they are "integer
6119     // like". We still have to disallow a subsequent non-bitfield, for example:
6120     //   struct { int : 0; int x }
6121     // is non-integer like according to gcc.
6122     if (FD->isBitField()) {
6123       if (!RD->isUnion())
6124         HadField = true;
6125 
6126       if (!isIntegerLikeType(FD->getType(), Context, VMContext))
6127         return false;
6128 
6129       continue;
6130     }
6131 
6132     // Check if this field is at offset 0.
6133     if (Layout.getFieldOffset(idx) != 0)
6134       return false;
6135 
6136     if (!isIntegerLikeType(FD->getType(), Context, VMContext))
6137       return false;
6138 
6139     // Only allow at most one field in a structure. This doesn't match the
6140     // wording above, but follows gcc in situations with a field following an
6141     // empty structure.
6142     if (!RD->isUnion()) {
6143       if (HadField)
6144         return false;
6145 
6146       HadField = true;
6147     }
6148   }
6149 
6150   return true;
6151 }
6152 
6153 ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy, bool isVariadic,
6154                                           unsigned functionCallConv) const {
6155 
6156   // Variadic functions should always marshal to the base standard.
6157   bool IsAAPCS_VFP =
6158       !isVariadic && isEffectivelyAAPCS_VFP(functionCallConv, /* AAPCS16 */ true);
6159 
6160   if (RetTy->isVoidType())
6161     return ABIArgInfo::getIgnore();
6162 
6163   if (const VectorType *VT = RetTy->getAs<VectorType>()) {
6164     // Large vector types should be returned via memory.
6165     if (getContext().getTypeSize(RetTy) > 128)
6166       return getNaturalAlignIndirect(RetTy);
6167     // FP16 vectors should be converted to integer vectors
6168     if (!getTarget().hasLegalHalfType() &&
6169         (VT->getElementType()->isFloat16Type() ||
6170          VT->getElementType()->isHalfType()))
6171       return coerceIllegalVector(RetTy);
6172   }
6173 
6174   // _Float16 and __fp16 get returned as if it were an int or float, but with
6175   // the top 16 bits unspecified. This is not done for OpenCL as it handles the
6176   // half type natively, and does not need to interwork with AAPCS code.
6177   if ((RetTy->isFloat16Type() || RetTy->isHalfType()) &&
6178       !getContext().getLangOpts().NativeHalfArgsAndReturns) {
6179     llvm::Type *ResType = IsAAPCS_VFP ?
6180       llvm::Type::getFloatTy(getVMContext()) :
6181       llvm::Type::getInt32Ty(getVMContext());
6182     return ABIArgInfo::getDirect(ResType);
6183   }
6184 
6185   if (!isAggregateTypeForABI(RetTy)) {
6186     // Treat an enum type as its underlying type.
6187     if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6188       RetTy = EnumTy->getDecl()->getIntegerType();
6189 
6190     return RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy)
6191                                             : ABIArgInfo::getDirect();
6192   }
6193 
6194   // Are we following APCS?
6195   if (getABIKind() == APCS) {
6196     if (isEmptyRecord(getContext(), RetTy, false))
6197       return ABIArgInfo::getIgnore();
6198 
6199     // Complex types are all returned as packed integers.
6200     //
6201     // FIXME: Consider using 2 x vector types if the back end handles them
6202     // correctly.
6203     if (RetTy->isAnyComplexType())
6204       return ABIArgInfo::getDirect(llvm::IntegerType::get(
6205           getVMContext(), getContext().getTypeSize(RetTy)));
6206 
6207     // Integer like structures are returned in r0.
6208     if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
6209       // Return in the smallest viable integer type.
6210       uint64_t Size = getContext().getTypeSize(RetTy);
6211       if (Size <= 8)
6212         return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6213       if (Size <= 16)
6214         return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6215       return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6216     }
6217 
6218     // Otherwise return in memory.
6219     return getNaturalAlignIndirect(RetTy);
6220   }
6221 
6222   // Otherwise this is an AAPCS variant.
6223 
6224   if (isEmptyRecord(getContext(), RetTy, true))
6225     return ABIArgInfo::getIgnore();
6226 
6227   // Check for homogeneous aggregates with AAPCS-VFP.
6228   if (IsAAPCS_VFP) {
6229     const Type *Base = nullptr;
6230     uint64_t Members = 0;
6231     if (isHomogeneousAggregate(RetTy, Base, Members))
6232       return classifyHomogeneousAggregate(RetTy, Base, Members);
6233   }
6234 
6235   // Aggregates <= 4 bytes are returned in r0; other aggregates
6236   // are returned indirectly.
6237   uint64_t Size = getContext().getTypeSize(RetTy);
6238   if (Size <= 32) {
6239     // On RenderScript, coerce Aggregates <= 4 bytes to an integer array of
6240     // same size and alignment.
6241     if (getTarget().isRenderScriptTarget()) {
6242       return coerceToIntArray(RetTy, getContext(), getVMContext());
6243     }
6244     if (getDataLayout().isBigEndian())
6245       // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4)
6246       return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6247 
6248     // Return in the smallest viable integer type.
6249     if (Size <= 8)
6250       return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6251     if (Size <= 16)
6252       return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6253     return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6254   } else if (Size <= 128 && getABIKind() == AAPCS16_VFP) {
6255     llvm::Type *Int32Ty = llvm::Type::getInt32Ty(getVMContext());
6256     llvm::Type *CoerceTy =
6257         llvm::ArrayType::get(Int32Ty, llvm::alignTo(Size, 32) / 32);
6258     return ABIArgInfo::getDirect(CoerceTy);
6259   }
6260 
6261   return getNaturalAlignIndirect(RetTy);
6262 }
6263 
6264 /// isIllegalVector - check whether Ty is an illegal vector type.
6265 bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
6266   if (const VectorType *VT = Ty->getAs<VectorType> ()) {
6267     // On targets that don't support FP16, FP16 is expanded into float, and we
6268     // don't want the ABI to depend on whether or not FP16 is supported in
6269     // hardware. Thus return false to coerce FP16 vectors into integer vectors.
6270     if (!getTarget().hasLegalHalfType() &&
6271         (VT->getElementType()->isFloat16Type() ||
6272          VT->getElementType()->isHalfType()))
6273       return true;
6274     if (isAndroid()) {
6275       // Android shipped using Clang 3.1, which supported a slightly different
6276       // vector ABI. The primary differences were that 3-element vector types
6277       // were legal, and so were sub 32-bit vectors (i.e. <2 x i8>). This path
6278       // accepts that legacy behavior for Android only.
6279       // Check whether VT is legal.
6280       unsigned NumElements = VT->getNumElements();
6281       // NumElements should be power of 2 or equal to 3.
6282       if (!llvm::isPowerOf2_32(NumElements) && NumElements != 3)
6283         return true;
6284     } else {
6285       // Check whether VT is legal.
6286       unsigned NumElements = VT->getNumElements();
6287       uint64_t Size = getContext().getTypeSize(VT);
6288       // NumElements should be power of 2.
6289       if (!llvm::isPowerOf2_32(NumElements))
6290         return true;
6291       // Size should be greater than 32 bits.
6292       return Size <= 32;
6293     }
6294   }
6295   return false;
6296 }
6297 
6298 /// Return true if a type contains any 16-bit floating point vectors
6299 bool ARMABIInfo::containsAnyFP16Vectors(QualType Ty) const {
6300   if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
6301     uint64_t NElements = AT->getSize().getZExtValue();
6302     if (NElements == 0)
6303       return false;
6304     return containsAnyFP16Vectors(AT->getElementType());
6305   } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
6306     const RecordDecl *RD = RT->getDecl();
6307 
6308     // If this is a C++ record, check the bases first.
6309     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
6310       if (llvm::any_of(CXXRD->bases(), [this](const CXXBaseSpecifier &B) {
6311             return containsAnyFP16Vectors(B.getType());
6312           }))
6313         return true;
6314 
6315     if (llvm::any_of(RD->fields(), [this](FieldDecl *FD) {
6316           return FD && containsAnyFP16Vectors(FD->getType());
6317         }))
6318       return true;
6319 
6320     return false;
6321   } else {
6322     if (const VectorType *VT = Ty->getAs<VectorType>())
6323       return (VT->getElementType()->isFloat16Type() ||
6324               VT->getElementType()->isHalfType());
6325     return false;
6326   }
6327 }
6328 
6329 bool ARMABIInfo::isLegalVectorTypeForSwift(CharUnits vectorSize,
6330                                            llvm::Type *eltTy,
6331                                            unsigned numElts) const {
6332   if (!llvm::isPowerOf2_32(numElts))
6333     return false;
6334   unsigned size = getDataLayout().getTypeStoreSizeInBits(eltTy);
6335   if (size > 64)
6336     return false;
6337   if (vectorSize.getQuantity() != 8 &&
6338       (vectorSize.getQuantity() != 16 || numElts == 1))
6339     return false;
6340   return true;
6341 }
6342 
6343 bool ARMABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
6344   // Homogeneous aggregates for AAPCS-VFP must have base types of float,
6345   // double, or 64-bit or 128-bit vectors.
6346   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
6347     if (BT->getKind() == BuiltinType::Float ||
6348         BT->getKind() == BuiltinType::Double ||
6349         BT->getKind() == BuiltinType::LongDouble)
6350       return true;
6351   } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
6352     unsigned VecSize = getContext().getTypeSize(VT);
6353     if (VecSize == 64 || VecSize == 128)
6354       return true;
6355   }
6356   return false;
6357 }
6358 
6359 bool ARMABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
6360                                                    uint64_t Members) const {
6361   return Members <= 4;
6362 }
6363 
6364 bool ARMABIInfo::isEffectivelyAAPCS_VFP(unsigned callConvention,
6365                                         bool acceptHalf) const {
6366   // Give precedence to user-specified calling conventions.
6367   if (callConvention != llvm::CallingConv::C)
6368     return (callConvention == llvm::CallingConv::ARM_AAPCS_VFP);
6369   else
6370     return (getABIKind() == AAPCS_VFP) ||
6371            (acceptHalf && (getABIKind() == AAPCS16_VFP));
6372 }
6373 
6374 Address ARMABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6375                               QualType Ty) const {
6376   CharUnits SlotSize = CharUnits::fromQuantity(4);
6377 
6378   // Empty records are ignored for parameter passing purposes.
6379   if (isEmptyRecord(getContext(), Ty, true)) {
6380     Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize);
6381     Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
6382     return Addr;
6383   }
6384 
6385   CharUnits TySize = getContext().getTypeSizeInChars(Ty);
6386   CharUnits TyAlignForABI = getContext().getTypeUnadjustedAlignInChars(Ty);
6387 
6388   // Use indirect if size of the illegal vector is bigger than 16 bytes.
6389   bool IsIndirect = false;
6390   const Type *Base = nullptr;
6391   uint64_t Members = 0;
6392   if (TySize > CharUnits::fromQuantity(16) && isIllegalVectorType(Ty)) {
6393     IsIndirect = true;
6394 
6395   // ARMv7k passes structs bigger than 16 bytes indirectly, in space
6396   // allocated by the caller.
6397   } else if (TySize > CharUnits::fromQuantity(16) &&
6398              getABIKind() == ARMABIInfo::AAPCS16_VFP &&
6399              !isHomogeneousAggregate(Ty, Base, Members)) {
6400     IsIndirect = true;
6401 
6402   // Otherwise, bound the type's ABI alignment.
6403   // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
6404   // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
6405   // Our callers should be prepared to handle an under-aligned address.
6406   } else if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
6407              getABIKind() == ARMABIInfo::AAPCS) {
6408     TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
6409     TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(8));
6410   } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
6411     // ARMv7k allows type alignment up to 16 bytes.
6412     TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
6413     TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(16));
6414   } else {
6415     TyAlignForABI = CharUnits::fromQuantity(4);
6416   }
6417 
6418   std::pair<CharUnits, CharUnits> TyInfo = { TySize, TyAlignForABI };
6419   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TyInfo,
6420                           SlotSize, /*AllowHigherAlign*/ true);
6421 }
6422 
6423 //===----------------------------------------------------------------------===//
6424 // NVPTX ABI Implementation
6425 //===----------------------------------------------------------------------===//
6426 
6427 namespace {
6428 
6429 class NVPTXABIInfo : public ABIInfo {
6430 public:
6431   NVPTXABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
6432 
6433   ABIArgInfo classifyReturnType(QualType RetTy) const;
6434   ABIArgInfo classifyArgumentType(QualType Ty) const;
6435 
6436   void computeInfo(CGFunctionInfo &FI) const override;
6437   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6438                     QualType Ty) const override;
6439 };
6440 
6441 class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
6442 public:
6443   NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
6444     : TargetCodeGenInfo(new NVPTXABIInfo(CGT)) {}
6445 
6446   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
6447                            CodeGen::CodeGenModule &M) const override;
6448   bool shouldEmitStaticExternCAliases() const override;
6449 
6450 private:
6451   // Adds a NamedMDNode with F, Name, and Operand as operands, and adds the
6452   // resulting MDNode to the nvvm.annotations MDNode.
6453   static void addNVVMMetadata(llvm::Function *F, StringRef Name, int Operand);
6454 };
6455 
6456 /// Checks if the type is unsupported directly by the current target.
6457 static bool isUnsupportedType(ASTContext &Context, QualType T) {
6458   if (!Context.getTargetInfo().hasFloat16Type() && T->isFloat16Type())
6459     return true;
6460   if (!Context.getTargetInfo().hasFloat128Type() &&
6461       (T->isFloat128Type() ||
6462        (T->isRealFloatingType() && Context.getTypeSize(T) == 128)))
6463     return true;
6464   if (!Context.getTargetInfo().hasInt128Type() && T->isIntegerType() &&
6465       Context.getTypeSize(T) > 64)
6466     return true;
6467   if (const auto *AT = T->getAsArrayTypeUnsafe())
6468     return isUnsupportedType(Context, AT->getElementType());
6469   const auto *RT = T->getAs<RecordType>();
6470   if (!RT)
6471     return false;
6472   const RecordDecl *RD = RT->getDecl();
6473 
6474   // If this is a C++ record, check the bases first.
6475   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
6476     for (const CXXBaseSpecifier &I : CXXRD->bases())
6477       if (isUnsupportedType(Context, I.getType()))
6478         return true;
6479 
6480   for (const FieldDecl *I : RD->fields())
6481     if (isUnsupportedType(Context, I->getType()))
6482       return true;
6483   return false;
6484 }
6485 
6486 /// Coerce the given type into an array with maximum allowed size of elements.
6487 static ABIArgInfo coerceToIntArrayWithLimit(QualType Ty, ASTContext &Context,
6488                                             llvm::LLVMContext &LLVMContext,
6489                                             unsigned MaxSize) {
6490   // Alignment and Size are measured in bits.
6491   const uint64_t Size = Context.getTypeSize(Ty);
6492   const uint64_t Alignment = Context.getTypeAlign(Ty);
6493   const unsigned Div = std::min<unsigned>(MaxSize, Alignment);
6494   llvm::Type *IntType = llvm::Type::getIntNTy(LLVMContext, Div);
6495   const uint64_t NumElements = (Size + Div - 1) / Div;
6496   return ABIArgInfo::getDirect(llvm::ArrayType::get(IntType, NumElements));
6497 }
6498 
6499 ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
6500   if (RetTy->isVoidType())
6501     return ABIArgInfo::getIgnore();
6502 
6503   if (getContext().getLangOpts().OpenMP &&
6504       getContext().getLangOpts().OpenMPIsDevice &&
6505       isUnsupportedType(getContext(), RetTy))
6506     return coerceToIntArrayWithLimit(RetTy, getContext(), getVMContext(), 64);
6507 
6508   // note: this is different from default ABI
6509   if (!RetTy->isScalarType())
6510     return ABIArgInfo::getDirect();
6511 
6512   // Treat an enum type as its underlying type.
6513   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6514     RetTy = EnumTy->getDecl()->getIntegerType();
6515 
6516   return (RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy)
6517                                            : ABIArgInfo::getDirect());
6518 }
6519 
6520 ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
6521   // Treat an enum type as its underlying type.
6522   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6523     Ty = EnumTy->getDecl()->getIntegerType();
6524 
6525   // Return aggregates type as indirect by value
6526   if (isAggregateTypeForABI(Ty))
6527     return getNaturalAlignIndirect(Ty, /* byval */ true);
6528 
6529   return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty)
6530                                         : ABIArgInfo::getDirect());
6531 }
6532 
6533 void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
6534   if (!getCXXABI().classifyReturnType(FI))
6535     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
6536   for (auto &I : FI.arguments())
6537     I.info = classifyArgumentType(I.type);
6538 
6539   // Always honor user-specified calling convention.
6540   if (FI.getCallingConvention() != llvm::CallingConv::C)
6541     return;
6542 
6543   FI.setEffectiveCallingConvention(getRuntimeCC());
6544 }
6545 
6546 Address NVPTXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6547                                 QualType Ty) const {
6548   llvm_unreachable("NVPTX does not support varargs");
6549 }
6550 
6551 void NVPTXTargetCodeGenInfo::setTargetAttributes(
6552     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
6553   if (GV->isDeclaration())
6554     return;
6555   const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
6556   if (!FD) return;
6557 
6558   llvm::Function *F = cast<llvm::Function>(GV);
6559 
6560   // Perform special handling in OpenCL mode
6561   if (M.getLangOpts().OpenCL) {
6562     // Use OpenCL function attributes to check for kernel functions
6563     // By default, all functions are device functions
6564     if (FD->hasAttr<OpenCLKernelAttr>()) {
6565       // OpenCL __kernel functions get kernel metadata
6566       // Create !{<func-ref>, metadata !"kernel", i32 1} node
6567       addNVVMMetadata(F, "kernel", 1);
6568       // And kernel functions are not subject to inlining
6569       F->addFnAttr(llvm::Attribute::NoInline);
6570     }
6571   }
6572 
6573   // Perform special handling in CUDA mode.
6574   if (M.getLangOpts().CUDA) {
6575     // CUDA __global__ functions get a kernel metadata entry.  Since
6576     // __global__ functions cannot be called from the device, we do not
6577     // need to set the noinline attribute.
6578     if (FD->hasAttr<CUDAGlobalAttr>()) {
6579       // Create !{<func-ref>, metadata !"kernel", i32 1} node
6580       addNVVMMetadata(F, "kernel", 1);
6581     }
6582     if (CUDALaunchBoundsAttr *Attr = FD->getAttr<CUDALaunchBoundsAttr>()) {
6583       // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node
6584       llvm::APSInt MaxThreads(32);
6585       MaxThreads = Attr->getMaxThreads()->EvaluateKnownConstInt(M.getContext());
6586       if (MaxThreads > 0)
6587         addNVVMMetadata(F, "maxntidx", MaxThreads.getExtValue());
6588 
6589       // min blocks is an optional argument for CUDALaunchBoundsAttr. If it was
6590       // not specified in __launch_bounds__ or if the user specified a 0 value,
6591       // we don't have to add a PTX directive.
6592       if (Attr->getMinBlocks()) {
6593         llvm::APSInt MinBlocks(32);
6594         MinBlocks = Attr->getMinBlocks()->EvaluateKnownConstInt(M.getContext());
6595         if (MinBlocks > 0)
6596           // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node
6597           addNVVMMetadata(F, "minctasm", MinBlocks.getExtValue());
6598       }
6599     }
6600   }
6601 }
6602 
6603 void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::Function *F, StringRef Name,
6604                                              int Operand) {
6605   llvm::Module *M = F->getParent();
6606   llvm::LLVMContext &Ctx = M->getContext();
6607 
6608   // Get "nvvm.annotations" metadata node
6609   llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
6610 
6611   llvm::Metadata *MDVals[] = {
6612       llvm::ConstantAsMetadata::get(F), llvm::MDString::get(Ctx, Name),
6613       llvm::ConstantAsMetadata::get(
6614           llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand))};
6615   // Append metadata to nvvm.annotations
6616   MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
6617 }
6618 
6619 bool NVPTXTargetCodeGenInfo::shouldEmitStaticExternCAliases() const {
6620   return false;
6621 }
6622 }
6623 
6624 //===----------------------------------------------------------------------===//
6625 // SystemZ ABI Implementation
6626 //===----------------------------------------------------------------------===//
6627 
6628 namespace {
6629 
6630 class SystemZABIInfo : public SwiftABIInfo {
6631   bool HasVector;
6632 
6633 public:
6634   SystemZABIInfo(CodeGenTypes &CGT, bool HV)
6635     : SwiftABIInfo(CGT), HasVector(HV) {}
6636 
6637   bool isPromotableIntegerType(QualType Ty) const;
6638   bool isCompoundType(QualType Ty) const;
6639   bool isVectorArgumentType(QualType Ty) const;
6640   bool isFPArgumentType(QualType Ty) const;
6641   QualType GetSingleElementType(QualType Ty) const;
6642 
6643   ABIArgInfo classifyReturnType(QualType RetTy) const;
6644   ABIArgInfo classifyArgumentType(QualType ArgTy) const;
6645 
6646   void computeInfo(CGFunctionInfo &FI) const override {
6647     if (!getCXXABI().classifyReturnType(FI))
6648       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
6649     for (auto &I : FI.arguments())
6650       I.info = classifyArgumentType(I.type);
6651   }
6652 
6653   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6654                     QualType Ty) const override;
6655 
6656   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
6657                                     bool asReturnValue) const override {
6658     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
6659   }
6660   bool isSwiftErrorInRegister() const override {
6661     return false;
6662   }
6663 };
6664 
6665 class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
6666 public:
6667   SystemZTargetCodeGenInfo(CodeGenTypes &CGT, bool HasVector)
6668     : TargetCodeGenInfo(new SystemZABIInfo(CGT, HasVector)) {}
6669 };
6670 
6671 }
6672 
6673 bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const {
6674   // Treat an enum type as its underlying type.
6675   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6676     Ty = EnumTy->getDecl()->getIntegerType();
6677 
6678   // Promotable integer types are required to be promoted by the ABI.
6679   if (Ty->isPromotableIntegerType())
6680     return true;
6681 
6682   // 32-bit values must also be promoted.
6683   if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
6684     switch (BT->getKind()) {
6685     case BuiltinType::Int:
6686     case BuiltinType::UInt:
6687       return true;
6688     default:
6689       return false;
6690     }
6691   return false;
6692 }
6693 
6694 bool SystemZABIInfo::isCompoundType(QualType Ty) const {
6695   return (Ty->isAnyComplexType() ||
6696           Ty->isVectorType() ||
6697           isAggregateTypeForABI(Ty));
6698 }
6699 
6700 bool SystemZABIInfo::isVectorArgumentType(QualType Ty) const {
6701   return (HasVector &&
6702           Ty->isVectorType() &&
6703           getContext().getTypeSize(Ty) <= 128);
6704 }
6705 
6706 bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
6707   if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
6708     switch (BT->getKind()) {
6709     case BuiltinType::Float:
6710     case BuiltinType::Double:
6711       return true;
6712     default:
6713       return false;
6714     }
6715 
6716   return false;
6717 }
6718 
6719 QualType SystemZABIInfo::GetSingleElementType(QualType Ty) const {
6720   if (const RecordType *RT = Ty->getAsStructureType()) {
6721     const RecordDecl *RD = RT->getDecl();
6722     QualType Found;
6723 
6724     // If this is a C++ record, check the bases first.
6725     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
6726       for (const auto &I : CXXRD->bases()) {
6727         QualType Base = I.getType();
6728 
6729         // Empty bases don't affect things either way.
6730         if (isEmptyRecord(getContext(), Base, true))
6731           continue;
6732 
6733         if (!Found.isNull())
6734           return Ty;
6735         Found = GetSingleElementType(Base);
6736       }
6737 
6738     // Check the fields.
6739     for (const auto *FD : RD->fields()) {
6740       // For compatibility with GCC, ignore empty bitfields in C++ mode.
6741       // Unlike isSingleElementStruct(), empty structure and array fields
6742       // do count.  So do anonymous bitfields that aren't zero-sized.
6743       if (getContext().getLangOpts().CPlusPlus &&
6744           FD->isZeroLengthBitField(getContext()))
6745         continue;
6746 
6747       // Unlike isSingleElementStruct(), arrays do not count.
6748       // Nested structures still do though.
6749       if (!Found.isNull())
6750         return Ty;
6751       Found = GetSingleElementType(FD->getType());
6752     }
6753 
6754     // Unlike isSingleElementStruct(), trailing padding is allowed.
6755     // An 8-byte aligned struct s { float f; } is passed as a double.
6756     if (!Found.isNull())
6757       return Found;
6758   }
6759 
6760   return Ty;
6761 }
6762 
6763 Address SystemZABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6764                                   QualType Ty) const {
6765   // Assume that va_list type is correct; should be pointer to LLVM type:
6766   // struct {
6767   //   i64 __gpr;
6768   //   i64 __fpr;
6769   //   i8 *__overflow_arg_area;
6770   //   i8 *__reg_save_area;
6771   // };
6772 
6773   // Every non-vector argument occupies 8 bytes and is passed by preference
6774   // in either GPRs or FPRs.  Vector arguments occupy 8 or 16 bytes and are
6775   // always passed on the stack.
6776   Ty = getContext().getCanonicalType(Ty);
6777   auto TyInfo = getContext().getTypeInfoInChars(Ty);
6778   llvm::Type *ArgTy = CGF.ConvertTypeForMem(Ty);
6779   llvm::Type *DirectTy = ArgTy;
6780   ABIArgInfo AI = classifyArgumentType(Ty);
6781   bool IsIndirect = AI.isIndirect();
6782   bool InFPRs = false;
6783   bool IsVector = false;
6784   CharUnits UnpaddedSize;
6785   CharUnits DirectAlign;
6786   if (IsIndirect) {
6787     DirectTy = llvm::PointerType::getUnqual(DirectTy);
6788     UnpaddedSize = DirectAlign = CharUnits::fromQuantity(8);
6789   } else {
6790     if (AI.getCoerceToType())
6791       ArgTy = AI.getCoerceToType();
6792     InFPRs = ArgTy->isFloatTy() || ArgTy->isDoubleTy();
6793     IsVector = ArgTy->isVectorTy();
6794     UnpaddedSize = TyInfo.first;
6795     DirectAlign = TyInfo.second;
6796   }
6797   CharUnits PaddedSize = CharUnits::fromQuantity(8);
6798   if (IsVector && UnpaddedSize > PaddedSize)
6799     PaddedSize = CharUnits::fromQuantity(16);
6800   assert((UnpaddedSize <= PaddedSize) && "Invalid argument size.");
6801 
6802   CharUnits Padding = (PaddedSize - UnpaddedSize);
6803 
6804   llvm::Type *IndexTy = CGF.Int64Ty;
6805   llvm::Value *PaddedSizeV =
6806     llvm::ConstantInt::get(IndexTy, PaddedSize.getQuantity());
6807 
6808   if (IsVector) {
6809     // Work out the address of a vector argument on the stack.
6810     // Vector arguments are always passed in the high bits of a
6811     // single (8 byte) or double (16 byte) stack slot.
6812     Address OverflowArgAreaPtr =
6813         CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr");
6814     Address OverflowArgArea =
6815       Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
6816               TyInfo.second);
6817     Address MemAddr =
6818       CGF.Builder.CreateElementBitCast(OverflowArgArea, DirectTy, "mem_addr");
6819 
6820     // Update overflow_arg_area_ptr pointer
6821     llvm::Value *NewOverflowArgArea =
6822       CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
6823                             "overflow_arg_area");
6824     CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
6825 
6826     return MemAddr;
6827   }
6828 
6829   assert(PaddedSize.getQuantity() == 8);
6830 
6831   unsigned MaxRegs, RegCountField, RegSaveIndex;
6832   CharUnits RegPadding;
6833   if (InFPRs) {
6834     MaxRegs = 4; // Maximum of 4 FPR arguments
6835     RegCountField = 1; // __fpr
6836     RegSaveIndex = 16; // save offset for f0
6837     RegPadding = CharUnits(); // floats are passed in the high bits of an FPR
6838   } else {
6839     MaxRegs = 5; // Maximum of 5 GPR arguments
6840     RegCountField = 0; // __gpr
6841     RegSaveIndex = 2; // save offset for r2
6842     RegPadding = Padding; // values are passed in the low bits of a GPR
6843   }
6844 
6845   Address RegCountPtr =
6846       CGF.Builder.CreateStructGEP(VAListAddr, RegCountField, "reg_count_ptr");
6847   llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
6848   llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
6849   llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
6850                                                  "fits_in_regs");
6851 
6852   llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
6853   llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
6854   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
6855   CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
6856 
6857   // Emit code to load the value if it was passed in registers.
6858   CGF.EmitBlock(InRegBlock);
6859 
6860   // Work out the address of an argument register.
6861   llvm::Value *ScaledRegCount =
6862     CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
6863   llvm::Value *RegBase =
6864     llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize.getQuantity()
6865                                       + RegPadding.getQuantity());
6866   llvm::Value *RegOffset =
6867     CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
6868   Address RegSaveAreaPtr =
6869       CGF.Builder.CreateStructGEP(VAListAddr, 3, "reg_save_area_ptr");
6870   llvm::Value *RegSaveArea =
6871     CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
6872   Address RawRegAddr(CGF.Builder.CreateGEP(RegSaveArea, RegOffset,
6873                                            "raw_reg_addr"),
6874                      PaddedSize);
6875   Address RegAddr =
6876     CGF.Builder.CreateElementBitCast(RawRegAddr, DirectTy, "reg_addr");
6877 
6878   // Update the register count
6879   llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
6880   llvm::Value *NewRegCount =
6881     CGF.Builder.CreateAdd(RegCount, One, "reg_count");
6882   CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
6883   CGF.EmitBranch(ContBlock);
6884 
6885   // Emit code to load the value if it was passed in memory.
6886   CGF.EmitBlock(InMemBlock);
6887 
6888   // Work out the address of a stack argument.
6889   Address OverflowArgAreaPtr =
6890       CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr");
6891   Address OverflowArgArea =
6892     Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
6893             PaddedSize);
6894   Address RawMemAddr =
6895     CGF.Builder.CreateConstByteGEP(OverflowArgArea, Padding, "raw_mem_addr");
6896   Address MemAddr =
6897     CGF.Builder.CreateElementBitCast(RawMemAddr, DirectTy, "mem_addr");
6898 
6899   // Update overflow_arg_area_ptr pointer
6900   llvm::Value *NewOverflowArgArea =
6901     CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
6902                           "overflow_arg_area");
6903   CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
6904   CGF.EmitBranch(ContBlock);
6905 
6906   // Return the appropriate result.
6907   CGF.EmitBlock(ContBlock);
6908   Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
6909                                  MemAddr, InMemBlock, "va_arg.addr");
6910 
6911   if (IsIndirect)
6912     ResAddr = Address(CGF.Builder.CreateLoad(ResAddr, "indirect_arg"),
6913                       TyInfo.second);
6914 
6915   return ResAddr;
6916 }
6917 
6918 ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
6919   if (RetTy->isVoidType())
6920     return ABIArgInfo::getIgnore();
6921   if (isVectorArgumentType(RetTy))
6922     return ABIArgInfo::getDirect();
6923   if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
6924     return getNaturalAlignIndirect(RetTy);
6925   return (isPromotableIntegerType(RetTy) ? ABIArgInfo::getExtend(RetTy)
6926                                          : ABIArgInfo::getDirect());
6927 }
6928 
6929 ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
6930   // Handle the generic C++ ABI.
6931   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
6932     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
6933 
6934   // Integers and enums are extended to full register width.
6935   if (isPromotableIntegerType(Ty))
6936     return ABIArgInfo::getExtend(Ty);
6937 
6938   // Handle vector types and vector-like structure types.  Note that
6939   // as opposed to float-like structure types, we do not allow any
6940   // padding for vector-like structures, so verify the sizes match.
6941   uint64_t Size = getContext().getTypeSize(Ty);
6942   QualType SingleElementTy = GetSingleElementType(Ty);
6943   if (isVectorArgumentType(SingleElementTy) &&
6944       getContext().getTypeSize(SingleElementTy) == Size)
6945     return ABIArgInfo::getDirect(CGT.ConvertType(SingleElementTy));
6946 
6947   // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
6948   if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
6949     return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
6950 
6951   // Handle small structures.
6952   if (const RecordType *RT = Ty->getAs<RecordType>()) {
6953     // Structures with flexible arrays have variable length, so really
6954     // fail the size test above.
6955     const RecordDecl *RD = RT->getDecl();
6956     if (RD->hasFlexibleArrayMember())
6957       return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
6958 
6959     // The structure is passed as an unextended integer, a float, or a double.
6960     llvm::Type *PassTy;
6961     if (isFPArgumentType(SingleElementTy)) {
6962       assert(Size == 32 || Size == 64);
6963       if (Size == 32)
6964         PassTy = llvm::Type::getFloatTy(getVMContext());
6965       else
6966         PassTy = llvm::Type::getDoubleTy(getVMContext());
6967     } else
6968       PassTy = llvm::IntegerType::get(getVMContext(), Size);
6969     return ABIArgInfo::getDirect(PassTy);
6970   }
6971 
6972   // Non-structure compounds are passed indirectly.
6973   if (isCompoundType(Ty))
6974     return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
6975 
6976   return ABIArgInfo::getDirect(nullptr);
6977 }
6978 
6979 //===----------------------------------------------------------------------===//
6980 // MSP430 ABI Implementation
6981 //===----------------------------------------------------------------------===//
6982 
6983 namespace {
6984 
6985 class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
6986 public:
6987   MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
6988     : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
6989   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
6990                            CodeGen::CodeGenModule &M) const override;
6991 };
6992 
6993 }
6994 
6995 void MSP430TargetCodeGenInfo::setTargetAttributes(
6996     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
6997   if (GV->isDeclaration())
6998     return;
6999   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
7000     const auto *InterruptAttr = FD->getAttr<MSP430InterruptAttr>();
7001     if (!InterruptAttr)
7002       return;
7003 
7004     // Handle 'interrupt' attribute:
7005     llvm::Function *F = cast<llvm::Function>(GV);
7006 
7007     // Step 1: Set ISR calling convention.
7008     F->setCallingConv(llvm::CallingConv::MSP430_INTR);
7009 
7010     // Step 2: Add attributes goodness.
7011     F->addFnAttr(llvm::Attribute::NoInline);
7012     F->addFnAttr("interrupt", llvm::utostr(InterruptAttr->getNumber()));
7013   }
7014 }
7015 
7016 //===----------------------------------------------------------------------===//
7017 // MIPS ABI Implementation.  This works for both little-endian and
7018 // big-endian variants.
7019 //===----------------------------------------------------------------------===//
7020 
7021 namespace {
7022 class MipsABIInfo : public ABIInfo {
7023   bool IsO32;
7024   unsigned MinABIStackAlignInBytes, StackAlignInBytes;
7025   void CoerceToIntArgs(uint64_t TySize,
7026                        SmallVectorImpl<llvm::Type *> &ArgList) const;
7027   llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
7028   llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
7029   llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
7030 public:
7031   MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
7032     ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
7033     StackAlignInBytes(IsO32 ? 8 : 16) {}
7034 
7035   ABIArgInfo classifyReturnType(QualType RetTy) const;
7036   ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
7037   void computeInfo(CGFunctionInfo &FI) const override;
7038   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7039                     QualType Ty) const override;
7040   ABIArgInfo extendType(QualType Ty) const;
7041 };
7042 
7043 class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
7044   unsigned SizeOfUnwindException;
7045 public:
7046   MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
7047     : TargetCodeGenInfo(new MipsABIInfo(CGT, IsO32)),
7048       SizeOfUnwindException(IsO32 ? 24 : 32) {}
7049 
7050   int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
7051     return 29;
7052   }
7053 
7054   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
7055                            CodeGen::CodeGenModule &CGM) const override {
7056     const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
7057     if (!FD) return;
7058     llvm::Function *Fn = cast<llvm::Function>(GV);
7059 
7060     if (FD->hasAttr<MipsLongCallAttr>())
7061       Fn->addFnAttr("long-call");
7062     else if (FD->hasAttr<MipsShortCallAttr>())
7063       Fn->addFnAttr("short-call");
7064 
7065     // Other attributes do not have a meaning for declarations.
7066     if (GV->isDeclaration())
7067       return;
7068 
7069     if (FD->hasAttr<Mips16Attr>()) {
7070       Fn->addFnAttr("mips16");
7071     }
7072     else if (FD->hasAttr<NoMips16Attr>()) {
7073       Fn->addFnAttr("nomips16");
7074     }
7075 
7076     if (FD->hasAttr<MicroMipsAttr>())
7077       Fn->addFnAttr("micromips");
7078     else if (FD->hasAttr<NoMicroMipsAttr>())
7079       Fn->addFnAttr("nomicromips");
7080 
7081     const MipsInterruptAttr *Attr = FD->getAttr<MipsInterruptAttr>();
7082     if (!Attr)
7083       return;
7084 
7085     const char *Kind;
7086     switch (Attr->getInterrupt()) {
7087     case MipsInterruptAttr::eic:     Kind = "eic"; break;
7088     case MipsInterruptAttr::sw0:     Kind = "sw0"; break;
7089     case MipsInterruptAttr::sw1:     Kind = "sw1"; break;
7090     case MipsInterruptAttr::hw0:     Kind = "hw0"; break;
7091     case MipsInterruptAttr::hw1:     Kind = "hw1"; break;
7092     case MipsInterruptAttr::hw2:     Kind = "hw2"; break;
7093     case MipsInterruptAttr::hw3:     Kind = "hw3"; break;
7094     case MipsInterruptAttr::hw4:     Kind = "hw4"; break;
7095     case MipsInterruptAttr::hw5:     Kind = "hw5"; break;
7096     }
7097 
7098     Fn->addFnAttr("interrupt", Kind);
7099 
7100   }
7101 
7102   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
7103                                llvm::Value *Address) const override;
7104 
7105   unsigned getSizeOfUnwindException() const override {
7106     return SizeOfUnwindException;
7107   }
7108 };
7109 }
7110 
7111 void MipsABIInfo::CoerceToIntArgs(
7112     uint64_t TySize, SmallVectorImpl<llvm::Type *> &ArgList) const {
7113   llvm::IntegerType *IntTy =
7114     llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
7115 
7116   // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
7117   for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
7118     ArgList.push_back(IntTy);
7119 
7120   // If necessary, add one more integer type to ArgList.
7121   unsigned R = TySize % (MinABIStackAlignInBytes * 8);
7122 
7123   if (R)
7124     ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
7125 }
7126 
7127 // In N32/64, an aligned double precision floating point field is passed in
7128 // a register.
7129 llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
7130   SmallVector<llvm::Type*, 8> ArgList, IntArgList;
7131 
7132   if (IsO32) {
7133     CoerceToIntArgs(TySize, ArgList);
7134     return llvm::StructType::get(getVMContext(), ArgList);
7135   }
7136 
7137   if (Ty->isComplexType())
7138     return CGT.ConvertType(Ty);
7139 
7140   const RecordType *RT = Ty->getAs<RecordType>();
7141 
7142   // Unions/vectors are passed in integer registers.
7143   if (!RT || !RT->isStructureOrClassType()) {
7144     CoerceToIntArgs(TySize, ArgList);
7145     return llvm::StructType::get(getVMContext(), ArgList);
7146   }
7147 
7148   const RecordDecl *RD = RT->getDecl();
7149   const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
7150   assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
7151 
7152   uint64_t LastOffset = 0;
7153   unsigned idx = 0;
7154   llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
7155 
7156   // Iterate over fields in the struct/class and check if there are any aligned
7157   // double fields.
7158   for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
7159        i != e; ++i, ++idx) {
7160     const QualType Ty = i->getType();
7161     const BuiltinType *BT = Ty->getAs<BuiltinType>();
7162 
7163     if (!BT || BT->getKind() != BuiltinType::Double)
7164       continue;
7165 
7166     uint64_t Offset = Layout.getFieldOffset(idx);
7167     if (Offset % 64) // Ignore doubles that are not aligned.
7168       continue;
7169 
7170     // Add ((Offset - LastOffset) / 64) args of type i64.
7171     for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
7172       ArgList.push_back(I64);
7173 
7174     // Add double type.
7175     ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
7176     LastOffset = Offset + 64;
7177   }
7178 
7179   CoerceToIntArgs(TySize - LastOffset, IntArgList);
7180   ArgList.append(IntArgList.begin(), IntArgList.end());
7181 
7182   return llvm::StructType::get(getVMContext(), ArgList);
7183 }
7184 
7185 llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
7186                                         uint64_t Offset) const {
7187   if (OrigOffset + MinABIStackAlignInBytes > Offset)
7188     return nullptr;
7189 
7190   return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
7191 }
7192 
7193 ABIArgInfo
7194 MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
7195   Ty = useFirstFieldIfTransparentUnion(Ty);
7196 
7197   uint64_t OrigOffset = Offset;
7198   uint64_t TySize = getContext().getTypeSize(Ty);
7199   uint64_t Align = getContext().getTypeAlign(Ty) / 8;
7200 
7201   Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
7202                    (uint64_t)StackAlignInBytes);
7203   unsigned CurrOffset = llvm::alignTo(Offset, Align);
7204   Offset = CurrOffset + llvm::alignTo(TySize, Align * 8) / 8;
7205 
7206   if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
7207     // Ignore empty aggregates.
7208     if (TySize == 0)
7209       return ABIArgInfo::getIgnore();
7210 
7211     if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
7212       Offset = OrigOffset + MinABIStackAlignInBytes;
7213       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
7214     }
7215 
7216     // If we have reached here, aggregates are passed directly by coercing to
7217     // another structure type. Padding is inserted if the offset of the
7218     // aggregate is unaligned.
7219     ABIArgInfo ArgInfo =
7220         ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
7221                               getPaddingType(OrigOffset, CurrOffset));
7222     ArgInfo.setInReg(true);
7223     return ArgInfo;
7224   }
7225 
7226   // Treat an enum type as its underlying type.
7227   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7228     Ty = EnumTy->getDecl()->getIntegerType();
7229 
7230   // All integral types are promoted to the GPR width.
7231   if (Ty->isIntegralOrEnumerationType())
7232     return extendType(Ty);
7233 
7234   return ABIArgInfo::getDirect(
7235       nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset));
7236 }
7237 
7238 llvm::Type*
7239 MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
7240   const RecordType *RT = RetTy->getAs<RecordType>();
7241   SmallVector<llvm::Type*, 8> RTList;
7242 
7243   if (RT && RT->isStructureOrClassType()) {
7244     const RecordDecl *RD = RT->getDecl();
7245     const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
7246     unsigned FieldCnt = Layout.getFieldCount();
7247 
7248     // N32/64 returns struct/classes in floating point registers if the
7249     // following conditions are met:
7250     // 1. The size of the struct/class is no larger than 128-bit.
7251     // 2. The struct/class has one or two fields all of which are floating
7252     //    point types.
7253     // 3. The offset of the first field is zero (this follows what gcc does).
7254     //
7255     // Any other composite results are returned in integer registers.
7256     //
7257     if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
7258       RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
7259       for (; b != e; ++b) {
7260         const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
7261 
7262         if (!BT || !BT->isFloatingPoint())
7263           break;
7264 
7265         RTList.push_back(CGT.ConvertType(b->getType()));
7266       }
7267 
7268       if (b == e)
7269         return llvm::StructType::get(getVMContext(), RTList,
7270                                      RD->hasAttr<PackedAttr>());
7271 
7272       RTList.clear();
7273     }
7274   }
7275 
7276   CoerceToIntArgs(Size, RTList);
7277   return llvm::StructType::get(getVMContext(), RTList);
7278 }
7279 
7280 ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
7281   uint64_t Size = getContext().getTypeSize(RetTy);
7282 
7283   if (RetTy->isVoidType())
7284     return ABIArgInfo::getIgnore();
7285 
7286   // O32 doesn't treat zero-sized structs differently from other structs.
7287   // However, N32/N64 ignores zero sized return values.
7288   if (!IsO32 && Size == 0)
7289     return ABIArgInfo::getIgnore();
7290 
7291   if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
7292     if (Size <= 128) {
7293       if (RetTy->isAnyComplexType())
7294         return ABIArgInfo::getDirect();
7295 
7296       // O32 returns integer vectors in registers and N32/N64 returns all small
7297       // aggregates in registers.
7298       if (!IsO32 ||
7299           (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) {
7300         ABIArgInfo ArgInfo =
7301             ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
7302         ArgInfo.setInReg(true);
7303         return ArgInfo;
7304       }
7305     }
7306 
7307     return getNaturalAlignIndirect(RetTy);
7308   }
7309 
7310   // Treat an enum type as its underlying type.
7311   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
7312     RetTy = EnumTy->getDecl()->getIntegerType();
7313 
7314   if (RetTy->isPromotableIntegerType())
7315     return ABIArgInfo::getExtend(RetTy);
7316 
7317   if ((RetTy->isUnsignedIntegerOrEnumerationType() ||
7318       RetTy->isSignedIntegerOrEnumerationType()) && Size == 32 && !IsO32)
7319     return ABIArgInfo::getSignExtend(RetTy);
7320 
7321   return ABIArgInfo::getDirect();
7322 }
7323 
7324 void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
7325   ABIArgInfo &RetInfo = FI.getReturnInfo();
7326   if (!getCXXABI().classifyReturnType(FI))
7327     RetInfo = classifyReturnType(FI.getReturnType());
7328 
7329   // Check if a pointer to an aggregate is passed as a hidden argument.
7330   uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
7331 
7332   for (auto &I : FI.arguments())
7333     I.info = classifyArgumentType(I.type, Offset);
7334 }
7335 
7336 Address MipsABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7337                                QualType OrigTy) const {
7338   QualType Ty = OrigTy;
7339 
7340   // Integer arguments are promoted to 32-bit on O32 and 64-bit on N32/N64.
7341   // Pointers are also promoted in the same way but this only matters for N32.
7342   unsigned SlotSizeInBits = IsO32 ? 32 : 64;
7343   unsigned PtrWidth = getTarget().getPointerWidth(0);
7344   bool DidPromote = false;
7345   if ((Ty->isIntegerType() &&
7346           getContext().getIntWidth(Ty) < SlotSizeInBits) ||
7347       (Ty->isPointerType() && PtrWidth < SlotSizeInBits)) {
7348     DidPromote = true;
7349     Ty = getContext().getIntTypeForBitwidth(SlotSizeInBits,
7350                                             Ty->isSignedIntegerType());
7351   }
7352 
7353   auto TyInfo = getContext().getTypeInfoInChars(Ty);
7354 
7355   // The alignment of things in the argument area is never larger than
7356   // StackAlignInBytes.
7357   TyInfo.second =
7358     std::min(TyInfo.second, CharUnits::fromQuantity(StackAlignInBytes));
7359 
7360   // MinABIStackAlignInBytes is the size of argument slots on the stack.
7361   CharUnits ArgSlotSize = CharUnits::fromQuantity(MinABIStackAlignInBytes);
7362 
7363   Address Addr = emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
7364                           TyInfo, ArgSlotSize, /*AllowHigherAlign*/ true);
7365 
7366 
7367   // If there was a promotion, "unpromote" into a temporary.
7368   // TODO: can we just use a pointer into a subset of the original slot?
7369   if (DidPromote) {
7370     Address Temp = CGF.CreateMemTemp(OrigTy, "vaarg.promotion-temp");
7371     llvm::Value *Promoted = CGF.Builder.CreateLoad(Addr);
7372 
7373     // Truncate down to the right width.
7374     llvm::Type *IntTy = (OrigTy->isIntegerType() ? Temp.getElementType()
7375                                                  : CGF.IntPtrTy);
7376     llvm::Value *V = CGF.Builder.CreateTrunc(Promoted, IntTy);
7377     if (OrigTy->isPointerType())
7378       V = CGF.Builder.CreateIntToPtr(V, Temp.getElementType());
7379 
7380     CGF.Builder.CreateStore(V, Temp);
7381     Addr = Temp;
7382   }
7383 
7384   return Addr;
7385 }
7386 
7387 ABIArgInfo MipsABIInfo::extendType(QualType Ty) const {
7388   int TySize = getContext().getTypeSize(Ty);
7389 
7390   // MIPS64 ABI requires unsigned 32 bit integers to be sign extended.
7391   if (Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
7392     return ABIArgInfo::getSignExtend(Ty);
7393 
7394   return ABIArgInfo::getExtend(Ty);
7395 }
7396 
7397 bool
7398 MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
7399                                                llvm::Value *Address) const {
7400   // This information comes from gcc's implementation, which seems to
7401   // as canonical as it gets.
7402 
7403   // Everything on MIPS is 4 bytes.  Double-precision FP registers
7404   // are aliased to pairs of single-precision FP registers.
7405   llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
7406 
7407   // 0-31 are the general purpose registers, $0 - $31.
7408   // 32-63 are the floating-point registers, $f0 - $f31.
7409   // 64 and 65 are the multiply/divide registers, $hi and $lo.
7410   // 66 is the (notional, I think) register for signal-handler return.
7411   AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
7412 
7413   // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
7414   // They are one bit wide and ignored here.
7415 
7416   // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
7417   // (coprocessor 1 is the FP unit)
7418   // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
7419   // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
7420   // 176-181 are the DSP accumulator registers.
7421   AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
7422   return false;
7423 }
7424 
7425 //===----------------------------------------------------------------------===//
7426 // AVR ABI Implementation.
7427 //===----------------------------------------------------------------------===//
7428 
7429 namespace {
7430 class AVRTargetCodeGenInfo : public TargetCodeGenInfo {
7431 public:
7432   AVRTargetCodeGenInfo(CodeGenTypes &CGT)
7433     : TargetCodeGenInfo(new DefaultABIInfo(CGT)) { }
7434 
7435   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
7436                            CodeGen::CodeGenModule &CGM) const override {
7437     if (GV->isDeclaration())
7438       return;
7439     const auto *FD = dyn_cast_or_null<FunctionDecl>(D);
7440     if (!FD) return;
7441     auto *Fn = cast<llvm::Function>(GV);
7442 
7443     if (FD->getAttr<AVRInterruptAttr>())
7444       Fn->addFnAttr("interrupt");
7445 
7446     if (FD->getAttr<AVRSignalAttr>())
7447       Fn->addFnAttr("signal");
7448   }
7449 };
7450 }
7451 
7452 //===----------------------------------------------------------------------===//
7453 // TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
7454 // Currently subclassed only to implement custom OpenCL C function attribute
7455 // handling.
7456 //===----------------------------------------------------------------------===//
7457 
7458 namespace {
7459 
7460 class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
7461 public:
7462   TCETargetCodeGenInfo(CodeGenTypes &CGT)
7463     : DefaultTargetCodeGenInfo(CGT) {}
7464 
7465   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
7466                            CodeGen::CodeGenModule &M) const override;
7467 };
7468 
7469 void TCETargetCodeGenInfo::setTargetAttributes(
7470     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
7471   if (GV->isDeclaration())
7472     return;
7473   const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
7474   if (!FD) return;
7475 
7476   llvm::Function *F = cast<llvm::Function>(GV);
7477 
7478   if (M.getLangOpts().OpenCL) {
7479     if (FD->hasAttr<OpenCLKernelAttr>()) {
7480       // OpenCL C Kernel functions are not subject to inlining
7481       F->addFnAttr(llvm::Attribute::NoInline);
7482       const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
7483       if (Attr) {
7484         // Convert the reqd_work_group_size() attributes to metadata.
7485         llvm::LLVMContext &Context = F->getContext();
7486         llvm::NamedMDNode *OpenCLMetadata =
7487             M.getModule().getOrInsertNamedMetadata(
7488                 "opencl.kernel_wg_size_info");
7489 
7490         SmallVector<llvm::Metadata *, 5> Operands;
7491         Operands.push_back(llvm::ConstantAsMetadata::get(F));
7492 
7493         Operands.push_back(
7494             llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
7495                 M.Int32Ty, llvm::APInt(32, Attr->getXDim()))));
7496         Operands.push_back(
7497             llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
7498                 M.Int32Ty, llvm::APInt(32, Attr->getYDim()))));
7499         Operands.push_back(
7500             llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
7501                 M.Int32Ty, llvm::APInt(32, Attr->getZDim()))));
7502 
7503         // Add a boolean constant operand for "required" (true) or "hint"
7504         // (false) for implementing the work_group_size_hint attr later.
7505         // Currently always true as the hint is not yet implemented.
7506         Operands.push_back(
7507             llvm::ConstantAsMetadata::get(llvm::ConstantInt::getTrue(Context)));
7508         OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
7509       }
7510     }
7511   }
7512 }
7513 
7514 }
7515 
7516 //===----------------------------------------------------------------------===//
7517 // Hexagon ABI Implementation
7518 //===----------------------------------------------------------------------===//
7519 
7520 namespace {
7521 
7522 class HexagonABIInfo : public ABIInfo {
7523 
7524 
7525 public:
7526   HexagonABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
7527 
7528 private:
7529 
7530   ABIArgInfo classifyReturnType(QualType RetTy) const;
7531   ABIArgInfo classifyArgumentType(QualType RetTy) const;
7532 
7533   void computeInfo(CGFunctionInfo &FI) const override;
7534 
7535   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7536                     QualType Ty) const override;
7537 };
7538 
7539 class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
7540 public:
7541   HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
7542     :TargetCodeGenInfo(new HexagonABIInfo(CGT)) {}
7543 
7544   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
7545     return 29;
7546   }
7547 };
7548 
7549 }
7550 
7551 void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
7552   if (!getCXXABI().classifyReturnType(FI))
7553     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7554   for (auto &I : FI.arguments())
7555     I.info = classifyArgumentType(I.type);
7556 }
7557 
7558 ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty) const {
7559   if (!isAggregateTypeForABI(Ty)) {
7560     // Treat an enum type as its underlying type.
7561     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7562       Ty = EnumTy->getDecl()->getIntegerType();
7563 
7564     return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty)
7565                                           : ABIArgInfo::getDirect());
7566   }
7567 
7568   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
7569     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
7570 
7571   // Ignore empty records.
7572   if (isEmptyRecord(getContext(), Ty, true))
7573     return ABIArgInfo::getIgnore();
7574 
7575   uint64_t Size = getContext().getTypeSize(Ty);
7576   if (Size > 64)
7577     return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
7578     // Pass in the smallest viable integer type.
7579   else if (Size > 32)
7580       return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
7581   else if (Size > 16)
7582       return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
7583   else if (Size > 8)
7584       return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
7585   else
7586       return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
7587 }
7588 
7589 ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
7590   if (RetTy->isVoidType())
7591     return ABIArgInfo::getIgnore();
7592 
7593   // Large vector types should be returned via memory.
7594   if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 64)
7595     return getNaturalAlignIndirect(RetTy);
7596 
7597   if (!isAggregateTypeForABI(RetTy)) {
7598     // Treat an enum type as its underlying type.
7599     if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
7600       RetTy = EnumTy->getDecl()->getIntegerType();
7601 
7602     return (RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy)
7603                                              : ABIArgInfo::getDirect());
7604   }
7605 
7606   if (isEmptyRecord(getContext(), RetTy, true))
7607     return ABIArgInfo::getIgnore();
7608 
7609   // Aggregates <= 8 bytes are returned in r0; other aggregates
7610   // are returned indirectly.
7611   uint64_t Size = getContext().getTypeSize(RetTy);
7612   if (Size <= 64) {
7613     // Return in the smallest viable integer type.
7614     if (Size <= 8)
7615       return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
7616     if (Size <= 16)
7617       return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
7618     if (Size <= 32)
7619       return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
7620     return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
7621   }
7622 
7623   return getNaturalAlignIndirect(RetTy, /*ByVal=*/true);
7624 }
7625 
7626 Address HexagonABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7627                                   QualType Ty) const {
7628   // FIXME: Someone needs to audit that this handle alignment correctly.
7629   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
7630                           getContext().getTypeInfoInChars(Ty),
7631                           CharUnits::fromQuantity(4),
7632                           /*AllowHigherAlign*/ true);
7633 }
7634 
7635 //===----------------------------------------------------------------------===//
7636 // Lanai ABI Implementation
7637 //===----------------------------------------------------------------------===//
7638 
7639 namespace {
7640 class LanaiABIInfo : public DefaultABIInfo {
7641 public:
7642   LanaiABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
7643 
7644   bool shouldUseInReg(QualType Ty, CCState &State) const;
7645 
7646   void computeInfo(CGFunctionInfo &FI) const override {
7647     CCState State(FI);
7648     // Lanai uses 4 registers to pass arguments unless the function has the
7649     // regparm attribute set.
7650     if (FI.getHasRegParm()) {
7651       State.FreeRegs = FI.getRegParm();
7652     } else {
7653       State.FreeRegs = 4;
7654     }
7655 
7656     if (!getCXXABI().classifyReturnType(FI))
7657       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7658     for (auto &I : FI.arguments())
7659       I.info = classifyArgumentType(I.type, State);
7660   }
7661 
7662   ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
7663   ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
7664 };
7665 } // end anonymous namespace
7666 
7667 bool LanaiABIInfo::shouldUseInReg(QualType Ty, CCState &State) const {
7668   unsigned Size = getContext().getTypeSize(Ty);
7669   unsigned SizeInRegs = llvm::alignTo(Size, 32U) / 32U;
7670 
7671   if (SizeInRegs == 0)
7672     return false;
7673 
7674   if (SizeInRegs > State.FreeRegs) {
7675     State.FreeRegs = 0;
7676     return false;
7677   }
7678 
7679   State.FreeRegs -= SizeInRegs;
7680 
7681   return true;
7682 }
7683 
7684 ABIArgInfo LanaiABIInfo::getIndirectResult(QualType Ty, bool ByVal,
7685                                            CCState &State) const {
7686   if (!ByVal) {
7687     if (State.FreeRegs) {
7688       --State.FreeRegs; // Non-byval indirects just use one pointer.
7689       return getNaturalAlignIndirectInReg(Ty);
7690     }
7691     return getNaturalAlignIndirect(Ty, false);
7692   }
7693 
7694   // Compute the byval alignment.
7695   const unsigned MinABIStackAlignInBytes = 4;
7696   unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
7697   return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true,
7698                                  /*Realign=*/TypeAlign >
7699                                      MinABIStackAlignInBytes);
7700 }
7701 
7702 ABIArgInfo LanaiABIInfo::classifyArgumentType(QualType Ty,
7703                                               CCState &State) const {
7704   // Check with the C++ ABI first.
7705   const RecordType *RT = Ty->getAs<RecordType>();
7706   if (RT) {
7707     CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
7708     if (RAA == CGCXXABI::RAA_Indirect) {
7709       return getIndirectResult(Ty, /*ByVal=*/false, State);
7710     } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
7711       return getNaturalAlignIndirect(Ty, /*ByRef=*/true);
7712     }
7713   }
7714 
7715   if (isAggregateTypeForABI(Ty)) {
7716     // Structures with flexible arrays are always indirect.
7717     if (RT && RT->getDecl()->hasFlexibleArrayMember())
7718       return getIndirectResult(Ty, /*ByVal=*/true, State);
7719 
7720     // Ignore empty structs/unions.
7721     if (isEmptyRecord(getContext(), Ty, true))
7722       return ABIArgInfo::getIgnore();
7723 
7724     llvm::LLVMContext &LLVMContext = getVMContext();
7725     unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
7726     if (SizeInRegs <= State.FreeRegs) {
7727       llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
7728       SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32);
7729       llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
7730       State.FreeRegs -= SizeInRegs;
7731       return ABIArgInfo::getDirectInReg(Result);
7732     } else {
7733       State.FreeRegs = 0;
7734     }
7735     return getIndirectResult(Ty, true, State);
7736   }
7737 
7738   // Treat an enum type as its underlying type.
7739   if (const auto *EnumTy = Ty->getAs<EnumType>())
7740     Ty = EnumTy->getDecl()->getIntegerType();
7741 
7742   bool InReg = shouldUseInReg(Ty, State);
7743   if (Ty->isPromotableIntegerType()) {
7744     if (InReg)
7745       return ABIArgInfo::getDirectInReg();
7746     return ABIArgInfo::getExtend(Ty);
7747   }
7748   if (InReg)
7749     return ABIArgInfo::getDirectInReg();
7750   return ABIArgInfo::getDirect();
7751 }
7752 
7753 namespace {
7754 class LanaiTargetCodeGenInfo : public TargetCodeGenInfo {
7755 public:
7756   LanaiTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
7757       : TargetCodeGenInfo(new LanaiABIInfo(CGT)) {}
7758 };
7759 }
7760 
7761 //===----------------------------------------------------------------------===//
7762 // AMDGPU ABI Implementation
7763 //===----------------------------------------------------------------------===//
7764 
7765 namespace {
7766 
7767 class AMDGPUABIInfo final : public DefaultABIInfo {
7768 private:
7769   static const unsigned MaxNumRegsForArgsRet = 16;
7770 
7771   unsigned numRegsForType(QualType Ty) const;
7772 
7773   bool isHomogeneousAggregateBaseType(QualType Ty) const override;
7774   bool isHomogeneousAggregateSmallEnough(const Type *Base,
7775                                          uint64_t Members) const override;
7776 
7777   // Coerce HIP pointer arguments from generic pointers to global ones.
7778   llvm::Type *coerceKernelArgumentType(llvm::Type *Ty, unsigned FromAS,
7779                                        unsigned ToAS) const {
7780     // Structure types.
7781     if (auto STy = dyn_cast<llvm::StructType>(Ty)) {
7782       SmallVector<llvm::Type *, 8> EltTys;
7783       bool Changed = false;
7784       for (auto T : STy->elements()) {
7785         auto NT = coerceKernelArgumentType(T, FromAS, ToAS);
7786         EltTys.push_back(NT);
7787         Changed |= (NT != T);
7788       }
7789       // Skip if there is no change in element types.
7790       if (!Changed)
7791         return STy;
7792       if (STy->hasName())
7793         return llvm::StructType::create(
7794             EltTys, (STy->getName() + ".coerce").str(), STy->isPacked());
7795       return llvm::StructType::get(getVMContext(), EltTys, STy->isPacked());
7796     }
7797     // Arrary types.
7798     if (auto ATy = dyn_cast<llvm::ArrayType>(Ty)) {
7799       auto T = ATy->getElementType();
7800       auto NT = coerceKernelArgumentType(T, FromAS, ToAS);
7801       // Skip if there is no change in that element type.
7802       if (NT == T)
7803         return ATy;
7804       return llvm::ArrayType::get(NT, ATy->getNumElements());
7805     }
7806     // Single value types.
7807     if (Ty->isPointerTy() && Ty->getPointerAddressSpace() == FromAS)
7808       return llvm::PointerType::get(
7809           cast<llvm::PointerType>(Ty)->getElementType(), ToAS);
7810     return Ty;
7811   }
7812 
7813 public:
7814   explicit AMDGPUABIInfo(CodeGen::CodeGenTypes &CGT) :
7815     DefaultABIInfo(CGT) {}
7816 
7817   ABIArgInfo classifyReturnType(QualType RetTy) const;
7818   ABIArgInfo classifyKernelArgumentType(QualType Ty) const;
7819   ABIArgInfo classifyArgumentType(QualType Ty, unsigned &NumRegsLeft) const;
7820 
7821   void computeInfo(CGFunctionInfo &FI) const override;
7822   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7823                     QualType Ty) const override;
7824 };
7825 
7826 bool AMDGPUABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
7827   return true;
7828 }
7829 
7830 bool AMDGPUABIInfo::isHomogeneousAggregateSmallEnough(
7831   const Type *Base, uint64_t Members) const {
7832   uint32_t NumRegs = (getContext().getTypeSize(Base) + 31) / 32;
7833 
7834   // Homogeneous Aggregates may occupy at most 16 registers.
7835   return Members * NumRegs <= MaxNumRegsForArgsRet;
7836 }
7837 
7838 /// Estimate number of registers the type will use when passed in registers.
7839 unsigned AMDGPUABIInfo::numRegsForType(QualType Ty) const {
7840   unsigned NumRegs = 0;
7841 
7842   if (const VectorType *VT = Ty->getAs<VectorType>()) {
7843     // Compute from the number of elements. The reported size is based on the
7844     // in-memory size, which includes the padding 4th element for 3-vectors.
7845     QualType EltTy = VT->getElementType();
7846     unsigned EltSize = getContext().getTypeSize(EltTy);
7847 
7848     // 16-bit element vectors should be passed as packed.
7849     if (EltSize == 16)
7850       return (VT->getNumElements() + 1) / 2;
7851 
7852     unsigned EltNumRegs = (EltSize + 31) / 32;
7853     return EltNumRegs * VT->getNumElements();
7854   }
7855 
7856   if (const RecordType *RT = Ty->getAs<RecordType>()) {
7857     const RecordDecl *RD = RT->getDecl();
7858     assert(!RD->hasFlexibleArrayMember());
7859 
7860     for (const FieldDecl *Field : RD->fields()) {
7861       QualType FieldTy = Field->getType();
7862       NumRegs += numRegsForType(FieldTy);
7863     }
7864 
7865     return NumRegs;
7866   }
7867 
7868   return (getContext().getTypeSize(Ty) + 31) / 32;
7869 }
7870 
7871 void AMDGPUABIInfo::computeInfo(CGFunctionInfo &FI) const {
7872   llvm::CallingConv::ID CC = FI.getCallingConvention();
7873 
7874   if (!getCXXABI().classifyReturnType(FI))
7875     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7876 
7877   unsigned NumRegsLeft = MaxNumRegsForArgsRet;
7878   for (auto &Arg : FI.arguments()) {
7879     if (CC == llvm::CallingConv::AMDGPU_KERNEL) {
7880       Arg.info = classifyKernelArgumentType(Arg.type);
7881     } else {
7882       Arg.info = classifyArgumentType(Arg.type, NumRegsLeft);
7883     }
7884   }
7885 }
7886 
7887 Address AMDGPUABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7888                                  QualType Ty) const {
7889   llvm_unreachable("AMDGPU does not support varargs");
7890 }
7891 
7892 ABIArgInfo AMDGPUABIInfo::classifyReturnType(QualType RetTy) const {
7893   if (isAggregateTypeForABI(RetTy)) {
7894     // Records with non-trivial destructors/copy-constructors should not be
7895     // returned by value.
7896     if (!getRecordArgABI(RetTy, getCXXABI())) {
7897       // Ignore empty structs/unions.
7898       if (isEmptyRecord(getContext(), RetTy, true))
7899         return ABIArgInfo::getIgnore();
7900 
7901       // Lower single-element structs to just return a regular value.
7902       if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
7903         return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
7904 
7905       if (const RecordType *RT = RetTy->getAs<RecordType>()) {
7906         const RecordDecl *RD = RT->getDecl();
7907         if (RD->hasFlexibleArrayMember())
7908           return DefaultABIInfo::classifyReturnType(RetTy);
7909       }
7910 
7911       // Pack aggregates <= 4 bytes into single VGPR or pair.
7912       uint64_t Size = getContext().getTypeSize(RetTy);
7913       if (Size <= 16)
7914         return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
7915 
7916       if (Size <= 32)
7917         return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
7918 
7919       if (Size <= 64) {
7920         llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext());
7921         return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2));
7922       }
7923 
7924       if (numRegsForType(RetTy) <= MaxNumRegsForArgsRet)
7925         return ABIArgInfo::getDirect();
7926     }
7927   }
7928 
7929   // Otherwise just do the default thing.
7930   return DefaultABIInfo::classifyReturnType(RetTy);
7931 }
7932 
7933 /// For kernels all parameters are really passed in a special buffer. It doesn't
7934 /// make sense to pass anything byval, so everything must be direct.
7935 ABIArgInfo AMDGPUABIInfo::classifyKernelArgumentType(QualType Ty) const {
7936   Ty = useFirstFieldIfTransparentUnion(Ty);
7937 
7938   // TODO: Can we omit empty structs?
7939 
7940   llvm::Type *LTy = nullptr;
7941   if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
7942     LTy = CGT.ConvertType(QualType(SeltTy, 0));
7943 
7944   if (getContext().getLangOpts().HIP) {
7945     if (!LTy)
7946       LTy = CGT.ConvertType(Ty);
7947     LTy = coerceKernelArgumentType(
7948         LTy, /*FromAS=*/getContext().getTargetAddressSpace(LangAS::Default),
7949         /*ToAS=*/getContext().getTargetAddressSpace(LangAS::cuda_device));
7950   }
7951 
7952   // If we set CanBeFlattened to true, CodeGen will expand the struct to its
7953   // individual elements, which confuses the Clover OpenCL backend; therefore we
7954   // have to set it to false here. Other args of getDirect() are just defaults.
7955   return ABIArgInfo::getDirect(LTy, 0, nullptr, false);
7956 }
7957 
7958 ABIArgInfo AMDGPUABIInfo::classifyArgumentType(QualType Ty,
7959                                                unsigned &NumRegsLeft) const {
7960   assert(NumRegsLeft <= MaxNumRegsForArgsRet && "register estimate underflow");
7961 
7962   Ty = useFirstFieldIfTransparentUnion(Ty);
7963 
7964   if (isAggregateTypeForABI(Ty)) {
7965     // Records with non-trivial destructors/copy-constructors should not be
7966     // passed by value.
7967     if (auto RAA = getRecordArgABI(Ty, getCXXABI()))
7968       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
7969 
7970     // Ignore empty structs/unions.
7971     if (isEmptyRecord(getContext(), Ty, true))
7972       return ABIArgInfo::getIgnore();
7973 
7974     // Lower single-element structs to just pass a regular value. TODO: We
7975     // could do reasonable-size multiple-element structs too, using getExpand(),
7976     // though watch out for things like bitfields.
7977     if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
7978       return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
7979 
7980     if (const RecordType *RT = Ty->getAs<RecordType>()) {
7981       const RecordDecl *RD = RT->getDecl();
7982       if (RD->hasFlexibleArrayMember())
7983         return DefaultABIInfo::classifyArgumentType(Ty);
7984     }
7985 
7986     // Pack aggregates <= 8 bytes into single VGPR or pair.
7987     uint64_t Size = getContext().getTypeSize(Ty);
7988     if (Size <= 64) {
7989       unsigned NumRegs = (Size + 31) / 32;
7990       NumRegsLeft -= std::min(NumRegsLeft, NumRegs);
7991 
7992       if (Size <= 16)
7993         return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
7994 
7995       if (Size <= 32)
7996         return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
7997 
7998       // XXX: Should this be i64 instead, and should the limit increase?
7999       llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext());
8000       return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2));
8001     }
8002 
8003     if (NumRegsLeft > 0) {
8004       unsigned NumRegs = numRegsForType(Ty);
8005       if (NumRegsLeft >= NumRegs) {
8006         NumRegsLeft -= NumRegs;
8007         return ABIArgInfo::getDirect();
8008       }
8009     }
8010   }
8011 
8012   // Otherwise just do the default thing.
8013   ABIArgInfo ArgInfo = DefaultABIInfo::classifyArgumentType(Ty);
8014   if (!ArgInfo.isIndirect()) {
8015     unsigned NumRegs = numRegsForType(Ty);
8016     NumRegsLeft -= std::min(NumRegs, NumRegsLeft);
8017   }
8018 
8019   return ArgInfo;
8020 }
8021 
8022 class AMDGPUTargetCodeGenInfo : public TargetCodeGenInfo {
8023 public:
8024   AMDGPUTargetCodeGenInfo(CodeGenTypes &CGT)
8025     : TargetCodeGenInfo(new AMDGPUABIInfo(CGT)) {}
8026   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
8027                            CodeGen::CodeGenModule &M) const override;
8028   unsigned getOpenCLKernelCallingConv() const override;
8029 
8030   llvm::Constant *getNullPointer(const CodeGen::CodeGenModule &CGM,
8031       llvm::PointerType *T, QualType QT) const override;
8032 
8033   LangAS getASTAllocaAddressSpace() const override {
8034     return getLangASFromTargetAS(
8035         getABIInfo().getDataLayout().getAllocaAddrSpace());
8036   }
8037   LangAS getGlobalVarAddressSpace(CodeGenModule &CGM,
8038                                   const VarDecl *D) const override;
8039   llvm::SyncScope::ID getLLVMSyncScopeID(const LangOptions &LangOpts,
8040                                          SyncScope Scope,
8041                                          llvm::AtomicOrdering Ordering,
8042                                          llvm::LLVMContext &Ctx) const override;
8043   llvm::Function *
8044   createEnqueuedBlockKernel(CodeGenFunction &CGF,
8045                             llvm::Function *BlockInvokeFunc,
8046                             llvm::Value *BlockLiteral) const override;
8047   bool shouldEmitStaticExternCAliases() const override;
8048   void setCUDAKernelCallingConvention(const FunctionType *&FT) const override;
8049 };
8050 }
8051 
8052 static bool requiresAMDGPUProtectedVisibility(const Decl *D,
8053                                               llvm::GlobalValue *GV) {
8054   if (GV->getVisibility() != llvm::GlobalValue::HiddenVisibility)
8055     return false;
8056 
8057   return D->hasAttr<OpenCLKernelAttr>() ||
8058          (isa<FunctionDecl>(D) && D->hasAttr<CUDAGlobalAttr>()) ||
8059          (isa<VarDecl>(D) &&
8060           (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>() ||
8061            D->hasAttr<HIPPinnedShadowAttr>()));
8062 }
8063 
8064 static bool requiresAMDGPUDefaultVisibility(const Decl *D,
8065                                             llvm::GlobalValue *GV) {
8066   if (GV->getVisibility() != llvm::GlobalValue::HiddenVisibility)
8067     return false;
8068 
8069   return isa<VarDecl>(D) && D->hasAttr<HIPPinnedShadowAttr>();
8070 }
8071 
8072 void AMDGPUTargetCodeGenInfo::setTargetAttributes(
8073     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
8074   if (requiresAMDGPUDefaultVisibility(D, GV)) {
8075     GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
8076     GV->setDSOLocal(false);
8077   } else if (requiresAMDGPUProtectedVisibility(D, GV)) {
8078     GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
8079     GV->setDSOLocal(true);
8080   }
8081 
8082   if (GV->isDeclaration())
8083     return;
8084   const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
8085   if (!FD)
8086     return;
8087 
8088   llvm::Function *F = cast<llvm::Function>(GV);
8089 
8090   const auto *ReqdWGS = M.getLangOpts().OpenCL ?
8091     FD->getAttr<ReqdWorkGroupSizeAttr>() : nullptr;
8092 
8093 
8094   const bool IsOpenCLKernel = M.getLangOpts().OpenCL &&
8095                               FD->hasAttr<OpenCLKernelAttr>();
8096   const bool IsHIPKernel = M.getLangOpts().HIP &&
8097                            FD->hasAttr<CUDAGlobalAttr>();
8098   if ((IsOpenCLKernel || IsHIPKernel) &&
8099       (M.getTriple().getOS() == llvm::Triple::AMDHSA))
8100     F->addFnAttr("amdgpu-implicitarg-num-bytes", "56");
8101 
8102   const auto *FlatWGS = FD->getAttr<AMDGPUFlatWorkGroupSizeAttr>();
8103   if (ReqdWGS || FlatWGS) {
8104     unsigned Min = 0;
8105     unsigned Max = 0;
8106     if (FlatWGS) {
8107       Min = FlatWGS->getMin()
8108                 ->EvaluateKnownConstInt(M.getContext())
8109                 .getExtValue();
8110       Max = FlatWGS->getMax()
8111                 ->EvaluateKnownConstInt(M.getContext())
8112                 .getExtValue();
8113     }
8114     if (ReqdWGS && Min == 0 && Max == 0)
8115       Min = Max = ReqdWGS->getXDim() * ReqdWGS->getYDim() * ReqdWGS->getZDim();
8116 
8117     if (Min != 0) {
8118       assert(Min <= Max && "Min must be less than or equal Max");
8119 
8120       std::string AttrVal = llvm::utostr(Min) + "," + llvm::utostr(Max);
8121       F->addFnAttr("amdgpu-flat-work-group-size", AttrVal);
8122     } else
8123       assert(Max == 0 && "Max must be zero");
8124   } else if (IsOpenCLKernel || IsHIPKernel) {
8125     // By default, restrict the maximum size to a value specified by
8126     // --gpu-max-threads-per-block=n or its default value.
8127     std::string AttrVal =
8128         std::string("1,") + llvm::utostr(M.getLangOpts().GPUMaxThreadsPerBlock);
8129     F->addFnAttr("amdgpu-flat-work-group-size", AttrVal);
8130   }
8131 
8132   if (const auto *Attr = FD->getAttr<AMDGPUWavesPerEUAttr>()) {
8133     unsigned Min =
8134         Attr->getMin()->EvaluateKnownConstInt(M.getContext()).getExtValue();
8135     unsigned Max = Attr->getMax() ? Attr->getMax()
8136                                         ->EvaluateKnownConstInt(M.getContext())
8137                                         .getExtValue()
8138                                   : 0;
8139 
8140     if (Min != 0) {
8141       assert((Max == 0 || Min <= Max) && "Min must be less than or equal Max");
8142 
8143       std::string AttrVal = llvm::utostr(Min);
8144       if (Max != 0)
8145         AttrVal = AttrVal + "," + llvm::utostr(Max);
8146       F->addFnAttr("amdgpu-waves-per-eu", AttrVal);
8147     } else
8148       assert(Max == 0 && "Max must be zero");
8149   }
8150 
8151   if (const auto *Attr = FD->getAttr<AMDGPUNumSGPRAttr>()) {
8152     unsigned NumSGPR = Attr->getNumSGPR();
8153 
8154     if (NumSGPR != 0)
8155       F->addFnAttr("amdgpu-num-sgpr", llvm::utostr(NumSGPR));
8156   }
8157 
8158   if (const auto *Attr = FD->getAttr<AMDGPUNumVGPRAttr>()) {
8159     uint32_t NumVGPR = Attr->getNumVGPR();
8160 
8161     if (NumVGPR != 0)
8162       F->addFnAttr("amdgpu-num-vgpr", llvm::utostr(NumVGPR));
8163   }
8164 }
8165 
8166 unsigned AMDGPUTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
8167   return llvm::CallingConv::AMDGPU_KERNEL;
8168 }
8169 
8170 // Currently LLVM assumes null pointers always have value 0,
8171 // which results in incorrectly transformed IR. Therefore, instead of
8172 // emitting null pointers in private and local address spaces, a null
8173 // pointer in generic address space is emitted which is casted to a
8174 // pointer in local or private address space.
8175 llvm::Constant *AMDGPUTargetCodeGenInfo::getNullPointer(
8176     const CodeGen::CodeGenModule &CGM, llvm::PointerType *PT,
8177     QualType QT) const {
8178   if (CGM.getContext().getTargetNullPointerValue(QT) == 0)
8179     return llvm::ConstantPointerNull::get(PT);
8180 
8181   auto &Ctx = CGM.getContext();
8182   auto NPT = llvm::PointerType::get(PT->getElementType(),
8183       Ctx.getTargetAddressSpace(LangAS::opencl_generic));
8184   return llvm::ConstantExpr::getAddrSpaceCast(
8185       llvm::ConstantPointerNull::get(NPT), PT);
8186 }
8187 
8188 LangAS
8189 AMDGPUTargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM,
8190                                                   const VarDecl *D) const {
8191   assert(!CGM.getLangOpts().OpenCL &&
8192          !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) &&
8193          "Address space agnostic languages only");
8194   LangAS DefaultGlobalAS = getLangASFromTargetAS(
8195       CGM.getContext().getTargetAddressSpace(LangAS::opencl_global));
8196   if (!D)
8197     return DefaultGlobalAS;
8198 
8199   LangAS AddrSpace = D->getType().getAddressSpace();
8200   assert(AddrSpace == LangAS::Default || isTargetAddressSpace(AddrSpace));
8201   if (AddrSpace != LangAS::Default)
8202     return AddrSpace;
8203 
8204   if (CGM.isTypeConstant(D->getType(), false)) {
8205     if (auto ConstAS = CGM.getTarget().getConstantAddressSpace())
8206       return ConstAS.getValue();
8207   }
8208   return DefaultGlobalAS;
8209 }
8210 
8211 llvm::SyncScope::ID
8212 AMDGPUTargetCodeGenInfo::getLLVMSyncScopeID(const LangOptions &LangOpts,
8213                                             SyncScope Scope,
8214                                             llvm::AtomicOrdering Ordering,
8215                                             llvm::LLVMContext &Ctx) const {
8216   std::string Name;
8217   switch (Scope) {
8218   case SyncScope::OpenCLWorkGroup:
8219     Name = "workgroup";
8220     break;
8221   case SyncScope::OpenCLDevice:
8222     Name = "agent";
8223     break;
8224   case SyncScope::OpenCLAllSVMDevices:
8225     Name = "";
8226     break;
8227   case SyncScope::OpenCLSubGroup:
8228     Name = "wavefront";
8229   }
8230 
8231   if (Ordering != llvm::AtomicOrdering::SequentiallyConsistent) {
8232     if (!Name.empty())
8233       Name = Twine(Twine(Name) + Twine("-")).str();
8234 
8235     Name = Twine(Twine(Name) + Twine("one-as")).str();
8236   }
8237 
8238   return Ctx.getOrInsertSyncScopeID(Name);
8239 }
8240 
8241 bool AMDGPUTargetCodeGenInfo::shouldEmitStaticExternCAliases() const {
8242   return false;
8243 }
8244 
8245 void AMDGPUTargetCodeGenInfo::setCUDAKernelCallingConvention(
8246     const FunctionType *&FT) const {
8247   FT = getABIInfo().getContext().adjustFunctionType(
8248       FT, FT->getExtInfo().withCallingConv(CC_OpenCLKernel));
8249 }
8250 
8251 //===----------------------------------------------------------------------===//
8252 // SPARC v8 ABI Implementation.
8253 // Based on the SPARC Compliance Definition version 2.4.1.
8254 //
8255 // Ensures that complex values are passed in registers.
8256 //
8257 namespace {
8258 class SparcV8ABIInfo : public DefaultABIInfo {
8259 public:
8260   SparcV8ABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
8261 
8262 private:
8263   ABIArgInfo classifyReturnType(QualType RetTy) const;
8264   void computeInfo(CGFunctionInfo &FI) const override;
8265 };
8266 } // end anonymous namespace
8267 
8268 
8269 ABIArgInfo
8270 SparcV8ABIInfo::classifyReturnType(QualType Ty) const {
8271   if (Ty->isAnyComplexType()) {
8272     return ABIArgInfo::getDirect();
8273   }
8274   else {
8275     return DefaultABIInfo::classifyReturnType(Ty);
8276   }
8277 }
8278 
8279 void SparcV8ABIInfo::computeInfo(CGFunctionInfo &FI) const {
8280 
8281   FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
8282   for (auto &Arg : FI.arguments())
8283     Arg.info = classifyArgumentType(Arg.type);
8284 }
8285 
8286 namespace {
8287 class SparcV8TargetCodeGenInfo : public TargetCodeGenInfo {
8288 public:
8289   SparcV8TargetCodeGenInfo(CodeGenTypes &CGT)
8290     : TargetCodeGenInfo(new SparcV8ABIInfo(CGT)) {}
8291 };
8292 } // end anonymous namespace
8293 
8294 //===----------------------------------------------------------------------===//
8295 // SPARC v9 ABI Implementation.
8296 // Based on the SPARC Compliance Definition version 2.4.1.
8297 //
8298 // Function arguments a mapped to a nominal "parameter array" and promoted to
8299 // registers depending on their type. Each argument occupies 8 or 16 bytes in
8300 // the array, structs larger than 16 bytes are passed indirectly.
8301 //
8302 // One case requires special care:
8303 //
8304 //   struct mixed {
8305 //     int i;
8306 //     float f;
8307 //   };
8308 //
8309 // When a struct mixed is passed by value, it only occupies 8 bytes in the
8310 // parameter array, but the int is passed in an integer register, and the float
8311 // is passed in a floating point register. This is represented as two arguments
8312 // with the LLVM IR inreg attribute:
8313 //
8314 //   declare void f(i32 inreg %i, float inreg %f)
8315 //
8316 // The code generator will only allocate 4 bytes from the parameter array for
8317 // the inreg arguments. All other arguments are allocated a multiple of 8
8318 // bytes.
8319 //
8320 namespace {
8321 class SparcV9ABIInfo : public ABIInfo {
8322 public:
8323   SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
8324 
8325 private:
8326   ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
8327   void computeInfo(CGFunctionInfo &FI) const override;
8328   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8329                     QualType Ty) const override;
8330 
8331   // Coercion type builder for structs passed in registers. The coercion type
8332   // serves two purposes:
8333   //
8334   // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
8335   //    in registers.
8336   // 2. Expose aligned floating point elements as first-level elements, so the
8337   //    code generator knows to pass them in floating point registers.
8338   //
8339   // We also compute the InReg flag which indicates that the struct contains
8340   // aligned 32-bit floats.
8341   //
8342   struct CoerceBuilder {
8343     llvm::LLVMContext &Context;
8344     const llvm::DataLayout &DL;
8345     SmallVector<llvm::Type*, 8> Elems;
8346     uint64_t Size;
8347     bool InReg;
8348 
8349     CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
8350       : Context(c), DL(dl), Size(0), InReg(false) {}
8351 
8352     // Pad Elems with integers until Size is ToSize.
8353     void pad(uint64_t ToSize) {
8354       assert(ToSize >= Size && "Cannot remove elements");
8355       if (ToSize == Size)
8356         return;
8357 
8358       // Finish the current 64-bit word.
8359       uint64_t Aligned = llvm::alignTo(Size, 64);
8360       if (Aligned > Size && Aligned <= ToSize) {
8361         Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
8362         Size = Aligned;
8363       }
8364 
8365       // Add whole 64-bit words.
8366       while (Size + 64 <= ToSize) {
8367         Elems.push_back(llvm::Type::getInt64Ty(Context));
8368         Size += 64;
8369       }
8370 
8371       // Final in-word padding.
8372       if (Size < ToSize) {
8373         Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
8374         Size = ToSize;
8375       }
8376     }
8377 
8378     // Add a floating point element at Offset.
8379     void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
8380       // Unaligned floats are treated as integers.
8381       if (Offset % Bits)
8382         return;
8383       // The InReg flag is only required if there are any floats < 64 bits.
8384       if (Bits < 64)
8385         InReg = true;
8386       pad(Offset);
8387       Elems.push_back(Ty);
8388       Size = Offset + Bits;
8389     }
8390 
8391     // Add a struct type to the coercion type, starting at Offset (in bits).
8392     void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
8393       const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
8394       for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
8395         llvm::Type *ElemTy = StrTy->getElementType(i);
8396         uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
8397         switch (ElemTy->getTypeID()) {
8398         case llvm::Type::StructTyID:
8399           addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
8400           break;
8401         case llvm::Type::FloatTyID:
8402           addFloat(ElemOffset, ElemTy, 32);
8403           break;
8404         case llvm::Type::DoubleTyID:
8405           addFloat(ElemOffset, ElemTy, 64);
8406           break;
8407         case llvm::Type::FP128TyID:
8408           addFloat(ElemOffset, ElemTy, 128);
8409           break;
8410         case llvm::Type::PointerTyID:
8411           if (ElemOffset % 64 == 0) {
8412             pad(ElemOffset);
8413             Elems.push_back(ElemTy);
8414             Size += 64;
8415           }
8416           break;
8417         default:
8418           break;
8419         }
8420       }
8421     }
8422 
8423     // Check if Ty is a usable substitute for the coercion type.
8424     bool isUsableType(llvm::StructType *Ty) const {
8425       return llvm::makeArrayRef(Elems) == Ty->elements();
8426     }
8427 
8428     // Get the coercion type as a literal struct type.
8429     llvm::Type *getType() const {
8430       if (Elems.size() == 1)
8431         return Elems.front();
8432       else
8433         return llvm::StructType::get(Context, Elems);
8434     }
8435   };
8436 };
8437 } // end anonymous namespace
8438 
8439 ABIArgInfo
8440 SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
8441   if (Ty->isVoidType())
8442     return ABIArgInfo::getIgnore();
8443 
8444   uint64_t Size = getContext().getTypeSize(Ty);
8445 
8446   // Anything too big to fit in registers is passed with an explicit indirect
8447   // pointer / sret pointer.
8448   if (Size > SizeLimit)
8449     return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
8450 
8451   // Treat an enum type as its underlying type.
8452   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
8453     Ty = EnumTy->getDecl()->getIntegerType();
8454 
8455   // Integer types smaller than a register are extended.
8456   if (Size < 64 && Ty->isIntegerType())
8457     return ABIArgInfo::getExtend(Ty);
8458 
8459   // Other non-aggregates go in registers.
8460   if (!isAggregateTypeForABI(Ty))
8461     return ABIArgInfo::getDirect();
8462 
8463   // If a C++ object has either a non-trivial copy constructor or a non-trivial
8464   // destructor, it is passed with an explicit indirect pointer / sret pointer.
8465   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
8466     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
8467 
8468   // This is a small aggregate type that should be passed in registers.
8469   // Build a coercion type from the LLVM struct type.
8470   llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
8471   if (!StrTy)
8472     return ABIArgInfo::getDirect();
8473 
8474   CoerceBuilder CB(getVMContext(), getDataLayout());
8475   CB.addStruct(0, StrTy);
8476   CB.pad(llvm::alignTo(CB.DL.getTypeSizeInBits(StrTy), 64));
8477 
8478   // Try to use the original type for coercion.
8479   llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
8480 
8481   if (CB.InReg)
8482     return ABIArgInfo::getDirectInReg(CoerceTy);
8483   else
8484     return ABIArgInfo::getDirect(CoerceTy);
8485 }
8486 
8487 Address SparcV9ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8488                                   QualType Ty) const {
8489   ABIArgInfo AI = classifyType(Ty, 16 * 8);
8490   llvm::Type *ArgTy = CGT.ConvertType(Ty);
8491   if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
8492     AI.setCoerceToType(ArgTy);
8493 
8494   CharUnits SlotSize = CharUnits::fromQuantity(8);
8495 
8496   CGBuilderTy &Builder = CGF.Builder;
8497   Address Addr(Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
8498   llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
8499 
8500   auto TypeInfo = getContext().getTypeInfoInChars(Ty);
8501 
8502   Address ArgAddr = Address::invalid();
8503   CharUnits Stride;
8504   switch (AI.getKind()) {
8505   case ABIArgInfo::Expand:
8506   case ABIArgInfo::CoerceAndExpand:
8507   case ABIArgInfo::InAlloca:
8508     llvm_unreachable("Unsupported ABI kind for va_arg");
8509 
8510   case ABIArgInfo::Extend: {
8511     Stride = SlotSize;
8512     CharUnits Offset = SlotSize - TypeInfo.first;
8513     ArgAddr = Builder.CreateConstInBoundsByteGEP(Addr, Offset, "extend");
8514     break;
8515   }
8516 
8517   case ABIArgInfo::Direct: {
8518     auto AllocSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
8519     Stride = CharUnits::fromQuantity(AllocSize).alignTo(SlotSize);
8520     ArgAddr = Addr;
8521     break;
8522   }
8523 
8524   case ABIArgInfo::Indirect:
8525     Stride = SlotSize;
8526     ArgAddr = Builder.CreateElementBitCast(Addr, ArgPtrTy, "indirect");
8527     ArgAddr = Address(Builder.CreateLoad(ArgAddr, "indirect.arg"),
8528                       TypeInfo.second);
8529     break;
8530 
8531   case ABIArgInfo::Ignore:
8532     return Address(llvm::UndefValue::get(ArgPtrTy), TypeInfo.second);
8533   }
8534 
8535   // Update VAList.
8536   Address NextPtr = Builder.CreateConstInBoundsByteGEP(Addr, Stride, "ap.next");
8537   Builder.CreateStore(NextPtr.getPointer(), VAListAddr);
8538 
8539   return Builder.CreateBitCast(ArgAddr, ArgPtrTy, "arg.addr");
8540 }
8541 
8542 void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
8543   FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
8544   for (auto &I : FI.arguments())
8545     I.info = classifyType(I.type, 16 * 8);
8546 }
8547 
8548 namespace {
8549 class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
8550 public:
8551   SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
8552     : TargetCodeGenInfo(new SparcV9ABIInfo(CGT)) {}
8553 
8554   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
8555     return 14;
8556   }
8557 
8558   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
8559                                llvm::Value *Address) const override;
8560 };
8561 } // end anonymous namespace
8562 
8563 bool
8564 SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
8565                                                 llvm::Value *Address) const {
8566   // This is calculated from the LLVM and GCC tables and verified
8567   // against gcc output.  AFAIK all ABIs use the same encoding.
8568 
8569   CodeGen::CGBuilderTy &Builder = CGF.Builder;
8570 
8571   llvm::IntegerType *i8 = CGF.Int8Ty;
8572   llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
8573   llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
8574 
8575   // 0-31: the 8-byte general-purpose registers
8576   AssignToArrayRange(Builder, Address, Eight8, 0, 31);
8577 
8578   // 32-63: f0-31, the 4-byte floating-point registers
8579   AssignToArrayRange(Builder, Address, Four8, 32, 63);
8580 
8581   //   Y   = 64
8582   //   PSR = 65
8583   //   WIM = 66
8584   //   TBR = 67
8585   //   PC  = 68
8586   //   NPC = 69
8587   //   FSR = 70
8588   //   CSR = 71
8589   AssignToArrayRange(Builder, Address, Eight8, 64, 71);
8590 
8591   // 72-87: d0-15, the 8-byte floating-point registers
8592   AssignToArrayRange(Builder, Address, Eight8, 72, 87);
8593 
8594   return false;
8595 }
8596 
8597 // ARC ABI implementation.
8598 namespace {
8599 
8600 class ARCABIInfo : public DefaultABIInfo {
8601 public:
8602   using DefaultABIInfo::DefaultABIInfo;
8603 
8604 private:
8605   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8606                     QualType Ty) const override;
8607 
8608   void updateState(const ABIArgInfo &Info, QualType Ty, CCState &State) const {
8609     if (!State.FreeRegs)
8610       return;
8611     if (Info.isIndirect() && Info.getInReg())
8612       State.FreeRegs--;
8613     else if (Info.isDirect() && Info.getInReg()) {
8614       unsigned sz = (getContext().getTypeSize(Ty) + 31) / 32;
8615       if (sz < State.FreeRegs)
8616         State.FreeRegs -= sz;
8617       else
8618         State.FreeRegs = 0;
8619     }
8620   }
8621 
8622   void computeInfo(CGFunctionInfo &FI) const override {
8623     CCState State(FI);
8624     // ARC uses 8 registers to pass arguments.
8625     State.FreeRegs = 8;
8626 
8627     if (!getCXXABI().classifyReturnType(FI))
8628       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
8629     updateState(FI.getReturnInfo(), FI.getReturnType(), State);
8630     for (auto &I : FI.arguments()) {
8631       I.info = classifyArgumentType(I.type, State.FreeRegs);
8632       updateState(I.info, I.type, State);
8633     }
8634   }
8635 
8636   ABIArgInfo getIndirectByRef(QualType Ty, bool HasFreeRegs) const;
8637   ABIArgInfo getIndirectByValue(QualType Ty) const;
8638   ABIArgInfo classifyArgumentType(QualType Ty, uint8_t FreeRegs) const;
8639   ABIArgInfo classifyReturnType(QualType RetTy) const;
8640 };
8641 
8642 class ARCTargetCodeGenInfo : public TargetCodeGenInfo {
8643 public:
8644   ARCTargetCodeGenInfo(CodeGenTypes &CGT)
8645       : TargetCodeGenInfo(new ARCABIInfo(CGT)) {}
8646 };
8647 
8648 
8649 ABIArgInfo ARCABIInfo::getIndirectByRef(QualType Ty, bool HasFreeRegs) const {
8650   return HasFreeRegs ? getNaturalAlignIndirectInReg(Ty) :
8651                        getNaturalAlignIndirect(Ty, false);
8652 }
8653 
8654 ABIArgInfo ARCABIInfo::getIndirectByValue(QualType Ty) const {
8655   // Compute the byval alignment.
8656   const unsigned MinABIStackAlignInBytes = 4;
8657   unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
8658   return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true,
8659                                  TypeAlign > MinABIStackAlignInBytes);
8660 }
8661 
8662 Address ARCABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8663                               QualType Ty) const {
8664   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
8665                           getContext().getTypeInfoInChars(Ty),
8666                           CharUnits::fromQuantity(4), true);
8667 }
8668 
8669 ABIArgInfo ARCABIInfo::classifyArgumentType(QualType Ty,
8670                                             uint8_t FreeRegs) const {
8671   // Handle the generic C++ ABI.
8672   const RecordType *RT = Ty->getAs<RecordType>();
8673   if (RT) {
8674     CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
8675     if (RAA == CGCXXABI::RAA_Indirect)
8676       return getIndirectByRef(Ty, FreeRegs > 0);
8677 
8678     if (RAA == CGCXXABI::RAA_DirectInMemory)
8679       return getIndirectByValue(Ty);
8680   }
8681 
8682   // Treat an enum type as its underlying type.
8683   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
8684     Ty = EnumTy->getDecl()->getIntegerType();
8685 
8686   auto SizeInRegs = llvm::alignTo(getContext().getTypeSize(Ty), 32) / 32;
8687 
8688   if (isAggregateTypeForABI(Ty)) {
8689     // Structures with flexible arrays are always indirect.
8690     if (RT && RT->getDecl()->hasFlexibleArrayMember())
8691       return getIndirectByValue(Ty);
8692 
8693     // Ignore empty structs/unions.
8694     if (isEmptyRecord(getContext(), Ty, true))
8695       return ABIArgInfo::getIgnore();
8696 
8697     llvm::LLVMContext &LLVMContext = getVMContext();
8698 
8699     llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
8700     SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32);
8701     llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
8702 
8703     return FreeRegs >= SizeInRegs ?
8704         ABIArgInfo::getDirectInReg(Result) :
8705         ABIArgInfo::getDirect(Result, 0, nullptr, false);
8706   }
8707 
8708   return Ty->isPromotableIntegerType() ?
8709       (FreeRegs >= SizeInRegs ? ABIArgInfo::getExtendInReg(Ty) :
8710                                 ABIArgInfo::getExtend(Ty)) :
8711       (FreeRegs >= SizeInRegs ? ABIArgInfo::getDirectInReg() :
8712                                 ABIArgInfo::getDirect());
8713 }
8714 
8715 ABIArgInfo ARCABIInfo::classifyReturnType(QualType RetTy) const {
8716   if (RetTy->isAnyComplexType())
8717     return ABIArgInfo::getDirectInReg();
8718 
8719   // Arguments of size > 4 registers are indirect.
8720   auto RetSize = llvm::alignTo(getContext().getTypeSize(RetTy), 32) / 32;
8721   if (RetSize > 4)
8722     return getIndirectByRef(RetTy, /*HasFreeRegs*/ true);
8723 
8724   return DefaultABIInfo::classifyReturnType(RetTy);
8725 }
8726 
8727 } // End anonymous namespace.
8728 
8729 //===----------------------------------------------------------------------===//
8730 // XCore ABI Implementation
8731 //===----------------------------------------------------------------------===//
8732 
8733 namespace {
8734 
8735 /// A SmallStringEnc instance is used to build up the TypeString by passing
8736 /// it by reference between functions that append to it.
8737 typedef llvm::SmallString<128> SmallStringEnc;
8738 
8739 /// TypeStringCache caches the meta encodings of Types.
8740 ///
8741 /// The reason for caching TypeStrings is two fold:
8742 ///   1. To cache a type's encoding for later uses;
8743 ///   2. As a means to break recursive member type inclusion.
8744 ///
8745 /// A cache Entry can have a Status of:
8746 ///   NonRecursive:   The type encoding is not recursive;
8747 ///   Recursive:      The type encoding is recursive;
8748 ///   Incomplete:     An incomplete TypeString;
8749 ///   IncompleteUsed: An incomplete TypeString that has been used in a
8750 ///                   Recursive type encoding.
8751 ///
8752 /// A NonRecursive entry will have all of its sub-members expanded as fully
8753 /// as possible. Whilst it may contain types which are recursive, the type
8754 /// itself is not recursive and thus its encoding may be safely used whenever
8755 /// the type is encountered.
8756 ///
8757 /// A Recursive entry will have all of its sub-members expanded as fully as
8758 /// possible. The type itself is recursive and it may contain other types which
8759 /// are recursive. The Recursive encoding must not be used during the expansion
8760 /// of a recursive type's recursive branch. For simplicity the code uses
8761 /// IncompleteCount to reject all usage of Recursive encodings for member types.
8762 ///
8763 /// An Incomplete entry is always a RecordType and only encodes its
8764 /// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and
8765 /// are placed into the cache during type expansion as a means to identify and
8766 /// handle recursive inclusion of types as sub-members. If there is recursion
8767 /// the entry becomes IncompleteUsed.
8768 ///
8769 /// During the expansion of a RecordType's members:
8770 ///
8771 ///   If the cache contains a NonRecursive encoding for the member type, the
8772 ///   cached encoding is used;
8773 ///
8774 ///   If the cache contains a Recursive encoding for the member type, the
8775 ///   cached encoding is 'Swapped' out, as it may be incorrect, and...
8776 ///
8777 ///   If the member is a RecordType, an Incomplete encoding is placed into the
8778 ///   cache to break potential recursive inclusion of itself as a sub-member;
8779 ///
8780 ///   Once a member RecordType has been expanded, its temporary incomplete
8781 ///   entry is removed from the cache. If a Recursive encoding was swapped out
8782 ///   it is swapped back in;
8783 ///
8784 ///   If an incomplete entry is used to expand a sub-member, the incomplete
8785 ///   entry is marked as IncompleteUsed. The cache keeps count of how many
8786 ///   IncompleteUsed entries it currently contains in IncompleteUsedCount;
8787 ///
8788 ///   If a member's encoding is found to be a NonRecursive or Recursive viz:
8789 ///   IncompleteUsedCount==0, the member's encoding is added to the cache.
8790 ///   Else the member is part of a recursive type and thus the recursion has
8791 ///   been exited too soon for the encoding to be correct for the member.
8792 ///
8793 class TypeStringCache {
8794   enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed};
8795   struct Entry {
8796     std::string Str;     // The encoded TypeString for the type.
8797     enum Status State;   // Information about the encoding in 'Str'.
8798     std::string Swapped; // A temporary place holder for a Recursive encoding
8799                          // during the expansion of RecordType's members.
8800   };
8801   std::map<const IdentifierInfo *, struct Entry> Map;
8802   unsigned IncompleteCount;     // Number of Incomplete entries in the Map.
8803   unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map.
8804 public:
8805   TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {}
8806   void addIncomplete(const IdentifierInfo *ID, std::string StubEnc);
8807   bool removeIncomplete(const IdentifierInfo *ID);
8808   void addIfComplete(const IdentifierInfo *ID, StringRef Str,
8809                      bool IsRecursive);
8810   StringRef lookupStr(const IdentifierInfo *ID);
8811 };
8812 
8813 /// TypeString encodings for enum & union fields must be order.
8814 /// FieldEncoding is a helper for this ordering process.
8815 class FieldEncoding {
8816   bool HasName;
8817   std::string Enc;
8818 public:
8819   FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {}
8820   StringRef str() { return Enc; }
8821   bool operator<(const FieldEncoding &rhs) const {
8822     if (HasName != rhs.HasName) return HasName;
8823     return Enc < rhs.Enc;
8824   }
8825 };
8826 
8827 class XCoreABIInfo : public DefaultABIInfo {
8828 public:
8829   XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
8830   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8831                     QualType Ty) const override;
8832 };
8833 
8834 class XCoreTargetCodeGenInfo : public TargetCodeGenInfo {
8835   mutable TypeStringCache TSC;
8836 public:
8837   XCoreTargetCodeGenInfo(CodeGenTypes &CGT)
8838     :TargetCodeGenInfo(new XCoreABIInfo(CGT)) {}
8839   void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
8840                     CodeGen::CodeGenModule &M) const override;
8841 };
8842 
8843 } // End anonymous namespace.
8844 
8845 // TODO: this implementation is likely now redundant with the default
8846 // EmitVAArg.
8847 Address XCoreABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8848                                 QualType Ty) const {
8849   CGBuilderTy &Builder = CGF.Builder;
8850 
8851   // Get the VAList.
8852   CharUnits SlotSize = CharUnits::fromQuantity(4);
8853   Address AP(Builder.CreateLoad(VAListAddr), SlotSize);
8854 
8855   // Handle the argument.
8856   ABIArgInfo AI = classifyArgumentType(Ty);
8857   CharUnits TypeAlign = getContext().getTypeAlignInChars(Ty);
8858   llvm::Type *ArgTy = CGT.ConvertType(Ty);
8859   if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
8860     AI.setCoerceToType(ArgTy);
8861   llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
8862 
8863   Address Val = Address::invalid();
8864   CharUnits ArgSize = CharUnits::Zero();
8865   switch (AI.getKind()) {
8866   case ABIArgInfo::Expand:
8867   case ABIArgInfo::CoerceAndExpand:
8868   case ABIArgInfo::InAlloca:
8869     llvm_unreachable("Unsupported ABI kind for va_arg");
8870   case ABIArgInfo::Ignore:
8871     Val = Address(llvm::UndefValue::get(ArgPtrTy), TypeAlign);
8872     ArgSize = CharUnits::Zero();
8873     break;
8874   case ABIArgInfo::Extend:
8875   case ABIArgInfo::Direct:
8876     Val = Builder.CreateBitCast(AP, ArgPtrTy);
8877     ArgSize = CharUnits::fromQuantity(
8878                        getDataLayout().getTypeAllocSize(AI.getCoerceToType()));
8879     ArgSize = ArgSize.alignTo(SlotSize);
8880     break;
8881   case ABIArgInfo::Indirect:
8882     Val = Builder.CreateElementBitCast(AP, ArgPtrTy);
8883     Val = Address(Builder.CreateLoad(Val), TypeAlign);
8884     ArgSize = SlotSize;
8885     break;
8886   }
8887 
8888   // Increment the VAList.
8889   if (!ArgSize.isZero()) {
8890     Address APN = Builder.CreateConstInBoundsByteGEP(AP, ArgSize);
8891     Builder.CreateStore(APN.getPointer(), VAListAddr);
8892   }
8893 
8894   return Val;
8895 }
8896 
8897 /// During the expansion of a RecordType, an incomplete TypeString is placed
8898 /// into the cache as a means to identify and break recursion.
8899 /// If there is a Recursive encoding in the cache, it is swapped out and will
8900 /// be reinserted by removeIncomplete().
8901 /// All other types of encoding should have been used rather than arriving here.
8902 void TypeStringCache::addIncomplete(const IdentifierInfo *ID,
8903                                     std::string StubEnc) {
8904   if (!ID)
8905     return;
8906   Entry &E = Map[ID];
8907   assert( (E.Str.empty() || E.State == Recursive) &&
8908          "Incorrectly use of addIncomplete");
8909   assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()");
8910   E.Swapped.swap(E.Str); // swap out the Recursive
8911   E.Str.swap(StubEnc);
8912   E.State = Incomplete;
8913   ++IncompleteCount;
8914 }
8915 
8916 /// Once the RecordType has been expanded, the temporary incomplete TypeString
8917 /// must be removed from the cache.
8918 /// If a Recursive was swapped out by addIncomplete(), it will be replaced.
8919 /// Returns true if the RecordType was defined recursively.
8920 bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) {
8921   if (!ID)
8922     return false;
8923   auto I = Map.find(ID);
8924   assert(I != Map.end() && "Entry not present");
8925   Entry &E = I->second;
8926   assert( (E.State == Incomplete ||
8927            E.State == IncompleteUsed) &&
8928          "Entry must be an incomplete type");
8929   bool IsRecursive = false;
8930   if (E.State == IncompleteUsed) {
8931     // We made use of our Incomplete encoding, thus we are recursive.
8932     IsRecursive = true;
8933     --IncompleteUsedCount;
8934   }
8935   if (E.Swapped.empty())
8936     Map.erase(I);
8937   else {
8938     // Swap the Recursive back.
8939     E.Swapped.swap(E.Str);
8940     E.Swapped.clear();
8941     E.State = Recursive;
8942   }
8943   --IncompleteCount;
8944   return IsRecursive;
8945 }
8946 
8947 /// Add the encoded TypeString to the cache only if it is NonRecursive or
8948 /// Recursive (viz: all sub-members were expanded as fully as possible).
8949 void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str,
8950                                     bool IsRecursive) {
8951   if (!ID || IncompleteUsedCount)
8952     return; // No key or it is is an incomplete sub-type so don't add.
8953   Entry &E = Map[ID];
8954   if (IsRecursive && !E.Str.empty()) {
8955     assert(E.State==Recursive && E.Str.size() == Str.size() &&
8956            "This is not the same Recursive entry");
8957     // The parent container was not recursive after all, so we could have used
8958     // this Recursive sub-member entry after all, but we assumed the worse when
8959     // we started viz: IncompleteCount!=0.
8960     return;
8961   }
8962   assert(E.Str.empty() && "Entry already present");
8963   E.Str = Str.str();
8964   E.State = IsRecursive? Recursive : NonRecursive;
8965 }
8966 
8967 /// Return a cached TypeString encoding for the ID. If there isn't one, or we
8968 /// are recursively expanding a type (IncompleteCount != 0) and the cached
8969 /// encoding is Recursive, return an empty StringRef.
8970 StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) {
8971   if (!ID)
8972     return StringRef();   // We have no key.
8973   auto I = Map.find(ID);
8974   if (I == Map.end())
8975     return StringRef();   // We have no encoding.
8976   Entry &E = I->second;
8977   if (E.State == Recursive && IncompleteCount)
8978     return StringRef();   // We don't use Recursive encodings for member types.
8979 
8980   if (E.State == Incomplete) {
8981     // The incomplete type is being used to break out of recursion.
8982     E.State = IncompleteUsed;
8983     ++IncompleteUsedCount;
8984   }
8985   return E.Str;
8986 }
8987 
8988 /// The XCore ABI includes a type information section that communicates symbol
8989 /// type information to the linker. The linker uses this information to verify
8990 /// safety/correctness of things such as array bound and pointers et al.
8991 /// The ABI only requires C (and XC) language modules to emit TypeStrings.
8992 /// This type information (TypeString) is emitted into meta data for all global
8993 /// symbols: definitions, declarations, functions & variables.
8994 ///
8995 /// The TypeString carries type, qualifier, name, size & value details.
8996 /// Please see 'Tools Development Guide' section 2.16.2 for format details:
8997 /// https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf
8998 /// The output is tested by test/CodeGen/xcore-stringtype.c.
8999 ///
9000 static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
9001                           CodeGen::CodeGenModule &CGM, TypeStringCache &TSC);
9002 
9003 /// XCore uses emitTargetMD to emit TypeString metadata for global symbols.
9004 void XCoreTargetCodeGenInfo::emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
9005                                           CodeGen::CodeGenModule &CGM) const {
9006   SmallStringEnc Enc;
9007   if (getTypeString(Enc, D, CGM, TSC)) {
9008     llvm::LLVMContext &Ctx = CGM.getModule().getContext();
9009     llvm::Metadata *MDVals[] = {llvm::ConstantAsMetadata::get(GV),
9010                                 llvm::MDString::get(Ctx, Enc.str())};
9011     llvm::NamedMDNode *MD =
9012       CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings");
9013     MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
9014   }
9015 }
9016 
9017 //===----------------------------------------------------------------------===//
9018 // SPIR ABI Implementation
9019 //===----------------------------------------------------------------------===//
9020 
9021 namespace {
9022 class SPIRTargetCodeGenInfo : public TargetCodeGenInfo {
9023 public:
9024   SPIRTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
9025     : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
9026   unsigned getOpenCLKernelCallingConv() const override;
9027 };
9028 
9029 } // End anonymous namespace.
9030 
9031 namespace clang {
9032 namespace CodeGen {
9033 void computeSPIRKernelABIInfo(CodeGenModule &CGM, CGFunctionInfo &FI) {
9034   DefaultABIInfo SPIRABI(CGM.getTypes());
9035   SPIRABI.computeInfo(FI);
9036 }
9037 }
9038 }
9039 
9040 unsigned SPIRTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
9041   return llvm::CallingConv::SPIR_KERNEL;
9042 }
9043 
9044 static bool appendType(SmallStringEnc &Enc, QualType QType,
9045                        const CodeGen::CodeGenModule &CGM,
9046                        TypeStringCache &TSC);
9047 
9048 /// Helper function for appendRecordType().
9049 /// Builds a SmallVector containing the encoded field types in declaration
9050 /// order.
9051 static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE,
9052                              const RecordDecl *RD,
9053                              const CodeGen::CodeGenModule &CGM,
9054                              TypeStringCache &TSC) {
9055   for (const auto *Field : RD->fields()) {
9056     SmallStringEnc Enc;
9057     Enc += "m(";
9058     Enc += Field->getName();
9059     Enc += "){";
9060     if (Field->isBitField()) {
9061       Enc += "b(";
9062       llvm::raw_svector_ostream OS(Enc);
9063       OS << Field->getBitWidthValue(CGM.getContext());
9064       Enc += ':';
9065     }
9066     if (!appendType(Enc, Field->getType(), CGM, TSC))
9067       return false;
9068     if (Field->isBitField())
9069       Enc += ')';
9070     Enc += '}';
9071     FE.emplace_back(!Field->getName().empty(), Enc);
9072   }
9073   return true;
9074 }
9075 
9076 /// Appends structure and union types to Enc and adds encoding to cache.
9077 /// Recursively calls appendType (via extractFieldType) for each field.
9078 /// Union types have their fields ordered according to the ABI.
9079 static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT,
9080                              const CodeGen::CodeGenModule &CGM,
9081                              TypeStringCache &TSC, const IdentifierInfo *ID) {
9082   // Append the cached TypeString if we have one.
9083   StringRef TypeString = TSC.lookupStr(ID);
9084   if (!TypeString.empty()) {
9085     Enc += TypeString;
9086     return true;
9087   }
9088 
9089   // Start to emit an incomplete TypeString.
9090   size_t Start = Enc.size();
9091   Enc += (RT->isUnionType()? 'u' : 's');
9092   Enc += '(';
9093   if (ID)
9094     Enc += ID->getName();
9095   Enc += "){";
9096 
9097   // We collect all encoded fields and order as necessary.
9098   bool IsRecursive = false;
9099   const RecordDecl *RD = RT->getDecl()->getDefinition();
9100   if (RD && !RD->field_empty()) {
9101     // An incomplete TypeString stub is placed in the cache for this RecordType
9102     // so that recursive calls to this RecordType will use it whilst building a
9103     // complete TypeString for this RecordType.
9104     SmallVector<FieldEncoding, 16> FE;
9105     std::string StubEnc(Enc.substr(Start).str());
9106     StubEnc += '}';  // StubEnc now holds a valid incomplete TypeString.
9107     TSC.addIncomplete(ID, std::move(StubEnc));
9108     if (!extractFieldType(FE, RD, CGM, TSC)) {
9109       (void) TSC.removeIncomplete(ID);
9110       return false;
9111     }
9112     IsRecursive = TSC.removeIncomplete(ID);
9113     // The ABI requires unions to be sorted but not structures.
9114     // See FieldEncoding::operator< for sort algorithm.
9115     if (RT->isUnionType())
9116       llvm::sort(FE);
9117     // We can now complete the TypeString.
9118     unsigned E = FE.size();
9119     for (unsigned I = 0; I != E; ++I) {
9120       if (I)
9121         Enc += ',';
9122       Enc += FE[I].str();
9123     }
9124   }
9125   Enc += '}';
9126   TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive);
9127   return true;
9128 }
9129 
9130 /// Appends enum types to Enc and adds the encoding to the cache.
9131 static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET,
9132                            TypeStringCache &TSC,
9133                            const IdentifierInfo *ID) {
9134   // Append the cached TypeString if we have one.
9135   StringRef TypeString = TSC.lookupStr(ID);
9136   if (!TypeString.empty()) {
9137     Enc += TypeString;
9138     return true;
9139   }
9140 
9141   size_t Start = Enc.size();
9142   Enc += "e(";
9143   if (ID)
9144     Enc += ID->getName();
9145   Enc += "){";
9146 
9147   // We collect all encoded enumerations and order them alphanumerically.
9148   if (const EnumDecl *ED = ET->getDecl()->getDefinition()) {
9149     SmallVector<FieldEncoding, 16> FE;
9150     for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E;
9151          ++I) {
9152       SmallStringEnc EnumEnc;
9153       EnumEnc += "m(";
9154       EnumEnc += I->getName();
9155       EnumEnc += "){";
9156       I->getInitVal().toString(EnumEnc);
9157       EnumEnc += '}';
9158       FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc));
9159     }
9160     llvm::sort(FE);
9161     unsigned E = FE.size();
9162     for (unsigned I = 0; I != E; ++I) {
9163       if (I)
9164         Enc += ',';
9165       Enc += FE[I].str();
9166     }
9167   }
9168   Enc += '}';
9169   TSC.addIfComplete(ID, Enc.substr(Start), false);
9170   return true;
9171 }
9172 
9173 /// Appends type's qualifier to Enc.
9174 /// This is done prior to appending the type's encoding.
9175 static void appendQualifier(SmallStringEnc &Enc, QualType QT) {
9176   // Qualifiers are emitted in alphabetical order.
9177   static const char *const Table[]={"","c:","r:","cr:","v:","cv:","rv:","crv:"};
9178   int Lookup = 0;
9179   if (QT.isConstQualified())
9180     Lookup += 1<<0;
9181   if (QT.isRestrictQualified())
9182     Lookup += 1<<1;
9183   if (QT.isVolatileQualified())
9184     Lookup += 1<<2;
9185   Enc += Table[Lookup];
9186 }
9187 
9188 /// Appends built-in types to Enc.
9189 static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) {
9190   const char *EncType;
9191   switch (BT->getKind()) {
9192     case BuiltinType::Void:
9193       EncType = "0";
9194       break;
9195     case BuiltinType::Bool:
9196       EncType = "b";
9197       break;
9198     case BuiltinType::Char_U:
9199       EncType = "uc";
9200       break;
9201     case BuiltinType::UChar:
9202       EncType = "uc";
9203       break;
9204     case BuiltinType::SChar:
9205       EncType = "sc";
9206       break;
9207     case BuiltinType::UShort:
9208       EncType = "us";
9209       break;
9210     case BuiltinType::Short:
9211       EncType = "ss";
9212       break;
9213     case BuiltinType::UInt:
9214       EncType = "ui";
9215       break;
9216     case BuiltinType::Int:
9217       EncType = "si";
9218       break;
9219     case BuiltinType::ULong:
9220       EncType = "ul";
9221       break;
9222     case BuiltinType::Long:
9223       EncType = "sl";
9224       break;
9225     case BuiltinType::ULongLong:
9226       EncType = "ull";
9227       break;
9228     case BuiltinType::LongLong:
9229       EncType = "sll";
9230       break;
9231     case BuiltinType::Float:
9232       EncType = "ft";
9233       break;
9234     case BuiltinType::Double:
9235       EncType = "d";
9236       break;
9237     case BuiltinType::LongDouble:
9238       EncType = "ld";
9239       break;
9240     default:
9241       return false;
9242   }
9243   Enc += EncType;
9244   return true;
9245 }
9246 
9247 /// Appends a pointer encoding to Enc before calling appendType for the pointee.
9248 static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT,
9249                               const CodeGen::CodeGenModule &CGM,
9250                               TypeStringCache &TSC) {
9251   Enc += "p(";
9252   if (!appendType(Enc, PT->getPointeeType(), CGM, TSC))
9253     return false;
9254   Enc += ')';
9255   return true;
9256 }
9257 
9258 /// Appends array encoding to Enc before calling appendType for the element.
9259 static bool appendArrayType(SmallStringEnc &Enc, QualType QT,
9260                             const ArrayType *AT,
9261                             const CodeGen::CodeGenModule &CGM,
9262                             TypeStringCache &TSC, StringRef NoSizeEnc) {
9263   if (AT->getSizeModifier() != ArrayType::Normal)
9264     return false;
9265   Enc += "a(";
9266   if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
9267     CAT->getSize().toStringUnsigned(Enc);
9268   else
9269     Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "".
9270   Enc += ':';
9271   // The Qualifiers should be attached to the type rather than the array.
9272   appendQualifier(Enc, QT);
9273   if (!appendType(Enc, AT->getElementType(), CGM, TSC))
9274     return false;
9275   Enc += ')';
9276   return true;
9277 }
9278 
9279 /// Appends a function encoding to Enc, calling appendType for the return type
9280 /// and the arguments.
9281 static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT,
9282                              const CodeGen::CodeGenModule &CGM,
9283                              TypeStringCache &TSC) {
9284   Enc += "f{";
9285   if (!appendType(Enc, FT->getReturnType(), CGM, TSC))
9286     return false;
9287   Enc += "}(";
9288   if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) {
9289     // N.B. we are only interested in the adjusted param types.
9290     auto I = FPT->param_type_begin();
9291     auto E = FPT->param_type_end();
9292     if (I != E) {
9293       do {
9294         if (!appendType(Enc, *I, CGM, TSC))
9295           return false;
9296         ++I;
9297         if (I != E)
9298           Enc += ',';
9299       } while (I != E);
9300       if (FPT->isVariadic())
9301         Enc += ",va";
9302     } else {
9303       if (FPT->isVariadic())
9304         Enc += "va";
9305       else
9306         Enc += '0';
9307     }
9308   }
9309   Enc += ')';
9310   return true;
9311 }
9312 
9313 /// Handles the type's qualifier before dispatching a call to handle specific
9314 /// type encodings.
9315 static bool appendType(SmallStringEnc &Enc, QualType QType,
9316                        const CodeGen::CodeGenModule &CGM,
9317                        TypeStringCache &TSC) {
9318 
9319   QualType QT = QType.getCanonicalType();
9320 
9321   if (const ArrayType *AT = QT->getAsArrayTypeUnsafe())
9322     // The Qualifiers should be attached to the type rather than the array.
9323     // Thus we don't call appendQualifier() here.
9324     return appendArrayType(Enc, QT, AT, CGM, TSC, "");
9325 
9326   appendQualifier(Enc, QT);
9327 
9328   if (const BuiltinType *BT = QT->getAs<BuiltinType>())
9329     return appendBuiltinType(Enc, BT);
9330 
9331   if (const PointerType *PT = QT->getAs<PointerType>())
9332     return appendPointerType(Enc, PT, CGM, TSC);
9333 
9334   if (const EnumType *ET = QT->getAs<EnumType>())
9335     return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier());
9336 
9337   if (const RecordType *RT = QT->getAsStructureType())
9338     return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
9339 
9340   if (const RecordType *RT = QT->getAsUnionType())
9341     return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
9342 
9343   if (const FunctionType *FT = QT->getAs<FunctionType>())
9344     return appendFunctionType(Enc, FT, CGM, TSC);
9345 
9346   return false;
9347 }
9348 
9349 static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
9350                           CodeGen::CodeGenModule &CGM, TypeStringCache &TSC) {
9351   if (!D)
9352     return false;
9353 
9354   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
9355     if (FD->getLanguageLinkage() != CLanguageLinkage)
9356       return false;
9357     return appendType(Enc, FD->getType(), CGM, TSC);
9358   }
9359 
9360   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
9361     if (VD->getLanguageLinkage() != CLanguageLinkage)
9362       return false;
9363     QualType QT = VD->getType().getCanonicalType();
9364     if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) {
9365       // Global ArrayTypes are given a size of '*' if the size is unknown.
9366       // The Qualifiers should be attached to the type rather than the array.
9367       // Thus we don't call appendQualifier() here.
9368       return appendArrayType(Enc, QT, AT, CGM, TSC, "*");
9369     }
9370     return appendType(Enc, QT, CGM, TSC);
9371   }
9372   return false;
9373 }
9374 
9375 //===----------------------------------------------------------------------===//
9376 // RISCV ABI Implementation
9377 //===----------------------------------------------------------------------===//
9378 
9379 namespace {
9380 class RISCVABIInfo : public DefaultABIInfo {
9381 private:
9382   // Size of the integer ('x') registers in bits.
9383   unsigned XLen;
9384   // Size of the floating point ('f') registers in bits. Note that the target
9385   // ISA might have a wider FLen than the selected ABI (e.g. an RV32IF target
9386   // with soft float ABI has FLen==0).
9387   unsigned FLen;
9388   static const int NumArgGPRs = 8;
9389   static const int NumArgFPRs = 8;
9390   bool detectFPCCEligibleStructHelper(QualType Ty, CharUnits CurOff,
9391                                       llvm::Type *&Field1Ty,
9392                                       CharUnits &Field1Off,
9393                                       llvm::Type *&Field2Ty,
9394                                       CharUnits &Field2Off) const;
9395 
9396 public:
9397   RISCVABIInfo(CodeGen::CodeGenTypes &CGT, unsigned XLen, unsigned FLen)
9398       : DefaultABIInfo(CGT), XLen(XLen), FLen(FLen) {}
9399 
9400   // DefaultABIInfo's classifyReturnType and classifyArgumentType are
9401   // non-virtual, but computeInfo is virtual, so we overload it.
9402   void computeInfo(CGFunctionInfo &FI) const override;
9403 
9404   ABIArgInfo classifyArgumentType(QualType Ty, bool IsFixed, int &ArgGPRsLeft,
9405                                   int &ArgFPRsLeft) const;
9406   ABIArgInfo classifyReturnType(QualType RetTy) const;
9407 
9408   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9409                     QualType Ty) const override;
9410 
9411   ABIArgInfo extendType(QualType Ty) const;
9412 
9413   bool detectFPCCEligibleStruct(QualType Ty, llvm::Type *&Field1Ty,
9414                                 CharUnits &Field1Off, llvm::Type *&Field2Ty,
9415                                 CharUnits &Field2Off, int &NeededArgGPRs,
9416                                 int &NeededArgFPRs) const;
9417   ABIArgInfo coerceAndExpandFPCCEligibleStruct(llvm::Type *Field1Ty,
9418                                                CharUnits Field1Off,
9419                                                llvm::Type *Field2Ty,
9420                                                CharUnits Field2Off) const;
9421 };
9422 } // end anonymous namespace
9423 
9424 void RISCVABIInfo::computeInfo(CGFunctionInfo &FI) const {
9425   QualType RetTy = FI.getReturnType();
9426   if (!getCXXABI().classifyReturnType(FI))
9427     FI.getReturnInfo() = classifyReturnType(RetTy);
9428 
9429   // IsRetIndirect is true if classifyArgumentType indicated the value should
9430   // be passed indirect, or if the type size is a scalar greater than 2*XLen
9431   // and not a complex type with elements <= FLen. e.g. fp128 is passed direct
9432   // in LLVM IR, relying on the backend lowering code to rewrite the argument
9433   // list and pass indirectly on RV32.
9434   bool IsRetIndirect = FI.getReturnInfo().getKind() == ABIArgInfo::Indirect;
9435   if (!IsRetIndirect && RetTy->isScalarType() &&
9436       getContext().getTypeSize(RetTy) > (2 * XLen)) {
9437     if (RetTy->isComplexType() && FLen) {
9438       QualType EltTy = RetTy->getAs<ComplexType>()->getElementType();
9439       IsRetIndirect = getContext().getTypeSize(EltTy) > FLen;
9440     } else {
9441       // This is a normal scalar > 2*XLen, such as fp128 on RV32.
9442       IsRetIndirect = true;
9443     }
9444   }
9445 
9446   // We must track the number of GPRs used in order to conform to the RISC-V
9447   // ABI, as integer scalars passed in registers should have signext/zeroext
9448   // when promoted, but are anyext if passed on the stack. As GPR usage is
9449   // different for variadic arguments, we must also track whether we are
9450   // examining a vararg or not.
9451   int ArgGPRsLeft = IsRetIndirect ? NumArgGPRs - 1 : NumArgGPRs;
9452   int ArgFPRsLeft = FLen ? NumArgFPRs : 0;
9453   int NumFixedArgs = FI.getNumRequiredArgs();
9454 
9455   int ArgNum = 0;
9456   for (auto &ArgInfo : FI.arguments()) {
9457     bool IsFixed = ArgNum < NumFixedArgs;
9458     ArgInfo.info =
9459         classifyArgumentType(ArgInfo.type, IsFixed, ArgGPRsLeft, ArgFPRsLeft);
9460     ArgNum++;
9461   }
9462 }
9463 
9464 // Returns true if the struct is a potential candidate for the floating point
9465 // calling convention. If this function returns true, the caller is
9466 // responsible for checking that if there is only a single field then that
9467 // field is a float.
9468 bool RISCVABIInfo::detectFPCCEligibleStructHelper(QualType Ty, CharUnits CurOff,
9469                                                   llvm::Type *&Field1Ty,
9470                                                   CharUnits &Field1Off,
9471                                                   llvm::Type *&Field2Ty,
9472                                                   CharUnits &Field2Off) const {
9473   bool IsInt = Ty->isIntegralOrEnumerationType();
9474   bool IsFloat = Ty->isRealFloatingType();
9475 
9476   if (IsInt || IsFloat) {
9477     uint64_t Size = getContext().getTypeSize(Ty);
9478     if (IsInt && Size > XLen)
9479       return false;
9480     // Can't be eligible if larger than the FP registers. Half precision isn't
9481     // currently supported on RISC-V and the ABI hasn't been confirmed, so
9482     // default to the integer ABI in that case.
9483     if (IsFloat && (Size > FLen || Size < 32))
9484       return false;
9485     // Can't be eligible if an integer type was already found (int+int pairs
9486     // are not eligible).
9487     if (IsInt && Field1Ty && Field1Ty->isIntegerTy())
9488       return false;
9489     if (!Field1Ty) {
9490       Field1Ty = CGT.ConvertType(Ty);
9491       Field1Off = CurOff;
9492       return true;
9493     }
9494     if (!Field2Ty) {
9495       Field2Ty = CGT.ConvertType(Ty);
9496       Field2Off = CurOff;
9497       return true;
9498     }
9499     return false;
9500   }
9501 
9502   if (auto CTy = Ty->getAs<ComplexType>()) {
9503     if (Field1Ty)
9504       return false;
9505     QualType EltTy = CTy->getElementType();
9506     if (getContext().getTypeSize(EltTy) > FLen)
9507       return false;
9508     Field1Ty = CGT.ConvertType(EltTy);
9509     Field1Off = CurOff;
9510     assert(CurOff.isZero() && "Unexpected offset for first field");
9511     Field2Ty = Field1Ty;
9512     Field2Off = Field1Off + getContext().getTypeSizeInChars(EltTy);
9513     return true;
9514   }
9515 
9516   if (const ConstantArrayType *ATy = getContext().getAsConstantArrayType(Ty)) {
9517     uint64_t ArraySize = ATy->getSize().getZExtValue();
9518     QualType EltTy = ATy->getElementType();
9519     CharUnits EltSize = getContext().getTypeSizeInChars(EltTy);
9520     for (uint64_t i = 0; i < ArraySize; ++i) {
9521       bool Ret = detectFPCCEligibleStructHelper(EltTy, CurOff, Field1Ty,
9522                                                 Field1Off, Field2Ty, Field2Off);
9523       if (!Ret)
9524         return false;
9525       CurOff += EltSize;
9526     }
9527     return true;
9528   }
9529 
9530   if (const auto *RTy = Ty->getAs<RecordType>()) {
9531     // Structures with either a non-trivial destructor or a non-trivial
9532     // copy constructor are not eligible for the FP calling convention.
9533     if (getRecordArgABI(Ty, CGT.getCXXABI()))
9534       return false;
9535     if (isEmptyRecord(getContext(), Ty, true))
9536       return true;
9537     const RecordDecl *RD = RTy->getDecl();
9538     // Unions aren't eligible unless they're empty (which is caught above).
9539     if (RD->isUnion())
9540       return false;
9541     int ZeroWidthBitFieldCount = 0;
9542     for (const FieldDecl *FD : RD->fields()) {
9543       const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
9544       uint64_t FieldOffInBits = Layout.getFieldOffset(FD->getFieldIndex());
9545       QualType QTy = FD->getType();
9546       if (FD->isBitField()) {
9547         unsigned BitWidth = FD->getBitWidthValue(getContext());
9548         // Allow a bitfield with a type greater than XLen as long as the
9549         // bitwidth is XLen or less.
9550         if (getContext().getTypeSize(QTy) > XLen && BitWidth <= XLen)
9551           QTy = getContext().getIntTypeForBitwidth(XLen, false);
9552         if (BitWidth == 0) {
9553           ZeroWidthBitFieldCount++;
9554           continue;
9555         }
9556       }
9557 
9558       bool Ret = detectFPCCEligibleStructHelper(
9559           QTy, CurOff + getContext().toCharUnitsFromBits(FieldOffInBits),
9560           Field1Ty, Field1Off, Field2Ty, Field2Off);
9561       if (!Ret)
9562         return false;
9563 
9564       // As a quirk of the ABI, zero-width bitfields aren't ignored for fp+fp
9565       // or int+fp structs, but are ignored for a struct with an fp field and
9566       // any number of zero-width bitfields.
9567       if (Field2Ty && ZeroWidthBitFieldCount > 0)
9568         return false;
9569     }
9570     return Field1Ty != nullptr;
9571   }
9572 
9573   return false;
9574 }
9575 
9576 // Determine if a struct is eligible for passing according to the floating
9577 // point calling convention (i.e., when flattened it contains a single fp
9578 // value, fp+fp, or int+fp of appropriate size). If so, NeededArgFPRs and
9579 // NeededArgGPRs are incremented appropriately.
9580 bool RISCVABIInfo::detectFPCCEligibleStruct(QualType Ty, llvm::Type *&Field1Ty,
9581                                             CharUnits &Field1Off,
9582                                             llvm::Type *&Field2Ty,
9583                                             CharUnits &Field2Off,
9584                                             int &NeededArgGPRs,
9585                                             int &NeededArgFPRs) const {
9586   Field1Ty = nullptr;
9587   Field2Ty = nullptr;
9588   NeededArgGPRs = 0;
9589   NeededArgFPRs = 0;
9590   bool IsCandidate = detectFPCCEligibleStructHelper(
9591       Ty, CharUnits::Zero(), Field1Ty, Field1Off, Field2Ty, Field2Off);
9592   // Not really a candidate if we have a single int but no float.
9593   if (Field1Ty && !Field2Ty && !Field1Ty->isFloatingPointTy())
9594     return false;
9595   if (!IsCandidate)
9596     return false;
9597   if (Field1Ty && Field1Ty->isFloatingPointTy())
9598     NeededArgFPRs++;
9599   else if (Field1Ty)
9600     NeededArgGPRs++;
9601   if (Field2Ty && Field2Ty->isFloatingPointTy())
9602     NeededArgFPRs++;
9603   else if (Field2Ty)
9604     NeededArgGPRs++;
9605   return IsCandidate;
9606 }
9607 
9608 // Call getCoerceAndExpand for the two-element flattened struct described by
9609 // Field1Ty, Field1Off, Field2Ty, Field2Off. This method will create an
9610 // appropriate coerceToType and unpaddedCoerceToType.
9611 ABIArgInfo RISCVABIInfo::coerceAndExpandFPCCEligibleStruct(
9612     llvm::Type *Field1Ty, CharUnits Field1Off, llvm::Type *Field2Ty,
9613     CharUnits Field2Off) const {
9614   SmallVector<llvm::Type *, 3> CoerceElts;
9615   SmallVector<llvm::Type *, 2> UnpaddedCoerceElts;
9616   if (!Field1Off.isZero())
9617     CoerceElts.push_back(llvm::ArrayType::get(
9618         llvm::Type::getInt8Ty(getVMContext()), Field1Off.getQuantity()));
9619 
9620   CoerceElts.push_back(Field1Ty);
9621   UnpaddedCoerceElts.push_back(Field1Ty);
9622 
9623   if (!Field2Ty) {
9624     return ABIArgInfo::getCoerceAndExpand(
9625         llvm::StructType::get(getVMContext(), CoerceElts, !Field1Off.isZero()),
9626         UnpaddedCoerceElts[0]);
9627   }
9628 
9629   CharUnits Field2Align =
9630       CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(Field2Ty));
9631   CharUnits Field1Size =
9632       CharUnits::fromQuantity(getDataLayout().getTypeStoreSize(Field1Ty));
9633   CharUnits Field2OffNoPadNoPack = Field1Size.alignTo(Field2Align);
9634 
9635   CharUnits Padding = CharUnits::Zero();
9636   if (Field2Off > Field2OffNoPadNoPack)
9637     Padding = Field2Off - Field2OffNoPadNoPack;
9638   else if (Field2Off != Field2Align && Field2Off > Field1Size)
9639     Padding = Field2Off - Field1Size;
9640 
9641   bool IsPacked = !Field2Off.isMultipleOf(Field2Align);
9642 
9643   if (!Padding.isZero())
9644     CoerceElts.push_back(llvm::ArrayType::get(
9645         llvm::Type::getInt8Ty(getVMContext()), Padding.getQuantity()));
9646 
9647   CoerceElts.push_back(Field2Ty);
9648   UnpaddedCoerceElts.push_back(Field2Ty);
9649 
9650   auto CoerceToType =
9651       llvm::StructType::get(getVMContext(), CoerceElts, IsPacked);
9652   auto UnpaddedCoerceToType =
9653       llvm::StructType::get(getVMContext(), UnpaddedCoerceElts, IsPacked);
9654 
9655   return ABIArgInfo::getCoerceAndExpand(CoerceToType, UnpaddedCoerceToType);
9656 }
9657 
9658 ABIArgInfo RISCVABIInfo::classifyArgumentType(QualType Ty, bool IsFixed,
9659                                               int &ArgGPRsLeft,
9660                                               int &ArgFPRsLeft) const {
9661   assert(ArgGPRsLeft <= NumArgGPRs && "Arg GPR tracking underflow");
9662   Ty = useFirstFieldIfTransparentUnion(Ty);
9663 
9664   // Structures with either a non-trivial destructor or a non-trivial
9665   // copy constructor are always passed indirectly.
9666   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
9667     if (ArgGPRsLeft)
9668       ArgGPRsLeft -= 1;
9669     return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA ==
9670                                            CGCXXABI::RAA_DirectInMemory);
9671   }
9672 
9673   // Ignore empty structs/unions.
9674   if (isEmptyRecord(getContext(), Ty, true))
9675     return ABIArgInfo::getIgnore();
9676 
9677   uint64_t Size = getContext().getTypeSize(Ty);
9678 
9679   // Pass floating point values via FPRs if possible.
9680   if (IsFixed && Ty->isFloatingType() && !Ty->isComplexType() &&
9681       FLen >= Size && ArgFPRsLeft) {
9682     ArgFPRsLeft--;
9683     return ABIArgInfo::getDirect();
9684   }
9685 
9686   // Complex types for the hard float ABI must be passed direct rather than
9687   // using CoerceAndExpand.
9688   if (IsFixed && Ty->isComplexType() && FLen && ArgFPRsLeft >= 2) {
9689     QualType EltTy = Ty->castAs<ComplexType>()->getElementType();
9690     if (getContext().getTypeSize(EltTy) <= FLen) {
9691       ArgFPRsLeft -= 2;
9692       return ABIArgInfo::getDirect();
9693     }
9694   }
9695 
9696   if (IsFixed && FLen && Ty->isStructureOrClassType()) {
9697     llvm::Type *Field1Ty = nullptr;
9698     llvm::Type *Field2Ty = nullptr;
9699     CharUnits Field1Off = CharUnits::Zero();
9700     CharUnits Field2Off = CharUnits::Zero();
9701     int NeededArgGPRs;
9702     int NeededArgFPRs;
9703     bool IsCandidate =
9704         detectFPCCEligibleStruct(Ty, Field1Ty, Field1Off, Field2Ty, Field2Off,
9705                                  NeededArgGPRs, NeededArgFPRs);
9706     if (IsCandidate && NeededArgGPRs <= ArgGPRsLeft &&
9707         NeededArgFPRs <= ArgFPRsLeft) {
9708       ArgGPRsLeft -= NeededArgGPRs;
9709       ArgFPRsLeft -= NeededArgFPRs;
9710       return coerceAndExpandFPCCEligibleStruct(Field1Ty, Field1Off, Field2Ty,
9711                                                Field2Off);
9712     }
9713   }
9714 
9715   uint64_t NeededAlign = getContext().getTypeAlign(Ty);
9716   bool MustUseStack = false;
9717   // Determine the number of GPRs needed to pass the current argument
9718   // according to the ABI. 2*XLen-aligned varargs are passed in "aligned"
9719   // register pairs, so may consume 3 registers.
9720   int NeededArgGPRs = 1;
9721   if (!IsFixed && NeededAlign == 2 * XLen)
9722     NeededArgGPRs = 2 + (ArgGPRsLeft % 2);
9723   else if (Size > XLen && Size <= 2 * XLen)
9724     NeededArgGPRs = 2;
9725 
9726   if (NeededArgGPRs > ArgGPRsLeft) {
9727     MustUseStack = true;
9728     NeededArgGPRs = ArgGPRsLeft;
9729   }
9730 
9731   ArgGPRsLeft -= NeededArgGPRs;
9732 
9733   if (!isAggregateTypeForABI(Ty) && !Ty->isVectorType()) {
9734     // Treat an enum type as its underlying type.
9735     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
9736       Ty = EnumTy->getDecl()->getIntegerType();
9737 
9738     // All integral types are promoted to XLen width, unless passed on the
9739     // stack.
9740     if (Size < XLen && Ty->isIntegralOrEnumerationType() && !MustUseStack) {
9741       return extendType(Ty);
9742     }
9743 
9744     return ABIArgInfo::getDirect();
9745   }
9746 
9747   // Aggregates which are <= 2*XLen will be passed in registers if possible,
9748   // so coerce to integers.
9749   if (Size <= 2 * XLen) {
9750     unsigned Alignment = getContext().getTypeAlign(Ty);
9751 
9752     // Use a single XLen int if possible, 2*XLen if 2*XLen alignment is
9753     // required, and a 2-element XLen array if only XLen alignment is required.
9754     if (Size <= XLen) {
9755       return ABIArgInfo::getDirect(
9756           llvm::IntegerType::get(getVMContext(), XLen));
9757     } else if (Alignment == 2 * XLen) {
9758       return ABIArgInfo::getDirect(
9759           llvm::IntegerType::get(getVMContext(), 2 * XLen));
9760     } else {
9761       return ABIArgInfo::getDirect(llvm::ArrayType::get(
9762           llvm::IntegerType::get(getVMContext(), XLen), 2));
9763     }
9764   }
9765   return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
9766 }
9767 
9768 ABIArgInfo RISCVABIInfo::classifyReturnType(QualType RetTy) const {
9769   if (RetTy->isVoidType())
9770     return ABIArgInfo::getIgnore();
9771 
9772   int ArgGPRsLeft = 2;
9773   int ArgFPRsLeft = FLen ? 2 : 0;
9774 
9775   // The rules for return and argument types are the same, so defer to
9776   // classifyArgumentType.
9777   return classifyArgumentType(RetTy, /*IsFixed=*/true, ArgGPRsLeft,
9778                               ArgFPRsLeft);
9779 }
9780 
9781 Address RISCVABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9782                                 QualType Ty) const {
9783   CharUnits SlotSize = CharUnits::fromQuantity(XLen / 8);
9784 
9785   // Empty records are ignored for parameter passing purposes.
9786   if (isEmptyRecord(getContext(), Ty, true)) {
9787     Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize);
9788     Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
9789     return Addr;
9790   }
9791 
9792   std::pair<CharUnits, CharUnits> SizeAndAlign =
9793       getContext().getTypeInfoInChars(Ty);
9794 
9795   // Arguments bigger than 2*Xlen bytes are passed indirectly.
9796   bool IsIndirect = SizeAndAlign.first > 2 * SlotSize;
9797 
9798   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, SizeAndAlign,
9799                           SlotSize, /*AllowHigherAlign=*/true);
9800 }
9801 
9802 ABIArgInfo RISCVABIInfo::extendType(QualType Ty) const {
9803   int TySize = getContext().getTypeSize(Ty);
9804   // RV64 ABI requires unsigned 32 bit integers to be sign extended.
9805   if (XLen == 64 && Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
9806     return ABIArgInfo::getSignExtend(Ty);
9807   return ABIArgInfo::getExtend(Ty);
9808 }
9809 
9810 namespace {
9811 class RISCVTargetCodeGenInfo : public TargetCodeGenInfo {
9812 public:
9813   RISCVTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, unsigned XLen,
9814                          unsigned FLen)
9815       : TargetCodeGenInfo(new RISCVABIInfo(CGT, XLen, FLen)) {}
9816 
9817   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
9818                            CodeGen::CodeGenModule &CGM) const override {
9819     const auto *FD = dyn_cast_or_null<FunctionDecl>(D);
9820     if (!FD) return;
9821 
9822     const auto *Attr = FD->getAttr<RISCVInterruptAttr>();
9823     if (!Attr)
9824       return;
9825 
9826     const char *Kind;
9827     switch (Attr->getInterrupt()) {
9828     case RISCVInterruptAttr::user: Kind = "user"; break;
9829     case RISCVInterruptAttr::supervisor: Kind = "supervisor"; break;
9830     case RISCVInterruptAttr::machine: Kind = "machine"; break;
9831     }
9832 
9833     auto *Fn = cast<llvm::Function>(GV);
9834 
9835     Fn->addFnAttr("interrupt", Kind);
9836   }
9837 };
9838 } // namespace
9839 
9840 //===----------------------------------------------------------------------===//
9841 // Driver code
9842 //===----------------------------------------------------------------------===//
9843 
9844 bool CodeGenModule::supportsCOMDAT() const {
9845   return getTriple().supportsCOMDAT();
9846 }
9847 
9848 const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
9849   if (TheTargetCodeGenInfo)
9850     return *TheTargetCodeGenInfo;
9851 
9852   // Helper to set the unique_ptr while still keeping the return value.
9853   auto SetCGInfo = [&](TargetCodeGenInfo *P) -> const TargetCodeGenInfo & {
9854     this->TheTargetCodeGenInfo.reset(P);
9855     return *P;
9856   };
9857 
9858   const llvm::Triple &Triple = getTarget().getTriple();
9859   switch (Triple.getArch()) {
9860   default:
9861     return SetCGInfo(new DefaultTargetCodeGenInfo(Types));
9862 
9863   case llvm::Triple::le32:
9864     return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
9865   case llvm::Triple::mips:
9866   case llvm::Triple::mipsel:
9867     if (Triple.getOS() == llvm::Triple::NaCl)
9868       return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
9869     return SetCGInfo(new MIPSTargetCodeGenInfo(Types, true));
9870 
9871   case llvm::Triple::mips64:
9872   case llvm::Triple::mips64el:
9873     return SetCGInfo(new MIPSTargetCodeGenInfo(Types, false));
9874 
9875   case llvm::Triple::avr:
9876     return SetCGInfo(new AVRTargetCodeGenInfo(Types));
9877 
9878   case llvm::Triple::aarch64:
9879   case llvm::Triple::aarch64_32:
9880   case llvm::Triple::aarch64_be: {
9881     AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS;
9882     if (getTarget().getABI() == "darwinpcs")
9883       Kind = AArch64ABIInfo::DarwinPCS;
9884     else if (Triple.isOSWindows())
9885       return SetCGInfo(
9886           new WindowsAArch64TargetCodeGenInfo(Types, AArch64ABIInfo::Win64));
9887 
9888     return SetCGInfo(new AArch64TargetCodeGenInfo(Types, Kind));
9889   }
9890 
9891   case llvm::Triple::wasm32:
9892   case llvm::Triple::wasm64:
9893     return SetCGInfo(new WebAssemblyTargetCodeGenInfo(Types));
9894 
9895   case llvm::Triple::arm:
9896   case llvm::Triple::armeb:
9897   case llvm::Triple::thumb:
9898   case llvm::Triple::thumbeb: {
9899     if (Triple.getOS() == llvm::Triple::Win32) {
9900       return SetCGInfo(
9901           new WindowsARMTargetCodeGenInfo(Types, ARMABIInfo::AAPCS_VFP));
9902     }
9903 
9904     ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
9905     StringRef ABIStr = getTarget().getABI();
9906     if (ABIStr == "apcs-gnu")
9907       Kind = ARMABIInfo::APCS;
9908     else if (ABIStr == "aapcs16")
9909       Kind = ARMABIInfo::AAPCS16_VFP;
9910     else if (CodeGenOpts.FloatABI == "hard" ||
9911              (CodeGenOpts.FloatABI != "soft" &&
9912               (Triple.getEnvironment() == llvm::Triple::GNUEABIHF ||
9913                Triple.getEnvironment() == llvm::Triple::MuslEABIHF ||
9914                Triple.getEnvironment() == llvm::Triple::EABIHF)))
9915       Kind = ARMABIInfo::AAPCS_VFP;
9916 
9917     return SetCGInfo(new ARMTargetCodeGenInfo(Types, Kind));
9918   }
9919 
9920   case llvm::Triple::ppc: {
9921     bool IsSoftFloat =
9922         CodeGenOpts.FloatABI == "soft" || getTarget().hasFeature("spe");
9923     bool RetSmallStructInRegABI =
9924         PPC32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
9925     return SetCGInfo(
9926         new PPC32TargetCodeGenInfo(Types, IsSoftFloat, RetSmallStructInRegABI));
9927   }
9928   case llvm::Triple::ppc64:
9929     if (Triple.isOSBinFormatELF()) {
9930       PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1;
9931       if (getTarget().getABI() == "elfv2")
9932         Kind = PPC64_SVR4_ABIInfo::ELFv2;
9933       bool HasQPX = getTarget().getABI() == "elfv1-qpx";
9934       bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
9935 
9936       return SetCGInfo(new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX,
9937                                                         IsSoftFloat));
9938     } else
9939       return SetCGInfo(new PPC64TargetCodeGenInfo(Types));
9940   case llvm::Triple::ppc64le: {
9941     assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
9942     PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2;
9943     if (getTarget().getABI() == "elfv1" || getTarget().getABI() == "elfv1-qpx")
9944       Kind = PPC64_SVR4_ABIInfo::ELFv1;
9945     bool HasQPX = getTarget().getABI() == "elfv1-qpx";
9946     bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
9947 
9948     return SetCGInfo(new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX,
9949                                                       IsSoftFloat));
9950   }
9951 
9952   case llvm::Triple::nvptx:
9953   case llvm::Triple::nvptx64:
9954     return SetCGInfo(new NVPTXTargetCodeGenInfo(Types));
9955 
9956   case llvm::Triple::msp430:
9957     return SetCGInfo(new MSP430TargetCodeGenInfo(Types));
9958 
9959   case llvm::Triple::riscv32:
9960   case llvm::Triple::riscv64: {
9961     StringRef ABIStr = getTarget().getABI();
9962     unsigned XLen = getTarget().getPointerWidth(0);
9963     unsigned ABIFLen = 0;
9964     if (ABIStr.endswith("f"))
9965       ABIFLen = 32;
9966     else if (ABIStr.endswith("d"))
9967       ABIFLen = 64;
9968     return SetCGInfo(new RISCVTargetCodeGenInfo(Types, XLen, ABIFLen));
9969   }
9970 
9971   case llvm::Triple::systemz: {
9972     bool HasVector = getTarget().getABI() == "vector";
9973     return SetCGInfo(new SystemZTargetCodeGenInfo(Types, HasVector));
9974   }
9975 
9976   case llvm::Triple::tce:
9977   case llvm::Triple::tcele:
9978     return SetCGInfo(new TCETargetCodeGenInfo(Types));
9979 
9980   case llvm::Triple::x86: {
9981     bool IsDarwinVectorABI = Triple.isOSDarwin();
9982     bool RetSmallStructInRegABI =
9983         X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
9984     bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
9985 
9986     if (Triple.getOS() == llvm::Triple::Win32) {
9987       return SetCGInfo(new WinX86_32TargetCodeGenInfo(
9988           Types, IsDarwinVectorABI, RetSmallStructInRegABI,
9989           IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters));
9990     } else {
9991       return SetCGInfo(new X86_32TargetCodeGenInfo(
9992           Types, IsDarwinVectorABI, RetSmallStructInRegABI,
9993           IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters,
9994           CodeGenOpts.FloatABI == "soft"));
9995     }
9996   }
9997 
9998   case llvm::Triple::x86_64: {
9999     StringRef ABI = getTarget().getABI();
10000     X86AVXABILevel AVXLevel =
10001         (ABI == "avx512"
10002              ? X86AVXABILevel::AVX512
10003              : ABI == "avx" ? X86AVXABILevel::AVX : X86AVXABILevel::None);
10004 
10005     switch (Triple.getOS()) {
10006     case llvm::Triple::Win32:
10007       return SetCGInfo(new WinX86_64TargetCodeGenInfo(Types, AVXLevel));
10008     default:
10009       return SetCGInfo(new X86_64TargetCodeGenInfo(Types, AVXLevel));
10010     }
10011   }
10012   case llvm::Triple::hexagon:
10013     return SetCGInfo(new HexagonTargetCodeGenInfo(Types));
10014   case llvm::Triple::lanai:
10015     return SetCGInfo(new LanaiTargetCodeGenInfo(Types));
10016   case llvm::Triple::r600:
10017     return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
10018   case llvm::Triple::amdgcn:
10019     return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
10020   case llvm::Triple::sparc:
10021     return SetCGInfo(new SparcV8TargetCodeGenInfo(Types));
10022   case llvm::Triple::sparcv9:
10023     return SetCGInfo(new SparcV9TargetCodeGenInfo(Types));
10024   case llvm::Triple::xcore:
10025     return SetCGInfo(new XCoreTargetCodeGenInfo(Types));
10026   case llvm::Triple::arc:
10027     return SetCGInfo(new ARCTargetCodeGenInfo(Types));
10028   case llvm::Triple::spir:
10029   case llvm::Triple::spir64:
10030     return SetCGInfo(new SPIRTargetCodeGenInfo(Types));
10031   }
10032 }
10033 
10034 /// Create an OpenCL kernel for an enqueued block.
10035 ///
10036 /// The kernel has the same function type as the block invoke function. Its
10037 /// name is the name of the block invoke function postfixed with "_kernel".
10038 /// It simply calls the block invoke function then returns.
10039 llvm::Function *
10040 TargetCodeGenInfo::createEnqueuedBlockKernel(CodeGenFunction &CGF,
10041                                              llvm::Function *Invoke,
10042                                              llvm::Value *BlockLiteral) const {
10043   auto *InvokeFT = Invoke->getFunctionType();
10044   llvm::SmallVector<llvm::Type *, 2> ArgTys;
10045   for (auto &P : InvokeFT->params())
10046     ArgTys.push_back(P);
10047   auto &C = CGF.getLLVMContext();
10048   std::string Name = Invoke->getName().str() + "_kernel";
10049   auto *FT = llvm::FunctionType::get(llvm::Type::getVoidTy(C), ArgTys, false);
10050   auto *F = llvm::Function::Create(FT, llvm::GlobalValue::InternalLinkage, Name,
10051                                    &CGF.CGM.getModule());
10052   auto IP = CGF.Builder.saveIP();
10053   auto *BB = llvm::BasicBlock::Create(C, "entry", F);
10054   auto &Builder = CGF.Builder;
10055   Builder.SetInsertPoint(BB);
10056   llvm::SmallVector<llvm::Value *, 2> Args;
10057   for (auto &A : F->args())
10058     Args.push_back(&A);
10059   Builder.CreateCall(Invoke, Args);
10060   Builder.CreateRetVoid();
10061   Builder.restoreIP(IP);
10062   return F;
10063 }
10064 
10065 /// Create an OpenCL kernel for an enqueued block.
10066 ///
10067 /// The type of the first argument (the block literal) is the struct type
10068 /// of the block literal instead of a pointer type. The first argument
10069 /// (block literal) is passed directly by value to the kernel. The kernel
10070 /// allocates the same type of struct on stack and stores the block literal
10071 /// to it and passes its pointer to the block invoke function. The kernel
10072 /// has "enqueued-block" function attribute and kernel argument metadata.
10073 llvm::Function *AMDGPUTargetCodeGenInfo::createEnqueuedBlockKernel(
10074     CodeGenFunction &CGF, llvm::Function *Invoke,
10075     llvm::Value *BlockLiteral) const {
10076   auto &Builder = CGF.Builder;
10077   auto &C = CGF.getLLVMContext();
10078 
10079   auto *BlockTy = BlockLiteral->getType()->getPointerElementType();
10080   auto *InvokeFT = Invoke->getFunctionType();
10081   llvm::SmallVector<llvm::Type *, 2> ArgTys;
10082   llvm::SmallVector<llvm::Metadata *, 8> AddressQuals;
10083   llvm::SmallVector<llvm::Metadata *, 8> AccessQuals;
10084   llvm::SmallVector<llvm::Metadata *, 8> ArgTypeNames;
10085   llvm::SmallVector<llvm::Metadata *, 8> ArgBaseTypeNames;
10086   llvm::SmallVector<llvm::Metadata *, 8> ArgTypeQuals;
10087   llvm::SmallVector<llvm::Metadata *, 8> ArgNames;
10088 
10089   ArgTys.push_back(BlockTy);
10090   ArgTypeNames.push_back(llvm::MDString::get(C, "__block_literal"));
10091   AddressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(0)));
10092   ArgBaseTypeNames.push_back(llvm::MDString::get(C, "__block_literal"));
10093   ArgTypeQuals.push_back(llvm::MDString::get(C, ""));
10094   AccessQuals.push_back(llvm::MDString::get(C, "none"));
10095   ArgNames.push_back(llvm::MDString::get(C, "block_literal"));
10096   for (unsigned I = 1, E = InvokeFT->getNumParams(); I < E; ++I) {
10097     ArgTys.push_back(InvokeFT->getParamType(I));
10098     ArgTypeNames.push_back(llvm::MDString::get(C, "void*"));
10099     AddressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(3)));
10100     AccessQuals.push_back(llvm::MDString::get(C, "none"));
10101     ArgBaseTypeNames.push_back(llvm::MDString::get(C, "void*"));
10102     ArgTypeQuals.push_back(llvm::MDString::get(C, ""));
10103     ArgNames.push_back(
10104         llvm::MDString::get(C, (Twine("local_arg") + Twine(I)).str()));
10105   }
10106   std::string Name = Invoke->getName().str() + "_kernel";
10107   auto *FT = llvm::FunctionType::get(llvm::Type::getVoidTy(C), ArgTys, false);
10108   auto *F = llvm::Function::Create(FT, llvm::GlobalValue::InternalLinkage, Name,
10109                                    &CGF.CGM.getModule());
10110   F->addFnAttr("enqueued-block");
10111   auto IP = CGF.Builder.saveIP();
10112   auto *BB = llvm::BasicBlock::Create(C, "entry", F);
10113   Builder.SetInsertPoint(BB);
10114   unsigned BlockAlign = CGF.CGM.getDataLayout().getPrefTypeAlignment(BlockTy);
10115   auto *BlockPtr = Builder.CreateAlloca(BlockTy, nullptr);
10116   BlockPtr->setAlignment(llvm::MaybeAlign(BlockAlign));
10117   Builder.CreateAlignedStore(F->arg_begin(), BlockPtr, BlockAlign);
10118   auto *Cast = Builder.CreatePointerCast(BlockPtr, InvokeFT->getParamType(0));
10119   llvm::SmallVector<llvm::Value *, 2> Args;
10120   Args.push_back(Cast);
10121   for (auto I = F->arg_begin() + 1, E = F->arg_end(); I != E; ++I)
10122     Args.push_back(I);
10123   Builder.CreateCall(Invoke, Args);
10124   Builder.CreateRetVoid();
10125   Builder.restoreIP(IP);
10126 
10127   F->setMetadata("kernel_arg_addr_space", llvm::MDNode::get(C, AddressQuals));
10128   F->setMetadata("kernel_arg_access_qual", llvm::MDNode::get(C, AccessQuals));
10129   F->setMetadata("kernel_arg_type", llvm::MDNode::get(C, ArgTypeNames));
10130   F->setMetadata("kernel_arg_base_type",
10131                  llvm::MDNode::get(C, ArgBaseTypeNames));
10132   F->setMetadata("kernel_arg_type_qual", llvm::MDNode::get(C, ArgTypeQuals));
10133   if (CGF.CGM.getCodeGenOpts().EmitOpenCLArgMetadata)
10134     F->setMetadata("kernel_arg_name", llvm::MDNode::get(C, ArgNames));
10135 
10136   return F;
10137 }
10138