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