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