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   unsigned NumRequiredArgs = FI.getNumRequiredArgs();
2572   // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
2573   // get assigned (in left-to-right order) for passing as follows...
2574   unsigned ArgNo = 0;
2575   for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
2576        it != ie; ++it, ++ArgNo) {
2577     bool IsNamedArg = ArgNo < NumRequiredArgs;
2578 
2579     unsigned neededInt, neededSSE;
2580     it->info = classifyArgumentType(it->type, freeIntRegs, neededInt,
2581                                     neededSSE, IsNamedArg);
2582 
2583     // AMD64-ABI 3.2.3p3: If there are no registers available for any
2584     // eightbyte of an argument, the whole argument is passed on the
2585     // stack. If registers have already been assigned for some
2586     // eightbytes of such an argument, the assignments get reverted.
2587     if (freeIntRegs >= neededInt && freeSSERegs >= neededSSE) {
2588       freeIntRegs -= neededInt;
2589       freeSSERegs -= neededSSE;
2590     } else {
2591       it->info = getIndirectResult(it->type, freeIntRegs);
2592     }
2593   }
2594 }
2595 
2596 static llvm::Value *EmitVAArgFromMemory(llvm::Value *VAListAddr,
2597                                         QualType Ty,
2598                                         CodeGenFunction &CGF) {
2599   llvm::Value *overflow_arg_area_p =
2600     CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_p");
2601   llvm::Value *overflow_arg_area =
2602     CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
2603 
2604   // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
2605   // byte boundary if alignment needed by type exceeds 8 byte boundary.
2606   // It isn't stated explicitly in the standard, but in practice we use
2607   // alignment greater than 16 where necessary.
2608   uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8;
2609   if (Align > 8) {
2610     // overflow_arg_area = (overflow_arg_area + align - 1) & -align;
2611     llvm::Value *Offset =
2612       llvm::ConstantInt::get(CGF.Int64Ty, Align - 1);
2613     overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset);
2614     llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(overflow_arg_area,
2615                                                     CGF.Int64Ty);
2616     llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int64Ty, -(uint64_t)Align);
2617     overflow_arg_area =
2618       CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask),
2619                                  overflow_arg_area->getType(),
2620                                  "overflow_arg_area.align");
2621   }
2622 
2623   // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
2624   llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
2625   llvm::Value *Res =
2626     CGF.Builder.CreateBitCast(overflow_arg_area,
2627                               llvm::PointerType::getUnqual(LTy));
2628 
2629   // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
2630   // l->overflow_arg_area + sizeof(type).
2631   // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
2632   // an 8 byte boundary.
2633 
2634   uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
2635   llvm::Value *Offset =
2636       llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7)  & ~7);
2637   overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
2638                                             "overflow_arg_area.next");
2639   CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
2640 
2641   // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
2642   return Res;
2643 }
2644 
2645 llvm::Value *X86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2646                                       CodeGenFunction &CGF) const {
2647   // Assume that va_list type is correct; should be pointer to LLVM type:
2648   // struct {
2649   //   i32 gp_offset;
2650   //   i32 fp_offset;
2651   //   i8* overflow_arg_area;
2652   //   i8* reg_save_area;
2653   // };
2654   unsigned neededInt, neededSSE;
2655 
2656   Ty = CGF.getContext().getCanonicalType(Ty);
2657   ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
2658                                        /*isNamedArg*/false);
2659 
2660   // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
2661   // in the registers. If not go to step 7.
2662   if (!neededInt && !neededSSE)
2663     return EmitVAArgFromMemory(VAListAddr, Ty, CGF);
2664 
2665   // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
2666   // general purpose registers needed to pass type and num_fp to hold
2667   // the number of floating point registers needed.
2668 
2669   // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
2670   // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
2671   // l->fp_offset > 304 - num_fp * 16 go to step 7.
2672   //
2673   // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
2674   // register save space).
2675 
2676   llvm::Value *InRegs = nullptr;
2677   llvm::Value *gp_offset_p = nullptr, *gp_offset = nullptr;
2678   llvm::Value *fp_offset_p = nullptr, *fp_offset = nullptr;
2679   if (neededInt) {
2680     gp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "gp_offset_p");
2681     gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
2682     InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
2683     InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
2684   }
2685 
2686   if (neededSSE) {
2687     fp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 1, "fp_offset_p");
2688     fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
2689     llvm::Value *FitsInFP =
2690       llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
2691     FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
2692     InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
2693   }
2694 
2695   llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
2696   llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
2697   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
2698   CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
2699 
2700   // Emit code to load the value if it was passed in registers.
2701 
2702   CGF.EmitBlock(InRegBlock);
2703 
2704   // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
2705   // an offset of l->gp_offset and/or l->fp_offset. This may require
2706   // copying to a temporary location in case the parameter is passed
2707   // in different register classes or requires an alignment greater
2708   // than 8 for general purpose registers and 16 for XMM registers.
2709   //
2710   // FIXME: This really results in shameful code when we end up needing to
2711   // collect arguments from different places; often what should result in a
2712   // simple assembling of a structure from scattered addresses has many more
2713   // loads than necessary. Can we clean this up?
2714   llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
2715   llvm::Value *RegAddr =
2716     CGF.Builder.CreateLoad(CGF.Builder.CreateStructGEP(VAListAddr, 3),
2717                            "reg_save_area");
2718   if (neededInt && neededSSE) {
2719     // FIXME: Cleanup.
2720     assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
2721     llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
2722     llvm::Value *Tmp = CGF.CreateMemTemp(Ty);
2723     Tmp = CGF.Builder.CreateBitCast(Tmp, ST->getPointerTo());
2724     assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
2725     llvm::Type *TyLo = ST->getElementType(0);
2726     llvm::Type *TyHi = ST->getElementType(1);
2727     assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
2728            "Unexpected ABI info for mixed regs");
2729     llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
2730     llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
2731     llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
2732     llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
2733     llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr;
2734     llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr;
2735     llvm::Value *V =
2736       CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegLoAddr, PTyLo));
2737     CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
2738     V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegHiAddr, PTyHi));
2739     CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
2740 
2741     RegAddr = CGF.Builder.CreateBitCast(Tmp,
2742                                         llvm::PointerType::getUnqual(LTy));
2743   } else if (neededInt) {
2744     RegAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
2745     RegAddr = CGF.Builder.CreateBitCast(RegAddr,
2746                                         llvm::PointerType::getUnqual(LTy));
2747 
2748     // Copy to a temporary if necessary to ensure the appropriate alignment.
2749     std::pair<CharUnits, CharUnits> SizeAlign =
2750         CGF.getContext().getTypeInfoInChars(Ty);
2751     uint64_t TySize = SizeAlign.first.getQuantity();
2752     unsigned TyAlign = SizeAlign.second.getQuantity();
2753     if (TyAlign > 8) {
2754       llvm::Value *Tmp = CGF.CreateMemTemp(Ty);
2755       CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, 8, false);
2756       RegAddr = Tmp;
2757     }
2758   } else if (neededSSE == 1) {
2759     RegAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
2760     RegAddr = CGF.Builder.CreateBitCast(RegAddr,
2761                                         llvm::PointerType::getUnqual(LTy));
2762   } else {
2763     assert(neededSSE == 2 && "Invalid number of needed registers!");
2764     // SSE registers are spaced 16 bytes apart in the register save
2765     // area, we need to collect the two eightbytes together.
2766     llvm::Value *RegAddrLo = CGF.Builder.CreateGEP(RegAddr, fp_offset);
2767     llvm::Value *RegAddrHi = CGF.Builder.CreateConstGEP1_32(RegAddrLo, 16);
2768     llvm::Type *DoubleTy = CGF.DoubleTy;
2769     llvm::Type *DblPtrTy =
2770       llvm::PointerType::getUnqual(DoubleTy);
2771     llvm::StructType *ST = llvm::StructType::get(DoubleTy, DoubleTy, NULL);
2772     llvm::Value *V, *Tmp = CGF.CreateMemTemp(Ty);
2773     Tmp = CGF.Builder.CreateBitCast(Tmp, ST->getPointerTo());
2774     V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrLo,
2775                                                          DblPtrTy));
2776     CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
2777     V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrHi,
2778                                                          DblPtrTy));
2779     CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
2780     RegAddr = CGF.Builder.CreateBitCast(Tmp,
2781                                         llvm::PointerType::getUnqual(LTy));
2782   }
2783 
2784   // AMD64-ABI 3.5.7p5: Step 5. Set:
2785   // l->gp_offset = l->gp_offset + num_gp * 8
2786   // l->fp_offset = l->fp_offset + num_fp * 16.
2787   if (neededInt) {
2788     llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
2789     CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
2790                             gp_offset_p);
2791   }
2792   if (neededSSE) {
2793     llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
2794     CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
2795                             fp_offset_p);
2796   }
2797   CGF.EmitBranch(ContBlock);
2798 
2799   // Emit code to load the value if it was passed in memory.
2800 
2801   CGF.EmitBlock(InMemBlock);
2802   llvm::Value *MemAddr = EmitVAArgFromMemory(VAListAddr, Ty, CGF);
2803 
2804   // Return the appropriate result.
2805 
2806   CGF.EmitBlock(ContBlock);
2807   llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(RegAddr->getType(), 2,
2808                                                  "vaarg.addr");
2809   ResAddr->addIncoming(RegAddr, InRegBlock);
2810   ResAddr->addIncoming(MemAddr, InMemBlock);
2811   return ResAddr;
2812 }
2813 
2814 ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, bool IsReturnType) const {
2815 
2816   if (Ty->isVoidType())
2817     return ABIArgInfo::getIgnore();
2818 
2819   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2820     Ty = EnumTy->getDecl()->getIntegerType();
2821 
2822   uint64_t Size = getContext().getTypeSize(Ty);
2823 
2824   const RecordType *RT = Ty->getAs<RecordType>();
2825   if (RT) {
2826     if (!IsReturnType) {
2827       if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
2828         return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
2829     }
2830 
2831     if (RT->getDecl()->hasFlexibleArrayMember())
2832       return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
2833 
2834     // FIXME: mingw-w64-gcc emits 128-bit struct as i128
2835     if (Size == 128 && getTarget().getTriple().isWindowsGNUEnvironment())
2836       return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2837                                                           Size));
2838   }
2839 
2840   if (Ty->isMemberPointerType()) {
2841     // If the member pointer is represented by an LLVM int or ptr, pass it
2842     // directly.
2843     llvm::Type *LLTy = CGT.ConvertType(Ty);
2844     if (LLTy->isPointerTy() || LLTy->isIntegerTy())
2845       return ABIArgInfo::getDirect();
2846   }
2847 
2848   if (RT || Ty->isMemberPointerType()) {
2849     // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
2850     // not 1, 2, 4, or 8 bytes, must be passed by reference."
2851     if (Size > 64 || !llvm::isPowerOf2_64(Size))
2852       return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
2853 
2854     // Otherwise, coerce it to a small integer.
2855     return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
2856   }
2857 
2858   // Bool type is always extended to the ABI, other builtin types are not
2859   // extended.
2860   const BuiltinType *BT = Ty->getAs<BuiltinType>();
2861   if (BT && BT->getKind() == BuiltinType::Bool)
2862     return ABIArgInfo::getExtend();
2863 
2864   return ABIArgInfo::getDirect();
2865 }
2866 
2867 void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
2868   if (!getCXXABI().classifyReturnType(FI))
2869     FI.getReturnInfo() = classify(FI.getReturnType(), true);
2870 
2871   for (auto &I : FI.arguments())
2872     I.info = classify(I.type, false);
2873 }
2874 
2875 llvm::Value *WinX86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2876                                       CodeGenFunction &CGF) const {
2877   llvm::Type *BPP = CGF.Int8PtrPtrTy;
2878 
2879   CGBuilderTy &Builder = CGF.Builder;
2880   llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
2881                                                        "ap");
2882   llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
2883   llvm::Type *PTy =
2884     llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
2885   llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
2886 
2887   uint64_t Offset =
2888     llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 8);
2889   llvm::Value *NextAddr =
2890     Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
2891                       "ap.next");
2892   Builder.CreateStore(NextAddr, VAListAddrAsBPP);
2893 
2894   return AddrTyped;
2895 }
2896 
2897 namespace {
2898 
2899 class NaClX86_64ABIInfo : public ABIInfo {
2900  public:
2901   NaClX86_64ABIInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX)
2902       : ABIInfo(CGT), PInfo(CGT), NInfo(CGT, HasAVX) {}
2903   void computeInfo(CGFunctionInfo &FI) const override;
2904   llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2905                          CodeGenFunction &CGF) const override;
2906  private:
2907   PNaClABIInfo PInfo;  // Used for generating calls with pnaclcall callingconv.
2908   X86_64ABIInfo NInfo; // Used for everything else.
2909 };
2910 
2911 class NaClX86_64TargetCodeGenInfo : public TargetCodeGenInfo  {
2912  public:
2913   NaClX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX)
2914       : TargetCodeGenInfo(new NaClX86_64ABIInfo(CGT, HasAVX)) {}
2915 };
2916 
2917 }
2918 
2919 void NaClX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
2920   if (FI.getASTCallingConvention() == CC_PnaclCall)
2921     PInfo.computeInfo(FI);
2922   else
2923     NInfo.computeInfo(FI);
2924 }
2925 
2926 llvm::Value *NaClX86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2927                                           CodeGenFunction &CGF) const {
2928   // Always use the native convention; calling pnacl-style varargs functions
2929   // is unuspported.
2930   return NInfo.EmitVAArg(VAListAddr, Ty, CGF);
2931 }
2932 
2933 
2934 // PowerPC-32
2935 
2936 namespace {
2937 class PPC32TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
2938 public:
2939   PPC32TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
2940 
2941   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
2942     // This is recovered from gcc output.
2943     return 1; // r1 is the dedicated stack pointer
2944   }
2945 
2946   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2947                                llvm::Value *Address) const override;
2948 };
2949 
2950 }
2951 
2952 bool
2953 PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2954                                                 llvm::Value *Address) const {
2955   // This is calculated from the LLVM and GCC tables and verified
2956   // against gcc output.  AFAIK all ABIs use the same encoding.
2957 
2958   CodeGen::CGBuilderTy &Builder = CGF.Builder;
2959 
2960   llvm::IntegerType *i8 = CGF.Int8Ty;
2961   llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
2962   llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
2963   llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
2964 
2965   // 0-31: r0-31, the 4-byte general-purpose registers
2966   AssignToArrayRange(Builder, Address, Four8, 0, 31);
2967 
2968   // 32-63: fp0-31, the 8-byte floating-point registers
2969   AssignToArrayRange(Builder, Address, Eight8, 32, 63);
2970 
2971   // 64-76 are various 4-byte special-purpose registers:
2972   // 64: mq
2973   // 65: lr
2974   // 66: ctr
2975   // 67: ap
2976   // 68-75 cr0-7
2977   // 76: xer
2978   AssignToArrayRange(Builder, Address, Four8, 64, 76);
2979 
2980   // 77-108: v0-31, the 16-byte vector registers
2981   AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
2982 
2983   // 109: vrsave
2984   // 110: vscr
2985   // 111: spe_acc
2986   // 112: spefscr
2987   // 113: sfp
2988   AssignToArrayRange(Builder, Address, Four8, 109, 113);
2989 
2990   return false;
2991 }
2992 
2993 // PowerPC-64
2994 
2995 namespace {
2996 /// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
2997 class PPC64_SVR4_ABIInfo : public DefaultABIInfo {
2998 public:
2999   enum ABIKind {
3000     ELFv1 = 0,
3001     ELFv2
3002   };
3003 
3004 private:
3005   static const unsigned GPRBits = 64;
3006   ABIKind Kind;
3007 
3008 public:
3009   PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind)
3010     : DefaultABIInfo(CGT), Kind(Kind) {}
3011 
3012   bool isPromotableTypeForABI(QualType Ty) const;
3013   bool isAlignedParamType(QualType Ty) const;
3014   bool isHomogeneousAggregate(QualType Ty, const Type *&Base,
3015                               uint64_t &Members) const;
3016 
3017   ABIArgInfo classifyReturnType(QualType RetTy) const;
3018   ABIArgInfo classifyArgumentType(QualType Ty) const;
3019 
3020   // TODO: We can add more logic to computeInfo to improve performance.
3021   // Example: For aggregate arguments that fit in a register, we could
3022   // use getDirectInReg (as is done below for structs containing a single
3023   // floating-point value) to avoid pushing them to memory on function
3024   // entry.  This would require changing the logic in PPCISelLowering
3025   // when lowering the parameters in the caller and args in the callee.
3026   void computeInfo(CGFunctionInfo &FI) const override {
3027     if (!getCXXABI().classifyReturnType(FI))
3028       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
3029     for (auto &I : FI.arguments()) {
3030       // We rely on the default argument classification for the most part.
3031       // One exception:  An aggregate containing a single floating-point
3032       // or vector item must be passed in a register if one is available.
3033       const Type *T = isSingleElementStruct(I.type, getContext());
3034       if (T) {
3035         const BuiltinType *BT = T->getAs<BuiltinType>();
3036         if ((T->isVectorType() && getContext().getTypeSize(T) == 128) ||
3037             (BT && BT->isFloatingPoint())) {
3038           QualType QT(T, 0);
3039           I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
3040           continue;
3041         }
3042       }
3043       I.info = classifyArgumentType(I.type);
3044     }
3045   }
3046 
3047   llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3048                          CodeGenFunction &CGF) const override;
3049 };
3050 
3051 class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
3052 public:
3053   PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT,
3054                                PPC64_SVR4_ABIInfo::ABIKind Kind)
3055     : TargetCodeGenInfo(new PPC64_SVR4_ABIInfo(CGT, Kind)) {}
3056 
3057   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
3058     // This is recovered from gcc output.
3059     return 1; // r1 is the dedicated stack pointer
3060   }
3061 
3062   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3063                                llvm::Value *Address) const override;
3064 };
3065 
3066 class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
3067 public:
3068   PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
3069 
3070   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
3071     // This is recovered from gcc output.
3072     return 1; // r1 is the dedicated stack pointer
3073   }
3074 
3075   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3076                                llvm::Value *Address) const override;
3077 };
3078 
3079 }
3080 
3081 // Return true if the ABI requires Ty to be passed sign- or zero-
3082 // extended to 64 bits.
3083 bool
3084 PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
3085   // Treat an enum type as its underlying type.
3086   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3087     Ty = EnumTy->getDecl()->getIntegerType();
3088 
3089   // Promotable integer types are required to be promoted by the ABI.
3090   if (Ty->isPromotableIntegerType())
3091     return true;
3092 
3093   // In addition to the usual promotable integer types, we also need to
3094   // extend all 32-bit types, since the ABI requires promotion to 64 bits.
3095   if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
3096     switch (BT->getKind()) {
3097     case BuiltinType::Int:
3098     case BuiltinType::UInt:
3099       return true;
3100     default:
3101       break;
3102     }
3103 
3104   return false;
3105 }
3106 
3107 /// isAlignedParamType - Determine whether a type requires 16-byte
3108 /// alignment in the parameter area.
3109 bool
3110 PPC64_SVR4_ABIInfo::isAlignedParamType(QualType Ty) const {
3111   // Complex types are passed just like their elements.
3112   if (const ComplexType *CTy = Ty->getAs<ComplexType>())
3113     Ty = CTy->getElementType();
3114 
3115   // Only vector types of size 16 bytes need alignment (larger types are
3116   // passed via reference, smaller types are not aligned).
3117   if (Ty->isVectorType())
3118     return getContext().getTypeSize(Ty) == 128;
3119 
3120   // For single-element float/vector structs, we consider the whole type
3121   // to have the same alignment requirements as its single element.
3122   const Type *AlignAsType = nullptr;
3123   const Type *EltType = isSingleElementStruct(Ty, getContext());
3124   if (EltType) {
3125     const BuiltinType *BT = EltType->getAs<BuiltinType>();
3126     if ((EltType->isVectorType() &&
3127          getContext().getTypeSize(EltType) == 128) ||
3128         (BT && BT->isFloatingPoint()))
3129       AlignAsType = EltType;
3130   }
3131 
3132   // Likewise for ELFv2 homogeneous aggregates.
3133   const Type *Base = nullptr;
3134   uint64_t Members = 0;
3135   if (!AlignAsType && Kind == ELFv2 &&
3136       isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members))
3137     AlignAsType = Base;
3138 
3139   // With special case aggregates, only vector base types need alignment.
3140   if (AlignAsType)
3141     return AlignAsType->isVectorType();
3142 
3143   // Otherwise, we only need alignment for any aggregate type that
3144   // has an alignment requirement of >= 16 bytes.
3145   if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128)
3146     return true;
3147 
3148   return false;
3149 }
3150 
3151 /// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous
3152 /// aggregate.  Base is set to the base element type, and Members is set
3153 /// to the number of base elements.
3154 bool
3155 PPC64_SVR4_ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base,
3156                                            uint64_t &Members) const {
3157   if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
3158     uint64_t NElements = AT->getSize().getZExtValue();
3159     if (NElements == 0)
3160       return false;
3161     if (!isHomogeneousAggregate(AT->getElementType(), Base, Members))
3162       return false;
3163     Members *= NElements;
3164   } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
3165     const RecordDecl *RD = RT->getDecl();
3166     if (RD->hasFlexibleArrayMember())
3167       return false;
3168 
3169     Members = 0;
3170     for (const auto *FD : RD->fields()) {
3171       // Ignore (non-zero arrays of) empty records.
3172       QualType FT = FD->getType();
3173       while (const ConstantArrayType *AT =
3174              getContext().getAsConstantArrayType(FT)) {
3175         if (AT->getSize().getZExtValue() == 0)
3176           return false;
3177         FT = AT->getElementType();
3178       }
3179       if (isEmptyRecord(getContext(), FT, true))
3180         continue;
3181 
3182       // For compatibility with GCC, ignore empty bitfields in C++ mode.
3183       if (getContext().getLangOpts().CPlusPlus &&
3184           FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
3185         continue;
3186 
3187       uint64_t FldMembers;
3188       if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers))
3189         return false;
3190 
3191       Members = (RD->isUnion() ?
3192                  std::max(Members, FldMembers) : Members + FldMembers);
3193     }
3194 
3195     if (!Base)
3196       return false;
3197 
3198     // Ensure there is no padding.
3199     if (getContext().getTypeSize(Base) * Members !=
3200         getContext().getTypeSize(Ty))
3201       return false;
3202   } else {
3203     Members = 1;
3204     if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
3205       Members = 2;
3206       Ty = CT->getElementType();
3207     }
3208 
3209     // Homogeneous aggregates for ELFv2 must have base types of float,
3210     // double, long double, or 128-bit vectors.
3211     if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
3212       if (BT->getKind() != BuiltinType::Float &&
3213           BT->getKind() != BuiltinType::Double &&
3214           BT->getKind() != BuiltinType::LongDouble)
3215         return false;
3216     } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
3217       if (getContext().getTypeSize(VT) != 128)
3218         return false;
3219     } else {
3220       return false;
3221     }
3222 
3223     // The base type must be the same for all members.  Types that
3224     // agree in both total size and mode (float vs. vector) are
3225     // treated as being equivalent here.
3226     const Type *TyPtr = Ty.getTypePtr();
3227     if (!Base)
3228       Base = TyPtr;
3229 
3230     if (Base->isVectorType() != TyPtr->isVectorType() ||
3231         getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr))
3232       return false;
3233   }
3234 
3235   // Vector types require one register, floating point types require one
3236   // or two registers depending on their size.
3237   uint32_t NumRegs = Base->isVectorType() ? 1 :
3238                        (getContext().getTypeSize(Base) + 63) / 64;
3239 
3240   // Homogeneous Aggregates may occupy at most 8 registers.
3241   return (Members > 0 && Members * NumRegs <= 8);
3242 }
3243 
3244 ABIArgInfo
3245 PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
3246   if (Ty->isAnyComplexType())
3247     return ABIArgInfo::getDirect();
3248 
3249   // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes)
3250   // or via reference (larger than 16 bytes).
3251   if (Ty->isVectorType()) {
3252     uint64_t Size = getContext().getTypeSize(Ty);
3253     if (Size > 128)
3254       return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3255     else if (Size < 128) {
3256       llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
3257       return ABIArgInfo::getDirect(CoerceTy);
3258     }
3259   }
3260 
3261   if (isAggregateTypeForABI(Ty)) {
3262     if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
3263       return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
3264 
3265     uint64_t ABIAlign = isAlignedParamType(Ty)? 16 : 8;
3266     uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8;
3267 
3268     // ELFv2 homogeneous aggregates are passed as array types.
3269     const Type *Base = nullptr;
3270     uint64_t Members = 0;
3271     if (Kind == ELFv2 &&
3272         isHomogeneousAggregate(Ty, Base, Members)) {
3273       llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
3274       llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
3275       return ABIArgInfo::getDirect(CoerceTy);
3276     }
3277 
3278     // If an aggregate may end up fully in registers, we do not
3279     // use the ByVal method, but pass the aggregate as array.
3280     // This is usually beneficial since we avoid forcing the
3281     // back-end to store the argument to memory.
3282     uint64_t Bits = getContext().getTypeSize(Ty);
3283     if (Bits > 0 && Bits <= 8 * GPRBits) {
3284       llvm::Type *CoerceTy;
3285 
3286       // Types up to 8 bytes are passed as integer type (which will be
3287       // properly aligned in the argument save area doubleword).
3288       if (Bits <= GPRBits)
3289         CoerceTy = llvm::IntegerType::get(getVMContext(),
3290                                           llvm::RoundUpToAlignment(Bits, 8));
3291       // Larger types are passed as arrays, with the base type selected
3292       // according to the required alignment in the save area.
3293       else {
3294         uint64_t RegBits = ABIAlign * 8;
3295         uint64_t NumRegs = llvm::RoundUpToAlignment(Bits, RegBits) / RegBits;
3296         llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits);
3297         CoerceTy = llvm::ArrayType::get(RegTy, NumRegs);
3298       }
3299 
3300       return ABIArgInfo::getDirect(CoerceTy);
3301     }
3302 
3303     // All other aggregates are passed ByVal.
3304     return ABIArgInfo::getIndirect(ABIAlign, /*ByVal=*/true,
3305                                    /*Realign=*/TyAlign > ABIAlign);
3306   }
3307 
3308   return (isPromotableTypeForABI(Ty) ?
3309           ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
3310 }
3311 
3312 ABIArgInfo
3313 PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
3314   if (RetTy->isVoidType())
3315     return ABIArgInfo::getIgnore();
3316 
3317   if (RetTy->isAnyComplexType())
3318     return ABIArgInfo::getDirect();
3319 
3320   // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes)
3321   // or via reference (larger than 16 bytes).
3322   if (RetTy->isVectorType()) {
3323     uint64_t Size = getContext().getTypeSize(RetTy);
3324     if (Size > 128)
3325       return ABIArgInfo::getIndirect(0);
3326     else if (Size < 128) {
3327       llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
3328       return ABIArgInfo::getDirect(CoerceTy);
3329     }
3330   }
3331 
3332   if (isAggregateTypeForABI(RetTy)) {
3333     // ELFv2 homogeneous aggregates are returned as array types.
3334     const Type *Base = nullptr;
3335     uint64_t Members = 0;
3336     if (Kind == ELFv2 &&
3337         isHomogeneousAggregate(RetTy, Base, Members)) {
3338       llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
3339       llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
3340       return ABIArgInfo::getDirect(CoerceTy);
3341     }
3342 
3343     // ELFv2 small aggregates are returned in up to two registers.
3344     uint64_t Bits = getContext().getTypeSize(RetTy);
3345     if (Kind == ELFv2 && Bits <= 2 * GPRBits) {
3346       if (Bits == 0)
3347         return ABIArgInfo::getIgnore();
3348 
3349       llvm::Type *CoerceTy;
3350       if (Bits > GPRBits) {
3351         CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits);
3352         CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy, NULL);
3353       } else
3354         CoerceTy = llvm::IntegerType::get(getVMContext(),
3355                                           llvm::RoundUpToAlignment(Bits, 8));
3356       return ABIArgInfo::getDirect(CoerceTy);
3357     }
3358 
3359     // All other aggregates are returned indirectly.
3360     return ABIArgInfo::getIndirect(0);
3361   }
3362 
3363   return (isPromotableTypeForABI(RetTy) ?
3364           ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
3365 }
3366 
3367 // Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
3368 llvm::Value *PPC64_SVR4_ABIInfo::EmitVAArg(llvm::Value *VAListAddr,
3369                                            QualType Ty,
3370                                            CodeGenFunction &CGF) const {
3371   llvm::Type *BP = CGF.Int8PtrTy;
3372   llvm::Type *BPP = CGF.Int8PtrPtrTy;
3373 
3374   CGBuilderTy &Builder = CGF.Builder;
3375   llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
3376   llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
3377 
3378   // Handle types that require 16-byte alignment in the parameter save area.
3379   if (isAlignedParamType(Ty)) {
3380     llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
3381     AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt64(15));
3382     AddrAsInt = Builder.CreateAnd(AddrAsInt, Builder.getInt64(-16));
3383     Addr = Builder.CreateIntToPtr(AddrAsInt, BP, "ap.align");
3384   }
3385 
3386   // Update the va_list pointer.  The pointer should be bumped by the
3387   // size of the object.  We can trust getTypeSize() except for a complex
3388   // type whose base type is smaller than a doubleword.  For these, the
3389   // size of the object is 16 bytes; see below for further explanation.
3390   unsigned SizeInBytes = CGF.getContext().getTypeSize(Ty) / 8;
3391   QualType BaseTy;
3392   unsigned CplxBaseSize = 0;
3393 
3394   if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
3395     BaseTy = CTy->getElementType();
3396     CplxBaseSize = CGF.getContext().getTypeSize(BaseTy) / 8;
3397     if (CplxBaseSize < 8)
3398       SizeInBytes = 16;
3399   }
3400 
3401   unsigned Offset = llvm::RoundUpToAlignment(SizeInBytes, 8);
3402   llvm::Value *NextAddr =
3403     Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int64Ty, Offset),
3404                       "ap.next");
3405   Builder.CreateStore(NextAddr, VAListAddrAsBPP);
3406 
3407   // If we have a complex type and the base type is smaller than 8 bytes,
3408   // the ABI calls for the real and imaginary parts to be right-adjusted
3409   // in separate doublewords.  However, Clang expects us to produce a
3410   // pointer to a structure with the two parts packed tightly.  So generate
3411   // loads of the real and imaginary parts relative to the va_list pointer,
3412   // and store them to a temporary structure.
3413   if (CplxBaseSize && CplxBaseSize < 8) {
3414     llvm::Value *RealAddr = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
3415     llvm::Value *ImagAddr = RealAddr;
3416     if (CGF.CGM.getDataLayout().isBigEndian()) {
3417       RealAddr = Builder.CreateAdd(RealAddr, Builder.getInt64(8 - CplxBaseSize));
3418       ImagAddr = Builder.CreateAdd(ImagAddr, Builder.getInt64(16 - CplxBaseSize));
3419     } else {
3420       ImagAddr = Builder.CreateAdd(ImagAddr, Builder.getInt64(8));
3421     }
3422     llvm::Type *PBaseTy = llvm::PointerType::getUnqual(CGF.ConvertType(BaseTy));
3423     RealAddr = Builder.CreateIntToPtr(RealAddr, PBaseTy);
3424     ImagAddr = Builder.CreateIntToPtr(ImagAddr, PBaseTy);
3425     llvm::Value *Real = Builder.CreateLoad(RealAddr, false, ".vareal");
3426     llvm::Value *Imag = Builder.CreateLoad(ImagAddr, false, ".vaimag");
3427     llvm::Value *Ptr = CGF.CreateTempAlloca(CGT.ConvertTypeForMem(Ty),
3428                                             "vacplx");
3429     llvm::Value *RealPtr = Builder.CreateStructGEP(Ptr, 0, ".real");
3430     llvm::Value *ImagPtr = Builder.CreateStructGEP(Ptr, 1, ".imag");
3431     Builder.CreateStore(Real, RealPtr, false);
3432     Builder.CreateStore(Imag, ImagPtr, false);
3433     return Ptr;
3434   }
3435 
3436   // If the argument is smaller than 8 bytes, it is right-adjusted in
3437   // its doubleword slot.  Adjust the pointer to pick it up from the
3438   // correct offset.
3439   if (SizeInBytes < 8 && CGF.CGM.getDataLayout().isBigEndian()) {
3440     llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
3441     AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt64(8 - SizeInBytes));
3442     Addr = Builder.CreateIntToPtr(AddrAsInt, BP);
3443   }
3444 
3445   llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
3446   return Builder.CreateBitCast(Addr, PTy);
3447 }
3448 
3449 static bool
3450 PPC64_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3451                               llvm::Value *Address) {
3452   // This is calculated from the LLVM and GCC tables and verified
3453   // against gcc output.  AFAIK all ABIs use the same encoding.
3454 
3455   CodeGen::CGBuilderTy &Builder = CGF.Builder;
3456 
3457   llvm::IntegerType *i8 = CGF.Int8Ty;
3458   llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
3459   llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
3460   llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
3461 
3462   // 0-31: r0-31, the 8-byte general-purpose registers
3463   AssignToArrayRange(Builder, Address, Eight8, 0, 31);
3464 
3465   // 32-63: fp0-31, the 8-byte floating-point registers
3466   AssignToArrayRange(Builder, Address, Eight8, 32, 63);
3467 
3468   // 64-76 are various 4-byte special-purpose registers:
3469   // 64: mq
3470   // 65: lr
3471   // 66: ctr
3472   // 67: ap
3473   // 68-75 cr0-7
3474   // 76: xer
3475   AssignToArrayRange(Builder, Address, Four8, 64, 76);
3476 
3477   // 77-108: v0-31, the 16-byte vector registers
3478   AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
3479 
3480   // 109: vrsave
3481   // 110: vscr
3482   // 111: spe_acc
3483   // 112: spefscr
3484   // 113: sfp
3485   AssignToArrayRange(Builder, Address, Four8, 109, 113);
3486 
3487   return false;
3488 }
3489 
3490 bool
3491 PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
3492   CodeGen::CodeGenFunction &CGF,
3493   llvm::Value *Address) const {
3494 
3495   return PPC64_initDwarfEHRegSizeTable(CGF, Address);
3496 }
3497 
3498 bool
3499 PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3500                                                 llvm::Value *Address) const {
3501 
3502   return PPC64_initDwarfEHRegSizeTable(CGF, Address);
3503 }
3504 
3505 //===----------------------------------------------------------------------===//
3506 // AArch64 ABI Implementation
3507 //===----------------------------------------------------------------------===//
3508 
3509 namespace {
3510 
3511 class AArch64ABIInfo : public ABIInfo {
3512 public:
3513   enum ABIKind {
3514     AAPCS = 0,
3515     DarwinPCS
3516   };
3517 
3518 private:
3519   ABIKind Kind;
3520 
3521 public:
3522   AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind) : ABIInfo(CGT), Kind(Kind) {}
3523 
3524 private:
3525   ABIKind getABIKind() const { return Kind; }
3526   bool isDarwinPCS() const { return Kind == DarwinPCS; }
3527 
3528   ABIArgInfo classifyReturnType(QualType RetTy) const;
3529   ABIArgInfo classifyArgumentType(QualType RetTy, unsigned &AllocatedVFP,
3530                                   bool &IsHA, unsigned &AllocatedGPR,
3531                                   bool &IsSmallAggr, bool IsNamedArg) const;
3532   bool isIllegalVectorType(QualType Ty) const;
3533 
3534   virtual void computeInfo(CGFunctionInfo &FI) const {
3535     // To correctly handle Homogeneous Aggregate, we need to keep track of the
3536     // number of SIMD and Floating-point registers allocated so far.
3537     // If the argument is an HFA or an HVA and there are sufficient unallocated
3538     // SIMD and Floating-point registers, then the argument is allocated to SIMD
3539     // and Floating-point Registers (with one register per member of the HFA or
3540     // HVA). Otherwise, the NSRN is set to 8.
3541     unsigned AllocatedVFP = 0;
3542 
3543     // To correctly handle small aggregates, we need to keep track of the number
3544     // of GPRs allocated so far. If the small aggregate can't all fit into
3545     // registers, it will be on stack. We don't allow the aggregate to be
3546     // partially in registers.
3547     unsigned AllocatedGPR = 0;
3548 
3549     // Find the number of named arguments. Variadic arguments get special
3550     // treatment with the Darwin ABI.
3551     unsigned NumRequiredArgs = FI.getNumRequiredArgs();
3552 
3553     if (!getCXXABI().classifyReturnType(FI))
3554       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
3555     unsigned ArgNo = 0;
3556     for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
3557          it != ie; ++it, ++ArgNo) {
3558       unsigned PreAllocation = AllocatedVFP, PreGPR = AllocatedGPR;
3559       bool IsHA = false, IsSmallAggr = false;
3560       const unsigned NumVFPs = 8;
3561       const unsigned NumGPRs = 8;
3562       bool IsNamedArg = ArgNo < NumRequiredArgs;
3563       it->info = classifyArgumentType(it->type, AllocatedVFP, IsHA,
3564                                       AllocatedGPR, IsSmallAggr, IsNamedArg);
3565 
3566       // Under AAPCS the 64-bit stack slot alignment means we can't pass HAs
3567       // as sequences of floats since they'll get "holes" inserted as
3568       // padding by the back end.
3569       if (IsHA && AllocatedVFP > NumVFPs && !isDarwinPCS() &&
3570           getContext().getTypeAlign(it->type) < 64) {
3571         uint32_t NumStackSlots = getContext().getTypeSize(it->type);
3572         NumStackSlots = llvm::RoundUpToAlignment(NumStackSlots, 64) / 64;
3573 
3574         llvm::Type *CoerceTy = llvm::ArrayType::get(
3575             llvm::Type::getDoubleTy(getVMContext()), NumStackSlots);
3576         it->info = ABIArgInfo::getDirect(CoerceTy);
3577       }
3578 
3579       // If we do not have enough VFP registers for the HA, any VFP registers
3580       // that are unallocated are marked as unavailable. To achieve this, we add
3581       // padding of (NumVFPs - PreAllocation) floats.
3582       if (IsHA && AllocatedVFP > NumVFPs && PreAllocation < NumVFPs) {
3583         llvm::Type *PaddingTy = llvm::ArrayType::get(
3584             llvm::Type::getFloatTy(getVMContext()), NumVFPs - PreAllocation);
3585         it->info.setPaddingType(PaddingTy);
3586       }
3587 
3588       // If we do not have enough GPRs for the small aggregate, any GPR regs
3589       // that are unallocated are marked as unavailable.
3590       if (IsSmallAggr && AllocatedGPR > NumGPRs && PreGPR < NumGPRs) {
3591         llvm::Type *PaddingTy = llvm::ArrayType::get(
3592             llvm::Type::getInt32Ty(getVMContext()), NumGPRs - PreGPR);
3593         it->info =
3594             ABIArgInfo::getDirect(it->info.getCoerceToType(), 0, PaddingTy);
3595       }
3596     }
3597   }
3598 
3599   llvm::Value *EmitDarwinVAArg(llvm::Value *VAListAddr, QualType Ty,
3600                                CodeGenFunction &CGF) const;
3601 
3602   llvm::Value *EmitAAPCSVAArg(llvm::Value *VAListAddr, QualType Ty,
3603                               CodeGenFunction &CGF) const;
3604 
3605   virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3606                                  CodeGenFunction &CGF) const {
3607     return isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF)
3608                          : EmitAAPCSVAArg(VAListAddr, Ty, CGF);
3609   }
3610 };
3611 
3612 class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
3613 public:
3614   AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind)
3615       : TargetCodeGenInfo(new AArch64ABIInfo(CGT, Kind)) {}
3616 
3617   StringRef getARCRetainAutoreleasedReturnValueMarker() const {
3618     return "mov\tfp, fp\t\t; marker for objc_retainAutoreleaseReturnValue";
3619   }
3620 
3621   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const { return 31; }
3622 
3623   virtual bool doesReturnSlotInterfereWithArgs() const { return false; }
3624 };
3625 }
3626 
3627 static bool isARMHomogeneousAggregate(QualType Ty, const Type *&Base,
3628                                    ASTContext &Context,
3629                                    bool isAArch64,
3630                                    uint64_t *HAMembers = nullptr);
3631 
3632 ABIArgInfo AArch64ABIInfo::classifyArgumentType(QualType Ty,
3633                                                 unsigned &AllocatedVFP,
3634                                                 bool &IsHA,
3635                                                 unsigned &AllocatedGPR,
3636                                                 bool &IsSmallAggr,
3637                                                 bool IsNamedArg) const {
3638   // Handle illegal vector types here.
3639   if (isIllegalVectorType(Ty)) {
3640     uint64_t Size = getContext().getTypeSize(Ty);
3641     if (Size <= 32) {
3642       llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext());
3643       AllocatedGPR++;
3644       return ABIArgInfo::getDirect(ResType);
3645     }
3646     if (Size == 64) {
3647       llvm::Type *ResType =
3648           llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2);
3649       AllocatedVFP++;
3650       return ABIArgInfo::getDirect(ResType);
3651     }
3652     if (Size == 128) {
3653       llvm::Type *ResType =
3654           llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4);
3655       AllocatedVFP++;
3656       return ABIArgInfo::getDirect(ResType);
3657     }
3658     AllocatedGPR++;
3659     return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3660   }
3661   if (Ty->isVectorType())
3662     // Size of a legal vector should be either 64 or 128.
3663     AllocatedVFP++;
3664   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
3665     if (BT->getKind() == BuiltinType::Half ||
3666         BT->getKind() == BuiltinType::Float ||
3667         BT->getKind() == BuiltinType::Double ||
3668         BT->getKind() == BuiltinType::LongDouble)
3669       AllocatedVFP++;
3670   }
3671 
3672   if (!isAggregateTypeForABI(Ty)) {
3673     // Treat an enum type as its underlying type.
3674     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3675       Ty = EnumTy->getDecl()->getIntegerType();
3676 
3677     if (!Ty->isFloatingType() && !Ty->isVectorType()) {
3678       unsigned Alignment = getContext().getTypeAlign(Ty);
3679       if (!isDarwinPCS() && Alignment > 64)
3680         AllocatedGPR = llvm::RoundUpToAlignment(AllocatedGPR, Alignment / 64);
3681 
3682       int RegsNeeded = getContext().getTypeSize(Ty) > 64 ? 2 : 1;
3683       AllocatedGPR += RegsNeeded;
3684     }
3685     return (Ty->isPromotableIntegerType() && isDarwinPCS()
3686                 ? ABIArgInfo::getExtend()
3687                 : ABIArgInfo::getDirect());
3688   }
3689 
3690   // Structures with either a non-trivial destructor or a non-trivial
3691   // copy constructor are always indirect.
3692   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
3693     AllocatedGPR++;
3694     return ABIArgInfo::getIndirect(0, /*ByVal=*/RAA ==
3695                                           CGCXXABI::RAA_DirectInMemory);
3696   }
3697 
3698   // Empty records are always ignored on Darwin, but actually passed in C++ mode
3699   // elsewhere for GNU compatibility.
3700   if (isEmptyRecord(getContext(), Ty, true)) {
3701     if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS())
3702       return ABIArgInfo::getIgnore();
3703 
3704     ++AllocatedGPR;
3705     return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
3706   }
3707 
3708   // Homogeneous Floating-point Aggregates (HFAs) need to be expanded.
3709   const Type *Base = nullptr;
3710   uint64_t Members = 0;
3711   if (isARMHomogeneousAggregate(Ty, Base, getContext(), true, &Members)) {
3712     IsHA = true;
3713     if (!IsNamedArg && isDarwinPCS()) {
3714       // With the Darwin ABI, variadic arguments are always passed on the stack
3715       // and should not be expanded. Treat variadic HFAs as arrays of doubles.
3716       uint64_t Size = getContext().getTypeSize(Ty);
3717       llvm::Type *BaseTy = llvm::Type::getDoubleTy(getVMContext());
3718       return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
3719     }
3720     AllocatedVFP += Members;
3721     return ABIArgInfo::getExpand();
3722   }
3723 
3724   // Aggregates <= 16 bytes are passed directly in registers or on the stack.
3725   uint64_t Size = getContext().getTypeSize(Ty);
3726   if (Size <= 128) {
3727     unsigned Alignment = getContext().getTypeAlign(Ty);
3728     if (!isDarwinPCS() && Alignment > 64)
3729       AllocatedGPR = llvm::RoundUpToAlignment(AllocatedGPR, Alignment / 64);
3730 
3731     Size = 64 * ((Size + 63) / 64); // round up to multiple of 8 bytes
3732     AllocatedGPR += Size / 64;
3733     IsSmallAggr = true;
3734     // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
3735     // For aggregates with 16-byte alignment, we use i128.
3736     if (Alignment < 128 && Size == 128) {
3737       llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
3738       return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
3739     }
3740     return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
3741   }
3742 
3743   AllocatedGPR++;
3744   return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3745 }
3746 
3747 ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy) const {
3748   if (RetTy->isVoidType())
3749     return ABIArgInfo::getIgnore();
3750 
3751   // Large vector types should be returned via memory.
3752   if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
3753     return ABIArgInfo::getIndirect(0);
3754 
3755   if (!isAggregateTypeForABI(RetTy)) {
3756     // Treat an enum type as its underlying type.
3757     if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
3758       RetTy = EnumTy->getDecl()->getIntegerType();
3759 
3760     return (RetTy->isPromotableIntegerType() && isDarwinPCS()
3761                 ? ABIArgInfo::getExtend()
3762                 : ABIArgInfo::getDirect());
3763   }
3764 
3765   if (isEmptyRecord(getContext(), RetTy, true))
3766     return ABIArgInfo::getIgnore();
3767 
3768   const Type *Base = nullptr;
3769   if (isARMHomogeneousAggregate(RetTy, Base, getContext(), true))
3770     // Homogeneous Floating-point Aggregates (HFAs) are returned directly.
3771     return ABIArgInfo::getDirect();
3772 
3773   // Aggregates <= 16 bytes are returned directly in registers or on the stack.
3774   uint64_t Size = getContext().getTypeSize(RetTy);
3775   if (Size <= 128) {
3776     Size = 64 * ((Size + 63) / 64); // round up to multiple of 8 bytes
3777     return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
3778   }
3779 
3780   return ABIArgInfo::getIndirect(0);
3781 }
3782 
3783 /// isIllegalVectorType - check whether the vector type is legal for AArch64.
3784 bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const {
3785   if (const VectorType *VT = Ty->getAs<VectorType>()) {
3786     // Check whether VT is legal.
3787     unsigned NumElements = VT->getNumElements();
3788     uint64_t Size = getContext().getTypeSize(VT);
3789     // NumElements should be power of 2 between 1 and 16.
3790     if ((NumElements & (NumElements - 1)) != 0 || NumElements > 16)
3791       return true;
3792     return Size != 64 && (Size != 128 || NumElements == 1);
3793   }
3794   return false;
3795 }
3796 
3797 static llvm::Value *EmitAArch64VAArg(llvm::Value *VAListAddr, QualType Ty,
3798                                      int AllocatedGPR, int AllocatedVFP,
3799                                      bool IsIndirect, CodeGenFunction &CGF) {
3800   // The AArch64 va_list type and handling is specified in the Procedure Call
3801   // Standard, section B.4:
3802   //
3803   // struct {
3804   //   void *__stack;
3805   //   void *__gr_top;
3806   //   void *__vr_top;
3807   //   int __gr_offs;
3808   //   int __vr_offs;
3809   // };
3810 
3811   llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
3812   llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
3813   llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
3814   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
3815   auto &Ctx = CGF.getContext();
3816 
3817   llvm::Value *reg_offs_p = nullptr, *reg_offs = nullptr;
3818   int reg_top_index;
3819   int RegSize;
3820   if (AllocatedGPR) {
3821     assert(!AllocatedVFP && "Arguments never split between int & VFP regs");
3822     // 3 is the field number of __gr_offs
3823     reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 3, "gr_offs_p");
3824     reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
3825     reg_top_index = 1; // field number for __gr_top
3826     RegSize = 8 * AllocatedGPR;
3827   } else {
3828     assert(!AllocatedGPR && "Argument must go in VFP or int regs");
3829     // 4 is the field number of __vr_offs.
3830     reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 4, "vr_offs_p");
3831     reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
3832     reg_top_index = 2; // field number for __vr_top
3833     RegSize = 16 * AllocatedVFP;
3834   }
3835 
3836   //=======================================
3837   // Find out where argument was passed
3838   //=======================================
3839 
3840   // If reg_offs >= 0 we're already using the stack for this type of
3841   // argument. We don't want to keep updating reg_offs (in case it overflows,
3842   // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
3843   // whatever they get).
3844   llvm::Value *UsingStack = nullptr;
3845   UsingStack = CGF.Builder.CreateICmpSGE(
3846       reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0));
3847 
3848   CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
3849 
3850   // Otherwise, at least some kind of argument could go in these registers, the
3851   // question is whether this particular type is too big.
3852   CGF.EmitBlock(MaybeRegBlock);
3853 
3854   // Integer arguments may need to correct register alignment (for example a
3855   // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
3856   // align __gr_offs to calculate the potential address.
3857   if (AllocatedGPR && !IsIndirect && Ctx.getTypeAlign(Ty) > 64) {
3858     int Align = Ctx.getTypeAlign(Ty) / 8;
3859 
3860     reg_offs = CGF.Builder.CreateAdd(
3861         reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
3862         "align_regoffs");
3863     reg_offs = CGF.Builder.CreateAnd(
3864         reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align),
3865         "aligned_regoffs");
3866   }
3867 
3868   // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
3869   llvm::Value *NewOffset = nullptr;
3870   NewOffset = CGF.Builder.CreateAdd(
3871       reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs");
3872   CGF.Builder.CreateStore(NewOffset, reg_offs_p);
3873 
3874   // Now we're in a position to decide whether this argument really was in
3875   // registers or not.
3876   llvm::Value *InRegs = nullptr;
3877   InRegs = CGF.Builder.CreateICmpSLE(
3878       NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg");
3879 
3880   CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
3881 
3882   //=======================================
3883   // Argument was in registers
3884   //=======================================
3885 
3886   // Now we emit the code for if the argument was originally passed in
3887   // registers. First start the appropriate block:
3888   CGF.EmitBlock(InRegBlock);
3889 
3890   llvm::Value *reg_top_p = nullptr, *reg_top = nullptr;
3891   reg_top_p =
3892       CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index, "reg_top_p");
3893   reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
3894   llvm::Value *BaseAddr = CGF.Builder.CreateGEP(reg_top, reg_offs);
3895   llvm::Value *RegAddr = nullptr;
3896   llvm::Type *MemTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
3897 
3898   if (IsIndirect) {
3899     // If it's been passed indirectly (actually a struct), whatever we find from
3900     // stored registers or on the stack will actually be a struct **.
3901     MemTy = llvm::PointerType::getUnqual(MemTy);
3902   }
3903 
3904   const Type *Base = nullptr;
3905   uint64_t NumMembers;
3906   bool IsHFA = isARMHomogeneousAggregate(Ty, Base, Ctx, true, &NumMembers);
3907   if (IsHFA && NumMembers > 1) {
3908     // Homogeneous aggregates passed in registers will have their elements split
3909     // and stored 16-bytes apart regardless of size (they're notionally in qN,
3910     // qN+1, ...). We reload and store into a temporary local variable
3911     // contiguously.
3912     assert(!IsIndirect && "Homogeneous aggregates should be passed directly");
3913     llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
3914     llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
3915     llvm::Value *Tmp = CGF.CreateTempAlloca(HFATy);
3916     int Offset = 0;
3917 
3918     if (CGF.CGM.getDataLayout().isBigEndian() && Ctx.getTypeSize(Base) < 128)
3919       Offset = 16 - Ctx.getTypeSize(Base) / 8;
3920     for (unsigned i = 0; i < NumMembers; ++i) {
3921       llvm::Value *BaseOffset =
3922           llvm::ConstantInt::get(CGF.Int32Ty, 16 * i + Offset);
3923       llvm::Value *LoadAddr = CGF.Builder.CreateGEP(BaseAddr, BaseOffset);
3924       LoadAddr = CGF.Builder.CreateBitCast(
3925           LoadAddr, llvm::PointerType::getUnqual(BaseTy));
3926       llvm::Value *StoreAddr = CGF.Builder.CreateStructGEP(Tmp, i);
3927 
3928       llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
3929       CGF.Builder.CreateStore(Elem, StoreAddr);
3930     }
3931 
3932     RegAddr = CGF.Builder.CreateBitCast(Tmp, MemTy);
3933   } else {
3934     // Otherwise the object is contiguous in memory
3935     unsigned BeAlign = reg_top_index == 2 ? 16 : 8;
3936     if (CGF.CGM.getDataLayout().isBigEndian() &&
3937         (IsHFA || !isAggregateTypeForABI(Ty)) &&
3938         Ctx.getTypeSize(Ty) < (BeAlign * 8)) {
3939       int Offset = BeAlign - Ctx.getTypeSize(Ty) / 8;
3940       BaseAddr = CGF.Builder.CreatePtrToInt(BaseAddr, CGF.Int64Ty);
3941 
3942       BaseAddr = CGF.Builder.CreateAdd(
3943           BaseAddr, llvm::ConstantInt::get(CGF.Int64Ty, Offset), "align_be");
3944 
3945       BaseAddr = CGF.Builder.CreateIntToPtr(BaseAddr, CGF.Int8PtrTy);
3946     }
3947 
3948     RegAddr = CGF.Builder.CreateBitCast(BaseAddr, MemTy);
3949   }
3950 
3951   CGF.EmitBranch(ContBlock);
3952 
3953   //=======================================
3954   // Argument was on the stack
3955   //=======================================
3956   CGF.EmitBlock(OnStackBlock);
3957 
3958   llvm::Value *stack_p = nullptr, *OnStackAddr = nullptr;
3959   stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "stack_p");
3960   OnStackAddr = CGF.Builder.CreateLoad(stack_p, "stack");
3961 
3962   // Again, stack arguments may need realigmnent. In this case both integer and
3963   // floating-point ones might be affected.
3964   if (!IsIndirect && Ctx.getTypeAlign(Ty) > 64) {
3965     int Align = Ctx.getTypeAlign(Ty) / 8;
3966 
3967     OnStackAddr = CGF.Builder.CreatePtrToInt(OnStackAddr, CGF.Int64Ty);
3968 
3969     OnStackAddr = CGF.Builder.CreateAdd(
3970         OnStackAddr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
3971         "align_stack");
3972     OnStackAddr = CGF.Builder.CreateAnd(
3973         OnStackAddr, llvm::ConstantInt::get(CGF.Int64Ty, -Align),
3974         "align_stack");
3975 
3976     OnStackAddr = CGF.Builder.CreateIntToPtr(OnStackAddr, CGF.Int8PtrTy);
3977   }
3978 
3979   uint64_t StackSize;
3980   if (IsIndirect)
3981     StackSize = 8;
3982   else
3983     StackSize = Ctx.getTypeSize(Ty) / 8;
3984 
3985   // All stack slots are 8 bytes
3986   StackSize = llvm::RoundUpToAlignment(StackSize, 8);
3987 
3988   llvm::Value *StackSizeC = llvm::ConstantInt::get(CGF.Int32Ty, StackSize);
3989   llvm::Value *NewStack =
3990       CGF.Builder.CreateGEP(OnStackAddr, StackSizeC, "new_stack");
3991 
3992   // Write the new value of __stack for the next call to va_arg
3993   CGF.Builder.CreateStore(NewStack, stack_p);
3994 
3995   if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) &&
3996       Ctx.getTypeSize(Ty) < 64) {
3997     int Offset = 8 - Ctx.getTypeSize(Ty) / 8;
3998     OnStackAddr = CGF.Builder.CreatePtrToInt(OnStackAddr, CGF.Int64Ty);
3999 
4000     OnStackAddr = CGF.Builder.CreateAdd(
4001         OnStackAddr, llvm::ConstantInt::get(CGF.Int64Ty, Offset), "align_be");
4002 
4003     OnStackAddr = CGF.Builder.CreateIntToPtr(OnStackAddr, CGF.Int8PtrTy);
4004   }
4005 
4006   OnStackAddr = CGF.Builder.CreateBitCast(OnStackAddr, MemTy);
4007 
4008   CGF.EmitBranch(ContBlock);
4009 
4010   //=======================================
4011   // Tidy up
4012   //=======================================
4013   CGF.EmitBlock(ContBlock);
4014 
4015   llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(MemTy, 2, "vaarg.addr");
4016   ResAddr->addIncoming(RegAddr, InRegBlock);
4017   ResAddr->addIncoming(OnStackAddr, OnStackBlock);
4018 
4019   if (IsIndirect)
4020     return CGF.Builder.CreateLoad(ResAddr, "vaarg.addr");
4021 
4022   return ResAddr;
4023 }
4024 
4025 llvm::Value *AArch64ABIInfo::EmitAAPCSVAArg(llvm::Value *VAListAddr, QualType Ty,
4026                                           CodeGenFunction &CGF) const {
4027 
4028   unsigned AllocatedGPR = 0, AllocatedVFP = 0;
4029   bool IsHA = false, IsSmallAggr = false;
4030   ABIArgInfo AI = classifyArgumentType(Ty, AllocatedVFP, IsHA, AllocatedGPR,
4031                                        IsSmallAggr, false /*IsNamedArg*/);
4032 
4033   return EmitAArch64VAArg(VAListAddr, Ty, AllocatedGPR, AllocatedVFP,
4034                           AI.isIndirect(), CGF);
4035 }
4036 
4037 llvm::Value *AArch64ABIInfo::EmitDarwinVAArg(llvm::Value *VAListAddr, QualType Ty,
4038                                            CodeGenFunction &CGF) const {
4039   // We do not support va_arg for aggregates or illegal vector types.
4040   // Lower VAArg here for these cases and use the LLVM va_arg instruction for
4041   // other cases.
4042   if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty))
4043     return nullptr;
4044 
4045   uint64_t Size = CGF.getContext().getTypeSize(Ty) / 8;
4046   uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8;
4047 
4048   const Type *Base = nullptr;
4049   bool isHA = isARMHomogeneousAggregate(Ty, Base, getContext(), true);
4050 
4051   bool isIndirect = false;
4052   // Arguments bigger than 16 bytes which aren't homogeneous aggregates should
4053   // be passed indirectly.
4054   if (Size > 16 && !isHA) {
4055     isIndirect = true;
4056     Size = 8;
4057     Align = 8;
4058   }
4059 
4060   llvm::Type *BP = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
4061   llvm::Type *BPP = llvm::PointerType::getUnqual(BP);
4062 
4063   CGBuilderTy &Builder = CGF.Builder;
4064   llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
4065   llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
4066 
4067   if (isEmptyRecord(getContext(), Ty, true)) {
4068     // These are ignored for parameter passing purposes.
4069     llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
4070     return Builder.CreateBitCast(Addr, PTy);
4071   }
4072 
4073   const uint64_t MinABIAlign = 8;
4074   if (Align > MinABIAlign) {
4075     llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, Align - 1);
4076     Addr = Builder.CreateGEP(Addr, Offset);
4077     llvm::Value *AsInt = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
4078     llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int64Ty, ~(Align - 1));
4079     llvm::Value *Aligned = Builder.CreateAnd(AsInt, Mask);
4080     Addr = Builder.CreateIntToPtr(Aligned, BP, "ap.align");
4081   }
4082 
4083   uint64_t Offset = llvm::RoundUpToAlignment(Size, MinABIAlign);
4084   llvm::Value *NextAddr = Builder.CreateGEP(
4085       Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset), "ap.next");
4086   Builder.CreateStore(NextAddr, VAListAddrAsBPP);
4087 
4088   if (isIndirect)
4089     Addr = Builder.CreateLoad(Builder.CreateBitCast(Addr, BPP));
4090   llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
4091   llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
4092 
4093   return AddrTyped;
4094 }
4095 
4096 //===----------------------------------------------------------------------===//
4097 // ARM ABI Implementation
4098 //===----------------------------------------------------------------------===//
4099 
4100 namespace {
4101 
4102 class ARMABIInfo : public ABIInfo {
4103 public:
4104   enum ABIKind {
4105     APCS = 0,
4106     AAPCS = 1,
4107     AAPCS_VFP
4108   };
4109 
4110 private:
4111   ABIKind Kind;
4112   mutable int VFPRegs[16];
4113   const unsigned NumVFPs;
4114   const unsigned NumGPRs;
4115   mutable unsigned AllocatedGPRs;
4116   mutable unsigned AllocatedVFPs;
4117 
4118 public:
4119   ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind) : ABIInfo(CGT), Kind(_Kind),
4120     NumVFPs(16), NumGPRs(4) {
4121     setRuntimeCC();
4122     resetAllocatedRegs();
4123   }
4124 
4125   bool isEABI() const {
4126     switch (getTarget().getTriple().getEnvironment()) {
4127     case llvm::Triple::Android:
4128     case llvm::Triple::EABI:
4129     case llvm::Triple::EABIHF:
4130     case llvm::Triple::GNUEABI:
4131     case llvm::Triple::GNUEABIHF:
4132       return true;
4133     default:
4134       return false;
4135     }
4136   }
4137 
4138   bool isEABIHF() const {
4139     switch (getTarget().getTriple().getEnvironment()) {
4140     case llvm::Triple::EABIHF:
4141     case llvm::Triple::GNUEABIHF:
4142       return true;
4143     default:
4144       return false;
4145     }
4146   }
4147 
4148   ABIKind getABIKind() const { return Kind; }
4149 
4150 private:
4151   ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic) const;
4152   ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic,
4153                                   bool &IsCPRC) const;
4154   bool isIllegalVectorType(QualType Ty) const;
4155 
4156   void computeInfo(CGFunctionInfo &FI) const override;
4157 
4158   llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4159                          CodeGenFunction &CGF) const override;
4160 
4161   llvm::CallingConv::ID getLLVMDefaultCC() const;
4162   llvm::CallingConv::ID getABIDefaultCC() const;
4163   void setRuntimeCC();
4164 
4165   void markAllocatedGPRs(unsigned Alignment, unsigned NumRequired) const;
4166   void markAllocatedVFPs(unsigned Alignment, unsigned NumRequired) const;
4167   void resetAllocatedRegs(void) const;
4168 };
4169 
4170 class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
4171 public:
4172   ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
4173     :TargetCodeGenInfo(new ARMABIInfo(CGT, K)) {}
4174 
4175   const ARMABIInfo &getABIInfo() const {
4176     return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
4177   }
4178 
4179   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4180     return 13;
4181   }
4182 
4183   StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
4184     return "mov\tr7, r7\t\t@ marker for objc_retainAutoreleaseReturnValue";
4185   }
4186 
4187   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4188                                llvm::Value *Address) const override {
4189     llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
4190 
4191     // 0-15 are the 16 integer registers.
4192     AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
4193     return false;
4194   }
4195 
4196   unsigned getSizeOfUnwindException() const override {
4197     if (getABIInfo().isEABI()) return 88;
4198     return TargetCodeGenInfo::getSizeOfUnwindException();
4199   }
4200 
4201   void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
4202                            CodeGen::CodeGenModule &CGM) const override {
4203     const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
4204     if (!FD)
4205       return;
4206 
4207     const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
4208     if (!Attr)
4209       return;
4210 
4211     const char *Kind;
4212     switch (Attr->getInterrupt()) {
4213     case ARMInterruptAttr::Generic: Kind = ""; break;
4214     case ARMInterruptAttr::IRQ:     Kind = "IRQ"; break;
4215     case ARMInterruptAttr::FIQ:     Kind = "FIQ"; break;
4216     case ARMInterruptAttr::SWI:     Kind = "SWI"; break;
4217     case ARMInterruptAttr::ABORT:   Kind = "ABORT"; break;
4218     case ARMInterruptAttr::UNDEF:   Kind = "UNDEF"; break;
4219     }
4220 
4221     llvm::Function *Fn = cast<llvm::Function>(GV);
4222 
4223     Fn->addFnAttr("interrupt", Kind);
4224 
4225     if (cast<ARMABIInfo>(getABIInfo()).getABIKind() == ARMABIInfo::APCS)
4226       return;
4227 
4228     // AAPCS guarantees that sp will be 8-byte aligned on any public interface,
4229     // however this is not necessarily true on taking any interrupt. Instruct
4230     // the backend to perform a realignment as part of the function prologue.
4231     llvm::AttrBuilder B;
4232     B.addStackAlignmentAttr(8);
4233     Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
4234                       llvm::AttributeSet::get(CGM.getLLVMContext(),
4235                                               llvm::AttributeSet::FunctionIndex,
4236                                               B));
4237   }
4238 
4239 };
4240 
4241 }
4242 
4243 void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
4244   // To correctly handle Homogeneous Aggregate, we need to keep track of the
4245   // VFP registers allocated so far.
4246   // C.1.vfp If the argument is a VFP CPRC and there are sufficient consecutive
4247   // VFP registers of the appropriate type unallocated then the argument is
4248   // allocated to the lowest-numbered sequence of such registers.
4249   // C.2.vfp If the argument is a VFP CPRC then any VFP registers that are
4250   // unallocated are marked as unavailable.
4251   resetAllocatedRegs();
4252 
4253   const bool isAAPCS_VFP =
4254       getABIKind() == ARMABIInfo::AAPCS_VFP && !FI.isVariadic();
4255 
4256   if (getCXXABI().classifyReturnType(FI)) {
4257     if (FI.getReturnInfo().isIndirect())
4258       markAllocatedGPRs(1, 1);
4259   } else {
4260     FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), FI.isVariadic());
4261   }
4262   for (auto &I : FI.arguments()) {
4263     unsigned PreAllocationVFPs = AllocatedVFPs;
4264     unsigned PreAllocationGPRs = AllocatedGPRs;
4265     bool IsCPRC = false;
4266     // 6.1.2.3 There is one VFP co-processor register class using registers
4267     // s0-s15 (d0-d7) for passing arguments.
4268     I.info = classifyArgumentType(I.type, FI.isVariadic(), IsCPRC);
4269 
4270     // If we have allocated some arguments onto the stack (due to running
4271     // out of VFP registers), we cannot split an argument between GPRs and
4272     // the stack. If this situation occurs, we add padding to prevent the
4273     // GPRs from being used. In this situation, the current argument could
4274     // only be allocated by rule C.8, so rule C.6 would mark these GPRs as
4275     // unusable anyway.
4276     // We do not have to do this if the argument is being passed ByVal, as the
4277     // backend can handle that situation correctly.
4278     const bool StackUsed = PreAllocationGPRs > NumGPRs || PreAllocationVFPs > NumVFPs;
4279     const bool IsByVal = I.info.isIndirect() && I.info.getIndirectByVal();
4280     if (!IsCPRC && PreAllocationGPRs < NumGPRs && AllocatedGPRs > NumGPRs &&
4281         StackUsed && !IsByVal) {
4282       llvm::Type *PaddingTy = llvm::ArrayType::get(
4283           llvm::Type::getInt32Ty(getVMContext()), NumGPRs - PreAllocationGPRs);
4284       if (I.info.canHaveCoerceToType()) {
4285         I.info = ABIArgInfo::getDirect(I.info.getCoerceToType() /* type */, 0 /* offset */,
4286                                        PaddingTy, !isAAPCS_VFP);
4287       } else {
4288         I.info = ABIArgInfo::getDirect(nullptr /* type */, 0 /* offset */,
4289                                        PaddingTy, !isAAPCS_VFP);
4290       }
4291     }
4292   }
4293 
4294   // Always honor user-specified calling convention.
4295   if (FI.getCallingConvention() != llvm::CallingConv::C)
4296     return;
4297 
4298   llvm::CallingConv::ID cc = getRuntimeCC();
4299   if (cc != llvm::CallingConv::C)
4300     FI.setEffectiveCallingConvention(cc);
4301 }
4302 
4303 /// Return the default calling convention that LLVM will use.
4304 llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
4305   // The default calling convention that LLVM will infer.
4306   if (isEABIHF())
4307     return llvm::CallingConv::ARM_AAPCS_VFP;
4308   else if (isEABI())
4309     return llvm::CallingConv::ARM_AAPCS;
4310   else
4311     return llvm::CallingConv::ARM_APCS;
4312 }
4313 
4314 /// Return the calling convention that our ABI would like us to use
4315 /// as the C calling convention.
4316 llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
4317   switch (getABIKind()) {
4318   case APCS: return llvm::CallingConv::ARM_APCS;
4319   case AAPCS: return llvm::CallingConv::ARM_AAPCS;
4320   case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
4321   }
4322   llvm_unreachable("bad ABI kind");
4323 }
4324 
4325 void ARMABIInfo::setRuntimeCC() {
4326   assert(getRuntimeCC() == llvm::CallingConv::C);
4327 
4328   // Don't muddy up the IR with a ton of explicit annotations if
4329   // they'd just match what LLVM will infer from the triple.
4330   llvm::CallingConv::ID abiCC = getABIDefaultCC();
4331   if (abiCC != getLLVMDefaultCC())
4332     RuntimeCC = abiCC;
4333 }
4334 
4335 /// isARMHomogeneousAggregate - Return true if a type is an AAPCS-VFP homogeneous
4336 /// aggregate.  If HAMembers is non-null, the number of base elements
4337 /// contained in the type is returned through it; this is used for the
4338 /// recursive calls that check aggregate component types.
4339 static bool isARMHomogeneousAggregate(QualType Ty, const Type *&Base,
4340                                    ASTContext &Context, bool isAArch64,
4341                                    uint64_t *HAMembers) {
4342   uint64_t Members = 0;
4343   if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
4344     if (!isARMHomogeneousAggregate(AT->getElementType(), Base, Context, isAArch64, &Members))
4345       return false;
4346     Members *= AT->getSize().getZExtValue();
4347   } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
4348     const RecordDecl *RD = RT->getDecl();
4349     if (RD->hasFlexibleArrayMember())
4350       return false;
4351 
4352     Members = 0;
4353     for (const auto *FD : RD->fields()) {
4354       uint64_t FldMembers;
4355       if (!isARMHomogeneousAggregate(FD->getType(), Base, Context, isAArch64, &FldMembers))
4356         return false;
4357 
4358       Members = (RD->isUnion() ?
4359                  std::max(Members, FldMembers) : Members + FldMembers);
4360     }
4361   } else {
4362     Members = 1;
4363     if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
4364       Members = 2;
4365       Ty = CT->getElementType();
4366     }
4367 
4368     // Homogeneous aggregates for AAPCS-VFP must have base types of float,
4369     // double, or 64-bit or 128-bit vectors. "long double" has the same machine
4370     // type as double, so it is also allowed as a base type.
4371     // Homogeneous aggregates for AAPCS64 must have base types of a floating
4372     // point type or a short-vector type. This is the same as the 32-bit ABI,
4373     // but with the difference that any floating-point type is allowed,
4374     // including __fp16.
4375     if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4376       if (isAArch64) {
4377         if (!BT->isFloatingPoint())
4378           return false;
4379       } else {
4380         if (BT->getKind() != BuiltinType::Float &&
4381             BT->getKind() != BuiltinType::Double &&
4382             BT->getKind() != BuiltinType::LongDouble)
4383           return false;
4384       }
4385     } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
4386       unsigned VecSize = Context.getTypeSize(VT);
4387       if (VecSize != 64 && VecSize != 128)
4388         return false;
4389     } else {
4390       return false;
4391     }
4392 
4393     // The base type must be the same for all members.  Vector types of the
4394     // same total size are treated as being equivalent here.
4395     const Type *TyPtr = Ty.getTypePtr();
4396     if (!Base)
4397       Base = TyPtr;
4398 
4399     if (Base != TyPtr) {
4400       // Homogeneous aggregates are defined as containing members with the
4401       // same machine type. There are two cases in which two members have
4402       // different TypePtrs but the same machine type:
4403 
4404       // 1) Vectors of the same length, regardless of the type and number
4405       //    of their members.
4406       const bool SameLengthVectors = Base->isVectorType() && TyPtr->isVectorType()
4407         && (Context.getTypeSize(Base) == Context.getTypeSize(TyPtr));
4408 
4409       // 2) In the 32-bit AAPCS, `double' and `long double' have the same
4410       //    machine type. This is not the case for the 64-bit AAPCS.
4411       const bool SameSizeDoubles =
4412            (   (   Base->isSpecificBuiltinType(BuiltinType::Double)
4413                 && TyPtr->isSpecificBuiltinType(BuiltinType::LongDouble))
4414             || (   Base->isSpecificBuiltinType(BuiltinType::LongDouble)
4415                 && TyPtr->isSpecificBuiltinType(BuiltinType::Double)))
4416         && (Context.getTypeSize(Base) == Context.getTypeSize(TyPtr));
4417 
4418       if (!SameLengthVectors && !SameSizeDoubles)
4419         return false;
4420     }
4421   }
4422 
4423   // Homogeneous Aggregates can have at most 4 members of the base type.
4424   if (HAMembers)
4425     *HAMembers = Members;
4426 
4427   return (Members > 0 && Members <= 4);
4428 }
4429 
4430 /// markAllocatedVFPs - update VFPRegs according to the alignment and
4431 /// number of VFP registers (unit is S register) requested.
4432 void ARMABIInfo::markAllocatedVFPs(unsigned Alignment,
4433                                    unsigned NumRequired) const {
4434   // Early Exit.
4435   if (AllocatedVFPs >= 16) {
4436     // We use AllocatedVFP > 16 to signal that some CPRCs were allocated on
4437     // the stack.
4438     AllocatedVFPs = 17;
4439     return;
4440   }
4441   // C.1.vfp If the argument is a VFP CPRC and there are sufficient consecutive
4442   // VFP registers of the appropriate type unallocated then the argument is
4443   // allocated to the lowest-numbered sequence of such registers.
4444   for (unsigned I = 0; I < 16; I += Alignment) {
4445     bool FoundSlot = true;
4446     for (unsigned J = I, JEnd = I + NumRequired; J < JEnd; J++)
4447       if (J >= 16 || VFPRegs[J]) {
4448          FoundSlot = false;
4449          break;
4450       }
4451     if (FoundSlot) {
4452       for (unsigned J = I, JEnd = I + NumRequired; J < JEnd; J++)
4453         VFPRegs[J] = 1;
4454       AllocatedVFPs += NumRequired;
4455       return;
4456     }
4457   }
4458   // C.2.vfp If the argument is a VFP CPRC then any VFP registers that are
4459   // unallocated are marked as unavailable.
4460   for (unsigned I = 0; I < 16; I++)
4461     VFPRegs[I] = 1;
4462   AllocatedVFPs = 17; // We do not have enough VFP registers.
4463 }
4464 
4465 /// Update AllocatedGPRs to record the number of general purpose registers
4466 /// which have been allocated. It is valid for AllocatedGPRs to go above 4,
4467 /// this represents arguments being stored on the stack.
4468 void ARMABIInfo::markAllocatedGPRs(unsigned Alignment,
4469                                    unsigned NumRequired) const {
4470   assert((Alignment == 1 || Alignment == 2) && "Alignment must be 4 or 8 bytes");
4471 
4472   if (Alignment == 2 && AllocatedGPRs & 0x1)
4473     AllocatedGPRs += 1;
4474 
4475   AllocatedGPRs += NumRequired;
4476 }
4477 
4478 void ARMABIInfo::resetAllocatedRegs(void) const {
4479   AllocatedGPRs = 0;
4480   AllocatedVFPs = 0;
4481   for (unsigned i = 0; i < NumVFPs; ++i)
4482     VFPRegs[i] = 0;
4483 }
4484 
4485 ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty, bool isVariadic,
4486                                             bool &IsCPRC) const {
4487   // We update number of allocated VFPs according to
4488   // 6.1.2.1 The following argument types are VFP CPRCs:
4489   //   A single-precision floating-point type (including promoted
4490   //   half-precision types); A double-precision floating-point type;
4491   //   A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
4492   //   with a Base Type of a single- or double-precision floating-point type,
4493   //   64-bit containerized vectors or 128-bit containerized vectors with one
4494   //   to four Elements.
4495 
4496   const bool isAAPCS_VFP =
4497       getABIKind() == ARMABIInfo::AAPCS_VFP && !isVariadic;
4498 
4499   // Handle illegal vector types here.
4500   if (isIllegalVectorType(Ty)) {
4501     uint64_t Size = getContext().getTypeSize(Ty);
4502     if (Size <= 32) {
4503       llvm::Type *ResType =
4504           llvm::Type::getInt32Ty(getVMContext());
4505       markAllocatedGPRs(1, 1);
4506       return ABIArgInfo::getDirect(ResType, 0, nullptr, !isAAPCS_VFP);
4507     }
4508     if (Size == 64) {
4509       llvm::Type *ResType = llvm::VectorType::get(
4510           llvm::Type::getInt32Ty(getVMContext()), 2);
4511       if (getABIKind() == ARMABIInfo::AAPCS || isVariadic){
4512         markAllocatedGPRs(2, 2);
4513       } else {
4514         markAllocatedVFPs(2, 2);
4515         IsCPRC = true;
4516       }
4517       return ABIArgInfo::getDirect(ResType, 0, nullptr, !isAAPCS_VFP);
4518     }
4519     if (Size == 128) {
4520       llvm::Type *ResType = llvm::VectorType::get(
4521           llvm::Type::getInt32Ty(getVMContext()), 4);
4522       if (getABIKind() == ARMABIInfo::AAPCS || isVariadic) {
4523         markAllocatedGPRs(2, 4);
4524       } else {
4525         markAllocatedVFPs(4, 4);
4526         IsCPRC = true;
4527       }
4528       return ABIArgInfo::getDirect(ResType, 0, nullptr, !isAAPCS_VFP);
4529     }
4530     markAllocatedGPRs(1, 1);
4531     return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
4532   }
4533   // Update VFPRegs for legal vector types.
4534   if (getABIKind() == ARMABIInfo::AAPCS_VFP && !isVariadic) {
4535     if (const VectorType *VT = Ty->getAs<VectorType>()) {
4536       uint64_t Size = getContext().getTypeSize(VT);
4537       // Size of a legal vector should be power of 2 and above 64.
4538       markAllocatedVFPs(Size >= 128 ? 4 : 2, Size / 32);
4539       IsCPRC = true;
4540     }
4541   }
4542   // Update VFPRegs for floating point types.
4543   if (getABIKind() == ARMABIInfo::AAPCS_VFP && !isVariadic) {
4544     if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4545       if (BT->getKind() == BuiltinType::Half ||
4546           BT->getKind() == BuiltinType::Float) {
4547         markAllocatedVFPs(1, 1);
4548         IsCPRC = true;
4549       }
4550       if (BT->getKind() == BuiltinType::Double ||
4551           BT->getKind() == BuiltinType::LongDouble) {
4552         markAllocatedVFPs(2, 2);
4553         IsCPRC = true;
4554       }
4555     }
4556   }
4557 
4558   if (!isAggregateTypeForABI(Ty)) {
4559     // Treat an enum type as its underlying type.
4560     if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
4561       Ty = EnumTy->getDecl()->getIntegerType();
4562     }
4563 
4564     unsigned Size = getContext().getTypeSize(Ty);
4565     if (!IsCPRC)
4566       markAllocatedGPRs(Size > 32 ? 2 : 1, (Size + 31) / 32);
4567     return (Ty->isPromotableIntegerType()
4568                 ? ABIArgInfo::getExtend()
4569                 : ABIArgInfo::getDirect(nullptr, 0, nullptr, !isAAPCS_VFP));
4570   }
4571 
4572   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
4573     markAllocatedGPRs(1, 1);
4574     return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
4575   }
4576 
4577   // Ignore empty records.
4578   if (isEmptyRecord(getContext(), Ty, true))
4579     return ABIArgInfo::getIgnore();
4580 
4581   if (isAAPCS_VFP) {
4582     // Homogeneous Aggregates need to be expanded when we can fit the aggregate
4583     // into VFP registers.
4584     const Type *Base = nullptr;
4585     uint64_t Members = 0;
4586     if (isARMHomogeneousAggregate(Ty, Base, getContext(), false, &Members)) {
4587       assert(Base && "Base class should be set for homogeneous aggregate");
4588       // Base can be a floating-point or a vector.
4589       if (Base->isVectorType()) {
4590         // ElementSize is in number of floats.
4591         unsigned ElementSize = getContext().getTypeSize(Base) == 64 ? 2 : 4;
4592         markAllocatedVFPs(ElementSize,
4593                           Members * ElementSize);
4594       } else if (Base->isSpecificBuiltinType(BuiltinType::Float))
4595         markAllocatedVFPs(1, Members);
4596       else {
4597         assert(Base->isSpecificBuiltinType(BuiltinType::Double) ||
4598                Base->isSpecificBuiltinType(BuiltinType::LongDouble));
4599         markAllocatedVFPs(2, Members * 2);
4600       }
4601       IsCPRC = true;
4602       return ABIArgInfo::getDirect(nullptr, 0, nullptr, !isAAPCS_VFP);
4603     }
4604   }
4605 
4606   // Support byval for ARM.
4607   // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
4608   // most 8-byte. We realign the indirect argument if type alignment is bigger
4609   // than ABI alignment.
4610   uint64_t ABIAlign = 4;
4611   uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8;
4612   if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
4613       getABIKind() == ARMABIInfo::AAPCS)
4614     ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
4615   if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
4616     // Update Allocated GPRs. Since this is only used when the size of the
4617     // argument is greater than 64 bytes, this will always use up any available
4618     // registers (of which there are 4). We also don't care about getting the
4619     // alignment right, because general-purpose registers cannot be back-filled.
4620     markAllocatedGPRs(1, 4);
4621     return ABIArgInfo::getIndirect(TyAlign, /*ByVal=*/true,
4622            /*Realign=*/TyAlign > ABIAlign);
4623   }
4624 
4625   // Otherwise, pass by coercing to a structure of the appropriate size.
4626   llvm::Type* ElemTy;
4627   unsigned SizeRegs;
4628   // FIXME: Try to match the types of the arguments more accurately where
4629   // we can.
4630   if (getContext().getTypeAlign(Ty) <= 32) {
4631     ElemTy = llvm::Type::getInt32Ty(getVMContext());
4632     SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
4633     markAllocatedGPRs(1, SizeRegs);
4634   } else {
4635     ElemTy = llvm::Type::getInt64Ty(getVMContext());
4636     SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
4637     markAllocatedGPRs(2, SizeRegs * 2);
4638   }
4639 
4640   llvm::Type *STy =
4641     llvm::StructType::get(llvm::ArrayType::get(ElemTy, SizeRegs), NULL);
4642   return ABIArgInfo::getDirect(STy, 0, nullptr, !isAAPCS_VFP);
4643 }
4644 
4645 static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
4646                               llvm::LLVMContext &VMContext) {
4647   // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
4648   // is called integer-like if its size is less than or equal to one word, and
4649   // the offset of each of its addressable sub-fields is zero.
4650 
4651   uint64_t Size = Context.getTypeSize(Ty);
4652 
4653   // Check that the type fits in a word.
4654   if (Size > 32)
4655     return false;
4656 
4657   // FIXME: Handle vector types!
4658   if (Ty->isVectorType())
4659     return false;
4660 
4661   // Float types are never treated as "integer like".
4662   if (Ty->isRealFloatingType())
4663     return false;
4664 
4665   // If this is a builtin or pointer type then it is ok.
4666   if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
4667     return true;
4668 
4669   // Small complex integer types are "integer like".
4670   if (const ComplexType *CT = Ty->getAs<ComplexType>())
4671     return isIntegerLikeType(CT->getElementType(), Context, VMContext);
4672 
4673   // Single element and zero sized arrays should be allowed, by the definition
4674   // above, but they are not.
4675 
4676   // Otherwise, it must be a record type.
4677   const RecordType *RT = Ty->getAs<RecordType>();
4678   if (!RT) return false;
4679 
4680   // Ignore records with flexible arrays.
4681   const RecordDecl *RD = RT->getDecl();
4682   if (RD->hasFlexibleArrayMember())
4683     return false;
4684 
4685   // Check that all sub-fields are at offset 0, and are themselves "integer
4686   // like".
4687   const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
4688 
4689   bool HadField = false;
4690   unsigned idx = 0;
4691   for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
4692        i != e; ++i, ++idx) {
4693     const FieldDecl *FD = *i;
4694 
4695     // Bit-fields are not addressable, we only need to verify they are "integer
4696     // like". We still have to disallow a subsequent non-bitfield, for example:
4697     //   struct { int : 0; int x }
4698     // is non-integer like according to gcc.
4699     if (FD->isBitField()) {
4700       if (!RD->isUnion())
4701         HadField = true;
4702 
4703       if (!isIntegerLikeType(FD->getType(), Context, VMContext))
4704         return false;
4705 
4706       continue;
4707     }
4708 
4709     // Check if this field is at offset 0.
4710     if (Layout.getFieldOffset(idx) != 0)
4711       return false;
4712 
4713     if (!isIntegerLikeType(FD->getType(), Context, VMContext))
4714       return false;
4715 
4716     // Only allow at most one field in a structure. This doesn't match the
4717     // wording above, but follows gcc in situations with a field following an
4718     // empty structure.
4719     if (!RD->isUnion()) {
4720       if (HadField)
4721         return false;
4722 
4723       HadField = true;
4724     }
4725   }
4726 
4727   return true;
4728 }
4729 
4730 ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy,
4731                                           bool isVariadic) const {
4732   const bool isAAPCS_VFP =
4733       getABIKind() == ARMABIInfo::AAPCS_VFP && !isVariadic;
4734 
4735   if (RetTy->isVoidType())
4736     return ABIArgInfo::getIgnore();
4737 
4738   // Large vector types should be returned via memory.
4739   if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128) {
4740     markAllocatedGPRs(1, 1);
4741     return ABIArgInfo::getIndirect(0);
4742   }
4743 
4744   if (!isAggregateTypeForABI(RetTy)) {
4745     // Treat an enum type as its underlying type.
4746     if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
4747       RetTy = EnumTy->getDecl()->getIntegerType();
4748 
4749     return (RetTy->isPromotableIntegerType()
4750                 ? ABIArgInfo::getExtend()
4751                 : ABIArgInfo::getDirect(nullptr, 0, nullptr, !isAAPCS_VFP));
4752   }
4753 
4754   // Are we following APCS?
4755   if (getABIKind() == APCS) {
4756     if (isEmptyRecord(getContext(), RetTy, false))
4757       return ABIArgInfo::getIgnore();
4758 
4759     // Complex types are all returned as packed integers.
4760     //
4761     // FIXME: Consider using 2 x vector types if the back end handles them
4762     // correctly.
4763     if (RetTy->isAnyComplexType())
4764       return ABIArgInfo::getDirect(llvm::IntegerType::get(
4765           getVMContext(), getContext().getTypeSize(RetTy)));
4766 
4767     // Integer like structures are returned in r0.
4768     if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
4769       // Return in the smallest viable integer type.
4770       uint64_t Size = getContext().getTypeSize(RetTy);
4771       if (Size <= 8)
4772         return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
4773       if (Size <= 16)
4774         return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
4775       return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
4776     }
4777 
4778     // Otherwise return in memory.
4779     markAllocatedGPRs(1, 1);
4780     return ABIArgInfo::getIndirect(0);
4781   }
4782 
4783   // Otherwise this is an AAPCS variant.
4784 
4785   if (isEmptyRecord(getContext(), RetTy, true))
4786     return ABIArgInfo::getIgnore();
4787 
4788   // Check for homogeneous aggregates with AAPCS-VFP.
4789   if (getABIKind() == AAPCS_VFP && !isVariadic) {
4790     const Type *Base = nullptr;
4791     if (isARMHomogeneousAggregate(RetTy, Base, getContext(), false)) {
4792       assert(Base && "Base class should be set for homogeneous aggregate");
4793       // Homogeneous Aggregates are returned directly.
4794       return ABIArgInfo::getDirect(nullptr, 0, nullptr, !isAAPCS_VFP);
4795     }
4796   }
4797 
4798   // Aggregates <= 4 bytes are returned in r0; other aggregates
4799   // are returned indirectly.
4800   uint64_t Size = getContext().getTypeSize(RetTy);
4801   if (Size <= 32) {
4802     if (getDataLayout().isBigEndian())
4803       // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4)
4804       return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()), 0,
4805                                    nullptr, !isAAPCS_VFP);
4806 
4807     // Return in the smallest viable integer type.
4808     if (Size <= 8)
4809       return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()), 0,
4810                                    nullptr, !isAAPCS_VFP);
4811     if (Size <= 16)
4812       return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()), 0,
4813                                    nullptr, !isAAPCS_VFP);
4814     return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()), 0,
4815                                  nullptr, !isAAPCS_VFP);
4816   }
4817 
4818   markAllocatedGPRs(1, 1);
4819   return ABIArgInfo::getIndirect(0);
4820 }
4821 
4822 /// isIllegalVector - check whether Ty is an illegal vector type.
4823 bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
4824   if (const VectorType *VT = Ty->getAs<VectorType>()) {
4825     // Check whether VT is legal.
4826     unsigned NumElements = VT->getNumElements();
4827     uint64_t Size = getContext().getTypeSize(VT);
4828     // NumElements should be power of 2.
4829     if ((NumElements & (NumElements - 1)) != 0)
4830       return true;
4831     // Size should be greater than 32 bits.
4832     return Size <= 32;
4833   }
4834   return false;
4835 }
4836 
4837 llvm::Value *ARMABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4838                                    CodeGenFunction &CGF) const {
4839   llvm::Type *BP = CGF.Int8PtrTy;
4840   llvm::Type *BPP = CGF.Int8PtrPtrTy;
4841 
4842   CGBuilderTy &Builder = CGF.Builder;
4843   llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
4844   llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
4845 
4846   if (isEmptyRecord(getContext(), Ty, true)) {
4847     // These are ignored for parameter passing purposes.
4848     llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
4849     return Builder.CreateBitCast(Addr, PTy);
4850   }
4851 
4852   uint64_t Size = CGF.getContext().getTypeSize(Ty) / 8;
4853   uint64_t TyAlign = CGF.getContext().getTypeAlign(Ty) / 8;
4854   bool IsIndirect = false;
4855 
4856   // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
4857   // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
4858   if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
4859       getABIKind() == ARMABIInfo::AAPCS)
4860     TyAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
4861   else
4862     TyAlign = 4;
4863   // Use indirect if size of the illegal vector is bigger than 16 bytes.
4864   if (isIllegalVectorType(Ty) && Size > 16) {
4865     IsIndirect = true;
4866     Size = 4;
4867     TyAlign = 4;
4868   }
4869 
4870   // Handle address alignment for ABI alignment > 4 bytes.
4871   if (TyAlign > 4) {
4872     assert((TyAlign & (TyAlign - 1)) == 0 &&
4873            "Alignment is not power of 2!");
4874     llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int32Ty);
4875     AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt32(TyAlign - 1));
4876     AddrAsInt = Builder.CreateAnd(AddrAsInt, Builder.getInt32(~(TyAlign - 1)));
4877     Addr = Builder.CreateIntToPtr(AddrAsInt, BP, "ap.align");
4878   }
4879 
4880   uint64_t Offset =
4881     llvm::RoundUpToAlignment(Size, 4);
4882   llvm::Value *NextAddr =
4883     Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
4884                       "ap.next");
4885   Builder.CreateStore(NextAddr, VAListAddrAsBPP);
4886 
4887   if (IsIndirect)
4888     Addr = Builder.CreateLoad(Builder.CreateBitCast(Addr, BPP));
4889   else if (TyAlign < CGF.getContext().getTypeAlign(Ty) / 8) {
4890     // We can't directly cast ap.cur to pointer to a vector type, since ap.cur
4891     // may not be correctly aligned for the vector type. We create an aligned
4892     // temporary space and copy the content over from ap.cur to the temporary
4893     // space. This is necessary if the natural alignment of the type is greater
4894     // than the ABI alignment.
4895     llvm::Type *I8PtrTy = Builder.getInt8PtrTy();
4896     CharUnits CharSize = getContext().getTypeSizeInChars(Ty);
4897     llvm::Value *AlignedTemp = CGF.CreateTempAlloca(CGF.ConvertType(Ty),
4898                                                     "var.align");
4899     llvm::Value *Dst = Builder.CreateBitCast(AlignedTemp, I8PtrTy);
4900     llvm::Value *Src = Builder.CreateBitCast(Addr, I8PtrTy);
4901     Builder.CreateMemCpy(Dst, Src,
4902         llvm::ConstantInt::get(CGF.IntPtrTy, CharSize.getQuantity()),
4903         TyAlign, false);
4904     Addr = AlignedTemp; //The content is in aligned location.
4905   }
4906   llvm::Type *PTy =
4907     llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
4908   llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
4909 
4910   return AddrTyped;
4911 }
4912 
4913 namespace {
4914 
4915 class NaClARMABIInfo : public ABIInfo {
4916  public:
4917   NaClARMABIInfo(CodeGen::CodeGenTypes &CGT, ARMABIInfo::ABIKind Kind)
4918       : ABIInfo(CGT), PInfo(CGT), NInfo(CGT, Kind) {}
4919   void computeInfo(CGFunctionInfo &FI) const override;
4920   llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4921                          CodeGenFunction &CGF) const override;
4922  private:
4923   PNaClABIInfo PInfo; // Used for generating calls with pnaclcall callingconv.
4924   ARMABIInfo NInfo; // Used for everything else.
4925 };
4926 
4927 class NaClARMTargetCodeGenInfo : public TargetCodeGenInfo  {
4928  public:
4929   NaClARMTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, ARMABIInfo::ABIKind Kind)
4930       : TargetCodeGenInfo(new NaClARMABIInfo(CGT, Kind)) {}
4931 };
4932 
4933 }
4934 
4935 void NaClARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
4936   if (FI.getASTCallingConvention() == CC_PnaclCall)
4937     PInfo.computeInfo(FI);
4938   else
4939     static_cast<const ABIInfo&>(NInfo).computeInfo(FI);
4940 }
4941 
4942 llvm::Value *NaClARMABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4943                                        CodeGenFunction &CGF) const {
4944   // Always use the native convention; calling pnacl-style varargs functions
4945   // is unsupported.
4946   return static_cast<const ABIInfo&>(NInfo).EmitVAArg(VAListAddr, Ty, CGF);
4947 }
4948 
4949 //===----------------------------------------------------------------------===//
4950 // NVPTX ABI Implementation
4951 //===----------------------------------------------------------------------===//
4952 
4953 namespace {
4954 
4955 class NVPTXABIInfo : public ABIInfo {
4956 public:
4957   NVPTXABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
4958 
4959   ABIArgInfo classifyReturnType(QualType RetTy) const;
4960   ABIArgInfo classifyArgumentType(QualType Ty) const;
4961 
4962   void computeInfo(CGFunctionInfo &FI) const override;
4963   llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4964                          CodeGenFunction &CFG) const override;
4965 };
4966 
4967 class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
4968 public:
4969   NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
4970     : TargetCodeGenInfo(new NVPTXABIInfo(CGT)) {}
4971 
4972   void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
4973                            CodeGen::CodeGenModule &M) const override;
4974 private:
4975   // Adds a NamedMDNode with F, Name, and Operand as operands, and adds the
4976   // resulting MDNode to the nvvm.annotations MDNode.
4977   static void addNVVMMetadata(llvm::Function *F, StringRef Name, int Operand);
4978 };
4979 
4980 ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
4981   if (RetTy->isVoidType())
4982     return ABIArgInfo::getIgnore();
4983 
4984   // note: this is different from default ABI
4985   if (!RetTy->isScalarType())
4986     return ABIArgInfo::getDirect();
4987 
4988   // Treat an enum type as its underlying type.
4989   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
4990     RetTy = EnumTy->getDecl()->getIntegerType();
4991 
4992   return (RetTy->isPromotableIntegerType() ?
4993           ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
4994 }
4995 
4996 ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
4997   // Treat an enum type as its underlying type.
4998   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4999     Ty = EnumTy->getDecl()->getIntegerType();
5000 
5001   return (Ty->isPromotableIntegerType() ?
5002           ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5003 }
5004 
5005 void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
5006   if (!getCXXABI().classifyReturnType(FI))
5007     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
5008   for (auto &I : FI.arguments())
5009     I.info = classifyArgumentType(I.type);
5010 
5011   // Always honor user-specified calling convention.
5012   if (FI.getCallingConvention() != llvm::CallingConv::C)
5013     return;
5014 
5015   FI.setEffectiveCallingConvention(getRuntimeCC());
5016 }
5017 
5018 llvm::Value *NVPTXABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5019                                      CodeGenFunction &CFG) const {
5020   llvm_unreachable("NVPTX does not support varargs");
5021 }
5022 
5023 void NVPTXTargetCodeGenInfo::
5024 SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5025                     CodeGen::CodeGenModule &M) const{
5026   const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
5027   if (!FD) return;
5028 
5029   llvm::Function *F = cast<llvm::Function>(GV);
5030 
5031   // Perform special handling in OpenCL mode
5032   if (M.getLangOpts().OpenCL) {
5033     // Use OpenCL function attributes to check for kernel functions
5034     // By default, all functions are device functions
5035     if (FD->hasAttr<OpenCLKernelAttr>()) {
5036       // OpenCL __kernel functions get kernel metadata
5037       // Create !{<func-ref>, metadata !"kernel", i32 1} node
5038       addNVVMMetadata(F, "kernel", 1);
5039       // And kernel functions are not subject to inlining
5040       F->addFnAttr(llvm::Attribute::NoInline);
5041     }
5042   }
5043 
5044   // Perform special handling in CUDA mode.
5045   if (M.getLangOpts().CUDA) {
5046     // CUDA __global__ functions get a kernel metadata entry.  Since
5047     // __global__ functions cannot be called from the device, we do not
5048     // need to set the noinline attribute.
5049     if (FD->hasAttr<CUDAGlobalAttr>()) {
5050       // Create !{<func-ref>, metadata !"kernel", i32 1} node
5051       addNVVMMetadata(F, "kernel", 1);
5052     }
5053     if (FD->hasAttr<CUDALaunchBoundsAttr>()) {
5054       // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node
5055       addNVVMMetadata(F, "maxntidx",
5056                       FD->getAttr<CUDALaunchBoundsAttr>()->getMaxThreads());
5057       // min blocks is a default argument for CUDALaunchBoundsAttr, so getting a
5058       // zero value from getMinBlocks either means it was not specified in
5059       // __launch_bounds__ or the user specified a 0 value. In both cases, we
5060       // don't have to add a PTX directive.
5061       int MinCTASM = FD->getAttr<CUDALaunchBoundsAttr>()->getMinBlocks();
5062       if (MinCTASM > 0) {
5063         // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node
5064         addNVVMMetadata(F, "minctasm", MinCTASM);
5065       }
5066     }
5067   }
5068 }
5069 
5070 void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::Function *F, StringRef Name,
5071                                              int Operand) {
5072   llvm::Module *M = F->getParent();
5073   llvm::LLVMContext &Ctx = M->getContext();
5074 
5075   // Get "nvvm.annotations" metadata node
5076   llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
5077 
5078   llvm::Value *MDVals[] = {
5079       F, llvm::MDString::get(Ctx, Name),
5080       llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand)};
5081   // Append metadata to nvvm.annotations
5082   MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
5083 }
5084 }
5085 
5086 //===----------------------------------------------------------------------===//
5087 // SystemZ ABI Implementation
5088 //===----------------------------------------------------------------------===//
5089 
5090 namespace {
5091 
5092 class SystemZABIInfo : public ABIInfo {
5093 public:
5094   SystemZABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
5095 
5096   bool isPromotableIntegerType(QualType Ty) const;
5097   bool isCompoundType(QualType Ty) const;
5098   bool isFPArgumentType(QualType Ty) const;
5099 
5100   ABIArgInfo classifyReturnType(QualType RetTy) const;
5101   ABIArgInfo classifyArgumentType(QualType ArgTy) const;
5102 
5103   void computeInfo(CGFunctionInfo &FI) const override {
5104     if (!getCXXABI().classifyReturnType(FI))
5105       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
5106     for (auto &I : FI.arguments())
5107       I.info = classifyArgumentType(I.type);
5108   }
5109 
5110   llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5111                          CodeGenFunction &CGF) const override;
5112 };
5113 
5114 class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
5115 public:
5116   SystemZTargetCodeGenInfo(CodeGenTypes &CGT)
5117     : TargetCodeGenInfo(new SystemZABIInfo(CGT)) {}
5118 };
5119 
5120 }
5121 
5122 bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const {
5123   // Treat an enum type as its underlying type.
5124   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5125     Ty = EnumTy->getDecl()->getIntegerType();
5126 
5127   // Promotable integer types are required to be promoted by the ABI.
5128   if (Ty->isPromotableIntegerType())
5129     return true;
5130 
5131   // 32-bit values must also be promoted.
5132   if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
5133     switch (BT->getKind()) {
5134     case BuiltinType::Int:
5135     case BuiltinType::UInt:
5136       return true;
5137     default:
5138       return false;
5139     }
5140   return false;
5141 }
5142 
5143 bool SystemZABIInfo::isCompoundType(QualType Ty) const {
5144   return Ty->isAnyComplexType() || isAggregateTypeForABI(Ty);
5145 }
5146 
5147 bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
5148   if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
5149     switch (BT->getKind()) {
5150     case BuiltinType::Float:
5151     case BuiltinType::Double:
5152       return true;
5153     default:
5154       return false;
5155     }
5156 
5157   if (const RecordType *RT = Ty->getAsStructureType()) {
5158     const RecordDecl *RD = RT->getDecl();
5159     bool Found = false;
5160 
5161     // If this is a C++ record, check the bases first.
5162     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
5163       for (const auto &I : CXXRD->bases()) {
5164         QualType Base = I.getType();
5165 
5166         // Empty bases don't affect things either way.
5167         if (isEmptyRecord(getContext(), Base, true))
5168           continue;
5169 
5170         if (Found)
5171           return false;
5172         Found = isFPArgumentType(Base);
5173         if (!Found)
5174           return false;
5175       }
5176 
5177     // Check the fields.
5178     for (const auto *FD : RD->fields()) {
5179       // Empty bitfields don't affect things either way.
5180       // Unlike isSingleElementStruct(), empty structure and array fields
5181       // do count.  So do anonymous bitfields that aren't zero-sized.
5182       if (FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
5183         return true;
5184 
5185       // Unlike isSingleElementStruct(), arrays do not count.
5186       // Nested isFPArgumentType structures still do though.
5187       if (Found)
5188         return false;
5189       Found = isFPArgumentType(FD->getType());
5190       if (!Found)
5191         return false;
5192     }
5193 
5194     // Unlike isSingleElementStruct(), trailing padding is allowed.
5195     // An 8-byte aligned struct s { float f; } is passed as a double.
5196     return Found;
5197   }
5198 
5199   return false;
5200 }
5201 
5202 llvm::Value *SystemZABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5203                                        CodeGenFunction &CGF) const {
5204   // Assume that va_list type is correct; should be pointer to LLVM type:
5205   // struct {
5206   //   i64 __gpr;
5207   //   i64 __fpr;
5208   //   i8 *__overflow_arg_area;
5209   //   i8 *__reg_save_area;
5210   // };
5211 
5212   // Every argument occupies 8 bytes and is passed by preference in either
5213   // GPRs or FPRs.
5214   Ty = CGF.getContext().getCanonicalType(Ty);
5215   ABIArgInfo AI = classifyArgumentType(Ty);
5216   bool InFPRs = isFPArgumentType(Ty);
5217 
5218   llvm::Type *APTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
5219   bool IsIndirect = AI.isIndirect();
5220   unsigned UnpaddedBitSize;
5221   if (IsIndirect) {
5222     APTy = llvm::PointerType::getUnqual(APTy);
5223     UnpaddedBitSize = 64;
5224   } else
5225     UnpaddedBitSize = getContext().getTypeSize(Ty);
5226   unsigned PaddedBitSize = 64;
5227   assert((UnpaddedBitSize <= PaddedBitSize) && "Invalid argument size.");
5228 
5229   unsigned PaddedSize = PaddedBitSize / 8;
5230   unsigned Padding = (PaddedBitSize - UnpaddedBitSize) / 8;
5231 
5232   unsigned MaxRegs, RegCountField, RegSaveIndex, RegPadding;
5233   if (InFPRs) {
5234     MaxRegs = 4; // Maximum of 4 FPR arguments
5235     RegCountField = 1; // __fpr
5236     RegSaveIndex = 16; // save offset for f0
5237     RegPadding = 0; // floats are passed in the high bits of an FPR
5238   } else {
5239     MaxRegs = 5; // Maximum of 5 GPR arguments
5240     RegCountField = 0; // __gpr
5241     RegSaveIndex = 2; // save offset for r2
5242     RegPadding = Padding; // values are passed in the low bits of a GPR
5243   }
5244 
5245   llvm::Value *RegCountPtr =
5246     CGF.Builder.CreateStructGEP(VAListAddr, RegCountField, "reg_count_ptr");
5247   llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
5248   llvm::Type *IndexTy = RegCount->getType();
5249   llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
5250   llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
5251                                                  "fits_in_regs");
5252 
5253   llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
5254   llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
5255   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
5256   CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
5257 
5258   // Emit code to load the value if it was passed in registers.
5259   CGF.EmitBlock(InRegBlock);
5260 
5261   // Work out the address of an argument register.
5262   llvm::Value *PaddedSizeV = llvm::ConstantInt::get(IndexTy, PaddedSize);
5263   llvm::Value *ScaledRegCount =
5264     CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
5265   llvm::Value *RegBase =
5266     llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize + RegPadding);
5267   llvm::Value *RegOffset =
5268     CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
5269   llvm::Value *RegSaveAreaPtr =
5270     CGF.Builder.CreateStructGEP(VAListAddr, 3, "reg_save_area_ptr");
5271   llvm::Value *RegSaveArea =
5272     CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
5273   llvm::Value *RawRegAddr =
5274     CGF.Builder.CreateGEP(RegSaveArea, RegOffset, "raw_reg_addr");
5275   llvm::Value *RegAddr =
5276     CGF.Builder.CreateBitCast(RawRegAddr, APTy, "reg_addr");
5277 
5278   // Update the register count
5279   llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
5280   llvm::Value *NewRegCount =
5281     CGF.Builder.CreateAdd(RegCount, One, "reg_count");
5282   CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
5283   CGF.EmitBranch(ContBlock);
5284 
5285   // Emit code to load the value if it was passed in memory.
5286   CGF.EmitBlock(InMemBlock);
5287 
5288   // Work out the address of a stack argument.
5289   llvm::Value *OverflowArgAreaPtr =
5290     CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr");
5291   llvm::Value *OverflowArgArea =
5292     CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area");
5293   llvm::Value *PaddingV = llvm::ConstantInt::get(IndexTy, Padding);
5294   llvm::Value *RawMemAddr =
5295     CGF.Builder.CreateGEP(OverflowArgArea, PaddingV, "raw_mem_addr");
5296   llvm::Value *MemAddr =
5297     CGF.Builder.CreateBitCast(RawMemAddr, APTy, "mem_addr");
5298 
5299   // Update overflow_arg_area_ptr pointer
5300   llvm::Value *NewOverflowArgArea =
5301     CGF.Builder.CreateGEP(OverflowArgArea, PaddedSizeV, "overflow_arg_area");
5302   CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
5303   CGF.EmitBranch(ContBlock);
5304 
5305   // Return the appropriate result.
5306   CGF.EmitBlock(ContBlock);
5307   llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(APTy, 2, "va_arg.addr");
5308   ResAddr->addIncoming(RegAddr, InRegBlock);
5309   ResAddr->addIncoming(MemAddr, InMemBlock);
5310 
5311   if (IsIndirect)
5312     return CGF.Builder.CreateLoad(ResAddr, "indirect_arg");
5313 
5314   return ResAddr;
5315 }
5316 
5317 ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
5318   if (RetTy->isVoidType())
5319     return ABIArgInfo::getIgnore();
5320   if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
5321     return ABIArgInfo::getIndirect(0);
5322   return (isPromotableIntegerType(RetTy) ?
5323           ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5324 }
5325 
5326 ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
5327   // Handle the generic C++ ABI.
5328   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
5329     return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
5330 
5331   // Integers and enums are extended to full register width.
5332   if (isPromotableIntegerType(Ty))
5333     return ABIArgInfo::getExtend();
5334 
5335   // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
5336   uint64_t Size = getContext().getTypeSize(Ty);
5337   if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
5338     return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
5339 
5340   // Handle small structures.
5341   if (const RecordType *RT = Ty->getAs<RecordType>()) {
5342     // Structures with flexible arrays have variable length, so really
5343     // fail the size test above.
5344     const RecordDecl *RD = RT->getDecl();
5345     if (RD->hasFlexibleArrayMember())
5346       return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
5347 
5348     // The structure is passed as an unextended integer, a float, or a double.
5349     llvm::Type *PassTy;
5350     if (isFPArgumentType(Ty)) {
5351       assert(Size == 32 || Size == 64);
5352       if (Size == 32)
5353         PassTy = llvm::Type::getFloatTy(getVMContext());
5354       else
5355         PassTy = llvm::Type::getDoubleTy(getVMContext());
5356     } else
5357       PassTy = llvm::IntegerType::get(getVMContext(), Size);
5358     return ABIArgInfo::getDirect(PassTy);
5359   }
5360 
5361   // Non-structure compounds are passed indirectly.
5362   if (isCompoundType(Ty))
5363     return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
5364 
5365   return ABIArgInfo::getDirect(nullptr);
5366 }
5367 
5368 //===----------------------------------------------------------------------===//
5369 // MSP430 ABI Implementation
5370 //===----------------------------------------------------------------------===//
5371 
5372 namespace {
5373 
5374 class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
5375 public:
5376   MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
5377     : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
5378   void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5379                            CodeGen::CodeGenModule &M) const override;
5380 };
5381 
5382 }
5383 
5384 void MSP430TargetCodeGenInfo::SetTargetAttributes(const Decl *D,
5385                                                   llvm::GlobalValue *GV,
5386                                              CodeGen::CodeGenModule &M) const {
5387   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5388     if (const MSP430InterruptAttr *attr = FD->getAttr<MSP430InterruptAttr>()) {
5389       // Handle 'interrupt' attribute:
5390       llvm::Function *F = cast<llvm::Function>(GV);
5391 
5392       // Step 1: Set ISR calling convention.
5393       F->setCallingConv(llvm::CallingConv::MSP430_INTR);
5394 
5395       // Step 2: Add attributes goodness.
5396       F->addFnAttr(llvm::Attribute::NoInline);
5397 
5398       // Step 3: Emit ISR vector alias.
5399       unsigned Num = attr->getNumber() / 2;
5400       llvm::GlobalAlias::create(llvm::Function::ExternalLinkage,
5401                                 "__isr_" + Twine(Num), F);
5402     }
5403   }
5404 }
5405 
5406 //===----------------------------------------------------------------------===//
5407 // MIPS ABI Implementation.  This works for both little-endian and
5408 // big-endian variants.
5409 //===----------------------------------------------------------------------===//
5410 
5411 namespace {
5412 class MipsABIInfo : public ABIInfo {
5413   bool IsO32;
5414   unsigned MinABIStackAlignInBytes, StackAlignInBytes;
5415   void CoerceToIntArgs(uint64_t TySize,
5416                        SmallVectorImpl<llvm::Type *> &ArgList) const;
5417   llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
5418   llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
5419   llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
5420 public:
5421   MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
5422     ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
5423     StackAlignInBytes(IsO32 ? 8 : 16) {}
5424 
5425   ABIArgInfo classifyReturnType(QualType RetTy) const;
5426   ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
5427   void computeInfo(CGFunctionInfo &FI) const override;
5428   llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5429                          CodeGenFunction &CGF) const override;
5430 };
5431 
5432 class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
5433   unsigned SizeOfUnwindException;
5434 public:
5435   MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
5436     : TargetCodeGenInfo(new MipsABIInfo(CGT, IsO32)),
5437       SizeOfUnwindException(IsO32 ? 24 : 32) {}
5438 
5439   int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
5440     return 29;
5441   }
5442 
5443   void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5444                            CodeGen::CodeGenModule &CGM) const override {
5445     const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
5446     if (!FD) return;
5447     llvm::Function *Fn = cast<llvm::Function>(GV);
5448     if (FD->hasAttr<Mips16Attr>()) {
5449       Fn->addFnAttr("mips16");
5450     }
5451     else if (FD->hasAttr<NoMips16Attr>()) {
5452       Fn->addFnAttr("nomips16");
5453     }
5454   }
5455 
5456   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
5457                                llvm::Value *Address) const override;
5458 
5459   unsigned getSizeOfUnwindException() const override {
5460     return SizeOfUnwindException;
5461   }
5462 };
5463 }
5464 
5465 void MipsABIInfo::CoerceToIntArgs(uint64_t TySize,
5466                                   SmallVectorImpl<llvm::Type *> &ArgList) const {
5467   llvm::IntegerType *IntTy =
5468     llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
5469 
5470   // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
5471   for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
5472     ArgList.push_back(IntTy);
5473 
5474   // If necessary, add one more integer type to ArgList.
5475   unsigned R = TySize % (MinABIStackAlignInBytes * 8);
5476 
5477   if (R)
5478     ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
5479 }
5480 
5481 // In N32/64, an aligned double precision floating point field is passed in
5482 // a register.
5483 llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
5484   SmallVector<llvm::Type*, 8> ArgList, IntArgList;
5485 
5486   if (IsO32) {
5487     CoerceToIntArgs(TySize, ArgList);
5488     return llvm::StructType::get(getVMContext(), ArgList);
5489   }
5490 
5491   if (Ty->isComplexType())
5492     return CGT.ConvertType(Ty);
5493 
5494   const RecordType *RT = Ty->getAs<RecordType>();
5495 
5496   // Unions/vectors are passed in integer registers.
5497   if (!RT || !RT->isStructureOrClassType()) {
5498     CoerceToIntArgs(TySize, ArgList);
5499     return llvm::StructType::get(getVMContext(), ArgList);
5500   }
5501 
5502   const RecordDecl *RD = RT->getDecl();
5503   const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
5504   assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
5505 
5506   uint64_t LastOffset = 0;
5507   unsigned idx = 0;
5508   llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
5509 
5510   // Iterate over fields in the struct/class and check if there are any aligned
5511   // double fields.
5512   for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
5513        i != e; ++i, ++idx) {
5514     const QualType Ty = i->getType();
5515     const BuiltinType *BT = Ty->getAs<BuiltinType>();
5516 
5517     if (!BT || BT->getKind() != BuiltinType::Double)
5518       continue;
5519 
5520     uint64_t Offset = Layout.getFieldOffset(idx);
5521     if (Offset % 64) // Ignore doubles that are not aligned.
5522       continue;
5523 
5524     // Add ((Offset - LastOffset) / 64) args of type i64.
5525     for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
5526       ArgList.push_back(I64);
5527 
5528     // Add double type.
5529     ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
5530     LastOffset = Offset + 64;
5531   }
5532 
5533   CoerceToIntArgs(TySize - LastOffset, IntArgList);
5534   ArgList.append(IntArgList.begin(), IntArgList.end());
5535 
5536   return llvm::StructType::get(getVMContext(), ArgList);
5537 }
5538 
5539 llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
5540                                         uint64_t Offset) const {
5541   if (OrigOffset + MinABIStackAlignInBytes > Offset)
5542     return nullptr;
5543 
5544   return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
5545 }
5546 
5547 ABIArgInfo
5548 MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
5549   uint64_t OrigOffset = Offset;
5550   uint64_t TySize = getContext().getTypeSize(Ty);
5551   uint64_t Align = getContext().getTypeAlign(Ty) / 8;
5552 
5553   Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
5554                    (uint64_t)StackAlignInBytes);
5555   unsigned CurrOffset = llvm::RoundUpToAlignment(Offset, Align);
5556   Offset = CurrOffset + llvm::RoundUpToAlignment(TySize, Align * 8) / 8;
5557 
5558   if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
5559     // Ignore empty aggregates.
5560     if (TySize == 0)
5561       return ABIArgInfo::getIgnore();
5562 
5563     if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
5564       Offset = OrigOffset + MinABIStackAlignInBytes;
5565       return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
5566     }
5567 
5568     // If we have reached here, aggregates are passed directly by coercing to
5569     // another structure type. Padding is inserted if the offset of the
5570     // aggregate is unaligned.
5571     return ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
5572                                  getPaddingType(OrigOffset, CurrOffset));
5573   }
5574 
5575   // Treat an enum type as its underlying type.
5576   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5577     Ty = EnumTy->getDecl()->getIntegerType();
5578 
5579   if (Ty->isPromotableIntegerType())
5580     return ABIArgInfo::getExtend();
5581 
5582   return ABIArgInfo::getDirect(
5583       nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset));
5584 }
5585 
5586 llvm::Type*
5587 MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
5588   const RecordType *RT = RetTy->getAs<RecordType>();
5589   SmallVector<llvm::Type*, 8> RTList;
5590 
5591   if (RT && RT->isStructureOrClassType()) {
5592     const RecordDecl *RD = RT->getDecl();
5593     const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
5594     unsigned FieldCnt = Layout.getFieldCount();
5595 
5596     // N32/64 returns struct/classes in floating point registers if the
5597     // following conditions are met:
5598     // 1. The size of the struct/class is no larger than 128-bit.
5599     // 2. The struct/class has one or two fields all of which are floating
5600     //    point types.
5601     // 3. The offset of the first field is zero (this follows what gcc does).
5602     //
5603     // Any other composite results are returned in integer registers.
5604     //
5605     if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
5606       RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
5607       for (; b != e; ++b) {
5608         const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
5609 
5610         if (!BT || !BT->isFloatingPoint())
5611           break;
5612 
5613         RTList.push_back(CGT.ConvertType(b->getType()));
5614       }
5615 
5616       if (b == e)
5617         return llvm::StructType::get(getVMContext(), RTList,
5618                                      RD->hasAttr<PackedAttr>());
5619 
5620       RTList.clear();
5621     }
5622   }
5623 
5624   CoerceToIntArgs(Size, RTList);
5625   return llvm::StructType::get(getVMContext(), RTList);
5626 }
5627 
5628 ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
5629   uint64_t Size = getContext().getTypeSize(RetTy);
5630 
5631   if (RetTy->isVoidType())
5632     return ABIArgInfo::getIgnore();
5633 
5634   // O32 doesn't treat zero-sized structs differently from other structs.
5635   // However, N32/N64 ignores zero sized return values.
5636   if (!IsO32 && Size == 0)
5637     return ABIArgInfo::getIgnore();
5638 
5639   if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
5640     if (Size <= 128) {
5641       if (RetTy->isAnyComplexType())
5642         return ABIArgInfo::getDirect();
5643 
5644       // O32 returns integer vectors in registers and N32/N64 returns all small
5645       // aggregates in registers.
5646       if (!IsO32 ||
5647           (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) {
5648         ABIArgInfo ArgInfo =
5649             ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
5650         ArgInfo.setInReg(true);
5651         return ArgInfo;
5652       }
5653     }
5654 
5655     return ABIArgInfo::getIndirect(0);
5656   }
5657 
5658   // Treat an enum type as its underlying type.
5659   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5660     RetTy = EnumTy->getDecl()->getIntegerType();
5661 
5662   return (RetTy->isPromotableIntegerType() ?
5663           ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5664 }
5665 
5666 void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
5667   ABIArgInfo &RetInfo = FI.getReturnInfo();
5668   if (!getCXXABI().classifyReturnType(FI))
5669     RetInfo = classifyReturnType(FI.getReturnType());
5670 
5671   // Check if a pointer to an aggregate is passed as a hidden argument.
5672   uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
5673 
5674   for (auto &I : FI.arguments())
5675     I.info = classifyArgumentType(I.type, Offset);
5676 }
5677 
5678 llvm::Value* MipsABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5679                                     CodeGenFunction &CGF) const {
5680   llvm::Type *BP = CGF.Int8PtrTy;
5681   llvm::Type *BPP = CGF.Int8PtrPtrTy;
5682 
5683   CGBuilderTy &Builder = CGF.Builder;
5684   llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
5685   llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
5686   int64_t TypeAlign =
5687       std::min(getContext().getTypeAlign(Ty) / 8, StackAlignInBytes);
5688   llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
5689   llvm::Value *AddrTyped;
5690   unsigned PtrWidth = getTarget().getPointerWidth(0);
5691   llvm::IntegerType *IntTy = (PtrWidth == 32) ? CGF.Int32Ty : CGF.Int64Ty;
5692 
5693   if (TypeAlign > MinABIStackAlignInBytes) {
5694     llvm::Value *AddrAsInt = CGF.Builder.CreatePtrToInt(Addr, IntTy);
5695     llvm::Value *Inc = llvm::ConstantInt::get(IntTy, TypeAlign - 1);
5696     llvm::Value *Mask = llvm::ConstantInt::get(IntTy, -TypeAlign);
5697     llvm::Value *Add = CGF.Builder.CreateAdd(AddrAsInt, Inc);
5698     llvm::Value *And = CGF.Builder.CreateAnd(Add, Mask);
5699     AddrTyped = CGF.Builder.CreateIntToPtr(And, PTy);
5700   }
5701   else
5702     AddrTyped = Builder.CreateBitCast(Addr, PTy);
5703 
5704   llvm::Value *AlignedAddr = Builder.CreateBitCast(AddrTyped, BP);
5705   TypeAlign = std::max((unsigned)TypeAlign, MinABIStackAlignInBytes);
5706   uint64_t Offset =
5707     llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, TypeAlign);
5708   llvm::Value *NextAddr =
5709     Builder.CreateGEP(AlignedAddr, llvm::ConstantInt::get(IntTy, Offset),
5710                       "ap.next");
5711   Builder.CreateStore(NextAddr, VAListAddrAsBPP);
5712 
5713   return AddrTyped;
5714 }
5715 
5716 bool
5717 MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
5718                                                llvm::Value *Address) const {
5719   // This information comes from gcc's implementation, which seems to
5720   // as canonical as it gets.
5721 
5722   // Everything on MIPS is 4 bytes.  Double-precision FP registers
5723   // are aliased to pairs of single-precision FP registers.
5724   llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
5725 
5726   // 0-31 are the general purpose registers, $0 - $31.
5727   // 32-63 are the floating-point registers, $f0 - $f31.
5728   // 64 and 65 are the multiply/divide registers, $hi and $lo.
5729   // 66 is the (notional, I think) register for signal-handler return.
5730   AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
5731 
5732   // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
5733   // They are one bit wide and ignored here.
5734 
5735   // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
5736   // (coprocessor 1 is the FP unit)
5737   // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
5738   // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
5739   // 176-181 are the DSP accumulator registers.
5740   AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
5741   return false;
5742 }
5743 
5744 //===----------------------------------------------------------------------===//
5745 // TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
5746 // Currently subclassed only to implement custom OpenCL C function attribute
5747 // handling.
5748 //===----------------------------------------------------------------------===//
5749 
5750 namespace {
5751 
5752 class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
5753 public:
5754   TCETargetCodeGenInfo(CodeGenTypes &CGT)
5755     : DefaultTargetCodeGenInfo(CGT) {}
5756 
5757   void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5758                            CodeGen::CodeGenModule &M) const override;
5759 };
5760 
5761 void TCETargetCodeGenInfo::SetTargetAttributes(const Decl *D,
5762                                                llvm::GlobalValue *GV,
5763                                                CodeGen::CodeGenModule &M) const {
5764   const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
5765   if (!FD) return;
5766 
5767   llvm::Function *F = cast<llvm::Function>(GV);
5768 
5769   if (M.getLangOpts().OpenCL) {
5770     if (FD->hasAttr<OpenCLKernelAttr>()) {
5771       // OpenCL C Kernel functions are not subject to inlining
5772       F->addFnAttr(llvm::Attribute::NoInline);
5773       const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
5774       if (Attr) {
5775         // Convert the reqd_work_group_size() attributes to metadata.
5776         llvm::LLVMContext &Context = F->getContext();
5777         llvm::NamedMDNode *OpenCLMetadata =
5778             M.getModule().getOrInsertNamedMetadata("opencl.kernel_wg_size_info");
5779 
5780         SmallVector<llvm::Value*, 5> Operands;
5781         Operands.push_back(F);
5782 
5783         Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty,
5784                              llvm::APInt(32, Attr->getXDim())));
5785         Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty,
5786                              llvm::APInt(32, Attr->getYDim())));
5787         Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty,
5788                              llvm::APInt(32, Attr->getZDim())));
5789 
5790         // Add a boolean constant operand for "required" (true) or "hint" (false)
5791         // for implementing the work_group_size_hint attr later. Currently
5792         // always true as the hint is not yet implemented.
5793         Operands.push_back(llvm::ConstantInt::getTrue(Context));
5794         OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
5795       }
5796     }
5797   }
5798 }
5799 
5800 }
5801 
5802 //===----------------------------------------------------------------------===//
5803 // Hexagon ABI Implementation
5804 //===----------------------------------------------------------------------===//
5805 
5806 namespace {
5807 
5808 class HexagonABIInfo : public ABIInfo {
5809 
5810 
5811 public:
5812   HexagonABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
5813 
5814 private:
5815 
5816   ABIArgInfo classifyReturnType(QualType RetTy) const;
5817   ABIArgInfo classifyArgumentType(QualType RetTy) const;
5818 
5819   void computeInfo(CGFunctionInfo &FI) const override;
5820 
5821   llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5822                          CodeGenFunction &CGF) const override;
5823 };
5824 
5825 class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
5826 public:
5827   HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
5828     :TargetCodeGenInfo(new HexagonABIInfo(CGT)) {}
5829 
5830   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
5831     return 29;
5832   }
5833 };
5834 
5835 }
5836 
5837 void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
5838   if (!getCXXABI().classifyReturnType(FI))
5839     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
5840   for (auto &I : FI.arguments())
5841     I.info = classifyArgumentType(I.type);
5842 }
5843 
5844 ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty) const {
5845   if (!isAggregateTypeForABI(Ty)) {
5846     // Treat an enum type as its underlying type.
5847     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5848       Ty = EnumTy->getDecl()->getIntegerType();
5849 
5850     return (Ty->isPromotableIntegerType() ?
5851             ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5852   }
5853 
5854   // Ignore empty records.
5855   if (isEmptyRecord(getContext(), Ty, true))
5856     return ABIArgInfo::getIgnore();
5857 
5858   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
5859     return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
5860 
5861   uint64_t Size = getContext().getTypeSize(Ty);
5862   if (Size > 64)
5863     return ABIArgInfo::getIndirect(0, /*ByVal=*/true);
5864     // Pass in the smallest viable integer type.
5865   else if (Size > 32)
5866       return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
5867   else if (Size > 16)
5868       return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
5869   else if (Size > 8)
5870       return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5871   else
5872       return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
5873 }
5874 
5875 ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
5876   if (RetTy->isVoidType())
5877     return ABIArgInfo::getIgnore();
5878 
5879   // Large vector types should be returned via memory.
5880   if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 64)
5881     return ABIArgInfo::getIndirect(0);
5882 
5883   if (!isAggregateTypeForABI(RetTy)) {
5884     // Treat an enum type as its underlying type.
5885     if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5886       RetTy = EnumTy->getDecl()->getIntegerType();
5887 
5888     return (RetTy->isPromotableIntegerType() ?
5889             ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5890   }
5891 
5892   if (isEmptyRecord(getContext(), RetTy, true))
5893     return ABIArgInfo::getIgnore();
5894 
5895   // Aggregates <= 8 bytes are returned in r0; other aggregates
5896   // are returned indirectly.
5897   uint64_t Size = getContext().getTypeSize(RetTy);
5898   if (Size <= 64) {
5899     // Return in the smallest viable integer type.
5900     if (Size <= 8)
5901       return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
5902     if (Size <= 16)
5903       return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5904     if (Size <= 32)
5905       return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
5906     return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
5907   }
5908 
5909   return ABIArgInfo::getIndirect(0, /*ByVal=*/true);
5910 }
5911 
5912 llvm::Value *HexagonABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5913                                        CodeGenFunction &CGF) const {
5914   // FIXME: Need to handle alignment
5915   llvm::Type *BPP = CGF.Int8PtrPtrTy;
5916 
5917   CGBuilderTy &Builder = CGF.Builder;
5918   llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
5919                                                        "ap");
5920   llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
5921   llvm::Type *PTy =
5922     llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
5923   llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
5924 
5925   uint64_t Offset =
5926     llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 4);
5927   llvm::Value *NextAddr =
5928     Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
5929                       "ap.next");
5930   Builder.CreateStore(NextAddr, VAListAddrAsBPP);
5931 
5932   return AddrTyped;
5933 }
5934 
5935 
5936 //===----------------------------------------------------------------------===//
5937 // SPARC v9 ABI Implementation.
5938 // Based on the SPARC Compliance Definition version 2.4.1.
5939 //
5940 // Function arguments a mapped to a nominal "parameter array" and promoted to
5941 // registers depending on their type. Each argument occupies 8 or 16 bytes in
5942 // the array, structs larger than 16 bytes are passed indirectly.
5943 //
5944 // One case requires special care:
5945 //
5946 //   struct mixed {
5947 //     int i;
5948 //     float f;
5949 //   };
5950 //
5951 // When a struct mixed is passed by value, it only occupies 8 bytes in the
5952 // parameter array, but the int is passed in an integer register, and the float
5953 // is passed in a floating point register. This is represented as two arguments
5954 // with the LLVM IR inreg attribute:
5955 //
5956 //   declare void f(i32 inreg %i, float inreg %f)
5957 //
5958 // The code generator will only allocate 4 bytes from the parameter array for
5959 // the inreg arguments. All other arguments are allocated a multiple of 8
5960 // bytes.
5961 //
5962 namespace {
5963 class SparcV9ABIInfo : public ABIInfo {
5964 public:
5965   SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
5966 
5967 private:
5968   ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
5969   void computeInfo(CGFunctionInfo &FI) const override;
5970   llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5971                          CodeGenFunction &CGF) const override;
5972 
5973   // Coercion type builder for structs passed in registers. The coercion type
5974   // serves two purposes:
5975   //
5976   // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
5977   //    in registers.
5978   // 2. Expose aligned floating point elements as first-level elements, so the
5979   //    code generator knows to pass them in floating point registers.
5980   //
5981   // We also compute the InReg flag which indicates that the struct contains
5982   // aligned 32-bit floats.
5983   //
5984   struct CoerceBuilder {
5985     llvm::LLVMContext &Context;
5986     const llvm::DataLayout &DL;
5987     SmallVector<llvm::Type*, 8> Elems;
5988     uint64_t Size;
5989     bool InReg;
5990 
5991     CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
5992       : Context(c), DL(dl), Size(0), InReg(false) {}
5993 
5994     // Pad Elems with integers until Size is ToSize.
5995     void pad(uint64_t ToSize) {
5996       assert(ToSize >= Size && "Cannot remove elements");
5997       if (ToSize == Size)
5998         return;
5999 
6000       // Finish the current 64-bit word.
6001       uint64_t Aligned = llvm::RoundUpToAlignment(Size, 64);
6002       if (Aligned > Size && Aligned <= ToSize) {
6003         Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
6004         Size = Aligned;
6005       }
6006 
6007       // Add whole 64-bit words.
6008       while (Size + 64 <= ToSize) {
6009         Elems.push_back(llvm::Type::getInt64Ty(Context));
6010         Size += 64;
6011       }
6012 
6013       // Final in-word padding.
6014       if (Size < ToSize) {
6015         Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
6016         Size = ToSize;
6017       }
6018     }
6019 
6020     // Add a floating point element at Offset.
6021     void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
6022       // Unaligned floats are treated as integers.
6023       if (Offset % Bits)
6024         return;
6025       // The InReg flag is only required if there are any floats < 64 bits.
6026       if (Bits < 64)
6027         InReg = true;
6028       pad(Offset);
6029       Elems.push_back(Ty);
6030       Size = Offset + Bits;
6031     }
6032 
6033     // Add a struct type to the coercion type, starting at Offset (in bits).
6034     void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
6035       const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
6036       for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
6037         llvm::Type *ElemTy = StrTy->getElementType(i);
6038         uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
6039         switch (ElemTy->getTypeID()) {
6040         case llvm::Type::StructTyID:
6041           addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
6042           break;
6043         case llvm::Type::FloatTyID:
6044           addFloat(ElemOffset, ElemTy, 32);
6045           break;
6046         case llvm::Type::DoubleTyID:
6047           addFloat(ElemOffset, ElemTy, 64);
6048           break;
6049         case llvm::Type::FP128TyID:
6050           addFloat(ElemOffset, ElemTy, 128);
6051           break;
6052         case llvm::Type::PointerTyID:
6053           if (ElemOffset % 64 == 0) {
6054             pad(ElemOffset);
6055             Elems.push_back(ElemTy);
6056             Size += 64;
6057           }
6058           break;
6059         default:
6060           break;
6061         }
6062       }
6063     }
6064 
6065     // Check if Ty is a usable substitute for the coercion type.
6066     bool isUsableType(llvm::StructType *Ty) const {
6067       if (Ty->getNumElements() != Elems.size())
6068         return false;
6069       for (unsigned i = 0, e = Elems.size(); i != e; ++i)
6070         if (Elems[i] != Ty->getElementType(i))
6071           return false;
6072       return true;
6073     }
6074 
6075     // Get the coercion type as a literal struct type.
6076     llvm::Type *getType() const {
6077       if (Elems.size() == 1)
6078         return Elems.front();
6079       else
6080         return llvm::StructType::get(Context, Elems);
6081     }
6082   };
6083 };
6084 } // end anonymous namespace
6085 
6086 ABIArgInfo
6087 SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
6088   if (Ty->isVoidType())
6089     return ABIArgInfo::getIgnore();
6090 
6091   uint64_t Size = getContext().getTypeSize(Ty);
6092 
6093   // Anything too big to fit in registers is passed with an explicit indirect
6094   // pointer / sret pointer.
6095   if (Size > SizeLimit)
6096     return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
6097 
6098   // Treat an enum type as its underlying type.
6099   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6100     Ty = EnumTy->getDecl()->getIntegerType();
6101 
6102   // Integer types smaller than a register are extended.
6103   if (Size < 64 && Ty->isIntegerType())
6104     return ABIArgInfo::getExtend();
6105 
6106   // Other non-aggregates go in registers.
6107   if (!isAggregateTypeForABI(Ty))
6108     return ABIArgInfo::getDirect();
6109 
6110   // If a C++ object has either a non-trivial copy constructor or a non-trivial
6111   // destructor, it is passed with an explicit indirect pointer / sret pointer.
6112   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
6113     return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
6114 
6115   // This is a small aggregate type that should be passed in registers.
6116   // Build a coercion type from the LLVM struct type.
6117   llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
6118   if (!StrTy)
6119     return ABIArgInfo::getDirect();
6120 
6121   CoerceBuilder CB(getVMContext(), getDataLayout());
6122   CB.addStruct(0, StrTy);
6123   CB.pad(llvm::RoundUpToAlignment(CB.DL.getTypeSizeInBits(StrTy), 64));
6124 
6125   // Try to use the original type for coercion.
6126   llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
6127 
6128   if (CB.InReg)
6129     return ABIArgInfo::getDirectInReg(CoerceTy);
6130   else
6131     return ABIArgInfo::getDirect(CoerceTy);
6132 }
6133 
6134 llvm::Value *SparcV9ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
6135                                        CodeGenFunction &CGF) const {
6136   ABIArgInfo AI = classifyType(Ty, 16 * 8);
6137   llvm::Type *ArgTy = CGT.ConvertType(Ty);
6138   if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
6139     AI.setCoerceToType(ArgTy);
6140 
6141   llvm::Type *BPP = CGF.Int8PtrPtrTy;
6142   CGBuilderTy &Builder = CGF.Builder;
6143   llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
6144   llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
6145   llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
6146   llvm::Value *ArgAddr;
6147   unsigned Stride;
6148 
6149   switch (AI.getKind()) {
6150   case ABIArgInfo::Expand:
6151   case ABIArgInfo::InAlloca:
6152     llvm_unreachable("Unsupported ABI kind for va_arg");
6153 
6154   case ABIArgInfo::Extend:
6155     Stride = 8;
6156     ArgAddr = Builder
6157       .CreateConstGEP1_32(Addr, 8 - getDataLayout().getTypeAllocSize(ArgTy),
6158                           "extend");
6159     break;
6160 
6161   case ABIArgInfo::Direct:
6162     Stride = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
6163     ArgAddr = Addr;
6164     break;
6165 
6166   case ABIArgInfo::Indirect:
6167     Stride = 8;
6168     ArgAddr = Builder.CreateBitCast(Addr,
6169                                     llvm::PointerType::getUnqual(ArgPtrTy),
6170                                     "indirect");
6171     ArgAddr = Builder.CreateLoad(ArgAddr, "indirect.arg");
6172     break;
6173 
6174   case ABIArgInfo::Ignore:
6175     return llvm::UndefValue::get(ArgPtrTy);
6176   }
6177 
6178   // Update VAList.
6179   Addr = Builder.CreateConstGEP1_32(Addr, Stride, "ap.next");
6180   Builder.CreateStore(Addr, VAListAddrAsBPP);
6181 
6182   return Builder.CreatePointerCast(ArgAddr, ArgPtrTy, "arg.addr");
6183 }
6184 
6185 void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
6186   FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
6187   for (auto &I : FI.arguments())
6188     I.info = classifyType(I.type, 16 * 8);
6189 }
6190 
6191 namespace {
6192 class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
6193 public:
6194   SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
6195     : TargetCodeGenInfo(new SparcV9ABIInfo(CGT)) {}
6196 
6197   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
6198     return 14;
6199   }
6200 
6201   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
6202                                llvm::Value *Address) const override;
6203 };
6204 } // end anonymous namespace
6205 
6206 bool
6207 SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
6208                                                 llvm::Value *Address) const {
6209   // This is calculated from the LLVM and GCC tables and verified
6210   // against gcc output.  AFAIK all ABIs use the same encoding.
6211 
6212   CodeGen::CGBuilderTy &Builder = CGF.Builder;
6213 
6214   llvm::IntegerType *i8 = CGF.Int8Ty;
6215   llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
6216   llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
6217 
6218   // 0-31: the 8-byte general-purpose registers
6219   AssignToArrayRange(Builder, Address, Eight8, 0, 31);
6220 
6221   // 32-63: f0-31, the 4-byte floating-point registers
6222   AssignToArrayRange(Builder, Address, Four8, 32, 63);
6223 
6224   //   Y   = 64
6225   //   PSR = 65
6226   //   WIM = 66
6227   //   TBR = 67
6228   //   PC  = 68
6229   //   NPC = 69
6230   //   FSR = 70
6231   //   CSR = 71
6232   AssignToArrayRange(Builder, Address, Eight8, 64, 71);
6233 
6234   // 72-87: d0-15, the 8-byte floating-point registers
6235   AssignToArrayRange(Builder, Address, Eight8, 72, 87);
6236 
6237   return false;
6238 }
6239 
6240 
6241 //===----------------------------------------------------------------------===//
6242 // XCore ABI Implementation
6243 //===----------------------------------------------------------------------===//
6244 
6245 namespace {
6246 
6247 /// A SmallStringEnc instance is used to build up the TypeString by passing
6248 /// it by reference between functions that append to it.
6249 typedef llvm::SmallString<128> SmallStringEnc;
6250 
6251 /// TypeStringCache caches the meta encodings of Types.
6252 ///
6253 /// The reason for caching TypeStrings is two fold:
6254 ///   1. To cache a type's encoding for later uses;
6255 ///   2. As a means to break recursive member type inclusion.
6256 ///
6257 /// A cache Entry can have a Status of:
6258 ///   NonRecursive:   The type encoding is not recursive;
6259 ///   Recursive:      The type encoding is recursive;
6260 ///   Incomplete:     An incomplete TypeString;
6261 ///   IncompleteUsed: An incomplete TypeString that has been used in a
6262 ///                   Recursive type encoding.
6263 ///
6264 /// A NonRecursive entry will have all of its sub-members expanded as fully
6265 /// as possible. Whilst it may contain types which are recursive, the type
6266 /// itself is not recursive and thus its encoding may be safely used whenever
6267 /// the type is encountered.
6268 ///
6269 /// A Recursive entry will have all of its sub-members expanded as fully as
6270 /// possible. The type itself is recursive and it may contain other types which
6271 /// are recursive. The Recursive encoding must not be used during the expansion
6272 /// of a recursive type's recursive branch. For simplicity the code uses
6273 /// IncompleteCount to reject all usage of Recursive encodings for member types.
6274 ///
6275 /// An Incomplete entry is always a RecordType and only encodes its
6276 /// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and
6277 /// are placed into the cache during type expansion as a means to identify and
6278 /// handle recursive inclusion of types as sub-members. If there is recursion
6279 /// the entry becomes IncompleteUsed.
6280 ///
6281 /// During the expansion of a RecordType's members:
6282 ///
6283 ///   If the cache contains a NonRecursive encoding for the member type, the
6284 ///   cached encoding is used;
6285 ///
6286 ///   If the cache contains a Recursive encoding for the member type, the
6287 ///   cached encoding is 'Swapped' out, as it may be incorrect, and...
6288 ///
6289 ///   If the member is a RecordType, an Incomplete encoding is placed into the
6290 ///   cache to break potential recursive inclusion of itself as a sub-member;
6291 ///
6292 ///   Once a member RecordType has been expanded, its temporary incomplete
6293 ///   entry is removed from the cache. If a Recursive encoding was swapped out
6294 ///   it is swapped back in;
6295 ///
6296 ///   If an incomplete entry is used to expand a sub-member, the incomplete
6297 ///   entry is marked as IncompleteUsed. The cache keeps count of how many
6298 ///   IncompleteUsed entries it currently contains in IncompleteUsedCount;
6299 ///
6300 ///   If a member's encoding is found to be a NonRecursive or Recursive viz:
6301 ///   IncompleteUsedCount==0, the member's encoding is added to the cache.
6302 ///   Else the member is part of a recursive type and thus the recursion has
6303 ///   been exited too soon for the encoding to be correct for the member.
6304 ///
6305 class TypeStringCache {
6306   enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed};
6307   struct Entry {
6308     std::string Str;     // The encoded TypeString for the type.
6309     enum Status State;   // Information about the encoding in 'Str'.
6310     std::string Swapped; // A temporary place holder for a Recursive encoding
6311                          // during the expansion of RecordType's members.
6312   };
6313   std::map<const IdentifierInfo *, struct Entry> Map;
6314   unsigned IncompleteCount;     // Number of Incomplete entries in the Map.
6315   unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map.
6316 public:
6317   TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {};
6318   void addIncomplete(const IdentifierInfo *ID, std::string StubEnc);
6319   bool removeIncomplete(const IdentifierInfo *ID);
6320   void addIfComplete(const IdentifierInfo *ID, StringRef Str,
6321                      bool IsRecursive);
6322   StringRef lookupStr(const IdentifierInfo *ID);
6323 };
6324 
6325 /// TypeString encodings for enum & union fields must be order.
6326 /// FieldEncoding is a helper for this ordering process.
6327 class FieldEncoding {
6328   bool HasName;
6329   std::string Enc;
6330 public:
6331   FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {};
6332   StringRef str() {return Enc.c_str();};
6333   bool operator<(const FieldEncoding &rhs) const {
6334     if (HasName != rhs.HasName) return HasName;
6335     return Enc < rhs.Enc;
6336   }
6337 };
6338 
6339 class XCoreABIInfo : public DefaultABIInfo {
6340 public:
6341   XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
6342   llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
6343                          CodeGenFunction &CGF) const override;
6344 };
6345 
6346 class XCoreTargetCodeGenInfo : public TargetCodeGenInfo {
6347   mutable TypeStringCache TSC;
6348 public:
6349   XCoreTargetCodeGenInfo(CodeGenTypes &CGT)
6350     :TargetCodeGenInfo(new XCoreABIInfo(CGT)) {}
6351   void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
6352                     CodeGen::CodeGenModule &M) const override;
6353 };
6354 
6355 } // End anonymous namespace.
6356 
6357 llvm::Value *XCoreABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
6358                                      CodeGenFunction &CGF) const {
6359   CGBuilderTy &Builder = CGF.Builder;
6360 
6361   // Get the VAList.
6362   llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr,
6363                                                        CGF.Int8PtrPtrTy);
6364   llvm::Value *AP = Builder.CreateLoad(VAListAddrAsBPP);
6365 
6366   // Handle the argument.
6367   ABIArgInfo AI = classifyArgumentType(Ty);
6368   llvm::Type *ArgTy = CGT.ConvertType(Ty);
6369   if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
6370     AI.setCoerceToType(ArgTy);
6371   llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
6372   llvm::Value *Val;
6373   uint64_t ArgSize = 0;
6374   switch (AI.getKind()) {
6375   case ABIArgInfo::Expand:
6376   case ABIArgInfo::InAlloca:
6377     llvm_unreachable("Unsupported ABI kind for va_arg");
6378   case ABIArgInfo::Ignore:
6379     Val = llvm::UndefValue::get(ArgPtrTy);
6380     ArgSize = 0;
6381     break;
6382   case ABIArgInfo::Extend:
6383   case ABIArgInfo::Direct:
6384     Val = Builder.CreatePointerCast(AP, ArgPtrTy);
6385     ArgSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
6386     if (ArgSize < 4)
6387       ArgSize = 4;
6388     break;
6389   case ABIArgInfo::Indirect:
6390     llvm::Value *ArgAddr;
6391     ArgAddr = Builder.CreateBitCast(AP, llvm::PointerType::getUnqual(ArgPtrTy));
6392     ArgAddr = Builder.CreateLoad(ArgAddr);
6393     Val = Builder.CreatePointerCast(ArgAddr, ArgPtrTy);
6394     ArgSize = 4;
6395     break;
6396   }
6397 
6398   // Increment the VAList.
6399   if (ArgSize) {
6400     llvm::Value *APN = Builder.CreateConstGEP1_32(AP, ArgSize);
6401     Builder.CreateStore(APN, VAListAddrAsBPP);
6402   }
6403   return Val;
6404 }
6405 
6406 /// During the expansion of a RecordType, an incomplete TypeString is placed
6407 /// into the cache as a means to identify and break recursion.
6408 /// If there is a Recursive encoding in the cache, it is swapped out and will
6409 /// be reinserted by removeIncomplete().
6410 /// All other types of encoding should have been used rather than arriving here.
6411 void TypeStringCache::addIncomplete(const IdentifierInfo *ID,
6412                                     std::string StubEnc) {
6413   if (!ID)
6414     return;
6415   Entry &E = Map[ID];
6416   assert( (E.Str.empty() || E.State == Recursive) &&
6417          "Incorrectly use of addIncomplete");
6418   assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()");
6419   E.Swapped.swap(E.Str); // swap out the Recursive
6420   E.Str.swap(StubEnc);
6421   E.State = Incomplete;
6422   ++IncompleteCount;
6423 }
6424 
6425 /// Once the RecordType has been expanded, the temporary incomplete TypeString
6426 /// must be removed from the cache.
6427 /// If a Recursive was swapped out by addIncomplete(), it will be replaced.
6428 /// Returns true if the RecordType was defined recursively.
6429 bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) {
6430   if (!ID)
6431     return false;
6432   auto I = Map.find(ID);
6433   assert(I != Map.end() && "Entry not present");
6434   Entry &E = I->second;
6435   assert( (E.State == Incomplete ||
6436            E.State == IncompleteUsed) &&
6437          "Entry must be an incomplete type");
6438   bool IsRecursive = false;
6439   if (E.State == IncompleteUsed) {
6440     // We made use of our Incomplete encoding, thus we are recursive.
6441     IsRecursive = true;
6442     --IncompleteUsedCount;
6443   }
6444   if (E.Swapped.empty())
6445     Map.erase(I);
6446   else {
6447     // Swap the Recursive back.
6448     E.Swapped.swap(E.Str);
6449     E.Swapped.clear();
6450     E.State = Recursive;
6451   }
6452   --IncompleteCount;
6453   return IsRecursive;
6454 }
6455 
6456 /// Add the encoded TypeString to the cache only if it is NonRecursive or
6457 /// Recursive (viz: all sub-members were expanded as fully as possible).
6458 void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str,
6459                                     bool IsRecursive) {
6460   if (!ID || IncompleteUsedCount)
6461     return; // No key or it is is an incomplete sub-type so don't add.
6462   Entry &E = Map[ID];
6463   if (IsRecursive && !E.Str.empty()) {
6464     assert(E.State==Recursive && E.Str.size() == Str.size() &&
6465            "This is not the same Recursive entry");
6466     // The parent container was not recursive after all, so we could have used
6467     // this Recursive sub-member entry after all, but we assumed the worse when
6468     // we started viz: IncompleteCount!=0.
6469     return;
6470   }
6471   assert(E.Str.empty() && "Entry already present");
6472   E.Str = Str.str();
6473   E.State = IsRecursive? Recursive : NonRecursive;
6474 }
6475 
6476 /// Return a cached TypeString encoding for the ID. If there isn't one, or we
6477 /// are recursively expanding a type (IncompleteCount != 0) and the cached
6478 /// encoding is Recursive, return an empty StringRef.
6479 StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) {
6480   if (!ID)
6481     return StringRef();   // We have no key.
6482   auto I = Map.find(ID);
6483   if (I == Map.end())
6484     return StringRef();   // We have no encoding.
6485   Entry &E = I->second;
6486   if (E.State == Recursive && IncompleteCount)
6487     return StringRef();   // We don't use Recursive encodings for member types.
6488 
6489   if (E.State == Incomplete) {
6490     // The incomplete type is being used to break out of recursion.
6491     E.State = IncompleteUsed;
6492     ++IncompleteUsedCount;
6493   }
6494   return E.Str.c_str();
6495 }
6496 
6497 /// The XCore ABI includes a type information section that communicates symbol
6498 /// type information to the linker. The linker uses this information to verify
6499 /// safety/correctness of things such as array bound and pointers et al.
6500 /// The ABI only requires C (and XC) language modules to emit TypeStrings.
6501 /// This type information (TypeString) is emitted into meta data for all global
6502 /// symbols: definitions, declarations, functions & variables.
6503 ///
6504 /// The TypeString carries type, qualifier, name, size & value details.
6505 /// Please see 'Tools Development Guide' section 2.16.2 for format details:
6506 /// <https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf>
6507 /// The output is tested by test/CodeGen/xcore-stringtype.c.
6508 ///
6509 static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
6510                           CodeGen::CodeGenModule &CGM, TypeStringCache &TSC);
6511 
6512 /// XCore uses emitTargetMD to emit TypeString metadata for global symbols.
6513 void XCoreTargetCodeGenInfo::emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
6514                                           CodeGen::CodeGenModule &CGM) const {
6515   SmallStringEnc Enc;
6516   if (getTypeString(Enc, D, CGM, TSC)) {
6517     llvm::LLVMContext &Ctx = CGM.getModule().getContext();
6518     llvm::SmallVector<llvm::Value *, 2> MDVals;
6519     MDVals.push_back(GV);
6520     MDVals.push_back(llvm::MDString::get(Ctx, Enc.str()));
6521     llvm::NamedMDNode *MD =
6522       CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings");
6523     MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
6524   }
6525 }
6526 
6527 static bool appendType(SmallStringEnc &Enc, QualType QType,
6528                        const CodeGen::CodeGenModule &CGM,
6529                        TypeStringCache &TSC);
6530 
6531 /// Helper function for appendRecordType().
6532 /// Builds a SmallVector containing the encoded field types in declaration order.
6533 static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE,
6534                              const RecordDecl *RD,
6535                              const CodeGen::CodeGenModule &CGM,
6536                              TypeStringCache &TSC) {
6537   for (const auto *Field : RD->fields()) {
6538     SmallStringEnc Enc;
6539     Enc += "m(";
6540     Enc += Field->getName();
6541     Enc += "){";
6542     if (Field->isBitField()) {
6543       Enc += "b(";
6544       llvm::raw_svector_ostream OS(Enc);
6545       OS.resync();
6546       OS << Field->getBitWidthValue(CGM.getContext());
6547       OS.flush();
6548       Enc += ':';
6549     }
6550     if (!appendType(Enc, Field->getType(), CGM, TSC))
6551       return false;
6552     if (Field->isBitField())
6553       Enc += ')';
6554     Enc += '}';
6555     FE.push_back(FieldEncoding(!Field->getName().empty(), Enc));
6556   }
6557   return true;
6558 }
6559 
6560 /// Appends structure and union types to Enc and adds encoding to cache.
6561 /// Recursively calls appendType (via extractFieldType) for each field.
6562 /// Union types have their fields ordered according to the ABI.
6563 static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT,
6564                              const CodeGen::CodeGenModule &CGM,
6565                              TypeStringCache &TSC, const IdentifierInfo *ID) {
6566   // Append the cached TypeString if we have one.
6567   StringRef TypeString = TSC.lookupStr(ID);
6568   if (!TypeString.empty()) {
6569     Enc += TypeString;
6570     return true;
6571   }
6572 
6573   // Start to emit an incomplete TypeString.
6574   size_t Start = Enc.size();
6575   Enc += (RT->isUnionType()? 'u' : 's');
6576   Enc += '(';
6577   if (ID)
6578     Enc += ID->getName();
6579   Enc += "){";
6580 
6581   // We collect all encoded fields and order as necessary.
6582   bool IsRecursive = false;
6583   const RecordDecl *RD = RT->getDecl()->getDefinition();
6584   if (RD && !RD->field_empty()) {
6585     // An incomplete TypeString stub is placed in the cache for this RecordType
6586     // so that recursive calls to this RecordType will use it whilst building a
6587     // complete TypeString for this RecordType.
6588     SmallVector<FieldEncoding, 16> FE;
6589     std::string StubEnc(Enc.substr(Start).str());
6590     StubEnc += '}';  // StubEnc now holds a valid incomplete TypeString.
6591     TSC.addIncomplete(ID, std::move(StubEnc));
6592     if (!extractFieldType(FE, RD, CGM, TSC)) {
6593       (void) TSC.removeIncomplete(ID);
6594       return false;
6595     }
6596     IsRecursive = TSC.removeIncomplete(ID);
6597     // The ABI requires unions to be sorted but not structures.
6598     // See FieldEncoding::operator< for sort algorithm.
6599     if (RT->isUnionType())
6600       std::sort(FE.begin(), FE.end());
6601     // We can now complete the TypeString.
6602     unsigned E = FE.size();
6603     for (unsigned I = 0; I != E; ++I) {
6604       if (I)
6605         Enc += ',';
6606       Enc += FE[I].str();
6607     }
6608   }
6609   Enc += '}';
6610   TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive);
6611   return true;
6612 }
6613 
6614 /// Appends enum types to Enc and adds the encoding to the cache.
6615 static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET,
6616                            TypeStringCache &TSC,
6617                            const IdentifierInfo *ID) {
6618   // Append the cached TypeString if we have one.
6619   StringRef TypeString = TSC.lookupStr(ID);
6620   if (!TypeString.empty()) {
6621     Enc += TypeString;
6622     return true;
6623   }
6624 
6625   size_t Start = Enc.size();
6626   Enc += "e(";
6627   if (ID)
6628     Enc += ID->getName();
6629   Enc += "){";
6630 
6631   // We collect all encoded enumerations and order them alphanumerically.
6632   if (const EnumDecl *ED = ET->getDecl()->getDefinition()) {
6633     SmallVector<FieldEncoding, 16> FE;
6634     for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E;
6635          ++I) {
6636       SmallStringEnc EnumEnc;
6637       EnumEnc += "m(";
6638       EnumEnc += I->getName();
6639       EnumEnc += "){";
6640       I->getInitVal().toString(EnumEnc);
6641       EnumEnc += '}';
6642       FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc));
6643     }
6644     std::sort(FE.begin(), FE.end());
6645     unsigned E = FE.size();
6646     for (unsigned I = 0; I != E; ++I) {
6647       if (I)
6648         Enc += ',';
6649       Enc += FE[I].str();
6650     }
6651   }
6652   Enc += '}';
6653   TSC.addIfComplete(ID, Enc.substr(Start), false);
6654   return true;
6655 }
6656 
6657 /// Appends type's qualifier to Enc.
6658 /// This is done prior to appending the type's encoding.
6659 static void appendQualifier(SmallStringEnc &Enc, QualType QT) {
6660   // Qualifiers are emitted in alphabetical order.
6661   static const char *Table[] = {"","c:","r:","cr:","v:","cv:","rv:","crv:"};
6662   int Lookup = 0;
6663   if (QT.isConstQualified())
6664     Lookup += 1<<0;
6665   if (QT.isRestrictQualified())
6666     Lookup += 1<<1;
6667   if (QT.isVolatileQualified())
6668     Lookup += 1<<2;
6669   Enc += Table[Lookup];
6670 }
6671 
6672 /// Appends built-in types to Enc.
6673 static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) {
6674   const char *EncType;
6675   switch (BT->getKind()) {
6676     case BuiltinType::Void:
6677       EncType = "0";
6678       break;
6679     case BuiltinType::Bool:
6680       EncType = "b";
6681       break;
6682     case BuiltinType::Char_U:
6683       EncType = "uc";
6684       break;
6685     case BuiltinType::UChar:
6686       EncType = "uc";
6687       break;
6688     case BuiltinType::SChar:
6689       EncType = "sc";
6690       break;
6691     case BuiltinType::UShort:
6692       EncType = "us";
6693       break;
6694     case BuiltinType::Short:
6695       EncType = "ss";
6696       break;
6697     case BuiltinType::UInt:
6698       EncType = "ui";
6699       break;
6700     case BuiltinType::Int:
6701       EncType = "si";
6702       break;
6703     case BuiltinType::ULong:
6704       EncType = "ul";
6705       break;
6706     case BuiltinType::Long:
6707       EncType = "sl";
6708       break;
6709     case BuiltinType::ULongLong:
6710       EncType = "ull";
6711       break;
6712     case BuiltinType::LongLong:
6713       EncType = "sll";
6714       break;
6715     case BuiltinType::Float:
6716       EncType = "ft";
6717       break;
6718     case BuiltinType::Double:
6719       EncType = "d";
6720       break;
6721     case BuiltinType::LongDouble:
6722       EncType = "ld";
6723       break;
6724     default:
6725       return false;
6726   }
6727   Enc += EncType;
6728   return true;
6729 }
6730 
6731 /// Appends a pointer encoding to Enc before calling appendType for the pointee.
6732 static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT,
6733                               const CodeGen::CodeGenModule &CGM,
6734                               TypeStringCache &TSC) {
6735   Enc += "p(";
6736   if (!appendType(Enc, PT->getPointeeType(), CGM, TSC))
6737     return false;
6738   Enc += ')';
6739   return true;
6740 }
6741 
6742 /// Appends array encoding to Enc before calling appendType for the element.
6743 static bool appendArrayType(SmallStringEnc &Enc, QualType QT,
6744                             const ArrayType *AT,
6745                             const CodeGen::CodeGenModule &CGM,
6746                             TypeStringCache &TSC, StringRef NoSizeEnc) {
6747   if (AT->getSizeModifier() != ArrayType::Normal)
6748     return false;
6749   Enc += "a(";
6750   if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
6751     CAT->getSize().toStringUnsigned(Enc);
6752   else
6753     Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "".
6754   Enc += ':';
6755   // The Qualifiers should be attached to the type rather than the array.
6756   appendQualifier(Enc, QT);
6757   if (!appendType(Enc, AT->getElementType(), CGM, TSC))
6758     return false;
6759   Enc += ')';
6760   return true;
6761 }
6762 
6763 /// Appends a function encoding to Enc, calling appendType for the return type
6764 /// and the arguments.
6765 static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT,
6766                              const CodeGen::CodeGenModule &CGM,
6767                              TypeStringCache &TSC) {
6768   Enc += "f{";
6769   if (!appendType(Enc, FT->getReturnType(), CGM, TSC))
6770     return false;
6771   Enc += "}(";
6772   if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) {
6773     // N.B. we are only interested in the adjusted param types.
6774     auto I = FPT->param_type_begin();
6775     auto E = FPT->param_type_end();
6776     if (I != E) {
6777       do {
6778         if (!appendType(Enc, *I, CGM, TSC))
6779           return false;
6780         ++I;
6781         if (I != E)
6782           Enc += ',';
6783       } while (I != E);
6784       if (FPT->isVariadic())
6785         Enc += ",va";
6786     } else {
6787       if (FPT->isVariadic())
6788         Enc += "va";
6789       else
6790         Enc += '0';
6791     }
6792   }
6793   Enc += ')';
6794   return true;
6795 }
6796 
6797 /// Handles the type's qualifier before dispatching a call to handle specific
6798 /// type encodings.
6799 static bool appendType(SmallStringEnc &Enc, QualType QType,
6800                        const CodeGen::CodeGenModule &CGM,
6801                        TypeStringCache &TSC) {
6802 
6803   QualType QT = QType.getCanonicalType();
6804 
6805   if (const ArrayType *AT = QT->getAsArrayTypeUnsafe())
6806     // The Qualifiers should be attached to the type rather than the array.
6807     // Thus we don't call appendQualifier() here.
6808     return appendArrayType(Enc, QT, AT, CGM, TSC, "");
6809 
6810   appendQualifier(Enc, QT);
6811 
6812   if (const BuiltinType *BT = QT->getAs<BuiltinType>())
6813     return appendBuiltinType(Enc, BT);
6814 
6815   if (const PointerType *PT = QT->getAs<PointerType>())
6816     return appendPointerType(Enc, PT, CGM, TSC);
6817 
6818   if (const EnumType *ET = QT->getAs<EnumType>())
6819     return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier());
6820 
6821   if (const RecordType *RT = QT->getAsStructureType())
6822     return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
6823 
6824   if (const RecordType *RT = QT->getAsUnionType())
6825     return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
6826 
6827   if (const FunctionType *FT = QT->getAs<FunctionType>())
6828     return appendFunctionType(Enc, FT, CGM, TSC);
6829 
6830   return false;
6831 }
6832 
6833 static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
6834                           CodeGen::CodeGenModule &CGM, TypeStringCache &TSC) {
6835   if (!D)
6836     return false;
6837 
6838   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6839     if (FD->getLanguageLinkage() != CLanguageLinkage)
6840       return false;
6841     return appendType(Enc, FD->getType(), CGM, TSC);
6842   }
6843 
6844   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
6845     if (VD->getLanguageLinkage() != CLanguageLinkage)
6846       return false;
6847     QualType QT = VD->getType().getCanonicalType();
6848     if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) {
6849       // Global ArrayTypes are given a size of '*' if the size is unknown.
6850       // The Qualifiers should be attached to the type rather than the array.
6851       // Thus we don't call appendQualifier() here.
6852       return appendArrayType(Enc, QT, AT, CGM, TSC, "*");
6853     }
6854     return appendType(Enc, QT, CGM, TSC);
6855   }
6856   return false;
6857 }
6858 
6859 
6860 //===----------------------------------------------------------------------===//
6861 // Driver code
6862 //===----------------------------------------------------------------------===//
6863 
6864 const llvm::Triple &CodeGenModule::getTriple() const {
6865   return getTarget().getTriple();
6866 }
6867 
6868 bool CodeGenModule::supportsCOMDAT() const {
6869   return !getTriple().isOSBinFormatMachO();
6870 }
6871 
6872 const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
6873   if (TheTargetCodeGenInfo)
6874     return *TheTargetCodeGenInfo;
6875 
6876   const llvm::Triple &Triple = getTarget().getTriple();
6877   switch (Triple.getArch()) {
6878   default:
6879     return *(TheTargetCodeGenInfo = new DefaultTargetCodeGenInfo(Types));
6880 
6881   case llvm::Triple::le32:
6882     return *(TheTargetCodeGenInfo = new PNaClTargetCodeGenInfo(Types));
6883   case llvm::Triple::mips:
6884   case llvm::Triple::mipsel:
6885     return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, true));
6886 
6887   case llvm::Triple::mips64:
6888   case llvm::Triple::mips64el:
6889     return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, false));
6890 
6891   case llvm::Triple::aarch64:
6892   case llvm::Triple::aarch64_be: {
6893     AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS;
6894     if (getTarget().getABI() == "darwinpcs")
6895       Kind = AArch64ABIInfo::DarwinPCS;
6896 
6897     return *(TheTargetCodeGenInfo = new AArch64TargetCodeGenInfo(Types, Kind));
6898   }
6899 
6900   case llvm::Triple::arm:
6901   case llvm::Triple::armeb:
6902   case llvm::Triple::thumb:
6903   case llvm::Triple::thumbeb:
6904     {
6905       ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
6906       if (getTarget().getABI() == "apcs-gnu")
6907         Kind = ARMABIInfo::APCS;
6908       else if (CodeGenOpts.FloatABI == "hard" ||
6909                (CodeGenOpts.FloatABI != "soft" &&
6910                 Triple.getEnvironment() == llvm::Triple::GNUEABIHF))
6911         Kind = ARMABIInfo::AAPCS_VFP;
6912 
6913       switch (Triple.getOS()) {
6914         case llvm::Triple::NaCl:
6915           return *(TheTargetCodeGenInfo =
6916                    new NaClARMTargetCodeGenInfo(Types, Kind));
6917         default:
6918           return *(TheTargetCodeGenInfo =
6919                    new ARMTargetCodeGenInfo(Types, Kind));
6920       }
6921     }
6922 
6923   case llvm::Triple::ppc:
6924     return *(TheTargetCodeGenInfo = new PPC32TargetCodeGenInfo(Types));
6925   case llvm::Triple::ppc64:
6926     if (Triple.isOSBinFormatELF()) {
6927       PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1;
6928       if (getTarget().getABI() == "elfv2")
6929         Kind = PPC64_SVR4_ABIInfo::ELFv2;
6930 
6931       return *(TheTargetCodeGenInfo =
6932                new PPC64_SVR4_TargetCodeGenInfo(Types, Kind));
6933     } else
6934       return *(TheTargetCodeGenInfo = new PPC64TargetCodeGenInfo(Types));
6935   case llvm::Triple::ppc64le: {
6936     assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
6937     PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2;
6938     if (getTarget().getABI() == "elfv1")
6939       Kind = PPC64_SVR4_ABIInfo::ELFv1;
6940 
6941     return *(TheTargetCodeGenInfo =
6942              new PPC64_SVR4_TargetCodeGenInfo(Types, Kind));
6943   }
6944 
6945   case llvm::Triple::nvptx:
6946   case llvm::Triple::nvptx64:
6947     return *(TheTargetCodeGenInfo = new NVPTXTargetCodeGenInfo(Types));
6948 
6949   case llvm::Triple::msp430:
6950     return *(TheTargetCodeGenInfo = new MSP430TargetCodeGenInfo(Types));
6951 
6952   case llvm::Triple::systemz:
6953     return *(TheTargetCodeGenInfo = new SystemZTargetCodeGenInfo(Types));
6954 
6955   case llvm::Triple::tce:
6956     return *(TheTargetCodeGenInfo = new TCETargetCodeGenInfo(Types));
6957 
6958   case llvm::Triple::x86: {
6959     bool IsDarwinVectorABI = Triple.isOSDarwin();
6960     bool IsSmallStructInRegABI =
6961         X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
6962     bool IsWin32FloatStructABI = Triple.isWindowsMSVCEnvironment();
6963 
6964     if (Triple.getOS() == llvm::Triple::Win32) {
6965       return *(TheTargetCodeGenInfo =
6966                new WinX86_32TargetCodeGenInfo(Types,
6967                                               IsDarwinVectorABI, IsSmallStructInRegABI,
6968                                               IsWin32FloatStructABI,
6969                                               CodeGenOpts.NumRegisterParameters));
6970     } else {
6971       return *(TheTargetCodeGenInfo =
6972                new X86_32TargetCodeGenInfo(Types,
6973                                            IsDarwinVectorABI, IsSmallStructInRegABI,
6974                                            IsWin32FloatStructABI,
6975                                            CodeGenOpts.NumRegisterParameters));
6976     }
6977   }
6978 
6979   case llvm::Triple::x86_64: {
6980     bool HasAVX = getTarget().getABI() == "avx";
6981 
6982     switch (Triple.getOS()) {
6983     case llvm::Triple::Win32:
6984       return *(TheTargetCodeGenInfo = new WinX86_64TargetCodeGenInfo(Types));
6985     case llvm::Triple::NaCl:
6986       return *(TheTargetCodeGenInfo = new NaClX86_64TargetCodeGenInfo(Types,
6987                                                                       HasAVX));
6988     default:
6989       return *(TheTargetCodeGenInfo = new X86_64TargetCodeGenInfo(Types,
6990                                                                   HasAVX));
6991     }
6992   }
6993   case llvm::Triple::hexagon:
6994     return *(TheTargetCodeGenInfo = new HexagonTargetCodeGenInfo(Types));
6995   case llvm::Triple::sparcv9:
6996     return *(TheTargetCodeGenInfo = new SparcV9TargetCodeGenInfo(Types));
6997   case llvm::Triple::xcore:
6998     return *(TheTargetCodeGenInfo = new XCoreTargetCodeGenInfo(Types));
6999   }
7000 }
7001