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 "CodeGenFunction.h"
19 #include "clang/AST/RecordLayout.h"
20 #include "clang/CodeGen/CGFunctionInfo.h"
21 #include "clang/Frontend/CodeGenOptions.h"
22 #include "llvm/ADT/Triple.h"
23 #include "llvm/IR/DataLayout.h"
24 #include "llvm/IR/Type.h"
25 #include "llvm/Support/raw_ostream.h"
26 using namespace clang;
27 using namespace CodeGen;
28 
29 static void AssignToArrayRange(CodeGen::CGBuilderTy &Builder,
30                                llvm::Value *Array,
31                                llvm::Value *Value,
32                                unsigned FirstIndex,
33                                unsigned LastIndex) {
34   // Alternatively, we could emit this as a loop in the source.
35   for (unsigned I = FirstIndex; I <= LastIndex; ++I) {
36     llvm::Value *Cell = Builder.CreateConstInBoundsGEP1_32(Array, I);
37     Builder.CreateStore(Value, Cell);
38   }
39 }
40 
41 static bool isAggregateTypeForABI(QualType T) {
42   return !CodeGenFunction::hasScalarEvaluationKind(T) ||
43          T->isMemberFunctionPointerType();
44 }
45 
46 ABIInfo::~ABIInfo() {}
47 
48 static bool isRecordReturnIndirect(const RecordType *RT,
49                                    CGCXXABI &CXXABI) {
50   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
51   if (!RD)
52     return false;
53   return CXXABI.isReturnTypeIndirect(RD);
54 }
55 
56 
57 static bool isRecordReturnIndirect(QualType T, CGCXXABI &CXXABI) {
58   const RecordType *RT = T->getAs<RecordType>();
59   if (!RT)
60     return false;
61   return isRecordReturnIndirect(RT, CXXABI);
62 }
63 
64 static CGCXXABI::RecordArgABI getRecordArgABI(const RecordType *RT,
65                                               CGCXXABI &CXXABI) {
66   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
67   if (!RD)
68     return CGCXXABI::RAA_Default;
69   return CXXABI.getRecordArgABI(RD);
70 }
71 
72 static CGCXXABI::RecordArgABI getRecordArgABI(QualType T,
73                                               CGCXXABI &CXXABI) {
74   const RecordType *RT = T->getAs<RecordType>();
75   if (!RT)
76     return CGCXXABI::RAA_Default;
77   return getRecordArgABI(RT, CXXABI);
78 }
79 
80 CGCXXABI &ABIInfo::getCXXABI() const {
81   return CGT.getCXXABI();
82 }
83 
84 ASTContext &ABIInfo::getContext() const {
85   return CGT.getContext();
86 }
87 
88 llvm::LLVMContext &ABIInfo::getVMContext() const {
89   return CGT.getLLVMContext();
90 }
91 
92 const llvm::DataLayout &ABIInfo::getDataLayout() const {
93   return CGT.getDataLayout();
94 }
95 
96 const TargetInfo &ABIInfo::getTarget() const {
97   return CGT.getTarget();
98 }
99 
100 void ABIArgInfo::dump() const {
101   raw_ostream &OS = llvm::errs();
102   OS << "(ABIArgInfo Kind=";
103   switch (TheKind) {
104   case Direct:
105     OS << "Direct Type=";
106     if (llvm::Type *Ty = getCoerceToType())
107       Ty->print(OS);
108     else
109       OS << "null";
110     break;
111   case Extend:
112     OS << "Extend";
113     break;
114   case Ignore:
115     OS << "Ignore";
116     break;
117   case Indirect:
118     OS << "Indirect Align=" << getIndirectAlign()
119        << " ByVal=" << getIndirectByVal()
120        << " Realign=" << getIndirectRealign();
121     break;
122   case Expand:
123     OS << "Expand";
124     break;
125   }
126   OS << ")\n";
127 }
128 
129 TargetCodeGenInfo::~TargetCodeGenInfo() { delete Info; }
130 
131 // If someone can figure out a general rule for this, that would be great.
132 // It's probably just doomed to be platform-dependent, though.
133 unsigned TargetCodeGenInfo::getSizeOfUnwindException() const {
134   // Verified for:
135   //   x86-64     FreeBSD, Linux, Darwin
136   //   x86-32     FreeBSD, Linux, Darwin
137   //   PowerPC    Linux, Darwin
138   //   ARM        Darwin (*not* EABI)
139   //   AArch64    Linux
140   return 32;
141 }
142 
143 bool TargetCodeGenInfo::isNoProtoCallVariadic(const CallArgList &args,
144                                      const FunctionNoProtoType *fnType) const {
145   // The following conventions are known to require this to be false:
146   //   x86_stdcall
147   //   MIPS
148   // For everything else, we just prefer false unless we opt out.
149   return false;
150 }
151 
152 void
153 TargetCodeGenInfo::getDependentLibraryOption(llvm::StringRef Lib,
154                                              llvm::SmallString<24> &Opt) const {
155   // This assumes the user is passing a library name like "rt" instead of a
156   // filename like "librt.a/so", and that they don't care whether it's static or
157   // dynamic.
158   Opt = "-l";
159   Opt += Lib;
160 }
161 
162 static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays);
163 
164 /// isEmptyField - Return true iff a the field is "empty", that is it
165 /// is an unnamed bit-field or an (array of) empty record(s).
166 static bool isEmptyField(ASTContext &Context, const FieldDecl *FD,
167                          bool AllowArrays) {
168   if (FD->isUnnamedBitfield())
169     return true;
170 
171   QualType FT = FD->getType();
172 
173   // Constant arrays of empty records count as empty, strip them off.
174   // Constant arrays of zero length always count as empty.
175   if (AllowArrays)
176     while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
177       if (AT->getSize() == 0)
178         return true;
179       FT = AT->getElementType();
180     }
181 
182   const RecordType *RT = FT->getAs<RecordType>();
183   if (!RT)
184     return false;
185 
186   // C++ record fields are never empty, at least in the Itanium ABI.
187   //
188   // FIXME: We should use a predicate for whether this behavior is true in the
189   // current ABI.
190   if (isa<CXXRecordDecl>(RT->getDecl()))
191     return false;
192 
193   return isEmptyRecord(Context, FT, AllowArrays);
194 }
195 
196 /// isEmptyRecord - Return true iff a structure contains only empty
197 /// fields. Note that a structure with a flexible array member is not
198 /// considered empty.
199 static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) {
200   const RecordType *RT = T->getAs<RecordType>();
201   if (!RT)
202     return 0;
203   const RecordDecl *RD = RT->getDecl();
204   if (RD->hasFlexibleArrayMember())
205     return false;
206 
207   // If this is a C++ record, check the bases first.
208   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
209     for (CXXRecordDecl::base_class_const_iterator i = CXXRD->bases_begin(),
210            e = CXXRD->bases_end(); i != e; ++i)
211       if (!isEmptyRecord(Context, i->getType(), true))
212         return false;
213 
214   for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
215          i != e; ++i)
216     if (!isEmptyField(Context, *i, AllowArrays))
217       return false;
218   return true;
219 }
220 
221 /// isSingleElementStruct - Determine if a structure is a "single
222 /// element struct", i.e. it has exactly one non-empty field or
223 /// exactly one field which is itself a single element
224 /// struct. Structures with flexible array members are never
225 /// considered single element structs.
226 ///
227 /// \return The field declaration for the single non-empty field, if
228 /// it exists.
229 static const Type *isSingleElementStruct(QualType T, ASTContext &Context) {
230   const RecordType *RT = T->getAsStructureType();
231   if (!RT)
232     return 0;
233 
234   const RecordDecl *RD = RT->getDecl();
235   if (RD->hasFlexibleArrayMember())
236     return 0;
237 
238   const Type *Found = 0;
239 
240   // If this is a C++ record, check the bases first.
241   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
242     for (CXXRecordDecl::base_class_const_iterator i = CXXRD->bases_begin(),
243            e = CXXRD->bases_end(); i != e; ++i) {
244       // Ignore empty records.
245       if (isEmptyRecord(Context, i->getType(), true))
246         continue;
247 
248       // If we already found an element then this isn't a single-element struct.
249       if (Found)
250         return 0;
251 
252       // If this is non-empty and not a single element struct, the composite
253       // cannot be a single element struct.
254       Found = isSingleElementStruct(i->getType(), Context);
255       if (!Found)
256         return 0;
257     }
258   }
259 
260   // Check for single element.
261   for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
262          i != e; ++i) {
263     const FieldDecl *FD = *i;
264     QualType FT = FD->getType();
265 
266     // Ignore empty fields.
267     if (isEmptyField(Context, FD, true))
268       continue;
269 
270     // If we already found an element then this isn't a single-element
271     // struct.
272     if (Found)
273       return 0;
274 
275     // Treat single element arrays as the element.
276     while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
277       if (AT->getSize().getZExtValue() != 1)
278         break;
279       FT = AT->getElementType();
280     }
281 
282     if (!isAggregateTypeForABI(FT)) {
283       Found = FT.getTypePtr();
284     } else {
285       Found = isSingleElementStruct(FT, Context);
286       if (!Found)
287         return 0;
288     }
289   }
290 
291   // We don't consider a struct a single-element struct if it has
292   // padding beyond the element type.
293   if (Found && Context.getTypeSize(Found) != Context.getTypeSize(T))
294     return 0;
295 
296   return Found;
297 }
298 
299 static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
300   // Treat complex types as the element type.
301   if (const ComplexType *CTy = Ty->getAs<ComplexType>())
302     Ty = CTy->getElementType();
303 
304   // Check for a type which we know has a simple scalar argument-passing
305   // convention without any padding.  (We're specifically looking for 32
306   // and 64-bit integer and integer-equivalents, float, and double.)
307   if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() &&
308       !Ty->isEnumeralType() && !Ty->isBlockPointerType())
309     return false;
310 
311   uint64_t Size = Context.getTypeSize(Ty);
312   return Size == 32 || Size == 64;
313 }
314 
315 /// canExpandIndirectArgument - Test whether an argument type which is to be
316 /// passed indirectly (on the stack) would have the equivalent layout if it was
317 /// expanded into separate arguments. If so, we prefer to do the latter to avoid
318 /// inhibiting optimizations.
319 ///
320 // FIXME: This predicate is missing many cases, currently it just follows
321 // llvm-gcc (checks that all fields are 32-bit or 64-bit primitive types). We
322 // should probably make this smarter, or better yet make the LLVM backend
323 // capable of handling it.
324 static bool canExpandIndirectArgument(QualType Ty, ASTContext &Context) {
325   // We can only expand structure types.
326   const RecordType *RT = Ty->getAs<RecordType>();
327   if (!RT)
328     return false;
329 
330   // We can only expand (C) structures.
331   //
332   // FIXME: This needs to be generalized to handle classes as well.
333   const RecordDecl *RD = RT->getDecl();
334   if (!RD->isStruct() || isa<CXXRecordDecl>(RD))
335     return false;
336 
337   uint64_t Size = 0;
338 
339   for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
340          i != e; ++i) {
341     const FieldDecl *FD = *i;
342 
343     if (!is32Or64BitBasicType(FD->getType(), Context))
344       return false;
345 
346     // FIXME: Reject bit-fields wholesale; there are two problems, we don't know
347     // how to expand them yet, and the predicate for telling if a bitfield still
348     // counts as "basic" is more complicated than what we were doing previously.
349     if (FD->isBitField())
350       return false;
351 
352     Size += Context.getTypeSize(FD->getType());
353   }
354 
355   // Make sure there are not any holes in the struct.
356   if (Size != Context.getTypeSize(Ty))
357     return false;
358 
359   return true;
360 }
361 
362 namespace {
363 /// DefaultABIInfo - The default implementation for ABI specific
364 /// details. This implementation provides information which results in
365 /// self-consistent and sensible LLVM IR generation, but does not
366 /// conform to any particular ABI.
367 class DefaultABIInfo : public ABIInfo {
368 public:
369   DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
370 
371   ABIArgInfo classifyReturnType(QualType RetTy) const;
372   ABIArgInfo classifyArgumentType(QualType RetTy) const;
373 
374   virtual void computeInfo(CGFunctionInfo &FI) const {
375     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
376     for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
377          it != ie; ++it)
378       it->info = classifyArgumentType(it->type);
379   }
380 
381   virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
382                                  CodeGenFunction &CGF) const;
383 };
384 
385 class DefaultTargetCodeGenInfo : public TargetCodeGenInfo {
386 public:
387   DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
388     : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
389 };
390 
391 llvm::Value *DefaultABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
392                                        CodeGenFunction &CGF) const {
393   return 0;
394 }
395 
396 ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const {
397   if (isAggregateTypeForABI(Ty)) {
398     // Records with non trivial destructors/constructors should not be passed
399     // by value.
400     if (isRecordReturnIndirect(Ty, getCXXABI()))
401       return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
402 
403     return ABIArgInfo::getIndirect(0);
404   }
405 
406   // Treat an enum type as its underlying type.
407   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
408     Ty = EnumTy->getDecl()->getIntegerType();
409 
410   return (Ty->isPromotableIntegerType() ?
411           ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
412 }
413 
414 ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const {
415   if (RetTy->isVoidType())
416     return ABIArgInfo::getIgnore();
417 
418   if (isAggregateTypeForABI(RetTy))
419     return ABIArgInfo::getIndirect(0);
420 
421   // Treat an enum type as its underlying type.
422   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
423     RetTy = EnumTy->getDecl()->getIntegerType();
424 
425   return (RetTy->isPromotableIntegerType() ?
426           ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
427 }
428 
429 //===----------------------------------------------------------------------===//
430 // le32/PNaCl bitcode ABI Implementation
431 //
432 // This is a simplified version of the x86_32 ABI.  Arguments and return values
433 // are always passed on the stack.
434 //===----------------------------------------------------------------------===//
435 
436 class PNaClABIInfo : public ABIInfo {
437  public:
438   PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
439 
440   ABIArgInfo classifyReturnType(QualType RetTy) const;
441   ABIArgInfo classifyArgumentType(QualType RetTy) const;
442 
443   virtual void computeInfo(CGFunctionInfo &FI) const;
444   virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
445                                  CodeGenFunction &CGF) const;
446 };
447 
448 class PNaClTargetCodeGenInfo : public TargetCodeGenInfo {
449  public:
450   PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
451     : TargetCodeGenInfo(new PNaClABIInfo(CGT)) {}
452 };
453 
454 void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const {
455     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
456 
457     for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
458          it != ie; ++it)
459       it->info = classifyArgumentType(it->type);
460   }
461 
462 llvm::Value *PNaClABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
463                                        CodeGenFunction &CGF) const {
464   return 0;
465 }
466 
467 /// \brief Classify argument of given type \p Ty.
468 ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const {
469   if (isAggregateTypeForABI(Ty)) {
470     if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
471       return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
472     return ABIArgInfo::getIndirect(0);
473   } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
474     // Treat an enum type as its underlying type.
475     Ty = EnumTy->getDecl()->getIntegerType();
476   } else if (Ty->isFloatingType()) {
477     // Floating-point types don't go inreg.
478     return ABIArgInfo::getDirect();
479   }
480 
481   return (Ty->isPromotableIntegerType() ?
482           ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
483 }
484 
485 ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const {
486   if (RetTy->isVoidType())
487     return ABIArgInfo::getIgnore();
488 
489   // In the PNaCl ABI we always return records/structures on the stack.
490   if (isAggregateTypeForABI(RetTy))
491     return ABIArgInfo::getIndirect(0);
492 
493   // Treat an enum type as its underlying type.
494   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
495     RetTy = EnumTy->getDecl()->getIntegerType();
496 
497   return (RetTy->isPromotableIntegerType() ?
498           ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
499 }
500 
501 /// IsX86_MMXType - Return true if this is an MMX type.
502 bool IsX86_MMXType(llvm::Type *IRType) {
503   // Return true if the type is an MMX type <2 x i32>, <4 x i16>, or <8 x i8>.
504   return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 &&
505     cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() &&
506     IRType->getScalarSizeInBits() != 64;
507 }
508 
509 static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
510                                           StringRef Constraint,
511                                           llvm::Type* Ty) {
512   if ((Constraint == "y" || Constraint == "&y") && Ty->isVectorTy()) {
513     if (cast<llvm::VectorType>(Ty)->getBitWidth() != 64) {
514       // Invalid MMX constraint
515       return 0;
516     }
517 
518     return llvm::Type::getX86_MMXTy(CGF.getLLVMContext());
519   }
520 
521   // No operation needed
522   return Ty;
523 }
524 
525 //===----------------------------------------------------------------------===//
526 // X86-32 ABI Implementation
527 //===----------------------------------------------------------------------===//
528 
529 /// X86_32ABIInfo - The X86-32 ABI information.
530 class X86_32ABIInfo : public ABIInfo {
531   enum Class {
532     Integer,
533     Float
534   };
535 
536   static const unsigned MinABIStackAlignInBytes = 4;
537 
538   bool IsDarwinVectorABI;
539   bool IsSmallStructInRegABI;
540   bool IsWin32StructABI;
541   unsigned DefaultNumRegisterParameters;
542 
543   static bool isRegisterSize(unsigned Size) {
544     return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
545   }
546 
547   static bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context,
548                                           unsigned callingConvention);
549 
550   /// getIndirectResult - Give a source type \arg Ty, return a suitable result
551   /// such that the argument will be passed in memory.
552   ABIArgInfo getIndirectResult(QualType Ty, bool ByVal,
553                                unsigned &FreeRegs) const;
554 
555   /// \brief Return the alignment to use for the given type on the stack.
556   unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const;
557 
558   Class classify(QualType Ty) const;
559   ABIArgInfo classifyReturnType(QualType RetTy,
560                                 unsigned callingConvention) const;
561   ABIArgInfo classifyArgumentType(QualType RetTy, unsigned &FreeRegs,
562                                   bool IsFastCall) const;
563   bool shouldUseInReg(QualType Ty, unsigned &FreeRegs,
564                       bool IsFastCall, bool &NeedsPadding) const;
565 
566 public:
567 
568   virtual void computeInfo(CGFunctionInfo &FI) const;
569   virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
570                                  CodeGenFunction &CGF) const;
571 
572   X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool d, bool p, bool w,
573                 unsigned r)
574     : ABIInfo(CGT), IsDarwinVectorABI(d), IsSmallStructInRegABI(p),
575       IsWin32StructABI(w), DefaultNumRegisterParameters(r) {}
576 };
577 
578 class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
579 public:
580   X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
581       bool d, bool p, bool w, unsigned r)
582     :TargetCodeGenInfo(new X86_32ABIInfo(CGT, d, p, w, r)) {}
583 
584   static bool isStructReturnInRegABI(
585       const llvm::Triple &Triple, const CodeGenOptions &Opts);
586 
587   void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
588                            CodeGen::CodeGenModule &CGM) const;
589 
590   int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const {
591     // Darwin uses different dwarf register numbers for EH.
592     if (CGM.getTarget().getTriple().isOSDarwin()) return 5;
593     return 4;
594   }
595 
596   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
597                                llvm::Value *Address) const;
598 
599   llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
600                                   StringRef Constraint,
601                                   llvm::Type* Ty) const {
602     return X86AdjustInlineAsmType(CGF, Constraint, Ty);
603   }
604 
605   llvm::Constant *getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const {
606     unsigned Sig = (0xeb << 0) |  // jmp rel8
607                    (0x06 << 8) |  //           .+0x08
608                    ('F' << 16) |
609                    ('T' << 24);
610     return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
611   }
612 
613 };
614 
615 }
616 
617 /// shouldReturnTypeInRegister - Determine if the given type should be
618 /// passed in a register (for the Darwin ABI).
619 bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
620                                                ASTContext &Context,
621                                                unsigned callingConvention) {
622   uint64_t Size = Context.getTypeSize(Ty);
623 
624   // Type must be register sized.
625   if (!isRegisterSize(Size))
626     return false;
627 
628   if (Ty->isVectorType()) {
629     // 64- and 128- bit vectors inside structures are not returned in
630     // registers.
631     if (Size == 64 || Size == 128)
632       return false;
633 
634     return true;
635   }
636 
637   // If this is a builtin, pointer, enum, complex type, member pointer, or
638   // member function pointer it is ok.
639   if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() ||
640       Ty->isAnyComplexType() || Ty->isEnumeralType() ||
641       Ty->isBlockPointerType() || Ty->isMemberPointerType())
642     return true;
643 
644   // Arrays are treated like records.
645   if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
646     return shouldReturnTypeInRegister(AT->getElementType(), Context,
647                                       callingConvention);
648 
649   // Otherwise, it must be a record type.
650   const RecordType *RT = Ty->getAs<RecordType>();
651   if (!RT) return false;
652 
653   // FIXME: Traverse bases here too.
654 
655   // For thiscall conventions, structures will never be returned in
656   // a register.  This is for compatibility with the MSVC ABI
657   if (callingConvention == llvm::CallingConv::X86_ThisCall &&
658       RT->isStructureType()) {
659     return false;
660   }
661 
662   // Structure types are passed in register if all fields would be
663   // passed in a register.
664   for (RecordDecl::field_iterator i = RT->getDecl()->field_begin(),
665          e = RT->getDecl()->field_end(); i != e; ++i) {
666     const FieldDecl *FD = *i;
667 
668     // Empty fields are ignored.
669     if (isEmptyField(Context, FD, true))
670       continue;
671 
672     // Check fields recursively.
673     if (!shouldReturnTypeInRegister(FD->getType(), Context,
674                                     callingConvention))
675       return false;
676   }
677   return true;
678 }
679 
680 ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy,
681                                             unsigned callingConvention) const {
682   if (RetTy->isVoidType())
683     return ABIArgInfo::getIgnore();
684 
685   if (const VectorType *VT = RetTy->getAs<VectorType>()) {
686     // On Darwin, some vectors are returned in registers.
687     if (IsDarwinVectorABI) {
688       uint64_t Size = getContext().getTypeSize(RetTy);
689 
690       // 128-bit vectors are a special case; they are returned in
691       // registers and we need to make sure to pick a type the LLVM
692       // backend will like.
693       if (Size == 128)
694         return ABIArgInfo::getDirect(llvm::VectorType::get(
695                   llvm::Type::getInt64Ty(getVMContext()), 2));
696 
697       // Always return in register if it fits in a general purpose
698       // register, or if it is 64 bits and has a single element.
699       if ((Size == 8 || Size == 16 || Size == 32) ||
700           (Size == 64 && VT->getNumElements() == 1))
701         return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
702                                                             Size));
703 
704       return ABIArgInfo::getIndirect(0);
705     }
706 
707     return ABIArgInfo::getDirect();
708   }
709 
710   if (isAggregateTypeForABI(RetTy)) {
711     if (const RecordType *RT = RetTy->getAs<RecordType>()) {
712       if (isRecordReturnIndirect(RT, getCXXABI()))
713         return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
714 
715       // Structures with flexible arrays are always indirect.
716       if (RT->getDecl()->hasFlexibleArrayMember())
717         return ABIArgInfo::getIndirect(0);
718     }
719 
720     // If specified, structs and unions are always indirect.
721     if (!IsSmallStructInRegABI && !RetTy->isAnyComplexType())
722       return ABIArgInfo::getIndirect(0);
723 
724     // Small structures which are register sized are generally returned
725     // in a register.
726     if (X86_32ABIInfo::shouldReturnTypeInRegister(RetTy, getContext(),
727                                                   callingConvention)) {
728       uint64_t Size = getContext().getTypeSize(RetTy);
729 
730       // As a special-case, if the struct is a "single-element" struct, and
731       // the field is of type "float" or "double", return it in a
732       // floating-point register. (MSVC does not apply this special case.)
733       // We apply a similar transformation for pointer types to improve the
734       // quality of the generated IR.
735       if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
736         if ((!IsWin32StructABI && SeltTy->isRealFloatingType())
737             || SeltTy->hasPointerRepresentation())
738           return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
739 
740       // FIXME: We should be able to narrow this integer in cases with dead
741       // padding.
742       return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
743     }
744 
745     return ABIArgInfo::getIndirect(0);
746   }
747 
748   // Treat an enum type as its underlying type.
749   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
750     RetTy = EnumTy->getDecl()->getIntegerType();
751 
752   return (RetTy->isPromotableIntegerType() ?
753           ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
754 }
755 
756 static bool isSSEVectorType(ASTContext &Context, QualType Ty) {
757   return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128;
758 }
759 
760 static bool isRecordWithSSEVectorType(ASTContext &Context, QualType Ty) {
761   const RecordType *RT = Ty->getAs<RecordType>();
762   if (!RT)
763     return 0;
764   const RecordDecl *RD = RT->getDecl();
765 
766   // If this is a C++ record, check the bases first.
767   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
768     for (CXXRecordDecl::base_class_const_iterator i = CXXRD->bases_begin(),
769            e = CXXRD->bases_end(); i != e; ++i)
770       if (!isRecordWithSSEVectorType(Context, i->getType()))
771         return false;
772 
773   for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
774        i != e; ++i) {
775     QualType FT = i->getType();
776 
777     if (isSSEVectorType(Context, FT))
778       return true;
779 
780     if (isRecordWithSSEVectorType(Context, FT))
781       return true;
782   }
783 
784   return false;
785 }
786 
787 unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
788                                                  unsigned Align) const {
789   // Otherwise, if the alignment is less than or equal to the minimum ABI
790   // alignment, just use the default; the backend will handle this.
791   if (Align <= MinABIStackAlignInBytes)
792     return 0; // Use default alignment.
793 
794   // On non-Darwin, the stack type alignment is always 4.
795   if (!IsDarwinVectorABI) {
796     // Set explicit alignment, since we may need to realign the top.
797     return MinABIStackAlignInBytes;
798   }
799 
800   // Otherwise, if the type contains an SSE vector type, the alignment is 16.
801   if (Align >= 16 && (isSSEVectorType(getContext(), Ty) ||
802                       isRecordWithSSEVectorType(getContext(), Ty)))
803     return 16;
804 
805   return MinABIStackAlignInBytes;
806 }
807 
808 ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal,
809                                             unsigned &FreeRegs) const {
810   if (!ByVal) {
811     if (FreeRegs) {
812       --FreeRegs; // Non byval indirects just use one pointer.
813       return ABIArgInfo::getIndirectInReg(0, false);
814     }
815     return ABIArgInfo::getIndirect(0, false);
816   }
817 
818   // Compute the byval alignment.
819   unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
820   unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign);
821   if (StackAlign == 0)
822     return ABIArgInfo::getIndirect(4);
823 
824   // If the stack alignment is less than the type alignment, realign the
825   // argument.
826   if (StackAlign < TypeAlign)
827     return ABIArgInfo::getIndirect(StackAlign, /*ByVal=*/true,
828                                    /*Realign=*/true);
829 
830   return ABIArgInfo::getIndirect(StackAlign);
831 }
832 
833 X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const {
834   const Type *T = isSingleElementStruct(Ty, getContext());
835   if (!T)
836     T = Ty.getTypePtr();
837 
838   if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
839     BuiltinType::Kind K = BT->getKind();
840     if (K == BuiltinType::Float || K == BuiltinType::Double)
841       return Float;
842   }
843   return Integer;
844 }
845 
846 bool X86_32ABIInfo::shouldUseInReg(QualType Ty, unsigned &FreeRegs,
847                                    bool IsFastCall, bool &NeedsPadding) const {
848   NeedsPadding = false;
849   Class C = classify(Ty);
850   if (C == Float)
851     return false;
852 
853   unsigned Size = getContext().getTypeSize(Ty);
854   unsigned SizeInRegs = (Size + 31) / 32;
855 
856   if (SizeInRegs == 0)
857     return false;
858 
859   if (SizeInRegs > FreeRegs) {
860     FreeRegs = 0;
861     return false;
862   }
863 
864   FreeRegs -= SizeInRegs;
865 
866   if (IsFastCall) {
867     if (Size > 32)
868       return false;
869 
870     if (Ty->isIntegralOrEnumerationType())
871       return true;
872 
873     if (Ty->isPointerType())
874       return true;
875 
876     if (Ty->isReferenceType())
877       return true;
878 
879     if (FreeRegs)
880       NeedsPadding = true;
881 
882     return false;
883   }
884 
885   return true;
886 }
887 
888 ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
889                                                unsigned &FreeRegs,
890                                                bool IsFastCall) const {
891   // FIXME: Set alignment on indirect arguments.
892   if (isAggregateTypeForABI(Ty)) {
893     if (const RecordType *RT = Ty->getAs<RecordType>()) {
894       if (IsWin32StructABI)
895         return getIndirectResult(Ty, true, FreeRegs);
896 
897       if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
898         return getIndirectResult(Ty, RAA == CGCXXABI::RAA_DirectInMemory, FreeRegs);
899 
900       // Structures with flexible arrays are always indirect.
901       if (RT->getDecl()->hasFlexibleArrayMember())
902         return getIndirectResult(Ty, true, FreeRegs);
903     }
904 
905     // Ignore empty structs/unions.
906     if (isEmptyRecord(getContext(), Ty, true))
907       return ABIArgInfo::getIgnore();
908 
909     llvm::LLVMContext &LLVMContext = getVMContext();
910     llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
911     bool NeedsPadding;
912     if (shouldUseInReg(Ty, FreeRegs, IsFastCall, NeedsPadding)) {
913       unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
914       SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32);
915       llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
916       return ABIArgInfo::getDirectInReg(Result);
917     }
918     llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : 0;
919 
920     // Expand small (<= 128-bit) record types when we know that the stack layout
921     // of those arguments will match the struct. This is important because the
922     // LLVM backend isn't smart enough to remove byval, which inhibits many
923     // optimizations.
924     if (getContext().getTypeSize(Ty) <= 4*32 &&
925         canExpandIndirectArgument(Ty, getContext()))
926       return ABIArgInfo::getExpandWithPadding(IsFastCall, PaddingType);
927 
928     return getIndirectResult(Ty, true, FreeRegs);
929   }
930 
931   if (const VectorType *VT = Ty->getAs<VectorType>()) {
932     // On Darwin, some vectors are passed in memory, we handle this by passing
933     // it as an i8/i16/i32/i64.
934     if (IsDarwinVectorABI) {
935       uint64_t Size = getContext().getTypeSize(Ty);
936       if ((Size == 8 || Size == 16 || Size == 32) ||
937           (Size == 64 && VT->getNumElements() == 1))
938         return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
939                                                             Size));
940     }
941 
942     if (IsX86_MMXType(CGT.ConvertType(Ty)))
943       return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64));
944 
945     return ABIArgInfo::getDirect();
946   }
947 
948 
949   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
950     Ty = EnumTy->getDecl()->getIntegerType();
951 
952   bool NeedsPadding;
953   bool InReg = shouldUseInReg(Ty, FreeRegs, IsFastCall, NeedsPadding);
954 
955   if (Ty->isPromotableIntegerType()) {
956     if (InReg)
957       return ABIArgInfo::getExtendInReg();
958     return ABIArgInfo::getExtend();
959   }
960   if (InReg)
961     return ABIArgInfo::getDirectInReg();
962   return ABIArgInfo::getDirect();
963 }
964 
965 void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const {
966   FI.getReturnInfo() = classifyReturnType(FI.getReturnType(),
967                                           FI.getCallingConvention());
968 
969   unsigned CC = FI.getCallingConvention();
970   bool IsFastCall = CC == llvm::CallingConv::X86_FastCall;
971   unsigned FreeRegs;
972   if (IsFastCall)
973     FreeRegs = 2;
974   else if (FI.getHasRegParm())
975     FreeRegs = FI.getRegParm();
976   else
977     FreeRegs = DefaultNumRegisterParameters;
978 
979   // If the return value is indirect, then the hidden argument is consuming one
980   // integer register.
981   if (FI.getReturnInfo().isIndirect() && FreeRegs) {
982     --FreeRegs;
983     ABIArgInfo &Old = FI.getReturnInfo();
984     Old = ABIArgInfo::getIndirectInReg(Old.getIndirectAlign(),
985                                        Old.getIndirectByVal(),
986                                        Old.getIndirectRealign());
987   }
988 
989   for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
990        it != ie; ++it)
991     it->info = classifyArgumentType(it->type, FreeRegs, IsFastCall);
992 }
993 
994 llvm::Value *X86_32ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
995                                       CodeGenFunction &CGF) const {
996   llvm::Type *BPP = CGF.Int8PtrPtrTy;
997 
998   CGBuilderTy &Builder = CGF.Builder;
999   llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
1000                                                        "ap");
1001   llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
1002 
1003   // Compute if the address needs to be aligned
1004   unsigned Align = CGF.getContext().getTypeAlignInChars(Ty).getQuantity();
1005   Align = getTypeStackAlignInBytes(Ty, Align);
1006   Align = std::max(Align, 4U);
1007   if (Align > 4) {
1008     // addr = (addr + align - 1) & -align;
1009     llvm::Value *Offset =
1010       llvm::ConstantInt::get(CGF.Int32Ty, Align - 1);
1011     Addr = CGF.Builder.CreateGEP(Addr, Offset);
1012     llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(Addr,
1013                                                     CGF.Int32Ty);
1014     llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int32Ty, -Align);
1015     Addr = CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask),
1016                                       Addr->getType(),
1017                                       "ap.cur.aligned");
1018   }
1019 
1020   llvm::Type *PTy =
1021     llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
1022   llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
1023 
1024   uint64_t Offset =
1025     llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, Align);
1026   llvm::Value *NextAddr =
1027     Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
1028                       "ap.next");
1029   Builder.CreateStore(NextAddr, VAListAddrAsBPP);
1030 
1031   return AddrTyped;
1032 }
1033 
1034 void X86_32TargetCodeGenInfo::SetTargetAttributes(const Decl *D,
1035                                                   llvm::GlobalValue *GV,
1036                                             CodeGen::CodeGenModule &CGM) const {
1037   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1038     if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
1039       // Get the LLVM function.
1040       llvm::Function *Fn = cast<llvm::Function>(GV);
1041 
1042       // Now add the 'alignstack' attribute with a value of 16.
1043       llvm::AttrBuilder B;
1044       B.addStackAlignmentAttr(16);
1045       Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
1046                       llvm::AttributeSet::get(CGM.getLLVMContext(),
1047                                               llvm::AttributeSet::FunctionIndex,
1048                                               B));
1049     }
1050   }
1051 }
1052 
1053 bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
1054                                                CodeGen::CodeGenFunction &CGF,
1055                                                llvm::Value *Address) const {
1056   CodeGen::CGBuilderTy &Builder = CGF.Builder;
1057 
1058   llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
1059 
1060   // 0-7 are the eight integer registers;  the order is different
1061   //   on Darwin (for EH), but the range is the same.
1062   // 8 is %eip.
1063   AssignToArrayRange(Builder, Address, Four8, 0, 8);
1064 
1065   if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
1066     // 12-16 are st(0..4).  Not sure why we stop at 4.
1067     // These have size 16, which is sizeof(long double) on
1068     // platforms with 8-byte alignment for that type.
1069     llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
1070     AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
1071 
1072   } else {
1073     // 9 is %eflags, which doesn't get a size on Darwin for some
1074     // reason.
1075     Builder.CreateStore(Four8, Builder.CreateConstInBoundsGEP1_32(Address, 9));
1076 
1077     // 11-16 are st(0..5).  Not sure why we stop at 5.
1078     // These have size 12, which is sizeof(long double) on
1079     // platforms with 4-byte alignment for that type.
1080     llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
1081     AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
1082   }
1083 
1084   return false;
1085 }
1086 
1087 //===----------------------------------------------------------------------===//
1088 // X86-64 ABI Implementation
1089 //===----------------------------------------------------------------------===//
1090 
1091 
1092 namespace {
1093 /// X86_64ABIInfo - The X86_64 ABI information.
1094 class X86_64ABIInfo : public ABIInfo {
1095   enum Class {
1096     Integer = 0,
1097     SSE,
1098     SSEUp,
1099     X87,
1100     X87Up,
1101     ComplexX87,
1102     NoClass,
1103     Memory
1104   };
1105 
1106   /// merge - Implement the X86_64 ABI merging algorithm.
1107   ///
1108   /// Merge an accumulating classification \arg Accum with a field
1109   /// classification \arg Field.
1110   ///
1111   /// \param Accum - The accumulating classification. This should
1112   /// always be either NoClass or the result of a previous merge
1113   /// call. In addition, this should never be Memory (the caller
1114   /// should just return Memory for the aggregate).
1115   static Class merge(Class Accum, Class Field);
1116 
1117   /// postMerge - Implement the X86_64 ABI post merging algorithm.
1118   ///
1119   /// Post merger cleanup, reduces a malformed Hi and Lo pair to
1120   /// final MEMORY or SSE classes when necessary.
1121   ///
1122   /// \param AggregateSize - The size of the current aggregate in
1123   /// the classification process.
1124   ///
1125   /// \param Lo - The classification for the parts of the type
1126   /// residing in the low word of the containing object.
1127   ///
1128   /// \param Hi - The classification for the parts of the type
1129   /// residing in the higher words of the containing object.
1130   ///
1131   void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
1132 
1133   /// classify - Determine the x86_64 register classes in which the
1134   /// given type T should be passed.
1135   ///
1136   /// \param Lo - The classification for the parts of the type
1137   /// residing in the low word of the containing object.
1138   ///
1139   /// \param Hi - The classification for the parts of the type
1140   /// residing in the high word of the containing object.
1141   ///
1142   /// \param OffsetBase - The bit offset of this type in the
1143   /// containing object.  Some parameters are classified different
1144   /// depending on whether they straddle an eightbyte boundary.
1145   ///
1146   /// \param isNamedArg - Whether the argument in question is a "named"
1147   /// argument, as used in AMD64-ABI 3.5.7.
1148   ///
1149   /// If a word is unused its result will be NoClass; if a type should
1150   /// be passed in Memory then at least the classification of \arg Lo
1151   /// will be Memory.
1152   ///
1153   /// The \arg Lo class will be NoClass iff the argument is ignored.
1154   ///
1155   /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
1156   /// also be ComplexX87.
1157   void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi,
1158                 bool isNamedArg) const;
1159 
1160   llvm::Type *GetByteVectorType(QualType Ty) const;
1161   llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
1162                                  unsigned IROffset, QualType SourceTy,
1163                                  unsigned SourceOffset) const;
1164   llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
1165                                      unsigned IROffset, QualType SourceTy,
1166                                      unsigned SourceOffset) const;
1167 
1168   /// getIndirectResult - Give a source type \arg Ty, return a suitable result
1169   /// such that the argument will be returned in memory.
1170   ABIArgInfo getIndirectReturnResult(QualType Ty) const;
1171 
1172   /// getIndirectResult - Give a source type \arg Ty, return a suitable result
1173   /// such that the argument will be passed in memory.
1174   ///
1175   /// \param freeIntRegs - The number of free integer registers remaining
1176   /// available.
1177   ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
1178 
1179   ABIArgInfo classifyReturnType(QualType RetTy) const;
1180 
1181   ABIArgInfo classifyArgumentType(QualType Ty,
1182                                   unsigned freeIntRegs,
1183                                   unsigned &neededInt,
1184                                   unsigned &neededSSE,
1185                                   bool isNamedArg) const;
1186 
1187   bool IsIllegalVectorType(QualType Ty) const;
1188 
1189   /// The 0.98 ABI revision clarified a lot of ambiguities,
1190   /// unfortunately in ways that were not always consistent with
1191   /// certain previous compilers.  In particular, platforms which
1192   /// required strict binary compatibility with older versions of GCC
1193   /// may need to exempt themselves.
1194   bool honorsRevision0_98() const {
1195     return !getTarget().getTriple().isOSDarwin();
1196   }
1197 
1198   bool HasAVX;
1199   // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
1200   // 64-bit hardware.
1201   bool Has64BitPointers;
1202 
1203 public:
1204   X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, bool hasavx) :
1205       ABIInfo(CGT), HasAVX(hasavx),
1206       Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {
1207   }
1208 
1209   bool isPassedUsingAVXType(QualType type) const {
1210     unsigned neededInt, neededSSE;
1211     // The freeIntRegs argument doesn't matter here.
1212     ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE,
1213                                            /*isNamedArg*/true);
1214     if (info.isDirect()) {
1215       llvm::Type *ty = info.getCoerceToType();
1216       if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
1217         return (vectorTy->getBitWidth() > 128);
1218     }
1219     return false;
1220   }
1221 
1222   virtual void computeInfo(CGFunctionInfo &FI) const;
1223 
1224   virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1225                                  CodeGenFunction &CGF) const;
1226 };
1227 
1228 /// WinX86_64ABIInfo - The Windows X86_64 ABI information.
1229 class WinX86_64ABIInfo : public ABIInfo {
1230 
1231   ABIArgInfo classify(QualType Ty, bool IsReturnType) const;
1232 
1233 public:
1234   WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
1235 
1236   virtual void computeInfo(CGFunctionInfo &FI) const;
1237 
1238   virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1239                                  CodeGenFunction &CGF) const;
1240 };
1241 
1242 class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
1243 public:
1244   X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX)
1245       : TargetCodeGenInfo(new X86_64ABIInfo(CGT, HasAVX)) {}
1246 
1247   const X86_64ABIInfo &getABIInfo() const {
1248     return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
1249   }
1250 
1251   int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const {
1252     return 7;
1253   }
1254 
1255   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
1256                                llvm::Value *Address) const {
1257     llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
1258 
1259     // 0-15 are the 16 integer registers.
1260     // 16 is %rip.
1261     AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
1262     return false;
1263   }
1264 
1265   llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
1266                                   StringRef Constraint,
1267                                   llvm::Type* Ty) const {
1268     return X86AdjustInlineAsmType(CGF, Constraint, Ty);
1269   }
1270 
1271   bool isNoProtoCallVariadic(const CallArgList &args,
1272                              const FunctionNoProtoType *fnType) const {
1273     // The default CC on x86-64 sets %al to the number of SSA
1274     // registers used, and GCC sets this when calling an unprototyped
1275     // function, so we override the default behavior.  However, don't do
1276     // that when AVX types are involved: the ABI explicitly states it is
1277     // undefined, and it doesn't work in practice because of how the ABI
1278     // defines varargs anyway.
1279     if (fnType->getCallConv() == CC_C) {
1280       bool HasAVXType = false;
1281       for (CallArgList::const_iterator
1282              it = args.begin(), ie = args.end(); it != ie; ++it) {
1283         if (getABIInfo().isPassedUsingAVXType(it->Ty)) {
1284           HasAVXType = true;
1285           break;
1286         }
1287       }
1288 
1289       if (!HasAVXType)
1290         return true;
1291     }
1292 
1293     return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
1294   }
1295 
1296   llvm::Constant *getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const {
1297     unsigned Sig = (0xeb << 0) |  // jmp rel8
1298                    (0x0a << 8) |  //           .+0x0c
1299                    ('F' << 16) |
1300                    ('T' << 24);
1301     return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
1302   }
1303 
1304 };
1305 
1306 static std::string qualifyWindowsLibrary(llvm::StringRef Lib) {
1307   // If the argument does not end in .lib, automatically add the suffix. This
1308   // matches the behavior of MSVC.
1309   std::string ArgStr = Lib;
1310   if (Lib.size() <= 4 ||
1311       Lib.substr(Lib.size() - 4).compare_lower(".lib") != 0) {
1312     ArgStr += ".lib";
1313   }
1314   return ArgStr;
1315 }
1316 
1317 class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
1318 public:
1319   WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
1320         bool d, bool p, bool w, unsigned RegParms)
1321     : X86_32TargetCodeGenInfo(CGT, d, p, w, RegParms) {}
1322 
1323   void getDependentLibraryOption(llvm::StringRef Lib,
1324                                  llvm::SmallString<24> &Opt) const {
1325     Opt = "/DEFAULTLIB:";
1326     Opt += qualifyWindowsLibrary(Lib);
1327   }
1328 
1329   void getDetectMismatchOption(llvm::StringRef Name,
1330                                llvm::StringRef Value,
1331                                llvm::SmallString<32> &Opt) const {
1332     Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
1333   }
1334 };
1335 
1336 class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
1337 public:
1338   WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
1339     : TargetCodeGenInfo(new WinX86_64ABIInfo(CGT)) {}
1340 
1341   int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const {
1342     return 7;
1343   }
1344 
1345   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
1346                                llvm::Value *Address) const {
1347     llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
1348 
1349     // 0-15 are the 16 integer registers.
1350     // 16 is %rip.
1351     AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
1352     return false;
1353   }
1354 
1355   void getDependentLibraryOption(llvm::StringRef Lib,
1356                                  llvm::SmallString<24> &Opt) const {
1357     Opt = "/DEFAULTLIB:";
1358     Opt += qualifyWindowsLibrary(Lib);
1359   }
1360 
1361   void getDetectMismatchOption(llvm::StringRef Name,
1362                                llvm::StringRef Value,
1363                                llvm::SmallString<32> &Opt) const {
1364     Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
1365   }
1366 };
1367 
1368 }
1369 
1370 void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
1371                               Class &Hi) const {
1372   // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
1373   //
1374   // (a) If one of the classes is Memory, the whole argument is passed in
1375   //     memory.
1376   //
1377   // (b) If X87UP is not preceded by X87, the whole argument is passed in
1378   //     memory.
1379   //
1380   // (c) If the size of the aggregate exceeds two eightbytes and the first
1381   //     eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
1382   //     argument is passed in memory. NOTE: This is necessary to keep the
1383   //     ABI working for processors that don't support the __m256 type.
1384   //
1385   // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
1386   //
1387   // Some of these are enforced by the merging logic.  Others can arise
1388   // only with unions; for example:
1389   //   union { _Complex double; unsigned; }
1390   //
1391   // Note that clauses (b) and (c) were added in 0.98.
1392   //
1393   if (Hi == Memory)
1394     Lo = Memory;
1395   if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
1396     Lo = Memory;
1397   if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
1398     Lo = Memory;
1399   if (Hi == SSEUp && Lo != SSE)
1400     Hi = SSE;
1401 }
1402 
1403 X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
1404   // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
1405   // classified recursively so that always two fields are
1406   // considered. The resulting class is calculated according to
1407   // the classes of the fields in the eightbyte:
1408   //
1409   // (a) If both classes are equal, this is the resulting class.
1410   //
1411   // (b) If one of the classes is NO_CLASS, the resulting class is
1412   // the other class.
1413   //
1414   // (c) If one of the classes is MEMORY, the result is the MEMORY
1415   // class.
1416   //
1417   // (d) If one of the classes is INTEGER, the result is the
1418   // INTEGER.
1419   //
1420   // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
1421   // MEMORY is used as class.
1422   //
1423   // (f) Otherwise class SSE is used.
1424 
1425   // Accum should never be memory (we should have returned) or
1426   // ComplexX87 (because this cannot be passed in a structure).
1427   assert((Accum != Memory && Accum != ComplexX87) &&
1428          "Invalid accumulated classification during merge.");
1429   if (Accum == Field || Field == NoClass)
1430     return Accum;
1431   if (Field == Memory)
1432     return Memory;
1433   if (Accum == NoClass)
1434     return Field;
1435   if (Accum == Integer || Field == Integer)
1436     return Integer;
1437   if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
1438       Accum == X87 || Accum == X87Up)
1439     return Memory;
1440   return SSE;
1441 }
1442 
1443 void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
1444                              Class &Lo, Class &Hi, bool isNamedArg) const {
1445   // FIXME: This code can be simplified by introducing a simple value class for
1446   // Class pairs with appropriate constructor methods for the various
1447   // situations.
1448 
1449   // FIXME: Some of the split computations are wrong; unaligned vectors
1450   // shouldn't be passed in registers for example, so there is no chance they
1451   // can straddle an eightbyte. Verify & simplify.
1452 
1453   Lo = Hi = NoClass;
1454 
1455   Class &Current = OffsetBase < 64 ? Lo : Hi;
1456   Current = Memory;
1457 
1458   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
1459     BuiltinType::Kind k = BT->getKind();
1460 
1461     if (k == BuiltinType::Void) {
1462       Current = NoClass;
1463     } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
1464       Lo = Integer;
1465       Hi = Integer;
1466     } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
1467       Current = Integer;
1468     } else if ((k == BuiltinType::Float || k == BuiltinType::Double) ||
1469                (k == BuiltinType::LongDouble &&
1470                 getTarget().getTriple().isOSNaCl())) {
1471       Current = SSE;
1472     } else if (k == BuiltinType::LongDouble) {
1473       Lo = X87;
1474       Hi = X87Up;
1475     }
1476     // FIXME: _Decimal32 and _Decimal64 are SSE.
1477     // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
1478     return;
1479   }
1480 
1481   if (const EnumType *ET = Ty->getAs<EnumType>()) {
1482     // Classify the underlying integer type.
1483     classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
1484     return;
1485   }
1486 
1487   if (Ty->hasPointerRepresentation()) {
1488     Current = Integer;
1489     return;
1490   }
1491 
1492   if (Ty->isMemberPointerType()) {
1493     if (Ty->isMemberFunctionPointerType() && Has64BitPointers)
1494       Lo = Hi = Integer;
1495     else
1496       Current = Integer;
1497     return;
1498   }
1499 
1500   if (const VectorType *VT = Ty->getAs<VectorType>()) {
1501     uint64_t Size = getContext().getTypeSize(VT);
1502     if (Size == 32) {
1503       // gcc passes all <4 x char>, <2 x short>, <1 x int>, <1 x
1504       // float> as integer.
1505       Current = Integer;
1506 
1507       // If this type crosses an eightbyte boundary, it should be
1508       // split.
1509       uint64_t EB_Real = (OffsetBase) / 64;
1510       uint64_t EB_Imag = (OffsetBase + Size - 1) / 64;
1511       if (EB_Real != EB_Imag)
1512         Hi = Lo;
1513     } else if (Size == 64) {
1514       // gcc passes <1 x double> in memory. :(
1515       if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double))
1516         return;
1517 
1518       // gcc passes <1 x long long> as INTEGER.
1519       if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::LongLong) ||
1520           VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULongLong) ||
1521           VT->getElementType()->isSpecificBuiltinType(BuiltinType::Long) ||
1522           VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULong))
1523         Current = Integer;
1524       else
1525         Current = SSE;
1526 
1527       // If this type crosses an eightbyte boundary, it should be
1528       // split.
1529       if (OffsetBase && OffsetBase != 64)
1530         Hi = Lo;
1531     } else if (Size == 128 || (HasAVX && isNamedArg && Size == 256)) {
1532       // Arguments of 256-bits are split into four eightbyte chunks. The
1533       // least significant one belongs to class SSE and all the others to class
1534       // SSEUP. The original Lo and Hi design considers that types can't be
1535       // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
1536       // This design isn't correct for 256-bits, but since there're no cases
1537       // where the upper parts would need to be inspected, avoid adding
1538       // complexity and just consider Hi to match the 64-256 part.
1539       //
1540       // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
1541       // registers if they are "named", i.e. not part of the "..." of a
1542       // variadic function.
1543       Lo = SSE;
1544       Hi = SSEUp;
1545     }
1546     return;
1547   }
1548 
1549   if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
1550     QualType ET = getContext().getCanonicalType(CT->getElementType());
1551 
1552     uint64_t Size = getContext().getTypeSize(Ty);
1553     if (ET->isIntegralOrEnumerationType()) {
1554       if (Size <= 64)
1555         Current = Integer;
1556       else if (Size <= 128)
1557         Lo = Hi = Integer;
1558     } else if (ET == getContext().FloatTy)
1559       Current = SSE;
1560     else if (ET == getContext().DoubleTy ||
1561              (ET == getContext().LongDoubleTy &&
1562               getTarget().getTriple().isOSNaCl()))
1563       Lo = Hi = SSE;
1564     else if (ET == getContext().LongDoubleTy)
1565       Current = ComplexX87;
1566 
1567     // If this complex type crosses an eightbyte boundary then it
1568     // should be split.
1569     uint64_t EB_Real = (OffsetBase) / 64;
1570     uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
1571     if (Hi == NoClass && EB_Real != EB_Imag)
1572       Hi = Lo;
1573 
1574     return;
1575   }
1576 
1577   if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
1578     // Arrays are treated like structures.
1579 
1580     uint64_t Size = getContext().getTypeSize(Ty);
1581 
1582     // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
1583     // than four eightbytes, ..., it has class MEMORY.
1584     if (Size > 256)
1585       return;
1586 
1587     // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
1588     // fields, it has class MEMORY.
1589     //
1590     // Only need to check alignment of array base.
1591     if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
1592       return;
1593 
1594     // Otherwise implement simplified merge. We could be smarter about
1595     // this, but it isn't worth it and would be harder to verify.
1596     Current = NoClass;
1597     uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
1598     uint64_t ArraySize = AT->getSize().getZExtValue();
1599 
1600     // The only case a 256-bit wide vector could be used is when the array
1601     // contains a single 256-bit element. Since Lo and Hi logic isn't extended
1602     // to work for sizes wider than 128, early check and fallback to memory.
1603     if (Size > 128 && EltSize != 256)
1604       return;
1605 
1606     for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
1607       Class FieldLo, FieldHi;
1608       classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
1609       Lo = merge(Lo, FieldLo);
1610       Hi = merge(Hi, FieldHi);
1611       if (Lo == Memory || Hi == Memory)
1612         break;
1613     }
1614 
1615     postMerge(Size, Lo, Hi);
1616     assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
1617     return;
1618   }
1619 
1620   if (const RecordType *RT = Ty->getAs<RecordType>()) {
1621     uint64_t Size = getContext().getTypeSize(Ty);
1622 
1623     // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
1624     // than four eightbytes, ..., it has class MEMORY.
1625     if (Size > 256)
1626       return;
1627 
1628     // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
1629     // copy constructor or a non-trivial destructor, it is passed by invisible
1630     // reference.
1631     if (getRecordArgABI(RT, getCXXABI()))
1632       return;
1633 
1634     const RecordDecl *RD = RT->getDecl();
1635 
1636     // Assume variable sized types are passed in memory.
1637     if (RD->hasFlexibleArrayMember())
1638       return;
1639 
1640     const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
1641 
1642     // Reset Lo class, this will be recomputed.
1643     Current = NoClass;
1644 
1645     // If this is a C++ record, classify the bases first.
1646     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
1647       for (CXXRecordDecl::base_class_const_iterator i = CXXRD->bases_begin(),
1648              e = CXXRD->bases_end(); i != e; ++i) {
1649         assert(!i->isVirtual() && !i->getType()->isDependentType() &&
1650                "Unexpected base class!");
1651         const CXXRecordDecl *Base =
1652           cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
1653 
1654         // Classify this field.
1655         //
1656         // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
1657         // single eightbyte, each is classified separately. Each eightbyte gets
1658         // initialized to class NO_CLASS.
1659         Class FieldLo, FieldHi;
1660         uint64_t Offset =
1661           OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
1662         classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
1663         Lo = merge(Lo, FieldLo);
1664         Hi = merge(Hi, FieldHi);
1665         if (Lo == Memory || Hi == Memory)
1666           break;
1667       }
1668     }
1669 
1670     // Classify the fields one at a time, merging the results.
1671     unsigned idx = 0;
1672     for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
1673            i != e; ++i, ++idx) {
1674       uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
1675       bool BitField = i->isBitField();
1676 
1677       // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
1678       // four eightbytes, or it contains unaligned fields, it has class MEMORY.
1679       //
1680       // The only case a 256-bit wide vector could be used is when the struct
1681       // contains a single 256-bit element. Since Lo and Hi logic isn't extended
1682       // to work for sizes wider than 128, early check and fallback to memory.
1683       //
1684       if (Size > 128 && getContext().getTypeSize(i->getType()) != 256) {
1685         Lo = Memory;
1686         return;
1687       }
1688       // Note, skip this test for bit-fields, see below.
1689       if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
1690         Lo = Memory;
1691         return;
1692       }
1693 
1694       // Classify this field.
1695       //
1696       // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
1697       // exceeds a single eightbyte, each is classified
1698       // separately. Each eightbyte gets initialized to class
1699       // NO_CLASS.
1700       Class FieldLo, FieldHi;
1701 
1702       // Bit-fields require special handling, they do not force the
1703       // structure to be passed in memory even if unaligned, and
1704       // therefore they can straddle an eightbyte.
1705       if (BitField) {
1706         // Ignore padding bit-fields.
1707         if (i->isUnnamedBitfield())
1708           continue;
1709 
1710         uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
1711         uint64_t Size = i->getBitWidthValue(getContext());
1712 
1713         uint64_t EB_Lo = Offset / 64;
1714         uint64_t EB_Hi = (Offset + Size - 1) / 64;
1715 
1716         if (EB_Lo) {
1717           assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
1718           FieldLo = NoClass;
1719           FieldHi = Integer;
1720         } else {
1721           FieldLo = Integer;
1722           FieldHi = EB_Hi ? Integer : NoClass;
1723         }
1724       } else
1725         classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
1726       Lo = merge(Lo, FieldLo);
1727       Hi = merge(Hi, FieldHi);
1728       if (Lo == Memory || Hi == Memory)
1729         break;
1730     }
1731 
1732     postMerge(Size, Lo, Hi);
1733   }
1734 }
1735 
1736 ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
1737   // If this is a scalar LLVM value then assume LLVM will pass it in the right
1738   // place naturally.
1739   if (!isAggregateTypeForABI(Ty)) {
1740     // Treat an enum type as its underlying type.
1741     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1742       Ty = EnumTy->getDecl()->getIntegerType();
1743 
1744     return (Ty->isPromotableIntegerType() ?
1745             ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
1746   }
1747 
1748   return ABIArgInfo::getIndirect(0);
1749 }
1750 
1751 bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
1752   if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
1753     uint64_t Size = getContext().getTypeSize(VecTy);
1754     unsigned LargestVector = HasAVX ? 256 : 128;
1755     if (Size <= 64 || Size > LargestVector)
1756       return true;
1757   }
1758 
1759   return false;
1760 }
1761 
1762 ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
1763                                             unsigned freeIntRegs) const {
1764   // If this is a scalar LLVM value then assume LLVM will pass it in the right
1765   // place naturally.
1766   //
1767   // This assumption is optimistic, as there could be free registers available
1768   // when we need to pass this argument in memory, and LLVM could try to pass
1769   // the argument in the free register. This does not seem to happen currently,
1770   // but this code would be much safer if we could mark the argument with
1771   // 'onstack'. See PR12193.
1772   if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty)) {
1773     // Treat an enum type as its underlying type.
1774     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1775       Ty = EnumTy->getDecl()->getIntegerType();
1776 
1777     return (Ty->isPromotableIntegerType() ?
1778             ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
1779   }
1780 
1781   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
1782     return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
1783 
1784   // Compute the byval alignment. We specify the alignment of the byval in all
1785   // cases so that the mid-level optimizer knows the alignment of the byval.
1786   unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
1787 
1788   // Attempt to avoid passing indirect results using byval when possible. This
1789   // is important for good codegen.
1790   //
1791   // We do this by coercing the value into a scalar type which the backend can
1792   // handle naturally (i.e., without using byval).
1793   //
1794   // For simplicity, we currently only do this when we have exhausted all of the
1795   // free integer registers. Doing this when there are free integer registers
1796   // would require more care, as we would have to ensure that the coerced value
1797   // did not claim the unused register. That would require either reording the
1798   // arguments to the function (so that any subsequent inreg values came first),
1799   // or only doing this optimization when there were no following arguments that
1800   // might be inreg.
1801   //
1802   // We currently expect it to be rare (particularly in well written code) for
1803   // arguments to be passed on the stack when there are still free integer
1804   // registers available (this would typically imply large structs being passed
1805   // by value), so this seems like a fair tradeoff for now.
1806   //
1807   // We can revisit this if the backend grows support for 'onstack' parameter
1808   // attributes. See PR12193.
1809   if (freeIntRegs == 0) {
1810     uint64_t Size = getContext().getTypeSize(Ty);
1811 
1812     // If this type fits in an eightbyte, coerce it into the matching integral
1813     // type, which will end up on the stack (with alignment 8).
1814     if (Align == 8 && Size <= 64)
1815       return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
1816                                                           Size));
1817   }
1818 
1819   return ABIArgInfo::getIndirect(Align);
1820 }
1821 
1822 /// GetByteVectorType - The ABI specifies that a value should be passed in an
1823 /// full vector XMM/YMM register.  Pick an LLVM IR type that will be passed as a
1824 /// vector register.
1825 llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
1826   llvm::Type *IRType = CGT.ConvertType(Ty);
1827 
1828   // Wrapper structs that just contain vectors are passed just like vectors,
1829   // strip them off if present.
1830   llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType);
1831   while (STy && STy->getNumElements() == 1) {
1832     IRType = STy->getElementType(0);
1833     STy = dyn_cast<llvm::StructType>(IRType);
1834   }
1835 
1836   // If the preferred type is a 16-byte vector, prefer to pass it.
1837   if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(IRType)){
1838     llvm::Type *EltTy = VT->getElementType();
1839     unsigned BitWidth = VT->getBitWidth();
1840     if ((BitWidth >= 128 && BitWidth <= 256) &&
1841         (EltTy->isFloatTy() || EltTy->isDoubleTy() ||
1842          EltTy->isIntegerTy(8) || EltTy->isIntegerTy(16) ||
1843          EltTy->isIntegerTy(32) || EltTy->isIntegerTy(64) ||
1844          EltTy->isIntegerTy(128)))
1845       return VT;
1846   }
1847 
1848   return llvm::VectorType::get(llvm::Type::getDoubleTy(getVMContext()), 2);
1849 }
1850 
1851 /// BitsContainNoUserData - Return true if the specified [start,end) bit range
1852 /// is known to either be off the end of the specified type or being in
1853 /// alignment padding.  The user type specified is known to be at most 128 bits
1854 /// in size, and have passed through X86_64ABIInfo::classify with a successful
1855 /// classification that put one of the two halves in the INTEGER class.
1856 ///
1857 /// It is conservatively correct to return false.
1858 static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
1859                                   unsigned EndBit, ASTContext &Context) {
1860   // If the bytes being queried are off the end of the type, there is no user
1861   // data hiding here.  This handles analysis of builtins, vectors and other
1862   // types that don't contain interesting padding.
1863   unsigned TySize = (unsigned)Context.getTypeSize(Ty);
1864   if (TySize <= StartBit)
1865     return true;
1866 
1867   if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
1868     unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
1869     unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
1870 
1871     // Check each element to see if the element overlaps with the queried range.
1872     for (unsigned i = 0; i != NumElts; ++i) {
1873       // If the element is after the span we care about, then we're done..
1874       unsigned EltOffset = i*EltSize;
1875       if (EltOffset >= EndBit) break;
1876 
1877       unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
1878       if (!BitsContainNoUserData(AT->getElementType(), EltStart,
1879                                  EndBit-EltOffset, Context))
1880         return false;
1881     }
1882     // If it overlaps no elements, then it is safe to process as padding.
1883     return true;
1884   }
1885 
1886   if (const RecordType *RT = Ty->getAs<RecordType>()) {
1887     const RecordDecl *RD = RT->getDecl();
1888     const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1889 
1890     // If this is a C++ record, check the bases first.
1891     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
1892       for (CXXRecordDecl::base_class_const_iterator i = CXXRD->bases_begin(),
1893            e = CXXRD->bases_end(); i != e; ++i) {
1894         assert(!i->isVirtual() && !i->getType()->isDependentType() &&
1895                "Unexpected base class!");
1896         const CXXRecordDecl *Base =
1897           cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
1898 
1899         // If the base is after the span we care about, ignore it.
1900         unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
1901         if (BaseOffset >= EndBit) continue;
1902 
1903         unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
1904         if (!BitsContainNoUserData(i->getType(), BaseStart,
1905                                    EndBit-BaseOffset, Context))
1906           return false;
1907       }
1908     }
1909 
1910     // Verify that no field has data that overlaps the region of interest.  Yes
1911     // this could be sped up a lot by being smarter about queried fields,
1912     // however we're only looking at structs up to 16 bytes, so we don't care
1913     // much.
1914     unsigned idx = 0;
1915     for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
1916          i != e; ++i, ++idx) {
1917       unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
1918 
1919       // If we found a field after the region we care about, then we're done.
1920       if (FieldOffset >= EndBit) break;
1921 
1922       unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
1923       if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
1924                                  Context))
1925         return false;
1926     }
1927 
1928     // If nothing in this record overlapped the area of interest, then we're
1929     // clean.
1930     return true;
1931   }
1932 
1933   return false;
1934 }
1935 
1936 /// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a
1937 /// float member at the specified offset.  For example, {int,{float}} has a
1938 /// float at offset 4.  It is conservatively correct for this routine to return
1939 /// false.
1940 static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset,
1941                                   const llvm::DataLayout &TD) {
1942   // Base case if we find a float.
1943   if (IROffset == 0 && IRType->isFloatTy())
1944     return true;
1945 
1946   // If this is a struct, recurse into the field at the specified offset.
1947   if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
1948     const llvm::StructLayout *SL = TD.getStructLayout(STy);
1949     unsigned Elt = SL->getElementContainingOffset(IROffset);
1950     IROffset -= SL->getElementOffset(Elt);
1951     return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD);
1952   }
1953 
1954   // If this is an array, recurse into the field at the specified offset.
1955   if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
1956     llvm::Type *EltTy = ATy->getElementType();
1957     unsigned EltSize = TD.getTypeAllocSize(EltTy);
1958     IROffset -= IROffset/EltSize*EltSize;
1959     return ContainsFloatAtOffset(EltTy, IROffset, TD);
1960   }
1961 
1962   return false;
1963 }
1964 
1965 
1966 /// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
1967 /// low 8 bytes of an XMM register, corresponding to the SSE class.
1968 llvm::Type *X86_64ABIInfo::
1969 GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
1970                    QualType SourceTy, unsigned SourceOffset) const {
1971   // The only three choices we have are either double, <2 x float>, or float. We
1972   // pass as float if the last 4 bytes is just padding.  This happens for
1973   // structs that contain 3 floats.
1974   if (BitsContainNoUserData(SourceTy, SourceOffset*8+32,
1975                             SourceOffset*8+64, getContext()))
1976     return llvm::Type::getFloatTy(getVMContext());
1977 
1978   // We want to pass as <2 x float> if the LLVM IR type contains a float at
1979   // offset+0 and offset+4.  Walk the LLVM IR type to find out if this is the
1980   // case.
1981   if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) &&
1982       ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout()))
1983     return llvm::VectorType::get(llvm::Type::getFloatTy(getVMContext()), 2);
1984 
1985   return llvm::Type::getDoubleTy(getVMContext());
1986 }
1987 
1988 
1989 /// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
1990 /// an 8-byte GPR.  This means that we either have a scalar or we are talking
1991 /// about the high or low part of an up-to-16-byte struct.  This routine picks
1992 /// the best LLVM IR type to represent this, which may be i64 or may be anything
1993 /// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
1994 /// etc).
1995 ///
1996 /// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
1997 /// the source type.  IROffset is an offset in bytes into the LLVM IR type that
1998 /// the 8-byte value references.  PrefType may be null.
1999 ///
2000 /// SourceTy is the source level type for the entire argument.  SourceOffset is
2001 /// an offset into this that we're processing (which is always either 0 or 8).
2002 ///
2003 llvm::Type *X86_64ABIInfo::
2004 GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
2005                        QualType SourceTy, unsigned SourceOffset) const {
2006   // If we're dealing with an un-offset LLVM IR type, then it means that we're
2007   // returning an 8-byte unit starting with it.  See if we can safely use it.
2008   if (IROffset == 0) {
2009     // Pointers and int64's always fill the 8-byte unit.
2010     if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
2011         IRType->isIntegerTy(64))
2012       return IRType;
2013 
2014     // If we have a 1/2/4-byte integer, we can use it only if the rest of the
2015     // goodness in the source type is just tail padding.  This is allowed to
2016     // kick in for struct {double,int} on the int, but not on
2017     // struct{double,int,int} because we wouldn't return the second int.  We
2018     // have to do this analysis on the source type because we can't depend on
2019     // unions being lowered a specific way etc.
2020     if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
2021         IRType->isIntegerTy(32) ||
2022         (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
2023       unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
2024           cast<llvm::IntegerType>(IRType)->getBitWidth();
2025 
2026       if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
2027                                 SourceOffset*8+64, getContext()))
2028         return IRType;
2029     }
2030   }
2031 
2032   if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
2033     // If this is a struct, recurse into the field at the specified offset.
2034     const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
2035     if (IROffset < SL->getSizeInBytes()) {
2036       unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
2037       IROffset -= SL->getElementOffset(FieldIdx);
2038 
2039       return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
2040                                     SourceTy, SourceOffset);
2041     }
2042   }
2043 
2044   if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
2045     llvm::Type *EltTy = ATy->getElementType();
2046     unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
2047     unsigned EltOffset = IROffset/EltSize*EltSize;
2048     return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
2049                                   SourceOffset);
2050   }
2051 
2052   // Okay, we don't have any better idea of what to pass, so we pass this in an
2053   // integer register that isn't too big to fit the rest of the struct.
2054   unsigned TySizeInBytes =
2055     (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
2056 
2057   assert(TySizeInBytes != SourceOffset && "Empty field?");
2058 
2059   // It is always safe to classify this as an integer type up to i64 that
2060   // isn't larger than the structure.
2061   return llvm::IntegerType::get(getVMContext(),
2062                                 std::min(TySizeInBytes-SourceOffset, 8U)*8);
2063 }
2064 
2065 
2066 /// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
2067 /// be used as elements of a two register pair to pass or return, return a
2068 /// first class aggregate to represent them.  For example, if the low part of
2069 /// a by-value argument should be passed as i32* and the high part as float,
2070 /// return {i32*, float}.
2071 static llvm::Type *
2072 GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
2073                            const llvm::DataLayout &TD) {
2074   // In order to correctly satisfy the ABI, we need to the high part to start
2075   // at offset 8.  If the high and low parts we inferred are both 4-byte types
2076   // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
2077   // the second element at offset 8.  Check for this:
2078   unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
2079   unsigned HiAlign = TD.getABITypeAlignment(Hi);
2080   unsigned HiStart = llvm::DataLayout::RoundUpAlignment(LoSize, HiAlign);
2081   assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
2082 
2083   // To handle this, we have to increase the size of the low part so that the
2084   // second element will start at an 8 byte offset.  We can't increase the size
2085   // of the second element because it might make us access off the end of the
2086   // struct.
2087   if (HiStart != 8) {
2088     // There are only two sorts of types the ABI generation code can produce for
2089     // the low part of a pair that aren't 8 bytes in size: float or i8/i16/i32.
2090     // Promote these to a larger type.
2091     if (Lo->isFloatTy())
2092       Lo = llvm::Type::getDoubleTy(Lo->getContext());
2093     else {
2094       assert(Lo->isIntegerTy() && "Invalid/unknown lo type");
2095       Lo = llvm::Type::getInt64Ty(Lo->getContext());
2096     }
2097   }
2098 
2099   llvm::StructType *Result = llvm::StructType::get(Lo, Hi, NULL);
2100 
2101 
2102   // Verify that the second element is at an 8-byte offset.
2103   assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
2104          "Invalid x86-64 argument pair!");
2105   return Result;
2106 }
2107 
2108 ABIArgInfo X86_64ABIInfo::
2109 classifyReturnType(QualType RetTy) const {
2110   // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
2111   // classification algorithm.
2112   X86_64ABIInfo::Class Lo, Hi;
2113   classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
2114 
2115   // Check some invariants.
2116   assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
2117   assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
2118 
2119   llvm::Type *ResType = 0;
2120   switch (Lo) {
2121   case NoClass:
2122     if (Hi == NoClass)
2123       return ABIArgInfo::getIgnore();
2124     // If the low part is just padding, it takes no register, leave ResType
2125     // null.
2126     assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
2127            "Unknown missing lo part");
2128     break;
2129 
2130   case SSEUp:
2131   case X87Up:
2132     llvm_unreachable("Invalid classification for lo word.");
2133 
2134     // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
2135     // hidden argument.
2136   case Memory:
2137     return getIndirectReturnResult(RetTy);
2138 
2139     // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
2140     // available register of the sequence %rax, %rdx is used.
2141   case Integer:
2142     ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
2143 
2144     // If we have a sign or zero extended integer, make sure to return Extend
2145     // so that the parameter gets the right LLVM IR attributes.
2146     if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
2147       // Treat an enum type as its underlying type.
2148       if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
2149         RetTy = EnumTy->getDecl()->getIntegerType();
2150 
2151       if (RetTy->isIntegralOrEnumerationType() &&
2152           RetTy->isPromotableIntegerType())
2153         return ABIArgInfo::getExtend();
2154     }
2155     break;
2156 
2157     // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
2158     // available SSE register of the sequence %xmm0, %xmm1 is used.
2159   case SSE:
2160     ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
2161     break;
2162 
2163     // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
2164     // returned on the X87 stack in %st0 as 80-bit x87 number.
2165   case X87:
2166     ResType = llvm::Type::getX86_FP80Ty(getVMContext());
2167     break;
2168 
2169     // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
2170     // part of the value is returned in %st0 and the imaginary part in
2171     // %st1.
2172   case ComplexX87:
2173     assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
2174     ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
2175                                     llvm::Type::getX86_FP80Ty(getVMContext()),
2176                                     NULL);
2177     break;
2178   }
2179 
2180   llvm::Type *HighPart = 0;
2181   switch (Hi) {
2182     // Memory was handled previously and X87 should
2183     // never occur as a hi class.
2184   case Memory:
2185   case X87:
2186     llvm_unreachable("Invalid classification for hi word.");
2187 
2188   case ComplexX87: // Previously handled.
2189   case NoClass:
2190     break;
2191 
2192   case Integer:
2193     HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
2194     if (Lo == NoClass)  // Return HighPart at offset 8 in memory.
2195       return ABIArgInfo::getDirect(HighPart, 8);
2196     break;
2197   case SSE:
2198     HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
2199     if (Lo == NoClass)  // Return HighPart at offset 8 in memory.
2200       return ABIArgInfo::getDirect(HighPart, 8);
2201     break;
2202 
2203     // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
2204     // is passed in the next available eightbyte chunk if the last used
2205     // vector register.
2206     //
2207     // SSEUP should always be preceded by SSE, just widen.
2208   case SSEUp:
2209     assert(Lo == SSE && "Unexpected SSEUp classification.");
2210     ResType = GetByteVectorType(RetTy);
2211     break;
2212 
2213     // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
2214     // returned together with the previous X87 value in %st0.
2215   case X87Up:
2216     // If X87Up is preceded by X87, we don't need to do
2217     // anything. However, in some cases with unions it may not be
2218     // preceded by X87. In such situations we follow gcc and pass the
2219     // extra bits in an SSE reg.
2220     if (Lo != X87) {
2221       HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
2222       if (Lo == NoClass)  // Return HighPart at offset 8 in memory.
2223         return ABIArgInfo::getDirect(HighPart, 8);
2224     }
2225     break;
2226   }
2227 
2228   // If a high part was specified, merge it together with the low part.  It is
2229   // known to pass in the high eightbyte of the result.  We do this by forming a
2230   // first class struct aggregate with the high and low part: {low, high}
2231   if (HighPart)
2232     ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
2233 
2234   return ABIArgInfo::getDirect(ResType);
2235 }
2236 
2237 ABIArgInfo X86_64ABIInfo::classifyArgumentType(
2238   QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE,
2239   bool isNamedArg)
2240   const
2241 {
2242   X86_64ABIInfo::Class Lo, Hi;
2243   classify(Ty, 0, Lo, Hi, isNamedArg);
2244 
2245   // Check some invariants.
2246   // FIXME: Enforce these by construction.
2247   assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
2248   assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
2249 
2250   neededInt = 0;
2251   neededSSE = 0;
2252   llvm::Type *ResType = 0;
2253   switch (Lo) {
2254   case NoClass:
2255     if (Hi == NoClass)
2256       return ABIArgInfo::getIgnore();
2257     // If the low part is just padding, it takes no register, leave ResType
2258     // null.
2259     assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
2260            "Unknown missing lo part");
2261     break;
2262 
2263     // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
2264     // on the stack.
2265   case Memory:
2266 
2267     // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
2268     // COMPLEX_X87, it is passed in memory.
2269   case X87:
2270   case ComplexX87:
2271     if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect)
2272       ++neededInt;
2273     return getIndirectResult(Ty, freeIntRegs);
2274 
2275   case SSEUp:
2276   case X87Up:
2277     llvm_unreachable("Invalid classification for lo word.");
2278 
2279     // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
2280     // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
2281     // and %r9 is used.
2282   case Integer:
2283     ++neededInt;
2284 
2285     // Pick an 8-byte type based on the preferred type.
2286     ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
2287 
2288     // If we have a sign or zero extended integer, make sure to return Extend
2289     // so that the parameter gets the right LLVM IR attributes.
2290     if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
2291       // Treat an enum type as its underlying type.
2292       if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2293         Ty = EnumTy->getDecl()->getIntegerType();
2294 
2295       if (Ty->isIntegralOrEnumerationType() &&
2296           Ty->isPromotableIntegerType())
2297         return ABIArgInfo::getExtend();
2298     }
2299 
2300     break;
2301 
2302     // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
2303     // available SSE register is used, the registers are taken in the
2304     // order from %xmm0 to %xmm7.
2305   case SSE: {
2306     llvm::Type *IRType = CGT.ConvertType(Ty);
2307     ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
2308     ++neededSSE;
2309     break;
2310   }
2311   }
2312 
2313   llvm::Type *HighPart = 0;
2314   switch (Hi) {
2315     // Memory was handled previously, ComplexX87 and X87 should
2316     // never occur as hi classes, and X87Up must be preceded by X87,
2317     // which is passed in memory.
2318   case Memory:
2319   case X87:
2320   case ComplexX87:
2321     llvm_unreachable("Invalid classification for hi word.");
2322 
2323   case NoClass: break;
2324 
2325   case Integer:
2326     ++neededInt;
2327     // Pick an 8-byte type based on the preferred type.
2328     HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
2329 
2330     if (Lo == NoClass)  // Pass HighPart at offset 8 in memory.
2331       return ABIArgInfo::getDirect(HighPart, 8);
2332     break;
2333 
2334     // X87Up generally doesn't occur here (long double is passed in
2335     // memory), except in situations involving unions.
2336   case X87Up:
2337   case SSE:
2338     HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
2339 
2340     if (Lo == NoClass)  // Pass HighPart at offset 8 in memory.
2341       return ABIArgInfo::getDirect(HighPart, 8);
2342 
2343     ++neededSSE;
2344     break;
2345 
2346     // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
2347     // eightbyte is passed in the upper half of the last used SSE
2348     // register.  This only happens when 128-bit vectors are passed.
2349   case SSEUp:
2350     assert(Lo == SSE && "Unexpected SSEUp classification");
2351     ResType = GetByteVectorType(Ty);
2352     break;
2353   }
2354 
2355   // If a high part was specified, merge it together with the low part.  It is
2356   // known to pass in the high eightbyte of the result.  We do this by forming a
2357   // first class struct aggregate with the high and low part: {low, high}
2358   if (HighPart)
2359     ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
2360 
2361   return ABIArgInfo::getDirect(ResType);
2362 }
2363 
2364 void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
2365 
2366   FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
2367 
2368   // Keep track of the number of assigned registers.
2369   unsigned freeIntRegs = 6, freeSSERegs = 8;
2370 
2371   // If the return value is indirect, then the hidden argument is consuming one
2372   // integer register.
2373   if (FI.getReturnInfo().isIndirect())
2374     --freeIntRegs;
2375 
2376   bool isVariadic = FI.isVariadic();
2377   unsigned numRequiredArgs = 0;
2378   if (isVariadic)
2379     numRequiredArgs = FI.getRequiredArgs().getNumRequiredArgs();
2380 
2381   // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
2382   // get assigned (in left-to-right order) for passing as follows...
2383   for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
2384        it != ie; ++it) {
2385     bool isNamedArg = true;
2386     if (isVariadic)
2387       isNamedArg = (it - FI.arg_begin()) <
2388                     static_cast<signed>(numRequiredArgs);
2389 
2390     unsigned neededInt, neededSSE;
2391     it->info = classifyArgumentType(it->type, freeIntRegs, neededInt,
2392                                     neededSSE, isNamedArg);
2393 
2394     // AMD64-ABI 3.2.3p3: If there are no registers available for any
2395     // eightbyte of an argument, the whole argument is passed on the
2396     // stack. If registers have already been assigned for some
2397     // eightbytes of such an argument, the assignments get reverted.
2398     if (freeIntRegs >= neededInt && freeSSERegs >= neededSSE) {
2399       freeIntRegs -= neededInt;
2400       freeSSERegs -= neededSSE;
2401     } else {
2402       it->info = getIndirectResult(it->type, freeIntRegs);
2403     }
2404   }
2405 }
2406 
2407 static llvm::Value *EmitVAArgFromMemory(llvm::Value *VAListAddr,
2408                                         QualType Ty,
2409                                         CodeGenFunction &CGF) {
2410   llvm::Value *overflow_arg_area_p =
2411     CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_p");
2412   llvm::Value *overflow_arg_area =
2413     CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
2414 
2415   // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
2416   // byte boundary if alignment needed by type exceeds 8 byte boundary.
2417   // It isn't stated explicitly in the standard, but in practice we use
2418   // alignment greater than 16 where necessary.
2419   uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8;
2420   if (Align > 8) {
2421     // overflow_arg_area = (overflow_arg_area + align - 1) & -align;
2422     llvm::Value *Offset =
2423       llvm::ConstantInt::get(CGF.Int64Ty, Align - 1);
2424     overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset);
2425     llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(overflow_arg_area,
2426                                                     CGF.Int64Ty);
2427     llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int64Ty, -(uint64_t)Align);
2428     overflow_arg_area =
2429       CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask),
2430                                  overflow_arg_area->getType(),
2431                                  "overflow_arg_area.align");
2432   }
2433 
2434   // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
2435   llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
2436   llvm::Value *Res =
2437     CGF.Builder.CreateBitCast(overflow_arg_area,
2438                               llvm::PointerType::getUnqual(LTy));
2439 
2440   // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
2441   // l->overflow_arg_area + sizeof(type).
2442   // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
2443   // an 8 byte boundary.
2444 
2445   uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
2446   llvm::Value *Offset =
2447       llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7)  & ~7);
2448   overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
2449                                             "overflow_arg_area.next");
2450   CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
2451 
2452   // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
2453   return Res;
2454 }
2455 
2456 llvm::Value *X86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2457                                       CodeGenFunction &CGF) const {
2458   // Assume that va_list type is correct; should be pointer to LLVM type:
2459   // struct {
2460   //   i32 gp_offset;
2461   //   i32 fp_offset;
2462   //   i8* overflow_arg_area;
2463   //   i8* reg_save_area;
2464   // };
2465   unsigned neededInt, neededSSE;
2466 
2467   Ty = CGF.getContext().getCanonicalType(Ty);
2468   ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
2469                                        /*isNamedArg*/false);
2470 
2471   // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
2472   // in the registers. If not go to step 7.
2473   if (!neededInt && !neededSSE)
2474     return EmitVAArgFromMemory(VAListAddr, Ty, CGF);
2475 
2476   // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
2477   // general purpose registers needed to pass type and num_fp to hold
2478   // the number of floating point registers needed.
2479 
2480   // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
2481   // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
2482   // l->fp_offset > 304 - num_fp * 16 go to step 7.
2483   //
2484   // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
2485   // register save space).
2486 
2487   llvm::Value *InRegs = 0;
2488   llvm::Value *gp_offset_p = 0, *gp_offset = 0;
2489   llvm::Value *fp_offset_p = 0, *fp_offset = 0;
2490   if (neededInt) {
2491     gp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "gp_offset_p");
2492     gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
2493     InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
2494     InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
2495   }
2496 
2497   if (neededSSE) {
2498     fp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 1, "fp_offset_p");
2499     fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
2500     llvm::Value *FitsInFP =
2501       llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
2502     FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
2503     InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
2504   }
2505 
2506   llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
2507   llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
2508   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
2509   CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
2510 
2511   // Emit code to load the value if it was passed in registers.
2512 
2513   CGF.EmitBlock(InRegBlock);
2514 
2515   // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
2516   // an offset of l->gp_offset and/or l->fp_offset. This may require
2517   // copying to a temporary location in case the parameter is passed
2518   // in different register classes or requires an alignment greater
2519   // than 8 for general purpose registers and 16 for XMM registers.
2520   //
2521   // FIXME: This really results in shameful code when we end up needing to
2522   // collect arguments from different places; often what should result in a
2523   // simple assembling of a structure from scattered addresses has many more
2524   // loads than necessary. Can we clean this up?
2525   llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
2526   llvm::Value *RegAddr =
2527     CGF.Builder.CreateLoad(CGF.Builder.CreateStructGEP(VAListAddr, 3),
2528                            "reg_save_area");
2529   if (neededInt && neededSSE) {
2530     // FIXME: Cleanup.
2531     assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
2532     llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
2533     llvm::Value *Tmp = CGF.CreateMemTemp(Ty);
2534     Tmp = CGF.Builder.CreateBitCast(Tmp, ST->getPointerTo());
2535     assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
2536     llvm::Type *TyLo = ST->getElementType(0);
2537     llvm::Type *TyHi = ST->getElementType(1);
2538     assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
2539            "Unexpected ABI info for mixed regs");
2540     llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
2541     llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
2542     llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
2543     llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
2544     llvm::Value *RegLoAddr = TyLo->isFloatingPointTy() ? FPAddr : GPAddr;
2545     llvm::Value *RegHiAddr = TyLo->isFloatingPointTy() ? GPAddr : FPAddr;
2546     llvm::Value *V =
2547       CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegLoAddr, PTyLo));
2548     CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
2549     V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegHiAddr, PTyHi));
2550     CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
2551 
2552     RegAddr = CGF.Builder.CreateBitCast(Tmp,
2553                                         llvm::PointerType::getUnqual(LTy));
2554   } else if (neededInt) {
2555     RegAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
2556     RegAddr = CGF.Builder.CreateBitCast(RegAddr,
2557                                         llvm::PointerType::getUnqual(LTy));
2558 
2559     // Copy to a temporary if necessary to ensure the appropriate alignment.
2560     std::pair<CharUnits, CharUnits> SizeAlign =
2561         CGF.getContext().getTypeInfoInChars(Ty);
2562     uint64_t TySize = SizeAlign.first.getQuantity();
2563     unsigned TyAlign = SizeAlign.second.getQuantity();
2564     if (TyAlign > 8) {
2565       llvm::Value *Tmp = CGF.CreateMemTemp(Ty);
2566       CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, 8, false);
2567       RegAddr = Tmp;
2568     }
2569   } else if (neededSSE == 1) {
2570     RegAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
2571     RegAddr = CGF.Builder.CreateBitCast(RegAddr,
2572                                         llvm::PointerType::getUnqual(LTy));
2573   } else {
2574     assert(neededSSE == 2 && "Invalid number of needed registers!");
2575     // SSE registers are spaced 16 bytes apart in the register save
2576     // area, we need to collect the two eightbytes together.
2577     llvm::Value *RegAddrLo = CGF.Builder.CreateGEP(RegAddr, fp_offset);
2578     llvm::Value *RegAddrHi = CGF.Builder.CreateConstGEP1_32(RegAddrLo, 16);
2579     llvm::Type *DoubleTy = CGF.DoubleTy;
2580     llvm::Type *DblPtrTy =
2581       llvm::PointerType::getUnqual(DoubleTy);
2582     llvm::StructType *ST = llvm::StructType::get(DoubleTy, DoubleTy, NULL);
2583     llvm::Value *V, *Tmp = CGF.CreateMemTemp(Ty);
2584     Tmp = CGF.Builder.CreateBitCast(Tmp, ST->getPointerTo());
2585     V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrLo,
2586                                                          DblPtrTy));
2587     CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
2588     V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrHi,
2589                                                          DblPtrTy));
2590     CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
2591     RegAddr = CGF.Builder.CreateBitCast(Tmp,
2592                                         llvm::PointerType::getUnqual(LTy));
2593   }
2594 
2595   // AMD64-ABI 3.5.7p5: Step 5. Set:
2596   // l->gp_offset = l->gp_offset + num_gp * 8
2597   // l->fp_offset = l->fp_offset + num_fp * 16.
2598   if (neededInt) {
2599     llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
2600     CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
2601                             gp_offset_p);
2602   }
2603   if (neededSSE) {
2604     llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
2605     CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
2606                             fp_offset_p);
2607   }
2608   CGF.EmitBranch(ContBlock);
2609 
2610   // Emit code to load the value if it was passed in memory.
2611 
2612   CGF.EmitBlock(InMemBlock);
2613   llvm::Value *MemAddr = EmitVAArgFromMemory(VAListAddr, Ty, CGF);
2614 
2615   // Return the appropriate result.
2616 
2617   CGF.EmitBlock(ContBlock);
2618   llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(RegAddr->getType(), 2,
2619                                                  "vaarg.addr");
2620   ResAddr->addIncoming(RegAddr, InRegBlock);
2621   ResAddr->addIncoming(MemAddr, InMemBlock);
2622   return ResAddr;
2623 }
2624 
2625 ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, bool IsReturnType) const {
2626 
2627   if (Ty->isVoidType())
2628     return ABIArgInfo::getIgnore();
2629 
2630   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2631     Ty = EnumTy->getDecl()->getIntegerType();
2632 
2633   uint64_t Size = getContext().getTypeSize(Ty);
2634 
2635   if (const RecordType *RT = Ty->getAs<RecordType>()) {
2636     if (IsReturnType) {
2637       if (isRecordReturnIndirect(RT, getCXXABI()))
2638         return ABIArgInfo::getIndirect(0, false);
2639     } else {
2640       if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
2641         return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
2642     }
2643 
2644     if (RT->getDecl()->hasFlexibleArrayMember())
2645       return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
2646 
2647     // FIXME: mingw-w64-gcc emits 128-bit struct as i128
2648     if (Size == 128 && getTarget().getTriple().getOS() == llvm::Triple::MinGW32)
2649       return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2650                                                           Size));
2651 
2652     // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
2653     // not 1, 2, 4, or 8 bytes, must be passed by reference."
2654     if (Size <= 64 &&
2655         (Size & (Size - 1)) == 0)
2656       return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2657                                                           Size));
2658 
2659     return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
2660   }
2661 
2662   if (Ty->isPromotableIntegerType())
2663     return ABIArgInfo::getExtend();
2664 
2665   return ABIArgInfo::getDirect();
2666 }
2667 
2668 void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
2669 
2670   QualType RetTy = FI.getReturnType();
2671   FI.getReturnInfo() = classify(RetTy, true);
2672 
2673   for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
2674        it != ie; ++it)
2675     it->info = classify(it->type, false);
2676 }
2677 
2678 llvm::Value *WinX86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2679                                       CodeGenFunction &CGF) const {
2680   llvm::Type *BPP = CGF.Int8PtrPtrTy;
2681 
2682   CGBuilderTy &Builder = CGF.Builder;
2683   llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
2684                                                        "ap");
2685   llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
2686   llvm::Type *PTy =
2687     llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
2688   llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
2689 
2690   uint64_t Offset =
2691     llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 8);
2692   llvm::Value *NextAddr =
2693     Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
2694                       "ap.next");
2695   Builder.CreateStore(NextAddr, VAListAddrAsBPP);
2696 
2697   return AddrTyped;
2698 }
2699 
2700 namespace {
2701 
2702 class NaClX86_64ABIInfo : public ABIInfo {
2703  public:
2704   NaClX86_64ABIInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX)
2705       : ABIInfo(CGT), PInfo(CGT), NInfo(CGT, HasAVX) {}
2706   virtual void computeInfo(CGFunctionInfo &FI) const;
2707   virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2708                                  CodeGenFunction &CGF) const;
2709  private:
2710   PNaClABIInfo PInfo;  // Used for generating calls with pnaclcall callingconv.
2711   X86_64ABIInfo NInfo; // Used for everything else.
2712 };
2713 
2714 class NaClX86_64TargetCodeGenInfo : public TargetCodeGenInfo  {
2715  public:
2716   NaClX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX)
2717       : TargetCodeGenInfo(new NaClX86_64ABIInfo(CGT, HasAVX)) {}
2718 };
2719 
2720 }
2721 
2722 void NaClX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
2723   if (FI.getASTCallingConvention() == CC_PnaclCall)
2724     PInfo.computeInfo(FI);
2725   else
2726     NInfo.computeInfo(FI);
2727 }
2728 
2729 llvm::Value *NaClX86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2730                                           CodeGenFunction &CGF) const {
2731   // Always use the native convention; calling pnacl-style varargs functions
2732   // is unuspported.
2733   return NInfo.EmitVAArg(VAListAddr, Ty, CGF);
2734 }
2735 
2736 
2737 // PowerPC-32
2738 
2739 namespace {
2740 class PPC32TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
2741 public:
2742   PPC32TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
2743 
2744   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const {
2745     // This is recovered from gcc output.
2746     return 1; // r1 is the dedicated stack pointer
2747   }
2748 
2749   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2750                                llvm::Value *Address) const;
2751 };
2752 
2753 }
2754 
2755 bool
2756 PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2757                                                 llvm::Value *Address) const {
2758   // This is calculated from the LLVM and GCC tables and verified
2759   // against gcc output.  AFAIK all ABIs use the same encoding.
2760 
2761   CodeGen::CGBuilderTy &Builder = CGF.Builder;
2762 
2763   llvm::IntegerType *i8 = CGF.Int8Ty;
2764   llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
2765   llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
2766   llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
2767 
2768   // 0-31: r0-31, the 4-byte general-purpose registers
2769   AssignToArrayRange(Builder, Address, Four8, 0, 31);
2770 
2771   // 32-63: fp0-31, the 8-byte floating-point registers
2772   AssignToArrayRange(Builder, Address, Eight8, 32, 63);
2773 
2774   // 64-76 are various 4-byte special-purpose registers:
2775   // 64: mq
2776   // 65: lr
2777   // 66: ctr
2778   // 67: ap
2779   // 68-75 cr0-7
2780   // 76: xer
2781   AssignToArrayRange(Builder, Address, Four8, 64, 76);
2782 
2783   // 77-108: v0-31, the 16-byte vector registers
2784   AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
2785 
2786   // 109: vrsave
2787   // 110: vscr
2788   // 111: spe_acc
2789   // 112: spefscr
2790   // 113: sfp
2791   AssignToArrayRange(Builder, Address, Four8, 109, 113);
2792 
2793   return false;
2794 }
2795 
2796 // PowerPC-64
2797 
2798 namespace {
2799 /// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
2800 class PPC64_SVR4_ABIInfo : public DefaultABIInfo {
2801 
2802 public:
2803   PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
2804 
2805   bool isPromotableTypeForABI(QualType Ty) const;
2806 
2807   ABIArgInfo classifyReturnType(QualType RetTy) const;
2808   ABIArgInfo classifyArgumentType(QualType Ty) const;
2809 
2810   // TODO: We can add more logic to computeInfo to improve performance.
2811   // Example: For aggregate arguments that fit in a register, we could
2812   // use getDirectInReg (as is done below for structs containing a single
2813   // floating-point value) to avoid pushing them to memory on function
2814   // entry.  This would require changing the logic in PPCISelLowering
2815   // when lowering the parameters in the caller and args in the callee.
2816   virtual void computeInfo(CGFunctionInfo &FI) const {
2817     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
2818     for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
2819          it != ie; ++it) {
2820       // We rely on the default argument classification for the most part.
2821       // One exception:  An aggregate containing a single floating-point
2822       // or vector item must be passed in a register if one is available.
2823       const Type *T = isSingleElementStruct(it->type, getContext());
2824       if (T) {
2825         const BuiltinType *BT = T->getAs<BuiltinType>();
2826         if (T->isVectorType() || (BT && BT->isFloatingPoint())) {
2827           QualType QT(T, 0);
2828           it->info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
2829           continue;
2830         }
2831       }
2832       it->info = classifyArgumentType(it->type);
2833     }
2834   }
2835 
2836   virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr,
2837                                  QualType Ty,
2838                                  CodeGenFunction &CGF) const;
2839 };
2840 
2841 class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
2842 public:
2843   PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT)
2844     : TargetCodeGenInfo(new PPC64_SVR4_ABIInfo(CGT)) {}
2845 
2846   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const {
2847     // This is recovered from gcc output.
2848     return 1; // r1 is the dedicated stack pointer
2849   }
2850 
2851   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2852                                llvm::Value *Address) const;
2853 };
2854 
2855 class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
2856 public:
2857   PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
2858 
2859   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const {
2860     // This is recovered from gcc output.
2861     return 1; // r1 is the dedicated stack pointer
2862   }
2863 
2864   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2865                                llvm::Value *Address) const;
2866 };
2867 
2868 }
2869 
2870 // Return true if the ABI requires Ty to be passed sign- or zero-
2871 // extended to 64 bits.
2872 bool
2873 PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
2874   // Treat an enum type as its underlying type.
2875   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2876     Ty = EnumTy->getDecl()->getIntegerType();
2877 
2878   // Promotable integer types are required to be promoted by the ABI.
2879   if (Ty->isPromotableIntegerType())
2880     return true;
2881 
2882   // In addition to the usual promotable integer types, we also need to
2883   // extend all 32-bit types, since the ABI requires promotion to 64 bits.
2884   if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
2885     switch (BT->getKind()) {
2886     case BuiltinType::Int:
2887     case BuiltinType::UInt:
2888       return true;
2889     default:
2890       break;
2891     }
2892 
2893   return false;
2894 }
2895 
2896 ABIArgInfo
2897 PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
2898   if (Ty->isAnyComplexType())
2899     return ABIArgInfo::getDirect();
2900 
2901   if (isAggregateTypeForABI(Ty)) {
2902     if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
2903       return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
2904 
2905     return ABIArgInfo::getIndirect(0);
2906   }
2907 
2908   return (isPromotableTypeForABI(Ty) ?
2909           ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
2910 }
2911 
2912 ABIArgInfo
2913 PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
2914   if (RetTy->isVoidType())
2915     return ABIArgInfo::getIgnore();
2916 
2917   if (RetTy->isAnyComplexType())
2918     return ABIArgInfo::getDirect();
2919 
2920   if (isAggregateTypeForABI(RetTy))
2921     return ABIArgInfo::getIndirect(0);
2922 
2923   return (isPromotableTypeForABI(RetTy) ?
2924           ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
2925 }
2926 
2927 // Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
2928 llvm::Value *PPC64_SVR4_ABIInfo::EmitVAArg(llvm::Value *VAListAddr,
2929                                            QualType Ty,
2930                                            CodeGenFunction &CGF) const {
2931   llvm::Type *BP = CGF.Int8PtrTy;
2932   llvm::Type *BPP = CGF.Int8PtrPtrTy;
2933 
2934   CGBuilderTy &Builder = CGF.Builder;
2935   llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
2936   llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
2937 
2938   // Update the va_list pointer.  The pointer should be bumped by the
2939   // size of the object.  We can trust getTypeSize() except for a complex
2940   // type whose base type is smaller than a doubleword.  For these, the
2941   // size of the object is 16 bytes; see below for further explanation.
2942   unsigned SizeInBytes = CGF.getContext().getTypeSize(Ty) / 8;
2943   QualType BaseTy;
2944   unsigned CplxBaseSize = 0;
2945 
2946   if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
2947     BaseTy = CTy->getElementType();
2948     CplxBaseSize = CGF.getContext().getTypeSize(BaseTy) / 8;
2949     if (CplxBaseSize < 8)
2950       SizeInBytes = 16;
2951   }
2952 
2953   unsigned Offset = llvm::RoundUpToAlignment(SizeInBytes, 8);
2954   llvm::Value *NextAddr =
2955     Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int64Ty, Offset),
2956                       "ap.next");
2957   Builder.CreateStore(NextAddr, VAListAddrAsBPP);
2958 
2959   // If we have a complex type and the base type is smaller than 8 bytes,
2960   // the ABI calls for the real and imaginary parts to be right-adjusted
2961   // in separate doublewords.  However, Clang expects us to produce a
2962   // pointer to a structure with the two parts packed tightly.  So generate
2963   // loads of the real and imaginary parts relative to the va_list pointer,
2964   // and store them to a temporary structure.
2965   if (CplxBaseSize && CplxBaseSize < 8) {
2966     llvm::Value *RealAddr = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
2967     llvm::Value *ImagAddr = RealAddr;
2968     RealAddr = Builder.CreateAdd(RealAddr, Builder.getInt64(8 - CplxBaseSize));
2969     ImagAddr = Builder.CreateAdd(ImagAddr, Builder.getInt64(16 - CplxBaseSize));
2970     llvm::Type *PBaseTy = llvm::PointerType::getUnqual(CGF.ConvertType(BaseTy));
2971     RealAddr = Builder.CreateIntToPtr(RealAddr, PBaseTy);
2972     ImagAddr = Builder.CreateIntToPtr(ImagAddr, PBaseTy);
2973     llvm::Value *Real = Builder.CreateLoad(RealAddr, false, ".vareal");
2974     llvm::Value *Imag = Builder.CreateLoad(ImagAddr, false, ".vaimag");
2975     llvm::Value *Ptr = CGF.CreateTempAlloca(CGT.ConvertTypeForMem(Ty),
2976                                             "vacplx");
2977     llvm::Value *RealPtr = Builder.CreateStructGEP(Ptr, 0, ".real");
2978     llvm::Value *ImagPtr = Builder.CreateStructGEP(Ptr, 1, ".imag");
2979     Builder.CreateStore(Real, RealPtr, false);
2980     Builder.CreateStore(Imag, ImagPtr, false);
2981     return Ptr;
2982   }
2983 
2984   // If the argument is smaller than 8 bytes, it is right-adjusted in
2985   // its doubleword slot.  Adjust the pointer to pick it up from the
2986   // correct offset.
2987   if (SizeInBytes < 8) {
2988     llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
2989     AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt64(8 - SizeInBytes));
2990     Addr = Builder.CreateIntToPtr(AddrAsInt, BP);
2991   }
2992 
2993   llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
2994   return Builder.CreateBitCast(Addr, PTy);
2995 }
2996 
2997 static bool
2998 PPC64_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2999                               llvm::Value *Address) {
3000   // This is calculated from the LLVM and GCC tables and verified
3001   // against gcc output.  AFAIK all ABIs use the same encoding.
3002 
3003   CodeGen::CGBuilderTy &Builder = CGF.Builder;
3004 
3005   llvm::IntegerType *i8 = CGF.Int8Ty;
3006   llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
3007   llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
3008   llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
3009 
3010   // 0-31: r0-31, the 8-byte general-purpose registers
3011   AssignToArrayRange(Builder, Address, Eight8, 0, 31);
3012 
3013   // 32-63: fp0-31, the 8-byte floating-point registers
3014   AssignToArrayRange(Builder, Address, Eight8, 32, 63);
3015 
3016   // 64-76 are various 4-byte special-purpose registers:
3017   // 64: mq
3018   // 65: lr
3019   // 66: ctr
3020   // 67: ap
3021   // 68-75 cr0-7
3022   // 76: xer
3023   AssignToArrayRange(Builder, Address, Four8, 64, 76);
3024 
3025   // 77-108: v0-31, the 16-byte vector registers
3026   AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
3027 
3028   // 109: vrsave
3029   // 110: vscr
3030   // 111: spe_acc
3031   // 112: spefscr
3032   // 113: sfp
3033   AssignToArrayRange(Builder, Address, Four8, 109, 113);
3034 
3035   return false;
3036 }
3037 
3038 bool
3039 PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
3040   CodeGen::CodeGenFunction &CGF,
3041   llvm::Value *Address) const {
3042 
3043   return PPC64_initDwarfEHRegSizeTable(CGF, Address);
3044 }
3045 
3046 bool
3047 PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3048                                                 llvm::Value *Address) const {
3049 
3050   return PPC64_initDwarfEHRegSizeTable(CGF, Address);
3051 }
3052 
3053 //===----------------------------------------------------------------------===//
3054 // ARM ABI Implementation
3055 //===----------------------------------------------------------------------===//
3056 
3057 namespace {
3058 
3059 class ARMABIInfo : public ABIInfo {
3060 public:
3061   enum ABIKind {
3062     APCS = 0,
3063     AAPCS = 1,
3064     AAPCS_VFP
3065   };
3066 
3067 private:
3068   ABIKind Kind;
3069 
3070 public:
3071   ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind) : ABIInfo(CGT), Kind(_Kind) {
3072     setRuntimeCC();
3073   }
3074 
3075   bool isEABI() const {
3076     StringRef Env = getTarget().getTriple().getEnvironmentName();
3077     return (Env == "gnueabi" || Env == "eabi" ||
3078             Env == "android" || Env == "androideabi");
3079   }
3080 
3081   ABIKind getABIKind() const { return Kind; }
3082 
3083 private:
3084   ABIArgInfo classifyReturnType(QualType RetTy) const;
3085   ABIArgInfo classifyArgumentType(QualType RetTy, int *VFPRegs,
3086                                   unsigned &AllocatedVFP,
3087                                   bool &IsHA) const;
3088   bool isIllegalVectorType(QualType Ty) const;
3089 
3090   virtual void computeInfo(CGFunctionInfo &FI) const;
3091 
3092   virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3093                                  CodeGenFunction &CGF) const;
3094 
3095   llvm::CallingConv::ID getLLVMDefaultCC() const;
3096   llvm::CallingConv::ID getABIDefaultCC() const;
3097   void setRuntimeCC();
3098 };
3099 
3100 class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
3101 public:
3102   ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
3103     :TargetCodeGenInfo(new ARMABIInfo(CGT, K)) {}
3104 
3105   const ARMABIInfo &getABIInfo() const {
3106     return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
3107   }
3108 
3109   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const {
3110     return 13;
3111   }
3112 
3113   StringRef getARCRetainAutoreleasedReturnValueMarker() const {
3114     return "mov\tr7, r7\t\t@ marker for objc_retainAutoreleaseReturnValue";
3115   }
3116 
3117   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3118                                llvm::Value *Address) const {
3119     llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
3120 
3121     // 0-15 are the 16 integer registers.
3122     AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
3123     return false;
3124   }
3125 
3126   unsigned getSizeOfUnwindException() const {
3127     if (getABIInfo().isEABI()) return 88;
3128     return TargetCodeGenInfo::getSizeOfUnwindException();
3129   }
3130 
3131   void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
3132                            CodeGen::CodeGenModule &CGM) const {
3133     const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
3134     if (!FD)
3135       return;
3136 
3137     const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
3138     if (!Attr)
3139       return;
3140 
3141     const char *Kind;
3142     switch (Attr->getInterrupt()) {
3143     case ARMInterruptAttr::Generic: Kind = ""; break;
3144     case ARMInterruptAttr::IRQ:     Kind = "IRQ"; break;
3145     case ARMInterruptAttr::FIQ:     Kind = "FIQ"; break;
3146     case ARMInterruptAttr::SWI:     Kind = "SWI"; break;
3147     case ARMInterruptAttr::ABORT:   Kind = "ABORT"; break;
3148     case ARMInterruptAttr::UNDEF:   Kind = "UNDEF"; break;
3149     }
3150 
3151     llvm::Function *Fn = cast<llvm::Function>(GV);
3152 
3153     Fn->addFnAttr("interrupt", Kind);
3154 
3155     if (cast<ARMABIInfo>(getABIInfo()).getABIKind() == ARMABIInfo::APCS)
3156       return;
3157 
3158     // AAPCS guarantees that sp will be 8-byte aligned on any public interface,
3159     // however this is not necessarily true on taking any interrupt. Instruct
3160     // the backend to perform a realignment as part of the function prologue.
3161     llvm::AttrBuilder B;
3162     B.addStackAlignmentAttr(8);
3163     Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
3164                       llvm::AttributeSet::get(CGM.getLLVMContext(),
3165                                               llvm::AttributeSet::FunctionIndex,
3166                                               B));
3167   }
3168 
3169 };
3170 
3171 }
3172 
3173 void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
3174   // To correctly handle Homogeneous Aggregate, we need to keep track of the
3175   // VFP registers allocated so far.
3176   // C.1.vfp If the argument is a VFP CPRC and there are sufficient consecutive
3177   // VFP registers of the appropriate type unallocated then the argument is
3178   // allocated to the lowest-numbered sequence of such registers.
3179   // C.2.vfp If the argument is a VFP CPRC then any VFP registers that are
3180   // unallocated are marked as unavailable.
3181   unsigned AllocatedVFP = 0;
3182   int VFPRegs[16] = { 0 };
3183   FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
3184   for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
3185        it != ie; ++it) {
3186     unsigned PreAllocation = AllocatedVFP;
3187     bool IsHA = false;
3188     // 6.1.2.3 There is one VFP co-processor register class using registers
3189     // s0-s15 (d0-d7) for passing arguments.
3190     const unsigned NumVFPs = 16;
3191     it->info = classifyArgumentType(it->type, VFPRegs, AllocatedVFP, IsHA);
3192     // If we do not have enough VFP registers for the HA, any VFP registers
3193     // that are unallocated are marked as unavailable. To achieve this, we add
3194     // padding of (NumVFPs - PreAllocation) floats.
3195     if (IsHA && AllocatedVFP > NumVFPs && PreAllocation < NumVFPs) {
3196       llvm::Type *PaddingTy = llvm::ArrayType::get(
3197           llvm::Type::getFloatTy(getVMContext()), NumVFPs - PreAllocation);
3198       it->info = ABIArgInfo::getExpandWithPadding(false, PaddingTy);
3199     }
3200   }
3201 
3202   // Always honor user-specified calling convention.
3203   if (FI.getCallingConvention() != llvm::CallingConv::C)
3204     return;
3205 
3206   llvm::CallingConv::ID cc = getRuntimeCC();
3207   if (cc != llvm::CallingConv::C)
3208     FI.setEffectiveCallingConvention(cc);
3209 }
3210 
3211 /// Return the default calling convention that LLVM will use.
3212 llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
3213   // The default calling convention that LLVM will infer.
3214   if (getTarget().getTriple().getEnvironmentName()=="gnueabihf")
3215     return llvm::CallingConv::ARM_AAPCS_VFP;
3216   else if (isEABI())
3217     return llvm::CallingConv::ARM_AAPCS;
3218   else
3219     return llvm::CallingConv::ARM_APCS;
3220 }
3221 
3222 /// Return the calling convention that our ABI would like us to use
3223 /// as the C calling convention.
3224 llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
3225   switch (getABIKind()) {
3226   case APCS: return llvm::CallingConv::ARM_APCS;
3227   case AAPCS: return llvm::CallingConv::ARM_AAPCS;
3228   case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
3229   }
3230   llvm_unreachable("bad ABI kind");
3231 }
3232 
3233 void ARMABIInfo::setRuntimeCC() {
3234   assert(getRuntimeCC() == llvm::CallingConv::C);
3235 
3236   // Don't muddy up the IR with a ton of explicit annotations if
3237   // they'd just match what LLVM will infer from the triple.
3238   llvm::CallingConv::ID abiCC = getABIDefaultCC();
3239   if (abiCC != getLLVMDefaultCC())
3240     RuntimeCC = abiCC;
3241 }
3242 
3243 /// isHomogeneousAggregate - Return true if a type is an AAPCS-VFP homogeneous
3244 /// aggregate.  If HAMembers is non-null, the number of base elements
3245 /// contained in the type is returned through it; this is used for the
3246 /// recursive calls that check aggregate component types.
3247 static bool isHomogeneousAggregate(QualType Ty, const Type *&Base,
3248                                    ASTContext &Context,
3249                                    uint64_t *HAMembers = 0) {
3250   uint64_t Members = 0;
3251   if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
3252     if (!isHomogeneousAggregate(AT->getElementType(), Base, Context, &Members))
3253       return false;
3254     Members *= AT->getSize().getZExtValue();
3255   } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
3256     const RecordDecl *RD = RT->getDecl();
3257     if (RD->hasFlexibleArrayMember())
3258       return false;
3259 
3260     Members = 0;
3261     for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
3262          i != e; ++i) {
3263       const FieldDecl *FD = *i;
3264       uint64_t FldMembers;
3265       if (!isHomogeneousAggregate(FD->getType(), Base, Context, &FldMembers))
3266         return false;
3267 
3268       Members = (RD->isUnion() ?
3269                  std::max(Members, FldMembers) : Members + FldMembers);
3270     }
3271   } else {
3272     Members = 1;
3273     if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
3274       Members = 2;
3275       Ty = CT->getElementType();
3276     }
3277 
3278     // Homogeneous aggregates for AAPCS-VFP must have base types of float,
3279     // double, or 64-bit or 128-bit vectors.
3280     if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
3281       if (BT->getKind() != BuiltinType::Float &&
3282           BT->getKind() != BuiltinType::Double &&
3283           BT->getKind() != BuiltinType::LongDouble)
3284         return false;
3285     } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
3286       unsigned VecSize = Context.getTypeSize(VT);
3287       if (VecSize != 64 && VecSize != 128)
3288         return false;
3289     } else {
3290       return false;
3291     }
3292 
3293     // The base type must be the same for all members.  Vector types of the
3294     // same total size are treated as being equivalent here.
3295     const Type *TyPtr = Ty.getTypePtr();
3296     if (!Base)
3297       Base = TyPtr;
3298     if (Base != TyPtr &&
3299         (!Base->isVectorType() || !TyPtr->isVectorType() ||
3300          Context.getTypeSize(Base) != Context.getTypeSize(TyPtr)))
3301       return false;
3302   }
3303 
3304   // Homogeneous Aggregates can have at most 4 members of the base type.
3305   if (HAMembers)
3306     *HAMembers = Members;
3307 
3308   return (Members > 0 && Members <= 4);
3309 }
3310 
3311 /// markAllocatedVFPs - update VFPRegs according to the alignment and
3312 /// number of VFP registers (unit is S register) requested.
3313 static void markAllocatedVFPs(int *VFPRegs, unsigned &AllocatedVFP,
3314                               unsigned Alignment,
3315                               unsigned NumRequired) {
3316   // Early Exit.
3317   if (AllocatedVFP >= 16)
3318     return;
3319   // C.1.vfp If the argument is a VFP CPRC and there are sufficient consecutive
3320   // VFP registers of the appropriate type unallocated then the argument is
3321   // allocated to the lowest-numbered sequence of such registers.
3322   for (unsigned I = 0; I < 16; I += Alignment) {
3323     bool FoundSlot = true;
3324     for (unsigned J = I, JEnd = I + NumRequired; J < JEnd; J++)
3325       if (J >= 16 || VFPRegs[J]) {
3326          FoundSlot = false;
3327          break;
3328       }
3329     if (FoundSlot) {
3330       for (unsigned J = I, JEnd = I + NumRequired; J < JEnd; J++)
3331         VFPRegs[J] = 1;
3332       AllocatedVFP += NumRequired;
3333       return;
3334     }
3335   }
3336   // C.2.vfp If the argument is a VFP CPRC then any VFP registers that are
3337   // unallocated are marked as unavailable.
3338   for (unsigned I = 0; I < 16; I++)
3339     VFPRegs[I] = 1;
3340   AllocatedVFP = 17; // We do not have enough VFP registers.
3341 }
3342 
3343 ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty, int *VFPRegs,
3344                                             unsigned &AllocatedVFP,
3345                                             bool &IsHA) const {
3346   // We update number of allocated VFPs according to
3347   // 6.1.2.1 The following argument types are VFP CPRCs:
3348   //   A single-precision floating-point type (including promoted
3349   //   half-precision types); A double-precision floating-point type;
3350   //   A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
3351   //   with a Base Type of a single- or double-precision floating-point type,
3352   //   64-bit containerized vectors or 128-bit containerized vectors with one
3353   //   to four Elements.
3354 
3355   // Handle illegal vector types here.
3356   if (isIllegalVectorType(Ty)) {
3357     uint64_t Size = getContext().getTypeSize(Ty);
3358     if (Size <= 32) {
3359       llvm::Type *ResType =
3360           llvm::Type::getInt32Ty(getVMContext());
3361       return ABIArgInfo::getDirect(ResType);
3362     }
3363     if (Size == 64) {
3364       llvm::Type *ResType = llvm::VectorType::get(
3365           llvm::Type::getInt32Ty(getVMContext()), 2);
3366       markAllocatedVFPs(VFPRegs, AllocatedVFP, 2, 2);
3367       return ABIArgInfo::getDirect(ResType);
3368     }
3369     if (Size == 128) {
3370       llvm::Type *ResType = llvm::VectorType::get(
3371           llvm::Type::getInt32Ty(getVMContext()), 4);
3372       markAllocatedVFPs(VFPRegs, AllocatedVFP, 4, 4);
3373       return ABIArgInfo::getDirect(ResType);
3374     }
3375     return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3376   }
3377   // Update VFPRegs for legal vector types.
3378   if (const VectorType *VT = Ty->getAs<VectorType>()) {
3379     uint64_t Size = getContext().getTypeSize(VT);
3380     // Size of a legal vector should be power of 2 and above 64.
3381     markAllocatedVFPs(VFPRegs, AllocatedVFP, Size >= 128 ? 4 : 2, Size / 32);
3382   }
3383   // Update VFPRegs for floating point types.
3384   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
3385     if (BT->getKind() == BuiltinType::Half ||
3386         BT->getKind() == BuiltinType::Float)
3387       markAllocatedVFPs(VFPRegs, AllocatedVFP, 1, 1);
3388     if (BT->getKind() == BuiltinType::Double ||
3389         BT->getKind() == BuiltinType::LongDouble)
3390       markAllocatedVFPs(VFPRegs, AllocatedVFP, 2, 2);
3391   }
3392 
3393   if (!isAggregateTypeForABI(Ty)) {
3394     // Treat an enum type as its underlying type.
3395     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3396       Ty = EnumTy->getDecl()->getIntegerType();
3397 
3398     return (Ty->isPromotableIntegerType() ?
3399             ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
3400   }
3401 
3402   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
3403     return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
3404 
3405   // Ignore empty records.
3406   if (isEmptyRecord(getContext(), Ty, true))
3407     return ABIArgInfo::getIgnore();
3408 
3409   if (getABIKind() == ARMABIInfo::AAPCS_VFP) {
3410     // Homogeneous Aggregates need to be expanded when we can fit the aggregate
3411     // into VFP registers.
3412     const Type *Base = 0;
3413     uint64_t Members = 0;
3414     if (isHomogeneousAggregate(Ty, Base, getContext(), &Members)) {
3415       assert(Base && "Base class should be set for homogeneous aggregate");
3416       // Base can be a floating-point or a vector.
3417       if (Base->isVectorType()) {
3418         // ElementSize is in number of floats.
3419         unsigned ElementSize = getContext().getTypeSize(Base) == 64 ? 2 : 4;
3420         markAllocatedVFPs(VFPRegs, AllocatedVFP, ElementSize,
3421                           Members * ElementSize);
3422       } else if (Base->isSpecificBuiltinType(BuiltinType::Float))
3423         markAllocatedVFPs(VFPRegs, AllocatedVFP, 1, Members);
3424       else {
3425         assert(Base->isSpecificBuiltinType(BuiltinType::Double) ||
3426                Base->isSpecificBuiltinType(BuiltinType::LongDouble));
3427         markAllocatedVFPs(VFPRegs, AllocatedVFP, 2, Members * 2);
3428       }
3429       IsHA = true;
3430       return ABIArgInfo::getExpand();
3431     }
3432   }
3433 
3434   // Support byval for ARM.
3435   // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
3436   // most 8-byte. We realign the indirect argument if type alignment is bigger
3437   // than ABI alignment.
3438   uint64_t ABIAlign = 4;
3439   uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8;
3440   if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
3441       getABIKind() == ARMABIInfo::AAPCS)
3442     ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
3443   if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
3444     return ABIArgInfo::getIndirect(0, /*ByVal=*/true,
3445            /*Realign=*/TyAlign > ABIAlign);
3446   }
3447 
3448   // Otherwise, pass by coercing to a structure of the appropriate size.
3449   llvm::Type* ElemTy;
3450   unsigned SizeRegs;
3451   // FIXME: Try to match the types of the arguments more accurately where
3452   // we can.
3453   if (getContext().getTypeAlign(Ty) <= 32) {
3454     ElemTy = llvm::Type::getInt32Ty(getVMContext());
3455     SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
3456   } else {
3457     ElemTy = llvm::Type::getInt64Ty(getVMContext());
3458     SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
3459   }
3460 
3461   llvm::Type *STy =
3462     llvm::StructType::get(llvm::ArrayType::get(ElemTy, SizeRegs), NULL);
3463   return ABIArgInfo::getDirect(STy);
3464 }
3465 
3466 static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
3467                               llvm::LLVMContext &VMContext) {
3468   // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
3469   // is called integer-like if its size is less than or equal to one word, and
3470   // the offset of each of its addressable sub-fields is zero.
3471 
3472   uint64_t Size = Context.getTypeSize(Ty);
3473 
3474   // Check that the type fits in a word.
3475   if (Size > 32)
3476     return false;
3477 
3478   // FIXME: Handle vector types!
3479   if (Ty->isVectorType())
3480     return false;
3481 
3482   // Float types are never treated as "integer like".
3483   if (Ty->isRealFloatingType())
3484     return false;
3485 
3486   // If this is a builtin or pointer type then it is ok.
3487   if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
3488     return true;
3489 
3490   // Small complex integer types are "integer like".
3491   if (const ComplexType *CT = Ty->getAs<ComplexType>())
3492     return isIntegerLikeType(CT->getElementType(), Context, VMContext);
3493 
3494   // Single element and zero sized arrays should be allowed, by the definition
3495   // above, but they are not.
3496 
3497   // Otherwise, it must be a record type.
3498   const RecordType *RT = Ty->getAs<RecordType>();
3499   if (!RT) return false;
3500 
3501   // Ignore records with flexible arrays.
3502   const RecordDecl *RD = RT->getDecl();
3503   if (RD->hasFlexibleArrayMember())
3504     return false;
3505 
3506   // Check that all sub-fields are at offset 0, and are themselves "integer
3507   // like".
3508   const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
3509 
3510   bool HadField = false;
3511   unsigned idx = 0;
3512   for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
3513        i != e; ++i, ++idx) {
3514     const FieldDecl *FD = *i;
3515 
3516     // Bit-fields are not addressable, we only need to verify they are "integer
3517     // like". We still have to disallow a subsequent non-bitfield, for example:
3518     //   struct { int : 0; int x }
3519     // is non-integer like according to gcc.
3520     if (FD->isBitField()) {
3521       if (!RD->isUnion())
3522         HadField = true;
3523 
3524       if (!isIntegerLikeType(FD->getType(), Context, VMContext))
3525         return false;
3526 
3527       continue;
3528     }
3529 
3530     // Check if this field is at offset 0.
3531     if (Layout.getFieldOffset(idx) != 0)
3532       return false;
3533 
3534     if (!isIntegerLikeType(FD->getType(), Context, VMContext))
3535       return false;
3536 
3537     // Only allow at most one field in a structure. This doesn't match the
3538     // wording above, but follows gcc in situations with a field following an
3539     // empty structure.
3540     if (!RD->isUnion()) {
3541       if (HadField)
3542         return false;
3543 
3544       HadField = true;
3545     }
3546   }
3547 
3548   return true;
3549 }
3550 
3551 ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy) const {
3552   if (RetTy->isVoidType())
3553     return ABIArgInfo::getIgnore();
3554 
3555   // Large vector types should be returned via memory.
3556   if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
3557     return ABIArgInfo::getIndirect(0);
3558 
3559   if (!isAggregateTypeForABI(RetTy)) {
3560     // Treat an enum type as its underlying type.
3561     if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
3562       RetTy = EnumTy->getDecl()->getIntegerType();
3563 
3564     return (RetTy->isPromotableIntegerType() ?
3565             ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
3566   }
3567 
3568   // Structures with either a non-trivial destructor or a non-trivial
3569   // copy constructor are always indirect.
3570   if (isRecordReturnIndirect(RetTy, getCXXABI()))
3571     return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3572 
3573   // Are we following APCS?
3574   if (getABIKind() == APCS) {
3575     if (isEmptyRecord(getContext(), RetTy, false))
3576       return ABIArgInfo::getIgnore();
3577 
3578     // Complex types are all returned as packed integers.
3579     //
3580     // FIXME: Consider using 2 x vector types if the back end handles them
3581     // correctly.
3582     if (RetTy->isAnyComplexType())
3583       return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
3584                                               getContext().getTypeSize(RetTy)));
3585 
3586     // Integer like structures are returned in r0.
3587     if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
3588       // Return in the smallest viable integer type.
3589       uint64_t Size = getContext().getTypeSize(RetTy);
3590       if (Size <= 8)
3591         return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
3592       if (Size <= 16)
3593         return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
3594       return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
3595     }
3596 
3597     // Otherwise return in memory.
3598     return ABIArgInfo::getIndirect(0);
3599   }
3600 
3601   // Otherwise this is an AAPCS variant.
3602 
3603   if (isEmptyRecord(getContext(), RetTy, true))
3604     return ABIArgInfo::getIgnore();
3605 
3606   // Check for homogeneous aggregates with AAPCS-VFP.
3607   if (getABIKind() == AAPCS_VFP) {
3608     const Type *Base = 0;
3609     if (isHomogeneousAggregate(RetTy, Base, getContext())) {
3610       assert(Base && "Base class should be set for homogeneous aggregate");
3611       // Homogeneous Aggregates are returned directly.
3612       return ABIArgInfo::getDirect();
3613     }
3614   }
3615 
3616   // Aggregates <= 4 bytes are returned in r0; other aggregates
3617   // are returned indirectly.
3618   uint64_t Size = getContext().getTypeSize(RetTy);
3619   if (Size <= 32) {
3620     // Return in the smallest viable integer type.
3621     if (Size <= 8)
3622       return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
3623     if (Size <= 16)
3624       return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
3625     return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
3626   }
3627 
3628   return ABIArgInfo::getIndirect(0);
3629 }
3630 
3631 /// isIllegalVector - check whether Ty is an illegal vector type.
3632 bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
3633   if (const VectorType *VT = Ty->getAs<VectorType>()) {
3634     // Check whether VT is legal.
3635     unsigned NumElements = VT->getNumElements();
3636     uint64_t Size = getContext().getTypeSize(VT);
3637     // NumElements should be power of 2.
3638     if ((NumElements & (NumElements - 1)) != 0)
3639       return true;
3640     // Size should be greater than 32 bits.
3641     return Size <= 32;
3642   }
3643   return false;
3644 }
3645 
3646 llvm::Value *ARMABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3647                                    CodeGenFunction &CGF) const {
3648   llvm::Type *BP = CGF.Int8PtrTy;
3649   llvm::Type *BPP = CGF.Int8PtrPtrTy;
3650 
3651   CGBuilderTy &Builder = CGF.Builder;
3652   llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
3653   llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
3654 
3655   if (isEmptyRecord(getContext(), Ty, true)) {
3656     // These are ignored for parameter passing purposes.
3657     llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
3658     return Builder.CreateBitCast(Addr, PTy);
3659   }
3660 
3661   uint64_t Size = CGF.getContext().getTypeSize(Ty) / 8;
3662   uint64_t TyAlign = CGF.getContext().getTypeAlign(Ty) / 8;
3663   bool IsIndirect = false;
3664 
3665   // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
3666   // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
3667   if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
3668       getABIKind() == ARMABIInfo::AAPCS)
3669     TyAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
3670   else
3671     TyAlign = 4;
3672   // Use indirect if size of the illegal vector is bigger than 16 bytes.
3673   if (isIllegalVectorType(Ty) && Size > 16) {
3674     IsIndirect = true;
3675     Size = 4;
3676     TyAlign = 4;
3677   }
3678 
3679   // Handle address alignment for ABI alignment > 4 bytes.
3680   if (TyAlign > 4) {
3681     assert((TyAlign & (TyAlign - 1)) == 0 &&
3682            "Alignment is not power of 2!");
3683     llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int32Ty);
3684     AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt32(TyAlign - 1));
3685     AddrAsInt = Builder.CreateAnd(AddrAsInt, Builder.getInt32(~(TyAlign - 1)));
3686     Addr = Builder.CreateIntToPtr(AddrAsInt, BP, "ap.align");
3687   }
3688 
3689   uint64_t Offset =
3690     llvm::RoundUpToAlignment(Size, 4);
3691   llvm::Value *NextAddr =
3692     Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
3693                       "ap.next");
3694   Builder.CreateStore(NextAddr, VAListAddrAsBPP);
3695 
3696   if (IsIndirect)
3697     Addr = Builder.CreateLoad(Builder.CreateBitCast(Addr, BPP));
3698   else if (TyAlign < CGF.getContext().getTypeAlign(Ty) / 8) {
3699     // We can't directly cast ap.cur to pointer to a vector type, since ap.cur
3700     // may not be correctly aligned for the vector type. We create an aligned
3701     // temporary space and copy the content over from ap.cur to the temporary
3702     // space. This is necessary if the natural alignment of the type is greater
3703     // than the ABI alignment.
3704     llvm::Type *I8PtrTy = Builder.getInt8PtrTy();
3705     CharUnits CharSize = getContext().getTypeSizeInChars(Ty);
3706     llvm::Value *AlignedTemp = CGF.CreateTempAlloca(CGF.ConvertType(Ty),
3707                                                     "var.align");
3708     llvm::Value *Dst = Builder.CreateBitCast(AlignedTemp, I8PtrTy);
3709     llvm::Value *Src = Builder.CreateBitCast(Addr, I8PtrTy);
3710     Builder.CreateMemCpy(Dst, Src,
3711         llvm::ConstantInt::get(CGF.IntPtrTy, CharSize.getQuantity()),
3712         TyAlign, false);
3713     Addr = AlignedTemp; //The content is in aligned location.
3714   }
3715   llvm::Type *PTy =
3716     llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
3717   llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
3718 
3719   return AddrTyped;
3720 }
3721 
3722 namespace {
3723 
3724 class NaClARMABIInfo : public ABIInfo {
3725  public:
3726   NaClARMABIInfo(CodeGen::CodeGenTypes &CGT, ARMABIInfo::ABIKind Kind)
3727       : ABIInfo(CGT), PInfo(CGT), NInfo(CGT, Kind) {}
3728   virtual void computeInfo(CGFunctionInfo &FI) const;
3729   virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3730                                  CodeGenFunction &CGF) const;
3731  private:
3732   PNaClABIInfo PInfo; // Used for generating calls with pnaclcall callingconv.
3733   ARMABIInfo NInfo; // Used for everything else.
3734 };
3735 
3736 class NaClARMTargetCodeGenInfo : public TargetCodeGenInfo  {
3737  public:
3738   NaClARMTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, ARMABIInfo::ABIKind Kind)
3739       : TargetCodeGenInfo(new NaClARMABIInfo(CGT, Kind)) {}
3740 };
3741 
3742 }
3743 
3744 void NaClARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
3745   if (FI.getASTCallingConvention() == CC_PnaclCall)
3746     PInfo.computeInfo(FI);
3747   else
3748     static_cast<const ABIInfo&>(NInfo).computeInfo(FI);
3749 }
3750 
3751 llvm::Value *NaClARMABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3752                                        CodeGenFunction &CGF) const {
3753   // Always use the native convention; calling pnacl-style varargs functions
3754   // is unsupported.
3755   return static_cast<const ABIInfo&>(NInfo).EmitVAArg(VAListAddr, Ty, CGF);
3756 }
3757 
3758 //===----------------------------------------------------------------------===//
3759 // AArch64 ABI Implementation
3760 //===----------------------------------------------------------------------===//
3761 
3762 namespace {
3763 
3764 class AArch64ABIInfo : public ABIInfo {
3765 public:
3766   AArch64ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
3767 
3768 private:
3769   // The AArch64 PCS is explicit about return types and argument types being
3770   // handled identically, so we don't need to draw a distinction between
3771   // Argument and Return classification.
3772   ABIArgInfo classifyGenericType(QualType Ty, int &FreeIntRegs,
3773                                  int &FreeVFPRegs) const;
3774 
3775   ABIArgInfo tryUseRegs(QualType Ty, int &FreeRegs, int RegsNeeded, bool IsInt,
3776                         llvm::Type *DirectTy = 0) const;
3777 
3778   virtual void computeInfo(CGFunctionInfo &FI) const;
3779 
3780   virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3781                                  CodeGenFunction &CGF) const;
3782 };
3783 
3784 class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
3785 public:
3786   AArch64TargetCodeGenInfo(CodeGenTypes &CGT)
3787     :TargetCodeGenInfo(new AArch64ABIInfo(CGT)) {}
3788 
3789   const AArch64ABIInfo &getABIInfo() const {
3790     return static_cast<const AArch64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
3791   }
3792 
3793   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const {
3794     return 31;
3795   }
3796 
3797   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3798                                llvm::Value *Address) const {
3799     // 0-31 are x0-x30 and sp: 8 bytes each
3800     llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
3801     AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 31);
3802 
3803     // 64-95 are v0-v31: 16 bytes each
3804     llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
3805     AssignToArrayRange(CGF.Builder, Address, Sixteen8, 64, 95);
3806 
3807     return false;
3808   }
3809 
3810 };
3811 
3812 }
3813 
3814 void AArch64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
3815   int FreeIntRegs = 8, FreeVFPRegs = 8;
3816 
3817   FI.getReturnInfo() = classifyGenericType(FI.getReturnType(),
3818                                            FreeIntRegs, FreeVFPRegs);
3819 
3820   FreeIntRegs = FreeVFPRegs = 8;
3821   for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
3822        it != ie; ++it) {
3823     it->info = classifyGenericType(it->type, FreeIntRegs, FreeVFPRegs);
3824 
3825   }
3826 }
3827 
3828 ABIArgInfo
3829 AArch64ABIInfo::tryUseRegs(QualType Ty, int &FreeRegs, int RegsNeeded,
3830                            bool IsInt, llvm::Type *DirectTy) const {
3831   if (FreeRegs >= RegsNeeded) {
3832     FreeRegs -= RegsNeeded;
3833     return ABIArgInfo::getDirect(DirectTy);
3834   }
3835 
3836   llvm::Type *Padding = 0;
3837 
3838   // We need padding so that later arguments don't get filled in anyway. That
3839   // wouldn't happen if only ByVal arguments followed in the same category, but
3840   // a large structure will simply seem to be a pointer as far as LLVM is
3841   // concerned.
3842   if (FreeRegs > 0) {
3843     if (IsInt)
3844       Padding = llvm::Type::getInt64Ty(getVMContext());
3845     else
3846       Padding = llvm::Type::getFloatTy(getVMContext());
3847 
3848     // Either [N x i64] or [N x float].
3849     Padding = llvm::ArrayType::get(Padding, FreeRegs);
3850     FreeRegs = 0;
3851   }
3852 
3853   return ABIArgInfo::getIndirect(getContext().getTypeAlign(Ty) / 8,
3854                                  /*IsByVal=*/ true, /*Realign=*/ false,
3855                                  Padding);
3856 }
3857 
3858 
3859 ABIArgInfo AArch64ABIInfo::classifyGenericType(QualType Ty,
3860                                                int &FreeIntRegs,
3861                                                int &FreeVFPRegs) const {
3862   // Can only occurs for return, but harmless otherwise.
3863   if (Ty->isVoidType())
3864     return ABIArgInfo::getIgnore();
3865 
3866   // Large vector types should be returned via memory. There's no such concept
3867   // in the ABI, but they'd be over 16 bytes anyway so no matter how they're
3868   // classified they'd go into memory (see B.3).
3869   if (Ty->isVectorType() && getContext().getTypeSize(Ty) > 128) {
3870     if (FreeIntRegs > 0)
3871       --FreeIntRegs;
3872     return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3873   }
3874 
3875   // All non-aggregate LLVM types have a concrete ABI representation so they can
3876   // be passed directly. After this block we're guaranteed to be in a
3877   // complicated case.
3878   if (!isAggregateTypeForABI(Ty)) {
3879     // Treat an enum type as its underlying type.
3880     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3881       Ty = EnumTy->getDecl()->getIntegerType();
3882 
3883     if (Ty->isFloatingType() || Ty->isVectorType())
3884       return tryUseRegs(Ty, FreeVFPRegs, /*RegsNeeded=*/ 1, /*IsInt=*/ false);
3885 
3886     assert(getContext().getTypeSize(Ty) <= 128 &&
3887            "unexpectedly large scalar type");
3888 
3889     int RegsNeeded = getContext().getTypeSize(Ty) > 64 ? 2 : 1;
3890 
3891     // If the type may need padding registers to ensure "alignment", we must be
3892     // careful when this is accounted for. Increasing the effective size covers
3893     // all cases.
3894     if (getContext().getTypeAlign(Ty) == 128)
3895       RegsNeeded += FreeIntRegs % 2 != 0;
3896 
3897     return tryUseRegs(Ty, FreeIntRegs, RegsNeeded, /*IsInt=*/ true);
3898   }
3899 
3900   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
3901     if (FreeIntRegs > 0 && RAA == CGCXXABI::RAA_Indirect)
3902       --FreeIntRegs;
3903     return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
3904   }
3905 
3906   if (isEmptyRecord(getContext(), Ty, true)) {
3907     if (!getContext().getLangOpts().CPlusPlus) {
3908       // Empty structs outside C++ mode are a GNU extension, so no ABI can
3909       // possibly tell us what to do. It turns out (I believe) that GCC ignores
3910       // the object for parameter-passsing purposes.
3911       return ABIArgInfo::getIgnore();
3912     }
3913 
3914     // The combination of C++98 9p5 (sizeof(struct) != 0) and the pseudocode
3915     // description of va_arg in the PCS require that an empty struct does
3916     // actually occupy space for parameter-passing. I'm hoping for a
3917     // clarification giving an explicit paragraph to point to in future.
3918     return tryUseRegs(Ty, FreeIntRegs, /*RegsNeeded=*/ 1, /*IsInt=*/ true,
3919                       llvm::Type::getInt8Ty(getVMContext()));
3920   }
3921 
3922   // Homogeneous vector aggregates get passed in registers or on the stack.
3923   const Type *Base = 0;
3924   uint64_t NumMembers = 0;
3925   if (isHomogeneousAggregate(Ty, Base, getContext(), &NumMembers)) {
3926     assert(Base && "Base class should be set for homogeneous aggregate");
3927     // Homogeneous aggregates are passed and returned directly.
3928     return tryUseRegs(Ty, FreeVFPRegs, /*RegsNeeded=*/ NumMembers,
3929                       /*IsInt=*/ false);
3930   }
3931 
3932   uint64_t Size = getContext().getTypeSize(Ty);
3933   if (Size <= 128) {
3934     // Small structs can use the same direct type whether they're in registers
3935     // or on the stack.
3936     llvm::Type *BaseTy;
3937     unsigned NumBases;
3938     int SizeInRegs = (Size + 63) / 64;
3939 
3940     if (getContext().getTypeAlign(Ty) == 128) {
3941       BaseTy = llvm::Type::getIntNTy(getVMContext(), 128);
3942       NumBases = 1;
3943 
3944       // If the type may need padding registers to ensure "alignment", we must
3945       // be careful when this is accounted for. Increasing the effective size
3946       // covers all cases.
3947       SizeInRegs += FreeIntRegs % 2 != 0;
3948     } else {
3949       BaseTy = llvm::Type::getInt64Ty(getVMContext());
3950       NumBases = SizeInRegs;
3951     }
3952     llvm::Type *DirectTy = llvm::ArrayType::get(BaseTy, NumBases);
3953 
3954     return tryUseRegs(Ty, FreeIntRegs, /*RegsNeeded=*/ SizeInRegs,
3955                       /*IsInt=*/ true, DirectTy);
3956   }
3957 
3958   // If the aggregate is > 16 bytes, it's passed and returned indirectly. In
3959   // LLVM terms the return uses an "sret" pointer, but that's handled elsewhere.
3960   --FreeIntRegs;
3961   return ABIArgInfo::getIndirect(0, /* byVal = */ false);
3962 }
3963 
3964 llvm::Value *AArch64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3965                                        CodeGenFunction &CGF) const {
3966   // The AArch64 va_list type and handling is specified in the Procedure Call
3967   // Standard, section B.4:
3968   //
3969   // struct {
3970   //   void *__stack;
3971   //   void *__gr_top;
3972   //   void *__vr_top;
3973   //   int __gr_offs;
3974   //   int __vr_offs;
3975   // };
3976 
3977   assert(!CGF.CGM.getDataLayout().isBigEndian()
3978          && "va_arg not implemented for big-endian AArch64");
3979 
3980   int FreeIntRegs = 8, FreeVFPRegs = 8;
3981   Ty = CGF.getContext().getCanonicalType(Ty);
3982   ABIArgInfo AI = classifyGenericType(Ty, FreeIntRegs, FreeVFPRegs);
3983 
3984   llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
3985   llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
3986   llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
3987   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
3988 
3989   llvm::Value *reg_offs_p = 0, *reg_offs = 0;
3990   int reg_top_index;
3991   int RegSize;
3992   if (FreeIntRegs < 8) {
3993     assert(FreeVFPRegs == 8 && "Arguments never split between int & VFP regs");
3994     // 3 is the field number of __gr_offs
3995     reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 3, "gr_offs_p");
3996     reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
3997     reg_top_index = 1; // field number for __gr_top
3998     RegSize = 8 * (8 - FreeIntRegs);
3999   } else {
4000     assert(FreeVFPRegs < 8 && "Argument must go in VFP or int regs");
4001     // 4 is the field number of __vr_offs.
4002     reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 4, "vr_offs_p");
4003     reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
4004     reg_top_index = 2; // field number for __vr_top
4005     RegSize = 16 * (8 - FreeVFPRegs);
4006   }
4007 
4008   //=======================================
4009   // Find out where argument was passed
4010   //=======================================
4011 
4012   // If reg_offs >= 0 we're already using the stack for this type of
4013   // argument. We don't want to keep updating reg_offs (in case it overflows,
4014   // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
4015   // whatever they get).
4016   llvm::Value *UsingStack = 0;
4017   UsingStack = CGF.Builder.CreateICmpSGE(reg_offs,
4018                                          llvm::ConstantInt::get(CGF.Int32Ty, 0));
4019 
4020   CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
4021 
4022   // Otherwise, at least some kind of argument could go in these registers, the
4023   // quesiton is whether this particular type is too big.
4024   CGF.EmitBlock(MaybeRegBlock);
4025 
4026   // Integer arguments may need to correct register alignment (for example a
4027   // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
4028   // align __gr_offs to calculate the potential address.
4029   if (FreeIntRegs < 8 && AI.isDirect() && getContext().getTypeAlign(Ty) > 64) {
4030     int Align = getContext().getTypeAlign(Ty) / 8;
4031 
4032     reg_offs = CGF.Builder.CreateAdd(reg_offs,
4033                                  llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
4034                                  "align_regoffs");
4035     reg_offs = CGF.Builder.CreateAnd(reg_offs,
4036                                     llvm::ConstantInt::get(CGF.Int32Ty, -Align),
4037                                     "aligned_regoffs");
4038   }
4039 
4040   // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
4041   llvm::Value *NewOffset = 0;
4042   NewOffset = CGF.Builder.CreateAdd(reg_offs,
4043                                     llvm::ConstantInt::get(CGF.Int32Ty, RegSize),
4044                                     "new_reg_offs");
4045   CGF.Builder.CreateStore(NewOffset, reg_offs_p);
4046 
4047   // Now we're in a position to decide whether this argument really was in
4048   // registers or not.
4049   llvm::Value *InRegs = 0;
4050   InRegs = CGF.Builder.CreateICmpSLE(NewOffset,
4051                                      llvm::ConstantInt::get(CGF.Int32Ty, 0),
4052                                      "inreg");
4053 
4054   CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
4055 
4056   //=======================================
4057   // Argument was in registers
4058   //=======================================
4059 
4060   // Now we emit the code for if the argument was originally passed in
4061   // registers. First start the appropriate block:
4062   CGF.EmitBlock(InRegBlock);
4063 
4064   llvm::Value *reg_top_p = 0, *reg_top = 0;
4065   reg_top_p = CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index, "reg_top_p");
4066   reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
4067   llvm::Value *BaseAddr = CGF.Builder.CreateGEP(reg_top, reg_offs);
4068   llvm::Value *RegAddr = 0;
4069   llvm::Type *MemTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
4070 
4071   if (!AI.isDirect()) {
4072     // If it's been passed indirectly (actually a struct), whatever we find from
4073     // stored registers or on the stack will actually be a struct **.
4074     MemTy = llvm::PointerType::getUnqual(MemTy);
4075   }
4076 
4077   const Type *Base = 0;
4078   uint64_t NumMembers;
4079   if (isHomogeneousAggregate(Ty, Base, getContext(), &NumMembers)
4080       && NumMembers > 1) {
4081     // Homogeneous aggregates passed in registers will have their elements split
4082     // and stored 16-bytes apart regardless of size (they're notionally in qN,
4083     // qN+1, ...). We reload and store into a temporary local variable
4084     // contiguously.
4085     assert(AI.isDirect() && "Homogeneous aggregates should be passed directly");
4086     llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
4087     llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
4088     llvm::Value *Tmp = CGF.CreateTempAlloca(HFATy);
4089 
4090     for (unsigned i = 0; i < NumMembers; ++i) {
4091       llvm::Value *BaseOffset = llvm::ConstantInt::get(CGF.Int32Ty, 16 * i);
4092       llvm::Value *LoadAddr = CGF.Builder.CreateGEP(BaseAddr, BaseOffset);
4093       LoadAddr = CGF.Builder.CreateBitCast(LoadAddr,
4094                                            llvm::PointerType::getUnqual(BaseTy));
4095       llvm::Value *StoreAddr = CGF.Builder.CreateStructGEP(Tmp, i);
4096 
4097       llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
4098       CGF.Builder.CreateStore(Elem, StoreAddr);
4099     }
4100 
4101     RegAddr = CGF.Builder.CreateBitCast(Tmp, MemTy);
4102   } else {
4103     // Otherwise the object is contiguous in memory
4104     RegAddr = CGF.Builder.CreateBitCast(BaseAddr, MemTy);
4105   }
4106 
4107   CGF.EmitBranch(ContBlock);
4108 
4109   //=======================================
4110   // Argument was on the stack
4111   //=======================================
4112   CGF.EmitBlock(OnStackBlock);
4113 
4114   llvm::Value *stack_p = 0, *OnStackAddr = 0;
4115   stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "stack_p");
4116   OnStackAddr = CGF.Builder.CreateLoad(stack_p, "stack");
4117 
4118   // Again, stack arguments may need realigmnent. In this case both integer and
4119   // floating-point ones might be affected.
4120   if (AI.isDirect() && getContext().getTypeAlign(Ty) > 64) {
4121     int Align = getContext().getTypeAlign(Ty) / 8;
4122 
4123     OnStackAddr = CGF.Builder.CreatePtrToInt(OnStackAddr, CGF.Int64Ty);
4124 
4125     OnStackAddr = CGF.Builder.CreateAdd(OnStackAddr,
4126                                  llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
4127                                  "align_stack");
4128     OnStackAddr = CGF.Builder.CreateAnd(OnStackAddr,
4129                                     llvm::ConstantInt::get(CGF.Int64Ty, -Align),
4130                                     "align_stack");
4131 
4132     OnStackAddr = CGF.Builder.CreateIntToPtr(OnStackAddr, CGF.Int8PtrTy);
4133   }
4134 
4135   uint64_t StackSize;
4136   if (AI.isDirect())
4137     StackSize = getContext().getTypeSize(Ty) / 8;
4138   else
4139     StackSize = 8;
4140 
4141   // All stack slots are 8 bytes
4142   StackSize = llvm::RoundUpToAlignment(StackSize, 8);
4143 
4144   llvm::Value *StackSizeC = llvm::ConstantInt::get(CGF.Int32Ty, StackSize);
4145   llvm::Value *NewStack = CGF.Builder.CreateGEP(OnStackAddr, StackSizeC,
4146                                                 "new_stack");
4147 
4148   // Write the new value of __stack for the next call to va_arg
4149   CGF.Builder.CreateStore(NewStack, stack_p);
4150 
4151   OnStackAddr = CGF.Builder.CreateBitCast(OnStackAddr, MemTy);
4152 
4153   CGF.EmitBranch(ContBlock);
4154 
4155   //=======================================
4156   // Tidy up
4157   //=======================================
4158   CGF.EmitBlock(ContBlock);
4159 
4160   llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(MemTy, 2, "vaarg.addr");
4161   ResAddr->addIncoming(RegAddr, InRegBlock);
4162   ResAddr->addIncoming(OnStackAddr, OnStackBlock);
4163 
4164   if (AI.isDirect())
4165     return ResAddr;
4166 
4167   return CGF.Builder.CreateLoad(ResAddr, "vaarg.addr");
4168 }
4169 
4170 //===----------------------------------------------------------------------===//
4171 // NVPTX ABI Implementation
4172 //===----------------------------------------------------------------------===//
4173 
4174 namespace {
4175 
4176 class NVPTXABIInfo : public ABIInfo {
4177 public:
4178   NVPTXABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
4179 
4180   ABIArgInfo classifyReturnType(QualType RetTy) const;
4181   ABIArgInfo classifyArgumentType(QualType Ty) const;
4182 
4183   virtual void computeInfo(CGFunctionInfo &FI) const;
4184   virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4185                                  CodeGenFunction &CFG) const;
4186 };
4187 
4188 class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
4189 public:
4190   NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
4191     : TargetCodeGenInfo(new NVPTXABIInfo(CGT)) {}
4192 
4193   virtual void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
4194                                    CodeGen::CodeGenModule &M) const;
4195 private:
4196   static void addKernelMetadata(llvm::Function *F);
4197 };
4198 
4199 ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
4200   if (RetTy->isVoidType())
4201     return ABIArgInfo::getIgnore();
4202   if (isAggregateTypeForABI(RetTy))
4203     return ABIArgInfo::getIndirect(0);
4204   return ABIArgInfo::getDirect();
4205 }
4206 
4207 ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
4208   if (isAggregateTypeForABI(Ty))
4209     return ABIArgInfo::getIndirect(0);
4210 
4211   return ABIArgInfo::getDirect();
4212 }
4213 
4214 void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
4215   FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
4216   for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
4217        it != ie; ++it)
4218     it->info = classifyArgumentType(it->type);
4219 
4220   // Always honor user-specified calling convention.
4221   if (FI.getCallingConvention() != llvm::CallingConv::C)
4222     return;
4223 
4224   FI.setEffectiveCallingConvention(getRuntimeCC());
4225 }
4226 
4227 llvm::Value *NVPTXABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4228                                      CodeGenFunction &CFG) const {
4229   llvm_unreachable("NVPTX does not support varargs");
4230 }
4231 
4232 void NVPTXTargetCodeGenInfo::
4233 SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
4234                     CodeGen::CodeGenModule &M) const{
4235   const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
4236   if (!FD) return;
4237 
4238   llvm::Function *F = cast<llvm::Function>(GV);
4239 
4240   // Perform special handling in OpenCL mode
4241   if (M.getLangOpts().OpenCL) {
4242     // Use OpenCL function attributes to check for kernel functions
4243     // By default, all functions are device functions
4244     if (FD->hasAttr<OpenCLKernelAttr>()) {
4245       // OpenCL __kernel functions get kernel metadata
4246       addKernelMetadata(F);
4247       // And kernel functions are not subject to inlining
4248       F->addFnAttr(llvm::Attribute::NoInline);
4249     }
4250   }
4251 
4252   // Perform special handling in CUDA mode.
4253   if (M.getLangOpts().CUDA) {
4254     // CUDA __global__ functions get a kernel metadata entry.  Since
4255     // __global__ functions cannot be called from the device, we do not
4256     // need to set the noinline attribute.
4257     if (FD->getAttr<CUDAGlobalAttr>())
4258       addKernelMetadata(F);
4259   }
4260 }
4261 
4262 void NVPTXTargetCodeGenInfo::addKernelMetadata(llvm::Function *F) {
4263   llvm::Module *M = F->getParent();
4264   llvm::LLVMContext &Ctx = M->getContext();
4265 
4266   // Get "nvvm.annotations" metadata node
4267   llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
4268 
4269   // Create !{<func-ref>, metadata !"kernel", i32 1} node
4270   llvm::SmallVector<llvm::Value *, 3> MDVals;
4271   MDVals.push_back(F);
4272   MDVals.push_back(llvm::MDString::get(Ctx, "kernel"));
4273   MDVals.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), 1));
4274 
4275   // Append metadata to nvvm.annotations
4276   MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
4277 }
4278 
4279 }
4280 
4281 //===----------------------------------------------------------------------===//
4282 // SystemZ ABI Implementation
4283 //===----------------------------------------------------------------------===//
4284 
4285 namespace {
4286 
4287 class SystemZABIInfo : public ABIInfo {
4288 public:
4289   SystemZABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
4290 
4291   bool isPromotableIntegerType(QualType Ty) const;
4292   bool isCompoundType(QualType Ty) const;
4293   bool isFPArgumentType(QualType Ty) const;
4294 
4295   ABIArgInfo classifyReturnType(QualType RetTy) const;
4296   ABIArgInfo classifyArgumentType(QualType ArgTy) const;
4297 
4298   virtual void computeInfo(CGFunctionInfo &FI) const {
4299     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
4300     for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
4301          it != ie; ++it)
4302       it->info = classifyArgumentType(it->type);
4303   }
4304 
4305   virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4306                                  CodeGenFunction &CGF) const;
4307 };
4308 
4309 class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
4310 public:
4311   SystemZTargetCodeGenInfo(CodeGenTypes &CGT)
4312     : TargetCodeGenInfo(new SystemZABIInfo(CGT)) {}
4313 };
4314 
4315 }
4316 
4317 bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const {
4318   // Treat an enum type as its underlying type.
4319   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4320     Ty = EnumTy->getDecl()->getIntegerType();
4321 
4322   // Promotable integer types are required to be promoted by the ABI.
4323   if (Ty->isPromotableIntegerType())
4324     return true;
4325 
4326   // 32-bit values must also be promoted.
4327   if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
4328     switch (BT->getKind()) {
4329     case BuiltinType::Int:
4330     case BuiltinType::UInt:
4331       return true;
4332     default:
4333       return false;
4334     }
4335   return false;
4336 }
4337 
4338 bool SystemZABIInfo::isCompoundType(QualType Ty) const {
4339   return Ty->isAnyComplexType() || isAggregateTypeForABI(Ty);
4340 }
4341 
4342 bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
4343   if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
4344     switch (BT->getKind()) {
4345     case BuiltinType::Float:
4346     case BuiltinType::Double:
4347       return true;
4348     default:
4349       return false;
4350     }
4351 
4352   if (const RecordType *RT = Ty->getAsStructureType()) {
4353     const RecordDecl *RD = RT->getDecl();
4354     bool Found = false;
4355 
4356     // If this is a C++ record, check the bases first.
4357     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
4358       for (CXXRecordDecl::base_class_const_iterator I = CXXRD->bases_begin(),
4359              E = CXXRD->bases_end(); I != E; ++I) {
4360         QualType Base = I->getType();
4361 
4362         // Empty bases don't affect things either way.
4363         if (isEmptyRecord(getContext(), Base, true))
4364           continue;
4365 
4366         if (Found)
4367           return false;
4368         Found = isFPArgumentType(Base);
4369         if (!Found)
4370           return false;
4371       }
4372 
4373     // Check the fields.
4374     for (RecordDecl::field_iterator I = RD->field_begin(),
4375            E = RD->field_end(); I != E; ++I) {
4376       const FieldDecl *FD = *I;
4377 
4378       // Empty bitfields don't affect things either way.
4379       // Unlike isSingleElementStruct(), empty structure and array fields
4380       // do count.  So do anonymous bitfields that aren't zero-sized.
4381       if (FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
4382         return true;
4383 
4384       // Unlike isSingleElementStruct(), arrays do not count.
4385       // Nested isFPArgumentType structures still do though.
4386       if (Found)
4387         return false;
4388       Found = isFPArgumentType(FD->getType());
4389       if (!Found)
4390         return false;
4391     }
4392 
4393     // Unlike isSingleElementStruct(), trailing padding is allowed.
4394     // An 8-byte aligned struct s { float f; } is passed as a double.
4395     return Found;
4396   }
4397 
4398   return false;
4399 }
4400 
4401 llvm::Value *SystemZABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4402                                        CodeGenFunction &CGF) const {
4403   // Assume that va_list type is correct; should be pointer to LLVM type:
4404   // struct {
4405   //   i64 __gpr;
4406   //   i64 __fpr;
4407   //   i8 *__overflow_arg_area;
4408   //   i8 *__reg_save_area;
4409   // };
4410 
4411   // Every argument occupies 8 bytes and is passed by preference in either
4412   // GPRs or FPRs.
4413   Ty = CGF.getContext().getCanonicalType(Ty);
4414   ABIArgInfo AI = classifyArgumentType(Ty);
4415   bool InFPRs = isFPArgumentType(Ty);
4416 
4417   llvm::Type *APTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
4418   bool IsIndirect = AI.isIndirect();
4419   unsigned UnpaddedBitSize;
4420   if (IsIndirect) {
4421     APTy = llvm::PointerType::getUnqual(APTy);
4422     UnpaddedBitSize = 64;
4423   } else
4424     UnpaddedBitSize = getContext().getTypeSize(Ty);
4425   unsigned PaddedBitSize = 64;
4426   assert((UnpaddedBitSize <= PaddedBitSize) && "Invalid argument size.");
4427 
4428   unsigned PaddedSize = PaddedBitSize / 8;
4429   unsigned Padding = (PaddedBitSize - UnpaddedBitSize) / 8;
4430 
4431   unsigned MaxRegs, RegCountField, RegSaveIndex, RegPadding;
4432   if (InFPRs) {
4433     MaxRegs = 4; // Maximum of 4 FPR arguments
4434     RegCountField = 1; // __fpr
4435     RegSaveIndex = 16; // save offset for f0
4436     RegPadding = 0; // floats are passed in the high bits of an FPR
4437   } else {
4438     MaxRegs = 5; // Maximum of 5 GPR arguments
4439     RegCountField = 0; // __gpr
4440     RegSaveIndex = 2; // save offset for r2
4441     RegPadding = Padding; // values are passed in the low bits of a GPR
4442   }
4443 
4444   llvm::Value *RegCountPtr =
4445     CGF.Builder.CreateStructGEP(VAListAddr, RegCountField, "reg_count_ptr");
4446   llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
4447   llvm::Type *IndexTy = RegCount->getType();
4448   llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
4449   llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
4450 						  "fits_in_regs");
4451 
4452   llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
4453   llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
4454   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
4455   CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
4456 
4457   // Emit code to load the value if it was passed in registers.
4458   CGF.EmitBlock(InRegBlock);
4459 
4460   // Work out the address of an argument register.
4461   llvm::Value *PaddedSizeV = llvm::ConstantInt::get(IndexTy, PaddedSize);
4462   llvm::Value *ScaledRegCount =
4463     CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
4464   llvm::Value *RegBase =
4465     llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize + RegPadding);
4466   llvm::Value *RegOffset =
4467     CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
4468   llvm::Value *RegSaveAreaPtr =
4469     CGF.Builder.CreateStructGEP(VAListAddr, 3, "reg_save_area_ptr");
4470   llvm::Value *RegSaveArea =
4471     CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
4472   llvm::Value *RawRegAddr =
4473     CGF.Builder.CreateGEP(RegSaveArea, RegOffset, "raw_reg_addr");
4474   llvm::Value *RegAddr =
4475     CGF.Builder.CreateBitCast(RawRegAddr, APTy, "reg_addr");
4476 
4477   // Update the register count
4478   llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
4479   llvm::Value *NewRegCount =
4480     CGF.Builder.CreateAdd(RegCount, One, "reg_count");
4481   CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
4482   CGF.EmitBranch(ContBlock);
4483 
4484   // Emit code to load the value if it was passed in memory.
4485   CGF.EmitBlock(InMemBlock);
4486 
4487   // Work out the address of a stack argument.
4488   llvm::Value *OverflowArgAreaPtr =
4489     CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr");
4490   llvm::Value *OverflowArgArea =
4491     CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area");
4492   llvm::Value *PaddingV = llvm::ConstantInt::get(IndexTy, Padding);
4493   llvm::Value *RawMemAddr =
4494     CGF.Builder.CreateGEP(OverflowArgArea, PaddingV, "raw_mem_addr");
4495   llvm::Value *MemAddr =
4496     CGF.Builder.CreateBitCast(RawMemAddr, APTy, "mem_addr");
4497 
4498   // Update overflow_arg_area_ptr pointer
4499   llvm::Value *NewOverflowArgArea =
4500     CGF.Builder.CreateGEP(OverflowArgArea, PaddedSizeV, "overflow_arg_area");
4501   CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
4502   CGF.EmitBranch(ContBlock);
4503 
4504   // Return the appropriate result.
4505   CGF.EmitBlock(ContBlock);
4506   llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(APTy, 2, "va_arg.addr");
4507   ResAddr->addIncoming(RegAddr, InRegBlock);
4508   ResAddr->addIncoming(MemAddr, InMemBlock);
4509 
4510   if (IsIndirect)
4511     return CGF.Builder.CreateLoad(ResAddr, "indirect_arg");
4512 
4513   return ResAddr;
4514 }
4515 
4516 bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
4517     const llvm::Triple &Triple, const CodeGenOptions &Opts) {
4518   assert(Triple.getArch() == llvm::Triple::x86);
4519 
4520   switch (Opts.getStructReturnConvention()) {
4521   case CodeGenOptions::SRCK_Default:
4522     break;
4523   case CodeGenOptions::SRCK_OnStack:  // -fpcc-struct-return
4524     return false;
4525   case CodeGenOptions::SRCK_InRegs:  // -freg-struct-return
4526     return true;
4527   }
4528 
4529   if (Triple.isOSDarwin())
4530     return true;
4531 
4532   switch (Triple.getOS()) {
4533   case llvm::Triple::Cygwin:
4534   case llvm::Triple::MinGW32:
4535   case llvm::Triple::AuroraUX:
4536   case llvm::Triple::DragonFly:
4537   case llvm::Triple::FreeBSD:
4538   case llvm::Triple::OpenBSD:
4539   case llvm::Triple::Bitrig:
4540   case llvm::Triple::Win32:
4541     return true;
4542   default:
4543     return false;
4544   }
4545 }
4546 
4547 ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
4548   if (RetTy->isVoidType())
4549     return ABIArgInfo::getIgnore();
4550   if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
4551     return ABIArgInfo::getIndirect(0);
4552   return (isPromotableIntegerType(RetTy) ?
4553           ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
4554 }
4555 
4556 ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
4557   // Handle the generic C++ ABI.
4558   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
4559     return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
4560 
4561   // Integers and enums are extended to full register width.
4562   if (isPromotableIntegerType(Ty))
4563     return ABIArgInfo::getExtend();
4564 
4565   // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
4566   uint64_t Size = getContext().getTypeSize(Ty);
4567   if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
4568     return ABIArgInfo::getIndirect(0);
4569 
4570   // Handle small structures.
4571   if (const RecordType *RT = Ty->getAs<RecordType>()) {
4572     // Structures with flexible arrays have variable length, so really
4573     // fail the size test above.
4574     const RecordDecl *RD = RT->getDecl();
4575     if (RD->hasFlexibleArrayMember())
4576       return ABIArgInfo::getIndirect(0);
4577 
4578     // The structure is passed as an unextended integer, a float, or a double.
4579     llvm::Type *PassTy;
4580     if (isFPArgumentType(Ty)) {
4581       assert(Size == 32 || Size == 64);
4582       if (Size == 32)
4583         PassTy = llvm::Type::getFloatTy(getVMContext());
4584       else
4585         PassTy = llvm::Type::getDoubleTy(getVMContext());
4586     } else
4587       PassTy = llvm::IntegerType::get(getVMContext(), Size);
4588     return ABIArgInfo::getDirect(PassTy);
4589   }
4590 
4591   // Non-structure compounds are passed indirectly.
4592   if (isCompoundType(Ty))
4593     return ABIArgInfo::getIndirect(0);
4594 
4595   return ABIArgInfo::getDirect(0);
4596 }
4597 
4598 //===----------------------------------------------------------------------===//
4599 // MSP430 ABI Implementation
4600 //===----------------------------------------------------------------------===//
4601 
4602 namespace {
4603 
4604 class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
4605 public:
4606   MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
4607     : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
4608   void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
4609                            CodeGen::CodeGenModule &M) const;
4610 };
4611 
4612 }
4613 
4614 void MSP430TargetCodeGenInfo::SetTargetAttributes(const Decl *D,
4615                                                   llvm::GlobalValue *GV,
4616                                              CodeGen::CodeGenModule &M) const {
4617   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
4618     if (const MSP430InterruptAttr *attr = FD->getAttr<MSP430InterruptAttr>()) {
4619       // Handle 'interrupt' attribute:
4620       llvm::Function *F = cast<llvm::Function>(GV);
4621 
4622       // Step 1: Set ISR calling convention.
4623       F->setCallingConv(llvm::CallingConv::MSP430_INTR);
4624 
4625       // Step 2: Add attributes goodness.
4626       F->addFnAttr(llvm::Attribute::NoInline);
4627 
4628       // Step 3: Emit ISR vector alias.
4629       unsigned Num = attr->getNumber() / 2;
4630       new llvm::GlobalAlias(GV->getType(), llvm::Function::ExternalLinkage,
4631                             "__isr_" + Twine(Num),
4632                             GV, &M.getModule());
4633     }
4634   }
4635 }
4636 
4637 //===----------------------------------------------------------------------===//
4638 // MIPS ABI Implementation.  This works for both little-endian and
4639 // big-endian variants.
4640 //===----------------------------------------------------------------------===//
4641 
4642 namespace {
4643 class MipsABIInfo : public ABIInfo {
4644   bool IsO32;
4645   unsigned MinABIStackAlignInBytes, StackAlignInBytes;
4646   void CoerceToIntArgs(uint64_t TySize,
4647                        SmallVectorImpl<llvm::Type *> &ArgList) const;
4648   llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
4649   llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
4650   llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
4651 public:
4652   MipsABIInfo(CodeGenTypes &CGT, bool _IsO32, bool HasFP64) :
4653     ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
4654     StackAlignInBytes(IsO32 && !HasFP64 ? 8 : 16) {}
4655 
4656   ABIArgInfo classifyReturnType(QualType RetTy) const;
4657   ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
4658   virtual void computeInfo(CGFunctionInfo &FI) const;
4659   virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4660                                  CodeGenFunction &CGF) const;
4661 };
4662 
4663 class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
4664   unsigned SizeOfUnwindException;
4665 public:
4666   MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32, const TargetInfo &Info)
4667     : TargetCodeGenInfo(new MipsABIInfo(CGT, IsO32, Info.hasFeature("fp64"))),
4668       SizeOfUnwindException(IsO32 ? 24 : 32) {}
4669 
4670   int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const {
4671     return 29;
4672   }
4673 
4674   void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
4675                            CodeGen::CodeGenModule &CGM) const {
4676     const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
4677     if (!FD) return;
4678     llvm::Function *Fn = cast<llvm::Function>(GV);
4679     if (FD->hasAttr<Mips16Attr>()) {
4680       Fn->addFnAttr("mips16");
4681     }
4682     else if (FD->hasAttr<NoMips16Attr>()) {
4683       Fn->addFnAttr("nomips16");
4684     }
4685   }
4686 
4687   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4688                                llvm::Value *Address) const;
4689 
4690   unsigned getSizeOfUnwindException() const {
4691     return SizeOfUnwindException;
4692   }
4693 };
4694 }
4695 
4696 void MipsABIInfo::CoerceToIntArgs(uint64_t TySize,
4697                                   SmallVectorImpl<llvm::Type *> &ArgList) const {
4698   llvm::IntegerType *IntTy =
4699     llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
4700 
4701   // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
4702   for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
4703     ArgList.push_back(IntTy);
4704 
4705   // If necessary, add one more integer type to ArgList.
4706   unsigned R = TySize % (MinABIStackAlignInBytes * 8);
4707 
4708   if (R)
4709     ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
4710 }
4711 
4712 // In N32/64, an aligned double precision floating point field is passed in
4713 // a register.
4714 llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
4715   SmallVector<llvm::Type*, 8> ArgList, IntArgList;
4716 
4717   if (IsO32) {
4718     CoerceToIntArgs(TySize, ArgList);
4719     return llvm::StructType::get(getVMContext(), ArgList);
4720   }
4721 
4722   if (Ty->isComplexType())
4723     return CGT.ConvertType(Ty);
4724 
4725   const RecordType *RT = Ty->getAs<RecordType>();
4726 
4727   // Unions/vectors are passed in integer registers.
4728   if (!RT || !RT->isStructureOrClassType()) {
4729     CoerceToIntArgs(TySize, ArgList);
4730     return llvm::StructType::get(getVMContext(), ArgList);
4731   }
4732 
4733   const RecordDecl *RD = RT->getDecl();
4734   const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
4735   assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
4736 
4737   uint64_t LastOffset = 0;
4738   unsigned idx = 0;
4739   llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
4740 
4741   // Iterate over fields in the struct/class and check if there are any aligned
4742   // double fields.
4743   for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
4744        i != e; ++i, ++idx) {
4745     const QualType Ty = i->getType();
4746     const BuiltinType *BT = Ty->getAs<BuiltinType>();
4747 
4748     if (!BT || BT->getKind() != BuiltinType::Double)
4749       continue;
4750 
4751     uint64_t Offset = Layout.getFieldOffset(idx);
4752     if (Offset % 64) // Ignore doubles that are not aligned.
4753       continue;
4754 
4755     // Add ((Offset - LastOffset) / 64) args of type i64.
4756     for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
4757       ArgList.push_back(I64);
4758 
4759     // Add double type.
4760     ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
4761     LastOffset = Offset + 64;
4762   }
4763 
4764   CoerceToIntArgs(TySize - LastOffset, IntArgList);
4765   ArgList.append(IntArgList.begin(), IntArgList.end());
4766 
4767   return llvm::StructType::get(getVMContext(), ArgList);
4768 }
4769 
4770 llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
4771                                         uint64_t Offset) const {
4772   if (OrigOffset + MinABIStackAlignInBytes > Offset)
4773     return 0;
4774 
4775   return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
4776 }
4777 
4778 ABIArgInfo
4779 MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
4780   uint64_t OrigOffset = Offset;
4781   uint64_t TySize = getContext().getTypeSize(Ty);
4782   uint64_t Align = getContext().getTypeAlign(Ty) / 8;
4783 
4784   Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
4785                    (uint64_t)StackAlignInBytes);
4786   unsigned CurrOffset = llvm::RoundUpToAlignment(Offset, Align);
4787   Offset = CurrOffset + llvm::RoundUpToAlignment(TySize, Align * 8) / 8;
4788 
4789   if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
4790     // Ignore empty aggregates.
4791     if (TySize == 0)
4792       return ABIArgInfo::getIgnore();
4793 
4794     if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
4795       Offset = OrigOffset + MinABIStackAlignInBytes;
4796       return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
4797     }
4798 
4799     // If we have reached here, aggregates are passed directly by coercing to
4800     // another structure type. Padding is inserted if the offset of the
4801     // aggregate is unaligned.
4802     return ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
4803                                  getPaddingType(OrigOffset, CurrOffset));
4804   }
4805 
4806   // Treat an enum type as its underlying type.
4807   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4808     Ty = EnumTy->getDecl()->getIntegerType();
4809 
4810   if (Ty->isPromotableIntegerType())
4811     return ABIArgInfo::getExtend();
4812 
4813   return ABIArgInfo::getDirect(
4814       0, 0, IsO32 ? 0 : getPaddingType(OrigOffset, CurrOffset));
4815 }
4816 
4817 llvm::Type*
4818 MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
4819   const RecordType *RT = RetTy->getAs<RecordType>();
4820   SmallVector<llvm::Type*, 8> RTList;
4821 
4822   if (RT && RT->isStructureOrClassType()) {
4823     const RecordDecl *RD = RT->getDecl();
4824     const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
4825     unsigned FieldCnt = Layout.getFieldCount();
4826 
4827     // N32/64 returns struct/classes in floating point registers if the
4828     // following conditions are met:
4829     // 1. The size of the struct/class is no larger than 128-bit.
4830     // 2. The struct/class has one or two fields all of which are floating
4831     //    point types.
4832     // 3. The offset of the first field is zero (this follows what gcc does).
4833     //
4834     // Any other composite results are returned in integer registers.
4835     //
4836     if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
4837       RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
4838       for (; b != e; ++b) {
4839         const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
4840 
4841         if (!BT || !BT->isFloatingPoint())
4842           break;
4843 
4844         RTList.push_back(CGT.ConvertType(b->getType()));
4845       }
4846 
4847       if (b == e)
4848         return llvm::StructType::get(getVMContext(), RTList,
4849                                      RD->hasAttr<PackedAttr>());
4850 
4851       RTList.clear();
4852     }
4853   }
4854 
4855   CoerceToIntArgs(Size, RTList);
4856   return llvm::StructType::get(getVMContext(), RTList);
4857 }
4858 
4859 ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
4860   uint64_t Size = getContext().getTypeSize(RetTy);
4861 
4862   if (RetTy->isVoidType() || Size == 0)
4863     return ABIArgInfo::getIgnore();
4864 
4865   if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
4866     if (isRecordReturnIndirect(RetTy, getCXXABI()))
4867       return ABIArgInfo::getIndirect(0);
4868 
4869     if (Size <= 128) {
4870       if (RetTy->isAnyComplexType())
4871         return ABIArgInfo::getDirect();
4872 
4873       // O32 returns integer vectors in registers.
4874       if (IsO32 && RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())
4875         return ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
4876 
4877       if (!IsO32)
4878         return ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
4879     }
4880 
4881     return ABIArgInfo::getIndirect(0);
4882   }
4883 
4884   // Treat an enum type as its underlying type.
4885   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
4886     RetTy = EnumTy->getDecl()->getIntegerType();
4887 
4888   return (RetTy->isPromotableIntegerType() ?
4889           ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
4890 }
4891 
4892 void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
4893   ABIArgInfo &RetInfo = FI.getReturnInfo();
4894   RetInfo = classifyReturnType(FI.getReturnType());
4895 
4896   // Check if a pointer to an aggregate is passed as a hidden argument.
4897   uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
4898 
4899   for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
4900        it != ie; ++it)
4901     it->info = classifyArgumentType(it->type, Offset);
4902 }
4903 
4904 llvm::Value* MipsABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4905                                     CodeGenFunction &CGF) const {
4906   llvm::Type *BP = CGF.Int8PtrTy;
4907   llvm::Type *BPP = CGF.Int8PtrPtrTy;
4908 
4909   CGBuilderTy &Builder = CGF.Builder;
4910   llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
4911   llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
4912   int64_t TypeAlign = getContext().getTypeAlign(Ty) / 8;
4913   llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
4914   llvm::Value *AddrTyped;
4915   unsigned PtrWidth = getTarget().getPointerWidth(0);
4916   llvm::IntegerType *IntTy = (PtrWidth == 32) ? CGF.Int32Ty : CGF.Int64Ty;
4917 
4918   if (TypeAlign > MinABIStackAlignInBytes) {
4919     llvm::Value *AddrAsInt = CGF.Builder.CreatePtrToInt(Addr, IntTy);
4920     llvm::Value *Inc = llvm::ConstantInt::get(IntTy, TypeAlign - 1);
4921     llvm::Value *Mask = llvm::ConstantInt::get(IntTy, -TypeAlign);
4922     llvm::Value *Add = CGF.Builder.CreateAdd(AddrAsInt, Inc);
4923     llvm::Value *And = CGF.Builder.CreateAnd(Add, Mask);
4924     AddrTyped = CGF.Builder.CreateIntToPtr(And, PTy);
4925   }
4926   else
4927     AddrTyped = Builder.CreateBitCast(Addr, PTy);
4928 
4929   llvm::Value *AlignedAddr = Builder.CreateBitCast(AddrTyped, BP);
4930   TypeAlign = std::max((unsigned)TypeAlign, MinABIStackAlignInBytes);
4931   uint64_t Offset =
4932     llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, TypeAlign);
4933   llvm::Value *NextAddr =
4934     Builder.CreateGEP(AlignedAddr, llvm::ConstantInt::get(IntTy, Offset),
4935                       "ap.next");
4936   Builder.CreateStore(NextAddr, VAListAddrAsBPP);
4937 
4938   return AddrTyped;
4939 }
4940 
4941 bool
4942 MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4943                                                llvm::Value *Address) const {
4944   // This information comes from gcc's implementation, which seems to
4945   // as canonical as it gets.
4946 
4947   // Everything on MIPS is 4 bytes.  Double-precision FP registers
4948   // are aliased to pairs of single-precision FP registers.
4949   llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
4950 
4951   // 0-31 are the general purpose registers, $0 - $31.
4952   // 32-63 are the floating-point registers, $f0 - $f31.
4953   // 64 and 65 are the multiply/divide registers, $hi and $lo.
4954   // 66 is the (notional, I think) register for signal-handler return.
4955   AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
4956 
4957   // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
4958   // They are one bit wide and ignored here.
4959 
4960   // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
4961   // (coprocessor 1 is the FP unit)
4962   // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
4963   // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
4964   // 176-181 are the DSP accumulator registers.
4965   AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
4966   return false;
4967 }
4968 
4969 //===----------------------------------------------------------------------===//
4970 // TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
4971 // Currently subclassed only to implement custom OpenCL C function attribute
4972 // handling.
4973 //===----------------------------------------------------------------------===//
4974 
4975 namespace {
4976 
4977 class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
4978 public:
4979   TCETargetCodeGenInfo(CodeGenTypes &CGT)
4980     : DefaultTargetCodeGenInfo(CGT) {}
4981 
4982   virtual void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
4983                                    CodeGen::CodeGenModule &M) const;
4984 };
4985 
4986 void TCETargetCodeGenInfo::SetTargetAttributes(const Decl *D,
4987                                                llvm::GlobalValue *GV,
4988                                                CodeGen::CodeGenModule &M) const {
4989   const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
4990   if (!FD) return;
4991 
4992   llvm::Function *F = cast<llvm::Function>(GV);
4993 
4994   if (M.getLangOpts().OpenCL) {
4995     if (FD->hasAttr<OpenCLKernelAttr>()) {
4996       // OpenCL C Kernel functions are not subject to inlining
4997       F->addFnAttr(llvm::Attribute::NoInline);
4998 
4999       if (FD->hasAttr<ReqdWorkGroupSizeAttr>()) {
5000 
5001         // Convert the reqd_work_group_size() attributes to metadata.
5002         llvm::LLVMContext &Context = F->getContext();
5003         llvm::NamedMDNode *OpenCLMetadata =
5004             M.getModule().getOrInsertNamedMetadata("opencl.kernel_wg_size_info");
5005 
5006         SmallVector<llvm::Value*, 5> Operands;
5007         Operands.push_back(F);
5008 
5009         Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty,
5010                              llvm::APInt(32,
5011                              FD->getAttr<ReqdWorkGroupSizeAttr>()->getXDim())));
5012         Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty,
5013                              llvm::APInt(32,
5014                                FD->getAttr<ReqdWorkGroupSizeAttr>()->getYDim())));
5015         Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty,
5016                              llvm::APInt(32,
5017                                FD->getAttr<ReqdWorkGroupSizeAttr>()->getZDim())));
5018 
5019         // Add a boolean constant operand for "required" (true) or "hint" (false)
5020         // for implementing the work_group_size_hint attr later. Currently
5021         // always true as the hint is not yet implemented.
5022         Operands.push_back(llvm::ConstantInt::getTrue(Context));
5023         OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
5024       }
5025     }
5026   }
5027 }
5028 
5029 }
5030 
5031 //===----------------------------------------------------------------------===//
5032 // Hexagon ABI Implementation
5033 //===----------------------------------------------------------------------===//
5034 
5035 namespace {
5036 
5037 class HexagonABIInfo : public ABIInfo {
5038 
5039 
5040 public:
5041   HexagonABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
5042 
5043 private:
5044 
5045   ABIArgInfo classifyReturnType(QualType RetTy) const;
5046   ABIArgInfo classifyArgumentType(QualType RetTy) const;
5047 
5048   virtual void computeInfo(CGFunctionInfo &FI) const;
5049 
5050   virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5051                                  CodeGenFunction &CGF) const;
5052 };
5053 
5054 class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
5055 public:
5056   HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
5057     :TargetCodeGenInfo(new HexagonABIInfo(CGT)) {}
5058 
5059   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const {
5060     return 29;
5061   }
5062 };
5063 
5064 }
5065 
5066 void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
5067   FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
5068   for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
5069        it != ie; ++it)
5070     it->info = classifyArgumentType(it->type);
5071 }
5072 
5073 ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty) const {
5074   if (!isAggregateTypeForABI(Ty)) {
5075     // Treat an enum type as its underlying type.
5076     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5077       Ty = EnumTy->getDecl()->getIntegerType();
5078 
5079     return (Ty->isPromotableIntegerType() ?
5080             ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5081   }
5082 
5083   // Ignore empty records.
5084   if (isEmptyRecord(getContext(), Ty, true))
5085     return ABIArgInfo::getIgnore();
5086 
5087   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
5088     return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
5089 
5090   uint64_t Size = getContext().getTypeSize(Ty);
5091   if (Size > 64)
5092     return ABIArgInfo::getIndirect(0, /*ByVal=*/true);
5093     // Pass in the smallest viable integer type.
5094   else if (Size > 32)
5095       return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
5096   else if (Size > 16)
5097       return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
5098   else if (Size > 8)
5099       return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5100   else
5101       return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
5102 }
5103 
5104 ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
5105   if (RetTy->isVoidType())
5106     return ABIArgInfo::getIgnore();
5107 
5108   // Large vector types should be returned via memory.
5109   if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 64)
5110     return ABIArgInfo::getIndirect(0);
5111 
5112   if (!isAggregateTypeForABI(RetTy)) {
5113     // Treat an enum type as its underlying type.
5114     if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5115       RetTy = EnumTy->getDecl()->getIntegerType();
5116 
5117     return (RetTy->isPromotableIntegerType() ?
5118             ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5119   }
5120 
5121   // Structures with either a non-trivial destructor or a non-trivial
5122   // copy constructor are always indirect.
5123   if (isRecordReturnIndirect(RetTy, getCXXABI()))
5124     return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
5125 
5126   if (isEmptyRecord(getContext(), RetTy, true))
5127     return ABIArgInfo::getIgnore();
5128 
5129   // Aggregates <= 8 bytes are returned in r0; other aggregates
5130   // are returned indirectly.
5131   uint64_t Size = getContext().getTypeSize(RetTy);
5132   if (Size <= 64) {
5133     // Return in the smallest viable integer type.
5134     if (Size <= 8)
5135       return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
5136     if (Size <= 16)
5137       return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5138     if (Size <= 32)
5139       return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
5140     return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
5141   }
5142 
5143   return ABIArgInfo::getIndirect(0, /*ByVal=*/true);
5144 }
5145 
5146 llvm::Value *HexagonABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5147                                        CodeGenFunction &CGF) const {
5148   // FIXME: Need to handle alignment
5149   llvm::Type *BPP = CGF.Int8PtrPtrTy;
5150 
5151   CGBuilderTy &Builder = CGF.Builder;
5152   llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
5153                                                        "ap");
5154   llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
5155   llvm::Type *PTy =
5156     llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
5157   llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
5158 
5159   uint64_t Offset =
5160     llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 4);
5161   llvm::Value *NextAddr =
5162     Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
5163                       "ap.next");
5164   Builder.CreateStore(NextAddr, VAListAddrAsBPP);
5165 
5166   return AddrTyped;
5167 }
5168 
5169 
5170 //===----------------------------------------------------------------------===//
5171 // SPARC v9 ABI Implementation.
5172 // Based on the SPARC Compliance Definition version 2.4.1.
5173 //
5174 // Function arguments a mapped to a nominal "parameter array" and promoted to
5175 // registers depending on their type. Each argument occupies 8 or 16 bytes in
5176 // the array, structs larger than 16 bytes are passed indirectly.
5177 //
5178 // One case requires special care:
5179 //
5180 //   struct mixed {
5181 //     int i;
5182 //     float f;
5183 //   };
5184 //
5185 // When a struct mixed is passed by value, it only occupies 8 bytes in the
5186 // parameter array, but the int is passed in an integer register, and the float
5187 // is passed in a floating point register. This is represented as two arguments
5188 // with the LLVM IR inreg attribute:
5189 //
5190 //   declare void f(i32 inreg %i, float inreg %f)
5191 //
5192 // The code generator will only allocate 4 bytes from the parameter array for
5193 // the inreg arguments. All other arguments are allocated a multiple of 8
5194 // bytes.
5195 //
5196 namespace {
5197 class SparcV9ABIInfo : public ABIInfo {
5198 public:
5199   SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
5200 
5201 private:
5202   ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
5203   virtual void computeInfo(CGFunctionInfo &FI) const;
5204   virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5205                                  CodeGenFunction &CGF) const;
5206 
5207   // Coercion type builder for structs passed in registers. The coercion type
5208   // serves two purposes:
5209   //
5210   // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
5211   //    in registers.
5212   // 2. Expose aligned floating point elements as first-level elements, so the
5213   //    code generator knows to pass them in floating point registers.
5214   //
5215   // We also compute the InReg flag which indicates that the struct contains
5216   // aligned 32-bit floats.
5217   //
5218   struct CoerceBuilder {
5219     llvm::LLVMContext &Context;
5220     const llvm::DataLayout &DL;
5221     SmallVector<llvm::Type*, 8> Elems;
5222     uint64_t Size;
5223     bool InReg;
5224 
5225     CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
5226       : Context(c), DL(dl), Size(0), InReg(false) {}
5227 
5228     // Pad Elems with integers until Size is ToSize.
5229     void pad(uint64_t ToSize) {
5230       assert(ToSize >= Size && "Cannot remove elements");
5231       if (ToSize == Size)
5232         return;
5233 
5234       // Finish the current 64-bit word.
5235       uint64_t Aligned = llvm::RoundUpToAlignment(Size, 64);
5236       if (Aligned > Size && Aligned <= ToSize) {
5237         Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
5238         Size = Aligned;
5239       }
5240 
5241       // Add whole 64-bit words.
5242       while (Size + 64 <= ToSize) {
5243         Elems.push_back(llvm::Type::getInt64Ty(Context));
5244         Size += 64;
5245       }
5246 
5247       // Final in-word padding.
5248       if (Size < ToSize) {
5249         Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
5250         Size = ToSize;
5251       }
5252     }
5253 
5254     // Add a floating point element at Offset.
5255     void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
5256       // Unaligned floats are treated as integers.
5257       if (Offset % Bits)
5258         return;
5259       // The InReg flag is only required if there are any floats < 64 bits.
5260       if (Bits < 64)
5261         InReg = true;
5262       pad(Offset);
5263       Elems.push_back(Ty);
5264       Size = Offset + Bits;
5265     }
5266 
5267     // Add a struct type to the coercion type, starting at Offset (in bits).
5268     void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
5269       const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
5270       for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
5271         llvm::Type *ElemTy = StrTy->getElementType(i);
5272         uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
5273         switch (ElemTy->getTypeID()) {
5274         case llvm::Type::StructTyID:
5275           addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
5276           break;
5277         case llvm::Type::FloatTyID:
5278           addFloat(ElemOffset, ElemTy, 32);
5279           break;
5280         case llvm::Type::DoubleTyID:
5281           addFloat(ElemOffset, ElemTy, 64);
5282           break;
5283         case llvm::Type::FP128TyID:
5284           addFloat(ElemOffset, ElemTy, 128);
5285           break;
5286         case llvm::Type::PointerTyID:
5287           if (ElemOffset % 64 == 0) {
5288             pad(ElemOffset);
5289             Elems.push_back(ElemTy);
5290             Size += 64;
5291           }
5292           break;
5293         default:
5294           break;
5295         }
5296       }
5297     }
5298 
5299     // Check if Ty is a usable substitute for the coercion type.
5300     bool isUsableType(llvm::StructType *Ty) const {
5301       if (Ty->getNumElements() != Elems.size())
5302         return false;
5303       for (unsigned i = 0, e = Elems.size(); i != e; ++i)
5304         if (Elems[i] != Ty->getElementType(i))
5305           return false;
5306       return true;
5307     }
5308 
5309     // Get the coercion type as a literal struct type.
5310     llvm::Type *getType() const {
5311       if (Elems.size() == 1)
5312         return Elems.front();
5313       else
5314         return llvm::StructType::get(Context, Elems);
5315     }
5316   };
5317 };
5318 } // end anonymous namespace
5319 
5320 ABIArgInfo
5321 SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
5322   if (Ty->isVoidType())
5323     return ABIArgInfo::getIgnore();
5324 
5325   uint64_t Size = getContext().getTypeSize(Ty);
5326 
5327   // Anything too big to fit in registers is passed with an explicit indirect
5328   // pointer / sret pointer.
5329   if (Size > SizeLimit)
5330     return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
5331 
5332   // Treat an enum type as its underlying type.
5333   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5334     Ty = EnumTy->getDecl()->getIntegerType();
5335 
5336   // Integer types smaller than a register are extended.
5337   if (Size < 64 && Ty->isIntegerType())
5338     return ABIArgInfo::getExtend();
5339 
5340   // Other non-aggregates go in registers.
5341   if (!isAggregateTypeForABI(Ty))
5342     return ABIArgInfo::getDirect();
5343 
5344   // This is a small aggregate type that should be passed in registers.
5345   // Build a coercion type from the LLVM struct type.
5346   llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
5347   if (!StrTy)
5348     return ABIArgInfo::getDirect();
5349 
5350   CoerceBuilder CB(getVMContext(), getDataLayout());
5351   CB.addStruct(0, StrTy);
5352   CB.pad(llvm::RoundUpToAlignment(CB.DL.getTypeSizeInBits(StrTy), 64));
5353 
5354   // Try to use the original type for coercion.
5355   llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
5356 
5357   if (CB.InReg)
5358     return ABIArgInfo::getDirectInReg(CoerceTy);
5359   else
5360     return ABIArgInfo::getDirect(CoerceTy);
5361 }
5362 
5363 llvm::Value *SparcV9ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5364                                        CodeGenFunction &CGF) const {
5365   ABIArgInfo AI = classifyType(Ty, 16 * 8);
5366   llvm::Type *ArgTy = CGT.ConvertType(Ty);
5367   if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
5368     AI.setCoerceToType(ArgTy);
5369 
5370   llvm::Type *BPP = CGF.Int8PtrPtrTy;
5371   CGBuilderTy &Builder = CGF.Builder;
5372   llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
5373   llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
5374   llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
5375   llvm::Value *ArgAddr;
5376   unsigned Stride;
5377 
5378   switch (AI.getKind()) {
5379   case ABIArgInfo::Expand:
5380     llvm_unreachable("Unsupported ABI kind for va_arg");
5381 
5382   case ABIArgInfo::Extend:
5383     Stride = 8;
5384     ArgAddr = Builder
5385       .CreateConstGEP1_32(Addr, 8 - getDataLayout().getTypeAllocSize(ArgTy),
5386                           "extend");
5387     break;
5388 
5389   case ABIArgInfo::Direct:
5390     Stride = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
5391     ArgAddr = Addr;
5392     break;
5393 
5394   case ABIArgInfo::Indirect:
5395     Stride = 8;
5396     ArgAddr = Builder.CreateBitCast(Addr,
5397                                     llvm::PointerType::getUnqual(ArgPtrTy),
5398                                     "indirect");
5399     ArgAddr = Builder.CreateLoad(ArgAddr, "indirect.arg");
5400     break;
5401 
5402   case ABIArgInfo::Ignore:
5403     return llvm::UndefValue::get(ArgPtrTy);
5404   }
5405 
5406   // Update VAList.
5407   Addr = Builder.CreateConstGEP1_32(Addr, Stride, "ap.next");
5408   Builder.CreateStore(Addr, VAListAddrAsBPP);
5409 
5410   return Builder.CreatePointerCast(ArgAddr, ArgPtrTy, "arg.addr");
5411 }
5412 
5413 void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
5414   FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
5415   for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
5416        it != ie; ++it)
5417     it->info = classifyType(it->type, 16 * 8);
5418 }
5419 
5420 namespace {
5421 class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
5422 public:
5423   SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
5424     : TargetCodeGenInfo(new SparcV9ABIInfo(CGT)) {}
5425 };
5426 } // end anonymous namespace
5427 
5428 
5429 //===----------------------------------------------------------------------===//
5430 // Xcore ABI Implementation
5431 //===----------------------------------------------------------------------===//
5432 namespace {
5433 class XCoreABIInfo : public DefaultABIInfo {
5434 public:
5435   XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
5436   virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5437                                  CodeGenFunction &CGF) const;
5438 };
5439 
5440 class XcoreTargetCodeGenInfo : public TargetCodeGenInfo {
5441 public:
5442   XcoreTargetCodeGenInfo(CodeGenTypes &CGT)
5443     :TargetCodeGenInfo(new XCoreABIInfo(CGT)) {}
5444 };
5445 } // End anonymous namespace.
5446 
5447 llvm::Value *XCoreABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5448                                      CodeGenFunction &CGF) const {
5449   CGBuilderTy &Builder = CGF.Builder;
5450 
5451   // Get the VAList.
5452   llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr,
5453                                                        CGF.Int8PtrPtrTy);
5454   llvm::Value *AP = Builder.CreateLoad(VAListAddrAsBPP);
5455 
5456   // Handle the argument.
5457   ABIArgInfo AI = classifyArgumentType(Ty);
5458   llvm::Type *ArgTy = CGT.ConvertType(Ty);
5459   if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
5460     AI.setCoerceToType(ArgTy);
5461   llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
5462   llvm::Value *Val;
5463   uint64_t ArgSize = 0;
5464   switch (AI.getKind()) {
5465   case ABIArgInfo::Expand:
5466     llvm_unreachable("Unsupported ABI kind for va_arg");
5467   case ABIArgInfo::Ignore:
5468     Val = llvm::UndefValue::get(ArgPtrTy);
5469     ArgSize = 0;
5470     break;
5471   case ABIArgInfo::Extend:
5472   case ABIArgInfo::Direct:
5473     Val = Builder.CreatePointerCast(AP, ArgPtrTy);
5474     ArgSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
5475     if (ArgSize < 4)
5476       ArgSize = 4;
5477     break;
5478   case ABIArgInfo::Indirect:
5479     llvm::Value *ArgAddr;
5480     ArgAddr = Builder.CreateBitCast(AP, llvm::PointerType::getUnqual(ArgPtrTy));
5481     ArgAddr = Builder.CreateLoad(ArgAddr);
5482     Val = Builder.CreatePointerCast(ArgAddr, ArgPtrTy);
5483     ArgSize = 4;
5484     break;
5485   }
5486 
5487   // Increment the VAList.
5488   if (ArgSize) {
5489     llvm::Value *APN = Builder.CreateConstGEP1_32(AP, ArgSize);
5490     Builder.CreateStore(APN, VAListAddrAsBPP);
5491   }
5492   return Val;
5493 }
5494 
5495 //===----------------------------------------------------------------------===//
5496 // Driver code
5497 //===----------------------------------------------------------------------===//
5498 
5499 const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
5500   if (TheTargetCodeGenInfo)
5501     return *TheTargetCodeGenInfo;
5502 
5503   const llvm::Triple &Triple = getTarget().getTriple();
5504   switch (Triple.getArch()) {
5505   default:
5506     return *(TheTargetCodeGenInfo = new DefaultTargetCodeGenInfo(Types));
5507 
5508   case llvm::Triple::le32:
5509     return *(TheTargetCodeGenInfo = new PNaClTargetCodeGenInfo(Types));
5510   case llvm::Triple::mips:
5511   case llvm::Triple::mipsel:
5512     return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, true,
5513                                                               getTarget()));
5514   case llvm::Triple::mips64:
5515   case llvm::Triple::mips64el:
5516     return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, false,
5517                                                               getTarget()));
5518   case llvm::Triple::aarch64:
5519     return *(TheTargetCodeGenInfo = new AArch64TargetCodeGenInfo(Types));
5520 
5521   case llvm::Triple::arm:
5522   case llvm::Triple::thumb:
5523     {
5524       ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
5525       if (strcmp(getTarget().getABI(), "apcs-gnu") == 0)
5526         Kind = ARMABIInfo::APCS;
5527       else if (CodeGenOpts.FloatABI == "hard" ||
5528                (CodeGenOpts.FloatABI != "soft" &&
5529                 Triple.getEnvironment() == llvm::Triple::GNUEABIHF))
5530         Kind = ARMABIInfo::AAPCS_VFP;
5531 
5532       switch (Triple.getOS()) {
5533         case llvm::Triple::NaCl:
5534           return *(TheTargetCodeGenInfo =
5535                    new NaClARMTargetCodeGenInfo(Types, Kind));
5536         default:
5537           return *(TheTargetCodeGenInfo =
5538                    new ARMTargetCodeGenInfo(Types, Kind));
5539       }
5540     }
5541 
5542   case llvm::Triple::ppc:
5543     return *(TheTargetCodeGenInfo = new PPC32TargetCodeGenInfo(Types));
5544   case llvm::Triple::ppc64:
5545     if (Triple.isOSBinFormatELF())
5546       return *(TheTargetCodeGenInfo = new PPC64_SVR4_TargetCodeGenInfo(Types));
5547     else
5548       return *(TheTargetCodeGenInfo = new PPC64TargetCodeGenInfo(Types));
5549   case llvm::Triple::ppc64le:
5550     assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
5551     return *(TheTargetCodeGenInfo = new PPC64_SVR4_TargetCodeGenInfo(Types));
5552 
5553   case llvm::Triple::nvptx:
5554   case llvm::Triple::nvptx64:
5555     return *(TheTargetCodeGenInfo = new NVPTXTargetCodeGenInfo(Types));
5556 
5557   case llvm::Triple::msp430:
5558     return *(TheTargetCodeGenInfo = new MSP430TargetCodeGenInfo(Types));
5559 
5560   case llvm::Triple::systemz:
5561     return *(TheTargetCodeGenInfo = new SystemZTargetCodeGenInfo(Types));
5562 
5563   case llvm::Triple::tce:
5564     return *(TheTargetCodeGenInfo = new TCETargetCodeGenInfo(Types));
5565 
5566   case llvm::Triple::x86: {
5567     bool IsDarwinVectorABI = Triple.isOSDarwin();
5568     bool IsSmallStructInRegABI =
5569         X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
5570     bool IsWin32FloatStructABI = (Triple.getOS() == llvm::Triple::Win32);
5571 
5572     if (Triple.getOS() == llvm::Triple::Win32) {
5573       return *(TheTargetCodeGenInfo =
5574                new WinX86_32TargetCodeGenInfo(Types,
5575                                               IsDarwinVectorABI, IsSmallStructInRegABI,
5576                                               IsWin32FloatStructABI,
5577                                               CodeGenOpts.NumRegisterParameters));
5578     } else {
5579       return *(TheTargetCodeGenInfo =
5580                new X86_32TargetCodeGenInfo(Types,
5581                                            IsDarwinVectorABI, IsSmallStructInRegABI,
5582                                            IsWin32FloatStructABI,
5583                                            CodeGenOpts.NumRegisterParameters));
5584     }
5585   }
5586 
5587   case llvm::Triple::x86_64: {
5588     bool HasAVX = strcmp(getTarget().getABI(), "avx") == 0;
5589 
5590     switch (Triple.getOS()) {
5591     case llvm::Triple::Win32:
5592     case llvm::Triple::MinGW32:
5593     case llvm::Triple::Cygwin:
5594       return *(TheTargetCodeGenInfo = new WinX86_64TargetCodeGenInfo(Types));
5595     case llvm::Triple::NaCl:
5596       return *(TheTargetCodeGenInfo = new NaClX86_64TargetCodeGenInfo(Types,
5597                                                                       HasAVX));
5598     default:
5599       return *(TheTargetCodeGenInfo = new X86_64TargetCodeGenInfo(Types,
5600                                                                   HasAVX));
5601     }
5602   }
5603   case llvm::Triple::hexagon:
5604     return *(TheTargetCodeGenInfo = new HexagonTargetCodeGenInfo(Types));
5605   case llvm::Triple::sparcv9:
5606     return *(TheTargetCodeGenInfo = new SparcV9TargetCodeGenInfo(Types));
5607   case llvm::Triple::xcore:
5608     return *(TheTargetCodeGenInfo = new XcoreTargetCodeGenInfo(Types));
5609 
5610   }
5611 }
5612