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"
18 #include "CodeGenFunction.h"
19 #include "clang/AST/RecordLayout.h"
20 #include "clang/CodeGen/CGFunctionInfo.h"
21 #include "clang/Frontend/CodeGenOptions.h"
22 #include "llvm/ADT/Triple.h"
23 #include "llvm/IR/DataLayout.h"
24 #include "llvm/IR/Type.h"
25 #include "llvm/Support/raw_ostream.h"
27 #include <algorithm> // std::sort
29 using namespace clang;
30 using namespace CodeGen;
32 static void AssignToArrayRange(CodeGen::CGBuilderTy &Builder,
37 // Alternatively, we could emit this as a loop in the source.
38 for (unsigned I = FirstIndex; I <= LastIndex; ++I) {
39 llvm::Value *Cell = Builder.CreateConstInBoundsGEP1_32(Array, I);
40 Builder.CreateStore(Value, Cell);
44 static bool isAggregateTypeForABI(QualType T) {
45 return !CodeGenFunction::hasScalarEvaluationKind(T) ||
46 T->isMemberFunctionPointerType();
49 ABIInfo::~ABIInfo() {}
51 static CGCXXABI::RecordArgABI getRecordArgABI(const RecordType *RT,
53 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
55 return CGCXXABI::RAA_Default;
56 return CXXABI.getRecordArgABI(RD);
59 static CGCXXABI::RecordArgABI getRecordArgABI(QualType T,
61 const RecordType *RT = T->getAs<RecordType>();
63 return CGCXXABI::RAA_Default;
64 return getRecordArgABI(RT, CXXABI);
67 CGCXXABI &ABIInfo::getCXXABI() const {
68 return CGT.getCXXABI();
71 ASTContext &ABIInfo::getContext() const {
72 return CGT.getContext();
75 llvm::LLVMContext &ABIInfo::getVMContext() const {
76 return CGT.getLLVMContext();
79 const llvm::DataLayout &ABIInfo::getDataLayout() const {
80 return CGT.getDataLayout();
83 const TargetInfo &ABIInfo::getTarget() const {
84 return CGT.getTarget();
87 void ABIArgInfo::dump() const {
88 raw_ostream &OS = llvm::errs();
89 OS << "(ABIArgInfo Kind=";
93 if (llvm::Type *Ty = getCoerceToType())
105 OS << "InAlloca Offset=" << getInAllocaFieldIndex();
108 OS << "Indirect Align=" << getIndirectAlign()
109 << " ByVal=" << getIndirectByVal()
110 << " Realign=" << getIndirectRealign();
119 TargetCodeGenInfo::~TargetCodeGenInfo() { delete Info; }
121 // If someone can figure out a general rule for this, that would be great.
122 // It's probably just doomed to be platform-dependent, though.
123 unsigned TargetCodeGenInfo::getSizeOfUnwindException() const {
125 // x86-64 FreeBSD, Linux, Darwin
126 // x86-32 FreeBSD, Linux, Darwin
127 // PowerPC Linux, Darwin
128 // ARM Darwin (*not* EABI)
133 bool TargetCodeGenInfo::isNoProtoCallVariadic(const CallArgList &args,
134 const FunctionNoProtoType *fnType) const {
135 // The following conventions are known to require this to be false:
138 // For everything else, we just prefer false unless we opt out.
143 TargetCodeGenInfo::getDependentLibraryOption(llvm::StringRef Lib,
144 llvm::SmallString<24> &Opt) const {
145 // This assumes the user is passing a library name like "rt" instead of a
146 // filename like "librt.a/so", and that they don't care whether it's static or
152 static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays);
154 /// isEmptyField - Return true iff a the field is "empty", that is it
155 /// is an unnamed bit-field or an (array of) empty record(s).
156 static bool isEmptyField(ASTContext &Context, const FieldDecl *FD,
158 if (FD->isUnnamedBitfield())
161 QualType FT = FD->getType();
163 // Constant arrays of empty records count as empty, strip them off.
164 // Constant arrays of zero length always count as empty.
166 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
167 if (AT->getSize() == 0)
169 FT = AT->getElementType();
172 const RecordType *RT = FT->getAs<RecordType>();
176 // C++ record fields are never empty, at least in the Itanium ABI.
178 // FIXME: We should use a predicate for whether this behavior is true in the
180 if (isa<CXXRecordDecl>(RT->getDecl()))
183 return isEmptyRecord(Context, FT, AllowArrays);
186 /// isEmptyRecord - Return true iff a structure contains only empty
187 /// fields. Note that a structure with a flexible array member is not
188 /// considered empty.
189 static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) {
190 const RecordType *RT = T->getAs<RecordType>();
193 const RecordDecl *RD = RT->getDecl();
194 if (RD->hasFlexibleArrayMember())
197 // If this is a C++ record, check the bases first.
198 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
199 for (const auto &I : CXXRD->bases())
200 if (!isEmptyRecord(Context, I.getType(), true))
203 for (const auto *I : RD->fields())
204 if (!isEmptyField(Context, I, AllowArrays))
209 /// isSingleElementStruct - Determine if a structure is a "single
210 /// element struct", i.e. it has exactly one non-empty field or
211 /// exactly one field which is itself a single element
212 /// struct. Structures with flexible array members are never
213 /// considered single element structs.
215 /// \return The field declaration for the single non-empty field, if
217 static const Type *isSingleElementStruct(QualType T, ASTContext &Context) {
218 const RecordType *RT = T->getAsStructureType();
222 const RecordDecl *RD = RT->getDecl();
223 if (RD->hasFlexibleArrayMember())
226 const Type *Found = nullptr;
228 // If this is a C++ record, check the bases first.
229 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
230 for (const auto &I : CXXRD->bases()) {
231 // Ignore empty records.
232 if (isEmptyRecord(Context, I.getType(), true))
235 // If we already found an element then this isn't a single-element struct.
239 // If this is non-empty and not a single element struct, the composite
240 // cannot be a single element struct.
241 Found = isSingleElementStruct(I.getType(), Context);
247 // Check for single element.
248 for (const auto *FD : RD->fields()) {
249 QualType FT = FD->getType();
251 // Ignore empty fields.
252 if (isEmptyField(Context, FD, true))
255 // If we already found an element then this isn't a single-element
260 // Treat single element arrays as the element.
261 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
262 if (AT->getSize().getZExtValue() != 1)
264 FT = AT->getElementType();
267 if (!isAggregateTypeForABI(FT)) {
268 Found = FT.getTypePtr();
270 Found = isSingleElementStruct(FT, Context);
276 // We don't consider a struct a single-element struct if it has
277 // padding beyond the element type.
278 if (Found && Context.getTypeSize(Found) != Context.getTypeSize(T))
284 static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
285 // Treat complex types as the element type.
286 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
287 Ty = CTy->getElementType();
289 // Check for a type which we know has a simple scalar argument-passing
290 // convention without any padding. (We're specifically looking for 32
291 // and 64-bit integer and integer-equivalents, float, and double.)
292 if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() &&
293 !Ty->isEnumeralType() && !Ty->isBlockPointerType())
296 uint64_t Size = Context.getTypeSize(Ty);
297 return Size == 32 || Size == 64;
300 /// canExpandIndirectArgument - Test whether an argument type which is to be
301 /// passed indirectly (on the stack) would have the equivalent layout if it was
302 /// expanded into separate arguments. If so, we prefer to do the latter to avoid
303 /// inhibiting optimizations.
305 // FIXME: This predicate is missing many cases, currently it just follows
306 // llvm-gcc (checks that all fields are 32-bit or 64-bit primitive types). We
307 // should probably make this smarter, or better yet make the LLVM backend
308 // capable of handling it.
309 static bool canExpandIndirectArgument(QualType Ty, ASTContext &Context) {
310 // We can only expand structure types.
311 const RecordType *RT = Ty->getAs<RecordType>();
315 // We can only expand (C) structures.
317 // FIXME: This needs to be generalized to handle classes as well.
318 const RecordDecl *RD = RT->getDecl();
319 if (!RD->isStruct() || isa<CXXRecordDecl>(RD))
324 for (const auto *FD : RD->fields()) {
325 if (!is32Or64BitBasicType(FD->getType(), Context))
328 // FIXME: Reject bit-fields wholesale; there are two problems, we don't know
329 // how to expand them yet, and the predicate for telling if a bitfield still
330 // counts as "basic" is more complicated than what we were doing previously.
331 if (FD->isBitField())
334 Size += Context.getTypeSize(FD->getType());
337 // Make sure there are not any holes in the struct.
338 if (Size != Context.getTypeSize(Ty))
345 /// DefaultABIInfo - The default implementation for ABI specific
346 /// details. This implementation provides information which results in
347 /// self-consistent and sensible LLVM IR generation, but does not
348 /// conform to any particular ABI.
349 class DefaultABIInfo : public ABIInfo {
351 DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
353 ABIArgInfo classifyReturnType(QualType RetTy) const;
354 ABIArgInfo classifyArgumentType(QualType RetTy) const;
356 void computeInfo(CGFunctionInfo &FI) const override {
357 if (!getCXXABI().classifyReturnType(FI))
358 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
359 for (auto &I : FI.arguments())
360 I.info = classifyArgumentType(I.type);
363 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
364 CodeGenFunction &CGF) const override;
367 class DefaultTargetCodeGenInfo : public TargetCodeGenInfo {
369 DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
370 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
373 llvm::Value *DefaultABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
374 CodeGenFunction &CGF) const {
378 ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const {
379 if (isAggregateTypeForABI(Ty))
380 return ABIArgInfo::getIndirect(0);
382 // Treat an enum type as its underlying type.
383 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
384 Ty = EnumTy->getDecl()->getIntegerType();
386 return (Ty->isPromotableIntegerType() ?
387 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
390 ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const {
391 if (RetTy->isVoidType())
392 return ABIArgInfo::getIgnore();
394 if (isAggregateTypeForABI(RetTy))
395 return ABIArgInfo::getIndirect(0);
397 // Treat an enum type as its underlying type.
398 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
399 RetTy = EnumTy->getDecl()->getIntegerType();
401 return (RetTy->isPromotableIntegerType() ?
402 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
405 //===----------------------------------------------------------------------===//
406 // le32/PNaCl bitcode ABI Implementation
408 // This is a simplified version of the x86_32 ABI. Arguments and return values
409 // are always passed on the stack.
410 //===----------------------------------------------------------------------===//
412 class PNaClABIInfo : public ABIInfo {
414 PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
416 ABIArgInfo classifyReturnType(QualType RetTy) const;
417 ABIArgInfo classifyArgumentType(QualType RetTy) const;
419 void computeInfo(CGFunctionInfo &FI) const override;
420 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
421 CodeGenFunction &CGF) const override;
424 class PNaClTargetCodeGenInfo : public TargetCodeGenInfo {
426 PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
427 : TargetCodeGenInfo(new PNaClABIInfo(CGT)) {}
430 void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const {
431 if (!getCXXABI().classifyReturnType(FI))
432 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
434 for (auto &I : FI.arguments())
435 I.info = classifyArgumentType(I.type);
438 llvm::Value *PNaClABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
439 CodeGenFunction &CGF) const {
443 /// \brief Classify argument of given type \p Ty.
444 ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const {
445 if (isAggregateTypeForABI(Ty)) {
446 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
447 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
448 return ABIArgInfo::getIndirect(0);
449 } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
450 // Treat an enum type as its underlying type.
451 Ty = EnumTy->getDecl()->getIntegerType();
452 } else if (Ty->isFloatingType()) {
453 // Floating-point types don't go inreg.
454 return ABIArgInfo::getDirect();
457 return (Ty->isPromotableIntegerType() ?
458 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
461 ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const {
462 if (RetTy->isVoidType())
463 return ABIArgInfo::getIgnore();
465 // In the PNaCl ABI we always return records/structures on the stack.
466 if (isAggregateTypeForABI(RetTy))
467 return ABIArgInfo::getIndirect(0);
469 // Treat an enum type as its underlying type.
470 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
471 RetTy = EnumTy->getDecl()->getIntegerType();
473 return (RetTy->isPromotableIntegerType() ?
474 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
477 /// IsX86_MMXType - Return true if this is an MMX type.
478 bool IsX86_MMXType(llvm::Type *IRType) {
479 // Return true if the type is an MMX type <2 x i32>, <4 x i16>, or <8 x i8>.
480 return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 &&
481 cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() &&
482 IRType->getScalarSizeInBits() != 64;
485 static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
486 StringRef Constraint,
488 if ((Constraint == "y" || Constraint == "&y") && Ty->isVectorTy()) {
489 if (cast<llvm::VectorType>(Ty)->getBitWidth() != 64) {
490 // Invalid MMX constraint
494 return llvm::Type::getX86_MMXTy(CGF.getLLVMContext());
497 // No operation needed
501 //===----------------------------------------------------------------------===//
502 // X86-32 ABI Implementation
503 //===----------------------------------------------------------------------===//
505 /// \brief Similar to llvm::CCState, but for Clang.
507 CCState(unsigned CC) : CC(CC), FreeRegs(0) {}
511 unsigned StackOffset;
515 /// X86_32ABIInfo - The X86-32 ABI information.
516 class X86_32ABIInfo : public ABIInfo {
522 static const unsigned MinABIStackAlignInBytes = 4;
524 bool IsDarwinVectorABI;
525 bool IsSmallStructInRegABI;
526 bool IsWin32StructABI;
527 unsigned DefaultNumRegisterParameters;
529 static bool isRegisterSize(unsigned Size) {
530 return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
533 bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context) const;
535 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
536 /// such that the argument will be passed in memory.
537 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
539 ABIArgInfo getIndirectReturnResult(CCState &State) const;
541 /// \brief Return the alignment to use for the given type on the stack.
542 unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const;
544 Class classify(QualType Ty) const;
545 ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const;
546 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
547 bool shouldUseInReg(QualType Ty, CCState &State, bool &NeedsPadding) const;
549 /// \brief Rewrite the function info so that all memory arguments use
551 void rewriteWithInAlloca(CGFunctionInfo &FI) const;
553 void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
554 unsigned &StackOffset, ABIArgInfo &Info,
555 QualType Type) const;
559 void computeInfo(CGFunctionInfo &FI) const override;
560 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
561 CodeGenFunction &CGF) const override;
563 X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool d, bool p, bool w,
565 : ABIInfo(CGT), IsDarwinVectorABI(d), IsSmallStructInRegABI(p),
566 IsWin32StructABI(w), DefaultNumRegisterParameters(r) {}
569 class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
571 X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
572 bool d, bool p, bool w, unsigned r)
573 :TargetCodeGenInfo(new X86_32ABIInfo(CGT, d, p, w, r)) {}
575 static bool isStructReturnInRegABI(
576 const llvm::Triple &Triple, const CodeGenOptions &Opts);
578 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
579 CodeGen::CodeGenModule &CGM) const override;
581 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
582 // Darwin uses different dwarf register numbers for EH.
583 if (CGM.getTarget().getTriple().isOSDarwin()) return 5;
587 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
588 llvm::Value *Address) const override;
590 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
591 StringRef Constraint,
592 llvm::Type* Ty) const override {
593 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
597 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
598 unsigned Sig = (0xeb << 0) | // jmp rel8
599 (0x06 << 8) | // .+0x08
602 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
609 /// shouldReturnTypeInRegister - Determine if the given type should be
610 /// passed in a register (for the Darwin ABI).
611 bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
612 ASTContext &Context) const {
613 uint64_t Size = Context.getTypeSize(Ty);
615 // Type must be register sized.
616 if (!isRegisterSize(Size))
619 if (Ty->isVectorType()) {
620 // 64- and 128- bit vectors inside structures are not returned in
622 if (Size == 64 || Size == 128)
628 // If this is a builtin, pointer, enum, complex type, member pointer, or
629 // member function pointer it is ok.
630 if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() ||
631 Ty->isAnyComplexType() || Ty->isEnumeralType() ||
632 Ty->isBlockPointerType() || Ty->isMemberPointerType())
635 // Arrays are treated like records.
636 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
637 return shouldReturnTypeInRegister(AT->getElementType(), Context);
639 // Otherwise, it must be a record type.
640 const RecordType *RT = Ty->getAs<RecordType>();
641 if (!RT) return false;
643 // FIXME: Traverse bases here too.
645 // Structure types are passed in register if all fields would be
646 // passed in a register.
647 for (const auto *FD : RT->getDecl()->fields()) {
648 // Empty fields are ignored.
649 if (isEmptyField(Context, FD, true))
652 // Check fields recursively.
653 if (!shouldReturnTypeInRegister(FD->getType(), Context))
659 ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(CCState &State) const {
660 // If the return value is indirect, then the hidden argument is consuming one
662 if (State.FreeRegs) {
664 return ABIArgInfo::getIndirectInReg(/*Align=*/0, /*ByVal=*/false);
666 return ABIArgInfo::getIndirect(/*Align=*/0, /*ByVal=*/false);
669 ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy, CCState &State) const {
670 if (RetTy->isVoidType())
671 return ABIArgInfo::getIgnore();
673 if (const VectorType *VT = RetTy->getAs<VectorType>()) {
674 // On Darwin, some vectors are returned in registers.
675 if (IsDarwinVectorABI) {
676 uint64_t Size = getContext().getTypeSize(RetTy);
678 // 128-bit vectors are a special case; they are returned in
679 // registers and we need to make sure to pick a type the LLVM
680 // backend will like.
682 return ABIArgInfo::getDirect(llvm::VectorType::get(
683 llvm::Type::getInt64Ty(getVMContext()), 2));
685 // Always return in register if it fits in a general purpose
686 // register, or if it is 64 bits and has a single element.
687 if ((Size == 8 || Size == 16 || Size == 32) ||
688 (Size == 64 && VT->getNumElements() == 1))
689 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
692 return getIndirectReturnResult(State);
695 return ABIArgInfo::getDirect();
698 if (isAggregateTypeForABI(RetTy)) {
699 if (const RecordType *RT = RetTy->getAs<RecordType>()) {
700 // Structures with flexible arrays are always indirect.
701 if (RT->getDecl()->hasFlexibleArrayMember())
702 return getIndirectReturnResult(State);
705 // If specified, structs and unions are always indirect.
706 if (!IsSmallStructInRegABI && !RetTy->isAnyComplexType())
707 return getIndirectReturnResult(State);
709 // Small structures which are register sized are generally returned
711 if (shouldReturnTypeInRegister(RetTy, getContext())) {
712 uint64_t Size = getContext().getTypeSize(RetTy);
714 // As a special-case, if the struct is a "single-element" struct, and
715 // the field is of type "float" or "double", return it in a
716 // floating-point register. (MSVC does not apply this special case.)
717 // We apply a similar transformation for pointer types to improve the
718 // quality of the generated IR.
719 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
720 if ((!IsWin32StructABI && SeltTy->isRealFloatingType())
721 || SeltTy->hasPointerRepresentation())
722 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
724 // FIXME: We should be able to narrow this integer in cases with dead
726 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
729 return getIndirectReturnResult(State);
732 // Treat an enum type as its underlying type.
733 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
734 RetTy = EnumTy->getDecl()->getIntegerType();
736 return (RetTy->isPromotableIntegerType() ?
737 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
740 static bool isSSEVectorType(ASTContext &Context, QualType Ty) {
741 return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128;
744 static bool isRecordWithSSEVectorType(ASTContext &Context, QualType Ty) {
745 const RecordType *RT = Ty->getAs<RecordType>();
748 const RecordDecl *RD = RT->getDecl();
750 // If this is a C++ record, check the bases first.
751 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
752 for (const auto &I : CXXRD->bases())
753 if (!isRecordWithSSEVectorType(Context, I.getType()))
756 for (const auto *i : RD->fields()) {
757 QualType FT = i->getType();
759 if (isSSEVectorType(Context, FT))
762 if (isRecordWithSSEVectorType(Context, FT))
769 unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
770 unsigned Align) const {
771 // Otherwise, if the alignment is less than or equal to the minimum ABI
772 // alignment, just use the default; the backend will handle this.
773 if (Align <= MinABIStackAlignInBytes)
774 return 0; // Use default alignment.
776 // On non-Darwin, the stack type alignment is always 4.
777 if (!IsDarwinVectorABI) {
778 // Set explicit alignment, since we may need to realign the top.
779 return MinABIStackAlignInBytes;
782 // Otherwise, if the type contains an SSE vector type, the alignment is 16.
783 if (Align >= 16 && (isSSEVectorType(getContext(), Ty) ||
784 isRecordWithSSEVectorType(getContext(), Ty)))
787 return MinABIStackAlignInBytes;
790 ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal,
791 CCState &State) const {
793 if (State.FreeRegs) {
794 --State.FreeRegs; // Non-byval indirects just use one pointer.
795 return ABIArgInfo::getIndirectInReg(0, false);
797 return ABIArgInfo::getIndirect(0, false);
800 // Compute the byval alignment.
801 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
802 unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign);
804 return ABIArgInfo::getIndirect(4, /*ByVal=*/true);
806 // If the stack alignment is less than the type alignment, realign the
808 bool Realign = TypeAlign > StackAlign;
809 return ABIArgInfo::getIndirect(StackAlign, /*ByVal=*/true, Realign);
812 X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const {
813 const Type *T = isSingleElementStruct(Ty, getContext());
817 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
818 BuiltinType::Kind K = BT->getKind();
819 if (K == BuiltinType::Float || K == BuiltinType::Double)
825 bool X86_32ABIInfo::shouldUseInReg(QualType Ty, CCState &State,
826 bool &NeedsPadding) const {
827 NeedsPadding = false;
828 Class C = classify(Ty);
832 unsigned Size = getContext().getTypeSize(Ty);
833 unsigned SizeInRegs = (Size + 31) / 32;
838 if (SizeInRegs > State.FreeRegs) {
843 State.FreeRegs -= SizeInRegs;
845 if (State.CC == llvm::CallingConv::X86_FastCall) {
849 if (Ty->isIntegralOrEnumerationType())
852 if (Ty->isPointerType())
855 if (Ty->isReferenceType())
867 ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
868 CCState &State) const {
869 // FIXME: Set alignment on indirect arguments.
870 if (isAggregateTypeForABI(Ty)) {
871 if (const RecordType *RT = Ty->getAs<RecordType>()) {
872 // Check with the C++ ABI first.
873 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
874 if (RAA == CGCXXABI::RAA_Indirect) {
875 return getIndirectResult(Ty, false, State);
876 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
877 // The field index doesn't matter, we'll fix it up later.
878 return ABIArgInfo::getInAlloca(/*FieldIndex=*/0);
881 // Structs are always byval on win32, regardless of what they contain.
882 if (IsWin32StructABI)
883 return getIndirectResult(Ty, true, State);
885 // Structures with flexible arrays are always indirect.
886 if (RT->getDecl()->hasFlexibleArrayMember())
887 return getIndirectResult(Ty, true, State);
890 // Ignore empty structs/unions.
891 if (isEmptyRecord(getContext(), Ty, true))
892 return ABIArgInfo::getIgnore();
894 llvm::LLVMContext &LLVMContext = getVMContext();
895 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
897 if (shouldUseInReg(Ty, State, NeedsPadding)) {
898 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
899 SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32);
900 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
901 return ABIArgInfo::getDirectInReg(Result);
903 llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : nullptr;
905 // Expand small (<= 128-bit) record types when we know that the stack layout
906 // of those arguments will match the struct. This is important because the
907 // LLVM backend isn't smart enough to remove byval, which inhibits many
909 if (getContext().getTypeSize(Ty) <= 4*32 &&
910 canExpandIndirectArgument(Ty, getContext()))
911 return ABIArgInfo::getExpandWithPadding(
912 State.CC == llvm::CallingConv::X86_FastCall, PaddingType);
914 return getIndirectResult(Ty, true, State);
917 if (const VectorType *VT = Ty->getAs<VectorType>()) {
918 // On Darwin, some vectors are passed in memory, we handle this by passing
919 // it as an i8/i16/i32/i64.
920 if (IsDarwinVectorABI) {
921 uint64_t Size = getContext().getTypeSize(Ty);
922 if ((Size == 8 || Size == 16 || Size == 32) ||
923 (Size == 64 && VT->getNumElements() == 1))
924 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
928 if (IsX86_MMXType(CGT.ConvertType(Ty)))
929 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64));
931 return ABIArgInfo::getDirect();
935 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
936 Ty = EnumTy->getDecl()->getIntegerType();
939 bool InReg = shouldUseInReg(Ty, State, NeedsPadding);
941 if (Ty->isPromotableIntegerType()) {
943 return ABIArgInfo::getExtendInReg();
944 return ABIArgInfo::getExtend();
947 return ABIArgInfo::getDirectInReg();
948 return ABIArgInfo::getDirect();
951 void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const {
952 CCState State(FI.getCallingConvention());
953 if (State.CC == llvm::CallingConv::X86_FastCall)
955 else if (FI.getHasRegParm())
956 State.FreeRegs = FI.getRegParm();
958 State.FreeRegs = DefaultNumRegisterParameters;
960 if (!getCXXABI().classifyReturnType(FI)) {
961 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), State);
962 } else if (FI.getReturnInfo().isIndirect()) {
963 // The C++ ABI is not aware of register usage, so we have to check if the
964 // return value was sret and put it in a register ourselves if appropriate.
965 if (State.FreeRegs) {
966 --State.FreeRegs; // The sret parameter consumes a register.
967 FI.getReturnInfo().setInReg(true);
971 bool UsedInAlloca = false;
972 for (auto &I : FI.arguments()) {
973 I.info = classifyArgumentType(I.type, State);
974 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca);
977 // If we needed to use inalloca for any argument, do a second pass and rewrite
978 // all the memory arguments to use inalloca.
980 rewriteWithInAlloca(FI);
984 X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
985 unsigned &StackOffset,
986 ABIArgInfo &Info, QualType Type) const {
987 assert(StackOffset % 4U == 0 && "unaligned inalloca struct");
988 Info = ABIArgInfo::getInAlloca(FrameFields.size());
989 FrameFields.push_back(CGT.ConvertTypeForMem(Type));
990 StackOffset += getContext().getTypeSizeInChars(Type).getQuantity();
992 // Insert padding bytes to respect alignment. For x86_32, each argument is 4
994 if (StackOffset % 4U) {
995 unsigned OldOffset = StackOffset;
996 StackOffset = llvm::RoundUpToAlignment(StackOffset, 4U);
997 unsigned NumBytes = StackOffset - OldOffset;
999 llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext());
1000 Ty = llvm::ArrayType::get(Ty, NumBytes);
1001 FrameFields.push_back(Ty);
1005 void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const {
1006 assert(IsWin32StructABI && "inalloca only supported on win32");
1008 // Build a packed struct type for all of the arguments in memory.
1009 SmallVector<llvm::Type *, 6> FrameFields;
1011 unsigned StackOffset = 0;
1013 // Put the sret parameter into the inalloca struct if it's in memory.
1014 ABIArgInfo &Ret = FI.getReturnInfo();
1015 if (Ret.isIndirect() && !Ret.getInReg()) {
1016 CanQualType PtrTy = getContext().getPointerType(FI.getReturnType());
1017 addFieldToArgStruct(FrameFields, StackOffset, Ret, PtrTy);
1018 // On Windows, the hidden sret parameter is always returned in eax.
1019 Ret.setInAllocaSRet(IsWin32StructABI);
1022 // Skip the 'this' parameter in ecx.
1023 CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end();
1024 if (FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall)
1027 // Put arguments passed in memory into the struct.
1028 for (; I != E; ++I) {
1030 // Leave ignored and inreg arguments alone.
1031 switch (I->info.getKind()) {
1032 case ABIArgInfo::Indirect:
1033 assert(I->info.getIndirectByVal());
1035 case ABIArgInfo::Ignore:
1037 case ABIArgInfo::Direct:
1038 case ABIArgInfo::Extend:
1039 if (I->info.getInReg())
1046 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
1049 FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields,
1050 /*isPacked=*/true));
1053 llvm::Value *X86_32ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1054 CodeGenFunction &CGF) const {
1055 llvm::Type *BPP = CGF.Int8PtrPtrTy;
1057 CGBuilderTy &Builder = CGF.Builder;
1058 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
1060 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
1062 // Compute if the address needs to be aligned
1063 unsigned Align = CGF.getContext().getTypeAlignInChars(Ty).getQuantity();
1064 Align = getTypeStackAlignInBytes(Ty, Align);
1065 Align = std::max(Align, 4U);
1067 // addr = (addr + align - 1) & -align;
1068 llvm::Value *Offset =
1069 llvm::ConstantInt::get(CGF.Int32Ty, Align - 1);
1070 Addr = CGF.Builder.CreateGEP(Addr, Offset);
1071 llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(Addr,
1073 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int32Ty, -Align);
1074 Addr = CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask),
1080 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
1081 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
1084 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, Align);
1085 llvm::Value *NextAddr =
1086 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
1088 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
1093 bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
1094 const llvm::Triple &Triple, const CodeGenOptions &Opts) {
1095 assert(Triple.getArch() == llvm::Triple::x86);
1097 switch (Opts.getStructReturnConvention()) {
1098 case CodeGenOptions::SRCK_Default:
1100 case CodeGenOptions::SRCK_OnStack: // -fpcc-struct-return
1102 case CodeGenOptions::SRCK_InRegs: // -freg-struct-return
1106 if (Triple.isOSDarwin())
1109 switch (Triple.getOS()) {
1110 case llvm::Triple::AuroraUX:
1111 case llvm::Triple::DragonFly:
1112 case llvm::Triple::FreeBSD:
1113 case llvm::Triple::OpenBSD:
1114 case llvm::Triple::Bitrig:
1116 case llvm::Triple::Win32:
1117 switch (Triple.getEnvironment()) {
1118 case llvm::Triple::UnknownEnvironment:
1119 case llvm::Triple::Cygnus:
1120 case llvm::Triple::GNU:
1121 case llvm::Triple::MSVC:
1131 void X86_32TargetCodeGenInfo::SetTargetAttributes(const Decl *D,
1132 llvm::GlobalValue *GV,
1133 CodeGen::CodeGenModule &CGM) const {
1134 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1135 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
1136 // Get the LLVM function.
1137 llvm::Function *Fn = cast<llvm::Function>(GV);
1139 // Now add the 'alignstack' attribute with a value of 16.
1140 llvm::AttrBuilder B;
1141 B.addStackAlignmentAttr(16);
1142 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
1143 llvm::AttributeSet::get(CGM.getLLVMContext(),
1144 llvm::AttributeSet::FunctionIndex,
1150 bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
1151 CodeGen::CodeGenFunction &CGF,
1152 llvm::Value *Address) const {
1153 CodeGen::CGBuilderTy &Builder = CGF.Builder;
1155 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
1157 // 0-7 are the eight integer registers; the order is different
1158 // on Darwin (for EH), but the range is the same.
1160 AssignToArrayRange(Builder, Address, Four8, 0, 8);
1162 if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
1163 // 12-16 are st(0..4). Not sure why we stop at 4.
1164 // These have size 16, which is sizeof(long double) on
1165 // platforms with 8-byte alignment for that type.
1166 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
1167 AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
1170 // 9 is %eflags, which doesn't get a size on Darwin for some
1172 Builder.CreateStore(Four8, Builder.CreateConstInBoundsGEP1_32(Address, 9));
1174 // 11-16 are st(0..5). Not sure why we stop at 5.
1175 // These have size 12, which is sizeof(long double) on
1176 // platforms with 4-byte alignment for that type.
1177 llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
1178 AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
1184 //===----------------------------------------------------------------------===//
1185 // X86-64 ABI Implementation
1186 //===----------------------------------------------------------------------===//
1190 /// X86_64ABIInfo - The X86_64 ABI information.
1191 class X86_64ABIInfo : public ABIInfo {
1203 /// merge - Implement the X86_64 ABI merging algorithm.
1205 /// Merge an accumulating classification \arg Accum with a field
1206 /// classification \arg Field.
1208 /// \param Accum - The accumulating classification. This should
1209 /// always be either NoClass or the result of a previous merge
1210 /// call. In addition, this should never be Memory (the caller
1211 /// should just return Memory for the aggregate).
1212 static Class merge(Class Accum, Class Field);
1214 /// postMerge - Implement the X86_64 ABI post merging algorithm.
1216 /// Post merger cleanup, reduces a malformed Hi and Lo pair to
1217 /// final MEMORY or SSE classes when necessary.
1219 /// \param AggregateSize - The size of the current aggregate in
1220 /// the classification process.
1222 /// \param Lo - The classification for the parts of the type
1223 /// residing in the low word of the containing object.
1225 /// \param Hi - The classification for the parts of the type
1226 /// residing in the higher words of the containing object.
1228 void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
1230 /// classify - Determine the x86_64 register classes in which the
1231 /// given type T should be passed.
1233 /// \param Lo - The classification for the parts of the type
1234 /// residing in the low word of the containing object.
1236 /// \param Hi - The classification for the parts of the type
1237 /// residing in the high word of the containing object.
1239 /// \param OffsetBase - The bit offset of this type in the
1240 /// containing object. Some parameters are classified different
1241 /// depending on whether they straddle an eightbyte boundary.
1243 /// \param isNamedArg - Whether the argument in question is a "named"
1244 /// argument, as used in AMD64-ABI 3.5.7.
1246 /// If a word is unused its result will be NoClass; if a type should
1247 /// be passed in Memory then at least the classification of \arg Lo
1250 /// The \arg Lo class will be NoClass iff the argument is ignored.
1252 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
1253 /// also be ComplexX87.
1254 void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi,
1255 bool isNamedArg) const;
1257 llvm::Type *GetByteVectorType(QualType Ty) const;
1258 llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
1259 unsigned IROffset, QualType SourceTy,
1260 unsigned SourceOffset) const;
1261 llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
1262 unsigned IROffset, QualType SourceTy,
1263 unsigned SourceOffset) const;
1265 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
1266 /// such that the argument will be returned in memory.
1267 ABIArgInfo getIndirectReturnResult(QualType Ty) const;
1269 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
1270 /// such that the argument will be passed in memory.
1272 /// \param freeIntRegs - The number of free integer registers remaining
1274 ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
1276 ABIArgInfo classifyReturnType(QualType RetTy) const;
1278 ABIArgInfo classifyArgumentType(QualType Ty,
1279 unsigned freeIntRegs,
1280 unsigned &neededInt,
1281 unsigned &neededSSE,
1282 bool isNamedArg) const;
1284 bool IsIllegalVectorType(QualType Ty) const;
1286 /// The 0.98 ABI revision clarified a lot of ambiguities,
1287 /// unfortunately in ways that were not always consistent with
1288 /// certain previous compilers. In particular, platforms which
1289 /// required strict binary compatibility with older versions of GCC
1290 /// may need to exempt themselves.
1291 bool honorsRevision0_98() const {
1292 return !getTarget().getTriple().isOSDarwin();
1296 // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
1298 bool Has64BitPointers;
1301 X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, bool hasavx) :
1302 ABIInfo(CGT), HasAVX(hasavx),
1303 Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {
1306 bool isPassedUsingAVXType(QualType type) const {
1307 unsigned neededInt, neededSSE;
1308 // The freeIntRegs argument doesn't matter here.
1309 ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE,
1310 /*isNamedArg*/true);
1311 if (info.isDirect()) {
1312 llvm::Type *ty = info.getCoerceToType();
1313 if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
1314 return (vectorTy->getBitWidth() > 128);
1319 void computeInfo(CGFunctionInfo &FI) const override;
1321 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1322 CodeGenFunction &CGF) const override;
1325 /// WinX86_64ABIInfo - The Windows X86_64 ABI information.
1326 class WinX86_64ABIInfo : public ABIInfo {
1328 ABIArgInfo classify(QualType Ty, bool IsReturnType) const;
1331 WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
1333 void computeInfo(CGFunctionInfo &FI) const override;
1335 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1336 CodeGenFunction &CGF) const override;
1339 class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
1341 X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX)
1342 : TargetCodeGenInfo(new X86_64ABIInfo(CGT, HasAVX)) {}
1344 const X86_64ABIInfo &getABIInfo() const {
1345 return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
1348 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
1352 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
1353 llvm::Value *Address) const override {
1354 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
1356 // 0-15 are the 16 integer registers.
1358 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
1362 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
1363 StringRef Constraint,
1364 llvm::Type* Ty) const override {
1365 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
1368 bool isNoProtoCallVariadic(const CallArgList &args,
1369 const FunctionNoProtoType *fnType) const override {
1370 // The default CC on x86-64 sets %al to the number of SSA
1371 // registers used, and GCC sets this when calling an unprototyped
1372 // function, so we override the default behavior. However, don't do
1373 // that when AVX types are involved: the ABI explicitly states it is
1374 // undefined, and it doesn't work in practice because of how the ABI
1375 // defines varargs anyway.
1376 if (fnType->getCallConv() == CC_C) {
1377 bool HasAVXType = false;
1378 for (CallArgList::const_iterator
1379 it = args.begin(), ie = args.end(); it != ie; ++it) {
1380 if (getABIInfo().isPassedUsingAVXType(it->Ty)) {
1390 return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
1394 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
1395 unsigned Sig = (0xeb << 0) | // jmp rel8
1396 (0x0a << 8) | // .+0x0c
1399 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
1404 static std::string qualifyWindowsLibrary(llvm::StringRef Lib) {
1405 // If the argument does not end in .lib, automatically add the suffix. This
1406 // matches the behavior of MSVC.
1407 std::string ArgStr = Lib;
1408 if (!Lib.endswith_lower(".lib"))
1413 class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
1415 WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
1416 bool d, bool p, bool w, unsigned RegParms)
1417 : X86_32TargetCodeGenInfo(CGT, d, p, w, RegParms) {}
1419 void getDependentLibraryOption(llvm::StringRef Lib,
1420 llvm::SmallString<24> &Opt) const override {
1421 Opt = "/DEFAULTLIB:";
1422 Opt += qualifyWindowsLibrary(Lib);
1425 void getDetectMismatchOption(llvm::StringRef Name,
1426 llvm::StringRef Value,
1427 llvm::SmallString<32> &Opt) const override {
1428 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
1432 class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
1434 WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
1435 : TargetCodeGenInfo(new WinX86_64ABIInfo(CGT)) {}
1437 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
1441 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
1442 llvm::Value *Address) const override {
1443 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
1445 // 0-15 are the 16 integer registers.
1447 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
1451 void getDependentLibraryOption(llvm::StringRef Lib,
1452 llvm::SmallString<24> &Opt) const override {
1453 Opt = "/DEFAULTLIB:";
1454 Opt += qualifyWindowsLibrary(Lib);
1457 void getDetectMismatchOption(llvm::StringRef Name,
1458 llvm::StringRef Value,
1459 llvm::SmallString<32> &Opt) const override {
1460 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
1466 void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
1468 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
1470 // (a) If one of the classes is Memory, the whole argument is passed in
1473 // (b) If X87UP is not preceded by X87, the whole argument is passed in
1476 // (c) If the size of the aggregate exceeds two eightbytes and the first
1477 // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
1478 // argument is passed in memory. NOTE: This is necessary to keep the
1479 // ABI working for processors that don't support the __m256 type.
1481 // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
1483 // Some of these are enforced by the merging logic. Others can arise
1484 // only with unions; for example:
1485 // union { _Complex double; unsigned; }
1487 // Note that clauses (b) and (c) were added in 0.98.
1491 if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
1493 if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
1495 if (Hi == SSEUp && Lo != SSE)
1499 X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
1500 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
1501 // classified recursively so that always two fields are
1502 // considered. The resulting class is calculated according to
1503 // the classes of the fields in the eightbyte:
1505 // (a) If both classes are equal, this is the resulting class.
1507 // (b) If one of the classes is NO_CLASS, the resulting class is
1510 // (c) If one of the classes is MEMORY, the result is the MEMORY
1513 // (d) If one of the classes is INTEGER, the result is the
1516 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
1517 // MEMORY is used as class.
1519 // (f) Otherwise class SSE is used.
1521 // Accum should never be memory (we should have returned) or
1522 // ComplexX87 (because this cannot be passed in a structure).
1523 assert((Accum != Memory && Accum != ComplexX87) &&
1524 "Invalid accumulated classification during merge.");
1525 if (Accum == Field || Field == NoClass)
1527 if (Field == Memory)
1529 if (Accum == NoClass)
1531 if (Accum == Integer || Field == Integer)
1533 if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
1534 Accum == X87 || Accum == X87Up)
1539 void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
1540 Class &Lo, Class &Hi, bool isNamedArg) const {
1541 // FIXME: This code can be simplified by introducing a simple value class for
1542 // Class pairs with appropriate constructor methods for the various
1545 // FIXME: Some of the split computations are wrong; unaligned vectors
1546 // shouldn't be passed in registers for example, so there is no chance they
1547 // can straddle an eightbyte. Verify & simplify.
1551 Class &Current = OffsetBase < 64 ? Lo : Hi;
1554 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
1555 BuiltinType::Kind k = BT->getKind();
1557 if (k == BuiltinType::Void) {
1559 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
1562 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
1564 } else if ((k == BuiltinType::Float || k == BuiltinType::Double) ||
1565 (k == BuiltinType::LongDouble &&
1566 getTarget().getTriple().isOSNaCl())) {
1568 } else if (k == BuiltinType::LongDouble) {
1572 // FIXME: _Decimal32 and _Decimal64 are SSE.
1573 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
1577 if (const EnumType *ET = Ty->getAs<EnumType>()) {
1578 // Classify the underlying integer type.
1579 classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
1583 if (Ty->hasPointerRepresentation()) {
1588 if (Ty->isMemberPointerType()) {
1589 if (Ty->isMemberFunctionPointerType() && Has64BitPointers)
1596 if (const VectorType *VT = Ty->getAs<VectorType>()) {
1597 uint64_t Size = getContext().getTypeSize(VT);
1599 // gcc passes all <4 x char>, <2 x short>, <1 x int>, <1 x
1600 // float> as integer.
1603 // If this type crosses an eightbyte boundary, it should be
1605 uint64_t EB_Real = (OffsetBase) / 64;
1606 uint64_t EB_Imag = (OffsetBase + Size - 1) / 64;
1607 if (EB_Real != EB_Imag)
1609 } else if (Size == 64) {
1610 // gcc passes <1 x double> in memory. :(
1611 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double))
1614 // gcc passes <1 x long long> as INTEGER.
1615 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::LongLong) ||
1616 VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULongLong) ||
1617 VT->getElementType()->isSpecificBuiltinType(BuiltinType::Long) ||
1618 VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULong))
1623 // If this type crosses an eightbyte boundary, it should be
1625 if (OffsetBase && OffsetBase != 64)
1627 } else if (Size == 128 || (HasAVX && isNamedArg && Size == 256)) {
1628 // Arguments of 256-bits are split into four eightbyte chunks. The
1629 // least significant one belongs to class SSE and all the others to class
1630 // SSEUP. The original Lo and Hi design considers that types can't be
1631 // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
1632 // This design isn't correct for 256-bits, but since there're no cases
1633 // where the upper parts would need to be inspected, avoid adding
1634 // complexity and just consider Hi to match the 64-256 part.
1636 // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
1637 // registers if they are "named", i.e. not part of the "..." of a
1638 // variadic function.
1645 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
1646 QualType ET = getContext().getCanonicalType(CT->getElementType());
1648 uint64_t Size = getContext().getTypeSize(Ty);
1649 if (ET->isIntegralOrEnumerationType()) {
1652 else if (Size <= 128)
1654 } else if (ET == getContext().FloatTy)
1656 else if (ET == getContext().DoubleTy ||
1657 (ET == getContext().LongDoubleTy &&
1658 getTarget().getTriple().isOSNaCl()))
1660 else if (ET == getContext().LongDoubleTy)
1661 Current = ComplexX87;
1663 // If this complex type crosses an eightbyte boundary then it
1665 uint64_t EB_Real = (OffsetBase) / 64;
1666 uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
1667 if (Hi == NoClass && EB_Real != EB_Imag)
1673 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
1674 // Arrays are treated like structures.
1676 uint64_t Size = getContext().getTypeSize(Ty);
1678 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
1679 // than four eightbytes, ..., it has class MEMORY.
1683 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
1684 // fields, it has class MEMORY.
1686 // Only need to check alignment of array base.
1687 if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
1690 // Otherwise implement simplified merge. We could be smarter about
1691 // this, but it isn't worth it and would be harder to verify.
1693 uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
1694 uint64_t ArraySize = AT->getSize().getZExtValue();
1696 // The only case a 256-bit wide vector could be used is when the array
1697 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
1698 // to work for sizes wider than 128, early check and fallback to memory.
1699 if (Size > 128 && EltSize != 256)
1702 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
1703 Class FieldLo, FieldHi;
1704 classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
1705 Lo = merge(Lo, FieldLo);
1706 Hi = merge(Hi, FieldHi);
1707 if (Lo == Memory || Hi == Memory)
1711 postMerge(Size, Lo, Hi);
1712 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
1716 if (const RecordType *RT = Ty->getAs<RecordType>()) {
1717 uint64_t Size = getContext().getTypeSize(Ty);
1719 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
1720 // than four eightbytes, ..., it has class MEMORY.
1724 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
1725 // copy constructor or a non-trivial destructor, it is passed by invisible
1727 if (getRecordArgABI(RT, getCXXABI()))
1730 const RecordDecl *RD = RT->getDecl();
1732 // Assume variable sized types are passed in memory.
1733 if (RD->hasFlexibleArrayMember())
1736 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
1738 // Reset Lo class, this will be recomputed.
1741 // If this is a C++ record, classify the bases first.
1742 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
1743 for (const auto &I : CXXRD->bases()) {
1744 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
1745 "Unexpected base class!");
1746 const CXXRecordDecl *Base =
1747 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
1749 // Classify this field.
1751 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
1752 // single eightbyte, each is classified separately. Each eightbyte gets
1753 // initialized to class NO_CLASS.
1754 Class FieldLo, FieldHi;
1756 OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
1757 classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg);
1758 Lo = merge(Lo, FieldLo);
1759 Hi = merge(Hi, FieldHi);
1760 if (Lo == Memory || Hi == Memory)
1765 // Classify the fields one at a time, merging the results.
1767 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
1768 i != e; ++i, ++idx) {
1769 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
1770 bool BitField = i->isBitField();
1772 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
1773 // four eightbytes, or it contains unaligned fields, it has class MEMORY.
1775 // The only case a 256-bit wide vector could be used is when the struct
1776 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
1777 // to work for sizes wider than 128, early check and fallback to memory.
1779 if (Size > 128 && getContext().getTypeSize(i->getType()) != 256) {
1783 // Note, skip this test for bit-fields, see below.
1784 if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
1789 // Classify this field.
1791 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
1792 // exceeds a single eightbyte, each is classified
1793 // separately. Each eightbyte gets initialized to class
1795 Class FieldLo, FieldHi;
1797 // Bit-fields require special handling, they do not force the
1798 // structure to be passed in memory even if unaligned, and
1799 // therefore they can straddle an eightbyte.
1801 // Ignore padding bit-fields.
1802 if (i->isUnnamedBitfield())
1805 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
1806 uint64_t Size = i->getBitWidthValue(getContext());
1808 uint64_t EB_Lo = Offset / 64;
1809 uint64_t EB_Hi = (Offset + Size - 1) / 64;
1812 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
1817 FieldHi = EB_Hi ? Integer : NoClass;
1820 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
1821 Lo = merge(Lo, FieldLo);
1822 Hi = merge(Hi, FieldHi);
1823 if (Lo == Memory || Hi == Memory)
1827 postMerge(Size, Lo, Hi);
1831 ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
1832 // If this is a scalar LLVM value then assume LLVM will pass it in the right
1834 if (!isAggregateTypeForABI(Ty)) {
1835 // Treat an enum type as its underlying type.
1836 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1837 Ty = EnumTy->getDecl()->getIntegerType();
1839 return (Ty->isPromotableIntegerType() ?
1840 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
1843 return ABIArgInfo::getIndirect(0);
1846 bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
1847 if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
1848 uint64_t Size = getContext().getTypeSize(VecTy);
1849 unsigned LargestVector = HasAVX ? 256 : 128;
1850 if (Size <= 64 || Size > LargestVector)
1857 ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
1858 unsigned freeIntRegs) const {
1859 // If this is a scalar LLVM value then assume LLVM will pass it in the right
1862 // This assumption is optimistic, as there could be free registers available
1863 // when we need to pass this argument in memory, and LLVM could try to pass
1864 // the argument in the free register. This does not seem to happen currently,
1865 // but this code would be much safer if we could mark the argument with
1866 // 'onstack'. See PR12193.
1867 if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty)) {
1868 // Treat an enum type as its underlying type.
1869 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1870 Ty = EnumTy->getDecl()->getIntegerType();
1872 return (Ty->isPromotableIntegerType() ?
1873 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
1876 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
1877 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
1879 // Compute the byval alignment. We specify the alignment of the byval in all
1880 // cases so that the mid-level optimizer knows the alignment of the byval.
1881 unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
1883 // Attempt to avoid passing indirect results using byval when possible. This
1884 // is important for good codegen.
1886 // We do this by coercing the value into a scalar type which the backend can
1887 // handle naturally (i.e., without using byval).
1889 // For simplicity, we currently only do this when we have exhausted all of the
1890 // free integer registers. Doing this when there are free integer registers
1891 // would require more care, as we would have to ensure that the coerced value
1892 // did not claim the unused register. That would require either reording the
1893 // arguments to the function (so that any subsequent inreg values came first),
1894 // or only doing this optimization when there were no following arguments that
1897 // We currently expect it to be rare (particularly in well written code) for
1898 // arguments to be passed on the stack when there are still free integer
1899 // registers available (this would typically imply large structs being passed
1900 // by value), so this seems like a fair tradeoff for now.
1902 // We can revisit this if the backend grows support for 'onstack' parameter
1903 // attributes. See PR12193.
1904 if (freeIntRegs == 0) {
1905 uint64_t Size = getContext().getTypeSize(Ty);
1907 // If this type fits in an eightbyte, coerce it into the matching integral
1908 // type, which will end up on the stack (with alignment 8).
1909 if (Align == 8 && Size <= 64)
1910 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
1914 return ABIArgInfo::getIndirect(Align);
1917 /// GetByteVectorType - The ABI specifies that a value should be passed in an
1918 /// full vector XMM/YMM register. Pick an LLVM IR type that will be passed as a
1919 /// vector register.
1920 llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
1921 llvm::Type *IRType = CGT.ConvertType(Ty);
1923 // Wrapper structs that just contain vectors are passed just like vectors,
1924 // strip them off if present.
1925 llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType);
1926 while (STy && STy->getNumElements() == 1) {
1927 IRType = STy->getElementType(0);
1928 STy = dyn_cast<llvm::StructType>(IRType);
1931 // If the preferred type is a 16-byte vector, prefer to pass it.
1932 if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(IRType)){
1933 llvm::Type *EltTy = VT->getElementType();
1934 unsigned BitWidth = VT->getBitWidth();
1935 if ((BitWidth >= 128 && BitWidth <= 256) &&
1936 (EltTy->isFloatTy() || EltTy->isDoubleTy() ||
1937 EltTy->isIntegerTy(8) || EltTy->isIntegerTy(16) ||
1938 EltTy->isIntegerTy(32) || EltTy->isIntegerTy(64) ||
1939 EltTy->isIntegerTy(128)))
1943 return llvm::VectorType::get(llvm::Type::getDoubleTy(getVMContext()), 2);
1946 /// BitsContainNoUserData - Return true if the specified [start,end) bit range
1947 /// is known to either be off the end of the specified type or being in
1948 /// alignment padding. The user type specified is known to be at most 128 bits
1949 /// in size, and have passed through X86_64ABIInfo::classify with a successful
1950 /// classification that put one of the two halves in the INTEGER class.
1952 /// It is conservatively correct to return false.
1953 static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
1954 unsigned EndBit, ASTContext &Context) {
1955 // If the bytes being queried are off the end of the type, there is no user
1956 // data hiding here. This handles analysis of builtins, vectors and other
1957 // types that don't contain interesting padding.
1958 unsigned TySize = (unsigned)Context.getTypeSize(Ty);
1959 if (TySize <= StartBit)
1962 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
1963 unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
1964 unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
1966 // Check each element to see if the element overlaps with the queried range.
1967 for (unsigned i = 0; i != NumElts; ++i) {
1968 // If the element is after the span we care about, then we're done..
1969 unsigned EltOffset = i*EltSize;
1970 if (EltOffset >= EndBit) break;
1972 unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
1973 if (!BitsContainNoUserData(AT->getElementType(), EltStart,
1974 EndBit-EltOffset, Context))
1977 // If it overlaps no elements, then it is safe to process as padding.
1981 if (const RecordType *RT = Ty->getAs<RecordType>()) {
1982 const RecordDecl *RD = RT->getDecl();
1983 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1985 // If this is a C++ record, check the bases first.
1986 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
1987 for (const auto &I : CXXRD->bases()) {
1988 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
1989 "Unexpected base class!");
1990 const CXXRecordDecl *Base =
1991 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
1993 // If the base is after the span we care about, ignore it.
1994 unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
1995 if (BaseOffset >= EndBit) continue;
1997 unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
1998 if (!BitsContainNoUserData(I.getType(), BaseStart,
1999 EndBit-BaseOffset, Context))
2004 // Verify that no field has data that overlaps the region of interest. Yes
2005 // this could be sped up a lot by being smarter about queried fields,
2006 // however we're only looking at structs up to 16 bytes, so we don't care
2009 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
2010 i != e; ++i, ++idx) {
2011 unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
2013 // If we found a field after the region we care about, then we're done.
2014 if (FieldOffset >= EndBit) break;
2016 unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
2017 if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
2022 // If nothing in this record overlapped the area of interest, then we're
2030 /// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a
2031 /// float member at the specified offset. For example, {int,{float}} has a
2032 /// float at offset 4. It is conservatively correct for this routine to return
2034 static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset,
2035 const llvm::DataLayout &TD) {
2036 // Base case if we find a float.
2037 if (IROffset == 0 && IRType->isFloatTy())
2040 // If this is a struct, recurse into the field at the specified offset.
2041 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
2042 const llvm::StructLayout *SL = TD.getStructLayout(STy);
2043 unsigned Elt = SL->getElementContainingOffset(IROffset);
2044 IROffset -= SL->getElementOffset(Elt);
2045 return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD);
2048 // If this is an array, recurse into the field at the specified offset.
2049 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
2050 llvm::Type *EltTy = ATy->getElementType();
2051 unsigned EltSize = TD.getTypeAllocSize(EltTy);
2052 IROffset -= IROffset/EltSize*EltSize;
2053 return ContainsFloatAtOffset(EltTy, IROffset, TD);
2060 /// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
2061 /// low 8 bytes of an XMM register, corresponding to the SSE class.
2062 llvm::Type *X86_64ABIInfo::
2063 GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
2064 QualType SourceTy, unsigned SourceOffset) const {
2065 // The only three choices we have are either double, <2 x float>, or float. We
2066 // pass as float if the last 4 bytes is just padding. This happens for
2067 // structs that contain 3 floats.
2068 if (BitsContainNoUserData(SourceTy, SourceOffset*8+32,
2069 SourceOffset*8+64, getContext()))
2070 return llvm::Type::getFloatTy(getVMContext());
2072 // We want to pass as <2 x float> if the LLVM IR type contains a float at
2073 // offset+0 and offset+4. Walk the LLVM IR type to find out if this is the
2075 if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) &&
2076 ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout()))
2077 return llvm::VectorType::get(llvm::Type::getFloatTy(getVMContext()), 2);
2079 return llvm::Type::getDoubleTy(getVMContext());
2083 /// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
2084 /// an 8-byte GPR. This means that we either have a scalar or we are talking
2085 /// about the high or low part of an up-to-16-byte struct. This routine picks
2086 /// the best LLVM IR type to represent this, which may be i64 or may be anything
2087 /// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
2090 /// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
2091 /// the source type. IROffset is an offset in bytes into the LLVM IR type that
2092 /// the 8-byte value references. PrefType may be null.
2094 /// SourceTy is the source-level type for the entire argument. SourceOffset is
2095 /// an offset into this that we're processing (which is always either 0 or 8).
2097 llvm::Type *X86_64ABIInfo::
2098 GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
2099 QualType SourceTy, unsigned SourceOffset) const {
2100 // If we're dealing with an un-offset LLVM IR type, then it means that we're
2101 // returning an 8-byte unit starting with it. See if we can safely use it.
2102 if (IROffset == 0) {
2103 // Pointers and int64's always fill the 8-byte unit.
2104 if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
2105 IRType->isIntegerTy(64))
2108 // If we have a 1/2/4-byte integer, we can use it only if the rest of the
2109 // goodness in the source type is just tail padding. This is allowed to
2110 // kick in for struct {double,int} on the int, but not on
2111 // struct{double,int,int} because we wouldn't return the second int. We
2112 // have to do this analysis on the source type because we can't depend on
2113 // unions being lowered a specific way etc.
2114 if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
2115 IRType->isIntegerTy(32) ||
2116 (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
2117 unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
2118 cast<llvm::IntegerType>(IRType)->getBitWidth();
2120 if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
2121 SourceOffset*8+64, getContext()))
2126 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
2127 // If this is a struct, recurse into the field at the specified offset.
2128 const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
2129 if (IROffset < SL->getSizeInBytes()) {
2130 unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
2131 IROffset -= SL->getElementOffset(FieldIdx);
2133 return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
2134 SourceTy, SourceOffset);
2138 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
2139 llvm::Type *EltTy = ATy->getElementType();
2140 unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
2141 unsigned EltOffset = IROffset/EltSize*EltSize;
2142 return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
2146 // Okay, we don't have any better idea of what to pass, so we pass this in an
2147 // integer register that isn't too big to fit the rest of the struct.
2148 unsigned TySizeInBytes =
2149 (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
2151 assert(TySizeInBytes != SourceOffset && "Empty field?");
2153 // It is always safe to classify this as an integer type up to i64 that
2154 // isn't larger than the structure.
2155 return llvm::IntegerType::get(getVMContext(),
2156 std::min(TySizeInBytes-SourceOffset, 8U)*8);
2160 /// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
2161 /// be used as elements of a two register pair to pass or return, return a
2162 /// first class aggregate to represent them. For example, if the low part of
2163 /// a by-value argument should be passed as i32* and the high part as float,
2164 /// return {i32*, float}.
2166 GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
2167 const llvm::DataLayout &TD) {
2168 // In order to correctly satisfy the ABI, we need to the high part to start
2169 // at offset 8. If the high and low parts we inferred are both 4-byte types
2170 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
2171 // the second element at offset 8. Check for this:
2172 unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
2173 unsigned HiAlign = TD.getABITypeAlignment(Hi);
2174 unsigned HiStart = llvm::DataLayout::RoundUpAlignment(LoSize, HiAlign);
2175 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
2177 // To handle this, we have to increase the size of the low part so that the
2178 // second element will start at an 8 byte offset. We can't increase the size
2179 // of the second element because it might make us access off the end of the
2182 // There are only two sorts of types the ABI generation code can produce for
2183 // the low part of a pair that aren't 8 bytes in size: float or i8/i16/i32.
2184 // Promote these to a larger type.
2185 if (Lo->isFloatTy())
2186 Lo = llvm::Type::getDoubleTy(Lo->getContext());
2188 assert(Lo->isIntegerTy() && "Invalid/unknown lo type");
2189 Lo = llvm::Type::getInt64Ty(Lo->getContext());
2193 llvm::StructType *Result = llvm::StructType::get(Lo, Hi, NULL);
2196 // Verify that the second element is at an 8-byte offset.
2197 assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
2198 "Invalid x86-64 argument pair!");
2202 ABIArgInfo X86_64ABIInfo::
2203 classifyReturnType(QualType RetTy) const {
2204 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
2205 // classification algorithm.
2206 X86_64ABIInfo::Class Lo, Hi;
2207 classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
2209 // Check some invariants.
2210 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
2211 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
2213 llvm::Type *ResType = nullptr;
2217 return ABIArgInfo::getIgnore();
2218 // If the low part is just padding, it takes no register, leave ResType
2220 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
2221 "Unknown missing lo part");
2226 llvm_unreachable("Invalid classification for lo word.");
2228 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
2231 return getIndirectReturnResult(RetTy);
2233 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
2234 // available register of the sequence %rax, %rdx is used.
2236 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
2238 // If we have a sign or zero extended integer, make sure to return Extend
2239 // so that the parameter gets the right LLVM IR attributes.
2240 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
2241 // Treat an enum type as its underlying type.
2242 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
2243 RetTy = EnumTy->getDecl()->getIntegerType();
2245 if (RetTy->isIntegralOrEnumerationType() &&
2246 RetTy->isPromotableIntegerType())
2247 return ABIArgInfo::getExtend();
2251 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
2252 // available SSE register of the sequence %xmm0, %xmm1 is used.
2254 ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
2257 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
2258 // returned on the X87 stack in %st0 as 80-bit x87 number.
2260 ResType = llvm::Type::getX86_FP80Ty(getVMContext());
2263 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
2264 // part of the value is returned in %st0 and the imaginary part in
2267 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
2268 ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
2269 llvm::Type::getX86_FP80Ty(getVMContext()),
2274 llvm::Type *HighPart = nullptr;
2276 // Memory was handled previously and X87 should
2277 // never occur as a hi class.
2280 llvm_unreachable("Invalid classification for hi word.");
2282 case ComplexX87: // Previously handled.
2287 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
2288 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2289 return ABIArgInfo::getDirect(HighPart, 8);
2292 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
2293 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2294 return ABIArgInfo::getDirect(HighPart, 8);
2297 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
2298 // is passed in the next available eightbyte chunk if the last used
2301 // SSEUP should always be preceded by SSE, just widen.
2303 assert(Lo == SSE && "Unexpected SSEUp classification.");
2304 ResType = GetByteVectorType(RetTy);
2307 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
2308 // returned together with the previous X87 value in %st0.
2310 // If X87Up is preceded by X87, we don't need to do
2311 // anything. However, in some cases with unions it may not be
2312 // preceded by X87. In such situations we follow gcc and pass the
2313 // extra bits in an SSE reg.
2315 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
2316 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2317 return ABIArgInfo::getDirect(HighPart, 8);
2322 // If a high part was specified, merge it together with the low part. It is
2323 // known to pass in the high eightbyte of the result. We do this by forming a
2324 // first class struct aggregate with the high and low part: {low, high}
2326 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
2328 return ABIArgInfo::getDirect(ResType);
2331 ABIArgInfo X86_64ABIInfo::classifyArgumentType(
2332 QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE,
2336 X86_64ABIInfo::Class Lo, Hi;
2337 classify(Ty, 0, Lo, Hi, isNamedArg);
2339 // Check some invariants.
2340 // FIXME: Enforce these by construction.
2341 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
2342 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
2346 llvm::Type *ResType = nullptr;
2350 return ABIArgInfo::getIgnore();
2351 // If the low part is just padding, it takes no register, leave ResType
2353 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
2354 "Unknown missing lo part");
2357 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
2361 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
2362 // COMPLEX_X87, it is passed in memory.
2365 if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect)
2367 return getIndirectResult(Ty, freeIntRegs);
2371 llvm_unreachable("Invalid classification for lo word.");
2373 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
2374 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
2379 // Pick an 8-byte type based on the preferred type.
2380 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
2382 // If we have a sign or zero extended integer, make sure to return Extend
2383 // so that the parameter gets the right LLVM IR attributes.
2384 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
2385 // Treat an enum type as its underlying type.
2386 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2387 Ty = EnumTy->getDecl()->getIntegerType();
2389 if (Ty->isIntegralOrEnumerationType() &&
2390 Ty->isPromotableIntegerType())
2391 return ABIArgInfo::getExtend();
2396 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
2397 // available SSE register is used, the registers are taken in the
2398 // order from %xmm0 to %xmm7.
2400 llvm::Type *IRType = CGT.ConvertType(Ty);
2401 ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
2407 llvm::Type *HighPart = nullptr;
2409 // Memory was handled previously, ComplexX87 and X87 should
2410 // never occur as hi classes, and X87Up must be preceded by X87,
2411 // which is passed in memory.
2415 llvm_unreachable("Invalid classification for hi word.");
2417 case NoClass: break;
2421 // Pick an 8-byte type based on the preferred type.
2422 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
2424 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
2425 return ABIArgInfo::getDirect(HighPart, 8);
2428 // X87Up generally doesn't occur here (long double is passed in
2429 // memory), except in situations involving unions.
2432 HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
2434 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
2435 return ABIArgInfo::getDirect(HighPart, 8);
2440 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
2441 // eightbyte is passed in the upper half of the last used SSE
2442 // register. This only happens when 128-bit vectors are passed.
2444 assert(Lo == SSE && "Unexpected SSEUp classification");
2445 ResType = GetByteVectorType(Ty);
2449 // If a high part was specified, merge it together with the low part. It is
2450 // known to pass in the high eightbyte of the result. We do this by forming a
2451 // first class struct aggregate with the high and low part: {low, high}
2453 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
2455 return ABIArgInfo::getDirect(ResType);
2458 void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
2460 if (!getCXXABI().classifyReturnType(FI))
2461 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
2463 // Keep track of the number of assigned registers.
2464 unsigned freeIntRegs = 6, freeSSERegs = 8;
2466 // If the return value is indirect, then the hidden argument is consuming one
2467 // integer register.
2468 if (FI.getReturnInfo().isIndirect())
2471 bool isVariadic = FI.isVariadic();
2472 unsigned numRequiredArgs = 0;
2474 numRequiredArgs = FI.getRequiredArgs().getNumRequiredArgs();
2476 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
2477 // get assigned (in left-to-right order) for passing as follows...
2478 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
2480 bool isNamedArg = true;
2482 isNamedArg = (it - FI.arg_begin()) <
2483 static_cast<signed>(numRequiredArgs);
2485 unsigned neededInt, neededSSE;
2486 it->info = classifyArgumentType(it->type, freeIntRegs, neededInt,
2487 neededSSE, isNamedArg);
2489 // AMD64-ABI 3.2.3p3: If there are no registers available for any
2490 // eightbyte of an argument, the whole argument is passed on the
2491 // stack. If registers have already been assigned for some
2492 // eightbytes of such an argument, the assignments get reverted.
2493 if (freeIntRegs >= neededInt && freeSSERegs >= neededSSE) {
2494 freeIntRegs -= neededInt;
2495 freeSSERegs -= neededSSE;
2497 it->info = getIndirectResult(it->type, freeIntRegs);
2502 static llvm::Value *EmitVAArgFromMemory(llvm::Value *VAListAddr,
2504 CodeGenFunction &CGF) {
2505 llvm::Value *overflow_arg_area_p =
2506 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_p");
2507 llvm::Value *overflow_arg_area =
2508 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
2510 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
2511 // byte boundary if alignment needed by type exceeds 8 byte boundary.
2512 // It isn't stated explicitly in the standard, but in practice we use
2513 // alignment greater than 16 where necessary.
2514 uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8;
2516 // overflow_arg_area = (overflow_arg_area + align - 1) & -align;
2517 llvm::Value *Offset =
2518 llvm::ConstantInt::get(CGF.Int64Ty, Align - 1);
2519 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset);
2520 llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(overflow_arg_area,
2522 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int64Ty, -(uint64_t)Align);
2524 CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask),
2525 overflow_arg_area->getType(),
2526 "overflow_arg_area.align");
2529 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
2530 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
2532 CGF.Builder.CreateBitCast(overflow_arg_area,
2533 llvm::PointerType::getUnqual(LTy));
2535 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
2536 // l->overflow_arg_area + sizeof(type).
2537 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
2538 // an 8 byte boundary.
2540 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
2541 llvm::Value *Offset =
2542 llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7);
2543 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
2544 "overflow_arg_area.next");
2545 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
2547 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
2551 llvm::Value *X86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2552 CodeGenFunction &CGF) const {
2553 // Assume that va_list type is correct; should be pointer to LLVM type:
2557 // i8* overflow_arg_area;
2558 // i8* reg_save_area;
2560 unsigned neededInt, neededSSE;
2562 Ty = CGF.getContext().getCanonicalType(Ty);
2563 ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
2564 /*isNamedArg*/false);
2566 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
2567 // in the registers. If not go to step 7.
2568 if (!neededInt && !neededSSE)
2569 return EmitVAArgFromMemory(VAListAddr, Ty, CGF);
2571 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
2572 // general purpose registers needed to pass type and num_fp to hold
2573 // the number of floating point registers needed.
2575 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
2576 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
2577 // l->fp_offset > 304 - num_fp * 16 go to step 7.
2579 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
2580 // register save space).
2582 llvm::Value *InRegs = nullptr;
2583 llvm::Value *gp_offset_p = nullptr, *gp_offset = nullptr;
2584 llvm::Value *fp_offset_p = nullptr, *fp_offset = nullptr;
2586 gp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "gp_offset_p");
2587 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
2588 InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
2589 InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
2593 fp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 1, "fp_offset_p");
2594 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
2595 llvm::Value *FitsInFP =
2596 llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
2597 FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
2598 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
2601 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
2602 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
2603 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
2604 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
2606 // Emit code to load the value if it was passed in registers.
2608 CGF.EmitBlock(InRegBlock);
2610 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
2611 // an offset of l->gp_offset and/or l->fp_offset. This may require
2612 // copying to a temporary location in case the parameter is passed
2613 // in different register classes or requires an alignment greater
2614 // than 8 for general purpose registers and 16 for XMM registers.
2616 // FIXME: This really results in shameful code when we end up needing to
2617 // collect arguments from different places; often what should result in a
2618 // simple assembling of a structure from scattered addresses has many more
2619 // loads than necessary. Can we clean this up?
2620 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
2621 llvm::Value *RegAddr =
2622 CGF.Builder.CreateLoad(CGF.Builder.CreateStructGEP(VAListAddr, 3),
2624 if (neededInt && neededSSE) {
2626 assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
2627 llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
2628 llvm::Value *Tmp = CGF.CreateMemTemp(Ty);
2629 Tmp = CGF.Builder.CreateBitCast(Tmp, ST->getPointerTo());
2630 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
2631 llvm::Type *TyLo = ST->getElementType(0);
2632 llvm::Type *TyHi = ST->getElementType(1);
2633 assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
2634 "Unexpected ABI info for mixed regs");
2635 llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
2636 llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
2637 llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
2638 llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
2639 llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr;
2640 llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr;
2642 CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegLoAddr, PTyLo));
2643 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
2644 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegHiAddr, PTyHi));
2645 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
2647 RegAddr = CGF.Builder.CreateBitCast(Tmp,
2648 llvm::PointerType::getUnqual(LTy));
2649 } else if (neededInt) {
2650 RegAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
2651 RegAddr = CGF.Builder.CreateBitCast(RegAddr,
2652 llvm::PointerType::getUnqual(LTy));
2654 // Copy to a temporary if necessary to ensure the appropriate alignment.
2655 std::pair<CharUnits, CharUnits> SizeAlign =
2656 CGF.getContext().getTypeInfoInChars(Ty);
2657 uint64_t TySize = SizeAlign.first.getQuantity();
2658 unsigned TyAlign = SizeAlign.second.getQuantity();
2660 llvm::Value *Tmp = CGF.CreateMemTemp(Ty);
2661 CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, 8, false);
2664 } else if (neededSSE == 1) {
2665 RegAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
2666 RegAddr = CGF.Builder.CreateBitCast(RegAddr,
2667 llvm::PointerType::getUnqual(LTy));
2669 assert(neededSSE == 2 && "Invalid number of needed registers!");
2670 // SSE registers are spaced 16 bytes apart in the register save
2671 // area, we need to collect the two eightbytes together.
2672 llvm::Value *RegAddrLo = CGF.Builder.CreateGEP(RegAddr, fp_offset);
2673 llvm::Value *RegAddrHi = CGF.Builder.CreateConstGEP1_32(RegAddrLo, 16);
2674 llvm::Type *DoubleTy = CGF.DoubleTy;
2675 llvm::Type *DblPtrTy =
2676 llvm::PointerType::getUnqual(DoubleTy);
2677 llvm::StructType *ST = llvm::StructType::get(DoubleTy, DoubleTy, NULL);
2678 llvm::Value *V, *Tmp = CGF.CreateMemTemp(Ty);
2679 Tmp = CGF.Builder.CreateBitCast(Tmp, ST->getPointerTo());
2680 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrLo,
2682 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
2683 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrHi,
2685 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
2686 RegAddr = CGF.Builder.CreateBitCast(Tmp,
2687 llvm::PointerType::getUnqual(LTy));
2690 // AMD64-ABI 3.5.7p5: Step 5. Set:
2691 // l->gp_offset = l->gp_offset + num_gp * 8
2692 // l->fp_offset = l->fp_offset + num_fp * 16.
2694 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
2695 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
2699 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
2700 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
2703 CGF.EmitBranch(ContBlock);
2705 // Emit code to load the value if it was passed in memory.
2707 CGF.EmitBlock(InMemBlock);
2708 llvm::Value *MemAddr = EmitVAArgFromMemory(VAListAddr, Ty, CGF);
2710 // Return the appropriate result.
2712 CGF.EmitBlock(ContBlock);
2713 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(RegAddr->getType(), 2,
2715 ResAddr->addIncoming(RegAddr, InRegBlock);
2716 ResAddr->addIncoming(MemAddr, InMemBlock);
2720 ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, bool IsReturnType) const {
2722 if (Ty->isVoidType())
2723 return ABIArgInfo::getIgnore();
2725 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2726 Ty = EnumTy->getDecl()->getIntegerType();
2728 uint64_t Size = getContext().getTypeSize(Ty);
2730 const RecordType *RT = Ty->getAs<RecordType>();
2732 if (!IsReturnType) {
2733 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
2734 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
2737 if (RT->getDecl()->hasFlexibleArrayMember())
2738 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
2740 // FIXME: mingw-w64-gcc emits 128-bit struct as i128
2741 if (Size == 128 && getTarget().getTriple().isWindowsGNUEnvironment())
2742 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2746 if (Ty->isMemberPointerType()) {
2747 // If the member pointer is represented by an LLVM int or ptr, pass it
2749 llvm::Type *LLTy = CGT.ConvertType(Ty);
2750 if (LLTy->isPointerTy() || LLTy->isIntegerTy())
2751 return ABIArgInfo::getDirect();
2754 if (RT || Ty->isMemberPointerType()) {
2755 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
2756 // not 1, 2, 4, or 8 bytes, must be passed by reference."
2757 if (Size > 64 || !llvm::isPowerOf2_64(Size))
2758 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
2760 // Otherwise, coerce it to a small integer.
2761 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
2764 if (Ty->isPromotableIntegerType())
2765 return ABIArgInfo::getExtend();
2767 return ABIArgInfo::getDirect();
2770 void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
2771 if (!getCXXABI().classifyReturnType(FI))
2772 FI.getReturnInfo() = classify(FI.getReturnType(), true);
2774 for (auto &I : FI.arguments())
2775 I.info = classify(I.type, false);
2778 llvm::Value *WinX86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2779 CodeGenFunction &CGF) const {
2780 llvm::Type *BPP = CGF.Int8PtrPtrTy;
2782 CGBuilderTy &Builder = CGF.Builder;
2783 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
2785 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
2787 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
2788 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
2791 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 8);
2792 llvm::Value *NextAddr =
2793 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
2795 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
2802 class NaClX86_64ABIInfo : public ABIInfo {
2804 NaClX86_64ABIInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX)
2805 : ABIInfo(CGT), PInfo(CGT), NInfo(CGT, HasAVX) {}
2806 void computeInfo(CGFunctionInfo &FI) const override;
2807 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2808 CodeGenFunction &CGF) const override;
2810 PNaClABIInfo PInfo; // Used for generating calls with pnaclcall callingconv.
2811 X86_64ABIInfo NInfo; // Used for everything else.
2814 class NaClX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2816 NaClX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX)
2817 : TargetCodeGenInfo(new NaClX86_64ABIInfo(CGT, HasAVX)) {}
2822 void NaClX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
2823 if (FI.getASTCallingConvention() == CC_PnaclCall)
2824 PInfo.computeInfo(FI);
2826 NInfo.computeInfo(FI);
2829 llvm::Value *NaClX86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2830 CodeGenFunction &CGF) const {
2831 // Always use the native convention; calling pnacl-style varargs functions
2833 return NInfo.EmitVAArg(VAListAddr, Ty, CGF);
2839 /// PPC32_SVR4_ABIInfo - The 32-bit PowerPC ELF (SVR4) ABI information.
2840 class PPC32_SVR4_ABIInfo : public DefaultABIInfo {
2842 PPC32_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
2844 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2845 CodeGenFunction &CGF) const override;
2848 class PPC32TargetCodeGenInfo : public TargetCodeGenInfo {
2850 PPC32TargetCodeGenInfo(CodeGenTypes &CGT) : TargetCodeGenInfo(new PPC32_SVR4_ABIInfo(CGT)) {}
2852 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
2853 // This is recovered from gcc output.
2854 return 1; // r1 is the dedicated stack pointer
2857 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2858 llvm::Value *Address) const override;
2863 llvm::Value *PPC32_SVR4_ABIInfo::EmitVAArg(llvm::Value *VAListAddr,
2865 CodeGenFunction &CGF) const {
2866 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
2867 // TODO: Implement this. For now ignore.
2872 bool isI64 = Ty->isIntegerType() && getContext().getTypeSize(Ty) == 64;
2873 bool isInt = Ty->isIntegerType() || Ty->isPointerType() || Ty->isAggregateType();
2874 llvm::Type *CharPtr = CGF.Int8PtrTy;
2875 llvm::Type *CharPtrPtr = CGF.Int8PtrPtrTy;
2877 CGBuilderTy &Builder = CGF.Builder;
2878 llvm::Value *GPRPtr = Builder.CreateBitCast(VAListAddr, CharPtr, "gprptr");
2879 llvm::Value *GPRPtrAsInt = Builder.CreatePtrToInt(GPRPtr, CGF.Int32Ty);
2880 llvm::Value *FPRPtrAsInt = Builder.CreateAdd(GPRPtrAsInt, Builder.getInt32(1));
2881 llvm::Value *FPRPtr = Builder.CreateIntToPtr(FPRPtrAsInt, CharPtr);
2882 llvm::Value *OverflowAreaPtrAsInt = Builder.CreateAdd(FPRPtrAsInt, Builder.getInt32(3));
2883 llvm::Value *OverflowAreaPtr = Builder.CreateIntToPtr(OverflowAreaPtrAsInt, CharPtrPtr);
2884 llvm::Value *RegsaveAreaPtrAsInt = Builder.CreateAdd(OverflowAreaPtrAsInt, Builder.getInt32(4));
2885 llvm::Value *RegsaveAreaPtr = Builder.CreateIntToPtr(RegsaveAreaPtrAsInt, CharPtrPtr);
2886 llvm::Value *GPR = Builder.CreateLoad(GPRPtr, false, "gpr");
2887 // Align GPR when TY is i64.
2889 llvm::Value *GPRAnd = Builder.CreateAnd(GPR, Builder.getInt8(1));
2890 llvm::Value *CC64 = Builder.CreateICmpEQ(GPRAnd, Builder.getInt8(1));
2891 llvm::Value *GPRPlusOne = Builder.CreateAdd(GPR, Builder.getInt8(1));
2892 GPR = Builder.CreateSelect(CC64, GPRPlusOne, GPR);
2894 llvm::Value *FPR = Builder.CreateLoad(FPRPtr, false, "fpr");
2895 llvm::Value *OverflowArea = Builder.CreateLoad(OverflowAreaPtr, false, "overflow_area");
2896 llvm::Value *OverflowAreaAsInt = Builder.CreatePtrToInt(OverflowArea, CGF.Int32Ty);
2897 llvm::Value *RegsaveArea = Builder.CreateLoad(RegsaveAreaPtr, false, "regsave_area");
2898 llvm::Value *RegsaveAreaAsInt = Builder.CreatePtrToInt(RegsaveArea, CGF.Int32Ty);
2900 llvm::Value *CC = Builder.CreateICmpULT(isInt ? GPR : FPR,
2901 Builder.getInt8(8), "cond");
2903 llvm::Value *RegConstant = Builder.CreateMul(isInt ? GPR : FPR,
2904 Builder.getInt8(isInt ? 4 : 8));
2906 llvm::Value *OurReg = Builder.CreateAdd(RegsaveAreaAsInt, Builder.CreateSExt(RegConstant, CGF.Int32Ty));
2908 if (Ty->isFloatingType())
2909 OurReg = Builder.CreateAdd(OurReg, Builder.getInt32(32));
2911 llvm::BasicBlock *UsingRegs = CGF.createBasicBlock("using_regs");
2912 llvm::BasicBlock *UsingOverflow = CGF.createBasicBlock("using_overflow");
2913 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
2915 Builder.CreateCondBr(CC, UsingRegs, UsingOverflow);
2917 CGF.EmitBlock(UsingRegs);
2919 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
2920 llvm::Value *Result1 = Builder.CreateIntToPtr(OurReg, PTy);
2921 // Increase the GPR/FPR indexes.
2923 GPR = Builder.CreateAdd(GPR, Builder.getInt8(isI64 ? 2 : 1));
2924 Builder.CreateStore(GPR, GPRPtr);
2926 FPR = Builder.CreateAdd(FPR, Builder.getInt8(1));
2927 Builder.CreateStore(FPR, FPRPtr);
2929 CGF.EmitBranch(Cont);
2931 CGF.EmitBlock(UsingOverflow);
2933 // Increase the overflow area.
2934 llvm::Value *Result2 = Builder.CreateIntToPtr(OverflowAreaAsInt, PTy);
2935 OverflowAreaAsInt = Builder.CreateAdd(OverflowAreaAsInt, Builder.getInt32(isInt ? 4 : 8));
2936 Builder.CreateStore(Builder.CreateIntToPtr(OverflowAreaAsInt, CharPtr), OverflowAreaPtr);
2937 CGF.EmitBranch(Cont);
2939 CGF.EmitBlock(Cont);
2941 llvm::PHINode *Result = CGF.Builder.CreatePHI(PTy, 2, "vaarg.addr");
2942 Result->addIncoming(Result1, UsingRegs);
2943 Result->addIncoming(Result2, UsingOverflow);
2945 if (Ty->isAggregateType()) {
2946 llvm::Value *AGGPtr = Builder.CreateBitCast(Result, CharPtrPtr, "aggrptr") ;
2947 return Builder.CreateLoad(AGGPtr, false, "aggr");
2954 PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2955 llvm::Value *Address) const {
2956 // This is calculated from the LLVM and GCC tables and verified
2957 // against gcc output. AFAIK all ABIs use the same encoding.
2959 CodeGen::CGBuilderTy &Builder = CGF.Builder;
2961 llvm::IntegerType *i8 = CGF.Int8Ty;
2962 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
2963 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
2964 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
2966 // 0-31: r0-31, the 4-byte general-purpose registers
2967 AssignToArrayRange(Builder, Address, Four8, 0, 31);
2969 // 32-63: fp0-31, the 8-byte floating-point registers
2970 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
2972 // 64-76 are various 4-byte special-purpose registers:
2979 AssignToArrayRange(Builder, Address, Four8, 64, 76);
2981 // 77-108: v0-31, the 16-byte vector registers
2982 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
2989 AssignToArrayRange(Builder, Address, Four8, 109, 113);
2997 /// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
2998 class PPC64_SVR4_ABIInfo : public DefaultABIInfo {
3006 static const unsigned GPRBits = 64;
3010 PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind)
3011 : DefaultABIInfo(CGT), Kind(Kind) {}
3013 bool isPromotableTypeForABI(QualType Ty) const;
3014 bool isAlignedParamType(QualType Ty) const;
3015 bool isHomogeneousAggregate(QualType Ty, const Type *&Base,
3016 uint64_t &Members) const;
3018 ABIArgInfo classifyReturnType(QualType RetTy) const;
3019 ABIArgInfo classifyArgumentType(QualType Ty) const;
3021 // TODO: We can add more logic to computeInfo to improve performance.
3022 // Example: For aggregate arguments that fit in a register, we could
3023 // use getDirectInReg (as is done below for structs containing a single
3024 // floating-point value) to avoid pushing them to memory on function
3025 // entry. This would require changing the logic in PPCISelLowering
3026 // when lowering the parameters in the caller and args in the callee.
3027 void computeInfo(CGFunctionInfo &FI) const override {
3028 if (!getCXXABI().classifyReturnType(FI))
3029 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
3030 for (auto &I : FI.arguments()) {
3031 // We rely on the default argument classification for the most part.
3032 // One exception: An aggregate containing a single floating-point
3033 // or vector item must be passed in a register if one is available.
3034 const Type *T = isSingleElementStruct(I.type, getContext());
3036 const BuiltinType *BT = T->getAs<BuiltinType>();
3037 if ((T->isVectorType() && getContext().getTypeSize(T) == 128) ||
3038 (BT && BT->isFloatingPoint())) {
3040 I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
3044 I.info = classifyArgumentType(I.type);
3048 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3049 CodeGenFunction &CGF) const override;
3052 class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
3054 PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT,
3055 PPC64_SVR4_ABIInfo::ABIKind Kind)
3056 : TargetCodeGenInfo(new PPC64_SVR4_ABIInfo(CGT, Kind)) {}
3058 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
3059 // This is recovered from gcc output.
3060 return 1; // r1 is the dedicated stack pointer
3063 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3064 llvm::Value *Address) const override;
3067 class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
3069 PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
3071 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
3072 // This is recovered from gcc output.
3073 return 1; // r1 is the dedicated stack pointer
3076 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3077 llvm::Value *Address) const override;
3082 // Return true if the ABI requires Ty to be passed sign- or zero-
3083 // extended to 64 bits.
3085 PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
3086 // Treat an enum type as its underlying type.
3087 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3088 Ty = EnumTy->getDecl()->getIntegerType();
3090 // Promotable integer types are required to be promoted by the ABI.
3091 if (Ty->isPromotableIntegerType())
3094 // In addition to the usual promotable integer types, we also need to
3095 // extend all 32-bit types, since the ABI requires promotion to 64 bits.
3096 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
3097 switch (BT->getKind()) {
3098 case BuiltinType::Int:
3099 case BuiltinType::UInt:
3108 /// isAlignedParamType - Determine whether a type requires 16-byte
3109 /// alignment in the parameter area.
3111 PPC64_SVR4_ABIInfo::isAlignedParamType(QualType Ty) const {
3112 // Complex types are passed just like their elements.
3113 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
3114 Ty = CTy->getElementType();
3116 // Only vector types of size 16 bytes need alignment (larger types are
3117 // passed via reference, smaller types are not aligned).
3118 if (Ty->isVectorType())
3119 return getContext().getTypeSize(Ty) == 128;
3121 // For single-element float/vector structs, we consider the whole type
3122 // to have the same alignment requirements as its single element.
3123 const Type *AlignAsType = nullptr;
3124 const Type *EltType = isSingleElementStruct(Ty, getContext());
3126 const BuiltinType *BT = EltType->getAs<BuiltinType>();
3127 if ((EltType->isVectorType() &&
3128 getContext().getTypeSize(EltType) == 128) ||
3129 (BT && BT->isFloatingPoint()))
3130 AlignAsType = EltType;
3133 // Likewise for ELFv2 homogeneous aggregates.
3134 const Type *Base = nullptr;
3135 uint64_t Members = 0;
3136 if (!AlignAsType && Kind == ELFv2 &&
3137 isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members))
3140 // With special case aggregates, only vector base types need alignment.
3142 return AlignAsType->isVectorType();
3144 // Otherwise, we only need alignment for any aggregate type that
3145 // has an alignment requirement of >= 16 bytes.
3146 if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128)
3152 /// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous
3153 /// aggregate. Base is set to the base element type, and Members is set
3154 /// to the number of base elements.
3156 PPC64_SVR4_ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base,
3157 uint64_t &Members) const {
3158 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
3159 uint64_t NElements = AT->getSize().getZExtValue();
3162 if (!isHomogeneousAggregate(AT->getElementType(), Base, Members))
3164 Members *= NElements;
3165 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
3166 const RecordDecl *RD = RT->getDecl();
3167 if (RD->hasFlexibleArrayMember())
3171 for (const auto *FD : RD->fields()) {
3172 // Ignore (non-zero arrays of) empty records.
3173 QualType FT = FD->getType();
3174 while (const ConstantArrayType *AT =
3175 getContext().getAsConstantArrayType(FT)) {
3176 if (AT->getSize().getZExtValue() == 0)
3178 FT = AT->getElementType();
3180 if (isEmptyRecord(getContext(), FT, true))
3183 // For compatibility with GCC, ignore empty bitfields in C++ mode.
3184 if (getContext().getLangOpts().CPlusPlus &&
3185 FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
3188 uint64_t FldMembers;
3189 if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers))
3192 Members = (RD->isUnion() ?
3193 std::max(Members, FldMembers) : Members + FldMembers);
3199 // Ensure there is no padding.
3200 if (getContext().getTypeSize(Base) * Members !=
3201 getContext().getTypeSize(Ty))
3205 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
3207 Ty = CT->getElementType();
3210 // Homogeneous aggregates for ELFv2 must have base types of float,
3211 // double, long double, or 128-bit vectors.
3212 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
3213 if (BT->getKind() != BuiltinType::Float &&
3214 BT->getKind() != BuiltinType::Double &&
3215 BT->getKind() != BuiltinType::LongDouble)
3217 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
3218 if (getContext().getTypeSize(VT) != 128)
3224 // The base type must be the same for all members. Types that
3225 // agree in both total size and mode (float vs. vector) are
3226 // treated as being equivalent here.
3227 const Type *TyPtr = Ty.getTypePtr();
3231 if (Base->isVectorType() != TyPtr->isVectorType() ||
3232 getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr))
3236 // Vector types require one register, floating point types require one
3237 // or two registers depending on their size.
3238 uint32_t NumRegs = Base->isVectorType() ? 1 :
3239 (getContext().getTypeSize(Base) + 63) / 64;
3241 // Homogeneous Aggregates may occupy at most 8 registers.
3242 return (Members > 0 && Members * NumRegs <= 8);
3246 PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
3247 if (Ty->isAnyComplexType())
3248 return ABIArgInfo::getDirect();
3250 // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes)
3251 // or via reference (larger than 16 bytes).
3252 if (Ty->isVectorType()) {
3253 uint64_t Size = getContext().getTypeSize(Ty);
3255 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3256 else if (Size < 128) {
3257 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
3258 return ABIArgInfo::getDirect(CoerceTy);
3262 if (isAggregateTypeForABI(Ty)) {
3263 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
3264 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
3266 uint64_t ABIAlign = isAlignedParamType(Ty)? 16 : 8;
3267 uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8;
3269 // ELFv2 homogeneous aggregates are passed as array types.
3270 const Type *Base = nullptr;
3271 uint64_t Members = 0;
3272 if (Kind == ELFv2 &&
3273 isHomogeneousAggregate(Ty, Base, Members)) {
3274 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
3275 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
3276 return ABIArgInfo::getDirect(CoerceTy);
3279 // If an aggregate may end up fully in registers, we do not
3280 // use the ByVal method, but pass the aggregate as array.
3281 // This is usually beneficial since we avoid forcing the
3282 // back-end to store the argument to memory.
3283 uint64_t Bits = getContext().getTypeSize(Ty);
3284 if (Bits > 0 && Bits <= 8 * GPRBits) {
3285 llvm::Type *CoerceTy;
3287 // Types up to 8 bytes are passed as integer type (which will be
3288 // properly aligned in the argument save area doubleword).
3289 if (Bits <= GPRBits)
3290 CoerceTy = llvm::IntegerType::get(getVMContext(),
3291 llvm::RoundUpToAlignment(Bits, 8));
3292 // Larger types are passed as arrays, with the base type selected
3293 // according to the required alignment in the save area.
3295 uint64_t RegBits = ABIAlign * 8;
3296 uint64_t NumRegs = llvm::RoundUpToAlignment(Bits, RegBits) / RegBits;
3297 llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits);
3298 CoerceTy = llvm::ArrayType::get(RegTy, NumRegs);
3301 return ABIArgInfo::getDirect(CoerceTy);
3304 // All other aggregates are passed ByVal.
3305 return ABIArgInfo::getIndirect(ABIAlign, /*ByVal=*/true,
3306 /*Realign=*/TyAlign > ABIAlign);
3309 return (isPromotableTypeForABI(Ty) ?
3310 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
3314 PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
3315 if (RetTy->isVoidType())
3316 return ABIArgInfo::getIgnore();
3318 if (RetTy->isAnyComplexType())
3319 return ABIArgInfo::getDirect();
3321 // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes)
3322 // or via reference (larger than 16 bytes).
3323 if (RetTy->isVectorType()) {
3324 uint64_t Size = getContext().getTypeSize(RetTy);
3326 return ABIArgInfo::getIndirect(0);
3327 else if (Size < 128) {
3328 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
3329 return ABIArgInfo::getDirect(CoerceTy);
3333 if (isAggregateTypeForABI(RetTy)) {
3334 // ELFv2 homogeneous aggregates are returned as array types.
3335 const Type *Base = nullptr;
3336 uint64_t Members = 0;
3337 if (Kind == ELFv2 &&
3338 isHomogeneousAggregate(RetTy, Base, Members)) {
3339 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
3340 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
3341 return ABIArgInfo::getDirect(CoerceTy);
3344 // ELFv2 small aggregates are returned in up to two registers.
3345 uint64_t Bits = getContext().getTypeSize(RetTy);
3346 if (Kind == ELFv2 && Bits <= 2 * GPRBits) {
3348 return ABIArgInfo::getIgnore();
3350 llvm::Type *CoerceTy;
3351 if (Bits > GPRBits) {
3352 CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits);
3353 CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy, NULL);
3355 CoerceTy = llvm::IntegerType::get(getVMContext(),
3356 llvm::RoundUpToAlignment(Bits, 8));
3357 return ABIArgInfo::getDirect(CoerceTy);
3360 // All other aggregates are returned indirectly.
3361 return ABIArgInfo::getIndirect(0);
3364 return (isPromotableTypeForABI(RetTy) ?
3365 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
3368 // Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
3369 llvm::Value *PPC64_SVR4_ABIInfo::EmitVAArg(llvm::Value *VAListAddr,
3371 CodeGenFunction &CGF) const {
3372 llvm::Type *BP = CGF.Int8PtrTy;
3373 llvm::Type *BPP = CGF.Int8PtrPtrTy;
3375 CGBuilderTy &Builder = CGF.Builder;
3376 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
3377 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
3379 // Handle types that require 16-byte alignment in the parameter save area.
3380 if (isAlignedParamType(Ty)) {
3381 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
3382 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt64(15));
3383 AddrAsInt = Builder.CreateAnd(AddrAsInt, Builder.getInt64(-16));
3384 Addr = Builder.CreateIntToPtr(AddrAsInt, BP, "ap.align");
3387 // Update the va_list pointer. The pointer should be bumped by the
3388 // size of the object. We can trust getTypeSize() except for a complex
3389 // type whose base type is smaller than a doubleword. For these, the
3390 // size of the object is 16 bytes; see below for further explanation.
3391 unsigned SizeInBytes = CGF.getContext().getTypeSize(Ty) / 8;
3393 unsigned CplxBaseSize = 0;
3395 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
3396 BaseTy = CTy->getElementType();
3397 CplxBaseSize = CGF.getContext().getTypeSize(BaseTy) / 8;
3398 if (CplxBaseSize < 8)
3402 unsigned Offset = llvm::RoundUpToAlignment(SizeInBytes, 8);
3403 llvm::Value *NextAddr =
3404 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int64Ty, Offset),
3406 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
3408 // If we have a complex type and the base type is smaller than 8 bytes,
3409 // the ABI calls for the real and imaginary parts to be right-adjusted
3410 // in separate doublewords. However, Clang expects us to produce a
3411 // pointer to a structure with the two parts packed tightly. So generate
3412 // loads of the real and imaginary parts relative to the va_list pointer,
3413 // and store them to a temporary structure.
3414 if (CplxBaseSize && CplxBaseSize < 8) {
3415 llvm::Value *RealAddr = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
3416 llvm::Value *ImagAddr = RealAddr;
3417 if (CGF.CGM.getDataLayout().isBigEndian()) {
3418 RealAddr = Builder.CreateAdd(RealAddr, Builder.getInt64(8 - CplxBaseSize));
3419 ImagAddr = Builder.CreateAdd(ImagAddr, Builder.getInt64(16 - CplxBaseSize));
3421 ImagAddr = Builder.CreateAdd(ImagAddr, Builder.getInt64(8));
3423 llvm::Type *PBaseTy = llvm::PointerType::getUnqual(CGF.ConvertType(BaseTy));
3424 RealAddr = Builder.CreateIntToPtr(RealAddr, PBaseTy);
3425 ImagAddr = Builder.CreateIntToPtr(ImagAddr, PBaseTy);
3426 llvm::Value *Real = Builder.CreateLoad(RealAddr, false, ".vareal");
3427 llvm::Value *Imag = Builder.CreateLoad(ImagAddr, false, ".vaimag");
3428 llvm::Value *Ptr = CGF.CreateTempAlloca(CGT.ConvertTypeForMem(Ty),
3430 llvm::Value *RealPtr = Builder.CreateStructGEP(Ptr, 0, ".real");
3431 llvm::Value *ImagPtr = Builder.CreateStructGEP(Ptr, 1, ".imag");
3432 Builder.CreateStore(Real, RealPtr, false);
3433 Builder.CreateStore(Imag, ImagPtr, false);
3437 // If the argument is smaller than 8 bytes, it is right-adjusted in
3438 // its doubleword slot. Adjust the pointer to pick it up from the
3440 if (SizeInBytes < 8 && CGF.CGM.getDataLayout().isBigEndian()) {
3441 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
3442 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt64(8 - SizeInBytes));
3443 Addr = Builder.CreateIntToPtr(AddrAsInt, BP);
3446 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
3447 return Builder.CreateBitCast(Addr, PTy);
3451 PPC64_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3452 llvm::Value *Address) {
3453 // This is calculated from the LLVM and GCC tables and verified
3454 // against gcc output. AFAIK all ABIs use the same encoding.
3456 CodeGen::CGBuilderTy &Builder = CGF.Builder;
3458 llvm::IntegerType *i8 = CGF.Int8Ty;
3459 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
3460 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
3461 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
3463 // 0-31: r0-31, the 8-byte general-purpose registers
3464 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
3466 // 32-63: fp0-31, the 8-byte floating-point registers
3467 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
3469 // 64-76 are various 4-byte special-purpose registers:
3476 AssignToArrayRange(Builder, Address, Four8, 64, 76);
3478 // 77-108: v0-31, the 16-byte vector registers
3479 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
3486 AssignToArrayRange(Builder, Address, Four8, 109, 113);
3492 PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
3493 CodeGen::CodeGenFunction &CGF,
3494 llvm::Value *Address) const {
3496 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
3500 PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3501 llvm::Value *Address) const {
3503 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
3506 //===----------------------------------------------------------------------===//
3507 // AArch64 ABI Implementation
3508 //===----------------------------------------------------------------------===//
3512 class AArch64ABIInfo : public ABIInfo {
3523 AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind) : ABIInfo(CGT), Kind(Kind) {}
3526 ABIKind getABIKind() const { return Kind; }
3527 bool isDarwinPCS() const { return Kind == DarwinPCS; }
3529 ABIArgInfo classifyReturnType(QualType RetTy) const;
3530 ABIArgInfo classifyArgumentType(QualType RetTy, unsigned &AllocatedVFP,
3531 bool &IsHA, unsigned &AllocatedGPR,
3532 bool &IsSmallAggr, bool IsNamedArg) const;
3533 bool isIllegalVectorType(QualType Ty) const;
3535 virtual void computeInfo(CGFunctionInfo &FI) const {
3536 // To correctly handle Homogeneous Aggregate, we need to keep track of the
3537 // number of SIMD and Floating-point registers allocated so far.
3538 // If the argument is an HFA or an HVA and there are sufficient unallocated
3539 // SIMD and Floating-point registers, then the argument is allocated to SIMD
3540 // and Floating-point Registers (with one register per member of the HFA or
3541 // HVA). Otherwise, the NSRN is set to 8.
3542 unsigned AllocatedVFP = 0;
3544 // To correctly handle small aggregates, we need to keep track of the number
3545 // of GPRs allocated so far. If the small aggregate can't all fit into
3546 // registers, it will be on stack. We don't allow the aggregate to be
3547 // partially in registers.
3548 unsigned AllocatedGPR = 0;
3550 // Find the number of named arguments. Variadic arguments get special
3551 // treatment with the Darwin ABI.
3552 unsigned NumRequiredArgs = (FI.isVariadic() ?
3553 FI.getRequiredArgs().getNumRequiredArgs() :
3556 if (!getCXXABI().classifyReturnType(FI))
3557 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
3558 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
3560 unsigned PreAllocation = AllocatedVFP, PreGPR = AllocatedGPR;
3561 bool IsHA = false, IsSmallAggr = false;
3562 const unsigned NumVFPs = 8;
3563 const unsigned NumGPRs = 8;
3564 bool IsNamedArg = ((it - FI.arg_begin()) <
3565 static_cast<signed>(NumRequiredArgs));
3566 it->info = classifyArgumentType(it->type, AllocatedVFP, IsHA,
3567 AllocatedGPR, IsSmallAggr, IsNamedArg);
3569 // Under AAPCS the 64-bit stack slot alignment means we can't pass HAs
3570 // as sequences of floats since they'll get "holes" inserted as
3571 // padding by the back end.
3572 if (IsHA && AllocatedVFP > NumVFPs && !isDarwinPCS() &&
3573 getContext().getTypeAlign(it->type) < 64) {
3574 uint32_t NumStackSlots = getContext().getTypeSize(it->type);
3575 NumStackSlots = llvm::RoundUpToAlignment(NumStackSlots, 64) / 64;
3577 llvm::Type *CoerceTy = llvm::ArrayType::get(
3578 llvm::Type::getDoubleTy(getVMContext()), NumStackSlots);
3579 it->info = ABIArgInfo::getDirect(CoerceTy);
3582 // If we do not have enough VFP registers for the HA, any VFP registers
3583 // that are unallocated are marked as unavailable. To achieve this, we add
3584 // padding of (NumVFPs - PreAllocation) floats.
3585 if (IsHA && AllocatedVFP > NumVFPs && PreAllocation < NumVFPs) {
3586 llvm::Type *PaddingTy = llvm::ArrayType::get(
3587 llvm::Type::getFloatTy(getVMContext()), NumVFPs - PreAllocation);
3588 it->info.setPaddingType(PaddingTy);
3591 // If we do not have enough GPRs for the small aggregate, any GPR regs
3592 // that are unallocated are marked as unavailable.
3593 if (IsSmallAggr && AllocatedGPR > NumGPRs && PreGPR < NumGPRs) {
3594 llvm::Type *PaddingTy = llvm::ArrayType::get(
3595 llvm::Type::getInt32Ty(getVMContext()), NumGPRs - PreGPR);
3597 ABIArgInfo::getDirect(it->info.getCoerceToType(), 0, PaddingTy);
3602 llvm::Value *EmitDarwinVAArg(llvm::Value *VAListAddr, QualType Ty,
3603 CodeGenFunction &CGF) const;
3605 llvm::Value *EmitAAPCSVAArg(llvm::Value *VAListAddr, QualType Ty,
3606 CodeGenFunction &CGF) const;
3608 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3609 CodeGenFunction &CGF) const {
3610 return isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF)
3611 : EmitAAPCSVAArg(VAListAddr, Ty, CGF);
3615 class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
3617 AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind)
3618 : TargetCodeGenInfo(new AArch64ABIInfo(CGT, Kind)) {}
3620 StringRef getARCRetainAutoreleasedReturnValueMarker() const {
3621 return "mov\tfp, fp\t\t; marker for objc_retainAutoreleaseReturnValue";
3624 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const { return 31; }
3626 virtual bool doesReturnSlotInterfereWithArgs() const { return false; }
3630 static bool isHomogeneousAggregate(QualType Ty, const Type *&Base,
3631 ASTContext &Context,
3632 uint64_t *HAMembers = nullptr);
3634 ABIArgInfo AArch64ABIInfo::classifyArgumentType(QualType Ty,
3635 unsigned &AllocatedVFP,
3637 unsigned &AllocatedGPR,
3639 bool IsNamedArg) const {
3640 // Handle illegal vector types here.
3641 if (isIllegalVectorType(Ty)) {
3642 uint64_t Size = getContext().getTypeSize(Ty);
3644 llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext());
3646 return ABIArgInfo::getDirect(ResType);
3649 llvm::Type *ResType =
3650 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2);
3652 return ABIArgInfo::getDirect(ResType);
3655 llvm::Type *ResType =
3656 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4);
3658 return ABIArgInfo::getDirect(ResType);
3661 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3663 if (Ty->isVectorType())
3664 // Size of a legal vector should be either 64 or 128.
3666 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
3667 if (BT->getKind() == BuiltinType::Half ||
3668 BT->getKind() == BuiltinType::Float ||
3669 BT->getKind() == BuiltinType::Double ||
3670 BT->getKind() == BuiltinType::LongDouble)
3674 if (!isAggregateTypeForABI(Ty)) {
3675 // Treat an enum type as its underlying type.
3676 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3677 Ty = EnumTy->getDecl()->getIntegerType();
3679 if (!Ty->isFloatingType() && !Ty->isVectorType()) {
3680 unsigned Alignment = getContext().getTypeAlign(Ty);
3681 if (!isDarwinPCS() && Alignment > 64)
3682 AllocatedGPR = llvm::RoundUpToAlignment(AllocatedGPR, Alignment / 64);
3684 int RegsNeeded = getContext().getTypeSize(Ty) > 64 ? 2 : 1;
3685 AllocatedGPR += RegsNeeded;
3687 return (Ty->isPromotableIntegerType() && isDarwinPCS()
3688 ? ABIArgInfo::getExtend()
3689 : ABIArgInfo::getDirect());
3692 // Structures with either a non-trivial destructor or a non-trivial
3693 // copy constructor are always indirect.
3694 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
3696 return ABIArgInfo::getIndirect(0, /*ByVal=*/RAA ==
3697 CGCXXABI::RAA_DirectInMemory);
3700 // Empty records are always ignored on Darwin, but actually passed in C++ mode
3701 // elsewhere for GNU compatibility.
3702 if (isEmptyRecord(getContext(), Ty, true)) {
3703 if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS())
3704 return ABIArgInfo::getIgnore();
3707 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
3710 // Homogeneous Floating-point Aggregates (HFAs) need to be expanded.
3711 const Type *Base = nullptr;
3712 uint64_t Members = 0;
3713 if (isHomogeneousAggregate(Ty, Base, getContext(), &Members)) {
3715 if (!IsNamedArg && isDarwinPCS()) {
3716 // With the Darwin ABI, variadic arguments are always passed on the stack
3717 // and should not be expanded. Treat variadic HFAs as arrays of doubles.
3718 uint64_t Size = getContext().getTypeSize(Ty);
3719 llvm::Type *BaseTy = llvm::Type::getDoubleTy(getVMContext());
3720 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
3722 AllocatedVFP += Members;
3723 return ABIArgInfo::getExpand();
3726 // Aggregates <= 16 bytes are passed directly in registers or on the stack.
3727 uint64_t Size = getContext().getTypeSize(Ty);
3729 unsigned Alignment = getContext().getTypeAlign(Ty);
3730 if (!isDarwinPCS() && Alignment > 64)
3731 AllocatedGPR = llvm::RoundUpToAlignment(AllocatedGPR, Alignment / 64);
3733 Size = 64 * ((Size + 63) / 64); // round up to multiple of 8 bytes
3734 AllocatedGPR += Size / 64;
3736 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
3737 // For aggregates with 16-byte alignment, we use i128.
3738 if (Alignment < 128 && Size == 128) {
3739 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
3740 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
3742 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
3746 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3749 ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy) const {
3750 if (RetTy->isVoidType())
3751 return ABIArgInfo::getIgnore();
3753 // Large vector types should be returned via memory.
3754 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
3755 return ABIArgInfo::getIndirect(0);
3757 if (!isAggregateTypeForABI(RetTy)) {
3758 // Treat an enum type as its underlying type.
3759 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
3760 RetTy = EnumTy->getDecl()->getIntegerType();
3762 return (RetTy->isPromotableIntegerType() && isDarwinPCS()
3763 ? ABIArgInfo::getExtend()
3764 : ABIArgInfo::getDirect());
3767 if (isEmptyRecord(getContext(), RetTy, true))
3768 return ABIArgInfo::getIgnore();
3770 const Type *Base = nullptr;
3771 if (isHomogeneousAggregate(RetTy, Base, getContext()))
3772 // Homogeneous Floating-point Aggregates (HFAs) are returned directly.
3773 return ABIArgInfo::getDirect();
3775 // Aggregates <= 16 bytes are returned directly in registers or on the stack.
3776 uint64_t Size = getContext().getTypeSize(RetTy);
3778 Size = 64 * ((Size + 63) / 64); // round up to multiple of 8 bytes
3779 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
3782 return ABIArgInfo::getIndirect(0);
3785 /// isIllegalVectorType - check whether the vector type is legal for AArch64.
3786 bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const {
3787 if (const VectorType *VT = Ty->getAs<VectorType>()) {
3788 // Check whether VT is legal.
3789 unsigned NumElements = VT->getNumElements();
3790 uint64_t Size = getContext().getTypeSize(VT);
3791 // NumElements should be power of 2 between 1 and 16.
3792 if ((NumElements & (NumElements - 1)) != 0 || NumElements > 16)
3794 return Size != 64 && (Size != 128 || NumElements == 1);
3799 static llvm::Value *EmitAArch64VAArg(llvm::Value *VAListAddr, QualType Ty,
3800 int AllocatedGPR, int AllocatedVFP,
3801 bool IsIndirect, CodeGenFunction &CGF) {
3802 // The AArch64 va_list type and handling is specified in the Procedure Call
3803 // Standard, section B.4:
3813 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
3814 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
3815 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
3816 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
3817 auto &Ctx = CGF.getContext();
3819 llvm::Value *reg_offs_p = nullptr, *reg_offs = nullptr;
3823 assert(!AllocatedVFP && "Arguments never split between int & VFP regs");
3824 // 3 is the field number of __gr_offs
3825 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 3, "gr_offs_p");
3826 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
3827 reg_top_index = 1; // field number for __gr_top
3828 RegSize = 8 * AllocatedGPR;
3830 assert(!AllocatedGPR && "Argument must go in VFP or int regs");
3831 // 4 is the field number of __vr_offs.
3832 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 4, "vr_offs_p");
3833 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
3834 reg_top_index = 2; // field number for __vr_top
3835 RegSize = 16 * AllocatedVFP;
3838 //=======================================
3839 // Find out where argument was passed
3840 //=======================================
3842 // If reg_offs >= 0 we're already using the stack for this type of
3843 // argument. We don't want to keep updating reg_offs (in case it overflows,
3844 // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
3845 // whatever they get).
3846 llvm::Value *UsingStack = nullptr;
3847 UsingStack = CGF.Builder.CreateICmpSGE(
3848 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0));
3850 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
3852 // Otherwise, at least some kind of argument could go in these registers, the
3853 // question is whether this particular type is too big.
3854 CGF.EmitBlock(MaybeRegBlock);
3856 // Integer arguments may need to correct register alignment (for example a
3857 // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
3858 // align __gr_offs to calculate the potential address.
3859 if (AllocatedGPR && !IsIndirect && Ctx.getTypeAlign(Ty) > 64) {
3860 int Align = Ctx.getTypeAlign(Ty) / 8;
3862 reg_offs = CGF.Builder.CreateAdd(
3863 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
3865 reg_offs = CGF.Builder.CreateAnd(
3866 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align),
3870 // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
3871 llvm::Value *NewOffset = nullptr;
3872 NewOffset = CGF.Builder.CreateAdd(
3873 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs");
3874 CGF.Builder.CreateStore(NewOffset, reg_offs_p);
3876 // Now we're in a position to decide whether this argument really was in
3877 // registers or not.
3878 llvm::Value *InRegs = nullptr;
3879 InRegs = CGF.Builder.CreateICmpSLE(
3880 NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg");
3882 CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
3884 //=======================================
3885 // Argument was in registers
3886 //=======================================
3888 // Now we emit the code for if the argument was originally passed in
3889 // registers. First start the appropriate block:
3890 CGF.EmitBlock(InRegBlock);
3892 llvm::Value *reg_top_p = nullptr, *reg_top = nullptr;
3894 CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index, "reg_top_p");
3895 reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
3896 llvm::Value *BaseAddr = CGF.Builder.CreateGEP(reg_top, reg_offs);
3897 llvm::Value *RegAddr = nullptr;
3898 llvm::Type *MemTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
3901 // If it's been passed indirectly (actually a struct), whatever we find from
3902 // stored registers or on the stack will actually be a struct **.
3903 MemTy = llvm::PointerType::getUnqual(MemTy);
3906 const Type *Base = nullptr;
3907 uint64_t NumMembers;
3908 bool IsHFA = isHomogeneousAggregate(Ty, Base, Ctx, &NumMembers);
3909 if (IsHFA && NumMembers > 1) {
3910 // Homogeneous aggregates passed in registers will have their elements split
3911 // and stored 16-bytes apart regardless of size (they're notionally in qN,
3912 // qN+1, ...). We reload and store into a temporary local variable
3914 assert(!IsIndirect && "Homogeneous aggregates should be passed directly");
3915 llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
3916 llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
3917 llvm::Value *Tmp = CGF.CreateTempAlloca(HFATy);
3920 if (CGF.CGM.getDataLayout().isBigEndian() && Ctx.getTypeSize(Base) < 128)
3921 Offset = 16 - Ctx.getTypeSize(Base) / 8;
3922 for (unsigned i = 0; i < NumMembers; ++i) {
3923 llvm::Value *BaseOffset =
3924 llvm::ConstantInt::get(CGF.Int32Ty, 16 * i + Offset);
3925 llvm::Value *LoadAddr = CGF.Builder.CreateGEP(BaseAddr, BaseOffset);
3926 LoadAddr = CGF.Builder.CreateBitCast(
3927 LoadAddr, llvm::PointerType::getUnqual(BaseTy));
3928 llvm::Value *StoreAddr = CGF.Builder.CreateStructGEP(Tmp, i);
3930 llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
3931 CGF.Builder.CreateStore(Elem, StoreAddr);
3934 RegAddr = CGF.Builder.CreateBitCast(Tmp, MemTy);
3936 // Otherwise the object is contiguous in memory
3937 unsigned BeAlign = reg_top_index == 2 ? 16 : 8;
3938 if (CGF.CGM.getDataLayout().isBigEndian() &&
3939 (IsHFA || !isAggregateTypeForABI(Ty)) &&
3940 Ctx.getTypeSize(Ty) < (BeAlign * 8)) {
3941 int Offset = BeAlign - Ctx.getTypeSize(Ty) / 8;
3942 BaseAddr = CGF.Builder.CreatePtrToInt(BaseAddr, CGF.Int64Ty);
3944 BaseAddr = CGF.Builder.CreateAdd(
3945 BaseAddr, llvm::ConstantInt::get(CGF.Int64Ty, Offset), "align_be");
3947 BaseAddr = CGF.Builder.CreateIntToPtr(BaseAddr, CGF.Int8PtrTy);
3950 RegAddr = CGF.Builder.CreateBitCast(BaseAddr, MemTy);
3953 CGF.EmitBranch(ContBlock);
3955 //=======================================
3956 // Argument was on the stack
3957 //=======================================
3958 CGF.EmitBlock(OnStackBlock);
3960 llvm::Value *stack_p = nullptr, *OnStackAddr = nullptr;
3961 stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "stack_p");
3962 OnStackAddr = CGF.Builder.CreateLoad(stack_p, "stack");
3964 // Again, stack arguments may need realigmnent. In this case both integer and
3965 // floating-point ones might be affected.
3966 if (!IsIndirect && Ctx.getTypeAlign(Ty) > 64) {
3967 int Align = Ctx.getTypeAlign(Ty) / 8;
3969 OnStackAddr = CGF.Builder.CreatePtrToInt(OnStackAddr, CGF.Int64Ty);
3971 OnStackAddr = CGF.Builder.CreateAdd(
3972 OnStackAddr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
3974 OnStackAddr = CGF.Builder.CreateAnd(
3975 OnStackAddr, llvm::ConstantInt::get(CGF.Int64Ty, -Align),
3978 OnStackAddr = CGF.Builder.CreateIntToPtr(OnStackAddr, CGF.Int8PtrTy);
3985 StackSize = Ctx.getTypeSize(Ty) / 8;
3987 // All stack slots are 8 bytes
3988 StackSize = llvm::RoundUpToAlignment(StackSize, 8);
3990 llvm::Value *StackSizeC = llvm::ConstantInt::get(CGF.Int32Ty, StackSize);
3991 llvm::Value *NewStack =
3992 CGF.Builder.CreateGEP(OnStackAddr, StackSizeC, "new_stack");
3994 // Write the new value of __stack for the next call to va_arg
3995 CGF.Builder.CreateStore(NewStack, stack_p);
3997 if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) &&
3998 Ctx.getTypeSize(Ty) < 64) {
3999 int Offset = 8 - Ctx.getTypeSize(Ty) / 8;
4000 OnStackAddr = CGF.Builder.CreatePtrToInt(OnStackAddr, CGF.Int64Ty);
4002 OnStackAddr = CGF.Builder.CreateAdd(
4003 OnStackAddr, llvm::ConstantInt::get(CGF.Int64Ty, Offset), "align_be");
4005 OnStackAddr = CGF.Builder.CreateIntToPtr(OnStackAddr, CGF.Int8PtrTy);
4008 OnStackAddr = CGF.Builder.CreateBitCast(OnStackAddr, MemTy);
4010 CGF.EmitBranch(ContBlock);
4012 //=======================================
4014 //=======================================
4015 CGF.EmitBlock(ContBlock);
4017 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(MemTy, 2, "vaarg.addr");
4018 ResAddr->addIncoming(RegAddr, InRegBlock);
4019 ResAddr->addIncoming(OnStackAddr, OnStackBlock);
4022 return CGF.Builder.CreateLoad(ResAddr, "vaarg.addr");
4027 llvm::Value *AArch64ABIInfo::EmitAAPCSVAArg(llvm::Value *VAListAddr, QualType Ty,
4028 CodeGenFunction &CGF) const {
4030 unsigned AllocatedGPR = 0, AllocatedVFP = 0;
4031 bool IsHA = false, IsSmallAggr = false;
4032 ABIArgInfo AI = classifyArgumentType(Ty, AllocatedVFP, IsHA, AllocatedGPR,
4033 IsSmallAggr, false /*IsNamedArg*/);
4035 return EmitAArch64VAArg(VAListAddr, Ty, AllocatedGPR, AllocatedVFP,
4036 AI.isIndirect(), CGF);
4039 llvm::Value *AArch64ABIInfo::EmitDarwinVAArg(llvm::Value *VAListAddr, QualType Ty,
4040 CodeGenFunction &CGF) const {
4041 // We do not support va_arg for aggregates or illegal vector types.
4042 // Lower VAArg here for these cases and use the LLVM va_arg instruction for
4044 if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty))
4047 uint64_t Size = CGF.getContext().getTypeSize(Ty) / 8;
4048 uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8;
4050 const Type *Base = nullptr;
4051 bool isHA = isHomogeneousAggregate(Ty, Base, getContext());
4053 bool isIndirect = false;
4054 // Arguments bigger than 16 bytes which aren't homogeneous aggregates should
4055 // be passed indirectly.
4056 if (Size > 16 && !isHA) {
4062 llvm::Type *BP = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
4063 llvm::Type *BPP = llvm::PointerType::getUnqual(BP);
4065 CGBuilderTy &Builder = CGF.Builder;
4066 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
4067 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
4069 if (isEmptyRecord(getContext(), Ty, true)) {
4070 // These are ignored for parameter passing purposes.
4071 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
4072 return Builder.CreateBitCast(Addr, PTy);
4075 const uint64_t MinABIAlign = 8;
4076 if (Align > MinABIAlign) {
4077 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, Align - 1);
4078 Addr = Builder.CreateGEP(Addr, Offset);
4079 llvm::Value *AsInt = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
4080 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int64Ty, ~(Align - 1));
4081 llvm::Value *Aligned = Builder.CreateAnd(AsInt, Mask);
4082 Addr = Builder.CreateIntToPtr(Aligned, BP, "ap.align");
4085 uint64_t Offset = llvm::RoundUpToAlignment(Size, MinABIAlign);
4086 llvm::Value *NextAddr = Builder.CreateGEP(
4087 Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset), "ap.next");
4088 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
4091 Addr = Builder.CreateLoad(Builder.CreateBitCast(Addr, BPP));
4092 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
4093 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
4098 //===----------------------------------------------------------------------===//
4099 // ARM ABI Implementation
4100 //===----------------------------------------------------------------------===//
4104 class ARMABIInfo : public ABIInfo {
4114 mutable int VFPRegs[16];
4115 const unsigned NumVFPs;
4116 const unsigned NumGPRs;
4117 mutable unsigned AllocatedGPRs;
4118 mutable unsigned AllocatedVFPs;
4121 ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind) : ABIInfo(CGT), Kind(_Kind),
4122 NumVFPs(16), NumGPRs(4) {
4124 resetAllocatedRegs();
4127 bool isEABI() const {
4128 switch (getTarget().getTriple().getEnvironment()) {
4129 case llvm::Triple::Android:
4130 case llvm::Triple::EABI:
4131 case llvm::Triple::EABIHF:
4132 case llvm::Triple::GNUEABI:
4133 case llvm::Triple::GNUEABIHF:
4140 bool isEABIHF() const {
4141 switch (getTarget().getTriple().getEnvironment()) {
4142 case llvm::Triple::EABIHF:
4143 case llvm::Triple::GNUEABIHF:
4150 ABIKind getABIKind() const { return Kind; }
4153 ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic) const;
4154 ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic,
4155 bool &IsCPRC) const;
4156 bool isIllegalVectorType(QualType Ty) const;
4158 void computeInfo(CGFunctionInfo &FI) const override;
4160 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4161 CodeGenFunction &CGF) const override;
4163 llvm::CallingConv::ID getLLVMDefaultCC() const;
4164 llvm::CallingConv::ID getABIDefaultCC() const;
4165 void setRuntimeCC();
4167 void markAllocatedGPRs(unsigned Alignment, unsigned NumRequired) const;
4168 void markAllocatedVFPs(unsigned Alignment, unsigned NumRequired) const;
4169 void resetAllocatedRegs(void) const;
4172 class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
4174 ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
4175 :TargetCodeGenInfo(new ARMABIInfo(CGT, K)) {}
4177 const ARMABIInfo &getABIInfo() const {
4178 return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
4181 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4185 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
4186 return "mov\tr7, r7\t\t@ marker for objc_retainAutoreleaseReturnValue";
4189 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4190 llvm::Value *Address) const override {
4191 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
4193 // 0-15 are the 16 integer registers.
4194 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
4198 unsigned getSizeOfUnwindException() const override {
4199 if (getABIInfo().isEABI()) return 88;
4200 return TargetCodeGenInfo::getSizeOfUnwindException();
4203 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
4204 CodeGen::CodeGenModule &CGM) const override {
4205 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
4209 const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
4214 switch (Attr->getInterrupt()) {
4215 case ARMInterruptAttr::Generic: Kind = ""; break;
4216 case ARMInterruptAttr::IRQ: Kind = "IRQ"; break;
4217 case ARMInterruptAttr::FIQ: Kind = "FIQ"; break;
4218 case ARMInterruptAttr::SWI: Kind = "SWI"; break;
4219 case ARMInterruptAttr::ABORT: Kind = "ABORT"; break;
4220 case ARMInterruptAttr::UNDEF: Kind = "UNDEF"; break;
4223 llvm::Function *Fn = cast<llvm::Function>(GV);
4225 Fn->addFnAttr("interrupt", Kind);
4227 if (cast<ARMABIInfo>(getABIInfo()).getABIKind() == ARMABIInfo::APCS)
4230 // AAPCS guarantees that sp will be 8-byte aligned on any public interface,
4231 // however this is not necessarily true on taking any interrupt. Instruct
4232 // the backend to perform a realignment as part of the function prologue.
4233 llvm::AttrBuilder B;
4234 B.addStackAlignmentAttr(8);
4235 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
4236 llvm::AttributeSet::get(CGM.getLLVMContext(),
4237 llvm::AttributeSet::FunctionIndex,
4245 void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
4246 // To correctly handle Homogeneous Aggregate, we need to keep track of the
4247 // VFP registers allocated so far.
4248 // C.1.vfp If the argument is a VFP CPRC and there are sufficient consecutive
4249 // VFP registers of the appropriate type unallocated then the argument is
4250 // allocated to the lowest-numbered sequence of such registers.
4251 // C.2.vfp If the argument is a VFP CPRC then any VFP registers that are
4252 // unallocated are marked as unavailable.
4253 resetAllocatedRegs();
4255 if (getCXXABI().classifyReturnType(FI)) {
4256 if (FI.getReturnInfo().isIndirect())
4257 markAllocatedGPRs(1, 1);
4259 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), FI.isVariadic());
4261 for (auto &I : FI.arguments()) {
4262 unsigned PreAllocationVFPs = AllocatedVFPs;
4263 unsigned PreAllocationGPRs = AllocatedGPRs;
4264 bool IsCPRC = false;
4265 // 6.1.2.3 There is one VFP co-processor register class using registers
4266 // s0-s15 (d0-d7) for passing arguments.
4267 I.info = classifyArgumentType(I.type, FI.isVariadic(), IsCPRC);
4269 // If we have allocated some arguments onto the stack (due to running
4270 // out of VFP registers), we cannot split an argument between GPRs and
4271 // the stack. If this situation occurs, we add padding to prevent the
4272 // GPRs from being used. In this situation, the current argument could
4273 // only be allocated by rule C.8, so rule C.6 would mark these GPRs as
4275 // We do not have to do this if the argument is being passed ByVal, as the
4276 // backend can handle that situation correctly.
4277 const bool StackUsed = PreAllocationGPRs > NumGPRs || PreAllocationVFPs > NumVFPs;
4278 const bool IsByVal = I.info.isIndirect() && I.info.getIndirectByVal();
4279 if (!IsCPRC && PreAllocationGPRs < NumGPRs && AllocatedGPRs > NumGPRs &&
4280 StackUsed && !IsByVal) {
4281 llvm::Type *PaddingTy = llvm::ArrayType::get(
4282 llvm::Type::getInt32Ty(getVMContext()), NumGPRs - PreAllocationGPRs);
4283 if (I.info.canHaveCoerceToType()) {
4284 I.info = ABIArgInfo::getDirect(I.info.getCoerceToType() /* type */, 0 /* offset */,
4287 I.info = ABIArgInfo::getDirect(nullptr /* type */, 0 /* offset */,
4293 // Always honor user-specified calling convention.
4294 if (FI.getCallingConvention() != llvm::CallingConv::C)
4297 llvm::CallingConv::ID cc = getRuntimeCC();
4298 if (cc != llvm::CallingConv::C)
4299 FI.setEffectiveCallingConvention(cc);
4302 /// Return the default calling convention that LLVM will use.
4303 llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
4304 // The default calling convention that LLVM will infer.
4306 return llvm::CallingConv::ARM_AAPCS_VFP;
4308 return llvm::CallingConv::ARM_AAPCS;
4310 return llvm::CallingConv::ARM_APCS;
4313 /// Return the calling convention that our ABI would like us to use
4314 /// as the C calling convention.
4315 llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
4316 switch (getABIKind()) {
4317 case APCS: return llvm::CallingConv::ARM_APCS;
4318 case AAPCS: return llvm::CallingConv::ARM_AAPCS;
4319 case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
4321 llvm_unreachable("bad ABI kind");
4324 void ARMABIInfo::setRuntimeCC() {
4325 assert(getRuntimeCC() == llvm::CallingConv::C);
4327 // Don't muddy up the IR with a ton of explicit annotations if
4328 // they'd just match what LLVM will infer from the triple.
4329 llvm::CallingConv::ID abiCC = getABIDefaultCC();
4330 if (abiCC != getLLVMDefaultCC())
4334 /// isHomogeneousAggregate - Return true if a type is an AAPCS-VFP homogeneous
4335 /// aggregate. If HAMembers is non-null, the number of base elements
4336 /// contained in the type is returned through it; this is used for the
4337 /// recursive calls that check aggregate component types.
4338 static bool isHomogeneousAggregate(QualType Ty, const Type *&Base,
4339 ASTContext &Context, uint64_t *HAMembers) {
4340 uint64_t Members = 0;
4341 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
4342 if (!isHomogeneousAggregate(AT->getElementType(), Base, Context, &Members))
4344 Members *= AT->getSize().getZExtValue();
4345 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
4346 const RecordDecl *RD = RT->getDecl();
4347 if (RD->hasFlexibleArrayMember())
4351 for (const auto *FD : RD->fields()) {
4352 uint64_t FldMembers;
4353 if (!isHomogeneousAggregate(FD->getType(), Base, Context, &FldMembers))
4356 Members = (RD->isUnion() ?
4357 std::max(Members, FldMembers) : Members + FldMembers);
4361 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
4363 Ty = CT->getElementType();
4366 // Homogeneous aggregates for AAPCS-VFP must have base types of float,
4367 // double, or 64-bit or 128-bit vectors.
4368 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4369 if (BT->getKind() != BuiltinType::Float &&
4370 BT->getKind() != BuiltinType::Double &&
4371 BT->getKind() != BuiltinType::LongDouble)
4373 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
4374 unsigned VecSize = Context.getTypeSize(VT);
4375 if (VecSize != 64 && VecSize != 128)
4381 // The base type must be the same for all members. Vector types of the
4382 // same total size are treated as being equivalent here.
4383 const Type *TyPtr = Ty.getTypePtr();
4387 if (Base != TyPtr) {
4388 // Homogeneous aggregates are defined as containing members with the
4389 // same machine type. There are two cases in which two members have
4390 // different TypePtrs but the same machine type:
4392 // 1) Vectors of the same length, regardless of the type and number
4393 // of their members.
4394 const bool SameLengthVectors = Base->isVectorType() && TyPtr->isVectorType()
4395 && (Context.getTypeSize(Base) == Context.getTypeSize(TyPtr));
4397 // 2) In the 32-bit AAPCS, `double' and `long double' have the same
4398 // machine type. This is not the case for the 64-bit AAPCS.
4399 const bool SameSizeDoubles =
4400 ( ( Base->isSpecificBuiltinType(BuiltinType::Double)
4401 && TyPtr->isSpecificBuiltinType(BuiltinType::LongDouble))
4402 || ( Base->isSpecificBuiltinType(BuiltinType::LongDouble)
4403 && TyPtr->isSpecificBuiltinType(BuiltinType::Double)))
4404 && (Context.getTypeSize(Base) == Context.getTypeSize(TyPtr));
4406 if (!SameLengthVectors && !SameSizeDoubles)
4411 // Homogeneous Aggregates can have at most 4 members of the base type.
4413 *HAMembers = Members;
4415 return (Members > 0 && Members <= 4);
4418 /// markAllocatedVFPs - update VFPRegs according to the alignment and
4419 /// number of VFP registers (unit is S register) requested.
4420 void ARMABIInfo::markAllocatedVFPs(unsigned Alignment,
4421 unsigned NumRequired) const {
4423 if (AllocatedVFPs >= 16) {
4424 // We use AllocatedVFP > 16 to signal that some CPRCs were allocated on
4429 // C.1.vfp If the argument is a VFP CPRC and there are sufficient consecutive
4430 // VFP registers of the appropriate type unallocated then the argument is
4431 // allocated to the lowest-numbered sequence of such registers.
4432 for (unsigned I = 0; I < 16; I += Alignment) {
4433 bool FoundSlot = true;
4434 for (unsigned J = I, JEnd = I + NumRequired; J < JEnd; J++)
4435 if (J >= 16 || VFPRegs[J]) {
4440 for (unsigned J = I, JEnd = I + NumRequired; J < JEnd; J++)
4442 AllocatedVFPs += NumRequired;
4446 // C.2.vfp If the argument is a VFP CPRC then any VFP registers that are
4447 // unallocated are marked as unavailable.
4448 for (unsigned I = 0; I < 16; I++)
4450 AllocatedVFPs = 17; // We do not have enough VFP registers.
4453 /// Update AllocatedGPRs to record the number of general purpose registers
4454 /// which have been allocated. It is valid for AllocatedGPRs to go above 4,
4455 /// this represents arguments being stored on the stack.
4456 void ARMABIInfo::markAllocatedGPRs(unsigned Alignment,
4457 unsigned NumRequired) const {
4458 assert((Alignment == 1 || Alignment == 2) && "Alignment must be 4 or 8 bytes");
4460 if (Alignment == 2 && AllocatedGPRs & 0x1)
4463 AllocatedGPRs += NumRequired;
4466 void ARMABIInfo::resetAllocatedRegs(void) const {
4469 for (unsigned i = 0; i < NumVFPs; ++i)
4473 ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty, bool isVariadic,
4474 bool &IsCPRC) const {
4475 // We update number of allocated VFPs according to
4476 // 6.1.2.1 The following argument types are VFP CPRCs:
4477 // A single-precision floating-point type (including promoted
4478 // half-precision types); A double-precision floating-point type;
4479 // A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
4480 // with a Base Type of a single- or double-precision floating-point type,
4481 // 64-bit containerized vectors or 128-bit containerized vectors with one
4482 // to four Elements.
4484 // Handle illegal vector types here.
4485 if (isIllegalVectorType(Ty)) {
4486 uint64_t Size = getContext().getTypeSize(Ty);
4488 llvm::Type *ResType =
4489 llvm::Type::getInt32Ty(getVMContext());
4490 markAllocatedGPRs(1, 1);
4491 return ABIArgInfo::getDirect(ResType);
4494 llvm::Type *ResType = llvm::VectorType::get(
4495 llvm::Type::getInt32Ty(getVMContext()), 2);
4496 if (getABIKind() == ARMABIInfo::AAPCS || isVariadic){
4497 markAllocatedGPRs(2, 2);
4499 markAllocatedVFPs(2, 2);
4502 return ABIArgInfo::getDirect(ResType);
4505 llvm::Type *ResType = llvm::VectorType::get(
4506 llvm::Type::getInt32Ty(getVMContext()), 4);
4507 if (getABIKind() == ARMABIInfo::AAPCS || isVariadic) {
4508 markAllocatedGPRs(2, 4);
4510 markAllocatedVFPs(4, 4);
4513 return ABIArgInfo::getDirect(ResType);
4515 markAllocatedGPRs(1, 1);
4516 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
4518 // Update VFPRegs for legal vector types.
4519 if (getABIKind() == ARMABIInfo::AAPCS_VFP && !isVariadic) {
4520 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4521 uint64_t Size = getContext().getTypeSize(VT);
4522 // Size of a legal vector should be power of 2 and above 64.
4523 markAllocatedVFPs(Size >= 128 ? 4 : 2, Size / 32);
4527 // Update VFPRegs for floating point types.
4528 if (getABIKind() == ARMABIInfo::AAPCS_VFP && !isVariadic) {
4529 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4530 if (BT->getKind() == BuiltinType::Half ||
4531 BT->getKind() == BuiltinType::Float) {
4532 markAllocatedVFPs(1, 1);
4535 if (BT->getKind() == BuiltinType::Double ||
4536 BT->getKind() == BuiltinType::LongDouble) {
4537 markAllocatedVFPs(2, 2);
4543 if (!isAggregateTypeForABI(Ty)) {
4544 // Treat an enum type as its underlying type.
4545 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
4546 Ty = EnumTy->getDecl()->getIntegerType();
4549 unsigned Size = getContext().getTypeSize(Ty);
4551 markAllocatedGPRs(Size > 32 ? 2 : 1, (Size + 31) / 32);
4552 return (Ty->isPromotableIntegerType() ?
4553 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
4556 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
4557 markAllocatedGPRs(1, 1);
4558 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
4561 // Ignore empty records.
4562 if (isEmptyRecord(getContext(), Ty, true))
4563 return ABIArgInfo::getIgnore();
4565 if (getABIKind() == ARMABIInfo::AAPCS_VFP && !isVariadic) {
4566 // Homogeneous Aggregates need to be expanded when we can fit the aggregate
4567 // into VFP registers.
4568 const Type *Base = nullptr;
4569 uint64_t Members = 0;
4570 if (isHomogeneousAggregate(Ty, Base, getContext(), &Members)) {
4571 assert(Base && "Base class should be set for homogeneous aggregate");
4572 // Base can be a floating-point or a vector.
4573 if (Base->isVectorType()) {
4574 // ElementSize is in number of floats.
4575 unsigned ElementSize = getContext().getTypeSize(Base) == 64 ? 2 : 4;
4576 markAllocatedVFPs(ElementSize,
4577 Members * ElementSize);
4578 } else if (Base->isSpecificBuiltinType(BuiltinType::Float))
4579 markAllocatedVFPs(1, Members);
4581 assert(Base->isSpecificBuiltinType(BuiltinType::Double) ||
4582 Base->isSpecificBuiltinType(BuiltinType::LongDouble));
4583 markAllocatedVFPs(2, Members * 2);
4586 return ABIArgInfo::getDirect();
4590 // Support byval for ARM.
4591 // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
4592 // most 8-byte. We realign the indirect argument if type alignment is bigger
4593 // than ABI alignment.
4594 uint64_t ABIAlign = 4;
4595 uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8;
4596 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
4597 getABIKind() == ARMABIInfo::AAPCS)
4598 ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
4599 if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
4600 // Update Allocated GPRs. Since this is only used when the size of the
4601 // argument is greater than 64 bytes, this will always use up any available
4602 // registers (of which there are 4). We also don't care about getting the
4603 // alignment right, because general-purpose registers cannot be back-filled.
4604 markAllocatedGPRs(1, 4);
4605 return ABIArgInfo::getIndirect(TyAlign, /*ByVal=*/true,
4606 /*Realign=*/TyAlign > ABIAlign);
4609 // Otherwise, pass by coercing to a structure of the appropriate size.
4612 // FIXME: Try to match the types of the arguments more accurately where
4614 if (getContext().getTypeAlign(Ty) <= 32) {
4615 ElemTy = llvm::Type::getInt32Ty(getVMContext());
4616 SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
4617 markAllocatedGPRs(1, SizeRegs);
4619 ElemTy = llvm::Type::getInt64Ty(getVMContext());
4620 SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
4621 markAllocatedGPRs(2, SizeRegs * 2);
4625 llvm::StructType::get(llvm::ArrayType::get(ElemTy, SizeRegs), NULL);
4626 return ABIArgInfo::getDirect(STy);
4629 static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
4630 llvm::LLVMContext &VMContext) {
4631 // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
4632 // is called integer-like if its size is less than or equal to one word, and
4633 // the offset of each of its addressable sub-fields is zero.
4635 uint64_t Size = Context.getTypeSize(Ty);
4637 // Check that the type fits in a word.
4641 // FIXME: Handle vector types!
4642 if (Ty->isVectorType())
4645 // Float types are never treated as "integer like".
4646 if (Ty->isRealFloatingType())
4649 // If this is a builtin or pointer type then it is ok.
4650 if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
4653 // Small complex integer types are "integer like".
4654 if (const ComplexType *CT = Ty->getAs<ComplexType>())
4655 return isIntegerLikeType(CT->getElementType(), Context, VMContext);
4657 // Single element and zero sized arrays should be allowed, by the definition
4658 // above, but they are not.
4660 // Otherwise, it must be a record type.
4661 const RecordType *RT = Ty->getAs<RecordType>();
4662 if (!RT) return false;
4664 // Ignore records with flexible arrays.
4665 const RecordDecl *RD = RT->getDecl();
4666 if (RD->hasFlexibleArrayMember())
4669 // Check that all sub-fields are at offset 0, and are themselves "integer
4671 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
4673 bool HadField = false;
4675 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
4676 i != e; ++i, ++idx) {
4677 const FieldDecl *FD = *i;
4679 // Bit-fields are not addressable, we only need to verify they are "integer
4680 // like". We still have to disallow a subsequent non-bitfield, for example:
4681 // struct { int : 0; int x }
4682 // is non-integer like according to gcc.
4683 if (FD->isBitField()) {
4687 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
4693 // Check if this field is at offset 0.
4694 if (Layout.getFieldOffset(idx) != 0)
4697 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
4700 // Only allow at most one field in a structure. This doesn't match the
4701 // wording above, but follows gcc in situations with a field following an
4703 if (!RD->isUnion()) {
4714 ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy,
4715 bool isVariadic) const {
4716 if (RetTy->isVoidType())
4717 return ABIArgInfo::getIgnore();
4719 // Large vector types should be returned via memory.
4720 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128) {
4721 markAllocatedGPRs(1, 1);
4722 return ABIArgInfo::getIndirect(0);
4725 if (!isAggregateTypeForABI(RetTy)) {
4726 // Treat an enum type as its underlying type.
4727 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
4728 RetTy = EnumTy->getDecl()->getIntegerType();
4730 return (RetTy->isPromotableIntegerType() ?
4731 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
4734 // Are we following APCS?
4735 if (getABIKind() == APCS) {
4736 if (isEmptyRecord(getContext(), RetTy, false))
4737 return ABIArgInfo::getIgnore();
4739 // Complex types are all returned as packed integers.
4741 // FIXME: Consider using 2 x vector types if the back end handles them
4743 if (RetTy->isAnyComplexType())
4744 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
4745 getContext().getTypeSize(RetTy)));
4747 // Integer like structures are returned in r0.
4748 if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
4749 // Return in the smallest viable integer type.
4750 uint64_t Size = getContext().getTypeSize(RetTy);
4752 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
4754 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
4755 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
4758 // Otherwise return in memory.
4759 markAllocatedGPRs(1, 1);
4760 return ABIArgInfo::getIndirect(0);
4763 // Otherwise this is an AAPCS variant.
4765 if (isEmptyRecord(getContext(), RetTy, true))
4766 return ABIArgInfo::getIgnore();
4768 // Check for homogeneous aggregates with AAPCS-VFP.
4769 if (getABIKind() == AAPCS_VFP && !isVariadic) {
4770 const Type *Base = nullptr;
4771 if (isHomogeneousAggregate(RetTy, Base, getContext())) {
4772 assert(Base && "Base class should be set for homogeneous aggregate");
4773 // Homogeneous Aggregates are returned directly.
4774 return ABIArgInfo::getDirect();
4778 // Aggregates <= 4 bytes are returned in r0; other aggregates
4779 // are returned indirectly.
4780 uint64_t Size = getContext().getTypeSize(RetTy);
4782 if (getDataLayout().isBigEndian())
4783 // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4)
4784 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
4786 // Return in the smallest viable integer type.
4788 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
4790 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
4791 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
4794 markAllocatedGPRs(1, 1);
4795 return ABIArgInfo::getIndirect(0);
4798 /// isIllegalVector - check whether Ty is an illegal vector type.
4799 bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
4800 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4801 // Check whether VT is legal.
4802 unsigned NumElements = VT->getNumElements();
4803 uint64_t Size = getContext().getTypeSize(VT);
4804 // NumElements should be power of 2.
4805 if ((NumElements & (NumElements - 1)) != 0)
4807 // Size should be greater than 32 bits.
4813 llvm::Value *ARMABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4814 CodeGenFunction &CGF) const {
4815 llvm::Type *BP = CGF.Int8PtrTy;
4816 llvm::Type *BPP = CGF.Int8PtrPtrTy;
4818 CGBuilderTy &Builder = CGF.Builder;
4819 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
4820 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
4822 if (isEmptyRecord(getContext(), Ty, true)) {
4823 // These are ignored for parameter passing purposes.
4824 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
4825 return Builder.CreateBitCast(Addr, PTy);
4828 uint64_t Size = CGF.getContext().getTypeSize(Ty) / 8;
4829 uint64_t TyAlign = CGF.getContext().getTypeAlign(Ty) / 8;
4830 bool IsIndirect = false;
4832 // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
4833 // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
4834 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
4835 getABIKind() == ARMABIInfo::AAPCS)
4836 TyAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
4839 // Use indirect if size of the illegal vector is bigger than 16 bytes.
4840 if (isIllegalVectorType(Ty) && Size > 16) {
4846 // Handle address alignment for ABI alignment > 4 bytes.
4848 assert((TyAlign & (TyAlign - 1)) == 0 &&
4849 "Alignment is not power of 2!");
4850 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int32Ty);
4851 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt32(TyAlign - 1));
4852 AddrAsInt = Builder.CreateAnd(AddrAsInt, Builder.getInt32(~(TyAlign - 1)));
4853 Addr = Builder.CreateIntToPtr(AddrAsInt, BP, "ap.align");
4857 llvm::RoundUpToAlignment(Size, 4);
4858 llvm::Value *NextAddr =
4859 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
4861 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
4864 Addr = Builder.CreateLoad(Builder.CreateBitCast(Addr, BPP));
4865 else if (TyAlign < CGF.getContext().getTypeAlign(Ty) / 8) {
4866 // We can't directly cast ap.cur to pointer to a vector type, since ap.cur
4867 // may not be correctly aligned for the vector type. We create an aligned
4868 // temporary space and copy the content over from ap.cur to the temporary
4869 // space. This is necessary if the natural alignment of the type is greater
4870 // than the ABI alignment.
4871 llvm::Type *I8PtrTy = Builder.getInt8PtrTy();
4872 CharUnits CharSize = getContext().getTypeSizeInChars(Ty);
4873 llvm::Value *AlignedTemp = CGF.CreateTempAlloca(CGF.ConvertType(Ty),
4875 llvm::Value *Dst = Builder.CreateBitCast(AlignedTemp, I8PtrTy);
4876 llvm::Value *Src = Builder.CreateBitCast(Addr, I8PtrTy);
4877 Builder.CreateMemCpy(Dst, Src,
4878 llvm::ConstantInt::get(CGF.IntPtrTy, CharSize.getQuantity()),
4880 Addr = AlignedTemp; //The content is in aligned location.
4883 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
4884 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
4891 class NaClARMABIInfo : public ABIInfo {
4893 NaClARMABIInfo(CodeGen::CodeGenTypes &CGT, ARMABIInfo::ABIKind Kind)
4894 : ABIInfo(CGT), PInfo(CGT), NInfo(CGT, Kind) {}
4895 void computeInfo(CGFunctionInfo &FI) const override;
4896 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4897 CodeGenFunction &CGF) const override;
4899 PNaClABIInfo PInfo; // Used for generating calls with pnaclcall callingconv.
4900 ARMABIInfo NInfo; // Used for everything else.
4903 class NaClARMTargetCodeGenInfo : public TargetCodeGenInfo {
4905 NaClARMTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, ARMABIInfo::ABIKind Kind)
4906 : TargetCodeGenInfo(new NaClARMABIInfo(CGT, Kind)) {}
4911 void NaClARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
4912 if (FI.getASTCallingConvention() == CC_PnaclCall)
4913 PInfo.computeInfo(FI);
4915 static_cast<const ABIInfo&>(NInfo).computeInfo(FI);
4918 llvm::Value *NaClARMABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4919 CodeGenFunction &CGF) const {
4920 // Always use the native convention; calling pnacl-style varargs functions
4922 return static_cast<const ABIInfo&>(NInfo).EmitVAArg(VAListAddr, Ty, CGF);
4925 //===----------------------------------------------------------------------===//
4926 // NVPTX ABI Implementation
4927 //===----------------------------------------------------------------------===//
4931 class NVPTXABIInfo : public ABIInfo {
4933 NVPTXABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
4935 ABIArgInfo classifyReturnType(QualType RetTy) const;
4936 ABIArgInfo classifyArgumentType(QualType Ty) const;
4938 void computeInfo(CGFunctionInfo &FI) const override;
4939 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4940 CodeGenFunction &CFG) const override;
4943 class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
4945 NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
4946 : TargetCodeGenInfo(new NVPTXABIInfo(CGT)) {}
4948 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
4949 CodeGen::CodeGenModule &M) const override;
4951 // Adds a NamedMDNode with F, Name, and Operand as operands, and adds the
4952 // resulting MDNode to the nvvm.annotations MDNode.
4953 static void addNVVMMetadata(llvm::Function *F, StringRef Name, int Operand);
4956 ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
4957 if (RetTy->isVoidType())
4958 return ABIArgInfo::getIgnore();
4960 // note: this is different from default ABI
4961 if (!RetTy->isScalarType())
4962 return ABIArgInfo::getDirect();
4964 // Treat an enum type as its underlying type.
4965 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
4966 RetTy = EnumTy->getDecl()->getIntegerType();
4968 return (RetTy->isPromotableIntegerType() ?
4969 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
4972 ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
4973 // Treat an enum type as its underlying type.
4974 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4975 Ty = EnumTy->getDecl()->getIntegerType();
4977 return (Ty->isPromotableIntegerType() ?
4978 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
4981 void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
4982 if (!getCXXABI().classifyReturnType(FI))
4983 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
4984 for (auto &I : FI.arguments())
4985 I.info = classifyArgumentType(I.type);
4987 // Always honor user-specified calling convention.
4988 if (FI.getCallingConvention() != llvm::CallingConv::C)
4991 FI.setEffectiveCallingConvention(getRuntimeCC());
4994 llvm::Value *NVPTXABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4995 CodeGenFunction &CFG) const {
4996 llvm_unreachable("NVPTX does not support varargs");
4999 void NVPTXTargetCodeGenInfo::
5000 SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5001 CodeGen::CodeGenModule &M) const{
5002 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
5005 llvm::Function *F = cast<llvm::Function>(GV);
5007 // Perform special handling in OpenCL mode
5008 if (M.getLangOpts().OpenCL) {
5009 // Use OpenCL function attributes to check for kernel functions
5010 // By default, all functions are device functions
5011 if (FD->hasAttr<OpenCLKernelAttr>()) {
5012 // OpenCL __kernel functions get kernel metadata
5013 // Create !{<func-ref>, metadata !"kernel", i32 1} node
5014 addNVVMMetadata(F, "kernel", 1);
5015 // And kernel functions are not subject to inlining
5016 F->addFnAttr(llvm::Attribute::NoInline);
5020 // Perform special handling in CUDA mode.
5021 if (M.getLangOpts().CUDA) {
5022 // CUDA __global__ functions get a kernel metadata entry. Since
5023 // __global__ functions cannot be called from the device, we do not
5024 // need to set the noinline attribute.
5025 if (FD->hasAttr<CUDAGlobalAttr>()) {
5026 // Create !{<func-ref>, metadata !"kernel", i32 1} node
5027 addNVVMMetadata(F, "kernel", 1);
5029 if (FD->hasAttr<CUDALaunchBoundsAttr>()) {
5030 // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node
5031 addNVVMMetadata(F, "maxntidx",
5032 FD->getAttr<CUDALaunchBoundsAttr>()->getMaxThreads());
5033 // min blocks is a default argument for CUDALaunchBoundsAttr, so getting a
5034 // zero value from getMinBlocks either means it was not specified in
5035 // __launch_bounds__ or the user specified a 0 value. In both cases, we
5036 // don't have to add a PTX directive.
5037 int MinCTASM = FD->getAttr<CUDALaunchBoundsAttr>()->getMinBlocks();
5039 // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node
5040 addNVVMMetadata(F, "minctasm", MinCTASM);
5046 void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::Function *F, StringRef Name,
5048 llvm::Module *M = F->getParent();
5049 llvm::LLVMContext &Ctx = M->getContext();
5051 // Get "nvvm.annotations" metadata node
5052 llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
5054 llvm::Value *MDVals[] = {
5055 F, llvm::MDString::get(Ctx, Name),
5056 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand)};
5057 // Append metadata to nvvm.annotations
5058 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
5062 //===----------------------------------------------------------------------===//
5063 // SystemZ ABI Implementation
5064 //===----------------------------------------------------------------------===//
5068 class SystemZABIInfo : public ABIInfo {
5070 SystemZABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
5072 bool isPromotableIntegerType(QualType Ty) const;
5073 bool isCompoundType(QualType Ty) const;
5074 bool isFPArgumentType(QualType Ty) const;
5076 ABIArgInfo classifyReturnType(QualType RetTy) const;
5077 ABIArgInfo classifyArgumentType(QualType ArgTy) const;
5079 void computeInfo(CGFunctionInfo &FI) const override {
5080 if (!getCXXABI().classifyReturnType(FI))
5081 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
5082 for (auto &I : FI.arguments())
5083 I.info = classifyArgumentType(I.type);
5086 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5087 CodeGenFunction &CGF) const override;
5090 class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
5092 SystemZTargetCodeGenInfo(CodeGenTypes &CGT)
5093 : TargetCodeGenInfo(new SystemZABIInfo(CGT)) {}
5098 bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const {
5099 // Treat an enum type as its underlying type.
5100 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5101 Ty = EnumTy->getDecl()->getIntegerType();
5103 // Promotable integer types are required to be promoted by the ABI.
5104 if (Ty->isPromotableIntegerType())
5107 // 32-bit values must also be promoted.
5108 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
5109 switch (BT->getKind()) {
5110 case BuiltinType::Int:
5111 case BuiltinType::UInt:
5119 bool SystemZABIInfo::isCompoundType(QualType Ty) const {
5120 return Ty->isAnyComplexType() || isAggregateTypeForABI(Ty);
5123 bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
5124 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
5125 switch (BT->getKind()) {
5126 case BuiltinType::Float:
5127 case BuiltinType::Double:
5133 if (const RecordType *RT = Ty->getAsStructureType()) {
5134 const RecordDecl *RD = RT->getDecl();
5137 // If this is a C++ record, check the bases first.
5138 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
5139 for (const auto &I : CXXRD->bases()) {
5140 QualType Base = I.getType();
5142 // Empty bases don't affect things either way.
5143 if (isEmptyRecord(getContext(), Base, true))
5148 Found = isFPArgumentType(Base);
5153 // Check the fields.
5154 for (const auto *FD : RD->fields()) {
5155 // Empty bitfields don't affect things either way.
5156 // Unlike isSingleElementStruct(), empty structure and array fields
5157 // do count. So do anonymous bitfields that aren't zero-sized.
5158 if (FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
5161 // Unlike isSingleElementStruct(), arrays do not count.
5162 // Nested isFPArgumentType structures still do though.
5165 Found = isFPArgumentType(FD->getType());
5170 // Unlike isSingleElementStruct(), trailing padding is allowed.
5171 // An 8-byte aligned struct s { float f; } is passed as a double.
5178 llvm::Value *SystemZABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5179 CodeGenFunction &CGF) const {
5180 // Assume that va_list type is correct; should be pointer to LLVM type:
5184 // i8 *__overflow_arg_area;
5185 // i8 *__reg_save_area;
5188 // Every argument occupies 8 bytes and is passed by preference in either
5190 Ty = CGF.getContext().getCanonicalType(Ty);
5191 ABIArgInfo AI = classifyArgumentType(Ty);
5192 bool InFPRs = isFPArgumentType(Ty);
5194 llvm::Type *APTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
5195 bool IsIndirect = AI.isIndirect();
5196 unsigned UnpaddedBitSize;
5198 APTy = llvm::PointerType::getUnqual(APTy);
5199 UnpaddedBitSize = 64;
5201 UnpaddedBitSize = getContext().getTypeSize(Ty);
5202 unsigned PaddedBitSize = 64;
5203 assert((UnpaddedBitSize <= PaddedBitSize) && "Invalid argument size.");
5205 unsigned PaddedSize = PaddedBitSize / 8;
5206 unsigned Padding = (PaddedBitSize - UnpaddedBitSize) / 8;
5208 unsigned MaxRegs, RegCountField, RegSaveIndex, RegPadding;
5210 MaxRegs = 4; // Maximum of 4 FPR arguments
5211 RegCountField = 1; // __fpr
5212 RegSaveIndex = 16; // save offset for f0
5213 RegPadding = 0; // floats are passed in the high bits of an FPR
5215 MaxRegs = 5; // Maximum of 5 GPR arguments
5216 RegCountField = 0; // __gpr
5217 RegSaveIndex = 2; // save offset for r2
5218 RegPadding = Padding; // values are passed in the low bits of a GPR
5221 llvm::Value *RegCountPtr =
5222 CGF.Builder.CreateStructGEP(VAListAddr, RegCountField, "reg_count_ptr");
5223 llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
5224 llvm::Type *IndexTy = RegCount->getType();
5225 llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
5226 llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
5229 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
5230 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
5231 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
5232 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
5234 // Emit code to load the value if it was passed in registers.
5235 CGF.EmitBlock(InRegBlock);
5237 // Work out the address of an argument register.
5238 llvm::Value *PaddedSizeV = llvm::ConstantInt::get(IndexTy, PaddedSize);
5239 llvm::Value *ScaledRegCount =
5240 CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
5241 llvm::Value *RegBase =
5242 llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize + RegPadding);
5243 llvm::Value *RegOffset =
5244 CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
5245 llvm::Value *RegSaveAreaPtr =
5246 CGF.Builder.CreateStructGEP(VAListAddr, 3, "reg_save_area_ptr");
5247 llvm::Value *RegSaveArea =
5248 CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
5249 llvm::Value *RawRegAddr =
5250 CGF.Builder.CreateGEP(RegSaveArea, RegOffset, "raw_reg_addr");
5251 llvm::Value *RegAddr =
5252 CGF.Builder.CreateBitCast(RawRegAddr, APTy, "reg_addr");
5254 // Update the register count
5255 llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
5256 llvm::Value *NewRegCount =
5257 CGF.Builder.CreateAdd(RegCount, One, "reg_count");
5258 CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
5259 CGF.EmitBranch(ContBlock);
5261 // Emit code to load the value if it was passed in memory.
5262 CGF.EmitBlock(InMemBlock);
5264 // Work out the address of a stack argument.
5265 llvm::Value *OverflowArgAreaPtr =
5266 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr");
5267 llvm::Value *OverflowArgArea =
5268 CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area");
5269 llvm::Value *PaddingV = llvm::ConstantInt::get(IndexTy, Padding);
5270 llvm::Value *RawMemAddr =
5271 CGF.Builder.CreateGEP(OverflowArgArea, PaddingV, "raw_mem_addr");
5272 llvm::Value *MemAddr =
5273 CGF.Builder.CreateBitCast(RawMemAddr, APTy, "mem_addr");
5275 // Update overflow_arg_area_ptr pointer
5276 llvm::Value *NewOverflowArgArea =
5277 CGF.Builder.CreateGEP(OverflowArgArea, PaddedSizeV, "overflow_arg_area");
5278 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
5279 CGF.EmitBranch(ContBlock);
5281 // Return the appropriate result.
5282 CGF.EmitBlock(ContBlock);
5283 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(APTy, 2, "va_arg.addr");
5284 ResAddr->addIncoming(RegAddr, InRegBlock);
5285 ResAddr->addIncoming(MemAddr, InMemBlock);
5288 return CGF.Builder.CreateLoad(ResAddr, "indirect_arg");
5293 ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
5294 if (RetTy->isVoidType())
5295 return ABIArgInfo::getIgnore();
5296 if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
5297 return ABIArgInfo::getIndirect(0);
5298 return (isPromotableIntegerType(RetTy) ?
5299 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5302 ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
5303 // Handle the generic C++ ABI.
5304 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
5305 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
5307 // Integers and enums are extended to full register width.
5308 if (isPromotableIntegerType(Ty))
5309 return ABIArgInfo::getExtend();
5311 // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
5312 uint64_t Size = getContext().getTypeSize(Ty);
5313 if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
5314 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
5316 // Handle small structures.
5317 if (const RecordType *RT = Ty->getAs<RecordType>()) {
5318 // Structures with flexible arrays have variable length, so really
5319 // fail the size test above.
5320 const RecordDecl *RD = RT->getDecl();
5321 if (RD->hasFlexibleArrayMember())
5322 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
5324 // The structure is passed as an unextended integer, a float, or a double.
5326 if (isFPArgumentType(Ty)) {
5327 assert(Size == 32 || Size == 64);
5329 PassTy = llvm::Type::getFloatTy(getVMContext());
5331 PassTy = llvm::Type::getDoubleTy(getVMContext());
5333 PassTy = llvm::IntegerType::get(getVMContext(), Size);
5334 return ABIArgInfo::getDirect(PassTy);
5337 // Non-structure compounds are passed indirectly.
5338 if (isCompoundType(Ty))
5339 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
5341 return ABIArgInfo::getDirect(nullptr);
5344 //===----------------------------------------------------------------------===//
5345 // MSP430 ABI Implementation
5346 //===----------------------------------------------------------------------===//
5350 class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
5352 MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
5353 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
5354 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5355 CodeGen::CodeGenModule &M) const override;
5360 void MSP430TargetCodeGenInfo::SetTargetAttributes(const Decl *D,
5361 llvm::GlobalValue *GV,
5362 CodeGen::CodeGenModule &M) const {
5363 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5364 if (const MSP430InterruptAttr *attr = FD->getAttr<MSP430InterruptAttr>()) {
5365 // Handle 'interrupt' attribute:
5366 llvm::Function *F = cast<llvm::Function>(GV);
5368 // Step 1: Set ISR calling convention.
5369 F->setCallingConv(llvm::CallingConv::MSP430_INTR);
5371 // Step 2: Add attributes goodness.
5372 F->addFnAttr(llvm::Attribute::NoInline);
5374 // Step 3: Emit ISR vector alias.
5375 unsigned Num = attr->getNumber() / 2;
5376 llvm::GlobalAlias::create(llvm::Function::ExternalLinkage,
5377 "__isr_" + Twine(Num), F);
5382 //===----------------------------------------------------------------------===//
5383 // MIPS ABI Implementation. This works for both little-endian and
5384 // big-endian variants.
5385 //===----------------------------------------------------------------------===//
5388 class MipsABIInfo : public ABIInfo {
5390 unsigned MinABIStackAlignInBytes, StackAlignInBytes;
5391 void CoerceToIntArgs(uint64_t TySize,
5392 SmallVectorImpl<llvm::Type *> &ArgList) const;
5393 llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
5394 llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
5395 llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
5397 MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
5398 ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
5399 StackAlignInBytes(IsO32 ? 8 : 16) {}
5401 ABIArgInfo classifyReturnType(QualType RetTy) const;
5402 ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
5403 void computeInfo(CGFunctionInfo &FI) const override;
5404 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5405 CodeGenFunction &CGF) const override;
5408 class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
5409 unsigned SizeOfUnwindException;
5411 MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
5412 : TargetCodeGenInfo(new MipsABIInfo(CGT, IsO32)),
5413 SizeOfUnwindException(IsO32 ? 24 : 32) {}
5415 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
5419 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5420 CodeGen::CodeGenModule &CGM) const override {
5421 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
5423 llvm::Function *Fn = cast<llvm::Function>(GV);
5424 if (FD->hasAttr<Mips16Attr>()) {
5425 Fn->addFnAttr("mips16");
5427 else if (FD->hasAttr<NoMips16Attr>()) {
5428 Fn->addFnAttr("nomips16");
5432 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
5433 llvm::Value *Address) const override;
5435 unsigned getSizeOfUnwindException() const override {
5436 return SizeOfUnwindException;
5441 void MipsABIInfo::CoerceToIntArgs(uint64_t TySize,
5442 SmallVectorImpl<llvm::Type *> &ArgList) const {
5443 llvm::IntegerType *IntTy =
5444 llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
5446 // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
5447 for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
5448 ArgList.push_back(IntTy);
5450 // If necessary, add one more integer type to ArgList.
5451 unsigned R = TySize % (MinABIStackAlignInBytes * 8);
5454 ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
5457 // In N32/64, an aligned double precision floating point field is passed in
5459 llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
5460 SmallVector<llvm::Type*, 8> ArgList, IntArgList;
5463 CoerceToIntArgs(TySize, ArgList);
5464 return llvm::StructType::get(getVMContext(), ArgList);
5467 if (Ty->isComplexType())
5468 return CGT.ConvertType(Ty);
5470 const RecordType *RT = Ty->getAs<RecordType>();
5472 // Unions/vectors are passed in integer registers.
5473 if (!RT || !RT->isStructureOrClassType()) {
5474 CoerceToIntArgs(TySize, ArgList);
5475 return llvm::StructType::get(getVMContext(), ArgList);
5478 const RecordDecl *RD = RT->getDecl();
5479 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
5480 assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
5482 uint64_t LastOffset = 0;
5484 llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
5486 // Iterate over fields in the struct/class and check if there are any aligned
5488 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
5489 i != e; ++i, ++idx) {
5490 const QualType Ty = i->getType();
5491 const BuiltinType *BT = Ty->getAs<BuiltinType>();
5493 if (!BT || BT->getKind() != BuiltinType::Double)
5496 uint64_t Offset = Layout.getFieldOffset(idx);
5497 if (Offset % 64) // Ignore doubles that are not aligned.
5500 // Add ((Offset - LastOffset) / 64) args of type i64.
5501 for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
5502 ArgList.push_back(I64);
5505 ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
5506 LastOffset = Offset + 64;
5509 CoerceToIntArgs(TySize - LastOffset, IntArgList);
5510 ArgList.append(IntArgList.begin(), IntArgList.end());
5512 return llvm::StructType::get(getVMContext(), ArgList);
5515 llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
5516 uint64_t Offset) const {
5517 if (OrigOffset + MinABIStackAlignInBytes > Offset)
5520 return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
5524 MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
5525 uint64_t OrigOffset = Offset;
5526 uint64_t TySize = getContext().getTypeSize(Ty);
5527 uint64_t Align = getContext().getTypeAlign(Ty) / 8;
5529 Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
5530 (uint64_t)StackAlignInBytes);
5531 unsigned CurrOffset = llvm::RoundUpToAlignment(Offset, Align);
5532 Offset = CurrOffset + llvm::RoundUpToAlignment(TySize, Align * 8) / 8;
5534 if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
5535 // Ignore empty aggregates.
5537 return ABIArgInfo::getIgnore();
5539 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
5540 Offset = OrigOffset + MinABIStackAlignInBytes;
5541 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
5544 // If we have reached here, aggregates are passed directly by coercing to
5545 // another structure type. Padding is inserted if the offset of the
5546 // aggregate is unaligned.
5547 ABIArgInfo ArgInfo =
5548 ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
5549 getPaddingType(OrigOffset, CurrOffset));
5550 ArgInfo.setInReg(true);
5554 // Treat an enum type as its underlying type.
5555 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5556 Ty = EnumTy->getDecl()->getIntegerType();
5558 // All integral types are promoted to the GPR width.
5559 if (Ty->isIntegralOrEnumerationType())
5560 return ABIArgInfo::getExtend();
5562 return ABIArgInfo::getDirect(
5563 nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset));
5567 MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
5568 const RecordType *RT = RetTy->getAs<RecordType>();
5569 SmallVector<llvm::Type*, 8> RTList;
5571 if (RT && RT->isStructureOrClassType()) {
5572 const RecordDecl *RD = RT->getDecl();
5573 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
5574 unsigned FieldCnt = Layout.getFieldCount();
5576 // N32/64 returns struct/classes in floating point registers if the
5577 // following conditions are met:
5578 // 1. The size of the struct/class is no larger than 128-bit.
5579 // 2. The struct/class has one or two fields all of which are floating
5581 // 3. The offset of the first field is zero (this follows what gcc does).
5583 // Any other composite results are returned in integer registers.
5585 if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
5586 RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
5587 for (; b != e; ++b) {
5588 const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
5590 if (!BT || !BT->isFloatingPoint())
5593 RTList.push_back(CGT.ConvertType(b->getType()));
5597 return llvm::StructType::get(getVMContext(), RTList,
5598 RD->hasAttr<PackedAttr>());
5604 CoerceToIntArgs(Size, RTList);
5605 return llvm::StructType::get(getVMContext(), RTList);
5608 ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
5609 uint64_t Size = getContext().getTypeSize(RetTy);
5611 if (RetTy->isVoidType())
5612 return ABIArgInfo::getIgnore();
5614 // O32 doesn't treat zero-sized structs differently from other structs.
5615 // However, N32/N64 ignores zero sized return values.
5616 if (!IsO32 && Size == 0)
5617 return ABIArgInfo::getIgnore();
5619 if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
5621 if (RetTy->isAnyComplexType())
5622 return ABIArgInfo::getDirect();
5624 // O32 returns integer vectors in registers and N32/N64 returns all small
5625 // aggregates in registers..
5627 (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) {
5628 ABIArgInfo ArgInfo =
5629 ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
5630 ArgInfo.setInReg(true);
5635 return ABIArgInfo::getIndirect(0);
5638 // Treat an enum type as its underlying type.
5639 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5640 RetTy = EnumTy->getDecl()->getIntegerType();
5642 return (RetTy->isPromotableIntegerType() ?
5643 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5646 void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
5647 ABIArgInfo &RetInfo = FI.getReturnInfo();
5648 if (!getCXXABI().classifyReturnType(FI))
5649 RetInfo = classifyReturnType(FI.getReturnType());
5651 // Check if a pointer to an aggregate is passed as a hidden argument.
5652 uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
5654 for (auto &I : FI.arguments())
5655 I.info = classifyArgumentType(I.type, Offset);
5658 llvm::Value* MipsABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5659 CodeGenFunction &CGF) const {
5660 llvm::Type *BP = CGF.Int8PtrTy;
5661 llvm::Type *BPP = CGF.Int8PtrPtrTy;
5663 // Integer arguments are promoted 32-bit on O32 and 64-bit on N32/N64.
5664 unsigned SlotSizeInBits = IsO32 ? 32 : 64;
5665 if (Ty->isIntegerType() &&
5666 CGF.getContext().getIntWidth(Ty) < SlotSizeInBits) {
5667 Ty = CGF.getContext().getIntTypeForBitwidth(SlotSizeInBits,
5668 Ty->isSignedIntegerType());
5671 CGBuilderTy &Builder = CGF.Builder;
5672 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
5673 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
5675 std::min(getContext().getTypeAlign(Ty) / 8, StackAlignInBytes);
5676 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
5677 llvm::Value *AddrTyped;
5678 unsigned PtrWidth = getTarget().getPointerWidth(0);
5679 llvm::IntegerType *IntTy = (PtrWidth == 32) ? CGF.Int32Ty : CGF.Int64Ty;
5681 if (TypeAlign > MinABIStackAlignInBytes) {
5682 llvm::Value *AddrAsInt = CGF.Builder.CreatePtrToInt(Addr, IntTy);
5683 llvm::Value *Inc = llvm::ConstantInt::get(IntTy, TypeAlign - 1);
5684 llvm::Value *Mask = llvm::ConstantInt::get(IntTy, -TypeAlign);
5685 llvm::Value *Add = CGF.Builder.CreateAdd(AddrAsInt, Inc);
5686 llvm::Value *And = CGF.Builder.CreateAnd(Add, Mask);
5687 AddrTyped = CGF.Builder.CreateIntToPtr(And, PTy);
5690 AddrTyped = Builder.CreateBitCast(Addr, PTy);
5692 llvm::Value *AlignedAddr = Builder.CreateBitCast(AddrTyped, BP);
5693 TypeAlign = std::max((unsigned)TypeAlign, MinABIStackAlignInBytes);
5694 unsigned ArgSizeInBits = CGF.getContext().getTypeSize(Ty);
5695 uint64_t Offset = llvm::RoundUpToAlignment(ArgSizeInBits / 8, TypeAlign);
5696 llvm::Value *NextAddr =
5697 Builder.CreateGEP(AlignedAddr, llvm::ConstantInt::get(IntTy, Offset),
5699 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
5705 MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
5706 llvm::Value *Address) const {
5707 // This information comes from gcc's implementation, which seems to
5708 // as canonical as it gets.
5710 // Everything on MIPS is 4 bytes. Double-precision FP registers
5711 // are aliased to pairs of single-precision FP registers.
5712 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
5714 // 0-31 are the general purpose registers, $0 - $31.
5715 // 32-63 are the floating-point registers, $f0 - $f31.
5716 // 64 and 65 are the multiply/divide registers, $hi and $lo.
5717 // 66 is the (notional, I think) register for signal-handler return.
5718 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
5720 // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
5721 // They are one bit wide and ignored here.
5723 // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
5724 // (coprocessor 1 is the FP unit)
5725 // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
5726 // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
5727 // 176-181 are the DSP accumulator registers.
5728 AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
5732 //===----------------------------------------------------------------------===//
5733 // TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
5734 // Currently subclassed only to implement custom OpenCL C function attribute
5736 //===----------------------------------------------------------------------===//
5740 class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
5742 TCETargetCodeGenInfo(CodeGenTypes &CGT)
5743 : DefaultTargetCodeGenInfo(CGT) {}
5745 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5746 CodeGen::CodeGenModule &M) const override;
5749 void TCETargetCodeGenInfo::SetTargetAttributes(const Decl *D,
5750 llvm::GlobalValue *GV,
5751 CodeGen::CodeGenModule &M) const {
5752 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
5755 llvm::Function *F = cast<llvm::Function>(GV);
5757 if (M.getLangOpts().OpenCL) {
5758 if (FD->hasAttr<OpenCLKernelAttr>()) {
5759 // OpenCL C Kernel functions are not subject to inlining
5760 F->addFnAttr(llvm::Attribute::NoInline);
5761 const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
5763 // Convert the reqd_work_group_size() attributes to metadata.
5764 llvm::LLVMContext &Context = F->getContext();
5765 llvm::NamedMDNode *OpenCLMetadata =
5766 M.getModule().getOrInsertNamedMetadata("opencl.kernel_wg_size_info");
5768 SmallVector<llvm::Value*, 5> Operands;
5769 Operands.push_back(F);
5771 Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty,
5772 llvm::APInt(32, Attr->getXDim())));
5773 Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty,
5774 llvm::APInt(32, Attr->getYDim())));
5775 Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty,
5776 llvm::APInt(32, Attr->getZDim())));
5778 // Add a boolean constant operand for "required" (true) or "hint" (false)
5779 // for implementing the work_group_size_hint attr later. Currently
5780 // always true as the hint is not yet implemented.
5781 Operands.push_back(llvm::ConstantInt::getTrue(Context));
5782 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
5790 //===----------------------------------------------------------------------===//
5791 // Hexagon ABI Implementation
5792 //===----------------------------------------------------------------------===//
5796 class HexagonABIInfo : public ABIInfo {
5800 HexagonABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
5804 ABIArgInfo classifyReturnType(QualType RetTy) const;
5805 ABIArgInfo classifyArgumentType(QualType RetTy) const;
5807 void computeInfo(CGFunctionInfo &FI) const override;
5809 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5810 CodeGenFunction &CGF) const override;
5813 class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
5815 HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
5816 :TargetCodeGenInfo(new HexagonABIInfo(CGT)) {}
5818 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
5825 void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
5826 if (!getCXXABI().classifyReturnType(FI))
5827 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
5828 for (auto &I : FI.arguments())
5829 I.info = classifyArgumentType(I.type);
5832 ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty) const {
5833 if (!isAggregateTypeForABI(Ty)) {
5834 // Treat an enum type as its underlying type.
5835 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5836 Ty = EnumTy->getDecl()->getIntegerType();
5838 return (Ty->isPromotableIntegerType() ?
5839 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5842 // Ignore empty records.
5843 if (isEmptyRecord(getContext(), Ty, true))
5844 return ABIArgInfo::getIgnore();
5846 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
5847 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
5849 uint64_t Size = getContext().getTypeSize(Ty);
5851 return ABIArgInfo::getIndirect(0, /*ByVal=*/true);
5852 // Pass in the smallest viable integer type.
5854 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
5856 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
5858 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5860 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
5863 ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
5864 if (RetTy->isVoidType())
5865 return ABIArgInfo::getIgnore();
5867 // Large vector types should be returned via memory.
5868 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 64)
5869 return ABIArgInfo::getIndirect(0);
5871 if (!isAggregateTypeForABI(RetTy)) {
5872 // Treat an enum type as its underlying type.
5873 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5874 RetTy = EnumTy->getDecl()->getIntegerType();
5876 return (RetTy->isPromotableIntegerType() ?
5877 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5880 if (isEmptyRecord(getContext(), RetTy, true))
5881 return ABIArgInfo::getIgnore();
5883 // Aggregates <= 8 bytes are returned in r0; other aggregates
5884 // are returned indirectly.
5885 uint64_t Size = getContext().getTypeSize(RetTy);
5887 // Return in the smallest viable integer type.
5889 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
5891 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5893 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
5894 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
5897 return ABIArgInfo::getIndirect(0, /*ByVal=*/true);
5900 llvm::Value *HexagonABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5901 CodeGenFunction &CGF) const {
5902 // FIXME: Need to handle alignment
5903 llvm::Type *BPP = CGF.Int8PtrPtrTy;
5905 CGBuilderTy &Builder = CGF.Builder;
5906 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
5908 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
5910 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
5911 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
5914 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 4);
5915 llvm::Value *NextAddr =
5916 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
5918 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
5924 //===----------------------------------------------------------------------===//
5925 // SPARC v9 ABI Implementation.
5926 // Based on the SPARC Compliance Definition version 2.4.1.
5928 // Function arguments a mapped to a nominal "parameter array" and promoted to
5929 // registers depending on their type. Each argument occupies 8 or 16 bytes in
5930 // the array, structs larger than 16 bytes are passed indirectly.
5932 // One case requires special care:
5939 // When a struct mixed is passed by value, it only occupies 8 bytes in the
5940 // parameter array, but the int is passed in an integer register, and the float
5941 // is passed in a floating point register. This is represented as two arguments
5942 // with the LLVM IR inreg attribute:
5944 // declare void f(i32 inreg %i, float inreg %f)
5946 // The code generator will only allocate 4 bytes from the parameter array for
5947 // the inreg arguments. All other arguments are allocated a multiple of 8
5951 class SparcV9ABIInfo : public ABIInfo {
5953 SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
5956 ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
5957 void computeInfo(CGFunctionInfo &FI) const override;
5958 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5959 CodeGenFunction &CGF) const override;
5961 // Coercion type builder for structs passed in registers. The coercion type
5962 // serves two purposes:
5964 // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
5966 // 2. Expose aligned floating point elements as first-level elements, so the
5967 // code generator knows to pass them in floating point registers.
5969 // We also compute the InReg flag which indicates that the struct contains
5970 // aligned 32-bit floats.
5972 struct CoerceBuilder {
5973 llvm::LLVMContext &Context;
5974 const llvm::DataLayout &DL;
5975 SmallVector<llvm::Type*, 8> Elems;
5979 CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
5980 : Context(c), DL(dl), Size(0), InReg(false) {}
5982 // Pad Elems with integers until Size is ToSize.
5983 void pad(uint64_t ToSize) {
5984 assert(ToSize >= Size && "Cannot remove elements");
5988 // Finish the current 64-bit word.
5989 uint64_t Aligned = llvm::RoundUpToAlignment(Size, 64);
5990 if (Aligned > Size && Aligned <= ToSize) {
5991 Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
5995 // Add whole 64-bit words.
5996 while (Size + 64 <= ToSize) {
5997 Elems.push_back(llvm::Type::getInt64Ty(Context));
6001 // Final in-word padding.
6002 if (Size < ToSize) {
6003 Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
6008 // Add a floating point element at Offset.
6009 void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
6010 // Unaligned floats are treated as integers.
6013 // The InReg flag is only required if there are any floats < 64 bits.
6017 Elems.push_back(Ty);
6018 Size = Offset + Bits;
6021 // Add a struct type to the coercion type, starting at Offset (in bits).
6022 void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
6023 const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
6024 for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
6025 llvm::Type *ElemTy = StrTy->getElementType(i);
6026 uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
6027 switch (ElemTy->getTypeID()) {
6028 case llvm::Type::StructTyID:
6029 addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
6031 case llvm::Type::FloatTyID:
6032 addFloat(ElemOffset, ElemTy, 32);
6034 case llvm::Type::DoubleTyID:
6035 addFloat(ElemOffset, ElemTy, 64);
6037 case llvm::Type::FP128TyID:
6038 addFloat(ElemOffset, ElemTy, 128);
6040 case llvm::Type::PointerTyID:
6041 if (ElemOffset % 64 == 0) {
6043 Elems.push_back(ElemTy);
6053 // Check if Ty is a usable substitute for the coercion type.
6054 bool isUsableType(llvm::StructType *Ty) const {
6055 if (Ty->getNumElements() != Elems.size())
6057 for (unsigned i = 0, e = Elems.size(); i != e; ++i)
6058 if (Elems[i] != Ty->getElementType(i))
6063 // Get the coercion type as a literal struct type.
6064 llvm::Type *getType() const {
6065 if (Elems.size() == 1)
6066 return Elems.front();
6068 return llvm::StructType::get(Context, Elems);
6072 } // end anonymous namespace
6075 SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
6076 if (Ty->isVoidType())
6077 return ABIArgInfo::getIgnore();
6079 uint64_t Size = getContext().getTypeSize(Ty);
6081 // Anything too big to fit in registers is passed with an explicit indirect
6082 // pointer / sret pointer.
6083 if (Size > SizeLimit)
6084 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
6086 // Treat an enum type as its underlying type.
6087 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6088 Ty = EnumTy->getDecl()->getIntegerType();
6090 // Integer types smaller than a register are extended.
6091 if (Size < 64 && Ty->isIntegerType())
6092 return ABIArgInfo::getExtend();
6094 // Other non-aggregates go in registers.
6095 if (!isAggregateTypeForABI(Ty))
6096 return ABIArgInfo::getDirect();
6098 // If a C++ object has either a non-trivial copy constructor or a non-trivial
6099 // destructor, it is passed with an explicit indirect pointer / sret pointer.
6100 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
6101 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
6103 // This is a small aggregate type that should be passed in registers.
6104 // Build a coercion type from the LLVM struct type.
6105 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
6107 return ABIArgInfo::getDirect();
6109 CoerceBuilder CB(getVMContext(), getDataLayout());
6110 CB.addStruct(0, StrTy);
6111 CB.pad(llvm::RoundUpToAlignment(CB.DL.getTypeSizeInBits(StrTy), 64));
6113 // Try to use the original type for coercion.
6114 llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
6117 return ABIArgInfo::getDirectInReg(CoerceTy);
6119 return ABIArgInfo::getDirect(CoerceTy);
6122 llvm::Value *SparcV9ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
6123 CodeGenFunction &CGF) const {
6124 ABIArgInfo AI = classifyType(Ty, 16 * 8);
6125 llvm::Type *ArgTy = CGT.ConvertType(Ty);
6126 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
6127 AI.setCoerceToType(ArgTy);
6129 llvm::Type *BPP = CGF.Int8PtrPtrTy;
6130 CGBuilderTy &Builder = CGF.Builder;
6131 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
6132 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
6133 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
6134 llvm::Value *ArgAddr;
6137 switch (AI.getKind()) {
6138 case ABIArgInfo::Expand:
6139 case ABIArgInfo::InAlloca:
6140 llvm_unreachable("Unsupported ABI kind for va_arg");
6142 case ABIArgInfo::Extend:
6145 .CreateConstGEP1_32(Addr, 8 - getDataLayout().getTypeAllocSize(ArgTy),
6149 case ABIArgInfo::Direct:
6150 Stride = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
6154 case ABIArgInfo::Indirect:
6156 ArgAddr = Builder.CreateBitCast(Addr,
6157 llvm::PointerType::getUnqual(ArgPtrTy),
6159 ArgAddr = Builder.CreateLoad(ArgAddr, "indirect.arg");
6162 case ABIArgInfo::Ignore:
6163 return llvm::UndefValue::get(ArgPtrTy);
6167 Addr = Builder.CreateConstGEP1_32(Addr, Stride, "ap.next");
6168 Builder.CreateStore(Addr, VAListAddrAsBPP);
6170 return Builder.CreatePointerCast(ArgAddr, ArgPtrTy, "arg.addr");
6173 void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
6174 FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
6175 for (auto &I : FI.arguments())
6176 I.info = classifyType(I.type, 16 * 8);
6180 class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
6182 SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
6183 : TargetCodeGenInfo(new SparcV9ABIInfo(CGT)) {}
6185 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
6189 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
6190 llvm::Value *Address) const override;
6192 } // end anonymous namespace
6195 SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
6196 llvm::Value *Address) const {
6197 // This is calculated from the LLVM and GCC tables and verified
6198 // against gcc output. AFAIK all ABIs use the same encoding.
6200 CodeGen::CGBuilderTy &Builder = CGF.Builder;
6202 llvm::IntegerType *i8 = CGF.Int8Ty;
6203 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
6204 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
6206 // 0-31: the 8-byte general-purpose registers
6207 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
6209 // 32-63: f0-31, the 4-byte floating-point registers
6210 AssignToArrayRange(Builder, Address, Four8, 32, 63);
6220 AssignToArrayRange(Builder, Address, Eight8, 64, 71);
6222 // 72-87: d0-15, the 8-byte floating-point registers
6223 AssignToArrayRange(Builder, Address, Eight8, 72, 87);
6229 //===----------------------------------------------------------------------===//
6230 // XCore ABI Implementation
6231 //===----------------------------------------------------------------------===//
6235 /// A SmallStringEnc instance is used to build up the TypeString by passing
6236 /// it by reference between functions that append to it.
6237 typedef llvm::SmallString<128> SmallStringEnc;
6239 /// TypeStringCache caches the meta encodings of Types.
6241 /// The reason for caching TypeStrings is two fold:
6242 /// 1. To cache a type's encoding for later uses;
6243 /// 2. As a means to break recursive member type inclusion.
6245 /// A cache Entry can have a Status of:
6246 /// NonRecursive: The type encoding is not recursive;
6247 /// Recursive: The type encoding is recursive;
6248 /// Incomplete: An incomplete TypeString;
6249 /// IncompleteUsed: An incomplete TypeString that has been used in a
6250 /// Recursive type encoding.
6252 /// A NonRecursive entry will have all of its sub-members expanded as fully
6253 /// as possible. Whilst it may contain types which are recursive, the type
6254 /// itself is not recursive and thus its encoding may be safely used whenever
6255 /// the type is encountered.
6257 /// A Recursive entry will have all of its sub-members expanded as fully as
6258 /// possible. The type itself is recursive and it may contain other types which
6259 /// are recursive. The Recursive encoding must not be used during the expansion
6260 /// of a recursive type's recursive branch. For simplicity the code uses
6261 /// IncompleteCount to reject all usage of Recursive encodings for member types.
6263 /// An Incomplete entry is always a RecordType and only encodes its
6264 /// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and
6265 /// are placed into the cache during type expansion as a means to identify and
6266 /// handle recursive inclusion of types as sub-members. If there is recursion
6267 /// the entry becomes IncompleteUsed.
6269 /// During the expansion of a RecordType's members:
6271 /// If the cache contains a NonRecursive encoding for the member type, the
6272 /// cached encoding is used;
6274 /// If the cache contains a Recursive encoding for the member type, the
6275 /// cached encoding is 'Swapped' out, as it may be incorrect, and...
6277 /// If the member is a RecordType, an Incomplete encoding is placed into the
6278 /// cache to break potential recursive inclusion of itself as a sub-member;
6280 /// Once a member RecordType has been expanded, its temporary incomplete
6281 /// entry is removed from the cache. If a Recursive encoding was swapped out
6282 /// it is swapped back in;
6284 /// If an incomplete entry is used to expand a sub-member, the incomplete
6285 /// entry is marked as IncompleteUsed. The cache keeps count of how many
6286 /// IncompleteUsed entries it currently contains in IncompleteUsedCount;
6288 /// If a member's encoding is found to be a NonRecursive or Recursive viz:
6289 /// IncompleteUsedCount==0, the member's encoding is added to the cache.
6290 /// Else the member is part of a recursive type and thus the recursion has
6291 /// been exited too soon for the encoding to be correct for the member.
6293 class TypeStringCache {
6294 enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed};
6296 std::string Str; // The encoded TypeString for the type.
6297 enum Status State; // Information about the encoding in 'Str'.
6298 std::string Swapped; // A temporary place holder for a Recursive encoding
6299 // during the expansion of RecordType's members.
6301 std::map<const IdentifierInfo *, struct Entry> Map;
6302 unsigned IncompleteCount; // Number of Incomplete entries in the Map.
6303 unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map.
6305 TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {};
6306 void addIncomplete(const IdentifierInfo *ID, std::string StubEnc);
6307 bool removeIncomplete(const IdentifierInfo *ID);
6308 void addIfComplete(const IdentifierInfo *ID, StringRef Str,
6310 StringRef lookupStr(const IdentifierInfo *ID);
6313 /// TypeString encodings for enum & union fields must be order.
6314 /// FieldEncoding is a helper for this ordering process.
6315 class FieldEncoding {
6319 FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {};
6320 StringRef str() {return Enc.c_str();};
6321 bool operator<(const FieldEncoding &rhs) const {
6322 if (HasName != rhs.HasName) return HasName;
6323 return Enc < rhs.Enc;
6327 class XCoreABIInfo : public DefaultABIInfo {
6329 XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
6330 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
6331 CodeGenFunction &CGF) const override;
6334 class XCoreTargetCodeGenInfo : public TargetCodeGenInfo {
6335 mutable TypeStringCache TSC;
6337 XCoreTargetCodeGenInfo(CodeGenTypes &CGT)
6338 :TargetCodeGenInfo(new XCoreABIInfo(CGT)) {}
6339 void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
6340 CodeGen::CodeGenModule &M) const override;
6343 } // End anonymous namespace.
6345 llvm::Value *XCoreABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
6346 CodeGenFunction &CGF) const {
6347 CGBuilderTy &Builder = CGF.Builder;
6350 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr,
6352 llvm::Value *AP = Builder.CreateLoad(VAListAddrAsBPP);
6354 // Handle the argument.
6355 ABIArgInfo AI = classifyArgumentType(Ty);
6356 llvm::Type *ArgTy = CGT.ConvertType(Ty);
6357 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
6358 AI.setCoerceToType(ArgTy);
6359 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
6361 uint64_t ArgSize = 0;
6362 switch (AI.getKind()) {
6363 case ABIArgInfo::Expand:
6364 case ABIArgInfo::InAlloca:
6365 llvm_unreachable("Unsupported ABI kind for va_arg");
6366 case ABIArgInfo::Ignore:
6367 Val = llvm::UndefValue::get(ArgPtrTy);
6370 case ABIArgInfo::Extend:
6371 case ABIArgInfo::Direct:
6372 Val = Builder.CreatePointerCast(AP, ArgPtrTy);
6373 ArgSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
6377 case ABIArgInfo::Indirect:
6378 llvm::Value *ArgAddr;
6379 ArgAddr = Builder.CreateBitCast(AP, llvm::PointerType::getUnqual(ArgPtrTy));
6380 ArgAddr = Builder.CreateLoad(ArgAddr);
6381 Val = Builder.CreatePointerCast(ArgAddr, ArgPtrTy);
6386 // Increment the VAList.
6388 llvm::Value *APN = Builder.CreateConstGEP1_32(AP, ArgSize);
6389 Builder.CreateStore(APN, VAListAddrAsBPP);
6394 /// During the expansion of a RecordType, an incomplete TypeString is placed
6395 /// into the cache as a means to identify and break recursion.
6396 /// If there is a Recursive encoding in the cache, it is swapped out and will
6397 /// be reinserted by removeIncomplete().
6398 /// All other types of encoding should have been used rather than arriving here.
6399 void TypeStringCache::addIncomplete(const IdentifierInfo *ID,
6400 std::string StubEnc) {
6404 assert( (E.Str.empty() || E.State == Recursive) &&
6405 "Incorrectly use of addIncomplete");
6406 assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()");
6407 E.Swapped.swap(E.Str); // swap out the Recursive
6408 E.Str.swap(StubEnc);
6409 E.State = Incomplete;
6413 /// Once the RecordType has been expanded, the temporary incomplete TypeString
6414 /// must be removed from the cache.
6415 /// If a Recursive was swapped out by addIncomplete(), it will be replaced.
6416 /// Returns true if the RecordType was defined recursively.
6417 bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) {
6420 auto I = Map.find(ID);
6421 assert(I != Map.end() && "Entry not present");
6422 Entry &E = I->second;
6423 assert( (E.State == Incomplete ||
6424 E.State == IncompleteUsed) &&
6425 "Entry must be an incomplete type");
6426 bool IsRecursive = false;
6427 if (E.State == IncompleteUsed) {
6428 // We made use of our Incomplete encoding, thus we are recursive.
6430 --IncompleteUsedCount;
6432 if (E.Swapped.empty())
6435 // Swap the Recursive back.
6436 E.Swapped.swap(E.Str);
6438 E.State = Recursive;
6444 /// Add the encoded TypeString to the cache only if it is NonRecursive or
6445 /// Recursive (viz: all sub-members were expanded as fully as possible).
6446 void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str,
6448 if (!ID || IncompleteUsedCount)
6449 return; // No key or it is is an incomplete sub-type so don't add.
6451 if (IsRecursive && !E.Str.empty()) {
6452 assert(E.State==Recursive && E.Str.size() == Str.size() &&
6453 "This is not the same Recursive entry");
6454 // The parent container was not recursive after all, so we could have used
6455 // this Recursive sub-member entry after all, but we assumed the worse when
6456 // we started viz: IncompleteCount!=0.
6459 assert(E.Str.empty() && "Entry already present");
6461 E.State = IsRecursive? Recursive : NonRecursive;
6464 /// Return a cached TypeString encoding for the ID. If there isn't one, or we
6465 /// are recursively expanding a type (IncompleteCount != 0) and the cached
6466 /// encoding is Recursive, return an empty StringRef.
6467 StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) {
6469 return StringRef(); // We have no key.
6470 auto I = Map.find(ID);
6472 return StringRef(); // We have no encoding.
6473 Entry &E = I->second;
6474 if (E.State == Recursive && IncompleteCount)
6475 return StringRef(); // We don't use Recursive encodings for member types.
6477 if (E.State == Incomplete) {
6478 // The incomplete type is being used to break out of recursion.
6479 E.State = IncompleteUsed;
6480 ++IncompleteUsedCount;
6482 return E.Str.c_str();
6485 /// The XCore ABI includes a type information section that communicates symbol
6486 /// type information to the linker. The linker uses this information to verify
6487 /// safety/correctness of things such as array bound and pointers et al.
6488 /// The ABI only requires C (and XC) language modules to emit TypeStrings.
6489 /// This type information (TypeString) is emitted into meta data for all global
6490 /// symbols: definitions, declarations, functions & variables.
6492 /// The TypeString carries type, qualifier, name, size & value details.
6493 /// Please see 'Tools Development Guide' section 2.16.2 for format details:
6494 /// <https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf>
6495 /// The output is tested by test/CodeGen/xcore-stringtype.c.
6497 static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
6498 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC);
6500 /// XCore uses emitTargetMD to emit TypeString metadata for global symbols.
6501 void XCoreTargetCodeGenInfo::emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
6502 CodeGen::CodeGenModule &CGM) const {
6504 if (getTypeString(Enc, D, CGM, TSC)) {
6505 llvm::LLVMContext &Ctx = CGM.getModule().getContext();
6506 llvm::SmallVector<llvm::Value *, 2> MDVals;
6507 MDVals.push_back(GV);
6508 MDVals.push_back(llvm::MDString::get(Ctx, Enc.str()));
6509 llvm::NamedMDNode *MD =
6510 CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings");
6511 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
6515 static bool appendType(SmallStringEnc &Enc, QualType QType,
6516 const CodeGen::CodeGenModule &CGM,
6517 TypeStringCache &TSC);
6519 /// Helper function for appendRecordType().
6520 /// Builds a SmallVector containing the encoded field types in declaration order.
6521 static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE,
6522 const RecordDecl *RD,
6523 const CodeGen::CodeGenModule &CGM,
6524 TypeStringCache &TSC) {
6525 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
6529 Enc += I->getName();
6531 if (I->isBitField()) {
6533 llvm::raw_svector_ostream OS(Enc);
6535 OS << I->getBitWidthValue(CGM.getContext());
6539 if (!appendType(Enc, I->getType(), CGM, TSC))
6541 if (I->isBitField())
6544 FE.push_back(FieldEncoding(!I->getName().empty(), Enc));
6549 /// Appends structure and union types to Enc and adds encoding to cache.
6550 /// Recursively calls appendType (via extractFieldType) for each field.
6551 /// Union types have their fields ordered according to the ABI.
6552 static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT,
6553 const CodeGen::CodeGenModule &CGM,
6554 TypeStringCache &TSC, const IdentifierInfo *ID) {
6555 // Append the cached TypeString if we have one.
6556 StringRef TypeString = TSC.lookupStr(ID);
6557 if (!TypeString.empty()) {
6562 // Start to emit an incomplete TypeString.
6563 size_t Start = Enc.size();
6564 Enc += (RT->isUnionType()? 'u' : 's');
6567 Enc += ID->getName();
6570 // We collect all encoded fields and order as necessary.
6571 bool IsRecursive = false;
6572 const RecordDecl *RD = RT->getDecl()->getDefinition();
6573 if (RD && !RD->field_empty()) {
6574 // An incomplete TypeString stub is placed in the cache for this RecordType
6575 // so that recursive calls to this RecordType will use it whilst building a
6576 // complete TypeString for this RecordType.
6577 SmallVector<FieldEncoding, 16> FE;
6578 std::string StubEnc(Enc.substr(Start).str());
6579 StubEnc += '}'; // StubEnc now holds a valid incomplete TypeString.
6580 TSC.addIncomplete(ID, std::move(StubEnc));
6581 if (!extractFieldType(FE, RD, CGM, TSC)) {
6582 (void) TSC.removeIncomplete(ID);
6585 IsRecursive = TSC.removeIncomplete(ID);
6586 // The ABI requires unions to be sorted but not structures.
6587 // See FieldEncoding::operator< for sort algorithm.
6588 if (RT->isUnionType())
6589 std::sort(FE.begin(), FE.end());
6590 // We can now complete the TypeString.
6591 unsigned E = FE.size();
6592 for (unsigned I = 0; I != E; ++I) {
6599 TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive);
6603 /// Appends enum types to Enc and adds the encoding to the cache.
6604 static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET,
6605 TypeStringCache &TSC,
6606 const IdentifierInfo *ID) {
6607 // Append the cached TypeString if we have one.
6608 StringRef TypeString = TSC.lookupStr(ID);
6609 if (!TypeString.empty()) {
6614 size_t Start = Enc.size();
6617 Enc += ID->getName();
6620 // We collect all encoded enumerations and order them alphanumerically.
6621 if (const EnumDecl *ED = ET->getDecl()->getDefinition()) {
6622 SmallVector<FieldEncoding, 16> FE;
6623 for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E;
6625 SmallStringEnc EnumEnc;
6627 EnumEnc += I->getName();
6629 I->getInitVal().toString(EnumEnc);
6631 FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc));
6633 std::sort(FE.begin(), FE.end());
6634 unsigned E = FE.size();
6635 for (unsigned I = 0; I != E; ++I) {
6642 TSC.addIfComplete(ID, Enc.substr(Start), false);
6646 /// Appends type's qualifier to Enc.
6647 /// This is done prior to appending the type's encoding.
6648 static void appendQualifier(SmallStringEnc &Enc, QualType QT) {
6649 // Qualifiers are emitted in alphabetical order.
6650 static const char *Table[] = {"","c:","r:","cr:","v:","cv:","rv:","crv:"};
6652 if (QT.isConstQualified())
6654 if (QT.isRestrictQualified())
6656 if (QT.isVolatileQualified())
6658 Enc += Table[Lookup];
6661 /// Appends built-in types to Enc.
6662 static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) {
6663 const char *EncType;
6664 switch (BT->getKind()) {
6665 case BuiltinType::Void:
6668 case BuiltinType::Bool:
6671 case BuiltinType::Char_U:
6674 case BuiltinType::UChar:
6677 case BuiltinType::SChar:
6680 case BuiltinType::UShort:
6683 case BuiltinType::Short:
6686 case BuiltinType::UInt:
6689 case BuiltinType::Int:
6692 case BuiltinType::ULong:
6695 case BuiltinType::Long:
6698 case BuiltinType::ULongLong:
6701 case BuiltinType::LongLong:
6704 case BuiltinType::Float:
6707 case BuiltinType::Double:
6710 case BuiltinType::LongDouble:
6720 /// Appends a pointer encoding to Enc before calling appendType for the pointee.
6721 static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT,
6722 const CodeGen::CodeGenModule &CGM,
6723 TypeStringCache &TSC) {
6725 if (!appendType(Enc, PT->getPointeeType(), CGM, TSC))
6731 /// Appends array encoding to Enc before calling appendType for the element.
6732 static bool appendArrayType(SmallStringEnc &Enc, QualType QT,
6733 const ArrayType *AT,
6734 const CodeGen::CodeGenModule &CGM,
6735 TypeStringCache &TSC, StringRef NoSizeEnc) {
6736 if (AT->getSizeModifier() != ArrayType::Normal)
6739 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
6740 CAT->getSize().toStringUnsigned(Enc);
6742 Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "".
6744 // The Qualifiers should be attached to the type rather than the array.
6745 appendQualifier(Enc, QT);
6746 if (!appendType(Enc, AT->getElementType(), CGM, TSC))
6752 /// Appends a function encoding to Enc, calling appendType for the return type
6753 /// and the arguments.
6754 static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT,
6755 const CodeGen::CodeGenModule &CGM,
6756 TypeStringCache &TSC) {
6758 if (!appendType(Enc, FT->getReturnType(), CGM, TSC))
6761 if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) {
6762 // N.B. we are only interested in the adjusted param types.
6763 auto I = FPT->param_type_begin();
6764 auto E = FPT->param_type_end();
6767 if (!appendType(Enc, *I, CGM, TSC))
6773 if (FPT->isVariadic())
6776 if (FPT->isVariadic())
6786 /// Handles the type's qualifier before dispatching a call to handle specific
6788 static bool appendType(SmallStringEnc &Enc, QualType QType,
6789 const CodeGen::CodeGenModule &CGM,
6790 TypeStringCache &TSC) {
6792 QualType QT = QType.getCanonicalType();
6794 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe())
6795 // The Qualifiers should be attached to the type rather than the array.
6796 // Thus we don't call appendQualifier() here.
6797 return appendArrayType(Enc, QT, AT, CGM, TSC, "");
6799 appendQualifier(Enc, QT);
6801 if (const BuiltinType *BT = QT->getAs<BuiltinType>())
6802 return appendBuiltinType(Enc, BT);
6804 if (const PointerType *PT = QT->getAs<PointerType>())
6805 return appendPointerType(Enc, PT, CGM, TSC);
6807 if (const EnumType *ET = QT->getAs<EnumType>())
6808 return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier());
6810 if (const RecordType *RT = QT->getAsStructureType())
6811 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
6813 if (const RecordType *RT = QT->getAsUnionType())
6814 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
6816 if (const FunctionType *FT = QT->getAs<FunctionType>())
6817 return appendFunctionType(Enc, FT, CGM, TSC);
6822 static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
6823 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC) {
6827 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6828 if (FD->getLanguageLinkage() != CLanguageLinkage)
6830 return appendType(Enc, FD->getType(), CGM, TSC);
6833 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
6834 if (VD->getLanguageLinkage() != CLanguageLinkage)
6836 QualType QT = VD->getType().getCanonicalType();
6837 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) {
6838 // Global ArrayTypes are given a size of '*' if the size is unknown.
6839 // The Qualifiers should be attached to the type rather than the array.
6840 // Thus we don't call appendQualifier() here.
6841 return appendArrayType(Enc, QT, AT, CGM, TSC, "*");
6843 return appendType(Enc, QT, CGM, TSC);
6849 //===----------------------------------------------------------------------===//
6851 //===----------------------------------------------------------------------===//
6853 const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
6854 if (TheTargetCodeGenInfo)
6855 return *TheTargetCodeGenInfo;
6857 const llvm::Triple &Triple = getTarget().getTriple();
6858 switch (Triple.getArch()) {
6860 return *(TheTargetCodeGenInfo = new DefaultTargetCodeGenInfo(Types));
6862 case llvm::Triple::le32:
6863 return *(TheTargetCodeGenInfo = new PNaClTargetCodeGenInfo(Types));
6864 case llvm::Triple::mips:
6865 case llvm::Triple::mipsel:
6866 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, true));
6868 case llvm::Triple::mips64:
6869 case llvm::Triple::mips64el:
6870 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, false));
6872 case llvm::Triple::aarch64:
6873 case llvm::Triple::aarch64_be:
6874 case llvm::Triple::arm64:
6875 case llvm::Triple::arm64_be: {
6876 AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS;
6877 if (getTarget().getABI() == "darwinpcs")
6878 Kind = AArch64ABIInfo::DarwinPCS;
6880 return *(TheTargetCodeGenInfo = new AArch64TargetCodeGenInfo(Types, Kind));
6883 case llvm::Triple::arm:
6884 case llvm::Triple::armeb:
6885 case llvm::Triple::thumb:
6886 case llvm::Triple::thumbeb:
6888 ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
6889 if (getTarget().getABI() == "apcs-gnu")
6890 Kind = ARMABIInfo::APCS;
6891 else if (CodeGenOpts.FloatABI == "hard" ||
6892 (CodeGenOpts.FloatABI != "soft" &&
6893 Triple.getEnvironment() == llvm::Triple::GNUEABIHF))
6894 Kind = ARMABIInfo::AAPCS_VFP;
6896 switch (Triple.getOS()) {
6897 case llvm::Triple::NaCl:
6898 return *(TheTargetCodeGenInfo =
6899 new NaClARMTargetCodeGenInfo(Types, Kind));
6901 return *(TheTargetCodeGenInfo =
6902 new ARMTargetCodeGenInfo(Types, Kind));
6906 case llvm::Triple::ppc:
6907 return *(TheTargetCodeGenInfo = new PPC32TargetCodeGenInfo(Types));
6908 case llvm::Triple::ppc64:
6909 if (Triple.isOSBinFormatELF()) {
6910 // FIXME: Should be switchable via command-line option.
6911 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1;
6912 return *(TheTargetCodeGenInfo =
6913 new PPC64_SVR4_TargetCodeGenInfo(Types, Kind));
6915 return *(TheTargetCodeGenInfo = new PPC64TargetCodeGenInfo(Types));
6916 case llvm::Triple::ppc64le: {
6917 assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
6918 // FIXME: Should be switchable via command-line option.
6919 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2;
6920 return *(TheTargetCodeGenInfo =
6921 new PPC64_SVR4_TargetCodeGenInfo(Types, Kind));
6924 case llvm::Triple::nvptx:
6925 case llvm::Triple::nvptx64:
6926 return *(TheTargetCodeGenInfo = new NVPTXTargetCodeGenInfo(Types));
6928 case llvm::Triple::msp430:
6929 return *(TheTargetCodeGenInfo = new MSP430TargetCodeGenInfo(Types));
6931 case llvm::Triple::systemz:
6932 return *(TheTargetCodeGenInfo = new SystemZTargetCodeGenInfo(Types));
6934 case llvm::Triple::tce:
6935 return *(TheTargetCodeGenInfo = new TCETargetCodeGenInfo(Types));
6937 case llvm::Triple::x86: {
6938 bool IsDarwinVectorABI = Triple.isOSDarwin();
6939 bool IsSmallStructInRegABI =
6940 X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
6941 bool IsWin32FloatStructABI = Triple.isWindowsMSVCEnvironment();
6943 if (Triple.getOS() == llvm::Triple::Win32) {
6944 return *(TheTargetCodeGenInfo =
6945 new WinX86_32TargetCodeGenInfo(Types,
6946 IsDarwinVectorABI, IsSmallStructInRegABI,
6947 IsWin32FloatStructABI,
6948 CodeGenOpts.NumRegisterParameters));
6950 return *(TheTargetCodeGenInfo =
6951 new X86_32TargetCodeGenInfo(Types,
6952 IsDarwinVectorABI, IsSmallStructInRegABI,
6953 IsWin32FloatStructABI,
6954 CodeGenOpts.NumRegisterParameters));
6958 case llvm::Triple::x86_64: {
6959 bool HasAVX = getTarget().getABI() == "avx";
6961 switch (Triple.getOS()) {
6962 case llvm::Triple::Win32:
6963 return *(TheTargetCodeGenInfo = new WinX86_64TargetCodeGenInfo(Types));
6964 case llvm::Triple::NaCl:
6965 return *(TheTargetCodeGenInfo = new NaClX86_64TargetCodeGenInfo(Types,
6968 return *(TheTargetCodeGenInfo = new X86_64TargetCodeGenInfo(Types,
6972 case llvm::Triple::hexagon:
6973 return *(TheTargetCodeGenInfo = new HexagonTargetCodeGenInfo(Types));
6974 case llvm::Triple::sparcv9:
6975 return *(TheTargetCodeGenInfo = new SparcV9TargetCodeGenInfo(Types));
6976 case llvm::Triple::xcore:
6977 return *(TheTargetCodeGenInfo = new XCoreTargetCodeGenInfo(Types));