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