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