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