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 "clang/Frontend/CodeGenOptions.h"
20 #include "llvm/Type.h"
21 #include "llvm/Target/TargetData.h"
22 #include "llvm/ADT/Triple.h"
23 #include "llvm/Support/raw_ostream.h"
24 using namespace clang;
25 using namespace CodeGen;
27 static void AssignToArrayRange(CodeGen::CGBuilderTy &Builder,
32 // Alternatively, we could emit this as a loop in the source.
33 for (unsigned I = FirstIndex; I <= LastIndex; ++I) {
34 llvm::Value *Cell = Builder.CreateConstInBoundsGEP1_32(Array, I);
35 Builder.CreateStore(Value, Cell);
39 static bool isAggregateTypeForABI(QualType T) {
40 return CodeGenFunction::hasAggregateLLVMType(T) ||
41 T->isMemberFunctionPointerType();
44 ABIInfo::~ABIInfo() {}
46 ASTContext &ABIInfo::getContext() const {
47 return CGT.getContext();
50 llvm::LLVMContext &ABIInfo::getVMContext() const {
51 return CGT.getLLVMContext();
54 const llvm::TargetData &ABIInfo::getTargetData() const {
55 return CGT.getTargetData();
59 void ABIArgInfo::dump() const {
60 raw_ostream &OS = llvm::errs();
61 OS << "(ABIArgInfo Kind=";
65 if (llvm::Type *Ty = getCoerceToType())
77 OS << "Indirect Align=" << getIndirectAlign()
78 << " ByVal=" << getIndirectByVal()
79 << " Realign=" << getIndirectRealign();
88 TargetCodeGenInfo::~TargetCodeGenInfo() { delete Info; }
90 // If someone can figure out a general rule for this, that would be great.
91 // It's probably just doomed to be platform-dependent, though.
92 unsigned TargetCodeGenInfo::getSizeOfUnwindException() const {
94 // x86-64 FreeBSD, Linux, Darwin
95 // x86-32 FreeBSD, Linux, Darwin
96 // PowerPC Linux, Darwin
97 // ARM Darwin (*not* EABI)
101 bool TargetCodeGenInfo::isNoProtoCallVariadic(CallingConv CC) const {
102 // The following conventions are known to require this to be false:
105 // For everything else, we just prefer false unless we opt out.
109 static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays);
111 /// isEmptyField - Return true iff a the field is "empty", that is it
112 /// is an unnamed bit-field or an (array of) empty record(s).
113 static bool isEmptyField(ASTContext &Context, const FieldDecl *FD,
115 if (FD->isUnnamedBitfield())
118 QualType FT = FD->getType();
120 // Constant arrays of empty records count as empty, strip them off.
122 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT))
123 FT = AT->getElementType();
125 const RecordType *RT = FT->getAs<RecordType>();
129 // C++ record fields are never empty, at least in the Itanium ABI.
131 // FIXME: We should use a predicate for whether this behavior is true in the
133 if (isa<CXXRecordDecl>(RT->getDecl()))
136 return isEmptyRecord(Context, FT, AllowArrays);
139 /// isEmptyRecord - Return true iff a structure contains only empty
140 /// fields. Note that a structure with a flexible array member is not
141 /// considered empty.
142 static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) {
143 const RecordType *RT = T->getAs<RecordType>();
146 const RecordDecl *RD = RT->getDecl();
147 if (RD->hasFlexibleArrayMember())
150 // If this is a C++ record, check the bases first.
151 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
152 for (CXXRecordDecl::base_class_const_iterator i = CXXRD->bases_begin(),
153 e = CXXRD->bases_end(); i != e; ++i)
154 if (!isEmptyRecord(Context, i->getType(), true))
157 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
159 if (!isEmptyField(Context, *i, AllowArrays))
164 /// hasNonTrivialDestructorOrCopyConstructor - Determine if a type has either
165 /// a non-trivial destructor or a non-trivial copy constructor.
166 static bool hasNonTrivialDestructorOrCopyConstructor(const RecordType *RT) {
167 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
171 return !RD->hasTrivialDestructor() || !RD->hasTrivialCopyConstructor();
174 /// isRecordWithNonTrivialDestructorOrCopyConstructor - Determine if a type is
175 /// a record type with either a non-trivial destructor or a non-trivial copy
177 static bool isRecordWithNonTrivialDestructorOrCopyConstructor(QualType T) {
178 const RecordType *RT = T->getAs<RecordType>();
182 return hasNonTrivialDestructorOrCopyConstructor(RT);
185 /// isSingleElementStruct - Determine if a structure is a "single
186 /// element struct", i.e. it has exactly one non-empty field or
187 /// exactly one field which is itself a single element
188 /// struct. Structures with flexible array members are never
189 /// considered single element structs.
191 /// \return The field declaration for the single non-empty field, if
193 static const Type *isSingleElementStruct(QualType T, ASTContext &Context) {
194 const RecordType *RT = T->getAsStructureType();
198 const RecordDecl *RD = RT->getDecl();
199 if (RD->hasFlexibleArrayMember())
202 const Type *Found = 0;
204 // If this is a C++ record, check the bases first.
205 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
206 for (CXXRecordDecl::base_class_const_iterator i = CXXRD->bases_begin(),
207 e = CXXRD->bases_end(); i != e; ++i) {
208 // Ignore empty records.
209 if (isEmptyRecord(Context, i->getType(), true))
212 // If we already found an element then this isn't a single-element struct.
216 // If this is non-empty and not a single element struct, the composite
217 // cannot be a single element struct.
218 Found = isSingleElementStruct(i->getType(), Context);
224 // Check for single element.
225 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
227 const FieldDecl *FD = *i;
228 QualType FT = FD->getType();
230 // Ignore empty fields.
231 if (isEmptyField(Context, FD, true))
234 // If we already found an element then this isn't a single-element
239 // Treat single element arrays as the element.
240 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
241 if (AT->getSize().getZExtValue() != 1)
243 FT = AT->getElementType();
246 if (!isAggregateTypeForABI(FT)) {
247 Found = FT.getTypePtr();
249 Found = isSingleElementStruct(FT, Context);
258 static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
259 if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() &&
260 !Ty->isAnyComplexType() && !Ty->isEnumeralType() &&
261 !Ty->isBlockPointerType())
264 uint64_t Size = Context.getTypeSize(Ty);
265 return Size == 32 || Size == 64;
268 /// canExpandIndirectArgument - Test whether an argument type which is to be
269 /// passed indirectly (on the stack) would have the equivalent layout if it was
270 /// expanded into separate arguments. If so, we prefer to do the latter to avoid
271 /// inhibiting optimizations.
273 // FIXME: This predicate is missing many cases, currently it just follows
274 // llvm-gcc (checks that all fields are 32-bit or 64-bit primitive types). We
275 // should probably make this smarter, or better yet make the LLVM backend
276 // capable of handling it.
277 static bool canExpandIndirectArgument(QualType Ty, ASTContext &Context) {
278 // We can only expand structure types.
279 const RecordType *RT = Ty->getAs<RecordType>();
283 // We can only expand (C) structures.
285 // FIXME: This needs to be generalized to handle classes as well.
286 const RecordDecl *RD = RT->getDecl();
287 if (!RD->isStruct() || isa<CXXRecordDecl>(RD))
290 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
292 const FieldDecl *FD = *i;
294 if (!is32Or64BitBasicType(FD->getType(), Context))
297 // FIXME: Reject bit-fields wholesale; there are two problems, we don't know
298 // how to expand them yet, and the predicate for telling if a bitfield still
299 // counts as "basic" is more complicated than what we were doing previously.
300 if (FD->isBitField())
308 /// DefaultABIInfo - The default implementation for ABI specific
309 /// details. This implementation provides information which results in
310 /// self-consistent and sensible LLVM IR generation, but does not
311 /// conform to any particular ABI.
312 class DefaultABIInfo : public ABIInfo {
314 DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
316 ABIArgInfo classifyReturnType(QualType RetTy) const;
317 ABIArgInfo classifyArgumentType(QualType RetTy) const;
319 virtual void computeInfo(CGFunctionInfo &FI) const {
320 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
321 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
323 it->info = classifyArgumentType(it->type);
326 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
327 CodeGenFunction &CGF) const;
330 class DefaultTargetCodeGenInfo : public TargetCodeGenInfo {
332 DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
333 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
336 llvm::Value *DefaultABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
337 CodeGenFunction &CGF) const {
341 ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const {
342 if (isAggregateTypeForABI(Ty))
343 return ABIArgInfo::getIndirect(0);
345 // Treat an enum type as its underlying type.
346 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
347 Ty = EnumTy->getDecl()->getIntegerType();
349 return (Ty->isPromotableIntegerType() ?
350 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
353 ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const {
354 if (RetTy->isVoidType())
355 return ABIArgInfo::getIgnore();
357 if (isAggregateTypeForABI(RetTy))
358 return ABIArgInfo::getIndirect(0);
360 // Treat an enum type as its underlying type.
361 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
362 RetTy = EnumTy->getDecl()->getIntegerType();
364 return (RetTy->isPromotableIntegerType() ?
365 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
368 /// UseX86_MMXType - Return true if this is an MMX type that should use the special
370 bool UseX86_MMXType(llvm::Type *IRType) {
371 // If the type is an MMX type <2 x i32>, <4 x i16>, or <8 x i8>, use the
372 // special x86_mmx type.
373 return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 &&
374 cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() &&
375 IRType->getScalarSizeInBits() != 64;
378 static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
379 StringRef Constraint,
381 if ((Constraint == "y" || Constraint == "&y") && Ty->isVectorTy())
382 return llvm::Type::getX86_MMXTy(CGF.getLLVMContext());
386 //===----------------------------------------------------------------------===//
387 // X86-32 ABI Implementation
388 //===----------------------------------------------------------------------===//
390 /// X86_32ABIInfo - The X86-32 ABI information.
391 class X86_32ABIInfo : public ABIInfo {
392 static const unsigned MinABIStackAlignInBytes = 4;
394 bool IsDarwinVectorABI;
395 bool IsSmallStructInRegABI;
398 static bool isRegisterSize(unsigned Size) {
399 return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
402 static bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context);
404 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
405 /// such that the argument will be passed in memory.
406 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal = true) const;
408 /// \brief Return the alignment to use for the given type on the stack.
409 unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const;
413 ABIArgInfo classifyReturnType(QualType RetTy) const;
414 ABIArgInfo classifyArgumentType(QualType RetTy) const;
416 virtual void computeInfo(CGFunctionInfo &FI) const {
417 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
418 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
420 it->info = classifyArgumentType(it->type);
423 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
424 CodeGenFunction &CGF) const;
426 X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool d, bool p, bool m)
427 : ABIInfo(CGT), IsDarwinVectorABI(d), IsSmallStructInRegABI(p),
431 class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
433 X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool d, bool p, bool m)
434 :TargetCodeGenInfo(new X86_32ABIInfo(CGT, d, p, m)) {}
436 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
437 CodeGen::CodeGenModule &CGM) const;
439 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const {
440 // Darwin uses different dwarf register numbers for EH.
441 if (CGM.isTargetDarwin()) return 5;
446 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
447 llvm::Value *Address) const;
449 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
450 StringRef Constraint,
451 llvm::Type* Ty) const {
452 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
459 /// shouldReturnTypeInRegister - Determine if the given type should be
460 /// passed in a register (for the Darwin ABI).
461 bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
462 ASTContext &Context) {
463 uint64_t Size = Context.getTypeSize(Ty);
465 // Type must be register sized.
466 if (!isRegisterSize(Size))
469 if (Ty->isVectorType()) {
470 // 64- and 128- bit vectors inside structures are not returned in
472 if (Size == 64 || Size == 128)
478 // If this is a builtin, pointer, enum, complex type, member pointer, or
479 // member function pointer it is ok.
480 if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() ||
481 Ty->isAnyComplexType() || Ty->isEnumeralType() ||
482 Ty->isBlockPointerType() || Ty->isMemberPointerType())
485 // Arrays are treated like records.
486 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
487 return shouldReturnTypeInRegister(AT->getElementType(), Context);
489 // Otherwise, it must be a record type.
490 const RecordType *RT = Ty->getAs<RecordType>();
491 if (!RT) return false;
493 // FIXME: Traverse bases here too.
495 // Structure types are passed in register if all fields would be
496 // passed in a register.
497 for (RecordDecl::field_iterator i = RT->getDecl()->field_begin(),
498 e = RT->getDecl()->field_end(); i != e; ++i) {
499 const FieldDecl *FD = *i;
501 // Empty fields are ignored.
502 if (isEmptyField(Context, FD, true))
505 // Check fields recursively.
506 if (!shouldReturnTypeInRegister(FD->getType(), Context))
513 ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy) const {
514 if (RetTy->isVoidType())
515 return ABIArgInfo::getIgnore();
517 if (const VectorType *VT = RetTy->getAs<VectorType>()) {
518 // On Darwin, some vectors are returned in registers.
519 if (IsDarwinVectorABI) {
520 uint64_t Size = getContext().getTypeSize(RetTy);
522 // 128-bit vectors are a special case; they are returned in
523 // registers and we need to make sure to pick a type the LLVM
524 // backend will like.
526 return ABIArgInfo::getDirect(llvm::VectorType::get(
527 llvm::Type::getInt64Ty(getVMContext()), 2));
529 // Always return in register if it fits in a general purpose
530 // register, or if it is 64 bits and has a single element.
531 if ((Size == 8 || Size == 16 || Size == 32) ||
532 (Size == 64 && VT->getNumElements() == 1))
533 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
536 return ABIArgInfo::getIndirect(0);
539 return ABIArgInfo::getDirect();
542 if (isAggregateTypeForABI(RetTy)) {
543 if (const RecordType *RT = RetTy->getAs<RecordType>()) {
544 // Structures with either a non-trivial destructor or a non-trivial
545 // copy constructor are always indirect.
546 if (hasNonTrivialDestructorOrCopyConstructor(RT))
547 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
549 // Structures with flexible arrays are always indirect.
550 if (RT->getDecl()->hasFlexibleArrayMember())
551 return ABIArgInfo::getIndirect(0);
554 // If specified, structs and unions are always indirect.
555 if (!IsSmallStructInRegABI && !RetTy->isAnyComplexType())
556 return ABIArgInfo::getIndirect(0);
558 // Classify "single element" structs as their element type.
559 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext())) {
560 if (const BuiltinType *BT = SeltTy->getAs<BuiltinType>()) {
561 if (BT->isIntegerType()) {
562 // We need to use the size of the structure, padding
563 // bit-fields can adjust that to be larger than the single
565 uint64_t Size = getContext().getTypeSize(RetTy);
566 return ABIArgInfo::getDirect(
567 llvm::IntegerType::get(getVMContext(), (unsigned)Size));
570 if (BT->getKind() == BuiltinType::Float) {
571 assert(getContext().getTypeSize(RetTy) ==
572 getContext().getTypeSize(SeltTy) &&
573 "Unexpect single element structure size!");
574 return ABIArgInfo::getDirect(llvm::Type::getFloatTy(getVMContext()));
577 if (BT->getKind() == BuiltinType::Double) {
578 assert(getContext().getTypeSize(RetTy) ==
579 getContext().getTypeSize(SeltTy) &&
580 "Unexpect single element structure size!");
581 return ABIArgInfo::getDirect(llvm::Type::getDoubleTy(getVMContext()));
583 } else if (SeltTy->isPointerType()) {
584 // FIXME: It would be really nice if this could come out as the proper
586 llvm::Type *PtrTy = llvm::Type::getInt8PtrTy(getVMContext());
587 return ABIArgInfo::getDirect(PtrTy);
588 } else if (SeltTy->isVectorType()) {
589 // 64- and 128-bit vectors are never returned in a
590 // register when inside a structure.
591 uint64_t Size = getContext().getTypeSize(RetTy);
592 if (Size == 64 || Size == 128)
593 return ABIArgInfo::getIndirect(0);
595 return classifyReturnType(QualType(SeltTy, 0));
599 // Small structures which are register sized are generally returned
601 if (X86_32ABIInfo::shouldReturnTypeInRegister(RetTy, getContext())) {
602 uint64_t Size = getContext().getTypeSize(RetTy);
603 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
606 return ABIArgInfo::getIndirect(0);
609 // Treat an enum type as its underlying type.
610 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
611 RetTy = EnumTy->getDecl()->getIntegerType();
613 return (RetTy->isPromotableIntegerType() ?
614 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
617 static bool isRecordWithSSEVectorType(ASTContext &Context, QualType Ty) {
618 const RecordType *RT = Ty->getAs<RecordType>();
621 const RecordDecl *RD = RT->getDecl();
623 // If this is a C++ record, check the bases first.
624 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
625 for (CXXRecordDecl::base_class_const_iterator i = CXXRD->bases_begin(),
626 e = CXXRD->bases_end(); i != e; ++i)
627 if (!isRecordWithSSEVectorType(Context, i->getType()))
630 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
632 QualType FT = i->getType();
634 if (FT->getAs<VectorType>() && Context.getTypeSize(Ty) == 128)
637 if (isRecordWithSSEVectorType(Context, FT))
644 unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
645 unsigned Align) const {
646 // Otherwise, if the alignment is less than or equal to the minimum ABI
647 // alignment, just use the default; the backend will handle this.
648 if (Align <= MinABIStackAlignInBytes)
649 return 0; // Use default alignment.
651 // On non-Darwin, the stack type alignment is always 4.
652 if (!IsDarwinVectorABI) {
653 // Set explicit alignment, since we may need to realign the top.
654 return MinABIStackAlignInBytes;
657 // Otherwise, if the type contains an SSE vector type, the alignment is 16.
658 if (isRecordWithSSEVectorType(getContext(), Ty))
661 return MinABIStackAlignInBytes;
664 ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal) const {
666 return ABIArgInfo::getIndirect(0, false);
668 // Compute the byval alignment.
669 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
670 unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign);
672 return ABIArgInfo::getIndirect(4);
674 // If the stack alignment is less than the type alignment, realign the
676 if (StackAlign < TypeAlign)
677 return ABIArgInfo::getIndirect(StackAlign, /*ByVal=*/true,
680 return ABIArgInfo::getIndirect(StackAlign);
683 ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty) const {
684 // FIXME: Set alignment on indirect arguments.
685 if (isAggregateTypeForABI(Ty)) {
686 // Structures with flexible arrays are always indirect.
687 if (const RecordType *RT = Ty->getAs<RecordType>()) {
688 // Structures with either a non-trivial destructor or a non-trivial
689 // copy constructor are always indirect.
690 if (hasNonTrivialDestructorOrCopyConstructor(RT))
691 return getIndirectResult(Ty, /*ByVal=*/false);
693 if (RT->getDecl()->hasFlexibleArrayMember())
694 return getIndirectResult(Ty);
697 // Ignore empty structs.
698 if (Ty->isStructureType() && getContext().getTypeSize(Ty) == 0)
699 return ABIArgInfo::getIgnore();
701 // Expand small (<= 128-bit) record types when we know that the stack layout
702 // of those arguments will match the struct. This is important because the
703 // LLVM backend isn't smart enough to remove byval, which inhibits many
705 if (getContext().getTypeSize(Ty) <= 4*32 &&
706 canExpandIndirectArgument(Ty, getContext()))
707 return ABIArgInfo::getExpand();
709 return getIndirectResult(Ty);
712 if (const VectorType *VT = Ty->getAs<VectorType>()) {
713 // On Darwin, some vectors are passed in memory, we handle this by passing
714 // it as an i8/i16/i32/i64.
715 if (IsDarwinVectorABI) {
716 uint64_t Size = getContext().getTypeSize(Ty);
717 if ((Size == 8 || Size == 16 || Size == 32) ||
718 (Size == 64 && VT->getNumElements() == 1))
719 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
723 llvm::Type *IRType = CGT.ConvertType(Ty);
724 if (UseX86_MMXType(IRType)) {
726 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
728 ABIArgInfo AAI = ABIArgInfo::getDirect(IRType);
729 AAI.setCoerceToType(llvm::Type::getX86_MMXTy(getVMContext()));
733 return ABIArgInfo::getDirect();
737 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
738 Ty = EnumTy->getDecl()->getIntegerType();
740 return (Ty->isPromotableIntegerType() ?
741 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
744 llvm::Value *X86_32ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
745 CodeGenFunction &CGF) const {
746 llvm::Type *BP = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
747 llvm::Type *BPP = llvm::PointerType::getUnqual(BP);
749 CGBuilderTy &Builder = CGF.Builder;
750 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
752 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
754 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
755 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
758 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 4);
759 llvm::Value *NextAddr =
760 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
762 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
767 void X86_32TargetCodeGenInfo::SetTargetAttributes(const Decl *D,
768 llvm::GlobalValue *GV,
769 CodeGen::CodeGenModule &CGM) const {
770 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
771 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
772 // Get the LLVM function.
773 llvm::Function *Fn = cast<llvm::Function>(GV);
775 // Now add the 'alignstack' attribute with a value of 16.
776 Fn->addFnAttr(llvm::Attribute::constructStackAlignmentFromInt(16));
781 bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
782 CodeGen::CodeGenFunction &CGF,
783 llvm::Value *Address) const {
784 CodeGen::CGBuilderTy &Builder = CGF.Builder;
785 llvm::LLVMContext &Context = CGF.getLLVMContext();
787 llvm::IntegerType *i8 = llvm::Type::getInt8Ty(Context);
788 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
790 // 0-7 are the eight integer registers; the order is different
791 // on Darwin (for EH), but the range is the same.
793 AssignToArrayRange(Builder, Address, Four8, 0, 8);
795 if (CGF.CGM.isTargetDarwin()) {
796 // 12-16 are st(0..4). Not sure why we stop at 4.
797 // These have size 16, which is sizeof(long double) on
798 // platforms with 8-byte alignment for that type.
799 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
800 AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
803 // 9 is %eflags, which doesn't get a size on Darwin for some
805 Builder.CreateStore(Four8, Builder.CreateConstInBoundsGEP1_32(Address, 9));
807 // 11-16 are st(0..5). Not sure why we stop at 5.
808 // These have size 12, which is sizeof(long double) on
809 // platforms with 4-byte alignment for that type.
810 llvm::Value *Twelve8 = llvm::ConstantInt::get(i8, 12);
811 AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
817 //===----------------------------------------------------------------------===//
818 // X86-64 ABI Implementation
819 //===----------------------------------------------------------------------===//
823 /// X86_64ABIInfo - The X86_64 ABI information.
824 class X86_64ABIInfo : public ABIInfo {
836 /// merge - Implement the X86_64 ABI merging algorithm.
838 /// Merge an accumulating classification \arg Accum with a field
839 /// classification \arg Field.
841 /// \param Accum - The accumulating classification. This should
842 /// always be either NoClass or the result of a previous merge
843 /// call. In addition, this should never be Memory (the caller
844 /// should just return Memory for the aggregate).
845 static Class merge(Class Accum, Class Field);
847 /// postMerge - Implement the X86_64 ABI post merging algorithm.
849 /// Post merger cleanup, reduces a malformed Hi and Lo pair to
850 /// final MEMORY or SSE classes when necessary.
852 /// \param AggregateSize - The size of the current aggregate in
853 /// the classification process.
855 /// \param Lo - The classification for the parts of the type
856 /// residing in the low word of the containing object.
858 /// \param Hi - The classification for the parts of the type
859 /// residing in the higher words of the containing object.
861 void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
863 /// classify - Determine the x86_64 register classes in which the
864 /// given type T should be passed.
866 /// \param Lo - The classification for the parts of the type
867 /// residing in the low word of the containing object.
869 /// \param Hi - The classification for the parts of the type
870 /// residing in the high word of the containing object.
872 /// \param OffsetBase - The bit offset of this type in the
873 /// containing object. Some parameters are classified different
874 /// depending on whether they straddle an eightbyte boundary.
876 /// If a word is unused its result will be NoClass; if a type should
877 /// be passed in Memory then at least the classification of \arg Lo
880 /// The \arg Lo class will be NoClass iff the argument is ignored.
882 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
883 /// also be ComplexX87.
884 void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi) const;
886 llvm::Type *GetByteVectorType(QualType Ty) const;
887 llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
888 unsigned IROffset, QualType SourceTy,
889 unsigned SourceOffset) const;
890 llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
891 unsigned IROffset, QualType SourceTy,
892 unsigned SourceOffset) const;
894 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
895 /// such that the argument will be returned in memory.
896 ABIArgInfo getIndirectReturnResult(QualType Ty) const;
898 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
899 /// such that the argument will be passed in memory.
900 ABIArgInfo getIndirectResult(QualType Ty) const;
902 ABIArgInfo classifyReturnType(QualType RetTy) const;
904 ABIArgInfo classifyArgumentType(QualType Ty,
906 unsigned &neededSSE) const;
908 /// The 0.98 ABI revision clarified a lot of ambiguities,
909 /// unfortunately in ways that were not always consistent with
910 /// certain previous compilers. In particular, platforms which
911 /// required strict binary compatibility with older versions of GCC
912 /// may need to exempt themselves.
913 bool honorsRevision0_98() const {
914 return !getContext().getTargetInfo().getTriple().isOSDarwin();
918 X86_64ABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
920 virtual void computeInfo(CGFunctionInfo &FI) const;
922 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
923 CodeGenFunction &CGF) const;
926 /// WinX86_64ABIInfo - The Windows X86_64 ABI information.
927 class WinX86_64ABIInfo : public ABIInfo {
929 ABIArgInfo classify(QualType Ty) const;
932 WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
934 virtual void computeInfo(CGFunctionInfo &FI) const;
936 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
937 CodeGenFunction &CGF) const;
940 class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
942 X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
943 : TargetCodeGenInfo(new X86_64ABIInfo(CGT)) {}
945 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const {
949 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
950 llvm::Value *Address) const {
951 CodeGen::CGBuilderTy &Builder = CGF.Builder;
952 llvm::LLVMContext &Context = CGF.getLLVMContext();
954 llvm::IntegerType *i8 = llvm::Type::getInt8Ty(Context);
955 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
957 // 0-15 are the 16 integer registers.
959 AssignToArrayRange(Builder, Address, Eight8, 0, 16);
964 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
965 StringRef Constraint,
966 llvm::Type* Ty) const {
967 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
970 bool isNoProtoCallVariadic(CallingConv CC) const {
971 // The default CC on x86-64 sets %al to the number of SSA
972 // registers used, and GCC sets this when calling an unprototyped
973 // function, so we override the default behavior.
974 if (CC == CC_Default || CC == CC_C) return true;
976 return TargetCodeGenInfo::isNoProtoCallVariadic(CC);
981 class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
983 WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
984 : TargetCodeGenInfo(new WinX86_64ABIInfo(CGT)) {}
986 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const {
990 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
991 llvm::Value *Address) const {
992 CodeGen::CGBuilderTy &Builder = CGF.Builder;
993 llvm::LLVMContext &Context = CGF.getLLVMContext();
995 llvm::IntegerType *i8 = llvm::Type::getInt8Ty(Context);
996 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
998 // 0-15 are the 16 integer registers.
1000 AssignToArrayRange(Builder, Address, Eight8, 0, 16);
1008 void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
1010 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
1012 // (a) If one of the classes is Memory, the whole argument is passed in
1015 // (b) If X87UP is not preceded by X87, the whole argument is passed in
1018 // (c) If the size of the aggregate exceeds two eightbytes and the first
1019 // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
1020 // argument is passed in memory. NOTE: This is necessary to keep the
1021 // ABI working for processors that don't support the __m256 type.
1023 // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
1025 // Some of these are enforced by the merging logic. Others can arise
1026 // only with unions; for example:
1027 // union { _Complex double; unsigned; }
1029 // Note that clauses (b) and (c) were added in 0.98.
1033 if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
1035 if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
1037 if (Hi == SSEUp && Lo != SSE)
1041 X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
1042 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
1043 // classified recursively so that always two fields are
1044 // considered. The resulting class is calculated according to
1045 // the classes of the fields in the eightbyte:
1047 // (a) If both classes are equal, this is the resulting class.
1049 // (b) If one of the classes is NO_CLASS, the resulting class is
1052 // (c) If one of the classes is MEMORY, the result is the MEMORY
1055 // (d) If one of the classes is INTEGER, the result is the
1058 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
1059 // MEMORY is used as class.
1061 // (f) Otherwise class SSE is used.
1063 // Accum should never be memory (we should have returned) or
1064 // ComplexX87 (because this cannot be passed in a structure).
1065 assert((Accum != Memory && Accum != ComplexX87) &&
1066 "Invalid accumulated classification during merge.");
1067 if (Accum == Field || Field == NoClass)
1069 if (Field == Memory)
1071 if (Accum == NoClass)
1073 if (Accum == Integer || Field == Integer)
1075 if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
1076 Accum == X87 || Accum == X87Up)
1081 void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
1082 Class &Lo, Class &Hi) const {
1083 // FIXME: This code can be simplified by introducing a simple value class for
1084 // Class pairs with appropriate constructor methods for the various
1087 // FIXME: Some of the split computations are wrong; unaligned vectors
1088 // shouldn't be passed in registers for example, so there is no chance they
1089 // can straddle an eightbyte. Verify & simplify.
1093 Class &Current = OffsetBase < 64 ? Lo : Hi;
1096 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
1097 BuiltinType::Kind k = BT->getKind();
1099 if (k == BuiltinType::Void) {
1101 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
1104 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
1106 } else if (k == BuiltinType::Float || k == BuiltinType::Double) {
1108 } else if (k == BuiltinType::LongDouble) {
1112 // FIXME: _Decimal32 and _Decimal64 are SSE.
1113 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
1117 if (const EnumType *ET = Ty->getAs<EnumType>()) {
1118 // Classify the underlying integer type.
1119 classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi);
1123 if (Ty->hasPointerRepresentation()) {
1128 if (Ty->isMemberPointerType()) {
1129 if (Ty->isMemberFunctionPointerType())
1136 if (const VectorType *VT = Ty->getAs<VectorType>()) {
1137 uint64_t Size = getContext().getTypeSize(VT);
1139 // gcc passes all <4 x char>, <2 x short>, <1 x int>, <1 x
1140 // float> as integer.
1143 // If this type crosses an eightbyte boundary, it should be
1145 uint64_t EB_Real = (OffsetBase) / 64;
1146 uint64_t EB_Imag = (OffsetBase + Size - 1) / 64;
1147 if (EB_Real != EB_Imag)
1149 } else if (Size == 64) {
1150 // gcc passes <1 x double> in memory. :(
1151 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double))
1154 // gcc passes <1 x long long> as INTEGER.
1155 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::LongLong) ||
1156 VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULongLong) ||
1157 VT->getElementType()->isSpecificBuiltinType(BuiltinType::Long) ||
1158 VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULong))
1163 // If this type crosses an eightbyte boundary, it should be
1165 if (OffsetBase && OffsetBase != 64)
1167 } else if (Size == 128 || Size == 256) {
1168 // Arguments of 256-bits are split into four eightbyte chunks. The
1169 // least significant one belongs to class SSE and all the others to class
1170 // SSEUP. The original Lo and Hi design considers that types can't be
1171 // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
1172 // This design isn't correct for 256-bits, but since there're no cases
1173 // where the upper parts would need to be inspected, avoid adding
1174 // complexity and just consider Hi to match the 64-256 part.
1181 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
1182 QualType ET = getContext().getCanonicalType(CT->getElementType());
1184 uint64_t Size = getContext().getTypeSize(Ty);
1185 if (ET->isIntegralOrEnumerationType()) {
1188 else if (Size <= 128)
1190 } else if (ET == getContext().FloatTy)
1192 else if (ET == getContext().DoubleTy)
1194 else if (ET == getContext().LongDoubleTy)
1195 Current = ComplexX87;
1197 // If this complex type crosses an eightbyte boundary then it
1199 uint64_t EB_Real = (OffsetBase) / 64;
1200 uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
1201 if (Hi == NoClass && EB_Real != EB_Imag)
1207 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
1208 // Arrays are treated like structures.
1210 uint64_t Size = getContext().getTypeSize(Ty);
1212 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
1213 // than four eightbytes, ..., it has class MEMORY.
1217 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
1218 // fields, it has class MEMORY.
1220 // Only need to check alignment of array base.
1221 if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
1224 // Otherwise implement simplified merge. We could be smarter about
1225 // this, but it isn't worth it and would be harder to verify.
1227 uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
1228 uint64_t ArraySize = AT->getSize().getZExtValue();
1230 // The only case a 256-bit wide vector could be used is when the array
1231 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
1232 // to work for sizes wider than 128, early check and fallback to memory.
1233 if (Size > 128 && EltSize != 256)
1236 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
1237 Class FieldLo, FieldHi;
1238 classify(AT->getElementType(), Offset, FieldLo, FieldHi);
1239 Lo = merge(Lo, FieldLo);
1240 Hi = merge(Hi, FieldHi);
1241 if (Lo == Memory || Hi == Memory)
1245 postMerge(Size, Lo, Hi);
1246 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
1250 if (const RecordType *RT = Ty->getAs<RecordType>()) {
1251 uint64_t Size = getContext().getTypeSize(Ty);
1253 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
1254 // than four eightbytes, ..., it has class MEMORY.
1258 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
1259 // copy constructor or a non-trivial destructor, it is passed by invisible
1261 if (hasNonTrivialDestructorOrCopyConstructor(RT))
1264 const RecordDecl *RD = RT->getDecl();
1266 // Assume variable sized types are passed in memory.
1267 if (RD->hasFlexibleArrayMember())
1270 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
1272 // Reset Lo class, this will be recomputed.
1275 // If this is a C++ record, classify the bases first.
1276 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
1277 for (CXXRecordDecl::base_class_const_iterator i = CXXRD->bases_begin(),
1278 e = CXXRD->bases_end(); i != e; ++i) {
1279 assert(!i->isVirtual() && !i->getType()->isDependentType() &&
1280 "Unexpected base class!");
1281 const CXXRecordDecl *Base =
1282 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
1284 // Classify this field.
1286 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
1287 // single eightbyte, each is classified separately. Each eightbyte gets
1288 // initialized to class NO_CLASS.
1289 Class FieldLo, FieldHi;
1290 uint64_t Offset = OffsetBase + Layout.getBaseClassOffsetInBits(Base);
1291 classify(i->getType(), Offset, FieldLo, FieldHi);
1292 Lo = merge(Lo, FieldLo);
1293 Hi = merge(Hi, FieldHi);
1294 if (Lo == Memory || Hi == Memory)
1299 // Classify the fields one at a time, merging the results.
1301 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
1302 i != e; ++i, ++idx) {
1303 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
1304 bool BitField = i->isBitField();
1306 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
1307 // four eightbytes, or it contains unaligned fields, it has class MEMORY.
1309 // The only case a 256-bit wide vector could be used is when the struct
1310 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
1311 // to work for sizes wider than 128, early check and fallback to memory.
1313 if (Size > 128 && getContext().getTypeSize(i->getType()) != 256) {
1317 // Note, skip this test for bit-fields, see below.
1318 if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
1323 // Classify this field.
1325 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
1326 // exceeds a single eightbyte, each is classified
1327 // separately. Each eightbyte gets initialized to class
1329 Class FieldLo, FieldHi;
1331 // Bit-fields require special handling, they do not force the
1332 // structure to be passed in memory even if unaligned, and
1333 // therefore they can straddle an eightbyte.
1335 // Ignore padding bit-fields.
1336 if (i->isUnnamedBitfield())
1339 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
1340 uint64_t Size = i->getBitWidthValue(getContext());
1342 uint64_t EB_Lo = Offset / 64;
1343 uint64_t EB_Hi = (Offset + Size - 1) / 64;
1344 FieldLo = FieldHi = NoClass;
1346 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
1351 FieldHi = EB_Hi ? Integer : NoClass;
1354 classify(i->getType(), Offset, FieldLo, FieldHi);
1355 Lo = merge(Lo, FieldLo);
1356 Hi = merge(Hi, FieldHi);
1357 if (Lo == Memory || Hi == Memory)
1361 postMerge(Size, Lo, Hi);
1365 ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
1366 // If this is a scalar LLVM value then assume LLVM will pass it in the right
1368 if (!isAggregateTypeForABI(Ty)) {
1369 // Treat an enum type as its underlying type.
1370 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1371 Ty = EnumTy->getDecl()->getIntegerType();
1373 return (Ty->isPromotableIntegerType() ?
1374 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
1377 return ABIArgInfo::getIndirect(0);
1380 ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty) const {
1381 // If this is a scalar LLVM value then assume LLVM will pass it in the right
1383 if (!isAggregateTypeForABI(Ty)) {
1384 // Treat an enum type as its underlying type.
1385 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1386 Ty = EnumTy->getDecl()->getIntegerType();
1388 return (Ty->isPromotableIntegerType() ?
1389 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
1392 if (isRecordWithNonTrivialDestructorOrCopyConstructor(Ty))
1393 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
1395 // Compute the byval alignment. We specify the alignment of the byval in all
1396 // cases so that the mid-level optimizer knows the alignment of the byval.
1397 unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
1398 return ABIArgInfo::getIndirect(Align);
1401 /// GetByteVectorType - The ABI specifies that a value should be passed in an
1402 /// full vector XMM/YMM register. Pick an LLVM IR type that will be passed as a
1403 /// vector register.
1404 llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
1405 llvm::Type *IRType = CGT.ConvertType(Ty);
1407 // Wrapper structs that just contain vectors are passed just like vectors,
1408 // strip them off if present.
1409 llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType);
1410 while (STy && STy->getNumElements() == 1) {
1411 IRType = STy->getElementType(0);
1412 STy = dyn_cast<llvm::StructType>(IRType);
1415 // If the preferred type is a 16-byte vector, prefer to pass it.
1416 if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(IRType)){
1417 llvm::Type *EltTy = VT->getElementType();
1418 unsigned BitWidth = VT->getBitWidth();
1419 if ((BitWidth == 128 || BitWidth == 256) &&
1420 (EltTy->isFloatTy() || EltTy->isDoubleTy() ||
1421 EltTy->isIntegerTy(8) || EltTy->isIntegerTy(16) ||
1422 EltTy->isIntegerTy(32) || EltTy->isIntegerTy(64) ||
1423 EltTy->isIntegerTy(128)))
1427 return llvm::VectorType::get(llvm::Type::getDoubleTy(getVMContext()), 2);
1430 /// BitsContainNoUserData - Return true if the specified [start,end) bit range
1431 /// is known to either be off the end of the specified type or being in
1432 /// alignment padding. The user type specified is known to be at most 128 bits
1433 /// in size, and have passed through X86_64ABIInfo::classify with a successful
1434 /// classification that put one of the two halves in the INTEGER class.
1436 /// It is conservatively correct to return false.
1437 static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
1438 unsigned EndBit, ASTContext &Context) {
1439 // If the bytes being queried are off the end of the type, there is no user
1440 // data hiding here. This handles analysis of builtins, vectors and other
1441 // types that don't contain interesting padding.
1442 unsigned TySize = (unsigned)Context.getTypeSize(Ty);
1443 if (TySize <= StartBit)
1446 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
1447 unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
1448 unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
1450 // Check each element to see if the element overlaps with the queried range.
1451 for (unsigned i = 0; i != NumElts; ++i) {
1452 // If the element is after the span we care about, then we're done..
1453 unsigned EltOffset = i*EltSize;
1454 if (EltOffset >= EndBit) break;
1456 unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
1457 if (!BitsContainNoUserData(AT->getElementType(), EltStart,
1458 EndBit-EltOffset, Context))
1461 // If it overlaps no elements, then it is safe to process as padding.
1465 if (const RecordType *RT = Ty->getAs<RecordType>()) {
1466 const RecordDecl *RD = RT->getDecl();
1467 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1469 // If this is a C++ record, check the bases first.
1470 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
1471 for (CXXRecordDecl::base_class_const_iterator i = CXXRD->bases_begin(),
1472 e = CXXRD->bases_end(); i != e; ++i) {
1473 assert(!i->isVirtual() && !i->getType()->isDependentType() &&
1474 "Unexpected base class!");
1475 const CXXRecordDecl *Base =
1476 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
1478 // If the base is after the span we care about, ignore it.
1479 unsigned BaseOffset = (unsigned)Layout.getBaseClassOffsetInBits(Base);
1480 if (BaseOffset >= EndBit) continue;
1482 unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
1483 if (!BitsContainNoUserData(i->getType(), BaseStart,
1484 EndBit-BaseOffset, Context))
1489 // Verify that no field has data that overlaps the region of interest. Yes
1490 // this could be sped up a lot by being smarter about queried fields,
1491 // however we're only looking at structs up to 16 bytes, so we don't care
1494 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
1495 i != e; ++i, ++idx) {
1496 unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
1498 // If we found a field after the region we care about, then we're done.
1499 if (FieldOffset >= EndBit) break;
1501 unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
1502 if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
1507 // If nothing in this record overlapped the area of interest, then we're
1515 /// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a
1516 /// float member at the specified offset. For example, {int,{float}} has a
1517 /// float at offset 4. It is conservatively correct for this routine to return
1519 static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset,
1520 const llvm::TargetData &TD) {
1521 // Base case if we find a float.
1522 if (IROffset == 0 && IRType->isFloatTy())
1525 // If this is a struct, recurse into the field at the specified offset.
1526 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
1527 const llvm::StructLayout *SL = TD.getStructLayout(STy);
1528 unsigned Elt = SL->getElementContainingOffset(IROffset);
1529 IROffset -= SL->getElementOffset(Elt);
1530 return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD);
1533 // If this is an array, recurse into the field at the specified offset.
1534 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
1535 llvm::Type *EltTy = ATy->getElementType();
1536 unsigned EltSize = TD.getTypeAllocSize(EltTy);
1537 IROffset -= IROffset/EltSize*EltSize;
1538 return ContainsFloatAtOffset(EltTy, IROffset, TD);
1545 /// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
1546 /// low 8 bytes of an XMM register, corresponding to the SSE class.
1547 llvm::Type *X86_64ABIInfo::
1548 GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
1549 QualType SourceTy, unsigned SourceOffset) const {
1550 // The only three choices we have are either double, <2 x float>, or float. We
1551 // pass as float if the last 4 bytes is just padding. This happens for
1552 // structs that contain 3 floats.
1553 if (BitsContainNoUserData(SourceTy, SourceOffset*8+32,
1554 SourceOffset*8+64, getContext()))
1555 return llvm::Type::getFloatTy(getVMContext());
1557 // We want to pass as <2 x float> if the LLVM IR type contains a float at
1558 // offset+0 and offset+4. Walk the LLVM IR type to find out if this is the
1560 if (ContainsFloatAtOffset(IRType, IROffset, getTargetData()) &&
1561 ContainsFloatAtOffset(IRType, IROffset+4, getTargetData()))
1562 return llvm::VectorType::get(llvm::Type::getFloatTy(getVMContext()), 2);
1564 return llvm::Type::getDoubleTy(getVMContext());
1568 /// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
1569 /// an 8-byte GPR. This means that we either have a scalar or we are talking
1570 /// about the high or low part of an up-to-16-byte struct. This routine picks
1571 /// the best LLVM IR type to represent this, which may be i64 or may be anything
1572 /// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
1575 /// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
1576 /// the source type. IROffset is an offset in bytes into the LLVM IR type that
1577 /// the 8-byte value references. PrefType may be null.
1579 /// SourceTy is the source level type for the entire argument. SourceOffset is
1580 /// an offset into this that we're processing (which is always either 0 or 8).
1582 llvm::Type *X86_64ABIInfo::
1583 GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
1584 QualType SourceTy, unsigned SourceOffset) const {
1585 // If we're dealing with an un-offset LLVM IR type, then it means that we're
1586 // returning an 8-byte unit starting with it. See if we can safely use it.
1587 if (IROffset == 0) {
1588 // Pointers and int64's always fill the 8-byte unit.
1589 if (isa<llvm::PointerType>(IRType) || IRType->isIntegerTy(64))
1592 // If we have a 1/2/4-byte integer, we can use it only if the rest of the
1593 // goodness in the source type is just tail padding. This is allowed to
1594 // kick in for struct {double,int} on the int, but not on
1595 // struct{double,int,int} because we wouldn't return the second int. We
1596 // have to do this analysis on the source type because we can't depend on
1597 // unions being lowered a specific way etc.
1598 if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
1599 IRType->isIntegerTy(32)) {
1600 unsigned BitWidth = cast<llvm::IntegerType>(IRType)->getBitWidth();
1602 if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
1603 SourceOffset*8+64, getContext()))
1608 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
1609 // If this is a struct, recurse into the field at the specified offset.
1610 const llvm::StructLayout *SL = getTargetData().getStructLayout(STy);
1611 if (IROffset < SL->getSizeInBytes()) {
1612 unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
1613 IROffset -= SL->getElementOffset(FieldIdx);
1615 return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
1616 SourceTy, SourceOffset);
1620 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
1621 llvm::Type *EltTy = ATy->getElementType();
1622 unsigned EltSize = getTargetData().getTypeAllocSize(EltTy);
1623 unsigned EltOffset = IROffset/EltSize*EltSize;
1624 return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
1628 // Okay, we don't have any better idea of what to pass, so we pass this in an
1629 // integer register that isn't too big to fit the rest of the struct.
1630 unsigned TySizeInBytes =
1631 (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
1633 assert(TySizeInBytes != SourceOffset && "Empty field?");
1635 // It is always safe to classify this as an integer type up to i64 that
1636 // isn't larger than the structure.
1637 return llvm::IntegerType::get(getVMContext(),
1638 std::min(TySizeInBytes-SourceOffset, 8U)*8);
1642 /// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
1643 /// be used as elements of a two register pair to pass or return, return a
1644 /// first class aggregate to represent them. For example, if the low part of
1645 /// a by-value argument should be passed as i32* and the high part as float,
1646 /// return {i32*, float}.
1648 GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
1649 const llvm::TargetData &TD) {
1650 // In order to correctly satisfy the ABI, we need to the high part to start
1651 // at offset 8. If the high and low parts we inferred are both 4-byte types
1652 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
1653 // the second element at offset 8. Check for this:
1654 unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
1655 unsigned HiAlign = TD.getABITypeAlignment(Hi);
1656 unsigned HiStart = llvm::TargetData::RoundUpAlignment(LoSize, HiAlign);
1657 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
1659 // To handle this, we have to increase the size of the low part so that the
1660 // second element will start at an 8 byte offset. We can't increase the size
1661 // of the second element because it might make us access off the end of the
1664 // There are only two sorts of types the ABI generation code can produce for
1665 // the low part of a pair that aren't 8 bytes in size: float or i8/i16/i32.
1666 // Promote these to a larger type.
1667 if (Lo->isFloatTy())
1668 Lo = llvm::Type::getDoubleTy(Lo->getContext());
1670 assert(Lo->isIntegerTy() && "Invalid/unknown lo type");
1671 Lo = llvm::Type::getInt64Ty(Lo->getContext());
1675 llvm::StructType *Result = llvm::StructType::get(Lo, Hi, NULL);
1678 // Verify that the second element is at an 8-byte offset.
1679 assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
1680 "Invalid x86-64 argument pair!");
1684 ABIArgInfo X86_64ABIInfo::
1685 classifyReturnType(QualType RetTy) const {
1686 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
1687 // classification algorithm.
1688 X86_64ABIInfo::Class Lo, Hi;
1689 classify(RetTy, 0, Lo, Hi);
1691 // Check some invariants.
1692 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
1693 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
1695 llvm::Type *ResType = 0;
1699 return ABIArgInfo::getIgnore();
1700 // If the low part is just padding, it takes no register, leave ResType
1702 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
1703 "Unknown missing lo part");
1708 llvm_unreachable("Invalid classification for lo word.");
1710 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
1713 return getIndirectReturnResult(RetTy);
1715 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
1716 // available register of the sequence %rax, %rdx is used.
1718 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
1720 // If we have a sign or zero extended integer, make sure to return Extend
1721 // so that the parameter gets the right LLVM IR attributes.
1722 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
1723 // Treat an enum type as its underlying type.
1724 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
1725 RetTy = EnumTy->getDecl()->getIntegerType();
1727 if (RetTy->isIntegralOrEnumerationType() &&
1728 RetTy->isPromotableIntegerType())
1729 return ABIArgInfo::getExtend();
1733 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
1734 // available SSE register of the sequence %xmm0, %xmm1 is used.
1736 ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
1739 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
1740 // returned on the X87 stack in %st0 as 80-bit x87 number.
1742 ResType = llvm::Type::getX86_FP80Ty(getVMContext());
1745 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
1746 // part of the value is returned in %st0 and the imaginary part in
1749 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
1750 ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
1751 llvm::Type::getX86_FP80Ty(getVMContext()),
1756 llvm::Type *HighPart = 0;
1758 // Memory was handled previously and X87 should
1759 // never occur as a hi class.
1762 llvm_unreachable("Invalid classification for hi word.");
1764 case ComplexX87: // Previously handled.
1769 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
1770 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
1771 return ABIArgInfo::getDirect(HighPart, 8);
1774 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
1775 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
1776 return ABIArgInfo::getDirect(HighPart, 8);
1779 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
1780 // is passed in the next available eightbyte chunk if the last used
1783 // SSEUP should always be preceded by SSE, just widen.
1785 assert(Lo == SSE && "Unexpected SSEUp classification.");
1786 ResType = GetByteVectorType(RetTy);
1789 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
1790 // returned together with the previous X87 value in %st0.
1792 // If X87Up is preceded by X87, we don't need to do
1793 // anything. However, in some cases with unions it may not be
1794 // preceded by X87. In such situations we follow gcc and pass the
1795 // extra bits in an SSE reg.
1797 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
1798 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
1799 return ABIArgInfo::getDirect(HighPart, 8);
1804 // If a high part was specified, merge it together with the low part. It is
1805 // known to pass in the high eightbyte of the result. We do this by forming a
1806 // first class struct aggregate with the high and low part: {low, high}
1808 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getTargetData());
1810 return ABIArgInfo::getDirect(ResType);
1813 ABIArgInfo X86_64ABIInfo::classifyArgumentType(QualType Ty, unsigned &neededInt,
1814 unsigned &neededSSE) const {
1815 X86_64ABIInfo::Class Lo, Hi;
1816 classify(Ty, 0, Lo, Hi);
1818 // Check some invariants.
1819 // FIXME: Enforce these by construction.
1820 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
1821 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
1825 llvm::Type *ResType = 0;
1829 return ABIArgInfo::getIgnore();
1830 // If the low part is just padding, it takes no register, leave ResType
1832 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
1833 "Unknown missing lo part");
1836 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
1840 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
1841 // COMPLEX_X87, it is passed in memory.
1844 if (isRecordWithNonTrivialDestructorOrCopyConstructor(Ty))
1846 return getIndirectResult(Ty);
1850 llvm_unreachable("Invalid classification for lo word.");
1852 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
1853 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
1858 // Pick an 8-byte type based on the preferred type.
1859 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
1861 // If we have a sign or zero extended integer, make sure to return Extend
1862 // so that the parameter gets the right LLVM IR attributes.
1863 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
1864 // Treat an enum type as its underlying type.
1865 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1866 Ty = EnumTy->getDecl()->getIntegerType();
1868 if (Ty->isIntegralOrEnumerationType() &&
1869 Ty->isPromotableIntegerType())
1870 return ABIArgInfo::getExtend();
1875 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
1876 // available SSE register is used, the registers are taken in the
1877 // order from %xmm0 to %xmm7.
1879 llvm::Type *IRType = CGT.ConvertType(Ty);
1880 ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
1886 llvm::Type *HighPart = 0;
1888 // Memory was handled previously, ComplexX87 and X87 should
1889 // never occur as hi classes, and X87Up must be preceded by X87,
1890 // which is passed in memory.
1894 llvm_unreachable("Invalid classification for hi word.");
1896 case NoClass: break;
1900 // Pick an 8-byte type based on the preferred type.
1901 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
1903 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
1904 return ABIArgInfo::getDirect(HighPart, 8);
1907 // X87Up generally doesn't occur here (long double is passed in
1908 // memory), except in situations involving unions.
1911 HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
1913 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
1914 return ABIArgInfo::getDirect(HighPart, 8);
1919 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
1920 // eightbyte is passed in the upper half of the last used SSE
1921 // register. This only happens when 128-bit vectors are passed.
1923 assert(Lo == SSE && "Unexpected SSEUp classification");
1924 ResType = GetByteVectorType(Ty);
1928 // If a high part was specified, merge it together with the low part. It is
1929 // known to pass in the high eightbyte of the result. We do this by forming a
1930 // first class struct aggregate with the high and low part: {low, high}
1932 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getTargetData());
1934 return ABIArgInfo::getDirect(ResType);
1937 void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
1939 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
1941 // Keep track of the number of assigned registers.
1942 unsigned freeIntRegs = 6, freeSSERegs = 8;
1944 // If the return value is indirect, then the hidden argument is consuming one
1945 // integer register.
1946 if (FI.getReturnInfo().isIndirect())
1949 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
1950 // get assigned (in left-to-right order) for passing as follows...
1951 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
1953 unsigned neededInt, neededSSE;
1954 it->info = classifyArgumentType(it->type, neededInt, neededSSE);
1956 // AMD64-ABI 3.2.3p3: If there are no registers available for any
1957 // eightbyte of an argument, the whole argument is passed on the
1958 // stack. If registers have already been assigned for some
1959 // eightbytes of such an argument, the assignments get reverted.
1960 if (freeIntRegs >= neededInt && freeSSERegs >= neededSSE) {
1961 freeIntRegs -= neededInt;
1962 freeSSERegs -= neededSSE;
1964 it->info = getIndirectResult(it->type);
1969 static llvm::Value *EmitVAArgFromMemory(llvm::Value *VAListAddr,
1971 CodeGenFunction &CGF) {
1972 llvm::Value *overflow_arg_area_p =
1973 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_p");
1974 llvm::Value *overflow_arg_area =
1975 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
1977 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
1978 // byte boundary if alignment needed by type exceeds 8 byte boundary.
1979 uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8;
1981 // Note that we follow the ABI & gcc here, even though the type
1982 // could in theory have an alignment greater than 16. This case
1983 // shouldn't ever matter in practice.
1985 // overflow_arg_area = (overflow_arg_area + 15) & ~15;
1986 llvm::Value *Offset =
1987 llvm::ConstantInt::get(CGF.Int32Ty, 15);
1988 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset);
1989 llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(overflow_arg_area,
1991 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int64Ty, ~15LL);
1993 CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask),
1994 overflow_arg_area->getType(),
1995 "overflow_arg_area.align");
1998 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
1999 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
2001 CGF.Builder.CreateBitCast(overflow_arg_area,
2002 llvm::PointerType::getUnqual(LTy));
2004 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
2005 // l->overflow_arg_area + sizeof(type).
2006 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
2007 // an 8 byte boundary.
2009 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
2010 llvm::Value *Offset =
2011 llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7);
2012 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
2013 "overflow_arg_area.next");
2014 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
2016 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
2020 llvm::Value *X86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2021 CodeGenFunction &CGF) const {
2022 llvm::LLVMContext &VMContext = CGF.getLLVMContext();
2024 // Assume that va_list type is correct; should be pointer to LLVM type:
2028 // i8* overflow_arg_area;
2029 // i8* reg_save_area;
2031 unsigned neededInt, neededSSE;
2033 Ty = CGF.getContext().getCanonicalType(Ty);
2034 ABIArgInfo AI = classifyArgumentType(Ty, neededInt, neededSSE);
2036 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
2037 // in the registers. If not go to step 7.
2038 if (!neededInt && !neededSSE)
2039 return EmitVAArgFromMemory(VAListAddr, Ty, CGF);
2041 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
2042 // general purpose registers needed to pass type and num_fp to hold
2043 // the number of floating point registers needed.
2045 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
2046 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
2047 // l->fp_offset > 304 - num_fp * 16 go to step 7.
2049 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
2050 // register save space).
2052 llvm::Value *InRegs = 0;
2053 llvm::Value *gp_offset_p = 0, *gp_offset = 0;
2054 llvm::Value *fp_offset_p = 0, *fp_offset = 0;
2056 gp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "gp_offset_p");
2057 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
2058 InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
2059 InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
2063 fp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 1, "fp_offset_p");
2064 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
2065 llvm::Value *FitsInFP =
2066 llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
2067 FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
2068 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
2071 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
2072 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
2073 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
2074 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
2076 // Emit code to load the value if it was passed in registers.
2078 CGF.EmitBlock(InRegBlock);
2080 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
2081 // an offset of l->gp_offset and/or l->fp_offset. This may require
2082 // copying to a temporary location in case the parameter is passed
2083 // in different register classes or requires an alignment greater
2084 // than 8 for general purpose registers and 16 for XMM registers.
2086 // FIXME: This really results in shameful code when we end up needing to
2087 // collect arguments from different places; often what should result in a
2088 // simple assembling of a structure from scattered addresses has many more
2089 // loads than necessary. Can we clean this up?
2090 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
2091 llvm::Value *RegAddr =
2092 CGF.Builder.CreateLoad(CGF.Builder.CreateStructGEP(VAListAddr, 3),
2094 if (neededInt && neededSSE) {
2096 assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
2097 llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
2098 llvm::Value *Tmp = CGF.CreateTempAlloca(ST);
2099 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
2100 llvm::Type *TyLo = ST->getElementType(0);
2101 llvm::Type *TyHi = ST->getElementType(1);
2102 assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
2103 "Unexpected ABI info for mixed regs");
2104 llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
2105 llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
2106 llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
2107 llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
2108 llvm::Value *RegLoAddr = TyLo->isFloatingPointTy() ? FPAddr : GPAddr;
2109 llvm::Value *RegHiAddr = TyLo->isFloatingPointTy() ? GPAddr : FPAddr;
2111 CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegLoAddr, PTyLo));
2112 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
2113 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegHiAddr, PTyHi));
2114 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
2116 RegAddr = CGF.Builder.CreateBitCast(Tmp,
2117 llvm::PointerType::getUnqual(LTy));
2118 } else if (neededInt) {
2119 RegAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
2120 RegAddr = CGF.Builder.CreateBitCast(RegAddr,
2121 llvm::PointerType::getUnqual(LTy));
2122 } else if (neededSSE == 1) {
2123 RegAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
2124 RegAddr = CGF.Builder.CreateBitCast(RegAddr,
2125 llvm::PointerType::getUnqual(LTy));
2127 assert(neededSSE == 2 && "Invalid number of needed registers!");
2128 // SSE registers are spaced 16 bytes apart in the register save
2129 // area, we need to collect the two eightbytes together.
2130 llvm::Value *RegAddrLo = CGF.Builder.CreateGEP(RegAddr, fp_offset);
2131 llvm::Value *RegAddrHi = CGF.Builder.CreateConstGEP1_32(RegAddrLo, 16);
2132 llvm::Type *DoubleTy = llvm::Type::getDoubleTy(VMContext);
2133 llvm::Type *DblPtrTy =
2134 llvm::PointerType::getUnqual(DoubleTy);
2135 llvm::StructType *ST = llvm::StructType::get(DoubleTy,
2137 llvm::Value *V, *Tmp = CGF.CreateTempAlloca(ST);
2138 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrLo,
2140 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
2141 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrHi,
2143 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
2144 RegAddr = CGF.Builder.CreateBitCast(Tmp,
2145 llvm::PointerType::getUnqual(LTy));
2148 // AMD64-ABI 3.5.7p5: Step 5. Set:
2149 // l->gp_offset = l->gp_offset + num_gp * 8
2150 // l->fp_offset = l->fp_offset + num_fp * 16.
2152 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
2153 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
2157 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
2158 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
2161 CGF.EmitBranch(ContBlock);
2163 // Emit code to load the value if it was passed in memory.
2165 CGF.EmitBlock(InMemBlock);
2166 llvm::Value *MemAddr = EmitVAArgFromMemory(VAListAddr, Ty, CGF);
2168 // Return the appropriate result.
2170 CGF.EmitBlock(ContBlock);
2171 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(RegAddr->getType(), 2,
2173 ResAddr->addIncoming(RegAddr, InRegBlock);
2174 ResAddr->addIncoming(MemAddr, InMemBlock);
2178 ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty) const {
2180 if (Ty->isVoidType())
2181 return ABIArgInfo::getIgnore();
2183 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2184 Ty = EnumTy->getDecl()->getIntegerType();
2186 uint64_t Size = getContext().getTypeSize(Ty);
2188 if (const RecordType *RT = Ty->getAs<RecordType>()) {
2189 if (hasNonTrivialDestructorOrCopyConstructor(RT) ||
2190 RT->getDecl()->hasFlexibleArrayMember())
2191 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
2193 // FIXME: mingw-w64-gcc emits 128-bit struct as i128
2195 getContext().getTargetInfo().getTriple().getOS() == llvm::Triple::MinGW32)
2196 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2199 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
2200 // not 1, 2, 4, or 8 bytes, must be passed by reference."
2202 (Size & (Size - 1)) == 0)
2203 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2206 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
2209 if (Ty->isPromotableIntegerType())
2210 return ABIArgInfo::getExtend();
2212 return ABIArgInfo::getDirect();
2215 void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
2217 QualType RetTy = FI.getReturnType();
2218 FI.getReturnInfo() = classify(RetTy);
2220 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
2222 it->info = classify(it->type);
2225 llvm::Value *WinX86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2226 CodeGenFunction &CGF) const {
2227 llvm::Type *BP = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
2228 llvm::Type *BPP = llvm::PointerType::getUnqual(BP);
2230 CGBuilderTy &Builder = CGF.Builder;
2231 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
2233 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
2235 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
2236 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
2239 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 8);
2240 llvm::Value *NextAddr =
2241 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
2243 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
2251 class PPC32TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
2253 PPC32TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
2255 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const {
2256 // This is recovered from gcc output.
2257 return 1; // r1 is the dedicated stack pointer
2260 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2261 llvm::Value *Address) const;
2267 PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2268 llvm::Value *Address) const {
2269 // This is calculated from the LLVM and GCC tables and verified
2270 // against gcc output. AFAIK all ABIs use the same encoding.
2272 CodeGen::CGBuilderTy &Builder = CGF.Builder;
2273 llvm::LLVMContext &Context = CGF.getLLVMContext();
2275 llvm::IntegerType *i8 = llvm::Type::getInt8Ty(Context);
2276 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
2277 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
2278 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
2280 // 0-31: r0-31, the 4-byte general-purpose registers
2281 AssignToArrayRange(Builder, Address, Four8, 0, 31);
2283 // 32-63: fp0-31, the 8-byte floating-point registers
2284 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
2286 // 64-76 are various 4-byte special-purpose registers:
2293 AssignToArrayRange(Builder, Address, Four8, 64, 76);
2295 // 77-108: v0-31, the 16-byte vector registers
2296 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
2303 AssignToArrayRange(Builder, Address, Four8, 109, 113);
2309 //===----------------------------------------------------------------------===//
2310 // ARM ABI Implementation
2311 //===----------------------------------------------------------------------===//
2315 class ARMABIInfo : public ABIInfo {
2327 ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind) : ABIInfo(CGT), Kind(_Kind) {}
2329 bool isEABI() const {
2330 StringRef Env = getContext().getTargetInfo().getTriple().getEnvironmentName();
2331 return (Env == "gnueabi" || Env == "eabi");
2335 ABIKind getABIKind() const { return Kind; }
2337 ABIArgInfo classifyReturnType(QualType RetTy) const;
2338 ABIArgInfo classifyArgumentType(QualType RetTy) const;
2340 virtual void computeInfo(CGFunctionInfo &FI) const;
2342 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2343 CodeGenFunction &CGF) const;
2346 class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
2348 ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
2349 :TargetCodeGenInfo(new ARMABIInfo(CGT, K)) {}
2351 const ARMABIInfo &getABIInfo() const {
2352 return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
2355 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const {
2359 StringRef getARCRetainAutoreleasedReturnValueMarker() const {
2360 return "mov\tr7, r7\t\t@ marker for objc_retainAutoreleaseReturnValue";
2363 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2364 llvm::Value *Address) const {
2365 CodeGen::CGBuilderTy &Builder = CGF.Builder;
2366 llvm::LLVMContext &Context = CGF.getLLVMContext();
2368 llvm::IntegerType *i8 = llvm::Type::getInt8Ty(Context);
2369 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
2371 // 0-15 are the 16 integer registers.
2372 AssignToArrayRange(Builder, Address, Four8, 0, 15);
2377 unsigned getSizeOfUnwindException() const {
2378 if (getABIInfo().isEABI()) return 88;
2379 return TargetCodeGenInfo::getSizeOfUnwindException();
2385 void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
2386 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
2387 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
2389 it->info = classifyArgumentType(it->type);
2391 // Always honor user-specified calling convention.
2392 if (FI.getCallingConvention() != llvm::CallingConv::C)
2395 // Calling convention as default by an ABI.
2396 llvm::CallingConv::ID DefaultCC;
2398 DefaultCC = llvm::CallingConv::ARM_AAPCS;
2400 DefaultCC = llvm::CallingConv::ARM_APCS;
2402 // If user did not ask for specific calling convention explicitly (e.g. via
2403 // pcs attribute), set effective calling convention if it's different than ABI
2405 switch (getABIKind()) {
2407 if (DefaultCC != llvm::CallingConv::ARM_APCS)
2408 FI.setEffectiveCallingConvention(llvm::CallingConv::ARM_APCS);
2411 if (DefaultCC != llvm::CallingConv::ARM_AAPCS)
2412 FI.setEffectiveCallingConvention(llvm::CallingConv::ARM_AAPCS);
2415 if (DefaultCC != llvm::CallingConv::ARM_AAPCS_VFP)
2416 FI.setEffectiveCallingConvention(llvm::CallingConv::ARM_AAPCS_VFP);
2421 /// isHomogeneousAggregate - Return true if a type is an AAPCS-VFP homogeneous
2422 /// aggregate. If HAMembers is non-null, the number of base elements
2423 /// contained in the type is returned through it; this is used for the
2424 /// recursive calls that check aggregate component types.
2425 static bool isHomogeneousAggregate(QualType Ty, const Type *&Base,
2426 ASTContext &Context,
2427 uint64_t *HAMembers = 0) {
2429 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
2430 if (!isHomogeneousAggregate(AT->getElementType(), Base, Context, &Members))
2432 Members *= AT->getSize().getZExtValue();
2433 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
2434 const RecordDecl *RD = RT->getDecl();
2435 if (RD->isUnion() || RD->hasFlexibleArrayMember())
2437 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
2438 if (!CXXRD->isAggregate())
2442 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
2444 const FieldDecl *FD = *i;
2445 uint64_t FldMembers;
2446 if (!isHomogeneousAggregate(FD->getType(), Base, Context, &FldMembers))
2448 Members += FldMembers;
2452 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
2454 Ty = CT->getElementType();
2457 // Homogeneous aggregates for AAPCS-VFP must have base types of float,
2458 // double, or 64-bit or 128-bit vectors.
2459 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
2460 if (BT->getKind() != BuiltinType::Float &&
2461 BT->getKind() != BuiltinType::Double)
2463 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
2464 unsigned VecSize = Context.getTypeSize(VT);
2465 if (VecSize != 64 && VecSize != 128)
2471 // The base type must be the same for all members. Vector types of the
2472 // same total size are treated as being equivalent here.
2473 const Type *TyPtr = Ty.getTypePtr();
2476 if (Base != TyPtr &&
2477 (!Base->isVectorType() || !TyPtr->isVectorType() ||
2478 Context.getTypeSize(Base) != Context.getTypeSize(TyPtr)))
2482 // Homogeneous Aggregates can have at most 4 members of the base type.
2484 *HAMembers = Members;
2485 return (Members <= 4);
2488 ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty) const {
2489 if (!isAggregateTypeForABI(Ty)) {
2490 // Treat an enum type as its underlying type.
2491 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2492 Ty = EnumTy->getDecl()->getIntegerType();
2494 return (Ty->isPromotableIntegerType() ?
2495 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
2498 // Ignore empty records.
2499 if (isEmptyRecord(getContext(), Ty, true))
2500 return ABIArgInfo::getIgnore();
2502 // Structures with either a non-trivial destructor or a non-trivial
2503 // copy constructor are always indirect.
2504 if (isRecordWithNonTrivialDestructorOrCopyConstructor(Ty))
2505 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
2507 if (getABIKind() == ARMABIInfo::AAPCS_VFP) {
2508 // Homogeneous Aggregates need to be expanded.
2509 const Type *Base = 0;
2510 if (isHomogeneousAggregate(Ty, Base, getContext()))
2511 return ABIArgInfo::getExpand();
2514 // Otherwise, pass by coercing to a structure of the appropriate size.
2516 // FIXME: This is kind of nasty... but there isn't much choice because the ARM
2517 // backend doesn't support byval.
2518 // FIXME: This doesn't handle alignment > 64 bits.
2521 if (getContext().getTypeAlign(Ty) > 32) {
2522 ElemTy = llvm::Type::getInt64Ty(getVMContext());
2523 SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
2525 ElemTy = llvm::Type::getInt32Ty(getVMContext());
2526 SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
2530 llvm::StructType::get(llvm::ArrayType::get(ElemTy, SizeRegs), NULL);
2531 return ABIArgInfo::getDirect(STy);
2534 static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
2535 llvm::LLVMContext &VMContext) {
2536 // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
2537 // is called integer-like if its size is less than or equal to one word, and
2538 // the offset of each of its addressable sub-fields is zero.
2540 uint64_t Size = Context.getTypeSize(Ty);
2542 // Check that the type fits in a word.
2546 // FIXME: Handle vector types!
2547 if (Ty->isVectorType())
2550 // Float types are never treated as "integer like".
2551 if (Ty->isRealFloatingType())
2554 // If this is a builtin or pointer type then it is ok.
2555 if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
2558 // Small complex integer types are "integer like".
2559 if (const ComplexType *CT = Ty->getAs<ComplexType>())
2560 return isIntegerLikeType(CT->getElementType(), Context, VMContext);
2562 // Single element and zero sized arrays should be allowed, by the definition
2563 // above, but they are not.
2565 // Otherwise, it must be a record type.
2566 const RecordType *RT = Ty->getAs<RecordType>();
2567 if (!RT) return false;
2569 // Ignore records with flexible arrays.
2570 const RecordDecl *RD = RT->getDecl();
2571 if (RD->hasFlexibleArrayMember())
2574 // Check that all sub-fields are at offset 0, and are themselves "integer
2576 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
2578 bool HadField = false;
2580 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
2581 i != e; ++i, ++idx) {
2582 const FieldDecl *FD = *i;
2584 // Bit-fields are not addressable, we only need to verify they are "integer
2585 // like". We still have to disallow a subsequent non-bitfield, for example:
2586 // struct { int : 0; int x }
2587 // is non-integer like according to gcc.
2588 if (FD->isBitField()) {
2592 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
2598 // Check if this field is at offset 0.
2599 if (Layout.getFieldOffset(idx) != 0)
2602 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
2605 // Only allow at most one field in a structure. This doesn't match the
2606 // wording above, but follows gcc in situations with a field following an
2608 if (!RD->isUnion()) {
2619 ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy) const {
2620 if (RetTy->isVoidType())
2621 return ABIArgInfo::getIgnore();
2623 // Large vector types should be returned via memory.
2624 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
2625 return ABIArgInfo::getIndirect(0);
2627 if (!isAggregateTypeForABI(RetTy)) {
2628 // Treat an enum type as its underlying type.
2629 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
2630 RetTy = EnumTy->getDecl()->getIntegerType();
2632 return (RetTy->isPromotableIntegerType() ?
2633 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
2636 // Structures with either a non-trivial destructor or a non-trivial
2637 // copy constructor are always indirect.
2638 if (isRecordWithNonTrivialDestructorOrCopyConstructor(RetTy))
2639 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
2641 // Are we following APCS?
2642 if (getABIKind() == APCS) {
2643 if (isEmptyRecord(getContext(), RetTy, false))
2644 return ABIArgInfo::getIgnore();
2646 // Complex types are all returned as packed integers.
2648 // FIXME: Consider using 2 x vector types if the back end handles them
2650 if (RetTy->isAnyComplexType())
2651 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2652 getContext().getTypeSize(RetTy)));
2654 // Integer like structures are returned in r0.
2655 if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
2656 // Return in the smallest viable integer type.
2657 uint64_t Size = getContext().getTypeSize(RetTy);
2659 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
2661 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
2662 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
2665 // Otherwise return in memory.
2666 return ABIArgInfo::getIndirect(0);
2669 // Otherwise this is an AAPCS variant.
2671 if (isEmptyRecord(getContext(), RetTy, true))
2672 return ABIArgInfo::getIgnore();
2674 // Aggregates <= 4 bytes are returned in r0; other aggregates
2675 // are returned indirectly.
2676 uint64_t Size = getContext().getTypeSize(RetTy);
2678 // Return in the smallest viable integer type.
2680 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
2682 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
2683 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
2686 return ABIArgInfo::getIndirect(0);
2689 llvm::Value *ARMABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2690 CodeGenFunction &CGF) const {
2691 llvm::Type *BP = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
2692 llvm::Type *BPP = llvm::PointerType::getUnqual(BP);
2694 CGBuilderTy &Builder = CGF.Builder;
2695 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
2697 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
2698 // Handle address alignment for type alignment > 32 bits
2699 uint64_t TyAlign = CGF.getContext().getTypeAlign(Ty) / 8;
2701 assert((TyAlign & (TyAlign - 1)) == 0 &&
2702 "Alignment is not power of 2!");
2703 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int32Ty);
2704 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt32(TyAlign - 1));
2705 AddrAsInt = Builder.CreateAnd(AddrAsInt, Builder.getInt32(~(TyAlign - 1)));
2706 Addr = Builder.CreateIntToPtr(AddrAsInt, BP);
2709 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
2710 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
2713 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 4);
2714 llvm::Value *NextAddr =
2715 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
2717 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
2722 //===----------------------------------------------------------------------===//
2723 // PTX ABI Implementation
2724 //===----------------------------------------------------------------------===//
2728 class PTXABIInfo : public ABIInfo {
2730 PTXABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
2732 ABIArgInfo classifyReturnType(QualType RetTy) const;
2733 ABIArgInfo classifyArgumentType(QualType Ty) const;
2735 virtual void computeInfo(CGFunctionInfo &FI) const;
2736 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2737 CodeGenFunction &CFG) const;
2740 class PTXTargetCodeGenInfo : public TargetCodeGenInfo {
2742 PTXTargetCodeGenInfo(CodeGenTypes &CGT)
2743 : TargetCodeGenInfo(new PTXABIInfo(CGT)) {}
2745 virtual void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2746 CodeGen::CodeGenModule &M) const;
2749 ABIArgInfo PTXABIInfo::classifyReturnType(QualType RetTy) const {
2750 if (RetTy->isVoidType())
2751 return ABIArgInfo::getIgnore();
2752 if (isAggregateTypeForABI(RetTy))
2753 return ABIArgInfo::getIndirect(0);
2754 return ABIArgInfo::getDirect();
2757 ABIArgInfo PTXABIInfo::classifyArgumentType(QualType Ty) const {
2758 if (isAggregateTypeForABI(Ty))
2759 return ABIArgInfo::getIndirect(0);
2761 return ABIArgInfo::getDirect();
2764 void PTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
2765 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
2766 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
2768 it->info = classifyArgumentType(it->type);
2770 // Always honor user-specified calling convention.
2771 if (FI.getCallingConvention() != llvm::CallingConv::C)
2774 // Calling convention as default by an ABI.
2775 llvm::CallingConv::ID DefaultCC;
2776 const LangOptions &LangOpts = getContext().getLangOptions();
2777 if (LangOpts.OpenCL || LangOpts.CUDA) {
2778 // If we are in OpenCL or CUDA mode, then default to device functions
2779 DefaultCC = llvm::CallingConv::PTX_Device;
2781 // If we are in standard C/C++ mode, use the triple to decide on the default
2783 getContext().getTargetInfo().getTriple().getEnvironmentName();
2784 if (Env == "device")
2785 DefaultCC = llvm::CallingConv::PTX_Device;
2787 DefaultCC = llvm::CallingConv::PTX_Kernel;
2789 FI.setEffectiveCallingConvention(DefaultCC);
2793 llvm::Value *PTXABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2794 CodeGenFunction &CFG) const {
2795 llvm_unreachable("PTX does not support varargs");
2799 void PTXTargetCodeGenInfo::SetTargetAttributes(const Decl *D,
2800 llvm::GlobalValue *GV,
2801 CodeGen::CodeGenModule &M) const{
2802 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
2805 llvm::Function *F = cast<llvm::Function>(GV);
2807 // Perform special handling in OpenCL mode
2808 if (M.getLangOptions().OpenCL) {
2809 // Use OpenCL function attributes to set proper calling conventions
2810 // By default, all functions are device functions
2811 if (FD->hasAttr<OpenCLKernelAttr>()) {
2812 // OpenCL __kernel functions get a kernel calling convention
2813 F->setCallingConv(llvm::CallingConv::PTX_Kernel);
2814 // And kernel functions are not subject to inlining
2815 F->addFnAttr(llvm::Attribute::NoInline);
2819 // Perform special handling in CUDA mode.
2820 if (M.getLangOptions().CUDA) {
2821 // CUDA __global__ functions get a kernel calling convention. Since
2822 // __global__ functions cannot be called from the device, we do not
2823 // need to set the noinline attribute.
2824 if (FD->getAttr<CUDAGlobalAttr>())
2825 F->setCallingConv(llvm::CallingConv::PTX_Kernel);
2831 //===----------------------------------------------------------------------===//
2832 // SystemZ ABI Implementation
2833 //===----------------------------------------------------------------------===//
2837 class SystemZABIInfo : public ABIInfo {
2839 SystemZABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
2841 bool isPromotableIntegerType(QualType Ty) const;
2843 ABIArgInfo classifyReturnType(QualType RetTy) const;
2844 ABIArgInfo classifyArgumentType(QualType RetTy) const;
2846 virtual void computeInfo(CGFunctionInfo &FI) const {
2847 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
2848 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
2850 it->info = classifyArgumentType(it->type);
2853 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2854 CodeGenFunction &CGF) const;
2857 class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
2859 SystemZTargetCodeGenInfo(CodeGenTypes &CGT)
2860 : TargetCodeGenInfo(new SystemZABIInfo(CGT)) {}
2865 bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const {
2866 // SystemZ ABI requires all 8, 16 and 32 bit quantities to be extended.
2867 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
2868 switch (BT->getKind()) {
2869 case BuiltinType::Bool:
2870 case BuiltinType::Char_S:
2871 case BuiltinType::Char_U:
2872 case BuiltinType::SChar:
2873 case BuiltinType::UChar:
2874 case BuiltinType::Short:
2875 case BuiltinType::UShort:
2876 case BuiltinType::Int:
2877 case BuiltinType::UInt:
2885 llvm::Value *SystemZABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2886 CodeGenFunction &CGF) const {
2892 ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
2893 if (RetTy->isVoidType())
2894 return ABIArgInfo::getIgnore();
2895 if (isAggregateTypeForABI(RetTy))
2896 return ABIArgInfo::getIndirect(0);
2898 return (isPromotableIntegerType(RetTy) ?
2899 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
2902 ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
2903 if (isAggregateTypeForABI(Ty))
2904 return ABIArgInfo::getIndirect(0);
2906 return (isPromotableIntegerType(Ty) ?
2907 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
2910 //===----------------------------------------------------------------------===//
2911 // MBlaze ABI Implementation
2912 //===----------------------------------------------------------------------===//
2916 class MBlazeABIInfo : public ABIInfo {
2918 MBlazeABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
2920 bool isPromotableIntegerType(QualType Ty) const;
2922 ABIArgInfo classifyReturnType(QualType RetTy) const;
2923 ABIArgInfo classifyArgumentType(QualType RetTy) const;
2925 virtual void computeInfo(CGFunctionInfo &FI) const {
2926 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
2927 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
2929 it->info = classifyArgumentType(it->type);
2932 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2933 CodeGenFunction &CGF) const;
2936 class MBlazeTargetCodeGenInfo : public TargetCodeGenInfo {
2938 MBlazeTargetCodeGenInfo(CodeGenTypes &CGT)
2939 : TargetCodeGenInfo(new MBlazeABIInfo(CGT)) {}
2940 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2941 CodeGen::CodeGenModule &M) const;
2946 bool MBlazeABIInfo::isPromotableIntegerType(QualType Ty) const {
2947 // MBlaze ABI requires all 8 and 16 bit quantities to be extended.
2948 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
2949 switch (BT->getKind()) {
2950 case BuiltinType::Bool:
2951 case BuiltinType::Char_S:
2952 case BuiltinType::Char_U:
2953 case BuiltinType::SChar:
2954 case BuiltinType::UChar:
2955 case BuiltinType::Short:
2956 case BuiltinType::UShort:
2964 llvm::Value *MBlazeABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2965 CodeGenFunction &CGF) const {
2971 ABIArgInfo MBlazeABIInfo::classifyReturnType(QualType RetTy) const {
2972 if (RetTy->isVoidType())
2973 return ABIArgInfo::getIgnore();
2974 if (isAggregateTypeForABI(RetTy))
2975 return ABIArgInfo::getIndirect(0);
2977 return (isPromotableIntegerType(RetTy) ?
2978 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
2981 ABIArgInfo MBlazeABIInfo::classifyArgumentType(QualType Ty) const {
2982 if (isAggregateTypeForABI(Ty))
2983 return ABIArgInfo::getIndirect(0);
2985 return (isPromotableIntegerType(Ty) ?
2986 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
2989 void MBlazeTargetCodeGenInfo::SetTargetAttributes(const Decl *D,
2990 llvm::GlobalValue *GV,
2991 CodeGen::CodeGenModule &M)
2993 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
2996 llvm::CallingConv::ID CC = llvm::CallingConv::C;
2997 if (FD->hasAttr<MBlazeInterruptHandlerAttr>())
2998 CC = llvm::CallingConv::MBLAZE_INTR;
2999 else if (FD->hasAttr<MBlazeSaveVolatilesAttr>())
3000 CC = llvm::CallingConv::MBLAZE_SVOL;
3002 if (CC != llvm::CallingConv::C) {
3003 // Handle 'interrupt_handler' attribute:
3004 llvm::Function *F = cast<llvm::Function>(GV);
3006 // Step 1: Set ISR calling convention.
3007 F->setCallingConv(CC);
3009 // Step 2: Add attributes goodness.
3010 F->addFnAttr(llvm::Attribute::NoInline);
3013 // Step 3: Emit _interrupt_handler alias.
3014 if (CC == llvm::CallingConv::MBLAZE_INTR)
3015 new llvm::GlobalAlias(GV->getType(), llvm::Function::ExternalLinkage,
3016 "_interrupt_handler", GV, &M.getModule());
3020 //===----------------------------------------------------------------------===//
3021 // MSP430 ABI Implementation
3022 //===----------------------------------------------------------------------===//
3026 class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
3028 MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
3029 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
3030 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
3031 CodeGen::CodeGenModule &M) const;
3036 void MSP430TargetCodeGenInfo::SetTargetAttributes(const Decl *D,
3037 llvm::GlobalValue *GV,
3038 CodeGen::CodeGenModule &M) const {
3039 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3040 if (const MSP430InterruptAttr *attr = FD->getAttr<MSP430InterruptAttr>()) {
3041 // Handle 'interrupt' attribute:
3042 llvm::Function *F = cast<llvm::Function>(GV);
3044 // Step 1: Set ISR calling convention.
3045 F->setCallingConv(llvm::CallingConv::MSP430_INTR);
3047 // Step 2: Add attributes goodness.
3048 F->addFnAttr(llvm::Attribute::NoInline);
3050 // Step 3: Emit ISR vector alias.
3051 unsigned Num = attr->getNumber() + 0xffe0;
3052 new llvm::GlobalAlias(GV->getType(), llvm::Function::ExternalLinkage,
3053 "vector_" + Twine::utohexstr(Num),
3054 GV, &M.getModule());
3059 //===----------------------------------------------------------------------===//
3060 // MIPS ABI Implementation. This works for both little-endian and
3061 // big-endian variants.
3062 //===----------------------------------------------------------------------===//
3065 class MipsABIInfo : public ABIInfo {
3066 static const unsigned MinABIStackAlignInBytes = 4;
3068 MipsABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
3070 ABIArgInfo classifyReturnType(QualType RetTy) const;
3071 ABIArgInfo classifyArgumentType(QualType RetTy) const;
3072 virtual void computeInfo(CGFunctionInfo &FI) const;
3073 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3074 CodeGenFunction &CGF) const;
3077 const unsigned MipsABIInfo::MinABIStackAlignInBytes;
3079 class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
3080 unsigned SizeOfUnwindException;
3082 MIPSTargetCodeGenInfo(CodeGenTypes &CGT, unsigned SZ)
3083 : TargetCodeGenInfo(new MipsABIInfo(CGT)), SizeOfUnwindException(SZ) {}
3085 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const {
3089 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3090 llvm::Value *Address) const;
3092 unsigned getSizeOfUnwindException() const {
3093 return SizeOfUnwindException;
3098 ABIArgInfo MipsABIInfo::classifyArgumentType(QualType Ty) const {
3099 if (isAggregateTypeForABI(Ty)) {
3100 // Ignore empty aggregates.
3101 if (getContext().getTypeSize(Ty) == 0)
3102 return ABIArgInfo::getIgnore();
3104 // Records with non trivial destructors/constructors should not be passed
3106 if (isRecordWithNonTrivialDestructorOrCopyConstructor(Ty))
3107 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3109 return ABIArgInfo::getIndirect(0);
3112 // Treat an enum type as its underlying type.
3113 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3114 Ty = EnumTy->getDecl()->getIntegerType();
3116 return (Ty->isPromotableIntegerType() ?
3117 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
3120 ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
3121 if (RetTy->isVoidType())
3122 return ABIArgInfo::getIgnore();
3124 if (isAggregateTypeForABI(RetTy)) {
3125 if (RetTy->isAnyComplexType())
3126 return ABIArgInfo::getDirect();
3128 return ABIArgInfo::getIndirect(0);
3131 // Treat an enum type as its underlying type.
3132 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
3133 RetTy = EnumTy->getDecl()->getIntegerType();
3135 return (RetTy->isPromotableIntegerType() ?
3136 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
3139 void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
3140 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
3141 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
3143 it->info = classifyArgumentType(it->type);
3146 llvm::Value* MipsABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3147 CodeGenFunction &CGF) const {
3148 llvm::Type *BP = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
3149 llvm::Type *BPP = llvm::PointerType::getUnqual(BP);
3151 CGBuilderTy &Builder = CGF.Builder;
3152 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
3153 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
3154 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
3155 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
3156 llvm::Value *AddrTyped;
3158 if (TypeAlign > MinABIStackAlignInBytes) {
3159 llvm::Value *AddrAsInt32 = CGF.Builder.CreatePtrToInt(Addr, CGF.Int32Ty);
3160 llvm::Value *Inc = llvm::ConstantInt::get(CGF.Int32Ty, TypeAlign - 1);
3161 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int32Ty, -TypeAlign);
3162 llvm::Value *Add = CGF.Builder.CreateAdd(AddrAsInt32, Inc);
3163 llvm::Value *And = CGF.Builder.CreateAnd(Add, Mask);
3164 AddrTyped = CGF.Builder.CreateIntToPtr(And, PTy);
3167 AddrTyped = Builder.CreateBitCast(Addr, PTy);
3169 llvm::Value *AlignedAddr = Builder.CreateBitCast(AddrTyped, BP);
3170 TypeAlign = std::max(TypeAlign, MinABIStackAlignInBytes);
3172 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, TypeAlign);
3173 llvm::Value *NextAddr =
3174 Builder.CreateGEP(AlignedAddr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
3176 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
3182 MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3183 llvm::Value *Address) const {
3184 // This information comes from gcc's implementation, which seems to
3185 // as canonical as it gets.
3187 CodeGen::CGBuilderTy &Builder = CGF.Builder;
3188 llvm::LLVMContext &Context = CGF.getLLVMContext();
3190 // Everything on MIPS is 4 bytes. Double-precision FP registers
3191 // are aliased to pairs of single-precision FP registers.
3192 llvm::IntegerType *i8 = llvm::Type::getInt8Ty(Context);
3193 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
3195 // 0-31 are the general purpose registers, $0 - $31.
3196 // 32-63 are the floating-point registers, $f0 - $f31.
3197 // 64 and 65 are the multiply/divide registers, $hi and $lo.
3198 // 66 is the (notional, I think) register for signal-handler return.
3199 AssignToArrayRange(Builder, Address, Four8, 0, 65);
3201 // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
3202 // They are one bit wide and ignored here.
3204 // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
3205 // (coprocessor 1 is the FP unit)
3206 // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
3207 // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
3208 // 176-181 are the DSP accumulator registers.
3209 AssignToArrayRange(Builder, Address, Four8, 80, 181);
3214 //===----------------------------------------------------------------------===//
3215 // TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
3216 // Currently subclassed only to implement custom OpenCL C function attribute
3218 //===----------------------------------------------------------------------===//
3222 class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
3224 TCETargetCodeGenInfo(CodeGenTypes &CGT)
3225 : DefaultTargetCodeGenInfo(CGT) {}
3227 virtual void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
3228 CodeGen::CodeGenModule &M) const;
3231 void TCETargetCodeGenInfo::SetTargetAttributes(const Decl *D,
3232 llvm::GlobalValue *GV,
3233 CodeGen::CodeGenModule &M) const {
3234 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
3237 llvm::Function *F = cast<llvm::Function>(GV);
3239 if (M.getLangOptions().OpenCL) {
3240 if (FD->hasAttr<OpenCLKernelAttr>()) {
3241 // OpenCL C Kernel functions are not subject to inlining
3242 F->addFnAttr(llvm::Attribute::NoInline);
3244 if (FD->hasAttr<ReqdWorkGroupSizeAttr>()) {
3246 // Convert the reqd_work_group_size() attributes to metadata.
3247 llvm::LLVMContext &Context = F->getContext();
3248 llvm::NamedMDNode *OpenCLMetadata =
3249 M.getModule().getOrInsertNamedMetadata("opencl.kernel_wg_size_info");
3251 SmallVector<llvm::Value*, 5> Operands;
3252 Operands.push_back(F);
3254 Operands.push_back(llvm::Constant::getIntegerValue(
3255 llvm::Type::getInt32Ty(Context),
3258 FD->getAttr<ReqdWorkGroupSizeAttr>()->getXDim())));
3259 Operands.push_back(llvm::Constant::getIntegerValue(
3260 llvm::Type::getInt32Ty(Context),
3263 FD->getAttr<ReqdWorkGroupSizeAttr>()->getYDim())));
3264 Operands.push_back(llvm::Constant::getIntegerValue(
3265 llvm::Type::getInt32Ty(Context),
3268 FD->getAttr<ReqdWorkGroupSizeAttr>()->getZDim())));
3270 // Add a boolean constant operand for "required" (true) or "hint" (false)
3271 // for implementing the work_group_size_hint attr later. Currently
3272 // always true as the hint is not yet implemented.
3273 Operands.push_back(llvm::ConstantInt::getTrue(llvm::Type::getInt1Ty(Context)));
3275 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
3283 const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
3284 if (TheTargetCodeGenInfo)
3285 return *TheTargetCodeGenInfo;
3287 const llvm::Triple &Triple = getContext().getTargetInfo().getTriple();
3288 switch (Triple.getArch()) {
3290 return *(TheTargetCodeGenInfo = new DefaultTargetCodeGenInfo(Types));
3292 case llvm::Triple::mips:
3293 case llvm::Triple::mipsel:
3294 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, 24));
3296 case llvm::Triple::mips64:
3297 case llvm::Triple::mips64el:
3298 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, 32));
3300 case llvm::Triple::arm:
3301 case llvm::Triple::thumb:
3303 ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
3305 if (strcmp(getContext().getTargetInfo().getABI(), "apcs-gnu") == 0)
3306 Kind = ARMABIInfo::APCS;
3307 else if (CodeGenOpts.FloatABI == "hard")
3308 Kind = ARMABIInfo::AAPCS_VFP;
3310 return *(TheTargetCodeGenInfo = new ARMTargetCodeGenInfo(Types, Kind));
3313 case llvm::Triple::ppc:
3314 return *(TheTargetCodeGenInfo = new PPC32TargetCodeGenInfo(Types));
3316 case llvm::Triple::ptx32:
3317 case llvm::Triple::ptx64:
3318 return *(TheTargetCodeGenInfo = new PTXTargetCodeGenInfo(Types));
3320 case llvm::Triple::systemz:
3321 return *(TheTargetCodeGenInfo = new SystemZTargetCodeGenInfo(Types));
3323 case llvm::Triple::mblaze:
3324 return *(TheTargetCodeGenInfo = new MBlazeTargetCodeGenInfo(Types));
3326 case llvm::Triple::msp430:
3327 return *(TheTargetCodeGenInfo = new MSP430TargetCodeGenInfo(Types));
3329 case llvm::Triple::tce:
3330 return *(TheTargetCodeGenInfo = new TCETargetCodeGenInfo(Types));
3332 case llvm::Triple::x86: {
3333 bool DisableMMX = strcmp(getContext().getTargetInfo().getABI(), "no-mmx") == 0;
3335 if (Triple.isOSDarwin())
3336 return *(TheTargetCodeGenInfo =
3337 new X86_32TargetCodeGenInfo(Types, true, true, DisableMMX));
3339 switch (Triple.getOS()) {
3340 case llvm::Triple::Cygwin:
3341 case llvm::Triple::MinGW32:
3342 case llvm::Triple::AuroraUX:
3343 case llvm::Triple::DragonFly:
3344 case llvm::Triple::FreeBSD:
3345 case llvm::Triple::OpenBSD:
3346 case llvm::Triple::NetBSD:
3347 return *(TheTargetCodeGenInfo =
3348 new X86_32TargetCodeGenInfo(Types, false, true, DisableMMX));
3351 return *(TheTargetCodeGenInfo =
3352 new X86_32TargetCodeGenInfo(Types, false, false, DisableMMX));
3356 case llvm::Triple::x86_64:
3357 switch (Triple.getOS()) {
3358 case llvm::Triple::Win32:
3359 case llvm::Triple::MinGW32:
3360 case llvm::Triple::Cygwin:
3361 return *(TheTargetCodeGenInfo = new WinX86_64TargetCodeGenInfo(Types));
3363 return *(TheTargetCodeGenInfo = new X86_64TargetCodeGenInfo(Types));