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