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