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