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