1 //===---- TargetABIInfo.cpp - Encapsulate target ABI details ----*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // These classes wrap the information about a call or function
11 // definition used to handle ABI compliancy.
13 //===----------------------------------------------------------------------===//
16 #include "CodeGenFunction.h"
17 #include "clang/AST/RecordLayout.h"
18 #include "llvm/Type.h"
19 #include "llvm/ADT/Triple.h"
22 using namespace clang;
23 using namespace CodeGen;
25 ABIInfo::~ABIInfo() {}
27 void ABIArgInfo::dump() const {
28 fprintf(stderr, "(ABIArgInfo Kind=");
31 fprintf(stderr, "Direct");
34 fprintf(stderr, "Extend");
37 fprintf(stderr, "Ignore");
40 fprintf(stderr, "Coerce Type=");
41 getCoerceToType()->print(llvm::errs());
44 fprintf(stderr, "Indirect Align=%d", getIndirectAlign());
47 fprintf(stderr, "Expand");
50 fprintf(stderr, ")\n");
53 static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays);
55 /// isEmptyField - Return true iff a the field is "empty", that is it
56 /// is an unnamed bit-field or an (array of) empty record(s).
57 static bool isEmptyField(ASTContext &Context, const FieldDecl *FD,
59 if (FD->isUnnamedBitfield())
62 QualType FT = FD->getType();
64 // Constant arrays of empty records count as empty, strip them off.
66 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT))
67 FT = AT->getElementType();
69 return isEmptyRecord(Context, FT, AllowArrays);
72 /// isEmptyRecord - Return true iff a structure contains only empty
73 /// fields. Note that a structure with a flexible array member is not
75 static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) {
76 const RecordType *RT = T->getAs<RecordType>();
79 const RecordDecl *RD = RT->getDecl();
80 if (RD->hasFlexibleArrayMember())
82 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
84 if (!isEmptyField(Context, *i, AllowArrays))
89 /// hasNonTrivialDestructorOrCopyConstructor - Determine if a type has either
90 /// a non-trivial destructor or a non-trivial copy constructor.
91 static bool hasNonTrivialDestructorOrCopyConstructor(const RecordType *RT) {
92 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
96 return !RD->hasTrivialDestructor() || !RD->hasTrivialCopyConstructor();
99 /// isRecordWithNonTrivialDestructorOrCopyConstructor - Determine if a type is
100 /// a record type with either a non-trivial destructor or a non-trivial copy
102 static bool isRecordWithNonTrivialDestructorOrCopyConstructor(QualType T) {
103 const RecordType *RT = T->getAs<RecordType>();
107 return hasNonTrivialDestructorOrCopyConstructor(RT);
110 /// isSingleElementStruct - Determine if a structure is a "single
111 /// element struct", i.e. it has exactly one non-empty field or
112 /// exactly one field which is itself a single element
113 /// struct. Structures with flexible array members are never
114 /// considered single element structs.
116 /// \return The field declaration for the single non-empty field, if
118 static const Type *isSingleElementStruct(QualType T, ASTContext &Context) {
119 const RecordType *RT = T->getAsStructureType();
123 const RecordDecl *RD = RT->getDecl();
124 if (RD->hasFlexibleArrayMember())
127 const Type *Found = 0;
128 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
130 const FieldDecl *FD = *i;
131 QualType FT = FD->getType();
133 // Ignore empty fields.
134 if (isEmptyField(Context, FD, true))
137 // If we already found an element then this isn't a single-element
142 // Treat single element arrays as the element.
143 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
144 if (AT->getSize().getZExtValue() != 1)
146 FT = AT->getElementType();
149 if (!CodeGenFunction::hasAggregateLLVMType(FT)) {
150 Found = FT.getTypePtr();
152 Found = isSingleElementStruct(FT, Context);
161 static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
162 if (!Ty->getAs<BuiltinType>() && !Ty->isAnyPointerType() &&
163 !Ty->isAnyComplexType() && !Ty->isEnumeralType() &&
164 !Ty->isBlockPointerType())
167 uint64_t Size = Context.getTypeSize(Ty);
168 return Size == 32 || Size == 64;
171 static bool areAllFields32Or64BitBasicType(const RecordDecl *RD,
172 ASTContext &Context) {
173 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
175 const FieldDecl *FD = *i;
177 if (!is32Or64BitBasicType(FD->getType(), Context))
180 // FIXME: Reject bit-fields wholesale; there are two problems, we don't know
181 // how to expand them yet, and the predicate for telling if a bitfield still
182 // counts as "basic" is more complicated than what we were doing previously.
183 if (FD->isBitField())
190 static bool typeContainsSSEVector(const RecordDecl *RD, ASTContext &Context) {
191 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
193 const FieldDecl *FD = *i;
195 if (FD->getType()->isVectorType() &&
196 Context.getTypeSize(FD->getType()) >= 128)
199 if (const RecordType* RT = FD->getType()->getAs<RecordType>())
200 if (typeContainsSSEVector(RT->getDecl(), Context))
208 /// DefaultABIInfo - The default implementation for ABI specific
209 /// details. This implementation provides information which results in
210 /// self-consistent and sensible LLVM IR generation, but does not
211 /// conform to any particular ABI.
212 class DefaultABIInfo : public ABIInfo {
213 ABIArgInfo classifyReturnType(QualType RetTy,
215 llvm::LLVMContext &VMContext) const;
217 ABIArgInfo classifyArgumentType(QualType RetTy,
219 llvm::LLVMContext &VMContext) const;
221 virtual void computeInfo(CGFunctionInfo &FI, ASTContext &Context,
222 llvm::LLVMContext &VMContext) const {
223 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), Context,
225 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
227 it->info = classifyArgumentType(it->type, Context, VMContext);
230 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
231 CodeGenFunction &CGF) const;
234 /// X86_32ABIInfo - The X86-32 ABI information.
235 class X86_32ABIInfo : public ABIInfo {
237 bool IsDarwinVectorABI;
238 bool IsSmallStructInRegABI;
240 static bool isRegisterSize(unsigned Size) {
241 return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
244 static bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context);
246 static unsigned getIndirectArgumentAlignment(QualType Ty,
247 ASTContext &Context);
250 ABIArgInfo classifyReturnType(QualType RetTy,
252 llvm::LLVMContext &VMContext) const;
254 ABIArgInfo classifyArgumentType(QualType RetTy,
256 llvm::LLVMContext &VMContext) const;
258 virtual void computeInfo(CGFunctionInfo &FI, ASTContext &Context,
259 llvm::LLVMContext &VMContext) const {
260 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), Context,
262 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
264 it->info = classifyArgumentType(it->type, Context, VMContext);
267 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
268 CodeGenFunction &CGF) const;
270 X86_32ABIInfo(ASTContext &Context, bool d, bool p)
271 : ABIInfo(), Context(Context), IsDarwinVectorABI(d),
272 IsSmallStructInRegABI(p) {}
277 /// shouldReturnTypeInRegister - Determine if the given type should be
278 /// passed in a register (for the Darwin ABI).
279 bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
280 ASTContext &Context) {
281 uint64_t Size = Context.getTypeSize(Ty);
283 // Type must be register sized.
284 if (!isRegisterSize(Size))
287 if (Ty->isVectorType()) {
288 // 64- and 128- bit vectors inside structures are not returned in
290 if (Size == 64 || Size == 128)
296 // If this is a builtin, pointer, enum, or complex type, it is ok.
297 if (Ty->getAs<BuiltinType>() || Ty->isAnyPointerType() ||
298 Ty->isAnyComplexType() || Ty->isEnumeralType() ||
299 Ty->isBlockPointerType())
302 // Arrays are treated like records.
303 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
304 return shouldReturnTypeInRegister(AT->getElementType(), Context);
306 // Otherwise, it must be a record type.
307 const RecordType *RT = Ty->getAs<RecordType>();
308 if (!RT) return false;
310 // Structure types are passed in register if all fields would be
311 // passed in a register.
312 for (RecordDecl::field_iterator i = RT->getDecl()->field_begin(),
313 e = RT->getDecl()->field_end(); i != e; ++i) {
314 const FieldDecl *FD = *i;
316 // Empty fields are ignored.
317 if (isEmptyField(Context, FD, true))
320 // Check fields recursively.
321 if (!shouldReturnTypeInRegister(FD->getType(), Context))
328 ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy,
330 llvm::LLVMContext &VMContext) const {
331 if (RetTy->isVoidType()) {
332 return ABIArgInfo::getIgnore();
333 } else if (const VectorType *VT = RetTy->getAs<VectorType>()) {
334 // On Darwin, some vectors are returned in registers.
335 if (IsDarwinVectorABI) {
336 uint64_t Size = Context.getTypeSize(RetTy);
338 // 128-bit vectors are a special case; they are returned in
339 // registers and we need to make sure to pick a type the LLVM
340 // backend will like.
342 return ABIArgInfo::getCoerce(llvm::VectorType::get(
343 llvm::Type::getInt64Ty(VMContext), 2));
345 // Always return in register if it fits in a general purpose
346 // register, or if it is 64 bits and has a single element.
347 if ((Size == 8 || Size == 16 || Size == 32) ||
348 (Size == 64 && VT->getNumElements() == 1))
349 return ABIArgInfo::getCoerce(llvm::IntegerType::get(VMContext, Size));
351 return ABIArgInfo::getIndirect(0);
354 return ABIArgInfo::getDirect();
355 } else if (CodeGenFunction::hasAggregateLLVMType(RetTy)) {
356 if (const RecordType *RT = RetTy->getAsStructureType()) {
357 // Structures with either a non-trivial destructor or a non-trivial
358 // copy constructor are always indirect.
359 if (hasNonTrivialDestructorOrCopyConstructor(RT))
360 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
362 // Structures with flexible arrays are always indirect.
363 if (RT->getDecl()->hasFlexibleArrayMember())
364 return ABIArgInfo::getIndirect(0);
367 // If specified, structs and unions are always indirect.
368 if (!IsSmallStructInRegABI && !RetTy->isAnyComplexType())
369 return ABIArgInfo::getIndirect(0);
371 // Classify "single element" structs as their element type.
372 if (const Type *SeltTy = isSingleElementStruct(RetTy, Context)) {
373 if (const BuiltinType *BT = SeltTy->getAs<BuiltinType>()) {
374 if (BT->isIntegerType()) {
375 // We need to use the size of the structure, padding
376 // bit-fields can adjust that to be larger than the single
378 uint64_t Size = Context.getTypeSize(RetTy);
379 return ABIArgInfo::getCoerce(
380 llvm::IntegerType::get(VMContext, (unsigned) Size));
381 } else if (BT->getKind() == BuiltinType::Float) {
382 assert(Context.getTypeSize(RetTy) == Context.getTypeSize(SeltTy) &&
383 "Unexpect single element structure size!");
384 return ABIArgInfo::getCoerce(llvm::Type::getFloatTy(VMContext));
385 } else if (BT->getKind() == BuiltinType::Double) {
386 assert(Context.getTypeSize(RetTy) == Context.getTypeSize(SeltTy) &&
387 "Unexpect single element structure size!");
388 return ABIArgInfo::getCoerce(llvm::Type::getDoubleTy(VMContext));
390 } else if (SeltTy->isPointerType()) {
391 // FIXME: It would be really nice if this could come out as the proper
393 const llvm::Type *PtrTy = llvm::Type::getInt8PtrTy(VMContext);
394 return ABIArgInfo::getCoerce(PtrTy);
395 } else if (SeltTy->isVectorType()) {
396 // 64- and 128-bit vectors are never returned in a
397 // register when inside a structure.
398 uint64_t Size = Context.getTypeSize(RetTy);
399 if (Size == 64 || Size == 128)
400 return ABIArgInfo::getIndirect(0);
402 return classifyReturnType(QualType(SeltTy, 0), Context, VMContext);
406 // Small structures which are register sized are generally returned
408 if (X86_32ABIInfo::shouldReturnTypeInRegister(RetTy, Context)) {
409 uint64_t Size = Context.getTypeSize(RetTy);
410 return ABIArgInfo::getCoerce(llvm::IntegerType::get(VMContext, Size));
413 return ABIArgInfo::getIndirect(0);
415 return (RetTy->isPromotableIntegerType() ?
416 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
420 unsigned X86_32ABIInfo::getIndirectArgumentAlignment(QualType Ty,
421 ASTContext &Context) {
422 unsigned Align = Context.getTypeAlign(Ty);
423 if (Align < 128) return 0;
424 if (const RecordType* RT = Ty->getAs<RecordType>())
425 if (typeContainsSSEVector(RT->getDecl(), Context))
430 ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
432 llvm::LLVMContext &VMContext) const {
433 // FIXME: Set alignment on indirect arguments.
434 if (CodeGenFunction::hasAggregateLLVMType(Ty)) {
435 // Structures with flexible arrays are always indirect.
436 if (const RecordType *RT = Ty->getAsStructureType())
437 if (RT->getDecl()->hasFlexibleArrayMember())
438 return ABIArgInfo::getIndirect(getIndirectArgumentAlignment(Ty,
441 // Ignore empty structs.
442 if (Ty->isStructureType() && Context.getTypeSize(Ty) == 0)
443 return ABIArgInfo::getIgnore();
445 // Expand structs with size <= 128-bits which consist only of
446 // basic types (int, long long, float, double, xxx*). This is
447 // non-recursive and does not ignore empty fields.
448 if (const RecordType *RT = Ty->getAsStructureType()) {
449 if (Context.getTypeSize(Ty) <= 4*32 &&
450 areAllFields32Or64BitBasicType(RT->getDecl(), Context))
451 return ABIArgInfo::getExpand();
454 return ABIArgInfo::getIndirect(getIndirectArgumentAlignment(Ty, Context));
456 return (Ty->isPromotableIntegerType() ?
457 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
461 llvm::Value *X86_32ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
462 CodeGenFunction &CGF) const {
463 const llvm::Type *BP = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
464 const llvm::Type *BPP = llvm::PointerType::getUnqual(BP);
466 CGBuilderTy &Builder = CGF.Builder;
467 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
469 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
471 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
472 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
475 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 4);
476 llvm::Value *NextAddr =
477 Builder.CreateGEP(Addr, llvm::ConstantInt::get(
478 llvm::Type::getInt32Ty(CGF.getLLVMContext()), Offset),
480 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
486 /// X86_64ABIInfo - The X86_64 ABI information.
487 class X86_64ABIInfo : public ABIInfo {
499 /// merge - Implement the X86_64 ABI merging algorithm.
501 /// Merge an accumulating classification \arg Accum with a field
502 /// classification \arg Field.
504 /// \param Accum - The accumulating classification. This should
505 /// always be either NoClass or the result of a previous merge
506 /// call. In addition, this should never be Memory (the caller
507 /// should just return Memory for the aggregate).
508 Class merge(Class Accum, Class Field) const;
510 /// classify - Determine the x86_64 register classes in which the
511 /// given type T should be passed.
513 /// \param Lo - The classification for the parts of the type
514 /// residing in the low word of the containing object.
516 /// \param Hi - The classification for the parts of the type
517 /// residing in the high word of the containing object.
519 /// \param OffsetBase - The bit offset of this type in the
520 /// containing object. Some parameters are classified different
521 /// depending on whether they straddle an eightbyte boundary.
523 /// If a word is unused its result will be NoClass; if a type should
524 /// be passed in Memory then at least the classification of \arg Lo
527 /// The \arg Lo class will be NoClass iff the argument is ignored.
529 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
530 /// also be ComplexX87.
531 void classify(QualType T, ASTContext &Context, uint64_t OffsetBase,
532 Class &Lo, Class &Hi) const;
534 /// getCoerceResult - Given a source type \arg Ty and an LLVM type
535 /// to coerce to, chose the best way to pass Ty in the same place
536 /// that \arg CoerceTo would be passed, but while keeping the
537 /// emitted code as simple as possible.
539 /// FIXME: Note, this should be cleaned up to just take an enumeration of all
540 /// the ways we might want to pass things, instead of constructing an LLVM
541 /// type. This makes this code more explicit, and it makes it clearer that we
542 /// are also doing this for correctness in the case of passing scalar types.
543 ABIArgInfo getCoerceResult(QualType Ty,
544 const llvm::Type *CoerceTo,
545 ASTContext &Context) const;
547 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
548 /// such that the argument will be passed in memory.
549 ABIArgInfo getIndirectResult(QualType Ty,
550 ASTContext &Context) const;
552 ABIArgInfo classifyReturnType(QualType RetTy,
554 llvm::LLVMContext &VMContext) const;
556 ABIArgInfo classifyArgumentType(QualType Ty,
558 llvm::LLVMContext &VMContext,
560 unsigned &neededSSE) const;
563 virtual void computeInfo(CGFunctionInfo &FI, ASTContext &Context,
564 llvm::LLVMContext &VMContext) const;
566 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
567 CodeGenFunction &CGF) const;
571 X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum,
573 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
574 // classified recursively so that always two fields are
575 // considered. The resulting class is calculated according to
576 // the classes of the fields in the eightbyte:
578 // (a) If both classes are equal, this is the resulting class.
580 // (b) If one of the classes is NO_CLASS, the resulting class is
583 // (c) If one of the classes is MEMORY, the result is the MEMORY
586 // (d) If one of the classes is INTEGER, the result is the
589 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
590 // MEMORY is used as class.
592 // (f) Otherwise class SSE is used.
594 // Accum should never be memory (we should have returned) or
595 // ComplexX87 (because this cannot be passed in a structure).
596 assert((Accum != Memory && Accum != ComplexX87) &&
597 "Invalid accumulated classification during merge.");
598 if (Accum == Field || Field == NoClass)
600 else if (Field == Memory)
602 else if (Accum == NoClass)
604 else if (Accum == Integer || Field == Integer)
606 else if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
607 Accum == X87 || Accum == X87Up)
613 void X86_64ABIInfo::classify(QualType Ty,
616 Class &Lo, Class &Hi) const {
617 // FIXME: This code can be simplified by introducing a simple value class for
618 // Class pairs with appropriate constructor methods for the various
621 // FIXME: Some of the split computations are wrong; unaligned vectors
622 // shouldn't be passed in registers for example, so there is no chance they
623 // can straddle an eightbyte. Verify & simplify.
627 Class &Current = OffsetBase < 64 ? Lo : Hi;
630 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
631 BuiltinType::Kind k = BT->getKind();
633 if (k == BuiltinType::Void) {
635 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
638 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
640 } else if (k == BuiltinType::Float || k == BuiltinType::Double) {
642 } else if (k == BuiltinType::LongDouble) {
646 // FIXME: _Decimal32 and _Decimal64 are SSE.
647 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
648 } else if (const EnumType *ET = Ty->getAs<EnumType>()) {
649 // Classify the underlying integer type.
650 classify(ET->getDecl()->getIntegerType(), Context, OffsetBase, Lo, Hi);
651 } else if (Ty->hasPointerRepresentation()) {
653 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
654 uint64_t Size = Context.getTypeSize(VT);
656 // gcc passes all <4 x char>, <2 x short>, <1 x int>, <1 x
657 // float> as integer.
660 // If this type crosses an eightbyte boundary, it should be
662 uint64_t EB_Real = (OffsetBase) / 64;
663 uint64_t EB_Imag = (OffsetBase + Size - 1) / 64;
664 if (EB_Real != EB_Imag)
666 } else if (Size == 64) {
667 // gcc passes <1 x double> in memory. :(
668 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double))
671 // gcc passes <1 x long long> as INTEGER.
672 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::LongLong))
677 // If this type crosses an eightbyte boundary, it should be
679 if (OffsetBase && OffsetBase != 64)
681 } else if (Size == 128) {
685 } else if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
686 QualType ET = Context.getCanonicalType(CT->getElementType());
688 uint64_t Size = Context.getTypeSize(Ty);
689 if (ET->isIntegralType()) {
692 else if (Size <= 128)
694 } else if (ET == Context.FloatTy)
696 else if (ET == Context.DoubleTy)
698 else if (ET == Context.LongDoubleTy)
699 Current = ComplexX87;
701 // If this complex type crosses an eightbyte boundary then it
703 uint64_t EB_Real = (OffsetBase) / 64;
704 uint64_t EB_Imag = (OffsetBase + Context.getTypeSize(ET)) / 64;
705 if (Hi == NoClass && EB_Real != EB_Imag)
707 } else if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
708 // Arrays are treated like structures.
710 uint64_t Size = Context.getTypeSize(Ty);
712 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
713 // than two eightbytes, ..., it has class MEMORY.
717 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
718 // fields, it has class MEMORY.
720 // Only need to check alignment of array base.
721 if (OffsetBase % Context.getTypeAlign(AT->getElementType()))
724 // Otherwise implement simplified merge. We could be smarter about
725 // this, but it isn't worth it and would be harder to verify.
727 uint64_t EltSize = Context.getTypeSize(AT->getElementType());
728 uint64_t ArraySize = AT->getSize().getZExtValue();
729 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
730 Class FieldLo, FieldHi;
731 classify(AT->getElementType(), Context, Offset, FieldLo, FieldHi);
732 Lo = merge(Lo, FieldLo);
733 Hi = merge(Hi, FieldHi);
734 if (Lo == Memory || Hi == Memory)
738 // Do post merger cleanup (see below). Only case we worry about is Memory.
741 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
742 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
743 uint64_t Size = Context.getTypeSize(Ty);
745 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
746 // than two eightbytes, ..., it has class MEMORY.
750 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
751 // copy constructor or a non-trivial destructor, it is passed by invisible
753 if (hasNonTrivialDestructorOrCopyConstructor(RT))
756 const RecordDecl *RD = RT->getDecl();
758 // Assume variable sized types are passed in memory.
759 if (RD->hasFlexibleArrayMember())
762 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
764 // Reset Lo class, this will be recomputed.
767 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
768 i != e; ++i, ++idx) {
769 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
770 bool BitField = i->isBitField();
772 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
773 // fields, it has class MEMORY.
775 // Note, skip this test for bit-fields, see below.
776 if (!BitField && Offset % Context.getTypeAlign(i->getType())) {
781 // Classify this field.
783 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
784 // exceeds a single eightbyte, each is classified
785 // separately. Each eightbyte gets initialized to class
787 Class FieldLo, FieldHi;
789 // Bit-fields require special handling, they do not force the
790 // structure to be passed in memory even if unaligned, and
791 // therefore they can straddle an eightbyte.
793 // Ignore padding bit-fields.
794 if (i->isUnnamedBitfield())
797 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
798 uint64_t Size = i->getBitWidth()->EvaluateAsInt(Context).getZExtValue();
800 uint64_t EB_Lo = Offset / 64;
801 uint64_t EB_Hi = (Offset + Size - 1) / 64;
802 FieldLo = FieldHi = NoClass;
804 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
809 FieldHi = EB_Hi ? Integer : NoClass;
812 classify(i->getType(), Context, Offset, FieldLo, FieldHi);
813 Lo = merge(Lo, FieldLo);
814 Hi = merge(Hi, FieldHi);
815 if (Lo == Memory || Hi == Memory)
819 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
821 // (a) If one of the classes is MEMORY, the whole argument is
824 // (b) If SSEUP is not preceeded by SSE, it is converted to SSE.
826 // The first of these conditions is guaranteed by how we implement
827 // the merge (just bail).
829 // The second condition occurs in the case of unions; for example
830 // union { _Complex double; unsigned; }.
833 if (Hi == SSEUp && Lo != SSE)
838 ABIArgInfo X86_64ABIInfo::getCoerceResult(QualType Ty,
839 const llvm::Type *CoerceTo,
840 ASTContext &Context) const {
841 if (CoerceTo == llvm::Type::getInt64Ty(CoerceTo->getContext())) {
842 // Integer and pointer types will end up in a general purpose
844 if (Ty->isIntegralType() || Ty->hasPointerRepresentation())
845 return (Ty->isPromotableIntegerType() ?
846 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
847 } else if (CoerceTo == llvm::Type::getDoubleTy(CoerceTo->getContext())) {
848 // FIXME: It would probably be better to make CGFunctionInfo only map using
849 // canonical types than to canonize here.
850 QualType CTy = Context.getCanonicalType(Ty);
852 // Float and double end up in a single SSE reg.
853 if (CTy == Context.FloatTy || CTy == Context.DoubleTy)
854 return ABIArgInfo::getDirect();
858 return ABIArgInfo::getCoerce(CoerceTo);
861 ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
862 ASTContext &Context) const {
863 // If this is a scalar LLVM value then assume LLVM will pass it in the right
865 if (!CodeGenFunction::hasAggregateLLVMType(Ty))
866 return (Ty->isPromotableIntegerType() ?
867 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
869 bool ByVal = !isRecordWithNonTrivialDestructorOrCopyConstructor(Ty);
871 // FIXME: Set alignment correctly.
872 return ABIArgInfo::getIndirect(0, ByVal);
875 ABIArgInfo X86_64ABIInfo::classifyReturnType(QualType RetTy,
877 llvm::LLVMContext &VMContext) const {
878 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
879 // classification algorithm.
880 X86_64ABIInfo::Class Lo, Hi;
881 classify(RetTy, Context, 0, Lo, Hi);
883 // Check some invariants.
884 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
885 assert((Lo != NoClass || Hi == NoClass) && "Invalid null classification.");
886 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
888 const llvm::Type *ResType = 0;
891 return ABIArgInfo::getIgnore();
895 assert(0 && "Invalid classification for lo word.");
897 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
900 return getIndirectResult(RetTy, Context);
902 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
903 // available register of the sequence %rax, %rdx is used.
905 ResType = llvm::Type::getInt64Ty(VMContext); break;
907 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
908 // available SSE register of the sequence %xmm0, %xmm1 is used.
910 ResType = llvm::Type::getDoubleTy(VMContext); break;
912 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
913 // returned on the X87 stack in %st0 as 80-bit x87 number.
915 ResType = llvm::Type::getX86_FP80Ty(VMContext); break;
917 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
918 // part of the value is returned in %st0 and the imaginary part in
921 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
922 ResType = llvm::StructType::get(VMContext, llvm::Type::getX86_FP80Ty(VMContext),
923 llvm::Type::getX86_FP80Ty(VMContext),
929 // Memory was handled previously and X87 should
930 // never occur as a hi class.
933 assert(0 && "Invalid classification for hi word.");
935 case ComplexX87: // Previously handled.
939 ResType = llvm::StructType::get(VMContext, ResType,
940 llvm::Type::getInt64Ty(VMContext), NULL);
943 ResType = llvm::StructType::get(VMContext, ResType,
944 llvm::Type::getDoubleTy(VMContext), NULL);
947 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
948 // is passed in the upper half of the last used SSE register.
950 // SSEUP should always be preceeded by SSE, just widen.
952 assert(Lo == SSE && "Unexpected SSEUp classification.");
953 ResType = llvm::VectorType::get(llvm::Type::getDoubleTy(VMContext), 2);
956 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
957 // returned together with the previous X87 value in %st0.
959 // If X87Up is preceeded by X87, we don't need to do
960 // anything. However, in some cases with unions it may not be
961 // preceeded by X87. In such situations we follow gcc and pass the
962 // extra bits in an SSE reg.
964 ResType = llvm::StructType::get(VMContext, ResType,
965 llvm::Type::getDoubleTy(VMContext), NULL);
969 return getCoerceResult(RetTy, ResType, Context);
972 ABIArgInfo X86_64ABIInfo::classifyArgumentType(QualType Ty, ASTContext &Context,
973 llvm::LLVMContext &VMContext,
975 unsigned &neededSSE) const {
976 X86_64ABIInfo::Class Lo, Hi;
977 classify(Ty, Context, 0, Lo, Hi);
979 // Check some invariants.
980 // FIXME: Enforce these by construction.
981 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
982 assert((Lo != NoClass || Hi == NoClass) && "Invalid null classification.");
983 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
987 const llvm::Type *ResType = 0;
990 return ABIArgInfo::getIgnore();
992 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
996 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
997 // COMPLEX_X87, it is passed in memory.
1000 return getIndirectResult(Ty, Context);
1004 assert(0 && "Invalid classification for lo word.");
1006 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
1007 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
1011 ResType = llvm::Type::getInt64Ty(VMContext);
1014 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
1015 // available SSE register is used, the registers are taken in the
1016 // order from %xmm0 to %xmm7.
1019 ResType = llvm::Type::getDoubleTy(VMContext);
1024 // Memory was handled previously, ComplexX87 and X87 should
1025 // never occur as hi classes, and X87Up must be preceed by X87,
1026 // which is passed in memory.
1030 assert(0 && "Invalid classification for hi word.");
1033 case NoClass: break;
1035 ResType = llvm::StructType::get(VMContext, ResType,
1036 llvm::Type::getInt64Ty(VMContext), NULL);
1040 // X87Up generally doesn't occur here (long double is passed in
1041 // memory), except in situations involving unions.
1044 ResType = llvm::StructType::get(VMContext, ResType,
1045 llvm::Type::getDoubleTy(VMContext), NULL);
1049 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
1050 // eightbyte is passed in the upper half of the last used SSE
1053 assert(Lo == SSE && "Unexpected SSEUp classification.");
1054 ResType = llvm::VectorType::get(llvm::Type::getDoubleTy(VMContext), 2);
1058 return getCoerceResult(Ty, ResType, Context);
1061 void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI, ASTContext &Context,
1062 llvm::LLVMContext &VMContext) const {
1063 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(),
1064 Context, VMContext);
1066 // Keep track of the number of assigned registers.
1067 unsigned freeIntRegs = 6, freeSSERegs = 8;
1069 // If the return value is indirect, then the hidden argument is consuming one
1070 // integer register.
1071 if (FI.getReturnInfo().isIndirect())
1074 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
1075 // get assigned (in left-to-right order) for passing as follows...
1076 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
1078 unsigned neededInt, neededSSE;
1079 it->info = classifyArgumentType(it->type, Context, VMContext,
1080 neededInt, neededSSE);
1082 // AMD64-ABI 3.2.3p3: If there are no registers available for any
1083 // eightbyte of an argument, the whole argument is passed on the
1084 // stack. If registers have already been assigned for some
1085 // eightbytes of such an argument, the assignments get reverted.
1086 if (freeIntRegs >= neededInt && freeSSERegs >= neededSSE) {
1087 freeIntRegs -= neededInt;
1088 freeSSERegs -= neededSSE;
1090 it->info = getIndirectResult(it->type, Context);
1095 static llvm::Value *EmitVAArgFromMemory(llvm::Value *VAListAddr,
1097 CodeGenFunction &CGF) {
1098 llvm::Value *overflow_arg_area_p =
1099 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_p");
1100 llvm::Value *overflow_arg_area =
1101 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
1103 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
1104 // byte boundary if alignment needed by type exceeds 8 byte boundary.
1105 uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8;
1107 // Note that we follow the ABI & gcc here, even though the type
1108 // could in theory have an alignment greater than 16. This case
1109 // shouldn't ever matter in practice.
1111 // overflow_arg_area = (overflow_arg_area + 15) & ~15;
1112 llvm::Value *Offset =
1113 llvm::ConstantInt::get(llvm::Type::getInt32Ty(CGF.getLLVMContext()), 15);
1114 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset);
1115 llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(overflow_arg_area,
1116 llvm::Type::getInt64Ty(CGF.getLLVMContext()));
1117 llvm::Value *Mask = llvm::ConstantInt::get(
1118 llvm::Type::getInt64Ty(CGF.getLLVMContext()), ~15LL);
1120 CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask),
1121 overflow_arg_area->getType(),
1122 "overflow_arg_area.align");
1125 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
1126 const llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
1128 CGF.Builder.CreateBitCast(overflow_arg_area,
1129 llvm::PointerType::getUnqual(LTy));
1131 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
1132 // l->overflow_arg_area + sizeof(type).
1133 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
1134 // an 8 byte boundary.
1136 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
1137 llvm::Value *Offset =
1138 llvm::ConstantInt::get(llvm::Type::getInt32Ty(CGF.getLLVMContext()),
1139 (SizeInBytes + 7) & ~7);
1140 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
1141 "overflow_arg_area.next");
1142 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
1144 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
1148 llvm::Value *X86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1149 CodeGenFunction &CGF) const {
1150 llvm::LLVMContext &VMContext = CGF.getLLVMContext();
1151 const llvm::Type *i32Ty = llvm::Type::getInt32Ty(VMContext);
1152 const llvm::Type *DoubleTy = llvm::Type::getDoubleTy(VMContext);
1154 // Assume that va_list type is correct; should be pointer to LLVM type:
1158 // i8* overflow_arg_area;
1159 // i8* reg_save_area;
1161 unsigned neededInt, neededSSE;
1162 ABIArgInfo AI = classifyArgumentType(Ty, CGF.getContext(), VMContext,
1163 neededInt, neededSSE);
1165 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
1166 // in the registers. If not go to step 7.
1167 if (!neededInt && !neededSSE)
1168 return EmitVAArgFromMemory(VAListAddr, Ty, CGF);
1170 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
1171 // general purpose registers needed to pass type and num_fp to hold
1172 // the number of floating point registers needed.
1174 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
1175 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
1176 // l->fp_offset > 304 - num_fp * 16 go to step 7.
1178 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
1179 // register save space).
1181 llvm::Value *InRegs = 0;
1182 llvm::Value *gp_offset_p = 0, *gp_offset = 0;
1183 llvm::Value *fp_offset_p = 0, *fp_offset = 0;
1185 gp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "gp_offset_p");
1186 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
1188 CGF.Builder.CreateICmpULE(gp_offset,
1189 llvm::ConstantInt::get(i32Ty,
1190 48 - neededInt * 8),
1195 fp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 1, "fp_offset_p");
1196 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
1197 llvm::Value *FitsInFP =
1198 CGF.Builder.CreateICmpULE(fp_offset,
1199 llvm::ConstantInt::get(i32Ty,
1200 176 - neededSSE * 16),
1202 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
1205 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
1206 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
1207 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
1208 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
1210 // Emit code to load the value if it was passed in registers.
1212 CGF.EmitBlock(InRegBlock);
1214 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
1215 // an offset of l->gp_offset and/or l->fp_offset. This may require
1216 // copying to a temporary location in case the parameter is passed
1217 // in different register classes or requires an alignment greater
1218 // than 8 for general purpose registers and 16 for XMM registers.
1220 // FIXME: This really results in shameful code when we end up needing to
1221 // collect arguments from different places; often what should result in a
1222 // simple assembling of a structure from scattered addresses has many more
1223 // loads than necessary. Can we clean this up?
1224 const llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
1225 llvm::Value *RegAddr =
1226 CGF.Builder.CreateLoad(CGF.Builder.CreateStructGEP(VAListAddr, 3),
1228 if (neededInt && neededSSE) {
1230 assert(AI.isCoerce() && "Unexpected ABI info for mixed regs");
1231 const llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
1232 llvm::Value *Tmp = CGF.CreateTempAlloca(ST);
1233 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
1234 const llvm::Type *TyLo = ST->getElementType(0);
1235 const llvm::Type *TyHi = ST->getElementType(1);
1236 assert((TyLo->isFloatingPoint() ^ TyHi->isFloatingPoint()) &&
1237 "Unexpected ABI info for mixed regs");
1238 const llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
1239 const llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
1240 llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
1241 llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
1242 llvm::Value *RegLoAddr = TyLo->isFloatingPoint() ? FPAddr : GPAddr;
1243 llvm::Value *RegHiAddr = TyLo->isFloatingPoint() ? GPAddr : FPAddr;
1245 CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegLoAddr, PTyLo));
1246 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
1247 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegHiAddr, PTyHi));
1248 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
1250 RegAddr = CGF.Builder.CreateBitCast(Tmp,
1251 llvm::PointerType::getUnqual(LTy));
1252 } else if (neededInt) {
1253 RegAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
1254 RegAddr = CGF.Builder.CreateBitCast(RegAddr,
1255 llvm::PointerType::getUnqual(LTy));
1257 if (neededSSE == 1) {
1258 RegAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
1259 RegAddr = CGF.Builder.CreateBitCast(RegAddr,
1260 llvm::PointerType::getUnqual(LTy));
1262 assert(neededSSE == 2 && "Invalid number of needed registers!");
1263 // SSE registers are spaced 16 bytes apart in the register save
1264 // area, we need to collect the two eightbytes together.
1265 llvm::Value *RegAddrLo = CGF.Builder.CreateGEP(RegAddr, fp_offset);
1266 llvm::Value *RegAddrHi =
1267 CGF.Builder.CreateGEP(RegAddrLo,
1268 llvm::ConstantInt::get(i32Ty, 16));
1269 const llvm::Type *DblPtrTy =
1270 llvm::PointerType::getUnqual(DoubleTy);
1271 const llvm::StructType *ST = llvm::StructType::get(VMContext, DoubleTy,
1273 llvm::Value *V, *Tmp = CGF.CreateTempAlloca(ST);
1274 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrLo,
1276 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
1277 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrHi,
1279 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
1280 RegAddr = CGF.Builder.CreateBitCast(Tmp,
1281 llvm::PointerType::getUnqual(LTy));
1285 // AMD64-ABI 3.5.7p5: Step 5. Set:
1286 // l->gp_offset = l->gp_offset + num_gp * 8
1287 // l->fp_offset = l->fp_offset + num_fp * 16.
1289 llvm::Value *Offset = llvm::ConstantInt::get(i32Ty, neededInt * 8);
1290 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
1294 llvm::Value *Offset = llvm::ConstantInt::get(i32Ty, neededSSE * 16);
1295 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
1298 CGF.EmitBranch(ContBlock);
1300 // Emit code to load the value if it was passed in memory.
1302 CGF.EmitBlock(InMemBlock);
1303 llvm::Value *MemAddr = EmitVAArgFromMemory(VAListAddr, Ty, CGF);
1305 // Return the appropriate result.
1307 CGF.EmitBlock(ContBlock);
1308 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(RegAddr->getType(),
1310 ResAddr->reserveOperandSpace(2);
1311 ResAddr->addIncoming(RegAddr, InRegBlock);
1312 ResAddr->addIncoming(MemAddr, InMemBlock);
1317 // PIC16 ABI Implementation
1321 class PIC16ABIInfo : public ABIInfo {
1322 ABIArgInfo classifyReturnType(QualType RetTy,
1323 ASTContext &Context,
1324 llvm::LLVMContext &VMContext) const;
1326 ABIArgInfo classifyArgumentType(QualType RetTy,
1327 ASTContext &Context,
1328 llvm::LLVMContext &VMContext) const;
1330 virtual void computeInfo(CGFunctionInfo &FI, ASTContext &Context,
1331 llvm::LLVMContext &VMContext) const {
1332 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), Context,
1334 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
1336 it->info = classifyArgumentType(it->type, Context, VMContext);
1339 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1340 CodeGenFunction &CGF) const;
1345 ABIArgInfo PIC16ABIInfo::classifyReturnType(QualType RetTy,
1346 ASTContext &Context,
1347 llvm::LLVMContext &VMContext) const {
1348 if (RetTy->isVoidType()) {
1349 return ABIArgInfo::getIgnore();
1351 return ABIArgInfo::getDirect();
1355 ABIArgInfo PIC16ABIInfo::classifyArgumentType(QualType Ty,
1356 ASTContext &Context,
1357 llvm::LLVMContext &VMContext) const {
1358 return ABIArgInfo::getDirect();
1361 llvm::Value *PIC16ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1362 CodeGenFunction &CGF) const {
1366 // ARM ABI Implementation
1370 class ARMABIInfo : public ABIInfo {
1382 ARMABIInfo(ABIKind _Kind) : Kind(_Kind) {}
1385 ABIKind getABIKind() const { return Kind; }
1387 ABIArgInfo classifyReturnType(QualType RetTy,
1388 ASTContext &Context,
1389 llvm::LLVMContext &VMCOntext) const;
1391 ABIArgInfo classifyArgumentType(QualType RetTy,
1392 ASTContext &Context,
1393 llvm::LLVMContext &VMContext) const;
1395 virtual void computeInfo(CGFunctionInfo &FI, ASTContext &Context,
1396 llvm::LLVMContext &VMContext) const;
1398 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1399 CodeGenFunction &CGF) const;
1404 void ARMABIInfo::computeInfo(CGFunctionInfo &FI, ASTContext &Context,
1405 llvm::LLVMContext &VMContext) const {
1406 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), Context,
1408 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
1410 it->info = classifyArgumentType(it->type, Context, VMContext);
1413 // ARM always overrides the calling convention.
1414 switch (getABIKind()) {
1416 FI.setEffectiveCallingConvention(llvm::CallingConv::ARM_APCS);
1420 FI.setEffectiveCallingConvention(llvm::CallingConv::ARM_AAPCS);
1424 FI.setEffectiveCallingConvention(llvm::CallingConv::ARM_AAPCS_VFP);
1429 ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty,
1430 ASTContext &Context,
1431 llvm::LLVMContext &VMContext) const {
1432 if (!CodeGenFunction::hasAggregateLLVMType(Ty))
1433 return (Ty->isPromotableIntegerType() ?
1434 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
1436 // Ignore empty records.
1437 if (isEmptyRecord(Context, Ty, true))
1438 return ABIArgInfo::getIgnore();
1440 // FIXME: This is kind of nasty... but there isn't much choice because the ARM
1441 // backend doesn't support byval.
1442 // FIXME: This doesn't handle alignment > 64 bits.
1443 const llvm::Type* ElemTy;
1445 if (Context.getTypeAlign(Ty) > 32) {
1446 ElemTy = llvm::Type::getInt64Ty(VMContext);
1447 SizeRegs = (Context.getTypeSize(Ty) + 63) / 64;
1449 ElemTy = llvm::Type::getInt32Ty(VMContext);
1450 SizeRegs = (Context.getTypeSize(Ty) + 31) / 32;
1452 std::vector<const llvm::Type*> LLVMFields;
1453 LLVMFields.push_back(llvm::ArrayType::get(ElemTy, SizeRegs));
1454 const llvm::Type* STy = llvm::StructType::get(VMContext, LLVMFields, true);
1455 return ABIArgInfo::getCoerce(STy);
1458 static bool isIntegerLikeType(QualType Ty,
1459 ASTContext &Context,
1460 llvm::LLVMContext &VMContext) {
1461 // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
1462 // is called integer-like if its size is less than or equal to one word, and
1463 // the offset of each of its addressable sub-fields is zero.
1465 uint64_t Size = Context.getTypeSize(Ty);
1467 // Check that the type fits in a word.
1471 // FIXME: Handle vector types!
1472 if (Ty->isVectorType())
1475 // Float types are never treated as "integer like".
1476 if (Ty->isRealFloatingType())
1479 // If this is a builtin or pointer type then it is ok.
1480 if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
1483 // Complex types "should" be ok by the definition above, but they are not.
1484 if (Ty->isAnyComplexType())
1487 // Single element and zero sized arrays should be allowed, by the definition
1488 // above, but they are not.
1490 // Otherwise, it must be a record type.
1491 const RecordType *RT = Ty->getAs<RecordType>();
1492 if (!RT) return false;
1494 // Ignore records with flexible arrays.
1495 const RecordDecl *RD = RT->getDecl();
1496 if (RD->hasFlexibleArrayMember())
1499 // Check that all sub-fields are at offset 0, and are themselves "integer
1501 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1503 bool HadField = false;
1505 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
1506 i != e; ++i, ++idx) {
1507 const FieldDecl *FD = *i;
1509 // Check if this field is at offset 0.
1510 uint64_t Offset = Layout.getFieldOffset(idx);
1512 // Allow padding bit-fields, but only if they are all at the end of the
1513 // structure (despite the wording above, this matches gcc).
1514 if (FD->isBitField() &&
1515 !FD->getBitWidth()->EvaluateAsInt(Context).getZExtValue()) {
1517 if (!i->isBitField() ||
1518 i->getBitWidth()->EvaluateAsInt(Context).getZExtValue())
1521 // All remaining fields are padding, allow this.
1528 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
1531 // Only allow at most one field in a structure. Again this doesn't match the
1532 // wording above, but follows gcc.
1533 if (!RD->isUnion()) {
1544 ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy,
1545 ASTContext &Context,
1546 llvm::LLVMContext &VMContext) const {
1547 if (RetTy->isVoidType())
1548 return ABIArgInfo::getIgnore();
1550 if (!CodeGenFunction::hasAggregateLLVMType(RetTy))
1551 return (RetTy->isPromotableIntegerType() ?
1552 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
1554 // Are we following APCS?
1555 if (getABIKind() == APCS) {
1556 if (isEmptyRecord(Context, RetTy, false))
1557 return ABIArgInfo::getIgnore();
1559 // Integer like structures are returned in r0.
1560 if (isIntegerLikeType(RetTy, Context, VMContext)) {
1561 // Return in the smallest viable integer type.
1562 uint64_t Size = Context.getTypeSize(RetTy);
1564 return ABIArgInfo::getCoerce(llvm::Type::getInt8Ty(VMContext));
1566 return ABIArgInfo::getCoerce(llvm::Type::getInt16Ty(VMContext));
1567 return ABIArgInfo::getCoerce(llvm::Type::getInt32Ty(VMContext));
1570 // Otherwise return in memory.
1571 return ABIArgInfo::getIndirect(0);
1574 // Otherwise this is an AAPCS variant.
1576 if (isEmptyRecord(Context, RetTy, true))
1577 return ABIArgInfo::getIgnore();
1579 // Aggregates <= 4 bytes are returned in r0; other aggregates
1580 // are returned indirectly.
1581 uint64_t Size = Context.getTypeSize(RetTy);
1583 // Return in the smallest viable integer type.
1585 return ABIArgInfo::getCoerce(llvm::Type::getInt8Ty(VMContext));
1587 return ABIArgInfo::getCoerce(llvm::Type::getInt16Ty(VMContext));
1588 return ABIArgInfo::getCoerce(llvm::Type::getInt32Ty(VMContext));
1591 return ABIArgInfo::getIndirect(0);
1594 llvm::Value *ARMABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1595 CodeGenFunction &CGF) const {
1596 // FIXME: Need to handle alignment
1597 const llvm::Type *BP = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
1598 const llvm::Type *BPP = llvm::PointerType::getUnqual(BP);
1600 CGBuilderTy &Builder = CGF.Builder;
1601 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
1603 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
1605 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
1606 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
1609 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 4);
1610 llvm::Value *NextAddr =
1611 Builder.CreateGEP(Addr, llvm::ConstantInt::get(
1612 llvm::Type::getInt32Ty(CGF.getLLVMContext()), Offset),
1614 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
1619 ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy,
1620 ASTContext &Context,
1621 llvm::LLVMContext &VMContext) const {
1622 if (RetTy->isVoidType()) {
1623 return ABIArgInfo::getIgnore();
1624 } else if (CodeGenFunction::hasAggregateLLVMType(RetTy)) {
1625 return ABIArgInfo::getIndirect(0);
1627 return (RetTy->isPromotableIntegerType() ?
1628 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
1632 // SystemZ ABI Implementation
1636 class SystemZABIInfo : public ABIInfo {
1637 bool isPromotableIntegerType(QualType Ty) const;
1639 ABIArgInfo classifyReturnType(QualType RetTy, ASTContext &Context,
1640 llvm::LLVMContext &VMContext) const;
1642 ABIArgInfo classifyArgumentType(QualType RetTy, ASTContext &Context,
1643 llvm::LLVMContext &VMContext) const;
1645 virtual void computeInfo(CGFunctionInfo &FI, ASTContext &Context,
1646 llvm::LLVMContext &VMContext) const {
1647 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(),
1648 Context, VMContext);
1649 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
1651 it->info = classifyArgumentType(it->type, Context, VMContext);
1654 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1655 CodeGenFunction &CGF) const;
1660 bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const {
1661 // SystemZ ABI requires all 8, 16 and 32 bit quantities to be extended.
1662 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
1663 switch (BT->getKind()) {
1664 case BuiltinType::Bool:
1665 case BuiltinType::Char_S:
1666 case BuiltinType::Char_U:
1667 case BuiltinType::SChar:
1668 case BuiltinType::UChar:
1669 case BuiltinType::Short:
1670 case BuiltinType::UShort:
1671 case BuiltinType::Int:
1672 case BuiltinType::UInt:
1680 llvm::Value *SystemZABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1681 CodeGenFunction &CGF) const {
1687 ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy,
1688 ASTContext &Context,
1689 llvm::LLVMContext &VMContext) const {
1690 if (RetTy->isVoidType()) {
1691 return ABIArgInfo::getIgnore();
1692 } else if (CodeGenFunction::hasAggregateLLVMType(RetTy)) {
1693 return ABIArgInfo::getIndirect(0);
1695 return (isPromotableIntegerType(RetTy) ?
1696 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
1700 ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty,
1701 ASTContext &Context,
1702 llvm::LLVMContext &VMContext) const {
1703 if (CodeGenFunction::hasAggregateLLVMType(Ty)) {
1704 return ABIArgInfo::getIndirect(0);
1706 return (isPromotableIntegerType(Ty) ?
1707 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
1711 ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty,
1712 ASTContext &Context,
1713 llvm::LLVMContext &VMContext) const {
1714 if (CodeGenFunction::hasAggregateLLVMType(Ty)) {
1715 return ABIArgInfo::getIndirect(0);
1717 return (Ty->isPromotableIntegerType() ?
1718 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
1722 llvm::Value *DefaultABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1723 CodeGenFunction &CGF) const {
1727 const ABIInfo &CodeGenTypes::getABIInfo() const {
1731 // For now we just cache the ABIInfo in CodeGenTypes and don't free it.
1733 const llvm::Triple &Triple(getContext().Target.getTriple());
1734 switch (Triple.getArch()) {
1736 return *(TheABIInfo = new DefaultABIInfo);
1738 case llvm::Triple::arm:
1739 case llvm::Triple::thumb:
1740 // FIXME: We want to know the float calling convention as well.
1741 if (strcmp(getContext().Target.getABI(), "apcs-gnu") == 0)
1742 return *(TheABIInfo = new ARMABIInfo(ARMABIInfo::APCS));
1744 return *(TheABIInfo = new ARMABIInfo(ARMABIInfo::AAPCS));
1746 case llvm::Triple::pic16:
1747 return *(TheABIInfo = new PIC16ABIInfo());
1749 case llvm::Triple::systemz:
1750 return *(TheABIInfo = new SystemZABIInfo());
1752 case llvm::Triple::x86:
1753 switch (Triple.getOS()) {
1754 case llvm::Triple::Darwin:
1755 return *(TheABIInfo = new X86_32ABIInfo(Context, true, true));
1756 case llvm::Triple::Cygwin:
1757 case llvm::Triple::MinGW32:
1758 case llvm::Triple::MinGW64:
1759 case llvm::Triple::AuroraUX:
1760 case llvm::Triple::DragonFly:
1761 case llvm::Triple::FreeBSD:
1762 case llvm::Triple::OpenBSD:
1763 return *(TheABIInfo = new X86_32ABIInfo(Context, false, true));
1766 return *(TheABIInfo = new X86_32ABIInfo(Context, false, false));
1769 case llvm::Triple::x86_64:
1770 return *(TheABIInfo = new X86_64ABIInfo());