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 "CodeGenFunction.h"
18 #include "clang/AST/RecordLayout.h"
19 #include "clang/Frontend/CodeGenOptions.h"
20 #include "llvm/Type.h"
21 #include "llvm/DataLayout.h"
22 #include "llvm/ADT/Triple.h"
23 #include "llvm/Support/raw_ostream.h"
24 using namespace clang;
25 using namespace CodeGen;
26 
27 static void AssignToArrayRange(CodeGen::CGBuilderTy &Builder,
28                                llvm::Value *Array,
29                                llvm::Value *Value,
30                                unsigned FirstIndex,
31                                unsigned LastIndex) {
32   // Alternatively, we could emit this as a loop in the source.
33   for (unsigned I = FirstIndex; I <= LastIndex; ++I) {
34     llvm::Value *Cell = Builder.CreateConstInBoundsGEP1_32(Array, I);
35     Builder.CreateStore(Value, Cell);
36   }
37 }
38 
39 static bool isAggregateTypeForABI(QualType T) {
40   return CodeGenFunction::hasAggregateLLVMType(T) ||
41          T->isMemberFunctionPointerType();
42 }
43 
44 ABIInfo::~ABIInfo() {}
45 
46 ASTContext &ABIInfo::getContext() const {
47   return CGT.getContext();
48 }
49 
50 llvm::LLVMContext &ABIInfo::getVMContext() const {
51   return CGT.getLLVMContext();
52 }
53 
54 const llvm::DataLayout &ABIInfo::getDataLayout() const {
55   return CGT.getDataLayout();
56 }
57 
58 
59 void ABIArgInfo::dump() const {
60   raw_ostream &OS = llvm::errs();
61   OS << "(ABIArgInfo Kind=";
62   switch (TheKind) {
63   case Direct:
64     OS << "Direct Type=";
65     if (llvm::Type *Ty = getCoerceToType())
66       Ty->print(OS);
67     else
68       OS << "null";
69     break;
70   case Extend:
71     OS << "Extend";
72     break;
73   case Ignore:
74     OS << "Ignore";
75     break;
76   case Indirect:
77     OS << "Indirect Align=" << getIndirectAlign()
78        << " ByVal=" << getIndirectByVal()
79        << " Realign=" << getIndirectRealign();
80     break;
81   case Expand:
82     OS << "Expand";
83     break;
84   }
85   OS << ")\n";
86 }
87 
88 TargetCodeGenInfo::~TargetCodeGenInfo() { delete Info; }
89 
90 // If someone can figure out a general rule for this, that would be great.
91 // It's probably just doomed to be platform-dependent, though.
92 unsigned TargetCodeGenInfo::getSizeOfUnwindException() const {
93   // Verified for:
94   //   x86-64     FreeBSD, Linux, Darwin
95   //   x86-32     FreeBSD, Linux, Darwin
96   //   PowerPC    Linux, Darwin
97   //   ARM        Darwin (*not* EABI)
98   return 32;
99 }
100 
101 bool TargetCodeGenInfo::isNoProtoCallVariadic(const CallArgList &args,
102                                      const FunctionNoProtoType *fnType) const {
103   // The following conventions are known to require this to be false:
104   //   x86_stdcall
105   //   MIPS
106   // For everything else, we just prefer false unless we opt out.
107   return false;
108 }
109 
110 static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays);
111 
112 /// isEmptyField - Return true iff a the field is "empty", that is it
113 /// is an unnamed bit-field or an (array of) empty record(s).
114 static bool isEmptyField(ASTContext &Context, const FieldDecl *FD,
115                          bool AllowArrays) {
116   if (FD->isUnnamedBitfield())
117     return true;
118 
119   QualType FT = FD->getType();
120 
121   // Constant arrays of empty records count as empty, strip them off.
122   // Constant arrays of zero length always count as empty.
123   if (AllowArrays)
124     while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
125       if (AT->getSize() == 0)
126         return true;
127       FT = AT->getElementType();
128     }
129 
130   const RecordType *RT = FT->getAs<RecordType>();
131   if (!RT)
132     return false;
133 
134   // C++ record fields are never empty, at least in the Itanium ABI.
135   //
136   // FIXME: We should use a predicate for whether this behavior is true in the
137   // current ABI.
138   if (isa<CXXRecordDecl>(RT->getDecl()))
139     return false;
140 
141   return isEmptyRecord(Context, FT, AllowArrays);
142 }
143 
144 /// isEmptyRecord - Return true iff a structure contains only empty
145 /// fields. Note that a structure with a flexible array member is not
146 /// considered empty.
147 static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) {
148   const RecordType *RT = T->getAs<RecordType>();
149   if (!RT)
150     return 0;
151   const RecordDecl *RD = RT->getDecl();
152   if (RD->hasFlexibleArrayMember())
153     return false;
154 
155   // If this is a C++ record, check the bases first.
156   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
157     for (CXXRecordDecl::base_class_const_iterator i = CXXRD->bases_begin(),
158            e = CXXRD->bases_end(); i != e; ++i)
159       if (!isEmptyRecord(Context, i->getType(), true))
160         return false;
161 
162   for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
163          i != e; ++i)
164     if (!isEmptyField(Context, *i, AllowArrays))
165       return false;
166   return true;
167 }
168 
169 /// hasNonTrivialDestructorOrCopyConstructor - Determine if a type has either
170 /// a non-trivial destructor or a non-trivial copy constructor.
171 static bool hasNonTrivialDestructorOrCopyConstructor(const RecordType *RT) {
172   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
173   if (!RD)
174     return false;
175 
176   return !RD->hasTrivialDestructor() || !RD->hasTrivialCopyConstructor();
177 }
178 
179 /// isRecordWithNonTrivialDestructorOrCopyConstructor - Determine if a type is
180 /// a record type with either a non-trivial destructor or a non-trivial copy
181 /// constructor.
182 static bool isRecordWithNonTrivialDestructorOrCopyConstructor(QualType T) {
183   const RecordType *RT = T->getAs<RecordType>();
184   if (!RT)
185     return false;
186 
187   return hasNonTrivialDestructorOrCopyConstructor(RT);
188 }
189 
190 /// isSingleElementStruct - Determine if a structure is a "single
191 /// element struct", i.e. it has exactly one non-empty field or
192 /// exactly one field which is itself a single element
193 /// struct. Structures with flexible array members are never
194 /// considered single element structs.
195 ///
196 /// \return The field declaration for the single non-empty field, if
197 /// it exists.
198 static const Type *isSingleElementStruct(QualType T, ASTContext &Context) {
199   const RecordType *RT = T->getAsStructureType();
200   if (!RT)
201     return 0;
202 
203   const RecordDecl *RD = RT->getDecl();
204   if (RD->hasFlexibleArrayMember())
205     return 0;
206 
207   const Type *Found = 0;
208 
209   // If this is a C++ record, check the bases first.
210   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
211     for (CXXRecordDecl::base_class_const_iterator i = CXXRD->bases_begin(),
212            e = CXXRD->bases_end(); i != e; ++i) {
213       // Ignore empty records.
214       if (isEmptyRecord(Context, i->getType(), true))
215         continue;
216 
217       // If we already found an element then this isn't a single-element struct.
218       if (Found)
219         return 0;
220 
221       // If this is non-empty and not a single element struct, the composite
222       // cannot be a single element struct.
223       Found = isSingleElementStruct(i->getType(), Context);
224       if (!Found)
225         return 0;
226     }
227   }
228 
229   // Check for single element.
230   for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
231          i != e; ++i) {
232     const FieldDecl *FD = *i;
233     QualType FT = FD->getType();
234 
235     // Ignore empty fields.
236     if (isEmptyField(Context, FD, true))
237       continue;
238 
239     // If we already found an element then this isn't a single-element
240     // struct.
241     if (Found)
242       return 0;
243 
244     // Treat single element arrays as the element.
245     while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
246       if (AT->getSize().getZExtValue() != 1)
247         break;
248       FT = AT->getElementType();
249     }
250 
251     if (!isAggregateTypeForABI(FT)) {
252       Found = FT.getTypePtr();
253     } else {
254       Found = isSingleElementStruct(FT, Context);
255       if (!Found)
256         return 0;
257     }
258   }
259 
260   // We don't consider a struct a single-element struct if it has
261   // padding beyond the element type.
262   if (Found && Context.getTypeSize(Found) != Context.getTypeSize(T))
263     return 0;
264 
265   return Found;
266 }
267 
268 static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
269   if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() &&
270       !Ty->isAnyComplexType() && !Ty->isEnumeralType() &&
271       !Ty->isBlockPointerType())
272     return false;
273 
274   uint64_t Size = Context.getTypeSize(Ty);
275   return Size == 32 || Size == 64;
276 }
277 
278 /// canExpandIndirectArgument - Test whether an argument type which is to be
279 /// passed indirectly (on the stack) would have the equivalent layout if it was
280 /// expanded into separate arguments. If so, we prefer to do the latter to avoid
281 /// inhibiting optimizations.
282 ///
283 // FIXME: This predicate is missing many cases, currently it just follows
284 // llvm-gcc (checks that all fields are 32-bit or 64-bit primitive types). We
285 // should probably make this smarter, or better yet make the LLVM backend
286 // capable of handling it.
287 static bool canExpandIndirectArgument(QualType Ty, ASTContext &Context) {
288   // We can only expand structure types.
289   const RecordType *RT = Ty->getAs<RecordType>();
290   if (!RT)
291     return false;
292 
293   // We can only expand (C) structures.
294   //
295   // FIXME: This needs to be generalized to handle classes as well.
296   const RecordDecl *RD = RT->getDecl();
297   if (!RD->isStruct() || isa<CXXRecordDecl>(RD))
298     return false;
299 
300   uint64_t Size = 0;
301 
302   for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
303          i != e; ++i) {
304     const FieldDecl *FD = *i;
305 
306     if (!is32Or64BitBasicType(FD->getType(), Context))
307       return false;
308 
309     // FIXME: Reject bit-fields wholesale; there are two problems, we don't know
310     // how to expand them yet, and the predicate for telling if a bitfield still
311     // counts as "basic" is more complicated than what we were doing previously.
312     if (FD->isBitField())
313       return false;
314 
315     Size += Context.getTypeSize(FD->getType());
316   }
317 
318   // Make sure there are not any holes in the struct.
319   if (Size != Context.getTypeSize(Ty))
320     return false;
321 
322   return true;
323 }
324 
325 namespace {
326 /// DefaultABIInfo - The default implementation for ABI specific
327 /// details. This implementation provides information which results in
328 /// self-consistent and sensible LLVM IR generation, but does not
329 /// conform to any particular ABI.
330 class DefaultABIInfo : public ABIInfo {
331 public:
332   DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
333 
334   ABIArgInfo classifyReturnType(QualType RetTy) const;
335   ABIArgInfo classifyArgumentType(QualType RetTy) const;
336 
337   virtual void computeInfo(CGFunctionInfo &FI) const {
338     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
339     for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
340          it != ie; ++it)
341       it->info = classifyArgumentType(it->type);
342   }
343 
344   virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
345                                  CodeGenFunction &CGF) const;
346 };
347 
348 class DefaultTargetCodeGenInfo : public TargetCodeGenInfo {
349 public:
350   DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
351     : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
352 };
353 
354 llvm::Value *DefaultABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
355                                        CodeGenFunction &CGF) const {
356   return 0;
357 }
358 
359 ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const {
360   if (isAggregateTypeForABI(Ty)) {
361     // Records with non trivial destructors/constructors should not be passed
362     // by value.
363     if (isRecordWithNonTrivialDestructorOrCopyConstructor(Ty))
364       return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
365 
366     return ABIArgInfo::getIndirect(0);
367   }
368 
369   // Treat an enum type as its underlying type.
370   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
371     Ty = EnumTy->getDecl()->getIntegerType();
372 
373   return (Ty->isPromotableIntegerType() ?
374           ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
375 }
376 
377 ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const {
378   if (RetTy->isVoidType())
379     return ABIArgInfo::getIgnore();
380 
381   if (isAggregateTypeForABI(RetTy))
382     return ABIArgInfo::getIndirect(0);
383 
384   // Treat an enum type as its underlying type.
385   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
386     RetTy = EnumTy->getDecl()->getIntegerType();
387 
388   return (RetTy->isPromotableIntegerType() ?
389           ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
390 }
391 
392 //===----------------------------------------------------------------------===//
393 // le32/PNaCl bitcode ABI Implementation
394 //===----------------------------------------------------------------------===//
395 
396 class PNaClABIInfo : public ABIInfo {
397  public:
398   PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
399 
400   ABIArgInfo classifyReturnType(QualType RetTy) const;
401   ABIArgInfo classifyArgumentType(QualType RetTy, unsigned &FreeRegs) const;
402 
403   virtual void computeInfo(CGFunctionInfo &FI) const;
404   virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
405                                  CodeGenFunction &CGF) const;
406 };
407 
408 class PNaClTargetCodeGenInfo : public TargetCodeGenInfo {
409  public:
410   PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
411     : TargetCodeGenInfo(new PNaClABIInfo(CGT)) {}
412 };
413 
414 void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const {
415     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
416 
417     unsigned FreeRegs = FI.getHasRegParm() ? FI.getRegParm() : 0;
418 
419     for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
420          it != ie; ++it)
421       it->info = classifyArgumentType(it->type, FreeRegs);
422   }
423 
424 llvm::Value *PNaClABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
425                                        CodeGenFunction &CGF) const {
426   return 0;
427 }
428 
429 ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty,
430                                               unsigned &FreeRegs) const {
431   if (isAggregateTypeForABI(Ty)) {
432     // Records with non trivial destructors/constructors should not be passed
433     // by value.
434     FreeRegs = 0;
435     if (isRecordWithNonTrivialDestructorOrCopyConstructor(Ty))
436       return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
437 
438     return ABIArgInfo::getIndirect(0);
439   }
440 
441   // Treat an enum type as its underlying type.
442   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
443     Ty = EnumTy->getDecl()->getIntegerType();
444 
445   ABIArgInfo BaseInfo = (Ty->isPromotableIntegerType() ?
446           ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
447 
448   // Regparm regs hold 32 bits.
449   unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
450   if (SizeInRegs == 0) return BaseInfo;
451   if (SizeInRegs > FreeRegs) {
452     FreeRegs = 0;
453     return BaseInfo;
454   }
455   FreeRegs -= SizeInRegs;
456   return BaseInfo.isDirect() ?
457       ABIArgInfo::getDirectInReg(BaseInfo.getCoerceToType()) :
458       ABIArgInfo::getExtendInReg(BaseInfo.getCoerceToType());
459 }
460 
461 ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const {
462   if (RetTy->isVoidType())
463     return ABIArgInfo::getIgnore();
464 
465   if (isAggregateTypeForABI(RetTy))
466     return ABIArgInfo::getIndirect(0);
467 
468   // Treat an enum type as its underlying type.
469   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
470     RetTy = EnumTy->getDecl()->getIntegerType();
471 
472   return (RetTy->isPromotableIntegerType() ?
473           ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
474 }
475 
476 /// UseX86_MMXType - Return true if this is an MMX type that should use the
477 /// special x86_mmx type.
478 bool UseX86_MMXType(llvm::Type *IRType) {
479   // If the type is an MMX type <2 x i32>, <4 x i16>, or <8 x i8>, use the
480   // special x86_mmx type.
481   return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 &&
482     cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() &&
483     IRType->getScalarSizeInBits() != 64;
484 }
485 
486 static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
487                                           StringRef Constraint,
488                                           llvm::Type* Ty) {
489   if ((Constraint == "y" || Constraint == "&y") && Ty->isVectorTy())
490     return llvm::Type::getX86_MMXTy(CGF.getLLVMContext());
491   return Ty;
492 }
493 
494 //===----------------------------------------------------------------------===//
495 // X86-32 ABI Implementation
496 //===----------------------------------------------------------------------===//
497 
498 /// X86_32ABIInfo - The X86-32 ABI information.
499 class X86_32ABIInfo : public ABIInfo {
500   enum Class {
501     Integer,
502     Float
503   };
504 
505   static const unsigned MinABIStackAlignInBytes = 4;
506 
507   bool IsDarwinVectorABI;
508   bool IsSmallStructInRegABI;
509   bool IsMMXDisabled;
510   bool IsWin32FloatStructABI;
511   unsigned DefaultNumRegisterParameters;
512 
513   static bool isRegisterSize(unsigned Size) {
514     return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
515   }
516 
517   static bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context,
518                                           unsigned callingConvention);
519 
520   /// getIndirectResult - Give a source type \arg Ty, return a suitable result
521   /// such that the argument will be passed in memory.
522   ABIArgInfo getIndirectResult(QualType Ty, bool ByVal = true) const;
523 
524   /// \brief Return the alignment to use for the given type on the stack.
525   unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const;
526 
527   Class classify(QualType Ty) const;
528   ABIArgInfo classifyReturnType(QualType RetTy,
529                                 unsigned callingConvention) const;
530   ABIArgInfo classifyArgumentTypeWithReg(QualType RetTy,
531                                          unsigned &FreeRegs) const;
532   ABIArgInfo classifyArgumentType(QualType RetTy) const;
533 
534 public:
535 
536   virtual void computeInfo(CGFunctionInfo &FI) const;
537   virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
538                                  CodeGenFunction &CGF) const;
539 
540   X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool d, bool p, bool m, bool w,
541                 unsigned r)
542     : ABIInfo(CGT), IsDarwinVectorABI(d), IsSmallStructInRegABI(p),
543       IsMMXDisabled(m), IsWin32FloatStructABI(w),
544       DefaultNumRegisterParameters(r) {}
545 };
546 
547 class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
548 public:
549   X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
550       bool d, bool p, bool m, bool w, unsigned r)
551     :TargetCodeGenInfo(new X86_32ABIInfo(CGT, d, p, m, w, r)) {}
552 
553   void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
554                            CodeGen::CodeGenModule &CGM) const;
555 
556   int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const {
557     // Darwin uses different dwarf register numbers for EH.
558     if (CGM.isTargetDarwin()) return 5;
559 
560     return 4;
561   }
562 
563   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
564                                llvm::Value *Address) const;
565 
566   llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
567                                   StringRef Constraint,
568                                   llvm::Type* Ty) const {
569     return X86AdjustInlineAsmType(CGF, Constraint, Ty);
570   }
571 
572 };
573 
574 }
575 
576 /// shouldReturnTypeInRegister - Determine if the given type should be
577 /// passed in a register (for the Darwin ABI).
578 bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
579                                                ASTContext &Context,
580                                                unsigned callingConvention) {
581   uint64_t Size = Context.getTypeSize(Ty);
582 
583   // Type must be register sized.
584   if (!isRegisterSize(Size))
585     return false;
586 
587   if (Ty->isVectorType()) {
588     // 64- and 128- bit vectors inside structures are not returned in
589     // registers.
590     if (Size == 64 || Size == 128)
591       return false;
592 
593     return true;
594   }
595 
596   // If this is a builtin, pointer, enum, complex type, member pointer, or
597   // member function pointer it is ok.
598   if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() ||
599       Ty->isAnyComplexType() || Ty->isEnumeralType() ||
600       Ty->isBlockPointerType() || Ty->isMemberPointerType())
601     return true;
602 
603   // Arrays are treated like records.
604   if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
605     return shouldReturnTypeInRegister(AT->getElementType(), Context,
606                                       callingConvention);
607 
608   // Otherwise, it must be a record type.
609   const RecordType *RT = Ty->getAs<RecordType>();
610   if (!RT) return false;
611 
612   // FIXME: Traverse bases here too.
613 
614   // For thiscall conventions, structures will never be returned in
615   // a register.  This is for compatibility with the MSVC ABI
616   if (callingConvention == llvm::CallingConv::X86_ThisCall &&
617       RT->isStructureType()) {
618     return false;
619   }
620 
621   // Structure types are passed in register if all fields would be
622   // passed in a register.
623   for (RecordDecl::field_iterator i = RT->getDecl()->field_begin(),
624          e = RT->getDecl()->field_end(); i != e; ++i) {
625     const FieldDecl *FD = *i;
626 
627     // Empty fields are ignored.
628     if (isEmptyField(Context, FD, true))
629       continue;
630 
631     // Check fields recursively.
632     if (!shouldReturnTypeInRegister(FD->getType(), Context,
633                                     callingConvention))
634       return false;
635   }
636   return true;
637 }
638 
639 ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy,
640                                             unsigned callingConvention) const {
641   if (RetTy->isVoidType())
642     return ABIArgInfo::getIgnore();
643 
644   if (const VectorType *VT = RetTy->getAs<VectorType>()) {
645     // On Darwin, some vectors are returned in registers.
646     if (IsDarwinVectorABI) {
647       uint64_t Size = getContext().getTypeSize(RetTy);
648 
649       // 128-bit vectors are a special case; they are returned in
650       // registers and we need to make sure to pick a type the LLVM
651       // backend will like.
652       if (Size == 128)
653         return ABIArgInfo::getDirect(llvm::VectorType::get(
654                   llvm::Type::getInt64Ty(getVMContext()), 2));
655 
656       // Always return in register if it fits in a general purpose
657       // register, or if it is 64 bits and has a single element.
658       if ((Size == 8 || Size == 16 || Size == 32) ||
659           (Size == 64 && VT->getNumElements() == 1))
660         return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
661                                                             Size));
662 
663       return ABIArgInfo::getIndirect(0);
664     }
665 
666     return ABIArgInfo::getDirect();
667   }
668 
669   if (isAggregateTypeForABI(RetTy)) {
670     if (const RecordType *RT = RetTy->getAs<RecordType>()) {
671       // Structures with either a non-trivial destructor or a non-trivial
672       // copy constructor are always indirect.
673       if (hasNonTrivialDestructorOrCopyConstructor(RT))
674         return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
675 
676       // Structures with flexible arrays are always indirect.
677       if (RT->getDecl()->hasFlexibleArrayMember())
678         return ABIArgInfo::getIndirect(0);
679     }
680 
681     // If specified, structs and unions are always indirect.
682     if (!IsSmallStructInRegABI && !RetTy->isAnyComplexType())
683       return ABIArgInfo::getIndirect(0);
684 
685     // Small structures which are register sized are generally returned
686     // in a register.
687     if (X86_32ABIInfo::shouldReturnTypeInRegister(RetTy, getContext(),
688                                                   callingConvention)) {
689       uint64_t Size = getContext().getTypeSize(RetTy);
690 
691       // As a special-case, if the struct is a "single-element" struct, and
692       // the field is of type "float" or "double", return it in a
693       // floating-point register. (MSVC does not apply this special case.)
694       // We apply a similar transformation for pointer types to improve the
695       // quality of the generated IR.
696       if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
697         if ((!IsWin32FloatStructABI && SeltTy->isRealFloatingType())
698             || SeltTy->hasPointerRepresentation())
699           return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
700 
701       // FIXME: We should be able to narrow this integer in cases with dead
702       // padding.
703       return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
704     }
705 
706     return ABIArgInfo::getIndirect(0);
707   }
708 
709   // Treat an enum type as its underlying type.
710   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
711     RetTy = EnumTy->getDecl()->getIntegerType();
712 
713   return (RetTy->isPromotableIntegerType() ?
714           ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
715 }
716 
717 static bool isSSEVectorType(ASTContext &Context, QualType Ty) {
718   return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128;
719 }
720 
721 static bool isRecordWithSSEVectorType(ASTContext &Context, QualType Ty) {
722   const RecordType *RT = Ty->getAs<RecordType>();
723   if (!RT)
724     return 0;
725   const RecordDecl *RD = RT->getDecl();
726 
727   // If this is a C++ record, check the bases first.
728   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
729     for (CXXRecordDecl::base_class_const_iterator i = CXXRD->bases_begin(),
730            e = CXXRD->bases_end(); i != e; ++i)
731       if (!isRecordWithSSEVectorType(Context, i->getType()))
732         return false;
733 
734   for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
735        i != e; ++i) {
736     QualType FT = i->getType();
737 
738     if (isSSEVectorType(Context, FT))
739       return true;
740 
741     if (isRecordWithSSEVectorType(Context, FT))
742       return true;
743   }
744 
745   return false;
746 }
747 
748 unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
749                                                  unsigned Align) const {
750   // Otherwise, if the alignment is less than or equal to the minimum ABI
751   // alignment, just use the default; the backend will handle this.
752   if (Align <= MinABIStackAlignInBytes)
753     return 0; // Use default alignment.
754 
755   // On non-Darwin, the stack type alignment is always 4.
756   if (!IsDarwinVectorABI) {
757     // Set explicit alignment, since we may need to realign the top.
758     return MinABIStackAlignInBytes;
759   }
760 
761   // Otherwise, if the type contains an SSE vector type, the alignment is 16.
762   if (Align >= 16 && (isSSEVectorType(getContext(), Ty) ||
763                       isRecordWithSSEVectorType(getContext(), Ty)))
764     return 16;
765 
766   return MinABIStackAlignInBytes;
767 }
768 
769 ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal) const {
770   if (!ByVal)
771     return ABIArgInfo::getIndirect(0, false);
772 
773   // Compute the byval alignment.
774   unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
775   unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign);
776   if (StackAlign == 0)
777     return ABIArgInfo::getIndirect(4);
778 
779   // If the stack alignment is less than the type alignment, realign the
780   // argument.
781   if (StackAlign < TypeAlign)
782     return ABIArgInfo::getIndirect(StackAlign, /*ByVal=*/true,
783                                    /*Realign=*/true);
784 
785   return ABIArgInfo::getIndirect(StackAlign);
786 }
787 
788 X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const {
789   const Type *T = isSingleElementStruct(Ty, getContext());
790   if (!T)
791     T = Ty.getTypePtr();
792 
793   if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
794     BuiltinType::Kind K = BT->getKind();
795     if (K == BuiltinType::Float || K == BuiltinType::Double)
796       return Float;
797   }
798   return Integer;
799 }
800 
801 ABIArgInfo
802 X86_32ABIInfo::classifyArgumentTypeWithReg(QualType Ty,
803                                            unsigned &FreeRegs) const {
804   // Common case first.
805   if (FreeRegs == 0)
806     return classifyArgumentType(Ty);
807 
808   Class C = classify(Ty);
809   if (C == Float)
810     return classifyArgumentType(Ty);
811 
812   unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
813   if (SizeInRegs == 0)
814     return classifyArgumentType(Ty);
815 
816   if (SizeInRegs > FreeRegs) {
817     FreeRegs = 0;
818     return classifyArgumentType(Ty);
819   }
820   assert(SizeInRegs >= 1 && SizeInRegs <= 3);
821   FreeRegs -= SizeInRegs;
822 
823   // If it is a simple scalar, keep the type so that we produce a cleaner IR.
824   ABIArgInfo Foo = classifyArgumentType(Ty);
825   if (Foo.isDirect() && !Foo.getDirectOffset() && !Foo.getPaddingType())
826     return ABIArgInfo::getDirectInReg(Foo.getCoerceToType());
827   if (Foo.isExtend())
828     return ABIArgInfo::getExtendInReg(Foo.getCoerceToType());
829 
830   llvm::LLVMContext &LLVMContext = getVMContext();
831   llvm::Type *Int32 = llvm::Type::getInt32Ty(LLVMContext);
832   SmallVector<llvm::Type*, 3> Elements;
833   for (unsigned I = 0; I < SizeInRegs; ++I)
834     Elements.push_back(Int32);
835   llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
836   return ABIArgInfo::getDirectInReg(Result);
837 }
838 
839 ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty) const {
840   // FIXME: Set alignment on indirect arguments.
841   if (isAggregateTypeForABI(Ty)) {
842     // Structures with flexible arrays are always indirect.
843     if (const RecordType *RT = Ty->getAs<RecordType>()) {
844       // Structures with either a non-trivial destructor or a non-trivial
845       // copy constructor are always indirect.
846       if (hasNonTrivialDestructorOrCopyConstructor(RT))
847         return getIndirectResult(Ty, /*ByVal=*/false);
848 
849       if (RT->getDecl()->hasFlexibleArrayMember())
850         return getIndirectResult(Ty);
851     }
852 
853     // Ignore empty structs/unions.
854     if (isEmptyRecord(getContext(), Ty, true))
855       return ABIArgInfo::getIgnore();
856 
857     // Expand small (<= 128-bit) record types when we know that the stack layout
858     // of those arguments will match the struct. This is important because the
859     // LLVM backend isn't smart enough to remove byval, which inhibits many
860     // optimizations.
861     if (getContext().getTypeSize(Ty) <= 4*32 &&
862         canExpandIndirectArgument(Ty, getContext()))
863       return ABIArgInfo::getExpand();
864 
865     return getIndirectResult(Ty);
866   }
867 
868   if (const VectorType *VT = Ty->getAs<VectorType>()) {
869     // On Darwin, some vectors are passed in memory, we handle this by passing
870     // it as an i8/i16/i32/i64.
871     if (IsDarwinVectorABI) {
872       uint64_t Size = getContext().getTypeSize(Ty);
873       if ((Size == 8 || Size == 16 || Size == 32) ||
874           (Size == 64 && VT->getNumElements() == 1))
875         return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
876                                                             Size));
877     }
878 
879     llvm::Type *IRType = CGT.ConvertType(Ty);
880     if (UseX86_MMXType(IRType)) {
881       if (IsMMXDisabled)
882         return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
883                                                             64));
884       ABIArgInfo AAI = ABIArgInfo::getDirect(IRType);
885       AAI.setCoerceToType(llvm::Type::getX86_MMXTy(getVMContext()));
886       return AAI;
887     }
888 
889     return ABIArgInfo::getDirect();
890   }
891 
892 
893   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
894     Ty = EnumTy->getDecl()->getIntegerType();
895 
896   return (Ty->isPromotableIntegerType() ?
897           ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
898 }
899 
900 void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const {
901   FI.getReturnInfo() = classifyReturnType(FI.getReturnType(),
902                                           FI.getCallingConvention());
903 
904   unsigned FreeRegs = FI.getHasRegParm() ? FI.getRegParm() :
905     DefaultNumRegisterParameters;
906 
907   // If the return value is indirect, then the hidden argument is consuming one
908   // integer register.
909   if (FI.getReturnInfo().isIndirect() && FreeRegs) {
910     --FreeRegs;
911     ABIArgInfo &Old = FI.getReturnInfo();
912     Old = ABIArgInfo::getIndirectInReg(Old.getIndirectAlign(),
913                                        Old.getIndirectByVal(),
914                                        Old.getIndirectRealign());
915   }
916 
917   for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
918        it != ie; ++it)
919     it->info = classifyArgumentTypeWithReg(it->type, FreeRegs);
920 }
921 
922 llvm::Value *X86_32ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
923                                       CodeGenFunction &CGF) const {
924   llvm::Type *BPP = CGF.Int8PtrPtrTy;
925 
926   CGBuilderTy &Builder = CGF.Builder;
927   llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
928                                                        "ap");
929   llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
930 
931   // Compute if the address needs to be aligned
932   unsigned Align = CGF.getContext().getTypeAlignInChars(Ty).getQuantity();
933   Align = getTypeStackAlignInBytes(Ty, Align);
934   Align = std::max(Align, 4U);
935   if (Align > 4) {
936     // addr = (addr + align - 1) & -align;
937     llvm::Value *Offset =
938       llvm::ConstantInt::get(CGF.Int32Ty, Align - 1);
939     Addr = CGF.Builder.CreateGEP(Addr, Offset);
940     llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(Addr,
941                                                     CGF.Int32Ty);
942     llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int32Ty, -Align);
943     Addr = CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask),
944                                       Addr->getType(),
945                                       "ap.cur.aligned");
946   }
947 
948   llvm::Type *PTy =
949     llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
950   llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
951 
952   uint64_t Offset =
953     llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, Align);
954   llvm::Value *NextAddr =
955     Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
956                       "ap.next");
957   Builder.CreateStore(NextAddr, VAListAddrAsBPP);
958 
959   return AddrTyped;
960 }
961 
962 void X86_32TargetCodeGenInfo::SetTargetAttributes(const Decl *D,
963                                                   llvm::GlobalValue *GV,
964                                             CodeGen::CodeGenModule &CGM) const {
965   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
966     if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
967       // Get the LLVM function.
968       llvm::Function *Fn = cast<llvm::Function>(GV);
969 
970       // Now add the 'alignstack' attribute with a value of 16.
971       Fn->addAttribute(~0U,
972                        llvm::Attributes::constructStackAlignmentFromInt(16));
973     }
974   }
975 }
976 
977 bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
978                                                CodeGen::CodeGenFunction &CGF,
979                                                llvm::Value *Address) const {
980   CodeGen::CGBuilderTy &Builder = CGF.Builder;
981 
982   llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
983 
984   // 0-7 are the eight integer registers;  the order is different
985   //   on Darwin (for EH), but the range is the same.
986   // 8 is %eip.
987   AssignToArrayRange(Builder, Address, Four8, 0, 8);
988 
989   if (CGF.CGM.isTargetDarwin()) {
990     // 12-16 are st(0..4).  Not sure why we stop at 4.
991     // These have size 16, which is sizeof(long double) on
992     // platforms with 8-byte alignment for that type.
993     llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
994     AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
995 
996   } else {
997     // 9 is %eflags, which doesn't get a size on Darwin for some
998     // reason.
999     Builder.CreateStore(Four8, Builder.CreateConstInBoundsGEP1_32(Address, 9));
1000 
1001     // 11-16 are st(0..5).  Not sure why we stop at 5.
1002     // These have size 12, which is sizeof(long double) on
1003     // platforms with 4-byte alignment for that type.
1004     llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
1005     AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
1006   }
1007 
1008   return false;
1009 }
1010 
1011 //===----------------------------------------------------------------------===//
1012 // X86-64 ABI Implementation
1013 //===----------------------------------------------------------------------===//
1014 
1015 
1016 namespace {
1017 /// X86_64ABIInfo - The X86_64 ABI information.
1018 class X86_64ABIInfo : public ABIInfo {
1019   enum Class {
1020     Integer = 0,
1021     SSE,
1022     SSEUp,
1023     X87,
1024     X87Up,
1025     ComplexX87,
1026     NoClass,
1027     Memory
1028   };
1029 
1030   /// merge - Implement the X86_64 ABI merging algorithm.
1031   ///
1032   /// Merge an accumulating classification \arg Accum with a field
1033   /// classification \arg Field.
1034   ///
1035   /// \param Accum - The accumulating classification. This should
1036   /// always be either NoClass or the result of a previous merge
1037   /// call. In addition, this should never be Memory (the caller
1038   /// should just return Memory for the aggregate).
1039   static Class merge(Class Accum, Class Field);
1040 
1041   /// postMerge - Implement the X86_64 ABI post merging algorithm.
1042   ///
1043   /// Post merger cleanup, reduces a malformed Hi and Lo pair to
1044   /// final MEMORY or SSE classes when necessary.
1045   ///
1046   /// \param AggregateSize - The size of the current aggregate in
1047   /// the classification process.
1048   ///
1049   /// \param Lo - The classification for the parts of the type
1050   /// residing in the low word of the containing object.
1051   ///
1052   /// \param Hi - The classification for the parts of the type
1053   /// residing in the higher words of the containing object.
1054   ///
1055   void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
1056 
1057   /// classify - Determine the x86_64 register classes in which the
1058   /// given type T should be passed.
1059   ///
1060   /// \param Lo - The classification for the parts of the type
1061   /// residing in the low word of the containing object.
1062   ///
1063   /// \param Hi - The classification for the parts of the type
1064   /// residing in the high word of the containing object.
1065   ///
1066   /// \param OffsetBase - The bit offset of this type in the
1067   /// containing object.  Some parameters are classified different
1068   /// depending on whether they straddle an eightbyte boundary.
1069   ///
1070   /// If a word is unused its result will be NoClass; if a type should
1071   /// be passed in Memory then at least the classification of \arg Lo
1072   /// will be Memory.
1073   ///
1074   /// The \arg Lo class will be NoClass iff the argument is ignored.
1075   ///
1076   /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
1077   /// also be ComplexX87.
1078   void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi) const;
1079 
1080   llvm::Type *GetByteVectorType(QualType Ty) const;
1081   llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
1082                                  unsigned IROffset, QualType SourceTy,
1083                                  unsigned SourceOffset) const;
1084   llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
1085                                      unsigned IROffset, QualType SourceTy,
1086                                      unsigned SourceOffset) const;
1087 
1088   /// getIndirectResult - Give a source type \arg Ty, return a suitable result
1089   /// such that the argument will be returned in memory.
1090   ABIArgInfo getIndirectReturnResult(QualType Ty) const;
1091 
1092   /// getIndirectResult - Give a source type \arg Ty, return a suitable result
1093   /// such that the argument will be passed in memory.
1094   ///
1095   /// \param freeIntRegs - The number of free integer registers remaining
1096   /// available.
1097   ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
1098 
1099   ABIArgInfo classifyReturnType(QualType RetTy) const;
1100 
1101   ABIArgInfo classifyArgumentType(QualType Ty,
1102                                   unsigned freeIntRegs,
1103                                   unsigned &neededInt,
1104                                   unsigned &neededSSE) const;
1105 
1106   bool IsIllegalVectorType(QualType Ty) const;
1107 
1108   /// The 0.98 ABI revision clarified a lot of ambiguities,
1109   /// unfortunately in ways that were not always consistent with
1110   /// certain previous compilers.  In particular, platforms which
1111   /// required strict binary compatibility with older versions of GCC
1112   /// may need to exempt themselves.
1113   bool honorsRevision0_98() const {
1114     return !getContext().getTargetInfo().getTriple().isOSDarwin();
1115   }
1116 
1117   bool HasAVX;
1118   // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
1119   // 64-bit hardware.
1120   bool Has64BitPointers;
1121 
1122 public:
1123   X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, bool hasavx) :
1124       ABIInfo(CGT), HasAVX(hasavx),
1125       Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {
1126   }
1127 
1128   bool isPassedUsingAVXType(QualType type) const {
1129     unsigned neededInt, neededSSE;
1130     // The freeIntRegs argument doesn't matter here.
1131     ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE);
1132     if (info.isDirect()) {
1133       llvm::Type *ty = info.getCoerceToType();
1134       if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
1135         return (vectorTy->getBitWidth() > 128);
1136     }
1137     return false;
1138   }
1139 
1140   virtual void computeInfo(CGFunctionInfo &FI) const;
1141 
1142   virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1143                                  CodeGenFunction &CGF) const;
1144 };
1145 
1146 /// WinX86_64ABIInfo - The Windows X86_64 ABI information.
1147 class WinX86_64ABIInfo : public ABIInfo {
1148 
1149   ABIArgInfo classify(QualType Ty) const;
1150 
1151 public:
1152   WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
1153 
1154   virtual void computeInfo(CGFunctionInfo &FI) const;
1155 
1156   virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1157                                  CodeGenFunction &CGF) const;
1158 };
1159 
1160 class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
1161 public:
1162   X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX)
1163       : TargetCodeGenInfo(new X86_64ABIInfo(CGT, HasAVX)) {}
1164 
1165   const X86_64ABIInfo &getABIInfo() const {
1166     return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
1167   }
1168 
1169   int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const {
1170     return 7;
1171   }
1172 
1173   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
1174                                llvm::Value *Address) const {
1175     llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
1176 
1177     // 0-15 are the 16 integer registers.
1178     // 16 is %rip.
1179     AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
1180     return false;
1181   }
1182 
1183   llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
1184                                   StringRef Constraint,
1185                                   llvm::Type* Ty) const {
1186     return X86AdjustInlineAsmType(CGF, Constraint, Ty);
1187   }
1188 
1189   bool isNoProtoCallVariadic(const CallArgList &args,
1190                              const FunctionNoProtoType *fnType) const {
1191     // The default CC on x86-64 sets %al to the number of SSA
1192     // registers used, and GCC sets this when calling an unprototyped
1193     // function, so we override the default behavior.  However, don't do
1194     // that when AVX types are involved: the ABI explicitly states it is
1195     // undefined, and it doesn't work in practice because of how the ABI
1196     // defines varargs anyway.
1197     if (fnType->getCallConv() == CC_Default || fnType->getCallConv() == CC_C) {
1198       bool HasAVXType = false;
1199       for (CallArgList::const_iterator
1200              it = args.begin(), ie = args.end(); it != ie; ++it) {
1201         if (getABIInfo().isPassedUsingAVXType(it->Ty)) {
1202           HasAVXType = true;
1203           break;
1204         }
1205       }
1206 
1207       if (!HasAVXType)
1208         return true;
1209     }
1210 
1211     return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
1212   }
1213 
1214 };
1215 
1216 class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
1217 public:
1218   WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
1219     : TargetCodeGenInfo(new WinX86_64ABIInfo(CGT)) {}
1220 
1221   int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const {
1222     return 7;
1223   }
1224 
1225   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
1226                                llvm::Value *Address) const {
1227     llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
1228 
1229     // 0-15 are the 16 integer registers.
1230     // 16 is %rip.
1231     AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
1232     return false;
1233   }
1234 };
1235 
1236 }
1237 
1238 void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
1239                               Class &Hi) const {
1240   // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
1241   //
1242   // (a) If one of the classes is Memory, the whole argument is passed in
1243   //     memory.
1244   //
1245   // (b) If X87UP is not preceded by X87, the whole argument is passed in
1246   //     memory.
1247   //
1248   // (c) If the size of the aggregate exceeds two eightbytes and the first
1249   //     eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
1250   //     argument is passed in memory. NOTE: This is necessary to keep the
1251   //     ABI working for processors that don't support the __m256 type.
1252   //
1253   // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
1254   //
1255   // Some of these are enforced by the merging logic.  Others can arise
1256   // only with unions; for example:
1257   //   union { _Complex double; unsigned; }
1258   //
1259   // Note that clauses (b) and (c) were added in 0.98.
1260   //
1261   if (Hi == Memory)
1262     Lo = Memory;
1263   if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
1264     Lo = Memory;
1265   if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
1266     Lo = Memory;
1267   if (Hi == SSEUp && Lo != SSE)
1268     Hi = SSE;
1269 }
1270 
1271 X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
1272   // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
1273   // classified recursively so that always two fields are
1274   // considered. The resulting class is calculated according to
1275   // the classes of the fields in the eightbyte:
1276   //
1277   // (a) If both classes are equal, this is the resulting class.
1278   //
1279   // (b) If one of the classes is NO_CLASS, the resulting class is
1280   // the other class.
1281   //
1282   // (c) If one of the classes is MEMORY, the result is the MEMORY
1283   // class.
1284   //
1285   // (d) If one of the classes is INTEGER, the result is the
1286   // INTEGER.
1287   //
1288   // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
1289   // MEMORY is used as class.
1290   //
1291   // (f) Otherwise class SSE is used.
1292 
1293   // Accum should never be memory (we should have returned) or
1294   // ComplexX87 (because this cannot be passed in a structure).
1295   assert((Accum != Memory && Accum != ComplexX87) &&
1296          "Invalid accumulated classification during merge.");
1297   if (Accum == Field || Field == NoClass)
1298     return Accum;
1299   if (Field == Memory)
1300     return Memory;
1301   if (Accum == NoClass)
1302     return Field;
1303   if (Accum == Integer || Field == Integer)
1304     return Integer;
1305   if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
1306       Accum == X87 || Accum == X87Up)
1307     return Memory;
1308   return SSE;
1309 }
1310 
1311 void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
1312                              Class &Lo, Class &Hi) const {
1313   // FIXME: This code can be simplified by introducing a simple value class for
1314   // Class pairs with appropriate constructor methods for the various
1315   // situations.
1316 
1317   // FIXME: Some of the split computations are wrong; unaligned vectors
1318   // shouldn't be passed in registers for example, so there is no chance they
1319   // can straddle an eightbyte. Verify & simplify.
1320 
1321   Lo = Hi = NoClass;
1322 
1323   Class &Current = OffsetBase < 64 ? Lo : Hi;
1324   Current = Memory;
1325 
1326   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
1327     BuiltinType::Kind k = BT->getKind();
1328 
1329     if (k == BuiltinType::Void) {
1330       Current = NoClass;
1331     } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
1332       Lo = Integer;
1333       Hi = Integer;
1334     } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
1335       Current = Integer;
1336     } else if ((k == BuiltinType::Float || k == BuiltinType::Double) ||
1337                (k == BuiltinType::LongDouble &&
1338                 getContext().getTargetInfo().getTriple().getOS() ==
1339                 llvm::Triple::NativeClient)) {
1340       Current = SSE;
1341     } else if (k == BuiltinType::LongDouble) {
1342       Lo = X87;
1343       Hi = X87Up;
1344     }
1345     // FIXME: _Decimal32 and _Decimal64 are SSE.
1346     // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
1347     return;
1348   }
1349 
1350   if (const EnumType *ET = Ty->getAs<EnumType>()) {
1351     // Classify the underlying integer type.
1352     classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi);
1353     return;
1354   }
1355 
1356   if (Ty->hasPointerRepresentation()) {
1357     Current = Integer;
1358     return;
1359   }
1360 
1361   if (Ty->isMemberPointerType()) {
1362     if (Ty->isMemberFunctionPointerType() && Has64BitPointers)
1363       Lo = Hi = Integer;
1364     else
1365       Current = Integer;
1366     return;
1367   }
1368 
1369   if (const VectorType *VT = Ty->getAs<VectorType>()) {
1370     uint64_t Size = getContext().getTypeSize(VT);
1371     if (Size == 32) {
1372       // gcc passes all <4 x char>, <2 x short>, <1 x int>, <1 x
1373       // float> as integer.
1374       Current = Integer;
1375 
1376       // If this type crosses an eightbyte boundary, it should be
1377       // split.
1378       uint64_t EB_Real = (OffsetBase) / 64;
1379       uint64_t EB_Imag = (OffsetBase + Size - 1) / 64;
1380       if (EB_Real != EB_Imag)
1381         Hi = Lo;
1382     } else if (Size == 64) {
1383       // gcc passes <1 x double> in memory. :(
1384       if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double))
1385         return;
1386 
1387       // gcc passes <1 x long long> as INTEGER.
1388       if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::LongLong) ||
1389           VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULongLong) ||
1390           VT->getElementType()->isSpecificBuiltinType(BuiltinType::Long) ||
1391           VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULong))
1392         Current = Integer;
1393       else
1394         Current = SSE;
1395 
1396       // If this type crosses an eightbyte boundary, it should be
1397       // split.
1398       if (OffsetBase && OffsetBase != 64)
1399         Hi = Lo;
1400     } else if (Size == 128 || (HasAVX && Size == 256)) {
1401       // Arguments of 256-bits are split into four eightbyte chunks. The
1402       // least significant one belongs to class SSE and all the others to class
1403       // SSEUP. The original Lo and Hi design considers that types can't be
1404       // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
1405       // This design isn't correct for 256-bits, but since there're no cases
1406       // where the upper parts would need to be inspected, avoid adding
1407       // complexity and just consider Hi to match the 64-256 part.
1408       Lo = SSE;
1409       Hi = SSEUp;
1410     }
1411     return;
1412   }
1413 
1414   if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
1415     QualType ET = getContext().getCanonicalType(CT->getElementType());
1416 
1417     uint64_t Size = getContext().getTypeSize(Ty);
1418     if (ET->isIntegralOrEnumerationType()) {
1419       if (Size <= 64)
1420         Current = Integer;
1421       else if (Size <= 128)
1422         Lo = Hi = Integer;
1423     } else if (ET == getContext().FloatTy)
1424       Current = SSE;
1425     else if (ET == getContext().DoubleTy ||
1426              (ET == getContext().LongDoubleTy &&
1427               getContext().getTargetInfo().getTriple().getOS() ==
1428               llvm::Triple::NativeClient))
1429       Lo = Hi = SSE;
1430     else if (ET == getContext().LongDoubleTy)
1431       Current = ComplexX87;
1432 
1433     // If this complex type crosses an eightbyte boundary then it
1434     // should be split.
1435     uint64_t EB_Real = (OffsetBase) / 64;
1436     uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
1437     if (Hi == NoClass && EB_Real != EB_Imag)
1438       Hi = Lo;
1439 
1440     return;
1441   }
1442 
1443   if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
1444     // Arrays are treated like structures.
1445 
1446     uint64_t Size = getContext().getTypeSize(Ty);
1447 
1448     // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
1449     // than four eightbytes, ..., it has class MEMORY.
1450     if (Size > 256)
1451       return;
1452 
1453     // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
1454     // fields, it has class MEMORY.
1455     //
1456     // Only need to check alignment of array base.
1457     if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
1458       return;
1459 
1460     // Otherwise implement simplified merge. We could be smarter about
1461     // this, but it isn't worth it and would be harder to verify.
1462     Current = NoClass;
1463     uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
1464     uint64_t ArraySize = AT->getSize().getZExtValue();
1465 
1466     // The only case a 256-bit wide vector could be used is when the array
1467     // contains a single 256-bit element. Since Lo and Hi logic isn't extended
1468     // to work for sizes wider than 128, early check and fallback to memory.
1469     if (Size > 128 && EltSize != 256)
1470       return;
1471 
1472     for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
1473       Class FieldLo, FieldHi;
1474       classify(AT->getElementType(), Offset, FieldLo, FieldHi);
1475       Lo = merge(Lo, FieldLo);
1476       Hi = merge(Hi, FieldHi);
1477       if (Lo == Memory || Hi == Memory)
1478         break;
1479     }
1480 
1481     postMerge(Size, Lo, Hi);
1482     assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
1483     return;
1484   }
1485 
1486   if (const RecordType *RT = Ty->getAs<RecordType>()) {
1487     uint64_t Size = getContext().getTypeSize(Ty);
1488 
1489     // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
1490     // than four eightbytes, ..., it has class MEMORY.
1491     if (Size > 256)
1492       return;
1493 
1494     // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
1495     // copy constructor or a non-trivial destructor, it is passed by invisible
1496     // reference.
1497     if (hasNonTrivialDestructorOrCopyConstructor(RT))
1498       return;
1499 
1500     const RecordDecl *RD = RT->getDecl();
1501 
1502     // Assume variable sized types are passed in memory.
1503     if (RD->hasFlexibleArrayMember())
1504       return;
1505 
1506     const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
1507 
1508     // Reset Lo class, this will be recomputed.
1509     Current = NoClass;
1510 
1511     // If this is a C++ record, classify the bases first.
1512     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
1513       for (CXXRecordDecl::base_class_const_iterator i = CXXRD->bases_begin(),
1514              e = CXXRD->bases_end(); i != e; ++i) {
1515         assert(!i->isVirtual() && !i->getType()->isDependentType() &&
1516                "Unexpected base class!");
1517         const CXXRecordDecl *Base =
1518           cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
1519 
1520         // Classify this field.
1521         //
1522         // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
1523         // single eightbyte, each is classified separately. Each eightbyte gets
1524         // initialized to class NO_CLASS.
1525         Class FieldLo, FieldHi;
1526         uint64_t Offset =
1527           OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
1528         classify(i->getType(), Offset, FieldLo, FieldHi);
1529         Lo = merge(Lo, FieldLo);
1530         Hi = merge(Hi, FieldHi);
1531         if (Lo == Memory || Hi == Memory)
1532           break;
1533       }
1534     }
1535 
1536     // Classify the fields one at a time, merging the results.
1537     unsigned idx = 0;
1538     for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
1539            i != e; ++i, ++idx) {
1540       uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
1541       bool BitField = i->isBitField();
1542 
1543       // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
1544       // four eightbytes, or it contains unaligned fields, it has class MEMORY.
1545       //
1546       // The only case a 256-bit wide vector could be used is when the struct
1547       // contains a single 256-bit element. Since Lo and Hi logic isn't extended
1548       // to work for sizes wider than 128, early check and fallback to memory.
1549       //
1550       if (Size > 128 && getContext().getTypeSize(i->getType()) != 256) {
1551         Lo = Memory;
1552         return;
1553       }
1554       // Note, skip this test for bit-fields, see below.
1555       if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
1556         Lo = Memory;
1557         return;
1558       }
1559 
1560       // Classify this field.
1561       //
1562       // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
1563       // exceeds a single eightbyte, each is classified
1564       // separately. Each eightbyte gets initialized to class
1565       // NO_CLASS.
1566       Class FieldLo, FieldHi;
1567 
1568       // Bit-fields require special handling, they do not force the
1569       // structure to be passed in memory even if unaligned, and
1570       // therefore they can straddle an eightbyte.
1571       if (BitField) {
1572         // Ignore padding bit-fields.
1573         if (i->isUnnamedBitfield())
1574           continue;
1575 
1576         uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
1577         uint64_t Size = i->getBitWidthValue(getContext());
1578 
1579         uint64_t EB_Lo = Offset / 64;
1580         uint64_t EB_Hi = (Offset + Size - 1) / 64;
1581         FieldLo = FieldHi = NoClass;
1582         if (EB_Lo) {
1583           assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
1584           FieldLo = NoClass;
1585           FieldHi = Integer;
1586         } else {
1587           FieldLo = Integer;
1588           FieldHi = EB_Hi ? Integer : NoClass;
1589         }
1590       } else
1591         classify(i->getType(), Offset, FieldLo, FieldHi);
1592       Lo = merge(Lo, FieldLo);
1593       Hi = merge(Hi, FieldHi);
1594       if (Lo == Memory || Hi == Memory)
1595         break;
1596     }
1597 
1598     postMerge(Size, Lo, Hi);
1599   }
1600 }
1601 
1602 ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
1603   // If this is a scalar LLVM value then assume LLVM will pass it in the right
1604   // place naturally.
1605   if (!isAggregateTypeForABI(Ty)) {
1606     // Treat an enum type as its underlying type.
1607     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1608       Ty = EnumTy->getDecl()->getIntegerType();
1609 
1610     return (Ty->isPromotableIntegerType() ?
1611             ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
1612   }
1613 
1614   return ABIArgInfo::getIndirect(0);
1615 }
1616 
1617 bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
1618   if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
1619     uint64_t Size = getContext().getTypeSize(VecTy);
1620     unsigned LargestVector = HasAVX ? 256 : 128;
1621     if (Size <= 64 || Size > LargestVector)
1622       return true;
1623   }
1624 
1625   return false;
1626 }
1627 
1628 ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
1629                                             unsigned freeIntRegs) const {
1630   // If this is a scalar LLVM value then assume LLVM will pass it in the right
1631   // place naturally.
1632   //
1633   // This assumption is optimistic, as there could be free registers available
1634   // when we need to pass this argument in memory, and LLVM could try to pass
1635   // the argument in the free register. This does not seem to happen currently,
1636   // but this code would be much safer if we could mark the argument with
1637   // 'onstack'. See PR12193.
1638   if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty)) {
1639     // Treat an enum type as its underlying type.
1640     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1641       Ty = EnumTy->getDecl()->getIntegerType();
1642 
1643     return (Ty->isPromotableIntegerType() ?
1644             ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
1645   }
1646 
1647   if (isRecordWithNonTrivialDestructorOrCopyConstructor(Ty))
1648     return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
1649 
1650   // Compute the byval alignment. We specify the alignment of the byval in all
1651   // cases so that the mid-level optimizer knows the alignment of the byval.
1652   unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
1653 
1654   // Attempt to avoid passing indirect results using byval when possible. This
1655   // is important for good codegen.
1656   //
1657   // We do this by coercing the value into a scalar type which the backend can
1658   // handle naturally (i.e., without using byval).
1659   //
1660   // For simplicity, we currently only do this when we have exhausted all of the
1661   // free integer registers. Doing this when there are free integer registers
1662   // would require more care, as we would have to ensure that the coerced value
1663   // did not claim the unused register. That would require either reording the
1664   // arguments to the function (so that any subsequent inreg values came first),
1665   // or only doing this optimization when there were no following arguments that
1666   // might be inreg.
1667   //
1668   // We currently expect it to be rare (particularly in well written code) for
1669   // arguments to be passed on the stack when there are still free integer
1670   // registers available (this would typically imply large structs being passed
1671   // by value), so this seems like a fair tradeoff for now.
1672   //
1673   // We can revisit this if the backend grows support for 'onstack' parameter
1674   // attributes. See PR12193.
1675   if (freeIntRegs == 0) {
1676     uint64_t Size = getContext().getTypeSize(Ty);
1677 
1678     // If this type fits in an eightbyte, coerce it into the matching integral
1679     // type, which will end up on the stack (with alignment 8).
1680     if (Align == 8 && Size <= 64)
1681       return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
1682                                                           Size));
1683   }
1684 
1685   return ABIArgInfo::getIndirect(Align);
1686 }
1687 
1688 /// GetByteVectorType - The ABI specifies that a value should be passed in an
1689 /// full vector XMM/YMM register.  Pick an LLVM IR type that will be passed as a
1690 /// vector register.
1691 llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
1692   llvm::Type *IRType = CGT.ConvertType(Ty);
1693 
1694   // Wrapper structs that just contain vectors are passed just like vectors,
1695   // strip them off if present.
1696   llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType);
1697   while (STy && STy->getNumElements() == 1) {
1698     IRType = STy->getElementType(0);
1699     STy = dyn_cast<llvm::StructType>(IRType);
1700   }
1701 
1702   // If the preferred type is a 16-byte vector, prefer to pass it.
1703   if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(IRType)){
1704     llvm::Type *EltTy = VT->getElementType();
1705     unsigned BitWidth = VT->getBitWidth();
1706     if ((BitWidth >= 128 && BitWidth <= 256) &&
1707         (EltTy->isFloatTy() || EltTy->isDoubleTy() ||
1708          EltTy->isIntegerTy(8) || EltTy->isIntegerTy(16) ||
1709          EltTy->isIntegerTy(32) || EltTy->isIntegerTy(64) ||
1710          EltTy->isIntegerTy(128)))
1711       return VT;
1712   }
1713 
1714   return llvm::VectorType::get(llvm::Type::getDoubleTy(getVMContext()), 2);
1715 }
1716 
1717 /// BitsContainNoUserData - Return true if the specified [start,end) bit range
1718 /// is known to either be off the end of the specified type or being in
1719 /// alignment padding.  The user type specified is known to be at most 128 bits
1720 /// in size, and have passed through X86_64ABIInfo::classify with a successful
1721 /// classification that put one of the two halves in the INTEGER class.
1722 ///
1723 /// It is conservatively correct to return false.
1724 static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
1725                                   unsigned EndBit, ASTContext &Context) {
1726   // If the bytes being queried are off the end of the type, there is no user
1727   // data hiding here.  This handles analysis of builtins, vectors and other
1728   // types that don't contain interesting padding.
1729   unsigned TySize = (unsigned)Context.getTypeSize(Ty);
1730   if (TySize <= StartBit)
1731     return true;
1732 
1733   if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
1734     unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
1735     unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
1736 
1737     // Check each element to see if the element overlaps with the queried range.
1738     for (unsigned i = 0; i != NumElts; ++i) {
1739       // If the element is after the span we care about, then we're done..
1740       unsigned EltOffset = i*EltSize;
1741       if (EltOffset >= EndBit) break;
1742 
1743       unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
1744       if (!BitsContainNoUserData(AT->getElementType(), EltStart,
1745                                  EndBit-EltOffset, Context))
1746         return false;
1747     }
1748     // If it overlaps no elements, then it is safe to process as padding.
1749     return true;
1750   }
1751 
1752   if (const RecordType *RT = Ty->getAs<RecordType>()) {
1753     const RecordDecl *RD = RT->getDecl();
1754     const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1755 
1756     // If this is a C++ record, check the bases first.
1757     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
1758       for (CXXRecordDecl::base_class_const_iterator i = CXXRD->bases_begin(),
1759            e = CXXRD->bases_end(); i != e; ++i) {
1760         assert(!i->isVirtual() && !i->getType()->isDependentType() &&
1761                "Unexpected base class!");
1762         const CXXRecordDecl *Base =
1763           cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
1764 
1765         // If the base is after the span we care about, ignore it.
1766         unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
1767         if (BaseOffset >= EndBit) continue;
1768 
1769         unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
1770         if (!BitsContainNoUserData(i->getType(), BaseStart,
1771                                    EndBit-BaseOffset, Context))
1772           return false;
1773       }
1774     }
1775 
1776     // Verify that no field has data that overlaps the region of interest.  Yes
1777     // this could be sped up a lot by being smarter about queried fields,
1778     // however we're only looking at structs up to 16 bytes, so we don't care
1779     // much.
1780     unsigned idx = 0;
1781     for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
1782          i != e; ++i, ++idx) {
1783       unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
1784 
1785       // If we found a field after the region we care about, then we're done.
1786       if (FieldOffset >= EndBit) break;
1787 
1788       unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
1789       if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
1790                                  Context))
1791         return false;
1792     }
1793 
1794     // If nothing in this record overlapped the area of interest, then we're
1795     // clean.
1796     return true;
1797   }
1798 
1799   return false;
1800 }
1801 
1802 /// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a
1803 /// float member at the specified offset.  For example, {int,{float}} has a
1804 /// float at offset 4.  It is conservatively correct for this routine to return
1805 /// false.
1806 static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset,
1807                                   const llvm::DataLayout &TD) {
1808   // Base case if we find a float.
1809   if (IROffset == 0 && IRType->isFloatTy())
1810     return true;
1811 
1812   // If this is a struct, recurse into the field at the specified offset.
1813   if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
1814     const llvm::StructLayout *SL = TD.getStructLayout(STy);
1815     unsigned Elt = SL->getElementContainingOffset(IROffset);
1816     IROffset -= SL->getElementOffset(Elt);
1817     return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD);
1818   }
1819 
1820   // If this is an array, recurse into the field at the specified offset.
1821   if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
1822     llvm::Type *EltTy = ATy->getElementType();
1823     unsigned EltSize = TD.getTypeAllocSize(EltTy);
1824     IROffset -= IROffset/EltSize*EltSize;
1825     return ContainsFloatAtOffset(EltTy, IROffset, TD);
1826   }
1827 
1828   return false;
1829 }
1830 
1831 
1832 /// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
1833 /// low 8 bytes of an XMM register, corresponding to the SSE class.
1834 llvm::Type *X86_64ABIInfo::
1835 GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
1836                    QualType SourceTy, unsigned SourceOffset) const {
1837   // The only three choices we have are either double, <2 x float>, or float. We
1838   // pass as float if the last 4 bytes is just padding.  This happens for
1839   // structs that contain 3 floats.
1840   if (BitsContainNoUserData(SourceTy, SourceOffset*8+32,
1841                             SourceOffset*8+64, getContext()))
1842     return llvm::Type::getFloatTy(getVMContext());
1843 
1844   // We want to pass as <2 x float> if the LLVM IR type contains a float at
1845   // offset+0 and offset+4.  Walk the LLVM IR type to find out if this is the
1846   // case.
1847   if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) &&
1848       ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout()))
1849     return llvm::VectorType::get(llvm::Type::getFloatTy(getVMContext()), 2);
1850 
1851   return llvm::Type::getDoubleTy(getVMContext());
1852 }
1853 
1854 
1855 /// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
1856 /// an 8-byte GPR.  This means that we either have a scalar or we are talking
1857 /// about the high or low part of an up-to-16-byte struct.  This routine picks
1858 /// the best LLVM IR type to represent this, which may be i64 or may be anything
1859 /// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
1860 /// etc).
1861 ///
1862 /// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
1863 /// the source type.  IROffset is an offset in bytes into the LLVM IR type that
1864 /// the 8-byte value references.  PrefType may be null.
1865 ///
1866 /// SourceTy is the source level type for the entire argument.  SourceOffset is
1867 /// an offset into this that we're processing (which is always either 0 or 8).
1868 ///
1869 llvm::Type *X86_64ABIInfo::
1870 GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
1871                        QualType SourceTy, unsigned SourceOffset) const {
1872   // If we're dealing with an un-offset LLVM IR type, then it means that we're
1873   // returning an 8-byte unit starting with it.  See if we can safely use it.
1874   if (IROffset == 0) {
1875     // Pointers and int64's always fill the 8-byte unit.
1876     if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
1877         IRType->isIntegerTy(64))
1878       return IRType;
1879 
1880     // If we have a 1/2/4-byte integer, we can use it only if the rest of the
1881     // goodness in the source type is just tail padding.  This is allowed to
1882     // kick in for struct {double,int} on the int, but not on
1883     // struct{double,int,int} because we wouldn't return the second int.  We
1884     // have to do this analysis on the source type because we can't depend on
1885     // unions being lowered a specific way etc.
1886     if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
1887         IRType->isIntegerTy(32) ||
1888         (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
1889       unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
1890           cast<llvm::IntegerType>(IRType)->getBitWidth();
1891 
1892       if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
1893                                 SourceOffset*8+64, getContext()))
1894         return IRType;
1895     }
1896   }
1897 
1898   if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
1899     // If this is a struct, recurse into the field at the specified offset.
1900     const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
1901     if (IROffset < SL->getSizeInBytes()) {
1902       unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
1903       IROffset -= SL->getElementOffset(FieldIdx);
1904 
1905       return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
1906                                     SourceTy, SourceOffset);
1907     }
1908   }
1909 
1910   if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
1911     llvm::Type *EltTy = ATy->getElementType();
1912     unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
1913     unsigned EltOffset = IROffset/EltSize*EltSize;
1914     return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
1915                                   SourceOffset);
1916   }
1917 
1918   // Okay, we don't have any better idea of what to pass, so we pass this in an
1919   // integer register that isn't too big to fit the rest of the struct.
1920   unsigned TySizeInBytes =
1921     (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
1922 
1923   assert(TySizeInBytes != SourceOffset && "Empty field?");
1924 
1925   // It is always safe to classify this as an integer type up to i64 that
1926   // isn't larger than the structure.
1927   return llvm::IntegerType::get(getVMContext(),
1928                                 std::min(TySizeInBytes-SourceOffset, 8U)*8);
1929 }
1930 
1931 
1932 /// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
1933 /// be used as elements of a two register pair to pass or return, return a
1934 /// first class aggregate to represent them.  For example, if the low part of
1935 /// a by-value argument should be passed as i32* and the high part as float,
1936 /// return {i32*, float}.
1937 static llvm::Type *
1938 GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
1939                            const llvm::DataLayout &TD) {
1940   // In order to correctly satisfy the ABI, we need to the high part to start
1941   // at offset 8.  If the high and low parts we inferred are both 4-byte types
1942   // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
1943   // the second element at offset 8.  Check for this:
1944   unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
1945   unsigned HiAlign = TD.getABITypeAlignment(Hi);
1946   unsigned HiStart = llvm::DataLayout::RoundUpAlignment(LoSize, HiAlign);
1947   assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
1948 
1949   // To handle this, we have to increase the size of the low part so that the
1950   // second element will start at an 8 byte offset.  We can't increase the size
1951   // of the second element because it might make us access off the end of the
1952   // struct.
1953   if (HiStart != 8) {
1954     // There are only two sorts of types the ABI generation code can produce for
1955     // the low part of a pair that aren't 8 bytes in size: float or i8/i16/i32.
1956     // Promote these to a larger type.
1957     if (Lo->isFloatTy())
1958       Lo = llvm::Type::getDoubleTy(Lo->getContext());
1959     else {
1960       assert(Lo->isIntegerTy() && "Invalid/unknown lo type");
1961       Lo = llvm::Type::getInt64Ty(Lo->getContext());
1962     }
1963   }
1964 
1965   llvm::StructType *Result = llvm::StructType::get(Lo, Hi, NULL);
1966 
1967 
1968   // Verify that the second element is at an 8-byte offset.
1969   assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
1970          "Invalid x86-64 argument pair!");
1971   return Result;
1972 }
1973 
1974 ABIArgInfo X86_64ABIInfo::
1975 classifyReturnType(QualType RetTy) const {
1976   // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
1977   // classification algorithm.
1978   X86_64ABIInfo::Class Lo, Hi;
1979   classify(RetTy, 0, Lo, Hi);
1980 
1981   // Check some invariants.
1982   assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
1983   assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
1984 
1985   llvm::Type *ResType = 0;
1986   switch (Lo) {
1987   case NoClass:
1988     if (Hi == NoClass)
1989       return ABIArgInfo::getIgnore();
1990     // If the low part is just padding, it takes no register, leave ResType
1991     // null.
1992     assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
1993            "Unknown missing lo part");
1994     break;
1995 
1996   case SSEUp:
1997   case X87Up:
1998     llvm_unreachable("Invalid classification for lo word.");
1999 
2000     // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
2001     // hidden argument.
2002   case Memory:
2003     return getIndirectReturnResult(RetTy);
2004 
2005     // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
2006     // available register of the sequence %rax, %rdx is used.
2007   case Integer:
2008     ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
2009 
2010     // If we have a sign or zero extended integer, make sure to return Extend
2011     // so that the parameter gets the right LLVM IR attributes.
2012     if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
2013       // Treat an enum type as its underlying type.
2014       if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
2015         RetTy = EnumTy->getDecl()->getIntegerType();
2016 
2017       if (RetTy->isIntegralOrEnumerationType() &&
2018           RetTy->isPromotableIntegerType())
2019         return ABIArgInfo::getExtend();
2020     }
2021     break;
2022 
2023     // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
2024     // available SSE register of the sequence %xmm0, %xmm1 is used.
2025   case SSE:
2026     ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
2027     break;
2028 
2029     // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
2030     // returned on the X87 stack in %st0 as 80-bit x87 number.
2031   case X87:
2032     ResType = llvm::Type::getX86_FP80Ty(getVMContext());
2033     break;
2034 
2035     // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
2036     // part of the value is returned in %st0 and the imaginary part in
2037     // %st1.
2038   case ComplexX87:
2039     assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
2040     ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
2041                                     llvm::Type::getX86_FP80Ty(getVMContext()),
2042                                     NULL);
2043     break;
2044   }
2045 
2046   llvm::Type *HighPart = 0;
2047   switch (Hi) {
2048     // Memory was handled previously and X87 should
2049     // never occur as a hi class.
2050   case Memory:
2051   case X87:
2052     llvm_unreachable("Invalid classification for hi word.");
2053 
2054   case ComplexX87: // Previously handled.
2055   case NoClass:
2056     break;
2057 
2058   case Integer:
2059     HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
2060     if (Lo == NoClass)  // Return HighPart at offset 8 in memory.
2061       return ABIArgInfo::getDirect(HighPart, 8);
2062     break;
2063   case SSE:
2064     HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
2065     if (Lo == NoClass)  // Return HighPart at offset 8 in memory.
2066       return ABIArgInfo::getDirect(HighPart, 8);
2067     break;
2068 
2069     // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
2070     // is passed in the next available eightbyte chunk if the last used
2071     // vector register.
2072     //
2073     // SSEUP should always be preceded by SSE, just widen.
2074   case SSEUp:
2075     assert(Lo == SSE && "Unexpected SSEUp classification.");
2076     ResType = GetByteVectorType(RetTy);
2077     break;
2078 
2079     // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
2080     // returned together with the previous X87 value in %st0.
2081   case X87Up:
2082     // If X87Up is preceded by X87, we don't need to do
2083     // anything. However, in some cases with unions it may not be
2084     // preceded by X87. In such situations we follow gcc and pass the
2085     // extra bits in an SSE reg.
2086     if (Lo != X87) {
2087       HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
2088       if (Lo == NoClass)  // Return HighPart at offset 8 in memory.
2089         return ABIArgInfo::getDirect(HighPart, 8);
2090     }
2091     break;
2092   }
2093 
2094   // If a high part was specified, merge it together with the low part.  It is
2095   // known to pass in the high eightbyte of the result.  We do this by forming a
2096   // first class struct aggregate with the high and low part: {low, high}
2097   if (HighPart)
2098     ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
2099 
2100   return ABIArgInfo::getDirect(ResType);
2101 }
2102 
2103 ABIArgInfo X86_64ABIInfo::classifyArgumentType(
2104   QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE)
2105   const
2106 {
2107   X86_64ABIInfo::Class Lo, Hi;
2108   classify(Ty, 0, Lo, Hi);
2109 
2110   // Check some invariants.
2111   // FIXME: Enforce these by construction.
2112   assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
2113   assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
2114 
2115   neededInt = 0;
2116   neededSSE = 0;
2117   llvm::Type *ResType = 0;
2118   switch (Lo) {
2119   case NoClass:
2120     if (Hi == NoClass)
2121       return ABIArgInfo::getIgnore();
2122     // If the low part is just padding, it takes no register, leave ResType
2123     // null.
2124     assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
2125            "Unknown missing lo part");
2126     break;
2127 
2128     // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
2129     // on the stack.
2130   case Memory:
2131 
2132     // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
2133     // COMPLEX_X87, it is passed in memory.
2134   case X87:
2135   case ComplexX87:
2136     if (isRecordWithNonTrivialDestructorOrCopyConstructor(Ty))
2137       ++neededInt;
2138     return getIndirectResult(Ty, freeIntRegs);
2139 
2140   case SSEUp:
2141   case X87Up:
2142     llvm_unreachable("Invalid classification for lo word.");
2143 
2144     // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
2145     // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
2146     // and %r9 is used.
2147   case Integer:
2148     ++neededInt;
2149 
2150     // Pick an 8-byte type based on the preferred type.
2151     ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
2152 
2153     // If we have a sign or zero extended integer, make sure to return Extend
2154     // so that the parameter gets the right LLVM IR attributes.
2155     if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
2156       // Treat an enum type as its underlying type.
2157       if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2158         Ty = EnumTy->getDecl()->getIntegerType();
2159 
2160       if (Ty->isIntegralOrEnumerationType() &&
2161           Ty->isPromotableIntegerType())
2162         return ABIArgInfo::getExtend();
2163     }
2164 
2165     break;
2166 
2167     // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
2168     // available SSE register is used, the registers are taken in the
2169     // order from %xmm0 to %xmm7.
2170   case SSE: {
2171     llvm::Type *IRType = CGT.ConvertType(Ty);
2172     ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
2173     ++neededSSE;
2174     break;
2175   }
2176   }
2177 
2178   llvm::Type *HighPart = 0;
2179   switch (Hi) {
2180     // Memory was handled previously, ComplexX87 and X87 should
2181     // never occur as hi classes, and X87Up must be preceded by X87,
2182     // which is passed in memory.
2183   case Memory:
2184   case X87:
2185   case ComplexX87:
2186     llvm_unreachable("Invalid classification for hi word.");
2187 
2188   case NoClass: break;
2189 
2190   case Integer:
2191     ++neededInt;
2192     // Pick an 8-byte type based on the preferred type.
2193     HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
2194 
2195     if (Lo == NoClass)  // Pass HighPart at offset 8 in memory.
2196       return ABIArgInfo::getDirect(HighPart, 8);
2197     break;
2198 
2199     // X87Up generally doesn't occur here (long double is passed in
2200     // memory), except in situations involving unions.
2201   case X87Up:
2202   case SSE:
2203     HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
2204 
2205     if (Lo == NoClass)  // Pass HighPart at offset 8 in memory.
2206       return ABIArgInfo::getDirect(HighPart, 8);
2207 
2208     ++neededSSE;
2209     break;
2210 
2211     // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
2212     // eightbyte is passed in the upper half of the last used SSE
2213     // register.  This only happens when 128-bit vectors are passed.
2214   case SSEUp:
2215     assert(Lo == SSE && "Unexpected SSEUp classification");
2216     ResType = GetByteVectorType(Ty);
2217     break;
2218   }
2219 
2220   // If a high part was specified, merge it together with the low part.  It is
2221   // known to pass in the high eightbyte of the result.  We do this by forming a
2222   // first class struct aggregate with the high and low part: {low, high}
2223   if (HighPart)
2224     ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
2225 
2226   return ABIArgInfo::getDirect(ResType);
2227 }
2228 
2229 void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
2230 
2231   FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
2232 
2233   // Keep track of the number of assigned registers.
2234   unsigned freeIntRegs = 6, freeSSERegs = 8;
2235 
2236   // If the return value is indirect, then the hidden argument is consuming one
2237   // integer register.
2238   if (FI.getReturnInfo().isIndirect())
2239     --freeIntRegs;
2240 
2241   // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
2242   // get assigned (in left-to-right order) for passing as follows...
2243   for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
2244        it != ie; ++it) {
2245     unsigned neededInt, neededSSE;
2246     it->info = classifyArgumentType(it->type, freeIntRegs, neededInt,
2247                                     neededSSE);
2248 
2249     // AMD64-ABI 3.2.3p3: If there are no registers available for any
2250     // eightbyte of an argument, the whole argument is passed on the
2251     // stack. If registers have already been assigned for some
2252     // eightbytes of such an argument, the assignments get reverted.
2253     if (freeIntRegs >= neededInt && freeSSERegs >= neededSSE) {
2254       freeIntRegs -= neededInt;
2255       freeSSERegs -= neededSSE;
2256     } else {
2257       it->info = getIndirectResult(it->type, freeIntRegs);
2258     }
2259   }
2260 }
2261 
2262 static llvm::Value *EmitVAArgFromMemory(llvm::Value *VAListAddr,
2263                                         QualType Ty,
2264                                         CodeGenFunction &CGF) {
2265   llvm::Value *overflow_arg_area_p =
2266     CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_p");
2267   llvm::Value *overflow_arg_area =
2268     CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
2269 
2270   // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
2271   // byte boundary if alignment needed by type exceeds 8 byte boundary.
2272   // It isn't stated explicitly in the standard, but in practice we use
2273   // alignment greater than 16 where necessary.
2274   uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8;
2275   if (Align > 8) {
2276     // overflow_arg_area = (overflow_arg_area + align - 1) & -align;
2277     llvm::Value *Offset =
2278       llvm::ConstantInt::get(CGF.Int64Ty, Align - 1);
2279     overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset);
2280     llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(overflow_arg_area,
2281                                                     CGF.Int64Ty);
2282     llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int64Ty, -(uint64_t)Align);
2283     overflow_arg_area =
2284       CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask),
2285                                  overflow_arg_area->getType(),
2286                                  "overflow_arg_area.align");
2287   }
2288 
2289   // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
2290   llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
2291   llvm::Value *Res =
2292     CGF.Builder.CreateBitCast(overflow_arg_area,
2293                               llvm::PointerType::getUnqual(LTy));
2294 
2295   // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
2296   // l->overflow_arg_area + sizeof(type).
2297   // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
2298   // an 8 byte boundary.
2299 
2300   uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
2301   llvm::Value *Offset =
2302       llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7)  & ~7);
2303   overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
2304                                             "overflow_arg_area.next");
2305   CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
2306 
2307   // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
2308   return Res;
2309 }
2310 
2311 llvm::Value *X86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2312                                       CodeGenFunction &CGF) const {
2313   // Assume that va_list type is correct; should be pointer to LLVM type:
2314   // struct {
2315   //   i32 gp_offset;
2316   //   i32 fp_offset;
2317   //   i8* overflow_arg_area;
2318   //   i8* reg_save_area;
2319   // };
2320   unsigned neededInt, neededSSE;
2321 
2322   Ty = CGF.getContext().getCanonicalType(Ty);
2323   ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE);
2324 
2325   // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
2326   // in the registers. If not go to step 7.
2327   if (!neededInt && !neededSSE)
2328     return EmitVAArgFromMemory(VAListAddr, Ty, CGF);
2329 
2330   // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
2331   // general purpose registers needed to pass type and num_fp to hold
2332   // the number of floating point registers needed.
2333 
2334   // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
2335   // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
2336   // l->fp_offset > 304 - num_fp * 16 go to step 7.
2337   //
2338   // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
2339   // register save space).
2340 
2341   llvm::Value *InRegs = 0;
2342   llvm::Value *gp_offset_p = 0, *gp_offset = 0;
2343   llvm::Value *fp_offset_p = 0, *fp_offset = 0;
2344   if (neededInt) {
2345     gp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "gp_offset_p");
2346     gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
2347     InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
2348     InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
2349   }
2350 
2351   if (neededSSE) {
2352     fp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 1, "fp_offset_p");
2353     fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
2354     llvm::Value *FitsInFP =
2355       llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
2356     FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
2357     InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
2358   }
2359 
2360   llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
2361   llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
2362   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
2363   CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
2364 
2365   // Emit code to load the value if it was passed in registers.
2366 
2367   CGF.EmitBlock(InRegBlock);
2368 
2369   // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
2370   // an offset of l->gp_offset and/or l->fp_offset. This may require
2371   // copying to a temporary location in case the parameter is passed
2372   // in different register classes or requires an alignment greater
2373   // than 8 for general purpose registers and 16 for XMM registers.
2374   //
2375   // FIXME: This really results in shameful code when we end up needing to
2376   // collect arguments from different places; often what should result in a
2377   // simple assembling of a structure from scattered addresses has many more
2378   // loads than necessary. Can we clean this up?
2379   llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
2380   llvm::Value *RegAddr =
2381     CGF.Builder.CreateLoad(CGF.Builder.CreateStructGEP(VAListAddr, 3),
2382                            "reg_save_area");
2383   if (neededInt && neededSSE) {
2384     // FIXME: Cleanup.
2385     assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
2386     llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
2387     llvm::Value *Tmp = CGF.CreateTempAlloca(ST);
2388     assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
2389     llvm::Type *TyLo = ST->getElementType(0);
2390     llvm::Type *TyHi = ST->getElementType(1);
2391     assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
2392            "Unexpected ABI info for mixed regs");
2393     llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
2394     llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
2395     llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
2396     llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
2397     llvm::Value *RegLoAddr = TyLo->isFloatingPointTy() ? FPAddr : GPAddr;
2398     llvm::Value *RegHiAddr = TyLo->isFloatingPointTy() ? GPAddr : FPAddr;
2399     llvm::Value *V =
2400       CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegLoAddr, PTyLo));
2401     CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
2402     V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegHiAddr, PTyHi));
2403     CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
2404 
2405     RegAddr = CGF.Builder.CreateBitCast(Tmp,
2406                                         llvm::PointerType::getUnqual(LTy));
2407   } else if (neededInt) {
2408     RegAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
2409     RegAddr = CGF.Builder.CreateBitCast(RegAddr,
2410                                         llvm::PointerType::getUnqual(LTy));
2411   } else if (neededSSE == 1) {
2412     RegAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
2413     RegAddr = CGF.Builder.CreateBitCast(RegAddr,
2414                                         llvm::PointerType::getUnqual(LTy));
2415   } else {
2416     assert(neededSSE == 2 && "Invalid number of needed registers!");
2417     // SSE registers are spaced 16 bytes apart in the register save
2418     // area, we need to collect the two eightbytes together.
2419     llvm::Value *RegAddrLo = CGF.Builder.CreateGEP(RegAddr, fp_offset);
2420     llvm::Value *RegAddrHi = CGF.Builder.CreateConstGEP1_32(RegAddrLo, 16);
2421     llvm::Type *DoubleTy = CGF.DoubleTy;
2422     llvm::Type *DblPtrTy =
2423       llvm::PointerType::getUnqual(DoubleTy);
2424     llvm::StructType *ST = llvm::StructType::get(DoubleTy,
2425                                                        DoubleTy, NULL);
2426     llvm::Value *V, *Tmp = CGF.CreateTempAlloca(ST);
2427     V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrLo,
2428                                                          DblPtrTy));
2429     CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
2430     V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrHi,
2431                                                          DblPtrTy));
2432     CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
2433     RegAddr = CGF.Builder.CreateBitCast(Tmp,
2434                                         llvm::PointerType::getUnqual(LTy));
2435   }
2436 
2437   // AMD64-ABI 3.5.7p5: Step 5. Set:
2438   // l->gp_offset = l->gp_offset + num_gp * 8
2439   // l->fp_offset = l->fp_offset + num_fp * 16.
2440   if (neededInt) {
2441     llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
2442     CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
2443                             gp_offset_p);
2444   }
2445   if (neededSSE) {
2446     llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
2447     CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
2448                             fp_offset_p);
2449   }
2450   CGF.EmitBranch(ContBlock);
2451 
2452   // Emit code to load the value if it was passed in memory.
2453 
2454   CGF.EmitBlock(InMemBlock);
2455   llvm::Value *MemAddr = EmitVAArgFromMemory(VAListAddr, Ty, CGF);
2456 
2457   // Return the appropriate result.
2458 
2459   CGF.EmitBlock(ContBlock);
2460   llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(RegAddr->getType(), 2,
2461                                                  "vaarg.addr");
2462   ResAddr->addIncoming(RegAddr, InRegBlock);
2463   ResAddr->addIncoming(MemAddr, InMemBlock);
2464   return ResAddr;
2465 }
2466 
2467 ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty) const {
2468 
2469   if (Ty->isVoidType())
2470     return ABIArgInfo::getIgnore();
2471 
2472   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2473     Ty = EnumTy->getDecl()->getIntegerType();
2474 
2475   uint64_t Size = getContext().getTypeSize(Ty);
2476 
2477   if (const RecordType *RT = Ty->getAs<RecordType>()) {
2478     if (hasNonTrivialDestructorOrCopyConstructor(RT) ||
2479         RT->getDecl()->hasFlexibleArrayMember())
2480       return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
2481 
2482     // FIXME: mingw-w64-gcc emits 128-bit struct as i128
2483     if (Size == 128 &&
2484         getContext().getTargetInfo().getTriple().getOS()
2485           == llvm::Triple::MinGW32)
2486       return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2487                                                           Size));
2488 
2489     // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
2490     // not 1, 2, 4, or 8 bytes, must be passed by reference."
2491     if (Size <= 64 &&
2492         (Size & (Size - 1)) == 0)
2493       return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2494                                                           Size));
2495 
2496     return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
2497   }
2498 
2499   if (Ty->isPromotableIntegerType())
2500     return ABIArgInfo::getExtend();
2501 
2502   return ABIArgInfo::getDirect();
2503 }
2504 
2505 void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
2506 
2507   QualType RetTy = FI.getReturnType();
2508   FI.getReturnInfo() = classify(RetTy);
2509 
2510   for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
2511        it != ie; ++it)
2512     it->info = classify(it->type);
2513 }
2514 
2515 llvm::Value *WinX86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2516                                       CodeGenFunction &CGF) const {
2517   llvm::Type *BPP = CGF.Int8PtrPtrTy;
2518 
2519   CGBuilderTy &Builder = CGF.Builder;
2520   llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
2521                                                        "ap");
2522   llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
2523   llvm::Type *PTy =
2524     llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
2525   llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
2526 
2527   uint64_t Offset =
2528     llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 8);
2529   llvm::Value *NextAddr =
2530     Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
2531                       "ap.next");
2532   Builder.CreateStore(NextAddr, VAListAddrAsBPP);
2533 
2534   return AddrTyped;
2535 }
2536 
2537 // PowerPC-32
2538 
2539 namespace {
2540 class PPC32TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
2541 public:
2542   PPC32TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
2543 
2544   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const {
2545     // This is recovered from gcc output.
2546     return 1; // r1 is the dedicated stack pointer
2547   }
2548 
2549   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2550                                llvm::Value *Address) const;
2551 };
2552 
2553 }
2554 
2555 bool
2556 PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2557                                                 llvm::Value *Address) const {
2558   // This is calculated from the LLVM and GCC tables and verified
2559   // against gcc output.  AFAIK all ABIs use the same encoding.
2560 
2561   CodeGen::CGBuilderTy &Builder = CGF.Builder;
2562 
2563   llvm::IntegerType *i8 = CGF.Int8Ty;
2564   llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
2565   llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
2566   llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
2567 
2568   // 0-31: r0-31, the 4-byte general-purpose registers
2569   AssignToArrayRange(Builder, Address, Four8, 0, 31);
2570 
2571   // 32-63: fp0-31, the 8-byte floating-point registers
2572   AssignToArrayRange(Builder, Address, Eight8, 32, 63);
2573 
2574   // 64-76 are various 4-byte special-purpose registers:
2575   // 64: mq
2576   // 65: lr
2577   // 66: ctr
2578   // 67: ap
2579   // 68-75 cr0-7
2580   // 76: xer
2581   AssignToArrayRange(Builder, Address, Four8, 64, 76);
2582 
2583   // 77-108: v0-31, the 16-byte vector registers
2584   AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
2585 
2586   // 109: vrsave
2587   // 110: vscr
2588   // 111: spe_acc
2589   // 112: spefscr
2590   // 113: sfp
2591   AssignToArrayRange(Builder, Address, Four8, 109, 113);
2592 
2593   return false;
2594 }
2595 
2596 // PowerPC-64
2597 
2598 namespace {
2599 /// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
2600 class PPC64_SVR4_ABIInfo : public DefaultABIInfo {
2601 
2602 public:
2603   PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
2604 
2605   // TODO: We can add more logic to computeInfo to improve performance.
2606   // Example: For aggregate arguments that fit in a register, we could
2607   // use getDirectInReg (as is done below for structs containing a single
2608   // floating-point value) to avoid pushing them to memory on function
2609   // entry.  This would require changing the logic in PPCISelLowering
2610   // when lowering the parameters in the caller and args in the callee.
2611   virtual void computeInfo(CGFunctionInfo &FI) const {
2612     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
2613     for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
2614          it != ie; ++it) {
2615       // We rely on the default argument classification for the most part.
2616       // One exception:  An aggregate containing a single floating-point
2617       // item must be passed in a register if one is available.
2618       const Type *T = isSingleElementStruct(it->type, getContext());
2619       if (T) {
2620         const BuiltinType *BT = T->getAs<BuiltinType>();
2621         if (BT && BT->isFloatingPoint()) {
2622           QualType QT(T, 0);
2623           it->info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
2624           continue;
2625         }
2626       }
2627       it->info = classifyArgumentType(it->type);
2628     }
2629   }
2630 
2631   virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr,
2632                                  QualType Ty,
2633                                  CodeGenFunction &CGF) const;
2634 };
2635 
2636 class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
2637 public:
2638   PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT)
2639     : TargetCodeGenInfo(new PPC64_SVR4_ABIInfo(CGT)) {}
2640 
2641   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const {
2642     // This is recovered from gcc output.
2643     return 1; // r1 is the dedicated stack pointer
2644   }
2645 
2646   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2647                                llvm::Value *Address) const;
2648 };
2649 
2650 class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
2651 public:
2652   PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
2653 
2654   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const {
2655     // This is recovered from gcc output.
2656     return 1; // r1 is the dedicated stack pointer
2657   }
2658 
2659   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2660                                llvm::Value *Address) const;
2661 };
2662 
2663 }
2664 
2665 // Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
2666 llvm::Value *PPC64_SVR4_ABIInfo::EmitVAArg(llvm::Value *VAListAddr,
2667                                            QualType Ty,
2668                                            CodeGenFunction &CGF) const {
2669   llvm::Type *BP = CGF.Int8PtrTy;
2670   llvm::Type *BPP = CGF.Int8PtrPtrTy;
2671 
2672   CGBuilderTy &Builder = CGF.Builder;
2673   llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
2674   llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
2675 
2676   // Handle address alignment for type alignment > 64 bits.  Although
2677   // long double normally requires 16-byte alignment, this is not the
2678   // case when it is passed as an argument; so handle that special case.
2679   const BuiltinType *BT = Ty->getAs<BuiltinType>();
2680   unsigned TyAlign = CGF.getContext().getTypeAlign(Ty) / 8;
2681 
2682   if (TyAlign > 8 && (!BT || !BT->isFloatingPoint())) {
2683     assert((TyAlign & (TyAlign - 1)) == 0 &&
2684            "Alignment is not power of 2!");
2685     llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
2686     AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt64(TyAlign - 1));
2687     AddrAsInt = Builder.CreateAnd(AddrAsInt, Builder.getInt64(~(TyAlign - 1)));
2688     Addr = Builder.CreateIntToPtr(AddrAsInt, BP);
2689   }
2690 
2691   // Update the va_list pointer.
2692   unsigned SizeInBytes = CGF.getContext().getTypeSize(Ty) / 8;
2693   unsigned Offset = llvm::RoundUpToAlignment(SizeInBytes, 8);
2694   llvm::Value *NextAddr =
2695     Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int64Ty, Offset),
2696                       "ap.next");
2697   Builder.CreateStore(NextAddr, VAListAddrAsBPP);
2698 
2699   // If the argument is smaller than 8 bytes, it is right-adjusted in
2700   // its doubleword slot.  Adjust the pointer to pick it up from the
2701   // correct offset.
2702   if (SizeInBytes < 8) {
2703     llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
2704     AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt64(8 - SizeInBytes));
2705     Addr = Builder.CreateIntToPtr(AddrAsInt, BP);
2706   }
2707 
2708   llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
2709   return Builder.CreateBitCast(Addr, PTy);
2710 }
2711 
2712 static bool
2713 PPC64_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2714                               llvm::Value *Address) {
2715   // This is calculated from the LLVM and GCC tables and verified
2716   // against gcc output.  AFAIK all ABIs use the same encoding.
2717 
2718   CodeGen::CGBuilderTy &Builder = CGF.Builder;
2719 
2720   llvm::IntegerType *i8 = CGF.Int8Ty;
2721   llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
2722   llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
2723   llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
2724 
2725   // 0-31: r0-31, the 8-byte general-purpose registers
2726   AssignToArrayRange(Builder, Address, Eight8, 0, 31);
2727 
2728   // 32-63: fp0-31, the 8-byte floating-point registers
2729   AssignToArrayRange(Builder, Address, Eight8, 32, 63);
2730 
2731   // 64-76 are various 4-byte special-purpose registers:
2732   // 64: mq
2733   // 65: lr
2734   // 66: ctr
2735   // 67: ap
2736   // 68-75 cr0-7
2737   // 76: xer
2738   AssignToArrayRange(Builder, Address, Four8, 64, 76);
2739 
2740   // 77-108: v0-31, the 16-byte vector registers
2741   AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
2742 
2743   // 109: vrsave
2744   // 110: vscr
2745   // 111: spe_acc
2746   // 112: spefscr
2747   // 113: sfp
2748   AssignToArrayRange(Builder, Address, Four8, 109, 113);
2749 
2750   return false;
2751 }
2752 
2753 bool
2754 PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
2755   CodeGen::CodeGenFunction &CGF,
2756   llvm::Value *Address) const {
2757 
2758   return PPC64_initDwarfEHRegSizeTable(CGF, Address);
2759 }
2760 
2761 bool
2762 PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2763                                                 llvm::Value *Address) const {
2764 
2765   return PPC64_initDwarfEHRegSizeTable(CGF, Address);
2766 }
2767 
2768 //===----------------------------------------------------------------------===//
2769 // ARM ABI Implementation
2770 //===----------------------------------------------------------------------===//
2771 
2772 namespace {
2773 
2774 class ARMABIInfo : public ABIInfo {
2775 public:
2776   enum ABIKind {
2777     APCS = 0,
2778     AAPCS = 1,
2779     AAPCS_VFP
2780   };
2781 
2782 private:
2783   ABIKind Kind;
2784 
2785 public:
2786   ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind) : ABIInfo(CGT), Kind(_Kind) {}
2787 
2788   bool isEABI() const {
2789     StringRef Env =
2790       getContext().getTargetInfo().getTriple().getEnvironmentName();
2791     return (Env == "gnueabi" || Env == "eabi" ||
2792             Env == "android" || Env == "androideabi");
2793   }
2794 
2795 private:
2796   ABIKind getABIKind() const { return Kind; }
2797 
2798   ABIArgInfo classifyReturnType(QualType RetTy) const;
2799   ABIArgInfo classifyArgumentType(QualType RetTy) const;
2800 
2801   virtual void computeInfo(CGFunctionInfo &FI) const;
2802 
2803   virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2804                                  CodeGenFunction &CGF) const;
2805 };
2806 
2807 class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
2808 public:
2809   ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
2810     :TargetCodeGenInfo(new ARMABIInfo(CGT, K)) {}
2811 
2812   const ARMABIInfo &getABIInfo() const {
2813     return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
2814   }
2815 
2816   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const {
2817     return 13;
2818   }
2819 
2820   StringRef getARCRetainAutoreleasedReturnValueMarker() const {
2821     return "mov\tr7, r7\t\t@ marker for objc_retainAutoreleaseReturnValue";
2822   }
2823 
2824   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2825                                llvm::Value *Address) const {
2826     llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
2827 
2828     // 0-15 are the 16 integer registers.
2829     AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
2830     return false;
2831   }
2832 
2833   unsigned getSizeOfUnwindException() const {
2834     if (getABIInfo().isEABI()) return 88;
2835     return TargetCodeGenInfo::getSizeOfUnwindException();
2836   }
2837 };
2838 
2839 }
2840 
2841 void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
2842   FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
2843   for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
2844        it != ie; ++it)
2845     it->info = classifyArgumentType(it->type);
2846 
2847   // Always honor user-specified calling convention.
2848   if (FI.getCallingConvention() != llvm::CallingConv::C)
2849     return;
2850 
2851   // Calling convention as default by an ABI.
2852   llvm::CallingConv::ID DefaultCC;
2853   if (isEABI())
2854     DefaultCC = llvm::CallingConv::ARM_AAPCS;
2855   else
2856     DefaultCC = llvm::CallingConv::ARM_APCS;
2857 
2858   // If user did not ask for specific calling convention explicitly (e.g. via
2859   // pcs attribute), set effective calling convention if it's different than ABI
2860   // default.
2861   switch (getABIKind()) {
2862   case APCS:
2863     if (DefaultCC != llvm::CallingConv::ARM_APCS)
2864       FI.setEffectiveCallingConvention(llvm::CallingConv::ARM_APCS);
2865     break;
2866   case AAPCS:
2867     if (DefaultCC != llvm::CallingConv::ARM_AAPCS)
2868       FI.setEffectiveCallingConvention(llvm::CallingConv::ARM_AAPCS);
2869     break;
2870   case AAPCS_VFP:
2871     if (DefaultCC != llvm::CallingConv::ARM_AAPCS_VFP)
2872       FI.setEffectiveCallingConvention(llvm::CallingConv::ARM_AAPCS_VFP);
2873     break;
2874   }
2875 }
2876 
2877 /// isHomogeneousAggregate - Return true if a type is an AAPCS-VFP homogeneous
2878 /// aggregate.  If HAMembers is non-null, the number of base elements
2879 /// contained in the type is returned through it; this is used for the
2880 /// recursive calls that check aggregate component types.
2881 static bool isHomogeneousAggregate(QualType Ty, const Type *&Base,
2882                                    ASTContext &Context,
2883                                    uint64_t *HAMembers = 0) {
2884   uint64_t Members = 0;
2885   if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
2886     if (!isHomogeneousAggregate(AT->getElementType(), Base, Context, &Members))
2887       return false;
2888     Members *= AT->getSize().getZExtValue();
2889   } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
2890     const RecordDecl *RD = RT->getDecl();
2891     if (RD->hasFlexibleArrayMember())
2892       return false;
2893 
2894     Members = 0;
2895     for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
2896          i != e; ++i) {
2897       const FieldDecl *FD = *i;
2898       uint64_t FldMembers;
2899       if (!isHomogeneousAggregate(FD->getType(), Base, Context, &FldMembers))
2900         return false;
2901 
2902       Members = (RD->isUnion() ?
2903                  std::max(Members, FldMembers) : Members + FldMembers);
2904     }
2905   } else {
2906     Members = 1;
2907     if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
2908       Members = 2;
2909       Ty = CT->getElementType();
2910     }
2911 
2912     // Homogeneous aggregates for AAPCS-VFP must have base types of float,
2913     // double, or 64-bit or 128-bit vectors.
2914     if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
2915       if (BT->getKind() != BuiltinType::Float &&
2916           BT->getKind() != BuiltinType::Double &&
2917           BT->getKind() != BuiltinType::LongDouble)
2918         return false;
2919     } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
2920       unsigned VecSize = Context.getTypeSize(VT);
2921       if (VecSize != 64 && VecSize != 128)
2922         return false;
2923     } else {
2924       return false;
2925     }
2926 
2927     // The base type must be the same for all members.  Vector types of the
2928     // same total size are treated as being equivalent here.
2929     const Type *TyPtr = Ty.getTypePtr();
2930     if (!Base)
2931       Base = TyPtr;
2932     if (Base != TyPtr &&
2933         (!Base->isVectorType() || !TyPtr->isVectorType() ||
2934          Context.getTypeSize(Base) != Context.getTypeSize(TyPtr)))
2935       return false;
2936   }
2937 
2938   // Homogeneous Aggregates can have at most 4 members of the base type.
2939   if (HAMembers)
2940     *HAMembers = Members;
2941 
2942   return (Members > 0 && Members <= 4);
2943 }
2944 
2945 ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty) const {
2946   if (!isAggregateTypeForABI(Ty)) {
2947     // Treat an enum type as its underlying type.
2948     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2949       Ty = EnumTy->getDecl()->getIntegerType();
2950 
2951     return (Ty->isPromotableIntegerType() ?
2952             ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
2953   }
2954 
2955   // Ignore empty records.
2956   if (isEmptyRecord(getContext(), Ty, true))
2957     return ABIArgInfo::getIgnore();
2958 
2959   // Structures with either a non-trivial destructor or a non-trivial
2960   // copy constructor are always indirect.
2961   if (isRecordWithNonTrivialDestructorOrCopyConstructor(Ty))
2962     return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
2963 
2964   if (getABIKind() == ARMABIInfo::AAPCS_VFP) {
2965     // Homogeneous Aggregates need to be expanded.
2966     const Type *Base = 0;
2967     if (isHomogeneousAggregate(Ty, Base, getContext())) {
2968       assert(Base && "Base class should be set for homogeneous aggregate");
2969       return ABIArgInfo::getExpand();
2970     }
2971   }
2972 
2973   // Support byval for ARM.
2974   if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64) ||
2975       getContext().getTypeAlign(Ty) > 64) {
2976     return ABIArgInfo::getIndirect(0, /*ByVal=*/true);
2977   }
2978 
2979   // Otherwise, pass by coercing to a structure of the appropriate size.
2980   llvm::Type* ElemTy;
2981   unsigned SizeRegs;
2982   // FIXME: Try to match the types of the arguments more accurately where
2983   // we can.
2984   if (getContext().getTypeAlign(Ty) <= 32) {
2985     ElemTy = llvm::Type::getInt32Ty(getVMContext());
2986     SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
2987   } else {
2988     ElemTy = llvm::Type::getInt64Ty(getVMContext());
2989     SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
2990   }
2991 
2992   llvm::Type *STy =
2993     llvm::StructType::get(llvm::ArrayType::get(ElemTy, SizeRegs), NULL);
2994   return ABIArgInfo::getDirect(STy);
2995 }
2996 
2997 static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
2998                               llvm::LLVMContext &VMContext) {
2999   // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
3000   // is called integer-like if its size is less than or equal to one word, and
3001   // the offset of each of its addressable sub-fields is zero.
3002 
3003   uint64_t Size = Context.getTypeSize(Ty);
3004 
3005   // Check that the type fits in a word.
3006   if (Size > 32)
3007     return false;
3008 
3009   // FIXME: Handle vector types!
3010   if (Ty->isVectorType())
3011     return false;
3012 
3013   // Float types are never treated as "integer like".
3014   if (Ty->isRealFloatingType())
3015     return false;
3016 
3017   // If this is a builtin or pointer type then it is ok.
3018   if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
3019     return true;
3020 
3021   // Small complex integer types are "integer like".
3022   if (const ComplexType *CT = Ty->getAs<ComplexType>())
3023     return isIntegerLikeType(CT->getElementType(), Context, VMContext);
3024 
3025   // Single element and zero sized arrays should be allowed, by the definition
3026   // above, but they are not.
3027 
3028   // Otherwise, it must be a record type.
3029   const RecordType *RT = Ty->getAs<RecordType>();
3030   if (!RT) return false;
3031 
3032   // Ignore records with flexible arrays.
3033   const RecordDecl *RD = RT->getDecl();
3034   if (RD->hasFlexibleArrayMember())
3035     return false;
3036 
3037   // Check that all sub-fields are at offset 0, and are themselves "integer
3038   // like".
3039   const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
3040 
3041   bool HadField = false;
3042   unsigned idx = 0;
3043   for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
3044        i != e; ++i, ++idx) {
3045     const FieldDecl *FD = *i;
3046 
3047     // Bit-fields are not addressable, we only need to verify they are "integer
3048     // like". We still have to disallow a subsequent non-bitfield, for example:
3049     //   struct { int : 0; int x }
3050     // is non-integer like according to gcc.
3051     if (FD->isBitField()) {
3052       if (!RD->isUnion())
3053         HadField = true;
3054 
3055       if (!isIntegerLikeType(FD->getType(), Context, VMContext))
3056         return false;
3057 
3058       continue;
3059     }
3060 
3061     // Check if this field is at offset 0.
3062     if (Layout.getFieldOffset(idx) != 0)
3063       return false;
3064 
3065     if (!isIntegerLikeType(FD->getType(), Context, VMContext))
3066       return false;
3067 
3068     // Only allow at most one field in a structure. This doesn't match the
3069     // wording above, but follows gcc in situations with a field following an
3070     // empty structure.
3071     if (!RD->isUnion()) {
3072       if (HadField)
3073         return false;
3074 
3075       HadField = true;
3076     }
3077   }
3078 
3079   return true;
3080 }
3081 
3082 ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy) const {
3083   if (RetTy->isVoidType())
3084     return ABIArgInfo::getIgnore();
3085 
3086   // Large vector types should be returned via memory.
3087   if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
3088     return ABIArgInfo::getIndirect(0);
3089 
3090   if (!isAggregateTypeForABI(RetTy)) {
3091     // Treat an enum type as its underlying type.
3092     if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
3093       RetTy = EnumTy->getDecl()->getIntegerType();
3094 
3095     return (RetTy->isPromotableIntegerType() ?
3096             ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
3097   }
3098 
3099   // Structures with either a non-trivial destructor or a non-trivial
3100   // copy constructor are always indirect.
3101   if (isRecordWithNonTrivialDestructorOrCopyConstructor(RetTy))
3102     return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3103 
3104   // Are we following APCS?
3105   if (getABIKind() == APCS) {
3106     if (isEmptyRecord(getContext(), RetTy, false))
3107       return ABIArgInfo::getIgnore();
3108 
3109     // Complex types are all returned as packed integers.
3110     //
3111     // FIXME: Consider using 2 x vector types if the back end handles them
3112     // correctly.
3113     if (RetTy->isAnyComplexType())
3114       return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
3115                                               getContext().getTypeSize(RetTy)));
3116 
3117     // Integer like structures are returned in r0.
3118     if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
3119       // Return in the smallest viable integer type.
3120       uint64_t Size = getContext().getTypeSize(RetTy);
3121       if (Size <= 8)
3122         return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
3123       if (Size <= 16)
3124         return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
3125       return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
3126     }
3127 
3128     // Otherwise return in memory.
3129     return ABIArgInfo::getIndirect(0);
3130   }
3131 
3132   // Otherwise this is an AAPCS variant.
3133 
3134   if (isEmptyRecord(getContext(), RetTy, true))
3135     return ABIArgInfo::getIgnore();
3136 
3137   // Check for homogeneous aggregates with AAPCS-VFP.
3138   if (getABIKind() == AAPCS_VFP) {
3139     const Type *Base = 0;
3140     if (isHomogeneousAggregate(RetTy, Base, getContext())) {
3141       assert(Base && "Base class should be set for homogeneous aggregate");
3142       // Homogeneous Aggregates are returned directly.
3143       return ABIArgInfo::getDirect();
3144     }
3145   }
3146 
3147   // Aggregates <= 4 bytes are returned in r0; other aggregates
3148   // are returned indirectly.
3149   uint64_t Size = getContext().getTypeSize(RetTy);
3150   if (Size <= 32) {
3151     // Return in the smallest viable integer type.
3152     if (Size <= 8)
3153       return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
3154     if (Size <= 16)
3155       return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
3156     return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
3157   }
3158 
3159   return ABIArgInfo::getIndirect(0);
3160 }
3161 
3162 llvm::Value *ARMABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3163                                    CodeGenFunction &CGF) const {
3164   llvm::Type *BP = CGF.Int8PtrTy;
3165   llvm::Type *BPP = CGF.Int8PtrPtrTy;
3166 
3167   CGBuilderTy &Builder = CGF.Builder;
3168   llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
3169   llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
3170   // Handle address alignment for type alignment > 32 bits
3171   uint64_t TyAlign = CGF.getContext().getTypeAlign(Ty) / 8;
3172   if (TyAlign > 4) {
3173     assert((TyAlign & (TyAlign - 1)) == 0 &&
3174            "Alignment is not power of 2!");
3175     llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int32Ty);
3176     AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt32(TyAlign - 1));
3177     AddrAsInt = Builder.CreateAnd(AddrAsInt, Builder.getInt32(~(TyAlign - 1)));
3178     Addr = Builder.CreateIntToPtr(AddrAsInt, BP);
3179   }
3180   llvm::Type *PTy =
3181     llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
3182   llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
3183 
3184   uint64_t Offset =
3185     llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 4);
3186   llvm::Value *NextAddr =
3187     Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
3188                       "ap.next");
3189   Builder.CreateStore(NextAddr, VAListAddrAsBPP);
3190 
3191   return AddrTyped;
3192 }
3193 
3194 //===----------------------------------------------------------------------===//
3195 // NVPTX ABI Implementation
3196 //===----------------------------------------------------------------------===//
3197 
3198 namespace {
3199 
3200 class NVPTXABIInfo : public ABIInfo {
3201 public:
3202   NVPTXABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
3203 
3204   ABIArgInfo classifyReturnType(QualType RetTy) const;
3205   ABIArgInfo classifyArgumentType(QualType Ty) const;
3206 
3207   virtual void computeInfo(CGFunctionInfo &FI) const;
3208   virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3209                                  CodeGenFunction &CFG) const;
3210 };
3211 
3212 class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
3213 public:
3214   NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
3215     : TargetCodeGenInfo(new NVPTXABIInfo(CGT)) {}
3216 
3217   virtual void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
3218                                    CodeGen::CodeGenModule &M) const;
3219 };
3220 
3221 ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
3222   if (RetTy->isVoidType())
3223     return ABIArgInfo::getIgnore();
3224   if (isAggregateTypeForABI(RetTy))
3225     return ABIArgInfo::getIndirect(0);
3226   return ABIArgInfo::getDirect();
3227 }
3228 
3229 ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
3230   if (isAggregateTypeForABI(Ty))
3231     return ABIArgInfo::getIndirect(0);
3232 
3233   return ABIArgInfo::getDirect();
3234 }
3235 
3236 void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
3237   FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
3238   for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
3239        it != ie; ++it)
3240     it->info = classifyArgumentType(it->type);
3241 
3242   // Always honor user-specified calling convention.
3243   if (FI.getCallingConvention() != llvm::CallingConv::C)
3244     return;
3245 
3246   // Calling convention as default by an ABI.
3247   // We're still using the PTX_Kernel/PTX_Device calling conventions here,
3248   // but we should switch to NVVM metadata later on.
3249   llvm::CallingConv::ID DefaultCC;
3250   const LangOptions &LangOpts = getContext().getLangOpts();
3251   if (LangOpts.OpenCL || LangOpts.CUDA) {
3252     // If we are in OpenCL or CUDA mode, then default to device functions
3253     DefaultCC = llvm::CallingConv::PTX_Device;
3254   } else {
3255     // If we are in standard C/C++ mode, use the triple to decide on the default
3256     StringRef Env =
3257       getContext().getTargetInfo().getTriple().getEnvironmentName();
3258     if (Env == "device")
3259       DefaultCC = llvm::CallingConv::PTX_Device;
3260     else
3261       DefaultCC = llvm::CallingConv::PTX_Kernel;
3262   }
3263   FI.setEffectiveCallingConvention(DefaultCC);
3264 
3265 }
3266 
3267 llvm::Value *NVPTXABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3268                                      CodeGenFunction &CFG) const {
3269   llvm_unreachable("NVPTX does not support varargs");
3270 }
3271 
3272 void NVPTXTargetCodeGenInfo::
3273 SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
3274                     CodeGen::CodeGenModule &M) const{
3275   const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
3276   if (!FD) return;
3277 
3278   llvm::Function *F = cast<llvm::Function>(GV);
3279 
3280   // Perform special handling in OpenCL mode
3281   if (M.getLangOpts().OpenCL) {
3282     // Use OpenCL function attributes to set proper calling conventions
3283     // By default, all functions are device functions
3284     if (FD->hasAttr<OpenCLKernelAttr>()) {
3285       // OpenCL __kernel functions get a kernel calling convention
3286       F->setCallingConv(llvm::CallingConv::PTX_Kernel);
3287       // And kernel functions are not subject to inlining
3288       F->addFnAttr(llvm::Attributes::NoInline);
3289     }
3290   }
3291 
3292   // Perform special handling in CUDA mode.
3293   if (M.getLangOpts().CUDA) {
3294     // CUDA __global__ functions get a kernel calling convention.  Since
3295     // __global__ functions cannot be called from the device, we do not
3296     // need to set the noinline attribute.
3297     if (FD->getAttr<CUDAGlobalAttr>())
3298       F->setCallingConv(llvm::CallingConv::PTX_Kernel);
3299   }
3300 }
3301 
3302 }
3303 
3304 //===----------------------------------------------------------------------===//
3305 // MBlaze ABI Implementation
3306 //===----------------------------------------------------------------------===//
3307 
3308 namespace {
3309 
3310 class MBlazeABIInfo : public ABIInfo {
3311 public:
3312   MBlazeABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
3313 
3314   bool isPromotableIntegerType(QualType Ty) const;
3315 
3316   ABIArgInfo classifyReturnType(QualType RetTy) const;
3317   ABIArgInfo classifyArgumentType(QualType RetTy) const;
3318 
3319   virtual void computeInfo(CGFunctionInfo &FI) const {
3320     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
3321     for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
3322          it != ie; ++it)
3323       it->info = classifyArgumentType(it->type);
3324   }
3325 
3326   virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3327                                  CodeGenFunction &CGF) const;
3328 };
3329 
3330 class MBlazeTargetCodeGenInfo : public TargetCodeGenInfo {
3331 public:
3332   MBlazeTargetCodeGenInfo(CodeGenTypes &CGT)
3333     : TargetCodeGenInfo(new MBlazeABIInfo(CGT)) {}
3334   void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
3335                            CodeGen::CodeGenModule &M) const;
3336 };
3337 
3338 }
3339 
3340 bool MBlazeABIInfo::isPromotableIntegerType(QualType Ty) const {
3341   // MBlaze ABI requires all 8 and 16 bit quantities to be extended.
3342   if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
3343     switch (BT->getKind()) {
3344     case BuiltinType::Bool:
3345     case BuiltinType::Char_S:
3346     case BuiltinType::Char_U:
3347     case BuiltinType::SChar:
3348     case BuiltinType::UChar:
3349     case BuiltinType::Short:
3350     case BuiltinType::UShort:
3351       return true;
3352     default:
3353       return false;
3354     }
3355   return false;
3356 }
3357 
3358 llvm::Value *MBlazeABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3359                                       CodeGenFunction &CGF) const {
3360   // FIXME: Implement
3361   return 0;
3362 }
3363 
3364 
3365 ABIArgInfo MBlazeABIInfo::classifyReturnType(QualType RetTy) const {
3366   if (RetTy->isVoidType())
3367     return ABIArgInfo::getIgnore();
3368   if (isAggregateTypeForABI(RetTy))
3369     return ABIArgInfo::getIndirect(0);
3370 
3371   return (isPromotableIntegerType(RetTy) ?
3372           ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
3373 }
3374 
3375 ABIArgInfo MBlazeABIInfo::classifyArgumentType(QualType Ty) const {
3376   if (isAggregateTypeForABI(Ty))
3377     return ABIArgInfo::getIndirect(0);
3378 
3379   return (isPromotableIntegerType(Ty) ?
3380           ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
3381 }
3382 
3383 void MBlazeTargetCodeGenInfo::SetTargetAttributes(const Decl *D,
3384                                                   llvm::GlobalValue *GV,
3385                                                   CodeGen::CodeGenModule &M)
3386                                                   const {
3387   const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
3388   if (!FD) return;
3389 
3390   llvm::CallingConv::ID CC = llvm::CallingConv::C;
3391   if (FD->hasAttr<MBlazeInterruptHandlerAttr>())
3392     CC = llvm::CallingConv::MBLAZE_INTR;
3393   else if (FD->hasAttr<MBlazeSaveVolatilesAttr>())
3394     CC = llvm::CallingConv::MBLAZE_SVOL;
3395 
3396   if (CC != llvm::CallingConv::C) {
3397       // Handle 'interrupt_handler' attribute:
3398       llvm::Function *F = cast<llvm::Function>(GV);
3399 
3400       // Step 1: Set ISR calling convention.
3401       F->setCallingConv(CC);
3402 
3403       // Step 2: Add attributes goodness.
3404       F->addFnAttr(llvm::Attributes::NoInline);
3405   }
3406 
3407   // Step 3: Emit _interrupt_handler alias.
3408   if (CC == llvm::CallingConv::MBLAZE_INTR)
3409     new llvm::GlobalAlias(GV->getType(), llvm::Function::ExternalLinkage,
3410                           "_interrupt_handler", GV, &M.getModule());
3411 }
3412 
3413 
3414 //===----------------------------------------------------------------------===//
3415 // MSP430 ABI Implementation
3416 //===----------------------------------------------------------------------===//
3417 
3418 namespace {
3419 
3420 class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
3421 public:
3422   MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
3423     : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
3424   void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
3425                            CodeGen::CodeGenModule &M) const;
3426 };
3427 
3428 }
3429 
3430 void MSP430TargetCodeGenInfo::SetTargetAttributes(const Decl *D,
3431                                                   llvm::GlobalValue *GV,
3432                                              CodeGen::CodeGenModule &M) const {
3433   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3434     if (const MSP430InterruptAttr *attr = FD->getAttr<MSP430InterruptAttr>()) {
3435       // Handle 'interrupt' attribute:
3436       llvm::Function *F = cast<llvm::Function>(GV);
3437 
3438       // Step 1: Set ISR calling convention.
3439       F->setCallingConv(llvm::CallingConv::MSP430_INTR);
3440 
3441       // Step 2: Add attributes goodness.
3442       F->addFnAttr(llvm::Attributes::NoInline);
3443 
3444       // Step 3: Emit ISR vector alias.
3445       unsigned Num = attr->getNumber() + 0xffe0;
3446       new llvm::GlobalAlias(GV->getType(), llvm::Function::ExternalLinkage,
3447                             "vector_" + Twine::utohexstr(Num),
3448                             GV, &M.getModule());
3449     }
3450   }
3451 }
3452 
3453 //===----------------------------------------------------------------------===//
3454 // MIPS ABI Implementation.  This works for both little-endian and
3455 // big-endian variants.
3456 //===----------------------------------------------------------------------===//
3457 
3458 namespace {
3459 class MipsABIInfo : public ABIInfo {
3460   bool IsO32;
3461   unsigned MinABIStackAlignInBytes, StackAlignInBytes;
3462   void CoerceToIntArgs(uint64_t TySize,
3463                        SmallVector<llvm::Type*, 8> &ArgList) const;
3464   llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
3465   llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
3466   llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
3467 public:
3468   MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
3469     ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
3470     StackAlignInBytes(IsO32 ? 8 : 16) {}
3471 
3472   ABIArgInfo classifyReturnType(QualType RetTy) const;
3473   ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
3474   virtual void computeInfo(CGFunctionInfo &FI) const;
3475   virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3476                                  CodeGenFunction &CGF) const;
3477 };
3478 
3479 class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
3480   unsigned SizeOfUnwindException;
3481 public:
3482   MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
3483     : TargetCodeGenInfo(new MipsABIInfo(CGT, IsO32)),
3484       SizeOfUnwindException(IsO32 ? 24 : 32) {}
3485 
3486   int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const {
3487     return 29;
3488   }
3489 
3490   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3491                                llvm::Value *Address) const;
3492 
3493   unsigned getSizeOfUnwindException() const {
3494     return SizeOfUnwindException;
3495   }
3496 };
3497 }
3498 
3499 void MipsABIInfo::CoerceToIntArgs(uint64_t TySize,
3500                                   SmallVector<llvm::Type*, 8> &ArgList) const {
3501   llvm::IntegerType *IntTy =
3502     llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
3503 
3504   // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
3505   for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
3506     ArgList.push_back(IntTy);
3507 
3508   // If necessary, add one more integer type to ArgList.
3509   unsigned R = TySize % (MinABIStackAlignInBytes * 8);
3510 
3511   if (R)
3512     ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
3513 }
3514 
3515 // In N32/64, an aligned double precision floating point field is passed in
3516 // a register.
3517 llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
3518   SmallVector<llvm::Type*, 8> ArgList, IntArgList;
3519 
3520   if (IsO32) {
3521     CoerceToIntArgs(TySize, ArgList);
3522     return llvm::StructType::get(getVMContext(), ArgList);
3523   }
3524 
3525   if (Ty->isComplexType())
3526     return CGT.ConvertType(Ty);
3527 
3528   const RecordType *RT = Ty->getAs<RecordType>();
3529 
3530   // Unions/vectors are passed in integer registers.
3531   if (!RT || !RT->isStructureOrClassType()) {
3532     CoerceToIntArgs(TySize, ArgList);
3533     return llvm::StructType::get(getVMContext(), ArgList);
3534   }
3535 
3536   const RecordDecl *RD = RT->getDecl();
3537   const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
3538   assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
3539 
3540   uint64_t LastOffset = 0;
3541   unsigned idx = 0;
3542   llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
3543 
3544   // Iterate over fields in the struct/class and check if there are any aligned
3545   // double fields.
3546   for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
3547        i != e; ++i, ++idx) {
3548     const QualType Ty = i->getType();
3549     const BuiltinType *BT = Ty->getAs<BuiltinType>();
3550 
3551     if (!BT || BT->getKind() != BuiltinType::Double)
3552       continue;
3553 
3554     uint64_t Offset = Layout.getFieldOffset(idx);
3555     if (Offset % 64) // Ignore doubles that are not aligned.
3556       continue;
3557 
3558     // Add ((Offset - LastOffset) / 64) args of type i64.
3559     for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
3560       ArgList.push_back(I64);
3561 
3562     // Add double type.
3563     ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
3564     LastOffset = Offset + 64;
3565   }
3566 
3567   CoerceToIntArgs(TySize - LastOffset, IntArgList);
3568   ArgList.append(IntArgList.begin(), IntArgList.end());
3569 
3570   return llvm::StructType::get(getVMContext(), ArgList);
3571 }
3572 
3573 llvm::Type *MipsABIInfo::getPaddingType(uint64_t Align, uint64_t Offset) const {
3574   assert((Offset % MinABIStackAlignInBytes) == 0);
3575 
3576   if ((Align - 1) & Offset)
3577     return llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
3578 
3579   return 0;
3580 }
3581 
3582 ABIArgInfo
3583 MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
3584   uint64_t OrigOffset = Offset;
3585   uint64_t TySize = getContext().getTypeSize(Ty);
3586   uint64_t Align = getContext().getTypeAlign(Ty) / 8;
3587 
3588   Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
3589                    (uint64_t)StackAlignInBytes);
3590   Offset = llvm::RoundUpToAlignment(Offset, Align);
3591   Offset += llvm::RoundUpToAlignment(TySize, Align * 8) / 8;
3592 
3593   if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
3594     // Ignore empty aggregates.
3595     if (TySize == 0)
3596       return ABIArgInfo::getIgnore();
3597 
3598     // Records with non trivial destructors/constructors should not be passed
3599     // by value.
3600     if (isRecordWithNonTrivialDestructorOrCopyConstructor(Ty)) {
3601       Offset = OrigOffset + MinABIStackAlignInBytes;
3602       return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3603     }
3604 
3605     // If we have reached here, aggregates are passed directly by coercing to
3606     // another structure type. Padding is inserted if the offset of the
3607     // aggregate is unaligned.
3608     return ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
3609                                  getPaddingType(Align, OrigOffset));
3610   }
3611 
3612   // Treat an enum type as its underlying type.
3613   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3614     Ty = EnumTy->getDecl()->getIntegerType();
3615 
3616   if (Ty->isPromotableIntegerType())
3617     return ABIArgInfo::getExtend();
3618 
3619   return ABIArgInfo::getDirect(0, 0, getPaddingType(Align, OrigOffset));
3620 }
3621 
3622 llvm::Type*
3623 MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
3624   const RecordType *RT = RetTy->getAs<RecordType>();
3625   SmallVector<llvm::Type*, 8> RTList;
3626 
3627   if (RT && RT->isStructureOrClassType()) {
3628     const RecordDecl *RD = RT->getDecl();
3629     const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
3630     unsigned FieldCnt = Layout.getFieldCount();
3631 
3632     // N32/64 returns struct/classes in floating point registers if the
3633     // following conditions are met:
3634     // 1. The size of the struct/class is no larger than 128-bit.
3635     // 2. The struct/class has one or two fields all of which are floating
3636     //    point types.
3637     // 3. The offset of the first field is zero (this follows what gcc does).
3638     //
3639     // Any other composite results are returned in integer registers.
3640     //
3641     if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
3642       RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
3643       for (; b != e; ++b) {
3644         const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
3645 
3646         if (!BT || !BT->isFloatingPoint())
3647           break;
3648 
3649         RTList.push_back(CGT.ConvertType(b->getType()));
3650       }
3651 
3652       if (b == e)
3653         return llvm::StructType::get(getVMContext(), RTList,
3654                                      RD->hasAttr<PackedAttr>());
3655 
3656       RTList.clear();
3657     }
3658   }
3659 
3660   CoerceToIntArgs(Size, RTList);
3661   return llvm::StructType::get(getVMContext(), RTList);
3662 }
3663 
3664 ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
3665   uint64_t Size = getContext().getTypeSize(RetTy);
3666 
3667   if (RetTy->isVoidType() || Size == 0)
3668     return ABIArgInfo::getIgnore();
3669 
3670   if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
3671     if (Size <= 128) {
3672       if (RetTy->isAnyComplexType())
3673         return ABIArgInfo::getDirect();
3674 
3675       // O32 returns integer vectors in registers.
3676       if (IsO32 && RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())
3677         return ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
3678 
3679       if (!IsO32 && !isRecordWithNonTrivialDestructorOrCopyConstructor(RetTy))
3680         return ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
3681     }
3682 
3683     return ABIArgInfo::getIndirect(0);
3684   }
3685 
3686   // Treat an enum type as its underlying type.
3687   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
3688     RetTy = EnumTy->getDecl()->getIntegerType();
3689 
3690   return (RetTy->isPromotableIntegerType() ?
3691           ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
3692 }
3693 
3694 void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
3695   ABIArgInfo &RetInfo = FI.getReturnInfo();
3696   RetInfo = classifyReturnType(FI.getReturnType());
3697 
3698   // Check if a pointer to an aggregate is passed as a hidden argument.
3699   uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
3700 
3701   for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
3702        it != ie; ++it)
3703     it->info = classifyArgumentType(it->type, Offset);
3704 }
3705 
3706 llvm::Value* MipsABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3707                                     CodeGenFunction &CGF) const {
3708   llvm::Type *BP = CGF.Int8PtrTy;
3709   llvm::Type *BPP = CGF.Int8PtrPtrTy;
3710 
3711   CGBuilderTy &Builder = CGF.Builder;
3712   llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
3713   llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
3714   int64_t TypeAlign = getContext().getTypeAlign(Ty) / 8;
3715   llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
3716   llvm::Value *AddrTyped;
3717   unsigned PtrWidth = getContext().getTargetInfo().getPointerWidth(0);
3718   llvm::IntegerType *IntTy = (PtrWidth == 32) ? CGF.Int32Ty : CGF.Int64Ty;
3719 
3720   if (TypeAlign > MinABIStackAlignInBytes) {
3721     llvm::Value *AddrAsInt = CGF.Builder.CreatePtrToInt(Addr, IntTy);
3722     llvm::Value *Inc = llvm::ConstantInt::get(IntTy, TypeAlign - 1);
3723     llvm::Value *Mask = llvm::ConstantInt::get(IntTy, -TypeAlign);
3724     llvm::Value *Add = CGF.Builder.CreateAdd(AddrAsInt, Inc);
3725     llvm::Value *And = CGF.Builder.CreateAnd(Add, Mask);
3726     AddrTyped = CGF.Builder.CreateIntToPtr(And, PTy);
3727   }
3728   else
3729     AddrTyped = Builder.CreateBitCast(Addr, PTy);
3730 
3731   llvm::Value *AlignedAddr = Builder.CreateBitCast(AddrTyped, BP);
3732   TypeAlign = std::max((unsigned)TypeAlign, MinABIStackAlignInBytes);
3733   uint64_t Offset =
3734     llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, TypeAlign);
3735   llvm::Value *NextAddr =
3736     Builder.CreateGEP(AlignedAddr, llvm::ConstantInt::get(IntTy, Offset),
3737                       "ap.next");
3738   Builder.CreateStore(NextAddr, VAListAddrAsBPP);
3739 
3740   return AddrTyped;
3741 }
3742 
3743 bool
3744 MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3745                                                llvm::Value *Address) const {
3746   // This information comes from gcc's implementation, which seems to
3747   // as canonical as it gets.
3748 
3749   // Everything on MIPS is 4 bytes.  Double-precision FP registers
3750   // are aliased to pairs of single-precision FP registers.
3751   llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
3752 
3753   // 0-31 are the general purpose registers, $0 - $31.
3754   // 32-63 are the floating-point registers, $f0 - $f31.
3755   // 64 and 65 are the multiply/divide registers, $hi and $lo.
3756   // 66 is the (notional, I think) register for signal-handler return.
3757   AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
3758 
3759   // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
3760   // They are one bit wide and ignored here.
3761 
3762   // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
3763   // (coprocessor 1 is the FP unit)
3764   // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
3765   // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
3766   // 176-181 are the DSP accumulator registers.
3767   AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
3768   return false;
3769 }
3770 
3771 //===----------------------------------------------------------------------===//
3772 // TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
3773 // Currently subclassed only to implement custom OpenCL C function attribute
3774 // handling.
3775 //===----------------------------------------------------------------------===//
3776 
3777 namespace {
3778 
3779 class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
3780 public:
3781   TCETargetCodeGenInfo(CodeGenTypes &CGT)
3782     : DefaultTargetCodeGenInfo(CGT) {}
3783 
3784   virtual void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
3785                                    CodeGen::CodeGenModule &M) const;
3786 };
3787 
3788 void TCETargetCodeGenInfo::SetTargetAttributes(const Decl *D,
3789                                                llvm::GlobalValue *GV,
3790                                                CodeGen::CodeGenModule &M) const {
3791   const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
3792   if (!FD) return;
3793 
3794   llvm::Function *F = cast<llvm::Function>(GV);
3795 
3796   if (M.getLangOpts().OpenCL) {
3797     if (FD->hasAttr<OpenCLKernelAttr>()) {
3798       // OpenCL C Kernel functions are not subject to inlining
3799       F->addFnAttr(llvm::Attributes::NoInline);
3800 
3801       if (FD->hasAttr<ReqdWorkGroupSizeAttr>()) {
3802 
3803         // Convert the reqd_work_group_size() attributes to metadata.
3804         llvm::LLVMContext &Context = F->getContext();
3805         llvm::NamedMDNode *OpenCLMetadata =
3806             M.getModule().getOrInsertNamedMetadata("opencl.kernel_wg_size_info");
3807 
3808         SmallVector<llvm::Value*, 5> Operands;
3809         Operands.push_back(F);
3810 
3811         Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty,
3812                              llvm::APInt(32,
3813                              FD->getAttr<ReqdWorkGroupSizeAttr>()->getXDim())));
3814         Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty,
3815                              llvm::APInt(32,
3816                                FD->getAttr<ReqdWorkGroupSizeAttr>()->getYDim())));
3817         Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty,
3818                              llvm::APInt(32,
3819                                FD->getAttr<ReqdWorkGroupSizeAttr>()->getZDim())));
3820 
3821         // Add a boolean constant operand for "required" (true) or "hint" (false)
3822         // for implementing the work_group_size_hint attr later. Currently
3823         // always true as the hint is not yet implemented.
3824         Operands.push_back(llvm::ConstantInt::getTrue(Context));
3825         OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
3826       }
3827     }
3828   }
3829 }
3830 
3831 }
3832 
3833 //===----------------------------------------------------------------------===//
3834 // Hexagon ABI Implementation
3835 //===----------------------------------------------------------------------===//
3836 
3837 namespace {
3838 
3839 class HexagonABIInfo : public ABIInfo {
3840 
3841 
3842 public:
3843   HexagonABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
3844 
3845 private:
3846 
3847   ABIArgInfo classifyReturnType(QualType RetTy) const;
3848   ABIArgInfo classifyArgumentType(QualType RetTy) const;
3849 
3850   virtual void computeInfo(CGFunctionInfo &FI) const;
3851 
3852   virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3853                                  CodeGenFunction &CGF) const;
3854 };
3855 
3856 class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
3857 public:
3858   HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
3859     :TargetCodeGenInfo(new HexagonABIInfo(CGT)) {}
3860 
3861   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const {
3862     return 29;
3863   }
3864 };
3865 
3866 }
3867 
3868 void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
3869   FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
3870   for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
3871        it != ie; ++it)
3872     it->info = classifyArgumentType(it->type);
3873 }
3874 
3875 ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty) const {
3876   if (!isAggregateTypeForABI(Ty)) {
3877     // Treat an enum type as its underlying type.
3878     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3879       Ty = EnumTy->getDecl()->getIntegerType();
3880 
3881     return (Ty->isPromotableIntegerType() ?
3882             ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
3883   }
3884 
3885   // Ignore empty records.
3886   if (isEmptyRecord(getContext(), Ty, true))
3887     return ABIArgInfo::getIgnore();
3888 
3889   // Structures with either a non-trivial destructor or a non-trivial
3890   // copy constructor are always indirect.
3891   if (isRecordWithNonTrivialDestructorOrCopyConstructor(Ty))
3892     return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3893 
3894   uint64_t Size = getContext().getTypeSize(Ty);
3895   if (Size > 64)
3896     return ABIArgInfo::getIndirect(0, /*ByVal=*/true);
3897     // Pass in the smallest viable integer type.
3898   else if (Size > 32)
3899       return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
3900   else if (Size > 16)
3901       return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
3902   else if (Size > 8)
3903       return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
3904   else
3905       return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
3906 }
3907 
3908 ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
3909   if (RetTy->isVoidType())
3910     return ABIArgInfo::getIgnore();
3911 
3912   // Large vector types should be returned via memory.
3913   if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 64)
3914     return ABIArgInfo::getIndirect(0);
3915 
3916   if (!isAggregateTypeForABI(RetTy)) {
3917     // Treat an enum type as its underlying type.
3918     if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
3919       RetTy = EnumTy->getDecl()->getIntegerType();
3920 
3921     return (RetTy->isPromotableIntegerType() ?
3922             ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
3923   }
3924 
3925   // Structures with either a non-trivial destructor or a non-trivial
3926   // copy constructor are always indirect.
3927   if (isRecordWithNonTrivialDestructorOrCopyConstructor(RetTy))
3928     return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3929 
3930   if (isEmptyRecord(getContext(), RetTy, true))
3931     return ABIArgInfo::getIgnore();
3932 
3933   // Aggregates <= 8 bytes are returned in r0; other aggregates
3934   // are returned indirectly.
3935   uint64_t Size = getContext().getTypeSize(RetTy);
3936   if (Size <= 64) {
3937     // Return in the smallest viable integer type.
3938     if (Size <= 8)
3939       return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
3940     if (Size <= 16)
3941       return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
3942     if (Size <= 32)
3943       return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
3944     return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
3945   }
3946 
3947   return ABIArgInfo::getIndirect(0, /*ByVal=*/true);
3948 }
3949 
3950 llvm::Value *HexagonABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3951                                        CodeGenFunction &CGF) const {
3952   // FIXME: Need to handle alignment
3953   llvm::Type *BPP = CGF.Int8PtrPtrTy;
3954 
3955   CGBuilderTy &Builder = CGF.Builder;
3956   llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
3957                                                        "ap");
3958   llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
3959   llvm::Type *PTy =
3960     llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
3961   llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
3962 
3963   uint64_t Offset =
3964     llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 4);
3965   llvm::Value *NextAddr =
3966     Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
3967                       "ap.next");
3968   Builder.CreateStore(NextAddr, VAListAddrAsBPP);
3969 
3970   return AddrTyped;
3971 }
3972 
3973 
3974 const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
3975   if (TheTargetCodeGenInfo)
3976     return *TheTargetCodeGenInfo;
3977 
3978   const llvm::Triple &Triple = getContext().getTargetInfo().getTriple();
3979   switch (Triple.getArch()) {
3980   default:
3981     return *(TheTargetCodeGenInfo = new DefaultTargetCodeGenInfo(Types));
3982 
3983   case llvm::Triple::le32:
3984     return *(TheTargetCodeGenInfo = new PNaClTargetCodeGenInfo(Types));
3985   case llvm::Triple::mips:
3986   case llvm::Triple::mipsel:
3987     return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, true));
3988 
3989   case llvm::Triple::mips64:
3990   case llvm::Triple::mips64el:
3991     return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, false));
3992 
3993   case llvm::Triple::arm:
3994   case llvm::Triple::thumb:
3995     {
3996       ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
3997 
3998       if (strcmp(getContext().getTargetInfo().getABI(), "apcs-gnu") == 0)
3999         Kind = ARMABIInfo::APCS;
4000       else if (CodeGenOpts.FloatABI == "hard")
4001         Kind = ARMABIInfo::AAPCS_VFP;
4002 
4003       return *(TheTargetCodeGenInfo = new ARMTargetCodeGenInfo(Types, Kind));
4004     }
4005 
4006   case llvm::Triple::ppc:
4007     return *(TheTargetCodeGenInfo = new PPC32TargetCodeGenInfo(Types));
4008   case llvm::Triple::ppc64:
4009     if (Triple.isOSBinFormatELF())
4010       return *(TheTargetCodeGenInfo = new PPC64_SVR4_TargetCodeGenInfo(Types));
4011     else
4012       return *(TheTargetCodeGenInfo = new PPC64TargetCodeGenInfo(Types));
4013 
4014   case llvm::Triple::nvptx:
4015   case llvm::Triple::nvptx64:
4016     return *(TheTargetCodeGenInfo = new NVPTXTargetCodeGenInfo(Types));
4017 
4018   case llvm::Triple::mblaze:
4019     return *(TheTargetCodeGenInfo = new MBlazeTargetCodeGenInfo(Types));
4020 
4021   case llvm::Triple::msp430:
4022     return *(TheTargetCodeGenInfo = new MSP430TargetCodeGenInfo(Types));
4023 
4024   case llvm::Triple::tce:
4025     return *(TheTargetCodeGenInfo = new TCETargetCodeGenInfo(Types));
4026 
4027   case llvm::Triple::x86: {
4028     bool DisableMMX = strcmp(getContext().getTargetInfo().getABI(), "no-mmx") == 0;
4029 
4030     if (Triple.isOSDarwin())
4031       return *(TheTargetCodeGenInfo =
4032                new X86_32TargetCodeGenInfo(Types, true, true, DisableMMX, false,
4033                                            CodeGenOpts.NumRegisterParameters));
4034 
4035     switch (Triple.getOS()) {
4036     case llvm::Triple::Cygwin:
4037     case llvm::Triple::MinGW32:
4038     case llvm::Triple::AuroraUX:
4039     case llvm::Triple::DragonFly:
4040     case llvm::Triple::FreeBSD:
4041     case llvm::Triple::OpenBSD:
4042     case llvm::Triple::Bitrig:
4043       return *(TheTargetCodeGenInfo =
4044                new X86_32TargetCodeGenInfo(Types, false, true, DisableMMX,
4045                                            false,
4046                                            CodeGenOpts.NumRegisterParameters));
4047 
4048     case llvm::Triple::Win32:
4049       return *(TheTargetCodeGenInfo =
4050                new X86_32TargetCodeGenInfo(Types, false, true, DisableMMX, true,
4051                                            CodeGenOpts.NumRegisterParameters));
4052 
4053     default:
4054       return *(TheTargetCodeGenInfo =
4055                new X86_32TargetCodeGenInfo(Types, false, false, DisableMMX,
4056                                            false,
4057                                            CodeGenOpts.NumRegisterParameters));
4058     }
4059   }
4060 
4061   case llvm::Triple::x86_64: {
4062     bool HasAVX = strcmp(getContext().getTargetInfo().getABI(), "avx") == 0;
4063 
4064     switch (Triple.getOS()) {
4065     case llvm::Triple::Win32:
4066     case llvm::Triple::MinGW32:
4067     case llvm::Triple::Cygwin:
4068       return *(TheTargetCodeGenInfo = new WinX86_64TargetCodeGenInfo(Types));
4069     default:
4070       return *(TheTargetCodeGenInfo = new X86_64TargetCodeGenInfo(Types,
4071                                                                   HasAVX));
4072     }
4073   }
4074   case llvm::Triple::hexagon:
4075     return *(TheTargetCodeGenInfo = new HexagonTargetCodeGenInfo(Types));
4076   }
4077 }
4078