]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/CodeGen/TargetInfo.cpp
Merge ^/head r318658 through r318963.
[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
4826 class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
4827 public:
4828   AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind)
4829       : TargetCodeGenInfo(new AArch64ABIInfo(CGT, Kind)) {}
4830
4831   StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
4832     return "mov\tfp, fp\t\t# marker for objc_retainAutoreleaseReturnValue";
4833   }
4834
4835   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4836     return 31;
4837   }
4838
4839   bool doesReturnSlotInterfereWithArgs() const override { return false; }
4840 };
4841 }
4842
4843 ABIArgInfo AArch64ABIInfo::classifyArgumentType(QualType Ty) const {
4844   Ty = useFirstFieldIfTransparentUnion(Ty);
4845
4846   // Handle illegal vector types here.
4847   if (isIllegalVectorType(Ty)) {
4848     uint64_t Size = getContext().getTypeSize(Ty);
4849     // Android promotes <2 x i8> to i16, not i32
4850     if (isAndroid() && (Size <= 16)) {
4851       llvm::Type *ResType = llvm::Type::getInt16Ty(getVMContext());
4852       return ABIArgInfo::getDirect(ResType);
4853     }
4854     if (Size <= 32) {
4855       llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext());
4856       return ABIArgInfo::getDirect(ResType);
4857     }
4858     if (Size == 64) {
4859       llvm::Type *ResType =
4860           llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2);
4861       return ABIArgInfo::getDirect(ResType);
4862     }
4863     if (Size == 128) {
4864       llvm::Type *ResType =
4865           llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4);
4866       return ABIArgInfo::getDirect(ResType);
4867     }
4868     return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
4869   }
4870
4871   if (!isAggregateTypeForABI(Ty)) {
4872     // Treat an enum type as its underlying type.
4873     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4874       Ty = EnumTy->getDecl()->getIntegerType();
4875
4876     return (Ty->isPromotableIntegerType() && isDarwinPCS()
4877                 ? ABIArgInfo::getExtend()
4878                 : ABIArgInfo::getDirect());
4879   }
4880
4881   // Structures with either a non-trivial destructor or a non-trivial
4882   // copy constructor are always indirect.
4883   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
4884     return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA ==
4885                                      CGCXXABI::RAA_DirectInMemory);
4886   }
4887
4888   // Empty records are always ignored on Darwin, but actually passed in C++ mode
4889   // elsewhere for GNU compatibility.
4890   uint64_t Size = getContext().getTypeSize(Ty);
4891   bool IsEmpty = isEmptyRecord(getContext(), Ty, true);
4892   if (IsEmpty || Size == 0) {
4893     if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS())
4894       return ABIArgInfo::getIgnore();
4895
4896     // GNU C mode. The only argument that gets ignored is an empty one with size
4897     // 0.
4898     if (IsEmpty && Size == 0)
4899       return ABIArgInfo::getIgnore();
4900     return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
4901   }
4902
4903   // Homogeneous Floating-point Aggregates (HFAs) need to be expanded.
4904   const Type *Base = nullptr;
4905   uint64_t Members = 0;
4906   if (isHomogeneousAggregate(Ty, Base, Members)) {
4907     return ABIArgInfo::getDirect(
4908         llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members));
4909   }
4910
4911   // Aggregates <= 16 bytes are passed directly in registers or on the stack.
4912   if (Size <= 128) {
4913     // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
4914     // same size and alignment.
4915     if (getTarget().isRenderScriptTarget()) {
4916       return coerceToIntArray(Ty, getContext(), getVMContext());
4917     }
4918     unsigned Alignment = getContext().getTypeAlign(Ty);
4919     Size = llvm::alignTo(Size, 64); // round up to multiple of 8 bytes
4920
4921     // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
4922     // For aggregates with 16-byte alignment, we use i128.
4923     if (Alignment < 128 && Size == 128) {
4924       llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
4925       return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
4926     }
4927     return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
4928   }
4929
4930   return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
4931 }
4932
4933 ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy) const {
4934   if (RetTy->isVoidType())
4935     return ABIArgInfo::getIgnore();
4936
4937   // Large vector types should be returned via memory.
4938   if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
4939     return getNaturalAlignIndirect(RetTy);
4940
4941   if (!isAggregateTypeForABI(RetTy)) {
4942     // Treat an enum type as its underlying type.
4943     if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
4944       RetTy = EnumTy->getDecl()->getIntegerType();
4945
4946     return (RetTy->isPromotableIntegerType() && isDarwinPCS()
4947                 ? ABIArgInfo::getExtend()
4948                 : ABIArgInfo::getDirect());
4949   }
4950
4951   uint64_t Size = getContext().getTypeSize(RetTy);
4952   if (isEmptyRecord(getContext(), RetTy, true) || Size == 0)
4953     return ABIArgInfo::getIgnore();
4954
4955   const Type *Base = nullptr;
4956   uint64_t Members = 0;
4957   if (isHomogeneousAggregate(RetTy, Base, Members))
4958     // Homogeneous Floating-point Aggregates (HFAs) are returned directly.
4959     return ABIArgInfo::getDirect();
4960
4961   // Aggregates <= 16 bytes are returned directly in registers or on the stack.
4962   if (Size <= 128) {
4963     // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
4964     // same size and alignment.
4965     if (getTarget().isRenderScriptTarget()) {
4966       return coerceToIntArray(RetTy, getContext(), getVMContext());
4967     }
4968     unsigned Alignment = getContext().getTypeAlign(RetTy);
4969     Size = llvm::alignTo(Size, 64); // round up to multiple of 8 bytes
4970
4971     // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
4972     // For aggregates with 16-byte alignment, we use i128.
4973     if (Alignment < 128 && Size == 128) {
4974       llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
4975       return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
4976     }
4977     return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
4978   }
4979
4980   return getNaturalAlignIndirect(RetTy);
4981 }
4982
4983 /// isIllegalVectorType - check whether the vector type is legal for AArch64.
4984 bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const {
4985   if (const VectorType *VT = Ty->getAs<VectorType>()) {
4986     // Check whether VT is legal.
4987     unsigned NumElements = VT->getNumElements();
4988     uint64_t Size = getContext().getTypeSize(VT);
4989     // NumElements should be power of 2.
4990     if (!llvm::isPowerOf2_32(NumElements))
4991       return true;
4992     return Size != 64 && (Size != 128 || NumElements == 1);
4993   }
4994   return false;
4995 }
4996
4997 bool AArch64ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
4998   // Homogeneous aggregates for AAPCS64 must have base types of a floating
4999   // point type or a short-vector type. This is the same as the 32-bit ABI,
5000   // but with the difference that any floating-point type is allowed,
5001   // including __fp16.
5002   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
5003     if (BT->isFloatingPoint())
5004       return true;
5005   } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
5006     unsigned VecSize = getContext().getTypeSize(VT);
5007     if (VecSize == 64 || VecSize == 128)
5008       return true;
5009   }
5010   return false;
5011 }
5012
5013 bool AArch64ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
5014                                                        uint64_t Members) const {
5015   return Members <= 4;
5016 }
5017
5018 Address AArch64ABIInfo::EmitAAPCSVAArg(Address VAListAddr,
5019                                             QualType Ty,
5020                                             CodeGenFunction &CGF) const {
5021   ABIArgInfo AI = classifyArgumentType(Ty);
5022   bool IsIndirect = AI.isIndirect();
5023
5024   llvm::Type *BaseTy = CGF.ConvertType(Ty);
5025   if (IsIndirect)
5026     BaseTy = llvm::PointerType::getUnqual(BaseTy);
5027   else if (AI.getCoerceToType())
5028     BaseTy = AI.getCoerceToType();
5029
5030   unsigned NumRegs = 1;
5031   if (llvm::ArrayType *ArrTy = dyn_cast<llvm::ArrayType>(BaseTy)) {
5032     BaseTy = ArrTy->getElementType();
5033     NumRegs = ArrTy->getNumElements();
5034   }
5035   bool IsFPR = BaseTy->isFloatingPointTy() || BaseTy->isVectorTy();
5036
5037   // The AArch64 va_list type and handling is specified in the Procedure Call
5038   // Standard, section B.4:
5039   //
5040   // struct {
5041   //   void *__stack;
5042   //   void *__gr_top;
5043   //   void *__vr_top;
5044   //   int __gr_offs;
5045   //   int __vr_offs;
5046   // };
5047
5048   llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
5049   llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
5050   llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
5051   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
5052
5053   auto TyInfo = getContext().getTypeInfoInChars(Ty);
5054   CharUnits TyAlign = TyInfo.second;
5055
5056   Address reg_offs_p = Address::invalid();
5057   llvm::Value *reg_offs = nullptr;
5058   int reg_top_index;
5059   CharUnits reg_top_offset;
5060   int RegSize = IsIndirect ? 8 : TyInfo.first.getQuantity();
5061   if (!IsFPR) {
5062     // 3 is the field number of __gr_offs
5063     reg_offs_p =
5064         CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(24),
5065                                     "gr_offs_p");
5066     reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
5067     reg_top_index = 1; // field number for __gr_top
5068     reg_top_offset = CharUnits::fromQuantity(8);
5069     RegSize = llvm::alignTo(RegSize, 8);
5070   } else {
5071     // 4 is the field number of __vr_offs.
5072     reg_offs_p =
5073         CGF.Builder.CreateStructGEP(VAListAddr, 4, CharUnits::fromQuantity(28),
5074                                     "vr_offs_p");
5075     reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
5076     reg_top_index = 2; // field number for __vr_top
5077     reg_top_offset = CharUnits::fromQuantity(16);
5078     RegSize = 16 * NumRegs;
5079   }
5080
5081   //=======================================
5082   // Find out where argument was passed
5083   //=======================================
5084
5085   // If reg_offs >= 0 we're already using the stack for this type of
5086   // argument. We don't want to keep updating reg_offs (in case it overflows,
5087   // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
5088   // whatever they get).
5089   llvm::Value *UsingStack = nullptr;
5090   UsingStack = CGF.Builder.CreateICmpSGE(
5091       reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0));
5092
5093   CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
5094
5095   // Otherwise, at least some kind of argument could go in these registers, the
5096   // question is whether this particular type is too big.
5097   CGF.EmitBlock(MaybeRegBlock);
5098
5099   // Integer arguments may need to correct register alignment (for example a
5100   // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
5101   // align __gr_offs to calculate the potential address.
5102   if (!IsFPR && !IsIndirect && TyAlign.getQuantity() > 8) {
5103     int Align = TyAlign.getQuantity();
5104
5105     reg_offs = CGF.Builder.CreateAdd(
5106         reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
5107         "align_regoffs");
5108     reg_offs = CGF.Builder.CreateAnd(
5109         reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align),
5110         "aligned_regoffs");
5111   }
5112
5113   // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
5114   // The fact that this is done unconditionally reflects the fact that
5115   // allocating an argument to the stack also uses up all the remaining
5116   // registers of the appropriate kind.
5117   llvm::Value *NewOffset = nullptr;
5118   NewOffset = CGF.Builder.CreateAdd(
5119       reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs");
5120   CGF.Builder.CreateStore(NewOffset, reg_offs_p);
5121
5122   // Now we're in a position to decide whether this argument really was in
5123   // registers or not.
5124   llvm::Value *InRegs = nullptr;
5125   InRegs = CGF.Builder.CreateICmpSLE(
5126       NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg");
5127
5128   CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
5129
5130   //=======================================
5131   // Argument was in registers
5132   //=======================================
5133
5134   // Now we emit the code for if the argument was originally passed in
5135   // registers. First start the appropriate block:
5136   CGF.EmitBlock(InRegBlock);
5137
5138   llvm::Value *reg_top = nullptr;
5139   Address reg_top_p = CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index,
5140                                                   reg_top_offset, "reg_top_p");
5141   reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
5142   Address BaseAddr(CGF.Builder.CreateInBoundsGEP(reg_top, reg_offs),
5143                    CharUnits::fromQuantity(IsFPR ? 16 : 8));
5144   Address RegAddr = Address::invalid();
5145   llvm::Type *MemTy = CGF.ConvertTypeForMem(Ty);
5146
5147   if (IsIndirect) {
5148     // If it's been passed indirectly (actually a struct), whatever we find from
5149     // stored registers or on the stack will actually be a struct **.
5150     MemTy = llvm::PointerType::getUnqual(MemTy);
5151   }
5152
5153   const Type *Base = nullptr;
5154   uint64_t NumMembers = 0;
5155   bool IsHFA = isHomogeneousAggregate(Ty, Base, NumMembers);
5156   if (IsHFA && NumMembers > 1) {
5157     // Homogeneous aggregates passed in registers will have their elements split
5158     // and stored 16-bytes apart regardless of size (they're notionally in qN,
5159     // qN+1, ...). We reload and store into a temporary local variable
5160     // contiguously.
5161     assert(!IsIndirect && "Homogeneous aggregates should be passed directly");
5162     auto BaseTyInfo = getContext().getTypeInfoInChars(QualType(Base, 0));
5163     llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
5164     llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
5165     Address Tmp = CGF.CreateTempAlloca(HFATy,
5166                                        std::max(TyAlign, BaseTyInfo.second));
5167
5168     // On big-endian platforms, the value will be right-aligned in its slot.
5169     int Offset = 0;
5170     if (CGF.CGM.getDataLayout().isBigEndian() &&
5171         BaseTyInfo.first.getQuantity() < 16)
5172       Offset = 16 - BaseTyInfo.first.getQuantity();
5173
5174     for (unsigned i = 0; i < NumMembers; ++i) {
5175       CharUnits BaseOffset = CharUnits::fromQuantity(16 * i + Offset);
5176       Address LoadAddr =
5177         CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, BaseOffset);
5178       LoadAddr = CGF.Builder.CreateElementBitCast(LoadAddr, BaseTy);
5179
5180       Address StoreAddr =
5181         CGF.Builder.CreateConstArrayGEP(Tmp, i, BaseTyInfo.first);
5182
5183       llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
5184       CGF.Builder.CreateStore(Elem, StoreAddr);
5185     }
5186
5187     RegAddr = CGF.Builder.CreateElementBitCast(Tmp, MemTy);
5188   } else {
5189     // Otherwise the object is contiguous in memory.
5190
5191     // It might be right-aligned in its slot.
5192     CharUnits SlotSize = BaseAddr.getAlignment();
5193     if (CGF.CGM.getDataLayout().isBigEndian() && !IsIndirect &&
5194         (IsHFA || !isAggregateTypeForABI(Ty)) &&
5195         TyInfo.first < SlotSize) {
5196       CharUnits Offset = SlotSize - TyInfo.first;
5197       BaseAddr = CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, Offset);
5198     }
5199
5200     RegAddr = CGF.Builder.CreateElementBitCast(BaseAddr, MemTy);
5201   }
5202
5203   CGF.EmitBranch(ContBlock);
5204
5205   //=======================================
5206   // Argument was on the stack
5207   //=======================================
5208   CGF.EmitBlock(OnStackBlock);
5209
5210   Address stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0,
5211                                                 CharUnits::Zero(), "stack_p");
5212   llvm::Value *OnStackPtr = CGF.Builder.CreateLoad(stack_p, "stack");
5213
5214   // Again, stack arguments may need realignment. In this case both integer and
5215   // floating-point ones might be affected.
5216   if (!IsIndirect && TyAlign.getQuantity() > 8) {
5217     int Align = TyAlign.getQuantity();
5218
5219     OnStackPtr = CGF.Builder.CreatePtrToInt(OnStackPtr, CGF.Int64Ty);
5220
5221     OnStackPtr = CGF.Builder.CreateAdd(
5222         OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
5223         "align_stack");
5224     OnStackPtr = CGF.Builder.CreateAnd(
5225         OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, -Align),
5226         "align_stack");
5227
5228     OnStackPtr = CGF.Builder.CreateIntToPtr(OnStackPtr, CGF.Int8PtrTy);
5229   }
5230   Address OnStackAddr(OnStackPtr,
5231                       std::max(CharUnits::fromQuantity(8), TyAlign));
5232
5233   // All stack slots are multiples of 8 bytes.
5234   CharUnits StackSlotSize = CharUnits::fromQuantity(8);
5235   CharUnits StackSize;
5236   if (IsIndirect)
5237     StackSize = StackSlotSize;
5238   else
5239     StackSize = TyInfo.first.alignTo(StackSlotSize);
5240
5241   llvm::Value *StackSizeC = CGF.Builder.getSize(StackSize);
5242   llvm::Value *NewStack =
5243       CGF.Builder.CreateInBoundsGEP(OnStackPtr, StackSizeC, "new_stack");
5244
5245   // Write the new value of __stack for the next call to va_arg
5246   CGF.Builder.CreateStore(NewStack, stack_p);
5247
5248   if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) &&
5249       TyInfo.first < StackSlotSize) {
5250     CharUnits Offset = StackSlotSize - TyInfo.first;
5251     OnStackAddr = CGF.Builder.CreateConstInBoundsByteGEP(OnStackAddr, Offset);
5252   }
5253
5254   OnStackAddr = CGF.Builder.CreateElementBitCast(OnStackAddr, MemTy);
5255
5256   CGF.EmitBranch(ContBlock);
5257
5258   //=======================================
5259   // Tidy up
5260   //=======================================
5261   CGF.EmitBlock(ContBlock);
5262
5263   Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
5264                                  OnStackAddr, OnStackBlock, "vaargs.addr");
5265
5266   if (IsIndirect)
5267     return Address(CGF.Builder.CreateLoad(ResAddr, "vaarg.addr"),
5268                    TyInfo.second);
5269
5270   return ResAddr;
5271 }
5272
5273 Address AArch64ABIInfo::EmitDarwinVAArg(Address VAListAddr, QualType Ty,
5274                                         CodeGenFunction &CGF) const {
5275   // The backend's lowering doesn't support va_arg for aggregates or
5276   // illegal vector types.  Lower VAArg here for these cases and use
5277   // the LLVM va_arg instruction for everything else.
5278   if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty))
5279     return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
5280
5281   CharUnits SlotSize = CharUnits::fromQuantity(8);
5282
5283   // Empty records are ignored for parameter passing purposes.
5284   if (isEmptyRecord(getContext(), Ty, true)) {
5285     Address Addr(CGF.Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
5286     Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
5287     return Addr;
5288   }
5289
5290   // The size of the actual thing passed, which might end up just
5291   // being a pointer for indirect types.
5292   auto TyInfo = getContext().getTypeInfoInChars(Ty);
5293
5294   // Arguments bigger than 16 bytes which aren't homogeneous
5295   // aggregates should be passed indirectly.
5296   bool IsIndirect = false;
5297   if (TyInfo.first.getQuantity() > 16) {
5298     const Type *Base = nullptr;
5299     uint64_t Members = 0;
5300     IsIndirect = !isHomogeneousAggregate(Ty, Base, Members);
5301   }
5302
5303   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
5304                           TyInfo, SlotSize, /*AllowHigherAlign*/ true);
5305 }
5306
5307 //===----------------------------------------------------------------------===//
5308 // ARM ABI Implementation
5309 //===----------------------------------------------------------------------===//
5310
5311 namespace {
5312
5313 class ARMABIInfo : public SwiftABIInfo {
5314 public:
5315   enum ABIKind {
5316     APCS = 0,
5317     AAPCS = 1,
5318     AAPCS_VFP = 2,
5319     AAPCS16_VFP = 3,
5320   };
5321
5322 private:
5323   ABIKind Kind;
5324
5325 public:
5326   ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind)
5327       : SwiftABIInfo(CGT), Kind(_Kind) {
5328     setCCs();
5329   }
5330
5331   bool isEABI() const {
5332     switch (getTarget().getTriple().getEnvironment()) {
5333     case llvm::Triple::Android:
5334     case llvm::Triple::EABI:
5335     case llvm::Triple::EABIHF:
5336     case llvm::Triple::GNUEABI:
5337     case llvm::Triple::GNUEABIHF:
5338     case llvm::Triple::MuslEABI:
5339     case llvm::Triple::MuslEABIHF:
5340       return true;
5341     default:
5342       return false;
5343     }
5344   }
5345
5346   bool isEABIHF() const {
5347     switch (getTarget().getTriple().getEnvironment()) {
5348     case llvm::Triple::EABIHF:
5349     case llvm::Triple::GNUEABIHF:
5350     case llvm::Triple::MuslEABIHF:
5351       return true;
5352     default:
5353       return false;
5354     }
5355   }
5356
5357   ABIKind getABIKind() const { return Kind; }
5358
5359 private:
5360   ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic) const;
5361   ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic) const;
5362   bool isIllegalVectorType(QualType Ty) const;
5363
5364   bool isHomogeneousAggregateBaseType(QualType Ty) const override;
5365   bool isHomogeneousAggregateSmallEnough(const Type *Ty,
5366                                          uint64_t Members) const override;
5367
5368   void computeInfo(CGFunctionInfo &FI) const override;
5369
5370   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5371                     QualType Ty) const override;
5372
5373   llvm::CallingConv::ID getLLVMDefaultCC() const;
5374   llvm::CallingConv::ID getABIDefaultCC() const;
5375   void setCCs();
5376
5377   bool shouldPassIndirectlyForSwift(CharUnits totalSize,
5378                                     ArrayRef<llvm::Type*> scalars,
5379                                     bool asReturnValue) const override {
5380     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
5381   }
5382   bool isSwiftErrorInRegister() const override {
5383     return true;
5384   }
5385 };
5386
5387 class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
5388 public:
5389   ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
5390     :TargetCodeGenInfo(new ARMABIInfo(CGT, K)) {}
5391
5392   const ARMABIInfo &getABIInfo() const {
5393     return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
5394   }
5395
5396   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
5397     return 13;
5398   }
5399
5400   StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
5401     return "mov\tr7, r7\t\t@ marker for objc_retainAutoreleaseReturnValue";
5402   }
5403
5404   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
5405                                llvm::Value *Address) const override {
5406     llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
5407
5408     // 0-15 are the 16 integer registers.
5409     AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
5410     return false;
5411   }
5412
5413   unsigned getSizeOfUnwindException() const override {
5414     if (getABIInfo().isEABI()) return 88;
5415     return TargetCodeGenInfo::getSizeOfUnwindException();
5416   }
5417
5418   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5419                            CodeGen::CodeGenModule &CGM) const override {
5420     const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
5421     if (!FD)
5422       return;
5423
5424     const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
5425     if (!Attr)
5426       return;
5427
5428     const char *Kind;
5429     switch (Attr->getInterrupt()) {
5430     case ARMInterruptAttr::Generic: Kind = ""; break;
5431     case ARMInterruptAttr::IRQ:     Kind = "IRQ"; break;
5432     case ARMInterruptAttr::FIQ:     Kind = "FIQ"; break;
5433     case ARMInterruptAttr::SWI:     Kind = "SWI"; break;
5434     case ARMInterruptAttr::ABORT:   Kind = "ABORT"; break;
5435     case ARMInterruptAttr::UNDEF:   Kind = "UNDEF"; break;
5436     }
5437
5438     llvm::Function *Fn = cast<llvm::Function>(GV);
5439
5440     Fn->addFnAttr("interrupt", Kind);
5441
5442     ARMABIInfo::ABIKind ABI = cast<ARMABIInfo>(getABIInfo()).getABIKind();
5443     if (ABI == ARMABIInfo::APCS)
5444       return;
5445
5446     // AAPCS guarantees that sp will be 8-byte aligned on any public interface,
5447     // however this is not necessarily true on taking any interrupt. Instruct
5448     // the backend to perform a realignment as part of the function prologue.
5449     llvm::AttrBuilder B;
5450     B.addStackAlignmentAttr(8);
5451     Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
5452   }
5453 };
5454
5455 class WindowsARMTargetCodeGenInfo : public ARMTargetCodeGenInfo {
5456 public:
5457   WindowsARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
5458       : ARMTargetCodeGenInfo(CGT, K) {}
5459
5460   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5461                            CodeGen::CodeGenModule &CGM) const override;
5462
5463   void getDependentLibraryOption(llvm::StringRef Lib,
5464                                  llvm::SmallString<24> &Opt) const override {
5465     Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib);
5466   }
5467
5468   void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value,
5469                                llvm::SmallString<32> &Opt) const override {
5470     Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
5471   }
5472 };
5473
5474 void WindowsARMTargetCodeGenInfo::setTargetAttributes(
5475     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
5476   ARMTargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
5477   addStackProbeSizeTargetAttribute(D, GV, CGM);
5478 }
5479 }
5480
5481 void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
5482   if (!getCXXABI().classifyReturnType(FI))
5483     FI.getReturnInfo() =
5484         classifyReturnType(FI.getReturnType(), FI.isVariadic());
5485
5486   for (auto &I : FI.arguments())
5487     I.info = classifyArgumentType(I.type, FI.isVariadic());
5488
5489   // Always honor user-specified calling convention.
5490   if (FI.getCallingConvention() != llvm::CallingConv::C)
5491     return;
5492
5493   llvm::CallingConv::ID cc = getRuntimeCC();
5494   if (cc != llvm::CallingConv::C)
5495     FI.setEffectiveCallingConvention(cc);
5496 }
5497
5498 /// Return the default calling convention that LLVM will use.
5499 llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
5500   // The default calling convention that LLVM will infer.
5501   if (isEABIHF() || getTarget().getTriple().isWatchABI())
5502     return llvm::CallingConv::ARM_AAPCS_VFP;
5503   else if (isEABI())
5504     return llvm::CallingConv::ARM_AAPCS;
5505   else
5506     return llvm::CallingConv::ARM_APCS;
5507 }
5508
5509 /// Return the calling convention that our ABI would like us to use
5510 /// as the C calling convention.
5511 llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
5512   switch (getABIKind()) {
5513   case APCS: return llvm::CallingConv::ARM_APCS;
5514   case AAPCS: return llvm::CallingConv::ARM_AAPCS;
5515   case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
5516   case AAPCS16_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
5517   }
5518   llvm_unreachable("bad ABI kind");
5519 }
5520
5521 void ARMABIInfo::setCCs() {
5522   assert(getRuntimeCC() == llvm::CallingConv::C);
5523
5524   // Don't muddy up the IR with a ton of explicit annotations if
5525   // they'd just match what LLVM will infer from the triple.
5526   llvm::CallingConv::ID abiCC = getABIDefaultCC();
5527   if (abiCC != getLLVMDefaultCC())
5528     RuntimeCC = abiCC;
5529
5530   // AAPCS apparently requires runtime support functions to be soft-float, but
5531   // that's almost certainly for historic reasons (Thumb1 not supporting VFP
5532   // most likely). It's more convenient for AAPCS16_VFP to be hard-float.
5533   switch (getABIKind()) {
5534   case APCS:
5535   case AAPCS16_VFP:
5536     if (abiCC != getLLVMDefaultCC())
5537       BuiltinCC = abiCC;
5538     break;
5539   case AAPCS:
5540   case AAPCS_VFP:
5541     BuiltinCC = llvm::CallingConv::ARM_AAPCS;
5542     break;
5543   }
5544 }
5545
5546 ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty,
5547                                             bool isVariadic) const {
5548   // 6.1.2.1 The following argument types are VFP CPRCs:
5549   //   A single-precision floating-point type (including promoted
5550   //   half-precision types); A double-precision floating-point type;
5551   //   A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
5552   //   with a Base Type of a single- or double-precision floating-point type,
5553   //   64-bit containerized vectors or 128-bit containerized vectors with one
5554   //   to four Elements.
5555   bool IsEffectivelyAAPCS_VFP = getABIKind() == AAPCS_VFP && !isVariadic;
5556
5557   Ty = useFirstFieldIfTransparentUnion(Ty);
5558
5559   // Handle illegal vector types here.
5560   if (isIllegalVectorType(Ty)) {
5561     uint64_t Size = getContext().getTypeSize(Ty);
5562     if (Size <= 32) {
5563       llvm::Type *ResType =
5564           llvm::Type::getInt32Ty(getVMContext());
5565       return ABIArgInfo::getDirect(ResType);
5566     }
5567     if (Size == 64) {
5568       llvm::Type *ResType = llvm::VectorType::get(
5569           llvm::Type::getInt32Ty(getVMContext()), 2);
5570       return ABIArgInfo::getDirect(ResType);
5571     }
5572     if (Size == 128) {
5573       llvm::Type *ResType = llvm::VectorType::get(
5574           llvm::Type::getInt32Ty(getVMContext()), 4);
5575       return ABIArgInfo::getDirect(ResType);
5576     }
5577     return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
5578   }
5579
5580   // __fp16 gets passed as if it were an int or float, but with the top 16 bits
5581   // unspecified. This is not done for OpenCL as it handles the half type
5582   // natively, and does not need to interwork with AAPCS code.
5583   if (Ty->isHalfType() && !getContext().getLangOpts().NativeHalfArgsAndReturns) {
5584     llvm::Type *ResType = IsEffectivelyAAPCS_VFP ?
5585       llvm::Type::getFloatTy(getVMContext()) :
5586       llvm::Type::getInt32Ty(getVMContext());
5587     return ABIArgInfo::getDirect(ResType);
5588   }
5589
5590   if (!isAggregateTypeForABI(Ty)) {
5591     // Treat an enum type as its underlying type.
5592     if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
5593       Ty = EnumTy->getDecl()->getIntegerType();
5594     }
5595
5596     return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend()
5597                                           : ABIArgInfo::getDirect());
5598   }
5599
5600   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
5601     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
5602   }
5603
5604   // Ignore empty records.
5605   if (isEmptyRecord(getContext(), Ty, true))
5606     return ABIArgInfo::getIgnore();
5607
5608   if (IsEffectivelyAAPCS_VFP) {
5609     // Homogeneous Aggregates need to be expanded when we can fit the aggregate
5610     // into VFP registers.
5611     const Type *Base = nullptr;
5612     uint64_t Members = 0;
5613     if (isHomogeneousAggregate(Ty, Base, Members)) {
5614       assert(Base && "Base class should be set for homogeneous aggregate");
5615       // Base can be a floating-point or a vector.
5616       return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
5617     }
5618   } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
5619     // WatchOS does have homogeneous aggregates. Note that we intentionally use
5620     // this convention even for a variadic function: the backend will use GPRs
5621     // if needed.
5622     const Type *Base = nullptr;
5623     uint64_t Members = 0;
5624     if (isHomogeneousAggregate(Ty, Base, Members)) {
5625       assert(Base && Members <= 4 && "unexpected homogeneous aggregate");
5626       llvm::Type *Ty =
5627         llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members);
5628       return ABIArgInfo::getDirect(Ty, 0, nullptr, false);
5629     }
5630   }
5631
5632   if (getABIKind() == ARMABIInfo::AAPCS16_VFP &&
5633       getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(16)) {
5634     // WatchOS is adopting the 64-bit AAPCS rule on composite types: if they're
5635     // bigger than 128-bits, they get placed in space allocated by the caller,
5636     // and a pointer is passed.
5637     return ABIArgInfo::getIndirect(
5638         CharUnits::fromQuantity(getContext().getTypeAlign(Ty) / 8), false);
5639   }
5640
5641   // Support byval for ARM.
5642   // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
5643   // most 8-byte. We realign the indirect argument if type alignment is bigger
5644   // than ABI alignment.
5645   uint64_t ABIAlign = 4;
5646   uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8;
5647   if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
5648        getABIKind() == ARMABIInfo::AAPCS)
5649     ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
5650
5651   if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
5652     assert(getABIKind() != ARMABIInfo::AAPCS16_VFP && "unexpected byval");
5653     return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
5654                                    /*ByVal=*/true,
5655                                    /*Realign=*/TyAlign > ABIAlign);
5656   }
5657
5658   // On RenderScript, coerce Aggregates <= 64 bytes to an integer array of
5659   // same size and alignment.
5660   if (getTarget().isRenderScriptTarget()) {
5661     return coerceToIntArray(Ty, getContext(), getVMContext());
5662   }
5663
5664   // Otherwise, pass by coercing to a structure of the appropriate size.
5665   llvm::Type* ElemTy;
5666   unsigned SizeRegs;
5667   // FIXME: Try to match the types of the arguments more accurately where
5668   // we can.
5669   if (getContext().getTypeAlign(Ty) <= 32) {
5670     ElemTy = llvm::Type::getInt32Ty(getVMContext());
5671     SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
5672   } else {
5673     ElemTy = llvm::Type::getInt64Ty(getVMContext());
5674     SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
5675   }
5676
5677   return ABIArgInfo::getDirect(llvm::ArrayType::get(ElemTy, SizeRegs));
5678 }
5679
5680 static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
5681                               llvm::LLVMContext &VMContext) {
5682   // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
5683   // is called integer-like if its size is less than or equal to one word, and
5684   // the offset of each of its addressable sub-fields is zero.
5685
5686   uint64_t Size = Context.getTypeSize(Ty);
5687
5688   // Check that the type fits in a word.
5689   if (Size > 32)
5690     return false;
5691
5692   // FIXME: Handle vector types!
5693   if (Ty->isVectorType())
5694     return false;
5695
5696   // Float types are never treated as "integer like".
5697   if (Ty->isRealFloatingType())
5698     return false;
5699
5700   // If this is a builtin or pointer type then it is ok.
5701   if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
5702     return true;
5703
5704   // Small complex integer types are "integer like".
5705   if (const ComplexType *CT = Ty->getAs<ComplexType>())
5706     return isIntegerLikeType(CT->getElementType(), Context, VMContext);
5707
5708   // Single element and zero sized arrays should be allowed, by the definition
5709   // above, but they are not.
5710
5711   // Otherwise, it must be a record type.
5712   const RecordType *RT = Ty->getAs<RecordType>();
5713   if (!RT) return false;
5714
5715   // Ignore records with flexible arrays.
5716   const RecordDecl *RD = RT->getDecl();
5717   if (RD->hasFlexibleArrayMember())
5718     return false;
5719
5720   // Check that all sub-fields are at offset 0, and are themselves "integer
5721   // like".
5722   const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
5723
5724   bool HadField = false;
5725   unsigned idx = 0;
5726   for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
5727        i != e; ++i, ++idx) {
5728     const FieldDecl *FD = *i;
5729
5730     // Bit-fields are not addressable, we only need to verify they are "integer
5731     // like". We still have to disallow a subsequent non-bitfield, for example:
5732     //   struct { int : 0; int x }
5733     // is non-integer like according to gcc.
5734     if (FD->isBitField()) {
5735       if (!RD->isUnion())
5736         HadField = true;
5737
5738       if (!isIntegerLikeType(FD->getType(), Context, VMContext))
5739         return false;
5740
5741       continue;
5742     }
5743
5744     // Check if this field is at offset 0.
5745     if (Layout.getFieldOffset(idx) != 0)
5746       return false;
5747
5748     if (!isIntegerLikeType(FD->getType(), Context, VMContext))
5749       return false;
5750
5751     // Only allow at most one field in a structure. This doesn't match the
5752     // wording above, but follows gcc in situations with a field following an
5753     // empty structure.
5754     if (!RD->isUnion()) {
5755       if (HadField)
5756         return false;
5757
5758       HadField = true;
5759     }
5760   }
5761
5762   return true;
5763 }
5764
5765 ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy,
5766                                           bool isVariadic) const {
5767   bool IsEffectivelyAAPCS_VFP =
5768       (getABIKind() == AAPCS_VFP || getABIKind() == AAPCS16_VFP) && !isVariadic;
5769
5770   if (RetTy->isVoidType())
5771     return ABIArgInfo::getIgnore();
5772
5773   // Large vector types should be returned via memory.
5774   if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128) {
5775     return getNaturalAlignIndirect(RetTy);
5776   }
5777
5778   // __fp16 gets returned as if it were an int or float, but with the top 16
5779   // bits unspecified. This is not done for OpenCL as it handles the half type
5780   // natively, and does not need to interwork with AAPCS code.
5781   if (RetTy->isHalfType() && !getContext().getLangOpts().NativeHalfArgsAndReturns) {
5782     llvm::Type *ResType = IsEffectivelyAAPCS_VFP ?
5783       llvm::Type::getFloatTy(getVMContext()) :
5784       llvm::Type::getInt32Ty(getVMContext());
5785     return ABIArgInfo::getDirect(ResType);
5786   }
5787
5788   if (!isAggregateTypeForABI(RetTy)) {
5789     // Treat an enum type as its underlying type.
5790     if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5791       RetTy = EnumTy->getDecl()->getIntegerType();
5792
5793     return RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend()
5794                                             : ABIArgInfo::getDirect();
5795   }
5796
5797   // Are we following APCS?
5798   if (getABIKind() == APCS) {
5799     if (isEmptyRecord(getContext(), RetTy, false))
5800       return ABIArgInfo::getIgnore();
5801
5802     // Complex types are all returned as packed integers.
5803     //
5804     // FIXME: Consider using 2 x vector types if the back end handles them
5805     // correctly.
5806     if (RetTy->isAnyComplexType())
5807       return ABIArgInfo::getDirect(llvm::IntegerType::get(
5808           getVMContext(), getContext().getTypeSize(RetTy)));
5809
5810     // Integer like structures are returned in r0.
5811     if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
5812       // Return in the smallest viable integer type.
5813       uint64_t Size = getContext().getTypeSize(RetTy);
5814       if (Size <= 8)
5815         return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
5816       if (Size <= 16)
5817         return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5818       return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
5819     }
5820
5821     // Otherwise return in memory.
5822     return getNaturalAlignIndirect(RetTy);
5823   }
5824
5825   // Otherwise this is an AAPCS variant.
5826
5827   if (isEmptyRecord(getContext(), RetTy, true))
5828     return ABIArgInfo::getIgnore();
5829
5830   // Check for homogeneous aggregates with AAPCS-VFP.
5831   if (IsEffectivelyAAPCS_VFP) {
5832     const Type *Base = nullptr;
5833     uint64_t Members = 0;
5834     if (isHomogeneousAggregate(RetTy, Base, Members)) {
5835       assert(Base && "Base class should be set for homogeneous aggregate");
5836       // Homogeneous Aggregates are returned directly.
5837       return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
5838     }
5839   }
5840
5841   // Aggregates <= 4 bytes are returned in r0; other aggregates
5842   // are returned indirectly.
5843   uint64_t Size = getContext().getTypeSize(RetTy);
5844   if (Size <= 32) {
5845     // On RenderScript, coerce Aggregates <= 4 bytes to an integer array of
5846     // same size and alignment.
5847     if (getTarget().isRenderScriptTarget()) {
5848       return coerceToIntArray(RetTy, getContext(), getVMContext());
5849     }
5850     if (getDataLayout().isBigEndian())
5851       // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4)
5852       return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
5853
5854     // Return in the smallest viable integer type.
5855     if (Size <= 8)
5856       return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
5857     if (Size <= 16)
5858       return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5859     return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
5860   } else if (Size <= 128 && getABIKind() == AAPCS16_VFP) {
5861     llvm::Type *Int32Ty = llvm::Type::getInt32Ty(getVMContext());
5862     llvm::Type *CoerceTy =
5863         llvm::ArrayType::get(Int32Ty, llvm::alignTo(Size, 32) / 32);
5864     return ABIArgInfo::getDirect(CoerceTy);
5865   }
5866
5867   return getNaturalAlignIndirect(RetTy);
5868 }
5869
5870 /// isIllegalVector - check whether Ty is an illegal vector type.
5871 bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
5872   if (const VectorType *VT = Ty->getAs<VectorType> ()) {
5873     if (isAndroid()) {
5874       // Android shipped using Clang 3.1, which supported a slightly different
5875       // vector ABI. The primary differences were that 3-element vector types
5876       // were legal, and so were sub 32-bit vectors (i.e. <2 x i8>). This path
5877       // accepts that legacy behavior for Android only.
5878       // Check whether VT is legal.
5879       unsigned NumElements = VT->getNumElements();
5880       // NumElements should be power of 2 or equal to 3.
5881       if (!llvm::isPowerOf2_32(NumElements) && NumElements != 3)
5882         return true;
5883     } else {
5884       // Check whether VT is legal.
5885       unsigned NumElements = VT->getNumElements();
5886       uint64_t Size = getContext().getTypeSize(VT);
5887       // NumElements should be power of 2.
5888       if (!llvm::isPowerOf2_32(NumElements))
5889         return true;
5890       // Size should be greater than 32 bits.
5891       return Size <= 32;
5892     }
5893   }
5894   return false;
5895 }
5896
5897 bool ARMABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
5898   // Homogeneous aggregates for AAPCS-VFP must have base types of float,
5899   // double, or 64-bit or 128-bit vectors.
5900   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
5901     if (BT->getKind() == BuiltinType::Float ||
5902         BT->getKind() == BuiltinType::Double ||
5903         BT->getKind() == BuiltinType::LongDouble)
5904       return true;
5905   } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
5906     unsigned VecSize = getContext().getTypeSize(VT);
5907     if (VecSize == 64 || VecSize == 128)
5908       return true;
5909   }
5910   return false;
5911 }
5912
5913 bool ARMABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
5914                                                    uint64_t Members) const {
5915   return Members <= 4;
5916 }
5917
5918 Address ARMABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5919                               QualType Ty) const {
5920   CharUnits SlotSize = CharUnits::fromQuantity(4);
5921
5922   // Empty records are ignored for parameter passing purposes.
5923   if (isEmptyRecord(getContext(), Ty, true)) {
5924     Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize);
5925     Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
5926     return Addr;
5927   }
5928
5929   auto TyInfo = getContext().getTypeInfoInChars(Ty);
5930   CharUnits TyAlignForABI = TyInfo.second;
5931
5932   // Use indirect if size of the illegal vector is bigger than 16 bytes.
5933   bool IsIndirect = false;
5934   const Type *Base = nullptr;
5935   uint64_t Members = 0;
5936   if (TyInfo.first > CharUnits::fromQuantity(16) && isIllegalVectorType(Ty)) {
5937     IsIndirect = true;
5938
5939   // ARMv7k passes structs bigger than 16 bytes indirectly, in space
5940   // allocated by the caller.
5941   } else if (TyInfo.first > CharUnits::fromQuantity(16) &&
5942              getABIKind() == ARMABIInfo::AAPCS16_VFP &&
5943              !isHomogeneousAggregate(Ty, Base, Members)) {
5944     IsIndirect = true;
5945
5946   // Otherwise, bound the type's ABI alignment.
5947   // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
5948   // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
5949   // Our callers should be prepared to handle an under-aligned address.
5950   } else if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
5951              getABIKind() == ARMABIInfo::AAPCS) {
5952     TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
5953     TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(8));
5954   } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
5955     // ARMv7k allows type alignment up to 16 bytes.
5956     TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
5957     TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(16));
5958   } else {
5959     TyAlignForABI = CharUnits::fromQuantity(4);
5960   }
5961   TyInfo.second = TyAlignForABI;
5962
5963   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TyInfo,
5964                           SlotSize, /*AllowHigherAlign*/ true);
5965 }
5966
5967 //===----------------------------------------------------------------------===//
5968 // NVPTX ABI Implementation
5969 //===----------------------------------------------------------------------===//
5970
5971 namespace {
5972
5973 class NVPTXABIInfo : public ABIInfo {
5974 public:
5975   NVPTXABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
5976
5977   ABIArgInfo classifyReturnType(QualType RetTy) const;
5978   ABIArgInfo classifyArgumentType(QualType Ty) const;
5979
5980   void computeInfo(CGFunctionInfo &FI) const override;
5981   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5982                     QualType Ty) const override;
5983 };
5984
5985 class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
5986 public:
5987   NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
5988     : TargetCodeGenInfo(new NVPTXABIInfo(CGT)) {}
5989
5990   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5991                            CodeGen::CodeGenModule &M) const override;
5992 private:
5993   // Adds a NamedMDNode with F, Name, and Operand as operands, and adds the
5994   // resulting MDNode to the nvvm.annotations MDNode.
5995   static void addNVVMMetadata(llvm::Function *F, StringRef Name, int Operand);
5996 };
5997
5998 ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
5999   if (RetTy->isVoidType())
6000     return ABIArgInfo::getIgnore();
6001
6002   // note: this is different from default ABI
6003   if (!RetTy->isScalarType())
6004     return ABIArgInfo::getDirect();
6005
6006   // Treat an enum type as its underlying type.
6007   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6008     RetTy = EnumTy->getDecl()->getIntegerType();
6009
6010   return (RetTy->isPromotableIntegerType() ?
6011           ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6012 }
6013
6014 ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
6015   // Treat an enum type as its underlying type.
6016   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6017     Ty = EnumTy->getDecl()->getIntegerType();
6018
6019   // Return aggregates type as indirect by value
6020   if (isAggregateTypeForABI(Ty))
6021     return getNaturalAlignIndirect(Ty, /* byval */ true);
6022
6023   return (Ty->isPromotableIntegerType() ?
6024           ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6025 }
6026
6027 void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
6028   if (!getCXXABI().classifyReturnType(FI))
6029     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
6030   for (auto &I : FI.arguments())
6031     I.info = classifyArgumentType(I.type);
6032
6033   // Always honor user-specified calling convention.
6034   if (FI.getCallingConvention() != llvm::CallingConv::C)
6035     return;
6036
6037   FI.setEffectiveCallingConvention(getRuntimeCC());
6038 }
6039
6040 Address NVPTXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6041                                 QualType Ty) const {
6042   llvm_unreachable("NVPTX does not support varargs");
6043 }
6044
6045 void NVPTXTargetCodeGenInfo::
6046 setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
6047                     CodeGen::CodeGenModule &M) const{
6048   const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
6049   if (!FD) return;
6050
6051   llvm::Function *F = cast<llvm::Function>(GV);
6052
6053   // Perform special handling in OpenCL mode
6054   if (M.getLangOpts().OpenCL) {
6055     // Use OpenCL function attributes to check for kernel functions
6056     // By default, all functions are device functions
6057     if (FD->hasAttr<OpenCLKernelAttr>()) {
6058       // OpenCL __kernel functions get kernel metadata
6059       // Create !{<func-ref>, metadata !"kernel", i32 1} node
6060       addNVVMMetadata(F, "kernel", 1);
6061       // And kernel functions are not subject to inlining
6062       F->addFnAttr(llvm::Attribute::NoInline);
6063     }
6064   }
6065
6066   // Perform special handling in CUDA mode.
6067   if (M.getLangOpts().CUDA) {
6068     // CUDA __global__ functions get a kernel metadata entry.  Since
6069     // __global__ functions cannot be called from the device, we do not
6070     // need to set the noinline attribute.
6071     if (FD->hasAttr<CUDAGlobalAttr>()) {
6072       // Create !{<func-ref>, metadata !"kernel", i32 1} node
6073       addNVVMMetadata(F, "kernel", 1);
6074     }
6075     if (CUDALaunchBoundsAttr *Attr = FD->getAttr<CUDALaunchBoundsAttr>()) {
6076       // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node
6077       llvm::APSInt MaxThreads(32);
6078       MaxThreads = Attr->getMaxThreads()->EvaluateKnownConstInt(M.getContext());
6079       if (MaxThreads > 0)
6080         addNVVMMetadata(F, "maxntidx", MaxThreads.getExtValue());
6081
6082       // min blocks is an optional argument for CUDALaunchBoundsAttr. If it was
6083       // not specified in __launch_bounds__ or if the user specified a 0 value,
6084       // we don't have to add a PTX directive.
6085       if (Attr->getMinBlocks()) {
6086         llvm::APSInt MinBlocks(32);
6087         MinBlocks = Attr->getMinBlocks()->EvaluateKnownConstInt(M.getContext());
6088         if (MinBlocks > 0)
6089           // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node
6090           addNVVMMetadata(F, "minctasm", MinBlocks.getExtValue());
6091       }
6092     }
6093   }
6094 }
6095
6096 void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::Function *F, StringRef Name,
6097                                              int Operand) {
6098   llvm::Module *M = F->getParent();
6099   llvm::LLVMContext &Ctx = M->getContext();
6100
6101   // Get "nvvm.annotations" metadata node
6102   llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
6103
6104   llvm::Metadata *MDVals[] = {
6105       llvm::ConstantAsMetadata::get(F), llvm::MDString::get(Ctx, Name),
6106       llvm::ConstantAsMetadata::get(
6107           llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand))};
6108   // Append metadata to nvvm.annotations
6109   MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
6110 }
6111 }
6112
6113 //===----------------------------------------------------------------------===//
6114 // SystemZ ABI Implementation
6115 //===----------------------------------------------------------------------===//
6116
6117 namespace {
6118
6119 class SystemZABIInfo : public SwiftABIInfo {
6120   bool HasVector;
6121
6122 public:
6123   SystemZABIInfo(CodeGenTypes &CGT, bool HV)
6124     : SwiftABIInfo(CGT), HasVector(HV) {}
6125
6126   bool isPromotableIntegerType(QualType Ty) const;
6127   bool isCompoundType(QualType Ty) const;
6128   bool isVectorArgumentType(QualType Ty) const;
6129   bool isFPArgumentType(QualType Ty) const;
6130   QualType GetSingleElementType(QualType Ty) const;
6131
6132   ABIArgInfo classifyReturnType(QualType RetTy) const;
6133   ABIArgInfo classifyArgumentType(QualType ArgTy) const;
6134
6135   void computeInfo(CGFunctionInfo &FI) const override {
6136     if (!getCXXABI().classifyReturnType(FI))
6137       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
6138     for (auto &I : FI.arguments())
6139       I.info = classifyArgumentType(I.type);
6140   }
6141
6142   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6143                     QualType Ty) const override;
6144
6145   bool shouldPassIndirectlyForSwift(CharUnits totalSize,
6146                                     ArrayRef<llvm::Type*> scalars,
6147                                     bool asReturnValue) const override {
6148     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
6149   }
6150   bool isSwiftErrorInRegister() const override {
6151     return true;
6152   }
6153 };
6154
6155 class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
6156 public:
6157   SystemZTargetCodeGenInfo(CodeGenTypes &CGT, bool HasVector)
6158     : TargetCodeGenInfo(new SystemZABIInfo(CGT, HasVector)) {}
6159 };
6160
6161 }
6162
6163 bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const {
6164   // Treat an enum type as its underlying type.
6165   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6166     Ty = EnumTy->getDecl()->getIntegerType();
6167
6168   // Promotable integer types are required to be promoted by the ABI.
6169   if (Ty->isPromotableIntegerType())
6170     return true;
6171
6172   // 32-bit values must also be promoted.
6173   if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
6174     switch (BT->getKind()) {
6175     case BuiltinType::Int:
6176     case BuiltinType::UInt:
6177       return true;
6178     default:
6179       return false;
6180     }
6181   return false;
6182 }
6183
6184 bool SystemZABIInfo::isCompoundType(QualType Ty) const {
6185   return (Ty->isAnyComplexType() ||
6186           Ty->isVectorType() ||
6187           isAggregateTypeForABI(Ty));
6188 }
6189
6190 bool SystemZABIInfo::isVectorArgumentType(QualType Ty) const {
6191   return (HasVector &&
6192           Ty->isVectorType() &&
6193           getContext().getTypeSize(Ty) <= 128);
6194 }
6195
6196 bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
6197   if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
6198     switch (BT->getKind()) {
6199     case BuiltinType::Float:
6200     case BuiltinType::Double:
6201       return true;
6202     default:
6203       return false;
6204     }
6205
6206   return false;
6207 }
6208
6209 QualType SystemZABIInfo::GetSingleElementType(QualType Ty) const {
6210   if (const RecordType *RT = Ty->getAsStructureType()) {
6211     const RecordDecl *RD = RT->getDecl();
6212     QualType Found;
6213
6214     // If this is a C++ record, check the bases first.
6215     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
6216       for (const auto &I : CXXRD->bases()) {
6217         QualType Base = I.getType();
6218
6219         // Empty bases don't affect things either way.
6220         if (isEmptyRecord(getContext(), Base, true))
6221           continue;
6222
6223         if (!Found.isNull())
6224           return Ty;
6225         Found = GetSingleElementType(Base);
6226       }
6227
6228     // Check the fields.
6229     for (const auto *FD : RD->fields()) {
6230       // For compatibility with GCC, ignore empty bitfields in C++ mode.
6231       // Unlike isSingleElementStruct(), empty structure and array fields
6232       // do count.  So do anonymous bitfields that aren't zero-sized.
6233       if (getContext().getLangOpts().CPlusPlus &&
6234           FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
6235         continue;
6236
6237       // Unlike isSingleElementStruct(), arrays do not count.
6238       // Nested structures still do though.
6239       if (!Found.isNull())
6240         return Ty;
6241       Found = GetSingleElementType(FD->getType());
6242     }
6243
6244     // Unlike isSingleElementStruct(), trailing padding is allowed.
6245     // An 8-byte aligned struct s { float f; } is passed as a double.
6246     if (!Found.isNull())
6247       return Found;
6248   }
6249
6250   return Ty;
6251 }
6252
6253 Address SystemZABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6254                                   QualType Ty) const {
6255   // Assume that va_list type is correct; should be pointer to LLVM type:
6256   // struct {
6257   //   i64 __gpr;
6258   //   i64 __fpr;
6259   //   i8 *__overflow_arg_area;
6260   //   i8 *__reg_save_area;
6261   // };
6262
6263   // Every non-vector argument occupies 8 bytes and is passed by preference
6264   // in either GPRs or FPRs.  Vector arguments occupy 8 or 16 bytes and are
6265   // always passed on the stack.
6266   Ty = getContext().getCanonicalType(Ty);
6267   auto TyInfo = getContext().getTypeInfoInChars(Ty);
6268   llvm::Type *ArgTy = CGF.ConvertTypeForMem(Ty);
6269   llvm::Type *DirectTy = ArgTy;
6270   ABIArgInfo AI = classifyArgumentType(Ty);
6271   bool IsIndirect = AI.isIndirect();
6272   bool InFPRs = false;
6273   bool IsVector = false;
6274   CharUnits UnpaddedSize;
6275   CharUnits DirectAlign;
6276   if (IsIndirect) {
6277     DirectTy = llvm::PointerType::getUnqual(DirectTy);
6278     UnpaddedSize = DirectAlign = CharUnits::fromQuantity(8);
6279   } else {
6280     if (AI.getCoerceToType())
6281       ArgTy = AI.getCoerceToType();
6282     InFPRs = ArgTy->isFloatTy() || ArgTy->isDoubleTy();
6283     IsVector = ArgTy->isVectorTy();
6284     UnpaddedSize = TyInfo.first;
6285     DirectAlign = TyInfo.second;
6286   }
6287   CharUnits PaddedSize = CharUnits::fromQuantity(8);
6288   if (IsVector && UnpaddedSize > PaddedSize)
6289     PaddedSize = CharUnits::fromQuantity(16);
6290   assert((UnpaddedSize <= PaddedSize) && "Invalid argument size.");
6291
6292   CharUnits Padding = (PaddedSize - UnpaddedSize);
6293
6294   llvm::Type *IndexTy = CGF.Int64Ty;
6295   llvm::Value *PaddedSizeV =
6296     llvm::ConstantInt::get(IndexTy, PaddedSize.getQuantity());
6297
6298   if (IsVector) {
6299     // Work out the address of a vector argument on the stack.
6300     // Vector arguments are always passed in the high bits of a
6301     // single (8 byte) or double (16 byte) stack slot.
6302     Address OverflowArgAreaPtr =
6303       CGF.Builder.CreateStructGEP(VAListAddr, 2, CharUnits::fromQuantity(16),
6304                                   "overflow_arg_area_ptr");
6305     Address OverflowArgArea =
6306       Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
6307               TyInfo.second);
6308     Address MemAddr =
6309       CGF.Builder.CreateElementBitCast(OverflowArgArea, DirectTy, "mem_addr");
6310
6311     // Update overflow_arg_area_ptr pointer
6312     llvm::Value *NewOverflowArgArea =
6313       CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
6314                             "overflow_arg_area");
6315     CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
6316
6317     return MemAddr;
6318   }
6319
6320   assert(PaddedSize.getQuantity() == 8);
6321
6322   unsigned MaxRegs, RegCountField, RegSaveIndex;
6323   CharUnits RegPadding;
6324   if (InFPRs) {
6325     MaxRegs = 4; // Maximum of 4 FPR arguments
6326     RegCountField = 1; // __fpr
6327     RegSaveIndex = 16; // save offset for f0
6328     RegPadding = CharUnits(); // floats are passed in the high bits of an FPR
6329   } else {
6330     MaxRegs = 5; // Maximum of 5 GPR arguments
6331     RegCountField = 0; // __gpr
6332     RegSaveIndex = 2; // save offset for r2
6333     RegPadding = Padding; // values are passed in the low bits of a GPR
6334   }
6335
6336   Address RegCountPtr = CGF.Builder.CreateStructGEP(
6337       VAListAddr, RegCountField, RegCountField * CharUnits::fromQuantity(8),
6338       "reg_count_ptr");
6339   llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
6340   llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
6341   llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
6342                                                  "fits_in_regs");
6343
6344   llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
6345   llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
6346   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
6347   CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
6348
6349   // Emit code to load the value if it was passed in registers.
6350   CGF.EmitBlock(InRegBlock);
6351
6352   // Work out the address of an argument register.
6353   llvm::Value *ScaledRegCount =
6354     CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
6355   llvm::Value *RegBase =
6356     llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize.getQuantity()
6357                                       + RegPadding.getQuantity());
6358   llvm::Value *RegOffset =
6359     CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
6360   Address RegSaveAreaPtr =
6361       CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(24),
6362                                   "reg_save_area_ptr");
6363   llvm::Value *RegSaveArea =
6364     CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
6365   Address RawRegAddr(CGF.Builder.CreateGEP(RegSaveArea, RegOffset,
6366                                            "raw_reg_addr"),
6367                      PaddedSize);
6368   Address RegAddr =
6369     CGF.Builder.CreateElementBitCast(RawRegAddr, DirectTy, "reg_addr");
6370
6371   // Update the register count
6372   llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
6373   llvm::Value *NewRegCount =
6374     CGF.Builder.CreateAdd(RegCount, One, "reg_count");
6375   CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
6376   CGF.EmitBranch(ContBlock);
6377
6378   // Emit code to load the value if it was passed in memory.
6379   CGF.EmitBlock(InMemBlock);
6380
6381   // Work out the address of a stack argument.
6382   Address OverflowArgAreaPtr = CGF.Builder.CreateStructGEP(
6383       VAListAddr, 2, CharUnits::fromQuantity(16), "overflow_arg_area_ptr");
6384   Address OverflowArgArea =
6385     Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
6386             PaddedSize);
6387   Address RawMemAddr =
6388     CGF.Builder.CreateConstByteGEP(OverflowArgArea, Padding, "raw_mem_addr");
6389   Address MemAddr =
6390     CGF.Builder.CreateElementBitCast(RawMemAddr, DirectTy, "mem_addr");
6391
6392   // Update overflow_arg_area_ptr pointer
6393   llvm::Value *NewOverflowArgArea =
6394     CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
6395                           "overflow_arg_area");
6396   CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
6397   CGF.EmitBranch(ContBlock);
6398
6399   // Return the appropriate result.
6400   CGF.EmitBlock(ContBlock);
6401   Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
6402                                  MemAddr, InMemBlock, "va_arg.addr");
6403
6404   if (IsIndirect)
6405     ResAddr = Address(CGF.Builder.CreateLoad(ResAddr, "indirect_arg"),
6406                       TyInfo.second);
6407
6408   return ResAddr;
6409 }
6410
6411 ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
6412   if (RetTy->isVoidType())
6413     return ABIArgInfo::getIgnore();
6414   if (isVectorArgumentType(RetTy))
6415     return ABIArgInfo::getDirect();
6416   if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
6417     return getNaturalAlignIndirect(RetTy);
6418   return (isPromotableIntegerType(RetTy) ?
6419           ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6420 }
6421
6422 ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
6423   // Handle the generic C++ ABI.
6424   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
6425     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
6426
6427   // Integers and enums are extended to full register width.
6428   if (isPromotableIntegerType(Ty))
6429     return ABIArgInfo::getExtend();
6430
6431   // Handle vector types and vector-like structure types.  Note that
6432   // as opposed to float-like structure types, we do not allow any
6433   // padding for vector-like structures, so verify the sizes match.
6434   uint64_t Size = getContext().getTypeSize(Ty);
6435   QualType SingleElementTy = GetSingleElementType(Ty);
6436   if (isVectorArgumentType(SingleElementTy) &&
6437       getContext().getTypeSize(SingleElementTy) == Size)
6438     return ABIArgInfo::getDirect(CGT.ConvertType(SingleElementTy));
6439
6440   // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
6441   if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
6442     return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
6443
6444   // Handle small structures.
6445   if (const RecordType *RT = Ty->getAs<RecordType>()) {
6446     // Structures with flexible arrays have variable length, so really
6447     // fail the size test above.
6448     const RecordDecl *RD = RT->getDecl();
6449     if (RD->hasFlexibleArrayMember())
6450       return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
6451
6452     // The structure is passed as an unextended integer, a float, or a double.
6453     llvm::Type *PassTy;
6454     if (isFPArgumentType(SingleElementTy)) {
6455       assert(Size == 32 || Size == 64);
6456       if (Size == 32)
6457         PassTy = llvm::Type::getFloatTy(getVMContext());
6458       else
6459         PassTy = llvm::Type::getDoubleTy(getVMContext());
6460     } else
6461       PassTy = llvm::IntegerType::get(getVMContext(), Size);
6462     return ABIArgInfo::getDirect(PassTy);
6463   }
6464
6465   // Non-structure compounds are passed indirectly.
6466   if (isCompoundType(Ty))
6467     return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
6468
6469   return ABIArgInfo::getDirect(nullptr);
6470 }
6471
6472 //===----------------------------------------------------------------------===//
6473 // MSP430 ABI Implementation
6474 //===----------------------------------------------------------------------===//
6475
6476 namespace {
6477
6478 class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
6479 public:
6480   MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
6481     : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
6482   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
6483                            CodeGen::CodeGenModule &M) const override;
6484 };
6485
6486 }
6487
6488 void MSP430TargetCodeGenInfo::setTargetAttributes(const Decl *D,
6489                                                   llvm::GlobalValue *GV,
6490                                              CodeGen::CodeGenModule &M) const {
6491   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
6492     if (const MSP430InterruptAttr *attr = FD->getAttr<MSP430InterruptAttr>()) {
6493       // Handle 'interrupt' attribute:
6494       llvm::Function *F = cast<llvm::Function>(GV);
6495
6496       // Step 1: Set ISR calling convention.
6497       F->setCallingConv(llvm::CallingConv::MSP430_INTR);
6498
6499       // Step 2: Add attributes goodness.
6500       F->addFnAttr(llvm::Attribute::NoInline);
6501
6502       // Step 3: Emit ISR vector alias.
6503       unsigned Num = attr->getNumber() / 2;
6504       llvm::GlobalAlias::create(llvm::Function::ExternalLinkage,
6505                                 "__isr_" + Twine(Num), F);
6506     }
6507   }
6508 }
6509
6510 //===----------------------------------------------------------------------===//
6511 // MIPS ABI Implementation.  This works for both little-endian and
6512 // big-endian variants.
6513 //===----------------------------------------------------------------------===//
6514
6515 namespace {
6516 class MipsABIInfo : public ABIInfo {
6517   bool IsO32;
6518   unsigned MinABIStackAlignInBytes, StackAlignInBytes;
6519   void CoerceToIntArgs(uint64_t TySize,
6520                        SmallVectorImpl<llvm::Type *> &ArgList) const;
6521   llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
6522   llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
6523   llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
6524 public:
6525   MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
6526     ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
6527     StackAlignInBytes(IsO32 ? 8 : 16) {}
6528
6529   ABIArgInfo classifyReturnType(QualType RetTy) const;
6530   ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
6531   void computeInfo(CGFunctionInfo &FI) const override;
6532   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6533                     QualType Ty) const override;
6534   bool shouldSignExtUnsignedType(QualType Ty) const override;
6535 };
6536
6537 class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
6538   unsigned SizeOfUnwindException;
6539 public:
6540   MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
6541     : TargetCodeGenInfo(new MipsABIInfo(CGT, IsO32)),
6542       SizeOfUnwindException(IsO32 ? 24 : 32) {}
6543
6544   int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
6545     return 29;
6546   }
6547
6548   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
6549                            CodeGen::CodeGenModule &CGM) const override {
6550     const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
6551     if (!FD) return;
6552     llvm::Function *Fn = cast<llvm::Function>(GV);
6553     if (FD->hasAttr<Mips16Attr>()) {
6554       Fn->addFnAttr("mips16");
6555     }
6556     else if (FD->hasAttr<NoMips16Attr>()) {
6557       Fn->addFnAttr("nomips16");
6558     }
6559
6560     if (FD->hasAttr<MicroMipsAttr>())
6561       Fn->addFnAttr("micromips");
6562     else if (FD->hasAttr<NoMicroMipsAttr>())
6563       Fn->addFnAttr("nomicromips");
6564
6565     const MipsInterruptAttr *Attr = FD->getAttr<MipsInterruptAttr>();
6566     if (!Attr)
6567       return;
6568
6569     const char *Kind;
6570     switch (Attr->getInterrupt()) {
6571     case MipsInterruptAttr::eic:     Kind = "eic"; break;
6572     case MipsInterruptAttr::sw0:     Kind = "sw0"; break;
6573     case MipsInterruptAttr::sw1:     Kind = "sw1"; break;
6574     case MipsInterruptAttr::hw0:     Kind = "hw0"; break;
6575     case MipsInterruptAttr::hw1:     Kind = "hw1"; break;
6576     case MipsInterruptAttr::hw2:     Kind = "hw2"; break;
6577     case MipsInterruptAttr::hw3:     Kind = "hw3"; break;
6578     case MipsInterruptAttr::hw4:     Kind = "hw4"; break;
6579     case MipsInterruptAttr::hw5:     Kind = "hw5"; break;
6580     }
6581
6582     Fn->addFnAttr("interrupt", Kind);
6583
6584   }
6585
6586   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
6587                                llvm::Value *Address) const override;
6588
6589   unsigned getSizeOfUnwindException() const override {
6590     return SizeOfUnwindException;
6591   }
6592 };
6593 }
6594
6595 void MipsABIInfo::CoerceToIntArgs(
6596     uint64_t TySize, SmallVectorImpl<llvm::Type *> &ArgList) const {
6597   llvm::IntegerType *IntTy =
6598     llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
6599
6600   // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
6601   for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
6602     ArgList.push_back(IntTy);
6603
6604   // If necessary, add one more integer type to ArgList.
6605   unsigned R = TySize % (MinABIStackAlignInBytes * 8);
6606
6607   if (R)
6608     ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
6609 }
6610
6611 // In N32/64, an aligned double precision floating point field is passed in
6612 // a register.
6613 llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
6614   SmallVector<llvm::Type*, 8> ArgList, IntArgList;
6615
6616   if (IsO32) {
6617     CoerceToIntArgs(TySize, ArgList);
6618     return llvm::StructType::get(getVMContext(), ArgList);
6619   }
6620
6621   if (Ty->isComplexType())
6622     return CGT.ConvertType(Ty);
6623
6624   const RecordType *RT = Ty->getAs<RecordType>();
6625
6626   // Unions/vectors are passed in integer registers.
6627   if (!RT || !RT->isStructureOrClassType()) {
6628     CoerceToIntArgs(TySize, ArgList);
6629     return llvm::StructType::get(getVMContext(), ArgList);
6630   }
6631
6632   const RecordDecl *RD = RT->getDecl();
6633   const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
6634   assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
6635
6636   uint64_t LastOffset = 0;
6637   unsigned idx = 0;
6638   llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
6639
6640   // Iterate over fields in the struct/class and check if there are any aligned
6641   // double fields.
6642   for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
6643        i != e; ++i, ++idx) {
6644     const QualType Ty = i->getType();
6645     const BuiltinType *BT = Ty->getAs<BuiltinType>();
6646
6647     if (!BT || BT->getKind() != BuiltinType::Double)
6648       continue;
6649
6650     uint64_t Offset = Layout.getFieldOffset(idx);
6651     if (Offset % 64) // Ignore doubles that are not aligned.
6652       continue;
6653
6654     // Add ((Offset - LastOffset) / 64) args of type i64.
6655     for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
6656       ArgList.push_back(I64);
6657
6658     // Add double type.
6659     ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
6660     LastOffset = Offset + 64;
6661   }
6662
6663   CoerceToIntArgs(TySize - LastOffset, IntArgList);
6664   ArgList.append(IntArgList.begin(), IntArgList.end());
6665
6666   return llvm::StructType::get(getVMContext(), ArgList);
6667 }
6668
6669 llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
6670                                         uint64_t Offset) const {
6671   if (OrigOffset + MinABIStackAlignInBytes > Offset)
6672     return nullptr;
6673
6674   return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
6675 }
6676
6677 ABIArgInfo
6678 MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
6679   Ty = useFirstFieldIfTransparentUnion(Ty);
6680
6681   uint64_t OrigOffset = Offset;
6682   uint64_t TySize = getContext().getTypeSize(Ty);
6683   uint64_t Align = getContext().getTypeAlign(Ty) / 8;
6684
6685   Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
6686                    (uint64_t)StackAlignInBytes);
6687   unsigned CurrOffset = llvm::alignTo(Offset, Align);
6688   Offset = CurrOffset + llvm::alignTo(TySize, Align * 8) / 8;
6689
6690   if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
6691     // Ignore empty aggregates.
6692     if (TySize == 0)
6693       return ABIArgInfo::getIgnore();
6694
6695     if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
6696       Offset = OrigOffset + MinABIStackAlignInBytes;
6697       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
6698     }
6699
6700     // Use indirect if the aggregate cannot fit into registers for
6701     // passing arguments according to the ABI
6702     unsigned Threshold = IsO32 ? 16 : 64;
6703
6704     if(getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(Threshold))
6705       return ABIArgInfo::getIndirect(CharUnits::fromQuantity(Align), true,
6706                                      getContext().getTypeAlign(Ty) / 8 > Align);
6707
6708     // If we have reached here, aggregates are passed directly by coercing to
6709     // another structure type. Padding is inserted if the offset of the
6710     // aggregate is unaligned.
6711     ABIArgInfo ArgInfo =
6712         ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
6713                               getPaddingType(OrigOffset, CurrOffset));
6714     ArgInfo.setInReg(true);
6715     return ArgInfo;
6716   }
6717
6718   // Treat an enum type as its underlying type.
6719   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6720     Ty = EnumTy->getDecl()->getIntegerType();
6721
6722   // All integral types are promoted to the GPR width.
6723   if (Ty->isIntegralOrEnumerationType())
6724     return ABIArgInfo::getExtend();
6725
6726   return ABIArgInfo::getDirect(
6727       nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset));
6728 }
6729
6730 llvm::Type*
6731 MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
6732   const RecordType *RT = RetTy->getAs<RecordType>();
6733   SmallVector<llvm::Type*, 8> RTList;
6734
6735   if (RT && RT->isStructureOrClassType()) {
6736     const RecordDecl *RD = RT->getDecl();
6737     const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
6738     unsigned FieldCnt = Layout.getFieldCount();
6739
6740     // N32/64 returns struct/classes in floating point registers if the
6741     // following conditions are met:
6742     // 1. The size of the struct/class is no larger than 128-bit.
6743     // 2. The struct/class has one or two fields all of which are floating
6744     //    point types.
6745     // 3. The offset of the first field is zero (this follows what gcc does).
6746     //
6747     // Any other composite results are returned in integer registers.
6748     //
6749     if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
6750       RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
6751       for (; b != e; ++b) {
6752         const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
6753
6754         if (!BT || !BT->isFloatingPoint())
6755           break;
6756
6757         RTList.push_back(CGT.ConvertType(b->getType()));
6758       }
6759
6760       if (b == e)
6761         return llvm::StructType::get(getVMContext(), RTList,
6762                                      RD->hasAttr<PackedAttr>());
6763
6764       RTList.clear();
6765     }
6766   }
6767
6768   CoerceToIntArgs(Size, RTList);
6769   return llvm::StructType::get(getVMContext(), RTList);
6770 }
6771
6772 ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
6773   uint64_t Size = getContext().getTypeSize(RetTy);
6774
6775   if (RetTy->isVoidType())
6776     return ABIArgInfo::getIgnore();
6777
6778   // O32 doesn't treat zero-sized structs differently from other structs.
6779   // However, N32/N64 ignores zero sized return values.
6780   if (!IsO32 && Size == 0)
6781     return ABIArgInfo::getIgnore();
6782
6783   if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
6784     if (Size <= 128) {
6785       if (RetTy->isAnyComplexType())
6786         return ABIArgInfo::getDirect();
6787
6788       // O32 returns integer vectors in registers and N32/N64 returns all small
6789       // aggregates in registers.
6790       if (!IsO32 ||
6791           (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) {
6792         ABIArgInfo ArgInfo =
6793             ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
6794         ArgInfo.setInReg(true);
6795         return ArgInfo;
6796       }
6797     }
6798
6799     return getNaturalAlignIndirect(RetTy);
6800   }
6801
6802   // Treat an enum type as its underlying type.
6803   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6804     RetTy = EnumTy->getDecl()->getIntegerType();
6805
6806   return (RetTy->isPromotableIntegerType() ?
6807           ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6808 }
6809
6810 void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
6811   ABIArgInfo &RetInfo = FI.getReturnInfo();
6812   if (!getCXXABI().classifyReturnType(FI))
6813     RetInfo = classifyReturnType(FI.getReturnType());
6814
6815   // Check if a pointer to an aggregate is passed as a hidden argument.
6816   uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
6817
6818   for (auto &I : FI.arguments())
6819     I.info = classifyArgumentType(I.type, Offset);
6820 }
6821
6822 Address MipsABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6823                                QualType OrigTy) const {
6824   QualType Ty = OrigTy;
6825
6826   // Integer arguments are promoted to 32-bit on O32 and 64-bit on N32/N64.
6827   // Pointers are also promoted in the same way but this only matters for N32.
6828   unsigned SlotSizeInBits = IsO32 ? 32 : 64;
6829   unsigned PtrWidth = getTarget().getPointerWidth(0);
6830   bool DidPromote = false;
6831   if ((Ty->isIntegerType() &&
6832           getContext().getIntWidth(Ty) < SlotSizeInBits) ||
6833       (Ty->isPointerType() && PtrWidth < SlotSizeInBits)) {
6834     DidPromote = true;
6835     Ty = getContext().getIntTypeForBitwidth(SlotSizeInBits,
6836                                             Ty->isSignedIntegerType());
6837   }
6838
6839   auto TyInfo = getContext().getTypeInfoInChars(Ty);
6840
6841   // The alignment of things in the argument area is never larger than
6842   // StackAlignInBytes.
6843   TyInfo.second =
6844     std::min(TyInfo.second, CharUnits::fromQuantity(StackAlignInBytes));
6845
6846   // MinABIStackAlignInBytes is the size of argument slots on the stack.
6847   CharUnits ArgSlotSize = CharUnits::fromQuantity(MinABIStackAlignInBytes);
6848
6849   Address Addr = emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
6850                           TyInfo, ArgSlotSize, /*AllowHigherAlign*/ true);
6851
6852
6853   // If there was a promotion, "unpromote" into a temporary.
6854   // TODO: can we just use a pointer into a subset of the original slot?
6855   if (DidPromote) {
6856     Address Temp = CGF.CreateMemTemp(OrigTy, "vaarg.promotion-temp");
6857     llvm::Value *Promoted = CGF.Builder.CreateLoad(Addr);
6858
6859     // Truncate down to the right width.
6860     llvm::Type *IntTy = (OrigTy->isIntegerType() ? Temp.getElementType()
6861                                                  : CGF.IntPtrTy);
6862     llvm::Value *V = CGF.Builder.CreateTrunc(Promoted, IntTy);
6863     if (OrigTy->isPointerType())
6864       V = CGF.Builder.CreateIntToPtr(V, Temp.getElementType());
6865
6866     CGF.Builder.CreateStore(V, Temp);
6867     Addr = Temp;
6868   }
6869
6870   return Addr;
6871 }
6872
6873 bool MipsABIInfo::shouldSignExtUnsignedType(QualType Ty) const {
6874   int TySize = getContext().getTypeSize(Ty);
6875
6876   // MIPS64 ABI requires unsigned 32 bit integers to be sign extended.
6877   if (Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
6878     return true;
6879
6880   return false;
6881 }
6882
6883 bool
6884 MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
6885                                                llvm::Value *Address) const {
6886   // This information comes from gcc's implementation, which seems to
6887   // as canonical as it gets.
6888
6889   // Everything on MIPS is 4 bytes.  Double-precision FP registers
6890   // are aliased to pairs of single-precision FP registers.
6891   llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
6892
6893   // 0-31 are the general purpose registers, $0 - $31.
6894   // 32-63 are the floating-point registers, $f0 - $f31.
6895   // 64 and 65 are the multiply/divide registers, $hi and $lo.
6896   // 66 is the (notional, I think) register for signal-handler return.
6897   AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
6898
6899   // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
6900   // They are one bit wide and ignored here.
6901
6902   // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
6903   // (coprocessor 1 is the FP unit)
6904   // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
6905   // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
6906   // 176-181 are the DSP accumulator registers.
6907   AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
6908   return false;
6909 }
6910
6911 //===----------------------------------------------------------------------===//
6912 // AVR ABI Implementation.
6913 //===----------------------------------------------------------------------===//
6914
6915 namespace {
6916 class AVRTargetCodeGenInfo : public TargetCodeGenInfo {
6917 public:
6918   AVRTargetCodeGenInfo(CodeGenTypes &CGT)
6919     : TargetCodeGenInfo(new DefaultABIInfo(CGT)) { }
6920
6921   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
6922                            CodeGen::CodeGenModule &CGM) const override {
6923     const auto *FD = dyn_cast_or_null<FunctionDecl>(D);
6924     if (!FD) return;
6925     auto *Fn = cast<llvm::Function>(GV);
6926
6927     if (FD->getAttr<AVRInterruptAttr>())
6928       Fn->addFnAttr("interrupt");
6929
6930     if (FD->getAttr<AVRSignalAttr>())
6931       Fn->addFnAttr("signal");
6932   }
6933 };
6934 }
6935
6936 //===----------------------------------------------------------------------===//
6937 // TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
6938 // Currently subclassed only to implement custom OpenCL C function attribute
6939 // handling.
6940 //===----------------------------------------------------------------------===//
6941
6942 namespace {
6943
6944 class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
6945 public:
6946   TCETargetCodeGenInfo(CodeGenTypes &CGT)
6947     : DefaultTargetCodeGenInfo(CGT) {}
6948
6949   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
6950                            CodeGen::CodeGenModule &M) const override;
6951 };
6952
6953 void TCETargetCodeGenInfo::setTargetAttributes(
6954     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
6955   const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
6956   if (!FD) return;
6957
6958   llvm::Function *F = cast<llvm::Function>(GV);
6959
6960   if (M.getLangOpts().OpenCL) {
6961     if (FD->hasAttr<OpenCLKernelAttr>()) {
6962       // OpenCL C Kernel functions are not subject to inlining
6963       F->addFnAttr(llvm::Attribute::NoInline);
6964       const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
6965       if (Attr) {
6966         // Convert the reqd_work_group_size() attributes to metadata.
6967         llvm::LLVMContext &Context = F->getContext();
6968         llvm::NamedMDNode *OpenCLMetadata =
6969             M.getModule().getOrInsertNamedMetadata(
6970                 "opencl.kernel_wg_size_info");
6971
6972         SmallVector<llvm::Metadata *, 5> Operands;
6973         Operands.push_back(llvm::ConstantAsMetadata::get(F));
6974
6975         Operands.push_back(
6976             llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
6977                 M.Int32Ty, llvm::APInt(32, Attr->getXDim()))));
6978         Operands.push_back(
6979             llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
6980                 M.Int32Ty, llvm::APInt(32, Attr->getYDim()))));
6981         Operands.push_back(
6982             llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
6983                 M.Int32Ty, llvm::APInt(32, Attr->getZDim()))));
6984
6985         // Add a boolean constant operand for "required" (true) or "hint"
6986         // (false) for implementing the work_group_size_hint attr later.
6987         // Currently always true as the hint is not yet implemented.
6988         Operands.push_back(
6989             llvm::ConstantAsMetadata::get(llvm::ConstantInt::getTrue(Context)));
6990         OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
6991       }
6992     }
6993   }
6994 }
6995
6996 }
6997
6998 //===----------------------------------------------------------------------===//
6999 // Hexagon ABI Implementation
7000 //===----------------------------------------------------------------------===//
7001
7002 namespace {
7003
7004 class HexagonABIInfo : public ABIInfo {
7005
7006
7007 public:
7008   HexagonABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
7009
7010 private:
7011
7012   ABIArgInfo classifyReturnType(QualType RetTy) const;
7013   ABIArgInfo classifyArgumentType(QualType RetTy) const;
7014
7015   void computeInfo(CGFunctionInfo &FI) const override;
7016
7017   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7018                     QualType Ty) const override;
7019 };
7020
7021 class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
7022 public:
7023   HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
7024     :TargetCodeGenInfo(new HexagonABIInfo(CGT)) {}
7025
7026   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
7027     return 29;
7028   }
7029 };
7030
7031 }
7032
7033 void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
7034   if (!getCXXABI().classifyReturnType(FI))
7035     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7036   for (auto &I : FI.arguments())
7037     I.info = classifyArgumentType(I.type);
7038 }
7039
7040 ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty) const {
7041   if (!isAggregateTypeForABI(Ty)) {
7042     // Treat an enum type as its underlying type.
7043     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7044       Ty = EnumTy->getDecl()->getIntegerType();
7045
7046     return (Ty->isPromotableIntegerType() ?
7047             ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
7048   }
7049
7050   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
7051     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
7052
7053   // Ignore empty records.
7054   if (isEmptyRecord(getContext(), Ty, true))
7055     return ABIArgInfo::getIgnore();
7056
7057   uint64_t Size = getContext().getTypeSize(Ty);
7058   if (Size > 64)
7059     return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
7060     // Pass in the smallest viable integer type.
7061   else if (Size > 32)
7062       return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
7063   else if (Size > 16)
7064       return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
7065   else if (Size > 8)
7066       return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
7067   else
7068       return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
7069 }
7070
7071 ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
7072   if (RetTy->isVoidType())
7073     return ABIArgInfo::getIgnore();
7074
7075   // Large vector types should be returned via memory.
7076   if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 64)
7077     return getNaturalAlignIndirect(RetTy);
7078
7079   if (!isAggregateTypeForABI(RetTy)) {
7080     // Treat an enum type as its underlying type.
7081     if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
7082       RetTy = EnumTy->getDecl()->getIntegerType();
7083
7084     return (RetTy->isPromotableIntegerType() ?
7085             ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
7086   }
7087
7088   if (isEmptyRecord(getContext(), RetTy, true))
7089     return ABIArgInfo::getIgnore();
7090
7091   // Aggregates <= 8 bytes are returned in r0; other aggregates
7092   // are returned indirectly.
7093   uint64_t Size = getContext().getTypeSize(RetTy);
7094   if (Size <= 64) {
7095     // Return in the smallest viable integer type.
7096     if (Size <= 8)
7097       return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
7098     if (Size <= 16)
7099       return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
7100     if (Size <= 32)
7101       return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
7102     return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
7103   }
7104
7105   return getNaturalAlignIndirect(RetTy, /*ByVal=*/true);
7106 }
7107
7108 Address HexagonABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7109                                   QualType Ty) const {
7110   // FIXME: Someone needs to audit that this handle alignment correctly.
7111   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
7112                           getContext().getTypeInfoInChars(Ty),
7113                           CharUnits::fromQuantity(4),
7114                           /*AllowHigherAlign*/ true);
7115 }
7116
7117 //===----------------------------------------------------------------------===//
7118 // Lanai ABI Implementation
7119 //===----------------------------------------------------------------------===//
7120
7121 namespace {
7122 class LanaiABIInfo : public DefaultABIInfo {
7123 public:
7124   LanaiABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
7125
7126   bool shouldUseInReg(QualType Ty, CCState &State) const;
7127
7128   void computeInfo(CGFunctionInfo &FI) const override {
7129     CCState State(FI.getCallingConvention());
7130     // Lanai uses 4 registers to pass arguments unless the function has the
7131     // regparm attribute set.
7132     if (FI.getHasRegParm()) {
7133       State.FreeRegs = FI.getRegParm();
7134     } else {
7135       State.FreeRegs = 4;
7136     }
7137
7138     if (!getCXXABI().classifyReturnType(FI))
7139       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7140     for (auto &I : FI.arguments())
7141       I.info = classifyArgumentType(I.type, State);
7142   }
7143
7144   ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
7145   ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
7146 };
7147 } // end anonymous namespace
7148
7149 bool LanaiABIInfo::shouldUseInReg(QualType Ty, CCState &State) const {
7150   unsigned Size = getContext().getTypeSize(Ty);
7151   unsigned SizeInRegs = llvm::alignTo(Size, 32U) / 32U;
7152
7153   if (SizeInRegs == 0)
7154     return false;
7155
7156   if (SizeInRegs > State.FreeRegs) {
7157     State.FreeRegs = 0;
7158     return false;
7159   }
7160
7161   State.FreeRegs -= SizeInRegs;
7162
7163   return true;
7164 }
7165
7166 ABIArgInfo LanaiABIInfo::getIndirectResult(QualType Ty, bool ByVal,
7167                                            CCState &State) const {
7168   if (!ByVal) {
7169     if (State.FreeRegs) {
7170       --State.FreeRegs; // Non-byval indirects just use one pointer.
7171       return getNaturalAlignIndirectInReg(Ty);
7172     }
7173     return getNaturalAlignIndirect(Ty, false);
7174   }
7175
7176   // Compute the byval alignment.
7177   const unsigned MinABIStackAlignInBytes = 4;
7178   unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
7179   return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true,
7180                                  /*Realign=*/TypeAlign >
7181                                      MinABIStackAlignInBytes);
7182 }
7183
7184 ABIArgInfo LanaiABIInfo::classifyArgumentType(QualType Ty,
7185                                               CCState &State) const {
7186   // Check with the C++ ABI first.
7187   const RecordType *RT = Ty->getAs<RecordType>();
7188   if (RT) {
7189     CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
7190     if (RAA == CGCXXABI::RAA_Indirect) {
7191       return getIndirectResult(Ty, /*ByVal=*/false, State);
7192     } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
7193       return getNaturalAlignIndirect(Ty, /*ByRef=*/true);
7194     }
7195   }
7196
7197   if (isAggregateTypeForABI(Ty)) {
7198     // Structures with flexible arrays are always indirect.
7199     if (RT && RT->getDecl()->hasFlexibleArrayMember())
7200       return getIndirectResult(Ty, /*ByVal=*/true, State);
7201
7202     // Ignore empty structs/unions.
7203     if (isEmptyRecord(getContext(), Ty, true))
7204       return ABIArgInfo::getIgnore();
7205
7206     llvm::LLVMContext &LLVMContext = getVMContext();
7207     unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
7208     if (SizeInRegs <= State.FreeRegs) {
7209       llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
7210       SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32);
7211       llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
7212       State.FreeRegs -= SizeInRegs;
7213       return ABIArgInfo::getDirectInReg(Result);
7214     } else {
7215       State.FreeRegs = 0;
7216     }
7217     return getIndirectResult(Ty, true, State);
7218   }
7219
7220   // Treat an enum type as its underlying type.
7221   if (const auto *EnumTy = Ty->getAs<EnumType>())
7222     Ty = EnumTy->getDecl()->getIntegerType();
7223
7224   bool InReg = shouldUseInReg(Ty, State);
7225   if (Ty->isPromotableIntegerType()) {
7226     if (InReg)
7227       return ABIArgInfo::getDirectInReg();
7228     return ABIArgInfo::getExtend();
7229   }
7230   if (InReg)
7231     return ABIArgInfo::getDirectInReg();
7232   return ABIArgInfo::getDirect();
7233 }
7234
7235 namespace {
7236 class LanaiTargetCodeGenInfo : public TargetCodeGenInfo {
7237 public:
7238   LanaiTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
7239       : TargetCodeGenInfo(new LanaiABIInfo(CGT)) {}
7240 };
7241 }
7242
7243 //===----------------------------------------------------------------------===//
7244 // AMDGPU ABI Implementation
7245 //===----------------------------------------------------------------------===//
7246
7247 namespace {
7248
7249 class AMDGPUABIInfo final : public DefaultABIInfo {
7250 public:
7251   explicit AMDGPUABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
7252
7253 private:
7254   ABIArgInfo classifyArgumentType(QualType Ty) const;
7255
7256   void computeInfo(CGFunctionInfo &FI) const override;
7257 };
7258
7259 void AMDGPUABIInfo::computeInfo(CGFunctionInfo &FI) const {
7260   if (!getCXXABI().classifyReturnType(FI))
7261     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7262
7263   unsigned CC = FI.getCallingConvention();
7264   for (auto &Arg : FI.arguments())
7265     if (CC == llvm::CallingConv::AMDGPU_KERNEL)
7266       Arg.info = classifyArgumentType(Arg.type);
7267     else
7268       Arg.info = DefaultABIInfo::classifyArgumentType(Arg.type);
7269 }
7270
7271 /// \brief Classify argument of given type \p Ty.
7272 ABIArgInfo AMDGPUABIInfo::classifyArgumentType(QualType Ty) const {
7273   llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
7274   if (!StrTy) {
7275     return DefaultABIInfo::classifyArgumentType(Ty);
7276   }
7277
7278   // Coerce single element structs to its element.
7279   if (StrTy->getNumElements() == 1) {
7280     return ABIArgInfo::getDirect();
7281   }
7282
7283   // If we set CanBeFlattened to true, CodeGen will expand the struct to its
7284   // individual elements, which confuses the Clover OpenCL backend; therefore we
7285   // have to set it to false here. Other args of getDirect() are just defaults.
7286   return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
7287 }
7288
7289 class AMDGPUTargetCodeGenInfo : public TargetCodeGenInfo {
7290 public:
7291   AMDGPUTargetCodeGenInfo(CodeGenTypes &CGT)
7292     : TargetCodeGenInfo(new AMDGPUABIInfo(CGT)) {}
7293   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
7294                            CodeGen::CodeGenModule &M) const override;
7295   unsigned getOpenCLKernelCallingConv() const override;
7296
7297   llvm::Constant *getNullPointer(const CodeGen::CodeGenModule &CGM,
7298       llvm::PointerType *T, QualType QT) const override;
7299
7300   unsigned getASTAllocaAddressSpace() const override {
7301     return LangAS::FirstTargetAddressSpace +
7302            getABIInfo().getDataLayout().getAllocaAddrSpace();
7303   }
7304 };
7305 }
7306
7307 static void appendOpenCLVersionMD (CodeGen::CodeGenModule &CGM);
7308
7309 void AMDGPUTargetCodeGenInfo::setTargetAttributes(
7310     const Decl *D,
7311     llvm::GlobalValue *GV,
7312     CodeGen::CodeGenModule &M) const {
7313   const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
7314   if (!FD)
7315     return;
7316
7317   llvm::Function *F = cast<llvm::Function>(GV);
7318
7319   const auto *ReqdWGS = M.getLangOpts().OpenCL ?
7320     FD->getAttr<ReqdWorkGroupSizeAttr>() : nullptr;
7321   const auto *FlatWGS = FD->getAttr<AMDGPUFlatWorkGroupSizeAttr>();
7322   if (ReqdWGS || FlatWGS) {
7323     unsigned Min = FlatWGS ? FlatWGS->getMin() : 0;
7324     unsigned Max = FlatWGS ? FlatWGS->getMax() : 0;
7325     if (ReqdWGS && Min == 0 && Max == 0)
7326       Min = Max = ReqdWGS->getXDim() * ReqdWGS->getYDim() * ReqdWGS->getZDim();
7327
7328     if (Min != 0) {
7329       assert(Min <= Max && "Min must be less than or equal Max");
7330
7331       std::string AttrVal = llvm::utostr(Min) + "," + llvm::utostr(Max);
7332       F->addFnAttr("amdgpu-flat-work-group-size", AttrVal);
7333     } else
7334       assert(Max == 0 && "Max must be zero");
7335   }
7336
7337   if (const auto *Attr = FD->getAttr<AMDGPUWavesPerEUAttr>()) {
7338     unsigned Min = Attr->getMin();
7339     unsigned Max = Attr->getMax();
7340
7341     if (Min != 0) {
7342       assert((Max == 0 || Min <= Max) && "Min must be less than or equal Max");
7343
7344       std::string AttrVal = llvm::utostr(Min);
7345       if (Max != 0)
7346         AttrVal = AttrVal + "," + llvm::utostr(Max);
7347       F->addFnAttr("amdgpu-waves-per-eu", AttrVal);
7348     } else
7349       assert(Max == 0 && "Max must be zero");
7350   }
7351
7352   if (const auto *Attr = FD->getAttr<AMDGPUNumSGPRAttr>()) {
7353     unsigned NumSGPR = Attr->getNumSGPR();
7354
7355     if (NumSGPR != 0)
7356       F->addFnAttr("amdgpu-num-sgpr", llvm::utostr(NumSGPR));
7357   }
7358
7359   if (const auto *Attr = FD->getAttr<AMDGPUNumVGPRAttr>()) {
7360     uint32_t NumVGPR = Attr->getNumVGPR();
7361
7362     if (NumVGPR != 0)
7363       F->addFnAttr("amdgpu-num-vgpr", llvm::utostr(NumVGPR));
7364   }
7365
7366   appendOpenCLVersionMD(M);
7367 }
7368
7369 unsigned AMDGPUTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
7370   return llvm::CallingConv::AMDGPU_KERNEL;
7371 }
7372
7373 // Currently LLVM assumes null pointers always have value 0,
7374 // which results in incorrectly transformed IR. Therefore, instead of
7375 // emitting null pointers in private and local address spaces, a null
7376 // pointer in generic address space is emitted which is casted to a
7377 // pointer in local or private address space.
7378 llvm::Constant *AMDGPUTargetCodeGenInfo::getNullPointer(
7379     const CodeGen::CodeGenModule &CGM, llvm::PointerType *PT,
7380     QualType QT) const {
7381   if (CGM.getContext().getTargetNullPointerValue(QT) == 0)
7382     return llvm::ConstantPointerNull::get(PT);
7383
7384   auto &Ctx = CGM.getContext();
7385   auto NPT = llvm::PointerType::get(PT->getElementType(),
7386       Ctx.getTargetAddressSpace(LangAS::opencl_generic));
7387   return llvm::ConstantExpr::getAddrSpaceCast(
7388       llvm::ConstantPointerNull::get(NPT), PT);
7389 }
7390
7391 //===----------------------------------------------------------------------===//
7392 // SPARC v8 ABI Implementation.
7393 // Based on the SPARC Compliance Definition version 2.4.1.
7394 //
7395 // Ensures that complex values are passed in registers.
7396 //
7397 namespace {
7398 class SparcV8ABIInfo : public DefaultABIInfo {
7399 public:
7400   SparcV8ABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
7401
7402 private:
7403   ABIArgInfo classifyReturnType(QualType RetTy) const;
7404   void computeInfo(CGFunctionInfo &FI) const override;
7405 };
7406 } // end anonymous namespace
7407
7408
7409 ABIArgInfo
7410 SparcV8ABIInfo::classifyReturnType(QualType Ty) const {
7411   if (Ty->isAnyComplexType()) {
7412     return ABIArgInfo::getDirect();
7413   }
7414   else {
7415     return DefaultABIInfo::classifyReturnType(Ty);
7416   }
7417 }
7418
7419 void SparcV8ABIInfo::computeInfo(CGFunctionInfo &FI) const {
7420
7421   FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7422   for (auto &Arg : FI.arguments())
7423     Arg.info = classifyArgumentType(Arg.type);
7424 }
7425
7426 namespace {
7427 class SparcV8TargetCodeGenInfo : public TargetCodeGenInfo {
7428 public:
7429   SparcV8TargetCodeGenInfo(CodeGenTypes &CGT)
7430     : TargetCodeGenInfo(new SparcV8ABIInfo(CGT)) {}
7431 };
7432 } // end anonymous namespace
7433
7434 //===----------------------------------------------------------------------===//
7435 // SPARC v9 ABI Implementation.
7436 // Based on the SPARC Compliance Definition version 2.4.1.
7437 //
7438 // Function arguments a mapped to a nominal "parameter array" and promoted to
7439 // registers depending on their type. Each argument occupies 8 or 16 bytes in
7440 // the array, structs larger than 16 bytes are passed indirectly.
7441 //
7442 // One case requires special care:
7443 //
7444 //   struct mixed {
7445 //     int i;
7446 //     float f;
7447 //   };
7448 //
7449 // When a struct mixed is passed by value, it only occupies 8 bytes in the
7450 // parameter array, but the int is passed in an integer register, and the float
7451 // is passed in a floating point register. This is represented as two arguments
7452 // with the LLVM IR inreg attribute:
7453 //
7454 //   declare void f(i32 inreg %i, float inreg %f)
7455 //
7456 // The code generator will only allocate 4 bytes from the parameter array for
7457 // the inreg arguments. All other arguments are allocated a multiple of 8
7458 // bytes.
7459 //
7460 namespace {
7461 class SparcV9ABIInfo : public ABIInfo {
7462 public:
7463   SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
7464
7465 private:
7466   ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
7467   void computeInfo(CGFunctionInfo &FI) const override;
7468   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7469                     QualType Ty) const override;
7470
7471   // Coercion type builder for structs passed in registers. The coercion type
7472   // serves two purposes:
7473   //
7474   // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
7475   //    in registers.
7476   // 2. Expose aligned floating point elements as first-level elements, so the
7477   //    code generator knows to pass them in floating point registers.
7478   //
7479   // We also compute the InReg flag which indicates that the struct contains
7480   // aligned 32-bit floats.
7481   //
7482   struct CoerceBuilder {
7483     llvm::LLVMContext &Context;
7484     const llvm::DataLayout &DL;
7485     SmallVector<llvm::Type*, 8> Elems;
7486     uint64_t Size;
7487     bool InReg;
7488
7489     CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
7490       : Context(c), DL(dl), Size(0), InReg(false) {}
7491
7492     // Pad Elems with integers until Size is ToSize.
7493     void pad(uint64_t ToSize) {
7494       assert(ToSize >= Size && "Cannot remove elements");
7495       if (ToSize == Size)
7496         return;
7497
7498       // Finish the current 64-bit word.
7499       uint64_t Aligned = llvm::alignTo(Size, 64);
7500       if (Aligned > Size && Aligned <= ToSize) {
7501         Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
7502         Size = Aligned;
7503       }
7504
7505       // Add whole 64-bit words.
7506       while (Size + 64 <= ToSize) {
7507         Elems.push_back(llvm::Type::getInt64Ty(Context));
7508         Size += 64;
7509       }
7510
7511       // Final in-word padding.
7512       if (Size < ToSize) {
7513         Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
7514         Size = ToSize;
7515       }
7516     }
7517
7518     // Add a floating point element at Offset.
7519     void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
7520       // Unaligned floats are treated as integers.
7521       if (Offset % Bits)
7522         return;
7523       // The InReg flag is only required if there are any floats < 64 bits.
7524       if (Bits < 64)
7525         InReg = true;
7526       pad(Offset);
7527       Elems.push_back(Ty);
7528       Size = Offset + Bits;
7529     }
7530
7531     // Add a struct type to the coercion type, starting at Offset (in bits).
7532     void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
7533       const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
7534       for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
7535         llvm::Type *ElemTy = StrTy->getElementType(i);
7536         uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
7537         switch (ElemTy->getTypeID()) {
7538         case llvm::Type::StructTyID:
7539           addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
7540           break;
7541         case llvm::Type::FloatTyID:
7542           addFloat(ElemOffset, ElemTy, 32);
7543           break;
7544         case llvm::Type::DoubleTyID:
7545           addFloat(ElemOffset, ElemTy, 64);
7546           break;
7547         case llvm::Type::FP128TyID:
7548           addFloat(ElemOffset, ElemTy, 128);
7549           break;
7550         case llvm::Type::PointerTyID:
7551           if (ElemOffset % 64 == 0) {
7552             pad(ElemOffset);
7553             Elems.push_back(ElemTy);
7554             Size += 64;
7555           }
7556           break;
7557         default:
7558           break;
7559         }
7560       }
7561     }
7562
7563     // Check if Ty is a usable substitute for the coercion type.
7564     bool isUsableType(llvm::StructType *Ty) const {
7565       return llvm::makeArrayRef(Elems) == Ty->elements();
7566     }
7567
7568     // Get the coercion type as a literal struct type.
7569     llvm::Type *getType() const {
7570       if (Elems.size() == 1)
7571         return Elems.front();
7572       else
7573         return llvm::StructType::get(Context, Elems);
7574     }
7575   };
7576 };
7577 } // end anonymous namespace
7578
7579 ABIArgInfo
7580 SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
7581   if (Ty->isVoidType())
7582     return ABIArgInfo::getIgnore();
7583
7584   uint64_t Size = getContext().getTypeSize(Ty);
7585
7586   // Anything too big to fit in registers is passed with an explicit indirect
7587   // pointer / sret pointer.
7588   if (Size > SizeLimit)
7589     return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
7590
7591   // Treat an enum type as its underlying type.
7592   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7593     Ty = EnumTy->getDecl()->getIntegerType();
7594
7595   // Integer types smaller than a register are extended.
7596   if (Size < 64 && Ty->isIntegerType())
7597     return ABIArgInfo::getExtend();
7598
7599   // Other non-aggregates go in registers.
7600   if (!isAggregateTypeForABI(Ty))
7601     return ABIArgInfo::getDirect();
7602
7603   // If a C++ object has either a non-trivial copy constructor or a non-trivial
7604   // destructor, it is passed with an explicit indirect pointer / sret pointer.
7605   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
7606     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
7607
7608   // This is a small aggregate type that should be passed in registers.
7609   // Build a coercion type from the LLVM struct type.
7610   llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
7611   if (!StrTy)
7612     return ABIArgInfo::getDirect();
7613
7614   CoerceBuilder CB(getVMContext(), getDataLayout());
7615   CB.addStruct(0, StrTy);
7616   CB.pad(llvm::alignTo(CB.DL.getTypeSizeInBits(StrTy), 64));
7617
7618   // Try to use the original type for coercion.
7619   llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
7620
7621   if (CB.InReg)
7622     return ABIArgInfo::getDirectInReg(CoerceTy);
7623   else
7624     return ABIArgInfo::getDirect(CoerceTy);
7625 }
7626
7627 Address SparcV9ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7628                                   QualType Ty) const {
7629   ABIArgInfo AI = classifyType(Ty, 16 * 8);
7630   llvm::Type *ArgTy = CGT.ConvertType(Ty);
7631   if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
7632     AI.setCoerceToType(ArgTy);
7633
7634   CharUnits SlotSize = CharUnits::fromQuantity(8);
7635
7636   CGBuilderTy &Builder = CGF.Builder;
7637   Address Addr(Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
7638   llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
7639
7640   auto TypeInfo = getContext().getTypeInfoInChars(Ty);
7641
7642   Address ArgAddr = Address::invalid();
7643   CharUnits Stride;
7644   switch (AI.getKind()) {
7645   case ABIArgInfo::Expand:
7646   case ABIArgInfo::CoerceAndExpand:
7647   case ABIArgInfo::InAlloca:
7648     llvm_unreachable("Unsupported ABI kind for va_arg");
7649
7650   case ABIArgInfo::Extend: {
7651     Stride = SlotSize;
7652     CharUnits Offset = SlotSize - TypeInfo.first;
7653     ArgAddr = Builder.CreateConstInBoundsByteGEP(Addr, Offset, "extend");
7654     break;
7655   }
7656
7657   case ABIArgInfo::Direct: {
7658     auto AllocSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
7659     Stride = CharUnits::fromQuantity(AllocSize).alignTo(SlotSize);
7660     ArgAddr = Addr;
7661     break;
7662   }
7663
7664   case ABIArgInfo::Indirect:
7665     Stride = SlotSize;
7666     ArgAddr = Builder.CreateElementBitCast(Addr, ArgPtrTy, "indirect");
7667     ArgAddr = Address(Builder.CreateLoad(ArgAddr, "indirect.arg"),
7668                       TypeInfo.second);
7669     break;
7670
7671   case ABIArgInfo::Ignore:
7672     return Address(llvm::UndefValue::get(ArgPtrTy), TypeInfo.second);
7673   }
7674
7675   // Update VAList.
7676   llvm::Value *NextPtr =
7677     Builder.CreateConstInBoundsByteGEP(Addr.getPointer(), Stride, "ap.next");
7678   Builder.CreateStore(NextPtr, VAListAddr);
7679
7680   return Builder.CreateBitCast(ArgAddr, ArgPtrTy, "arg.addr");
7681 }
7682
7683 void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
7684   FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
7685   for (auto &I : FI.arguments())
7686     I.info = classifyType(I.type, 16 * 8);
7687 }
7688
7689 namespace {
7690 class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
7691 public:
7692   SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
7693     : TargetCodeGenInfo(new SparcV9ABIInfo(CGT)) {}
7694
7695   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
7696     return 14;
7697   }
7698
7699   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
7700                                llvm::Value *Address) const override;
7701 };
7702 } // end anonymous namespace
7703
7704 bool
7705 SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
7706                                                 llvm::Value *Address) const {
7707   // This is calculated from the LLVM and GCC tables and verified
7708   // against gcc output.  AFAIK all ABIs use the same encoding.
7709
7710   CodeGen::CGBuilderTy &Builder = CGF.Builder;
7711
7712   llvm::IntegerType *i8 = CGF.Int8Ty;
7713   llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
7714   llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
7715
7716   // 0-31: the 8-byte general-purpose registers
7717   AssignToArrayRange(Builder, Address, Eight8, 0, 31);
7718
7719   // 32-63: f0-31, the 4-byte floating-point registers
7720   AssignToArrayRange(Builder, Address, Four8, 32, 63);
7721
7722   //   Y   = 64
7723   //   PSR = 65
7724   //   WIM = 66
7725   //   TBR = 67
7726   //   PC  = 68
7727   //   NPC = 69
7728   //   FSR = 70
7729   //   CSR = 71
7730   AssignToArrayRange(Builder, Address, Eight8, 64, 71);
7731
7732   // 72-87: d0-15, the 8-byte floating-point registers
7733   AssignToArrayRange(Builder, Address, Eight8, 72, 87);
7734
7735   return false;
7736 }
7737
7738
7739 //===----------------------------------------------------------------------===//
7740 // XCore ABI Implementation
7741 //===----------------------------------------------------------------------===//
7742
7743 namespace {
7744
7745 /// A SmallStringEnc instance is used to build up the TypeString by passing
7746 /// it by reference between functions that append to it.
7747 typedef llvm::SmallString<128> SmallStringEnc;
7748
7749 /// TypeStringCache caches the meta encodings of Types.
7750 ///
7751 /// The reason for caching TypeStrings is two fold:
7752 ///   1. To cache a type's encoding for later uses;
7753 ///   2. As a means to break recursive member type inclusion.
7754 ///
7755 /// A cache Entry can have a Status of:
7756 ///   NonRecursive:   The type encoding is not recursive;
7757 ///   Recursive:      The type encoding is recursive;
7758 ///   Incomplete:     An incomplete TypeString;
7759 ///   IncompleteUsed: An incomplete TypeString that has been used in a
7760 ///                   Recursive type encoding.
7761 ///
7762 /// A NonRecursive entry will have all of its sub-members expanded as fully
7763 /// as possible. Whilst it may contain types which are recursive, the type
7764 /// itself is not recursive and thus its encoding may be safely used whenever
7765 /// the type is encountered.
7766 ///
7767 /// A Recursive entry will have all of its sub-members expanded as fully as
7768 /// possible. The type itself is recursive and it may contain other types which
7769 /// are recursive. The Recursive encoding must not be used during the expansion
7770 /// of a recursive type's recursive branch. For simplicity the code uses
7771 /// IncompleteCount to reject all usage of Recursive encodings for member types.
7772 ///
7773 /// An Incomplete entry is always a RecordType and only encodes its
7774 /// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and
7775 /// are placed into the cache during type expansion as a means to identify and
7776 /// handle recursive inclusion of types as sub-members. If there is recursion
7777 /// the entry becomes IncompleteUsed.
7778 ///
7779 /// During the expansion of a RecordType's members:
7780 ///
7781 ///   If the cache contains a NonRecursive encoding for the member type, the
7782 ///   cached encoding is used;
7783 ///
7784 ///   If the cache contains a Recursive encoding for the member type, the
7785 ///   cached encoding is 'Swapped' out, as it may be incorrect, and...
7786 ///
7787 ///   If the member is a RecordType, an Incomplete encoding is placed into the
7788 ///   cache to break potential recursive inclusion of itself as a sub-member;
7789 ///
7790 ///   Once a member RecordType has been expanded, its temporary incomplete
7791 ///   entry is removed from the cache. If a Recursive encoding was swapped out
7792 ///   it is swapped back in;
7793 ///
7794 ///   If an incomplete entry is used to expand a sub-member, the incomplete
7795 ///   entry is marked as IncompleteUsed. The cache keeps count of how many
7796 ///   IncompleteUsed entries it currently contains in IncompleteUsedCount;
7797 ///
7798 ///   If a member's encoding is found to be a NonRecursive or Recursive viz:
7799 ///   IncompleteUsedCount==0, the member's encoding is added to the cache.
7800 ///   Else the member is part of a recursive type and thus the recursion has
7801 ///   been exited too soon for the encoding to be correct for the member.
7802 ///
7803 class TypeStringCache {
7804   enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed};
7805   struct Entry {
7806     std::string Str;     // The encoded TypeString for the type.
7807     enum Status State;   // Information about the encoding in 'Str'.
7808     std::string Swapped; // A temporary place holder for a Recursive encoding
7809                          // during the expansion of RecordType's members.
7810   };
7811   std::map<const IdentifierInfo *, struct Entry> Map;
7812   unsigned IncompleteCount;     // Number of Incomplete entries in the Map.
7813   unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map.
7814 public:
7815   TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {}
7816   void addIncomplete(const IdentifierInfo *ID, std::string StubEnc);
7817   bool removeIncomplete(const IdentifierInfo *ID);
7818   void addIfComplete(const IdentifierInfo *ID, StringRef Str,
7819                      bool IsRecursive);
7820   StringRef lookupStr(const IdentifierInfo *ID);
7821 };
7822
7823 /// TypeString encodings for enum & union fields must be order.
7824 /// FieldEncoding is a helper for this ordering process.
7825 class FieldEncoding {
7826   bool HasName;
7827   std::string Enc;
7828 public:
7829   FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {}
7830   StringRef str() { return Enc; }
7831   bool operator<(const FieldEncoding &rhs) const {
7832     if (HasName != rhs.HasName) return HasName;
7833     return Enc < rhs.Enc;
7834   }
7835 };
7836
7837 class XCoreABIInfo : public DefaultABIInfo {
7838 public:
7839   XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
7840   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7841                     QualType Ty) const override;
7842 };
7843
7844 class XCoreTargetCodeGenInfo : public TargetCodeGenInfo {
7845   mutable TypeStringCache TSC;
7846 public:
7847   XCoreTargetCodeGenInfo(CodeGenTypes &CGT)
7848     :TargetCodeGenInfo(new XCoreABIInfo(CGT)) {}
7849   void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
7850                     CodeGen::CodeGenModule &M) const override;
7851 };
7852
7853 } // End anonymous namespace.
7854
7855 // TODO: this implementation is likely now redundant with the default
7856 // EmitVAArg.
7857 Address XCoreABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7858                                 QualType Ty) const {
7859   CGBuilderTy &Builder = CGF.Builder;
7860
7861   // Get the VAList.
7862   CharUnits SlotSize = CharUnits::fromQuantity(4);
7863   Address AP(Builder.CreateLoad(VAListAddr), SlotSize);
7864
7865   // Handle the argument.
7866   ABIArgInfo AI = classifyArgumentType(Ty);
7867   CharUnits TypeAlign = getContext().getTypeAlignInChars(Ty);
7868   llvm::Type *ArgTy = CGT.ConvertType(Ty);
7869   if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
7870     AI.setCoerceToType(ArgTy);
7871   llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
7872
7873   Address Val = Address::invalid();
7874   CharUnits ArgSize = CharUnits::Zero();
7875   switch (AI.getKind()) {
7876   case ABIArgInfo::Expand:
7877   case ABIArgInfo::CoerceAndExpand:
7878   case ABIArgInfo::InAlloca:
7879     llvm_unreachable("Unsupported ABI kind for va_arg");
7880   case ABIArgInfo::Ignore:
7881     Val = Address(llvm::UndefValue::get(ArgPtrTy), TypeAlign);
7882     ArgSize = CharUnits::Zero();
7883     break;
7884   case ABIArgInfo::Extend:
7885   case ABIArgInfo::Direct:
7886     Val = Builder.CreateBitCast(AP, ArgPtrTy);
7887     ArgSize = CharUnits::fromQuantity(
7888                        getDataLayout().getTypeAllocSize(AI.getCoerceToType()));
7889     ArgSize = ArgSize.alignTo(SlotSize);
7890     break;
7891   case ABIArgInfo::Indirect:
7892     Val = Builder.CreateElementBitCast(AP, ArgPtrTy);
7893     Val = Address(Builder.CreateLoad(Val), TypeAlign);
7894     ArgSize = SlotSize;
7895     break;
7896   }
7897
7898   // Increment the VAList.
7899   if (!ArgSize.isZero()) {
7900     llvm::Value *APN =
7901       Builder.CreateConstInBoundsByteGEP(AP.getPointer(), ArgSize);
7902     Builder.CreateStore(APN, VAListAddr);
7903   }
7904
7905   return Val;
7906 }
7907
7908 /// During the expansion of a RecordType, an incomplete TypeString is placed
7909 /// into the cache as a means to identify and break recursion.
7910 /// If there is a Recursive encoding in the cache, it is swapped out and will
7911 /// be reinserted by removeIncomplete().
7912 /// All other types of encoding should have been used rather than arriving here.
7913 void TypeStringCache::addIncomplete(const IdentifierInfo *ID,
7914                                     std::string StubEnc) {
7915   if (!ID)
7916     return;
7917   Entry &E = Map[ID];
7918   assert( (E.Str.empty() || E.State == Recursive) &&
7919          "Incorrectly use of addIncomplete");
7920   assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()");
7921   E.Swapped.swap(E.Str); // swap out the Recursive
7922   E.Str.swap(StubEnc);
7923   E.State = Incomplete;
7924   ++IncompleteCount;
7925 }
7926
7927 /// Once the RecordType has been expanded, the temporary incomplete TypeString
7928 /// must be removed from the cache.
7929 /// If a Recursive was swapped out by addIncomplete(), it will be replaced.
7930 /// Returns true if the RecordType was defined recursively.
7931 bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) {
7932   if (!ID)
7933     return false;
7934   auto I = Map.find(ID);
7935   assert(I != Map.end() && "Entry not present");
7936   Entry &E = I->second;
7937   assert( (E.State == Incomplete ||
7938            E.State == IncompleteUsed) &&
7939          "Entry must be an incomplete type");
7940   bool IsRecursive = false;
7941   if (E.State == IncompleteUsed) {
7942     // We made use of our Incomplete encoding, thus we are recursive.
7943     IsRecursive = true;
7944     --IncompleteUsedCount;
7945   }
7946   if (E.Swapped.empty())
7947     Map.erase(I);
7948   else {
7949     // Swap the Recursive back.
7950     E.Swapped.swap(E.Str);
7951     E.Swapped.clear();
7952     E.State = Recursive;
7953   }
7954   --IncompleteCount;
7955   return IsRecursive;
7956 }
7957
7958 /// Add the encoded TypeString to the cache only if it is NonRecursive or
7959 /// Recursive (viz: all sub-members were expanded as fully as possible).
7960 void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str,
7961                                     bool IsRecursive) {
7962   if (!ID || IncompleteUsedCount)
7963     return; // No key or it is is an incomplete sub-type so don't add.
7964   Entry &E = Map[ID];
7965   if (IsRecursive && !E.Str.empty()) {
7966     assert(E.State==Recursive && E.Str.size() == Str.size() &&
7967            "This is not the same Recursive entry");
7968     // The parent container was not recursive after all, so we could have used
7969     // this Recursive sub-member entry after all, but we assumed the worse when
7970     // we started viz: IncompleteCount!=0.
7971     return;
7972   }
7973   assert(E.Str.empty() && "Entry already present");
7974   E.Str = Str.str();
7975   E.State = IsRecursive? Recursive : NonRecursive;
7976 }
7977
7978 /// Return a cached TypeString encoding for the ID. If there isn't one, or we
7979 /// are recursively expanding a type (IncompleteCount != 0) and the cached
7980 /// encoding is Recursive, return an empty StringRef.
7981 StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) {
7982   if (!ID)
7983     return StringRef();   // We have no key.
7984   auto I = Map.find(ID);
7985   if (I == Map.end())
7986     return StringRef();   // We have no encoding.
7987   Entry &E = I->second;
7988   if (E.State == Recursive && IncompleteCount)
7989     return StringRef();   // We don't use Recursive encodings for member types.
7990
7991   if (E.State == Incomplete) {
7992     // The incomplete type is being used to break out of recursion.
7993     E.State = IncompleteUsed;
7994     ++IncompleteUsedCount;
7995   }
7996   return E.Str;
7997 }
7998
7999 /// The XCore ABI includes a type information section that communicates symbol
8000 /// type information to the linker. The linker uses this information to verify
8001 /// safety/correctness of things such as array bound and pointers et al.
8002 /// The ABI only requires C (and XC) language modules to emit TypeStrings.
8003 /// This type information (TypeString) is emitted into meta data for all global
8004 /// symbols: definitions, declarations, functions & variables.
8005 ///
8006 /// The TypeString carries type, qualifier, name, size & value details.
8007 /// Please see 'Tools Development Guide' section 2.16.2 for format details:
8008 /// https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf
8009 /// The output is tested by test/CodeGen/xcore-stringtype.c.
8010 ///
8011 static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
8012                           CodeGen::CodeGenModule &CGM, TypeStringCache &TSC);
8013
8014 /// XCore uses emitTargetMD to emit TypeString metadata for global symbols.
8015 void XCoreTargetCodeGenInfo::emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
8016                                           CodeGen::CodeGenModule &CGM) const {
8017   SmallStringEnc Enc;
8018   if (getTypeString(Enc, D, CGM, TSC)) {
8019     llvm::LLVMContext &Ctx = CGM.getModule().getContext();
8020     llvm::Metadata *MDVals[] = {llvm::ConstantAsMetadata::get(GV),
8021                                 llvm::MDString::get(Ctx, Enc.str())};
8022     llvm::NamedMDNode *MD =
8023       CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings");
8024     MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
8025   }
8026 }
8027
8028 //===----------------------------------------------------------------------===//
8029 // SPIR ABI Implementation
8030 //===----------------------------------------------------------------------===//
8031
8032 namespace {
8033 class SPIRTargetCodeGenInfo : public TargetCodeGenInfo {
8034 public:
8035   SPIRTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
8036     : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
8037   void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
8038                     CodeGen::CodeGenModule &M) const override;
8039   unsigned getOpenCLKernelCallingConv() const override;
8040 };
8041 } // End anonymous namespace.
8042
8043 /// Emit SPIR specific metadata: OpenCL and SPIR version.
8044 void SPIRTargetCodeGenInfo::emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
8045                                          CodeGen::CodeGenModule &CGM) const {
8046   llvm::LLVMContext &Ctx = CGM.getModule().getContext();
8047   llvm::Type *Int32Ty = llvm::Type::getInt32Ty(Ctx);
8048   llvm::Module &M = CGM.getModule();
8049   // SPIR v2.0 s2.12 - The SPIR version used by the module is stored in the
8050   // opencl.spir.version named metadata.
8051   llvm::Metadata *SPIRVerElts[] = {
8052       llvm::ConstantAsMetadata::get(
8053           llvm::ConstantInt::get(Int32Ty, CGM.getLangOpts().OpenCLVersion / 100)),
8054       llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
8055           Int32Ty, (CGM.getLangOpts().OpenCLVersion / 100 > 1) ? 0 : 2))};
8056   llvm::NamedMDNode *SPIRVerMD =
8057       M.getOrInsertNamedMetadata("opencl.spir.version");
8058   SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts));
8059   appendOpenCLVersionMD(CGM);
8060 }
8061
8062 static void appendOpenCLVersionMD(CodeGen::CodeGenModule &CGM) {
8063   llvm::LLVMContext &Ctx = CGM.getModule().getContext();
8064   llvm::Type *Int32Ty = llvm::Type::getInt32Ty(Ctx);
8065   llvm::Module &M = CGM.getModule();
8066   // SPIR v2.0 s2.13 - The OpenCL version used by the module is stored in the
8067   // opencl.ocl.version named metadata node.
8068   llvm::Metadata *OCLVerElts[] = {
8069       llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
8070           Int32Ty, CGM.getLangOpts().OpenCLVersion / 100)),
8071       llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
8072           Int32Ty, (CGM.getLangOpts().OpenCLVersion % 100) / 10))};
8073   llvm::NamedMDNode *OCLVerMD =
8074       M.getOrInsertNamedMetadata("opencl.ocl.version");
8075   OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts));
8076 }
8077
8078 unsigned SPIRTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
8079   return llvm::CallingConv::SPIR_KERNEL;
8080 }
8081
8082 static bool appendType(SmallStringEnc &Enc, QualType QType,
8083                        const CodeGen::CodeGenModule &CGM,
8084                        TypeStringCache &TSC);
8085
8086 /// Helper function for appendRecordType().
8087 /// Builds a SmallVector containing the encoded field types in declaration
8088 /// order.
8089 static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE,
8090                              const RecordDecl *RD,
8091                              const CodeGen::CodeGenModule &CGM,
8092                              TypeStringCache &TSC) {
8093   for (const auto *Field : RD->fields()) {
8094     SmallStringEnc Enc;
8095     Enc += "m(";
8096     Enc += Field->getName();
8097     Enc += "){";
8098     if (Field->isBitField()) {
8099       Enc += "b(";
8100       llvm::raw_svector_ostream OS(Enc);
8101       OS << Field->getBitWidthValue(CGM.getContext());
8102       Enc += ':';
8103     }
8104     if (!appendType(Enc, Field->getType(), CGM, TSC))
8105       return false;
8106     if (Field->isBitField())
8107       Enc += ')';
8108     Enc += '}';
8109     FE.emplace_back(!Field->getName().empty(), Enc);
8110   }
8111   return true;
8112 }
8113
8114 /// Appends structure and union types to Enc and adds encoding to cache.
8115 /// Recursively calls appendType (via extractFieldType) for each field.
8116 /// Union types have their fields ordered according to the ABI.
8117 static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT,
8118                              const CodeGen::CodeGenModule &CGM,
8119                              TypeStringCache &TSC, const IdentifierInfo *ID) {
8120   // Append the cached TypeString if we have one.
8121   StringRef TypeString = TSC.lookupStr(ID);
8122   if (!TypeString.empty()) {
8123     Enc += TypeString;
8124     return true;
8125   }
8126
8127   // Start to emit an incomplete TypeString.
8128   size_t Start = Enc.size();
8129   Enc += (RT->isUnionType()? 'u' : 's');
8130   Enc += '(';
8131   if (ID)
8132     Enc += ID->getName();
8133   Enc += "){";
8134
8135   // We collect all encoded fields and order as necessary.
8136   bool IsRecursive = false;
8137   const RecordDecl *RD = RT->getDecl()->getDefinition();
8138   if (RD && !RD->field_empty()) {
8139     // An incomplete TypeString stub is placed in the cache for this RecordType
8140     // so that recursive calls to this RecordType will use it whilst building a
8141     // complete TypeString for this RecordType.
8142     SmallVector<FieldEncoding, 16> FE;
8143     std::string StubEnc(Enc.substr(Start).str());
8144     StubEnc += '}';  // StubEnc now holds a valid incomplete TypeString.
8145     TSC.addIncomplete(ID, std::move(StubEnc));
8146     if (!extractFieldType(FE, RD, CGM, TSC)) {
8147       (void) TSC.removeIncomplete(ID);
8148       return false;
8149     }
8150     IsRecursive = TSC.removeIncomplete(ID);
8151     // The ABI requires unions to be sorted but not structures.
8152     // See FieldEncoding::operator< for sort algorithm.
8153     if (RT->isUnionType())
8154       std::sort(FE.begin(), FE.end());
8155     // We can now complete the TypeString.
8156     unsigned E = FE.size();
8157     for (unsigned I = 0; I != E; ++I) {
8158       if (I)
8159         Enc += ',';
8160       Enc += FE[I].str();
8161     }
8162   }
8163   Enc += '}';
8164   TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive);
8165   return true;
8166 }
8167
8168 /// Appends enum types to Enc and adds the encoding to the cache.
8169 static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET,
8170                            TypeStringCache &TSC,
8171                            const IdentifierInfo *ID) {
8172   // Append the cached TypeString if we have one.
8173   StringRef TypeString = TSC.lookupStr(ID);
8174   if (!TypeString.empty()) {
8175     Enc += TypeString;
8176     return true;
8177   }
8178
8179   size_t Start = Enc.size();
8180   Enc += "e(";
8181   if (ID)
8182     Enc += ID->getName();
8183   Enc += "){";
8184
8185   // We collect all encoded enumerations and order them alphanumerically.
8186   if (const EnumDecl *ED = ET->getDecl()->getDefinition()) {
8187     SmallVector<FieldEncoding, 16> FE;
8188     for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E;
8189          ++I) {
8190       SmallStringEnc EnumEnc;
8191       EnumEnc += "m(";
8192       EnumEnc += I->getName();
8193       EnumEnc += "){";
8194       I->getInitVal().toString(EnumEnc);
8195       EnumEnc += '}';
8196       FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc));
8197     }
8198     std::sort(FE.begin(), FE.end());
8199     unsigned E = FE.size();
8200     for (unsigned I = 0; I != E; ++I) {
8201       if (I)
8202         Enc += ',';
8203       Enc += FE[I].str();
8204     }
8205   }
8206   Enc += '}';
8207   TSC.addIfComplete(ID, Enc.substr(Start), false);
8208   return true;
8209 }
8210
8211 /// Appends type's qualifier to Enc.
8212 /// This is done prior to appending the type's encoding.
8213 static void appendQualifier(SmallStringEnc &Enc, QualType QT) {
8214   // Qualifiers are emitted in alphabetical order.
8215   static const char *const Table[]={"","c:","r:","cr:","v:","cv:","rv:","crv:"};
8216   int Lookup = 0;
8217   if (QT.isConstQualified())
8218     Lookup += 1<<0;
8219   if (QT.isRestrictQualified())
8220     Lookup += 1<<1;
8221   if (QT.isVolatileQualified())
8222     Lookup += 1<<2;
8223   Enc += Table[Lookup];
8224 }
8225
8226 /// Appends built-in types to Enc.
8227 static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) {
8228   const char *EncType;
8229   switch (BT->getKind()) {
8230     case BuiltinType::Void:
8231       EncType = "0";
8232       break;
8233     case BuiltinType::Bool:
8234       EncType = "b";
8235       break;
8236     case BuiltinType::Char_U:
8237       EncType = "uc";
8238       break;
8239     case BuiltinType::UChar:
8240       EncType = "uc";
8241       break;
8242     case BuiltinType::SChar:
8243       EncType = "sc";
8244       break;
8245     case BuiltinType::UShort:
8246       EncType = "us";
8247       break;
8248     case BuiltinType::Short:
8249       EncType = "ss";
8250       break;
8251     case BuiltinType::UInt:
8252       EncType = "ui";
8253       break;
8254     case BuiltinType::Int:
8255       EncType = "si";
8256       break;
8257     case BuiltinType::ULong:
8258       EncType = "ul";
8259       break;
8260     case BuiltinType::Long:
8261       EncType = "sl";
8262       break;
8263     case BuiltinType::ULongLong:
8264       EncType = "ull";
8265       break;
8266     case BuiltinType::LongLong:
8267       EncType = "sll";
8268       break;
8269     case BuiltinType::Float:
8270       EncType = "ft";
8271       break;
8272     case BuiltinType::Double:
8273       EncType = "d";
8274       break;
8275     case BuiltinType::LongDouble:
8276       EncType = "ld";
8277       break;
8278     default:
8279       return false;
8280   }
8281   Enc += EncType;
8282   return true;
8283 }
8284
8285 /// Appends a pointer encoding to Enc before calling appendType for the pointee.
8286 static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT,
8287                               const CodeGen::CodeGenModule &CGM,
8288                               TypeStringCache &TSC) {
8289   Enc += "p(";
8290   if (!appendType(Enc, PT->getPointeeType(), CGM, TSC))
8291     return false;
8292   Enc += ')';
8293   return true;
8294 }
8295
8296 /// Appends array encoding to Enc before calling appendType for the element.
8297 static bool appendArrayType(SmallStringEnc &Enc, QualType QT,
8298                             const ArrayType *AT,
8299                             const CodeGen::CodeGenModule &CGM,
8300                             TypeStringCache &TSC, StringRef NoSizeEnc) {
8301   if (AT->getSizeModifier() != ArrayType::Normal)
8302     return false;
8303   Enc += "a(";
8304   if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
8305     CAT->getSize().toStringUnsigned(Enc);
8306   else
8307     Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "".
8308   Enc += ':';
8309   // The Qualifiers should be attached to the type rather than the array.
8310   appendQualifier(Enc, QT);
8311   if (!appendType(Enc, AT->getElementType(), CGM, TSC))
8312     return false;
8313   Enc += ')';
8314   return true;
8315 }
8316
8317 /// Appends a function encoding to Enc, calling appendType for the return type
8318 /// and the arguments.
8319 static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT,
8320                              const CodeGen::CodeGenModule &CGM,
8321                              TypeStringCache &TSC) {
8322   Enc += "f{";
8323   if (!appendType(Enc, FT->getReturnType(), CGM, TSC))
8324     return false;
8325   Enc += "}(";
8326   if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) {
8327     // N.B. we are only interested in the adjusted param types.
8328     auto I = FPT->param_type_begin();
8329     auto E = FPT->param_type_end();
8330     if (I != E) {
8331       do {
8332         if (!appendType(Enc, *I, CGM, TSC))
8333           return false;
8334         ++I;
8335         if (I != E)
8336           Enc += ',';
8337       } while (I != E);
8338       if (FPT->isVariadic())
8339         Enc += ",va";
8340     } else {
8341       if (FPT->isVariadic())
8342         Enc += "va";
8343       else
8344         Enc += '0';
8345     }
8346   }
8347   Enc += ')';
8348   return true;
8349 }
8350
8351 /// Handles the type's qualifier before dispatching a call to handle specific
8352 /// type encodings.
8353 static bool appendType(SmallStringEnc &Enc, QualType QType,
8354                        const CodeGen::CodeGenModule &CGM,
8355                        TypeStringCache &TSC) {
8356
8357   QualType QT = QType.getCanonicalType();
8358
8359   if (const ArrayType *AT = QT->getAsArrayTypeUnsafe())
8360     // The Qualifiers should be attached to the type rather than the array.
8361     // Thus we don't call appendQualifier() here.
8362     return appendArrayType(Enc, QT, AT, CGM, TSC, "");
8363
8364   appendQualifier(Enc, QT);
8365
8366   if (const BuiltinType *BT = QT->getAs<BuiltinType>())
8367     return appendBuiltinType(Enc, BT);
8368
8369   if (const PointerType *PT = QT->getAs<PointerType>())
8370     return appendPointerType(Enc, PT, CGM, TSC);
8371
8372   if (const EnumType *ET = QT->getAs<EnumType>())
8373     return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier());
8374
8375   if (const RecordType *RT = QT->getAsStructureType())
8376     return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
8377
8378   if (const RecordType *RT = QT->getAsUnionType())
8379     return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
8380
8381   if (const FunctionType *FT = QT->getAs<FunctionType>())
8382     return appendFunctionType(Enc, FT, CGM, TSC);
8383
8384   return false;
8385 }
8386
8387 static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
8388                           CodeGen::CodeGenModule &CGM, TypeStringCache &TSC) {
8389   if (!D)
8390     return false;
8391
8392   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8393     if (FD->getLanguageLinkage() != CLanguageLinkage)
8394       return false;
8395     return appendType(Enc, FD->getType(), CGM, TSC);
8396   }
8397
8398   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
8399     if (VD->getLanguageLinkage() != CLanguageLinkage)
8400       return false;
8401     QualType QT = VD->getType().getCanonicalType();
8402     if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) {
8403       // Global ArrayTypes are given a size of '*' if the size is unknown.
8404       // The Qualifiers should be attached to the type rather than the array.
8405       // Thus we don't call appendQualifier() here.
8406       return appendArrayType(Enc, QT, AT, CGM, TSC, "*");
8407     }
8408     return appendType(Enc, QT, CGM, TSC);
8409   }
8410   return false;
8411 }
8412
8413
8414 //===----------------------------------------------------------------------===//
8415 // Driver code
8416 //===----------------------------------------------------------------------===//
8417
8418 bool CodeGenModule::supportsCOMDAT() const {
8419   return getTriple().supportsCOMDAT();
8420 }
8421
8422 const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
8423   if (TheTargetCodeGenInfo)
8424     return *TheTargetCodeGenInfo;
8425
8426   // Helper to set the unique_ptr while still keeping the return value.
8427   auto SetCGInfo = [&](TargetCodeGenInfo *P) -> const TargetCodeGenInfo & {
8428     this->TheTargetCodeGenInfo.reset(P);
8429     return *P;
8430   };
8431
8432   const llvm::Triple &Triple = getTarget().getTriple();
8433   switch (Triple.getArch()) {
8434   default:
8435     return SetCGInfo(new DefaultTargetCodeGenInfo(Types));
8436
8437   case llvm::Triple::le32:
8438     return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
8439   case llvm::Triple::mips:
8440   case llvm::Triple::mipsel:
8441     if (Triple.getOS() == llvm::Triple::NaCl)
8442       return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
8443     return SetCGInfo(new MIPSTargetCodeGenInfo(Types, true));
8444
8445   case llvm::Triple::mips64:
8446   case llvm::Triple::mips64el:
8447     return SetCGInfo(new MIPSTargetCodeGenInfo(Types, false));
8448
8449   case llvm::Triple::avr:
8450     return SetCGInfo(new AVRTargetCodeGenInfo(Types));
8451
8452   case llvm::Triple::aarch64:
8453   case llvm::Triple::aarch64_be: {
8454     AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS;
8455     if (getTarget().getABI() == "darwinpcs")
8456       Kind = AArch64ABIInfo::DarwinPCS;
8457
8458     return SetCGInfo(new AArch64TargetCodeGenInfo(Types, Kind));
8459   }
8460
8461   case llvm::Triple::wasm32:
8462   case llvm::Triple::wasm64:
8463     return SetCGInfo(new WebAssemblyTargetCodeGenInfo(Types));
8464
8465   case llvm::Triple::arm:
8466   case llvm::Triple::armeb:
8467   case llvm::Triple::thumb:
8468   case llvm::Triple::thumbeb: {
8469     if (Triple.getOS() == llvm::Triple::Win32) {
8470       return SetCGInfo(
8471           new WindowsARMTargetCodeGenInfo(Types, ARMABIInfo::AAPCS_VFP));
8472     }
8473
8474     ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
8475     StringRef ABIStr = getTarget().getABI();
8476     if (ABIStr == "apcs-gnu")
8477       Kind = ARMABIInfo::APCS;
8478     else if (ABIStr == "aapcs16")
8479       Kind = ARMABIInfo::AAPCS16_VFP;
8480     else if (CodeGenOpts.FloatABI == "hard" ||
8481              (CodeGenOpts.FloatABI != "soft" &&
8482               (Triple.getEnvironment() == llvm::Triple::GNUEABIHF ||
8483                Triple.getEnvironment() == llvm::Triple::MuslEABIHF ||
8484                Triple.getEnvironment() == llvm::Triple::EABIHF)))
8485       Kind = ARMABIInfo::AAPCS_VFP;
8486
8487     return SetCGInfo(new ARMTargetCodeGenInfo(Types, Kind));
8488   }
8489
8490   case llvm::Triple::ppc:
8491     return SetCGInfo(
8492         new PPC32TargetCodeGenInfo(Types, CodeGenOpts.FloatABI == "soft"));
8493   case llvm::Triple::ppc64:
8494     if (Triple.isOSBinFormatELF()) {
8495       PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1;
8496       if (getTarget().getABI() == "elfv2")
8497         Kind = PPC64_SVR4_ABIInfo::ELFv2;
8498       bool HasQPX = getTarget().getABI() == "elfv1-qpx";
8499       bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
8500
8501       return SetCGInfo(new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX,
8502                                                         IsSoftFloat));
8503     } else
8504       return SetCGInfo(new PPC64TargetCodeGenInfo(Types));
8505   case llvm::Triple::ppc64le: {
8506     assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
8507     PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2;
8508     if (getTarget().getABI() == "elfv1" || getTarget().getABI() == "elfv1-qpx")
8509       Kind = PPC64_SVR4_ABIInfo::ELFv1;
8510     bool HasQPX = getTarget().getABI() == "elfv1-qpx";
8511     bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
8512
8513     return SetCGInfo(new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX,
8514                                                       IsSoftFloat));
8515   }
8516
8517   case llvm::Triple::nvptx:
8518   case llvm::Triple::nvptx64:
8519     return SetCGInfo(new NVPTXTargetCodeGenInfo(Types));
8520
8521   case llvm::Triple::msp430:
8522     return SetCGInfo(new MSP430TargetCodeGenInfo(Types));
8523
8524   case llvm::Triple::systemz: {
8525     bool HasVector = getTarget().getABI() == "vector";
8526     return SetCGInfo(new SystemZTargetCodeGenInfo(Types, HasVector));
8527   }
8528
8529   case llvm::Triple::tce:
8530   case llvm::Triple::tcele:
8531     return SetCGInfo(new TCETargetCodeGenInfo(Types));
8532
8533   case llvm::Triple::x86: {
8534     bool IsDarwinVectorABI = Triple.isOSDarwin();
8535     bool RetSmallStructInRegABI =
8536         X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
8537     bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
8538
8539     if (Triple.getOS() == llvm::Triple::Win32) {
8540       return SetCGInfo(new WinX86_32TargetCodeGenInfo(
8541           Types, IsDarwinVectorABI, RetSmallStructInRegABI,
8542           IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters));
8543     } else {
8544       return SetCGInfo(new X86_32TargetCodeGenInfo(
8545           Types, IsDarwinVectorABI, RetSmallStructInRegABI,
8546           IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters,
8547           CodeGenOpts.FloatABI == "soft"));
8548     }
8549   }
8550
8551   case llvm::Triple::x86_64: {
8552     StringRef ABI = getTarget().getABI();
8553     X86AVXABILevel AVXLevel =
8554         (ABI == "avx512"
8555              ? X86AVXABILevel::AVX512
8556              : ABI == "avx" ? X86AVXABILevel::AVX : X86AVXABILevel::None);
8557
8558     switch (Triple.getOS()) {
8559     case llvm::Triple::Win32:
8560       return SetCGInfo(new WinX86_64TargetCodeGenInfo(Types, AVXLevel));
8561     case llvm::Triple::PS4:
8562       return SetCGInfo(new PS4TargetCodeGenInfo(Types, AVXLevel));
8563     default:
8564       return SetCGInfo(new X86_64TargetCodeGenInfo(Types, AVXLevel));
8565     }
8566   }
8567   case llvm::Triple::hexagon:
8568     return SetCGInfo(new HexagonTargetCodeGenInfo(Types));
8569   case llvm::Triple::lanai:
8570     return SetCGInfo(new LanaiTargetCodeGenInfo(Types));
8571   case llvm::Triple::r600:
8572     return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
8573   case llvm::Triple::amdgcn:
8574     return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
8575   case llvm::Triple::sparc:
8576     return SetCGInfo(new SparcV8TargetCodeGenInfo(Types));
8577   case llvm::Triple::sparcv9:
8578     return SetCGInfo(new SparcV9TargetCodeGenInfo(Types));
8579   case llvm::Triple::xcore:
8580     return SetCGInfo(new XCoreTargetCodeGenInfo(Types));
8581   case llvm::Triple::spir:
8582   case llvm::Triple::spir64:
8583     return SetCGInfo(new SPIRTargetCodeGenInfo(Types));
8584   }
8585 }