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