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