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 "llvm/Type.h"
20 #include "llvm/Target/TargetData.h"
21 #include "llvm/ADT/StringExtras.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   llvm::raw_ostream &OS = llvm::errs();
61   OS << "(ABIArgInfo Kind=";
62   switch (TheKind) {
63   case Direct:
64     OS << "Direct Type=";
65     if (const 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        << " Byal=" << getIndirectByVal();
79     break;
80   case Expand:
81     OS << "Expand";
82     break;
83   }
84   OS << ")\n";
85 }
86 
87 TargetCodeGenInfo::~TargetCodeGenInfo() { delete Info; }
88 
89 static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays);
90 
91 /// isEmptyField - Return true iff a the field is "empty", that is it
92 /// is an unnamed bit-field or an (array of) empty record(s).
93 static bool isEmptyField(ASTContext &Context, const FieldDecl *FD,
94                          bool AllowArrays) {
95   if (FD->isUnnamedBitfield())
96     return true;
97 
98   QualType FT = FD->getType();
99 
100     // Constant arrays of empty records count as empty, strip them off.
101   if (AllowArrays)
102     while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT))
103       FT = AT->getElementType();
104 
105   const RecordType *RT = FT->getAs<RecordType>();
106   if (!RT)
107     return false;
108 
109   // C++ record fields are never empty, at least in the Itanium ABI.
110   //
111   // FIXME: We should use a predicate for whether this behavior is true in the
112   // current ABI.
113   if (isa<CXXRecordDecl>(RT->getDecl()))
114     return false;
115 
116   return isEmptyRecord(Context, FT, AllowArrays);
117 }
118 
119 /// isEmptyRecord - Return true iff a structure contains only empty
120 /// fields. Note that a structure with a flexible array member is not
121 /// considered empty.
122 static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) {
123   const RecordType *RT = T->getAs<RecordType>();
124   if (!RT)
125     return 0;
126   const RecordDecl *RD = RT->getDecl();
127   if (RD->hasFlexibleArrayMember())
128     return false;
129 
130   // If this is a C++ record, check the bases first.
131   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
132     for (CXXRecordDecl::base_class_const_iterator i = CXXRD->bases_begin(),
133            e = CXXRD->bases_end(); i != e; ++i)
134       if (!isEmptyRecord(Context, i->getType(), true))
135         return false;
136 
137   for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
138          i != e; ++i)
139     if (!isEmptyField(Context, *i, AllowArrays))
140       return false;
141   return true;
142 }
143 
144 /// hasNonTrivialDestructorOrCopyConstructor - Determine if a type has either
145 /// a non-trivial destructor or a non-trivial copy constructor.
146 static bool hasNonTrivialDestructorOrCopyConstructor(const RecordType *RT) {
147   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
148   if (!RD)
149     return false;
150 
151   return !RD->hasTrivialDestructor() || !RD->hasTrivialCopyConstructor();
152 }
153 
154 /// isRecordWithNonTrivialDestructorOrCopyConstructor - Determine if a type is
155 /// a record type with either a non-trivial destructor or a non-trivial copy
156 /// constructor.
157 static bool isRecordWithNonTrivialDestructorOrCopyConstructor(QualType T) {
158   const RecordType *RT = T->getAs<RecordType>();
159   if (!RT)
160     return false;
161 
162   return hasNonTrivialDestructorOrCopyConstructor(RT);
163 }
164 
165 /// isSingleElementStruct - Determine if a structure is a "single
166 /// element struct", i.e. it has exactly one non-empty field or
167 /// exactly one field which is itself a single element
168 /// struct. Structures with flexible array members are never
169 /// considered single element structs.
170 ///
171 /// \return The field declaration for the single non-empty field, if
172 /// it exists.
173 static const Type *isSingleElementStruct(QualType T, ASTContext &Context) {
174   const RecordType *RT = T->getAsStructureType();
175   if (!RT)
176     return 0;
177 
178   const RecordDecl *RD = RT->getDecl();
179   if (RD->hasFlexibleArrayMember())
180     return 0;
181 
182   const Type *Found = 0;
183 
184   // If this is a C++ record, check the bases first.
185   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
186     for (CXXRecordDecl::base_class_const_iterator i = CXXRD->bases_begin(),
187            e = CXXRD->bases_end(); i != e; ++i) {
188       // Ignore empty records.
189       if (isEmptyRecord(Context, i->getType(), true))
190         continue;
191 
192       // If we already found an element then this isn't a single-element struct.
193       if (Found)
194         return 0;
195 
196       // If this is non-empty and not a single element struct, the composite
197       // cannot be a single element struct.
198       Found = isSingleElementStruct(i->getType(), Context);
199       if (!Found)
200         return 0;
201     }
202   }
203 
204   // Check for single element.
205   for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
206          i != e; ++i) {
207     const FieldDecl *FD = *i;
208     QualType FT = FD->getType();
209 
210     // Ignore empty fields.
211     if (isEmptyField(Context, FD, true))
212       continue;
213 
214     // If we already found an element then this isn't a single-element
215     // struct.
216     if (Found)
217       return 0;
218 
219     // Treat single element arrays as the element.
220     while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
221       if (AT->getSize().getZExtValue() != 1)
222         break;
223       FT = AT->getElementType();
224     }
225 
226     if (!isAggregateTypeForABI(FT)) {
227       Found = FT.getTypePtr();
228     } else {
229       Found = isSingleElementStruct(FT, Context);
230       if (!Found)
231         return 0;
232     }
233   }
234 
235   return Found;
236 }
237 
238 static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
239   if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() &&
240       !Ty->isAnyComplexType() && !Ty->isEnumeralType() &&
241       !Ty->isBlockPointerType())
242     return false;
243 
244   uint64_t Size = Context.getTypeSize(Ty);
245   return Size == 32 || Size == 64;
246 }
247 
248 /// canExpandIndirectArgument - Test whether an argument type which is to be
249 /// passed indirectly (on the stack) would have the equivalent layout if it was
250 /// expanded into separate arguments. If so, we prefer to do the latter to avoid
251 /// inhibiting optimizations.
252 ///
253 // FIXME: This predicate is missing many cases, currently it just follows
254 // llvm-gcc (checks that all fields are 32-bit or 64-bit primitive types). We
255 // should probably make this smarter, or better yet make the LLVM backend
256 // capable of handling it.
257 static bool canExpandIndirectArgument(QualType Ty, ASTContext &Context) {
258   // We can only expand structure types.
259   const RecordType *RT = Ty->getAs<RecordType>();
260   if (!RT)
261     return false;
262 
263   // We can only expand (C) structures.
264   //
265   // FIXME: This needs to be generalized to handle classes as well.
266   const RecordDecl *RD = RT->getDecl();
267   if (!RD->isStruct() || isa<CXXRecordDecl>(RD))
268     return false;
269 
270   for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
271          i != e; ++i) {
272     const FieldDecl *FD = *i;
273 
274     if (!is32Or64BitBasicType(FD->getType(), Context))
275       return false;
276 
277     // FIXME: Reject bit-fields wholesale; there are two problems, we don't know
278     // how to expand them yet, and the predicate for telling if a bitfield still
279     // counts as "basic" is more complicated than what we were doing previously.
280     if (FD->isBitField())
281       return false;
282   }
283 
284   return true;
285 }
286 
287 namespace {
288 /// DefaultABIInfo - The default implementation for ABI specific
289 /// details. This implementation provides information which results in
290 /// self-consistent and sensible LLVM IR generation, but does not
291 /// conform to any particular ABI.
292 class DefaultABIInfo : public ABIInfo {
293 public:
294   DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
295 
296   ABIArgInfo classifyReturnType(QualType RetTy) const;
297   ABIArgInfo classifyArgumentType(QualType RetTy) const;
298 
299   virtual void computeInfo(CGFunctionInfo &FI) const {
300     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
301     for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
302          it != ie; ++it)
303       it->info = classifyArgumentType(it->type);
304   }
305 
306   virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
307                                  CodeGenFunction &CGF) const;
308 };
309 
310 class DefaultTargetCodeGenInfo : public TargetCodeGenInfo {
311 public:
312   DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
313     : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
314 };
315 
316 llvm::Value *DefaultABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
317                                        CodeGenFunction &CGF) const {
318   return 0;
319 }
320 
321 ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const {
322   if (isAggregateTypeForABI(Ty))
323     return ABIArgInfo::getIndirect(0);
324 
325   // Treat an enum type as its underlying type.
326   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
327     Ty = EnumTy->getDecl()->getIntegerType();
328 
329   return (Ty->isPromotableIntegerType() ?
330           ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
331 }
332 
333 //===----------------------------------------------------------------------===//
334 // X86-32 ABI Implementation
335 //===----------------------------------------------------------------------===//
336 
337 /// X86_32ABIInfo - The X86-32 ABI information.
338 class X86_32ABIInfo : public ABIInfo {
339   bool IsDarwinVectorABI;
340   bool IsSmallStructInRegABI;
341 
342   static bool isRegisterSize(unsigned Size) {
343     return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
344   }
345 
346   static bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context);
347 
348   /// getIndirectResult - Give a source type \arg Ty, return a suitable result
349   /// such that the argument will be passed in memory.
350   ABIArgInfo getIndirectResult(QualType Ty, bool ByVal = true) const;
351 
352 public:
353 
354   ABIArgInfo classifyReturnType(QualType RetTy) const;
355   ABIArgInfo classifyArgumentType(QualType RetTy) const;
356 
357   virtual void computeInfo(CGFunctionInfo &FI) const {
358     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
359     for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
360          it != ie; ++it)
361       it->info = classifyArgumentType(it->type);
362   }
363 
364   virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
365                                  CodeGenFunction &CGF) const;
366 
367   X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool d, bool p)
368     : ABIInfo(CGT), IsDarwinVectorABI(d), IsSmallStructInRegABI(p) {}
369 };
370 
371 class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
372 public:
373   X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool d, bool p)
374     :TargetCodeGenInfo(new X86_32ABIInfo(CGT, d, p)) {}
375 
376   void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
377                            CodeGen::CodeGenModule &CGM) const;
378 
379   int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const {
380     // Darwin uses different dwarf register numbers for EH.
381     if (CGM.isTargetDarwin()) return 5;
382 
383     return 4;
384   }
385 
386   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
387                                llvm::Value *Address) const;
388 };
389 
390 }
391 
392 /// shouldReturnTypeInRegister - Determine if the given type should be
393 /// passed in a register (for the Darwin ABI).
394 bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
395                                                ASTContext &Context) {
396   uint64_t Size = Context.getTypeSize(Ty);
397 
398   // Type must be register sized.
399   if (!isRegisterSize(Size))
400     return false;
401 
402   if (Ty->isVectorType()) {
403     // 64- and 128- bit vectors inside structures are not returned in
404     // registers.
405     if (Size == 64 || Size == 128)
406       return false;
407 
408     return true;
409   }
410 
411   // If this is a builtin, pointer, enum, complex type, member pointer, or
412   // member function pointer it is ok.
413   if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() ||
414       Ty->isAnyComplexType() || Ty->isEnumeralType() ||
415       Ty->isBlockPointerType() || Ty->isMemberPointerType())
416     return true;
417 
418   // Arrays are treated like records.
419   if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
420     return shouldReturnTypeInRegister(AT->getElementType(), Context);
421 
422   // Otherwise, it must be a record type.
423   const RecordType *RT = Ty->getAs<RecordType>();
424   if (!RT) return false;
425 
426   // FIXME: Traverse bases here too.
427 
428   // Structure types are passed in register if all fields would be
429   // passed in a register.
430   for (RecordDecl::field_iterator i = RT->getDecl()->field_begin(),
431          e = RT->getDecl()->field_end(); i != e; ++i) {
432     const FieldDecl *FD = *i;
433 
434     // Empty fields are ignored.
435     if (isEmptyField(Context, FD, true))
436       continue;
437 
438     // Check fields recursively.
439     if (!shouldReturnTypeInRegister(FD->getType(), Context))
440       return false;
441   }
442 
443   return true;
444 }
445 
446 ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy) const {
447   if (RetTy->isVoidType())
448     return ABIArgInfo::getIgnore();
449 
450   if (const VectorType *VT = RetTy->getAs<VectorType>()) {
451     // On Darwin, some vectors are returned in registers.
452     if (IsDarwinVectorABI) {
453       uint64_t Size = getContext().getTypeSize(RetTy);
454 
455       // 128-bit vectors are a special case; they are returned in
456       // registers and we need to make sure to pick a type the LLVM
457       // backend will like.
458       if (Size == 128)
459         return ABIArgInfo::getDirect(llvm::VectorType::get(
460                   llvm::Type::getInt64Ty(getVMContext()), 2));
461 
462       // Always return in register if it fits in a general purpose
463       // register, or if it is 64 bits and has a single element.
464       if ((Size == 8 || Size == 16 || Size == 32) ||
465           (Size == 64 && VT->getNumElements() == 1))
466         return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
467                                                             Size));
468 
469       return ABIArgInfo::getIndirect(0);
470     }
471 
472     return ABIArgInfo::getDirect();
473   }
474 
475   if (isAggregateTypeForABI(RetTy)) {
476     if (const RecordType *RT = RetTy->getAs<RecordType>()) {
477       // Structures with either a non-trivial destructor or a non-trivial
478       // copy constructor are always indirect.
479       if (hasNonTrivialDestructorOrCopyConstructor(RT))
480         return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
481 
482       // Structures with flexible arrays are always indirect.
483       if (RT->getDecl()->hasFlexibleArrayMember())
484         return ABIArgInfo::getIndirect(0);
485     }
486 
487     // If specified, structs and unions are always indirect.
488     if (!IsSmallStructInRegABI && !RetTy->isAnyComplexType())
489       return ABIArgInfo::getIndirect(0);
490 
491     // Classify "single element" structs as their element type.
492     if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext())) {
493       if (const BuiltinType *BT = SeltTy->getAs<BuiltinType>()) {
494         if (BT->isIntegerType()) {
495           // We need to use the size of the structure, padding
496           // bit-fields can adjust that to be larger than the single
497           // element type.
498           uint64_t Size = getContext().getTypeSize(RetTy);
499           return ABIArgInfo::getDirect(
500             llvm::IntegerType::get(getVMContext(), (unsigned)Size));
501         }
502 
503         if (BT->getKind() == BuiltinType::Float) {
504           assert(getContext().getTypeSize(RetTy) ==
505                  getContext().getTypeSize(SeltTy) &&
506                  "Unexpect single element structure size!");
507           return ABIArgInfo::getDirect(llvm::Type::getFloatTy(getVMContext()));
508         }
509 
510         if (BT->getKind() == BuiltinType::Double) {
511           assert(getContext().getTypeSize(RetTy) ==
512                  getContext().getTypeSize(SeltTy) &&
513                  "Unexpect single element structure size!");
514           return ABIArgInfo::getDirect(llvm::Type::getDoubleTy(getVMContext()));
515         }
516       } else if (SeltTy->isPointerType()) {
517         // FIXME: It would be really nice if this could come out as the proper
518         // pointer type.
519         const llvm::Type *PtrTy = llvm::Type::getInt8PtrTy(getVMContext());
520         return ABIArgInfo::getDirect(PtrTy);
521       } else if (SeltTy->isVectorType()) {
522         // 64- and 128-bit vectors are never returned in a
523         // register when inside a structure.
524         uint64_t Size = getContext().getTypeSize(RetTy);
525         if (Size == 64 || Size == 128)
526           return ABIArgInfo::getIndirect(0);
527 
528         return classifyReturnType(QualType(SeltTy, 0));
529       }
530     }
531 
532     // Small structures which are register sized are generally returned
533     // in a register.
534     if (X86_32ABIInfo::shouldReturnTypeInRegister(RetTy, getContext())) {
535       uint64_t Size = getContext().getTypeSize(RetTy);
536       return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
537     }
538 
539     return ABIArgInfo::getIndirect(0);
540   }
541 
542   // Treat an enum type as its underlying type.
543   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
544     RetTy = EnumTy->getDecl()->getIntegerType();
545 
546   return (RetTy->isPromotableIntegerType() ?
547           ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
548 }
549 
550 ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal) const {
551   if (!ByVal)
552     return ABIArgInfo::getIndirect(0, false);
553 
554   // Compute the byval alignment. We trust the back-end to honor the
555   // minimum ABI alignment for byval, to make cleaner IR.
556   const unsigned MinABIAlign = 4;
557   unsigned Align = getContext().getTypeAlign(Ty) / 8;
558   if (Align > MinABIAlign)
559     return ABIArgInfo::getIndirect(Align);
560   return ABIArgInfo::getIndirect(0);
561 }
562 
563 ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty) const {
564   // FIXME: Set alignment on indirect arguments.
565   if (isAggregateTypeForABI(Ty)) {
566     // Structures with flexible arrays are always indirect.
567     if (const RecordType *RT = Ty->getAs<RecordType>()) {
568       // Structures with either a non-trivial destructor or a non-trivial
569       // copy constructor are always indirect.
570       if (hasNonTrivialDestructorOrCopyConstructor(RT))
571         return getIndirectResult(Ty, /*ByVal=*/false);
572 
573       if (RT->getDecl()->hasFlexibleArrayMember())
574         return getIndirectResult(Ty);
575     }
576 
577     // Ignore empty structs.
578     if (Ty->isStructureType() && getContext().getTypeSize(Ty) == 0)
579       return ABIArgInfo::getIgnore();
580 
581     // Expand small (<= 128-bit) record types when we know that the stack layout
582     // of those arguments will match the struct. This is important because the
583     // LLVM backend isn't smart enough to remove byval, which inhibits many
584     // optimizations.
585     if (getContext().getTypeSize(Ty) <= 4*32 &&
586         canExpandIndirectArgument(Ty, getContext()))
587       return ABIArgInfo::getExpand();
588 
589     return getIndirectResult(Ty);
590   }
591 
592   if (const VectorType *VT = Ty->getAs<VectorType>()) {
593     // On Darwin, some vectors are passed in memory, we handle this by passing
594     // it as an i8/i16/i32/i64.
595     if (IsDarwinVectorABI) {
596       uint64_t Size = getContext().getTypeSize(Ty);
597       if ((Size == 8 || Size == 16 || Size == 32) ||
598           (Size == 64 && VT->getNumElements() == 1))
599         return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
600                                                             Size));
601     }
602 
603     return ABIArgInfo::getDirect();
604   }
605 
606 
607   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
608     Ty = EnumTy->getDecl()->getIntegerType();
609 
610   return (Ty->isPromotableIntegerType() ?
611           ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
612 }
613 
614 llvm::Value *X86_32ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
615                                       CodeGenFunction &CGF) const {
616   const llvm::Type *BP = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
617   const llvm::Type *BPP = llvm::PointerType::getUnqual(BP);
618 
619   CGBuilderTy &Builder = CGF.Builder;
620   llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
621                                                        "ap");
622   llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
623   llvm::Type *PTy =
624     llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
625   llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
626 
627   uint64_t Offset =
628     llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 4);
629   llvm::Value *NextAddr =
630     Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
631                       "ap.next");
632   Builder.CreateStore(NextAddr, VAListAddrAsBPP);
633 
634   return AddrTyped;
635 }
636 
637 void X86_32TargetCodeGenInfo::SetTargetAttributes(const Decl *D,
638                                                   llvm::GlobalValue *GV,
639                                             CodeGen::CodeGenModule &CGM) const {
640   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
641     if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
642       // Get the LLVM function.
643       llvm::Function *Fn = cast<llvm::Function>(GV);
644 
645       // Now add the 'alignstack' attribute with a value of 16.
646       Fn->addFnAttr(llvm::Attribute::constructStackAlignmentFromInt(16));
647     }
648   }
649 }
650 
651 bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
652                                                CodeGen::CodeGenFunction &CGF,
653                                                llvm::Value *Address) const {
654   CodeGen::CGBuilderTy &Builder = CGF.Builder;
655   llvm::LLVMContext &Context = CGF.getLLVMContext();
656 
657   const llvm::IntegerType *i8 = llvm::Type::getInt8Ty(Context);
658   llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
659 
660   // 0-7 are the eight integer registers;  the order is different
661   //   on Darwin (for EH), but the range is the same.
662   // 8 is %eip.
663   AssignToArrayRange(Builder, Address, Four8, 0, 8);
664 
665   if (CGF.CGM.isTargetDarwin()) {
666     // 12-16 are st(0..4).  Not sure why we stop at 4.
667     // These have size 16, which is sizeof(long double) on
668     // platforms with 8-byte alignment for that type.
669     llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
670     AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
671 
672   } else {
673     // 9 is %eflags, which doesn't get a size on Darwin for some
674     // reason.
675     Builder.CreateStore(Four8, Builder.CreateConstInBoundsGEP1_32(Address, 9));
676 
677     // 11-16 are st(0..5).  Not sure why we stop at 5.
678     // These have size 12, which is sizeof(long double) on
679     // platforms with 4-byte alignment for that type.
680     llvm::Value *Twelve8 = llvm::ConstantInt::get(i8, 12);
681     AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
682   }
683 
684   return false;
685 }
686 
687 //===----------------------------------------------------------------------===//
688 // X86-64 ABI Implementation
689 //===----------------------------------------------------------------------===//
690 
691 
692 namespace {
693 /// X86_64ABIInfo - The X86_64 ABI information.
694 class X86_64ABIInfo : public ABIInfo {
695   enum Class {
696     Integer = 0,
697     SSE,
698     SSEUp,
699     X87,
700     X87Up,
701     ComplexX87,
702     NoClass,
703     Memory
704   };
705 
706   /// merge - Implement the X86_64 ABI merging algorithm.
707   ///
708   /// Merge an accumulating classification \arg Accum with a field
709   /// classification \arg Field.
710   ///
711   /// \param Accum - The accumulating classification. This should
712   /// always be either NoClass or the result of a previous merge
713   /// call. In addition, this should never be Memory (the caller
714   /// should just return Memory for the aggregate).
715   static Class merge(Class Accum, Class Field);
716 
717   /// classify - Determine the x86_64 register classes in which the
718   /// given type T should be passed.
719   ///
720   /// \param Lo - The classification for the parts of the type
721   /// residing in the low word of the containing object.
722   ///
723   /// \param Hi - The classification for the parts of the type
724   /// residing in the high word of the containing object.
725   ///
726   /// \param OffsetBase - The bit offset of this type in the
727   /// containing object.  Some parameters are classified different
728   /// depending on whether they straddle an eightbyte boundary.
729   ///
730   /// If a word is unused its result will be NoClass; if a type should
731   /// be passed in Memory then at least the classification of \arg Lo
732   /// will be Memory.
733   ///
734   /// The \arg Lo class will be NoClass iff the argument is ignored.
735   ///
736   /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
737   /// also be ComplexX87.
738   void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi) const;
739 
740   const llvm::Type *Get16ByteVectorType(QualType Ty) const;
741   const llvm::Type *GetSSETypeAtOffset(const llvm::Type *IRType,
742                                        unsigned IROffset, QualType SourceTy,
743                                        unsigned SourceOffset) const;
744   const llvm::Type *GetINTEGERTypeAtOffset(const llvm::Type *IRType,
745                                            unsigned IROffset, QualType SourceTy,
746                                            unsigned SourceOffset) const;
747 
748   /// getIndirectResult - Give a source type \arg Ty, return a suitable result
749   /// such that the argument will be returned in memory.
750   ABIArgInfo getIndirectReturnResult(QualType Ty) const;
751 
752   /// getIndirectResult - Give a source type \arg Ty, return a suitable result
753   /// such that the argument will be passed in memory.
754   ABIArgInfo getIndirectResult(QualType Ty) const;
755 
756   ABIArgInfo classifyReturnType(QualType RetTy) const;
757 
758   ABIArgInfo classifyArgumentType(QualType Ty, unsigned &neededInt,
759                                   unsigned &neededSSE) const;
760 
761 public:
762   X86_64ABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
763 
764   virtual void computeInfo(CGFunctionInfo &FI) const;
765 
766   virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
767                                  CodeGenFunction &CGF) const;
768 };
769 
770 /// WinX86_64ABIInfo - The Windows X86_64 ABI information.
771 class WinX86_64ABIInfo : public X86_64ABIInfo {
772 public:
773   WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT) : X86_64ABIInfo(CGT) {}
774 
775   virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
776                                  CodeGenFunction &CGF) const;
777 };
778 
779 class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
780 public:
781   X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
782     : TargetCodeGenInfo(new X86_64ABIInfo(CGT)) {}
783 
784   int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const {
785     return 7;
786   }
787 
788   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
789                                llvm::Value *Address) const {
790     CodeGen::CGBuilderTy &Builder = CGF.Builder;
791     llvm::LLVMContext &Context = CGF.getLLVMContext();
792 
793     const llvm::IntegerType *i8 = llvm::Type::getInt8Ty(Context);
794     llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
795 
796     // 0-15 are the 16 integer registers.
797     // 16 is %rip.
798     AssignToArrayRange(Builder, Address, Eight8, 0, 16);
799 
800     return false;
801   }
802 };
803 
804 class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
805 public:
806   WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
807     : TargetCodeGenInfo(new WinX86_64ABIInfo(CGT)) {}
808 
809   int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const {
810     return 7;
811   }
812 
813   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
814                                llvm::Value *Address) const {
815     CodeGen::CGBuilderTy &Builder = CGF.Builder;
816     llvm::LLVMContext &Context = CGF.getLLVMContext();
817 
818     const llvm::IntegerType *i8 = llvm::Type::getInt8Ty(Context);
819     llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
820 
821     // 0-15 are the 16 integer registers.
822     // 16 is %rip.
823     AssignToArrayRange(Builder, Address, Eight8, 0, 16);
824 
825     return false;
826   }
827 };
828 
829 }
830 
831 X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
832   // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
833   // classified recursively so that always two fields are
834   // considered. The resulting class is calculated according to
835   // the classes of the fields in the eightbyte:
836   //
837   // (a) If both classes are equal, this is the resulting class.
838   //
839   // (b) If one of the classes is NO_CLASS, the resulting class is
840   // the other class.
841   //
842   // (c) If one of the classes is MEMORY, the result is the MEMORY
843   // class.
844   //
845   // (d) If one of the classes is INTEGER, the result is the
846   // INTEGER.
847   //
848   // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
849   // MEMORY is used as class.
850   //
851   // (f) Otherwise class SSE is used.
852 
853   // Accum should never be memory (we should have returned) or
854   // ComplexX87 (because this cannot be passed in a structure).
855   assert((Accum != Memory && Accum != ComplexX87) &&
856          "Invalid accumulated classification during merge.");
857   if (Accum == Field || Field == NoClass)
858     return Accum;
859   if (Field == Memory)
860     return Memory;
861   if (Accum == NoClass)
862     return Field;
863   if (Accum == Integer || Field == Integer)
864     return Integer;
865   if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
866       Accum == X87 || Accum == X87Up)
867     return Memory;
868   return SSE;
869 }
870 
871 void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
872                              Class &Lo, Class &Hi) const {
873   // FIXME: This code can be simplified by introducing a simple value class for
874   // Class pairs with appropriate constructor methods for the various
875   // situations.
876 
877   // FIXME: Some of the split computations are wrong; unaligned vectors
878   // shouldn't be passed in registers for example, so there is no chance they
879   // can straddle an eightbyte. Verify & simplify.
880 
881   Lo = Hi = NoClass;
882 
883   Class &Current = OffsetBase < 64 ? Lo : Hi;
884   Current = Memory;
885 
886   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
887     BuiltinType::Kind k = BT->getKind();
888 
889     if (k == BuiltinType::Void) {
890       Current = NoClass;
891     } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
892       Lo = Integer;
893       Hi = Integer;
894     } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
895       Current = Integer;
896     } else if (k == BuiltinType::Float || k == BuiltinType::Double) {
897       Current = SSE;
898     } else if (k == BuiltinType::LongDouble) {
899       Lo = X87;
900       Hi = X87Up;
901     }
902     // FIXME: _Decimal32 and _Decimal64 are SSE.
903     // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
904     return;
905   }
906 
907   if (const EnumType *ET = Ty->getAs<EnumType>()) {
908     // Classify the underlying integer type.
909     classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi);
910     return;
911   }
912 
913   if (Ty->hasPointerRepresentation()) {
914     Current = Integer;
915     return;
916   }
917 
918   if (Ty->isMemberPointerType()) {
919     if (Ty->isMemberFunctionPointerType())
920       Lo = Hi = Integer;
921     else
922       Current = Integer;
923     return;
924   }
925 
926   if (const VectorType *VT = Ty->getAs<VectorType>()) {
927     uint64_t Size = getContext().getTypeSize(VT);
928     if (Size == 32) {
929       // gcc passes all <4 x char>, <2 x short>, <1 x int>, <1 x
930       // float> as integer.
931       Current = Integer;
932 
933       // If this type crosses an eightbyte boundary, it should be
934       // split.
935       uint64_t EB_Real = (OffsetBase) / 64;
936       uint64_t EB_Imag = (OffsetBase + Size - 1) / 64;
937       if (EB_Real != EB_Imag)
938         Hi = Lo;
939     } else if (Size == 64) {
940       // gcc passes <1 x double> in memory. :(
941       if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double))
942         return;
943 
944       // gcc passes <1 x long long> as INTEGER.
945       if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::LongLong) ||
946           VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULongLong) ||
947           VT->getElementType()->isSpecificBuiltinType(BuiltinType::Long) ||
948           VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULong))
949         Current = Integer;
950       else
951         Current = SSE;
952 
953       // If this type crosses an eightbyte boundary, it should be
954       // split.
955       if (OffsetBase && OffsetBase != 64)
956         Hi = Lo;
957     } else if (Size == 128) {
958       Lo = SSE;
959       Hi = SSEUp;
960     }
961     return;
962   }
963 
964   if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
965     QualType ET = getContext().getCanonicalType(CT->getElementType());
966 
967     uint64_t Size = getContext().getTypeSize(Ty);
968     if (ET->isIntegralOrEnumerationType()) {
969       if (Size <= 64)
970         Current = Integer;
971       else if (Size <= 128)
972         Lo = Hi = Integer;
973     } else if (ET == getContext().FloatTy)
974       Current = SSE;
975     else if (ET == getContext().DoubleTy)
976       Lo = Hi = SSE;
977     else if (ET == getContext().LongDoubleTy)
978       Current = ComplexX87;
979 
980     // If this complex type crosses an eightbyte boundary then it
981     // should be split.
982     uint64_t EB_Real = (OffsetBase) / 64;
983     uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
984     if (Hi == NoClass && EB_Real != EB_Imag)
985       Hi = Lo;
986 
987     return;
988   }
989 
990   if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
991     // Arrays are treated like structures.
992 
993     uint64_t Size = getContext().getTypeSize(Ty);
994 
995     // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
996     // than two eightbytes, ..., it has class MEMORY.
997     if (Size > 128)
998       return;
999 
1000     // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
1001     // fields, it has class MEMORY.
1002     //
1003     // Only need to check alignment of array base.
1004     if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
1005       return;
1006 
1007     // Otherwise implement simplified merge. We could be smarter about
1008     // this, but it isn't worth it and would be harder to verify.
1009     Current = NoClass;
1010     uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
1011     uint64_t ArraySize = AT->getSize().getZExtValue();
1012     for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
1013       Class FieldLo, FieldHi;
1014       classify(AT->getElementType(), Offset, FieldLo, FieldHi);
1015       Lo = merge(Lo, FieldLo);
1016       Hi = merge(Hi, FieldHi);
1017       if (Lo == Memory || Hi == Memory)
1018         break;
1019     }
1020 
1021     // Do post merger cleanup (see below). Only case we worry about is Memory.
1022     if (Hi == Memory)
1023       Lo = Memory;
1024     assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
1025     return;
1026   }
1027 
1028   if (const RecordType *RT = Ty->getAs<RecordType>()) {
1029     uint64_t Size = getContext().getTypeSize(Ty);
1030 
1031     // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
1032     // than two eightbytes, ..., it has class MEMORY.
1033     if (Size > 128)
1034       return;
1035 
1036     // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
1037     // copy constructor or a non-trivial destructor, it is passed by invisible
1038     // reference.
1039     if (hasNonTrivialDestructorOrCopyConstructor(RT))
1040       return;
1041 
1042     const RecordDecl *RD = RT->getDecl();
1043 
1044     // Assume variable sized types are passed in memory.
1045     if (RD->hasFlexibleArrayMember())
1046       return;
1047 
1048     const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
1049 
1050     // Reset Lo class, this will be recomputed.
1051     Current = NoClass;
1052 
1053     // If this is a C++ record, classify the bases first.
1054     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
1055       for (CXXRecordDecl::base_class_const_iterator i = CXXRD->bases_begin(),
1056              e = CXXRD->bases_end(); i != e; ++i) {
1057         assert(!i->isVirtual() && !i->getType()->isDependentType() &&
1058                "Unexpected base class!");
1059         const CXXRecordDecl *Base =
1060           cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
1061 
1062         // Classify this field.
1063         //
1064         // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
1065         // single eightbyte, each is classified separately. Each eightbyte gets
1066         // initialized to class NO_CLASS.
1067         Class FieldLo, FieldHi;
1068         uint64_t Offset = OffsetBase + Layout.getBaseClassOffset(Base);
1069         classify(i->getType(), Offset, FieldLo, FieldHi);
1070         Lo = merge(Lo, FieldLo);
1071         Hi = merge(Hi, FieldHi);
1072         if (Lo == Memory || Hi == Memory)
1073           break;
1074       }
1075     }
1076 
1077     // Classify the fields one at a time, merging the results.
1078     unsigned idx = 0;
1079     for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
1080            i != e; ++i, ++idx) {
1081       uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
1082       bool BitField = i->isBitField();
1083 
1084       // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
1085       // fields, it has class MEMORY.
1086       //
1087       // Note, skip this test for bit-fields, see below.
1088       if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
1089         Lo = Memory;
1090         return;
1091       }
1092 
1093       // Classify this field.
1094       //
1095       // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
1096       // exceeds a single eightbyte, each is classified
1097       // separately. Each eightbyte gets initialized to class
1098       // NO_CLASS.
1099       Class FieldLo, FieldHi;
1100 
1101       // Bit-fields require special handling, they do not force the
1102       // structure to be passed in memory even if unaligned, and
1103       // therefore they can straddle an eightbyte.
1104       if (BitField) {
1105         // Ignore padding bit-fields.
1106         if (i->isUnnamedBitfield())
1107           continue;
1108 
1109         uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
1110         uint64_t Size =
1111           i->getBitWidth()->EvaluateAsInt(getContext()).getZExtValue();
1112 
1113         uint64_t EB_Lo = Offset / 64;
1114         uint64_t EB_Hi = (Offset + Size - 1) / 64;
1115         FieldLo = FieldHi = NoClass;
1116         if (EB_Lo) {
1117           assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
1118           FieldLo = NoClass;
1119           FieldHi = Integer;
1120         } else {
1121           FieldLo = Integer;
1122           FieldHi = EB_Hi ? Integer : NoClass;
1123         }
1124       } else
1125         classify(i->getType(), Offset, FieldLo, FieldHi);
1126       Lo = merge(Lo, FieldLo);
1127       Hi = merge(Hi, FieldHi);
1128       if (Lo == Memory || Hi == Memory)
1129         break;
1130     }
1131 
1132     // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
1133     //
1134     // (a) If one of the classes is MEMORY, the whole argument is
1135     // passed in memory.
1136     //
1137     // (b) If SSEUP is not preceeded by SSE, it is converted to SSE.
1138 
1139     // The first of these conditions is guaranteed by how we implement
1140     // the merge (just bail).
1141     //
1142     // The second condition occurs in the case of unions; for example
1143     // union { _Complex double; unsigned; }.
1144     if (Hi == Memory)
1145       Lo = Memory;
1146     if (Hi == SSEUp && Lo != SSE)
1147       Hi = SSE;
1148   }
1149 }
1150 
1151 ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
1152   // If this is a scalar LLVM value then assume LLVM will pass it in the right
1153   // place naturally.
1154   if (!isAggregateTypeForABI(Ty)) {
1155     // Treat an enum type as its underlying type.
1156     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1157       Ty = EnumTy->getDecl()->getIntegerType();
1158 
1159     return (Ty->isPromotableIntegerType() ?
1160             ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
1161   }
1162 
1163   return ABIArgInfo::getIndirect(0);
1164 }
1165 
1166 ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty) const {
1167   // If this is a scalar LLVM value then assume LLVM will pass it in the right
1168   // place naturally.
1169   if (!isAggregateTypeForABI(Ty)) {
1170     // Treat an enum type as its underlying type.
1171     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1172       Ty = EnumTy->getDecl()->getIntegerType();
1173 
1174     return (Ty->isPromotableIntegerType() ?
1175             ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
1176   }
1177 
1178   if (isRecordWithNonTrivialDestructorOrCopyConstructor(Ty))
1179     return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
1180 
1181   // Compute the byval alignment. We trust the back-end to honor the
1182   // minimum ABI alignment for byval, to make cleaner IR.
1183   const unsigned MinABIAlign = 8;
1184   unsigned Align = getContext().getTypeAlign(Ty) / 8;
1185   if (Align > MinABIAlign)
1186     return ABIArgInfo::getIndirect(Align);
1187   return ABIArgInfo::getIndirect(0);
1188 }
1189 
1190 /// Get16ByteVectorType - The ABI specifies that a value should be passed in an
1191 /// full vector XMM register.  Pick an LLVM IR type that will be passed as a
1192 /// vector register.
1193 const llvm::Type *X86_64ABIInfo::Get16ByteVectorType(QualType Ty) const {
1194   const llvm::Type *IRType = CGT.ConvertTypeRecursive(Ty);
1195 
1196   // Wrapper structs that just contain vectors are passed just like vectors,
1197   // strip them off if present.
1198   const llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType);
1199   while (STy && STy->getNumElements() == 1) {
1200     IRType = STy->getElementType(0);
1201     STy = dyn_cast<llvm::StructType>(IRType);
1202   }
1203 
1204   // If the preferred type is a 16-byte vector, prefer to pass it.
1205   if (const llvm::VectorType *VT = dyn_cast<llvm::VectorType>(IRType)){
1206     const llvm::Type *EltTy = VT->getElementType();
1207     if (VT->getBitWidth() == 128 &&
1208         (EltTy->isFloatTy() || EltTy->isDoubleTy() ||
1209          EltTy->isIntegerTy(8) || EltTy->isIntegerTy(16) ||
1210          EltTy->isIntegerTy(32) || EltTy->isIntegerTy(64) ||
1211          EltTy->isIntegerTy(128)))
1212       return VT;
1213   }
1214 
1215   return llvm::VectorType::get(llvm::Type::getDoubleTy(getVMContext()), 2);
1216 }
1217 
1218 /// BitsContainNoUserData - Return true if the specified [start,end) bit range
1219 /// is known to either be off the end of the specified type or being in
1220 /// alignment padding.  The user type specified is known to be at most 128 bits
1221 /// in size, and have passed through X86_64ABIInfo::classify with a successful
1222 /// classification that put one of the two halves in the INTEGER class.
1223 ///
1224 /// It is conservatively correct to return false.
1225 static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
1226                                   unsigned EndBit, ASTContext &Context) {
1227   // If the bytes being queried are off the end of the type, there is no user
1228   // data hiding here.  This handles analysis of builtins, vectors and other
1229   // types that don't contain interesting padding.
1230   unsigned TySize = (unsigned)Context.getTypeSize(Ty);
1231   if (TySize <= StartBit)
1232     return true;
1233 
1234   if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
1235     unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
1236     unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
1237 
1238     // Check each element to see if the element overlaps with the queried range.
1239     for (unsigned i = 0; i != NumElts; ++i) {
1240       // If the element is after the span we care about, then we're done..
1241       unsigned EltOffset = i*EltSize;
1242       if (EltOffset >= EndBit) break;
1243 
1244       unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
1245       if (!BitsContainNoUserData(AT->getElementType(), EltStart,
1246                                  EndBit-EltOffset, Context))
1247         return false;
1248     }
1249     // If it overlaps no elements, then it is safe to process as padding.
1250     return true;
1251   }
1252 
1253   if (const RecordType *RT = Ty->getAs<RecordType>()) {
1254     const RecordDecl *RD = RT->getDecl();
1255     const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1256 
1257     // If this is a C++ record, check the bases first.
1258     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
1259       for (CXXRecordDecl::base_class_const_iterator i = CXXRD->bases_begin(),
1260            e = CXXRD->bases_end(); i != e; ++i) {
1261         assert(!i->isVirtual() && !i->getType()->isDependentType() &&
1262                "Unexpected base class!");
1263         const CXXRecordDecl *Base =
1264           cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
1265 
1266         // If the base is after the span we care about, ignore it.
1267         unsigned BaseOffset = (unsigned)Layout.getBaseClassOffset(Base);
1268         if (BaseOffset >= EndBit) continue;
1269 
1270         unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
1271         if (!BitsContainNoUserData(i->getType(), BaseStart,
1272                                    EndBit-BaseOffset, Context))
1273           return false;
1274       }
1275     }
1276 
1277     // Verify that no field has data that overlaps the region of interest.  Yes
1278     // this could be sped up a lot by being smarter about queried fields,
1279     // however we're only looking at structs up to 16 bytes, so we don't care
1280     // much.
1281     unsigned idx = 0;
1282     for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
1283          i != e; ++i, ++idx) {
1284       unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
1285 
1286       // If we found a field after the region we care about, then we're done.
1287       if (FieldOffset >= EndBit) break;
1288 
1289       unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
1290       if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
1291                                  Context))
1292         return false;
1293     }
1294 
1295     // If nothing in this record overlapped the area of interest, then we're
1296     // clean.
1297     return true;
1298   }
1299 
1300   return false;
1301 }
1302 
1303 /// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a
1304 /// float member at the specified offset.  For example, {int,{float}} has a
1305 /// float at offset 4.  It is conservatively correct for this routine to return
1306 /// false.
1307 static bool ContainsFloatAtOffset(const llvm::Type *IRType, unsigned IROffset,
1308                                   const llvm::TargetData &TD) {
1309   // Base case if we find a float.
1310   if (IROffset == 0 && IRType->isFloatTy())
1311     return true;
1312 
1313   // If this is a struct, recurse into the field at the specified offset.
1314   if (const llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
1315     const llvm::StructLayout *SL = TD.getStructLayout(STy);
1316     unsigned Elt = SL->getElementContainingOffset(IROffset);
1317     IROffset -= SL->getElementOffset(Elt);
1318     return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD);
1319   }
1320 
1321   // If this is an array, recurse into the field at the specified offset.
1322   if (const llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
1323     const llvm::Type *EltTy = ATy->getElementType();
1324     unsigned EltSize = TD.getTypeAllocSize(EltTy);
1325     IROffset -= IROffset/EltSize*EltSize;
1326     return ContainsFloatAtOffset(EltTy, IROffset, TD);
1327   }
1328 
1329   return false;
1330 }
1331 
1332 
1333 /// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
1334 /// low 8 bytes of an XMM register, corresponding to the SSE class.
1335 const llvm::Type *X86_64ABIInfo::
1336 GetSSETypeAtOffset(const llvm::Type *IRType, unsigned IROffset,
1337                    QualType SourceTy, unsigned SourceOffset) const {
1338   // The only three choices we have are either double, <2 x float>, or float. We
1339   // pass as float if the last 4 bytes is just padding.  This happens for
1340   // structs that contain 3 floats.
1341   if (BitsContainNoUserData(SourceTy, SourceOffset*8+32,
1342                             SourceOffset*8+64, getContext()))
1343     return llvm::Type::getFloatTy(getVMContext());
1344 
1345   // We want to pass as <2 x float> if the LLVM IR type contains a float at
1346   // offset+0 and offset+4.  Walk the LLVM IR type to find out if this is the
1347   // case.
1348   if (ContainsFloatAtOffset(IRType, IROffset, getTargetData()) &&
1349       ContainsFloatAtOffset(IRType, IROffset+4, getTargetData()))
1350     return llvm::VectorType::get(llvm::Type::getFloatTy(getVMContext()), 2);
1351 
1352   return llvm::Type::getDoubleTy(getVMContext());
1353 }
1354 
1355 
1356 /// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
1357 /// an 8-byte GPR.  This means that we either have a scalar or we are talking
1358 /// about the high or low part of an up-to-16-byte struct.  This routine picks
1359 /// the best LLVM IR type to represent this, which may be i64 or may be anything
1360 /// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
1361 /// etc).
1362 ///
1363 /// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
1364 /// the source type.  IROffset is an offset in bytes into the LLVM IR type that
1365 /// the 8-byte value references.  PrefType may be null.
1366 ///
1367 /// SourceTy is the source level type for the entire argument.  SourceOffset is
1368 /// an offset into this that we're processing (which is always either 0 or 8).
1369 ///
1370 const llvm::Type *X86_64ABIInfo::
1371 GetINTEGERTypeAtOffset(const llvm::Type *IRType, unsigned IROffset,
1372                        QualType SourceTy, unsigned SourceOffset) const {
1373   // If we're dealing with an un-offset LLVM IR type, then it means that we're
1374   // returning an 8-byte unit starting with it.  See if we can safely use it.
1375   if (IROffset == 0) {
1376     // Pointers and int64's always fill the 8-byte unit.
1377     if (isa<llvm::PointerType>(IRType) || IRType->isIntegerTy(64))
1378       return IRType;
1379 
1380     // If we have a 1/2/4-byte integer, we can use it only if the rest of the
1381     // goodness in the source type is just tail padding.  This is allowed to
1382     // kick in for struct {double,int} on the int, but not on
1383     // struct{double,int,int} because we wouldn't return the second int.  We
1384     // have to do this analysis on the source type because we can't depend on
1385     // unions being lowered a specific way etc.
1386     if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
1387         IRType->isIntegerTy(32)) {
1388       unsigned BitWidth = cast<llvm::IntegerType>(IRType)->getBitWidth();
1389 
1390       if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
1391                                 SourceOffset*8+64, getContext()))
1392         return IRType;
1393     }
1394   }
1395 
1396   if (const llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
1397     // If this is a struct, recurse into the field at the specified offset.
1398     const llvm::StructLayout *SL = getTargetData().getStructLayout(STy);
1399     if (IROffset < SL->getSizeInBytes()) {
1400       unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
1401       IROffset -= SL->getElementOffset(FieldIdx);
1402 
1403       return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
1404                                     SourceTy, SourceOffset);
1405     }
1406   }
1407 
1408   if (const llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
1409     const llvm::Type *EltTy = ATy->getElementType();
1410     unsigned EltSize = getTargetData().getTypeAllocSize(EltTy);
1411     unsigned EltOffset = IROffset/EltSize*EltSize;
1412     return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
1413                                   SourceOffset);
1414   }
1415 
1416   // Okay, we don't have any better idea of what to pass, so we pass this in an
1417   // integer register that isn't too big to fit the rest of the struct.
1418   unsigned TySizeInBytes =
1419     (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
1420 
1421   assert(TySizeInBytes != SourceOffset && "Empty field?");
1422 
1423   // It is always safe to classify this as an integer type up to i64 that
1424   // isn't larger than the structure.
1425   return llvm::IntegerType::get(getVMContext(),
1426                                 std::min(TySizeInBytes-SourceOffset, 8U)*8);
1427 }
1428 
1429 
1430 /// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
1431 /// be used as elements of a two register pair to pass or return, return a
1432 /// first class aggregate to represent them.  For example, if the low part of
1433 /// a by-value argument should be passed as i32* and the high part as float,
1434 /// return {i32*, float}.
1435 static const llvm::Type *
1436 GetX86_64ByValArgumentPair(const llvm::Type *Lo, const llvm::Type *Hi,
1437                            const llvm::TargetData &TD) {
1438   // In order to correctly satisfy the ABI, we need to the high part to start
1439   // at offset 8.  If the high and low parts we inferred are both 4-byte types
1440   // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
1441   // the second element at offset 8.  Check for this:
1442   unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
1443   unsigned HiAlign = TD.getABITypeAlignment(Hi);
1444   unsigned HiStart = llvm::TargetData::RoundUpAlignment(LoSize, HiAlign);
1445   assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
1446 
1447   // To handle this, we have to increase the size of the low part so that the
1448   // second element will start at an 8 byte offset.  We can't increase the size
1449   // of the second element because it might make us access off the end of the
1450   // struct.
1451   if (HiStart != 8) {
1452     // There are only two sorts of types the ABI generation code can produce for
1453     // the low part of a pair that aren't 8 bytes in size: float or i8/i16/i32.
1454     // Promote these to a larger type.
1455     if (Lo->isFloatTy())
1456       Lo = llvm::Type::getDoubleTy(Lo->getContext());
1457     else {
1458       assert(Lo->isIntegerTy() && "Invalid/unknown lo type");
1459       Lo = llvm::Type::getInt64Ty(Lo->getContext());
1460     }
1461   }
1462 
1463   const llvm::StructType *Result =
1464     llvm::StructType::get(Lo->getContext(), Lo, Hi, NULL);
1465 
1466 
1467   // Verify that the second element is at an 8-byte offset.
1468   assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
1469          "Invalid x86-64 argument pair!");
1470   return Result;
1471 }
1472 
1473 ABIArgInfo X86_64ABIInfo::
1474 classifyReturnType(QualType RetTy) const {
1475   // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
1476   // classification algorithm.
1477   X86_64ABIInfo::Class Lo, Hi;
1478   classify(RetTy, 0, Lo, Hi);
1479 
1480   // Check some invariants.
1481   assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
1482   assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
1483 
1484   const llvm::Type *ResType = 0;
1485   switch (Lo) {
1486   case NoClass:
1487     if (Hi == NoClass)
1488       return ABIArgInfo::getIgnore();
1489     // If the low part is just padding, it takes no register, leave ResType
1490     // null.
1491     assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
1492            "Unknown missing lo part");
1493     break;
1494 
1495   case SSEUp:
1496   case X87Up:
1497     assert(0 && "Invalid classification for lo word.");
1498 
1499     // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
1500     // hidden argument.
1501   case Memory:
1502     return getIndirectReturnResult(RetTy);
1503 
1504     // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
1505     // available register of the sequence %rax, %rdx is used.
1506   case Integer:
1507     ResType = GetINTEGERTypeAtOffset(CGT.ConvertTypeRecursive(RetTy), 0,
1508                                      RetTy, 0);
1509 
1510     // If we have a sign or zero extended integer, make sure to return Extend
1511     // so that the parameter gets the right LLVM IR attributes.
1512     if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
1513       // Treat an enum type as its underlying type.
1514       if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
1515         RetTy = EnumTy->getDecl()->getIntegerType();
1516 
1517       if (RetTy->isIntegralOrEnumerationType() &&
1518           RetTy->isPromotableIntegerType())
1519         return ABIArgInfo::getExtend();
1520     }
1521     break;
1522 
1523     // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
1524     // available SSE register of the sequence %xmm0, %xmm1 is used.
1525   case SSE:
1526     ResType = GetSSETypeAtOffset(CGT.ConvertTypeRecursive(RetTy), 0, RetTy, 0);
1527     break;
1528 
1529     // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
1530     // returned on the X87 stack in %st0 as 80-bit x87 number.
1531   case X87:
1532     ResType = llvm::Type::getX86_FP80Ty(getVMContext());
1533     break;
1534 
1535     // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
1536     // part of the value is returned in %st0 and the imaginary part in
1537     // %st1.
1538   case ComplexX87:
1539     assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
1540     ResType = llvm::StructType::get(getVMContext(),
1541                                     llvm::Type::getX86_FP80Ty(getVMContext()),
1542                                     llvm::Type::getX86_FP80Ty(getVMContext()),
1543                                     NULL);
1544     break;
1545   }
1546 
1547   const llvm::Type *HighPart = 0;
1548   switch (Hi) {
1549     // Memory was handled previously and X87 should
1550     // never occur as a hi class.
1551   case Memory:
1552   case X87:
1553     assert(0 && "Invalid classification for hi word.");
1554 
1555   case ComplexX87: // Previously handled.
1556   case NoClass:
1557     break;
1558 
1559   case Integer:
1560     HighPart = GetINTEGERTypeAtOffset(CGT.ConvertTypeRecursive(RetTy),
1561                                       8, RetTy, 8);
1562     if (Lo == NoClass)  // Return HighPart at offset 8 in memory.
1563       return ABIArgInfo::getDirect(HighPart, 8);
1564     break;
1565   case SSE:
1566     HighPart = GetSSETypeAtOffset(CGT.ConvertTypeRecursive(RetTy), 8, RetTy, 8);
1567     if (Lo == NoClass)  // Return HighPart at offset 8 in memory.
1568       return ABIArgInfo::getDirect(HighPart, 8);
1569     break;
1570 
1571     // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
1572     // is passed in the upper half of the last used SSE register.
1573     //
1574     // SSEUP should always be preceeded by SSE, just widen.
1575   case SSEUp:
1576     assert(Lo == SSE && "Unexpected SSEUp classification.");
1577     ResType = Get16ByteVectorType(RetTy);
1578     break;
1579 
1580     // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
1581     // returned together with the previous X87 value in %st0.
1582   case X87Up:
1583     // If X87Up is preceeded by X87, we don't need to do
1584     // anything. However, in some cases with unions it may not be
1585     // preceeded by X87. In such situations we follow gcc and pass the
1586     // extra bits in an SSE reg.
1587     if (Lo != X87) {
1588       HighPart = GetSSETypeAtOffset(CGT.ConvertTypeRecursive(RetTy),
1589                                     8, RetTy, 8);
1590       if (Lo == NoClass)  // Return HighPart at offset 8 in memory.
1591         return ABIArgInfo::getDirect(HighPart, 8);
1592     }
1593     break;
1594   }
1595 
1596   // If a high part was specified, merge it together with the low part.  It is
1597   // known to pass in the high eightbyte of the result.  We do this by forming a
1598   // first class struct aggregate with the high and low part: {low, high}
1599   if (HighPart)
1600     ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getTargetData());
1601 
1602   return ABIArgInfo::getDirect(ResType);
1603 }
1604 
1605 ABIArgInfo X86_64ABIInfo::classifyArgumentType(QualType Ty, unsigned &neededInt,
1606                                                unsigned &neededSSE) const {
1607   X86_64ABIInfo::Class Lo, Hi;
1608   classify(Ty, 0, Lo, Hi);
1609 
1610   // Check some invariants.
1611   // FIXME: Enforce these by construction.
1612   assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
1613   assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
1614 
1615   neededInt = 0;
1616   neededSSE = 0;
1617   const llvm::Type *ResType = 0;
1618   switch (Lo) {
1619   case NoClass:
1620     if (Hi == NoClass)
1621       return ABIArgInfo::getIgnore();
1622     // If the low part is just padding, it takes no register, leave ResType
1623     // null.
1624     assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
1625            "Unknown missing lo part");
1626     break;
1627 
1628     // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
1629     // on the stack.
1630   case Memory:
1631 
1632     // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
1633     // COMPLEX_X87, it is passed in memory.
1634   case X87:
1635   case ComplexX87:
1636     return getIndirectResult(Ty);
1637 
1638   case SSEUp:
1639   case X87Up:
1640     assert(0 && "Invalid classification for lo word.");
1641 
1642     // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
1643     // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
1644     // and %r9 is used.
1645   case Integer:
1646     ++neededInt;
1647 
1648     // Pick an 8-byte type based on the preferred type.
1649     ResType = GetINTEGERTypeAtOffset(CGT.ConvertTypeRecursive(Ty), 0, Ty, 0);
1650 
1651     // If we have a sign or zero extended integer, make sure to return Extend
1652     // so that the parameter gets the right LLVM IR attributes.
1653     if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
1654       // Treat an enum type as its underlying type.
1655       if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1656         Ty = EnumTy->getDecl()->getIntegerType();
1657 
1658       if (Ty->isIntegralOrEnumerationType() &&
1659           Ty->isPromotableIntegerType())
1660         return ABIArgInfo::getExtend();
1661     }
1662 
1663     break;
1664 
1665     // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
1666     // available SSE register is used, the registers are taken in the
1667     // order from %xmm0 to %xmm7.
1668   case SSE:
1669     ++neededSSE;
1670     ResType = GetSSETypeAtOffset(CGT.ConvertTypeRecursive(Ty), 0, Ty, 0);
1671     break;
1672   }
1673 
1674   const llvm::Type *HighPart = 0;
1675   switch (Hi) {
1676     // Memory was handled previously, ComplexX87 and X87 should
1677     // never occur as hi classes, and X87Up must be preceed by X87,
1678     // which is passed in memory.
1679   case Memory:
1680   case X87:
1681   case ComplexX87:
1682     assert(0 && "Invalid classification for hi word.");
1683     break;
1684 
1685   case NoClass: break;
1686 
1687   case Integer:
1688     ++neededInt;
1689     // Pick an 8-byte type based on the preferred type.
1690     HighPart = GetINTEGERTypeAtOffset(CGT.ConvertTypeRecursive(Ty), 8, Ty, 8);
1691 
1692     if (Lo == NoClass)  // Pass HighPart at offset 8 in memory.
1693       return ABIArgInfo::getDirect(HighPart, 8);
1694     break;
1695 
1696     // X87Up generally doesn't occur here (long double is passed in
1697     // memory), except in situations involving unions.
1698   case X87Up:
1699   case SSE:
1700     HighPart = GetSSETypeAtOffset(CGT.ConvertTypeRecursive(Ty), 8, Ty, 8);
1701 
1702     if (Lo == NoClass)  // Pass HighPart at offset 8 in memory.
1703       return ABIArgInfo::getDirect(HighPart, 8);
1704 
1705     ++neededSSE;
1706     break;
1707 
1708     // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
1709     // eightbyte is passed in the upper half of the last used SSE
1710     // register.  This only happens when 128-bit vectors are passed.
1711   case SSEUp:
1712     assert(Lo == SSE && "Unexpected SSEUp classification");
1713     ResType = Get16ByteVectorType(Ty);
1714     break;
1715   }
1716 
1717   // If a high part was specified, merge it together with the low part.  It is
1718   // known to pass in the high eightbyte of the result.  We do this by forming a
1719   // first class struct aggregate with the high and low part: {low, high}
1720   if (HighPart)
1721     ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getTargetData());
1722 
1723   return ABIArgInfo::getDirect(ResType);
1724 }
1725 
1726 void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
1727 
1728   FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
1729 
1730   // Keep track of the number of assigned registers.
1731   unsigned freeIntRegs = 6, freeSSERegs = 8;
1732 
1733   // If the return value is indirect, then the hidden argument is consuming one
1734   // integer register.
1735   if (FI.getReturnInfo().isIndirect())
1736     --freeIntRegs;
1737 
1738   // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
1739   // get assigned (in left-to-right order) for passing as follows...
1740   for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
1741        it != ie; ++it) {
1742     unsigned neededInt, neededSSE;
1743     it->info = classifyArgumentType(it->type, neededInt, neededSSE);
1744 
1745     // AMD64-ABI 3.2.3p3: If there are no registers available for any
1746     // eightbyte of an argument, the whole argument is passed on the
1747     // stack. If registers have already been assigned for some
1748     // eightbytes of such an argument, the assignments get reverted.
1749     if (freeIntRegs >= neededInt && freeSSERegs >= neededSSE) {
1750       freeIntRegs -= neededInt;
1751       freeSSERegs -= neededSSE;
1752     } else {
1753       it->info = getIndirectResult(it->type);
1754     }
1755   }
1756 }
1757 
1758 static llvm::Value *EmitVAArgFromMemory(llvm::Value *VAListAddr,
1759                                         QualType Ty,
1760                                         CodeGenFunction &CGF) {
1761   llvm::Value *overflow_arg_area_p =
1762     CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_p");
1763   llvm::Value *overflow_arg_area =
1764     CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
1765 
1766   // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
1767   // byte boundary if alignment needed by type exceeds 8 byte boundary.
1768   uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8;
1769   if (Align > 8) {
1770     // Note that we follow the ABI & gcc here, even though the type
1771     // could in theory have an alignment greater than 16. This case
1772     // shouldn't ever matter in practice.
1773 
1774     // overflow_arg_area = (overflow_arg_area + 15) & ~15;
1775     llvm::Value *Offset =
1776       llvm::ConstantInt::get(CGF.Int32Ty, 15);
1777     overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset);
1778     llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(overflow_arg_area,
1779                                                     CGF.Int64Ty);
1780     llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int64Ty, ~15LL);
1781     overflow_arg_area =
1782       CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask),
1783                                  overflow_arg_area->getType(),
1784                                  "overflow_arg_area.align");
1785   }
1786 
1787   // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
1788   const llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
1789   llvm::Value *Res =
1790     CGF.Builder.CreateBitCast(overflow_arg_area,
1791                               llvm::PointerType::getUnqual(LTy));
1792 
1793   // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
1794   // l->overflow_arg_area + sizeof(type).
1795   // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
1796   // an 8 byte boundary.
1797 
1798   uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
1799   llvm::Value *Offset =
1800       llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7)  & ~7);
1801   overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
1802                                             "overflow_arg_area.next");
1803   CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
1804 
1805   // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
1806   return Res;
1807 }
1808 
1809 llvm::Value *X86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1810                                       CodeGenFunction &CGF) const {
1811   llvm::LLVMContext &VMContext = CGF.getLLVMContext();
1812 
1813   // Assume that va_list type is correct; should be pointer to LLVM type:
1814   // struct {
1815   //   i32 gp_offset;
1816   //   i32 fp_offset;
1817   //   i8* overflow_arg_area;
1818   //   i8* reg_save_area;
1819   // };
1820   unsigned neededInt, neededSSE;
1821 
1822   Ty = CGF.getContext().getCanonicalType(Ty);
1823   ABIArgInfo AI = classifyArgumentType(Ty, neededInt, neededSSE);
1824 
1825   // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
1826   // in the registers. If not go to step 7.
1827   if (!neededInt && !neededSSE)
1828     return EmitVAArgFromMemory(VAListAddr, Ty, CGF);
1829 
1830   // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
1831   // general purpose registers needed to pass type and num_fp to hold
1832   // the number of floating point registers needed.
1833 
1834   // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
1835   // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
1836   // l->fp_offset > 304 - num_fp * 16 go to step 7.
1837   //
1838   // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
1839   // register save space).
1840 
1841   llvm::Value *InRegs = 0;
1842   llvm::Value *gp_offset_p = 0, *gp_offset = 0;
1843   llvm::Value *fp_offset_p = 0, *fp_offset = 0;
1844   if (neededInt) {
1845     gp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "gp_offset_p");
1846     gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
1847     InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
1848     InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
1849   }
1850 
1851   if (neededSSE) {
1852     fp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 1, "fp_offset_p");
1853     fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
1854     llvm::Value *FitsInFP =
1855       llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
1856     FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
1857     InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
1858   }
1859 
1860   llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
1861   llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
1862   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
1863   CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
1864 
1865   // Emit code to load the value if it was passed in registers.
1866 
1867   CGF.EmitBlock(InRegBlock);
1868 
1869   // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
1870   // an offset of l->gp_offset and/or l->fp_offset. This may require
1871   // copying to a temporary location in case the parameter is passed
1872   // in different register classes or requires an alignment greater
1873   // than 8 for general purpose registers and 16 for XMM registers.
1874   //
1875   // FIXME: This really results in shameful code when we end up needing to
1876   // collect arguments from different places; often what should result in a
1877   // simple assembling of a structure from scattered addresses has many more
1878   // loads than necessary. Can we clean this up?
1879   const llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
1880   llvm::Value *RegAddr =
1881     CGF.Builder.CreateLoad(CGF.Builder.CreateStructGEP(VAListAddr, 3),
1882                            "reg_save_area");
1883   if (neededInt && neededSSE) {
1884     // FIXME: Cleanup.
1885     assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
1886     const llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
1887     llvm::Value *Tmp = CGF.CreateTempAlloca(ST);
1888     assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
1889     const llvm::Type *TyLo = ST->getElementType(0);
1890     const llvm::Type *TyHi = ST->getElementType(1);
1891     assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
1892            "Unexpected ABI info for mixed regs");
1893     const llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
1894     const llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
1895     llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
1896     llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
1897     llvm::Value *RegLoAddr = TyLo->isFloatingPointTy() ? FPAddr : GPAddr;
1898     llvm::Value *RegHiAddr = TyLo->isFloatingPointTy() ? GPAddr : FPAddr;
1899     llvm::Value *V =
1900       CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegLoAddr, PTyLo));
1901     CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
1902     V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegHiAddr, PTyHi));
1903     CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
1904 
1905     RegAddr = CGF.Builder.CreateBitCast(Tmp,
1906                                         llvm::PointerType::getUnqual(LTy));
1907   } else if (neededInt) {
1908     RegAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
1909     RegAddr = CGF.Builder.CreateBitCast(RegAddr,
1910                                         llvm::PointerType::getUnqual(LTy));
1911   } else if (neededSSE == 1) {
1912     RegAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
1913     RegAddr = CGF.Builder.CreateBitCast(RegAddr,
1914                                         llvm::PointerType::getUnqual(LTy));
1915   } else {
1916     assert(neededSSE == 2 && "Invalid number of needed registers!");
1917     // SSE registers are spaced 16 bytes apart in the register save
1918     // area, we need to collect the two eightbytes together.
1919     llvm::Value *RegAddrLo = CGF.Builder.CreateGEP(RegAddr, fp_offset);
1920     llvm::Value *RegAddrHi = CGF.Builder.CreateConstGEP1_32(RegAddrLo, 16);
1921     const llvm::Type *DoubleTy = llvm::Type::getDoubleTy(VMContext);
1922     const llvm::Type *DblPtrTy =
1923       llvm::PointerType::getUnqual(DoubleTy);
1924     const llvm::StructType *ST = llvm::StructType::get(VMContext, DoubleTy,
1925                                                        DoubleTy, NULL);
1926     llvm::Value *V, *Tmp = CGF.CreateTempAlloca(ST);
1927     V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrLo,
1928                                                          DblPtrTy));
1929     CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
1930     V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrHi,
1931                                                          DblPtrTy));
1932     CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
1933     RegAddr = CGF.Builder.CreateBitCast(Tmp,
1934                                         llvm::PointerType::getUnqual(LTy));
1935   }
1936 
1937   // AMD64-ABI 3.5.7p5: Step 5. Set:
1938   // l->gp_offset = l->gp_offset + num_gp * 8
1939   // l->fp_offset = l->fp_offset + num_fp * 16.
1940   if (neededInt) {
1941     llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
1942     CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
1943                             gp_offset_p);
1944   }
1945   if (neededSSE) {
1946     llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
1947     CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
1948                             fp_offset_p);
1949   }
1950   CGF.EmitBranch(ContBlock);
1951 
1952   // Emit code to load the value if it was passed in memory.
1953 
1954   CGF.EmitBlock(InMemBlock);
1955   llvm::Value *MemAddr = EmitVAArgFromMemory(VAListAddr, Ty, CGF);
1956 
1957   // Return the appropriate result.
1958 
1959   CGF.EmitBlock(ContBlock);
1960   llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(RegAddr->getType(),
1961                                                  "vaarg.addr");
1962   ResAddr->reserveOperandSpace(2);
1963   ResAddr->addIncoming(RegAddr, InRegBlock);
1964   ResAddr->addIncoming(MemAddr, InMemBlock);
1965   return ResAddr;
1966 }
1967 
1968 llvm::Value *WinX86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1969                                       CodeGenFunction &CGF) const {
1970   const llvm::Type *BP = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
1971   const llvm::Type *BPP = llvm::PointerType::getUnqual(BP);
1972 
1973   CGBuilderTy &Builder = CGF.Builder;
1974   llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
1975                                                        "ap");
1976   llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
1977   llvm::Type *PTy =
1978     llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
1979   llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
1980 
1981   uint64_t Offset =
1982     llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 8);
1983   llvm::Value *NextAddr =
1984     Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
1985                       "ap.next");
1986   Builder.CreateStore(NextAddr, VAListAddrAsBPP);
1987 
1988   return AddrTyped;
1989 }
1990 
1991 //===----------------------------------------------------------------------===//
1992 // PIC16 ABI Implementation
1993 //===----------------------------------------------------------------------===//
1994 
1995 namespace {
1996 
1997 class PIC16ABIInfo : public ABIInfo {
1998 public:
1999   PIC16ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
2000 
2001   ABIArgInfo classifyReturnType(QualType RetTy) const;
2002 
2003   ABIArgInfo classifyArgumentType(QualType RetTy) const;
2004 
2005   virtual void computeInfo(CGFunctionInfo &FI) const {
2006     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
2007     for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
2008          it != ie; ++it)
2009       it->info = classifyArgumentType(it->type);
2010   }
2011 
2012   virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2013                                  CodeGenFunction &CGF) const;
2014 };
2015 
2016 class PIC16TargetCodeGenInfo : public TargetCodeGenInfo {
2017 public:
2018   PIC16TargetCodeGenInfo(CodeGenTypes &CGT)
2019     : TargetCodeGenInfo(new PIC16ABIInfo(CGT)) {}
2020 };
2021 
2022 }
2023 
2024 ABIArgInfo PIC16ABIInfo::classifyReturnType(QualType RetTy) const {
2025   if (RetTy->isVoidType()) {
2026     return ABIArgInfo::getIgnore();
2027   } else {
2028     return ABIArgInfo::getDirect();
2029   }
2030 }
2031 
2032 ABIArgInfo PIC16ABIInfo::classifyArgumentType(QualType Ty) const {
2033   return ABIArgInfo::getDirect();
2034 }
2035 
2036 llvm::Value *PIC16ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2037                                      CodeGenFunction &CGF) const {
2038   const llvm::Type *BP = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
2039   const llvm::Type *BPP = llvm::PointerType::getUnqual(BP);
2040 
2041   CGBuilderTy &Builder = CGF.Builder;
2042   llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
2043                                                        "ap");
2044   llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
2045   llvm::Type *PTy =
2046     llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
2047   llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
2048 
2049   uint64_t Offset = CGF.getContext().getTypeSize(Ty) / 8;
2050 
2051   llvm::Value *NextAddr =
2052     Builder.CreateGEP(Addr, llvm::ConstantInt::get(
2053                           llvm::Type::getInt32Ty(CGF.getLLVMContext()), Offset),
2054                       "ap.next");
2055   Builder.CreateStore(NextAddr, VAListAddrAsBPP);
2056 
2057   return AddrTyped;
2058 }
2059 
2060 
2061 // PowerPC-32
2062 
2063 namespace {
2064 class PPC32TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
2065 public:
2066   PPC32TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
2067 
2068   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const {
2069     // This is recovered from gcc output.
2070     return 1; // r1 is the dedicated stack pointer
2071   }
2072 
2073   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2074                                llvm::Value *Address) const;
2075 };
2076 
2077 }
2078 
2079 bool
2080 PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2081                                                 llvm::Value *Address) const {
2082   // This is calculated from the LLVM and GCC tables and verified
2083   // against gcc output.  AFAIK all ABIs use the same encoding.
2084 
2085   CodeGen::CGBuilderTy &Builder = CGF.Builder;
2086   llvm::LLVMContext &Context = CGF.getLLVMContext();
2087 
2088   const llvm::IntegerType *i8 = llvm::Type::getInt8Ty(Context);
2089   llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
2090   llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
2091   llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
2092 
2093   // 0-31: r0-31, the 4-byte general-purpose registers
2094   AssignToArrayRange(Builder, Address, Four8, 0, 31);
2095 
2096   // 32-63: fp0-31, the 8-byte floating-point registers
2097   AssignToArrayRange(Builder, Address, Eight8, 32, 63);
2098 
2099   // 64-76 are various 4-byte special-purpose registers:
2100   // 64: mq
2101   // 65: lr
2102   // 66: ctr
2103   // 67: ap
2104   // 68-75 cr0-7
2105   // 76: xer
2106   AssignToArrayRange(Builder, Address, Four8, 64, 76);
2107 
2108   // 77-108: v0-31, the 16-byte vector registers
2109   AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
2110 
2111   // 109: vrsave
2112   // 110: vscr
2113   // 111: spe_acc
2114   // 112: spefscr
2115   // 113: sfp
2116   AssignToArrayRange(Builder, Address, Four8, 109, 113);
2117 
2118   return false;
2119 }
2120 
2121 
2122 //===----------------------------------------------------------------------===//
2123 // ARM ABI Implementation
2124 //===----------------------------------------------------------------------===//
2125 
2126 namespace {
2127 
2128 class ARMABIInfo : public ABIInfo {
2129 public:
2130   enum ABIKind {
2131     APCS = 0,
2132     AAPCS = 1,
2133     AAPCS_VFP
2134   };
2135 
2136 private:
2137   ABIKind Kind;
2138 
2139 public:
2140   ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind) : ABIInfo(CGT), Kind(_Kind) {}
2141 
2142 private:
2143   ABIKind getABIKind() const { return Kind; }
2144 
2145   ABIArgInfo classifyReturnType(QualType RetTy) const;
2146   ABIArgInfo classifyArgumentType(QualType RetTy) const;
2147 
2148   virtual void computeInfo(CGFunctionInfo &FI) const;
2149 
2150   virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2151                                  CodeGenFunction &CGF) const;
2152 };
2153 
2154 class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
2155 public:
2156   ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
2157     :TargetCodeGenInfo(new ARMABIInfo(CGT, K)) {}
2158 
2159   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const {
2160     return 13;
2161   }
2162 };
2163 
2164 }
2165 
2166 void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
2167   FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
2168   for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
2169        it != ie; ++it)
2170     it->info = classifyArgumentType(it->type);
2171 
2172   const llvm::Triple &Triple(getContext().Target.getTriple());
2173   llvm::CallingConv::ID DefaultCC;
2174   if (Triple.getEnvironmentName() == "gnueabi" ||
2175       Triple.getEnvironmentName() == "eabi")
2176     DefaultCC = llvm::CallingConv::ARM_AAPCS;
2177   else
2178     DefaultCC = llvm::CallingConv::ARM_APCS;
2179 
2180   switch (getABIKind()) {
2181   case APCS:
2182     if (DefaultCC != llvm::CallingConv::ARM_APCS)
2183       FI.setEffectiveCallingConvention(llvm::CallingConv::ARM_APCS);
2184     break;
2185 
2186   case AAPCS:
2187     if (DefaultCC != llvm::CallingConv::ARM_AAPCS)
2188       FI.setEffectiveCallingConvention(llvm::CallingConv::ARM_AAPCS);
2189     break;
2190 
2191   case AAPCS_VFP:
2192     FI.setEffectiveCallingConvention(llvm::CallingConv::ARM_AAPCS_VFP);
2193     break;
2194   }
2195 }
2196 
2197 ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty) const {
2198   if (!isAggregateTypeForABI(Ty)) {
2199     // Treat an enum type as its underlying type.
2200     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2201       Ty = EnumTy->getDecl()->getIntegerType();
2202 
2203     return (Ty->isPromotableIntegerType() ?
2204             ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
2205   }
2206 
2207   // Ignore empty records.
2208   if (isEmptyRecord(getContext(), Ty, true))
2209     return ABIArgInfo::getIgnore();
2210 
2211   // Structures with either a non-trivial destructor or a non-trivial
2212   // copy constructor are always indirect.
2213   if (isRecordWithNonTrivialDestructorOrCopyConstructor(Ty))
2214     return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
2215 
2216   // FIXME: This is kind of nasty... but there isn't much choice because the ARM
2217   // backend doesn't support byval.
2218   // FIXME: This doesn't handle alignment > 64 bits.
2219   const llvm::Type* ElemTy;
2220   unsigned SizeRegs;
2221   if (getContext().getTypeAlign(Ty) > 32) {
2222     ElemTy = llvm::Type::getInt64Ty(getVMContext());
2223     SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
2224   } else {
2225     ElemTy = llvm::Type::getInt32Ty(getVMContext());
2226     SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
2227   }
2228   std::vector<const llvm::Type*> LLVMFields;
2229   LLVMFields.push_back(llvm::ArrayType::get(ElemTy, SizeRegs));
2230   const llvm::Type* STy = llvm::StructType::get(getVMContext(), LLVMFields,
2231                                                 true);
2232   return ABIArgInfo::getDirect(STy);
2233 }
2234 
2235 static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
2236                               llvm::LLVMContext &VMContext) {
2237   // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
2238   // is called integer-like if its size is less than or equal to one word, and
2239   // the offset of each of its addressable sub-fields is zero.
2240 
2241   uint64_t Size = Context.getTypeSize(Ty);
2242 
2243   // Check that the type fits in a word.
2244   if (Size > 32)
2245     return false;
2246 
2247   // FIXME: Handle vector types!
2248   if (Ty->isVectorType())
2249     return false;
2250 
2251   // Float types are never treated as "integer like".
2252   if (Ty->isRealFloatingType())
2253     return false;
2254 
2255   // If this is a builtin or pointer type then it is ok.
2256   if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
2257     return true;
2258 
2259   // Small complex integer types are "integer like".
2260   if (const ComplexType *CT = Ty->getAs<ComplexType>())
2261     return isIntegerLikeType(CT->getElementType(), Context, VMContext);
2262 
2263   // Single element and zero sized arrays should be allowed, by the definition
2264   // above, but they are not.
2265 
2266   // Otherwise, it must be a record type.
2267   const RecordType *RT = Ty->getAs<RecordType>();
2268   if (!RT) return false;
2269 
2270   // Ignore records with flexible arrays.
2271   const RecordDecl *RD = RT->getDecl();
2272   if (RD->hasFlexibleArrayMember())
2273     return false;
2274 
2275   // Check that all sub-fields are at offset 0, and are themselves "integer
2276   // like".
2277   const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
2278 
2279   bool HadField = false;
2280   unsigned idx = 0;
2281   for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
2282        i != e; ++i, ++idx) {
2283     const FieldDecl *FD = *i;
2284 
2285     // Bit-fields are not addressable, we only need to verify they are "integer
2286     // like". We still have to disallow a subsequent non-bitfield, for example:
2287     //   struct { int : 0; int x }
2288     // is non-integer like according to gcc.
2289     if (FD->isBitField()) {
2290       if (!RD->isUnion())
2291         HadField = true;
2292 
2293       if (!isIntegerLikeType(FD->getType(), Context, VMContext))
2294         return false;
2295 
2296       continue;
2297     }
2298 
2299     // Check if this field is at offset 0.
2300     if (Layout.getFieldOffset(idx) != 0)
2301       return false;
2302 
2303     if (!isIntegerLikeType(FD->getType(), Context, VMContext))
2304       return false;
2305 
2306     // Only allow at most one field in a structure. This doesn't match the
2307     // wording above, but follows gcc in situations with a field following an
2308     // empty structure.
2309     if (!RD->isUnion()) {
2310       if (HadField)
2311         return false;
2312 
2313       HadField = true;
2314     }
2315   }
2316 
2317   return true;
2318 }
2319 
2320 ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy) const {
2321   if (RetTy->isVoidType())
2322     return ABIArgInfo::getIgnore();
2323 
2324   if (!isAggregateTypeForABI(RetTy)) {
2325     // Treat an enum type as its underlying type.
2326     if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
2327       RetTy = EnumTy->getDecl()->getIntegerType();
2328 
2329     return (RetTy->isPromotableIntegerType() ?
2330             ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
2331   }
2332 
2333   // Structures with either a non-trivial destructor or a non-trivial
2334   // copy constructor are always indirect.
2335   if (isRecordWithNonTrivialDestructorOrCopyConstructor(RetTy))
2336     return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
2337 
2338   // Are we following APCS?
2339   if (getABIKind() == APCS) {
2340     if (isEmptyRecord(getContext(), RetTy, false))
2341       return ABIArgInfo::getIgnore();
2342 
2343     // Complex types are all returned as packed integers.
2344     //
2345     // FIXME: Consider using 2 x vector types if the back end handles them
2346     // correctly.
2347     if (RetTy->isAnyComplexType())
2348       return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2349                                               getContext().getTypeSize(RetTy)));
2350 
2351     // Integer like structures are returned in r0.
2352     if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
2353       // Return in the smallest viable integer type.
2354       uint64_t Size = getContext().getTypeSize(RetTy);
2355       if (Size <= 8)
2356         return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
2357       if (Size <= 16)
2358         return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
2359       return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
2360     }
2361 
2362     // Otherwise return in memory.
2363     return ABIArgInfo::getIndirect(0);
2364   }
2365 
2366   // Otherwise this is an AAPCS variant.
2367 
2368   if (isEmptyRecord(getContext(), RetTy, true))
2369     return ABIArgInfo::getIgnore();
2370 
2371   // Aggregates <= 4 bytes are returned in r0; other aggregates
2372   // are returned indirectly.
2373   uint64_t Size = getContext().getTypeSize(RetTy);
2374   if (Size <= 32) {
2375     // Return in the smallest viable integer type.
2376     if (Size <= 8)
2377       return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
2378     if (Size <= 16)
2379       return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
2380     return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
2381   }
2382 
2383   return ABIArgInfo::getIndirect(0);
2384 }
2385 
2386 llvm::Value *ARMABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2387                                    CodeGenFunction &CGF) const {
2388   // FIXME: Need to handle alignment
2389   const llvm::Type *BP = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
2390   const llvm::Type *BPP = llvm::PointerType::getUnqual(BP);
2391 
2392   CGBuilderTy &Builder = CGF.Builder;
2393   llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
2394                                                        "ap");
2395   llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
2396   llvm::Type *PTy =
2397     llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
2398   llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
2399 
2400   uint64_t Offset =
2401     llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 4);
2402   llvm::Value *NextAddr =
2403     Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
2404                       "ap.next");
2405   Builder.CreateStore(NextAddr, VAListAddrAsBPP);
2406 
2407   return AddrTyped;
2408 }
2409 
2410 ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const {
2411   if (RetTy->isVoidType())
2412     return ABIArgInfo::getIgnore();
2413 
2414   if (isAggregateTypeForABI(RetTy))
2415     return ABIArgInfo::getIndirect(0);
2416 
2417   // Treat an enum type as its underlying type.
2418   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
2419     RetTy = EnumTy->getDecl()->getIntegerType();
2420 
2421   return (RetTy->isPromotableIntegerType() ?
2422           ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
2423 }
2424 
2425 //===----------------------------------------------------------------------===//
2426 // SystemZ ABI Implementation
2427 //===----------------------------------------------------------------------===//
2428 
2429 namespace {
2430 
2431 class SystemZABIInfo : public ABIInfo {
2432 public:
2433   SystemZABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
2434 
2435   bool isPromotableIntegerType(QualType Ty) const;
2436 
2437   ABIArgInfo classifyReturnType(QualType RetTy) const;
2438   ABIArgInfo classifyArgumentType(QualType RetTy) const;
2439 
2440   virtual void computeInfo(CGFunctionInfo &FI) const {
2441     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
2442     for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
2443          it != ie; ++it)
2444       it->info = classifyArgumentType(it->type);
2445   }
2446 
2447   virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2448                                  CodeGenFunction &CGF) const;
2449 };
2450 
2451 class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
2452 public:
2453   SystemZTargetCodeGenInfo(CodeGenTypes &CGT)
2454     : TargetCodeGenInfo(new SystemZABIInfo(CGT)) {}
2455 };
2456 
2457 }
2458 
2459 bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const {
2460   // SystemZ ABI requires all 8, 16 and 32 bit quantities to be extended.
2461   if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
2462     switch (BT->getKind()) {
2463     case BuiltinType::Bool:
2464     case BuiltinType::Char_S:
2465     case BuiltinType::Char_U:
2466     case BuiltinType::SChar:
2467     case BuiltinType::UChar:
2468     case BuiltinType::Short:
2469     case BuiltinType::UShort:
2470     case BuiltinType::Int:
2471     case BuiltinType::UInt:
2472       return true;
2473     default:
2474       return false;
2475     }
2476   return false;
2477 }
2478 
2479 llvm::Value *SystemZABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2480                                        CodeGenFunction &CGF) const {
2481   // FIXME: Implement
2482   return 0;
2483 }
2484 
2485 
2486 ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
2487   if (RetTy->isVoidType())
2488     return ABIArgInfo::getIgnore();
2489   if (isAggregateTypeForABI(RetTy))
2490     return ABIArgInfo::getIndirect(0);
2491 
2492   return (isPromotableIntegerType(RetTy) ?
2493           ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
2494 }
2495 
2496 ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
2497   if (isAggregateTypeForABI(Ty))
2498     return ABIArgInfo::getIndirect(0);
2499 
2500   return (isPromotableIntegerType(Ty) ?
2501           ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
2502 }
2503 
2504 //===----------------------------------------------------------------------===//
2505 // MSP430 ABI Implementation
2506 //===----------------------------------------------------------------------===//
2507 
2508 namespace {
2509 
2510 class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
2511 public:
2512   MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
2513     : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
2514   void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2515                            CodeGen::CodeGenModule &M) const;
2516 };
2517 
2518 }
2519 
2520 void MSP430TargetCodeGenInfo::SetTargetAttributes(const Decl *D,
2521                                                   llvm::GlobalValue *GV,
2522                                              CodeGen::CodeGenModule &M) const {
2523   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2524     if (const MSP430InterruptAttr *attr = FD->getAttr<MSP430InterruptAttr>()) {
2525       // Handle 'interrupt' attribute:
2526       llvm::Function *F = cast<llvm::Function>(GV);
2527 
2528       // Step 1: Set ISR calling convention.
2529       F->setCallingConv(llvm::CallingConv::MSP430_INTR);
2530 
2531       // Step 2: Add attributes goodness.
2532       F->addFnAttr(llvm::Attribute::NoInline);
2533 
2534       // Step 3: Emit ISR vector alias.
2535       unsigned Num = attr->getNumber() + 0xffe0;
2536       new llvm::GlobalAlias(GV->getType(), llvm::Function::ExternalLinkage,
2537                             "vector_" +
2538                             llvm::LowercaseString(llvm::utohexstr(Num)),
2539                             GV, &M.getModule());
2540     }
2541   }
2542 }
2543 
2544 //===----------------------------------------------------------------------===//
2545 // MIPS ABI Implementation.  This works for both little-endian and
2546 // big-endian variants.
2547 //===----------------------------------------------------------------------===//
2548 
2549 namespace {
2550 class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
2551 public:
2552   MIPSTargetCodeGenInfo(CodeGenTypes &CGT)
2553     : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
2554 
2555   int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const {
2556     return 29;
2557   }
2558 
2559   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2560                                llvm::Value *Address) const;
2561 };
2562 }
2563 
2564 bool
2565 MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2566                                                llvm::Value *Address) const {
2567   // This information comes from gcc's implementation, which seems to
2568   // as canonical as it gets.
2569 
2570   CodeGen::CGBuilderTy &Builder = CGF.Builder;
2571   llvm::LLVMContext &Context = CGF.getLLVMContext();
2572 
2573   // Everything on MIPS is 4 bytes.  Double-precision FP registers
2574   // are aliased to pairs of single-precision FP registers.
2575   const llvm::IntegerType *i8 = llvm::Type::getInt8Ty(Context);
2576   llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
2577 
2578   // 0-31 are the general purpose registers, $0 - $31.
2579   // 32-63 are the floating-point registers, $f0 - $f31.
2580   // 64 and 65 are the multiply/divide registers, $hi and $lo.
2581   // 66 is the (notional, I think) register for signal-handler return.
2582   AssignToArrayRange(Builder, Address, Four8, 0, 65);
2583 
2584   // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
2585   // They are one bit wide and ignored here.
2586 
2587   // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
2588   // (coprocessor 1 is the FP unit)
2589   // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
2590   // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
2591   // 176-181 are the DSP accumulator registers.
2592   AssignToArrayRange(Builder, Address, Four8, 80, 181);
2593 
2594   return false;
2595 }
2596 
2597 
2598 const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
2599   if (TheTargetCodeGenInfo)
2600     return *TheTargetCodeGenInfo;
2601 
2602   // For now we just cache the TargetCodeGenInfo in CodeGenModule and don't
2603   // free it.
2604 
2605   const llvm::Triple &Triple = getContext().Target.getTriple();
2606   switch (Triple.getArch()) {
2607   default:
2608     return *(TheTargetCodeGenInfo = new DefaultTargetCodeGenInfo(Types));
2609 
2610   case llvm::Triple::mips:
2611   case llvm::Triple::mipsel:
2612     return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types));
2613 
2614   case llvm::Triple::arm:
2615   case llvm::Triple::thumb:
2616     // FIXME: We want to know the float calling convention as well.
2617     if (strcmp(getContext().Target.getABI(), "apcs-gnu") == 0)
2618       return *(TheTargetCodeGenInfo =
2619                new ARMTargetCodeGenInfo(Types, ARMABIInfo::APCS));
2620 
2621     return *(TheTargetCodeGenInfo =
2622              new ARMTargetCodeGenInfo(Types, ARMABIInfo::AAPCS));
2623 
2624   case llvm::Triple::pic16:
2625     return *(TheTargetCodeGenInfo = new PIC16TargetCodeGenInfo(Types));
2626 
2627   case llvm::Triple::ppc:
2628     return *(TheTargetCodeGenInfo = new PPC32TargetCodeGenInfo(Types));
2629 
2630   case llvm::Triple::systemz:
2631     return *(TheTargetCodeGenInfo = new SystemZTargetCodeGenInfo(Types));
2632 
2633   case llvm::Triple::msp430:
2634     return *(TheTargetCodeGenInfo = new MSP430TargetCodeGenInfo(Types));
2635 
2636   case llvm::Triple::x86:
2637     switch (Triple.getOS()) {
2638     case llvm::Triple::Darwin:
2639       return *(TheTargetCodeGenInfo =
2640                new X86_32TargetCodeGenInfo(Types, true, true));
2641     case llvm::Triple::Cygwin:
2642     case llvm::Triple::MinGW32:
2643     case llvm::Triple::AuroraUX:
2644     case llvm::Triple::DragonFly:
2645     case llvm::Triple::FreeBSD:
2646     case llvm::Triple::OpenBSD:
2647       return *(TheTargetCodeGenInfo =
2648                new X86_32TargetCodeGenInfo(Types, false, true));
2649 
2650     default:
2651       return *(TheTargetCodeGenInfo =
2652                new X86_32TargetCodeGenInfo(Types, false, false));
2653     }
2654 
2655   case llvm::Triple::x86_64:
2656     switch (Triple.getOS()) {
2657     case llvm::Triple::Win32:
2658     case llvm::Triple::MinGW64:
2659     case llvm::Triple::Cygwin:
2660       return *(TheTargetCodeGenInfo = new WinX86_64TargetCodeGenInfo(Types));
2661     default:
2662       return *(TheTargetCodeGenInfo = new X86_64TargetCodeGenInfo(Types));
2663     }
2664   }
2665 }
2666