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"
19 #include "CodeGenFunction.h"
20 #include "clang/AST/RecordLayout.h"
21 #include "clang/CodeGen/CGFunctionInfo.h"
22 #include "clang/CodeGen/SwiftCallingConv.h"
23 #include "clang/Frontend/CodeGenOptions.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/Triple.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/Type.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include <algorithm> // std::sort
31 using namespace clang;
32 using namespace CodeGen;
34 // Helper for coercing an aggregate argument or return value into an integer
35 // array of the same size (including padding) and alignment. This alternate
36 // coercion happens only for the RenderScript ABI and can be removed after
37 // runtimes that rely on it are no longer supported.
39 // RenderScript assumes that the size of the argument / return value in the IR
40 // is the same as the size of the corresponding qualified type. This helper
41 // coerces the aggregate type into an array of the same size (including
42 // padding). This coercion is used in lieu of expansion of struct members or
43 // other canonical coercions that return a coerced-type of larger size.
45 // Ty - The argument / return value type
46 // Context - The associated ASTContext
47 // LLVMContext - The associated LLVMContext
48 static ABIArgInfo coerceToIntArray(QualType Ty,
50 llvm::LLVMContext &LLVMContext) {
51 // Alignment and Size are measured in bits.
52 const uint64_t Size = Context.getTypeSize(Ty);
53 const uint64_t Alignment = Context.getTypeAlign(Ty);
54 llvm::Type *IntType = llvm::Type::getIntNTy(LLVMContext, Alignment);
55 const uint64_t NumElements = (Size + Alignment - 1) / Alignment;
56 return ABIArgInfo::getDirect(llvm::ArrayType::get(IntType, NumElements));
59 static void AssignToArrayRange(CodeGen::CGBuilderTy &Builder,
64 // Alternatively, we could emit this as a loop in the source.
65 for (unsigned I = FirstIndex; I <= LastIndex; ++I) {
67 Builder.CreateConstInBoundsGEP1_32(Builder.getInt8Ty(), Array, I);
68 Builder.CreateAlignedStore(Value, Cell, CharUnits::One());
72 static bool isAggregateTypeForABI(QualType T) {
73 return !CodeGenFunction::hasScalarEvaluationKind(T) ||
74 T->isMemberFunctionPointerType();
78 ABIInfo::getNaturalAlignIndirect(QualType Ty, bool ByRef, bool Realign,
79 llvm::Type *Padding) const {
80 return ABIArgInfo::getIndirect(getContext().getTypeAlignInChars(Ty),
81 ByRef, Realign, Padding);
85 ABIInfo::getNaturalAlignIndirectInReg(QualType Ty, bool Realign) const {
86 return ABIArgInfo::getIndirectInReg(getContext().getTypeAlignInChars(Ty),
87 /*ByRef*/ false, Realign);
90 Address ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
92 return Address::invalid();
95 ABIInfo::~ABIInfo() {}
97 /// Does the given lowering require more than the given number of
98 /// registers when expanded?
100 /// This is intended to be the basis of a reasonable basic implementation
101 /// of should{Pass,Return}IndirectlyForSwift.
103 /// For most targets, a limit of four total registers is reasonable; this
104 /// limits the amount of code required in order to move around the value
105 /// in case it wasn't produced immediately prior to the call by the caller
106 /// (or wasn't produced in exactly the right registers) or isn't used
107 /// immediately within the callee. But some targets may need to further
108 /// limit the register count due to an inability to support that many
109 /// return registers.
110 static bool occupiesMoreThan(CodeGenTypes &cgt,
111 ArrayRef<llvm::Type*> scalarTypes,
112 unsigned maxAllRegisters) {
113 unsigned intCount = 0, fpCount = 0;
114 for (llvm::Type *type : scalarTypes) {
115 if (type->isPointerTy()) {
117 } else if (auto intTy = dyn_cast<llvm::IntegerType>(type)) {
118 auto ptrWidth = cgt.getTarget().getPointerWidth(0);
119 intCount += (intTy->getBitWidth() + ptrWidth - 1) / ptrWidth;
121 assert(type->isVectorTy() || type->isFloatingPointTy());
126 return (intCount + fpCount > maxAllRegisters);
129 bool SwiftABIInfo::isLegalVectorTypeForSwift(CharUnits vectorSize,
131 unsigned numElts) const {
132 // The default implementation of this assumes that the target guarantees
133 // 128-bit SIMD support but nothing more.
134 return (vectorSize.getQuantity() > 8 && vectorSize.getQuantity() <= 16);
137 static CGCXXABI::RecordArgABI getRecordArgABI(const RecordType *RT,
139 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
141 return CGCXXABI::RAA_Default;
142 return CXXABI.getRecordArgABI(RD);
145 static CGCXXABI::RecordArgABI getRecordArgABI(QualType T,
147 const RecordType *RT = T->getAs<RecordType>();
149 return CGCXXABI::RAA_Default;
150 return getRecordArgABI(RT, CXXABI);
153 /// Pass transparent unions as if they were the type of the first element. Sema
154 /// should ensure that all elements of the union have the same "machine type".
155 static QualType useFirstFieldIfTransparentUnion(QualType Ty) {
156 if (const RecordType *UT = Ty->getAsUnionType()) {
157 const RecordDecl *UD = UT->getDecl();
158 if (UD->hasAttr<TransparentUnionAttr>()) {
159 assert(!UD->field_empty() && "sema created an empty transparent union");
160 return UD->field_begin()->getType();
166 CGCXXABI &ABIInfo::getCXXABI() const {
167 return CGT.getCXXABI();
170 ASTContext &ABIInfo::getContext() const {
171 return CGT.getContext();
174 llvm::LLVMContext &ABIInfo::getVMContext() const {
175 return CGT.getLLVMContext();
178 const llvm::DataLayout &ABIInfo::getDataLayout() const {
179 return CGT.getDataLayout();
182 const TargetInfo &ABIInfo::getTarget() const {
183 return CGT.getTarget();
186 bool ABIInfo:: isAndroid() const { return getTarget().getTriple().isAndroid(); }
188 bool ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
192 bool ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
193 uint64_t Members) const {
197 bool ABIInfo::shouldSignExtUnsignedType(QualType Ty) const {
201 LLVM_DUMP_METHOD void ABIArgInfo::dump() const {
202 raw_ostream &OS = llvm::errs();
203 OS << "(ABIArgInfo Kind=";
206 OS << "Direct Type=";
207 if (llvm::Type *Ty = getCoerceToType())
219 OS << "InAlloca Offset=" << getInAllocaFieldIndex();
222 OS << "Indirect Align=" << getIndirectAlign().getQuantity()
223 << " ByVal=" << getIndirectByVal()
224 << " Realign=" << getIndirectRealign();
229 case CoerceAndExpand:
230 OS << "CoerceAndExpand Type=";
231 getCoerceAndExpandType()->print(OS);
237 // Dynamically round a pointer up to a multiple of the given alignment.
238 static llvm::Value *emitRoundPointerUpToAlignment(CodeGenFunction &CGF,
241 llvm::Value *PtrAsInt = Ptr;
242 // OverflowArgArea = (OverflowArgArea + Align - 1) & -Align;
243 PtrAsInt = CGF.Builder.CreatePtrToInt(PtrAsInt, CGF.IntPtrTy);
244 PtrAsInt = CGF.Builder.CreateAdd(PtrAsInt,
245 llvm::ConstantInt::get(CGF.IntPtrTy, Align.getQuantity() - 1));
246 PtrAsInt = CGF.Builder.CreateAnd(PtrAsInt,
247 llvm::ConstantInt::get(CGF.IntPtrTy, -Align.getQuantity()));
248 PtrAsInt = CGF.Builder.CreateIntToPtr(PtrAsInt,
250 Ptr->getName() + ".aligned");
254 /// Emit va_arg for a platform using the common void* representation,
255 /// where arguments are simply emitted in an array of slots on the stack.
257 /// This version implements the core direct-value passing rules.
259 /// \param SlotSize - The size and alignment of a stack slot.
260 /// Each argument will be allocated to a multiple of this number of
261 /// slots, and all the slots will be aligned to this value.
262 /// \param AllowHigherAlign - The slot alignment is not a cap;
263 /// an argument type with an alignment greater than the slot size
264 /// will be emitted on a higher-alignment address, potentially
265 /// leaving one or more empty slots behind as padding. If this
266 /// is false, the returned address might be less-aligned than
268 static Address emitVoidPtrDirectVAArg(CodeGenFunction &CGF,
270 llvm::Type *DirectTy,
271 CharUnits DirectSize,
272 CharUnits DirectAlign,
274 bool AllowHigherAlign) {
275 // Cast the element type to i8* if necessary. Some platforms define
276 // va_list as a struct containing an i8* instead of just an i8*.
277 if (VAListAddr.getElementType() != CGF.Int8PtrTy)
278 VAListAddr = CGF.Builder.CreateElementBitCast(VAListAddr, CGF.Int8PtrTy);
280 llvm::Value *Ptr = CGF.Builder.CreateLoad(VAListAddr, "argp.cur");
282 // If the CC aligns values higher than the slot size, do so if needed.
283 Address Addr = Address::invalid();
284 if (AllowHigherAlign && DirectAlign > SlotSize) {
285 Addr = Address(emitRoundPointerUpToAlignment(CGF, Ptr, DirectAlign),
288 Addr = Address(Ptr, SlotSize);
291 // Advance the pointer past the argument, then store that back.
292 CharUnits FullDirectSize = DirectSize.alignTo(SlotSize);
293 llvm::Value *NextPtr =
294 CGF.Builder.CreateConstInBoundsByteGEP(Addr.getPointer(), FullDirectSize,
296 CGF.Builder.CreateStore(NextPtr, VAListAddr);
298 // If the argument is smaller than a slot, and this is a big-endian
299 // target, the argument will be right-adjusted in its slot.
300 if (DirectSize < SlotSize && CGF.CGM.getDataLayout().isBigEndian() &&
301 !DirectTy->isStructTy()) {
302 Addr = CGF.Builder.CreateConstInBoundsByteGEP(Addr, SlotSize - DirectSize);
305 Addr = CGF.Builder.CreateElementBitCast(Addr, DirectTy);
309 /// Emit va_arg for a platform using the common void* representation,
310 /// where arguments are simply emitted in an array of slots on the stack.
312 /// \param IsIndirect - Values of this type are passed indirectly.
313 /// \param ValueInfo - The size and alignment of this type, generally
314 /// computed with getContext().getTypeInfoInChars(ValueTy).
315 /// \param SlotSizeAndAlign - The size and alignment of a stack slot.
316 /// Each argument will be allocated to a multiple of this number of
317 /// slots, and all the slots will be aligned to this value.
318 /// \param AllowHigherAlign - The slot alignment is not a cap;
319 /// an argument type with an alignment greater than the slot size
320 /// will be emitted on a higher-alignment address, potentially
321 /// leaving one or more empty slots behind as padding.
322 static Address emitVoidPtrVAArg(CodeGenFunction &CGF, Address VAListAddr,
323 QualType ValueTy, bool IsIndirect,
324 std::pair<CharUnits, CharUnits> ValueInfo,
325 CharUnits SlotSizeAndAlign,
326 bool AllowHigherAlign) {
327 // The size and alignment of the value that was passed directly.
328 CharUnits DirectSize, DirectAlign;
330 DirectSize = CGF.getPointerSize();
331 DirectAlign = CGF.getPointerAlign();
333 DirectSize = ValueInfo.first;
334 DirectAlign = ValueInfo.second;
337 // Cast the address we've calculated to the right type.
338 llvm::Type *DirectTy = CGF.ConvertTypeForMem(ValueTy);
340 DirectTy = DirectTy->getPointerTo(0);
342 Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, DirectTy,
343 DirectSize, DirectAlign,
348 Addr = Address(CGF.Builder.CreateLoad(Addr), ValueInfo.second);
355 static Address emitMergePHI(CodeGenFunction &CGF,
356 Address Addr1, llvm::BasicBlock *Block1,
357 Address Addr2, llvm::BasicBlock *Block2,
358 const llvm::Twine &Name = "") {
359 assert(Addr1.getType() == Addr2.getType());
360 llvm::PHINode *PHI = CGF.Builder.CreatePHI(Addr1.getType(), 2, Name);
361 PHI->addIncoming(Addr1.getPointer(), Block1);
362 PHI->addIncoming(Addr2.getPointer(), Block2);
363 CharUnits Align = std::min(Addr1.getAlignment(), Addr2.getAlignment());
364 return Address(PHI, Align);
367 TargetCodeGenInfo::~TargetCodeGenInfo() { delete Info; }
369 // If someone can figure out a general rule for this, that would be great.
370 // It's probably just doomed to be platform-dependent, though.
371 unsigned TargetCodeGenInfo::getSizeOfUnwindException() const {
373 // x86-64 FreeBSD, Linux, Darwin
374 // x86-32 FreeBSD, Linux, Darwin
375 // PowerPC Linux, Darwin
376 // ARM Darwin (*not* EABI)
381 bool TargetCodeGenInfo::isNoProtoCallVariadic(const CallArgList &args,
382 const FunctionNoProtoType *fnType) const {
383 // The following conventions are known to require this to be false:
386 // For everything else, we just prefer false unless we opt out.
391 TargetCodeGenInfo::getDependentLibraryOption(llvm::StringRef Lib,
392 llvm::SmallString<24> &Opt) const {
393 // This assumes the user is passing a library name like "rt" instead of a
394 // filename like "librt.a/so", and that they don't care whether it's static or
400 unsigned TargetCodeGenInfo::getOpenCLKernelCallingConv() const {
401 // OpenCL kernels are called via an explicit runtime API with arguments
402 // set with clSetKernelArg(), not as normal sub-functions.
403 // Return SPIR_KERNEL by default as the kernel calling convention to
404 // ensure the fingerprint is fixed such way that each OpenCL argument
405 // gets one matching argument in the produced kernel function argument
406 // list to enable feasible implementation of clSetKernelArg() with
407 // aggregates etc. In case we would use the default C calling conv here,
408 // clSetKernelArg() might break depending on the target-specific
409 // conventions; different targets might split structs passed as values
410 // to multiple function arguments etc.
411 return llvm::CallingConv::SPIR_KERNEL;
414 llvm::Constant *TargetCodeGenInfo::getNullPointer(const CodeGen::CodeGenModule &CGM,
415 llvm::PointerType *T, QualType QT) const {
416 return llvm::ConstantPointerNull::get(T);
419 llvm::Value *TargetCodeGenInfo::performAddrSpaceCast(
420 CodeGen::CodeGenFunction &CGF, llvm::Value *Src, unsigned SrcAddr,
421 unsigned DestAddr, llvm::Type *DestTy, bool isNonNull) const {
422 // Since target may map different address spaces in AST to the same address
423 // space, an address space conversion may end up as a bitcast.
424 return CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Src, DestTy);
427 static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays);
429 /// isEmptyField - Return true iff a the field is "empty", that is it
430 /// is an unnamed bit-field or an (array of) empty record(s).
431 static bool isEmptyField(ASTContext &Context, const FieldDecl *FD,
433 if (FD->isUnnamedBitfield())
436 QualType FT = FD->getType();
438 // Constant arrays of empty records count as empty, strip them off.
439 // Constant arrays of zero length always count as empty.
441 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
442 if (AT->getSize() == 0)
444 FT = AT->getElementType();
447 const RecordType *RT = FT->getAs<RecordType>();
451 // C++ record fields are never empty, at least in the Itanium ABI.
453 // FIXME: We should use a predicate for whether this behavior is true in the
455 if (isa<CXXRecordDecl>(RT->getDecl()))
458 return isEmptyRecord(Context, FT, AllowArrays);
461 /// isEmptyRecord - Return true iff a structure contains only empty
462 /// fields. Note that a structure with a flexible array member is not
463 /// considered empty.
464 static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) {
465 const RecordType *RT = T->getAs<RecordType>();
468 const RecordDecl *RD = RT->getDecl();
469 if (RD->hasFlexibleArrayMember())
472 // If this is a C++ record, check the bases first.
473 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
474 for (const auto &I : CXXRD->bases())
475 if (!isEmptyRecord(Context, I.getType(), true))
478 for (const auto *I : RD->fields())
479 if (!isEmptyField(Context, I, AllowArrays))
484 /// isSingleElementStruct - Determine if a structure is a "single
485 /// element struct", i.e. it has exactly one non-empty field or
486 /// exactly one field which is itself a single element
487 /// struct. Structures with flexible array members are never
488 /// considered single element structs.
490 /// \return The field declaration for the single non-empty field, if
492 static const Type *isSingleElementStruct(QualType T, ASTContext &Context) {
493 const RecordType *RT = T->getAs<RecordType>();
497 const RecordDecl *RD = RT->getDecl();
498 if (RD->hasFlexibleArrayMember())
501 const Type *Found = nullptr;
503 // If this is a C++ record, check the bases first.
504 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
505 for (const auto &I : CXXRD->bases()) {
506 // Ignore empty records.
507 if (isEmptyRecord(Context, I.getType(), true))
510 // If we already found an element then this isn't a single-element struct.
514 // If this is non-empty and not a single element struct, the composite
515 // cannot be a single element struct.
516 Found = isSingleElementStruct(I.getType(), Context);
522 // Check for single element.
523 for (const auto *FD : RD->fields()) {
524 QualType FT = FD->getType();
526 // Ignore empty fields.
527 if (isEmptyField(Context, FD, true))
530 // If we already found an element then this isn't a single-element
535 // Treat single element arrays as the element.
536 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
537 if (AT->getSize().getZExtValue() != 1)
539 FT = AT->getElementType();
542 if (!isAggregateTypeForABI(FT)) {
543 Found = FT.getTypePtr();
545 Found = isSingleElementStruct(FT, Context);
551 // We don't consider a struct a single-element struct if it has
552 // padding beyond the element type.
553 if (Found && Context.getTypeSize(Found) != Context.getTypeSize(T))
560 Address EmitVAArgInstr(CodeGenFunction &CGF, Address VAListAddr, QualType Ty,
561 const ABIArgInfo &AI) {
562 // This default implementation defers to the llvm backend's va_arg
563 // instruction. It can handle only passing arguments directly
564 // (typically only handled in the backend for primitive types), or
565 // aggregates passed indirectly by pointer (NOTE: if the "byval"
566 // flag has ABI impact in the callee, this implementation cannot
569 // Only a few cases are covered here at the moment -- those needed
570 // by the default abi.
573 if (AI.isIndirect()) {
574 assert(!AI.getPaddingType() &&
575 "Unexpected PaddingType seen in arginfo in generic VAArg emitter!");
577 !AI.getIndirectRealign() &&
578 "Unexpected IndirectRealign seen in arginfo in generic VAArg emitter!");
580 auto TyInfo = CGF.getContext().getTypeInfoInChars(Ty);
581 CharUnits TyAlignForABI = TyInfo.second;
584 llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
586 CGF.Builder.CreateVAArg(VAListAddr.getPointer(), BaseTy);
587 return Address(Addr, TyAlignForABI);
589 assert((AI.isDirect() || AI.isExtend()) &&
590 "Unexpected ArgInfo Kind in generic VAArg emitter!");
592 assert(!AI.getInReg() &&
593 "Unexpected InReg seen in arginfo in generic VAArg emitter!");
594 assert(!AI.getPaddingType() &&
595 "Unexpected PaddingType seen in arginfo in generic VAArg emitter!");
596 assert(!AI.getDirectOffset() &&
597 "Unexpected DirectOffset seen in arginfo in generic VAArg emitter!");
598 assert(!AI.getCoerceToType() &&
599 "Unexpected CoerceToType seen in arginfo in generic VAArg emitter!");
601 Address Temp = CGF.CreateMemTemp(Ty, "varet");
602 Val = CGF.Builder.CreateVAArg(VAListAddr.getPointer(), CGF.ConvertType(Ty));
603 CGF.Builder.CreateStore(Val, Temp);
608 /// DefaultABIInfo - The default implementation for ABI specific
609 /// details. This implementation provides information which results in
610 /// self-consistent and sensible LLVM IR generation, but does not
611 /// conform to any particular ABI.
612 class DefaultABIInfo : public ABIInfo {
614 DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
616 ABIArgInfo classifyReturnType(QualType RetTy) const;
617 ABIArgInfo classifyArgumentType(QualType RetTy) const;
619 void computeInfo(CGFunctionInfo &FI) const override {
620 if (!getCXXABI().classifyReturnType(FI))
621 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
622 for (auto &I : FI.arguments())
623 I.info = classifyArgumentType(I.type);
626 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
627 QualType Ty) const override {
628 return EmitVAArgInstr(CGF, VAListAddr, Ty, classifyArgumentType(Ty));
632 class DefaultTargetCodeGenInfo : public TargetCodeGenInfo {
634 DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
635 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
638 ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const {
639 Ty = useFirstFieldIfTransparentUnion(Ty);
641 if (isAggregateTypeForABI(Ty)) {
642 // Records with non-trivial destructors/copy-constructors should not be
644 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
645 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
647 return getNaturalAlignIndirect(Ty);
650 // Treat an enum type as its underlying type.
651 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
652 Ty = EnumTy->getDecl()->getIntegerType();
654 return (Ty->isPromotableIntegerType() ?
655 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
658 ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const {
659 if (RetTy->isVoidType())
660 return ABIArgInfo::getIgnore();
662 if (isAggregateTypeForABI(RetTy))
663 return getNaturalAlignIndirect(RetTy);
665 // Treat an enum type as its underlying type.
666 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
667 RetTy = EnumTy->getDecl()->getIntegerType();
669 return (RetTy->isPromotableIntegerType() ?
670 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
673 //===----------------------------------------------------------------------===//
674 // WebAssembly ABI Implementation
676 // This is a very simple ABI that relies a lot on DefaultABIInfo.
677 //===----------------------------------------------------------------------===//
679 class WebAssemblyABIInfo final : public DefaultABIInfo {
681 explicit WebAssemblyABIInfo(CodeGen::CodeGenTypes &CGT)
682 : DefaultABIInfo(CGT) {}
685 ABIArgInfo classifyReturnType(QualType RetTy) const;
686 ABIArgInfo classifyArgumentType(QualType Ty) const;
688 // DefaultABIInfo's classifyReturnType and classifyArgumentType are
689 // non-virtual, but computeInfo and EmitVAArg are virtual, so we
691 void computeInfo(CGFunctionInfo &FI) const override {
692 if (!getCXXABI().classifyReturnType(FI))
693 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
694 for (auto &Arg : FI.arguments())
695 Arg.info = classifyArgumentType(Arg.type);
698 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
699 QualType Ty) const override;
702 class WebAssemblyTargetCodeGenInfo final : public TargetCodeGenInfo {
704 explicit WebAssemblyTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
705 : TargetCodeGenInfo(new WebAssemblyABIInfo(CGT)) {}
708 /// \brief Classify argument of given type \p Ty.
709 ABIArgInfo WebAssemblyABIInfo::classifyArgumentType(QualType Ty) const {
710 Ty = useFirstFieldIfTransparentUnion(Ty);
712 if (isAggregateTypeForABI(Ty)) {
713 // Records with non-trivial destructors/copy-constructors should not be
715 if (auto RAA = getRecordArgABI(Ty, getCXXABI()))
716 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
717 // Ignore empty structs/unions.
718 if (isEmptyRecord(getContext(), Ty, true))
719 return ABIArgInfo::getIgnore();
720 // Lower single-element structs to just pass a regular value. TODO: We
721 // could do reasonable-size multiple-element structs too, using getExpand(),
722 // though watch out for things like bitfields.
723 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
724 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
727 // Otherwise just do the default thing.
728 return DefaultABIInfo::classifyArgumentType(Ty);
731 ABIArgInfo WebAssemblyABIInfo::classifyReturnType(QualType RetTy) const {
732 if (isAggregateTypeForABI(RetTy)) {
733 // Records with non-trivial destructors/copy-constructors should not be
734 // returned by value.
735 if (!getRecordArgABI(RetTy, getCXXABI())) {
736 // Ignore empty structs/unions.
737 if (isEmptyRecord(getContext(), RetTy, true))
738 return ABIArgInfo::getIgnore();
739 // Lower single-element structs to just return a regular value. TODO: We
740 // could do reasonable-size multiple-element structs too, using
741 // ABIArgInfo::getDirect().
742 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
743 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
747 // Otherwise just do the default thing.
748 return DefaultABIInfo::classifyReturnType(RetTy);
751 Address WebAssemblyABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
753 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect=*/ false,
754 getContext().getTypeInfoInChars(Ty),
755 CharUnits::fromQuantity(4),
756 /*AllowHigherAlign=*/ true);
759 //===----------------------------------------------------------------------===//
760 // le32/PNaCl bitcode ABI Implementation
762 // This is a simplified version of the x86_32 ABI. Arguments and return values
763 // are always passed on the stack.
764 //===----------------------------------------------------------------------===//
766 class PNaClABIInfo : public ABIInfo {
768 PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
770 ABIArgInfo classifyReturnType(QualType RetTy) const;
771 ABIArgInfo classifyArgumentType(QualType RetTy) const;
773 void computeInfo(CGFunctionInfo &FI) const override;
774 Address EmitVAArg(CodeGenFunction &CGF,
775 Address VAListAddr, QualType Ty) const override;
778 class PNaClTargetCodeGenInfo : public TargetCodeGenInfo {
780 PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
781 : TargetCodeGenInfo(new PNaClABIInfo(CGT)) {}
784 void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const {
785 if (!getCXXABI().classifyReturnType(FI))
786 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
788 for (auto &I : FI.arguments())
789 I.info = classifyArgumentType(I.type);
792 Address PNaClABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
794 // The PNaCL ABI is a bit odd, in that varargs don't use normal
795 // function classification. Structs get passed directly for varargs
796 // functions, through a rewriting transform in
797 // pnacl-llvm/lib/Transforms/NaCl/ExpandVarArgs.cpp, which allows
798 // this target to actually support a va_arg instructions with an
799 // aggregate type, unlike other targets.
800 return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
803 /// \brief Classify argument of given type \p Ty.
804 ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const {
805 if (isAggregateTypeForABI(Ty)) {
806 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
807 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
808 return getNaturalAlignIndirect(Ty);
809 } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
810 // Treat an enum type as its underlying type.
811 Ty = EnumTy->getDecl()->getIntegerType();
812 } else if (Ty->isFloatingType()) {
813 // Floating-point types don't go inreg.
814 return ABIArgInfo::getDirect();
817 return (Ty->isPromotableIntegerType() ?
818 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
821 ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const {
822 if (RetTy->isVoidType())
823 return ABIArgInfo::getIgnore();
825 // In the PNaCl ABI we always return records/structures on the stack.
826 if (isAggregateTypeForABI(RetTy))
827 return getNaturalAlignIndirect(RetTy);
829 // Treat an enum type as its underlying type.
830 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
831 RetTy = EnumTy->getDecl()->getIntegerType();
833 return (RetTy->isPromotableIntegerType() ?
834 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
837 /// IsX86_MMXType - Return true if this is an MMX type.
838 bool IsX86_MMXType(llvm::Type *IRType) {
839 // Return true if the type is an MMX type <2 x i32>, <4 x i16>, or <8 x i8>.
840 return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 &&
841 cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() &&
842 IRType->getScalarSizeInBits() != 64;
845 static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
846 StringRef Constraint,
848 if ((Constraint == "y" || Constraint == "&y") && Ty->isVectorTy()) {
849 if (cast<llvm::VectorType>(Ty)->getBitWidth() != 64) {
850 // Invalid MMX constraint
854 return llvm::Type::getX86_MMXTy(CGF.getLLVMContext());
857 // No operation needed
861 /// Returns true if this type can be passed in SSE registers with the
862 /// X86_VectorCall calling convention. Shared between x86_32 and x86_64.
863 static bool isX86VectorTypeForVectorCall(ASTContext &Context, QualType Ty) {
864 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
865 if (BT->isFloatingPoint() && BT->getKind() != BuiltinType::Half)
867 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
868 // vectorcall can pass XMM, YMM, and ZMM vectors. We don't pass SSE1 MMX
869 // registers specially.
870 unsigned VecSize = Context.getTypeSize(VT);
871 if (VecSize == 128 || VecSize == 256 || VecSize == 512)
877 /// Returns true if this aggregate is small enough to be passed in SSE registers
878 /// in the X86_VectorCall calling convention. Shared between x86_32 and x86_64.
879 static bool isX86VectorCallAggregateSmallEnough(uint64_t NumMembers) {
880 return NumMembers <= 4;
883 /// Returns a Homogeneous Vector Aggregate ABIArgInfo, used in X86.
884 static ABIArgInfo getDirectX86Hva(llvm::Type* T = nullptr) {
885 auto AI = ABIArgInfo::getDirect(T);
887 AI.setCanBeFlattened(false);
891 //===----------------------------------------------------------------------===//
892 // X86-32 ABI Implementation
893 //===----------------------------------------------------------------------===//
895 /// \brief Similar to llvm::CCState, but for Clang.
897 CCState(unsigned CC) : CC(CC), FreeRegs(0), FreeSSERegs(0) {}
901 unsigned FreeSSERegs;
905 // Vectorcall only allows the first 6 parameters to be passed in registers.
906 VectorcallMaxParamNumAsReg = 6
909 /// X86_32ABIInfo - The X86-32 ABI information.
910 class X86_32ABIInfo : public SwiftABIInfo {
916 static const unsigned MinABIStackAlignInBytes = 4;
918 bool IsDarwinVectorABI;
919 bool IsRetSmallStructInRegABI;
920 bool IsWin32StructABI;
923 unsigned DefaultNumRegisterParameters;
925 static bool isRegisterSize(unsigned Size) {
926 return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
929 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
930 // FIXME: Assumes vectorcall is in use.
931 return isX86VectorTypeForVectorCall(getContext(), Ty);
934 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
935 uint64_t NumMembers) const override {
936 // FIXME: Assumes vectorcall is in use.
937 return isX86VectorCallAggregateSmallEnough(NumMembers);
940 bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context) const;
942 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
943 /// such that the argument will be passed in memory.
944 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
946 ABIArgInfo getIndirectReturnResult(QualType Ty, CCState &State) const;
948 /// \brief Return the alignment to use for the given type on the stack.
949 unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const;
951 Class classify(QualType Ty) const;
952 ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const;
953 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
955 /// \brief Updates the number of available free registers, returns
956 /// true if any registers were allocated.
957 bool updateFreeRegs(QualType Ty, CCState &State) const;
959 bool shouldAggregateUseDirect(QualType Ty, CCState &State, bool &InReg,
960 bool &NeedsPadding) const;
961 bool shouldPrimitiveUseInReg(QualType Ty, CCState &State) const;
963 bool canExpandIndirectArgument(QualType Ty) const;
965 /// \brief Rewrite the function info so that all memory arguments use
967 void rewriteWithInAlloca(CGFunctionInfo &FI) const;
969 void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
970 CharUnits &StackOffset, ABIArgInfo &Info,
971 QualType Type) const;
972 void computeVectorCallArgs(CGFunctionInfo &FI, CCState &State,
973 bool &UsedInAlloca) const;
977 void computeInfo(CGFunctionInfo &FI) const override;
978 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
979 QualType Ty) const override;
981 X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
982 bool RetSmallStructInRegABI, bool Win32StructABI,
983 unsigned NumRegisterParameters, bool SoftFloatABI)
984 : SwiftABIInfo(CGT), IsDarwinVectorABI(DarwinVectorABI),
985 IsRetSmallStructInRegABI(RetSmallStructInRegABI),
986 IsWin32StructABI(Win32StructABI),
987 IsSoftFloatABI(SoftFloatABI),
988 IsMCUABI(CGT.getTarget().getTriple().isOSIAMCU()),
989 DefaultNumRegisterParameters(NumRegisterParameters) {}
991 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
992 ArrayRef<llvm::Type*> scalars,
993 bool asReturnValue) const override {
994 // LLVM's x86-32 lowering currently only assigns up to three
995 // integer registers and three fp registers. Oddly, it'll use up to
996 // four vector registers for vectors, but those can overlap with the
998 return occupiesMoreThan(CGT, scalars, /*total*/ 3);
1001 bool isSwiftErrorInRegister() const override {
1002 // x86-32 lowering does not support passing swifterror in a register.
1007 class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
1009 X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
1010 bool RetSmallStructInRegABI, bool Win32StructABI,
1011 unsigned NumRegisterParameters, bool SoftFloatABI)
1012 : TargetCodeGenInfo(new X86_32ABIInfo(
1013 CGT, DarwinVectorABI, RetSmallStructInRegABI, Win32StructABI,
1014 NumRegisterParameters, SoftFloatABI)) {}
1016 static bool isStructReturnInRegABI(
1017 const llvm::Triple &Triple, const CodeGenOptions &Opts);
1019 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
1020 CodeGen::CodeGenModule &CGM) const override;
1022 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
1023 // Darwin uses different dwarf register numbers for EH.
1024 if (CGM.getTarget().getTriple().isOSDarwin()) return 5;
1028 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
1029 llvm::Value *Address) const override;
1031 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
1032 StringRef Constraint,
1033 llvm::Type* Ty) const override {
1034 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
1037 void addReturnRegisterOutputs(CodeGenFunction &CGF, LValue ReturnValue,
1038 std::string &Constraints,
1039 std::vector<llvm::Type *> &ResultRegTypes,
1040 std::vector<llvm::Type *> &ResultTruncRegTypes,
1041 std::vector<LValue> &ResultRegDests,
1042 std::string &AsmString,
1043 unsigned NumOutputs) const override;
1046 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
1047 unsigned Sig = (0xeb << 0) | // jmp rel8
1048 (0x06 << 8) | // .+0x08
1051 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
1054 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
1055 return "movl\t%ebp, %ebp"
1056 "\t\t## marker for objc_retainAutoreleaseReturnValue";
1062 /// Rewrite input constraint references after adding some output constraints.
1063 /// In the case where there is one output and one input and we add one output,
1064 /// we need to replace all operand references greater than or equal to 1:
1067 /// The result will be:
1070 static void rewriteInputConstraintReferences(unsigned FirstIn,
1071 unsigned NumNewOuts,
1072 std::string &AsmString) {
1074 llvm::raw_string_ostream OS(Buf);
1076 while (Pos < AsmString.size()) {
1077 size_t DollarStart = AsmString.find('$', Pos);
1078 if (DollarStart == std::string::npos)
1079 DollarStart = AsmString.size();
1080 size_t DollarEnd = AsmString.find_first_not_of('$', DollarStart);
1081 if (DollarEnd == std::string::npos)
1082 DollarEnd = AsmString.size();
1083 OS << StringRef(&AsmString[Pos], DollarEnd - Pos);
1085 size_t NumDollars = DollarEnd - DollarStart;
1086 if (NumDollars % 2 != 0 && Pos < AsmString.size()) {
1087 // We have an operand reference.
1088 size_t DigitStart = Pos;
1089 size_t DigitEnd = AsmString.find_first_not_of("0123456789", DigitStart);
1090 if (DigitEnd == std::string::npos)
1091 DigitEnd = AsmString.size();
1092 StringRef OperandStr(&AsmString[DigitStart], DigitEnd - DigitStart);
1093 unsigned OperandIndex;
1094 if (!OperandStr.getAsInteger(10, OperandIndex)) {
1095 if (OperandIndex >= FirstIn)
1096 OperandIndex += NumNewOuts;
1104 AsmString = std::move(OS.str());
1107 /// Add output constraints for EAX:EDX because they are return registers.
1108 void X86_32TargetCodeGenInfo::addReturnRegisterOutputs(
1109 CodeGenFunction &CGF, LValue ReturnSlot, std::string &Constraints,
1110 std::vector<llvm::Type *> &ResultRegTypes,
1111 std::vector<llvm::Type *> &ResultTruncRegTypes,
1112 std::vector<LValue> &ResultRegDests, std::string &AsmString,
1113 unsigned NumOutputs) const {
1114 uint64_t RetWidth = CGF.getContext().getTypeSize(ReturnSlot.getType());
1116 // Use the EAX constraint if the width is 32 or smaller and EAX:EDX if it is
1118 if (!Constraints.empty())
1120 if (RetWidth <= 32) {
1121 Constraints += "={eax}";
1122 ResultRegTypes.push_back(CGF.Int32Ty);
1124 // Use the 'A' constraint for EAX:EDX.
1125 Constraints += "=A";
1126 ResultRegTypes.push_back(CGF.Int64Ty);
1129 // Truncate EAX or EAX:EDX to an integer of the appropriate size.
1130 llvm::Type *CoerceTy = llvm::IntegerType::get(CGF.getLLVMContext(), RetWidth);
1131 ResultTruncRegTypes.push_back(CoerceTy);
1133 // Coerce the integer by bitcasting the return slot pointer.
1134 ReturnSlot.setAddress(CGF.Builder.CreateBitCast(ReturnSlot.getAddress(),
1135 CoerceTy->getPointerTo()));
1136 ResultRegDests.push_back(ReturnSlot);
1138 rewriteInputConstraintReferences(NumOutputs, 1, AsmString);
1141 /// shouldReturnTypeInRegister - Determine if the given type should be
1142 /// returned in a register (for the Darwin and MCU ABI).
1143 bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
1144 ASTContext &Context) const {
1145 uint64_t Size = Context.getTypeSize(Ty);
1147 // For i386, type must be register sized.
1148 // For the MCU ABI, it only needs to be <= 8-byte
1149 if ((IsMCUABI && Size > 64) || (!IsMCUABI && !isRegisterSize(Size)))
1152 if (Ty->isVectorType()) {
1153 // 64- and 128- bit vectors inside structures are not returned in
1155 if (Size == 64 || Size == 128)
1161 // If this is a builtin, pointer, enum, complex type, member pointer, or
1162 // member function pointer it is ok.
1163 if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() ||
1164 Ty->isAnyComplexType() || Ty->isEnumeralType() ||
1165 Ty->isBlockPointerType() || Ty->isMemberPointerType())
1168 // Arrays are treated like records.
1169 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
1170 return shouldReturnTypeInRegister(AT->getElementType(), Context);
1172 // Otherwise, it must be a record type.
1173 const RecordType *RT = Ty->getAs<RecordType>();
1174 if (!RT) return false;
1176 // FIXME: Traverse bases here too.
1178 // Structure types are passed in register if all fields would be
1179 // passed in a register.
1180 for (const auto *FD : RT->getDecl()->fields()) {
1181 // Empty fields are ignored.
1182 if (isEmptyField(Context, FD, true))
1185 // Check fields recursively.
1186 if (!shouldReturnTypeInRegister(FD->getType(), Context))
1192 static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
1193 // Treat complex types as the element type.
1194 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
1195 Ty = CTy->getElementType();
1197 // Check for a type which we know has a simple scalar argument-passing
1198 // convention without any padding. (We're specifically looking for 32
1199 // and 64-bit integer and integer-equivalents, float, and double.)
1200 if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() &&
1201 !Ty->isEnumeralType() && !Ty->isBlockPointerType())
1204 uint64_t Size = Context.getTypeSize(Ty);
1205 return Size == 32 || Size == 64;
1208 static bool addFieldSizes(ASTContext &Context, const RecordDecl *RD,
1210 for (const auto *FD : RD->fields()) {
1211 // Scalar arguments on the stack get 4 byte alignment on x86. If the
1212 // argument is smaller than 32-bits, expanding the struct will create
1213 // alignment padding.
1214 if (!is32Or64BitBasicType(FD->getType(), Context))
1217 // FIXME: Reject bit-fields wholesale; there are two problems, we don't know
1218 // how to expand them yet, and the predicate for telling if a bitfield still
1219 // counts as "basic" is more complicated than what we were doing previously.
1220 if (FD->isBitField())
1223 Size += Context.getTypeSize(FD->getType());
1228 static bool addBaseAndFieldSizes(ASTContext &Context, const CXXRecordDecl *RD,
1230 // Don't do this if there are any non-empty bases.
1231 for (const CXXBaseSpecifier &Base : RD->bases()) {
1232 if (!addBaseAndFieldSizes(Context, Base.getType()->getAsCXXRecordDecl(),
1236 if (!addFieldSizes(Context, RD, Size))
1241 /// Test whether an argument type which is to be passed indirectly (on the
1242 /// stack) would have the equivalent layout if it was expanded into separate
1243 /// arguments. If so, we prefer to do the latter to avoid inhibiting
1245 bool X86_32ABIInfo::canExpandIndirectArgument(QualType Ty) const {
1246 // We can only expand structure types.
1247 const RecordType *RT = Ty->getAs<RecordType>();
1250 const RecordDecl *RD = RT->getDecl();
1252 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
1253 if (!IsWin32StructABI) {
1254 // On non-Windows, we have to conservatively match our old bitcode
1255 // prototypes in order to be ABI-compatible at the bitcode level.
1256 if (!CXXRD->isCLike())
1259 // Don't do this for dynamic classes.
1260 if (CXXRD->isDynamicClass())
1263 if (!addBaseAndFieldSizes(getContext(), CXXRD, Size))
1266 if (!addFieldSizes(getContext(), RD, Size))
1270 // We can do this if there was no alignment padding.
1271 return Size == getContext().getTypeSize(Ty);
1274 ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(QualType RetTy, CCState &State) const {
1275 // If the return value is indirect, then the hidden argument is consuming one
1276 // integer register.
1277 if (State.FreeRegs) {
1280 return getNaturalAlignIndirectInReg(RetTy);
1282 return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
1285 ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy,
1286 CCState &State) const {
1287 if (RetTy->isVoidType())
1288 return ABIArgInfo::getIgnore();
1290 const Type *Base = nullptr;
1291 uint64_t NumElts = 0;
1292 if ((State.CC == llvm::CallingConv::X86_VectorCall ||
1293 State.CC == llvm::CallingConv::X86_RegCall) &&
1294 isHomogeneousAggregate(RetTy, Base, NumElts)) {
1295 // The LLVM struct type for such an aggregate should lower properly.
1296 return ABIArgInfo::getDirect();
1299 if (const VectorType *VT = RetTy->getAs<VectorType>()) {
1300 // On Darwin, some vectors are returned in registers.
1301 if (IsDarwinVectorABI) {
1302 uint64_t Size = getContext().getTypeSize(RetTy);
1304 // 128-bit vectors are a special case; they are returned in
1305 // registers and we need to make sure to pick a type the LLVM
1306 // backend will like.
1308 return ABIArgInfo::getDirect(llvm::VectorType::get(
1309 llvm::Type::getInt64Ty(getVMContext()), 2));
1311 // Always return in register if it fits in a general purpose
1312 // register, or if it is 64 bits and has a single element.
1313 if ((Size == 8 || Size == 16 || Size == 32) ||
1314 (Size == 64 && VT->getNumElements() == 1))
1315 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
1318 return getIndirectReturnResult(RetTy, State);
1321 return ABIArgInfo::getDirect();
1324 if (isAggregateTypeForABI(RetTy)) {
1325 if (const RecordType *RT = RetTy->getAs<RecordType>()) {
1326 // Structures with flexible arrays are always indirect.
1327 if (RT->getDecl()->hasFlexibleArrayMember())
1328 return getIndirectReturnResult(RetTy, State);
1331 // If specified, structs and unions are always indirect.
1332 if (!IsRetSmallStructInRegABI && !RetTy->isAnyComplexType())
1333 return getIndirectReturnResult(RetTy, State);
1335 // Ignore empty structs/unions.
1336 if (isEmptyRecord(getContext(), RetTy, true))
1337 return ABIArgInfo::getIgnore();
1339 // Small structures which are register sized are generally returned
1341 if (shouldReturnTypeInRegister(RetTy, getContext())) {
1342 uint64_t Size = getContext().getTypeSize(RetTy);
1344 // As a special-case, if the struct is a "single-element" struct, and
1345 // the field is of type "float" or "double", return it in a
1346 // floating-point register. (MSVC does not apply this special case.)
1347 // We apply a similar transformation for pointer types to improve the
1348 // quality of the generated IR.
1349 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
1350 if ((!IsWin32StructABI && SeltTy->isRealFloatingType())
1351 || SeltTy->hasPointerRepresentation())
1352 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
1354 // FIXME: We should be able to narrow this integer in cases with dead
1356 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
1359 return getIndirectReturnResult(RetTy, State);
1362 // Treat an enum type as its underlying type.
1363 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
1364 RetTy = EnumTy->getDecl()->getIntegerType();
1366 return (RetTy->isPromotableIntegerType() ?
1367 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
1370 static bool isSSEVectorType(ASTContext &Context, QualType Ty) {
1371 return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128;
1374 static bool isRecordWithSSEVectorType(ASTContext &Context, QualType Ty) {
1375 const RecordType *RT = Ty->getAs<RecordType>();
1378 const RecordDecl *RD = RT->getDecl();
1380 // If this is a C++ record, check the bases first.
1381 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
1382 for (const auto &I : CXXRD->bases())
1383 if (!isRecordWithSSEVectorType(Context, I.getType()))
1386 for (const auto *i : RD->fields()) {
1387 QualType FT = i->getType();
1389 if (isSSEVectorType(Context, FT))
1392 if (isRecordWithSSEVectorType(Context, FT))
1399 unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
1400 unsigned Align) const {
1401 // Otherwise, if the alignment is less than or equal to the minimum ABI
1402 // alignment, just use the default; the backend will handle this.
1403 if (Align <= MinABIStackAlignInBytes)
1404 return 0; // Use default alignment.
1406 // On non-Darwin, the stack type alignment is always 4.
1407 if (!IsDarwinVectorABI) {
1408 // Set explicit alignment, since we may need to realign the top.
1409 return MinABIStackAlignInBytes;
1412 // Otherwise, if the type contains an SSE vector type, the alignment is 16.
1413 if (Align >= 16 && (isSSEVectorType(getContext(), Ty) ||
1414 isRecordWithSSEVectorType(getContext(), Ty)))
1417 return MinABIStackAlignInBytes;
1420 ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal,
1421 CCState &State) const {
1423 if (State.FreeRegs) {
1424 --State.FreeRegs; // Non-byval indirects just use one pointer.
1426 return getNaturalAlignIndirectInReg(Ty);
1428 return getNaturalAlignIndirect(Ty, false);
1431 // Compute the byval alignment.
1432 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
1433 unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign);
1434 if (StackAlign == 0)
1435 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true);
1437 // If the stack alignment is less than the type alignment, realign the
1439 bool Realign = TypeAlign > StackAlign;
1440 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(StackAlign),
1441 /*ByVal=*/true, Realign);
1444 X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const {
1445 const Type *T = isSingleElementStruct(Ty, getContext());
1447 T = Ty.getTypePtr();
1449 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
1450 BuiltinType::Kind K = BT->getKind();
1451 if (K == BuiltinType::Float || K == BuiltinType::Double)
1457 bool X86_32ABIInfo::updateFreeRegs(QualType Ty, CCState &State) const {
1458 if (!IsSoftFloatABI) {
1459 Class C = classify(Ty);
1464 unsigned Size = getContext().getTypeSize(Ty);
1465 unsigned SizeInRegs = (Size + 31) / 32;
1467 if (SizeInRegs == 0)
1471 if (SizeInRegs > State.FreeRegs) {
1476 // The MCU psABI allows passing parameters in-reg even if there are
1477 // earlier parameters that are passed on the stack. Also,
1478 // it does not allow passing >8-byte structs in-register,
1479 // even if there are 3 free registers available.
1480 if (SizeInRegs > State.FreeRegs || SizeInRegs > 2)
1484 State.FreeRegs -= SizeInRegs;
1488 bool X86_32ABIInfo::shouldAggregateUseDirect(QualType Ty, CCState &State,
1490 bool &NeedsPadding) const {
1491 // On Windows, aggregates other than HFAs are never passed in registers, and
1492 // they do not consume register slots. Homogenous floating-point aggregates
1493 // (HFAs) have already been dealt with at this point.
1494 if (IsWin32StructABI && isAggregateTypeForABI(Ty))
1497 NeedsPadding = false;
1500 if (!updateFreeRegs(Ty, State))
1506 if (State.CC == llvm::CallingConv::X86_FastCall ||
1507 State.CC == llvm::CallingConv::X86_VectorCall ||
1508 State.CC == llvm::CallingConv::X86_RegCall) {
1509 if (getContext().getTypeSize(Ty) <= 32 && State.FreeRegs)
1510 NeedsPadding = true;
1518 bool X86_32ABIInfo::shouldPrimitiveUseInReg(QualType Ty, CCState &State) const {
1519 if (!updateFreeRegs(Ty, State))
1525 if (State.CC == llvm::CallingConv::X86_FastCall ||
1526 State.CC == llvm::CallingConv::X86_VectorCall ||
1527 State.CC == llvm::CallingConv::X86_RegCall) {
1528 if (getContext().getTypeSize(Ty) > 32)
1531 return (Ty->isIntegralOrEnumerationType() || Ty->isPointerType() ||
1532 Ty->isReferenceType());
1538 ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
1539 CCState &State) const {
1540 // FIXME: Set alignment on indirect arguments.
1542 Ty = useFirstFieldIfTransparentUnion(Ty);
1544 // Check with the C++ ABI first.
1545 const RecordType *RT = Ty->getAs<RecordType>();
1547 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
1548 if (RAA == CGCXXABI::RAA_Indirect) {
1549 return getIndirectResult(Ty, false, State);
1550 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
1551 // The field index doesn't matter, we'll fix it up later.
1552 return ABIArgInfo::getInAlloca(/*FieldIndex=*/0);
1556 // Regcall uses the concept of a homogenous vector aggregate, similar
1557 // to other targets.
1558 const Type *Base = nullptr;
1559 uint64_t NumElts = 0;
1560 if (State.CC == llvm::CallingConv::X86_RegCall &&
1561 isHomogeneousAggregate(Ty, Base, NumElts)) {
1563 if (State.FreeSSERegs >= NumElts) {
1564 State.FreeSSERegs -= NumElts;
1565 if (Ty->isBuiltinType() || Ty->isVectorType())
1566 return ABIArgInfo::getDirect();
1567 return ABIArgInfo::getExpand();
1569 return getIndirectResult(Ty, /*ByVal=*/false, State);
1572 if (isAggregateTypeForABI(Ty)) {
1573 // Structures with flexible arrays are always indirect.
1574 // FIXME: This should not be byval!
1575 if (RT && RT->getDecl()->hasFlexibleArrayMember())
1576 return getIndirectResult(Ty, true, State);
1578 // Ignore empty structs/unions on non-Windows.
1579 if (!IsWin32StructABI && isEmptyRecord(getContext(), Ty, true))
1580 return ABIArgInfo::getIgnore();
1582 llvm::LLVMContext &LLVMContext = getVMContext();
1583 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
1584 bool NeedsPadding = false;
1586 if (shouldAggregateUseDirect(Ty, State, InReg, NeedsPadding)) {
1587 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
1588 SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32);
1589 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
1591 return ABIArgInfo::getDirectInReg(Result);
1593 return ABIArgInfo::getDirect(Result);
1595 llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : nullptr;
1597 // Expand small (<= 128-bit) record types when we know that the stack layout
1598 // of those arguments will match the struct. This is important because the
1599 // LLVM backend isn't smart enough to remove byval, which inhibits many
1601 // Don't do this for the MCU if there are still free integer registers
1602 // (see X86_64 ABI for full explanation).
1603 if (getContext().getTypeSize(Ty) <= 4 * 32 &&
1604 (!IsMCUABI || State.FreeRegs == 0) && canExpandIndirectArgument(Ty))
1605 return ABIArgInfo::getExpandWithPadding(
1606 State.CC == llvm::CallingConv::X86_FastCall ||
1607 State.CC == llvm::CallingConv::X86_VectorCall ||
1608 State.CC == llvm::CallingConv::X86_RegCall,
1611 return getIndirectResult(Ty, true, State);
1614 if (const VectorType *VT = Ty->getAs<VectorType>()) {
1615 // On Darwin, some vectors are passed in memory, we handle this by passing
1616 // it as an i8/i16/i32/i64.
1617 if (IsDarwinVectorABI) {
1618 uint64_t Size = getContext().getTypeSize(Ty);
1619 if ((Size == 8 || Size == 16 || Size == 32) ||
1620 (Size == 64 && VT->getNumElements() == 1))
1621 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
1625 if (IsX86_MMXType(CGT.ConvertType(Ty)))
1626 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64));
1628 return ABIArgInfo::getDirect();
1632 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1633 Ty = EnumTy->getDecl()->getIntegerType();
1635 bool InReg = shouldPrimitiveUseInReg(Ty, State);
1637 if (Ty->isPromotableIntegerType()) {
1639 return ABIArgInfo::getExtendInReg();
1640 return ABIArgInfo::getExtend();
1644 return ABIArgInfo::getDirectInReg();
1645 return ABIArgInfo::getDirect();
1648 void X86_32ABIInfo::computeVectorCallArgs(CGFunctionInfo &FI, CCState &State,
1649 bool &UsedInAlloca) const {
1650 // Vectorcall x86 works subtly different than in x64, so the format is
1651 // a bit different than the x64 version. First, all vector types (not HVAs)
1652 // are assigned, with the first 6 ending up in the YMM0-5 or XMM0-5 registers.
1653 // This differs from the x64 implementation, where the first 6 by INDEX get
1655 // After that, integers AND HVAs are assigned Left to Right in the same pass.
1656 // Integers are passed as ECX/EDX if one is available (in order). HVAs will
1657 // first take up the remaining YMM/XMM registers. If insufficient registers
1658 // remain but an integer register (ECX/EDX) is available, it will be passed
1659 // in that, else, on the stack.
1660 for (auto &I : FI.arguments()) {
1661 // First pass do all the vector types.
1662 const Type *Base = nullptr;
1663 uint64_t NumElts = 0;
1664 const QualType& Ty = I.type;
1665 if ((Ty->isVectorType() || Ty->isBuiltinType()) &&
1666 isHomogeneousAggregate(Ty, Base, NumElts)) {
1667 if (State.FreeSSERegs >= NumElts) {
1668 State.FreeSSERegs -= NumElts;
1669 I.info = ABIArgInfo::getDirect();
1671 I.info = classifyArgumentType(Ty, State);
1673 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca);
1677 for (auto &I : FI.arguments()) {
1678 // Second pass, do the rest!
1679 const Type *Base = nullptr;
1680 uint64_t NumElts = 0;
1681 const QualType& Ty = I.type;
1682 bool IsHva = isHomogeneousAggregate(Ty, Base, NumElts);
1684 if (IsHva && !Ty->isVectorType() && !Ty->isBuiltinType()) {
1685 // Assign true HVAs (non vector/native FP types).
1686 if (State.FreeSSERegs >= NumElts) {
1687 State.FreeSSERegs -= NumElts;
1688 I.info = getDirectX86Hva();
1690 I.info = getIndirectResult(Ty, /*ByVal=*/false, State);
1692 } else if (!IsHva) {
1693 // Assign all Non-HVAs, so this will exclude Vector/FP args.
1694 I.info = classifyArgumentType(Ty, State);
1695 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca);
1700 void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const {
1701 CCState State(FI.getCallingConvention());
1704 else if (State.CC == llvm::CallingConv::X86_FastCall)
1706 else if (State.CC == llvm::CallingConv::X86_VectorCall) {
1708 State.FreeSSERegs = 6;
1709 } else if (FI.getHasRegParm())
1710 State.FreeRegs = FI.getRegParm();
1711 else if (State.CC == llvm::CallingConv::X86_RegCall) {
1713 State.FreeSSERegs = 8;
1715 State.FreeRegs = DefaultNumRegisterParameters;
1717 if (!getCXXABI().classifyReturnType(FI)) {
1718 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), State);
1719 } else if (FI.getReturnInfo().isIndirect()) {
1720 // The C++ ABI is not aware of register usage, so we have to check if the
1721 // return value was sret and put it in a register ourselves if appropriate.
1722 if (State.FreeRegs) {
1723 --State.FreeRegs; // The sret parameter consumes a register.
1725 FI.getReturnInfo().setInReg(true);
1729 // The chain argument effectively gives us another free register.
1730 if (FI.isChainCall())
1733 bool UsedInAlloca = false;
1734 if (State.CC == llvm::CallingConv::X86_VectorCall) {
1735 computeVectorCallArgs(FI, State, UsedInAlloca);
1737 // If not vectorcall, revert to normal behavior.
1738 for (auto &I : FI.arguments()) {
1739 I.info = classifyArgumentType(I.type, State);
1740 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca);
1744 // If we needed to use inalloca for any argument, do a second pass and rewrite
1745 // all the memory arguments to use inalloca.
1747 rewriteWithInAlloca(FI);
1751 X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
1752 CharUnits &StackOffset, ABIArgInfo &Info,
1753 QualType Type) const {
1754 // Arguments are always 4-byte-aligned.
1755 CharUnits FieldAlign = CharUnits::fromQuantity(4);
1757 assert(StackOffset.isMultipleOf(FieldAlign) && "unaligned inalloca struct");
1758 Info = ABIArgInfo::getInAlloca(FrameFields.size());
1759 FrameFields.push_back(CGT.ConvertTypeForMem(Type));
1760 StackOffset += getContext().getTypeSizeInChars(Type);
1762 // Insert padding bytes to respect alignment.
1763 CharUnits FieldEnd = StackOffset;
1764 StackOffset = FieldEnd.alignTo(FieldAlign);
1765 if (StackOffset != FieldEnd) {
1766 CharUnits NumBytes = StackOffset - FieldEnd;
1767 llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext());
1768 Ty = llvm::ArrayType::get(Ty, NumBytes.getQuantity());
1769 FrameFields.push_back(Ty);
1773 static bool isArgInAlloca(const ABIArgInfo &Info) {
1774 // Leave ignored and inreg arguments alone.
1775 switch (Info.getKind()) {
1776 case ABIArgInfo::InAlloca:
1778 case ABIArgInfo::Indirect:
1779 assert(Info.getIndirectByVal());
1781 case ABIArgInfo::Ignore:
1783 case ABIArgInfo::Direct:
1784 case ABIArgInfo::Extend:
1785 if (Info.getInReg())
1788 case ABIArgInfo::Expand:
1789 case ABIArgInfo::CoerceAndExpand:
1790 // These are aggregate types which are never passed in registers when
1791 // inalloca is involved.
1794 llvm_unreachable("invalid enum");
1797 void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const {
1798 assert(IsWin32StructABI && "inalloca only supported on win32");
1800 // Build a packed struct type for all of the arguments in memory.
1801 SmallVector<llvm::Type *, 6> FrameFields;
1803 // The stack alignment is always 4.
1804 CharUnits StackAlign = CharUnits::fromQuantity(4);
1806 CharUnits StackOffset;
1807 CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end();
1809 // Put 'this' into the struct before 'sret', if necessary.
1811 FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall;
1812 ABIArgInfo &Ret = FI.getReturnInfo();
1813 if (Ret.isIndirect() && Ret.isSRetAfterThis() && !IsThisCall &&
1814 isArgInAlloca(I->info)) {
1815 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
1819 // Put the sret parameter into the inalloca struct if it's in memory.
1820 if (Ret.isIndirect() && !Ret.getInReg()) {
1821 CanQualType PtrTy = getContext().getPointerType(FI.getReturnType());
1822 addFieldToArgStruct(FrameFields, StackOffset, Ret, PtrTy);
1823 // On Windows, the hidden sret parameter is always returned in eax.
1824 Ret.setInAllocaSRet(IsWin32StructABI);
1827 // Skip the 'this' parameter in ecx.
1831 // Put arguments passed in memory into the struct.
1832 for (; I != E; ++I) {
1833 if (isArgInAlloca(I->info))
1834 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
1837 FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields,
1842 Address X86_32ABIInfo::EmitVAArg(CodeGenFunction &CGF,
1843 Address VAListAddr, QualType Ty) const {
1845 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
1847 // x86-32 changes the alignment of certain arguments on the stack.
1849 // Just messing with TypeInfo like this works because we never pass
1850 // anything indirectly.
1851 TypeInfo.second = CharUnits::fromQuantity(
1852 getTypeStackAlignInBytes(Ty, TypeInfo.second.getQuantity()));
1854 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
1855 TypeInfo, CharUnits::fromQuantity(4),
1856 /*AllowHigherAlign*/ true);
1859 bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
1860 const llvm::Triple &Triple, const CodeGenOptions &Opts) {
1861 assert(Triple.getArch() == llvm::Triple::x86);
1863 switch (Opts.getStructReturnConvention()) {
1864 case CodeGenOptions::SRCK_Default:
1866 case CodeGenOptions::SRCK_OnStack: // -fpcc-struct-return
1868 case CodeGenOptions::SRCK_InRegs: // -freg-struct-return
1872 if (Triple.isOSDarwin() || Triple.isOSIAMCU())
1875 switch (Triple.getOS()) {
1876 case llvm::Triple::DragonFly:
1877 case llvm::Triple::FreeBSD:
1878 case llvm::Triple::OpenBSD:
1879 case llvm::Triple::Bitrig:
1880 case llvm::Triple::Win32:
1887 void X86_32TargetCodeGenInfo::setTargetAttributes(const Decl *D,
1888 llvm::GlobalValue *GV,
1889 CodeGen::CodeGenModule &CGM) const {
1890 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
1891 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
1892 // Get the LLVM function.
1893 llvm::Function *Fn = cast<llvm::Function>(GV);
1895 // Now add the 'alignstack' attribute with a value of 16.
1896 llvm::AttrBuilder B;
1897 B.addStackAlignmentAttr(16);
1898 Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
1900 if (FD->hasAttr<AnyX86InterruptAttr>()) {
1901 llvm::Function *Fn = cast<llvm::Function>(GV);
1902 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
1907 bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
1908 CodeGen::CodeGenFunction &CGF,
1909 llvm::Value *Address) const {
1910 CodeGen::CGBuilderTy &Builder = CGF.Builder;
1912 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
1914 // 0-7 are the eight integer registers; the order is different
1915 // on Darwin (for EH), but the range is the same.
1917 AssignToArrayRange(Builder, Address, Four8, 0, 8);
1919 if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
1920 // 12-16 are st(0..4). Not sure why we stop at 4.
1921 // These have size 16, which is sizeof(long double) on
1922 // platforms with 8-byte alignment for that type.
1923 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
1924 AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
1927 // 9 is %eflags, which doesn't get a size on Darwin for some
1929 Builder.CreateAlignedStore(
1930 Four8, Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, Address, 9),
1933 // 11-16 are st(0..5). Not sure why we stop at 5.
1934 // These have size 12, which is sizeof(long double) on
1935 // platforms with 4-byte alignment for that type.
1936 llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
1937 AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
1943 //===----------------------------------------------------------------------===//
1944 // X86-64 ABI Implementation
1945 //===----------------------------------------------------------------------===//
1949 /// The AVX ABI level for X86 targets.
1950 enum class X86AVXABILevel {
1956 /// \p returns the size in bits of the largest (native) vector for \p AVXLevel.
1957 static unsigned getNativeVectorSizeForAVXABI(X86AVXABILevel AVXLevel) {
1959 case X86AVXABILevel::AVX512:
1961 case X86AVXABILevel::AVX:
1963 case X86AVXABILevel::None:
1966 llvm_unreachable("Unknown AVXLevel");
1969 /// X86_64ABIInfo - The X86_64 ABI information.
1970 class X86_64ABIInfo : public SwiftABIInfo {
1982 /// merge - Implement the X86_64 ABI merging algorithm.
1984 /// Merge an accumulating classification \arg Accum with a field
1985 /// classification \arg Field.
1987 /// \param Accum - The accumulating classification. This should
1988 /// always be either NoClass or the result of a previous merge
1989 /// call. In addition, this should never be Memory (the caller
1990 /// should just return Memory for the aggregate).
1991 static Class merge(Class Accum, Class Field);
1993 /// postMerge - Implement the X86_64 ABI post merging algorithm.
1995 /// Post merger cleanup, reduces a malformed Hi and Lo pair to
1996 /// final MEMORY or SSE classes when necessary.
1998 /// \param AggregateSize - The size of the current aggregate in
1999 /// the classification process.
2001 /// \param Lo - The classification for the parts of the type
2002 /// residing in the low word of the containing object.
2004 /// \param Hi - The classification for the parts of the type
2005 /// residing in the higher words of the containing object.
2007 void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
2009 /// classify - Determine the x86_64 register classes in which the
2010 /// given type T should be passed.
2012 /// \param Lo - The classification for the parts of the type
2013 /// residing in the low word of the containing object.
2015 /// \param Hi - The classification for the parts of the type
2016 /// residing in the high word of the containing object.
2018 /// \param OffsetBase - The bit offset of this type in the
2019 /// containing object. Some parameters are classified different
2020 /// depending on whether they straddle an eightbyte boundary.
2022 /// \param isNamedArg - Whether the argument in question is a "named"
2023 /// argument, as used in AMD64-ABI 3.5.7.
2025 /// If a word is unused its result will be NoClass; if a type should
2026 /// be passed in Memory then at least the classification of \arg Lo
2029 /// The \arg Lo class will be NoClass iff the argument is ignored.
2031 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
2032 /// also be ComplexX87.
2033 void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi,
2034 bool isNamedArg) const;
2036 llvm::Type *GetByteVectorType(QualType Ty) const;
2037 llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
2038 unsigned IROffset, QualType SourceTy,
2039 unsigned SourceOffset) const;
2040 llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
2041 unsigned IROffset, QualType SourceTy,
2042 unsigned SourceOffset) const;
2044 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
2045 /// such that the argument will be returned in memory.
2046 ABIArgInfo getIndirectReturnResult(QualType Ty) const;
2048 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
2049 /// such that the argument will be passed in memory.
2051 /// \param freeIntRegs - The number of free integer registers remaining
2053 ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
2055 ABIArgInfo classifyReturnType(QualType RetTy) const;
2057 ABIArgInfo classifyArgumentType(QualType Ty, unsigned freeIntRegs,
2058 unsigned &neededInt, unsigned &neededSSE,
2059 bool isNamedArg) const;
2061 ABIArgInfo classifyRegCallStructType(QualType Ty, unsigned &NeededInt,
2062 unsigned &NeededSSE) const;
2064 ABIArgInfo classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
2065 unsigned &NeededSSE) const;
2067 bool IsIllegalVectorType(QualType Ty) const;
2069 /// The 0.98 ABI revision clarified a lot of ambiguities,
2070 /// unfortunately in ways that were not always consistent with
2071 /// certain previous compilers. In particular, platforms which
2072 /// required strict binary compatibility with older versions of GCC
2073 /// may need to exempt themselves.
2074 bool honorsRevision0_98() const {
2075 return !getTarget().getTriple().isOSDarwin();
2078 /// GCC classifies <1 x long long> as SSE but compatibility with older clang
2079 // compilers require us to classify it as INTEGER.
2080 bool classifyIntegerMMXAsSSE() const {
2081 const llvm::Triple &Triple = getTarget().getTriple();
2082 if (Triple.isOSDarwin() || Triple.getOS() == llvm::Triple::PS4)
2084 if (Triple.isOSFreeBSD() && Triple.getOSMajorVersion() >= 10)
2089 X86AVXABILevel AVXLevel;
2090 // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
2092 bool Has64BitPointers;
2095 X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) :
2096 SwiftABIInfo(CGT), AVXLevel(AVXLevel),
2097 Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {
2100 bool isPassedUsingAVXType(QualType type) const {
2101 unsigned neededInt, neededSSE;
2102 // The freeIntRegs argument doesn't matter here.
2103 ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE,
2104 /*isNamedArg*/true);
2105 if (info.isDirect()) {
2106 llvm::Type *ty = info.getCoerceToType();
2107 if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
2108 return (vectorTy->getBitWidth() > 128);
2113 void computeInfo(CGFunctionInfo &FI) const override;
2115 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
2116 QualType Ty) const override;
2117 Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
2118 QualType Ty) const override;
2120 bool has64BitPointers() const {
2121 return Has64BitPointers;
2124 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
2125 ArrayRef<llvm::Type*> scalars,
2126 bool asReturnValue) const override {
2127 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
2129 bool isSwiftErrorInRegister() const override {
2134 /// WinX86_64ABIInfo - The Windows X86_64 ABI information.
2135 class WinX86_64ABIInfo : public SwiftABIInfo {
2137 WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT)
2138 : SwiftABIInfo(CGT),
2139 IsMingw64(getTarget().getTriple().isWindowsGNUEnvironment()) {}
2141 void computeInfo(CGFunctionInfo &FI) const override;
2143 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
2144 QualType Ty) const override;
2146 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
2147 // FIXME: Assumes vectorcall is in use.
2148 return isX86VectorTypeForVectorCall(getContext(), Ty);
2151 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
2152 uint64_t NumMembers) const override {
2153 // FIXME: Assumes vectorcall is in use.
2154 return isX86VectorCallAggregateSmallEnough(NumMembers);
2157 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
2158 ArrayRef<llvm::Type *> scalars,
2159 bool asReturnValue) const override {
2160 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
2163 bool isSwiftErrorInRegister() const override {
2168 ABIArgInfo classify(QualType Ty, unsigned &FreeSSERegs, bool IsReturnType,
2169 bool IsVectorCall, bool IsRegCall) const;
2170 ABIArgInfo reclassifyHvaArgType(QualType Ty, unsigned &FreeSSERegs,
2171 const ABIArgInfo ¤t) const;
2172 void computeVectorCallArgs(CGFunctionInfo &FI, unsigned FreeSSERegs,
2173 bool IsVectorCall, bool IsRegCall) const;
2178 class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2180 X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
2181 : TargetCodeGenInfo(new X86_64ABIInfo(CGT, AVXLevel)) {}
2183 const X86_64ABIInfo &getABIInfo() const {
2184 return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
2187 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
2191 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2192 llvm::Value *Address) const override {
2193 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
2195 // 0-15 are the 16 integer registers.
2197 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
2201 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
2202 StringRef Constraint,
2203 llvm::Type* Ty) const override {
2204 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
2207 bool isNoProtoCallVariadic(const CallArgList &args,
2208 const FunctionNoProtoType *fnType) const override {
2209 // The default CC on x86-64 sets %al to the number of SSA
2210 // registers used, and GCC sets this when calling an unprototyped
2211 // function, so we override the default behavior. However, don't do
2212 // that when AVX types are involved: the ABI explicitly states it is
2213 // undefined, and it doesn't work in practice because of how the ABI
2214 // defines varargs anyway.
2215 if (fnType->getCallConv() == CC_C) {
2216 bool HasAVXType = false;
2217 for (CallArgList::const_iterator
2218 it = args.begin(), ie = args.end(); it != ie; ++it) {
2219 if (getABIInfo().isPassedUsingAVXType(it->Ty)) {
2229 return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
2233 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
2235 if (getABIInfo().has64BitPointers())
2236 Sig = (0xeb << 0) | // jmp rel8
2237 (0x0a << 8) | // .+0x0c
2241 Sig = (0xeb << 0) | // jmp rel8
2242 (0x06 << 8) | // .+0x08
2245 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
2248 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2249 CodeGen::CodeGenModule &CGM) const override {
2250 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2251 if (FD->hasAttr<AnyX86InterruptAttr>()) {
2252 llvm::Function *Fn = cast<llvm::Function>(GV);
2253 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
2259 class PS4TargetCodeGenInfo : public X86_64TargetCodeGenInfo {
2261 PS4TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
2262 : X86_64TargetCodeGenInfo(CGT, AVXLevel) {}
2264 void getDependentLibraryOption(llvm::StringRef Lib,
2265 llvm::SmallString<24> &Opt) const override {
2267 // If the argument contains a space, enclose it in quotes.
2268 if (Lib.find(" ") != StringRef::npos)
2269 Opt += "\"" + Lib.str() + "\"";
2275 static std::string qualifyWindowsLibrary(llvm::StringRef Lib) {
2276 // If the argument does not end in .lib, automatically add the suffix.
2277 // If the argument contains a space, enclose it in quotes.
2278 // This matches the behavior of MSVC.
2279 bool Quote = (Lib.find(" ") != StringRef::npos);
2280 std::string ArgStr = Quote ? "\"" : "";
2282 if (!Lib.endswith_lower(".lib"))
2284 ArgStr += Quote ? "\"" : "";
2288 class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
2290 WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
2291 bool DarwinVectorABI, bool RetSmallStructInRegABI, bool Win32StructABI,
2292 unsigned NumRegisterParameters)
2293 : X86_32TargetCodeGenInfo(CGT, DarwinVectorABI, RetSmallStructInRegABI,
2294 Win32StructABI, NumRegisterParameters, false) {}
2296 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2297 CodeGen::CodeGenModule &CGM) const override;
2299 void getDependentLibraryOption(llvm::StringRef Lib,
2300 llvm::SmallString<24> &Opt) const override {
2301 Opt = "/DEFAULTLIB:";
2302 Opt += qualifyWindowsLibrary(Lib);
2305 void getDetectMismatchOption(llvm::StringRef Name,
2306 llvm::StringRef Value,
2307 llvm::SmallString<32> &Opt) const override {
2308 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
2312 static void addStackProbeSizeTargetAttribute(const Decl *D,
2313 llvm::GlobalValue *GV,
2314 CodeGen::CodeGenModule &CGM) {
2315 if (D && isa<FunctionDecl>(D)) {
2316 if (CGM.getCodeGenOpts().StackProbeSize != 4096) {
2317 llvm::Function *Fn = cast<llvm::Function>(GV);
2319 Fn->addFnAttr("stack-probe-size",
2320 llvm::utostr(CGM.getCodeGenOpts().StackProbeSize));
2325 void WinX86_32TargetCodeGenInfo::setTargetAttributes(const Decl *D,
2326 llvm::GlobalValue *GV,
2327 CodeGen::CodeGenModule &CGM) const {
2328 X86_32TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
2330 addStackProbeSizeTargetAttribute(D, GV, CGM);
2333 class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2335 WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
2336 X86AVXABILevel AVXLevel)
2337 : TargetCodeGenInfo(new WinX86_64ABIInfo(CGT)) {}
2339 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2340 CodeGen::CodeGenModule &CGM) const override;
2342 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
2346 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2347 llvm::Value *Address) const override {
2348 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
2350 // 0-15 are the 16 integer registers.
2352 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
2356 void getDependentLibraryOption(llvm::StringRef Lib,
2357 llvm::SmallString<24> &Opt) const override {
2358 Opt = "/DEFAULTLIB:";
2359 Opt += qualifyWindowsLibrary(Lib);
2362 void getDetectMismatchOption(llvm::StringRef Name,
2363 llvm::StringRef Value,
2364 llvm::SmallString<32> &Opt) const override {
2365 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
2369 void WinX86_64TargetCodeGenInfo::setTargetAttributes(const Decl *D,
2370 llvm::GlobalValue *GV,
2371 CodeGen::CodeGenModule &CGM) const {
2372 TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
2374 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2375 if (FD->hasAttr<AnyX86InterruptAttr>()) {
2376 llvm::Function *Fn = cast<llvm::Function>(GV);
2377 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
2381 addStackProbeSizeTargetAttribute(D, GV, CGM);
2385 void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
2387 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
2389 // (a) If one of the classes is Memory, the whole argument is passed in
2392 // (b) If X87UP is not preceded by X87, the whole argument is passed in
2395 // (c) If the size of the aggregate exceeds two eightbytes and the first
2396 // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
2397 // argument is passed in memory. NOTE: This is necessary to keep the
2398 // ABI working for processors that don't support the __m256 type.
2400 // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
2402 // Some of these are enforced by the merging logic. Others can arise
2403 // only with unions; for example:
2404 // union { _Complex double; unsigned; }
2406 // Note that clauses (b) and (c) were added in 0.98.
2410 if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
2412 if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
2414 if (Hi == SSEUp && Lo != SSE)
2418 X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
2419 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
2420 // classified recursively so that always two fields are
2421 // considered. The resulting class is calculated according to
2422 // the classes of the fields in the eightbyte:
2424 // (a) If both classes are equal, this is the resulting class.
2426 // (b) If one of the classes is NO_CLASS, the resulting class is
2429 // (c) If one of the classes is MEMORY, the result is the MEMORY
2432 // (d) If one of the classes is INTEGER, the result is the
2435 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
2436 // MEMORY is used as class.
2438 // (f) Otherwise class SSE is used.
2440 // Accum should never be memory (we should have returned) or
2441 // ComplexX87 (because this cannot be passed in a structure).
2442 assert((Accum != Memory && Accum != ComplexX87) &&
2443 "Invalid accumulated classification during merge.");
2444 if (Accum == Field || Field == NoClass)
2446 if (Field == Memory)
2448 if (Accum == NoClass)
2450 if (Accum == Integer || Field == Integer)
2452 if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
2453 Accum == X87 || Accum == X87Up)
2458 void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
2459 Class &Lo, Class &Hi, bool isNamedArg) const {
2460 // FIXME: This code can be simplified by introducing a simple value class for
2461 // Class pairs with appropriate constructor methods for the various
2464 // FIXME: Some of the split computations are wrong; unaligned vectors
2465 // shouldn't be passed in registers for example, so there is no chance they
2466 // can straddle an eightbyte. Verify & simplify.
2470 Class &Current = OffsetBase < 64 ? Lo : Hi;
2473 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
2474 BuiltinType::Kind k = BT->getKind();
2476 if (k == BuiltinType::Void) {
2478 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
2481 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
2483 } else if (k == BuiltinType::Float || k == BuiltinType::Double) {
2485 } else if (k == BuiltinType::LongDouble) {
2486 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
2487 if (LDF == &llvm::APFloat::IEEEquad()) {
2490 } else if (LDF == &llvm::APFloat::x87DoubleExtended()) {
2493 } else if (LDF == &llvm::APFloat::IEEEdouble()) {
2496 llvm_unreachable("unexpected long double representation!");
2498 // FIXME: _Decimal32 and _Decimal64 are SSE.
2499 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
2503 if (const EnumType *ET = Ty->getAs<EnumType>()) {
2504 // Classify the underlying integer type.
2505 classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
2509 if (Ty->hasPointerRepresentation()) {
2514 if (Ty->isMemberPointerType()) {
2515 if (Ty->isMemberFunctionPointerType()) {
2516 if (Has64BitPointers) {
2517 // If Has64BitPointers, this is an {i64, i64}, so classify both
2521 // Otherwise, with 32-bit pointers, this is an {i32, i32}. If that
2522 // straddles an eightbyte boundary, Hi should be classified as well.
2523 uint64_t EB_FuncPtr = (OffsetBase) / 64;
2524 uint64_t EB_ThisAdj = (OffsetBase + 64 - 1) / 64;
2525 if (EB_FuncPtr != EB_ThisAdj) {
2537 if (const VectorType *VT = Ty->getAs<VectorType>()) {
2538 uint64_t Size = getContext().getTypeSize(VT);
2539 if (Size == 1 || Size == 8 || Size == 16 || Size == 32) {
2540 // gcc passes the following as integer:
2541 // 4 bytes - <4 x char>, <2 x short>, <1 x int>, <1 x float>
2542 // 2 bytes - <2 x char>, <1 x short>
2543 // 1 byte - <1 x char>
2546 // If this type crosses an eightbyte boundary, it should be
2548 uint64_t EB_Lo = (OffsetBase) / 64;
2549 uint64_t EB_Hi = (OffsetBase + Size - 1) / 64;
2552 } else if (Size == 64) {
2553 QualType ElementType = VT->getElementType();
2555 // gcc passes <1 x double> in memory. :(
2556 if (ElementType->isSpecificBuiltinType(BuiltinType::Double))
2559 // gcc passes <1 x long long> as SSE but clang used to unconditionally
2560 // pass them as integer. For platforms where clang is the de facto
2561 // platform compiler, we must continue to use integer.
2562 if (!classifyIntegerMMXAsSSE() &&
2563 (ElementType->isSpecificBuiltinType(BuiltinType::LongLong) ||
2564 ElementType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
2565 ElementType->isSpecificBuiltinType(BuiltinType::Long) ||
2566 ElementType->isSpecificBuiltinType(BuiltinType::ULong)))
2571 // If this type crosses an eightbyte boundary, it should be
2573 if (OffsetBase && OffsetBase != 64)
2575 } else if (Size == 128 ||
2576 (isNamedArg && Size <= getNativeVectorSizeForAVXABI(AVXLevel))) {
2577 // Arguments of 256-bits are split into four eightbyte chunks. The
2578 // least significant one belongs to class SSE and all the others to class
2579 // SSEUP. The original Lo and Hi design considers that types can't be
2580 // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
2581 // This design isn't correct for 256-bits, but since there're no cases
2582 // where the upper parts would need to be inspected, avoid adding
2583 // complexity and just consider Hi to match the 64-256 part.
2585 // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
2586 // registers if they are "named", i.e. not part of the "..." of a
2587 // variadic function.
2589 // Similarly, per 3.2.3. of the AVX512 draft, 512-bits ("named") args are
2590 // split into eight eightbyte chunks, one SSE and seven SSEUP.
2597 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
2598 QualType ET = getContext().getCanonicalType(CT->getElementType());
2600 uint64_t Size = getContext().getTypeSize(Ty);
2601 if (ET->isIntegralOrEnumerationType()) {
2604 else if (Size <= 128)
2606 } else if (ET == getContext().FloatTy) {
2608 } else if (ET == getContext().DoubleTy) {
2610 } else if (ET == getContext().LongDoubleTy) {
2611 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
2612 if (LDF == &llvm::APFloat::IEEEquad())
2614 else if (LDF == &llvm::APFloat::x87DoubleExtended())
2615 Current = ComplexX87;
2616 else if (LDF == &llvm::APFloat::IEEEdouble())
2619 llvm_unreachable("unexpected long double representation!");
2622 // If this complex type crosses an eightbyte boundary then it
2624 uint64_t EB_Real = (OffsetBase) / 64;
2625 uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
2626 if (Hi == NoClass && EB_Real != EB_Imag)
2632 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
2633 // Arrays are treated like structures.
2635 uint64_t Size = getContext().getTypeSize(Ty);
2637 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
2638 // than eight eightbytes, ..., it has class MEMORY.
2642 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
2643 // fields, it has class MEMORY.
2645 // Only need to check alignment of array base.
2646 if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
2649 // Otherwise implement simplified merge. We could be smarter about
2650 // this, but it isn't worth it and would be harder to verify.
2652 uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
2653 uint64_t ArraySize = AT->getSize().getZExtValue();
2655 // The only case a 256-bit wide vector could be used is when the array
2656 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2657 // to work for sizes wider than 128, early check and fallback to memory.
2660 (Size != EltSize || Size > getNativeVectorSizeForAVXABI(AVXLevel)))
2663 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
2664 Class FieldLo, FieldHi;
2665 classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
2666 Lo = merge(Lo, FieldLo);
2667 Hi = merge(Hi, FieldHi);
2668 if (Lo == Memory || Hi == Memory)
2672 postMerge(Size, Lo, Hi);
2673 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
2677 if (const RecordType *RT = Ty->getAs<RecordType>()) {
2678 uint64_t Size = getContext().getTypeSize(Ty);
2680 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
2681 // than eight eightbytes, ..., it has class MEMORY.
2685 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
2686 // copy constructor or a non-trivial destructor, it is passed by invisible
2688 if (getRecordArgABI(RT, getCXXABI()))
2691 const RecordDecl *RD = RT->getDecl();
2693 // Assume variable sized types are passed in memory.
2694 if (RD->hasFlexibleArrayMember())
2697 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
2699 // Reset Lo class, this will be recomputed.
2702 // If this is a C++ record, classify the bases first.
2703 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
2704 for (const auto &I : CXXRD->bases()) {
2705 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
2706 "Unexpected base class!");
2707 const CXXRecordDecl *Base =
2708 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
2710 // Classify this field.
2712 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
2713 // single eightbyte, each is classified separately. Each eightbyte gets
2714 // initialized to class NO_CLASS.
2715 Class FieldLo, FieldHi;
2717 OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
2718 classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg);
2719 Lo = merge(Lo, FieldLo);
2720 Hi = merge(Hi, FieldHi);
2721 if (Lo == Memory || Hi == Memory) {
2722 postMerge(Size, Lo, Hi);
2728 // Classify the fields one at a time, merging the results.
2730 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
2731 i != e; ++i, ++idx) {
2732 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
2733 bool BitField = i->isBitField();
2735 // Ignore padding bit-fields.
2736 if (BitField && i->isUnnamedBitfield())
2739 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
2740 // four eightbytes, or it contains unaligned fields, it has class MEMORY.
2742 // The only case a 256-bit wide vector could be used is when the struct
2743 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2744 // to work for sizes wider than 128, early check and fallback to memory.
2746 if (Size > 128 && (Size != getContext().getTypeSize(i->getType()) ||
2747 Size > getNativeVectorSizeForAVXABI(AVXLevel))) {
2749 postMerge(Size, Lo, Hi);
2752 // Note, skip this test for bit-fields, see below.
2753 if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
2755 postMerge(Size, Lo, Hi);
2759 // Classify this field.
2761 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
2762 // exceeds a single eightbyte, each is classified
2763 // separately. Each eightbyte gets initialized to class
2765 Class FieldLo, FieldHi;
2767 // Bit-fields require special handling, they do not force the
2768 // structure to be passed in memory even if unaligned, and
2769 // therefore they can straddle an eightbyte.
2771 assert(!i->isUnnamedBitfield());
2772 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
2773 uint64_t Size = i->getBitWidthValue(getContext());
2775 uint64_t EB_Lo = Offset / 64;
2776 uint64_t EB_Hi = (Offset + Size - 1) / 64;
2779 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
2784 FieldHi = EB_Hi ? Integer : NoClass;
2787 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
2788 Lo = merge(Lo, FieldLo);
2789 Hi = merge(Hi, FieldHi);
2790 if (Lo == Memory || Hi == Memory)
2794 postMerge(Size, Lo, Hi);
2798 ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
2799 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2801 if (!isAggregateTypeForABI(Ty)) {
2802 // Treat an enum type as its underlying type.
2803 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2804 Ty = EnumTy->getDecl()->getIntegerType();
2806 return (Ty->isPromotableIntegerType() ?
2807 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
2810 return getNaturalAlignIndirect(Ty);
2813 bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
2814 if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
2815 uint64_t Size = getContext().getTypeSize(VecTy);
2816 unsigned LargestVector = getNativeVectorSizeForAVXABI(AVXLevel);
2817 if (Size <= 64 || Size > LargestVector)
2824 ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
2825 unsigned freeIntRegs) const {
2826 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2829 // This assumption is optimistic, as there could be free registers available
2830 // when we need to pass this argument in memory, and LLVM could try to pass
2831 // the argument in the free register. This does not seem to happen currently,
2832 // but this code would be much safer if we could mark the argument with
2833 // 'onstack'. See PR12193.
2834 if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty)) {
2835 // Treat an enum type as its underlying type.
2836 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2837 Ty = EnumTy->getDecl()->getIntegerType();
2839 return (Ty->isPromotableIntegerType() ?
2840 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
2843 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
2844 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
2846 // Compute the byval alignment. We specify the alignment of the byval in all
2847 // cases so that the mid-level optimizer knows the alignment of the byval.
2848 unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
2850 // Attempt to avoid passing indirect results using byval when possible. This
2851 // is important for good codegen.
2853 // We do this by coercing the value into a scalar type which the backend can
2854 // handle naturally (i.e., without using byval).
2856 // For simplicity, we currently only do this when we have exhausted all of the
2857 // free integer registers. Doing this when there are free integer registers
2858 // would require more care, as we would have to ensure that the coerced value
2859 // did not claim the unused register. That would require either reording the
2860 // arguments to the function (so that any subsequent inreg values came first),
2861 // or only doing this optimization when there were no following arguments that
2864 // We currently expect it to be rare (particularly in well written code) for
2865 // arguments to be passed on the stack when there are still free integer
2866 // registers available (this would typically imply large structs being passed
2867 // by value), so this seems like a fair tradeoff for now.
2869 // We can revisit this if the backend grows support for 'onstack' parameter
2870 // attributes. See PR12193.
2871 if (freeIntRegs == 0) {
2872 uint64_t Size = getContext().getTypeSize(Ty);
2874 // If this type fits in an eightbyte, coerce it into the matching integral
2875 // type, which will end up on the stack (with alignment 8).
2876 if (Align == 8 && Size <= 64)
2877 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2881 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(Align));
2884 /// The ABI specifies that a value should be passed in a full vector XMM/YMM
2885 /// register. Pick an LLVM IR type that will be passed as a vector register.
2886 llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
2887 // Wrapper structs/arrays that only contain vectors are passed just like
2888 // vectors; strip them off if present.
2889 if (const Type *InnerTy = isSingleElementStruct(Ty, getContext()))
2890 Ty = QualType(InnerTy, 0);
2892 llvm::Type *IRType = CGT.ConvertType(Ty);
2893 if (isa<llvm::VectorType>(IRType) ||
2894 IRType->getTypeID() == llvm::Type::FP128TyID)
2897 // We couldn't find the preferred IR vector type for 'Ty'.
2898 uint64_t Size = getContext().getTypeSize(Ty);
2899 assert((Size == 128 || Size == 256 || Size == 512) && "Invalid type found!");
2901 // Return a LLVM IR vector type based on the size of 'Ty'.
2902 return llvm::VectorType::get(llvm::Type::getDoubleTy(getVMContext()),
2906 /// BitsContainNoUserData - Return true if the specified [start,end) bit range
2907 /// is known to either be off the end of the specified type or being in
2908 /// alignment padding. The user type specified is known to be at most 128 bits
2909 /// in size, and have passed through X86_64ABIInfo::classify with a successful
2910 /// classification that put one of the two halves in the INTEGER class.
2912 /// It is conservatively correct to return false.
2913 static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
2914 unsigned EndBit, ASTContext &Context) {
2915 // If the bytes being queried are off the end of the type, there is no user
2916 // data hiding here. This handles analysis of builtins, vectors and other
2917 // types that don't contain interesting padding.
2918 unsigned TySize = (unsigned)Context.getTypeSize(Ty);
2919 if (TySize <= StartBit)
2922 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
2923 unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
2924 unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
2926 // Check each element to see if the element overlaps with the queried range.
2927 for (unsigned i = 0; i != NumElts; ++i) {
2928 // If the element is after the span we care about, then we're done..
2929 unsigned EltOffset = i*EltSize;
2930 if (EltOffset >= EndBit) break;
2932 unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
2933 if (!BitsContainNoUserData(AT->getElementType(), EltStart,
2934 EndBit-EltOffset, Context))
2937 // If it overlaps no elements, then it is safe to process as padding.
2941 if (const RecordType *RT = Ty->getAs<RecordType>()) {
2942 const RecordDecl *RD = RT->getDecl();
2943 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
2945 // If this is a C++ record, check the bases first.
2946 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
2947 for (const auto &I : CXXRD->bases()) {
2948 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
2949 "Unexpected base class!");
2950 const CXXRecordDecl *Base =
2951 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
2953 // If the base is after the span we care about, ignore it.
2954 unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
2955 if (BaseOffset >= EndBit) continue;
2957 unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
2958 if (!BitsContainNoUserData(I.getType(), BaseStart,
2959 EndBit-BaseOffset, Context))
2964 // Verify that no field has data that overlaps the region of interest. Yes
2965 // this could be sped up a lot by being smarter about queried fields,
2966 // however we're only looking at structs up to 16 bytes, so we don't care
2969 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
2970 i != e; ++i, ++idx) {
2971 unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
2973 // If we found a field after the region we care about, then we're done.
2974 if (FieldOffset >= EndBit) break;
2976 unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
2977 if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
2982 // If nothing in this record overlapped the area of interest, then we're
2990 /// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a
2991 /// float member at the specified offset. For example, {int,{float}} has a
2992 /// float at offset 4. It is conservatively correct for this routine to return
2994 static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset,
2995 const llvm::DataLayout &TD) {
2996 // Base case if we find a float.
2997 if (IROffset == 0 && IRType->isFloatTy())
3000 // If this is a struct, recurse into the field at the specified offset.
3001 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
3002 const llvm::StructLayout *SL = TD.getStructLayout(STy);
3003 unsigned Elt = SL->getElementContainingOffset(IROffset);
3004 IROffset -= SL->getElementOffset(Elt);
3005 return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD);
3008 // If this is an array, recurse into the field at the specified offset.
3009 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
3010 llvm::Type *EltTy = ATy->getElementType();
3011 unsigned EltSize = TD.getTypeAllocSize(EltTy);
3012 IROffset -= IROffset/EltSize*EltSize;
3013 return ContainsFloatAtOffset(EltTy, IROffset, TD);
3020 /// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
3021 /// low 8 bytes of an XMM register, corresponding to the SSE class.
3022 llvm::Type *X86_64ABIInfo::
3023 GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
3024 QualType SourceTy, unsigned SourceOffset) const {
3025 // The only three choices we have are either double, <2 x float>, or float. We
3026 // pass as float if the last 4 bytes is just padding. This happens for
3027 // structs that contain 3 floats.
3028 if (BitsContainNoUserData(SourceTy, SourceOffset*8+32,
3029 SourceOffset*8+64, getContext()))
3030 return llvm::Type::getFloatTy(getVMContext());
3032 // We want to pass as <2 x float> if the LLVM IR type contains a float at
3033 // offset+0 and offset+4. Walk the LLVM IR type to find out if this is the
3035 if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) &&
3036 ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout()))
3037 return llvm::VectorType::get(llvm::Type::getFloatTy(getVMContext()), 2);
3039 return llvm::Type::getDoubleTy(getVMContext());
3043 /// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
3044 /// an 8-byte GPR. This means that we either have a scalar or we are talking
3045 /// about the high or low part of an up-to-16-byte struct. This routine picks
3046 /// the best LLVM IR type to represent this, which may be i64 or may be anything
3047 /// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
3050 /// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
3051 /// the source type. IROffset is an offset in bytes into the LLVM IR type that
3052 /// the 8-byte value references. PrefType may be null.
3054 /// SourceTy is the source-level type for the entire argument. SourceOffset is
3055 /// an offset into this that we're processing (which is always either 0 or 8).
3057 llvm::Type *X86_64ABIInfo::
3058 GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
3059 QualType SourceTy, unsigned SourceOffset) const {
3060 // If we're dealing with an un-offset LLVM IR type, then it means that we're
3061 // returning an 8-byte unit starting with it. See if we can safely use it.
3062 if (IROffset == 0) {
3063 // Pointers and int64's always fill the 8-byte unit.
3064 if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
3065 IRType->isIntegerTy(64))
3068 // If we have a 1/2/4-byte integer, we can use it only if the rest of the
3069 // goodness in the source type is just tail padding. This is allowed to
3070 // kick in for struct {double,int} on the int, but not on
3071 // struct{double,int,int} because we wouldn't return the second int. We
3072 // have to do this analysis on the source type because we can't depend on
3073 // unions being lowered a specific way etc.
3074 if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
3075 IRType->isIntegerTy(32) ||
3076 (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
3077 unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
3078 cast<llvm::IntegerType>(IRType)->getBitWidth();
3080 if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
3081 SourceOffset*8+64, getContext()))
3086 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
3087 // If this is a struct, recurse into the field at the specified offset.
3088 const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
3089 if (IROffset < SL->getSizeInBytes()) {
3090 unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
3091 IROffset -= SL->getElementOffset(FieldIdx);
3093 return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
3094 SourceTy, SourceOffset);
3098 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
3099 llvm::Type *EltTy = ATy->getElementType();
3100 unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
3101 unsigned EltOffset = IROffset/EltSize*EltSize;
3102 return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
3106 // Okay, we don't have any better idea of what to pass, so we pass this in an
3107 // integer register that isn't too big to fit the rest of the struct.
3108 unsigned TySizeInBytes =
3109 (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
3111 assert(TySizeInBytes != SourceOffset && "Empty field?");
3113 // It is always safe to classify this as an integer type up to i64 that
3114 // isn't larger than the structure.
3115 return llvm::IntegerType::get(getVMContext(),
3116 std::min(TySizeInBytes-SourceOffset, 8U)*8);
3120 /// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
3121 /// be used as elements of a two register pair to pass or return, return a
3122 /// first class aggregate to represent them. For example, if the low part of
3123 /// a by-value argument should be passed as i32* and the high part as float,
3124 /// return {i32*, float}.
3126 GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
3127 const llvm::DataLayout &TD) {
3128 // In order to correctly satisfy the ABI, we need to the high part to start
3129 // at offset 8. If the high and low parts we inferred are both 4-byte types
3130 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
3131 // the second element at offset 8. Check for this:
3132 unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
3133 unsigned HiAlign = TD.getABITypeAlignment(Hi);
3134 unsigned HiStart = llvm::alignTo(LoSize, HiAlign);
3135 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
3137 // To handle this, we have to increase the size of the low part so that the
3138 // second element will start at an 8 byte offset. We can't increase the size
3139 // of the second element because it might make us access off the end of the
3142 // There are usually two sorts of types the ABI generation code can produce
3143 // for the low part of a pair that aren't 8 bytes in size: float or
3144 // i8/i16/i32. This can also include pointers when they are 32-bit (X32 and
3146 // Promote these to a larger type.
3147 if (Lo->isFloatTy())
3148 Lo = llvm::Type::getDoubleTy(Lo->getContext());
3150 assert((Lo->isIntegerTy() || Lo->isPointerTy())
3151 && "Invalid/unknown lo type");
3152 Lo = llvm::Type::getInt64Ty(Lo->getContext());
3156 llvm::StructType *Result = llvm::StructType::get(Lo, Hi);
3158 // Verify that the second element is at an 8-byte offset.
3159 assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
3160 "Invalid x86-64 argument pair!");
3164 ABIArgInfo X86_64ABIInfo::
3165 classifyReturnType(QualType RetTy) const {
3166 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
3167 // classification algorithm.
3168 X86_64ABIInfo::Class Lo, Hi;
3169 classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
3171 // Check some invariants.
3172 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
3173 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
3175 llvm::Type *ResType = nullptr;
3179 return ABIArgInfo::getIgnore();
3180 // If the low part is just padding, it takes no register, leave ResType
3182 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3183 "Unknown missing lo part");
3188 llvm_unreachable("Invalid classification for lo word.");
3190 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
3193 return getIndirectReturnResult(RetTy);
3195 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
3196 // available register of the sequence %rax, %rdx is used.
3198 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
3200 // If we have a sign or zero extended integer, make sure to return Extend
3201 // so that the parameter gets the right LLVM IR attributes.
3202 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3203 // Treat an enum type as its underlying type.
3204 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
3205 RetTy = EnumTy->getDecl()->getIntegerType();
3207 if (RetTy->isIntegralOrEnumerationType() &&
3208 RetTy->isPromotableIntegerType())
3209 return ABIArgInfo::getExtend();
3213 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
3214 // available SSE register of the sequence %xmm0, %xmm1 is used.
3216 ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
3219 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
3220 // returned on the X87 stack in %st0 as 80-bit x87 number.
3222 ResType = llvm::Type::getX86_FP80Ty(getVMContext());
3225 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
3226 // part of the value is returned in %st0 and the imaginary part in
3229 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
3230 ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
3231 llvm::Type::getX86_FP80Ty(getVMContext()));
3235 llvm::Type *HighPart = nullptr;
3237 // Memory was handled previously and X87 should
3238 // never occur as a hi class.
3241 llvm_unreachable("Invalid classification for hi word.");
3243 case ComplexX87: // Previously handled.
3248 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
3249 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3250 return ABIArgInfo::getDirect(HighPart, 8);
3253 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
3254 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3255 return ABIArgInfo::getDirect(HighPart, 8);
3258 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
3259 // is passed in the next available eightbyte chunk if the last used
3262 // SSEUP should always be preceded by SSE, just widen.
3264 assert(Lo == SSE && "Unexpected SSEUp classification.");
3265 ResType = GetByteVectorType(RetTy);
3268 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
3269 // returned together with the previous X87 value in %st0.
3271 // If X87Up is preceded by X87, we don't need to do
3272 // anything. However, in some cases with unions it may not be
3273 // preceded by X87. In such situations we follow gcc and pass the
3274 // extra bits in an SSE reg.
3276 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
3277 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3278 return ABIArgInfo::getDirect(HighPart, 8);
3283 // If a high part was specified, merge it together with the low part. It is
3284 // known to pass in the high eightbyte of the result. We do this by forming a
3285 // first class struct aggregate with the high and low part: {low, high}
3287 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
3289 return ABIArgInfo::getDirect(ResType);
3292 ABIArgInfo X86_64ABIInfo::classifyArgumentType(
3293 QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE,
3297 Ty = useFirstFieldIfTransparentUnion(Ty);
3299 X86_64ABIInfo::Class Lo, Hi;
3300 classify(Ty, 0, Lo, Hi, isNamedArg);
3302 // Check some invariants.
3303 // FIXME: Enforce these by construction.
3304 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
3305 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
3309 llvm::Type *ResType = nullptr;
3313 return ABIArgInfo::getIgnore();
3314 // If the low part is just padding, it takes no register, leave ResType
3316 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3317 "Unknown missing lo part");
3320 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
3324 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
3325 // COMPLEX_X87, it is passed in memory.
3328 if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect)
3330 return getIndirectResult(Ty, freeIntRegs);
3334 llvm_unreachable("Invalid classification for lo word.");
3336 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
3337 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
3342 // Pick an 8-byte type based on the preferred type.
3343 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
3345 // If we have a sign or zero extended integer, make sure to return Extend
3346 // so that the parameter gets the right LLVM IR attributes.
3347 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3348 // Treat an enum type as its underlying type.
3349 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3350 Ty = EnumTy->getDecl()->getIntegerType();
3352 if (Ty->isIntegralOrEnumerationType() &&
3353 Ty->isPromotableIntegerType())
3354 return ABIArgInfo::getExtend();
3359 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
3360 // available SSE register is used, the registers are taken in the
3361 // order from %xmm0 to %xmm7.
3363 llvm::Type *IRType = CGT.ConvertType(Ty);
3364 ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
3370 llvm::Type *HighPart = nullptr;
3372 // Memory was handled previously, ComplexX87 and X87 should
3373 // never occur as hi classes, and X87Up must be preceded by X87,
3374 // which is passed in memory.
3378 llvm_unreachable("Invalid classification for hi word.");
3380 case NoClass: break;
3384 // Pick an 8-byte type based on the preferred type.
3385 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
3387 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
3388 return ABIArgInfo::getDirect(HighPart, 8);
3391 // X87Up generally doesn't occur here (long double is passed in
3392 // memory), except in situations involving unions.
3395 HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
3397 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
3398 return ABIArgInfo::getDirect(HighPart, 8);
3403 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
3404 // eightbyte is passed in the upper half of the last used SSE
3405 // register. This only happens when 128-bit vectors are passed.
3407 assert(Lo == SSE && "Unexpected SSEUp classification");
3408 ResType = GetByteVectorType(Ty);
3412 // If a high part was specified, merge it together with the low part. It is
3413 // known to pass in the high eightbyte of the result. We do this by forming a
3414 // first class struct aggregate with the high and low part: {low, high}
3416 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
3418 return ABIArgInfo::getDirect(ResType);
3422 X86_64ABIInfo::classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
3423 unsigned &NeededSSE) const {
3424 auto RT = Ty->getAs<RecordType>();
3425 assert(RT && "classifyRegCallStructType only valid with struct types");
3427 if (RT->getDecl()->hasFlexibleArrayMember())
3428 return getIndirectReturnResult(Ty);
3431 if (auto CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
3432 if (CXXRD->isDynamicClass()) {
3433 NeededInt = NeededSSE = 0;
3434 return getIndirectReturnResult(Ty);
3437 for (const auto &I : CXXRD->bases())
3438 if (classifyRegCallStructTypeImpl(I.getType(), NeededInt, NeededSSE)
3440 NeededInt = NeededSSE = 0;
3441 return getIndirectReturnResult(Ty);
3446 for (const auto *FD : RT->getDecl()->fields()) {
3447 if (FD->getType()->isRecordType() && !FD->getType()->isUnionType()) {
3448 if (classifyRegCallStructTypeImpl(FD->getType(), NeededInt, NeededSSE)
3450 NeededInt = NeededSSE = 0;
3451 return getIndirectReturnResult(Ty);
3454 unsigned LocalNeededInt, LocalNeededSSE;
3455 if (classifyArgumentType(FD->getType(), UINT_MAX, LocalNeededInt,
3456 LocalNeededSSE, true)
3458 NeededInt = NeededSSE = 0;
3459 return getIndirectReturnResult(Ty);
3461 NeededInt += LocalNeededInt;
3462 NeededSSE += LocalNeededSSE;
3466 return ABIArgInfo::getDirect();
3469 ABIArgInfo X86_64ABIInfo::classifyRegCallStructType(QualType Ty,
3470 unsigned &NeededInt,
3471 unsigned &NeededSSE) const {
3476 return classifyRegCallStructTypeImpl(Ty, NeededInt, NeededSSE);
3479 void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
3481 bool IsRegCall = FI.getCallingConvention() == llvm::CallingConv::X86_RegCall;
3483 // Keep track of the number of assigned registers.
3484 unsigned FreeIntRegs = IsRegCall ? 11 : 6;
3485 unsigned FreeSSERegs = IsRegCall ? 16 : 8;
3486 unsigned NeededInt, NeededSSE;
3488 if (IsRegCall && FI.getReturnType()->getTypePtr()->isRecordType() &&
3489 !FI.getReturnType()->getTypePtr()->isUnionType()) {
3490 FI.getReturnInfo() =
3491 classifyRegCallStructType(FI.getReturnType(), NeededInt, NeededSSE);
3492 if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
3493 FreeIntRegs -= NeededInt;
3494 FreeSSERegs -= NeededSSE;
3496 FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType());
3498 } else if (!getCXXABI().classifyReturnType(FI))
3499 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
3501 // If the return value is indirect, then the hidden argument is consuming one
3502 // integer register.
3503 if (FI.getReturnInfo().isIndirect())
3506 // The chain argument effectively gives us another free register.
3507 if (FI.isChainCall())
3510 unsigned NumRequiredArgs = FI.getNumRequiredArgs();
3511 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
3512 // get assigned (in left-to-right order) for passing as follows...
3514 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
3515 it != ie; ++it, ++ArgNo) {
3516 bool IsNamedArg = ArgNo < NumRequiredArgs;
3518 if (IsRegCall && it->type->isStructureOrClassType())
3519 it->info = classifyRegCallStructType(it->type, NeededInt, NeededSSE);
3521 it->info = classifyArgumentType(it->type, FreeIntRegs, NeededInt,
3522 NeededSSE, IsNamedArg);
3524 // AMD64-ABI 3.2.3p3: If there are no registers available for any
3525 // eightbyte of an argument, the whole argument is passed on the
3526 // stack. If registers have already been assigned for some
3527 // eightbytes of such an argument, the assignments get reverted.
3528 if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
3529 FreeIntRegs -= NeededInt;
3530 FreeSSERegs -= NeededSSE;
3532 it->info = getIndirectResult(it->type, FreeIntRegs);
3537 static Address EmitX86_64VAArgFromMemory(CodeGenFunction &CGF,
3538 Address VAListAddr, QualType Ty) {
3539 Address overflow_arg_area_p = CGF.Builder.CreateStructGEP(
3540 VAListAddr, 2, CharUnits::fromQuantity(8), "overflow_arg_area_p");
3541 llvm::Value *overflow_arg_area =
3542 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
3544 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
3545 // byte boundary if alignment needed by type exceeds 8 byte boundary.
3546 // It isn't stated explicitly in the standard, but in practice we use
3547 // alignment greater than 16 where necessary.
3548 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
3549 if (Align > CharUnits::fromQuantity(8)) {
3550 overflow_arg_area = emitRoundPointerUpToAlignment(CGF, overflow_arg_area,
3554 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
3555 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
3557 CGF.Builder.CreateBitCast(overflow_arg_area,
3558 llvm::PointerType::getUnqual(LTy));
3560 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
3561 // l->overflow_arg_area + sizeof(type).
3562 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
3563 // an 8 byte boundary.
3565 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
3566 llvm::Value *Offset =
3567 llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7);
3568 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
3569 "overflow_arg_area.next");
3570 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
3572 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
3573 return Address(Res, Align);
3576 Address X86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3577 QualType Ty) const {
3578 // Assume that va_list type is correct; should be pointer to LLVM type:
3582 // i8* overflow_arg_area;
3583 // i8* reg_save_area;
3585 unsigned neededInt, neededSSE;
3587 Ty = getContext().getCanonicalType(Ty);
3588 ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
3589 /*isNamedArg*/false);
3591 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
3592 // in the registers. If not go to step 7.
3593 if (!neededInt && !neededSSE)
3594 return EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
3596 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
3597 // general purpose registers needed to pass type and num_fp to hold
3598 // the number of floating point registers needed.
3600 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
3601 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
3602 // l->fp_offset > 304 - num_fp * 16 go to step 7.
3604 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
3605 // register save space).
3607 llvm::Value *InRegs = nullptr;
3608 Address gp_offset_p = Address::invalid(), fp_offset_p = Address::invalid();
3609 llvm::Value *gp_offset = nullptr, *fp_offset = nullptr;
3612 CGF.Builder.CreateStructGEP(VAListAddr, 0, CharUnits::Zero(),
3614 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
3615 InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
3616 InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
3621 CGF.Builder.CreateStructGEP(VAListAddr, 1, CharUnits::fromQuantity(4),
3623 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
3624 llvm::Value *FitsInFP =
3625 llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
3626 FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
3627 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
3630 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
3631 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
3632 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
3633 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
3635 // Emit code to load the value if it was passed in registers.
3637 CGF.EmitBlock(InRegBlock);
3639 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
3640 // an offset of l->gp_offset and/or l->fp_offset. This may require
3641 // copying to a temporary location in case the parameter is passed
3642 // in different register classes or requires an alignment greater
3643 // than 8 for general purpose registers and 16 for XMM registers.
3645 // FIXME: This really results in shameful code when we end up needing to
3646 // collect arguments from different places; often what should result in a
3647 // simple assembling of a structure from scattered addresses has many more
3648 // loads than necessary. Can we clean this up?
3649 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
3650 llvm::Value *RegSaveArea = CGF.Builder.CreateLoad(
3651 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(16)),
3654 Address RegAddr = Address::invalid();
3655 if (neededInt && neededSSE) {
3657 assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
3658 llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
3659 Address Tmp = CGF.CreateMemTemp(Ty);
3660 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
3661 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
3662 llvm::Type *TyLo = ST->getElementType(0);
3663 llvm::Type *TyHi = ST->getElementType(1);
3664 assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
3665 "Unexpected ABI info for mixed regs");
3666 llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
3667 llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
3668 llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegSaveArea, gp_offset);
3669 llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegSaveArea, fp_offset);
3670 llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr;
3671 llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr;
3673 // Copy the first element.
3674 // FIXME: Our choice of alignment here and below is probably pessimistic.
3675 llvm::Value *V = CGF.Builder.CreateAlignedLoad(
3676 TyLo, CGF.Builder.CreateBitCast(RegLoAddr, PTyLo),
3677 CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyLo)));
3678 CGF.Builder.CreateStore(V,
3679 CGF.Builder.CreateStructGEP(Tmp, 0, CharUnits::Zero()));
3681 // Copy the second element.
3682 V = CGF.Builder.CreateAlignedLoad(
3683 TyHi, CGF.Builder.CreateBitCast(RegHiAddr, PTyHi),
3684 CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyHi)));
3685 CharUnits Offset = CharUnits::fromQuantity(
3686 getDataLayout().getStructLayout(ST)->getElementOffset(1));
3687 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1, Offset));
3689 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
3690 } else if (neededInt) {
3691 RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, gp_offset),
3692 CharUnits::fromQuantity(8));
3693 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
3695 // Copy to a temporary if necessary to ensure the appropriate alignment.
3696 std::pair<CharUnits, CharUnits> SizeAlign =
3697 getContext().getTypeInfoInChars(Ty);
3698 uint64_t TySize = SizeAlign.first.getQuantity();
3699 CharUnits TyAlign = SizeAlign.second;
3701 // Copy into a temporary if the type is more aligned than the
3702 // register save area.
3703 if (TyAlign.getQuantity() > 8) {
3704 Address Tmp = CGF.CreateMemTemp(Ty);
3705 CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, false);
3709 } else if (neededSSE == 1) {
3710 RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
3711 CharUnits::fromQuantity(16));
3712 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
3714 assert(neededSSE == 2 && "Invalid number of needed registers!");
3715 // SSE registers are spaced 16 bytes apart in the register save
3716 // area, we need to collect the two eightbytes together.
3717 // The ABI isn't explicit about this, but it seems reasonable
3718 // to assume that the slots are 16-byte aligned, since the stack is
3719 // naturally 16-byte aligned and the prologue is expected to store
3720 // all the SSE registers to the RSA.
3721 Address RegAddrLo = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
3722 CharUnits::fromQuantity(16));
3724 CGF.Builder.CreateConstInBoundsByteGEP(RegAddrLo,
3725 CharUnits::fromQuantity(16));
3726 llvm::Type *DoubleTy = CGF.DoubleTy;
3727 llvm::StructType *ST = llvm::StructType::get(DoubleTy, DoubleTy);
3729 Address Tmp = CGF.CreateMemTemp(Ty);
3730 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
3731 V = CGF.Builder.CreateLoad(
3732 CGF.Builder.CreateElementBitCast(RegAddrLo, DoubleTy));
3733 CGF.Builder.CreateStore(V,
3734 CGF.Builder.CreateStructGEP(Tmp, 0, CharUnits::Zero()));
3735 V = CGF.Builder.CreateLoad(
3736 CGF.Builder.CreateElementBitCast(RegAddrHi, DoubleTy));
3737 CGF.Builder.CreateStore(V,
3738 CGF.Builder.CreateStructGEP(Tmp, 1, CharUnits::fromQuantity(8)));
3740 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
3743 // AMD64-ABI 3.5.7p5: Step 5. Set:
3744 // l->gp_offset = l->gp_offset + num_gp * 8
3745 // l->fp_offset = l->fp_offset + num_fp * 16.
3747 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
3748 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
3752 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
3753 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
3756 CGF.EmitBranch(ContBlock);
3758 // Emit code to load the value if it was passed in memory.
3760 CGF.EmitBlock(InMemBlock);
3761 Address MemAddr = EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
3763 // Return the appropriate result.
3765 CGF.EmitBlock(ContBlock);
3766 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, MemAddr, InMemBlock,
3771 Address X86_64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
3772 QualType Ty) const {
3773 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
3774 CGF.getContext().getTypeInfoInChars(Ty),
3775 CharUnits::fromQuantity(8),
3776 /*allowHigherAlign*/ false);
3780 WinX86_64ABIInfo::reclassifyHvaArgType(QualType Ty, unsigned &FreeSSERegs,
3781 const ABIArgInfo ¤t) const {
3782 // Assumes vectorCall calling convention.
3783 const Type *Base = nullptr;
3784 uint64_t NumElts = 0;
3786 if (!Ty->isBuiltinType() && !Ty->isVectorType() &&
3787 isHomogeneousAggregate(Ty, Base, NumElts) && FreeSSERegs >= NumElts) {
3788 FreeSSERegs -= NumElts;
3789 return getDirectX86Hva();
3794 ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, unsigned &FreeSSERegs,
3795 bool IsReturnType, bool IsVectorCall,
3796 bool IsRegCall) const {
3798 if (Ty->isVoidType())
3799 return ABIArgInfo::getIgnore();
3801 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3802 Ty = EnumTy->getDecl()->getIntegerType();
3804 TypeInfo Info = getContext().getTypeInfo(Ty);
3805 uint64_t Width = Info.Width;
3806 CharUnits Align = getContext().toCharUnitsFromBits(Info.Align);
3808 const RecordType *RT = Ty->getAs<RecordType>();
3810 if (!IsReturnType) {
3811 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
3812 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
3815 if (RT->getDecl()->hasFlexibleArrayMember())
3816 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
3820 const Type *Base = nullptr;
3821 uint64_t NumElts = 0;
3822 // vectorcall adds the concept of a homogenous vector aggregate, similar to
3824 if ((IsVectorCall || IsRegCall) &&
3825 isHomogeneousAggregate(Ty, Base, NumElts)) {
3827 if (FreeSSERegs >= NumElts) {
3828 FreeSSERegs -= NumElts;
3829 if (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())
3830 return ABIArgInfo::getDirect();
3831 return ABIArgInfo::getExpand();
3833 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3834 } else if (IsVectorCall) {
3835 if (FreeSSERegs >= NumElts &&
3836 (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())) {
3837 FreeSSERegs -= NumElts;
3838 return ABIArgInfo::getDirect();
3839 } else if (IsReturnType) {
3840 return ABIArgInfo::getExpand();
3841 } else if (!Ty->isBuiltinType() && !Ty->isVectorType()) {
3842 // HVAs are delayed and reclassified in the 2nd step.
3843 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3848 if (Ty->isMemberPointerType()) {
3849 // If the member pointer is represented by an LLVM int or ptr, pass it
3851 llvm::Type *LLTy = CGT.ConvertType(Ty);
3852 if (LLTy->isPointerTy() || LLTy->isIntegerTy())
3853 return ABIArgInfo::getDirect();
3856 if (RT || Ty->isAnyComplexType() || Ty->isMemberPointerType()) {
3857 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
3858 // not 1, 2, 4, or 8 bytes, must be passed by reference."
3859 if (Width > 64 || !llvm::isPowerOf2_64(Width))
3860 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
3862 // Otherwise, coerce it to a small integer.
3863 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Width));
3866 // Bool type is always extended to the ABI, other builtin types are not
3868 const BuiltinType *BT = Ty->getAs<BuiltinType>();
3869 if (BT && BT->getKind() == BuiltinType::Bool)
3870 return ABIArgInfo::getExtend();
3872 // Mingw64 GCC uses the old 80 bit extended precision floating point unit. It
3873 // passes them indirectly through memory.
3874 if (IsMingw64 && BT && BT->getKind() == BuiltinType::LongDouble) {
3875 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
3876 if (LDF == &llvm::APFloat::x87DoubleExtended())
3877 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3880 return ABIArgInfo::getDirect();
3883 void WinX86_64ABIInfo::computeVectorCallArgs(CGFunctionInfo &FI,
3884 unsigned FreeSSERegs,
3886 bool IsRegCall) const {
3888 for (auto &I : FI.arguments()) {
3889 // Vectorcall in x64 only permits the first 6 arguments to be passed
3890 // as XMM/YMM registers.
3891 if (Count < VectorcallMaxParamNumAsReg)
3892 I.info = classify(I.type, FreeSSERegs, false, IsVectorCall, IsRegCall);
3894 // Since these cannot be passed in registers, pretend no registers
3896 unsigned ZeroSSERegsAvail = 0;
3897 I.info = classify(I.type, /*FreeSSERegs=*/ZeroSSERegsAvail, false,
3898 IsVectorCall, IsRegCall);
3903 for (auto &I : FI.arguments()) {
3904 I.info = reclassifyHvaArgType(I.type, FreeSSERegs, I.info);
3908 void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
3910 FI.getCallingConvention() == llvm::CallingConv::X86_VectorCall;
3911 bool IsRegCall = FI.getCallingConvention() == llvm::CallingConv::X86_RegCall;
3913 unsigned FreeSSERegs = 0;
3915 // We can use up to 4 SSE return registers with vectorcall.
3917 } else if (IsRegCall) {
3918 // RegCall gives us 16 SSE registers.
3922 if (!getCXXABI().classifyReturnType(FI))
3923 FI.getReturnInfo() = classify(FI.getReturnType(), FreeSSERegs, true,
3924 IsVectorCall, IsRegCall);
3927 // We can use up to 6 SSE register parameters with vectorcall.
3929 } else if (IsRegCall) {
3930 // RegCall gives us 16 SSE registers, we can reuse the return registers.
3935 computeVectorCallArgs(FI, FreeSSERegs, IsVectorCall, IsRegCall);
3937 for (auto &I : FI.arguments())
3938 I.info = classify(I.type, FreeSSERegs, false, IsVectorCall, IsRegCall);
3943 Address WinX86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3944 QualType Ty) const {
3946 bool IsIndirect = false;
3948 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
3949 // not 1, 2, 4, or 8 bytes, must be passed by reference."
3950 if (isAggregateTypeForABI(Ty) || Ty->isMemberPointerType()) {
3951 uint64_t Width = getContext().getTypeSize(Ty);
3952 IsIndirect = Width > 64 || !llvm::isPowerOf2_64(Width);
3955 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
3956 CGF.getContext().getTypeInfoInChars(Ty),
3957 CharUnits::fromQuantity(8),
3958 /*allowHigherAlign*/ false);
3963 /// PPC32_SVR4_ABIInfo - The 32-bit PowerPC ELF (SVR4) ABI information.
3964 class PPC32_SVR4_ABIInfo : public DefaultABIInfo {
3965 bool IsSoftFloatABI;
3967 PPC32_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, bool SoftFloatABI)
3968 : DefaultABIInfo(CGT), IsSoftFloatABI(SoftFloatABI) {}
3970 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3971 QualType Ty) const override;
3974 class PPC32TargetCodeGenInfo : public TargetCodeGenInfo {
3976 PPC32TargetCodeGenInfo(CodeGenTypes &CGT, bool SoftFloatABI)
3977 : TargetCodeGenInfo(new PPC32_SVR4_ABIInfo(CGT, SoftFloatABI)) {}
3979 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
3980 // This is recovered from gcc output.
3981 return 1; // r1 is the dedicated stack pointer
3984 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3985 llvm::Value *Address) const override;
3990 // TODO: this implementation is now likely redundant with
3991 // DefaultABIInfo::EmitVAArg.
3992 Address PPC32_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAList,
3993 QualType Ty) const {
3994 const unsigned OverflowLimit = 8;
3995 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
3996 // TODO: Implement this. For now ignore.
3998 return Address::invalid(); // FIXME?
4001 // struct __va_list_tag {
4002 // unsigned char gpr;
4003 // unsigned char fpr;
4004 // unsigned short reserved;
4005 // void *overflow_arg_area;
4006 // void *reg_save_area;
4009 bool isI64 = Ty->isIntegerType() && getContext().getTypeSize(Ty) == 64;
4011 Ty->isIntegerType() || Ty->isPointerType() || Ty->isAggregateType();
4012 bool isF64 = Ty->isFloatingType() && getContext().getTypeSize(Ty) == 64;
4014 // All aggregates are passed indirectly? That doesn't seem consistent
4015 // with the argument-lowering code.
4016 bool isIndirect = Ty->isAggregateType();
4018 CGBuilderTy &Builder = CGF.Builder;
4020 // The calling convention either uses 1-2 GPRs or 1 FPR.
4021 Address NumRegsAddr = Address::invalid();
4022 if (isInt || IsSoftFloatABI) {
4023 NumRegsAddr = Builder.CreateStructGEP(VAList, 0, CharUnits::Zero(), "gpr");
4025 NumRegsAddr = Builder.CreateStructGEP(VAList, 1, CharUnits::One(), "fpr");
4028 llvm::Value *NumRegs = Builder.CreateLoad(NumRegsAddr, "numUsedRegs");
4030 // "Align" the register count when TY is i64.
4031 if (isI64 || (isF64 && IsSoftFloatABI)) {
4032 NumRegs = Builder.CreateAdd(NumRegs, Builder.getInt8(1));
4033 NumRegs = Builder.CreateAnd(NumRegs, Builder.getInt8((uint8_t) ~1U));
4037 Builder.CreateICmpULT(NumRegs, Builder.getInt8(OverflowLimit), "cond");
4039 llvm::BasicBlock *UsingRegs = CGF.createBasicBlock("using_regs");
4040 llvm::BasicBlock *UsingOverflow = CGF.createBasicBlock("using_overflow");
4041 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
4043 Builder.CreateCondBr(CC, UsingRegs, UsingOverflow);
4045 llvm::Type *DirectTy = CGF.ConvertType(Ty);
4046 if (isIndirect) DirectTy = DirectTy->getPointerTo(0);
4048 // Case 1: consume registers.
4049 Address RegAddr = Address::invalid();
4051 CGF.EmitBlock(UsingRegs);
4053 Address RegSaveAreaPtr =
4054 Builder.CreateStructGEP(VAList, 4, CharUnits::fromQuantity(8));
4055 RegAddr = Address(Builder.CreateLoad(RegSaveAreaPtr),
4056 CharUnits::fromQuantity(8));
4057 assert(RegAddr.getElementType() == CGF.Int8Ty);
4059 // Floating-point registers start after the general-purpose registers.
4060 if (!(isInt || IsSoftFloatABI)) {
4061 RegAddr = Builder.CreateConstInBoundsByteGEP(RegAddr,
4062 CharUnits::fromQuantity(32));
4065 // Get the address of the saved value by scaling the number of
4066 // registers we've used by the number of
4067 CharUnits RegSize = CharUnits::fromQuantity((isInt || IsSoftFloatABI) ? 4 : 8);
4068 llvm::Value *RegOffset =
4069 Builder.CreateMul(NumRegs, Builder.getInt8(RegSize.getQuantity()));
4070 RegAddr = Address(Builder.CreateInBoundsGEP(CGF.Int8Ty,
4071 RegAddr.getPointer(), RegOffset),
4072 RegAddr.getAlignment().alignmentOfArrayElement(RegSize));
4073 RegAddr = Builder.CreateElementBitCast(RegAddr, DirectTy);
4075 // Increase the used-register count.
4077 Builder.CreateAdd(NumRegs,
4078 Builder.getInt8((isI64 || (isF64 && IsSoftFloatABI)) ? 2 : 1));
4079 Builder.CreateStore(NumRegs, NumRegsAddr);
4081 CGF.EmitBranch(Cont);
4084 // Case 2: consume space in the overflow area.
4085 Address MemAddr = Address::invalid();
4087 CGF.EmitBlock(UsingOverflow);
4089 Builder.CreateStore(Builder.getInt8(OverflowLimit), NumRegsAddr);
4091 // Everything in the overflow area is rounded up to a size of at least 4.
4092 CharUnits OverflowAreaAlign = CharUnits::fromQuantity(4);
4096 auto TypeInfo = CGF.getContext().getTypeInfoInChars(Ty);
4097 Size = TypeInfo.first.alignTo(OverflowAreaAlign);
4099 Size = CGF.getPointerSize();
4102 Address OverflowAreaAddr =
4103 Builder.CreateStructGEP(VAList, 3, CharUnits::fromQuantity(4));
4104 Address OverflowArea(Builder.CreateLoad(OverflowAreaAddr, "argp.cur"),
4106 // Round up address of argument to alignment
4107 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
4108 if (Align > OverflowAreaAlign) {
4109 llvm::Value *Ptr = OverflowArea.getPointer();
4110 OverflowArea = Address(emitRoundPointerUpToAlignment(CGF, Ptr, Align),
4114 MemAddr = Builder.CreateElementBitCast(OverflowArea, DirectTy);
4116 // Increase the overflow area.
4117 OverflowArea = Builder.CreateConstInBoundsByteGEP(OverflowArea, Size);
4118 Builder.CreateStore(OverflowArea.getPointer(), OverflowAreaAddr);
4119 CGF.EmitBranch(Cont);
4122 CGF.EmitBlock(Cont);
4124 // Merge the cases with a phi.
4125 Address Result = emitMergePHI(CGF, RegAddr, UsingRegs, MemAddr, UsingOverflow,
4128 // Load the pointer if the argument was passed indirectly.
4130 Result = Address(Builder.CreateLoad(Result, "aggr"),
4131 getContext().getTypeAlignInChars(Ty));
4138 PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4139 llvm::Value *Address) const {
4140 // This is calculated from the LLVM and GCC tables and verified
4141 // against gcc output. AFAIK all ABIs use the same encoding.
4143 CodeGen::CGBuilderTy &Builder = CGF.Builder;
4145 llvm::IntegerType *i8 = CGF.Int8Ty;
4146 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
4147 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
4148 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
4150 // 0-31: r0-31, the 4-byte general-purpose registers
4151 AssignToArrayRange(Builder, Address, Four8, 0, 31);
4153 // 32-63: fp0-31, the 8-byte floating-point registers
4154 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
4156 // 64-76 are various 4-byte special-purpose registers:
4163 AssignToArrayRange(Builder, Address, Four8, 64, 76);
4165 // 77-108: v0-31, the 16-byte vector registers
4166 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
4173 AssignToArrayRange(Builder, Address, Four8, 109, 113);
4181 /// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
4182 class PPC64_SVR4_ABIInfo : public ABIInfo {
4190 static const unsigned GPRBits = 64;
4193 bool IsSoftFloatABI;
4195 // A vector of float or double will be promoted to <4 x f32> or <4 x f64> and
4196 // will be passed in a QPX register.
4197 bool IsQPXVectorTy(const Type *Ty) const {
4201 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4202 unsigned NumElements = VT->getNumElements();
4203 if (NumElements == 1)
4206 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double)) {
4207 if (getContext().getTypeSize(Ty) <= 256)
4209 } else if (VT->getElementType()->
4210 isSpecificBuiltinType(BuiltinType::Float)) {
4211 if (getContext().getTypeSize(Ty) <= 128)
4219 bool IsQPXVectorTy(QualType Ty) const {
4220 return IsQPXVectorTy(Ty.getTypePtr());
4224 PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind, bool HasQPX,
4226 : ABIInfo(CGT), Kind(Kind), HasQPX(HasQPX),
4227 IsSoftFloatABI(SoftFloatABI) {}
4229 bool isPromotableTypeForABI(QualType Ty) const;
4230 CharUnits getParamTypeAlignment(QualType Ty) const;
4232 ABIArgInfo classifyReturnType(QualType RetTy) const;
4233 ABIArgInfo classifyArgumentType(QualType Ty) const;
4235 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4236 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4237 uint64_t Members) const override;
4239 // TODO: We can add more logic to computeInfo to improve performance.
4240 // Example: For aggregate arguments that fit in a register, we could
4241 // use getDirectInReg (as is done below for structs containing a single
4242 // floating-point value) to avoid pushing them to memory on function
4243 // entry. This would require changing the logic in PPCISelLowering
4244 // when lowering the parameters in the caller and args in the callee.
4245 void computeInfo(CGFunctionInfo &FI) const override {
4246 if (!getCXXABI().classifyReturnType(FI))
4247 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
4248 for (auto &I : FI.arguments()) {
4249 // We rely on the default argument classification for the most part.
4250 // One exception: An aggregate containing a single floating-point
4251 // or vector item must be passed in a register if one is available.
4252 const Type *T = isSingleElementStruct(I.type, getContext());
4254 const BuiltinType *BT = T->getAs<BuiltinType>();
4255 if (IsQPXVectorTy(T) ||
4256 (T->isVectorType() && getContext().getTypeSize(T) == 128) ||
4257 (BT && BT->isFloatingPoint())) {
4259 I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
4263 I.info = classifyArgumentType(I.type);
4267 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4268 QualType Ty) const override;
4271 class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
4274 PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT,
4275 PPC64_SVR4_ABIInfo::ABIKind Kind, bool HasQPX,
4277 : TargetCodeGenInfo(new PPC64_SVR4_ABIInfo(CGT, Kind, HasQPX,
4280 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4281 // This is recovered from gcc output.
4282 return 1; // r1 is the dedicated stack pointer
4285 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4286 llvm::Value *Address) const override;
4289 class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
4291 PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
4293 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4294 // This is recovered from gcc output.
4295 return 1; // r1 is the dedicated stack pointer
4298 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4299 llvm::Value *Address) const override;
4304 // Return true if the ABI requires Ty to be passed sign- or zero-
4305 // extended to 64 bits.
4307 PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
4308 // Treat an enum type as its underlying type.
4309 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4310 Ty = EnumTy->getDecl()->getIntegerType();
4312 // Promotable integer types are required to be promoted by the ABI.
4313 if (Ty->isPromotableIntegerType())
4316 // In addition to the usual promotable integer types, we also need to
4317 // extend all 32-bit types, since the ABI requires promotion to 64 bits.
4318 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
4319 switch (BT->getKind()) {
4320 case BuiltinType::Int:
4321 case BuiltinType::UInt:
4330 /// isAlignedParamType - Determine whether a type requires 16-byte or
4331 /// higher alignment in the parameter area. Always returns at least 8.
4332 CharUnits PPC64_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const {
4333 // Complex types are passed just like their elements.
4334 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
4335 Ty = CTy->getElementType();
4337 // Only vector types of size 16 bytes need alignment (larger types are
4338 // passed via reference, smaller types are not aligned).
4339 if (IsQPXVectorTy(Ty)) {
4340 if (getContext().getTypeSize(Ty) > 128)
4341 return CharUnits::fromQuantity(32);
4343 return CharUnits::fromQuantity(16);
4344 } else if (Ty->isVectorType()) {
4345 return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16 : 8);
4348 // For single-element float/vector structs, we consider the whole type
4349 // to have the same alignment requirements as its single element.
4350 const Type *AlignAsType = nullptr;
4351 const Type *EltType = isSingleElementStruct(Ty, getContext());
4353 const BuiltinType *BT = EltType->getAs<BuiltinType>();
4354 if (IsQPXVectorTy(EltType) || (EltType->isVectorType() &&
4355 getContext().getTypeSize(EltType) == 128) ||
4356 (BT && BT->isFloatingPoint()))
4357 AlignAsType = EltType;
4360 // Likewise for ELFv2 homogeneous aggregates.
4361 const Type *Base = nullptr;
4362 uint64_t Members = 0;
4363 if (!AlignAsType && Kind == ELFv2 &&
4364 isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members))
4367 // With special case aggregates, only vector base types need alignment.
4368 if (AlignAsType && IsQPXVectorTy(AlignAsType)) {
4369 if (getContext().getTypeSize(AlignAsType) > 128)
4370 return CharUnits::fromQuantity(32);
4372 return CharUnits::fromQuantity(16);
4373 } else if (AlignAsType) {
4374 return CharUnits::fromQuantity(AlignAsType->isVectorType() ? 16 : 8);
4377 // Otherwise, we only need alignment for any aggregate type that
4378 // has an alignment requirement of >= 16 bytes.
4379 if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128) {
4380 if (HasQPX && getContext().getTypeAlign(Ty) >= 256)
4381 return CharUnits::fromQuantity(32);
4382 return CharUnits::fromQuantity(16);
4385 return CharUnits::fromQuantity(8);
4388 /// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous
4389 /// aggregate. Base is set to the base element type, and Members is set
4390 /// to the number of base elements.
4391 bool ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base,
4392 uint64_t &Members) const {
4393 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
4394 uint64_t NElements = AT->getSize().getZExtValue();
4397 if (!isHomogeneousAggregate(AT->getElementType(), Base, Members))
4399 Members *= NElements;
4400 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
4401 const RecordDecl *RD = RT->getDecl();
4402 if (RD->hasFlexibleArrayMember())
4407 // If this is a C++ record, check the bases first.
4408 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
4409 for (const auto &I : CXXRD->bases()) {
4410 // Ignore empty records.
4411 if (isEmptyRecord(getContext(), I.getType(), true))
4414 uint64_t FldMembers;
4415 if (!isHomogeneousAggregate(I.getType(), Base, FldMembers))
4418 Members += FldMembers;
4422 for (const auto *FD : RD->fields()) {
4423 // Ignore (non-zero arrays of) empty records.
4424 QualType FT = FD->getType();
4425 while (const ConstantArrayType *AT =
4426 getContext().getAsConstantArrayType(FT)) {
4427 if (AT->getSize().getZExtValue() == 0)
4429 FT = AT->getElementType();
4431 if (isEmptyRecord(getContext(), FT, true))
4434 // For compatibility with GCC, ignore empty bitfields in C++ mode.
4435 if (getContext().getLangOpts().CPlusPlus &&
4436 FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
4439 uint64_t FldMembers;
4440 if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers))
4443 Members = (RD->isUnion() ?
4444 std::max(Members, FldMembers) : Members + FldMembers);
4450 // Ensure there is no padding.
4451 if (getContext().getTypeSize(Base) * Members !=
4452 getContext().getTypeSize(Ty))
4456 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
4458 Ty = CT->getElementType();
4461 // Most ABIs only support float, double, and some vector type widths.
4462 if (!isHomogeneousAggregateBaseType(Ty))
4465 // The base type must be the same for all members. Types that
4466 // agree in both total size and mode (float vs. vector) are
4467 // treated as being equivalent here.
4468 const Type *TyPtr = Ty.getTypePtr();
4471 // If it's a non-power-of-2 vector, its size is already a power-of-2,
4472 // so make sure to widen it explicitly.
4473 if (const VectorType *VT = Base->getAs<VectorType>()) {
4474 QualType EltTy = VT->getElementType();
4475 unsigned NumElements =
4476 getContext().getTypeSize(VT) / getContext().getTypeSize(EltTy);
4478 .getVectorType(EltTy, NumElements, VT->getVectorKind())
4483 if (Base->isVectorType() != TyPtr->isVectorType() ||
4484 getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr))
4487 return Members > 0 && isHomogeneousAggregateSmallEnough(Base, Members);
4490 bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
4491 // Homogeneous aggregates for ELFv2 must have base types of float,
4492 // double, long double, or 128-bit vectors.
4493 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4494 if (BT->getKind() == BuiltinType::Float ||
4495 BT->getKind() == BuiltinType::Double ||
4496 BT->getKind() == BuiltinType::LongDouble) {
4502 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4503 if (getContext().getTypeSize(VT) == 128 || IsQPXVectorTy(Ty))
4509 bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateSmallEnough(
4510 const Type *Base, uint64_t Members) const {
4511 // Vector types require one register, floating point types require one
4512 // or two registers depending on their size.
4514 Base->isVectorType() ? 1 : (getContext().getTypeSize(Base) + 63) / 64;
4516 // Homogeneous Aggregates may occupy at most 8 registers.
4517 return Members * NumRegs <= 8;
4521 PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
4522 Ty = useFirstFieldIfTransparentUnion(Ty);
4524 if (Ty->isAnyComplexType())
4525 return ABIArgInfo::getDirect();
4527 // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes)
4528 // or via reference (larger than 16 bytes).
4529 if (Ty->isVectorType() && !IsQPXVectorTy(Ty)) {
4530 uint64_t Size = getContext().getTypeSize(Ty);
4532 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
4533 else if (Size < 128) {
4534 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
4535 return ABIArgInfo::getDirect(CoerceTy);
4539 if (isAggregateTypeForABI(Ty)) {
4540 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
4541 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
4543 uint64_t ABIAlign = getParamTypeAlignment(Ty).getQuantity();
4544 uint64_t TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity();
4546 // ELFv2 homogeneous aggregates are passed as array types.
4547 const Type *Base = nullptr;
4548 uint64_t Members = 0;
4549 if (Kind == ELFv2 &&
4550 isHomogeneousAggregate(Ty, Base, Members)) {
4551 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
4552 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
4553 return ABIArgInfo::getDirect(CoerceTy);
4556 // If an aggregate may end up fully in registers, we do not
4557 // use the ByVal method, but pass the aggregate as array.
4558 // This is usually beneficial since we avoid forcing the
4559 // back-end to store the argument to memory.
4560 uint64_t Bits = getContext().getTypeSize(Ty);
4561 if (Bits > 0 && Bits <= 8 * GPRBits) {
4562 llvm::Type *CoerceTy;
4564 // Types up to 8 bytes are passed as integer type (which will be
4565 // properly aligned in the argument save area doubleword).
4566 if (Bits <= GPRBits)
4568 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
4569 // Larger types are passed as arrays, with the base type selected
4570 // according to the required alignment in the save area.
4572 uint64_t RegBits = ABIAlign * 8;
4573 uint64_t NumRegs = llvm::alignTo(Bits, RegBits) / RegBits;
4574 llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits);
4575 CoerceTy = llvm::ArrayType::get(RegTy, NumRegs);
4578 return ABIArgInfo::getDirect(CoerceTy);
4581 // All other aggregates are passed ByVal.
4582 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
4584 /*Realign=*/TyAlign > ABIAlign);
4587 return (isPromotableTypeForABI(Ty) ?
4588 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
4592 PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
4593 if (RetTy->isVoidType())
4594 return ABIArgInfo::getIgnore();
4596 if (RetTy->isAnyComplexType())
4597 return ABIArgInfo::getDirect();
4599 // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes)
4600 // or via reference (larger than 16 bytes).
4601 if (RetTy->isVectorType() && !IsQPXVectorTy(RetTy)) {
4602 uint64_t Size = getContext().getTypeSize(RetTy);
4604 return getNaturalAlignIndirect(RetTy);
4605 else if (Size < 128) {
4606 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
4607 return ABIArgInfo::getDirect(CoerceTy);
4611 if (isAggregateTypeForABI(RetTy)) {
4612 // ELFv2 homogeneous aggregates are returned as array types.
4613 const Type *Base = nullptr;
4614 uint64_t Members = 0;
4615 if (Kind == ELFv2 &&
4616 isHomogeneousAggregate(RetTy, Base, Members)) {
4617 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
4618 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
4619 return ABIArgInfo::getDirect(CoerceTy);
4622 // ELFv2 small aggregates are returned in up to two registers.
4623 uint64_t Bits = getContext().getTypeSize(RetTy);
4624 if (Kind == ELFv2 && Bits <= 2 * GPRBits) {
4626 return ABIArgInfo::getIgnore();
4628 llvm::Type *CoerceTy;
4629 if (Bits > GPRBits) {
4630 CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits);
4631 CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy);
4634 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
4635 return ABIArgInfo::getDirect(CoerceTy);
4638 // All other aggregates are returned indirectly.
4639 return getNaturalAlignIndirect(RetTy);
4642 return (isPromotableTypeForABI(RetTy) ?
4643 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
4646 // Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
4647 Address PPC64_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4648 QualType Ty) const {
4649 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
4650 TypeInfo.second = getParamTypeAlignment(Ty);
4652 CharUnits SlotSize = CharUnits::fromQuantity(8);
4654 // If we have a complex type and the base type is smaller than 8 bytes,
4655 // the ABI calls for the real and imaginary parts to be right-adjusted
4656 // in separate doublewords. However, Clang expects us to produce a
4657 // pointer to a structure with the two parts packed tightly. So generate
4658 // loads of the real and imaginary parts relative to the va_list pointer,
4659 // and store them to a temporary structure.
4660 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
4661 CharUnits EltSize = TypeInfo.first / 2;
4662 if (EltSize < SlotSize) {
4663 Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, CGF.Int8Ty,
4664 SlotSize * 2, SlotSize,
4665 SlotSize, /*AllowHigher*/ true);
4667 Address RealAddr = Addr;
4668 Address ImagAddr = RealAddr;
4669 if (CGF.CGM.getDataLayout().isBigEndian()) {
4670 RealAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr,
4671 SlotSize - EltSize);
4672 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(ImagAddr,
4673 2 * SlotSize - EltSize);
4675 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, SlotSize);
4678 llvm::Type *EltTy = CGF.ConvertTypeForMem(CTy->getElementType());
4679 RealAddr = CGF.Builder.CreateElementBitCast(RealAddr, EltTy);
4680 ImagAddr = CGF.Builder.CreateElementBitCast(ImagAddr, EltTy);
4681 llvm::Value *Real = CGF.Builder.CreateLoad(RealAddr, ".vareal");
4682 llvm::Value *Imag = CGF.Builder.CreateLoad(ImagAddr, ".vaimag");
4684 Address Temp = CGF.CreateMemTemp(Ty, "vacplx");
4685 CGF.EmitStoreOfComplex({Real, Imag}, CGF.MakeAddrLValue(Temp, Ty),
4691 // Otherwise, just use the general rule.
4692 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
4693 TypeInfo, SlotSize, /*AllowHigher*/ true);
4697 PPC64_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4698 llvm::Value *Address) {
4699 // This is calculated from the LLVM and GCC tables and verified
4700 // against gcc output. AFAIK all ABIs use the same encoding.
4702 CodeGen::CGBuilderTy &Builder = CGF.Builder;
4704 llvm::IntegerType *i8 = CGF.Int8Ty;
4705 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
4706 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
4707 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
4709 // 0-31: r0-31, the 8-byte general-purpose registers
4710 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
4712 // 32-63: fp0-31, the 8-byte floating-point registers
4713 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
4715 // 64-67 are various 8-byte special-purpose registers:
4720 AssignToArrayRange(Builder, Address, Eight8, 64, 67);
4722 // 68-76 are various 4-byte special-purpose registers:
4725 AssignToArrayRange(Builder, Address, Four8, 68, 76);
4727 // 77-108: v0-31, the 16-byte vector registers
4728 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
4738 AssignToArrayRange(Builder, Address, Eight8, 109, 116);
4744 PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
4745 CodeGen::CodeGenFunction &CGF,
4746 llvm::Value *Address) const {
4748 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
4752 PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4753 llvm::Value *Address) const {
4755 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
4758 //===----------------------------------------------------------------------===//
4759 // AArch64 ABI Implementation
4760 //===----------------------------------------------------------------------===//
4764 class AArch64ABIInfo : public SwiftABIInfo {
4775 AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind)
4776 : SwiftABIInfo(CGT), Kind(Kind) {}
4779 ABIKind getABIKind() const { return Kind; }
4780 bool isDarwinPCS() const { return Kind == DarwinPCS; }
4782 ABIArgInfo classifyReturnType(QualType RetTy) const;
4783 ABIArgInfo classifyArgumentType(QualType RetTy) const;
4784 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4785 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4786 uint64_t Members) const override;
4788 bool isIllegalVectorType(QualType Ty) const;
4790 void computeInfo(CGFunctionInfo &FI) const override {
4791 if (!getCXXABI().classifyReturnType(FI))
4792 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
4794 for (auto &it : FI.arguments())
4795 it.info = classifyArgumentType(it.type);
4798 Address EmitDarwinVAArg(Address VAListAddr, QualType Ty,
4799 CodeGenFunction &CGF) const;
4801 Address EmitAAPCSVAArg(Address VAListAddr, QualType Ty,
4802 CodeGenFunction &CGF) const;
4804 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4805 QualType Ty) const override {
4806 return isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF)
4807 : EmitAAPCSVAArg(VAListAddr, Ty, CGF);
4810 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
4811 ArrayRef<llvm::Type*> scalars,
4812 bool asReturnValue) const override {
4813 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
4815 bool isSwiftErrorInRegister() const override {
4819 bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy,
4820 unsigned elts) const override;
4823 class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
4825 AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind)
4826 : TargetCodeGenInfo(new AArch64ABIInfo(CGT, Kind)) {}
4828 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
4829 return "mov\tfp, fp\t\t# marker for objc_retainAutoreleaseReturnValue";
4832 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4836 bool doesReturnSlotInterfereWithArgs() const override { return false; }
4840 ABIArgInfo AArch64ABIInfo::classifyArgumentType(QualType Ty) const {
4841 Ty = useFirstFieldIfTransparentUnion(Ty);
4843 // Handle illegal vector types here.
4844 if (isIllegalVectorType(Ty)) {
4845 uint64_t Size = getContext().getTypeSize(Ty);
4846 // Android promotes <2 x i8> to i16, not i32
4847 if (isAndroid() && (Size <= 16)) {
4848 llvm::Type *ResType = llvm::Type::getInt16Ty(getVMContext());
4849 return ABIArgInfo::getDirect(ResType);
4852 llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext());
4853 return ABIArgInfo::getDirect(ResType);
4856 llvm::Type *ResType =
4857 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2);
4858 return ABIArgInfo::getDirect(ResType);
4861 llvm::Type *ResType =
4862 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4);
4863 return ABIArgInfo::getDirect(ResType);
4865 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
4868 if (!isAggregateTypeForABI(Ty)) {
4869 // Treat an enum type as its underlying type.
4870 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4871 Ty = EnumTy->getDecl()->getIntegerType();
4873 return (Ty->isPromotableIntegerType() && isDarwinPCS()
4874 ? ABIArgInfo::getExtend()
4875 : ABIArgInfo::getDirect());
4878 // Structures with either a non-trivial destructor or a non-trivial
4879 // copy constructor are always indirect.
4880 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
4881 return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA ==
4882 CGCXXABI::RAA_DirectInMemory);
4885 // Empty records are always ignored on Darwin, but actually passed in C++ mode
4886 // elsewhere for GNU compatibility.
4887 uint64_t Size = getContext().getTypeSize(Ty);
4888 bool IsEmpty = isEmptyRecord(getContext(), Ty, true);
4889 if (IsEmpty || Size == 0) {
4890 if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS())
4891 return ABIArgInfo::getIgnore();
4893 // GNU C mode. The only argument that gets ignored is an empty one with size
4895 if (IsEmpty && Size == 0)
4896 return ABIArgInfo::getIgnore();
4897 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
4900 // Homogeneous Floating-point Aggregates (HFAs) need to be expanded.
4901 const Type *Base = nullptr;
4902 uint64_t Members = 0;
4903 if (isHomogeneousAggregate(Ty, Base, Members)) {
4904 return ABIArgInfo::getDirect(
4905 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members));
4908 // Aggregates <= 16 bytes are passed directly in registers or on the stack.
4910 // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
4911 // same size and alignment.
4912 if (getTarget().isRenderScriptTarget()) {
4913 return coerceToIntArray(Ty, getContext(), getVMContext());
4915 unsigned Alignment = getContext().getTypeAlign(Ty);
4916 Size = llvm::alignTo(Size, 64); // round up to multiple of 8 bytes
4918 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
4919 // For aggregates with 16-byte alignment, we use i128.
4920 if (Alignment < 128 && Size == 128) {
4921 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
4922 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
4924 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
4927 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
4930 ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy) const {
4931 if (RetTy->isVoidType())
4932 return ABIArgInfo::getIgnore();
4934 // Large vector types should be returned via memory.
4935 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
4936 return getNaturalAlignIndirect(RetTy);
4938 if (!isAggregateTypeForABI(RetTy)) {
4939 // Treat an enum type as its underlying type.
4940 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
4941 RetTy = EnumTy->getDecl()->getIntegerType();
4943 return (RetTy->isPromotableIntegerType() && isDarwinPCS()
4944 ? ABIArgInfo::getExtend()
4945 : ABIArgInfo::getDirect());
4948 uint64_t Size = getContext().getTypeSize(RetTy);
4949 if (isEmptyRecord(getContext(), RetTy, true) || Size == 0)
4950 return ABIArgInfo::getIgnore();
4952 const Type *Base = nullptr;
4953 uint64_t Members = 0;
4954 if (isHomogeneousAggregate(RetTy, Base, Members))
4955 // Homogeneous Floating-point Aggregates (HFAs) are returned directly.
4956 return ABIArgInfo::getDirect();
4958 // Aggregates <= 16 bytes are returned directly in registers or on the stack.
4960 // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
4961 // same size and alignment.
4962 if (getTarget().isRenderScriptTarget()) {
4963 return coerceToIntArray(RetTy, getContext(), getVMContext());
4965 unsigned Alignment = getContext().getTypeAlign(RetTy);
4966 Size = llvm::alignTo(Size, 64); // round up to multiple of 8 bytes
4968 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
4969 // For aggregates with 16-byte alignment, we use i128.
4970 if (Alignment < 128 && Size == 128) {
4971 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
4972 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
4974 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
4977 return getNaturalAlignIndirect(RetTy);
4980 /// isIllegalVectorType - check whether the vector type is legal for AArch64.
4981 bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const {
4982 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4983 // Check whether VT is legal.
4984 unsigned NumElements = VT->getNumElements();
4985 uint64_t Size = getContext().getTypeSize(VT);
4986 // NumElements should be power of 2.
4987 if (!llvm::isPowerOf2_32(NumElements))
4989 return Size != 64 && (Size != 128 || NumElements == 1);
4994 bool AArch64ABIInfo::isLegalVectorTypeForSwift(CharUnits totalSize,
4996 unsigned elts) const {
4997 if (!llvm::isPowerOf2_32(elts))
4999 if (totalSize.getQuantity() != 8 &&
5000 (totalSize.getQuantity() != 16 || elts == 1))
5005 bool AArch64ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
5006 // Homogeneous aggregates for AAPCS64 must have base types of a floating
5007 // point type or a short-vector type. This is the same as the 32-bit ABI,
5008 // but with the difference that any floating-point type is allowed,
5009 // including __fp16.
5010 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
5011 if (BT->isFloatingPoint())
5013 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
5014 unsigned VecSize = getContext().getTypeSize(VT);
5015 if (VecSize == 64 || VecSize == 128)
5021 bool AArch64ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
5022 uint64_t Members) const {
5023 return Members <= 4;
5026 Address AArch64ABIInfo::EmitAAPCSVAArg(Address VAListAddr,
5028 CodeGenFunction &CGF) const {
5029 ABIArgInfo AI = classifyArgumentType(Ty);
5030 bool IsIndirect = AI.isIndirect();
5032 llvm::Type *BaseTy = CGF.ConvertType(Ty);
5034 BaseTy = llvm::PointerType::getUnqual(BaseTy);
5035 else if (AI.getCoerceToType())
5036 BaseTy = AI.getCoerceToType();
5038 unsigned NumRegs = 1;
5039 if (llvm::ArrayType *ArrTy = dyn_cast<llvm::ArrayType>(BaseTy)) {
5040 BaseTy = ArrTy->getElementType();
5041 NumRegs = ArrTy->getNumElements();
5043 bool IsFPR = BaseTy->isFloatingPointTy() || BaseTy->isVectorTy();
5045 // The AArch64 va_list type and handling is specified in the Procedure Call
5046 // Standard, section B.4:
5056 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
5057 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
5058 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
5059 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
5061 auto TyInfo = getContext().getTypeInfoInChars(Ty);
5062 CharUnits TyAlign = TyInfo.second;
5064 Address reg_offs_p = Address::invalid();
5065 llvm::Value *reg_offs = nullptr;
5067 CharUnits reg_top_offset;
5068 int RegSize = IsIndirect ? 8 : TyInfo.first.getQuantity();
5070 // 3 is the field number of __gr_offs
5072 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(24),
5074 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
5075 reg_top_index = 1; // field number for __gr_top
5076 reg_top_offset = CharUnits::fromQuantity(8);
5077 RegSize = llvm::alignTo(RegSize, 8);
5079 // 4 is the field number of __vr_offs.
5081 CGF.Builder.CreateStructGEP(VAListAddr, 4, CharUnits::fromQuantity(28),
5083 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
5084 reg_top_index = 2; // field number for __vr_top
5085 reg_top_offset = CharUnits::fromQuantity(16);
5086 RegSize = 16 * NumRegs;
5089 //=======================================
5090 // Find out where argument was passed
5091 //=======================================
5093 // If reg_offs >= 0 we're already using the stack for this type of
5094 // argument. We don't want to keep updating reg_offs (in case it overflows,
5095 // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
5096 // whatever they get).
5097 llvm::Value *UsingStack = nullptr;
5098 UsingStack = CGF.Builder.CreateICmpSGE(
5099 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0));
5101 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
5103 // Otherwise, at least some kind of argument could go in these registers, the
5104 // question is whether this particular type is too big.
5105 CGF.EmitBlock(MaybeRegBlock);
5107 // Integer arguments may need to correct register alignment (for example a
5108 // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
5109 // align __gr_offs to calculate the potential address.
5110 if (!IsFPR && !IsIndirect && TyAlign.getQuantity() > 8) {
5111 int Align = TyAlign.getQuantity();
5113 reg_offs = CGF.Builder.CreateAdd(
5114 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
5116 reg_offs = CGF.Builder.CreateAnd(
5117 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align),
5121 // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
5122 // The fact that this is done unconditionally reflects the fact that
5123 // allocating an argument to the stack also uses up all the remaining
5124 // registers of the appropriate kind.
5125 llvm::Value *NewOffset = nullptr;
5126 NewOffset = CGF.Builder.CreateAdd(
5127 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs");
5128 CGF.Builder.CreateStore(NewOffset, reg_offs_p);
5130 // Now we're in a position to decide whether this argument really was in
5131 // registers or not.
5132 llvm::Value *InRegs = nullptr;
5133 InRegs = CGF.Builder.CreateICmpSLE(
5134 NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg");
5136 CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
5138 //=======================================
5139 // Argument was in registers
5140 //=======================================
5142 // Now we emit the code for if the argument was originally passed in
5143 // registers. First start the appropriate block:
5144 CGF.EmitBlock(InRegBlock);
5146 llvm::Value *reg_top = nullptr;
5147 Address reg_top_p = CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index,
5148 reg_top_offset, "reg_top_p");
5149 reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
5150 Address BaseAddr(CGF.Builder.CreateInBoundsGEP(reg_top, reg_offs),
5151 CharUnits::fromQuantity(IsFPR ? 16 : 8));
5152 Address RegAddr = Address::invalid();
5153 llvm::Type *MemTy = CGF.ConvertTypeForMem(Ty);
5156 // If it's been passed indirectly (actually a struct), whatever we find from
5157 // stored registers or on the stack will actually be a struct **.
5158 MemTy = llvm::PointerType::getUnqual(MemTy);
5161 const Type *Base = nullptr;
5162 uint64_t NumMembers = 0;
5163 bool IsHFA = isHomogeneousAggregate(Ty, Base, NumMembers);
5164 if (IsHFA && NumMembers > 1) {
5165 // Homogeneous aggregates passed in registers will have their elements split
5166 // and stored 16-bytes apart regardless of size (they're notionally in qN,
5167 // qN+1, ...). We reload and store into a temporary local variable
5169 assert(!IsIndirect && "Homogeneous aggregates should be passed directly");
5170 auto BaseTyInfo = getContext().getTypeInfoInChars(QualType(Base, 0));
5171 llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
5172 llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
5173 Address Tmp = CGF.CreateTempAlloca(HFATy,
5174 std::max(TyAlign, BaseTyInfo.second));
5176 // On big-endian platforms, the value will be right-aligned in its slot.
5178 if (CGF.CGM.getDataLayout().isBigEndian() &&
5179 BaseTyInfo.first.getQuantity() < 16)
5180 Offset = 16 - BaseTyInfo.first.getQuantity();
5182 for (unsigned i = 0; i < NumMembers; ++i) {
5183 CharUnits BaseOffset = CharUnits::fromQuantity(16 * i + Offset);
5185 CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, BaseOffset);
5186 LoadAddr = CGF.Builder.CreateElementBitCast(LoadAddr, BaseTy);
5189 CGF.Builder.CreateConstArrayGEP(Tmp, i, BaseTyInfo.first);
5191 llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
5192 CGF.Builder.CreateStore(Elem, StoreAddr);
5195 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, MemTy);
5197 // Otherwise the object is contiguous in memory.
5199 // It might be right-aligned in its slot.
5200 CharUnits SlotSize = BaseAddr.getAlignment();
5201 if (CGF.CGM.getDataLayout().isBigEndian() && !IsIndirect &&
5202 (IsHFA || !isAggregateTypeForABI(Ty)) &&
5203 TyInfo.first < SlotSize) {
5204 CharUnits Offset = SlotSize - TyInfo.first;
5205 BaseAddr = CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, Offset);
5208 RegAddr = CGF.Builder.CreateElementBitCast(BaseAddr, MemTy);
5211 CGF.EmitBranch(ContBlock);
5213 //=======================================
5214 // Argument was on the stack
5215 //=======================================
5216 CGF.EmitBlock(OnStackBlock);
5218 Address stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0,
5219 CharUnits::Zero(), "stack_p");
5220 llvm::Value *OnStackPtr = CGF.Builder.CreateLoad(stack_p, "stack");
5222 // Again, stack arguments may need realignment. In this case both integer and
5223 // floating-point ones might be affected.
5224 if (!IsIndirect && TyAlign.getQuantity() > 8) {
5225 int Align = TyAlign.getQuantity();
5227 OnStackPtr = CGF.Builder.CreatePtrToInt(OnStackPtr, CGF.Int64Ty);
5229 OnStackPtr = CGF.Builder.CreateAdd(
5230 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
5232 OnStackPtr = CGF.Builder.CreateAnd(
5233 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, -Align),
5236 OnStackPtr = CGF.Builder.CreateIntToPtr(OnStackPtr, CGF.Int8PtrTy);
5238 Address OnStackAddr(OnStackPtr,
5239 std::max(CharUnits::fromQuantity(8), TyAlign));
5241 // All stack slots are multiples of 8 bytes.
5242 CharUnits StackSlotSize = CharUnits::fromQuantity(8);
5243 CharUnits StackSize;
5245 StackSize = StackSlotSize;
5247 StackSize = TyInfo.first.alignTo(StackSlotSize);
5249 llvm::Value *StackSizeC = CGF.Builder.getSize(StackSize);
5250 llvm::Value *NewStack =
5251 CGF.Builder.CreateInBoundsGEP(OnStackPtr, StackSizeC, "new_stack");
5253 // Write the new value of __stack for the next call to va_arg
5254 CGF.Builder.CreateStore(NewStack, stack_p);
5256 if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) &&
5257 TyInfo.first < StackSlotSize) {
5258 CharUnits Offset = StackSlotSize - TyInfo.first;
5259 OnStackAddr = CGF.Builder.CreateConstInBoundsByteGEP(OnStackAddr, Offset);
5262 OnStackAddr = CGF.Builder.CreateElementBitCast(OnStackAddr, MemTy);
5264 CGF.EmitBranch(ContBlock);
5266 //=======================================
5268 //=======================================
5269 CGF.EmitBlock(ContBlock);
5271 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
5272 OnStackAddr, OnStackBlock, "vaargs.addr");
5275 return Address(CGF.Builder.CreateLoad(ResAddr, "vaarg.addr"),
5281 Address AArch64ABIInfo::EmitDarwinVAArg(Address VAListAddr, QualType Ty,
5282 CodeGenFunction &CGF) const {
5283 // The backend's lowering doesn't support va_arg for aggregates or
5284 // illegal vector types. Lower VAArg here for these cases and use
5285 // the LLVM va_arg instruction for everything else.
5286 if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty))
5287 return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
5289 CharUnits SlotSize = CharUnits::fromQuantity(8);
5291 // Empty records are ignored for parameter passing purposes.
5292 if (isEmptyRecord(getContext(), Ty, true)) {
5293 Address Addr(CGF.Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
5294 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
5298 // The size of the actual thing passed, which might end up just
5299 // being a pointer for indirect types.
5300 auto TyInfo = getContext().getTypeInfoInChars(Ty);
5302 // Arguments bigger than 16 bytes which aren't homogeneous
5303 // aggregates should be passed indirectly.
5304 bool IsIndirect = false;
5305 if (TyInfo.first.getQuantity() > 16) {
5306 const Type *Base = nullptr;
5307 uint64_t Members = 0;
5308 IsIndirect = !isHomogeneousAggregate(Ty, Base, Members);
5311 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
5312 TyInfo, SlotSize, /*AllowHigherAlign*/ true);
5315 //===----------------------------------------------------------------------===//
5316 // ARM ABI Implementation
5317 //===----------------------------------------------------------------------===//
5321 class ARMABIInfo : public SwiftABIInfo {
5334 ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind)
5335 : SwiftABIInfo(CGT), Kind(_Kind) {
5339 bool isEABI() const {
5340 switch (getTarget().getTriple().getEnvironment()) {
5341 case llvm::Triple::Android:
5342 case llvm::Triple::EABI:
5343 case llvm::Triple::EABIHF:
5344 case llvm::Triple::GNUEABI:
5345 case llvm::Triple::GNUEABIHF:
5346 case llvm::Triple::MuslEABI:
5347 case llvm::Triple::MuslEABIHF:
5354 bool isEABIHF() const {
5355 switch (getTarget().getTriple().getEnvironment()) {
5356 case llvm::Triple::EABIHF:
5357 case llvm::Triple::GNUEABIHF:
5358 case llvm::Triple::MuslEABIHF:
5365 ABIKind getABIKind() const { return Kind; }
5368 ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic) const;
5369 ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic) const;
5370 bool isIllegalVectorType(QualType Ty) const;
5372 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
5373 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
5374 uint64_t Members) const override;
5376 void computeInfo(CGFunctionInfo &FI) const override;
5378 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5379 QualType Ty) const override;
5381 llvm::CallingConv::ID getLLVMDefaultCC() const;
5382 llvm::CallingConv::ID getABIDefaultCC() const;
5385 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
5386 ArrayRef<llvm::Type*> scalars,
5387 bool asReturnValue) const override {
5388 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
5390 bool isSwiftErrorInRegister() const override {
5393 bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy,
5394 unsigned elts) const override;
5397 class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
5399 ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
5400 :TargetCodeGenInfo(new ARMABIInfo(CGT, K)) {}
5402 const ARMABIInfo &getABIInfo() const {
5403 return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
5406 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
5410 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
5411 return "mov\tr7, r7\t\t@ marker for objc_retainAutoreleaseReturnValue";
5414 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
5415 llvm::Value *Address) const override {
5416 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
5418 // 0-15 are the 16 integer registers.
5419 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
5423 unsigned getSizeOfUnwindException() const override {
5424 if (getABIInfo().isEABI()) return 88;
5425 return TargetCodeGenInfo::getSizeOfUnwindException();
5428 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5429 CodeGen::CodeGenModule &CGM) const override {
5430 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
5434 const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
5439 switch (Attr->getInterrupt()) {
5440 case ARMInterruptAttr::Generic: Kind = ""; break;
5441 case ARMInterruptAttr::IRQ: Kind = "IRQ"; break;
5442 case ARMInterruptAttr::FIQ: Kind = "FIQ"; break;
5443 case ARMInterruptAttr::SWI: Kind = "SWI"; break;
5444 case ARMInterruptAttr::ABORT: Kind = "ABORT"; break;
5445 case ARMInterruptAttr::UNDEF: Kind = "UNDEF"; break;
5448 llvm::Function *Fn = cast<llvm::Function>(GV);
5450 Fn->addFnAttr("interrupt", Kind);
5452 ARMABIInfo::ABIKind ABI = cast<ARMABIInfo>(getABIInfo()).getABIKind();
5453 if (ABI == ARMABIInfo::APCS)
5456 // AAPCS guarantees that sp will be 8-byte aligned on any public interface,
5457 // however this is not necessarily true on taking any interrupt. Instruct
5458 // the backend to perform a realignment as part of the function prologue.
5459 llvm::AttrBuilder B;
5460 B.addStackAlignmentAttr(8);
5461 Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
5465 class WindowsARMTargetCodeGenInfo : public ARMTargetCodeGenInfo {
5467 WindowsARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
5468 : ARMTargetCodeGenInfo(CGT, K) {}
5470 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5471 CodeGen::CodeGenModule &CGM) const override;
5473 void getDependentLibraryOption(llvm::StringRef Lib,
5474 llvm::SmallString<24> &Opt) const override {
5475 Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib);
5478 void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value,
5479 llvm::SmallString<32> &Opt) const override {
5480 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
5484 void WindowsARMTargetCodeGenInfo::setTargetAttributes(
5485 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
5486 ARMTargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
5487 addStackProbeSizeTargetAttribute(D, GV, CGM);
5491 void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
5492 if (!getCXXABI().classifyReturnType(FI))
5493 FI.getReturnInfo() =
5494 classifyReturnType(FI.getReturnType(), FI.isVariadic());
5496 for (auto &I : FI.arguments())
5497 I.info = classifyArgumentType(I.type, FI.isVariadic());
5499 // Always honor user-specified calling convention.
5500 if (FI.getCallingConvention() != llvm::CallingConv::C)
5503 llvm::CallingConv::ID cc = getRuntimeCC();
5504 if (cc != llvm::CallingConv::C)
5505 FI.setEffectiveCallingConvention(cc);
5508 /// Return the default calling convention that LLVM will use.
5509 llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
5510 // The default calling convention that LLVM will infer.
5511 if (isEABIHF() || getTarget().getTriple().isWatchABI())
5512 return llvm::CallingConv::ARM_AAPCS_VFP;
5514 return llvm::CallingConv::ARM_AAPCS;
5516 return llvm::CallingConv::ARM_APCS;
5519 /// Return the calling convention that our ABI would like us to use
5520 /// as the C calling convention.
5521 llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
5522 switch (getABIKind()) {
5523 case APCS: return llvm::CallingConv::ARM_APCS;
5524 case AAPCS: return llvm::CallingConv::ARM_AAPCS;
5525 case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
5526 case AAPCS16_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
5528 llvm_unreachable("bad ABI kind");
5531 void ARMABIInfo::setCCs() {
5532 assert(getRuntimeCC() == llvm::CallingConv::C);
5534 // Don't muddy up the IR with a ton of explicit annotations if
5535 // they'd just match what LLVM will infer from the triple.
5536 llvm::CallingConv::ID abiCC = getABIDefaultCC();
5537 if (abiCC != getLLVMDefaultCC())
5540 // AAPCS apparently requires runtime support functions to be soft-float, but
5541 // that's almost certainly for historic reasons (Thumb1 not supporting VFP
5542 // most likely). It's more convenient for AAPCS16_VFP to be hard-float.
5543 switch (getABIKind()) {
5546 if (abiCC != getLLVMDefaultCC())
5551 BuiltinCC = llvm::CallingConv::ARM_AAPCS;
5556 ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty,
5557 bool isVariadic) const {
5558 // 6.1.2.1 The following argument types are VFP CPRCs:
5559 // A single-precision floating-point type (including promoted
5560 // half-precision types); A double-precision floating-point type;
5561 // A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
5562 // with a Base Type of a single- or double-precision floating-point type,
5563 // 64-bit containerized vectors or 128-bit containerized vectors with one
5564 // to four Elements.
5565 bool IsEffectivelyAAPCS_VFP = getABIKind() == AAPCS_VFP && !isVariadic;
5567 Ty = useFirstFieldIfTransparentUnion(Ty);
5569 // Handle illegal vector types here.
5570 if (isIllegalVectorType(Ty)) {
5571 uint64_t Size = getContext().getTypeSize(Ty);
5573 llvm::Type *ResType =
5574 llvm::Type::getInt32Ty(getVMContext());
5575 return ABIArgInfo::getDirect(ResType);
5578 llvm::Type *ResType = llvm::VectorType::get(
5579 llvm::Type::getInt32Ty(getVMContext()), 2);
5580 return ABIArgInfo::getDirect(ResType);
5583 llvm::Type *ResType = llvm::VectorType::get(
5584 llvm::Type::getInt32Ty(getVMContext()), 4);
5585 return ABIArgInfo::getDirect(ResType);
5587 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
5590 // __fp16 gets passed as if it were an int or float, but with the top 16 bits
5591 // unspecified. This is not done for OpenCL as it handles the half type
5592 // natively, and does not need to interwork with AAPCS code.
5593 if (Ty->isHalfType() && !getContext().getLangOpts().NativeHalfArgsAndReturns) {
5594 llvm::Type *ResType = IsEffectivelyAAPCS_VFP ?
5595 llvm::Type::getFloatTy(getVMContext()) :
5596 llvm::Type::getInt32Ty(getVMContext());
5597 return ABIArgInfo::getDirect(ResType);
5600 if (!isAggregateTypeForABI(Ty)) {
5601 // Treat an enum type as its underlying type.
5602 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
5603 Ty = EnumTy->getDecl()->getIntegerType();
5606 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend()
5607 : ABIArgInfo::getDirect());
5610 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
5611 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
5614 // Ignore empty records.
5615 if (isEmptyRecord(getContext(), Ty, true))
5616 return ABIArgInfo::getIgnore();
5618 if (IsEffectivelyAAPCS_VFP) {
5619 // Homogeneous Aggregates need to be expanded when we can fit the aggregate
5620 // into VFP registers.
5621 const Type *Base = nullptr;
5622 uint64_t Members = 0;
5623 if (isHomogeneousAggregate(Ty, Base, Members)) {
5624 assert(Base && "Base class should be set for homogeneous aggregate");
5625 // Base can be a floating-point or a vector.
5626 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
5628 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
5629 // WatchOS does have homogeneous aggregates. Note that we intentionally use
5630 // this convention even for a variadic function: the backend will use GPRs
5632 const Type *Base = nullptr;
5633 uint64_t Members = 0;
5634 if (isHomogeneousAggregate(Ty, Base, Members)) {
5635 assert(Base && Members <= 4 && "unexpected homogeneous aggregate");
5637 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members);
5638 return ABIArgInfo::getDirect(Ty, 0, nullptr, false);
5642 if (getABIKind() == ARMABIInfo::AAPCS16_VFP &&
5643 getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(16)) {
5644 // WatchOS is adopting the 64-bit AAPCS rule on composite types: if they're
5645 // bigger than 128-bits, they get placed in space allocated by the caller,
5646 // and a pointer is passed.
5647 return ABIArgInfo::getIndirect(
5648 CharUnits::fromQuantity(getContext().getTypeAlign(Ty) / 8), false);
5651 // Support byval for ARM.
5652 // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
5653 // most 8-byte. We realign the indirect argument if type alignment is bigger
5654 // than ABI alignment.
5655 uint64_t ABIAlign = 4;
5656 uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8;
5657 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
5658 getABIKind() == ARMABIInfo::AAPCS)
5659 ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
5661 if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
5662 assert(getABIKind() != ARMABIInfo::AAPCS16_VFP && "unexpected byval");
5663 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
5665 /*Realign=*/TyAlign > ABIAlign);
5668 // On RenderScript, coerce Aggregates <= 64 bytes to an integer array of
5669 // same size and alignment.
5670 if (getTarget().isRenderScriptTarget()) {
5671 return coerceToIntArray(Ty, getContext(), getVMContext());
5674 // Otherwise, pass by coercing to a structure of the appropriate size.
5677 // FIXME: Try to match the types of the arguments more accurately where
5679 if (getContext().getTypeAlign(Ty) <= 32) {
5680 ElemTy = llvm::Type::getInt32Ty(getVMContext());
5681 SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
5683 ElemTy = llvm::Type::getInt64Ty(getVMContext());
5684 SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
5687 return ABIArgInfo::getDirect(llvm::ArrayType::get(ElemTy, SizeRegs));
5690 static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
5691 llvm::LLVMContext &VMContext) {
5692 // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
5693 // is called integer-like if its size is less than or equal to one word, and
5694 // the offset of each of its addressable sub-fields is zero.
5696 uint64_t Size = Context.getTypeSize(Ty);
5698 // Check that the type fits in a word.
5702 // FIXME: Handle vector types!
5703 if (Ty->isVectorType())
5706 // Float types are never treated as "integer like".
5707 if (Ty->isRealFloatingType())
5710 // If this is a builtin or pointer type then it is ok.
5711 if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
5714 // Small complex integer types are "integer like".
5715 if (const ComplexType *CT = Ty->getAs<ComplexType>())
5716 return isIntegerLikeType(CT->getElementType(), Context, VMContext);
5718 // Single element and zero sized arrays should be allowed, by the definition
5719 // above, but they are not.
5721 // Otherwise, it must be a record type.
5722 const RecordType *RT = Ty->getAs<RecordType>();
5723 if (!RT) return false;
5725 // Ignore records with flexible arrays.
5726 const RecordDecl *RD = RT->getDecl();
5727 if (RD->hasFlexibleArrayMember())
5730 // Check that all sub-fields are at offset 0, and are themselves "integer
5732 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
5734 bool HadField = false;
5736 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
5737 i != e; ++i, ++idx) {
5738 const FieldDecl *FD = *i;
5740 // Bit-fields are not addressable, we only need to verify they are "integer
5741 // like". We still have to disallow a subsequent non-bitfield, for example:
5742 // struct { int : 0; int x }
5743 // is non-integer like according to gcc.
5744 if (FD->isBitField()) {
5748 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
5754 // Check if this field is at offset 0.
5755 if (Layout.getFieldOffset(idx) != 0)
5758 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
5761 // Only allow at most one field in a structure. This doesn't match the
5762 // wording above, but follows gcc in situations with a field following an
5764 if (!RD->isUnion()) {
5775 ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy,
5776 bool isVariadic) const {
5777 bool IsEffectivelyAAPCS_VFP =
5778 (getABIKind() == AAPCS_VFP || getABIKind() == AAPCS16_VFP) && !isVariadic;
5780 if (RetTy->isVoidType())
5781 return ABIArgInfo::getIgnore();
5783 // Large vector types should be returned via memory.
5784 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128) {
5785 return getNaturalAlignIndirect(RetTy);
5788 // __fp16 gets returned as if it were an int or float, but with the top 16
5789 // bits unspecified. This is not done for OpenCL as it handles the half type
5790 // natively, and does not need to interwork with AAPCS code.
5791 if (RetTy->isHalfType() && !getContext().getLangOpts().NativeHalfArgsAndReturns) {
5792 llvm::Type *ResType = IsEffectivelyAAPCS_VFP ?
5793 llvm::Type::getFloatTy(getVMContext()) :
5794 llvm::Type::getInt32Ty(getVMContext());
5795 return ABIArgInfo::getDirect(ResType);
5798 if (!isAggregateTypeForABI(RetTy)) {
5799 // Treat an enum type as its underlying type.
5800 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5801 RetTy = EnumTy->getDecl()->getIntegerType();
5803 return RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend()
5804 : ABIArgInfo::getDirect();
5807 // Are we following APCS?
5808 if (getABIKind() == APCS) {
5809 if (isEmptyRecord(getContext(), RetTy, false))
5810 return ABIArgInfo::getIgnore();
5812 // Complex types are all returned as packed integers.
5814 // FIXME: Consider using 2 x vector types if the back end handles them
5816 if (RetTy->isAnyComplexType())
5817 return ABIArgInfo::getDirect(llvm::IntegerType::get(
5818 getVMContext(), getContext().getTypeSize(RetTy)));
5820 // Integer like structures are returned in r0.
5821 if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
5822 // Return in the smallest viable integer type.
5823 uint64_t Size = getContext().getTypeSize(RetTy);
5825 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
5827 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5828 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
5831 // Otherwise return in memory.
5832 return getNaturalAlignIndirect(RetTy);
5835 // Otherwise this is an AAPCS variant.
5837 if (isEmptyRecord(getContext(), RetTy, true))
5838 return ABIArgInfo::getIgnore();
5840 // Check for homogeneous aggregates with AAPCS-VFP.
5841 if (IsEffectivelyAAPCS_VFP) {
5842 const Type *Base = nullptr;
5843 uint64_t Members = 0;
5844 if (isHomogeneousAggregate(RetTy, Base, Members)) {
5845 assert(Base && "Base class should be set for homogeneous aggregate");
5846 // Homogeneous Aggregates are returned directly.
5847 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
5851 // Aggregates <= 4 bytes are returned in r0; other aggregates
5852 // are returned indirectly.
5853 uint64_t Size = getContext().getTypeSize(RetTy);
5855 // On RenderScript, coerce Aggregates <= 4 bytes to an integer array of
5856 // same size and alignment.
5857 if (getTarget().isRenderScriptTarget()) {
5858 return coerceToIntArray(RetTy, getContext(), getVMContext());
5860 if (getDataLayout().isBigEndian())
5861 // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4)
5862 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
5864 // Return in the smallest viable integer type.
5866 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
5868 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5869 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
5870 } else if (Size <= 128 && getABIKind() == AAPCS16_VFP) {
5871 llvm::Type *Int32Ty = llvm::Type::getInt32Ty(getVMContext());
5872 llvm::Type *CoerceTy =
5873 llvm::ArrayType::get(Int32Ty, llvm::alignTo(Size, 32) / 32);
5874 return ABIArgInfo::getDirect(CoerceTy);
5877 return getNaturalAlignIndirect(RetTy);
5880 /// isIllegalVector - check whether Ty is an illegal vector type.
5881 bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
5882 if (const VectorType *VT = Ty->getAs<VectorType> ()) {
5884 // Android shipped using Clang 3.1, which supported a slightly different
5885 // vector ABI. The primary differences were that 3-element vector types
5886 // were legal, and so were sub 32-bit vectors (i.e. <2 x i8>). This path
5887 // accepts that legacy behavior for Android only.
5888 // Check whether VT is legal.
5889 unsigned NumElements = VT->getNumElements();
5890 // NumElements should be power of 2 or equal to 3.
5891 if (!llvm::isPowerOf2_32(NumElements) && NumElements != 3)
5894 // Check whether VT is legal.
5895 unsigned NumElements = VT->getNumElements();
5896 uint64_t Size = getContext().getTypeSize(VT);
5897 // NumElements should be power of 2.
5898 if (!llvm::isPowerOf2_32(NumElements))
5900 // Size should be greater than 32 bits.
5907 bool ARMABIInfo::isLegalVectorTypeForSwift(CharUnits vectorSize,
5909 unsigned numElts) const {
5910 if (!llvm::isPowerOf2_32(numElts))
5912 unsigned size = getDataLayout().getTypeStoreSizeInBits(eltTy);
5915 if (vectorSize.getQuantity() != 8 &&
5916 (vectorSize.getQuantity() != 16 || numElts == 1))
5921 bool ARMABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
5922 // Homogeneous aggregates for AAPCS-VFP must have base types of float,
5923 // double, or 64-bit or 128-bit vectors.
5924 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
5925 if (BT->getKind() == BuiltinType::Float ||
5926 BT->getKind() == BuiltinType::Double ||
5927 BT->getKind() == BuiltinType::LongDouble)
5929 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
5930 unsigned VecSize = getContext().getTypeSize(VT);
5931 if (VecSize == 64 || VecSize == 128)
5937 bool ARMABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
5938 uint64_t Members) const {
5939 return Members <= 4;
5942 Address ARMABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5943 QualType Ty) const {
5944 CharUnits SlotSize = CharUnits::fromQuantity(4);
5946 // Empty records are ignored for parameter passing purposes.
5947 if (isEmptyRecord(getContext(), Ty, true)) {
5948 Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize);
5949 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
5953 auto TyInfo = getContext().getTypeInfoInChars(Ty);
5954 CharUnits TyAlignForABI = TyInfo.second;
5956 // Use indirect if size of the illegal vector is bigger than 16 bytes.
5957 bool IsIndirect = false;
5958 const Type *Base = nullptr;
5959 uint64_t Members = 0;
5960 if (TyInfo.first > CharUnits::fromQuantity(16) && isIllegalVectorType(Ty)) {
5963 // ARMv7k passes structs bigger than 16 bytes indirectly, in space
5964 // allocated by the caller.
5965 } else if (TyInfo.first > CharUnits::fromQuantity(16) &&
5966 getABIKind() == ARMABIInfo::AAPCS16_VFP &&
5967 !isHomogeneousAggregate(Ty, Base, Members)) {
5970 // Otherwise, bound the type's ABI alignment.
5971 // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
5972 // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
5973 // Our callers should be prepared to handle an under-aligned address.
5974 } else if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
5975 getABIKind() == ARMABIInfo::AAPCS) {
5976 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
5977 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(8));
5978 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
5979 // ARMv7k allows type alignment up to 16 bytes.
5980 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
5981 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(16));
5983 TyAlignForABI = CharUnits::fromQuantity(4);
5985 TyInfo.second = TyAlignForABI;
5987 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TyInfo,
5988 SlotSize, /*AllowHigherAlign*/ true);
5991 //===----------------------------------------------------------------------===//
5992 // NVPTX ABI Implementation
5993 //===----------------------------------------------------------------------===//
5997 class NVPTXABIInfo : public ABIInfo {
5999 NVPTXABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
6001 ABIArgInfo classifyReturnType(QualType RetTy) const;
6002 ABIArgInfo classifyArgumentType(QualType Ty) const;
6004 void computeInfo(CGFunctionInfo &FI) const override;
6005 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6006 QualType Ty) const override;
6009 class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
6011 NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
6012 : TargetCodeGenInfo(new NVPTXABIInfo(CGT)) {}
6014 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
6015 CodeGen::CodeGenModule &M) const override;
6017 // Adds a NamedMDNode with F, Name, and Operand as operands, and adds the
6018 // resulting MDNode to the nvvm.annotations MDNode.
6019 static void addNVVMMetadata(llvm::Function *F, StringRef Name, int Operand);
6022 ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
6023 if (RetTy->isVoidType())
6024 return ABIArgInfo::getIgnore();
6026 // note: this is different from default ABI
6027 if (!RetTy->isScalarType())
6028 return ABIArgInfo::getDirect();
6030 // Treat an enum type as its underlying type.
6031 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6032 RetTy = EnumTy->getDecl()->getIntegerType();
6034 return (RetTy->isPromotableIntegerType() ?
6035 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6038 ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
6039 // Treat an enum type as its underlying type.
6040 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6041 Ty = EnumTy->getDecl()->getIntegerType();
6043 // Return aggregates type as indirect by value
6044 if (isAggregateTypeForABI(Ty))
6045 return getNaturalAlignIndirect(Ty, /* byval */ true);
6047 return (Ty->isPromotableIntegerType() ?
6048 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6051 void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
6052 if (!getCXXABI().classifyReturnType(FI))
6053 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
6054 for (auto &I : FI.arguments())
6055 I.info = classifyArgumentType(I.type);
6057 // Always honor user-specified calling convention.
6058 if (FI.getCallingConvention() != llvm::CallingConv::C)
6061 FI.setEffectiveCallingConvention(getRuntimeCC());
6064 Address NVPTXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6065 QualType Ty) const {
6066 llvm_unreachable("NVPTX does not support varargs");
6069 void NVPTXTargetCodeGenInfo::
6070 setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
6071 CodeGen::CodeGenModule &M) const{
6072 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
6075 llvm::Function *F = cast<llvm::Function>(GV);
6077 // Perform special handling in OpenCL mode
6078 if (M.getLangOpts().OpenCL) {
6079 // Use OpenCL function attributes to check for kernel functions
6080 // By default, all functions are device functions
6081 if (FD->hasAttr<OpenCLKernelAttr>()) {
6082 // OpenCL __kernel functions get kernel metadata
6083 // Create !{<func-ref>, metadata !"kernel", i32 1} node
6084 addNVVMMetadata(F, "kernel", 1);
6085 // And kernel functions are not subject to inlining
6086 F->addFnAttr(llvm::Attribute::NoInline);
6090 // Perform special handling in CUDA mode.
6091 if (M.getLangOpts().CUDA) {
6092 // CUDA __global__ functions get a kernel metadata entry. Since
6093 // __global__ functions cannot be called from the device, we do not
6094 // need to set the noinline attribute.
6095 if (FD->hasAttr<CUDAGlobalAttr>()) {
6096 // Create !{<func-ref>, metadata !"kernel", i32 1} node
6097 addNVVMMetadata(F, "kernel", 1);
6099 if (CUDALaunchBoundsAttr *Attr = FD->getAttr<CUDALaunchBoundsAttr>()) {
6100 // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node
6101 llvm::APSInt MaxThreads(32);
6102 MaxThreads = Attr->getMaxThreads()->EvaluateKnownConstInt(M.getContext());
6104 addNVVMMetadata(F, "maxntidx", MaxThreads.getExtValue());
6106 // min blocks is an optional argument for CUDALaunchBoundsAttr. If it was
6107 // not specified in __launch_bounds__ or if the user specified a 0 value,
6108 // we don't have to add a PTX directive.
6109 if (Attr->getMinBlocks()) {
6110 llvm::APSInt MinBlocks(32);
6111 MinBlocks = Attr->getMinBlocks()->EvaluateKnownConstInt(M.getContext());
6113 // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node
6114 addNVVMMetadata(F, "minctasm", MinBlocks.getExtValue());
6120 void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::Function *F, StringRef Name,
6122 llvm::Module *M = F->getParent();
6123 llvm::LLVMContext &Ctx = M->getContext();
6125 // Get "nvvm.annotations" metadata node
6126 llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
6128 llvm::Metadata *MDVals[] = {
6129 llvm::ConstantAsMetadata::get(F), llvm::MDString::get(Ctx, Name),
6130 llvm::ConstantAsMetadata::get(
6131 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand))};
6132 // Append metadata to nvvm.annotations
6133 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
6137 //===----------------------------------------------------------------------===//
6138 // SystemZ ABI Implementation
6139 //===----------------------------------------------------------------------===//
6143 class SystemZABIInfo : public SwiftABIInfo {
6147 SystemZABIInfo(CodeGenTypes &CGT, bool HV)
6148 : SwiftABIInfo(CGT), HasVector(HV) {}
6150 bool isPromotableIntegerType(QualType Ty) const;
6151 bool isCompoundType(QualType Ty) const;
6152 bool isVectorArgumentType(QualType Ty) const;
6153 bool isFPArgumentType(QualType Ty) const;
6154 QualType GetSingleElementType(QualType Ty) const;
6156 ABIArgInfo classifyReturnType(QualType RetTy) const;
6157 ABIArgInfo classifyArgumentType(QualType ArgTy) const;
6159 void computeInfo(CGFunctionInfo &FI) const override {
6160 if (!getCXXABI().classifyReturnType(FI))
6161 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
6162 for (auto &I : FI.arguments())
6163 I.info = classifyArgumentType(I.type);
6166 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6167 QualType Ty) const override;
6169 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
6170 ArrayRef<llvm::Type*> scalars,
6171 bool asReturnValue) const override {
6172 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
6174 bool isSwiftErrorInRegister() const override {
6179 class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
6181 SystemZTargetCodeGenInfo(CodeGenTypes &CGT, bool HasVector)
6182 : TargetCodeGenInfo(new SystemZABIInfo(CGT, HasVector)) {}
6187 bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const {
6188 // Treat an enum type as its underlying type.
6189 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6190 Ty = EnumTy->getDecl()->getIntegerType();
6192 // Promotable integer types are required to be promoted by the ABI.
6193 if (Ty->isPromotableIntegerType())
6196 // 32-bit values must also be promoted.
6197 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
6198 switch (BT->getKind()) {
6199 case BuiltinType::Int:
6200 case BuiltinType::UInt:
6208 bool SystemZABIInfo::isCompoundType(QualType Ty) const {
6209 return (Ty->isAnyComplexType() ||
6210 Ty->isVectorType() ||
6211 isAggregateTypeForABI(Ty));
6214 bool SystemZABIInfo::isVectorArgumentType(QualType Ty) const {
6215 return (HasVector &&
6216 Ty->isVectorType() &&
6217 getContext().getTypeSize(Ty) <= 128);
6220 bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
6221 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
6222 switch (BT->getKind()) {
6223 case BuiltinType::Float:
6224 case BuiltinType::Double:
6233 QualType SystemZABIInfo::GetSingleElementType(QualType Ty) const {
6234 if (const RecordType *RT = Ty->getAsStructureType()) {
6235 const RecordDecl *RD = RT->getDecl();
6238 // If this is a C++ record, check the bases first.
6239 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
6240 for (const auto &I : CXXRD->bases()) {
6241 QualType Base = I.getType();
6243 // Empty bases don't affect things either way.
6244 if (isEmptyRecord(getContext(), Base, true))
6247 if (!Found.isNull())
6249 Found = GetSingleElementType(Base);
6252 // Check the fields.
6253 for (const auto *FD : RD->fields()) {
6254 // For compatibility with GCC, ignore empty bitfields in C++ mode.
6255 // Unlike isSingleElementStruct(), empty structure and array fields
6256 // do count. So do anonymous bitfields that aren't zero-sized.
6257 if (getContext().getLangOpts().CPlusPlus &&
6258 FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
6261 // Unlike isSingleElementStruct(), arrays do not count.
6262 // Nested structures still do though.
6263 if (!Found.isNull())
6265 Found = GetSingleElementType(FD->getType());
6268 // Unlike isSingleElementStruct(), trailing padding is allowed.
6269 // An 8-byte aligned struct s { float f; } is passed as a double.
6270 if (!Found.isNull())
6277 Address SystemZABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6278 QualType Ty) const {
6279 // Assume that va_list type is correct; should be pointer to LLVM type:
6283 // i8 *__overflow_arg_area;
6284 // i8 *__reg_save_area;
6287 // Every non-vector argument occupies 8 bytes and is passed by preference
6288 // in either GPRs or FPRs. Vector arguments occupy 8 or 16 bytes and are
6289 // always passed on the stack.
6290 Ty = getContext().getCanonicalType(Ty);
6291 auto TyInfo = getContext().getTypeInfoInChars(Ty);
6292 llvm::Type *ArgTy = CGF.ConvertTypeForMem(Ty);
6293 llvm::Type *DirectTy = ArgTy;
6294 ABIArgInfo AI = classifyArgumentType(Ty);
6295 bool IsIndirect = AI.isIndirect();
6296 bool InFPRs = false;
6297 bool IsVector = false;
6298 CharUnits UnpaddedSize;
6299 CharUnits DirectAlign;
6301 DirectTy = llvm::PointerType::getUnqual(DirectTy);
6302 UnpaddedSize = DirectAlign = CharUnits::fromQuantity(8);
6304 if (AI.getCoerceToType())
6305 ArgTy = AI.getCoerceToType();
6306 InFPRs = ArgTy->isFloatTy() || ArgTy->isDoubleTy();
6307 IsVector = ArgTy->isVectorTy();
6308 UnpaddedSize = TyInfo.first;
6309 DirectAlign = TyInfo.second;
6311 CharUnits PaddedSize = CharUnits::fromQuantity(8);
6312 if (IsVector && UnpaddedSize > PaddedSize)
6313 PaddedSize = CharUnits::fromQuantity(16);
6314 assert((UnpaddedSize <= PaddedSize) && "Invalid argument size.");
6316 CharUnits Padding = (PaddedSize - UnpaddedSize);
6318 llvm::Type *IndexTy = CGF.Int64Ty;
6319 llvm::Value *PaddedSizeV =
6320 llvm::ConstantInt::get(IndexTy, PaddedSize.getQuantity());
6323 // Work out the address of a vector argument on the stack.
6324 // Vector arguments are always passed in the high bits of a
6325 // single (8 byte) or double (16 byte) stack slot.
6326 Address OverflowArgAreaPtr =
6327 CGF.Builder.CreateStructGEP(VAListAddr, 2, CharUnits::fromQuantity(16),
6328 "overflow_arg_area_ptr");
6329 Address OverflowArgArea =
6330 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
6333 CGF.Builder.CreateElementBitCast(OverflowArgArea, DirectTy, "mem_addr");
6335 // Update overflow_arg_area_ptr pointer
6336 llvm::Value *NewOverflowArgArea =
6337 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
6338 "overflow_arg_area");
6339 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
6344 assert(PaddedSize.getQuantity() == 8);
6346 unsigned MaxRegs, RegCountField, RegSaveIndex;
6347 CharUnits RegPadding;
6349 MaxRegs = 4; // Maximum of 4 FPR arguments
6350 RegCountField = 1; // __fpr
6351 RegSaveIndex = 16; // save offset for f0
6352 RegPadding = CharUnits(); // floats are passed in the high bits of an FPR
6354 MaxRegs = 5; // Maximum of 5 GPR arguments
6355 RegCountField = 0; // __gpr
6356 RegSaveIndex = 2; // save offset for r2
6357 RegPadding = Padding; // values are passed in the low bits of a GPR
6360 Address RegCountPtr = CGF.Builder.CreateStructGEP(
6361 VAListAddr, RegCountField, RegCountField * CharUnits::fromQuantity(8),
6363 llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
6364 llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
6365 llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
6368 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
6369 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
6370 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
6371 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
6373 // Emit code to load the value if it was passed in registers.
6374 CGF.EmitBlock(InRegBlock);
6376 // Work out the address of an argument register.
6377 llvm::Value *ScaledRegCount =
6378 CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
6379 llvm::Value *RegBase =
6380 llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize.getQuantity()
6381 + RegPadding.getQuantity());
6382 llvm::Value *RegOffset =
6383 CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
6384 Address RegSaveAreaPtr =
6385 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(24),
6386 "reg_save_area_ptr");
6387 llvm::Value *RegSaveArea =
6388 CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
6389 Address RawRegAddr(CGF.Builder.CreateGEP(RegSaveArea, RegOffset,
6393 CGF.Builder.CreateElementBitCast(RawRegAddr, DirectTy, "reg_addr");
6395 // Update the register count
6396 llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
6397 llvm::Value *NewRegCount =
6398 CGF.Builder.CreateAdd(RegCount, One, "reg_count");
6399 CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
6400 CGF.EmitBranch(ContBlock);
6402 // Emit code to load the value if it was passed in memory.
6403 CGF.EmitBlock(InMemBlock);
6405 // Work out the address of a stack argument.
6406 Address OverflowArgAreaPtr = CGF.Builder.CreateStructGEP(
6407 VAListAddr, 2, CharUnits::fromQuantity(16), "overflow_arg_area_ptr");
6408 Address OverflowArgArea =
6409 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
6411 Address RawMemAddr =
6412 CGF.Builder.CreateConstByteGEP(OverflowArgArea, Padding, "raw_mem_addr");
6414 CGF.Builder.CreateElementBitCast(RawMemAddr, DirectTy, "mem_addr");
6416 // Update overflow_arg_area_ptr pointer
6417 llvm::Value *NewOverflowArgArea =
6418 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
6419 "overflow_arg_area");
6420 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
6421 CGF.EmitBranch(ContBlock);
6423 // Return the appropriate result.
6424 CGF.EmitBlock(ContBlock);
6425 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
6426 MemAddr, InMemBlock, "va_arg.addr");
6429 ResAddr = Address(CGF.Builder.CreateLoad(ResAddr, "indirect_arg"),
6435 ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
6436 if (RetTy->isVoidType())
6437 return ABIArgInfo::getIgnore();
6438 if (isVectorArgumentType(RetTy))
6439 return ABIArgInfo::getDirect();
6440 if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
6441 return getNaturalAlignIndirect(RetTy);
6442 return (isPromotableIntegerType(RetTy) ?
6443 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6446 ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
6447 // Handle the generic C++ ABI.
6448 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
6449 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
6451 // Integers and enums are extended to full register width.
6452 if (isPromotableIntegerType(Ty))
6453 return ABIArgInfo::getExtend();
6455 // Handle vector types and vector-like structure types. Note that
6456 // as opposed to float-like structure types, we do not allow any
6457 // padding for vector-like structures, so verify the sizes match.
6458 uint64_t Size = getContext().getTypeSize(Ty);
6459 QualType SingleElementTy = GetSingleElementType(Ty);
6460 if (isVectorArgumentType(SingleElementTy) &&
6461 getContext().getTypeSize(SingleElementTy) == Size)
6462 return ABIArgInfo::getDirect(CGT.ConvertType(SingleElementTy));
6464 // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
6465 if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
6466 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
6468 // Handle small structures.
6469 if (const RecordType *RT = Ty->getAs<RecordType>()) {
6470 // Structures with flexible arrays have variable length, so really
6471 // fail the size test above.
6472 const RecordDecl *RD = RT->getDecl();
6473 if (RD->hasFlexibleArrayMember())
6474 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
6476 // The structure is passed as an unextended integer, a float, or a double.
6478 if (isFPArgumentType(SingleElementTy)) {
6479 assert(Size == 32 || Size == 64);
6481 PassTy = llvm::Type::getFloatTy(getVMContext());
6483 PassTy = llvm::Type::getDoubleTy(getVMContext());
6485 PassTy = llvm::IntegerType::get(getVMContext(), Size);
6486 return ABIArgInfo::getDirect(PassTy);
6489 // Non-structure compounds are passed indirectly.
6490 if (isCompoundType(Ty))
6491 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
6493 return ABIArgInfo::getDirect(nullptr);
6496 //===----------------------------------------------------------------------===//
6497 // MSP430 ABI Implementation
6498 //===----------------------------------------------------------------------===//
6502 class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
6504 MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
6505 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
6506 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
6507 CodeGen::CodeGenModule &M) const override;
6512 void MSP430TargetCodeGenInfo::setTargetAttributes(const Decl *D,
6513 llvm::GlobalValue *GV,
6514 CodeGen::CodeGenModule &M) const {
6515 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
6516 if (const MSP430InterruptAttr *attr = FD->getAttr<MSP430InterruptAttr>()) {
6517 // Handle 'interrupt' attribute:
6518 llvm::Function *F = cast<llvm::Function>(GV);
6520 // Step 1: Set ISR calling convention.
6521 F->setCallingConv(llvm::CallingConv::MSP430_INTR);
6523 // Step 2: Add attributes goodness.
6524 F->addFnAttr(llvm::Attribute::NoInline);
6526 // Step 3: Emit ISR vector alias.
6527 unsigned Num = attr->getNumber() / 2;
6528 llvm::GlobalAlias::create(llvm::Function::ExternalLinkage,
6529 "__isr_" + Twine(Num), F);
6534 //===----------------------------------------------------------------------===//
6535 // MIPS ABI Implementation. This works for both little-endian and
6536 // big-endian variants.
6537 //===----------------------------------------------------------------------===//
6540 class MipsABIInfo : public ABIInfo {
6542 unsigned MinABIStackAlignInBytes, StackAlignInBytes;
6543 void CoerceToIntArgs(uint64_t TySize,
6544 SmallVectorImpl<llvm::Type *> &ArgList) const;
6545 llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
6546 llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
6547 llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
6549 MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
6550 ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
6551 StackAlignInBytes(IsO32 ? 8 : 16) {}
6553 ABIArgInfo classifyReturnType(QualType RetTy) const;
6554 ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
6555 void computeInfo(CGFunctionInfo &FI) const override;
6556 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6557 QualType Ty) const override;
6558 bool shouldSignExtUnsignedType(QualType Ty) const override;
6561 class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
6562 unsigned SizeOfUnwindException;
6564 MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
6565 : TargetCodeGenInfo(new MipsABIInfo(CGT, IsO32)),
6566 SizeOfUnwindException(IsO32 ? 24 : 32) {}
6568 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
6572 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
6573 CodeGen::CodeGenModule &CGM) const override {
6574 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
6576 llvm::Function *Fn = cast<llvm::Function>(GV);
6577 if (FD->hasAttr<Mips16Attr>()) {
6578 Fn->addFnAttr("mips16");
6580 else if (FD->hasAttr<NoMips16Attr>()) {
6581 Fn->addFnAttr("nomips16");
6584 if (FD->hasAttr<MicroMipsAttr>())
6585 Fn->addFnAttr("micromips");
6586 else if (FD->hasAttr<NoMicroMipsAttr>())
6587 Fn->addFnAttr("nomicromips");
6589 const MipsInterruptAttr *Attr = FD->getAttr<MipsInterruptAttr>();
6594 switch (Attr->getInterrupt()) {
6595 case MipsInterruptAttr::eic: Kind = "eic"; break;
6596 case MipsInterruptAttr::sw0: Kind = "sw0"; break;
6597 case MipsInterruptAttr::sw1: Kind = "sw1"; break;
6598 case MipsInterruptAttr::hw0: Kind = "hw0"; break;
6599 case MipsInterruptAttr::hw1: Kind = "hw1"; break;
6600 case MipsInterruptAttr::hw2: Kind = "hw2"; break;
6601 case MipsInterruptAttr::hw3: Kind = "hw3"; break;
6602 case MipsInterruptAttr::hw4: Kind = "hw4"; break;
6603 case MipsInterruptAttr::hw5: Kind = "hw5"; break;
6606 Fn->addFnAttr("interrupt", Kind);
6610 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
6611 llvm::Value *Address) const override;
6613 unsigned getSizeOfUnwindException() const override {
6614 return SizeOfUnwindException;
6619 void MipsABIInfo::CoerceToIntArgs(
6620 uint64_t TySize, SmallVectorImpl<llvm::Type *> &ArgList) const {
6621 llvm::IntegerType *IntTy =
6622 llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
6624 // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
6625 for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
6626 ArgList.push_back(IntTy);
6628 // If necessary, add one more integer type to ArgList.
6629 unsigned R = TySize % (MinABIStackAlignInBytes * 8);
6632 ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
6635 // In N32/64, an aligned double precision floating point field is passed in
6637 llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
6638 SmallVector<llvm::Type*, 8> ArgList, IntArgList;
6641 CoerceToIntArgs(TySize, ArgList);
6642 return llvm::StructType::get(getVMContext(), ArgList);
6645 if (Ty->isComplexType())
6646 return CGT.ConvertType(Ty);
6648 const RecordType *RT = Ty->getAs<RecordType>();
6650 // Unions/vectors are passed in integer registers.
6651 if (!RT || !RT->isStructureOrClassType()) {
6652 CoerceToIntArgs(TySize, ArgList);
6653 return llvm::StructType::get(getVMContext(), ArgList);
6656 const RecordDecl *RD = RT->getDecl();
6657 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
6658 assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
6660 uint64_t LastOffset = 0;
6662 llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
6664 // Iterate over fields in the struct/class and check if there are any aligned
6666 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
6667 i != e; ++i, ++idx) {
6668 const QualType Ty = i->getType();
6669 const BuiltinType *BT = Ty->getAs<BuiltinType>();
6671 if (!BT || BT->getKind() != BuiltinType::Double)
6674 uint64_t Offset = Layout.getFieldOffset(idx);
6675 if (Offset % 64) // Ignore doubles that are not aligned.
6678 // Add ((Offset - LastOffset) / 64) args of type i64.
6679 for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
6680 ArgList.push_back(I64);
6683 ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
6684 LastOffset = Offset + 64;
6687 CoerceToIntArgs(TySize - LastOffset, IntArgList);
6688 ArgList.append(IntArgList.begin(), IntArgList.end());
6690 return llvm::StructType::get(getVMContext(), ArgList);
6693 llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
6694 uint64_t Offset) const {
6695 if (OrigOffset + MinABIStackAlignInBytes > Offset)
6698 return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
6702 MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
6703 Ty = useFirstFieldIfTransparentUnion(Ty);
6705 uint64_t OrigOffset = Offset;
6706 uint64_t TySize = getContext().getTypeSize(Ty);
6707 uint64_t Align = getContext().getTypeAlign(Ty) / 8;
6709 Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
6710 (uint64_t)StackAlignInBytes);
6711 unsigned CurrOffset = llvm::alignTo(Offset, Align);
6712 Offset = CurrOffset + llvm::alignTo(TySize, Align * 8) / 8;
6714 if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
6715 // Ignore empty aggregates.
6717 return ABIArgInfo::getIgnore();
6719 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
6720 Offset = OrigOffset + MinABIStackAlignInBytes;
6721 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
6724 // Use indirect if the aggregate cannot fit into registers for
6725 // passing arguments according to the ABI
6726 unsigned Threshold = IsO32 ? 16 : 64;
6728 if(getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(Threshold))
6729 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(Align), true,
6730 getContext().getTypeAlign(Ty) / 8 > Align);
6732 // If we have reached here, aggregates are passed directly by coercing to
6733 // another structure type. Padding is inserted if the offset of the
6734 // aggregate is unaligned.
6735 ABIArgInfo ArgInfo =
6736 ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
6737 getPaddingType(OrigOffset, CurrOffset));
6738 ArgInfo.setInReg(true);
6742 // Treat an enum type as its underlying type.
6743 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6744 Ty = EnumTy->getDecl()->getIntegerType();
6746 // All integral types are promoted to the GPR width.
6747 if (Ty->isIntegralOrEnumerationType())
6748 return ABIArgInfo::getExtend();
6750 return ABIArgInfo::getDirect(
6751 nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset));
6755 MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
6756 const RecordType *RT = RetTy->getAs<RecordType>();
6757 SmallVector<llvm::Type*, 8> RTList;
6759 if (RT && RT->isStructureOrClassType()) {
6760 const RecordDecl *RD = RT->getDecl();
6761 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
6762 unsigned FieldCnt = Layout.getFieldCount();
6764 // N32/64 returns struct/classes in floating point registers if the
6765 // following conditions are met:
6766 // 1. The size of the struct/class is no larger than 128-bit.
6767 // 2. The struct/class has one or two fields all of which are floating
6769 // 3. The offset of the first field is zero (this follows what gcc does).
6771 // Any other composite results are returned in integer registers.
6773 if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
6774 RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
6775 for (; b != e; ++b) {
6776 const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
6778 if (!BT || !BT->isFloatingPoint())
6781 RTList.push_back(CGT.ConvertType(b->getType()));
6785 return llvm::StructType::get(getVMContext(), RTList,
6786 RD->hasAttr<PackedAttr>());
6792 CoerceToIntArgs(Size, RTList);
6793 return llvm::StructType::get(getVMContext(), RTList);
6796 ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
6797 uint64_t Size = getContext().getTypeSize(RetTy);
6799 if (RetTy->isVoidType())
6800 return ABIArgInfo::getIgnore();
6802 // O32 doesn't treat zero-sized structs differently from other structs.
6803 // However, N32/N64 ignores zero sized return values.
6804 if (!IsO32 && Size == 0)
6805 return ABIArgInfo::getIgnore();
6807 if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
6809 if (RetTy->isAnyComplexType())
6810 return ABIArgInfo::getDirect();
6812 // O32 returns integer vectors in registers and N32/N64 returns all small
6813 // aggregates in registers.
6815 (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) {
6816 ABIArgInfo ArgInfo =
6817 ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
6818 ArgInfo.setInReg(true);
6823 return getNaturalAlignIndirect(RetTy);
6826 // Treat an enum type as its underlying type.
6827 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6828 RetTy = EnumTy->getDecl()->getIntegerType();
6830 return (RetTy->isPromotableIntegerType() ?
6831 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6834 void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
6835 ABIArgInfo &RetInfo = FI.getReturnInfo();
6836 if (!getCXXABI().classifyReturnType(FI))
6837 RetInfo = classifyReturnType(FI.getReturnType());
6839 // Check if a pointer to an aggregate is passed as a hidden argument.
6840 uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
6842 for (auto &I : FI.arguments())
6843 I.info = classifyArgumentType(I.type, Offset);
6846 Address MipsABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6847 QualType OrigTy) const {
6848 QualType Ty = OrigTy;
6850 // Integer arguments are promoted to 32-bit on O32 and 64-bit on N32/N64.
6851 // Pointers are also promoted in the same way but this only matters for N32.
6852 unsigned SlotSizeInBits = IsO32 ? 32 : 64;
6853 unsigned PtrWidth = getTarget().getPointerWidth(0);
6854 bool DidPromote = false;
6855 if ((Ty->isIntegerType() &&
6856 getContext().getIntWidth(Ty) < SlotSizeInBits) ||
6857 (Ty->isPointerType() && PtrWidth < SlotSizeInBits)) {
6859 Ty = getContext().getIntTypeForBitwidth(SlotSizeInBits,
6860 Ty->isSignedIntegerType());
6863 auto TyInfo = getContext().getTypeInfoInChars(Ty);
6865 // The alignment of things in the argument area is never larger than
6866 // StackAlignInBytes.
6868 std::min(TyInfo.second, CharUnits::fromQuantity(StackAlignInBytes));
6870 // MinABIStackAlignInBytes is the size of argument slots on the stack.
6871 CharUnits ArgSlotSize = CharUnits::fromQuantity(MinABIStackAlignInBytes);
6873 Address Addr = emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
6874 TyInfo, ArgSlotSize, /*AllowHigherAlign*/ true);
6877 // If there was a promotion, "unpromote" into a temporary.
6878 // TODO: can we just use a pointer into a subset of the original slot?
6880 Address Temp = CGF.CreateMemTemp(OrigTy, "vaarg.promotion-temp");
6881 llvm::Value *Promoted = CGF.Builder.CreateLoad(Addr);
6883 // Truncate down to the right width.
6884 llvm::Type *IntTy = (OrigTy->isIntegerType() ? Temp.getElementType()
6886 llvm::Value *V = CGF.Builder.CreateTrunc(Promoted, IntTy);
6887 if (OrigTy->isPointerType())
6888 V = CGF.Builder.CreateIntToPtr(V, Temp.getElementType());
6890 CGF.Builder.CreateStore(V, Temp);
6897 bool MipsABIInfo::shouldSignExtUnsignedType(QualType Ty) const {
6898 int TySize = getContext().getTypeSize(Ty);
6900 // MIPS64 ABI requires unsigned 32 bit integers to be sign extended.
6901 if (Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
6908 MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
6909 llvm::Value *Address) const {
6910 // This information comes from gcc's implementation, which seems to
6911 // as canonical as it gets.
6913 // Everything on MIPS is 4 bytes. Double-precision FP registers
6914 // are aliased to pairs of single-precision FP registers.
6915 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
6917 // 0-31 are the general purpose registers, $0 - $31.
6918 // 32-63 are the floating-point registers, $f0 - $f31.
6919 // 64 and 65 are the multiply/divide registers, $hi and $lo.
6920 // 66 is the (notional, I think) register for signal-handler return.
6921 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
6923 // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
6924 // They are one bit wide and ignored here.
6926 // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
6927 // (coprocessor 1 is the FP unit)
6928 // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
6929 // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
6930 // 176-181 are the DSP accumulator registers.
6931 AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
6935 //===----------------------------------------------------------------------===//
6936 // AVR ABI Implementation.
6937 //===----------------------------------------------------------------------===//
6940 class AVRTargetCodeGenInfo : public TargetCodeGenInfo {
6942 AVRTargetCodeGenInfo(CodeGenTypes &CGT)
6943 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) { }
6945 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
6946 CodeGen::CodeGenModule &CGM) const override {
6947 const auto *FD = dyn_cast_or_null<FunctionDecl>(D);
6949 auto *Fn = cast<llvm::Function>(GV);
6951 if (FD->getAttr<AVRInterruptAttr>())
6952 Fn->addFnAttr("interrupt");
6954 if (FD->getAttr<AVRSignalAttr>())
6955 Fn->addFnAttr("signal");
6960 //===----------------------------------------------------------------------===//
6961 // TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
6962 // Currently subclassed only to implement custom OpenCL C function attribute
6964 //===----------------------------------------------------------------------===//
6968 class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
6970 TCETargetCodeGenInfo(CodeGenTypes &CGT)
6971 : DefaultTargetCodeGenInfo(CGT) {}
6973 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
6974 CodeGen::CodeGenModule &M) const override;
6977 void TCETargetCodeGenInfo::setTargetAttributes(
6978 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
6979 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
6982 llvm::Function *F = cast<llvm::Function>(GV);
6984 if (M.getLangOpts().OpenCL) {
6985 if (FD->hasAttr<OpenCLKernelAttr>()) {
6986 // OpenCL C Kernel functions are not subject to inlining
6987 F->addFnAttr(llvm::Attribute::NoInline);
6988 const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
6990 // Convert the reqd_work_group_size() attributes to metadata.
6991 llvm::LLVMContext &Context = F->getContext();
6992 llvm::NamedMDNode *OpenCLMetadata =
6993 M.getModule().getOrInsertNamedMetadata(
6994 "opencl.kernel_wg_size_info");
6996 SmallVector<llvm::Metadata *, 5> Operands;
6997 Operands.push_back(llvm::ConstantAsMetadata::get(F));
7000 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
7001 M.Int32Ty, llvm::APInt(32, Attr->getXDim()))));
7003 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
7004 M.Int32Ty, llvm::APInt(32, Attr->getYDim()))));
7006 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
7007 M.Int32Ty, llvm::APInt(32, Attr->getZDim()))));
7009 // Add a boolean constant operand for "required" (true) or "hint"
7010 // (false) for implementing the work_group_size_hint attr later.
7011 // Currently always true as the hint is not yet implemented.
7013 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getTrue(Context)));
7014 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
7022 //===----------------------------------------------------------------------===//
7023 // Hexagon ABI Implementation
7024 //===----------------------------------------------------------------------===//
7028 class HexagonABIInfo : public ABIInfo {
7032 HexagonABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
7036 ABIArgInfo classifyReturnType(QualType RetTy) const;
7037 ABIArgInfo classifyArgumentType(QualType RetTy) const;
7039 void computeInfo(CGFunctionInfo &FI) const override;
7041 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7042 QualType Ty) const override;
7045 class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
7047 HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
7048 :TargetCodeGenInfo(new HexagonABIInfo(CGT)) {}
7050 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
7057 void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
7058 if (!getCXXABI().classifyReturnType(FI))
7059 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7060 for (auto &I : FI.arguments())
7061 I.info = classifyArgumentType(I.type);
7064 ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty) const {
7065 if (!isAggregateTypeForABI(Ty)) {
7066 // Treat an enum type as its underlying type.
7067 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7068 Ty = EnumTy->getDecl()->getIntegerType();
7070 return (Ty->isPromotableIntegerType() ?
7071 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
7074 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
7075 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
7077 // Ignore empty records.
7078 if (isEmptyRecord(getContext(), Ty, true))
7079 return ABIArgInfo::getIgnore();
7081 uint64_t Size = getContext().getTypeSize(Ty);
7083 return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
7084 // Pass in the smallest viable integer type.
7086 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
7088 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
7090 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
7092 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
7095 ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
7096 if (RetTy->isVoidType())
7097 return ABIArgInfo::getIgnore();
7099 // Large vector types should be returned via memory.
7100 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 64)
7101 return getNaturalAlignIndirect(RetTy);
7103 if (!isAggregateTypeForABI(RetTy)) {
7104 // Treat an enum type as its underlying type.
7105 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
7106 RetTy = EnumTy->getDecl()->getIntegerType();
7108 return (RetTy->isPromotableIntegerType() ?
7109 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
7112 if (isEmptyRecord(getContext(), RetTy, true))
7113 return ABIArgInfo::getIgnore();
7115 // Aggregates <= 8 bytes are returned in r0; other aggregates
7116 // are returned indirectly.
7117 uint64_t Size = getContext().getTypeSize(RetTy);
7119 // Return in the smallest viable integer type.
7121 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
7123 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
7125 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
7126 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
7129 return getNaturalAlignIndirect(RetTy, /*ByVal=*/true);
7132 Address HexagonABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7133 QualType Ty) const {
7134 // FIXME: Someone needs to audit that this handle alignment correctly.
7135 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
7136 getContext().getTypeInfoInChars(Ty),
7137 CharUnits::fromQuantity(4),
7138 /*AllowHigherAlign*/ true);
7141 //===----------------------------------------------------------------------===//
7142 // Lanai ABI Implementation
7143 //===----------------------------------------------------------------------===//
7146 class LanaiABIInfo : public DefaultABIInfo {
7148 LanaiABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
7150 bool shouldUseInReg(QualType Ty, CCState &State) const;
7152 void computeInfo(CGFunctionInfo &FI) const override {
7153 CCState State(FI.getCallingConvention());
7154 // Lanai uses 4 registers to pass arguments unless the function has the
7155 // regparm attribute set.
7156 if (FI.getHasRegParm()) {
7157 State.FreeRegs = FI.getRegParm();
7162 if (!getCXXABI().classifyReturnType(FI))
7163 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7164 for (auto &I : FI.arguments())
7165 I.info = classifyArgumentType(I.type, State);
7168 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
7169 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
7171 } // end anonymous namespace
7173 bool LanaiABIInfo::shouldUseInReg(QualType Ty, CCState &State) const {
7174 unsigned Size = getContext().getTypeSize(Ty);
7175 unsigned SizeInRegs = llvm::alignTo(Size, 32U) / 32U;
7177 if (SizeInRegs == 0)
7180 if (SizeInRegs > State.FreeRegs) {
7185 State.FreeRegs -= SizeInRegs;
7190 ABIArgInfo LanaiABIInfo::getIndirectResult(QualType Ty, bool ByVal,
7191 CCState &State) const {
7193 if (State.FreeRegs) {
7194 --State.FreeRegs; // Non-byval indirects just use one pointer.
7195 return getNaturalAlignIndirectInReg(Ty);
7197 return getNaturalAlignIndirect(Ty, false);
7200 // Compute the byval alignment.
7201 const unsigned MinABIStackAlignInBytes = 4;
7202 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
7203 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true,
7204 /*Realign=*/TypeAlign >
7205 MinABIStackAlignInBytes);
7208 ABIArgInfo LanaiABIInfo::classifyArgumentType(QualType Ty,
7209 CCState &State) const {
7210 // Check with the C++ ABI first.
7211 const RecordType *RT = Ty->getAs<RecordType>();
7213 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
7214 if (RAA == CGCXXABI::RAA_Indirect) {
7215 return getIndirectResult(Ty, /*ByVal=*/false, State);
7216 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
7217 return getNaturalAlignIndirect(Ty, /*ByRef=*/true);
7221 if (isAggregateTypeForABI(Ty)) {
7222 // Structures with flexible arrays are always indirect.
7223 if (RT && RT->getDecl()->hasFlexibleArrayMember())
7224 return getIndirectResult(Ty, /*ByVal=*/true, State);
7226 // Ignore empty structs/unions.
7227 if (isEmptyRecord(getContext(), Ty, true))
7228 return ABIArgInfo::getIgnore();
7230 llvm::LLVMContext &LLVMContext = getVMContext();
7231 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
7232 if (SizeInRegs <= State.FreeRegs) {
7233 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
7234 SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32);
7235 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
7236 State.FreeRegs -= SizeInRegs;
7237 return ABIArgInfo::getDirectInReg(Result);
7241 return getIndirectResult(Ty, true, State);
7244 // Treat an enum type as its underlying type.
7245 if (const auto *EnumTy = Ty->getAs<EnumType>())
7246 Ty = EnumTy->getDecl()->getIntegerType();
7248 bool InReg = shouldUseInReg(Ty, State);
7249 if (Ty->isPromotableIntegerType()) {
7251 return ABIArgInfo::getDirectInReg();
7252 return ABIArgInfo::getExtend();
7255 return ABIArgInfo::getDirectInReg();
7256 return ABIArgInfo::getDirect();
7260 class LanaiTargetCodeGenInfo : public TargetCodeGenInfo {
7262 LanaiTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
7263 : TargetCodeGenInfo(new LanaiABIInfo(CGT)) {}
7267 //===----------------------------------------------------------------------===//
7268 // AMDGPU ABI Implementation
7269 //===----------------------------------------------------------------------===//
7273 class AMDGPUABIInfo final : public DefaultABIInfo {
7275 explicit AMDGPUABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
7278 ABIArgInfo classifyArgumentType(QualType Ty) const;
7280 void computeInfo(CGFunctionInfo &FI) const override;
7283 void AMDGPUABIInfo::computeInfo(CGFunctionInfo &FI) const {
7284 if (!getCXXABI().classifyReturnType(FI))
7285 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7287 unsigned CC = FI.getCallingConvention();
7288 for (auto &Arg : FI.arguments())
7289 if (CC == llvm::CallingConv::AMDGPU_KERNEL)
7290 Arg.info = classifyArgumentType(Arg.type);
7292 Arg.info = DefaultABIInfo::classifyArgumentType(Arg.type);
7295 /// \brief Classify argument of given type \p Ty.
7296 ABIArgInfo AMDGPUABIInfo::classifyArgumentType(QualType Ty) const {
7297 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
7299 return DefaultABIInfo::classifyArgumentType(Ty);
7302 // Coerce single element structs to its element.
7303 if (StrTy->getNumElements() == 1) {
7304 return ABIArgInfo::getDirect();
7307 // If we set CanBeFlattened to true, CodeGen will expand the struct to its
7308 // individual elements, which confuses the Clover OpenCL backend; therefore we
7309 // have to set it to false here. Other args of getDirect() are just defaults.
7310 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
7313 class AMDGPUTargetCodeGenInfo : public TargetCodeGenInfo {
7315 AMDGPUTargetCodeGenInfo(CodeGenTypes &CGT)
7316 : TargetCodeGenInfo(new AMDGPUABIInfo(CGT)) {}
7317 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
7318 CodeGen::CodeGenModule &M) const override;
7319 unsigned getOpenCLKernelCallingConv() const override;
7321 llvm::Constant *getNullPointer(const CodeGen::CodeGenModule &CGM,
7322 llvm::PointerType *T, QualType QT) const override;
7324 unsigned getASTAllocaAddressSpace() const override {
7325 return LangAS::FirstTargetAddressSpace +
7326 getABIInfo().getDataLayout().getAllocaAddrSpace();
7331 void AMDGPUTargetCodeGenInfo::setTargetAttributes(
7333 llvm::GlobalValue *GV,
7334 CodeGen::CodeGenModule &M) const {
7335 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
7339 llvm::Function *F = cast<llvm::Function>(GV);
7341 const auto *ReqdWGS = M.getLangOpts().OpenCL ?
7342 FD->getAttr<ReqdWorkGroupSizeAttr>() : nullptr;
7343 const auto *FlatWGS = FD->getAttr<AMDGPUFlatWorkGroupSizeAttr>();
7344 if (ReqdWGS || FlatWGS) {
7345 unsigned Min = FlatWGS ? FlatWGS->getMin() : 0;
7346 unsigned Max = FlatWGS ? FlatWGS->getMax() : 0;
7347 if (ReqdWGS && Min == 0 && Max == 0)
7348 Min = Max = ReqdWGS->getXDim() * ReqdWGS->getYDim() * ReqdWGS->getZDim();
7351 assert(Min <= Max && "Min must be less than or equal Max");
7353 std::string AttrVal = llvm::utostr(Min) + "," + llvm::utostr(Max);
7354 F->addFnAttr("amdgpu-flat-work-group-size", AttrVal);
7356 assert(Max == 0 && "Max must be zero");
7359 if (const auto *Attr = FD->getAttr<AMDGPUWavesPerEUAttr>()) {
7360 unsigned Min = Attr->getMin();
7361 unsigned Max = Attr->getMax();
7364 assert((Max == 0 || Min <= Max) && "Min must be less than or equal Max");
7366 std::string AttrVal = llvm::utostr(Min);
7368 AttrVal = AttrVal + "," + llvm::utostr(Max);
7369 F->addFnAttr("amdgpu-waves-per-eu", AttrVal);
7371 assert(Max == 0 && "Max must be zero");
7374 if (const auto *Attr = FD->getAttr<AMDGPUNumSGPRAttr>()) {
7375 unsigned NumSGPR = Attr->getNumSGPR();
7378 F->addFnAttr("amdgpu-num-sgpr", llvm::utostr(NumSGPR));
7381 if (const auto *Attr = FD->getAttr<AMDGPUNumVGPRAttr>()) {
7382 uint32_t NumVGPR = Attr->getNumVGPR();
7385 F->addFnAttr("amdgpu-num-vgpr", llvm::utostr(NumVGPR));
7389 unsigned AMDGPUTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
7390 return llvm::CallingConv::AMDGPU_KERNEL;
7393 // Currently LLVM assumes null pointers always have value 0,
7394 // which results in incorrectly transformed IR. Therefore, instead of
7395 // emitting null pointers in private and local address spaces, a null
7396 // pointer in generic address space is emitted which is casted to a
7397 // pointer in local or private address space.
7398 llvm::Constant *AMDGPUTargetCodeGenInfo::getNullPointer(
7399 const CodeGen::CodeGenModule &CGM, llvm::PointerType *PT,
7400 QualType QT) const {
7401 if (CGM.getContext().getTargetNullPointerValue(QT) == 0)
7402 return llvm::ConstantPointerNull::get(PT);
7404 auto &Ctx = CGM.getContext();
7405 auto NPT = llvm::PointerType::get(PT->getElementType(),
7406 Ctx.getTargetAddressSpace(LangAS::opencl_generic));
7407 return llvm::ConstantExpr::getAddrSpaceCast(
7408 llvm::ConstantPointerNull::get(NPT), PT);
7411 //===----------------------------------------------------------------------===//
7412 // SPARC v8 ABI Implementation.
7413 // Based on the SPARC Compliance Definition version 2.4.1.
7415 // Ensures that complex values are passed in registers.
7418 class SparcV8ABIInfo : public DefaultABIInfo {
7420 SparcV8ABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
7423 ABIArgInfo classifyReturnType(QualType RetTy) const;
7424 void computeInfo(CGFunctionInfo &FI) const override;
7426 } // end anonymous namespace
7430 SparcV8ABIInfo::classifyReturnType(QualType Ty) const {
7431 if (Ty->isAnyComplexType()) {
7432 return ABIArgInfo::getDirect();
7435 return DefaultABIInfo::classifyReturnType(Ty);
7439 void SparcV8ABIInfo::computeInfo(CGFunctionInfo &FI) const {
7441 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7442 for (auto &Arg : FI.arguments())
7443 Arg.info = classifyArgumentType(Arg.type);
7447 class SparcV8TargetCodeGenInfo : public TargetCodeGenInfo {
7449 SparcV8TargetCodeGenInfo(CodeGenTypes &CGT)
7450 : TargetCodeGenInfo(new SparcV8ABIInfo(CGT)) {}
7452 } // end anonymous namespace
7454 //===----------------------------------------------------------------------===//
7455 // SPARC v9 ABI Implementation.
7456 // Based on the SPARC Compliance Definition version 2.4.1.
7458 // Function arguments a mapped to a nominal "parameter array" and promoted to
7459 // registers depending on their type. Each argument occupies 8 or 16 bytes in
7460 // the array, structs larger than 16 bytes are passed indirectly.
7462 // One case requires special care:
7469 // When a struct mixed is passed by value, it only occupies 8 bytes in the
7470 // parameter array, but the int is passed in an integer register, and the float
7471 // is passed in a floating point register. This is represented as two arguments
7472 // with the LLVM IR inreg attribute:
7474 // declare void f(i32 inreg %i, float inreg %f)
7476 // The code generator will only allocate 4 bytes from the parameter array for
7477 // the inreg arguments. All other arguments are allocated a multiple of 8
7481 class SparcV9ABIInfo : public ABIInfo {
7483 SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
7486 ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
7487 void computeInfo(CGFunctionInfo &FI) const override;
7488 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7489 QualType Ty) const override;
7491 // Coercion type builder for structs passed in registers. The coercion type
7492 // serves two purposes:
7494 // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
7496 // 2. Expose aligned floating point elements as first-level elements, so the
7497 // code generator knows to pass them in floating point registers.
7499 // We also compute the InReg flag which indicates that the struct contains
7500 // aligned 32-bit floats.
7502 struct CoerceBuilder {
7503 llvm::LLVMContext &Context;
7504 const llvm::DataLayout &DL;
7505 SmallVector<llvm::Type*, 8> Elems;
7509 CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
7510 : Context(c), DL(dl), Size(0), InReg(false) {}
7512 // Pad Elems with integers until Size is ToSize.
7513 void pad(uint64_t ToSize) {
7514 assert(ToSize >= Size && "Cannot remove elements");
7518 // Finish the current 64-bit word.
7519 uint64_t Aligned = llvm::alignTo(Size, 64);
7520 if (Aligned > Size && Aligned <= ToSize) {
7521 Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
7525 // Add whole 64-bit words.
7526 while (Size + 64 <= ToSize) {
7527 Elems.push_back(llvm::Type::getInt64Ty(Context));
7531 // Final in-word padding.
7532 if (Size < ToSize) {
7533 Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
7538 // Add a floating point element at Offset.
7539 void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
7540 // Unaligned floats are treated as integers.
7543 // The InReg flag is only required if there are any floats < 64 bits.
7547 Elems.push_back(Ty);
7548 Size = Offset + Bits;
7551 // Add a struct type to the coercion type, starting at Offset (in bits).
7552 void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
7553 const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
7554 for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
7555 llvm::Type *ElemTy = StrTy->getElementType(i);
7556 uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
7557 switch (ElemTy->getTypeID()) {
7558 case llvm::Type::StructTyID:
7559 addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
7561 case llvm::Type::FloatTyID:
7562 addFloat(ElemOffset, ElemTy, 32);
7564 case llvm::Type::DoubleTyID:
7565 addFloat(ElemOffset, ElemTy, 64);
7567 case llvm::Type::FP128TyID:
7568 addFloat(ElemOffset, ElemTy, 128);
7570 case llvm::Type::PointerTyID:
7571 if (ElemOffset % 64 == 0) {
7573 Elems.push_back(ElemTy);
7583 // Check if Ty is a usable substitute for the coercion type.
7584 bool isUsableType(llvm::StructType *Ty) const {
7585 return llvm::makeArrayRef(Elems) == Ty->elements();
7588 // Get the coercion type as a literal struct type.
7589 llvm::Type *getType() const {
7590 if (Elems.size() == 1)
7591 return Elems.front();
7593 return llvm::StructType::get(Context, Elems);
7597 } // end anonymous namespace
7600 SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
7601 if (Ty->isVoidType())
7602 return ABIArgInfo::getIgnore();
7604 uint64_t Size = getContext().getTypeSize(Ty);
7606 // Anything too big to fit in registers is passed with an explicit indirect
7607 // pointer / sret pointer.
7608 if (Size > SizeLimit)
7609 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
7611 // Treat an enum type as its underlying type.
7612 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7613 Ty = EnumTy->getDecl()->getIntegerType();
7615 // Integer types smaller than a register are extended.
7616 if (Size < 64 && Ty->isIntegerType())
7617 return ABIArgInfo::getExtend();
7619 // Other non-aggregates go in registers.
7620 if (!isAggregateTypeForABI(Ty))
7621 return ABIArgInfo::getDirect();
7623 // If a C++ object has either a non-trivial copy constructor or a non-trivial
7624 // destructor, it is passed with an explicit indirect pointer / sret pointer.
7625 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
7626 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
7628 // This is a small aggregate type that should be passed in registers.
7629 // Build a coercion type from the LLVM struct type.
7630 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
7632 return ABIArgInfo::getDirect();
7634 CoerceBuilder CB(getVMContext(), getDataLayout());
7635 CB.addStruct(0, StrTy);
7636 CB.pad(llvm::alignTo(CB.DL.getTypeSizeInBits(StrTy), 64));
7638 // Try to use the original type for coercion.
7639 llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
7642 return ABIArgInfo::getDirectInReg(CoerceTy);
7644 return ABIArgInfo::getDirect(CoerceTy);
7647 Address SparcV9ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7648 QualType Ty) const {
7649 ABIArgInfo AI = classifyType(Ty, 16 * 8);
7650 llvm::Type *ArgTy = CGT.ConvertType(Ty);
7651 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
7652 AI.setCoerceToType(ArgTy);
7654 CharUnits SlotSize = CharUnits::fromQuantity(8);
7656 CGBuilderTy &Builder = CGF.Builder;
7657 Address Addr(Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
7658 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
7660 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
7662 Address ArgAddr = Address::invalid();
7664 switch (AI.getKind()) {
7665 case ABIArgInfo::Expand:
7666 case ABIArgInfo::CoerceAndExpand:
7667 case ABIArgInfo::InAlloca:
7668 llvm_unreachable("Unsupported ABI kind for va_arg");
7670 case ABIArgInfo::Extend: {
7672 CharUnits Offset = SlotSize - TypeInfo.first;
7673 ArgAddr = Builder.CreateConstInBoundsByteGEP(Addr, Offset, "extend");
7677 case ABIArgInfo::Direct: {
7678 auto AllocSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
7679 Stride = CharUnits::fromQuantity(AllocSize).alignTo(SlotSize);
7684 case ABIArgInfo::Indirect:
7686 ArgAddr = Builder.CreateElementBitCast(Addr, ArgPtrTy, "indirect");
7687 ArgAddr = Address(Builder.CreateLoad(ArgAddr, "indirect.arg"),
7691 case ABIArgInfo::Ignore:
7692 return Address(llvm::UndefValue::get(ArgPtrTy), TypeInfo.second);
7696 llvm::Value *NextPtr =
7697 Builder.CreateConstInBoundsByteGEP(Addr.getPointer(), Stride, "ap.next");
7698 Builder.CreateStore(NextPtr, VAListAddr);
7700 return Builder.CreateBitCast(ArgAddr, ArgPtrTy, "arg.addr");
7703 void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
7704 FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
7705 for (auto &I : FI.arguments())
7706 I.info = classifyType(I.type, 16 * 8);
7710 class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
7712 SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
7713 : TargetCodeGenInfo(new SparcV9ABIInfo(CGT)) {}
7715 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
7719 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
7720 llvm::Value *Address) const override;
7722 } // end anonymous namespace
7725 SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
7726 llvm::Value *Address) const {
7727 // This is calculated from the LLVM and GCC tables and verified
7728 // against gcc output. AFAIK all ABIs use the same encoding.
7730 CodeGen::CGBuilderTy &Builder = CGF.Builder;
7732 llvm::IntegerType *i8 = CGF.Int8Ty;
7733 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
7734 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
7736 // 0-31: the 8-byte general-purpose registers
7737 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
7739 // 32-63: f0-31, the 4-byte floating-point registers
7740 AssignToArrayRange(Builder, Address, Four8, 32, 63);
7750 AssignToArrayRange(Builder, Address, Eight8, 64, 71);
7752 // 72-87: d0-15, the 8-byte floating-point registers
7753 AssignToArrayRange(Builder, Address, Eight8, 72, 87);
7759 //===----------------------------------------------------------------------===//
7760 // XCore ABI Implementation
7761 //===----------------------------------------------------------------------===//
7765 /// A SmallStringEnc instance is used to build up the TypeString by passing
7766 /// it by reference between functions that append to it.
7767 typedef llvm::SmallString<128> SmallStringEnc;
7769 /// TypeStringCache caches the meta encodings of Types.
7771 /// The reason for caching TypeStrings is two fold:
7772 /// 1. To cache a type's encoding for later uses;
7773 /// 2. As a means to break recursive member type inclusion.
7775 /// A cache Entry can have a Status of:
7776 /// NonRecursive: The type encoding is not recursive;
7777 /// Recursive: The type encoding is recursive;
7778 /// Incomplete: An incomplete TypeString;
7779 /// IncompleteUsed: An incomplete TypeString that has been used in a
7780 /// Recursive type encoding.
7782 /// A NonRecursive entry will have all of its sub-members expanded as fully
7783 /// as possible. Whilst it may contain types which are recursive, the type
7784 /// itself is not recursive and thus its encoding may be safely used whenever
7785 /// the type is encountered.
7787 /// A Recursive entry will have all of its sub-members expanded as fully as
7788 /// possible. The type itself is recursive and it may contain other types which
7789 /// are recursive. The Recursive encoding must not be used during the expansion
7790 /// of a recursive type's recursive branch. For simplicity the code uses
7791 /// IncompleteCount to reject all usage of Recursive encodings for member types.
7793 /// An Incomplete entry is always a RecordType and only encodes its
7794 /// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and
7795 /// are placed into the cache during type expansion as a means to identify and
7796 /// handle recursive inclusion of types as sub-members. If there is recursion
7797 /// the entry becomes IncompleteUsed.
7799 /// During the expansion of a RecordType's members:
7801 /// If the cache contains a NonRecursive encoding for the member type, the
7802 /// cached encoding is used;
7804 /// If the cache contains a Recursive encoding for the member type, the
7805 /// cached encoding is 'Swapped' out, as it may be incorrect, and...
7807 /// If the member is a RecordType, an Incomplete encoding is placed into the
7808 /// cache to break potential recursive inclusion of itself as a sub-member;
7810 /// Once a member RecordType has been expanded, its temporary incomplete
7811 /// entry is removed from the cache. If a Recursive encoding was swapped out
7812 /// it is swapped back in;
7814 /// If an incomplete entry is used to expand a sub-member, the incomplete
7815 /// entry is marked as IncompleteUsed. The cache keeps count of how many
7816 /// IncompleteUsed entries it currently contains in IncompleteUsedCount;
7818 /// If a member's encoding is found to be a NonRecursive or Recursive viz:
7819 /// IncompleteUsedCount==0, the member's encoding is added to the cache.
7820 /// Else the member is part of a recursive type and thus the recursion has
7821 /// been exited too soon for the encoding to be correct for the member.
7823 class TypeStringCache {
7824 enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed};
7826 std::string Str; // The encoded TypeString for the type.
7827 enum Status State; // Information about the encoding in 'Str'.
7828 std::string Swapped; // A temporary place holder for a Recursive encoding
7829 // during the expansion of RecordType's members.
7831 std::map<const IdentifierInfo *, struct Entry> Map;
7832 unsigned IncompleteCount; // Number of Incomplete entries in the Map.
7833 unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map.
7835 TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {}
7836 void addIncomplete(const IdentifierInfo *ID, std::string StubEnc);
7837 bool removeIncomplete(const IdentifierInfo *ID);
7838 void addIfComplete(const IdentifierInfo *ID, StringRef Str,
7840 StringRef lookupStr(const IdentifierInfo *ID);
7843 /// TypeString encodings for enum & union fields must be order.
7844 /// FieldEncoding is a helper for this ordering process.
7845 class FieldEncoding {
7849 FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {}
7850 StringRef str() { return Enc; }
7851 bool operator<(const FieldEncoding &rhs) const {
7852 if (HasName != rhs.HasName) return HasName;
7853 return Enc < rhs.Enc;
7857 class XCoreABIInfo : public DefaultABIInfo {
7859 XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
7860 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7861 QualType Ty) const override;
7864 class XCoreTargetCodeGenInfo : public TargetCodeGenInfo {
7865 mutable TypeStringCache TSC;
7867 XCoreTargetCodeGenInfo(CodeGenTypes &CGT)
7868 :TargetCodeGenInfo(new XCoreABIInfo(CGT)) {}
7869 void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
7870 CodeGen::CodeGenModule &M) const override;
7873 } // End anonymous namespace.
7875 // TODO: this implementation is likely now redundant with the default
7877 Address XCoreABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7878 QualType Ty) const {
7879 CGBuilderTy &Builder = CGF.Builder;
7882 CharUnits SlotSize = CharUnits::fromQuantity(4);
7883 Address AP(Builder.CreateLoad(VAListAddr), SlotSize);
7885 // Handle the argument.
7886 ABIArgInfo AI = classifyArgumentType(Ty);
7887 CharUnits TypeAlign = getContext().getTypeAlignInChars(Ty);
7888 llvm::Type *ArgTy = CGT.ConvertType(Ty);
7889 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
7890 AI.setCoerceToType(ArgTy);
7891 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
7893 Address Val = Address::invalid();
7894 CharUnits ArgSize = CharUnits::Zero();
7895 switch (AI.getKind()) {
7896 case ABIArgInfo::Expand:
7897 case ABIArgInfo::CoerceAndExpand:
7898 case ABIArgInfo::InAlloca:
7899 llvm_unreachable("Unsupported ABI kind for va_arg");
7900 case ABIArgInfo::Ignore:
7901 Val = Address(llvm::UndefValue::get(ArgPtrTy), TypeAlign);
7902 ArgSize = CharUnits::Zero();
7904 case ABIArgInfo::Extend:
7905 case ABIArgInfo::Direct:
7906 Val = Builder.CreateBitCast(AP, ArgPtrTy);
7907 ArgSize = CharUnits::fromQuantity(
7908 getDataLayout().getTypeAllocSize(AI.getCoerceToType()));
7909 ArgSize = ArgSize.alignTo(SlotSize);
7911 case ABIArgInfo::Indirect:
7912 Val = Builder.CreateElementBitCast(AP, ArgPtrTy);
7913 Val = Address(Builder.CreateLoad(Val), TypeAlign);
7918 // Increment the VAList.
7919 if (!ArgSize.isZero()) {
7921 Builder.CreateConstInBoundsByteGEP(AP.getPointer(), ArgSize);
7922 Builder.CreateStore(APN, VAListAddr);
7928 /// During the expansion of a RecordType, an incomplete TypeString is placed
7929 /// into the cache as a means to identify and break recursion.
7930 /// If there is a Recursive encoding in the cache, it is swapped out and will
7931 /// be reinserted by removeIncomplete().
7932 /// All other types of encoding should have been used rather than arriving here.
7933 void TypeStringCache::addIncomplete(const IdentifierInfo *ID,
7934 std::string StubEnc) {
7938 assert( (E.Str.empty() || E.State == Recursive) &&
7939 "Incorrectly use of addIncomplete");
7940 assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()");
7941 E.Swapped.swap(E.Str); // swap out the Recursive
7942 E.Str.swap(StubEnc);
7943 E.State = Incomplete;
7947 /// Once the RecordType has been expanded, the temporary incomplete TypeString
7948 /// must be removed from the cache.
7949 /// If a Recursive was swapped out by addIncomplete(), it will be replaced.
7950 /// Returns true if the RecordType was defined recursively.
7951 bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) {
7954 auto I = Map.find(ID);
7955 assert(I != Map.end() && "Entry not present");
7956 Entry &E = I->second;
7957 assert( (E.State == Incomplete ||
7958 E.State == IncompleteUsed) &&
7959 "Entry must be an incomplete type");
7960 bool IsRecursive = false;
7961 if (E.State == IncompleteUsed) {
7962 // We made use of our Incomplete encoding, thus we are recursive.
7964 --IncompleteUsedCount;
7966 if (E.Swapped.empty())
7969 // Swap the Recursive back.
7970 E.Swapped.swap(E.Str);
7972 E.State = Recursive;
7978 /// Add the encoded TypeString to the cache only if it is NonRecursive or
7979 /// Recursive (viz: all sub-members were expanded as fully as possible).
7980 void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str,
7982 if (!ID || IncompleteUsedCount)
7983 return; // No key or it is is an incomplete sub-type so don't add.
7985 if (IsRecursive && !E.Str.empty()) {
7986 assert(E.State==Recursive && E.Str.size() == Str.size() &&
7987 "This is not the same Recursive entry");
7988 // The parent container was not recursive after all, so we could have used
7989 // this Recursive sub-member entry after all, but we assumed the worse when
7990 // we started viz: IncompleteCount!=0.
7993 assert(E.Str.empty() && "Entry already present");
7995 E.State = IsRecursive? Recursive : NonRecursive;
7998 /// Return a cached TypeString encoding for the ID. If there isn't one, or we
7999 /// are recursively expanding a type (IncompleteCount != 0) and the cached
8000 /// encoding is Recursive, return an empty StringRef.
8001 StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) {
8003 return StringRef(); // We have no key.
8004 auto I = Map.find(ID);
8006 return StringRef(); // We have no encoding.
8007 Entry &E = I->second;
8008 if (E.State == Recursive && IncompleteCount)
8009 return StringRef(); // We don't use Recursive encodings for member types.
8011 if (E.State == Incomplete) {
8012 // The incomplete type is being used to break out of recursion.
8013 E.State = IncompleteUsed;
8014 ++IncompleteUsedCount;
8019 /// The XCore ABI includes a type information section that communicates symbol
8020 /// type information to the linker. The linker uses this information to verify
8021 /// safety/correctness of things such as array bound and pointers et al.
8022 /// The ABI only requires C (and XC) language modules to emit TypeStrings.
8023 /// This type information (TypeString) is emitted into meta data for all global
8024 /// symbols: definitions, declarations, functions & variables.
8026 /// The TypeString carries type, qualifier, name, size & value details.
8027 /// Please see 'Tools Development Guide' section 2.16.2 for format details:
8028 /// https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf
8029 /// The output is tested by test/CodeGen/xcore-stringtype.c.
8031 static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
8032 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC);
8034 /// XCore uses emitTargetMD to emit TypeString metadata for global symbols.
8035 void XCoreTargetCodeGenInfo::emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
8036 CodeGen::CodeGenModule &CGM) const {
8038 if (getTypeString(Enc, D, CGM, TSC)) {
8039 llvm::LLVMContext &Ctx = CGM.getModule().getContext();
8040 llvm::Metadata *MDVals[] = {llvm::ConstantAsMetadata::get(GV),
8041 llvm::MDString::get(Ctx, Enc.str())};
8042 llvm::NamedMDNode *MD =
8043 CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings");
8044 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
8048 //===----------------------------------------------------------------------===//
8049 // SPIR ABI Implementation
8050 //===----------------------------------------------------------------------===//
8053 class SPIRTargetCodeGenInfo : public TargetCodeGenInfo {
8055 SPIRTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
8056 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
8057 unsigned getOpenCLKernelCallingConv() const override;
8060 } // End anonymous namespace.
8064 void computeSPIRKernelABIInfo(CodeGenModule &CGM, CGFunctionInfo &FI) {
8065 DefaultABIInfo SPIRABI(CGM.getTypes());
8066 SPIRABI.computeInfo(FI);
8071 unsigned SPIRTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
8072 return llvm::CallingConv::SPIR_KERNEL;
8075 static bool appendType(SmallStringEnc &Enc, QualType QType,
8076 const CodeGen::CodeGenModule &CGM,
8077 TypeStringCache &TSC);
8079 /// Helper function for appendRecordType().
8080 /// Builds a SmallVector containing the encoded field types in declaration
8082 static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE,
8083 const RecordDecl *RD,
8084 const CodeGen::CodeGenModule &CGM,
8085 TypeStringCache &TSC) {
8086 for (const auto *Field : RD->fields()) {
8089 Enc += Field->getName();
8091 if (Field->isBitField()) {
8093 llvm::raw_svector_ostream OS(Enc);
8094 OS << Field->getBitWidthValue(CGM.getContext());
8097 if (!appendType(Enc, Field->getType(), CGM, TSC))
8099 if (Field->isBitField())
8102 FE.emplace_back(!Field->getName().empty(), Enc);
8107 /// Appends structure and union types to Enc and adds encoding to cache.
8108 /// Recursively calls appendType (via extractFieldType) for each field.
8109 /// Union types have their fields ordered according to the ABI.
8110 static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT,
8111 const CodeGen::CodeGenModule &CGM,
8112 TypeStringCache &TSC, const IdentifierInfo *ID) {
8113 // Append the cached TypeString if we have one.
8114 StringRef TypeString = TSC.lookupStr(ID);
8115 if (!TypeString.empty()) {
8120 // Start to emit an incomplete TypeString.
8121 size_t Start = Enc.size();
8122 Enc += (RT->isUnionType()? 'u' : 's');
8125 Enc += ID->getName();
8128 // We collect all encoded fields and order as necessary.
8129 bool IsRecursive = false;
8130 const RecordDecl *RD = RT->getDecl()->getDefinition();
8131 if (RD && !RD->field_empty()) {
8132 // An incomplete TypeString stub is placed in the cache for this RecordType
8133 // so that recursive calls to this RecordType will use it whilst building a
8134 // complete TypeString for this RecordType.
8135 SmallVector<FieldEncoding, 16> FE;
8136 std::string StubEnc(Enc.substr(Start).str());
8137 StubEnc += '}'; // StubEnc now holds a valid incomplete TypeString.
8138 TSC.addIncomplete(ID, std::move(StubEnc));
8139 if (!extractFieldType(FE, RD, CGM, TSC)) {
8140 (void) TSC.removeIncomplete(ID);
8143 IsRecursive = TSC.removeIncomplete(ID);
8144 // The ABI requires unions to be sorted but not structures.
8145 // See FieldEncoding::operator< for sort algorithm.
8146 if (RT->isUnionType())
8147 std::sort(FE.begin(), FE.end());
8148 // We can now complete the TypeString.
8149 unsigned E = FE.size();
8150 for (unsigned I = 0; I != E; ++I) {
8157 TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive);
8161 /// Appends enum types to Enc and adds the encoding to the cache.
8162 static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET,
8163 TypeStringCache &TSC,
8164 const IdentifierInfo *ID) {
8165 // Append the cached TypeString if we have one.
8166 StringRef TypeString = TSC.lookupStr(ID);
8167 if (!TypeString.empty()) {
8172 size_t Start = Enc.size();
8175 Enc += ID->getName();
8178 // We collect all encoded enumerations and order them alphanumerically.
8179 if (const EnumDecl *ED = ET->getDecl()->getDefinition()) {
8180 SmallVector<FieldEncoding, 16> FE;
8181 for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E;
8183 SmallStringEnc EnumEnc;
8185 EnumEnc += I->getName();
8187 I->getInitVal().toString(EnumEnc);
8189 FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc));
8191 std::sort(FE.begin(), FE.end());
8192 unsigned E = FE.size();
8193 for (unsigned I = 0; I != E; ++I) {
8200 TSC.addIfComplete(ID, Enc.substr(Start), false);
8204 /// Appends type's qualifier to Enc.
8205 /// This is done prior to appending the type's encoding.
8206 static void appendQualifier(SmallStringEnc &Enc, QualType QT) {
8207 // Qualifiers are emitted in alphabetical order.
8208 static const char *const Table[]={"","c:","r:","cr:","v:","cv:","rv:","crv:"};
8210 if (QT.isConstQualified())
8212 if (QT.isRestrictQualified())
8214 if (QT.isVolatileQualified())
8216 Enc += Table[Lookup];
8219 /// Appends built-in types to Enc.
8220 static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) {
8221 const char *EncType;
8222 switch (BT->getKind()) {
8223 case BuiltinType::Void:
8226 case BuiltinType::Bool:
8229 case BuiltinType::Char_U:
8232 case BuiltinType::UChar:
8235 case BuiltinType::SChar:
8238 case BuiltinType::UShort:
8241 case BuiltinType::Short:
8244 case BuiltinType::UInt:
8247 case BuiltinType::Int:
8250 case BuiltinType::ULong:
8253 case BuiltinType::Long:
8256 case BuiltinType::ULongLong:
8259 case BuiltinType::LongLong:
8262 case BuiltinType::Float:
8265 case BuiltinType::Double:
8268 case BuiltinType::LongDouble:
8278 /// Appends a pointer encoding to Enc before calling appendType for the pointee.
8279 static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT,
8280 const CodeGen::CodeGenModule &CGM,
8281 TypeStringCache &TSC) {
8283 if (!appendType(Enc, PT->getPointeeType(), CGM, TSC))
8289 /// Appends array encoding to Enc before calling appendType for the element.
8290 static bool appendArrayType(SmallStringEnc &Enc, QualType QT,
8291 const ArrayType *AT,
8292 const CodeGen::CodeGenModule &CGM,
8293 TypeStringCache &TSC, StringRef NoSizeEnc) {
8294 if (AT->getSizeModifier() != ArrayType::Normal)
8297 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
8298 CAT->getSize().toStringUnsigned(Enc);
8300 Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "".
8302 // The Qualifiers should be attached to the type rather than the array.
8303 appendQualifier(Enc, QT);
8304 if (!appendType(Enc, AT->getElementType(), CGM, TSC))
8310 /// Appends a function encoding to Enc, calling appendType for the return type
8311 /// and the arguments.
8312 static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT,
8313 const CodeGen::CodeGenModule &CGM,
8314 TypeStringCache &TSC) {
8316 if (!appendType(Enc, FT->getReturnType(), CGM, TSC))
8319 if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) {
8320 // N.B. we are only interested in the adjusted param types.
8321 auto I = FPT->param_type_begin();
8322 auto E = FPT->param_type_end();
8325 if (!appendType(Enc, *I, CGM, TSC))
8331 if (FPT->isVariadic())
8334 if (FPT->isVariadic())
8344 /// Handles the type's qualifier before dispatching a call to handle specific
8346 static bool appendType(SmallStringEnc &Enc, QualType QType,
8347 const CodeGen::CodeGenModule &CGM,
8348 TypeStringCache &TSC) {
8350 QualType QT = QType.getCanonicalType();
8352 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe())
8353 // The Qualifiers should be attached to the type rather than the array.
8354 // Thus we don't call appendQualifier() here.
8355 return appendArrayType(Enc, QT, AT, CGM, TSC, "");
8357 appendQualifier(Enc, QT);
8359 if (const BuiltinType *BT = QT->getAs<BuiltinType>())
8360 return appendBuiltinType(Enc, BT);
8362 if (const PointerType *PT = QT->getAs<PointerType>())
8363 return appendPointerType(Enc, PT, CGM, TSC);
8365 if (const EnumType *ET = QT->getAs<EnumType>())
8366 return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier());
8368 if (const RecordType *RT = QT->getAsStructureType())
8369 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
8371 if (const RecordType *RT = QT->getAsUnionType())
8372 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
8374 if (const FunctionType *FT = QT->getAs<FunctionType>())
8375 return appendFunctionType(Enc, FT, CGM, TSC);
8380 static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
8381 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC) {
8385 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8386 if (FD->getLanguageLinkage() != CLanguageLinkage)
8388 return appendType(Enc, FD->getType(), CGM, TSC);
8391 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
8392 if (VD->getLanguageLinkage() != CLanguageLinkage)
8394 QualType QT = VD->getType().getCanonicalType();
8395 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) {
8396 // Global ArrayTypes are given a size of '*' if the size is unknown.
8397 // The Qualifiers should be attached to the type rather than the array.
8398 // Thus we don't call appendQualifier() here.
8399 return appendArrayType(Enc, QT, AT, CGM, TSC, "*");
8401 return appendType(Enc, QT, CGM, TSC);
8407 //===----------------------------------------------------------------------===//
8409 //===----------------------------------------------------------------------===//
8411 bool CodeGenModule::supportsCOMDAT() const {
8412 return getTriple().supportsCOMDAT();
8415 const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
8416 if (TheTargetCodeGenInfo)
8417 return *TheTargetCodeGenInfo;
8419 // Helper to set the unique_ptr while still keeping the return value.
8420 auto SetCGInfo = [&](TargetCodeGenInfo *P) -> const TargetCodeGenInfo & {
8421 this->TheTargetCodeGenInfo.reset(P);
8425 const llvm::Triple &Triple = getTarget().getTriple();
8426 switch (Triple.getArch()) {
8428 return SetCGInfo(new DefaultTargetCodeGenInfo(Types));
8430 case llvm::Triple::le32:
8431 return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
8432 case llvm::Triple::mips:
8433 case llvm::Triple::mipsel:
8434 if (Triple.getOS() == llvm::Triple::NaCl)
8435 return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
8436 return SetCGInfo(new MIPSTargetCodeGenInfo(Types, true));
8438 case llvm::Triple::mips64:
8439 case llvm::Triple::mips64el:
8440 return SetCGInfo(new MIPSTargetCodeGenInfo(Types, false));
8442 case llvm::Triple::avr:
8443 return SetCGInfo(new AVRTargetCodeGenInfo(Types));
8445 case llvm::Triple::aarch64:
8446 case llvm::Triple::aarch64_be: {
8447 AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS;
8448 if (getTarget().getABI() == "darwinpcs")
8449 Kind = AArch64ABIInfo::DarwinPCS;
8451 return SetCGInfo(new AArch64TargetCodeGenInfo(Types, Kind));
8454 case llvm::Triple::wasm32:
8455 case llvm::Triple::wasm64:
8456 return SetCGInfo(new WebAssemblyTargetCodeGenInfo(Types));
8458 case llvm::Triple::arm:
8459 case llvm::Triple::armeb:
8460 case llvm::Triple::thumb:
8461 case llvm::Triple::thumbeb: {
8462 if (Triple.getOS() == llvm::Triple::Win32) {
8464 new WindowsARMTargetCodeGenInfo(Types, ARMABIInfo::AAPCS_VFP));
8467 ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
8468 StringRef ABIStr = getTarget().getABI();
8469 if (ABIStr == "apcs-gnu")
8470 Kind = ARMABIInfo::APCS;
8471 else if (ABIStr == "aapcs16")
8472 Kind = ARMABIInfo::AAPCS16_VFP;
8473 else if (CodeGenOpts.FloatABI == "hard" ||
8474 (CodeGenOpts.FloatABI != "soft" &&
8475 (Triple.getEnvironment() == llvm::Triple::GNUEABIHF ||
8476 Triple.getEnvironment() == llvm::Triple::MuslEABIHF ||
8477 Triple.getEnvironment() == llvm::Triple::EABIHF)))
8478 Kind = ARMABIInfo::AAPCS_VFP;
8480 return SetCGInfo(new ARMTargetCodeGenInfo(Types, Kind));
8483 case llvm::Triple::ppc:
8485 new PPC32TargetCodeGenInfo(Types, CodeGenOpts.FloatABI == "soft"));
8486 case llvm::Triple::ppc64:
8487 if (Triple.isOSBinFormatELF()) {
8488 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1;
8489 if (getTarget().getABI() == "elfv2")
8490 Kind = PPC64_SVR4_ABIInfo::ELFv2;
8491 bool HasQPX = getTarget().getABI() == "elfv1-qpx";
8492 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
8494 return SetCGInfo(new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX,
8497 return SetCGInfo(new PPC64TargetCodeGenInfo(Types));
8498 case llvm::Triple::ppc64le: {
8499 assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
8500 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2;
8501 if (getTarget().getABI() == "elfv1" || getTarget().getABI() == "elfv1-qpx")
8502 Kind = PPC64_SVR4_ABIInfo::ELFv1;
8503 bool HasQPX = getTarget().getABI() == "elfv1-qpx";
8504 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
8506 return SetCGInfo(new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX,
8510 case llvm::Triple::nvptx:
8511 case llvm::Triple::nvptx64:
8512 return SetCGInfo(new NVPTXTargetCodeGenInfo(Types));
8514 case llvm::Triple::msp430:
8515 return SetCGInfo(new MSP430TargetCodeGenInfo(Types));
8517 case llvm::Triple::systemz: {
8518 bool HasVector = getTarget().getABI() == "vector";
8519 return SetCGInfo(new SystemZTargetCodeGenInfo(Types, HasVector));
8522 case llvm::Triple::tce:
8523 case llvm::Triple::tcele:
8524 return SetCGInfo(new TCETargetCodeGenInfo(Types));
8526 case llvm::Triple::x86: {
8527 bool IsDarwinVectorABI = Triple.isOSDarwin();
8528 bool RetSmallStructInRegABI =
8529 X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
8530 bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
8532 if (Triple.getOS() == llvm::Triple::Win32) {
8533 return SetCGInfo(new WinX86_32TargetCodeGenInfo(
8534 Types, IsDarwinVectorABI, RetSmallStructInRegABI,
8535 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters));
8537 return SetCGInfo(new X86_32TargetCodeGenInfo(
8538 Types, IsDarwinVectorABI, RetSmallStructInRegABI,
8539 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters,
8540 CodeGenOpts.FloatABI == "soft"));
8544 case llvm::Triple::x86_64: {
8545 StringRef ABI = getTarget().getABI();
8546 X86AVXABILevel AVXLevel =
8548 ? X86AVXABILevel::AVX512
8549 : ABI == "avx" ? X86AVXABILevel::AVX : X86AVXABILevel::None);
8551 switch (Triple.getOS()) {
8552 case llvm::Triple::Win32:
8553 return SetCGInfo(new WinX86_64TargetCodeGenInfo(Types, AVXLevel));
8554 case llvm::Triple::PS4:
8555 return SetCGInfo(new PS4TargetCodeGenInfo(Types, AVXLevel));
8557 return SetCGInfo(new X86_64TargetCodeGenInfo(Types, AVXLevel));
8560 case llvm::Triple::hexagon:
8561 return SetCGInfo(new HexagonTargetCodeGenInfo(Types));
8562 case llvm::Triple::lanai:
8563 return SetCGInfo(new LanaiTargetCodeGenInfo(Types));
8564 case llvm::Triple::r600:
8565 return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
8566 case llvm::Triple::amdgcn:
8567 return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
8568 case llvm::Triple::sparc:
8569 return SetCGInfo(new SparcV8TargetCodeGenInfo(Types));
8570 case llvm::Triple::sparcv9:
8571 return SetCGInfo(new SparcV9TargetCodeGenInfo(Types));
8572 case llvm::Triple::xcore:
8573 return SetCGInfo(new XCoreTargetCodeGenInfo(Types));
8574 case llvm::Triple::spir:
8575 case llvm::Triple::spir64:
8576 return SetCGInfo(new SPIRTargetCodeGenInfo(Types));