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