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