1 //===---- TargetInfo.cpp - Encapsulate target 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 //===----------------------------------------------------------------------===//
15 #include "TargetInfo.h"
17 #include "CodeGenFunction.h"
18 #include "clang/AST/RecordLayout.h"
19 #include "llvm/Type.h"
20 #include "llvm/ADT/StringExtras.h"
21 #include "llvm/ADT/Triple.h"
22 #include "llvm/Support/raw_ostream.h"
23 using namespace clang;
24 using namespace CodeGen;
26 ABIInfo::~ABIInfo() {}
28 void ABIArgInfo::dump() const {
29 llvm::raw_ostream &OS = llvm::errs();
30 OS << "(ABIArgInfo Kind=";
43 getCoerceToType()->print(OS);
46 OS << "Indirect Align=" << getIndirectAlign();
55 TargetCodeGenInfo::~TargetCodeGenInfo() { delete Info; }
57 static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays);
59 /// isEmptyField - Return true iff a the field is "empty", that is it
60 /// is an unnamed bit-field or an (array of) empty record(s).
61 static bool isEmptyField(ASTContext &Context, const FieldDecl *FD,
63 if (FD->isUnnamedBitfield())
66 QualType FT = FD->getType();
68 // Constant arrays of empty records count as empty, strip them off.
70 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT))
71 FT = AT->getElementType();
73 return isEmptyRecord(Context, FT, AllowArrays);
76 /// isEmptyRecord - Return true iff a structure contains only empty
77 /// fields. Note that a structure with a flexible array member is not
79 static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) {
80 const RecordType *RT = T->getAs<RecordType>();
83 const RecordDecl *RD = RT->getDecl();
84 if (RD->hasFlexibleArrayMember())
86 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
88 if (!isEmptyField(Context, *i, AllowArrays))
93 /// hasNonTrivialDestructorOrCopyConstructor - Determine if a type has either
94 /// a non-trivial destructor or a non-trivial copy constructor.
95 static bool hasNonTrivialDestructorOrCopyConstructor(const RecordType *RT) {
96 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
100 return !RD->hasTrivialDestructor() || !RD->hasTrivialCopyConstructor();
103 /// isRecordWithNonTrivialDestructorOrCopyConstructor - Determine if a type is
104 /// a record type with either a non-trivial destructor or a non-trivial copy
106 static bool isRecordWithNonTrivialDestructorOrCopyConstructor(QualType T) {
107 const RecordType *RT = T->getAs<RecordType>();
111 return hasNonTrivialDestructorOrCopyConstructor(RT);
114 /// isSingleElementStruct - Determine if a structure is a "single
115 /// element struct", i.e. it has exactly one non-empty field or
116 /// exactly one field which is itself a single element
117 /// struct. Structures with flexible array members are never
118 /// considered single element structs.
120 /// \return The field declaration for the single non-empty field, if
122 static const Type *isSingleElementStruct(QualType T, ASTContext &Context) {
123 const RecordType *RT = T->getAsStructureType();
127 const RecordDecl *RD = RT->getDecl();
128 if (RD->hasFlexibleArrayMember())
131 const Type *Found = 0;
132 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
134 const FieldDecl *FD = *i;
135 QualType FT = FD->getType();
137 // Ignore empty fields.
138 if (isEmptyField(Context, FD, true))
141 // If we already found an element then this isn't a single-element
146 // Treat single element arrays as the element.
147 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
148 if (AT->getSize().getZExtValue() != 1)
150 FT = AT->getElementType();
153 if (!CodeGenFunction::hasAggregateLLVMType(FT)) {
154 Found = FT.getTypePtr();
156 Found = isSingleElementStruct(FT, Context);
165 static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
166 if (!Ty->getAs<BuiltinType>() && !Ty->isAnyPointerType() &&
167 !Ty->isAnyComplexType() && !Ty->isEnumeralType() &&
168 !Ty->isBlockPointerType())
171 uint64_t Size = Context.getTypeSize(Ty);
172 return Size == 32 || Size == 64;
175 /// canExpandIndirectArgument - Test whether an argument type which is to be
176 /// passed indirectly (on the stack) would have the equivalent layout if it was
177 /// expanded into separate arguments. If so, we prefer to do the latter to avoid
178 /// inhibiting optimizations.
180 // FIXME: This predicate is missing many cases, currently it just follows
181 // llvm-gcc (checks that all fields are 32-bit or 64-bit primitive types). We
182 // should probably make this smarter, or better yet make the LLVM backend
183 // capable of handling it.
184 static bool canExpandIndirectArgument(QualType Ty, ASTContext &Context) {
185 // We can only expand structure types.
186 const RecordType *RT = Ty->getAs<RecordType>();
190 // We can only expand (C) structures.
192 // FIXME: This needs to be generalized to handle classes as well.
193 const RecordDecl *RD = RT->getDecl();
194 if (!RD->isStruct() || isa<CXXRecordDecl>(RD))
197 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
199 const FieldDecl *FD = *i;
201 if (!is32Or64BitBasicType(FD->getType(), Context))
204 // FIXME: Reject bit-fields wholesale; there are two problems, we don't know
205 // how to expand them yet, and the predicate for telling if a bitfield still
206 // counts as "basic" is more complicated than what we were doing previously.
207 if (FD->isBitField())
214 static bool typeContainsSSEVector(const RecordDecl *RD, ASTContext &Context) {
215 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
217 const FieldDecl *FD = *i;
219 if (FD->getType()->isVectorType() &&
220 Context.getTypeSize(FD->getType()) >= 128)
223 if (const RecordType* RT = FD->getType()->getAs<RecordType>())
224 if (typeContainsSSEVector(RT->getDecl(), Context))
232 /// DefaultABIInfo - The default implementation for ABI specific
233 /// details. This implementation provides information which results in
234 /// self-consistent and sensible LLVM IR generation, but does not
235 /// conform to any particular ABI.
236 class DefaultABIInfo : public ABIInfo {
237 ABIArgInfo classifyReturnType(QualType RetTy,
239 llvm::LLVMContext &VMContext) const;
241 ABIArgInfo classifyArgumentType(QualType RetTy,
243 llvm::LLVMContext &VMContext) const;
245 virtual void computeInfo(CGFunctionInfo &FI, ASTContext &Context,
246 llvm::LLVMContext &VMContext) const {
247 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), Context,
249 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
251 it->info = classifyArgumentType(it->type, Context, VMContext);
254 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
255 CodeGenFunction &CGF) const;
258 class DefaultTargetCodeGenInfo : public TargetCodeGenInfo {
260 DefaultTargetCodeGenInfo():TargetCodeGenInfo(new DefaultABIInfo()) {}
263 llvm::Value *DefaultABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
264 CodeGenFunction &CGF) const {
268 ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty,
270 llvm::LLVMContext &VMContext) const {
271 if (CodeGenFunction::hasAggregateLLVMType(Ty)) {
272 return ABIArgInfo::getIndirect(0);
274 // Treat an enum type as its underlying type.
275 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
276 Ty = EnumTy->getDecl()->getIntegerType();
278 return (Ty->isPromotableIntegerType() ?
279 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
283 /// X86_32ABIInfo - The X86-32 ABI information.
284 class X86_32ABIInfo : public ABIInfo {
286 bool IsDarwinVectorABI;
287 bool IsSmallStructInRegABI;
289 static bool isRegisterSize(unsigned Size) {
290 return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
293 static bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context);
295 static unsigned getIndirectArgumentAlignment(QualType Ty,
296 ASTContext &Context);
299 ABIArgInfo classifyReturnType(QualType RetTy,
301 llvm::LLVMContext &VMContext) const;
303 ABIArgInfo classifyArgumentType(QualType RetTy,
305 llvm::LLVMContext &VMContext) const;
307 virtual void computeInfo(CGFunctionInfo &FI, ASTContext &Context,
308 llvm::LLVMContext &VMContext) const {
309 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), Context,
311 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
313 it->info = classifyArgumentType(it->type, Context, VMContext);
316 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
317 CodeGenFunction &CGF) const;
319 X86_32ABIInfo(ASTContext &Context, bool d, bool p)
320 : ABIInfo(), Context(Context), IsDarwinVectorABI(d),
321 IsSmallStructInRegABI(p) {}
324 class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
326 X86_32TargetCodeGenInfo(ASTContext &Context, bool d, bool p)
327 :TargetCodeGenInfo(new X86_32ABIInfo(Context, d, p)) {}
329 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
330 CodeGen::CodeGenModule &CGM) const;
335 /// shouldReturnTypeInRegister - Determine if the given type should be
336 /// passed in a register (for the Darwin ABI).
337 bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
338 ASTContext &Context) {
339 uint64_t Size = Context.getTypeSize(Ty);
341 // Type must be register sized.
342 if (!isRegisterSize(Size))
345 if (Ty->isVectorType()) {
346 // 64- and 128- bit vectors inside structures are not returned in
348 if (Size == 64 || Size == 128)
354 // If this is a builtin, pointer, enum, or complex type, it is ok.
355 if (Ty->getAs<BuiltinType>() || Ty->isAnyPointerType() ||
356 Ty->isAnyComplexType() || Ty->isEnumeralType() ||
357 Ty->isBlockPointerType())
360 // Arrays are treated like records.
361 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
362 return shouldReturnTypeInRegister(AT->getElementType(), Context);
364 // Otherwise, it must be a record type.
365 const RecordType *RT = Ty->getAs<RecordType>();
366 if (!RT) return false;
368 // FIXME: Traverse bases here too.
370 // Structure types are passed in register if all fields would be
371 // passed in a register.
372 for (RecordDecl::field_iterator i = RT->getDecl()->field_begin(),
373 e = RT->getDecl()->field_end(); i != e; ++i) {
374 const FieldDecl *FD = *i;
376 // Empty fields are ignored.
377 if (isEmptyField(Context, FD, true))
380 // Check fields recursively.
381 if (!shouldReturnTypeInRegister(FD->getType(), Context))
388 ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy,
390 llvm::LLVMContext &VMContext) const {
391 if (RetTy->isVoidType()) {
392 return ABIArgInfo::getIgnore();
393 } else if (const VectorType *VT = RetTy->getAs<VectorType>()) {
394 // On Darwin, some vectors are returned in registers.
395 if (IsDarwinVectorABI) {
396 uint64_t Size = Context.getTypeSize(RetTy);
398 // 128-bit vectors are a special case; they are returned in
399 // registers and we need to make sure to pick a type the LLVM
400 // backend will like.
402 return ABIArgInfo::getCoerce(llvm::VectorType::get(
403 llvm::Type::getInt64Ty(VMContext), 2));
405 // Always return in register if it fits in a general purpose
406 // register, or if it is 64 bits and has a single element.
407 if ((Size == 8 || Size == 16 || Size == 32) ||
408 (Size == 64 && VT->getNumElements() == 1))
409 return ABIArgInfo::getCoerce(llvm::IntegerType::get(VMContext, Size));
411 return ABIArgInfo::getIndirect(0);
414 return ABIArgInfo::getDirect();
415 } else if (CodeGenFunction::hasAggregateLLVMType(RetTy)) {
416 if (const RecordType *RT = RetTy->getAs<RecordType>()) {
417 // Structures with either a non-trivial destructor or a non-trivial
418 // copy constructor are always indirect.
419 if (hasNonTrivialDestructorOrCopyConstructor(RT))
420 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
422 // Structures with flexible arrays are always indirect.
423 if (RT->getDecl()->hasFlexibleArrayMember())
424 return ABIArgInfo::getIndirect(0);
427 // If specified, structs and unions are always indirect.
428 if (!IsSmallStructInRegABI && !RetTy->isAnyComplexType())
429 return ABIArgInfo::getIndirect(0);
431 // Classify "single element" structs as their element type.
432 if (const Type *SeltTy = isSingleElementStruct(RetTy, Context)) {
433 if (const BuiltinType *BT = SeltTy->getAs<BuiltinType>()) {
434 if (BT->isIntegerType()) {
435 // We need to use the size of the structure, padding
436 // bit-fields can adjust that to be larger than the single
438 uint64_t Size = Context.getTypeSize(RetTy);
439 return ABIArgInfo::getCoerce(
440 llvm::IntegerType::get(VMContext, (unsigned) Size));
441 } else if (BT->getKind() == BuiltinType::Float) {
442 assert(Context.getTypeSize(RetTy) == Context.getTypeSize(SeltTy) &&
443 "Unexpect single element structure size!");
444 return ABIArgInfo::getCoerce(llvm::Type::getFloatTy(VMContext));
445 } else if (BT->getKind() == BuiltinType::Double) {
446 assert(Context.getTypeSize(RetTy) == Context.getTypeSize(SeltTy) &&
447 "Unexpect single element structure size!");
448 return ABIArgInfo::getCoerce(llvm::Type::getDoubleTy(VMContext));
450 } else if (SeltTy->isPointerType()) {
451 // FIXME: It would be really nice if this could come out as the proper
453 const llvm::Type *PtrTy = llvm::Type::getInt8PtrTy(VMContext);
454 return ABIArgInfo::getCoerce(PtrTy);
455 } else if (SeltTy->isVectorType()) {
456 // 64- and 128-bit vectors are never returned in a
457 // register when inside a structure.
458 uint64_t Size = Context.getTypeSize(RetTy);
459 if (Size == 64 || Size == 128)
460 return ABIArgInfo::getIndirect(0);
462 return classifyReturnType(QualType(SeltTy, 0), Context, VMContext);
466 // Small structures which are register sized are generally returned
468 if (X86_32ABIInfo::shouldReturnTypeInRegister(RetTy, Context)) {
469 uint64_t Size = Context.getTypeSize(RetTy);
470 return ABIArgInfo::getCoerce(llvm::IntegerType::get(VMContext, Size));
473 return ABIArgInfo::getIndirect(0);
475 // Treat an enum type as its underlying type.
476 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
477 RetTy = EnumTy->getDecl()->getIntegerType();
479 return (RetTy->isPromotableIntegerType() ?
480 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
484 unsigned X86_32ABIInfo::getIndirectArgumentAlignment(QualType Ty,
485 ASTContext &Context) {
486 unsigned Align = Context.getTypeAlign(Ty);
487 if (Align < 128) return 0;
488 if (const RecordType* RT = Ty->getAs<RecordType>())
489 if (typeContainsSSEVector(RT->getDecl(), Context))
494 ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
496 llvm::LLVMContext &VMContext) const {
497 // FIXME: Set alignment on indirect arguments.
498 if (CodeGenFunction::hasAggregateLLVMType(Ty)) {
499 // Structures with flexible arrays are always indirect.
500 if (const RecordType *RT = Ty->getAs<RecordType>()) {
501 // Structures with either a non-trivial destructor or a non-trivial
502 // copy constructor are always indirect.
503 if (hasNonTrivialDestructorOrCopyConstructor(RT))
504 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
506 if (RT->getDecl()->hasFlexibleArrayMember())
507 return ABIArgInfo::getIndirect(getIndirectArgumentAlignment(Ty,
511 // Ignore empty structs.
512 if (Ty->isStructureType() && Context.getTypeSize(Ty) == 0)
513 return ABIArgInfo::getIgnore();
515 // Expand small (<= 128-bit) record types when we know that the stack layout
516 // of those arguments will match the struct. This is important because the
517 // LLVM backend isn't smart enough to remove byval, which inhibits many
519 if (Context.getTypeSize(Ty) <= 4*32 &&
520 canExpandIndirectArgument(Ty, Context))
521 return ABIArgInfo::getExpand();
523 return ABIArgInfo::getIndirect(getIndirectArgumentAlignment(Ty, Context));
525 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
526 Ty = EnumTy->getDecl()->getIntegerType();
528 return (Ty->isPromotableIntegerType() ?
529 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
533 llvm::Value *X86_32ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
534 CodeGenFunction &CGF) const {
535 const llvm::Type *BP = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
536 const llvm::Type *BPP = llvm::PointerType::getUnqual(BP);
538 CGBuilderTy &Builder = CGF.Builder;
539 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
541 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
543 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
544 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
547 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 4);
548 llvm::Value *NextAddr =
549 Builder.CreateGEP(Addr, llvm::ConstantInt::get(
550 llvm::Type::getInt32Ty(CGF.getLLVMContext()), Offset),
552 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
557 void X86_32TargetCodeGenInfo::SetTargetAttributes(const Decl *D,
558 llvm::GlobalValue *GV,
559 CodeGen::CodeGenModule &CGM) const {
560 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
561 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
562 // Get the LLVM function.
563 llvm::Function *Fn = cast<llvm::Function>(GV);
565 // Now add the 'alignstack' attribute with a value of 16.
566 Fn->addFnAttr(llvm::Attribute::constructStackAlignmentFromInt(16));
572 /// X86_64ABIInfo - The X86_64 ABI information.
573 class X86_64ABIInfo : public ABIInfo {
585 /// merge - Implement the X86_64 ABI merging algorithm.
587 /// Merge an accumulating classification \arg Accum with a field
588 /// classification \arg Field.
590 /// \param Accum - The accumulating classification. This should
591 /// always be either NoClass or the result of a previous merge
592 /// call. In addition, this should never be Memory (the caller
593 /// should just return Memory for the aggregate).
594 Class merge(Class Accum, Class Field) const;
596 /// classify - Determine the x86_64 register classes in which the
597 /// given type T should be passed.
599 /// \param Lo - The classification for the parts of the type
600 /// residing in the low word of the containing object.
602 /// \param Hi - The classification for the parts of the type
603 /// residing in the high word of the containing object.
605 /// \param OffsetBase - The bit offset of this type in the
606 /// containing object. Some parameters are classified different
607 /// depending on whether they straddle an eightbyte boundary.
609 /// If a word is unused its result will be NoClass; if a type should
610 /// be passed in Memory then at least the classification of \arg Lo
613 /// The \arg Lo class will be NoClass iff the argument is ignored.
615 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
616 /// also be ComplexX87.
617 void classify(QualType T, ASTContext &Context, uint64_t OffsetBase,
618 Class &Lo, Class &Hi) const;
620 /// getCoerceResult - Given a source type \arg Ty and an LLVM type
621 /// to coerce to, chose the best way to pass Ty in the same place
622 /// that \arg CoerceTo would be passed, but while keeping the
623 /// emitted code as simple as possible.
625 /// FIXME: Note, this should be cleaned up to just take an enumeration of all
626 /// the ways we might want to pass things, instead of constructing an LLVM
627 /// type. This makes this code more explicit, and it makes it clearer that we
628 /// are also doing this for correctness in the case of passing scalar types.
629 ABIArgInfo getCoerceResult(QualType Ty,
630 const llvm::Type *CoerceTo,
631 ASTContext &Context) const;
633 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
634 /// such that the argument will be passed in memory.
635 ABIArgInfo getIndirectResult(QualType Ty,
636 ASTContext &Context) const;
638 ABIArgInfo classifyReturnType(QualType RetTy,
640 llvm::LLVMContext &VMContext) const;
642 ABIArgInfo classifyArgumentType(QualType Ty,
644 llvm::LLVMContext &VMContext,
646 unsigned &neededSSE) const;
649 virtual void computeInfo(CGFunctionInfo &FI, ASTContext &Context,
650 llvm::LLVMContext &VMContext) const;
652 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
653 CodeGenFunction &CGF) const;
656 class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
658 X86_64TargetCodeGenInfo():TargetCodeGenInfo(new X86_64ABIInfo()) {}
663 X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum,
665 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
666 // classified recursively so that always two fields are
667 // considered. The resulting class is calculated according to
668 // the classes of the fields in the eightbyte:
670 // (a) If both classes are equal, this is the resulting class.
672 // (b) If one of the classes is NO_CLASS, the resulting class is
675 // (c) If one of the classes is MEMORY, the result is the MEMORY
678 // (d) If one of the classes is INTEGER, the result is the
681 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
682 // MEMORY is used as class.
684 // (f) Otherwise class SSE is used.
686 // Accum should never be memory (we should have returned) or
687 // ComplexX87 (because this cannot be passed in a structure).
688 assert((Accum != Memory && Accum != ComplexX87) &&
689 "Invalid accumulated classification during merge.");
690 if (Accum == Field || Field == NoClass)
692 else if (Field == Memory)
694 else if (Accum == NoClass)
696 else if (Accum == Integer || Field == Integer)
698 else if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
699 Accum == X87 || Accum == X87Up)
705 void X86_64ABIInfo::classify(QualType Ty,
708 Class &Lo, Class &Hi) const {
709 // FIXME: This code can be simplified by introducing a simple value class for
710 // Class pairs with appropriate constructor methods for the various
713 // FIXME: Some of the split computations are wrong; unaligned vectors
714 // shouldn't be passed in registers for example, so there is no chance they
715 // can straddle an eightbyte. Verify & simplify.
719 Class &Current = OffsetBase < 64 ? Lo : Hi;
722 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
723 BuiltinType::Kind k = BT->getKind();
725 if (k == BuiltinType::Void) {
727 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
730 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
732 } else if (k == BuiltinType::Float || k == BuiltinType::Double) {
734 } else if (k == BuiltinType::LongDouble) {
738 // FIXME: _Decimal32 and _Decimal64 are SSE.
739 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
740 } else if (const EnumType *ET = Ty->getAs<EnumType>()) {
741 // Classify the underlying integer type.
742 classify(ET->getDecl()->getIntegerType(), Context, OffsetBase, Lo, Hi);
743 } else if (Ty->hasPointerRepresentation()) {
745 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
746 uint64_t Size = Context.getTypeSize(VT);
748 // gcc passes all <4 x char>, <2 x short>, <1 x int>, <1 x
749 // float> as integer.
752 // If this type crosses an eightbyte boundary, it should be
754 uint64_t EB_Real = (OffsetBase) / 64;
755 uint64_t EB_Imag = (OffsetBase + Size - 1) / 64;
756 if (EB_Real != EB_Imag)
758 } else if (Size == 64) {
759 // gcc passes <1 x double> in memory. :(
760 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double))
763 // gcc passes <1 x long long> as INTEGER.
764 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::LongLong))
769 // If this type crosses an eightbyte boundary, it should be
771 if (OffsetBase && OffsetBase != 64)
773 } else if (Size == 128) {
777 } else if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
778 QualType ET = Context.getCanonicalType(CT->getElementType());
780 uint64_t Size = Context.getTypeSize(Ty);
781 if (ET->isIntegralType()) {
784 else if (Size <= 128)
786 } else if (ET == Context.FloatTy)
788 else if (ET == Context.DoubleTy)
790 else if (ET == Context.LongDoubleTy)
791 Current = ComplexX87;
793 // If this complex type crosses an eightbyte boundary then it
795 uint64_t EB_Real = (OffsetBase) / 64;
796 uint64_t EB_Imag = (OffsetBase + Context.getTypeSize(ET)) / 64;
797 if (Hi == NoClass && EB_Real != EB_Imag)
799 } else if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
800 // Arrays are treated like structures.
802 uint64_t Size = Context.getTypeSize(Ty);
804 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
805 // than two eightbytes, ..., it has class MEMORY.
809 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
810 // fields, it has class MEMORY.
812 // Only need to check alignment of array base.
813 if (OffsetBase % Context.getTypeAlign(AT->getElementType()))
816 // Otherwise implement simplified merge. We could be smarter about
817 // this, but it isn't worth it and would be harder to verify.
819 uint64_t EltSize = Context.getTypeSize(AT->getElementType());
820 uint64_t ArraySize = AT->getSize().getZExtValue();
821 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
822 Class FieldLo, FieldHi;
823 classify(AT->getElementType(), Context, Offset, FieldLo, FieldHi);
824 Lo = merge(Lo, FieldLo);
825 Hi = merge(Hi, FieldHi);
826 if (Lo == Memory || Hi == Memory)
830 // Do post merger cleanup (see below). Only case we worry about is Memory.
833 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
834 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
835 uint64_t Size = Context.getTypeSize(Ty);
837 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
838 // than two eightbytes, ..., it has class MEMORY.
842 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
843 // copy constructor or a non-trivial destructor, it is passed by invisible
845 if (hasNonTrivialDestructorOrCopyConstructor(RT))
848 const RecordDecl *RD = RT->getDecl();
850 // Assume variable sized types are passed in memory.
851 if (RD->hasFlexibleArrayMember())
854 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
856 // Reset Lo class, this will be recomputed.
859 // If this is a C++ record, classify the bases first.
860 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
861 for (CXXRecordDecl::base_class_const_iterator i = CXXRD->bases_begin(),
862 e = CXXRD->bases_end(); i != e; ++i) {
863 assert(!i->isVirtual() && !i->getType()->isDependentType() &&
864 "Unexpected base class!");
865 const CXXRecordDecl *Base =
866 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
868 // Classify this field.
870 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
871 // single eightbyte, each is classified separately. Each eightbyte gets
872 // initialized to class NO_CLASS.
873 Class FieldLo, FieldHi;
874 uint64_t Offset = OffsetBase + Layout.getBaseClassOffset(Base);
875 classify(i->getType(), Context, Offset, FieldLo, FieldHi);
876 Lo = merge(Lo, FieldLo);
877 Hi = merge(Hi, FieldHi);
878 if (Lo == Memory || Hi == Memory)
882 // If this record has no fields but isn't empty, classify as INTEGER.
883 if (RD->field_empty() && Size)
887 // Classify the fields one at a time, merging the results.
889 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
890 i != e; ++i, ++idx) {
891 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
892 bool BitField = i->isBitField();
894 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
895 // fields, it has class MEMORY.
897 // Note, skip this test for bit-fields, see below.
898 if (!BitField && Offset % Context.getTypeAlign(i->getType())) {
903 // Classify this field.
905 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
906 // exceeds a single eightbyte, each is classified
907 // separately. Each eightbyte gets initialized to class
909 Class FieldLo, FieldHi;
911 // Bit-fields require special handling, they do not force the
912 // structure to be passed in memory even if unaligned, and
913 // therefore they can straddle an eightbyte.
915 // Ignore padding bit-fields.
916 if (i->isUnnamedBitfield())
919 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
920 uint64_t Size = i->getBitWidth()->EvaluateAsInt(Context).getZExtValue();
922 uint64_t EB_Lo = Offset / 64;
923 uint64_t EB_Hi = (Offset + Size - 1) / 64;
924 FieldLo = FieldHi = NoClass;
926 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
931 FieldHi = EB_Hi ? Integer : NoClass;
934 classify(i->getType(), Context, Offset, FieldLo, FieldHi);
935 Lo = merge(Lo, FieldLo);
936 Hi = merge(Hi, FieldHi);
937 if (Lo == Memory || Hi == Memory)
941 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
943 // (a) If one of the classes is MEMORY, the whole argument is
946 // (b) If SSEUP is not preceeded by SSE, it is converted to SSE.
948 // The first of these conditions is guaranteed by how we implement
949 // the merge (just bail).
951 // The second condition occurs in the case of unions; for example
952 // union { _Complex double; unsigned; }.
955 if (Hi == SSEUp && Lo != SSE)
960 ABIArgInfo X86_64ABIInfo::getCoerceResult(QualType Ty,
961 const llvm::Type *CoerceTo,
962 ASTContext &Context) const {
963 if (CoerceTo == llvm::Type::getInt64Ty(CoerceTo->getContext())) {
964 // Integer and pointer types will end up in a general purpose
967 // Treat an enum type as its underlying type.
968 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
969 Ty = EnumTy->getDecl()->getIntegerType();
971 if (Ty->isIntegralType() || Ty->hasPointerRepresentation())
972 return (Ty->isPromotableIntegerType() ?
973 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
974 } else if (CoerceTo == llvm::Type::getDoubleTy(CoerceTo->getContext())) {
975 // FIXME: It would probably be better to make CGFunctionInfo only map using
976 // canonical types than to canonize here.
977 QualType CTy = Context.getCanonicalType(Ty);
979 // Float and double end up in a single SSE reg.
980 if (CTy == Context.FloatTy || CTy == Context.DoubleTy)
981 return ABIArgInfo::getDirect();
985 return ABIArgInfo::getCoerce(CoerceTo);
988 ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
989 ASTContext &Context) const {
990 // If this is a scalar LLVM value then assume LLVM will pass it in the right
992 if (!CodeGenFunction::hasAggregateLLVMType(Ty)) {
993 // Treat an enum type as its underlying type.
994 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
995 Ty = EnumTy->getDecl()->getIntegerType();
997 return (Ty->isPromotableIntegerType() ?
998 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
1001 bool ByVal = !isRecordWithNonTrivialDestructorOrCopyConstructor(Ty);
1003 // FIXME: Set alignment correctly.
1004 return ABIArgInfo::getIndirect(0, ByVal);
1007 ABIArgInfo X86_64ABIInfo::classifyReturnType(QualType RetTy,
1008 ASTContext &Context,
1009 llvm::LLVMContext &VMContext) const {
1010 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
1011 // classification algorithm.
1012 X86_64ABIInfo::Class Lo, Hi;
1013 classify(RetTy, Context, 0, Lo, Hi);
1015 // Check some invariants.
1016 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
1017 assert((Lo != NoClass || Hi == NoClass) && "Invalid null classification.");
1018 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
1020 const llvm::Type *ResType = 0;
1023 return ABIArgInfo::getIgnore();
1027 assert(0 && "Invalid classification for lo word.");
1029 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
1032 return getIndirectResult(RetTy, Context);
1034 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
1035 // available register of the sequence %rax, %rdx is used.
1037 ResType = llvm::Type::getInt64Ty(VMContext); break;
1039 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
1040 // available SSE register of the sequence %xmm0, %xmm1 is used.
1042 ResType = llvm::Type::getDoubleTy(VMContext); break;
1044 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
1045 // returned on the X87 stack in %st0 as 80-bit x87 number.
1047 ResType = llvm::Type::getX86_FP80Ty(VMContext); break;
1049 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
1050 // part of the value is returned in %st0 and the imaginary part in
1053 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
1054 ResType = llvm::StructType::get(VMContext, llvm::Type::getX86_FP80Ty(VMContext),
1055 llvm::Type::getX86_FP80Ty(VMContext),
1061 // Memory was handled previously and X87 should
1062 // never occur as a hi class.
1065 assert(0 && "Invalid classification for hi word.");
1067 case ComplexX87: // Previously handled.
1068 case NoClass: break;
1071 ResType = llvm::StructType::get(VMContext, ResType,
1072 llvm::Type::getInt64Ty(VMContext), NULL);
1075 ResType = llvm::StructType::get(VMContext, ResType,
1076 llvm::Type::getDoubleTy(VMContext), NULL);
1079 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
1080 // is passed in the upper half of the last used SSE register.
1082 // SSEUP should always be preceeded by SSE, just widen.
1084 assert(Lo == SSE && "Unexpected SSEUp classification.");
1085 ResType = llvm::VectorType::get(llvm::Type::getDoubleTy(VMContext), 2);
1088 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
1089 // returned together with the previous X87 value in %st0.
1091 // If X87Up is preceeded by X87, we don't need to do
1092 // anything. However, in some cases with unions it may not be
1093 // preceeded by X87. In such situations we follow gcc and pass the
1094 // extra bits in an SSE reg.
1096 ResType = llvm::StructType::get(VMContext, ResType,
1097 llvm::Type::getDoubleTy(VMContext), NULL);
1101 return getCoerceResult(RetTy, ResType, Context);
1104 ABIArgInfo X86_64ABIInfo::classifyArgumentType(QualType Ty, ASTContext &Context,
1105 llvm::LLVMContext &VMContext,
1106 unsigned &neededInt,
1107 unsigned &neededSSE) const {
1108 X86_64ABIInfo::Class Lo, Hi;
1109 classify(Ty, Context, 0, Lo, Hi);
1111 // Check some invariants.
1112 // FIXME: Enforce these by construction.
1113 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
1114 assert((Lo != NoClass || Hi == NoClass) && "Invalid null classification.");
1115 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
1119 const llvm::Type *ResType = 0;
1122 return ABIArgInfo::getIgnore();
1124 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
1128 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
1129 // COMPLEX_X87, it is passed in memory.
1132 return getIndirectResult(Ty, Context);
1136 assert(0 && "Invalid classification for lo word.");
1138 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
1139 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
1143 ResType = llvm::Type::getInt64Ty(VMContext);
1146 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
1147 // available SSE register is used, the registers are taken in the
1148 // order from %xmm0 to %xmm7.
1151 ResType = llvm::Type::getDoubleTy(VMContext);
1156 // Memory was handled previously, ComplexX87 and X87 should
1157 // never occur as hi classes, and X87Up must be preceed by X87,
1158 // which is passed in memory.
1162 assert(0 && "Invalid classification for hi word.");
1165 case NoClass: break;
1167 ResType = llvm::StructType::get(VMContext, ResType,
1168 llvm::Type::getInt64Ty(VMContext), NULL);
1172 // X87Up generally doesn't occur here (long double is passed in
1173 // memory), except in situations involving unions.
1176 ResType = llvm::StructType::get(VMContext, ResType,
1177 llvm::Type::getDoubleTy(VMContext), NULL);
1181 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
1182 // eightbyte is passed in the upper half of the last used SSE
1185 assert(Lo == SSE && "Unexpected SSEUp classification.");
1186 ResType = llvm::VectorType::get(llvm::Type::getDoubleTy(VMContext), 2);
1190 return getCoerceResult(Ty, ResType, Context);
1193 void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI, ASTContext &Context,
1194 llvm::LLVMContext &VMContext) const {
1195 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(),
1196 Context, VMContext);
1198 // Keep track of the number of assigned registers.
1199 unsigned freeIntRegs = 6, freeSSERegs = 8;
1201 // If the return value is indirect, then the hidden argument is consuming one
1202 // integer register.
1203 if (FI.getReturnInfo().isIndirect())
1206 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
1207 // get assigned (in left-to-right order) for passing as follows...
1208 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
1210 unsigned neededInt, neededSSE;
1211 it->info = classifyArgumentType(it->type, Context, VMContext,
1212 neededInt, neededSSE);
1214 // AMD64-ABI 3.2.3p3: If there are no registers available for any
1215 // eightbyte of an argument, the whole argument is passed on the
1216 // stack. If registers have already been assigned for some
1217 // eightbytes of such an argument, the assignments get reverted.
1218 if (freeIntRegs >= neededInt && freeSSERegs >= neededSSE) {
1219 freeIntRegs -= neededInt;
1220 freeSSERegs -= neededSSE;
1222 it->info = getIndirectResult(it->type, Context);
1227 static llvm::Value *EmitVAArgFromMemory(llvm::Value *VAListAddr,
1229 CodeGenFunction &CGF) {
1230 llvm::Value *overflow_arg_area_p =
1231 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_p");
1232 llvm::Value *overflow_arg_area =
1233 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
1235 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
1236 // byte boundary if alignment needed by type exceeds 8 byte boundary.
1237 uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8;
1239 // Note that we follow the ABI & gcc here, even though the type
1240 // could in theory have an alignment greater than 16. This case
1241 // shouldn't ever matter in practice.
1243 // overflow_arg_area = (overflow_arg_area + 15) & ~15;
1244 llvm::Value *Offset =
1245 llvm::ConstantInt::get(llvm::Type::getInt32Ty(CGF.getLLVMContext()), 15);
1246 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset);
1247 llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(overflow_arg_area,
1248 llvm::Type::getInt64Ty(CGF.getLLVMContext()));
1249 llvm::Value *Mask = llvm::ConstantInt::get(
1250 llvm::Type::getInt64Ty(CGF.getLLVMContext()), ~15LL);
1252 CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask),
1253 overflow_arg_area->getType(),
1254 "overflow_arg_area.align");
1257 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
1258 const llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
1260 CGF.Builder.CreateBitCast(overflow_arg_area,
1261 llvm::PointerType::getUnqual(LTy));
1263 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
1264 // l->overflow_arg_area + sizeof(type).
1265 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
1266 // an 8 byte boundary.
1268 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
1269 llvm::Value *Offset =
1270 llvm::ConstantInt::get(llvm::Type::getInt32Ty(CGF.getLLVMContext()),
1271 (SizeInBytes + 7) & ~7);
1272 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
1273 "overflow_arg_area.next");
1274 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
1276 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
1280 llvm::Value *X86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1281 CodeGenFunction &CGF) const {
1282 llvm::LLVMContext &VMContext = CGF.getLLVMContext();
1283 const llvm::Type *i32Ty = llvm::Type::getInt32Ty(VMContext);
1284 const llvm::Type *DoubleTy = llvm::Type::getDoubleTy(VMContext);
1286 // Assume that va_list type is correct; should be pointer to LLVM type:
1290 // i8* overflow_arg_area;
1291 // i8* reg_save_area;
1293 unsigned neededInt, neededSSE;
1294 ABIArgInfo AI = classifyArgumentType(Ty, CGF.getContext(), VMContext,
1295 neededInt, neededSSE);
1297 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
1298 // in the registers. If not go to step 7.
1299 if (!neededInt && !neededSSE)
1300 return EmitVAArgFromMemory(VAListAddr, Ty, CGF);
1302 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
1303 // general purpose registers needed to pass type and num_fp to hold
1304 // the number of floating point registers needed.
1306 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
1307 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
1308 // l->fp_offset > 304 - num_fp * 16 go to step 7.
1310 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
1311 // register save space).
1313 llvm::Value *InRegs = 0;
1314 llvm::Value *gp_offset_p = 0, *gp_offset = 0;
1315 llvm::Value *fp_offset_p = 0, *fp_offset = 0;
1317 gp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "gp_offset_p");
1318 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
1320 CGF.Builder.CreateICmpULE(gp_offset,
1321 llvm::ConstantInt::get(i32Ty,
1322 48 - neededInt * 8),
1327 fp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 1, "fp_offset_p");
1328 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
1329 llvm::Value *FitsInFP =
1330 CGF.Builder.CreateICmpULE(fp_offset,
1331 llvm::ConstantInt::get(i32Ty,
1332 176 - neededSSE * 16),
1334 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
1337 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
1338 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
1339 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
1340 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
1342 // Emit code to load the value if it was passed in registers.
1344 CGF.EmitBlock(InRegBlock);
1346 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
1347 // an offset of l->gp_offset and/or l->fp_offset. This may require
1348 // copying to a temporary location in case the parameter is passed
1349 // in different register classes or requires an alignment greater
1350 // than 8 for general purpose registers and 16 for XMM registers.
1352 // FIXME: This really results in shameful code when we end up needing to
1353 // collect arguments from different places; often what should result in a
1354 // simple assembling of a structure from scattered addresses has many more
1355 // loads than necessary. Can we clean this up?
1356 const llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
1357 llvm::Value *RegAddr =
1358 CGF.Builder.CreateLoad(CGF.Builder.CreateStructGEP(VAListAddr, 3),
1360 if (neededInt && neededSSE) {
1362 assert(AI.isCoerce() && "Unexpected ABI info for mixed regs");
1363 const llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
1364 llvm::Value *Tmp = CGF.CreateTempAlloca(ST);
1365 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
1366 const llvm::Type *TyLo = ST->getElementType(0);
1367 const llvm::Type *TyHi = ST->getElementType(1);
1368 assert((TyLo->isFloatingPointTy() ^ TyHi->isFloatingPointTy()) &&
1369 "Unexpected ABI info for mixed regs");
1370 const llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
1371 const llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
1372 llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
1373 llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
1374 llvm::Value *RegLoAddr = TyLo->isFloatingPointTy() ? FPAddr : GPAddr;
1375 llvm::Value *RegHiAddr = TyLo->isFloatingPointTy() ? GPAddr : FPAddr;
1377 CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegLoAddr, PTyLo));
1378 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
1379 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegHiAddr, PTyHi));
1380 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
1382 RegAddr = CGF.Builder.CreateBitCast(Tmp,
1383 llvm::PointerType::getUnqual(LTy));
1384 } else if (neededInt) {
1385 RegAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
1386 RegAddr = CGF.Builder.CreateBitCast(RegAddr,
1387 llvm::PointerType::getUnqual(LTy));
1389 if (neededSSE == 1) {
1390 RegAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
1391 RegAddr = CGF.Builder.CreateBitCast(RegAddr,
1392 llvm::PointerType::getUnqual(LTy));
1394 assert(neededSSE == 2 && "Invalid number of needed registers!");
1395 // SSE registers are spaced 16 bytes apart in the register save
1396 // area, we need to collect the two eightbytes together.
1397 llvm::Value *RegAddrLo = CGF.Builder.CreateGEP(RegAddr, fp_offset);
1398 llvm::Value *RegAddrHi =
1399 CGF.Builder.CreateGEP(RegAddrLo,
1400 llvm::ConstantInt::get(i32Ty, 16));
1401 const llvm::Type *DblPtrTy =
1402 llvm::PointerType::getUnqual(DoubleTy);
1403 const llvm::StructType *ST = llvm::StructType::get(VMContext, DoubleTy,
1405 llvm::Value *V, *Tmp = CGF.CreateTempAlloca(ST);
1406 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrLo,
1408 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
1409 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrHi,
1411 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
1412 RegAddr = CGF.Builder.CreateBitCast(Tmp,
1413 llvm::PointerType::getUnqual(LTy));
1417 // AMD64-ABI 3.5.7p5: Step 5. Set:
1418 // l->gp_offset = l->gp_offset + num_gp * 8
1419 // l->fp_offset = l->fp_offset + num_fp * 16.
1421 llvm::Value *Offset = llvm::ConstantInt::get(i32Ty, neededInt * 8);
1422 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
1426 llvm::Value *Offset = llvm::ConstantInt::get(i32Ty, neededSSE * 16);
1427 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
1430 CGF.EmitBranch(ContBlock);
1432 // Emit code to load the value if it was passed in memory.
1434 CGF.EmitBlock(InMemBlock);
1435 llvm::Value *MemAddr = EmitVAArgFromMemory(VAListAddr, Ty, CGF);
1437 // Return the appropriate result.
1439 CGF.EmitBlock(ContBlock);
1440 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(RegAddr->getType(),
1442 ResAddr->reserveOperandSpace(2);
1443 ResAddr->addIncoming(RegAddr, InRegBlock);
1444 ResAddr->addIncoming(MemAddr, InMemBlock);
1449 // PIC16 ABI Implementation
1453 class PIC16ABIInfo : public ABIInfo {
1454 ABIArgInfo classifyReturnType(QualType RetTy,
1455 ASTContext &Context,
1456 llvm::LLVMContext &VMContext) const;
1458 ABIArgInfo classifyArgumentType(QualType RetTy,
1459 ASTContext &Context,
1460 llvm::LLVMContext &VMContext) const;
1462 virtual void computeInfo(CGFunctionInfo &FI, ASTContext &Context,
1463 llvm::LLVMContext &VMContext) const {
1464 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), Context,
1466 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
1468 it->info = classifyArgumentType(it->type, Context, VMContext);
1471 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1472 CodeGenFunction &CGF) const;
1475 class PIC16TargetCodeGenInfo : public TargetCodeGenInfo {
1477 PIC16TargetCodeGenInfo():TargetCodeGenInfo(new PIC16ABIInfo()) {}
1482 ABIArgInfo PIC16ABIInfo::classifyReturnType(QualType RetTy,
1483 ASTContext &Context,
1484 llvm::LLVMContext &VMContext) const {
1485 if (RetTy->isVoidType()) {
1486 return ABIArgInfo::getIgnore();
1488 return ABIArgInfo::getDirect();
1492 ABIArgInfo PIC16ABIInfo::classifyArgumentType(QualType Ty,
1493 ASTContext &Context,
1494 llvm::LLVMContext &VMContext) const {
1495 return ABIArgInfo::getDirect();
1498 llvm::Value *PIC16ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1499 CodeGenFunction &CGF) const {
1503 // ARM ABI Implementation
1507 class ARMABIInfo : public ABIInfo {
1519 ARMABIInfo(ABIKind _Kind) : Kind(_Kind) {}
1522 ABIKind getABIKind() const { return Kind; }
1524 ABIArgInfo classifyReturnType(QualType RetTy,
1525 ASTContext &Context,
1526 llvm::LLVMContext &VMCOntext) const;
1528 ABIArgInfo classifyArgumentType(QualType RetTy,
1529 ASTContext &Context,
1530 llvm::LLVMContext &VMContext) const;
1532 virtual void computeInfo(CGFunctionInfo &FI, ASTContext &Context,
1533 llvm::LLVMContext &VMContext) const;
1535 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1536 CodeGenFunction &CGF) const;
1539 class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
1541 ARMTargetCodeGenInfo(ARMABIInfo::ABIKind K)
1542 :TargetCodeGenInfo(new ARMABIInfo(K)) {}
1547 void ARMABIInfo::computeInfo(CGFunctionInfo &FI, ASTContext &Context,
1548 llvm::LLVMContext &VMContext) const {
1549 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), Context,
1551 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
1553 it->info = classifyArgumentType(it->type, Context, VMContext);
1556 // ARM always overrides the calling convention.
1557 switch (getABIKind()) {
1559 FI.setEffectiveCallingConvention(llvm::CallingConv::ARM_APCS);
1563 FI.setEffectiveCallingConvention(llvm::CallingConv::ARM_AAPCS);
1567 FI.setEffectiveCallingConvention(llvm::CallingConv::ARM_AAPCS_VFP);
1572 ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty,
1573 ASTContext &Context,
1574 llvm::LLVMContext &VMContext) const {
1575 if (!CodeGenFunction::hasAggregateLLVMType(Ty)) {
1576 // Treat an enum type as its underlying type.
1577 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1578 Ty = EnumTy->getDecl()->getIntegerType();
1580 return (Ty->isPromotableIntegerType() ?
1581 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
1584 // Ignore empty records.
1585 if (isEmptyRecord(Context, Ty, true))
1586 return ABIArgInfo::getIgnore();
1588 // FIXME: This is kind of nasty... but there isn't much choice because the ARM
1589 // backend doesn't support byval.
1590 // FIXME: This doesn't handle alignment > 64 bits.
1591 const llvm::Type* ElemTy;
1593 if (Context.getTypeAlign(Ty) > 32) {
1594 ElemTy = llvm::Type::getInt64Ty(VMContext);
1595 SizeRegs = (Context.getTypeSize(Ty) + 63) / 64;
1597 ElemTy = llvm::Type::getInt32Ty(VMContext);
1598 SizeRegs = (Context.getTypeSize(Ty) + 31) / 32;
1600 std::vector<const llvm::Type*> LLVMFields;
1601 LLVMFields.push_back(llvm::ArrayType::get(ElemTy, SizeRegs));
1602 const llvm::Type* STy = llvm::StructType::get(VMContext, LLVMFields, true);
1603 return ABIArgInfo::getCoerce(STy);
1606 static bool isIntegerLikeType(QualType Ty,
1607 ASTContext &Context,
1608 llvm::LLVMContext &VMContext) {
1609 // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
1610 // is called integer-like if its size is less than or equal to one word, and
1611 // the offset of each of its addressable sub-fields is zero.
1613 uint64_t Size = Context.getTypeSize(Ty);
1615 // Check that the type fits in a word.
1619 // FIXME: Handle vector types!
1620 if (Ty->isVectorType())
1623 // Float types are never treated as "integer like".
1624 if (Ty->isRealFloatingType())
1627 // If this is a builtin or pointer type then it is ok.
1628 if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
1631 // Small complex integer types are "integer like".
1632 if (const ComplexType *CT = Ty->getAs<ComplexType>())
1633 return isIntegerLikeType(CT->getElementType(), Context, VMContext);
1635 // Single element and zero sized arrays should be allowed, by the definition
1636 // above, but they are not.
1638 // Otherwise, it must be a record type.
1639 const RecordType *RT = Ty->getAs<RecordType>();
1640 if (!RT) return false;
1642 // Ignore records with flexible arrays.
1643 const RecordDecl *RD = RT->getDecl();
1644 if (RD->hasFlexibleArrayMember())
1647 // Check that all sub-fields are at offset 0, and are themselves "integer
1649 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1651 bool HadField = false;
1653 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
1654 i != e; ++i, ++idx) {
1655 const FieldDecl *FD = *i;
1657 // Bit-fields are not addressable, we only need to verify they are "integer
1658 // like". We still have to disallow a subsequent non-bitfield, for example:
1659 // struct { int : 0; int x }
1660 // is non-integer like according to gcc.
1661 if (FD->isBitField()) {
1665 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
1671 // Check if this field is at offset 0.
1672 if (Layout.getFieldOffset(idx) != 0)
1675 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
1678 // Only allow at most one field in a structure. This doesn't match the
1679 // wording above, but follows gcc in situations with a field following an
1681 if (!RD->isUnion()) {
1692 ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy,
1693 ASTContext &Context,
1694 llvm::LLVMContext &VMContext) const {
1695 if (RetTy->isVoidType())
1696 return ABIArgInfo::getIgnore();
1698 if (!CodeGenFunction::hasAggregateLLVMType(RetTy)) {
1699 // Treat an enum type as its underlying type.
1700 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
1701 RetTy = EnumTy->getDecl()->getIntegerType();
1703 return (RetTy->isPromotableIntegerType() ?
1704 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
1707 // Are we following APCS?
1708 if (getABIKind() == APCS) {
1709 if (isEmptyRecord(Context, RetTy, false))
1710 return ABIArgInfo::getIgnore();
1712 // Complex types are all returned as packed integers.
1714 // FIXME: Consider using 2 x vector types if the back end handles them
1716 if (RetTy->isAnyComplexType())
1717 return ABIArgInfo::getCoerce(llvm::IntegerType::get(
1718 VMContext, Context.getTypeSize(RetTy)));
1720 // Integer like structures are returned in r0.
1721 if (isIntegerLikeType(RetTy, Context, VMContext)) {
1722 // Return in the smallest viable integer type.
1723 uint64_t Size = Context.getTypeSize(RetTy);
1725 return ABIArgInfo::getCoerce(llvm::Type::getInt8Ty(VMContext));
1727 return ABIArgInfo::getCoerce(llvm::Type::getInt16Ty(VMContext));
1728 return ABIArgInfo::getCoerce(llvm::Type::getInt32Ty(VMContext));
1731 // Otherwise return in memory.
1732 return ABIArgInfo::getIndirect(0);
1735 // Otherwise this is an AAPCS variant.
1737 if (isEmptyRecord(Context, RetTy, true))
1738 return ABIArgInfo::getIgnore();
1740 // Aggregates <= 4 bytes are returned in r0; other aggregates
1741 // are returned indirectly.
1742 uint64_t Size = Context.getTypeSize(RetTy);
1744 // Return in the smallest viable integer type.
1746 return ABIArgInfo::getCoerce(llvm::Type::getInt8Ty(VMContext));
1748 return ABIArgInfo::getCoerce(llvm::Type::getInt16Ty(VMContext));
1749 return ABIArgInfo::getCoerce(llvm::Type::getInt32Ty(VMContext));
1752 return ABIArgInfo::getIndirect(0);
1755 llvm::Value *ARMABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1756 CodeGenFunction &CGF) const {
1757 // FIXME: Need to handle alignment
1758 const llvm::Type *BP = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
1759 const llvm::Type *BPP = llvm::PointerType::getUnqual(BP);
1761 CGBuilderTy &Builder = CGF.Builder;
1762 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
1764 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
1766 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
1767 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
1770 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 4);
1771 llvm::Value *NextAddr =
1772 Builder.CreateGEP(Addr, llvm::ConstantInt::get(
1773 llvm::Type::getInt32Ty(CGF.getLLVMContext()), Offset),
1775 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
1780 ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy,
1781 ASTContext &Context,
1782 llvm::LLVMContext &VMContext) const {
1783 if (RetTy->isVoidType()) {
1784 return ABIArgInfo::getIgnore();
1785 } else if (CodeGenFunction::hasAggregateLLVMType(RetTy)) {
1786 return ABIArgInfo::getIndirect(0);
1788 // Treat an enum type as its underlying type.
1789 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
1790 RetTy = EnumTy->getDecl()->getIntegerType();
1792 return (RetTy->isPromotableIntegerType() ?
1793 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
1797 // SystemZ ABI Implementation
1801 class SystemZABIInfo : public ABIInfo {
1802 bool isPromotableIntegerType(QualType Ty) const;
1804 ABIArgInfo classifyReturnType(QualType RetTy, ASTContext &Context,
1805 llvm::LLVMContext &VMContext) const;
1807 ABIArgInfo classifyArgumentType(QualType RetTy, ASTContext &Context,
1808 llvm::LLVMContext &VMContext) const;
1810 virtual void computeInfo(CGFunctionInfo &FI, ASTContext &Context,
1811 llvm::LLVMContext &VMContext) const {
1812 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(),
1813 Context, VMContext);
1814 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
1816 it->info = classifyArgumentType(it->type, Context, VMContext);
1819 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1820 CodeGenFunction &CGF) const;
1823 class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
1825 SystemZTargetCodeGenInfo():TargetCodeGenInfo(new SystemZABIInfo()) {}
1830 bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const {
1831 // SystemZ ABI requires all 8, 16 and 32 bit quantities to be extended.
1832 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
1833 switch (BT->getKind()) {
1834 case BuiltinType::Bool:
1835 case BuiltinType::Char_S:
1836 case BuiltinType::Char_U:
1837 case BuiltinType::SChar:
1838 case BuiltinType::UChar:
1839 case BuiltinType::Short:
1840 case BuiltinType::UShort:
1841 case BuiltinType::Int:
1842 case BuiltinType::UInt:
1850 llvm::Value *SystemZABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1851 CodeGenFunction &CGF) const {
1857 ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy,
1858 ASTContext &Context,
1859 llvm::LLVMContext &VMContext) const {
1860 if (RetTy->isVoidType()) {
1861 return ABIArgInfo::getIgnore();
1862 } else if (CodeGenFunction::hasAggregateLLVMType(RetTy)) {
1863 return ABIArgInfo::getIndirect(0);
1865 return (isPromotableIntegerType(RetTy) ?
1866 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
1870 ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty,
1871 ASTContext &Context,
1872 llvm::LLVMContext &VMContext) const {
1873 if (CodeGenFunction::hasAggregateLLVMType(Ty)) {
1874 return ABIArgInfo::getIndirect(0);
1876 return (isPromotableIntegerType(Ty) ?
1877 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
1881 // MSP430 ABI Implementation
1885 class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
1887 MSP430TargetCodeGenInfo():TargetCodeGenInfo(new DefaultABIInfo()) {}
1888 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
1889 CodeGen::CodeGenModule &M) const;
1894 void MSP430TargetCodeGenInfo::SetTargetAttributes(const Decl *D,
1895 llvm::GlobalValue *GV,
1896 CodeGen::CodeGenModule &M) const {
1897 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1898 if (const MSP430InterruptAttr *attr = FD->getAttr<MSP430InterruptAttr>()) {
1899 // Handle 'interrupt' attribute:
1900 llvm::Function *F = cast<llvm::Function>(GV);
1902 // Step 1: Set ISR calling convention.
1903 F->setCallingConv(llvm::CallingConv::MSP430_INTR);
1905 // Step 2: Add attributes goodness.
1906 F->addFnAttr(llvm::Attribute::NoInline);
1908 // Step 3: Emit ISR vector alias.
1909 unsigned Num = attr->getNumber() + 0xffe0;
1910 new llvm::GlobalAlias(GV->getType(), llvm::Function::ExternalLinkage,
1912 llvm::LowercaseString(llvm::utohexstr(Num)),
1913 GV, &M.getModule());
1918 const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() const {
1919 if (TheTargetCodeGenInfo)
1920 return *TheTargetCodeGenInfo;
1922 // For now we just cache the TargetCodeGenInfo in CodeGenModule and don't
1925 const llvm::Triple &Triple(getContext().Target.getTriple());
1926 switch (Triple.getArch()) {
1928 return *(TheTargetCodeGenInfo = new DefaultTargetCodeGenInfo);
1930 case llvm::Triple::arm:
1931 case llvm::Triple::thumb:
1932 // FIXME: We want to know the float calling convention as well.
1933 if (strcmp(getContext().Target.getABI(), "apcs-gnu") == 0)
1934 return *(TheTargetCodeGenInfo =
1935 new ARMTargetCodeGenInfo(ARMABIInfo::APCS));
1937 return *(TheTargetCodeGenInfo =
1938 new ARMTargetCodeGenInfo(ARMABIInfo::AAPCS));
1940 case llvm::Triple::pic16:
1941 return *(TheTargetCodeGenInfo = new PIC16TargetCodeGenInfo());
1943 case llvm::Triple::systemz:
1944 return *(TheTargetCodeGenInfo = new SystemZTargetCodeGenInfo());
1946 case llvm::Triple::msp430:
1947 return *(TheTargetCodeGenInfo = new MSP430TargetCodeGenInfo());
1949 case llvm::Triple::x86:
1950 switch (Triple.getOS()) {
1951 case llvm::Triple::Darwin:
1952 return *(TheTargetCodeGenInfo =
1953 new X86_32TargetCodeGenInfo(Context, true, true));
1954 case llvm::Triple::Cygwin:
1955 case llvm::Triple::MinGW32:
1956 case llvm::Triple::MinGW64:
1957 case llvm::Triple::AuroraUX:
1958 case llvm::Triple::DragonFly:
1959 case llvm::Triple::FreeBSD:
1960 case llvm::Triple::OpenBSD:
1961 return *(TheTargetCodeGenInfo =
1962 new X86_32TargetCodeGenInfo(Context, false, true));
1965 return *(TheTargetCodeGenInfo =
1966 new X86_32TargetCodeGenInfo(Context, false, false));
1969 case llvm::Triple::x86_64:
1970 return *(TheTargetCodeGenInfo = new X86_64TargetCodeGenInfo());