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