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