1 //===---- TargetInfo.cpp - Encapsulate target details -----------*- C++ -*-===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // These classes wrap the information about a call or function 10 // definition used to handle ABI compliancy. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "TargetInfo.h" 15 #include "ABIInfo.h" 16 #include "CGBlocks.h" 17 #include "CGCXXABI.h" 18 #include "CGValue.h" 19 #include "CodeGenFunction.h" 20 #include "clang/AST/Attr.h" 21 #include "clang/AST/RecordLayout.h" 22 #include "clang/Basic/CodeGenOptions.h" 23 #include "clang/Basic/DiagnosticFrontend.h" 24 #include "clang/Basic/Builtins.h" 25 #include "clang/CodeGen/CGFunctionInfo.h" 26 #include "clang/CodeGen/SwiftCallingConv.h" 27 #include "llvm/ADT/SmallBitVector.h" 28 #include "llvm/ADT/StringExtras.h" 29 #include "llvm/ADT/StringSwitch.h" 30 #include "llvm/ADT/Triple.h" 31 #include "llvm/ADT/Twine.h" 32 #include "llvm/IR/DataLayout.h" 33 #include "llvm/IR/IntrinsicsNVPTX.h" 34 #include "llvm/IR/IntrinsicsS390.h" 35 #include "llvm/IR/Type.h" 36 #include "llvm/Support/raw_ostream.h" 37 #include <algorithm> // std::sort 38 39 using namespace clang; 40 using namespace CodeGen; 41 42 // Helper for coercing an aggregate argument or return value into an integer 43 // array of the same size (including padding) and alignment. This alternate 44 // coercion happens only for the RenderScript ABI and can be removed after 45 // runtimes that rely on it are no longer supported. 46 // 47 // RenderScript assumes that the size of the argument / return value in the IR 48 // is the same as the size of the corresponding qualified type. This helper 49 // coerces the aggregate type into an array of the same size (including 50 // padding). This coercion is used in lieu of expansion of struct members or 51 // other canonical coercions that return a coerced-type of larger size. 52 // 53 // Ty - The argument / return value type 54 // Context - The associated ASTContext 55 // LLVMContext - The associated LLVMContext 56 static ABIArgInfo coerceToIntArray(QualType Ty, 57 ASTContext &Context, 58 llvm::LLVMContext &LLVMContext) { 59 // Alignment and Size are measured in bits. 60 const uint64_t Size = Context.getTypeSize(Ty); 61 const uint64_t Alignment = Context.getTypeAlign(Ty); 62 llvm::Type *IntType = llvm::Type::getIntNTy(LLVMContext, Alignment); 63 const uint64_t NumElements = (Size + Alignment - 1) / Alignment; 64 return ABIArgInfo::getDirect(llvm::ArrayType::get(IntType, NumElements)); 65 } 66 67 static void AssignToArrayRange(CodeGen::CGBuilderTy &Builder, 68 llvm::Value *Array, 69 llvm::Value *Value, 70 unsigned FirstIndex, 71 unsigned LastIndex) { 72 // Alternatively, we could emit this as a loop in the source. 73 for (unsigned I = FirstIndex; I <= LastIndex; ++I) { 74 llvm::Value *Cell = 75 Builder.CreateConstInBoundsGEP1_32(Builder.getInt8Ty(), Array, I); 76 Builder.CreateAlignedStore(Value, Cell, CharUnits::One()); 77 } 78 } 79 80 static bool isAggregateTypeForABI(QualType T) { 81 return !CodeGenFunction::hasScalarEvaluationKind(T) || 82 T->isMemberFunctionPointerType(); 83 } 84 85 ABIArgInfo ABIInfo::getNaturalAlignIndirect(QualType Ty, bool ByVal, 86 bool Realign, 87 llvm::Type *Padding) const { 88 return ABIArgInfo::getIndirect(getContext().getTypeAlignInChars(Ty), ByVal, 89 Realign, Padding); 90 } 91 92 ABIArgInfo 93 ABIInfo::getNaturalAlignIndirectInReg(QualType Ty, bool Realign) const { 94 return ABIArgInfo::getIndirectInReg(getContext().getTypeAlignInChars(Ty), 95 /*ByVal*/ false, Realign); 96 } 97 98 Address ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr, 99 QualType Ty) const { 100 return Address::invalid(); 101 } 102 103 bool ABIInfo::isPromotableIntegerTypeForABI(QualType Ty) const { 104 if (Ty->isPromotableIntegerType()) 105 return true; 106 107 if (const auto *EIT = Ty->getAs<ExtIntType>()) 108 if (EIT->getNumBits() < getContext().getTypeSize(getContext().IntTy)) 109 return true; 110 111 return false; 112 } 113 114 ABIInfo::~ABIInfo() {} 115 116 /// Does the given lowering require more than the given number of 117 /// registers when expanded? 118 /// 119 /// This is intended to be the basis of a reasonable basic implementation 120 /// of should{Pass,Return}IndirectlyForSwift. 121 /// 122 /// For most targets, a limit of four total registers is reasonable; this 123 /// limits the amount of code required in order to move around the value 124 /// in case it wasn't produced immediately prior to the call by the caller 125 /// (or wasn't produced in exactly the right registers) or isn't used 126 /// immediately within the callee. But some targets may need to further 127 /// limit the register count due to an inability to support that many 128 /// return registers. 129 static bool occupiesMoreThan(CodeGenTypes &cgt, 130 ArrayRef<llvm::Type*> scalarTypes, 131 unsigned maxAllRegisters) { 132 unsigned intCount = 0, fpCount = 0; 133 for (llvm::Type *type : scalarTypes) { 134 if (type->isPointerTy()) { 135 intCount++; 136 } else if (auto intTy = dyn_cast<llvm::IntegerType>(type)) { 137 auto ptrWidth = cgt.getTarget().getPointerWidth(0); 138 intCount += (intTy->getBitWidth() + ptrWidth - 1) / ptrWidth; 139 } else { 140 assert(type->isVectorTy() || type->isFloatingPointTy()); 141 fpCount++; 142 } 143 } 144 145 return (intCount + fpCount > maxAllRegisters); 146 } 147 148 bool SwiftABIInfo::isLegalVectorTypeForSwift(CharUnits vectorSize, 149 llvm::Type *eltTy, 150 unsigned numElts) const { 151 // The default implementation of this assumes that the target guarantees 152 // 128-bit SIMD support but nothing more. 153 return (vectorSize.getQuantity() > 8 && vectorSize.getQuantity() <= 16); 154 } 155 156 static CGCXXABI::RecordArgABI getRecordArgABI(const RecordType *RT, 157 CGCXXABI &CXXABI) { 158 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 159 if (!RD) { 160 if (!RT->getDecl()->canPassInRegisters()) 161 return CGCXXABI::RAA_Indirect; 162 return CGCXXABI::RAA_Default; 163 } 164 return CXXABI.getRecordArgABI(RD); 165 } 166 167 static CGCXXABI::RecordArgABI getRecordArgABI(QualType T, 168 CGCXXABI &CXXABI) { 169 const RecordType *RT = T->getAs<RecordType>(); 170 if (!RT) 171 return CGCXXABI::RAA_Default; 172 return getRecordArgABI(RT, CXXABI); 173 } 174 175 static bool classifyReturnType(const CGCXXABI &CXXABI, CGFunctionInfo &FI, 176 const ABIInfo &Info) { 177 QualType Ty = FI.getReturnType(); 178 179 if (const auto *RT = Ty->getAs<RecordType>()) 180 if (!isa<CXXRecordDecl>(RT->getDecl()) && 181 !RT->getDecl()->canPassInRegisters()) { 182 FI.getReturnInfo() = Info.getNaturalAlignIndirect(Ty); 183 return true; 184 } 185 186 return CXXABI.classifyReturnType(FI); 187 } 188 189 /// Pass transparent unions as if they were the type of the first element. Sema 190 /// should ensure that all elements of the union have the same "machine type". 191 static QualType useFirstFieldIfTransparentUnion(QualType Ty) { 192 if (const RecordType *UT = Ty->getAsUnionType()) { 193 const RecordDecl *UD = UT->getDecl(); 194 if (UD->hasAttr<TransparentUnionAttr>()) { 195 assert(!UD->field_empty() && "sema created an empty transparent union"); 196 return UD->field_begin()->getType(); 197 } 198 } 199 return Ty; 200 } 201 202 CGCXXABI &ABIInfo::getCXXABI() const { 203 return CGT.getCXXABI(); 204 } 205 206 ASTContext &ABIInfo::getContext() const { 207 return CGT.getContext(); 208 } 209 210 llvm::LLVMContext &ABIInfo::getVMContext() const { 211 return CGT.getLLVMContext(); 212 } 213 214 const llvm::DataLayout &ABIInfo::getDataLayout() const { 215 return CGT.getDataLayout(); 216 } 217 218 const TargetInfo &ABIInfo::getTarget() const { 219 return CGT.getTarget(); 220 } 221 222 const CodeGenOptions &ABIInfo::getCodeGenOpts() const { 223 return CGT.getCodeGenOpts(); 224 } 225 226 bool ABIInfo::isAndroid() const { return getTarget().getTriple().isAndroid(); } 227 228 bool ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const { 229 return false; 230 } 231 232 bool ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base, 233 uint64_t Members) const { 234 return false; 235 } 236 237 LLVM_DUMP_METHOD void ABIArgInfo::dump() const { 238 raw_ostream &OS = llvm::errs(); 239 OS << "(ABIArgInfo Kind="; 240 switch (TheKind) { 241 case Direct: 242 OS << "Direct Type="; 243 if (llvm::Type *Ty = getCoerceToType()) 244 Ty->print(OS); 245 else 246 OS << "null"; 247 break; 248 case Extend: 249 OS << "Extend"; 250 break; 251 case Ignore: 252 OS << "Ignore"; 253 break; 254 case InAlloca: 255 OS << "InAlloca Offset=" << getInAllocaFieldIndex(); 256 break; 257 case Indirect: 258 OS << "Indirect Align=" << getIndirectAlign().getQuantity() 259 << " ByVal=" << getIndirectByVal() 260 << " Realign=" << getIndirectRealign(); 261 break; 262 case IndirectAliased: 263 OS << "Indirect Align=" << getIndirectAlign().getQuantity() 264 << " AadrSpace=" << getIndirectAddrSpace() 265 << " Realign=" << getIndirectRealign(); 266 break; 267 case Expand: 268 OS << "Expand"; 269 break; 270 case CoerceAndExpand: 271 OS << "CoerceAndExpand Type="; 272 getCoerceAndExpandType()->print(OS); 273 break; 274 } 275 OS << ")\n"; 276 } 277 278 // Dynamically round a pointer up to a multiple of the given alignment. 279 static llvm::Value *emitRoundPointerUpToAlignment(CodeGenFunction &CGF, 280 llvm::Value *Ptr, 281 CharUnits Align) { 282 llvm::Value *PtrAsInt = Ptr; 283 // OverflowArgArea = (OverflowArgArea + Align - 1) & -Align; 284 PtrAsInt = CGF.Builder.CreatePtrToInt(PtrAsInt, CGF.IntPtrTy); 285 PtrAsInt = CGF.Builder.CreateAdd(PtrAsInt, 286 llvm::ConstantInt::get(CGF.IntPtrTy, Align.getQuantity() - 1)); 287 PtrAsInt = CGF.Builder.CreateAnd(PtrAsInt, 288 llvm::ConstantInt::get(CGF.IntPtrTy, -Align.getQuantity())); 289 PtrAsInt = CGF.Builder.CreateIntToPtr(PtrAsInt, 290 Ptr->getType(), 291 Ptr->getName() + ".aligned"); 292 return PtrAsInt; 293 } 294 295 /// Emit va_arg for a platform using the common void* representation, 296 /// where arguments are simply emitted in an array of slots on the stack. 297 /// 298 /// This version implements the core direct-value passing rules. 299 /// 300 /// \param SlotSize - The size and alignment of a stack slot. 301 /// Each argument will be allocated to a multiple of this number of 302 /// slots, and all the slots will be aligned to this value. 303 /// \param AllowHigherAlign - The slot alignment is not a cap; 304 /// an argument type with an alignment greater than the slot size 305 /// will be emitted on a higher-alignment address, potentially 306 /// leaving one or more empty slots behind as padding. If this 307 /// is false, the returned address might be less-aligned than 308 /// DirectAlign. 309 static Address emitVoidPtrDirectVAArg(CodeGenFunction &CGF, 310 Address VAListAddr, 311 llvm::Type *DirectTy, 312 CharUnits DirectSize, 313 CharUnits DirectAlign, 314 CharUnits SlotSize, 315 bool AllowHigherAlign) { 316 // Cast the element type to i8* if necessary. Some platforms define 317 // va_list as a struct containing an i8* instead of just an i8*. 318 if (VAListAddr.getElementType() != CGF.Int8PtrTy) 319 VAListAddr = CGF.Builder.CreateElementBitCast(VAListAddr, CGF.Int8PtrTy); 320 321 llvm::Value *Ptr = CGF.Builder.CreateLoad(VAListAddr, "argp.cur"); 322 323 // If the CC aligns values higher than the slot size, do so if needed. 324 Address Addr = Address::invalid(); 325 if (AllowHigherAlign && DirectAlign > SlotSize) { 326 Addr = Address(emitRoundPointerUpToAlignment(CGF, Ptr, DirectAlign), 327 DirectAlign); 328 } else { 329 Addr = Address(Ptr, SlotSize); 330 } 331 332 // Advance the pointer past the argument, then store that back. 333 CharUnits FullDirectSize = DirectSize.alignTo(SlotSize); 334 Address NextPtr = 335 CGF.Builder.CreateConstInBoundsByteGEP(Addr, FullDirectSize, "argp.next"); 336 CGF.Builder.CreateStore(NextPtr.getPointer(), VAListAddr); 337 338 // If the argument is smaller than a slot, and this is a big-endian 339 // target, the argument will be right-adjusted in its slot. 340 if (DirectSize < SlotSize && CGF.CGM.getDataLayout().isBigEndian() && 341 !DirectTy->isStructTy()) { 342 Addr = CGF.Builder.CreateConstInBoundsByteGEP(Addr, SlotSize - DirectSize); 343 } 344 345 Addr = CGF.Builder.CreateElementBitCast(Addr, DirectTy); 346 return Addr; 347 } 348 349 /// Emit va_arg for a platform using the common void* representation, 350 /// where arguments are simply emitted in an array of slots on the stack. 351 /// 352 /// \param IsIndirect - Values of this type are passed indirectly. 353 /// \param ValueInfo - The size and alignment of this type, generally 354 /// computed with getContext().getTypeInfoInChars(ValueTy). 355 /// \param SlotSizeAndAlign - The size and alignment of a stack slot. 356 /// Each argument will be allocated to a multiple of this number of 357 /// slots, and all the slots will be aligned to this value. 358 /// \param AllowHigherAlign - The slot alignment is not a cap; 359 /// an argument type with an alignment greater than the slot size 360 /// will be emitted on a higher-alignment address, potentially 361 /// leaving one or more empty slots behind as padding. 362 static Address emitVoidPtrVAArg(CodeGenFunction &CGF, Address VAListAddr, 363 QualType ValueTy, bool IsIndirect, 364 TypeInfoChars ValueInfo, 365 CharUnits SlotSizeAndAlign, 366 bool AllowHigherAlign) { 367 // The size and alignment of the value that was passed directly. 368 CharUnits DirectSize, DirectAlign; 369 if (IsIndirect) { 370 DirectSize = CGF.getPointerSize(); 371 DirectAlign = CGF.getPointerAlign(); 372 } else { 373 DirectSize = ValueInfo.Width; 374 DirectAlign = ValueInfo.Align; 375 } 376 377 // Cast the address we've calculated to the right type. 378 llvm::Type *DirectTy = CGF.ConvertTypeForMem(ValueTy); 379 if (IsIndirect) 380 DirectTy = DirectTy->getPointerTo(0); 381 382 Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, DirectTy, 383 DirectSize, DirectAlign, 384 SlotSizeAndAlign, 385 AllowHigherAlign); 386 387 if (IsIndirect) { 388 Addr = Address(CGF.Builder.CreateLoad(Addr), ValueInfo.Align); 389 } 390 391 return Addr; 392 393 } 394 395 static Address complexTempStructure(CodeGenFunction &CGF, Address VAListAddr, 396 QualType Ty, CharUnits SlotSize, 397 CharUnits EltSize, const ComplexType *CTy) { 398 Address Addr = 399 emitVoidPtrDirectVAArg(CGF, VAListAddr, CGF.Int8Ty, SlotSize * 2, 400 SlotSize, SlotSize, /*AllowHigher*/ true); 401 402 Address RealAddr = Addr; 403 Address ImagAddr = RealAddr; 404 if (CGF.CGM.getDataLayout().isBigEndian()) { 405 RealAddr = 406 CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, SlotSize - EltSize); 407 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(ImagAddr, 408 2 * SlotSize - EltSize); 409 } else { 410 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, SlotSize); 411 } 412 413 llvm::Type *EltTy = CGF.ConvertTypeForMem(CTy->getElementType()); 414 RealAddr = CGF.Builder.CreateElementBitCast(RealAddr, EltTy); 415 ImagAddr = CGF.Builder.CreateElementBitCast(ImagAddr, EltTy); 416 llvm::Value *Real = CGF.Builder.CreateLoad(RealAddr, ".vareal"); 417 llvm::Value *Imag = CGF.Builder.CreateLoad(ImagAddr, ".vaimag"); 418 419 Address Temp = CGF.CreateMemTemp(Ty, "vacplx"); 420 CGF.EmitStoreOfComplex({Real, Imag}, CGF.MakeAddrLValue(Temp, Ty), 421 /*init*/ true); 422 return Temp; 423 } 424 425 static Address emitMergePHI(CodeGenFunction &CGF, 426 Address Addr1, llvm::BasicBlock *Block1, 427 Address Addr2, llvm::BasicBlock *Block2, 428 const llvm::Twine &Name = "") { 429 assert(Addr1.getType() == Addr2.getType()); 430 llvm::PHINode *PHI = CGF.Builder.CreatePHI(Addr1.getType(), 2, Name); 431 PHI->addIncoming(Addr1.getPointer(), Block1); 432 PHI->addIncoming(Addr2.getPointer(), Block2); 433 CharUnits Align = std::min(Addr1.getAlignment(), Addr2.getAlignment()); 434 return Address(PHI, Align); 435 } 436 437 TargetCodeGenInfo::~TargetCodeGenInfo() = default; 438 439 // If someone can figure out a general rule for this, that would be great. 440 // It's probably just doomed to be platform-dependent, though. 441 unsigned TargetCodeGenInfo::getSizeOfUnwindException() const { 442 // Verified for: 443 // x86-64 FreeBSD, Linux, Darwin 444 // x86-32 FreeBSD, Linux, Darwin 445 // PowerPC Linux, Darwin 446 // ARM Darwin (*not* EABI) 447 // AArch64 Linux 448 return 32; 449 } 450 451 bool TargetCodeGenInfo::isNoProtoCallVariadic(const CallArgList &args, 452 const FunctionNoProtoType *fnType) const { 453 // The following conventions are known to require this to be false: 454 // x86_stdcall 455 // MIPS 456 // For everything else, we just prefer false unless we opt out. 457 return false; 458 } 459 460 void 461 TargetCodeGenInfo::getDependentLibraryOption(llvm::StringRef Lib, 462 llvm::SmallString<24> &Opt) const { 463 // This assumes the user is passing a library name like "rt" instead of a 464 // filename like "librt.a/so", and that they don't care whether it's static or 465 // dynamic. 466 Opt = "-l"; 467 Opt += Lib; 468 } 469 470 unsigned TargetCodeGenInfo::getOpenCLKernelCallingConv() const { 471 // OpenCL kernels are called via an explicit runtime API with arguments 472 // set with clSetKernelArg(), not as normal sub-functions. 473 // Return SPIR_KERNEL by default as the kernel calling convention to 474 // ensure the fingerprint is fixed such way that each OpenCL argument 475 // gets one matching argument in the produced kernel function argument 476 // list to enable feasible implementation of clSetKernelArg() with 477 // aggregates etc. In case we would use the default C calling conv here, 478 // clSetKernelArg() might break depending on the target-specific 479 // conventions; different targets might split structs passed as values 480 // to multiple function arguments etc. 481 return llvm::CallingConv::SPIR_KERNEL; 482 } 483 484 llvm::Constant *TargetCodeGenInfo::getNullPointer(const CodeGen::CodeGenModule &CGM, 485 llvm::PointerType *T, QualType QT) const { 486 return llvm::ConstantPointerNull::get(T); 487 } 488 489 LangAS TargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM, 490 const VarDecl *D) const { 491 assert(!CGM.getLangOpts().OpenCL && 492 !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) && 493 "Address space agnostic languages only"); 494 return D ? D->getType().getAddressSpace() : LangAS::Default; 495 } 496 497 llvm::Value *TargetCodeGenInfo::performAddrSpaceCast( 498 CodeGen::CodeGenFunction &CGF, llvm::Value *Src, LangAS SrcAddr, 499 LangAS DestAddr, llvm::Type *DestTy, bool isNonNull) const { 500 // Since target may map different address spaces in AST to the same address 501 // space, an address space conversion may end up as a bitcast. 502 if (auto *C = dyn_cast<llvm::Constant>(Src)) 503 return performAddrSpaceCast(CGF.CGM, C, SrcAddr, DestAddr, DestTy); 504 // Try to preserve the source's name to make IR more readable. 505 return CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( 506 Src, DestTy, Src->hasName() ? Src->getName() + ".ascast" : ""); 507 } 508 509 llvm::Constant * 510 TargetCodeGenInfo::performAddrSpaceCast(CodeGenModule &CGM, llvm::Constant *Src, 511 LangAS SrcAddr, LangAS DestAddr, 512 llvm::Type *DestTy) const { 513 // Since target may map different address spaces in AST to the same address 514 // space, an address space conversion may end up as a bitcast. 515 return llvm::ConstantExpr::getPointerCast(Src, DestTy); 516 } 517 518 llvm::SyncScope::ID 519 TargetCodeGenInfo::getLLVMSyncScopeID(const LangOptions &LangOpts, 520 SyncScope Scope, 521 llvm::AtomicOrdering Ordering, 522 llvm::LLVMContext &Ctx) const { 523 return Ctx.getOrInsertSyncScopeID(""); /* default sync scope */ 524 } 525 526 static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays); 527 528 /// isEmptyField - Return true iff a the field is "empty", that is it 529 /// is an unnamed bit-field or an (array of) empty record(s). 530 static bool isEmptyField(ASTContext &Context, const FieldDecl *FD, 531 bool AllowArrays) { 532 if (FD->isUnnamedBitfield()) 533 return true; 534 535 QualType FT = FD->getType(); 536 537 // Constant arrays of empty records count as empty, strip them off. 538 // Constant arrays of zero length always count as empty. 539 bool WasArray = false; 540 if (AllowArrays) 541 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) { 542 if (AT->getSize() == 0) 543 return true; 544 FT = AT->getElementType(); 545 // The [[no_unique_address]] special case below does not apply to 546 // arrays of C++ empty records, so we need to remember this fact. 547 WasArray = true; 548 } 549 550 const RecordType *RT = FT->getAs<RecordType>(); 551 if (!RT) 552 return false; 553 554 // C++ record fields are never empty, at least in the Itanium ABI. 555 // 556 // FIXME: We should use a predicate for whether this behavior is true in the 557 // current ABI. 558 // 559 // The exception to the above rule are fields marked with the 560 // [[no_unique_address]] attribute (since C++20). Those do count as empty 561 // according to the Itanium ABI. The exception applies only to records, 562 // not arrays of records, so we must also check whether we stripped off an 563 // array type above. 564 if (isa<CXXRecordDecl>(RT->getDecl()) && 565 (WasArray || !FD->hasAttr<NoUniqueAddressAttr>())) 566 return false; 567 568 return isEmptyRecord(Context, FT, AllowArrays); 569 } 570 571 /// isEmptyRecord - Return true iff a structure contains only empty 572 /// fields. Note that a structure with a flexible array member is not 573 /// considered empty. 574 static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) { 575 const RecordType *RT = T->getAs<RecordType>(); 576 if (!RT) 577 return false; 578 const RecordDecl *RD = RT->getDecl(); 579 if (RD->hasFlexibleArrayMember()) 580 return false; 581 582 // If this is a C++ record, check the bases first. 583 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 584 for (const auto &I : CXXRD->bases()) 585 if (!isEmptyRecord(Context, I.getType(), true)) 586 return false; 587 588 for (const auto *I : RD->fields()) 589 if (!isEmptyField(Context, I, AllowArrays)) 590 return false; 591 return true; 592 } 593 594 /// isSingleElementStruct - Determine if a structure is a "single 595 /// element struct", i.e. it has exactly one non-empty field or 596 /// exactly one field which is itself a single element 597 /// struct. Structures with flexible array members are never 598 /// considered single element structs. 599 /// 600 /// \return The field declaration for the single non-empty field, if 601 /// it exists. 602 static const Type *isSingleElementStruct(QualType T, ASTContext &Context) { 603 const RecordType *RT = T->getAs<RecordType>(); 604 if (!RT) 605 return nullptr; 606 607 const RecordDecl *RD = RT->getDecl(); 608 if (RD->hasFlexibleArrayMember()) 609 return nullptr; 610 611 const Type *Found = nullptr; 612 613 // If this is a C++ record, check the bases first. 614 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 615 for (const auto &I : CXXRD->bases()) { 616 // Ignore empty records. 617 if (isEmptyRecord(Context, I.getType(), true)) 618 continue; 619 620 // If we already found an element then this isn't a single-element struct. 621 if (Found) 622 return nullptr; 623 624 // If this is non-empty and not a single element struct, the composite 625 // cannot be a single element struct. 626 Found = isSingleElementStruct(I.getType(), Context); 627 if (!Found) 628 return nullptr; 629 } 630 } 631 632 // Check for single element. 633 for (const auto *FD : RD->fields()) { 634 QualType FT = FD->getType(); 635 636 // Ignore empty fields. 637 if (isEmptyField(Context, FD, true)) 638 continue; 639 640 // If we already found an element then this isn't a single-element 641 // struct. 642 if (Found) 643 return nullptr; 644 645 // Treat single element arrays as the element. 646 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) { 647 if (AT->getSize().getZExtValue() != 1) 648 break; 649 FT = AT->getElementType(); 650 } 651 652 if (!isAggregateTypeForABI(FT)) { 653 Found = FT.getTypePtr(); 654 } else { 655 Found = isSingleElementStruct(FT, Context); 656 if (!Found) 657 return nullptr; 658 } 659 } 660 661 // We don't consider a struct a single-element struct if it has 662 // padding beyond the element type. 663 if (Found && Context.getTypeSize(Found) != Context.getTypeSize(T)) 664 return nullptr; 665 666 return Found; 667 } 668 669 namespace { 670 Address EmitVAArgInstr(CodeGenFunction &CGF, Address VAListAddr, QualType Ty, 671 const ABIArgInfo &AI) { 672 // This default implementation defers to the llvm backend's va_arg 673 // instruction. It can handle only passing arguments directly 674 // (typically only handled in the backend for primitive types), or 675 // aggregates passed indirectly by pointer (NOTE: if the "byval" 676 // flag has ABI impact in the callee, this implementation cannot 677 // work.) 678 679 // Only a few cases are covered here at the moment -- those needed 680 // by the default abi. 681 llvm::Value *Val; 682 683 if (AI.isIndirect()) { 684 assert(!AI.getPaddingType() && 685 "Unexpected PaddingType seen in arginfo in generic VAArg emitter!"); 686 assert( 687 !AI.getIndirectRealign() && 688 "Unexpected IndirectRealign seen in arginfo in generic VAArg emitter!"); 689 690 auto TyInfo = CGF.getContext().getTypeInfoInChars(Ty); 691 CharUnits TyAlignForABI = TyInfo.Align; 692 693 llvm::Type *BaseTy = 694 llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty)); 695 llvm::Value *Addr = 696 CGF.Builder.CreateVAArg(VAListAddr.getPointer(), BaseTy); 697 return Address(Addr, TyAlignForABI); 698 } else { 699 assert((AI.isDirect() || AI.isExtend()) && 700 "Unexpected ArgInfo Kind in generic VAArg emitter!"); 701 702 assert(!AI.getInReg() && 703 "Unexpected InReg seen in arginfo in generic VAArg emitter!"); 704 assert(!AI.getPaddingType() && 705 "Unexpected PaddingType seen in arginfo in generic VAArg emitter!"); 706 assert(!AI.getDirectOffset() && 707 "Unexpected DirectOffset seen in arginfo in generic VAArg emitter!"); 708 assert(!AI.getCoerceToType() && 709 "Unexpected CoerceToType seen in arginfo in generic VAArg emitter!"); 710 711 Address Temp = CGF.CreateMemTemp(Ty, "varet"); 712 Val = CGF.Builder.CreateVAArg(VAListAddr.getPointer(), CGF.ConvertType(Ty)); 713 CGF.Builder.CreateStore(Val, Temp); 714 return Temp; 715 } 716 } 717 718 /// DefaultABIInfo - The default implementation for ABI specific 719 /// details. This implementation provides information which results in 720 /// self-consistent and sensible LLVM IR generation, but does not 721 /// conform to any particular ABI. 722 class DefaultABIInfo : public ABIInfo { 723 public: 724 DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {} 725 726 ABIArgInfo classifyReturnType(QualType RetTy) const; 727 ABIArgInfo classifyArgumentType(QualType RetTy) const; 728 729 void computeInfo(CGFunctionInfo &FI) const override { 730 if (!getCXXABI().classifyReturnType(FI)) 731 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 732 for (auto &I : FI.arguments()) 733 I.info = classifyArgumentType(I.type); 734 } 735 736 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 737 QualType Ty) const override { 738 return EmitVAArgInstr(CGF, VAListAddr, Ty, classifyArgumentType(Ty)); 739 } 740 }; 741 742 class DefaultTargetCodeGenInfo : public TargetCodeGenInfo { 743 public: 744 DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT) 745 : TargetCodeGenInfo(std::make_unique<DefaultABIInfo>(CGT)) {} 746 }; 747 748 ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const { 749 Ty = useFirstFieldIfTransparentUnion(Ty); 750 751 if (isAggregateTypeForABI(Ty)) { 752 // Records with non-trivial destructors/copy-constructors should not be 753 // passed by value. 754 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 755 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 756 757 return getNaturalAlignIndirect(Ty); 758 } 759 760 // Treat an enum type as its underlying type. 761 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 762 Ty = EnumTy->getDecl()->getIntegerType(); 763 764 ASTContext &Context = getContext(); 765 if (const auto *EIT = Ty->getAs<ExtIntType>()) 766 if (EIT->getNumBits() > 767 Context.getTypeSize(Context.getTargetInfo().hasInt128Type() 768 ? Context.Int128Ty 769 : Context.LongLongTy)) 770 return getNaturalAlignIndirect(Ty); 771 772 return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty) 773 : ABIArgInfo::getDirect()); 774 } 775 776 ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const { 777 if (RetTy->isVoidType()) 778 return ABIArgInfo::getIgnore(); 779 780 if (isAggregateTypeForABI(RetTy)) 781 return getNaturalAlignIndirect(RetTy); 782 783 // Treat an enum type as its underlying type. 784 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 785 RetTy = EnumTy->getDecl()->getIntegerType(); 786 787 if (const auto *EIT = RetTy->getAs<ExtIntType>()) 788 if (EIT->getNumBits() > 789 getContext().getTypeSize(getContext().getTargetInfo().hasInt128Type() 790 ? getContext().Int128Ty 791 : getContext().LongLongTy)) 792 return getNaturalAlignIndirect(RetTy); 793 794 return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy) 795 : ABIArgInfo::getDirect()); 796 } 797 798 //===----------------------------------------------------------------------===// 799 // WebAssembly ABI Implementation 800 // 801 // This is a very simple ABI that relies a lot on DefaultABIInfo. 802 //===----------------------------------------------------------------------===// 803 804 class WebAssemblyABIInfo final : public SwiftABIInfo { 805 public: 806 enum ABIKind { 807 MVP = 0, 808 ExperimentalMV = 1, 809 }; 810 811 private: 812 DefaultABIInfo defaultInfo; 813 ABIKind Kind; 814 815 public: 816 explicit WebAssemblyABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind) 817 : SwiftABIInfo(CGT), defaultInfo(CGT), Kind(Kind) {} 818 819 private: 820 ABIArgInfo classifyReturnType(QualType RetTy) const; 821 ABIArgInfo classifyArgumentType(QualType Ty) const; 822 823 // DefaultABIInfo's classifyReturnType and classifyArgumentType are 824 // non-virtual, but computeInfo and EmitVAArg are virtual, so we 825 // overload them. 826 void computeInfo(CGFunctionInfo &FI) const override { 827 if (!getCXXABI().classifyReturnType(FI)) 828 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 829 for (auto &Arg : FI.arguments()) 830 Arg.info = classifyArgumentType(Arg.type); 831 } 832 833 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 834 QualType Ty) const override; 835 836 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars, 837 bool asReturnValue) const override { 838 return occupiesMoreThan(CGT, scalars, /*total*/ 4); 839 } 840 841 bool isSwiftErrorInRegister() const override { 842 return false; 843 } 844 }; 845 846 class WebAssemblyTargetCodeGenInfo final : public TargetCodeGenInfo { 847 public: 848 explicit WebAssemblyTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, 849 WebAssemblyABIInfo::ABIKind K) 850 : TargetCodeGenInfo(std::make_unique<WebAssemblyABIInfo>(CGT, K)) {} 851 852 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 853 CodeGen::CodeGenModule &CGM) const override { 854 TargetCodeGenInfo::setTargetAttributes(D, GV, CGM); 855 if (const auto *FD = dyn_cast_or_null<FunctionDecl>(D)) { 856 if (const auto *Attr = FD->getAttr<WebAssemblyImportModuleAttr>()) { 857 llvm::Function *Fn = cast<llvm::Function>(GV); 858 llvm::AttrBuilder B; 859 B.addAttribute("wasm-import-module", Attr->getImportModule()); 860 Fn->addFnAttrs(B); 861 } 862 if (const auto *Attr = FD->getAttr<WebAssemblyImportNameAttr>()) { 863 llvm::Function *Fn = cast<llvm::Function>(GV); 864 llvm::AttrBuilder B; 865 B.addAttribute("wasm-import-name", Attr->getImportName()); 866 Fn->addFnAttrs(B); 867 } 868 if (const auto *Attr = FD->getAttr<WebAssemblyExportNameAttr>()) { 869 llvm::Function *Fn = cast<llvm::Function>(GV); 870 llvm::AttrBuilder B; 871 B.addAttribute("wasm-export-name", Attr->getExportName()); 872 Fn->addFnAttrs(B); 873 } 874 } 875 876 if (auto *FD = dyn_cast_or_null<FunctionDecl>(D)) { 877 llvm::Function *Fn = cast<llvm::Function>(GV); 878 if (!FD->doesThisDeclarationHaveABody() && !FD->hasPrototype()) 879 Fn->addFnAttr("no-prototype"); 880 } 881 } 882 }; 883 884 /// Classify argument of given type \p Ty. 885 ABIArgInfo WebAssemblyABIInfo::classifyArgumentType(QualType Ty) const { 886 Ty = useFirstFieldIfTransparentUnion(Ty); 887 888 if (isAggregateTypeForABI(Ty)) { 889 // Records with non-trivial destructors/copy-constructors should not be 890 // passed by value. 891 if (auto RAA = getRecordArgABI(Ty, getCXXABI())) 892 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 893 // Ignore empty structs/unions. 894 if (isEmptyRecord(getContext(), Ty, true)) 895 return ABIArgInfo::getIgnore(); 896 // Lower single-element structs to just pass a regular value. TODO: We 897 // could do reasonable-size multiple-element structs too, using getExpand(), 898 // though watch out for things like bitfields. 899 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext())) 900 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0))); 901 // For the experimental multivalue ABI, fully expand all other aggregates 902 if (Kind == ABIKind::ExperimentalMV) { 903 const RecordType *RT = Ty->getAs<RecordType>(); 904 assert(RT); 905 bool HasBitField = false; 906 for (auto *Field : RT->getDecl()->fields()) { 907 if (Field->isBitField()) { 908 HasBitField = true; 909 break; 910 } 911 } 912 if (!HasBitField) 913 return ABIArgInfo::getExpand(); 914 } 915 } 916 917 // Otherwise just do the default thing. 918 return defaultInfo.classifyArgumentType(Ty); 919 } 920 921 ABIArgInfo WebAssemblyABIInfo::classifyReturnType(QualType RetTy) const { 922 if (isAggregateTypeForABI(RetTy)) { 923 // Records with non-trivial destructors/copy-constructors should not be 924 // returned by value. 925 if (!getRecordArgABI(RetTy, getCXXABI())) { 926 // Ignore empty structs/unions. 927 if (isEmptyRecord(getContext(), RetTy, true)) 928 return ABIArgInfo::getIgnore(); 929 // Lower single-element structs to just return a regular value. TODO: We 930 // could do reasonable-size multiple-element structs too, using 931 // ABIArgInfo::getDirect(). 932 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext())) 933 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0))); 934 // For the experimental multivalue ABI, return all other aggregates 935 if (Kind == ABIKind::ExperimentalMV) 936 return ABIArgInfo::getDirect(); 937 } 938 } 939 940 // Otherwise just do the default thing. 941 return defaultInfo.classifyReturnType(RetTy); 942 } 943 944 Address WebAssemblyABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 945 QualType Ty) const { 946 bool IsIndirect = isAggregateTypeForABI(Ty) && 947 !isEmptyRecord(getContext(), Ty, true) && 948 !isSingleElementStruct(Ty, getContext()); 949 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, 950 getContext().getTypeInfoInChars(Ty), 951 CharUnits::fromQuantity(4), 952 /*AllowHigherAlign=*/true); 953 } 954 955 //===----------------------------------------------------------------------===// 956 // le32/PNaCl bitcode ABI Implementation 957 // 958 // This is a simplified version of the x86_32 ABI. Arguments and return values 959 // are always passed on the stack. 960 //===----------------------------------------------------------------------===// 961 962 class PNaClABIInfo : public ABIInfo { 963 public: 964 PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {} 965 966 ABIArgInfo classifyReturnType(QualType RetTy) const; 967 ABIArgInfo classifyArgumentType(QualType RetTy) const; 968 969 void computeInfo(CGFunctionInfo &FI) const override; 970 Address EmitVAArg(CodeGenFunction &CGF, 971 Address VAListAddr, QualType Ty) const override; 972 }; 973 974 class PNaClTargetCodeGenInfo : public TargetCodeGenInfo { 975 public: 976 PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT) 977 : TargetCodeGenInfo(std::make_unique<PNaClABIInfo>(CGT)) {} 978 }; 979 980 void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const { 981 if (!getCXXABI().classifyReturnType(FI)) 982 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 983 984 for (auto &I : FI.arguments()) 985 I.info = classifyArgumentType(I.type); 986 } 987 988 Address PNaClABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 989 QualType Ty) const { 990 // The PNaCL ABI is a bit odd, in that varargs don't use normal 991 // function classification. Structs get passed directly for varargs 992 // functions, through a rewriting transform in 993 // pnacl-llvm/lib/Transforms/NaCl/ExpandVarArgs.cpp, which allows 994 // this target to actually support a va_arg instructions with an 995 // aggregate type, unlike other targets. 996 return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect()); 997 } 998 999 /// Classify argument of given type \p Ty. 1000 ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const { 1001 if (isAggregateTypeForABI(Ty)) { 1002 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 1003 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 1004 return getNaturalAlignIndirect(Ty); 1005 } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) { 1006 // Treat an enum type as its underlying type. 1007 Ty = EnumTy->getDecl()->getIntegerType(); 1008 } else if (Ty->isFloatingType()) { 1009 // Floating-point types don't go inreg. 1010 return ABIArgInfo::getDirect(); 1011 } else if (const auto *EIT = Ty->getAs<ExtIntType>()) { 1012 // Treat extended integers as integers if <=64, otherwise pass indirectly. 1013 if (EIT->getNumBits() > 64) 1014 return getNaturalAlignIndirect(Ty); 1015 return ABIArgInfo::getDirect(); 1016 } 1017 1018 return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty) 1019 : ABIArgInfo::getDirect()); 1020 } 1021 1022 ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const { 1023 if (RetTy->isVoidType()) 1024 return ABIArgInfo::getIgnore(); 1025 1026 // In the PNaCl ABI we always return records/structures on the stack. 1027 if (isAggregateTypeForABI(RetTy)) 1028 return getNaturalAlignIndirect(RetTy); 1029 1030 // Treat extended integers as integers if <=64, otherwise pass indirectly. 1031 if (const auto *EIT = RetTy->getAs<ExtIntType>()) { 1032 if (EIT->getNumBits() > 64) 1033 return getNaturalAlignIndirect(RetTy); 1034 return ABIArgInfo::getDirect(); 1035 } 1036 1037 // Treat an enum type as its underlying type. 1038 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 1039 RetTy = EnumTy->getDecl()->getIntegerType(); 1040 1041 return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy) 1042 : ABIArgInfo::getDirect()); 1043 } 1044 1045 /// IsX86_MMXType - Return true if this is an MMX type. 1046 bool IsX86_MMXType(llvm::Type *IRType) { 1047 // Return true if the type is an MMX type <2 x i32>, <4 x i16>, or <8 x i8>. 1048 return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 && 1049 cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() && 1050 IRType->getScalarSizeInBits() != 64; 1051 } 1052 1053 static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF, 1054 StringRef Constraint, 1055 llvm::Type* Ty) { 1056 bool IsMMXCons = llvm::StringSwitch<bool>(Constraint) 1057 .Cases("y", "&y", "^Ym", true) 1058 .Default(false); 1059 if (IsMMXCons && Ty->isVectorTy()) { 1060 if (cast<llvm::VectorType>(Ty)->getPrimitiveSizeInBits().getFixedSize() != 1061 64) { 1062 // Invalid MMX constraint 1063 return nullptr; 1064 } 1065 1066 return llvm::Type::getX86_MMXTy(CGF.getLLVMContext()); 1067 } 1068 1069 // No operation needed 1070 return Ty; 1071 } 1072 1073 /// Returns true if this type can be passed in SSE registers with the 1074 /// X86_VectorCall calling convention. Shared between x86_32 and x86_64. 1075 static bool isX86VectorTypeForVectorCall(ASTContext &Context, QualType Ty) { 1076 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) { 1077 if (BT->isFloatingPoint() && BT->getKind() != BuiltinType::Half) { 1078 if (BT->getKind() == BuiltinType::LongDouble) { 1079 if (&Context.getTargetInfo().getLongDoubleFormat() == 1080 &llvm::APFloat::x87DoubleExtended()) 1081 return false; 1082 } 1083 return true; 1084 } 1085 } else if (const VectorType *VT = Ty->getAs<VectorType>()) { 1086 // vectorcall can pass XMM, YMM, and ZMM vectors. We don't pass SSE1 MMX 1087 // registers specially. 1088 unsigned VecSize = Context.getTypeSize(VT); 1089 if (VecSize == 128 || VecSize == 256 || VecSize == 512) 1090 return true; 1091 } 1092 return false; 1093 } 1094 1095 /// Returns true if this aggregate is small enough to be passed in SSE registers 1096 /// in the X86_VectorCall calling convention. Shared between x86_32 and x86_64. 1097 static bool isX86VectorCallAggregateSmallEnough(uint64_t NumMembers) { 1098 return NumMembers <= 4; 1099 } 1100 1101 /// Returns a Homogeneous Vector Aggregate ABIArgInfo, used in X86. 1102 static ABIArgInfo getDirectX86Hva(llvm::Type* T = nullptr) { 1103 auto AI = ABIArgInfo::getDirect(T); 1104 AI.setInReg(true); 1105 AI.setCanBeFlattened(false); 1106 return AI; 1107 } 1108 1109 //===----------------------------------------------------------------------===// 1110 // X86-32 ABI Implementation 1111 //===----------------------------------------------------------------------===// 1112 1113 /// Similar to llvm::CCState, but for Clang. 1114 struct CCState { 1115 CCState(CGFunctionInfo &FI) 1116 : IsPreassigned(FI.arg_size()), CC(FI.getCallingConvention()) {} 1117 1118 llvm::SmallBitVector IsPreassigned; 1119 unsigned CC = CallingConv::CC_C; 1120 unsigned FreeRegs = 0; 1121 unsigned FreeSSERegs = 0; 1122 }; 1123 1124 /// X86_32ABIInfo - The X86-32 ABI information. 1125 class X86_32ABIInfo : public SwiftABIInfo { 1126 enum Class { 1127 Integer, 1128 Float 1129 }; 1130 1131 static const unsigned MinABIStackAlignInBytes = 4; 1132 1133 bool IsDarwinVectorABI; 1134 bool IsRetSmallStructInRegABI; 1135 bool IsWin32StructABI; 1136 bool IsSoftFloatABI; 1137 bool IsMCUABI; 1138 bool IsLinuxABI; 1139 unsigned DefaultNumRegisterParameters; 1140 1141 static bool isRegisterSize(unsigned Size) { 1142 return (Size == 8 || Size == 16 || Size == 32 || Size == 64); 1143 } 1144 1145 bool isHomogeneousAggregateBaseType(QualType Ty) const override { 1146 // FIXME: Assumes vectorcall is in use. 1147 return isX86VectorTypeForVectorCall(getContext(), Ty); 1148 } 1149 1150 bool isHomogeneousAggregateSmallEnough(const Type *Ty, 1151 uint64_t NumMembers) const override { 1152 // FIXME: Assumes vectorcall is in use. 1153 return isX86VectorCallAggregateSmallEnough(NumMembers); 1154 } 1155 1156 bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context) const; 1157 1158 /// getIndirectResult - Give a source type \arg Ty, return a suitable result 1159 /// such that the argument will be passed in memory. 1160 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const; 1161 1162 ABIArgInfo getIndirectReturnResult(QualType Ty, CCState &State) const; 1163 1164 /// Return the alignment to use for the given type on the stack. 1165 unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const; 1166 1167 Class classify(QualType Ty) const; 1168 ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const; 1169 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const; 1170 1171 /// Updates the number of available free registers, returns 1172 /// true if any registers were allocated. 1173 bool updateFreeRegs(QualType Ty, CCState &State) const; 1174 1175 bool shouldAggregateUseDirect(QualType Ty, CCState &State, bool &InReg, 1176 bool &NeedsPadding) const; 1177 bool shouldPrimitiveUseInReg(QualType Ty, CCState &State) const; 1178 1179 bool canExpandIndirectArgument(QualType Ty) const; 1180 1181 /// Rewrite the function info so that all memory arguments use 1182 /// inalloca. 1183 void rewriteWithInAlloca(CGFunctionInfo &FI) const; 1184 1185 void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields, 1186 CharUnits &StackOffset, ABIArgInfo &Info, 1187 QualType Type) const; 1188 void runVectorCallFirstPass(CGFunctionInfo &FI, CCState &State) const; 1189 1190 public: 1191 1192 void computeInfo(CGFunctionInfo &FI) const override; 1193 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 1194 QualType Ty) const override; 1195 1196 X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI, 1197 bool RetSmallStructInRegABI, bool Win32StructABI, 1198 unsigned NumRegisterParameters, bool SoftFloatABI) 1199 : SwiftABIInfo(CGT), IsDarwinVectorABI(DarwinVectorABI), 1200 IsRetSmallStructInRegABI(RetSmallStructInRegABI), 1201 IsWin32StructABI(Win32StructABI), IsSoftFloatABI(SoftFloatABI), 1202 IsMCUABI(CGT.getTarget().getTriple().isOSIAMCU()), 1203 IsLinuxABI(CGT.getTarget().getTriple().isOSLinux() || 1204 CGT.getTarget().getTriple().isOSCygMing()), 1205 DefaultNumRegisterParameters(NumRegisterParameters) {} 1206 1207 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars, 1208 bool asReturnValue) const override { 1209 // LLVM's x86-32 lowering currently only assigns up to three 1210 // integer registers and three fp registers. Oddly, it'll use up to 1211 // four vector registers for vectors, but those can overlap with the 1212 // scalar registers. 1213 return occupiesMoreThan(CGT, scalars, /*total*/ 3); 1214 } 1215 1216 bool isSwiftErrorInRegister() const override { 1217 // x86-32 lowering does not support passing swifterror in a register. 1218 return false; 1219 } 1220 }; 1221 1222 class X86_32TargetCodeGenInfo : public TargetCodeGenInfo { 1223 public: 1224 X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI, 1225 bool RetSmallStructInRegABI, bool Win32StructABI, 1226 unsigned NumRegisterParameters, bool SoftFloatABI) 1227 : TargetCodeGenInfo(std::make_unique<X86_32ABIInfo>( 1228 CGT, DarwinVectorABI, RetSmallStructInRegABI, Win32StructABI, 1229 NumRegisterParameters, SoftFloatABI)) {} 1230 1231 static bool isStructReturnInRegABI( 1232 const llvm::Triple &Triple, const CodeGenOptions &Opts); 1233 1234 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 1235 CodeGen::CodeGenModule &CGM) const override; 1236 1237 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override { 1238 // Darwin uses different dwarf register numbers for EH. 1239 if (CGM.getTarget().getTriple().isOSDarwin()) return 5; 1240 return 4; 1241 } 1242 1243 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 1244 llvm::Value *Address) const override; 1245 1246 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF, 1247 StringRef Constraint, 1248 llvm::Type* Ty) const override { 1249 return X86AdjustInlineAsmType(CGF, Constraint, Ty); 1250 } 1251 1252 void addReturnRegisterOutputs(CodeGenFunction &CGF, LValue ReturnValue, 1253 std::string &Constraints, 1254 std::vector<llvm::Type *> &ResultRegTypes, 1255 std::vector<llvm::Type *> &ResultTruncRegTypes, 1256 std::vector<LValue> &ResultRegDests, 1257 std::string &AsmString, 1258 unsigned NumOutputs) const override; 1259 1260 llvm::Constant * 1261 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override { 1262 unsigned Sig = (0xeb << 0) | // jmp rel8 1263 (0x06 << 8) | // .+0x08 1264 ('v' << 16) | 1265 ('2' << 24); 1266 return llvm::ConstantInt::get(CGM.Int32Ty, Sig); 1267 } 1268 1269 StringRef getARCRetainAutoreleasedReturnValueMarker() const override { 1270 return "movl\t%ebp, %ebp" 1271 "\t\t// marker for objc_retainAutoreleaseReturnValue"; 1272 } 1273 }; 1274 1275 } 1276 1277 /// Rewrite input constraint references after adding some output constraints. 1278 /// In the case where there is one output and one input and we add one output, 1279 /// we need to replace all operand references greater than or equal to 1: 1280 /// mov $0, $1 1281 /// mov eax, $1 1282 /// The result will be: 1283 /// mov $0, $2 1284 /// mov eax, $2 1285 static void rewriteInputConstraintReferences(unsigned FirstIn, 1286 unsigned NumNewOuts, 1287 std::string &AsmString) { 1288 std::string Buf; 1289 llvm::raw_string_ostream OS(Buf); 1290 size_t Pos = 0; 1291 while (Pos < AsmString.size()) { 1292 size_t DollarStart = AsmString.find('$', Pos); 1293 if (DollarStart == std::string::npos) 1294 DollarStart = AsmString.size(); 1295 size_t DollarEnd = AsmString.find_first_not_of('$', DollarStart); 1296 if (DollarEnd == std::string::npos) 1297 DollarEnd = AsmString.size(); 1298 OS << StringRef(&AsmString[Pos], DollarEnd - Pos); 1299 Pos = DollarEnd; 1300 size_t NumDollars = DollarEnd - DollarStart; 1301 if (NumDollars % 2 != 0 && Pos < AsmString.size()) { 1302 // We have an operand reference. 1303 size_t DigitStart = Pos; 1304 if (AsmString[DigitStart] == '{') { 1305 OS << '{'; 1306 ++DigitStart; 1307 } 1308 size_t DigitEnd = AsmString.find_first_not_of("0123456789", DigitStart); 1309 if (DigitEnd == std::string::npos) 1310 DigitEnd = AsmString.size(); 1311 StringRef OperandStr(&AsmString[DigitStart], DigitEnd - DigitStart); 1312 unsigned OperandIndex; 1313 if (!OperandStr.getAsInteger(10, OperandIndex)) { 1314 if (OperandIndex >= FirstIn) 1315 OperandIndex += NumNewOuts; 1316 OS << OperandIndex; 1317 } else { 1318 OS << OperandStr; 1319 } 1320 Pos = DigitEnd; 1321 } 1322 } 1323 AsmString = std::move(OS.str()); 1324 } 1325 1326 /// Add output constraints for EAX:EDX because they are return registers. 1327 void X86_32TargetCodeGenInfo::addReturnRegisterOutputs( 1328 CodeGenFunction &CGF, LValue ReturnSlot, std::string &Constraints, 1329 std::vector<llvm::Type *> &ResultRegTypes, 1330 std::vector<llvm::Type *> &ResultTruncRegTypes, 1331 std::vector<LValue> &ResultRegDests, std::string &AsmString, 1332 unsigned NumOutputs) const { 1333 uint64_t RetWidth = CGF.getContext().getTypeSize(ReturnSlot.getType()); 1334 1335 // Use the EAX constraint if the width is 32 or smaller and EAX:EDX if it is 1336 // larger. 1337 if (!Constraints.empty()) 1338 Constraints += ','; 1339 if (RetWidth <= 32) { 1340 Constraints += "={eax}"; 1341 ResultRegTypes.push_back(CGF.Int32Ty); 1342 } else { 1343 // Use the 'A' constraint for EAX:EDX. 1344 Constraints += "=A"; 1345 ResultRegTypes.push_back(CGF.Int64Ty); 1346 } 1347 1348 // Truncate EAX or EAX:EDX to an integer of the appropriate size. 1349 llvm::Type *CoerceTy = llvm::IntegerType::get(CGF.getLLVMContext(), RetWidth); 1350 ResultTruncRegTypes.push_back(CoerceTy); 1351 1352 // Coerce the integer by bitcasting the return slot pointer. 1353 ReturnSlot.setAddress(CGF.Builder.CreateBitCast(ReturnSlot.getAddress(CGF), 1354 CoerceTy->getPointerTo())); 1355 ResultRegDests.push_back(ReturnSlot); 1356 1357 rewriteInputConstraintReferences(NumOutputs, 1, AsmString); 1358 } 1359 1360 /// shouldReturnTypeInRegister - Determine if the given type should be 1361 /// returned in a register (for the Darwin and MCU ABI). 1362 bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty, 1363 ASTContext &Context) const { 1364 uint64_t Size = Context.getTypeSize(Ty); 1365 1366 // For i386, type must be register sized. 1367 // For the MCU ABI, it only needs to be <= 8-byte 1368 if ((IsMCUABI && Size > 64) || (!IsMCUABI && !isRegisterSize(Size))) 1369 return false; 1370 1371 if (Ty->isVectorType()) { 1372 // 64- and 128- bit vectors inside structures are not returned in 1373 // registers. 1374 if (Size == 64 || Size == 128) 1375 return false; 1376 1377 return true; 1378 } 1379 1380 // If this is a builtin, pointer, enum, complex type, member pointer, or 1381 // member function pointer it is ok. 1382 if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() || 1383 Ty->isAnyComplexType() || Ty->isEnumeralType() || 1384 Ty->isBlockPointerType() || Ty->isMemberPointerType()) 1385 return true; 1386 1387 // Arrays are treated like records. 1388 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) 1389 return shouldReturnTypeInRegister(AT->getElementType(), Context); 1390 1391 // Otherwise, it must be a record type. 1392 const RecordType *RT = Ty->getAs<RecordType>(); 1393 if (!RT) return false; 1394 1395 // FIXME: Traverse bases here too. 1396 1397 // Structure types are passed in register if all fields would be 1398 // passed in a register. 1399 for (const auto *FD : RT->getDecl()->fields()) { 1400 // Empty fields are ignored. 1401 if (isEmptyField(Context, FD, true)) 1402 continue; 1403 1404 // Check fields recursively. 1405 if (!shouldReturnTypeInRegister(FD->getType(), Context)) 1406 return false; 1407 } 1408 return true; 1409 } 1410 1411 static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) { 1412 // Treat complex types as the element type. 1413 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) 1414 Ty = CTy->getElementType(); 1415 1416 // Check for a type which we know has a simple scalar argument-passing 1417 // convention without any padding. (We're specifically looking for 32 1418 // and 64-bit integer and integer-equivalents, float, and double.) 1419 if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() && 1420 !Ty->isEnumeralType() && !Ty->isBlockPointerType()) 1421 return false; 1422 1423 uint64_t Size = Context.getTypeSize(Ty); 1424 return Size == 32 || Size == 64; 1425 } 1426 1427 static bool addFieldSizes(ASTContext &Context, const RecordDecl *RD, 1428 uint64_t &Size) { 1429 for (const auto *FD : RD->fields()) { 1430 // Scalar arguments on the stack get 4 byte alignment on x86. If the 1431 // argument is smaller than 32-bits, expanding the struct will create 1432 // alignment padding. 1433 if (!is32Or64BitBasicType(FD->getType(), Context)) 1434 return false; 1435 1436 // FIXME: Reject bit-fields wholesale; there are two problems, we don't know 1437 // how to expand them yet, and the predicate for telling if a bitfield still 1438 // counts as "basic" is more complicated than what we were doing previously. 1439 if (FD->isBitField()) 1440 return false; 1441 1442 Size += Context.getTypeSize(FD->getType()); 1443 } 1444 return true; 1445 } 1446 1447 static bool addBaseAndFieldSizes(ASTContext &Context, const CXXRecordDecl *RD, 1448 uint64_t &Size) { 1449 // Don't do this if there are any non-empty bases. 1450 for (const CXXBaseSpecifier &Base : RD->bases()) { 1451 if (!addBaseAndFieldSizes(Context, Base.getType()->getAsCXXRecordDecl(), 1452 Size)) 1453 return false; 1454 } 1455 if (!addFieldSizes(Context, RD, Size)) 1456 return false; 1457 return true; 1458 } 1459 1460 /// Test whether an argument type which is to be passed indirectly (on the 1461 /// stack) would have the equivalent layout if it was expanded into separate 1462 /// arguments. If so, we prefer to do the latter to avoid inhibiting 1463 /// optimizations. 1464 bool X86_32ABIInfo::canExpandIndirectArgument(QualType Ty) const { 1465 // We can only expand structure types. 1466 const RecordType *RT = Ty->getAs<RecordType>(); 1467 if (!RT) 1468 return false; 1469 const RecordDecl *RD = RT->getDecl(); 1470 uint64_t Size = 0; 1471 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 1472 if (!IsWin32StructABI) { 1473 // On non-Windows, we have to conservatively match our old bitcode 1474 // prototypes in order to be ABI-compatible at the bitcode level. 1475 if (!CXXRD->isCLike()) 1476 return false; 1477 } else { 1478 // Don't do this for dynamic classes. 1479 if (CXXRD->isDynamicClass()) 1480 return false; 1481 } 1482 if (!addBaseAndFieldSizes(getContext(), CXXRD, Size)) 1483 return false; 1484 } else { 1485 if (!addFieldSizes(getContext(), RD, Size)) 1486 return false; 1487 } 1488 1489 // We can do this if there was no alignment padding. 1490 return Size == getContext().getTypeSize(Ty); 1491 } 1492 1493 ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(QualType RetTy, CCState &State) const { 1494 // If the return value is indirect, then the hidden argument is consuming one 1495 // integer register. 1496 if (State.FreeRegs) { 1497 --State.FreeRegs; 1498 if (!IsMCUABI) 1499 return getNaturalAlignIndirectInReg(RetTy); 1500 } 1501 return getNaturalAlignIndirect(RetTy, /*ByVal=*/false); 1502 } 1503 1504 ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy, 1505 CCState &State) const { 1506 if (RetTy->isVoidType()) 1507 return ABIArgInfo::getIgnore(); 1508 1509 const Type *Base = nullptr; 1510 uint64_t NumElts = 0; 1511 if ((State.CC == llvm::CallingConv::X86_VectorCall || 1512 State.CC == llvm::CallingConv::X86_RegCall) && 1513 isHomogeneousAggregate(RetTy, Base, NumElts)) { 1514 // The LLVM struct type for such an aggregate should lower properly. 1515 return ABIArgInfo::getDirect(); 1516 } 1517 1518 if (const VectorType *VT = RetTy->getAs<VectorType>()) { 1519 // On Darwin, some vectors are returned in registers. 1520 if (IsDarwinVectorABI) { 1521 uint64_t Size = getContext().getTypeSize(RetTy); 1522 1523 // 128-bit vectors are a special case; they are returned in 1524 // registers and we need to make sure to pick a type the LLVM 1525 // backend will like. 1526 if (Size == 128) 1527 return ABIArgInfo::getDirect(llvm::FixedVectorType::get( 1528 llvm::Type::getInt64Ty(getVMContext()), 2)); 1529 1530 // Always return in register if it fits in a general purpose 1531 // register, or if it is 64 bits and has a single element. 1532 if ((Size == 8 || Size == 16 || Size == 32) || 1533 (Size == 64 && VT->getNumElements() == 1)) 1534 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 1535 Size)); 1536 1537 return getIndirectReturnResult(RetTy, State); 1538 } 1539 1540 return ABIArgInfo::getDirect(); 1541 } 1542 1543 if (isAggregateTypeForABI(RetTy)) { 1544 if (const RecordType *RT = RetTy->getAs<RecordType>()) { 1545 // Structures with flexible arrays are always indirect. 1546 if (RT->getDecl()->hasFlexibleArrayMember()) 1547 return getIndirectReturnResult(RetTy, State); 1548 } 1549 1550 // If specified, structs and unions are always indirect. 1551 if (!IsRetSmallStructInRegABI && !RetTy->isAnyComplexType()) 1552 return getIndirectReturnResult(RetTy, State); 1553 1554 // Ignore empty structs/unions. 1555 if (isEmptyRecord(getContext(), RetTy, true)) 1556 return ABIArgInfo::getIgnore(); 1557 1558 // Return complex of _Float16 as <2 x half> so the backend will use xmm0. 1559 if (const ComplexType *CT = RetTy->getAs<ComplexType>()) { 1560 QualType ET = getContext().getCanonicalType(CT->getElementType()); 1561 if (ET->isFloat16Type()) 1562 return ABIArgInfo::getDirect(llvm::FixedVectorType::get( 1563 llvm::Type::getHalfTy(getVMContext()), 2)); 1564 } 1565 1566 // Small structures which are register sized are generally returned 1567 // in a register. 1568 if (shouldReturnTypeInRegister(RetTy, getContext())) { 1569 uint64_t Size = getContext().getTypeSize(RetTy); 1570 1571 // As a special-case, if the struct is a "single-element" struct, and 1572 // the field is of type "float" or "double", return it in a 1573 // floating-point register. (MSVC does not apply this special case.) 1574 // We apply a similar transformation for pointer types to improve the 1575 // quality of the generated IR. 1576 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext())) 1577 if ((!IsWin32StructABI && SeltTy->isRealFloatingType()) 1578 || SeltTy->hasPointerRepresentation()) 1579 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0))); 1580 1581 // FIXME: We should be able to narrow this integer in cases with dead 1582 // padding. 1583 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size)); 1584 } 1585 1586 return getIndirectReturnResult(RetTy, State); 1587 } 1588 1589 // Treat an enum type as its underlying type. 1590 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 1591 RetTy = EnumTy->getDecl()->getIntegerType(); 1592 1593 if (const auto *EIT = RetTy->getAs<ExtIntType>()) 1594 if (EIT->getNumBits() > 64) 1595 return getIndirectReturnResult(RetTy, State); 1596 1597 return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy) 1598 : ABIArgInfo::getDirect()); 1599 } 1600 1601 static bool isSIMDVectorType(ASTContext &Context, QualType Ty) { 1602 return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128; 1603 } 1604 1605 static bool isRecordWithSIMDVectorType(ASTContext &Context, QualType Ty) { 1606 const RecordType *RT = Ty->getAs<RecordType>(); 1607 if (!RT) 1608 return 0; 1609 const RecordDecl *RD = RT->getDecl(); 1610 1611 // If this is a C++ record, check the bases first. 1612 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 1613 for (const auto &I : CXXRD->bases()) 1614 if (!isRecordWithSIMDVectorType(Context, I.getType())) 1615 return false; 1616 1617 for (const auto *i : RD->fields()) { 1618 QualType FT = i->getType(); 1619 1620 if (isSIMDVectorType(Context, FT)) 1621 return true; 1622 1623 if (isRecordWithSIMDVectorType(Context, FT)) 1624 return true; 1625 } 1626 1627 return false; 1628 } 1629 1630 unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty, 1631 unsigned Align) const { 1632 // Otherwise, if the alignment is less than or equal to the minimum ABI 1633 // alignment, just use the default; the backend will handle this. 1634 if (Align <= MinABIStackAlignInBytes) 1635 return 0; // Use default alignment. 1636 1637 if (IsLinuxABI) { 1638 // Exclude other System V OS (e.g Darwin, PS4 and FreeBSD) since we don't 1639 // want to spend any effort dealing with the ramifications of ABI breaks. 1640 // 1641 // If the vector type is __m128/__m256/__m512, return the default alignment. 1642 if (Ty->isVectorType() && (Align == 16 || Align == 32 || Align == 64)) 1643 return Align; 1644 } 1645 // On non-Darwin, the stack type alignment is always 4. 1646 if (!IsDarwinVectorABI) { 1647 // Set explicit alignment, since we may need to realign the top. 1648 return MinABIStackAlignInBytes; 1649 } 1650 1651 // Otherwise, if the type contains an SSE vector type, the alignment is 16. 1652 if (Align >= 16 && (isSIMDVectorType(getContext(), Ty) || 1653 isRecordWithSIMDVectorType(getContext(), Ty))) 1654 return 16; 1655 1656 return MinABIStackAlignInBytes; 1657 } 1658 1659 ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal, 1660 CCState &State) const { 1661 if (!ByVal) { 1662 if (State.FreeRegs) { 1663 --State.FreeRegs; // Non-byval indirects just use one pointer. 1664 if (!IsMCUABI) 1665 return getNaturalAlignIndirectInReg(Ty); 1666 } 1667 return getNaturalAlignIndirect(Ty, false); 1668 } 1669 1670 // Compute the byval alignment. 1671 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8; 1672 unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign); 1673 if (StackAlign == 0) 1674 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true); 1675 1676 // If the stack alignment is less than the type alignment, realign the 1677 // argument. 1678 bool Realign = TypeAlign > StackAlign; 1679 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(StackAlign), 1680 /*ByVal=*/true, Realign); 1681 } 1682 1683 X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const { 1684 const Type *T = isSingleElementStruct(Ty, getContext()); 1685 if (!T) 1686 T = Ty.getTypePtr(); 1687 1688 if (const BuiltinType *BT = T->getAs<BuiltinType>()) { 1689 BuiltinType::Kind K = BT->getKind(); 1690 if (K == BuiltinType::Float || K == BuiltinType::Double) 1691 return Float; 1692 } 1693 return Integer; 1694 } 1695 1696 bool X86_32ABIInfo::updateFreeRegs(QualType Ty, CCState &State) const { 1697 if (!IsSoftFloatABI) { 1698 Class C = classify(Ty); 1699 if (C == Float) 1700 return false; 1701 } 1702 1703 unsigned Size = getContext().getTypeSize(Ty); 1704 unsigned SizeInRegs = (Size + 31) / 32; 1705 1706 if (SizeInRegs == 0) 1707 return false; 1708 1709 if (!IsMCUABI) { 1710 if (SizeInRegs > State.FreeRegs) { 1711 State.FreeRegs = 0; 1712 return false; 1713 } 1714 } else { 1715 // The MCU psABI allows passing parameters in-reg even if there are 1716 // earlier parameters that are passed on the stack. Also, 1717 // it does not allow passing >8-byte structs in-register, 1718 // even if there are 3 free registers available. 1719 if (SizeInRegs > State.FreeRegs || SizeInRegs > 2) 1720 return false; 1721 } 1722 1723 State.FreeRegs -= SizeInRegs; 1724 return true; 1725 } 1726 1727 bool X86_32ABIInfo::shouldAggregateUseDirect(QualType Ty, CCState &State, 1728 bool &InReg, 1729 bool &NeedsPadding) const { 1730 // On Windows, aggregates other than HFAs are never passed in registers, and 1731 // they do not consume register slots. Homogenous floating-point aggregates 1732 // (HFAs) have already been dealt with at this point. 1733 if (IsWin32StructABI && isAggregateTypeForABI(Ty)) 1734 return false; 1735 1736 NeedsPadding = false; 1737 InReg = !IsMCUABI; 1738 1739 if (!updateFreeRegs(Ty, State)) 1740 return false; 1741 1742 if (IsMCUABI) 1743 return true; 1744 1745 if (State.CC == llvm::CallingConv::X86_FastCall || 1746 State.CC == llvm::CallingConv::X86_VectorCall || 1747 State.CC == llvm::CallingConv::X86_RegCall) { 1748 if (getContext().getTypeSize(Ty) <= 32 && State.FreeRegs) 1749 NeedsPadding = true; 1750 1751 return false; 1752 } 1753 1754 return true; 1755 } 1756 1757 bool X86_32ABIInfo::shouldPrimitiveUseInReg(QualType Ty, CCState &State) const { 1758 if (!updateFreeRegs(Ty, State)) 1759 return false; 1760 1761 if (IsMCUABI) 1762 return false; 1763 1764 if (State.CC == llvm::CallingConv::X86_FastCall || 1765 State.CC == llvm::CallingConv::X86_VectorCall || 1766 State.CC == llvm::CallingConv::X86_RegCall) { 1767 if (getContext().getTypeSize(Ty) > 32) 1768 return false; 1769 1770 return (Ty->isIntegralOrEnumerationType() || Ty->isPointerType() || 1771 Ty->isReferenceType()); 1772 } 1773 1774 return true; 1775 } 1776 1777 void X86_32ABIInfo::runVectorCallFirstPass(CGFunctionInfo &FI, CCState &State) const { 1778 // Vectorcall x86 works subtly different than in x64, so the format is 1779 // a bit different than the x64 version. First, all vector types (not HVAs) 1780 // are assigned, with the first 6 ending up in the [XYZ]MM0-5 registers. 1781 // This differs from the x64 implementation, where the first 6 by INDEX get 1782 // registers. 1783 // In the second pass over the arguments, HVAs are passed in the remaining 1784 // vector registers if possible, or indirectly by address. The address will be 1785 // passed in ECX/EDX if available. Any other arguments are passed according to 1786 // the usual fastcall rules. 1787 MutableArrayRef<CGFunctionInfoArgInfo> Args = FI.arguments(); 1788 for (int I = 0, E = Args.size(); I < E; ++I) { 1789 const Type *Base = nullptr; 1790 uint64_t NumElts = 0; 1791 const QualType &Ty = Args[I].type; 1792 if ((Ty->isVectorType() || Ty->isBuiltinType()) && 1793 isHomogeneousAggregate(Ty, Base, NumElts)) { 1794 if (State.FreeSSERegs >= NumElts) { 1795 State.FreeSSERegs -= NumElts; 1796 Args[I].info = ABIArgInfo::getDirectInReg(); 1797 State.IsPreassigned.set(I); 1798 } 1799 } 1800 } 1801 } 1802 1803 ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty, 1804 CCState &State) const { 1805 // FIXME: Set alignment on indirect arguments. 1806 bool IsFastCall = State.CC == llvm::CallingConv::X86_FastCall; 1807 bool IsRegCall = State.CC == llvm::CallingConv::X86_RegCall; 1808 bool IsVectorCall = State.CC == llvm::CallingConv::X86_VectorCall; 1809 1810 Ty = useFirstFieldIfTransparentUnion(Ty); 1811 TypeInfo TI = getContext().getTypeInfo(Ty); 1812 1813 // Check with the C++ ABI first. 1814 const RecordType *RT = Ty->getAs<RecordType>(); 1815 if (RT) { 1816 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()); 1817 if (RAA == CGCXXABI::RAA_Indirect) { 1818 return getIndirectResult(Ty, false, State); 1819 } else if (RAA == CGCXXABI::RAA_DirectInMemory) { 1820 // The field index doesn't matter, we'll fix it up later. 1821 return ABIArgInfo::getInAlloca(/*FieldIndex=*/0); 1822 } 1823 } 1824 1825 // Regcall uses the concept of a homogenous vector aggregate, similar 1826 // to other targets. 1827 const Type *Base = nullptr; 1828 uint64_t NumElts = 0; 1829 if ((IsRegCall || IsVectorCall) && 1830 isHomogeneousAggregate(Ty, Base, NumElts)) { 1831 if (State.FreeSSERegs >= NumElts) { 1832 State.FreeSSERegs -= NumElts; 1833 1834 // Vectorcall passes HVAs directly and does not flatten them, but regcall 1835 // does. 1836 if (IsVectorCall) 1837 return getDirectX86Hva(); 1838 1839 if (Ty->isBuiltinType() || Ty->isVectorType()) 1840 return ABIArgInfo::getDirect(); 1841 return ABIArgInfo::getExpand(); 1842 } 1843 return getIndirectResult(Ty, /*ByVal=*/false, State); 1844 } 1845 1846 if (isAggregateTypeForABI(Ty)) { 1847 // Structures with flexible arrays are always indirect. 1848 // FIXME: This should not be byval! 1849 if (RT && RT->getDecl()->hasFlexibleArrayMember()) 1850 return getIndirectResult(Ty, true, State); 1851 1852 // Ignore empty structs/unions on non-Windows. 1853 if (!IsWin32StructABI && isEmptyRecord(getContext(), Ty, true)) 1854 return ABIArgInfo::getIgnore(); 1855 1856 llvm::LLVMContext &LLVMContext = getVMContext(); 1857 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext); 1858 bool NeedsPadding = false; 1859 bool InReg; 1860 if (shouldAggregateUseDirect(Ty, State, InReg, NeedsPadding)) { 1861 unsigned SizeInRegs = (TI.Width + 31) / 32; 1862 SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32); 1863 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements); 1864 if (InReg) 1865 return ABIArgInfo::getDirectInReg(Result); 1866 else 1867 return ABIArgInfo::getDirect(Result); 1868 } 1869 llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : nullptr; 1870 1871 // Pass over-aligned aggregates on Windows indirectly. This behavior was 1872 // added in MSVC 2015. 1873 if (IsWin32StructABI && TI.isAlignRequired() && TI.Align > 32) 1874 return getIndirectResult(Ty, /*ByVal=*/false, State); 1875 1876 // Expand small (<= 128-bit) record types when we know that the stack layout 1877 // of those arguments will match the struct. This is important because the 1878 // LLVM backend isn't smart enough to remove byval, which inhibits many 1879 // optimizations. 1880 // Don't do this for the MCU if there are still free integer registers 1881 // (see X86_64 ABI for full explanation). 1882 if (TI.Width <= 4 * 32 && (!IsMCUABI || State.FreeRegs == 0) && 1883 canExpandIndirectArgument(Ty)) 1884 return ABIArgInfo::getExpandWithPadding( 1885 IsFastCall || IsVectorCall || IsRegCall, PaddingType); 1886 1887 return getIndirectResult(Ty, true, State); 1888 } 1889 1890 if (const VectorType *VT = Ty->getAs<VectorType>()) { 1891 // On Windows, vectors are passed directly if registers are available, or 1892 // indirectly if not. This avoids the need to align argument memory. Pass 1893 // user-defined vector types larger than 512 bits indirectly for simplicity. 1894 if (IsWin32StructABI) { 1895 if (TI.Width <= 512 && State.FreeSSERegs > 0) { 1896 --State.FreeSSERegs; 1897 return ABIArgInfo::getDirectInReg(); 1898 } 1899 return getIndirectResult(Ty, /*ByVal=*/false, State); 1900 } 1901 1902 // On Darwin, some vectors are passed in memory, we handle this by passing 1903 // it as an i8/i16/i32/i64. 1904 if (IsDarwinVectorABI) { 1905 if ((TI.Width == 8 || TI.Width == 16 || TI.Width == 32) || 1906 (TI.Width == 64 && VT->getNumElements() == 1)) 1907 return ABIArgInfo::getDirect( 1908 llvm::IntegerType::get(getVMContext(), TI.Width)); 1909 } 1910 1911 if (IsX86_MMXType(CGT.ConvertType(Ty))) 1912 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64)); 1913 1914 return ABIArgInfo::getDirect(); 1915 } 1916 1917 1918 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 1919 Ty = EnumTy->getDecl()->getIntegerType(); 1920 1921 bool InReg = shouldPrimitiveUseInReg(Ty, State); 1922 1923 if (isPromotableIntegerTypeForABI(Ty)) { 1924 if (InReg) 1925 return ABIArgInfo::getExtendInReg(Ty); 1926 return ABIArgInfo::getExtend(Ty); 1927 } 1928 1929 if (const auto * EIT = Ty->getAs<ExtIntType>()) { 1930 if (EIT->getNumBits() <= 64) { 1931 if (InReg) 1932 return ABIArgInfo::getDirectInReg(); 1933 return ABIArgInfo::getDirect(); 1934 } 1935 return getIndirectResult(Ty, /*ByVal=*/false, State); 1936 } 1937 1938 if (InReg) 1939 return ABIArgInfo::getDirectInReg(); 1940 return ABIArgInfo::getDirect(); 1941 } 1942 1943 void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const { 1944 CCState State(FI); 1945 if (IsMCUABI) 1946 State.FreeRegs = 3; 1947 else if (State.CC == llvm::CallingConv::X86_FastCall) { 1948 State.FreeRegs = 2; 1949 State.FreeSSERegs = 3; 1950 } else if (State.CC == llvm::CallingConv::X86_VectorCall) { 1951 State.FreeRegs = 2; 1952 State.FreeSSERegs = 6; 1953 } else if (FI.getHasRegParm()) 1954 State.FreeRegs = FI.getRegParm(); 1955 else if (State.CC == llvm::CallingConv::X86_RegCall) { 1956 State.FreeRegs = 5; 1957 State.FreeSSERegs = 8; 1958 } else if (IsWin32StructABI) { 1959 // Since MSVC 2015, the first three SSE vectors have been passed in 1960 // registers. The rest are passed indirectly. 1961 State.FreeRegs = DefaultNumRegisterParameters; 1962 State.FreeSSERegs = 3; 1963 } else 1964 State.FreeRegs = DefaultNumRegisterParameters; 1965 1966 if (!::classifyReturnType(getCXXABI(), FI, *this)) { 1967 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), State); 1968 } else if (FI.getReturnInfo().isIndirect()) { 1969 // The C++ ABI is not aware of register usage, so we have to check if the 1970 // return value was sret and put it in a register ourselves if appropriate. 1971 if (State.FreeRegs) { 1972 --State.FreeRegs; // The sret parameter consumes a register. 1973 if (!IsMCUABI) 1974 FI.getReturnInfo().setInReg(true); 1975 } 1976 } 1977 1978 // The chain argument effectively gives us another free register. 1979 if (FI.isChainCall()) 1980 ++State.FreeRegs; 1981 1982 // For vectorcall, do a first pass over the arguments, assigning FP and vector 1983 // arguments to XMM registers as available. 1984 if (State.CC == llvm::CallingConv::X86_VectorCall) 1985 runVectorCallFirstPass(FI, State); 1986 1987 bool UsedInAlloca = false; 1988 MutableArrayRef<CGFunctionInfoArgInfo> Args = FI.arguments(); 1989 for (int I = 0, E = Args.size(); I < E; ++I) { 1990 // Skip arguments that have already been assigned. 1991 if (State.IsPreassigned.test(I)) 1992 continue; 1993 1994 Args[I].info = classifyArgumentType(Args[I].type, State); 1995 UsedInAlloca |= (Args[I].info.getKind() == ABIArgInfo::InAlloca); 1996 } 1997 1998 // If we needed to use inalloca for any argument, do a second pass and rewrite 1999 // all the memory arguments to use inalloca. 2000 if (UsedInAlloca) 2001 rewriteWithInAlloca(FI); 2002 } 2003 2004 void 2005 X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields, 2006 CharUnits &StackOffset, ABIArgInfo &Info, 2007 QualType Type) const { 2008 // Arguments are always 4-byte-aligned. 2009 CharUnits WordSize = CharUnits::fromQuantity(4); 2010 assert(StackOffset.isMultipleOf(WordSize) && "unaligned inalloca struct"); 2011 2012 // sret pointers and indirect things will require an extra pointer 2013 // indirection, unless they are byval. Most things are byval, and will not 2014 // require this indirection. 2015 bool IsIndirect = false; 2016 if (Info.isIndirect() && !Info.getIndirectByVal()) 2017 IsIndirect = true; 2018 Info = ABIArgInfo::getInAlloca(FrameFields.size(), IsIndirect); 2019 llvm::Type *LLTy = CGT.ConvertTypeForMem(Type); 2020 if (IsIndirect) 2021 LLTy = LLTy->getPointerTo(0); 2022 FrameFields.push_back(LLTy); 2023 StackOffset += IsIndirect ? WordSize : getContext().getTypeSizeInChars(Type); 2024 2025 // Insert padding bytes to respect alignment. 2026 CharUnits FieldEnd = StackOffset; 2027 StackOffset = FieldEnd.alignTo(WordSize); 2028 if (StackOffset != FieldEnd) { 2029 CharUnits NumBytes = StackOffset - FieldEnd; 2030 llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext()); 2031 Ty = llvm::ArrayType::get(Ty, NumBytes.getQuantity()); 2032 FrameFields.push_back(Ty); 2033 } 2034 } 2035 2036 static bool isArgInAlloca(const ABIArgInfo &Info) { 2037 // Leave ignored and inreg arguments alone. 2038 switch (Info.getKind()) { 2039 case ABIArgInfo::InAlloca: 2040 return true; 2041 case ABIArgInfo::Ignore: 2042 case ABIArgInfo::IndirectAliased: 2043 return false; 2044 case ABIArgInfo::Indirect: 2045 case ABIArgInfo::Direct: 2046 case ABIArgInfo::Extend: 2047 return !Info.getInReg(); 2048 case ABIArgInfo::Expand: 2049 case ABIArgInfo::CoerceAndExpand: 2050 // These are aggregate types which are never passed in registers when 2051 // inalloca is involved. 2052 return true; 2053 } 2054 llvm_unreachable("invalid enum"); 2055 } 2056 2057 void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const { 2058 assert(IsWin32StructABI && "inalloca only supported on win32"); 2059 2060 // Build a packed struct type for all of the arguments in memory. 2061 SmallVector<llvm::Type *, 6> FrameFields; 2062 2063 // The stack alignment is always 4. 2064 CharUnits StackAlign = CharUnits::fromQuantity(4); 2065 2066 CharUnits StackOffset; 2067 CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end(); 2068 2069 // Put 'this' into the struct before 'sret', if necessary. 2070 bool IsThisCall = 2071 FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall; 2072 ABIArgInfo &Ret = FI.getReturnInfo(); 2073 if (Ret.isIndirect() && Ret.isSRetAfterThis() && !IsThisCall && 2074 isArgInAlloca(I->info)) { 2075 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type); 2076 ++I; 2077 } 2078 2079 // Put the sret parameter into the inalloca struct if it's in memory. 2080 if (Ret.isIndirect() && !Ret.getInReg()) { 2081 addFieldToArgStruct(FrameFields, StackOffset, Ret, FI.getReturnType()); 2082 // On Windows, the hidden sret parameter is always returned in eax. 2083 Ret.setInAllocaSRet(IsWin32StructABI); 2084 } 2085 2086 // Skip the 'this' parameter in ecx. 2087 if (IsThisCall) 2088 ++I; 2089 2090 // Put arguments passed in memory into the struct. 2091 for (; I != E; ++I) { 2092 if (isArgInAlloca(I->info)) 2093 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type); 2094 } 2095 2096 FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields, 2097 /*isPacked=*/true), 2098 StackAlign); 2099 } 2100 2101 Address X86_32ABIInfo::EmitVAArg(CodeGenFunction &CGF, 2102 Address VAListAddr, QualType Ty) const { 2103 2104 auto TypeInfo = getContext().getTypeInfoInChars(Ty); 2105 2106 // x86-32 changes the alignment of certain arguments on the stack. 2107 // 2108 // Just messing with TypeInfo like this works because we never pass 2109 // anything indirectly. 2110 TypeInfo.Align = CharUnits::fromQuantity( 2111 getTypeStackAlignInBytes(Ty, TypeInfo.Align.getQuantity())); 2112 2113 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false, 2114 TypeInfo, CharUnits::fromQuantity(4), 2115 /*AllowHigherAlign*/ true); 2116 } 2117 2118 bool X86_32TargetCodeGenInfo::isStructReturnInRegABI( 2119 const llvm::Triple &Triple, const CodeGenOptions &Opts) { 2120 assert(Triple.getArch() == llvm::Triple::x86); 2121 2122 switch (Opts.getStructReturnConvention()) { 2123 case CodeGenOptions::SRCK_Default: 2124 break; 2125 case CodeGenOptions::SRCK_OnStack: // -fpcc-struct-return 2126 return false; 2127 case CodeGenOptions::SRCK_InRegs: // -freg-struct-return 2128 return true; 2129 } 2130 2131 if (Triple.isOSDarwin() || Triple.isOSIAMCU()) 2132 return true; 2133 2134 switch (Triple.getOS()) { 2135 case llvm::Triple::DragonFly: 2136 case llvm::Triple::FreeBSD: 2137 case llvm::Triple::OpenBSD: 2138 case llvm::Triple::Win32: 2139 return true; 2140 default: 2141 return false; 2142 } 2143 } 2144 2145 static void addX86InterruptAttrs(const FunctionDecl *FD, llvm::GlobalValue *GV, 2146 CodeGen::CodeGenModule &CGM) { 2147 if (!FD->hasAttr<AnyX86InterruptAttr>()) 2148 return; 2149 2150 llvm::Function *Fn = cast<llvm::Function>(GV); 2151 Fn->setCallingConv(llvm::CallingConv::X86_INTR); 2152 if (FD->getNumParams() == 0) 2153 return; 2154 2155 auto PtrTy = cast<PointerType>(FD->getParamDecl(0)->getType()); 2156 llvm::Type *ByValTy = CGM.getTypes().ConvertType(PtrTy->getPointeeType()); 2157 llvm::Attribute NewAttr = llvm::Attribute::getWithByValType( 2158 Fn->getContext(), ByValTy); 2159 Fn->addParamAttr(0, NewAttr); 2160 } 2161 2162 void X86_32TargetCodeGenInfo::setTargetAttributes( 2163 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const { 2164 if (GV->isDeclaration()) 2165 return; 2166 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) { 2167 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) { 2168 llvm::Function *Fn = cast<llvm::Function>(GV); 2169 Fn->addFnAttr("stackrealign"); 2170 } 2171 2172 addX86InterruptAttrs(FD, GV, CGM); 2173 } 2174 } 2175 2176 bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable( 2177 CodeGen::CodeGenFunction &CGF, 2178 llvm::Value *Address) const { 2179 CodeGen::CGBuilderTy &Builder = CGF.Builder; 2180 2181 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4); 2182 2183 // 0-7 are the eight integer registers; the order is different 2184 // on Darwin (for EH), but the range is the same. 2185 // 8 is %eip. 2186 AssignToArrayRange(Builder, Address, Four8, 0, 8); 2187 2188 if (CGF.CGM.getTarget().getTriple().isOSDarwin()) { 2189 // 12-16 are st(0..4). Not sure why we stop at 4. 2190 // These have size 16, which is sizeof(long double) on 2191 // platforms with 8-byte alignment for that type. 2192 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16); 2193 AssignToArrayRange(Builder, Address, Sixteen8, 12, 16); 2194 2195 } else { 2196 // 9 is %eflags, which doesn't get a size on Darwin for some 2197 // reason. 2198 Builder.CreateAlignedStore( 2199 Four8, Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, Address, 9), 2200 CharUnits::One()); 2201 2202 // 11-16 are st(0..5). Not sure why we stop at 5. 2203 // These have size 12, which is sizeof(long double) on 2204 // platforms with 4-byte alignment for that type. 2205 llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12); 2206 AssignToArrayRange(Builder, Address, Twelve8, 11, 16); 2207 } 2208 2209 return false; 2210 } 2211 2212 //===----------------------------------------------------------------------===// 2213 // X86-64 ABI Implementation 2214 //===----------------------------------------------------------------------===// 2215 2216 2217 namespace { 2218 /// The AVX ABI level for X86 targets. 2219 enum class X86AVXABILevel { 2220 None, 2221 AVX, 2222 AVX512 2223 }; 2224 2225 /// \p returns the size in bits of the largest (native) vector for \p AVXLevel. 2226 static unsigned getNativeVectorSizeForAVXABI(X86AVXABILevel AVXLevel) { 2227 switch (AVXLevel) { 2228 case X86AVXABILevel::AVX512: 2229 return 512; 2230 case X86AVXABILevel::AVX: 2231 return 256; 2232 case X86AVXABILevel::None: 2233 return 128; 2234 } 2235 llvm_unreachable("Unknown AVXLevel"); 2236 } 2237 2238 /// X86_64ABIInfo - The X86_64 ABI information. 2239 class X86_64ABIInfo : public SwiftABIInfo { 2240 enum Class { 2241 Integer = 0, 2242 SSE, 2243 SSEUp, 2244 X87, 2245 X87Up, 2246 ComplexX87, 2247 NoClass, 2248 Memory 2249 }; 2250 2251 /// merge - Implement the X86_64 ABI merging algorithm. 2252 /// 2253 /// Merge an accumulating classification \arg Accum with a field 2254 /// classification \arg Field. 2255 /// 2256 /// \param Accum - The accumulating classification. This should 2257 /// always be either NoClass or the result of a previous merge 2258 /// call. In addition, this should never be Memory (the caller 2259 /// should just return Memory for the aggregate). 2260 static Class merge(Class Accum, Class Field); 2261 2262 /// postMerge - Implement the X86_64 ABI post merging algorithm. 2263 /// 2264 /// Post merger cleanup, reduces a malformed Hi and Lo pair to 2265 /// final MEMORY or SSE classes when necessary. 2266 /// 2267 /// \param AggregateSize - The size of the current aggregate in 2268 /// the classification process. 2269 /// 2270 /// \param Lo - The classification for the parts of the type 2271 /// residing in the low word of the containing object. 2272 /// 2273 /// \param Hi - The classification for the parts of the type 2274 /// residing in the higher words of the containing object. 2275 /// 2276 void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const; 2277 2278 /// classify - Determine the x86_64 register classes in which the 2279 /// given type T should be passed. 2280 /// 2281 /// \param Lo - The classification for the parts of the type 2282 /// residing in the low word of the containing object. 2283 /// 2284 /// \param Hi - The classification for the parts of the type 2285 /// residing in the high word of the containing object. 2286 /// 2287 /// \param OffsetBase - The bit offset of this type in the 2288 /// containing object. Some parameters are classified different 2289 /// depending on whether they straddle an eightbyte boundary. 2290 /// 2291 /// \param isNamedArg - Whether the argument in question is a "named" 2292 /// argument, as used in AMD64-ABI 3.5.7. 2293 /// 2294 /// If a word is unused its result will be NoClass; if a type should 2295 /// be passed in Memory then at least the classification of \arg Lo 2296 /// will be Memory. 2297 /// 2298 /// The \arg Lo class will be NoClass iff the argument is ignored. 2299 /// 2300 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will 2301 /// also be ComplexX87. 2302 void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi, 2303 bool isNamedArg) const; 2304 2305 llvm::Type *GetByteVectorType(QualType Ty) const; 2306 llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType, 2307 unsigned IROffset, QualType SourceTy, 2308 unsigned SourceOffset) const; 2309 llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType, 2310 unsigned IROffset, QualType SourceTy, 2311 unsigned SourceOffset) const; 2312 2313 /// getIndirectResult - Give a source type \arg Ty, return a suitable result 2314 /// such that the argument will be returned in memory. 2315 ABIArgInfo getIndirectReturnResult(QualType Ty) const; 2316 2317 /// getIndirectResult - Give a source type \arg Ty, return a suitable result 2318 /// such that the argument will be passed in memory. 2319 /// 2320 /// \param freeIntRegs - The number of free integer registers remaining 2321 /// available. 2322 ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const; 2323 2324 ABIArgInfo classifyReturnType(QualType RetTy) const; 2325 2326 ABIArgInfo classifyArgumentType(QualType Ty, unsigned freeIntRegs, 2327 unsigned &neededInt, unsigned &neededSSE, 2328 bool isNamedArg) const; 2329 2330 ABIArgInfo classifyRegCallStructType(QualType Ty, unsigned &NeededInt, 2331 unsigned &NeededSSE) const; 2332 2333 ABIArgInfo classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt, 2334 unsigned &NeededSSE) const; 2335 2336 bool IsIllegalVectorType(QualType Ty) const; 2337 2338 /// The 0.98 ABI revision clarified a lot of ambiguities, 2339 /// unfortunately in ways that were not always consistent with 2340 /// certain previous compilers. In particular, platforms which 2341 /// required strict binary compatibility with older versions of GCC 2342 /// may need to exempt themselves. 2343 bool honorsRevision0_98() const { 2344 return !getTarget().getTriple().isOSDarwin(); 2345 } 2346 2347 /// GCC classifies <1 x long long> as SSE but some platform ABIs choose to 2348 /// classify it as INTEGER (for compatibility with older clang compilers). 2349 bool classifyIntegerMMXAsSSE() const { 2350 // Clang <= 3.8 did not do this. 2351 if (getContext().getLangOpts().getClangABICompat() <= 2352 LangOptions::ClangABI::Ver3_8) 2353 return false; 2354 2355 const llvm::Triple &Triple = getTarget().getTriple(); 2356 if (Triple.isOSDarwin() || Triple.getOS() == llvm::Triple::PS4) 2357 return false; 2358 if (Triple.isOSFreeBSD() && Triple.getOSMajorVersion() >= 10) 2359 return false; 2360 return true; 2361 } 2362 2363 // GCC classifies vectors of __int128 as memory. 2364 bool passInt128VectorsInMem() const { 2365 // Clang <= 9.0 did not do this. 2366 if (getContext().getLangOpts().getClangABICompat() <= 2367 LangOptions::ClangABI::Ver9) 2368 return false; 2369 2370 const llvm::Triple &T = getTarget().getTriple(); 2371 return T.isOSLinux() || T.isOSNetBSD(); 2372 } 2373 2374 X86AVXABILevel AVXLevel; 2375 // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on 2376 // 64-bit hardware. 2377 bool Has64BitPointers; 2378 2379 public: 2380 X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) : 2381 SwiftABIInfo(CGT), AVXLevel(AVXLevel), 2382 Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) { 2383 } 2384 2385 bool isPassedUsingAVXType(QualType type) const { 2386 unsigned neededInt, neededSSE; 2387 // The freeIntRegs argument doesn't matter here. 2388 ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE, 2389 /*isNamedArg*/true); 2390 if (info.isDirect()) { 2391 llvm::Type *ty = info.getCoerceToType(); 2392 if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty)) 2393 return vectorTy->getPrimitiveSizeInBits().getFixedSize() > 128; 2394 } 2395 return false; 2396 } 2397 2398 void computeInfo(CGFunctionInfo &FI) const override; 2399 2400 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 2401 QualType Ty) const override; 2402 Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr, 2403 QualType Ty) const override; 2404 2405 bool has64BitPointers() const { 2406 return Has64BitPointers; 2407 } 2408 2409 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars, 2410 bool asReturnValue) const override { 2411 return occupiesMoreThan(CGT, scalars, /*total*/ 4); 2412 } 2413 bool isSwiftErrorInRegister() const override { 2414 return true; 2415 } 2416 }; 2417 2418 /// WinX86_64ABIInfo - The Windows X86_64 ABI information. 2419 class WinX86_64ABIInfo : public SwiftABIInfo { 2420 public: 2421 WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) 2422 : SwiftABIInfo(CGT), AVXLevel(AVXLevel), 2423 IsMingw64(getTarget().getTriple().isWindowsGNUEnvironment()) {} 2424 2425 void computeInfo(CGFunctionInfo &FI) const override; 2426 2427 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 2428 QualType Ty) const override; 2429 2430 bool isHomogeneousAggregateBaseType(QualType Ty) const override { 2431 // FIXME: Assumes vectorcall is in use. 2432 return isX86VectorTypeForVectorCall(getContext(), Ty); 2433 } 2434 2435 bool isHomogeneousAggregateSmallEnough(const Type *Ty, 2436 uint64_t NumMembers) const override { 2437 // FIXME: Assumes vectorcall is in use. 2438 return isX86VectorCallAggregateSmallEnough(NumMembers); 2439 } 2440 2441 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type *> scalars, 2442 bool asReturnValue) const override { 2443 return occupiesMoreThan(CGT, scalars, /*total*/ 4); 2444 } 2445 2446 bool isSwiftErrorInRegister() const override { 2447 return true; 2448 } 2449 2450 private: 2451 ABIArgInfo classify(QualType Ty, unsigned &FreeSSERegs, bool IsReturnType, 2452 bool IsVectorCall, bool IsRegCall) const; 2453 ABIArgInfo reclassifyHvaArgForVectorCall(QualType Ty, unsigned &FreeSSERegs, 2454 const ABIArgInfo ¤t) const; 2455 2456 X86AVXABILevel AVXLevel; 2457 2458 bool IsMingw64; 2459 }; 2460 2461 class X86_64TargetCodeGenInfo : public TargetCodeGenInfo { 2462 public: 2463 X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) 2464 : TargetCodeGenInfo(std::make_unique<X86_64ABIInfo>(CGT, AVXLevel)) {} 2465 2466 const X86_64ABIInfo &getABIInfo() const { 2467 return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo()); 2468 } 2469 2470 /// Disable tail call on x86-64. The epilogue code before the tail jump blocks 2471 /// autoreleaseRV/retainRV and autoreleaseRV/unsafeClaimRV optimizations. 2472 bool markARCOptimizedReturnCallsAsNoTail() const override { return true; } 2473 2474 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override { 2475 return 7; 2476 } 2477 2478 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 2479 llvm::Value *Address) const override { 2480 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8); 2481 2482 // 0-15 are the 16 integer registers. 2483 // 16 is %rip. 2484 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16); 2485 return false; 2486 } 2487 2488 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF, 2489 StringRef Constraint, 2490 llvm::Type* Ty) const override { 2491 return X86AdjustInlineAsmType(CGF, Constraint, Ty); 2492 } 2493 2494 bool isNoProtoCallVariadic(const CallArgList &args, 2495 const FunctionNoProtoType *fnType) const override { 2496 // The default CC on x86-64 sets %al to the number of SSA 2497 // registers used, and GCC sets this when calling an unprototyped 2498 // function, so we override the default behavior. However, don't do 2499 // that when AVX types are involved: the ABI explicitly states it is 2500 // undefined, and it doesn't work in practice because of how the ABI 2501 // defines varargs anyway. 2502 if (fnType->getCallConv() == CC_C) { 2503 bool HasAVXType = false; 2504 for (CallArgList::const_iterator 2505 it = args.begin(), ie = args.end(); it != ie; ++it) { 2506 if (getABIInfo().isPassedUsingAVXType(it->Ty)) { 2507 HasAVXType = true; 2508 break; 2509 } 2510 } 2511 2512 if (!HasAVXType) 2513 return true; 2514 } 2515 2516 return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType); 2517 } 2518 2519 llvm::Constant * 2520 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override { 2521 unsigned Sig = (0xeb << 0) | // jmp rel8 2522 (0x06 << 8) | // .+0x08 2523 ('v' << 16) | 2524 ('2' << 24); 2525 return llvm::ConstantInt::get(CGM.Int32Ty, Sig); 2526 } 2527 2528 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 2529 CodeGen::CodeGenModule &CGM) const override { 2530 if (GV->isDeclaration()) 2531 return; 2532 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) { 2533 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) { 2534 llvm::Function *Fn = cast<llvm::Function>(GV); 2535 Fn->addFnAttr("stackrealign"); 2536 } 2537 2538 addX86InterruptAttrs(FD, GV, CGM); 2539 } 2540 } 2541 2542 void checkFunctionCallABI(CodeGenModule &CGM, SourceLocation CallLoc, 2543 const FunctionDecl *Caller, 2544 const FunctionDecl *Callee, 2545 const CallArgList &Args) const override; 2546 }; 2547 2548 static void initFeatureMaps(const ASTContext &Ctx, 2549 llvm::StringMap<bool> &CallerMap, 2550 const FunctionDecl *Caller, 2551 llvm::StringMap<bool> &CalleeMap, 2552 const FunctionDecl *Callee) { 2553 if (CalleeMap.empty() && CallerMap.empty()) { 2554 // The caller is potentially nullptr in the case where the call isn't in a 2555 // function. In this case, the getFunctionFeatureMap ensures we just get 2556 // the TU level setting (since it cannot be modified by 'target'.. 2557 Ctx.getFunctionFeatureMap(CallerMap, Caller); 2558 Ctx.getFunctionFeatureMap(CalleeMap, Callee); 2559 } 2560 } 2561 2562 static bool checkAVXParamFeature(DiagnosticsEngine &Diag, 2563 SourceLocation CallLoc, 2564 const llvm::StringMap<bool> &CallerMap, 2565 const llvm::StringMap<bool> &CalleeMap, 2566 QualType Ty, StringRef Feature, 2567 bool IsArgument) { 2568 bool CallerHasFeat = CallerMap.lookup(Feature); 2569 bool CalleeHasFeat = CalleeMap.lookup(Feature); 2570 if (!CallerHasFeat && !CalleeHasFeat) 2571 return Diag.Report(CallLoc, diag::warn_avx_calling_convention) 2572 << IsArgument << Ty << Feature; 2573 2574 // Mixing calling conventions here is very clearly an error. 2575 if (!CallerHasFeat || !CalleeHasFeat) 2576 return Diag.Report(CallLoc, diag::err_avx_calling_convention) 2577 << IsArgument << Ty << Feature; 2578 2579 // Else, both caller and callee have the required feature, so there is no need 2580 // to diagnose. 2581 return false; 2582 } 2583 2584 static bool checkAVXParam(DiagnosticsEngine &Diag, ASTContext &Ctx, 2585 SourceLocation CallLoc, 2586 const llvm::StringMap<bool> &CallerMap, 2587 const llvm::StringMap<bool> &CalleeMap, QualType Ty, 2588 bool IsArgument) { 2589 uint64_t Size = Ctx.getTypeSize(Ty); 2590 if (Size > 256) 2591 return checkAVXParamFeature(Diag, CallLoc, CallerMap, CalleeMap, Ty, 2592 "avx512f", IsArgument); 2593 2594 if (Size > 128) 2595 return checkAVXParamFeature(Diag, CallLoc, CallerMap, CalleeMap, Ty, "avx", 2596 IsArgument); 2597 2598 return false; 2599 } 2600 2601 void X86_64TargetCodeGenInfo::checkFunctionCallABI( 2602 CodeGenModule &CGM, SourceLocation CallLoc, const FunctionDecl *Caller, 2603 const FunctionDecl *Callee, const CallArgList &Args) const { 2604 llvm::StringMap<bool> CallerMap; 2605 llvm::StringMap<bool> CalleeMap; 2606 unsigned ArgIndex = 0; 2607 2608 // We need to loop through the actual call arguments rather than the the 2609 // function's parameters, in case this variadic. 2610 for (const CallArg &Arg : Args) { 2611 // The "avx" feature changes how vectors >128 in size are passed. "avx512f" 2612 // additionally changes how vectors >256 in size are passed. Like GCC, we 2613 // warn when a function is called with an argument where this will change. 2614 // Unlike GCC, we also error when it is an obvious ABI mismatch, that is, 2615 // the caller and callee features are mismatched. 2616 // Unfortunately, we cannot do this diagnostic in SEMA, since the callee can 2617 // change its ABI with attribute-target after this call. 2618 if (Arg.getType()->isVectorType() && 2619 CGM.getContext().getTypeSize(Arg.getType()) > 128) { 2620 initFeatureMaps(CGM.getContext(), CallerMap, Caller, CalleeMap, Callee); 2621 QualType Ty = Arg.getType(); 2622 // The CallArg seems to have desugared the type already, so for clearer 2623 // diagnostics, replace it with the type in the FunctionDecl if possible. 2624 if (ArgIndex < Callee->getNumParams()) 2625 Ty = Callee->getParamDecl(ArgIndex)->getType(); 2626 2627 if (checkAVXParam(CGM.getDiags(), CGM.getContext(), CallLoc, CallerMap, 2628 CalleeMap, Ty, /*IsArgument*/ true)) 2629 return; 2630 } 2631 ++ArgIndex; 2632 } 2633 2634 // Check return always, as we don't have a good way of knowing in codegen 2635 // whether this value is used, tail-called, etc. 2636 if (Callee->getReturnType()->isVectorType() && 2637 CGM.getContext().getTypeSize(Callee->getReturnType()) > 128) { 2638 initFeatureMaps(CGM.getContext(), CallerMap, Caller, CalleeMap, Callee); 2639 checkAVXParam(CGM.getDiags(), CGM.getContext(), CallLoc, CallerMap, 2640 CalleeMap, Callee->getReturnType(), 2641 /*IsArgument*/ false); 2642 } 2643 } 2644 2645 static std::string qualifyWindowsLibrary(llvm::StringRef Lib) { 2646 // If the argument does not end in .lib, automatically add the suffix. 2647 // If the argument contains a space, enclose it in quotes. 2648 // This matches the behavior of MSVC. 2649 bool Quote = (Lib.find(' ') != StringRef::npos); 2650 std::string ArgStr = Quote ? "\"" : ""; 2651 ArgStr += Lib; 2652 if (!Lib.endswith_insensitive(".lib") && !Lib.endswith_insensitive(".a")) 2653 ArgStr += ".lib"; 2654 ArgStr += Quote ? "\"" : ""; 2655 return ArgStr; 2656 } 2657 2658 class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo { 2659 public: 2660 WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, 2661 bool DarwinVectorABI, bool RetSmallStructInRegABI, bool Win32StructABI, 2662 unsigned NumRegisterParameters) 2663 : X86_32TargetCodeGenInfo(CGT, DarwinVectorABI, RetSmallStructInRegABI, 2664 Win32StructABI, NumRegisterParameters, false) {} 2665 2666 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 2667 CodeGen::CodeGenModule &CGM) const override; 2668 2669 void getDependentLibraryOption(llvm::StringRef Lib, 2670 llvm::SmallString<24> &Opt) const override { 2671 Opt = "/DEFAULTLIB:"; 2672 Opt += qualifyWindowsLibrary(Lib); 2673 } 2674 2675 void getDetectMismatchOption(llvm::StringRef Name, 2676 llvm::StringRef Value, 2677 llvm::SmallString<32> &Opt) const override { 2678 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\""; 2679 } 2680 }; 2681 2682 static void addStackProbeTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 2683 CodeGen::CodeGenModule &CGM) { 2684 if (llvm::Function *Fn = dyn_cast_or_null<llvm::Function>(GV)) { 2685 2686 if (CGM.getCodeGenOpts().StackProbeSize != 4096) 2687 Fn->addFnAttr("stack-probe-size", 2688 llvm::utostr(CGM.getCodeGenOpts().StackProbeSize)); 2689 if (CGM.getCodeGenOpts().NoStackArgProbe) 2690 Fn->addFnAttr("no-stack-arg-probe"); 2691 } 2692 } 2693 2694 void WinX86_32TargetCodeGenInfo::setTargetAttributes( 2695 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const { 2696 X86_32TargetCodeGenInfo::setTargetAttributes(D, GV, CGM); 2697 if (GV->isDeclaration()) 2698 return; 2699 addStackProbeTargetAttributes(D, GV, CGM); 2700 } 2701 2702 class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo { 2703 public: 2704 WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, 2705 X86AVXABILevel AVXLevel) 2706 : TargetCodeGenInfo(std::make_unique<WinX86_64ABIInfo>(CGT, AVXLevel)) {} 2707 2708 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 2709 CodeGen::CodeGenModule &CGM) const override; 2710 2711 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override { 2712 return 7; 2713 } 2714 2715 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 2716 llvm::Value *Address) const override { 2717 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8); 2718 2719 // 0-15 are the 16 integer registers. 2720 // 16 is %rip. 2721 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16); 2722 return false; 2723 } 2724 2725 void getDependentLibraryOption(llvm::StringRef Lib, 2726 llvm::SmallString<24> &Opt) const override { 2727 Opt = "/DEFAULTLIB:"; 2728 Opt += qualifyWindowsLibrary(Lib); 2729 } 2730 2731 void getDetectMismatchOption(llvm::StringRef Name, 2732 llvm::StringRef Value, 2733 llvm::SmallString<32> &Opt) const override { 2734 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\""; 2735 } 2736 }; 2737 2738 void WinX86_64TargetCodeGenInfo::setTargetAttributes( 2739 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const { 2740 TargetCodeGenInfo::setTargetAttributes(D, GV, CGM); 2741 if (GV->isDeclaration()) 2742 return; 2743 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) { 2744 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) { 2745 llvm::Function *Fn = cast<llvm::Function>(GV); 2746 Fn->addFnAttr("stackrealign"); 2747 } 2748 2749 addX86InterruptAttrs(FD, GV, CGM); 2750 } 2751 2752 addStackProbeTargetAttributes(D, GV, CGM); 2753 } 2754 } 2755 2756 void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo, 2757 Class &Hi) const { 2758 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done: 2759 // 2760 // (a) If one of the classes is Memory, the whole argument is passed in 2761 // memory. 2762 // 2763 // (b) If X87UP is not preceded by X87, the whole argument is passed in 2764 // memory. 2765 // 2766 // (c) If the size of the aggregate exceeds two eightbytes and the first 2767 // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole 2768 // argument is passed in memory. NOTE: This is necessary to keep the 2769 // ABI working for processors that don't support the __m256 type. 2770 // 2771 // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE. 2772 // 2773 // Some of these are enforced by the merging logic. Others can arise 2774 // only with unions; for example: 2775 // union { _Complex double; unsigned; } 2776 // 2777 // Note that clauses (b) and (c) were added in 0.98. 2778 // 2779 if (Hi == Memory) 2780 Lo = Memory; 2781 if (Hi == X87Up && Lo != X87 && honorsRevision0_98()) 2782 Lo = Memory; 2783 if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp)) 2784 Lo = Memory; 2785 if (Hi == SSEUp && Lo != SSE) 2786 Hi = SSE; 2787 } 2788 2789 X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) { 2790 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is 2791 // classified recursively so that always two fields are 2792 // considered. The resulting class is calculated according to 2793 // the classes of the fields in the eightbyte: 2794 // 2795 // (a) If both classes are equal, this is the resulting class. 2796 // 2797 // (b) If one of the classes is NO_CLASS, the resulting class is 2798 // the other class. 2799 // 2800 // (c) If one of the classes is MEMORY, the result is the MEMORY 2801 // class. 2802 // 2803 // (d) If one of the classes is INTEGER, the result is the 2804 // INTEGER. 2805 // 2806 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class, 2807 // MEMORY is used as class. 2808 // 2809 // (f) Otherwise class SSE is used. 2810 2811 // Accum should never be memory (we should have returned) or 2812 // ComplexX87 (because this cannot be passed in a structure). 2813 assert((Accum != Memory && Accum != ComplexX87) && 2814 "Invalid accumulated classification during merge."); 2815 if (Accum == Field || Field == NoClass) 2816 return Accum; 2817 if (Field == Memory) 2818 return Memory; 2819 if (Accum == NoClass) 2820 return Field; 2821 if (Accum == Integer || Field == Integer) 2822 return Integer; 2823 if (Field == X87 || Field == X87Up || Field == ComplexX87 || 2824 Accum == X87 || Accum == X87Up) 2825 return Memory; 2826 return SSE; 2827 } 2828 2829 void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase, 2830 Class &Lo, Class &Hi, bool isNamedArg) const { 2831 // FIXME: This code can be simplified by introducing a simple value class for 2832 // Class pairs with appropriate constructor methods for the various 2833 // situations. 2834 2835 // FIXME: Some of the split computations are wrong; unaligned vectors 2836 // shouldn't be passed in registers for example, so there is no chance they 2837 // can straddle an eightbyte. Verify & simplify. 2838 2839 Lo = Hi = NoClass; 2840 2841 Class &Current = OffsetBase < 64 ? Lo : Hi; 2842 Current = Memory; 2843 2844 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) { 2845 BuiltinType::Kind k = BT->getKind(); 2846 2847 if (k == BuiltinType::Void) { 2848 Current = NoClass; 2849 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) { 2850 Lo = Integer; 2851 Hi = Integer; 2852 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) { 2853 Current = Integer; 2854 } else if (k == BuiltinType::Float || k == BuiltinType::Double || 2855 k == BuiltinType::Float16) { 2856 Current = SSE; 2857 } else if (k == BuiltinType::LongDouble) { 2858 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat(); 2859 if (LDF == &llvm::APFloat::IEEEquad()) { 2860 Lo = SSE; 2861 Hi = SSEUp; 2862 } else if (LDF == &llvm::APFloat::x87DoubleExtended()) { 2863 Lo = X87; 2864 Hi = X87Up; 2865 } else if (LDF == &llvm::APFloat::IEEEdouble()) { 2866 Current = SSE; 2867 } else 2868 llvm_unreachable("unexpected long double representation!"); 2869 } 2870 // FIXME: _Decimal32 and _Decimal64 are SSE. 2871 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp). 2872 return; 2873 } 2874 2875 if (const EnumType *ET = Ty->getAs<EnumType>()) { 2876 // Classify the underlying integer type. 2877 classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg); 2878 return; 2879 } 2880 2881 if (Ty->hasPointerRepresentation()) { 2882 Current = Integer; 2883 return; 2884 } 2885 2886 if (Ty->isMemberPointerType()) { 2887 if (Ty->isMemberFunctionPointerType()) { 2888 if (Has64BitPointers) { 2889 // If Has64BitPointers, this is an {i64, i64}, so classify both 2890 // Lo and Hi now. 2891 Lo = Hi = Integer; 2892 } else { 2893 // Otherwise, with 32-bit pointers, this is an {i32, i32}. If that 2894 // straddles an eightbyte boundary, Hi should be classified as well. 2895 uint64_t EB_FuncPtr = (OffsetBase) / 64; 2896 uint64_t EB_ThisAdj = (OffsetBase + 64 - 1) / 64; 2897 if (EB_FuncPtr != EB_ThisAdj) { 2898 Lo = Hi = Integer; 2899 } else { 2900 Current = Integer; 2901 } 2902 } 2903 } else { 2904 Current = Integer; 2905 } 2906 return; 2907 } 2908 2909 if (const VectorType *VT = Ty->getAs<VectorType>()) { 2910 uint64_t Size = getContext().getTypeSize(VT); 2911 if (Size == 1 || Size == 8 || Size == 16 || Size == 32) { 2912 // gcc passes the following as integer: 2913 // 4 bytes - <4 x char>, <2 x short>, <1 x int>, <1 x float> 2914 // 2 bytes - <2 x char>, <1 x short> 2915 // 1 byte - <1 x char> 2916 Current = Integer; 2917 2918 // If this type crosses an eightbyte boundary, it should be 2919 // split. 2920 uint64_t EB_Lo = (OffsetBase) / 64; 2921 uint64_t EB_Hi = (OffsetBase + Size - 1) / 64; 2922 if (EB_Lo != EB_Hi) 2923 Hi = Lo; 2924 } else if (Size == 64) { 2925 QualType ElementType = VT->getElementType(); 2926 2927 // gcc passes <1 x double> in memory. :( 2928 if (ElementType->isSpecificBuiltinType(BuiltinType::Double)) 2929 return; 2930 2931 // gcc passes <1 x long long> as SSE but clang used to unconditionally 2932 // pass them as integer. For platforms where clang is the de facto 2933 // platform compiler, we must continue to use integer. 2934 if (!classifyIntegerMMXAsSSE() && 2935 (ElementType->isSpecificBuiltinType(BuiltinType::LongLong) || 2936 ElementType->isSpecificBuiltinType(BuiltinType::ULongLong) || 2937 ElementType->isSpecificBuiltinType(BuiltinType::Long) || 2938 ElementType->isSpecificBuiltinType(BuiltinType::ULong))) 2939 Current = Integer; 2940 else 2941 Current = SSE; 2942 2943 // If this type crosses an eightbyte boundary, it should be 2944 // split. 2945 if (OffsetBase && OffsetBase != 64) 2946 Hi = Lo; 2947 } else if (Size == 128 || 2948 (isNamedArg && Size <= getNativeVectorSizeForAVXABI(AVXLevel))) { 2949 QualType ElementType = VT->getElementType(); 2950 2951 // gcc passes 256 and 512 bit <X x __int128> vectors in memory. :( 2952 if (passInt128VectorsInMem() && Size != 128 && 2953 (ElementType->isSpecificBuiltinType(BuiltinType::Int128) || 2954 ElementType->isSpecificBuiltinType(BuiltinType::UInt128))) 2955 return; 2956 2957 // Arguments of 256-bits are split into four eightbyte chunks. The 2958 // least significant one belongs to class SSE and all the others to class 2959 // SSEUP. The original Lo and Hi design considers that types can't be 2960 // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense. 2961 // This design isn't correct for 256-bits, but since there're no cases 2962 // where the upper parts would need to be inspected, avoid adding 2963 // complexity and just consider Hi to match the 64-256 part. 2964 // 2965 // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in 2966 // registers if they are "named", i.e. not part of the "..." of a 2967 // variadic function. 2968 // 2969 // Similarly, per 3.2.3. of the AVX512 draft, 512-bits ("named") args are 2970 // split into eight eightbyte chunks, one SSE and seven SSEUP. 2971 Lo = SSE; 2972 Hi = SSEUp; 2973 } 2974 return; 2975 } 2976 2977 if (const ComplexType *CT = Ty->getAs<ComplexType>()) { 2978 QualType ET = getContext().getCanonicalType(CT->getElementType()); 2979 2980 uint64_t Size = getContext().getTypeSize(Ty); 2981 if (ET->isIntegralOrEnumerationType()) { 2982 if (Size <= 64) 2983 Current = Integer; 2984 else if (Size <= 128) 2985 Lo = Hi = Integer; 2986 } else if (ET->isFloat16Type() || ET == getContext().FloatTy) { 2987 Current = SSE; 2988 } else if (ET == getContext().DoubleTy) { 2989 Lo = Hi = SSE; 2990 } else if (ET == getContext().LongDoubleTy) { 2991 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat(); 2992 if (LDF == &llvm::APFloat::IEEEquad()) 2993 Current = Memory; 2994 else if (LDF == &llvm::APFloat::x87DoubleExtended()) 2995 Current = ComplexX87; 2996 else if (LDF == &llvm::APFloat::IEEEdouble()) 2997 Lo = Hi = SSE; 2998 else 2999 llvm_unreachable("unexpected long double representation!"); 3000 } 3001 3002 // If this complex type crosses an eightbyte boundary then it 3003 // should be split. 3004 uint64_t EB_Real = (OffsetBase) / 64; 3005 uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64; 3006 if (Hi == NoClass && EB_Real != EB_Imag) 3007 Hi = Lo; 3008 3009 return; 3010 } 3011 3012 if (const auto *EITy = Ty->getAs<ExtIntType>()) { 3013 if (EITy->getNumBits() <= 64) 3014 Current = Integer; 3015 else if (EITy->getNumBits() <= 128) 3016 Lo = Hi = Integer; 3017 // Larger values need to get passed in memory. 3018 return; 3019 } 3020 3021 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) { 3022 // Arrays are treated like structures. 3023 3024 uint64_t Size = getContext().getTypeSize(Ty); 3025 3026 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger 3027 // than eight eightbytes, ..., it has class MEMORY. 3028 if (Size > 512) 3029 return; 3030 3031 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned 3032 // fields, it has class MEMORY. 3033 // 3034 // Only need to check alignment of array base. 3035 if (OffsetBase % getContext().getTypeAlign(AT->getElementType())) 3036 return; 3037 3038 // Otherwise implement simplified merge. We could be smarter about 3039 // this, but it isn't worth it and would be harder to verify. 3040 Current = NoClass; 3041 uint64_t EltSize = getContext().getTypeSize(AT->getElementType()); 3042 uint64_t ArraySize = AT->getSize().getZExtValue(); 3043 3044 // The only case a 256-bit wide vector could be used is when the array 3045 // contains a single 256-bit element. Since Lo and Hi logic isn't extended 3046 // to work for sizes wider than 128, early check and fallback to memory. 3047 // 3048 if (Size > 128 && 3049 (Size != EltSize || Size > getNativeVectorSizeForAVXABI(AVXLevel))) 3050 return; 3051 3052 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) { 3053 Class FieldLo, FieldHi; 3054 classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg); 3055 Lo = merge(Lo, FieldLo); 3056 Hi = merge(Hi, FieldHi); 3057 if (Lo == Memory || Hi == Memory) 3058 break; 3059 } 3060 3061 postMerge(Size, Lo, Hi); 3062 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification."); 3063 return; 3064 } 3065 3066 if (const RecordType *RT = Ty->getAs<RecordType>()) { 3067 uint64_t Size = getContext().getTypeSize(Ty); 3068 3069 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger 3070 // than eight eightbytes, ..., it has class MEMORY. 3071 if (Size > 512) 3072 return; 3073 3074 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial 3075 // copy constructor or a non-trivial destructor, it is passed by invisible 3076 // reference. 3077 if (getRecordArgABI(RT, getCXXABI())) 3078 return; 3079 3080 const RecordDecl *RD = RT->getDecl(); 3081 3082 // Assume variable sized types are passed in memory. 3083 if (RD->hasFlexibleArrayMember()) 3084 return; 3085 3086 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD); 3087 3088 // Reset Lo class, this will be recomputed. 3089 Current = NoClass; 3090 3091 // If this is a C++ record, classify the bases first. 3092 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 3093 for (const auto &I : CXXRD->bases()) { 3094 assert(!I.isVirtual() && !I.getType()->isDependentType() && 3095 "Unexpected base class!"); 3096 const auto *Base = 3097 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl()); 3098 3099 // Classify this field. 3100 // 3101 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a 3102 // single eightbyte, each is classified separately. Each eightbyte gets 3103 // initialized to class NO_CLASS. 3104 Class FieldLo, FieldHi; 3105 uint64_t Offset = 3106 OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base)); 3107 classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg); 3108 Lo = merge(Lo, FieldLo); 3109 Hi = merge(Hi, FieldHi); 3110 if (Lo == Memory || Hi == Memory) { 3111 postMerge(Size, Lo, Hi); 3112 return; 3113 } 3114 } 3115 } 3116 3117 // Classify the fields one at a time, merging the results. 3118 unsigned idx = 0; 3119 bool UseClang11Compat = getContext().getLangOpts().getClangABICompat() <= 3120 LangOptions::ClangABI::Ver11 || 3121 getContext().getTargetInfo().getTriple().isPS4(); 3122 bool IsUnion = RT->isUnionType() && !UseClang11Compat; 3123 3124 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 3125 i != e; ++i, ++idx) { 3126 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx); 3127 bool BitField = i->isBitField(); 3128 3129 // Ignore padding bit-fields. 3130 if (BitField && i->isUnnamedBitfield()) 3131 continue; 3132 3133 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than 3134 // eight eightbytes, or it contains unaligned fields, it has class MEMORY. 3135 // 3136 // The only case a 256-bit or a 512-bit wide vector could be used is when 3137 // the struct contains a single 256-bit or 512-bit element. Early check 3138 // and fallback to memory. 3139 // 3140 // FIXME: Extended the Lo and Hi logic properly to work for size wider 3141 // than 128. 3142 if (Size > 128 && 3143 ((!IsUnion && Size != getContext().getTypeSize(i->getType())) || 3144 Size > getNativeVectorSizeForAVXABI(AVXLevel))) { 3145 Lo = Memory; 3146 postMerge(Size, Lo, Hi); 3147 return; 3148 } 3149 // Note, skip this test for bit-fields, see below. 3150 if (!BitField && Offset % getContext().getTypeAlign(i->getType())) { 3151 Lo = Memory; 3152 postMerge(Size, Lo, Hi); 3153 return; 3154 } 3155 3156 // Classify this field. 3157 // 3158 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate 3159 // exceeds a single eightbyte, each is classified 3160 // separately. Each eightbyte gets initialized to class 3161 // NO_CLASS. 3162 Class FieldLo, FieldHi; 3163 3164 // Bit-fields require special handling, they do not force the 3165 // structure to be passed in memory even if unaligned, and 3166 // therefore they can straddle an eightbyte. 3167 if (BitField) { 3168 assert(!i->isUnnamedBitfield()); 3169 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx); 3170 uint64_t Size = i->getBitWidthValue(getContext()); 3171 3172 uint64_t EB_Lo = Offset / 64; 3173 uint64_t EB_Hi = (Offset + Size - 1) / 64; 3174 3175 if (EB_Lo) { 3176 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes."); 3177 FieldLo = NoClass; 3178 FieldHi = Integer; 3179 } else { 3180 FieldLo = Integer; 3181 FieldHi = EB_Hi ? Integer : NoClass; 3182 } 3183 } else 3184 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg); 3185 Lo = merge(Lo, FieldLo); 3186 Hi = merge(Hi, FieldHi); 3187 if (Lo == Memory || Hi == Memory) 3188 break; 3189 } 3190 3191 postMerge(Size, Lo, Hi); 3192 } 3193 } 3194 3195 ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const { 3196 // If this is a scalar LLVM value then assume LLVM will pass it in the right 3197 // place naturally. 3198 if (!isAggregateTypeForABI(Ty)) { 3199 // Treat an enum type as its underlying type. 3200 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 3201 Ty = EnumTy->getDecl()->getIntegerType(); 3202 3203 if (Ty->isExtIntType()) 3204 return getNaturalAlignIndirect(Ty); 3205 3206 return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty) 3207 : ABIArgInfo::getDirect()); 3208 } 3209 3210 return getNaturalAlignIndirect(Ty); 3211 } 3212 3213 bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const { 3214 if (const VectorType *VecTy = Ty->getAs<VectorType>()) { 3215 uint64_t Size = getContext().getTypeSize(VecTy); 3216 unsigned LargestVector = getNativeVectorSizeForAVXABI(AVXLevel); 3217 if (Size <= 64 || Size > LargestVector) 3218 return true; 3219 QualType EltTy = VecTy->getElementType(); 3220 if (passInt128VectorsInMem() && 3221 (EltTy->isSpecificBuiltinType(BuiltinType::Int128) || 3222 EltTy->isSpecificBuiltinType(BuiltinType::UInt128))) 3223 return true; 3224 } 3225 3226 return false; 3227 } 3228 3229 ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty, 3230 unsigned freeIntRegs) const { 3231 // If this is a scalar LLVM value then assume LLVM will pass it in the right 3232 // place naturally. 3233 // 3234 // This assumption is optimistic, as there could be free registers available 3235 // when we need to pass this argument in memory, and LLVM could try to pass 3236 // the argument in the free register. This does not seem to happen currently, 3237 // but this code would be much safer if we could mark the argument with 3238 // 'onstack'. See PR12193. 3239 if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty) && 3240 !Ty->isExtIntType()) { 3241 // Treat an enum type as its underlying type. 3242 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 3243 Ty = EnumTy->getDecl()->getIntegerType(); 3244 3245 return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty) 3246 : ABIArgInfo::getDirect()); 3247 } 3248 3249 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 3250 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 3251 3252 // Compute the byval alignment. We specify the alignment of the byval in all 3253 // cases so that the mid-level optimizer knows the alignment of the byval. 3254 unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U); 3255 3256 // Attempt to avoid passing indirect results using byval when possible. This 3257 // is important for good codegen. 3258 // 3259 // We do this by coercing the value into a scalar type which the backend can 3260 // handle naturally (i.e., without using byval). 3261 // 3262 // For simplicity, we currently only do this when we have exhausted all of the 3263 // free integer registers. Doing this when there are free integer registers 3264 // would require more care, as we would have to ensure that the coerced value 3265 // did not claim the unused register. That would require either reording the 3266 // arguments to the function (so that any subsequent inreg values came first), 3267 // or only doing this optimization when there were no following arguments that 3268 // might be inreg. 3269 // 3270 // We currently expect it to be rare (particularly in well written code) for 3271 // arguments to be passed on the stack when there are still free integer 3272 // registers available (this would typically imply large structs being passed 3273 // by value), so this seems like a fair tradeoff for now. 3274 // 3275 // We can revisit this if the backend grows support for 'onstack' parameter 3276 // attributes. See PR12193. 3277 if (freeIntRegs == 0) { 3278 uint64_t Size = getContext().getTypeSize(Ty); 3279 3280 // If this type fits in an eightbyte, coerce it into the matching integral 3281 // type, which will end up on the stack (with alignment 8). 3282 if (Align == 8 && Size <= 64) 3283 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 3284 Size)); 3285 } 3286 3287 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(Align)); 3288 } 3289 3290 /// The ABI specifies that a value should be passed in a full vector XMM/YMM 3291 /// register. Pick an LLVM IR type that will be passed as a vector register. 3292 llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const { 3293 // Wrapper structs/arrays that only contain vectors are passed just like 3294 // vectors; strip them off if present. 3295 if (const Type *InnerTy = isSingleElementStruct(Ty, getContext())) 3296 Ty = QualType(InnerTy, 0); 3297 3298 llvm::Type *IRType = CGT.ConvertType(Ty); 3299 if (isa<llvm::VectorType>(IRType)) { 3300 // Don't pass vXi128 vectors in their native type, the backend can't 3301 // legalize them. 3302 if (passInt128VectorsInMem() && 3303 cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy(128)) { 3304 // Use a vXi64 vector. 3305 uint64_t Size = getContext().getTypeSize(Ty); 3306 return llvm::FixedVectorType::get(llvm::Type::getInt64Ty(getVMContext()), 3307 Size / 64); 3308 } 3309 3310 return IRType; 3311 } 3312 3313 if (IRType->getTypeID() == llvm::Type::FP128TyID) 3314 return IRType; 3315 3316 // We couldn't find the preferred IR vector type for 'Ty'. 3317 uint64_t Size = getContext().getTypeSize(Ty); 3318 assert((Size == 128 || Size == 256 || Size == 512) && "Invalid type found!"); 3319 3320 3321 // Return a LLVM IR vector type based on the size of 'Ty'. 3322 return llvm::FixedVectorType::get(llvm::Type::getDoubleTy(getVMContext()), 3323 Size / 64); 3324 } 3325 3326 /// BitsContainNoUserData - Return true if the specified [start,end) bit range 3327 /// is known to either be off the end of the specified type or being in 3328 /// alignment padding. The user type specified is known to be at most 128 bits 3329 /// in size, and have passed through X86_64ABIInfo::classify with a successful 3330 /// classification that put one of the two halves in the INTEGER class. 3331 /// 3332 /// It is conservatively correct to return false. 3333 static bool BitsContainNoUserData(QualType Ty, unsigned StartBit, 3334 unsigned EndBit, ASTContext &Context) { 3335 // If the bytes being queried are off the end of the type, there is no user 3336 // data hiding here. This handles analysis of builtins, vectors and other 3337 // types that don't contain interesting padding. 3338 unsigned TySize = (unsigned)Context.getTypeSize(Ty); 3339 if (TySize <= StartBit) 3340 return true; 3341 3342 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) { 3343 unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType()); 3344 unsigned NumElts = (unsigned)AT->getSize().getZExtValue(); 3345 3346 // Check each element to see if the element overlaps with the queried range. 3347 for (unsigned i = 0; i != NumElts; ++i) { 3348 // If the element is after the span we care about, then we're done.. 3349 unsigned EltOffset = i*EltSize; 3350 if (EltOffset >= EndBit) break; 3351 3352 unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0; 3353 if (!BitsContainNoUserData(AT->getElementType(), EltStart, 3354 EndBit-EltOffset, Context)) 3355 return false; 3356 } 3357 // If it overlaps no elements, then it is safe to process as padding. 3358 return true; 3359 } 3360 3361 if (const RecordType *RT = Ty->getAs<RecordType>()) { 3362 const RecordDecl *RD = RT->getDecl(); 3363 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); 3364 3365 // If this is a C++ record, check the bases first. 3366 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 3367 for (const auto &I : CXXRD->bases()) { 3368 assert(!I.isVirtual() && !I.getType()->isDependentType() && 3369 "Unexpected base class!"); 3370 const auto *Base = 3371 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl()); 3372 3373 // If the base is after the span we care about, ignore it. 3374 unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base)); 3375 if (BaseOffset >= EndBit) continue; 3376 3377 unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0; 3378 if (!BitsContainNoUserData(I.getType(), BaseStart, 3379 EndBit-BaseOffset, Context)) 3380 return false; 3381 } 3382 } 3383 3384 // Verify that no field has data that overlaps the region of interest. Yes 3385 // this could be sped up a lot by being smarter about queried fields, 3386 // however we're only looking at structs up to 16 bytes, so we don't care 3387 // much. 3388 unsigned idx = 0; 3389 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 3390 i != e; ++i, ++idx) { 3391 unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx); 3392 3393 // If we found a field after the region we care about, then we're done. 3394 if (FieldOffset >= EndBit) break; 3395 3396 unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0; 3397 if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset, 3398 Context)) 3399 return false; 3400 } 3401 3402 // If nothing in this record overlapped the area of interest, then we're 3403 // clean. 3404 return true; 3405 } 3406 3407 return false; 3408 } 3409 3410 /// getFPTypeAtOffset - Return a floating point type at the specified offset. 3411 static llvm::Type *getFPTypeAtOffset(llvm::Type *IRType, unsigned IROffset, 3412 const llvm::DataLayout &TD) { 3413 if (IROffset == 0 && IRType->isFloatingPointTy()) 3414 return IRType; 3415 3416 // If this is a struct, recurse into the field at the specified offset. 3417 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) { 3418 const llvm::StructLayout *SL = TD.getStructLayout(STy); 3419 unsigned Elt = SL->getElementContainingOffset(IROffset); 3420 IROffset -= SL->getElementOffset(Elt); 3421 return getFPTypeAtOffset(STy->getElementType(Elt), IROffset, TD); 3422 } 3423 3424 // If this is an array, recurse into the field at the specified offset. 3425 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) { 3426 llvm::Type *EltTy = ATy->getElementType(); 3427 unsigned EltSize = TD.getTypeAllocSize(EltTy); 3428 IROffset -= IROffset / EltSize * EltSize; 3429 return getFPTypeAtOffset(EltTy, IROffset, TD); 3430 } 3431 3432 return nullptr; 3433 } 3434 3435 /// GetSSETypeAtOffset - Return a type that will be passed by the backend in the 3436 /// low 8 bytes of an XMM register, corresponding to the SSE class. 3437 llvm::Type *X86_64ABIInfo:: 3438 GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset, 3439 QualType SourceTy, unsigned SourceOffset) const { 3440 const llvm::DataLayout &TD = getDataLayout(); 3441 unsigned SourceSize = 3442 (unsigned)getContext().getTypeSize(SourceTy) / 8 - SourceOffset; 3443 llvm::Type *T0 = getFPTypeAtOffset(IRType, IROffset, TD); 3444 if (!T0 || T0->isDoubleTy()) 3445 return llvm::Type::getDoubleTy(getVMContext()); 3446 3447 // Get the adjacent FP type. 3448 llvm::Type *T1 = nullptr; 3449 unsigned T0Size = TD.getTypeAllocSize(T0); 3450 if (SourceSize > T0Size) 3451 T1 = getFPTypeAtOffset(IRType, IROffset + T0Size, TD); 3452 if (T1 == nullptr) { 3453 // Check if IRType is a half + float. float type will be in IROffset+4 due 3454 // to its alignment. 3455 if (T0->isHalfTy() && SourceSize > 4) 3456 T1 = getFPTypeAtOffset(IRType, IROffset + 4, TD); 3457 // If we can't get a second FP type, return a simple half or float. 3458 // avx512fp16-abi.c:pr51813_2 shows it works to return float for 3459 // {float, i8} too. 3460 if (T1 == nullptr) 3461 return T0; 3462 } 3463 3464 if (T0->isFloatTy() && T1->isFloatTy()) 3465 return llvm::FixedVectorType::get(T0, 2); 3466 3467 if (T0->isHalfTy() && T1->isHalfTy()) { 3468 llvm::Type *T2 = nullptr; 3469 if (SourceSize > 4) 3470 T2 = getFPTypeAtOffset(IRType, IROffset + 4, TD); 3471 if (T2 == nullptr) 3472 return llvm::FixedVectorType::get(T0, 2); 3473 return llvm::FixedVectorType::get(T0, 4); 3474 } 3475 3476 if (T0->isHalfTy() || T1->isHalfTy()) 3477 return llvm::FixedVectorType::get(llvm::Type::getHalfTy(getVMContext()), 4); 3478 3479 return llvm::Type::getDoubleTy(getVMContext()); 3480 } 3481 3482 3483 /// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in 3484 /// an 8-byte GPR. This means that we either have a scalar or we are talking 3485 /// about the high or low part of an up-to-16-byte struct. This routine picks 3486 /// the best LLVM IR type to represent this, which may be i64 or may be anything 3487 /// else that the backend will pass in a GPR that works better (e.g. i8, %foo*, 3488 /// etc). 3489 /// 3490 /// PrefType is an LLVM IR type that corresponds to (part of) the IR type for 3491 /// the source type. IROffset is an offset in bytes into the LLVM IR type that 3492 /// the 8-byte value references. PrefType may be null. 3493 /// 3494 /// SourceTy is the source-level type for the entire argument. SourceOffset is 3495 /// an offset into this that we're processing (which is always either 0 or 8). 3496 /// 3497 llvm::Type *X86_64ABIInfo:: 3498 GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset, 3499 QualType SourceTy, unsigned SourceOffset) const { 3500 // If we're dealing with an un-offset LLVM IR type, then it means that we're 3501 // returning an 8-byte unit starting with it. See if we can safely use it. 3502 if (IROffset == 0) { 3503 // Pointers and int64's always fill the 8-byte unit. 3504 if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) || 3505 IRType->isIntegerTy(64)) 3506 return IRType; 3507 3508 // If we have a 1/2/4-byte integer, we can use it only if the rest of the 3509 // goodness in the source type is just tail padding. This is allowed to 3510 // kick in for struct {double,int} on the int, but not on 3511 // struct{double,int,int} because we wouldn't return the second int. We 3512 // have to do this analysis on the source type because we can't depend on 3513 // unions being lowered a specific way etc. 3514 if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) || 3515 IRType->isIntegerTy(32) || 3516 (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) { 3517 unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 : 3518 cast<llvm::IntegerType>(IRType)->getBitWidth(); 3519 3520 if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth, 3521 SourceOffset*8+64, getContext())) 3522 return IRType; 3523 } 3524 } 3525 3526 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) { 3527 // If this is a struct, recurse into the field at the specified offset. 3528 const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy); 3529 if (IROffset < SL->getSizeInBytes()) { 3530 unsigned FieldIdx = SL->getElementContainingOffset(IROffset); 3531 IROffset -= SL->getElementOffset(FieldIdx); 3532 3533 return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset, 3534 SourceTy, SourceOffset); 3535 } 3536 } 3537 3538 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) { 3539 llvm::Type *EltTy = ATy->getElementType(); 3540 unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy); 3541 unsigned EltOffset = IROffset/EltSize*EltSize; 3542 return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy, 3543 SourceOffset); 3544 } 3545 3546 // Okay, we don't have any better idea of what to pass, so we pass this in an 3547 // integer register that isn't too big to fit the rest of the struct. 3548 unsigned TySizeInBytes = 3549 (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity(); 3550 3551 assert(TySizeInBytes != SourceOffset && "Empty field?"); 3552 3553 // It is always safe to classify this as an integer type up to i64 that 3554 // isn't larger than the structure. 3555 return llvm::IntegerType::get(getVMContext(), 3556 std::min(TySizeInBytes-SourceOffset, 8U)*8); 3557 } 3558 3559 3560 /// GetX86_64ByValArgumentPair - Given a high and low type that can ideally 3561 /// be used as elements of a two register pair to pass or return, return a 3562 /// first class aggregate to represent them. For example, if the low part of 3563 /// a by-value argument should be passed as i32* and the high part as float, 3564 /// return {i32*, float}. 3565 static llvm::Type * 3566 GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi, 3567 const llvm::DataLayout &TD) { 3568 // In order to correctly satisfy the ABI, we need to the high part to start 3569 // at offset 8. If the high and low parts we inferred are both 4-byte types 3570 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have 3571 // the second element at offset 8. Check for this: 3572 unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo); 3573 unsigned HiAlign = TD.getABITypeAlignment(Hi); 3574 unsigned HiStart = llvm::alignTo(LoSize, HiAlign); 3575 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!"); 3576 3577 // To handle this, we have to increase the size of the low part so that the 3578 // second element will start at an 8 byte offset. We can't increase the size 3579 // of the second element because it might make us access off the end of the 3580 // struct. 3581 if (HiStart != 8) { 3582 // There are usually two sorts of types the ABI generation code can produce 3583 // for the low part of a pair that aren't 8 bytes in size: half, float or 3584 // i8/i16/i32. This can also include pointers when they are 32-bit (X32 and 3585 // NaCl). 3586 // Promote these to a larger type. 3587 if (Lo->isHalfTy() || Lo->isFloatTy()) 3588 Lo = llvm::Type::getDoubleTy(Lo->getContext()); 3589 else { 3590 assert((Lo->isIntegerTy() || Lo->isPointerTy()) 3591 && "Invalid/unknown lo type"); 3592 Lo = llvm::Type::getInt64Ty(Lo->getContext()); 3593 } 3594 } 3595 3596 llvm::StructType *Result = llvm::StructType::get(Lo, Hi); 3597 3598 // Verify that the second element is at an 8-byte offset. 3599 assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 && 3600 "Invalid x86-64 argument pair!"); 3601 return Result; 3602 } 3603 3604 ABIArgInfo X86_64ABIInfo:: 3605 classifyReturnType(QualType RetTy) const { 3606 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the 3607 // classification algorithm. 3608 X86_64ABIInfo::Class Lo, Hi; 3609 classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true); 3610 3611 // Check some invariants. 3612 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification."); 3613 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification."); 3614 3615 llvm::Type *ResType = nullptr; 3616 switch (Lo) { 3617 case NoClass: 3618 if (Hi == NoClass) 3619 return ABIArgInfo::getIgnore(); 3620 // If the low part is just padding, it takes no register, leave ResType 3621 // null. 3622 assert((Hi == SSE || Hi == Integer || Hi == X87Up) && 3623 "Unknown missing lo part"); 3624 break; 3625 3626 case SSEUp: 3627 case X87Up: 3628 llvm_unreachable("Invalid classification for lo word."); 3629 3630 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via 3631 // hidden argument. 3632 case Memory: 3633 return getIndirectReturnResult(RetTy); 3634 3635 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next 3636 // available register of the sequence %rax, %rdx is used. 3637 case Integer: 3638 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0); 3639 3640 // If we have a sign or zero extended integer, make sure to return Extend 3641 // so that the parameter gets the right LLVM IR attributes. 3642 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) { 3643 // Treat an enum type as its underlying type. 3644 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 3645 RetTy = EnumTy->getDecl()->getIntegerType(); 3646 3647 if (RetTy->isIntegralOrEnumerationType() && 3648 isPromotableIntegerTypeForABI(RetTy)) 3649 return ABIArgInfo::getExtend(RetTy); 3650 } 3651 break; 3652 3653 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next 3654 // available SSE register of the sequence %xmm0, %xmm1 is used. 3655 case SSE: 3656 ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0); 3657 break; 3658 3659 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is 3660 // returned on the X87 stack in %st0 as 80-bit x87 number. 3661 case X87: 3662 ResType = llvm::Type::getX86_FP80Ty(getVMContext()); 3663 break; 3664 3665 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real 3666 // part of the value is returned in %st0 and the imaginary part in 3667 // %st1. 3668 case ComplexX87: 3669 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification."); 3670 ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()), 3671 llvm::Type::getX86_FP80Ty(getVMContext())); 3672 break; 3673 } 3674 3675 llvm::Type *HighPart = nullptr; 3676 switch (Hi) { 3677 // Memory was handled previously and X87 should 3678 // never occur as a hi class. 3679 case Memory: 3680 case X87: 3681 llvm_unreachable("Invalid classification for hi word."); 3682 3683 case ComplexX87: // Previously handled. 3684 case NoClass: 3685 break; 3686 3687 case Integer: 3688 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8); 3689 if (Lo == NoClass) // Return HighPart at offset 8 in memory. 3690 return ABIArgInfo::getDirect(HighPart, 8); 3691 break; 3692 case SSE: 3693 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8); 3694 if (Lo == NoClass) // Return HighPart at offset 8 in memory. 3695 return ABIArgInfo::getDirect(HighPart, 8); 3696 break; 3697 3698 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte 3699 // is passed in the next available eightbyte chunk if the last used 3700 // vector register. 3701 // 3702 // SSEUP should always be preceded by SSE, just widen. 3703 case SSEUp: 3704 assert(Lo == SSE && "Unexpected SSEUp classification."); 3705 ResType = GetByteVectorType(RetTy); 3706 break; 3707 3708 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is 3709 // returned together with the previous X87 value in %st0. 3710 case X87Up: 3711 // If X87Up is preceded by X87, we don't need to do 3712 // anything. However, in some cases with unions it may not be 3713 // preceded by X87. In such situations we follow gcc and pass the 3714 // extra bits in an SSE reg. 3715 if (Lo != X87) { 3716 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8); 3717 if (Lo == NoClass) // Return HighPart at offset 8 in memory. 3718 return ABIArgInfo::getDirect(HighPart, 8); 3719 } 3720 break; 3721 } 3722 3723 // If a high part was specified, merge it together with the low part. It is 3724 // known to pass in the high eightbyte of the result. We do this by forming a 3725 // first class struct aggregate with the high and low part: {low, high} 3726 if (HighPart) 3727 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout()); 3728 3729 return ABIArgInfo::getDirect(ResType); 3730 } 3731 3732 ABIArgInfo X86_64ABIInfo::classifyArgumentType( 3733 QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE, 3734 bool isNamedArg) 3735 const 3736 { 3737 Ty = useFirstFieldIfTransparentUnion(Ty); 3738 3739 X86_64ABIInfo::Class Lo, Hi; 3740 classify(Ty, 0, Lo, Hi, isNamedArg); 3741 3742 // Check some invariants. 3743 // FIXME: Enforce these by construction. 3744 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification."); 3745 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification."); 3746 3747 neededInt = 0; 3748 neededSSE = 0; 3749 llvm::Type *ResType = nullptr; 3750 switch (Lo) { 3751 case NoClass: 3752 if (Hi == NoClass) 3753 return ABIArgInfo::getIgnore(); 3754 // If the low part is just padding, it takes no register, leave ResType 3755 // null. 3756 assert((Hi == SSE || Hi == Integer || Hi == X87Up) && 3757 "Unknown missing lo part"); 3758 break; 3759 3760 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument 3761 // on the stack. 3762 case Memory: 3763 3764 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or 3765 // COMPLEX_X87, it is passed in memory. 3766 case X87: 3767 case ComplexX87: 3768 if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect) 3769 ++neededInt; 3770 return getIndirectResult(Ty, freeIntRegs); 3771 3772 case SSEUp: 3773 case X87Up: 3774 llvm_unreachable("Invalid classification for lo word."); 3775 3776 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next 3777 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8 3778 // and %r9 is used. 3779 case Integer: 3780 ++neededInt; 3781 3782 // Pick an 8-byte type based on the preferred type. 3783 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0); 3784 3785 // If we have a sign or zero extended integer, make sure to return Extend 3786 // so that the parameter gets the right LLVM IR attributes. 3787 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) { 3788 // Treat an enum type as its underlying type. 3789 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 3790 Ty = EnumTy->getDecl()->getIntegerType(); 3791 3792 if (Ty->isIntegralOrEnumerationType() && 3793 isPromotableIntegerTypeForABI(Ty)) 3794 return ABIArgInfo::getExtend(Ty); 3795 } 3796 3797 break; 3798 3799 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next 3800 // available SSE register is used, the registers are taken in the 3801 // order from %xmm0 to %xmm7. 3802 case SSE: { 3803 llvm::Type *IRType = CGT.ConvertType(Ty); 3804 ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0); 3805 ++neededSSE; 3806 break; 3807 } 3808 } 3809 3810 llvm::Type *HighPart = nullptr; 3811 switch (Hi) { 3812 // Memory was handled previously, ComplexX87 and X87 should 3813 // never occur as hi classes, and X87Up must be preceded by X87, 3814 // which is passed in memory. 3815 case Memory: 3816 case X87: 3817 case ComplexX87: 3818 llvm_unreachable("Invalid classification for hi word."); 3819 3820 case NoClass: break; 3821 3822 case Integer: 3823 ++neededInt; 3824 // Pick an 8-byte type based on the preferred type. 3825 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8); 3826 3827 if (Lo == NoClass) // Pass HighPart at offset 8 in memory. 3828 return ABIArgInfo::getDirect(HighPart, 8); 3829 break; 3830 3831 // X87Up generally doesn't occur here (long double is passed in 3832 // memory), except in situations involving unions. 3833 case X87Up: 3834 case SSE: 3835 HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8); 3836 3837 if (Lo == NoClass) // Pass HighPart at offset 8 in memory. 3838 return ABIArgInfo::getDirect(HighPart, 8); 3839 3840 ++neededSSE; 3841 break; 3842 3843 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the 3844 // eightbyte is passed in the upper half of the last used SSE 3845 // register. This only happens when 128-bit vectors are passed. 3846 case SSEUp: 3847 assert(Lo == SSE && "Unexpected SSEUp classification"); 3848 ResType = GetByteVectorType(Ty); 3849 break; 3850 } 3851 3852 // If a high part was specified, merge it together with the low part. It is 3853 // known to pass in the high eightbyte of the result. We do this by forming a 3854 // first class struct aggregate with the high and low part: {low, high} 3855 if (HighPart) 3856 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout()); 3857 3858 return ABIArgInfo::getDirect(ResType); 3859 } 3860 3861 ABIArgInfo 3862 X86_64ABIInfo::classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt, 3863 unsigned &NeededSSE) const { 3864 auto RT = Ty->getAs<RecordType>(); 3865 assert(RT && "classifyRegCallStructType only valid with struct types"); 3866 3867 if (RT->getDecl()->hasFlexibleArrayMember()) 3868 return getIndirectReturnResult(Ty); 3869 3870 // Sum up bases 3871 if (auto CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl())) { 3872 if (CXXRD->isDynamicClass()) { 3873 NeededInt = NeededSSE = 0; 3874 return getIndirectReturnResult(Ty); 3875 } 3876 3877 for (const auto &I : CXXRD->bases()) 3878 if (classifyRegCallStructTypeImpl(I.getType(), NeededInt, NeededSSE) 3879 .isIndirect()) { 3880 NeededInt = NeededSSE = 0; 3881 return getIndirectReturnResult(Ty); 3882 } 3883 } 3884 3885 // Sum up members 3886 for (const auto *FD : RT->getDecl()->fields()) { 3887 if (FD->getType()->isRecordType() && !FD->getType()->isUnionType()) { 3888 if (classifyRegCallStructTypeImpl(FD->getType(), NeededInt, NeededSSE) 3889 .isIndirect()) { 3890 NeededInt = NeededSSE = 0; 3891 return getIndirectReturnResult(Ty); 3892 } 3893 } else { 3894 unsigned LocalNeededInt, LocalNeededSSE; 3895 if (classifyArgumentType(FD->getType(), UINT_MAX, LocalNeededInt, 3896 LocalNeededSSE, true) 3897 .isIndirect()) { 3898 NeededInt = NeededSSE = 0; 3899 return getIndirectReturnResult(Ty); 3900 } 3901 NeededInt += LocalNeededInt; 3902 NeededSSE += LocalNeededSSE; 3903 } 3904 } 3905 3906 return ABIArgInfo::getDirect(); 3907 } 3908 3909 ABIArgInfo X86_64ABIInfo::classifyRegCallStructType(QualType Ty, 3910 unsigned &NeededInt, 3911 unsigned &NeededSSE) const { 3912 3913 NeededInt = 0; 3914 NeededSSE = 0; 3915 3916 return classifyRegCallStructTypeImpl(Ty, NeededInt, NeededSSE); 3917 } 3918 3919 void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const { 3920 3921 const unsigned CallingConv = FI.getCallingConvention(); 3922 // It is possible to force Win64 calling convention on any x86_64 target by 3923 // using __attribute__((ms_abi)). In such case to correctly emit Win64 3924 // compatible code delegate this call to WinX86_64ABIInfo::computeInfo. 3925 if (CallingConv == llvm::CallingConv::Win64) { 3926 WinX86_64ABIInfo Win64ABIInfo(CGT, AVXLevel); 3927 Win64ABIInfo.computeInfo(FI); 3928 return; 3929 } 3930 3931 bool IsRegCall = CallingConv == llvm::CallingConv::X86_RegCall; 3932 3933 // Keep track of the number of assigned registers. 3934 unsigned FreeIntRegs = IsRegCall ? 11 : 6; 3935 unsigned FreeSSERegs = IsRegCall ? 16 : 8; 3936 unsigned NeededInt, NeededSSE; 3937 3938 if (!::classifyReturnType(getCXXABI(), FI, *this)) { 3939 if (IsRegCall && FI.getReturnType()->getTypePtr()->isRecordType() && 3940 !FI.getReturnType()->getTypePtr()->isUnionType()) { 3941 FI.getReturnInfo() = 3942 classifyRegCallStructType(FI.getReturnType(), NeededInt, NeededSSE); 3943 if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) { 3944 FreeIntRegs -= NeededInt; 3945 FreeSSERegs -= NeededSSE; 3946 } else { 3947 FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType()); 3948 } 3949 } else if (IsRegCall && FI.getReturnType()->getAs<ComplexType>() && 3950 getContext().getCanonicalType(FI.getReturnType() 3951 ->getAs<ComplexType>() 3952 ->getElementType()) == 3953 getContext().LongDoubleTy) 3954 // Complex Long Double Type is passed in Memory when Regcall 3955 // calling convention is used. 3956 FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType()); 3957 else 3958 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 3959 } 3960 3961 // If the return value is indirect, then the hidden argument is consuming one 3962 // integer register. 3963 if (FI.getReturnInfo().isIndirect()) 3964 --FreeIntRegs; 3965 3966 // The chain argument effectively gives us another free register. 3967 if (FI.isChainCall()) 3968 ++FreeIntRegs; 3969 3970 unsigned NumRequiredArgs = FI.getNumRequiredArgs(); 3971 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers 3972 // get assigned (in left-to-right order) for passing as follows... 3973 unsigned ArgNo = 0; 3974 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end(); 3975 it != ie; ++it, ++ArgNo) { 3976 bool IsNamedArg = ArgNo < NumRequiredArgs; 3977 3978 if (IsRegCall && it->type->isStructureOrClassType()) 3979 it->info = classifyRegCallStructType(it->type, NeededInt, NeededSSE); 3980 else 3981 it->info = classifyArgumentType(it->type, FreeIntRegs, NeededInt, 3982 NeededSSE, IsNamedArg); 3983 3984 // AMD64-ABI 3.2.3p3: If there are no registers available for any 3985 // eightbyte of an argument, the whole argument is passed on the 3986 // stack. If registers have already been assigned for some 3987 // eightbytes of such an argument, the assignments get reverted. 3988 if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) { 3989 FreeIntRegs -= NeededInt; 3990 FreeSSERegs -= NeededSSE; 3991 } else { 3992 it->info = getIndirectResult(it->type, FreeIntRegs); 3993 } 3994 } 3995 } 3996 3997 static Address EmitX86_64VAArgFromMemory(CodeGenFunction &CGF, 3998 Address VAListAddr, QualType Ty) { 3999 Address overflow_arg_area_p = 4000 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_p"); 4001 llvm::Value *overflow_arg_area = 4002 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area"); 4003 4004 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16 4005 // byte boundary if alignment needed by type exceeds 8 byte boundary. 4006 // It isn't stated explicitly in the standard, but in practice we use 4007 // alignment greater than 16 where necessary. 4008 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty); 4009 if (Align > CharUnits::fromQuantity(8)) { 4010 overflow_arg_area = emitRoundPointerUpToAlignment(CGF, overflow_arg_area, 4011 Align); 4012 } 4013 4014 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area. 4015 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty); 4016 llvm::Value *Res = 4017 CGF.Builder.CreateBitCast(overflow_arg_area, 4018 llvm::PointerType::getUnqual(LTy)); 4019 4020 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to: 4021 // l->overflow_arg_area + sizeof(type). 4022 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to 4023 // an 8 byte boundary. 4024 4025 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8; 4026 llvm::Value *Offset = 4027 llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7); 4028 overflow_arg_area = CGF.Builder.CreateGEP(CGF.Int8Ty, overflow_arg_area, 4029 Offset, "overflow_arg_area.next"); 4030 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p); 4031 4032 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type. 4033 return Address(Res, Align); 4034 } 4035 4036 Address X86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 4037 QualType Ty) const { 4038 // Assume that va_list type is correct; should be pointer to LLVM type: 4039 // struct { 4040 // i32 gp_offset; 4041 // i32 fp_offset; 4042 // i8* overflow_arg_area; 4043 // i8* reg_save_area; 4044 // }; 4045 unsigned neededInt, neededSSE; 4046 4047 Ty = getContext().getCanonicalType(Ty); 4048 ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE, 4049 /*isNamedArg*/false); 4050 4051 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed 4052 // in the registers. If not go to step 7. 4053 if (!neededInt && !neededSSE) 4054 return EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty); 4055 4056 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of 4057 // general purpose registers needed to pass type and num_fp to hold 4058 // the number of floating point registers needed. 4059 4060 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into 4061 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or 4062 // l->fp_offset > 304 - num_fp * 16 go to step 7. 4063 // 4064 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of 4065 // register save space). 4066 4067 llvm::Value *InRegs = nullptr; 4068 Address gp_offset_p = Address::invalid(), fp_offset_p = Address::invalid(); 4069 llvm::Value *gp_offset = nullptr, *fp_offset = nullptr; 4070 if (neededInt) { 4071 gp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "gp_offset_p"); 4072 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset"); 4073 InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8); 4074 InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp"); 4075 } 4076 4077 if (neededSSE) { 4078 fp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 1, "fp_offset_p"); 4079 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset"); 4080 llvm::Value *FitsInFP = 4081 llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16); 4082 FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp"); 4083 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP; 4084 } 4085 4086 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg"); 4087 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem"); 4088 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end"); 4089 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock); 4090 4091 // Emit code to load the value if it was passed in registers. 4092 4093 CGF.EmitBlock(InRegBlock); 4094 4095 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with 4096 // an offset of l->gp_offset and/or l->fp_offset. This may require 4097 // copying to a temporary location in case the parameter is passed 4098 // in different register classes or requires an alignment greater 4099 // than 8 for general purpose registers and 16 for XMM registers. 4100 // 4101 // FIXME: This really results in shameful code when we end up needing to 4102 // collect arguments from different places; often what should result in a 4103 // simple assembling of a structure from scattered addresses has many more 4104 // loads than necessary. Can we clean this up? 4105 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty); 4106 llvm::Value *RegSaveArea = CGF.Builder.CreateLoad( 4107 CGF.Builder.CreateStructGEP(VAListAddr, 3), "reg_save_area"); 4108 4109 Address RegAddr = Address::invalid(); 4110 if (neededInt && neededSSE) { 4111 // FIXME: Cleanup. 4112 assert(AI.isDirect() && "Unexpected ABI info for mixed regs"); 4113 llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType()); 4114 Address Tmp = CGF.CreateMemTemp(Ty); 4115 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST); 4116 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs"); 4117 llvm::Type *TyLo = ST->getElementType(0); 4118 llvm::Type *TyHi = ST->getElementType(1); 4119 assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) && 4120 "Unexpected ABI info for mixed regs"); 4121 llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo); 4122 llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi); 4123 llvm::Value *GPAddr = 4124 CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, gp_offset); 4125 llvm::Value *FPAddr = 4126 CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, fp_offset); 4127 llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr; 4128 llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr; 4129 4130 // Copy the first element. 4131 // FIXME: Our choice of alignment here and below is probably pessimistic. 4132 llvm::Value *V = CGF.Builder.CreateAlignedLoad( 4133 TyLo, CGF.Builder.CreateBitCast(RegLoAddr, PTyLo), 4134 CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyLo))); 4135 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0)); 4136 4137 // Copy the second element. 4138 V = CGF.Builder.CreateAlignedLoad( 4139 TyHi, CGF.Builder.CreateBitCast(RegHiAddr, PTyHi), 4140 CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyHi))); 4141 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1)); 4142 4143 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy); 4144 } else if (neededInt) { 4145 RegAddr = Address(CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, gp_offset), 4146 CharUnits::fromQuantity(8)); 4147 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy); 4148 4149 // Copy to a temporary if necessary to ensure the appropriate alignment. 4150 auto TInfo = getContext().getTypeInfoInChars(Ty); 4151 uint64_t TySize = TInfo.Width.getQuantity(); 4152 CharUnits TyAlign = TInfo.Align; 4153 4154 // Copy into a temporary if the type is more aligned than the 4155 // register save area. 4156 if (TyAlign.getQuantity() > 8) { 4157 Address Tmp = CGF.CreateMemTemp(Ty); 4158 CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, false); 4159 RegAddr = Tmp; 4160 } 4161 4162 } else if (neededSSE == 1) { 4163 RegAddr = Address(CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, fp_offset), 4164 CharUnits::fromQuantity(16)); 4165 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy); 4166 } else { 4167 assert(neededSSE == 2 && "Invalid number of needed registers!"); 4168 // SSE registers are spaced 16 bytes apart in the register save 4169 // area, we need to collect the two eightbytes together. 4170 // The ABI isn't explicit about this, but it seems reasonable 4171 // to assume that the slots are 16-byte aligned, since the stack is 4172 // naturally 16-byte aligned and the prologue is expected to store 4173 // all the SSE registers to the RSA. 4174 Address RegAddrLo = Address(CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, 4175 fp_offset), 4176 CharUnits::fromQuantity(16)); 4177 Address RegAddrHi = 4178 CGF.Builder.CreateConstInBoundsByteGEP(RegAddrLo, 4179 CharUnits::fromQuantity(16)); 4180 llvm::Type *ST = AI.canHaveCoerceToType() 4181 ? AI.getCoerceToType() 4182 : llvm::StructType::get(CGF.DoubleTy, CGF.DoubleTy); 4183 llvm::Value *V; 4184 Address Tmp = CGF.CreateMemTemp(Ty); 4185 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST); 4186 V = CGF.Builder.CreateLoad(CGF.Builder.CreateElementBitCast( 4187 RegAddrLo, ST->getStructElementType(0))); 4188 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0)); 4189 V = CGF.Builder.CreateLoad(CGF.Builder.CreateElementBitCast( 4190 RegAddrHi, ST->getStructElementType(1))); 4191 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1)); 4192 4193 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy); 4194 } 4195 4196 // AMD64-ABI 3.5.7p5: Step 5. Set: 4197 // l->gp_offset = l->gp_offset + num_gp * 8 4198 // l->fp_offset = l->fp_offset + num_fp * 16. 4199 if (neededInt) { 4200 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8); 4201 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset), 4202 gp_offset_p); 4203 } 4204 if (neededSSE) { 4205 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16); 4206 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset), 4207 fp_offset_p); 4208 } 4209 CGF.EmitBranch(ContBlock); 4210 4211 // Emit code to load the value if it was passed in memory. 4212 4213 CGF.EmitBlock(InMemBlock); 4214 Address MemAddr = EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty); 4215 4216 // Return the appropriate result. 4217 4218 CGF.EmitBlock(ContBlock); 4219 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, MemAddr, InMemBlock, 4220 "vaarg.addr"); 4221 return ResAddr; 4222 } 4223 4224 Address X86_64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr, 4225 QualType Ty) const { 4226 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is 4227 // not 1, 2, 4, or 8 bytes, must be passed by reference." 4228 uint64_t Width = getContext().getTypeSize(Ty); 4229 bool IsIndirect = Width > 64 || !llvm::isPowerOf2_64(Width); 4230 4231 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, 4232 CGF.getContext().getTypeInfoInChars(Ty), 4233 CharUnits::fromQuantity(8), 4234 /*allowHigherAlign*/ false); 4235 } 4236 4237 ABIArgInfo WinX86_64ABIInfo::reclassifyHvaArgForVectorCall( 4238 QualType Ty, unsigned &FreeSSERegs, const ABIArgInfo ¤t) const { 4239 const Type *Base = nullptr; 4240 uint64_t NumElts = 0; 4241 4242 if (!Ty->isBuiltinType() && !Ty->isVectorType() && 4243 isHomogeneousAggregate(Ty, Base, NumElts) && FreeSSERegs >= NumElts) { 4244 FreeSSERegs -= NumElts; 4245 return getDirectX86Hva(); 4246 } 4247 return current; 4248 } 4249 4250 ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, unsigned &FreeSSERegs, 4251 bool IsReturnType, bool IsVectorCall, 4252 bool IsRegCall) const { 4253 4254 if (Ty->isVoidType()) 4255 return ABIArgInfo::getIgnore(); 4256 4257 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 4258 Ty = EnumTy->getDecl()->getIntegerType(); 4259 4260 TypeInfo Info = getContext().getTypeInfo(Ty); 4261 uint64_t Width = Info.Width; 4262 CharUnits Align = getContext().toCharUnitsFromBits(Info.Align); 4263 4264 const RecordType *RT = Ty->getAs<RecordType>(); 4265 if (RT) { 4266 if (!IsReturnType) { 4267 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI())) 4268 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 4269 } 4270 4271 if (RT->getDecl()->hasFlexibleArrayMember()) 4272 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 4273 4274 } 4275 4276 const Type *Base = nullptr; 4277 uint64_t NumElts = 0; 4278 // vectorcall adds the concept of a homogenous vector aggregate, similar to 4279 // other targets. 4280 if ((IsVectorCall || IsRegCall) && 4281 isHomogeneousAggregate(Ty, Base, NumElts)) { 4282 if (IsRegCall) { 4283 if (FreeSSERegs >= NumElts) { 4284 FreeSSERegs -= NumElts; 4285 if (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType()) 4286 return ABIArgInfo::getDirect(); 4287 return ABIArgInfo::getExpand(); 4288 } 4289 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false); 4290 } else if (IsVectorCall) { 4291 if (FreeSSERegs >= NumElts && 4292 (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())) { 4293 FreeSSERegs -= NumElts; 4294 return ABIArgInfo::getDirect(); 4295 } else if (IsReturnType) { 4296 return ABIArgInfo::getExpand(); 4297 } else if (!Ty->isBuiltinType() && !Ty->isVectorType()) { 4298 // HVAs are delayed and reclassified in the 2nd step. 4299 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false); 4300 } 4301 } 4302 } 4303 4304 if (Ty->isMemberPointerType()) { 4305 // If the member pointer is represented by an LLVM int or ptr, pass it 4306 // directly. 4307 llvm::Type *LLTy = CGT.ConvertType(Ty); 4308 if (LLTy->isPointerTy() || LLTy->isIntegerTy()) 4309 return ABIArgInfo::getDirect(); 4310 } 4311 4312 if (RT || Ty->isAnyComplexType() || Ty->isMemberPointerType()) { 4313 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is 4314 // not 1, 2, 4, or 8 bytes, must be passed by reference." 4315 if (Width > 64 || !llvm::isPowerOf2_64(Width)) 4316 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 4317 4318 // Otherwise, coerce it to a small integer. 4319 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Width)); 4320 } 4321 4322 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) { 4323 switch (BT->getKind()) { 4324 case BuiltinType::Bool: 4325 // Bool type is always extended to the ABI, other builtin types are not 4326 // extended. 4327 return ABIArgInfo::getExtend(Ty); 4328 4329 case BuiltinType::LongDouble: 4330 // Mingw64 GCC uses the old 80 bit extended precision floating point 4331 // unit. It passes them indirectly through memory. 4332 if (IsMingw64) { 4333 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat(); 4334 if (LDF == &llvm::APFloat::x87DoubleExtended()) 4335 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false); 4336 } 4337 break; 4338 4339 case BuiltinType::Int128: 4340 case BuiltinType::UInt128: 4341 // If it's a parameter type, the normal ABI rule is that arguments larger 4342 // than 8 bytes are passed indirectly. GCC follows it. We follow it too, 4343 // even though it isn't particularly efficient. 4344 if (!IsReturnType) 4345 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false); 4346 4347 // Mingw64 GCC returns i128 in XMM0. Coerce to v2i64 to handle that. 4348 // Clang matches them for compatibility. 4349 return ABIArgInfo::getDirect(llvm::FixedVectorType::get( 4350 llvm::Type::getInt64Ty(getVMContext()), 2)); 4351 4352 default: 4353 break; 4354 } 4355 } 4356 4357 if (Ty->isExtIntType()) { 4358 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is 4359 // not 1, 2, 4, or 8 bytes, must be passed by reference." 4360 // However, non-power-of-two _ExtInts will be passed as 1,2,4 or 8 bytes 4361 // anyway as long is it fits in them, so we don't have to check the power of 4362 // 2. 4363 if (Width <= 64) 4364 return ABIArgInfo::getDirect(); 4365 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false); 4366 } 4367 4368 return ABIArgInfo::getDirect(); 4369 } 4370 4371 void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const { 4372 const unsigned CC = FI.getCallingConvention(); 4373 bool IsVectorCall = CC == llvm::CallingConv::X86_VectorCall; 4374 bool IsRegCall = CC == llvm::CallingConv::X86_RegCall; 4375 4376 // If __attribute__((sysv_abi)) is in use, use the SysV argument 4377 // classification rules. 4378 if (CC == llvm::CallingConv::X86_64_SysV) { 4379 X86_64ABIInfo SysVABIInfo(CGT, AVXLevel); 4380 SysVABIInfo.computeInfo(FI); 4381 return; 4382 } 4383 4384 unsigned FreeSSERegs = 0; 4385 if (IsVectorCall) { 4386 // We can use up to 4 SSE return registers with vectorcall. 4387 FreeSSERegs = 4; 4388 } else if (IsRegCall) { 4389 // RegCall gives us 16 SSE registers. 4390 FreeSSERegs = 16; 4391 } 4392 4393 if (!getCXXABI().classifyReturnType(FI)) 4394 FI.getReturnInfo() = classify(FI.getReturnType(), FreeSSERegs, true, 4395 IsVectorCall, IsRegCall); 4396 4397 if (IsVectorCall) { 4398 // We can use up to 6 SSE register parameters with vectorcall. 4399 FreeSSERegs = 6; 4400 } else if (IsRegCall) { 4401 // RegCall gives us 16 SSE registers, we can reuse the return registers. 4402 FreeSSERegs = 16; 4403 } 4404 4405 unsigned ArgNum = 0; 4406 unsigned ZeroSSERegs = 0; 4407 for (auto &I : FI.arguments()) { 4408 // Vectorcall in x64 only permits the first 6 arguments to be passed as 4409 // XMM/YMM registers. After the sixth argument, pretend no vector 4410 // registers are left. 4411 unsigned *MaybeFreeSSERegs = 4412 (IsVectorCall && ArgNum >= 6) ? &ZeroSSERegs : &FreeSSERegs; 4413 I.info = 4414 classify(I.type, *MaybeFreeSSERegs, false, IsVectorCall, IsRegCall); 4415 ++ArgNum; 4416 } 4417 4418 if (IsVectorCall) { 4419 // For vectorcall, assign aggregate HVAs to any free vector registers in a 4420 // second pass. 4421 for (auto &I : FI.arguments()) 4422 I.info = reclassifyHvaArgForVectorCall(I.type, FreeSSERegs, I.info); 4423 } 4424 } 4425 4426 Address WinX86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 4427 QualType Ty) const { 4428 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is 4429 // not 1, 2, 4, or 8 bytes, must be passed by reference." 4430 uint64_t Width = getContext().getTypeSize(Ty); 4431 bool IsIndirect = Width > 64 || !llvm::isPowerOf2_64(Width); 4432 4433 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, 4434 CGF.getContext().getTypeInfoInChars(Ty), 4435 CharUnits::fromQuantity(8), 4436 /*allowHigherAlign*/ false); 4437 } 4438 4439 static bool PPC_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 4440 llvm::Value *Address, bool Is64Bit, 4441 bool IsAIX) { 4442 // This is calculated from the LLVM and GCC tables and verified 4443 // against gcc output. AFAIK all PPC ABIs use the same encoding. 4444 4445 CodeGen::CGBuilderTy &Builder = CGF.Builder; 4446 4447 llvm::IntegerType *i8 = CGF.Int8Ty; 4448 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4); 4449 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8); 4450 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16); 4451 4452 // 0-31: r0-31, the 4-byte or 8-byte general-purpose registers 4453 AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 0, 31); 4454 4455 // 32-63: fp0-31, the 8-byte floating-point registers 4456 AssignToArrayRange(Builder, Address, Eight8, 32, 63); 4457 4458 // 64-67 are various 4-byte or 8-byte special-purpose registers: 4459 // 64: mq 4460 // 65: lr 4461 // 66: ctr 4462 // 67: ap 4463 AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 64, 67); 4464 4465 // 68-76 are various 4-byte special-purpose registers: 4466 // 68-75 cr0-7 4467 // 76: xer 4468 AssignToArrayRange(Builder, Address, Four8, 68, 76); 4469 4470 // 77-108: v0-31, the 16-byte vector registers 4471 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108); 4472 4473 // 109: vrsave 4474 // 110: vscr 4475 AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 109, 110); 4476 4477 // AIX does not utilize the rest of the registers. 4478 if (IsAIX) 4479 return false; 4480 4481 // 111: spe_acc 4482 // 112: spefscr 4483 // 113: sfp 4484 AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 111, 113); 4485 4486 if (!Is64Bit) 4487 return false; 4488 4489 // TODO: Need to verify if these registers are used on 64 bit AIX with Power8 4490 // or above CPU. 4491 // 64-bit only registers: 4492 // 114: tfhar 4493 // 115: tfiar 4494 // 116: texasr 4495 AssignToArrayRange(Builder, Address, Eight8, 114, 116); 4496 4497 return false; 4498 } 4499 4500 // AIX 4501 namespace { 4502 /// AIXABIInfo - The AIX XCOFF ABI information. 4503 class AIXABIInfo : public ABIInfo { 4504 const bool Is64Bit; 4505 const unsigned PtrByteSize; 4506 CharUnits getParamTypeAlignment(QualType Ty) const; 4507 4508 public: 4509 AIXABIInfo(CodeGen::CodeGenTypes &CGT, bool Is64Bit) 4510 : ABIInfo(CGT), Is64Bit(Is64Bit), PtrByteSize(Is64Bit ? 8 : 4) {} 4511 4512 bool isPromotableTypeForABI(QualType Ty) const; 4513 4514 ABIArgInfo classifyReturnType(QualType RetTy) const; 4515 ABIArgInfo classifyArgumentType(QualType Ty) const; 4516 4517 void computeInfo(CGFunctionInfo &FI) const override { 4518 if (!getCXXABI().classifyReturnType(FI)) 4519 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 4520 4521 for (auto &I : FI.arguments()) 4522 I.info = classifyArgumentType(I.type); 4523 } 4524 4525 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 4526 QualType Ty) const override; 4527 }; 4528 4529 class AIXTargetCodeGenInfo : public TargetCodeGenInfo { 4530 const bool Is64Bit; 4531 4532 public: 4533 AIXTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool Is64Bit) 4534 : TargetCodeGenInfo(std::make_unique<AIXABIInfo>(CGT, Is64Bit)), 4535 Is64Bit(Is64Bit) {} 4536 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 4537 return 1; // r1 is the dedicated stack pointer 4538 } 4539 4540 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 4541 llvm::Value *Address) const override; 4542 }; 4543 } // namespace 4544 4545 // Return true if the ABI requires Ty to be passed sign- or zero- 4546 // extended to 32/64 bits. 4547 bool AIXABIInfo::isPromotableTypeForABI(QualType Ty) const { 4548 // Treat an enum type as its underlying type. 4549 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 4550 Ty = EnumTy->getDecl()->getIntegerType(); 4551 4552 // Promotable integer types are required to be promoted by the ABI. 4553 if (Ty->isPromotableIntegerType()) 4554 return true; 4555 4556 if (!Is64Bit) 4557 return false; 4558 4559 // For 64 bit mode, in addition to the usual promotable integer types, we also 4560 // need to extend all 32-bit types, since the ABI requires promotion to 64 4561 // bits. 4562 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) 4563 switch (BT->getKind()) { 4564 case BuiltinType::Int: 4565 case BuiltinType::UInt: 4566 return true; 4567 default: 4568 break; 4569 } 4570 4571 return false; 4572 } 4573 4574 ABIArgInfo AIXABIInfo::classifyReturnType(QualType RetTy) const { 4575 if (RetTy->isAnyComplexType()) 4576 return ABIArgInfo::getDirect(); 4577 4578 if (RetTy->isVectorType()) 4579 return ABIArgInfo::getDirect(); 4580 4581 if (RetTy->isVoidType()) 4582 return ABIArgInfo::getIgnore(); 4583 4584 if (isAggregateTypeForABI(RetTy)) 4585 return getNaturalAlignIndirect(RetTy); 4586 4587 return (isPromotableTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy) 4588 : ABIArgInfo::getDirect()); 4589 } 4590 4591 ABIArgInfo AIXABIInfo::classifyArgumentType(QualType Ty) const { 4592 Ty = useFirstFieldIfTransparentUnion(Ty); 4593 4594 if (Ty->isAnyComplexType()) 4595 return ABIArgInfo::getDirect(); 4596 4597 if (Ty->isVectorType()) 4598 return ABIArgInfo::getDirect(); 4599 4600 if (isAggregateTypeForABI(Ty)) { 4601 // Records with non-trivial destructors/copy-constructors should not be 4602 // passed by value. 4603 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 4604 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 4605 4606 CharUnits CCAlign = getParamTypeAlignment(Ty); 4607 CharUnits TyAlign = getContext().getTypeAlignInChars(Ty); 4608 4609 return ABIArgInfo::getIndirect(CCAlign, /*ByVal*/ true, 4610 /*Realign*/ TyAlign > CCAlign); 4611 } 4612 4613 return (isPromotableTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty) 4614 : ABIArgInfo::getDirect()); 4615 } 4616 4617 CharUnits AIXABIInfo::getParamTypeAlignment(QualType Ty) const { 4618 // Complex types are passed just like their elements. 4619 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) 4620 Ty = CTy->getElementType(); 4621 4622 if (Ty->isVectorType()) 4623 return CharUnits::fromQuantity(16); 4624 4625 // If the structure contains a vector type, the alignment is 16. 4626 if (isRecordWithSIMDVectorType(getContext(), Ty)) 4627 return CharUnits::fromQuantity(16); 4628 4629 return CharUnits::fromQuantity(PtrByteSize); 4630 } 4631 4632 Address AIXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 4633 QualType Ty) const { 4634 4635 auto TypeInfo = getContext().getTypeInfoInChars(Ty); 4636 TypeInfo.Align = getParamTypeAlignment(Ty); 4637 4638 CharUnits SlotSize = CharUnits::fromQuantity(PtrByteSize); 4639 4640 // If we have a complex type and the base type is smaller than the register 4641 // size, the ABI calls for the real and imaginary parts to be right-adjusted 4642 // in separate words in 32bit mode or doublewords in 64bit mode. However, 4643 // Clang expects us to produce a pointer to a structure with the two parts 4644 // packed tightly. So generate loads of the real and imaginary parts relative 4645 // to the va_list pointer, and store them to a temporary structure. We do the 4646 // same as the PPC64ABI here. 4647 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) { 4648 CharUnits EltSize = TypeInfo.Width / 2; 4649 if (EltSize < SlotSize) 4650 return complexTempStructure(CGF, VAListAddr, Ty, SlotSize, EltSize, CTy); 4651 } 4652 4653 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false, TypeInfo, 4654 SlotSize, /*AllowHigher*/ true); 4655 } 4656 4657 bool AIXTargetCodeGenInfo::initDwarfEHRegSizeTable( 4658 CodeGen::CodeGenFunction &CGF, llvm::Value *Address) const { 4659 return PPC_initDwarfEHRegSizeTable(CGF, Address, Is64Bit, /*IsAIX*/ true); 4660 } 4661 4662 // PowerPC-32 4663 namespace { 4664 /// PPC32_SVR4_ABIInfo - The 32-bit PowerPC ELF (SVR4) ABI information. 4665 class PPC32_SVR4_ABIInfo : public DefaultABIInfo { 4666 bool IsSoftFloatABI; 4667 bool IsRetSmallStructInRegABI; 4668 4669 CharUnits getParamTypeAlignment(QualType Ty) const; 4670 4671 public: 4672 PPC32_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, bool SoftFloatABI, 4673 bool RetSmallStructInRegABI) 4674 : DefaultABIInfo(CGT), IsSoftFloatABI(SoftFloatABI), 4675 IsRetSmallStructInRegABI(RetSmallStructInRegABI) {} 4676 4677 ABIArgInfo classifyReturnType(QualType RetTy) const; 4678 4679 void computeInfo(CGFunctionInfo &FI) const override { 4680 if (!getCXXABI().classifyReturnType(FI)) 4681 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 4682 for (auto &I : FI.arguments()) 4683 I.info = classifyArgumentType(I.type); 4684 } 4685 4686 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 4687 QualType Ty) const override; 4688 }; 4689 4690 class PPC32TargetCodeGenInfo : public TargetCodeGenInfo { 4691 public: 4692 PPC32TargetCodeGenInfo(CodeGenTypes &CGT, bool SoftFloatABI, 4693 bool RetSmallStructInRegABI) 4694 : TargetCodeGenInfo(std::make_unique<PPC32_SVR4_ABIInfo>( 4695 CGT, SoftFloatABI, RetSmallStructInRegABI)) {} 4696 4697 static bool isStructReturnInRegABI(const llvm::Triple &Triple, 4698 const CodeGenOptions &Opts); 4699 4700 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 4701 // This is recovered from gcc output. 4702 return 1; // r1 is the dedicated stack pointer 4703 } 4704 4705 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 4706 llvm::Value *Address) const override; 4707 }; 4708 } 4709 4710 CharUnits PPC32_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const { 4711 // Complex types are passed just like their elements. 4712 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) 4713 Ty = CTy->getElementType(); 4714 4715 if (Ty->isVectorType()) 4716 return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16 4717 : 4); 4718 4719 // For single-element float/vector structs, we consider the whole type 4720 // to have the same alignment requirements as its single element. 4721 const Type *AlignTy = nullptr; 4722 if (const Type *EltType = isSingleElementStruct(Ty, getContext())) { 4723 const BuiltinType *BT = EltType->getAs<BuiltinType>(); 4724 if ((EltType->isVectorType() && getContext().getTypeSize(EltType) == 128) || 4725 (BT && BT->isFloatingPoint())) 4726 AlignTy = EltType; 4727 } 4728 4729 if (AlignTy) 4730 return CharUnits::fromQuantity(AlignTy->isVectorType() ? 16 : 4); 4731 return CharUnits::fromQuantity(4); 4732 } 4733 4734 ABIArgInfo PPC32_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const { 4735 uint64_t Size; 4736 4737 // -msvr4-struct-return puts small aggregates in GPR3 and GPR4. 4738 if (isAggregateTypeForABI(RetTy) && IsRetSmallStructInRegABI && 4739 (Size = getContext().getTypeSize(RetTy)) <= 64) { 4740 // System V ABI (1995), page 3-22, specified: 4741 // > A structure or union whose size is less than or equal to 8 bytes 4742 // > shall be returned in r3 and r4, as if it were first stored in the 4743 // > 8-byte aligned memory area and then the low addressed word were 4744 // > loaded into r3 and the high-addressed word into r4. Bits beyond 4745 // > the last member of the structure or union are not defined. 4746 // 4747 // GCC for big-endian PPC32 inserts the pad before the first member, 4748 // not "beyond the last member" of the struct. To stay compatible 4749 // with GCC, we coerce the struct to an integer of the same size. 4750 // LLVM will extend it and return i32 in r3, or i64 in r3:r4. 4751 if (Size == 0) 4752 return ABIArgInfo::getIgnore(); 4753 else { 4754 llvm::Type *CoerceTy = llvm::Type::getIntNTy(getVMContext(), Size); 4755 return ABIArgInfo::getDirect(CoerceTy); 4756 } 4757 } 4758 4759 return DefaultABIInfo::classifyReturnType(RetTy); 4760 } 4761 4762 // TODO: this implementation is now likely redundant with 4763 // DefaultABIInfo::EmitVAArg. 4764 Address PPC32_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAList, 4765 QualType Ty) const { 4766 if (getTarget().getTriple().isOSDarwin()) { 4767 auto TI = getContext().getTypeInfoInChars(Ty); 4768 TI.Align = getParamTypeAlignment(Ty); 4769 4770 CharUnits SlotSize = CharUnits::fromQuantity(4); 4771 return emitVoidPtrVAArg(CGF, VAList, Ty, 4772 classifyArgumentType(Ty).isIndirect(), TI, SlotSize, 4773 /*AllowHigherAlign=*/true); 4774 } 4775 4776 const unsigned OverflowLimit = 8; 4777 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) { 4778 // TODO: Implement this. For now ignore. 4779 (void)CTy; 4780 return Address::invalid(); // FIXME? 4781 } 4782 4783 // struct __va_list_tag { 4784 // unsigned char gpr; 4785 // unsigned char fpr; 4786 // unsigned short reserved; 4787 // void *overflow_arg_area; 4788 // void *reg_save_area; 4789 // }; 4790 4791 bool isI64 = Ty->isIntegerType() && getContext().getTypeSize(Ty) == 64; 4792 bool isInt = !Ty->isFloatingType(); 4793 bool isF64 = Ty->isFloatingType() && getContext().getTypeSize(Ty) == 64; 4794 4795 // All aggregates are passed indirectly? That doesn't seem consistent 4796 // with the argument-lowering code. 4797 bool isIndirect = isAggregateTypeForABI(Ty); 4798 4799 CGBuilderTy &Builder = CGF.Builder; 4800 4801 // The calling convention either uses 1-2 GPRs or 1 FPR. 4802 Address NumRegsAddr = Address::invalid(); 4803 if (isInt || IsSoftFloatABI) { 4804 NumRegsAddr = Builder.CreateStructGEP(VAList, 0, "gpr"); 4805 } else { 4806 NumRegsAddr = Builder.CreateStructGEP(VAList, 1, "fpr"); 4807 } 4808 4809 llvm::Value *NumRegs = Builder.CreateLoad(NumRegsAddr, "numUsedRegs"); 4810 4811 // "Align" the register count when TY is i64. 4812 if (isI64 || (isF64 && IsSoftFloatABI)) { 4813 NumRegs = Builder.CreateAdd(NumRegs, Builder.getInt8(1)); 4814 NumRegs = Builder.CreateAnd(NumRegs, Builder.getInt8((uint8_t) ~1U)); 4815 } 4816 4817 llvm::Value *CC = 4818 Builder.CreateICmpULT(NumRegs, Builder.getInt8(OverflowLimit), "cond"); 4819 4820 llvm::BasicBlock *UsingRegs = CGF.createBasicBlock("using_regs"); 4821 llvm::BasicBlock *UsingOverflow = CGF.createBasicBlock("using_overflow"); 4822 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont"); 4823 4824 Builder.CreateCondBr(CC, UsingRegs, UsingOverflow); 4825 4826 llvm::Type *DirectTy = CGF.ConvertType(Ty); 4827 if (isIndirect) DirectTy = DirectTy->getPointerTo(0); 4828 4829 // Case 1: consume registers. 4830 Address RegAddr = Address::invalid(); 4831 { 4832 CGF.EmitBlock(UsingRegs); 4833 4834 Address RegSaveAreaPtr = Builder.CreateStructGEP(VAList, 4); 4835 RegAddr = Address(Builder.CreateLoad(RegSaveAreaPtr), 4836 CharUnits::fromQuantity(8)); 4837 assert(RegAddr.getElementType() == CGF.Int8Ty); 4838 4839 // Floating-point registers start after the general-purpose registers. 4840 if (!(isInt || IsSoftFloatABI)) { 4841 RegAddr = Builder.CreateConstInBoundsByteGEP(RegAddr, 4842 CharUnits::fromQuantity(32)); 4843 } 4844 4845 // Get the address of the saved value by scaling the number of 4846 // registers we've used by the number of 4847 CharUnits RegSize = CharUnits::fromQuantity((isInt || IsSoftFloatABI) ? 4 : 8); 4848 llvm::Value *RegOffset = 4849 Builder.CreateMul(NumRegs, Builder.getInt8(RegSize.getQuantity())); 4850 RegAddr = Address(Builder.CreateInBoundsGEP(CGF.Int8Ty, 4851 RegAddr.getPointer(), RegOffset), 4852 RegAddr.getAlignment().alignmentOfArrayElement(RegSize)); 4853 RegAddr = Builder.CreateElementBitCast(RegAddr, DirectTy); 4854 4855 // Increase the used-register count. 4856 NumRegs = 4857 Builder.CreateAdd(NumRegs, 4858 Builder.getInt8((isI64 || (isF64 && IsSoftFloatABI)) ? 2 : 1)); 4859 Builder.CreateStore(NumRegs, NumRegsAddr); 4860 4861 CGF.EmitBranch(Cont); 4862 } 4863 4864 // Case 2: consume space in the overflow area. 4865 Address MemAddr = Address::invalid(); 4866 { 4867 CGF.EmitBlock(UsingOverflow); 4868 4869 Builder.CreateStore(Builder.getInt8(OverflowLimit), NumRegsAddr); 4870 4871 // Everything in the overflow area is rounded up to a size of at least 4. 4872 CharUnits OverflowAreaAlign = CharUnits::fromQuantity(4); 4873 4874 CharUnits Size; 4875 if (!isIndirect) { 4876 auto TypeInfo = CGF.getContext().getTypeInfoInChars(Ty); 4877 Size = TypeInfo.Width.alignTo(OverflowAreaAlign); 4878 } else { 4879 Size = CGF.getPointerSize(); 4880 } 4881 4882 Address OverflowAreaAddr = Builder.CreateStructGEP(VAList, 3); 4883 Address OverflowArea(Builder.CreateLoad(OverflowAreaAddr, "argp.cur"), 4884 OverflowAreaAlign); 4885 // Round up address of argument to alignment 4886 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty); 4887 if (Align > OverflowAreaAlign) { 4888 llvm::Value *Ptr = OverflowArea.getPointer(); 4889 OverflowArea = Address(emitRoundPointerUpToAlignment(CGF, Ptr, Align), 4890 Align); 4891 } 4892 4893 MemAddr = Builder.CreateElementBitCast(OverflowArea, DirectTy); 4894 4895 // Increase the overflow area. 4896 OverflowArea = Builder.CreateConstInBoundsByteGEP(OverflowArea, Size); 4897 Builder.CreateStore(OverflowArea.getPointer(), OverflowAreaAddr); 4898 CGF.EmitBranch(Cont); 4899 } 4900 4901 CGF.EmitBlock(Cont); 4902 4903 // Merge the cases with a phi. 4904 Address Result = emitMergePHI(CGF, RegAddr, UsingRegs, MemAddr, UsingOverflow, 4905 "vaarg.addr"); 4906 4907 // Load the pointer if the argument was passed indirectly. 4908 if (isIndirect) { 4909 Result = Address(Builder.CreateLoad(Result, "aggr"), 4910 getContext().getTypeAlignInChars(Ty)); 4911 } 4912 4913 return Result; 4914 } 4915 4916 bool PPC32TargetCodeGenInfo::isStructReturnInRegABI( 4917 const llvm::Triple &Triple, const CodeGenOptions &Opts) { 4918 assert(Triple.isPPC32()); 4919 4920 switch (Opts.getStructReturnConvention()) { 4921 case CodeGenOptions::SRCK_Default: 4922 break; 4923 case CodeGenOptions::SRCK_OnStack: // -maix-struct-return 4924 return false; 4925 case CodeGenOptions::SRCK_InRegs: // -msvr4-struct-return 4926 return true; 4927 } 4928 4929 if (Triple.isOSBinFormatELF() && !Triple.isOSLinux()) 4930 return true; 4931 4932 return false; 4933 } 4934 4935 bool 4936 PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 4937 llvm::Value *Address) const { 4938 return PPC_initDwarfEHRegSizeTable(CGF, Address, /*Is64Bit*/ false, 4939 /*IsAIX*/ false); 4940 } 4941 4942 // PowerPC-64 4943 4944 namespace { 4945 /// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information. 4946 class PPC64_SVR4_ABIInfo : public SwiftABIInfo { 4947 public: 4948 enum ABIKind { 4949 ELFv1 = 0, 4950 ELFv2 4951 }; 4952 4953 private: 4954 static const unsigned GPRBits = 64; 4955 ABIKind Kind; 4956 bool IsSoftFloatABI; 4957 4958 public: 4959 PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind, 4960 bool SoftFloatABI) 4961 : SwiftABIInfo(CGT), Kind(Kind), IsSoftFloatABI(SoftFloatABI) {} 4962 4963 bool isPromotableTypeForABI(QualType Ty) const; 4964 CharUnits getParamTypeAlignment(QualType Ty) const; 4965 4966 ABIArgInfo classifyReturnType(QualType RetTy) const; 4967 ABIArgInfo classifyArgumentType(QualType Ty) const; 4968 4969 bool isHomogeneousAggregateBaseType(QualType Ty) const override; 4970 bool isHomogeneousAggregateSmallEnough(const Type *Ty, 4971 uint64_t Members) const override; 4972 4973 // TODO: We can add more logic to computeInfo to improve performance. 4974 // Example: For aggregate arguments that fit in a register, we could 4975 // use getDirectInReg (as is done below for structs containing a single 4976 // floating-point value) to avoid pushing them to memory on function 4977 // entry. This would require changing the logic in PPCISelLowering 4978 // when lowering the parameters in the caller and args in the callee. 4979 void computeInfo(CGFunctionInfo &FI) const override { 4980 if (!getCXXABI().classifyReturnType(FI)) 4981 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 4982 for (auto &I : FI.arguments()) { 4983 // We rely on the default argument classification for the most part. 4984 // One exception: An aggregate containing a single floating-point 4985 // or vector item must be passed in a register if one is available. 4986 const Type *T = isSingleElementStruct(I.type, getContext()); 4987 if (T) { 4988 const BuiltinType *BT = T->getAs<BuiltinType>(); 4989 if ((T->isVectorType() && getContext().getTypeSize(T) == 128) || 4990 (BT && BT->isFloatingPoint())) { 4991 QualType QT(T, 0); 4992 I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT)); 4993 continue; 4994 } 4995 } 4996 I.info = classifyArgumentType(I.type); 4997 } 4998 } 4999 5000 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 5001 QualType Ty) const override; 5002 5003 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars, 5004 bool asReturnValue) const override { 5005 return occupiesMoreThan(CGT, scalars, /*total*/ 4); 5006 } 5007 5008 bool isSwiftErrorInRegister() const override { 5009 return false; 5010 } 5011 }; 5012 5013 class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo { 5014 5015 public: 5016 PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT, 5017 PPC64_SVR4_ABIInfo::ABIKind Kind, 5018 bool SoftFloatABI) 5019 : TargetCodeGenInfo( 5020 std::make_unique<PPC64_SVR4_ABIInfo>(CGT, Kind, SoftFloatABI)) {} 5021 5022 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 5023 // This is recovered from gcc output. 5024 return 1; // r1 is the dedicated stack pointer 5025 } 5026 5027 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 5028 llvm::Value *Address) const override; 5029 }; 5030 5031 class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo { 5032 public: 5033 PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {} 5034 5035 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 5036 // This is recovered from gcc output. 5037 return 1; // r1 is the dedicated stack pointer 5038 } 5039 5040 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 5041 llvm::Value *Address) const override; 5042 }; 5043 5044 } 5045 5046 // Return true if the ABI requires Ty to be passed sign- or zero- 5047 // extended to 64 bits. 5048 bool 5049 PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const { 5050 // Treat an enum type as its underlying type. 5051 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 5052 Ty = EnumTy->getDecl()->getIntegerType(); 5053 5054 // Promotable integer types are required to be promoted by the ABI. 5055 if (isPromotableIntegerTypeForABI(Ty)) 5056 return true; 5057 5058 // In addition to the usual promotable integer types, we also need to 5059 // extend all 32-bit types, since the ABI requires promotion to 64 bits. 5060 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) 5061 switch (BT->getKind()) { 5062 case BuiltinType::Int: 5063 case BuiltinType::UInt: 5064 return true; 5065 default: 5066 break; 5067 } 5068 5069 if (const auto *EIT = Ty->getAs<ExtIntType>()) 5070 if (EIT->getNumBits() < 64) 5071 return true; 5072 5073 return false; 5074 } 5075 5076 /// isAlignedParamType - Determine whether a type requires 16-byte or 5077 /// higher alignment in the parameter area. Always returns at least 8. 5078 CharUnits PPC64_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const { 5079 // Complex types are passed just like their elements. 5080 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) 5081 Ty = CTy->getElementType(); 5082 5083 // Only vector types of size 16 bytes need alignment (larger types are 5084 // passed via reference, smaller types are not aligned). 5085 if (Ty->isVectorType()) { 5086 return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16 : 8); 5087 } else if (Ty->isRealFloatingType() && 5088 &getContext().getFloatTypeSemantics(Ty) == 5089 &llvm::APFloat::IEEEquad()) { 5090 // According to ABI document section 'Optional Save Areas': If extended 5091 // precision floating-point values in IEEE BINARY 128 QUADRUPLE PRECISION 5092 // format are supported, map them to a single quadword, quadword aligned. 5093 return CharUnits::fromQuantity(16); 5094 } 5095 5096 // For single-element float/vector structs, we consider the whole type 5097 // to have the same alignment requirements as its single element. 5098 const Type *AlignAsType = nullptr; 5099 const Type *EltType = isSingleElementStruct(Ty, getContext()); 5100 if (EltType) { 5101 const BuiltinType *BT = EltType->getAs<BuiltinType>(); 5102 if ((EltType->isVectorType() && getContext().getTypeSize(EltType) == 128) || 5103 (BT && BT->isFloatingPoint())) 5104 AlignAsType = EltType; 5105 } 5106 5107 // Likewise for ELFv2 homogeneous aggregates. 5108 const Type *Base = nullptr; 5109 uint64_t Members = 0; 5110 if (!AlignAsType && Kind == ELFv2 && 5111 isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members)) 5112 AlignAsType = Base; 5113 5114 // With special case aggregates, only vector base types need alignment. 5115 if (AlignAsType) { 5116 return CharUnits::fromQuantity(AlignAsType->isVectorType() ? 16 : 8); 5117 } 5118 5119 // Otherwise, we only need alignment for any aggregate type that 5120 // has an alignment requirement of >= 16 bytes. 5121 if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128) { 5122 return CharUnits::fromQuantity(16); 5123 } 5124 5125 return CharUnits::fromQuantity(8); 5126 } 5127 5128 /// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous 5129 /// aggregate. Base is set to the base element type, and Members is set 5130 /// to the number of base elements. 5131 bool ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base, 5132 uint64_t &Members) const { 5133 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) { 5134 uint64_t NElements = AT->getSize().getZExtValue(); 5135 if (NElements == 0) 5136 return false; 5137 if (!isHomogeneousAggregate(AT->getElementType(), Base, Members)) 5138 return false; 5139 Members *= NElements; 5140 } else if (const RecordType *RT = Ty->getAs<RecordType>()) { 5141 const RecordDecl *RD = RT->getDecl(); 5142 if (RD->hasFlexibleArrayMember()) 5143 return false; 5144 5145 Members = 0; 5146 5147 // If this is a C++ record, check the properties of the record such as 5148 // bases and ABI specific restrictions 5149 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 5150 if (!getCXXABI().isPermittedToBeHomogeneousAggregate(CXXRD)) 5151 return false; 5152 5153 for (const auto &I : CXXRD->bases()) { 5154 // Ignore empty records. 5155 if (isEmptyRecord(getContext(), I.getType(), true)) 5156 continue; 5157 5158 uint64_t FldMembers; 5159 if (!isHomogeneousAggregate(I.getType(), Base, FldMembers)) 5160 return false; 5161 5162 Members += FldMembers; 5163 } 5164 } 5165 5166 for (const auto *FD : RD->fields()) { 5167 // Ignore (non-zero arrays of) empty records. 5168 QualType FT = FD->getType(); 5169 while (const ConstantArrayType *AT = 5170 getContext().getAsConstantArrayType(FT)) { 5171 if (AT->getSize().getZExtValue() == 0) 5172 return false; 5173 FT = AT->getElementType(); 5174 } 5175 if (isEmptyRecord(getContext(), FT, true)) 5176 continue; 5177 5178 // For compatibility with GCC, ignore empty bitfields in C++ mode. 5179 if (getContext().getLangOpts().CPlusPlus && 5180 FD->isZeroLengthBitField(getContext())) 5181 continue; 5182 5183 uint64_t FldMembers; 5184 if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers)) 5185 return false; 5186 5187 Members = (RD->isUnion() ? 5188 std::max(Members, FldMembers) : Members + FldMembers); 5189 } 5190 5191 if (!Base) 5192 return false; 5193 5194 // Ensure there is no padding. 5195 if (getContext().getTypeSize(Base) * Members != 5196 getContext().getTypeSize(Ty)) 5197 return false; 5198 } else { 5199 Members = 1; 5200 if (const ComplexType *CT = Ty->getAs<ComplexType>()) { 5201 Members = 2; 5202 Ty = CT->getElementType(); 5203 } 5204 5205 // Most ABIs only support float, double, and some vector type widths. 5206 if (!isHomogeneousAggregateBaseType(Ty)) 5207 return false; 5208 5209 // The base type must be the same for all members. Types that 5210 // agree in both total size and mode (float vs. vector) are 5211 // treated as being equivalent here. 5212 const Type *TyPtr = Ty.getTypePtr(); 5213 if (!Base) { 5214 Base = TyPtr; 5215 // If it's a non-power-of-2 vector, its size is already a power-of-2, 5216 // so make sure to widen it explicitly. 5217 if (const VectorType *VT = Base->getAs<VectorType>()) { 5218 QualType EltTy = VT->getElementType(); 5219 unsigned NumElements = 5220 getContext().getTypeSize(VT) / getContext().getTypeSize(EltTy); 5221 Base = getContext() 5222 .getVectorType(EltTy, NumElements, VT->getVectorKind()) 5223 .getTypePtr(); 5224 } 5225 } 5226 5227 if (Base->isVectorType() != TyPtr->isVectorType() || 5228 getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr)) 5229 return false; 5230 } 5231 return Members > 0 && isHomogeneousAggregateSmallEnough(Base, Members); 5232 } 5233 5234 bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const { 5235 // Homogeneous aggregates for ELFv2 must have base types of float, 5236 // double, long double, or 128-bit vectors. 5237 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) { 5238 if (BT->getKind() == BuiltinType::Float || 5239 BT->getKind() == BuiltinType::Double || 5240 BT->getKind() == BuiltinType::LongDouble || 5241 BT->getKind() == BuiltinType::Ibm128 || 5242 (getContext().getTargetInfo().hasFloat128Type() && 5243 (BT->getKind() == BuiltinType::Float128))) { 5244 if (IsSoftFloatABI) 5245 return false; 5246 return true; 5247 } 5248 } 5249 if (const VectorType *VT = Ty->getAs<VectorType>()) { 5250 if (getContext().getTypeSize(VT) == 128) 5251 return true; 5252 } 5253 return false; 5254 } 5255 5256 bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateSmallEnough( 5257 const Type *Base, uint64_t Members) const { 5258 // Vector and fp128 types require one register, other floating point types 5259 // require one or two registers depending on their size. 5260 uint32_t NumRegs = 5261 ((getContext().getTargetInfo().hasFloat128Type() && 5262 Base->isFloat128Type()) || 5263 Base->isVectorType()) ? 1 5264 : (getContext().getTypeSize(Base) + 63) / 64; 5265 5266 // Homogeneous Aggregates may occupy at most 8 registers. 5267 return Members * NumRegs <= 8; 5268 } 5269 5270 ABIArgInfo 5271 PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const { 5272 Ty = useFirstFieldIfTransparentUnion(Ty); 5273 5274 if (Ty->isAnyComplexType()) 5275 return ABIArgInfo::getDirect(); 5276 5277 // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes) 5278 // or via reference (larger than 16 bytes). 5279 if (Ty->isVectorType()) { 5280 uint64_t Size = getContext().getTypeSize(Ty); 5281 if (Size > 128) 5282 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 5283 else if (Size < 128) { 5284 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size); 5285 return ABIArgInfo::getDirect(CoerceTy); 5286 } 5287 } 5288 5289 if (const auto *EIT = Ty->getAs<ExtIntType>()) 5290 if (EIT->getNumBits() > 128) 5291 return getNaturalAlignIndirect(Ty, /*ByVal=*/true); 5292 5293 if (isAggregateTypeForABI(Ty)) { 5294 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 5295 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 5296 5297 uint64_t ABIAlign = getParamTypeAlignment(Ty).getQuantity(); 5298 uint64_t TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity(); 5299 5300 // ELFv2 homogeneous aggregates are passed as array types. 5301 const Type *Base = nullptr; 5302 uint64_t Members = 0; 5303 if (Kind == ELFv2 && 5304 isHomogeneousAggregate(Ty, Base, Members)) { 5305 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0)); 5306 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members); 5307 return ABIArgInfo::getDirect(CoerceTy); 5308 } 5309 5310 // If an aggregate may end up fully in registers, we do not 5311 // use the ByVal method, but pass the aggregate as array. 5312 // This is usually beneficial since we avoid forcing the 5313 // back-end to store the argument to memory. 5314 uint64_t Bits = getContext().getTypeSize(Ty); 5315 if (Bits > 0 && Bits <= 8 * GPRBits) { 5316 llvm::Type *CoerceTy; 5317 5318 // Types up to 8 bytes are passed as integer type (which will be 5319 // properly aligned in the argument save area doubleword). 5320 if (Bits <= GPRBits) 5321 CoerceTy = 5322 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8)); 5323 // Larger types are passed as arrays, with the base type selected 5324 // according to the required alignment in the save area. 5325 else { 5326 uint64_t RegBits = ABIAlign * 8; 5327 uint64_t NumRegs = llvm::alignTo(Bits, RegBits) / RegBits; 5328 llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits); 5329 CoerceTy = llvm::ArrayType::get(RegTy, NumRegs); 5330 } 5331 5332 return ABIArgInfo::getDirect(CoerceTy); 5333 } 5334 5335 // All other aggregates are passed ByVal. 5336 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign), 5337 /*ByVal=*/true, 5338 /*Realign=*/TyAlign > ABIAlign); 5339 } 5340 5341 return (isPromotableTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty) 5342 : ABIArgInfo::getDirect()); 5343 } 5344 5345 ABIArgInfo 5346 PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const { 5347 if (RetTy->isVoidType()) 5348 return ABIArgInfo::getIgnore(); 5349 5350 if (RetTy->isAnyComplexType()) 5351 return ABIArgInfo::getDirect(); 5352 5353 // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes) 5354 // or via reference (larger than 16 bytes). 5355 if (RetTy->isVectorType()) { 5356 uint64_t Size = getContext().getTypeSize(RetTy); 5357 if (Size > 128) 5358 return getNaturalAlignIndirect(RetTy); 5359 else if (Size < 128) { 5360 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size); 5361 return ABIArgInfo::getDirect(CoerceTy); 5362 } 5363 } 5364 5365 if (const auto *EIT = RetTy->getAs<ExtIntType>()) 5366 if (EIT->getNumBits() > 128) 5367 return getNaturalAlignIndirect(RetTy, /*ByVal=*/false); 5368 5369 if (isAggregateTypeForABI(RetTy)) { 5370 // ELFv2 homogeneous aggregates are returned as array types. 5371 const Type *Base = nullptr; 5372 uint64_t Members = 0; 5373 if (Kind == ELFv2 && 5374 isHomogeneousAggregate(RetTy, Base, Members)) { 5375 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0)); 5376 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members); 5377 return ABIArgInfo::getDirect(CoerceTy); 5378 } 5379 5380 // ELFv2 small aggregates are returned in up to two registers. 5381 uint64_t Bits = getContext().getTypeSize(RetTy); 5382 if (Kind == ELFv2 && Bits <= 2 * GPRBits) { 5383 if (Bits == 0) 5384 return ABIArgInfo::getIgnore(); 5385 5386 llvm::Type *CoerceTy; 5387 if (Bits > GPRBits) { 5388 CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits); 5389 CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy); 5390 } else 5391 CoerceTy = 5392 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8)); 5393 return ABIArgInfo::getDirect(CoerceTy); 5394 } 5395 5396 // All other aggregates are returned indirectly. 5397 return getNaturalAlignIndirect(RetTy); 5398 } 5399 5400 return (isPromotableTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy) 5401 : ABIArgInfo::getDirect()); 5402 } 5403 5404 // Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine. 5405 Address PPC64_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 5406 QualType Ty) const { 5407 auto TypeInfo = getContext().getTypeInfoInChars(Ty); 5408 TypeInfo.Align = getParamTypeAlignment(Ty); 5409 5410 CharUnits SlotSize = CharUnits::fromQuantity(8); 5411 5412 // If we have a complex type and the base type is smaller than 8 bytes, 5413 // the ABI calls for the real and imaginary parts to be right-adjusted 5414 // in separate doublewords. However, Clang expects us to produce a 5415 // pointer to a structure with the two parts packed tightly. So generate 5416 // loads of the real and imaginary parts relative to the va_list pointer, 5417 // and store them to a temporary structure. 5418 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) { 5419 CharUnits EltSize = TypeInfo.Width / 2; 5420 if (EltSize < SlotSize) 5421 return complexTempStructure(CGF, VAListAddr, Ty, SlotSize, EltSize, CTy); 5422 } 5423 5424 // Otherwise, just use the general rule. 5425 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false, 5426 TypeInfo, SlotSize, /*AllowHigher*/ true); 5427 } 5428 5429 bool 5430 PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable( 5431 CodeGen::CodeGenFunction &CGF, 5432 llvm::Value *Address) const { 5433 return PPC_initDwarfEHRegSizeTable(CGF, Address, /*Is64Bit*/ true, 5434 /*IsAIX*/ false); 5435 } 5436 5437 bool 5438 PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 5439 llvm::Value *Address) const { 5440 return PPC_initDwarfEHRegSizeTable(CGF, Address, /*Is64Bit*/ true, 5441 /*IsAIX*/ false); 5442 } 5443 5444 //===----------------------------------------------------------------------===// 5445 // AArch64 ABI Implementation 5446 //===----------------------------------------------------------------------===// 5447 5448 namespace { 5449 5450 class AArch64ABIInfo : public SwiftABIInfo { 5451 public: 5452 enum ABIKind { 5453 AAPCS = 0, 5454 DarwinPCS, 5455 Win64 5456 }; 5457 5458 private: 5459 ABIKind Kind; 5460 5461 public: 5462 AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind) 5463 : SwiftABIInfo(CGT), Kind(Kind) {} 5464 5465 private: 5466 ABIKind getABIKind() const { return Kind; } 5467 bool isDarwinPCS() const { return Kind == DarwinPCS; } 5468 5469 ABIArgInfo classifyReturnType(QualType RetTy, bool IsVariadic) const; 5470 ABIArgInfo classifyArgumentType(QualType RetTy, bool IsVariadic, 5471 unsigned CallingConvention) const; 5472 ABIArgInfo coerceIllegalVector(QualType Ty) const; 5473 bool isHomogeneousAggregateBaseType(QualType Ty) const override; 5474 bool isHomogeneousAggregateSmallEnough(const Type *Ty, 5475 uint64_t Members) const override; 5476 5477 bool isIllegalVectorType(QualType Ty) const; 5478 5479 void computeInfo(CGFunctionInfo &FI) const override { 5480 if (!::classifyReturnType(getCXXABI(), FI, *this)) 5481 FI.getReturnInfo() = 5482 classifyReturnType(FI.getReturnType(), FI.isVariadic()); 5483 5484 for (auto &it : FI.arguments()) 5485 it.info = classifyArgumentType(it.type, FI.isVariadic(), 5486 FI.getCallingConvention()); 5487 } 5488 5489 Address EmitDarwinVAArg(Address VAListAddr, QualType Ty, 5490 CodeGenFunction &CGF) const; 5491 5492 Address EmitAAPCSVAArg(Address VAListAddr, QualType Ty, 5493 CodeGenFunction &CGF) const; 5494 5495 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 5496 QualType Ty) const override { 5497 llvm::Type *BaseTy = CGF.ConvertType(Ty); 5498 if (isa<llvm::ScalableVectorType>(BaseTy)) 5499 llvm::report_fatal_error("Passing SVE types to variadic functions is " 5500 "currently not supported"); 5501 5502 return Kind == Win64 ? EmitMSVAArg(CGF, VAListAddr, Ty) 5503 : isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF) 5504 : EmitAAPCSVAArg(VAListAddr, Ty, CGF); 5505 } 5506 5507 Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr, 5508 QualType Ty) const override; 5509 5510 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars, 5511 bool asReturnValue) const override { 5512 return occupiesMoreThan(CGT, scalars, /*total*/ 4); 5513 } 5514 bool isSwiftErrorInRegister() const override { 5515 return true; 5516 } 5517 5518 bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy, 5519 unsigned elts) const override; 5520 5521 bool allowBFloatArgsAndRet() const override { 5522 return getTarget().hasBFloat16Type(); 5523 } 5524 }; 5525 5526 class AArch64TargetCodeGenInfo : public TargetCodeGenInfo { 5527 public: 5528 AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind) 5529 : TargetCodeGenInfo(std::make_unique<AArch64ABIInfo>(CGT, Kind)) {} 5530 5531 StringRef getARCRetainAutoreleasedReturnValueMarker() const override { 5532 return "mov\tfp, fp\t\t// marker for objc_retainAutoreleaseReturnValue"; 5533 } 5534 5535 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 5536 return 31; 5537 } 5538 5539 bool doesReturnSlotInterfereWithArgs() const override { return false; } 5540 5541 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 5542 CodeGen::CodeGenModule &CGM) const override { 5543 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D); 5544 if (!FD) 5545 return; 5546 5547 const auto *TA = FD->getAttr<TargetAttr>(); 5548 if (TA == nullptr) 5549 return; 5550 5551 ParsedTargetAttr Attr = TA->parse(); 5552 if (Attr.BranchProtection.empty()) 5553 return; 5554 5555 TargetInfo::BranchProtectionInfo BPI; 5556 StringRef Error; 5557 (void)CGM.getTarget().validateBranchProtection(Attr.BranchProtection, 5558 BPI, Error); 5559 assert(Error.empty()); 5560 5561 auto *Fn = cast<llvm::Function>(GV); 5562 static const char *SignReturnAddrStr[] = {"none", "non-leaf", "all"}; 5563 Fn->addFnAttr("sign-return-address", SignReturnAddrStr[static_cast<int>(BPI.SignReturnAddr)]); 5564 5565 if (BPI.SignReturnAddr != LangOptions::SignReturnAddressScopeKind::None) { 5566 Fn->addFnAttr("sign-return-address-key", 5567 BPI.SignKey == LangOptions::SignReturnAddressKeyKind::AKey 5568 ? "a_key" 5569 : "b_key"); 5570 } 5571 5572 Fn->addFnAttr("branch-target-enforcement", 5573 BPI.BranchTargetEnforcement ? "true" : "false"); 5574 } 5575 5576 bool isScalarizableAsmOperand(CodeGen::CodeGenFunction &CGF, 5577 llvm::Type *Ty) const override { 5578 if (CGF.getTarget().hasFeature("ls64")) { 5579 auto *ST = dyn_cast<llvm::StructType>(Ty); 5580 if (ST && ST->getNumElements() == 1) { 5581 auto *AT = dyn_cast<llvm::ArrayType>(ST->getElementType(0)); 5582 if (AT && AT->getNumElements() == 8 && 5583 AT->getElementType()->isIntegerTy(64)) 5584 return true; 5585 } 5586 } 5587 return TargetCodeGenInfo::isScalarizableAsmOperand(CGF, Ty); 5588 } 5589 }; 5590 5591 class WindowsAArch64TargetCodeGenInfo : public AArch64TargetCodeGenInfo { 5592 public: 5593 WindowsAArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind K) 5594 : AArch64TargetCodeGenInfo(CGT, K) {} 5595 5596 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 5597 CodeGen::CodeGenModule &CGM) const override; 5598 5599 void getDependentLibraryOption(llvm::StringRef Lib, 5600 llvm::SmallString<24> &Opt) const override { 5601 Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib); 5602 } 5603 5604 void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value, 5605 llvm::SmallString<32> &Opt) const override { 5606 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\""; 5607 } 5608 }; 5609 5610 void WindowsAArch64TargetCodeGenInfo::setTargetAttributes( 5611 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const { 5612 AArch64TargetCodeGenInfo::setTargetAttributes(D, GV, CGM); 5613 if (GV->isDeclaration()) 5614 return; 5615 addStackProbeTargetAttributes(D, GV, CGM); 5616 } 5617 } 5618 5619 ABIArgInfo AArch64ABIInfo::coerceIllegalVector(QualType Ty) const { 5620 assert(Ty->isVectorType() && "expected vector type!"); 5621 5622 const auto *VT = Ty->castAs<VectorType>(); 5623 if (VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector) { 5624 assert(VT->getElementType()->isBuiltinType() && "expected builtin type!"); 5625 assert(VT->getElementType()->castAs<BuiltinType>()->getKind() == 5626 BuiltinType::UChar && 5627 "unexpected builtin type for SVE predicate!"); 5628 return ABIArgInfo::getDirect(llvm::ScalableVectorType::get( 5629 llvm::Type::getInt1Ty(getVMContext()), 16)); 5630 } 5631 5632 if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector) { 5633 assert(VT->getElementType()->isBuiltinType() && "expected builtin type!"); 5634 5635 const auto *BT = VT->getElementType()->castAs<BuiltinType>(); 5636 llvm::ScalableVectorType *ResType = nullptr; 5637 switch (BT->getKind()) { 5638 default: 5639 llvm_unreachable("unexpected builtin type for SVE vector!"); 5640 case BuiltinType::SChar: 5641 case BuiltinType::UChar: 5642 ResType = llvm::ScalableVectorType::get( 5643 llvm::Type::getInt8Ty(getVMContext()), 16); 5644 break; 5645 case BuiltinType::Short: 5646 case BuiltinType::UShort: 5647 ResType = llvm::ScalableVectorType::get( 5648 llvm::Type::getInt16Ty(getVMContext()), 8); 5649 break; 5650 case BuiltinType::Int: 5651 case BuiltinType::UInt: 5652 ResType = llvm::ScalableVectorType::get( 5653 llvm::Type::getInt32Ty(getVMContext()), 4); 5654 break; 5655 case BuiltinType::Long: 5656 case BuiltinType::ULong: 5657 ResType = llvm::ScalableVectorType::get( 5658 llvm::Type::getInt64Ty(getVMContext()), 2); 5659 break; 5660 case BuiltinType::Half: 5661 ResType = llvm::ScalableVectorType::get( 5662 llvm::Type::getHalfTy(getVMContext()), 8); 5663 break; 5664 case BuiltinType::Float: 5665 ResType = llvm::ScalableVectorType::get( 5666 llvm::Type::getFloatTy(getVMContext()), 4); 5667 break; 5668 case BuiltinType::Double: 5669 ResType = llvm::ScalableVectorType::get( 5670 llvm::Type::getDoubleTy(getVMContext()), 2); 5671 break; 5672 case BuiltinType::BFloat16: 5673 ResType = llvm::ScalableVectorType::get( 5674 llvm::Type::getBFloatTy(getVMContext()), 8); 5675 break; 5676 } 5677 return ABIArgInfo::getDirect(ResType); 5678 } 5679 5680 uint64_t Size = getContext().getTypeSize(Ty); 5681 // Android promotes <2 x i8> to i16, not i32 5682 if (isAndroid() && (Size <= 16)) { 5683 llvm::Type *ResType = llvm::Type::getInt16Ty(getVMContext()); 5684 return ABIArgInfo::getDirect(ResType); 5685 } 5686 if (Size <= 32) { 5687 llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext()); 5688 return ABIArgInfo::getDirect(ResType); 5689 } 5690 if (Size == 64) { 5691 auto *ResType = 5692 llvm::FixedVectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2); 5693 return ABIArgInfo::getDirect(ResType); 5694 } 5695 if (Size == 128) { 5696 auto *ResType = 5697 llvm::FixedVectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4); 5698 return ABIArgInfo::getDirect(ResType); 5699 } 5700 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 5701 } 5702 5703 ABIArgInfo 5704 AArch64ABIInfo::classifyArgumentType(QualType Ty, bool IsVariadic, 5705 unsigned CallingConvention) const { 5706 Ty = useFirstFieldIfTransparentUnion(Ty); 5707 5708 // Handle illegal vector types here. 5709 if (isIllegalVectorType(Ty)) 5710 return coerceIllegalVector(Ty); 5711 5712 if (!isAggregateTypeForABI(Ty)) { 5713 // Treat an enum type as its underlying type. 5714 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 5715 Ty = EnumTy->getDecl()->getIntegerType(); 5716 5717 if (const auto *EIT = Ty->getAs<ExtIntType>()) 5718 if (EIT->getNumBits() > 128) 5719 return getNaturalAlignIndirect(Ty); 5720 5721 return (isPromotableIntegerTypeForABI(Ty) && isDarwinPCS() 5722 ? ABIArgInfo::getExtend(Ty) 5723 : ABIArgInfo::getDirect()); 5724 } 5725 5726 // Structures with either a non-trivial destructor or a non-trivial 5727 // copy constructor are always indirect. 5728 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) { 5729 return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA == 5730 CGCXXABI::RAA_DirectInMemory); 5731 } 5732 5733 // Empty records are always ignored on Darwin, but actually passed in C++ mode 5734 // elsewhere for GNU compatibility. 5735 uint64_t Size = getContext().getTypeSize(Ty); 5736 bool IsEmpty = isEmptyRecord(getContext(), Ty, true); 5737 if (IsEmpty || Size == 0) { 5738 if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS()) 5739 return ABIArgInfo::getIgnore(); 5740 5741 // GNU C mode. The only argument that gets ignored is an empty one with size 5742 // 0. 5743 if (IsEmpty && Size == 0) 5744 return ABIArgInfo::getIgnore(); 5745 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext())); 5746 } 5747 5748 // Homogeneous Floating-point Aggregates (HFAs) need to be expanded. 5749 const Type *Base = nullptr; 5750 uint64_t Members = 0; 5751 bool IsWin64 = Kind == Win64 || CallingConvention == llvm::CallingConv::Win64; 5752 bool IsWinVariadic = IsWin64 && IsVariadic; 5753 // In variadic functions on Windows, all composite types are treated alike, 5754 // no special handling of HFAs/HVAs. 5755 if (!IsWinVariadic && isHomogeneousAggregate(Ty, Base, Members)) { 5756 if (Kind != AArch64ABIInfo::AAPCS) 5757 return ABIArgInfo::getDirect( 5758 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members)); 5759 5760 // For alignment adjusted HFAs, cap the argument alignment to 16, leave it 5761 // default otherwise. 5762 unsigned Align = 5763 getContext().getTypeUnadjustedAlignInChars(Ty).getQuantity(); 5764 unsigned BaseAlign = getContext().getTypeAlignInChars(Base).getQuantity(); 5765 Align = (Align > BaseAlign && Align >= 16) ? 16 : 0; 5766 return ABIArgInfo::getDirect( 5767 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members), 0, 5768 nullptr, true, Align); 5769 } 5770 5771 // Aggregates <= 16 bytes are passed directly in registers or on the stack. 5772 if (Size <= 128) { 5773 // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of 5774 // same size and alignment. 5775 if (getTarget().isRenderScriptTarget()) { 5776 return coerceToIntArray(Ty, getContext(), getVMContext()); 5777 } 5778 unsigned Alignment; 5779 if (Kind == AArch64ABIInfo::AAPCS) { 5780 Alignment = getContext().getTypeUnadjustedAlign(Ty); 5781 Alignment = Alignment < 128 ? 64 : 128; 5782 } else { 5783 Alignment = std::max(getContext().getTypeAlign(Ty), 5784 (unsigned)getTarget().getPointerWidth(0)); 5785 } 5786 Size = llvm::alignTo(Size, Alignment); 5787 5788 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment. 5789 // For aggregates with 16-byte alignment, we use i128. 5790 llvm::Type *BaseTy = llvm::Type::getIntNTy(getVMContext(), Alignment); 5791 return ABIArgInfo::getDirect( 5792 Size == Alignment ? BaseTy 5793 : llvm::ArrayType::get(BaseTy, Size / Alignment)); 5794 } 5795 5796 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 5797 } 5798 5799 ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy, 5800 bool IsVariadic) const { 5801 if (RetTy->isVoidType()) 5802 return ABIArgInfo::getIgnore(); 5803 5804 if (const auto *VT = RetTy->getAs<VectorType>()) { 5805 if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector || 5806 VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector) 5807 return coerceIllegalVector(RetTy); 5808 } 5809 5810 // Large vector types should be returned via memory. 5811 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128) 5812 return getNaturalAlignIndirect(RetTy); 5813 5814 if (!isAggregateTypeForABI(RetTy)) { 5815 // Treat an enum type as its underlying type. 5816 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 5817 RetTy = EnumTy->getDecl()->getIntegerType(); 5818 5819 if (const auto *EIT = RetTy->getAs<ExtIntType>()) 5820 if (EIT->getNumBits() > 128) 5821 return getNaturalAlignIndirect(RetTy); 5822 5823 return (isPromotableIntegerTypeForABI(RetTy) && isDarwinPCS() 5824 ? ABIArgInfo::getExtend(RetTy) 5825 : ABIArgInfo::getDirect()); 5826 } 5827 5828 uint64_t Size = getContext().getTypeSize(RetTy); 5829 if (isEmptyRecord(getContext(), RetTy, true) || Size == 0) 5830 return ABIArgInfo::getIgnore(); 5831 5832 const Type *Base = nullptr; 5833 uint64_t Members = 0; 5834 if (isHomogeneousAggregate(RetTy, Base, Members) && 5835 !(getTarget().getTriple().getArch() == llvm::Triple::aarch64_32 && 5836 IsVariadic)) 5837 // Homogeneous Floating-point Aggregates (HFAs) are returned directly. 5838 return ABIArgInfo::getDirect(); 5839 5840 // Aggregates <= 16 bytes are returned directly in registers or on the stack. 5841 if (Size <= 128) { 5842 // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of 5843 // same size and alignment. 5844 if (getTarget().isRenderScriptTarget()) { 5845 return coerceToIntArray(RetTy, getContext(), getVMContext()); 5846 } 5847 5848 if (Size <= 64 && getDataLayout().isLittleEndian()) { 5849 // Composite types are returned in lower bits of a 64-bit register for LE, 5850 // and in higher bits for BE. However, integer types are always returned 5851 // in lower bits for both LE and BE, and they are not rounded up to 5852 // 64-bits. We can skip rounding up of composite types for LE, but not for 5853 // BE, otherwise composite types will be indistinguishable from integer 5854 // types. 5855 return ABIArgInfo::getDirect( 5856 llvm::IntegerType::get(getVMContext(), Size)); 5857 } 5858 5859 unsigned Alignment = getContext().getTypeAlign(RetTy); 5860 Size = llvm::alignTo(Size, 64); // round up to multiple of 8 bytes 5861 5862 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment. 5863 // For aggregates with 16-byte alignment, we use i128. 5864 if (Alignment < 128 && Size == 128) { 5865 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext()); 5866 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64)); 5867 } 5868 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size)); 5869 } 5870 5871 return getNaturalAlignIndirect(RetTy); 5872 } 5873 5874 /// isIllegalVectorType - check whether the vector type is legal for AArch64. 5875 bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const { 5876 if (const VectorType *VT = Ty->getAs<VectorType>()) { 5877 // Check whether VT is a fixed-length SVE vector. These types are 5878 // represented as scalable vectors in function args/return and must be 5879 // coerced from fixed vectors. 5880 if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector || 5881 VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector) 5882 return true; 5883 5884 // Check whether VT is legal. 5885 unsigned NumElements = VT->getNumElements(); 5886 uint64_t Size = getContext().getTypeSize(VT); 5887 // NumElements should be power of 2. 5888 if (!llvm::isPowerOf2_32(NumElements)) 5889 return true; 5890 5891 // arm64_32 has to be compatible with the ARM logic here, which allows huge 5892 // vectors for some reason. 5893 llvm::Triple Triple = getTarget().getTriple(); 5894 if (Triple.getArch() == llvm::Triple::aarch64_32 && 5895 Triple.isOSBinFormatMachO()) 5896 return Size <= 32; 5897 5898 return Size != 64 && (Size != 128 || NumElements == 1); 5899 } 5900 return false; 5901 } 5902 5903 bool AArch64ABIInfo::isLegalVectorTypeForSwift(CharUnits totalSize, 5904 llvm::Type *eltTy, 5905 unsigned elts) const { 5906 if (!llvm::isPowerOf2_32(elts)) 5907 return false; 5908 if (totalSize.getQuantity() != 8 && 5909 (totalSize.getQuantity() != 16 || elts == 1)) 5910 return false; 5911 return true; 5912 } 5913 5914 bool AArch64ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const { 5915 // Homogeneous aggregates for AAPCS64 must have base types of a floating 5916 // point type or a short-vector type. This is the same as the 32-bit ABI, 5917 // but with the difference that any floating-point type is allowed, 5918 // including __fp16. 5919 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) { 5920 if (BT->isFloatingPoint()) 5921 return true; 5922 } else if (const VectorType *VT = Ty->getAs<VectorType>()) { 5923 unsigned VecSize = getContext().getTypeSize(VT); 5924 if (VecSize == 64 || VecSize == 128) 5925 return true; 5926 } 5927 return false; 5928 } 5929 5930 bool AArch64ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base, 5931 uint64_t Members) const { 5932 return Members <= 4; 5933 } 5934 5935 Address AArch64ABIInfo::EmitAAPCSVAArg(Address VAListAddr, QualType Ty, 5936 CodeGenFunction &CGF) const { 5937 ABIArgInfo AI = classifyArgumentType(Ty, /*IsVariadic=*/true, 5938 CGF.CurFnInfo->getCallingConvention()); 5939 bool IsIndirect = AI.isIndirect(); 5940 5941 llvm::Type *BaseTy = CGF.ConvertType(Ty); 5942 if (IsIndirect) 5943 BaseTy = llvm::PointerType::getUnqual(BaseTy); 5944 else if (AI.getCoerceToType()) 5945 BaseTy = AI.getCoerceToType(); 5946 5947 unsigned NumRegs = 1; 5948 if (llvm::ArrayType *ArrTy = dyn_cast<llvm::ArrayType>(BaseTy)) { 5949 BaseTy = ArrTy->getElementType(); 5950 NumRegs = ArrTy->getNumElements(); 5951 } 5952 bool IsFPR = BaseTy->isFloatingPointTy() || BaseTy->isVectorTy(); 5953 5954 // The AArch64 va_list type and handling is specified in the Procedure Call 5955 // Standard, section B.4: 5956 // 5957 // struct { 5958 // void *__stack; 5959 // void *__gr_top; 5960 // void *__vr_top; 5961 // int __gr_offs; 5962 // int __vr_offs; 5963 // }; 5964 5965 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg"); 5966 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg"); 5967 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack"); 5968 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end"); 5969 5970 CharUnits TySize = getContext().getTypeSizeInChars(Ty); 5971 CharUnits TyAlign = getContext().getTypeUnadjustedAlignInChars(Ty); 5972 5973 Address reg_offs_p = Address::invalid(); 5974 llvm::Value *reg_offs = nullptr; 5975 int reg_top_index; 5976 int RegSize = IsIndirect ? 8 : TySize.getQuantity(); 5977 if (!IsFPR) { 5978 // 3 is the field number of __gr_offs 5979 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 3, "gr_offs_p"); 5980 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs"); 5981 reg_top_index = 1; // field number for __gr_top 5982 RegSize = llvm::alignTo(RegSize, 8); 5983 } else { 5984 // 4 is the field number of __vr_offs. 5985 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 4, "vr_offs_p"); 5986 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs"); 5987 reg_top_index = 2; // field number for __vr_top 5988 RegSize = 16 * NumRegs; 5989 } 5990 5991 //======================================= 5992 // Find out where argument was passed 5993 //======================================= 5994 5995 // If reg_offs >= 0 we're already using the stack for this type of 5996 // argument. We don't want to keep updating reg_offs (in case it overflows, 5997 // though anyone passing 2GB of arguments, each at most 16 bytes, deserves 5998 // whatever they get). 5999 llvm::Value *UsingStack = nullptr; 6000 UsingStack = CGF.Builder.CreateICmpSGE( 6001 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0)); 6002 6003 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock); 6004 6005 // Otherwise, at least some kind of argument could go in these registers, the 6006 // question is whether this particular type is too big. 6007 CGF.EmitBlock(MaybeRegBlock); 6008 6009 // Integer arguments may need to correct register alignment (for example a 6010 // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we 6011 // align __gr_offs to calculate the potential address. 6012 if (!IsFPR && !IsIndirect && TyAlign.getQuantity() > 8) { 6013 int Align = TyAlign.getQuantity(); 6014 6015 reg_offs = CGF.Builder.CreateAdd( 6016 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1), 6017 "align_regoffs"); 6018 reg_offs = CGF.Builder.CreateAnd( 6019 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align), 6020 "aligned_regoffs"); 6021 } 6022 6023 // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list. 6024 // The fact that this is done unconditionally reflects the fact that 6025 // allocating an argument to the stack also uses up all the remaining 6026 // registers of the appropriate kind. 6027 llvm::Value *NewOffset = nullptr; 6028 NewOffset = CGF.Builder.CreateAdd( 6029 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs"); 6030 CGF.Builder.CreateStore(NewOffset, reg_offs_p); 6031 6032 // Now we're in a position to decide whether this argument really was in 6033 // registers or not. 6034 llvm::Value *InRegs = nullptr; 6035 InRegs = CGF.Builder.CreateICmpSLE( 6036 NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg"); 6037 6038 CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock); 6039 6040 //======================================= 6041 // Argument was in registers 6042 //======================================= 6043 6044 // Now we emit the code for if the argument was originally passed in 6045 // registers. First start the appropriate block: 6046 CGF.EmitBlock(InRegBlock); 6047 6048 llvm::Value *reg_top = nullptr; 6049 Address reg_top_p = 6050 CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index, "reg_top_p"); 6051 reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top"); 6052 Address BaseAddr(CGF.Builder.CreateInBoundsGEP(CGF.Int8Ty, reg_top, reg_offs), 6053 CharUnits::fromQuantity(IsFPR ? 16 : 8)); 6054 Address RegAddr = Address::invalid(); 6055 llvm::Type *MemTy = CGF.ConvertTypeForMem(Ty); 6056 6057 if (IsIndirect) { 6058 // If it's been passed indirectly (actually a struct), whatever we find from 6059 // stored registers or on the stack will actually be a struct **. 6060 MemTy = llvm::PointerType::getUnqual(MemTy); 6061 } 6062 6063 const Type *Base = nullptr; 6064 uint64_t NumMembers = 0; 6065 bool IsHFA = isHomogeneousAggregate(Ty, Base, NumMembers); 6066 if (IsHFA && NumMembers > 1) { 6067 // Homogeneous aggregates passed in registers will have their elements split 6068 // and stored 16-bytes apart regardless of size (they're notionally in qN, 6069 // qN+1, ...). We reload and store into a temporary local variable 6070 // contiguously. 6071 assert(!IsIndirect && "Homogeneous aggregates should be passed directly"); 6072 auto BaseTyInfo = getContext().getTypeInfoInChars(QualType(Base, 0)); 6073 llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0)); 6074 llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers); 6075 Address Tmp = CGF.CreateTempAlloca(HFATy, 6076 std::max(TyAlign, BaseTyInfo.Align)); 6077 6078 // On big-endian platforms, the value will be right-aligned in its slot. 6079 int Offset = 0; 6080 if (CGF.CGM.getDataLayout().isBigEndian() && 6081 BaseTyInfo.Width.getQuantity() < 16) 6082 Offset = 16 - BaseTyInfo.Width.getQuantity(); 6083 6084 for (unsigned i = 0; i < NumMembers; ++i) { 6085 CharUnits BaseOffset = CharUnits::fromQuantity(16 * i + Offset); 6086 Address LoadAddr = 6087 CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, BaseOffset); 6088 LoadAddr = CGF.Builder.CreateElementBitCast(LoadAddr, BaseTy); 6089 6090 Address StoreAddr = CGF.Builder.CreateConstArrayGEP(Tmp, i); 6091 6092 llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr); 6093 CGF.Builder.CreateStore(Elem, StoreAddr); 6094 } 6095 6096 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, MemTy); 6097 } else { 6098 // Otherwise the object is contiguous in memory. 6099 6100 // It might be right-aligned in its slot. 6101 CharUnits SlotSize = BaseAddr.getAlignment(); 6102 if (CGF.CGM.getDataLayout().isBigEndian() && !IsIndirect && 6103 (IsHFA || !isAggregateTypeForABI(Ty)) && 6104 TySize < SlotSize) { 6105 CharUnits Offset = SlotSize - TySize; 6106 BaseAddr = CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, Offset); 6107 } 6108 6109 RegAddr = CGF.Builder.CreateElementBitCast(BaseAddr, MemTy); 6110 } 6111 6112 CGF.EmitBranch(ContBlock); 6113 6114 //======================================= 6115 // Argument was on the stack 6116 //======================================= 6117 CGF.EmitBlock(OnStackBlock); 6118 6119 Address stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "stack_p"); 6120 llvm::Value *OnStackPtr = CGF.Builder.CreateLoad(stack_p, "stack"); 6121 6122 // Again, stack arguments may need realignment. In this case both integer and 6123 // floating-point ones might be affected. 6124 if (!IsIndirect && TyAlign.getQuantity() > 8) { 6125 int Align = TyAlign.getQuantity(); 6126 6127 OnStackPtr = CGF.Builder.CreatePtrToInt(OnStackPtr, CGF.Int64Ty); 6128 6129 OnStackPtr = CGF.Builder.CreateAdd( 6130 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1), 6131 "align_stack"); 6132 OnStackPtr = CGF.Builder.CreateAnd( 6133 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, -Align), 6134 "align_stack"); 6135 6136 OnStackPtr = CGF.Builder.CreateIntToPtr(OnStackPtr, CGF.Int8PtrTy); 6137 } 6138 Address OnStackAddr(OnStackPtr, 6139 std::max(CharUnits::fromQuantity(8), TyAlign)); 6140 6141 // All stack slots are multiples of 8 bytes. 6142 CharUnits StackSlotSize = CharUnits::fromQuantity(8); 6143 CharUnits StackSize; 6144 if (IsIndirect) 6145 StackSize = StackSlotSize; 6146 else 6147 StackSize = TySize.alignTo(StackSlotSize); 6148 6149 llvm::Value *StackSizeC = CGF.Builder.getSize(StackSize); 6150 llvm::Value *NewStack = CGF.Builder.CreateInBoundsGEP( 6151 CGF.Int8Ty, OnStackPtr, StackSizeC, "new_stack"); 6152 6153 // Write the new value of __stack for the next call to va_arg 6154 CGF.Builder.CreateStore(NewStack, stack_p); 6155 6156 if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) && 6157 TySize < StackSlotSize) { 6158 CharUnits Offset = StackSlotSize - TySize; 6159 OnStackAddr = CGF.Builder.CreateConstInBoundsByteGEP(OnStackAddr, Offset); 6160 } 6161 6162 OnStackAddr = CGF.Builder.CreateElementBitCast(OnStackAddr, MemTy); 6163 6164 CGF.EmitBranch(ContBlock); 6165 6166 //======================================= 6167 // Tidy up 6168 //======================================= 6169 CGF.EmitBlock(ContBlock); 6170 6171 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, 6172 OnStackAddr, OnStackBlock, "vaargs.addr"); 6173 6174 if (IsIndirect) 6175 return Address(CGF.Builder.CreateLoad(ResAddr, "vaarg.addr"), 6176 TyAlign); 6177 6178 return ResAddr; 6179 } 6180 6181 Address AArch64ABIInfo::EmitDarwinVAArg(Address VAListAddr, QualType Ty, 6182 CodeGenFunction &CGF) const { 6183 // The backend's lowering doesn't support va_arg for aggregates or 6184 // illegal vector types. Lower VAArg here for these cases and use 6185 // the LLVM va_arg instruction for everything else. 6186 if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty)) 6187 return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect()); 6188 6189 uint64_t PointerSize = getTarget().getPointerWidth(0) / 8; 6190 CharUnits SlotSize = CharUnits::fromQuantity(PointerSize); 6191 6192 // Empty records are ignored for parameter passing purposes. 6193 if (isEmptyRecord(getContext(), Ty, true)) { 6194 Address Addr(CGF.Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize); 6195 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty)); 6196 return Addr; 6197 } 6198 6199 // The size of the actual thing passed, which might end up just 6200 // being a pointer for indirect types. 6201 auto TyInfo = getContext().getTypeInfoInChars(Ty); 6202 6203 // Arguments bigger than 16 bytes which aren't homogeneous 6204 // aggregates should be passed indirectly. 6205 bool IsIndirect = false; 6206 if (TyInfo.Width.getQuantity() > 16) { 6207 const Type *Base = nullptr; 6208 uint64_t Members = 0; 6209 IsIndirect = !isHomogeneousAggregate(Ty, Base, Members); 6210 } 6211 6212 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, 6213 TyInfo, SlotSize, /*AllowHigherAlign*/ true); 6214 } 6215 6216 Address AArch64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr, 6217 QualType Ty) const { 6218 bool IsIndirect = false; 6219 6220 // Composites larger than 16 bytes are passed by reference. 6221 if (isAggregateTypeForABI(Ty) && getContext().getTypeSize(Ty) > 128) 6222 IsIndirect = true; 6223 6224 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, 6225 CGF.getContext().getTypeInfoInChars(Ty), 6226 CharUnits::fromQuantity(8), 6227 /*allowHigherAlign*/ false); 6228 } 6229 6230 //===----------------------------------------------------------------------===// 6231 // ARM ABI Implementation 6232 //===----------------------------------------------------------------------===// 6233 6234 namespace { 6235 6236 class ARMABIInfo : public SwiftABIInfo { 6237 public: 6238 enum ABIKind { 6239 APCS = 0, 6240 AAPCS = 1, 6241 AAPCS_VFP = 2, 6242 AAPCS16_VFP = 3, 6243 }; 6244 6245 private: 6246 ABIKind Kind; 6247 bool IsFloatABISoftFP; 6248 6249 public: 6250 ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind) 6251 : SwiftABIInfo(CGT), Kind(_Kind) { 6252 setCCs(); 6253 IsFloatABISoftFP = CGT.getCodeGenOpts().FloatABI == "softfp" || 6254 CGT.getCodeGenOpts().FloatABI == ""; // default 6255 } 6256 6257 bool isEABI() const { 6258 switch (getTarget().getTriple().getEnvironment()) { 6259 case llvm::Triple::Android: 6260 case llvm::Triple::EABI: 6261 case llvm::Triple::EABIHF: 6262 case llvm::Triple::GNUEABI: 6263 case llvm::Triple::GNUEABIHF: 6264 case llvm::Triple::MuslEABI: 6265 case llvm::Triple::MuslEABIHF: 6266 return true; 6267 default: 6268 return false; 6269 } 6270 } 6271 6272 bool isEABIHF() const { 6273 switch (getTarget().getTriple().getEnvironment()) { 6274 case llvm::Triple::EABIHF: 6275 case llvm::Triple::GNUEABIHF: 6276 case llvm::Triple::MuslEABIHF: 6277 return true; 6278 default: 6279 return false; 6280 } 6281 } 6282 6283 ABIKind getABIKind() const { return Kind; } 6284 6285 bool allowBFloatArgsAndRet() const override { 6286 return !IsFloatABISoftFP && getTarget().hasBFloat16Type(); 6287 } 6288 6289 private: 6290 ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic, 6291 unsigned functionCallConv) const; 6292 ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic, 6293 unsigned functionCallConv) const; 6294 ABIArgInfo classifyHomogeneousAggregate(QualType Ty, const Type *Base, 6295 uint64_t Members) const; 6296 ABIArgInfo coerceIllegalVector(QualType Ty) const; 6297 bool isIllegalVectorType(QualType Ty) const; 6298 bool containsAnyFP16Vectors(QualType Ty) const; 6299 6300 bool isHomogeneousAggregateBaseType(QualType Ty) const override; 6301 bool isHomogeneousAggregateSmallEnough(const Type *Ty, 6302 uint64_t Members) const override; 6303 6304 bool isEffectivelyAAPCS_VFP(unsigned callConvention, bool acceptHalf) const; 6305 6306 void computeInfo(CGFunctionInfo &FI) const override; 6307 6308 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 6309 QualType Ty) const override; 6310 6311 llvm::CallingConv::ID getLLVMDefaultCC() const; 6312 llvm::CallingConv::ID getABIDefaultCC() const; 6313 void setCCs(); 6314 6315 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars, 6316 bool asReturnValue) const override { 6317 return occupiesMoreThan(CGT, scalars, /*total*/ 4); 6318 } 6319 bool isSwiftErrorInRegister() const override { 6320 return true; 6321 } 6322 bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy, 6323 unsigned elts) const override; 6324 }; 6325 6326 class ARMTargetCodeGenInfo : public TargetCodeGenInfo { 6327 public: 6328 ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K) 6329 : TargetCodeGenInfo(std::make_unique<ARMABIInfo>(CGT, K)) {} 6330 6331 const ARMABIInfo &getABIInfo() const { 6332 return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo()); 6333 } 6334 6335 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 6336 return 13; 6337 } 6338 6339 StringRef getARCRetainAutoreleasedReturnValueMarker() const override { 6340 return "mov\tr7, r7\t\t// marker for objc_retainAutoreleaseReturnValue"; 6341 } 6342 6343 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 6344 llvm::Value *Address) const override { 6345 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4); 6346 6347 // 0-15 are the 16 integer registers. 6348 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15); 6349 return false; 6350 } 6351 6352 unsigned getSizeOfUnwindException() const override { 6353 if (getABIInfo().isEABI()) return 88; 6354 return TargetCodeGenInfo::getSizeOfUnwindException(); 6355 } 6356 6357 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 6358 CodeGen::CodeGenModule &CGM) const override { 6359 if (GV->isDeclaration()) 6360 return; 6361 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D); 6362 if (!FD) 6363 return; 6364 6365 const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>(); 6366 if (!Attr) 6367 return; 6368 6369 const char *Kind; 6370 switch (Attr->getInterrupt()) { 6371 case ARMInterruptAttr::Generic: Kind = ""; break; 6372 case ARMInterruptAttr::IRQ: Kind = "IRQ"; break; 6373 case ARMInterruptAttr::FIQ: Kind = "FIQ"; break; 6374 case ARMInterruptAttr::SWI: Kind = "SWI"; break; 6375 case ARMInterruptAttr::ABORT: Kind = "ABORT"; break; 6376 case ARMInterruptAttr::UNDEF: Kind = "UNDEF"; break; 6377 } 6378 6379 llvm::Function *Fn = cast<llvm::Function>(GV); 6380 6381 Fn->addFnAttr("interrupt", Kind); 6382 6383 ARMABIInfo::ABIKind ABI = cast<ARMABIInfo>(getABIInfo()).getABIKind(); 6384 if (ABI == ARMABIInfo::APCS) 6385 return; 6386 6387 // AAPCS guarantees that sp will be 8-byte aligned on any public interface, 6388 // however this is not necessarily true on taking any interrupt. Instruct 6389 // the backend to perform a realignment as part of the function prologue. 6390 llvm::AttrBuilder B; 6391 B.addStackAlignmentAttr(8); 6392 Fn->addFnAttrs(B); 6393 } 6394 }; 6395 6396 class WindowsARMTargetCodeGenInfo : public ARMTargetCodeGenInfo { 6397 public: 6398 WindowsARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K) 6399 : ARMTargetCodeGenInfo(CGT, K) {} 6400 6401 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 6402 CodeGen::CodeGenModule &CGM) const override; 6403 6404 void getDependentLibraryOption(llvm::StringRef Lib, 6405 llvm::SmallString<24> &Opt) const override { 6406 Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib); 6407 } 6408 6409 void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value, 6410 llvm::SmallString<32> &Opt) const override { 6411 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\""; 6412 } 6413 }; 6414 6415 void WindowsARMTargetCodeGenInfo::setTargetAttributes( 6416 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const { 6417 ARMTargetCodeGenInfo::setTargetAttributes(D, GV, CGM); 6418 if (GV->isDeclaration()) 6419 return; 6420 addStackProbeTargetAttributes(D, GV, CGM); 6421 } 6422 } 6423 6424 void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const { 6425 if (!::classifyReturnType(getCXXABI(), FI, *this)) 6426 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), FI.isVariadic(), 6427 FI.getCallingConvention()); 6428 6429 for (auto &I : FI.arguments()) 6430 I.info = classifyArgumentType(I.type, FI.isVariadic(), 6431 FI.getCallingConvention()); 6432 6433 6434 // Always honor user-specified calling convention. 6435 if (FI.getCallingConvention() != llvm::CallingConv::C) 6436 return; 6437 6438 llvm::CallingConv::ID cc = getRuntimeCC(); 6439 if (cc != llvm::CallingConv::C) 6440 FI.setEffectiveCallingConvention(cc); 6441 } 6442 6443 /// Return the default calling convention that LLVM will use. 6444 llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const { 6445 // The default calling convention that LLVM will infer. 6446 if (isEABIHF() || getTarget().getTriple().isWatchABI()) 6447 return llvm::CallingConv::ARM_AAPCS_VFP; 6448 else if (isEABI()) 6449 return llvm::CallingConv::ARM_AAPCS; 6450 else 6451 return llvm::CallingConv::ARM_APCS; 6452 } 6453 6454 /// Return the calling convention that our ABI would like us to use 6455 /// as the C calling convention. 6456 llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const { 6457 switch (getABIKind()) { 6458 case APCS: return llvm::CallingConv::ARM_APCS; 6459 case AAPCS: return llvm::CallingConv::ARM_AAPCS; 6460 case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP; 6461 case AAPCS16_VFP: return llvm::CallingConv::ARM_AAPCS_VFP; 6462 } 6463 llvm_unreachable("bad ABI kind"); 6464 } 6465 6466 void ARMABIInfo::setCCs() { 6467 assert(getRuntimeCC() == llvm::CallingConv::C); 6468 6469 // Don't muddy up the IR with a ton of explicit annotations if 6470 // they'd just match what LLVM will infer from the triple. 6471 llvm::CallingConv::ID abiCC = getABIDefaultCC(); 6472 if (abiCC != getLLVMDefaultCC()) 6473 RuntimeCC = abiCC; 6474 } 6475 6476 ABIArgInfo ARMABIInfo::coerceIllegalVector(QualType Ty) const { 6477 uint64_t Size = getContext().getTypeSize(Ty); 6478 if (Size <= 32) { 6479 llvm::Type *ResType = 6480 llvm::Type::getInt32Ty(getVMContext()); 6481 return ABIArgInfo::getDirect(ResType); 6482 } 6483 if (Size == 64 || Size == 128) { 6484 auto *ResType = llvm::FixedVectorType::get( 6485 llvm::Type::getInt32Ty(getVMContext()), Size / 32); 6486 return ABIArgInfo::getDirect(ResType); 6487 } 6488 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 6489 } 6490 6491 ABIArgInfo ARMABIInfo::classifyHomogeneousAggregate(QualType Ty, 6492 const Type *Base, 6493 uint64_t Members) const { 6494 assert(Base && "Base class should be set for homogeneous aggregate"); 6495 // Base can be a floating-point or a vector. 6496 if (const VectorType *VT = Base->getAs<VectorType>()) { 6497 // FP16 vectors should be converted to integer vectors 6498 if (!getTarget().hasLegalHalfType() && containsAnyFP16Vectors(Ty)) { 6499 uint64_t Size = getContext().getTypeSize(VT); 6500 auto *NewVecTy = llvm::FixedVectorType::get( 6501 llvm::Type::getInt32Ty(getVMContext()), Size / 32); 6502 llvm::Type *Ty = llvm::ArrayType::get(NewVecTy, Members); 6503 return ABIArgInfo::getDirect(Ty, 0, nullptr, false); 6504 } 6505 } 6506 unsigned Align = 0; 6507 if (getABIKind() == ARMABIInfo::AAPCS || 6508 getABIKind() == ARMABIInfo::AAPCS_VFP) { 6509 // For alignment adjusted HFAs, cap the argument alignment to 8, leave it 6510 // default otherwise. 6511 Align = getContext().getTypeUnadjustedAlignInChars(Ty).getQuantity(); 6512 unsigned BaseAlign = getContext().getTypeAlignInChars(Base).getQuantity(); 6513 Align = (Align > BaseAlign && Align >= 8) ? 8 : 0; 6514 } 6515 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false, Align); 6516 } 6517 6518 ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty, bool isVariadic, 6519 unsigned functionCallConv) const { 6520 // 6.1.2.1 The following argument types are VFP CPRCs: 6521 // A single-precision floating-point type (including promoted 6522 // half-precision types); A double-precision floating-point type; 6523 // A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate 6524 // with a Base Type of a single- or double-precision floating-point type, 6525 // 64-bit containerized vectors or 128-bit containerized vectors with one 6526 // to four Elements. 6527 // Variadic functions should always marshal to the base standard. 6528 bool IsAAPCS_VFP = 6529 !isVariadic && isEffectivelyAAPCS_VFP(functionCallConv, /* AAPCS16 */ false); 6530 6531 Ty = useFirstFieldIfTransparentUnion(Ty); 6532 6533 // Handle illegal vector types here. 6534 if (isIllegalVectorType(Ty)) 6535 return coerceIllegalVector(Ty); 6536 6537 if (!isAggregateTypeForABI(Ty)) { 6538 // Treat an enum type as its underlying type. 6539 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) { 6540 Ty = EnumTy->getDecl()->getIntegerType(); 6541 } 6542 6543 if (const auto *EIT = Ty->getAs<ExtIntType>()) 6544 if (EIT->getNumBits() > 64) 6545 return getNaturalAlignIndirect(Ty, /*ByVal=*/true); 6546 6547 return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty) 6548 : ABIArgInfo::getDirect()); 6549 } 6550 6551 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) { 6552 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 6553 } 6554 6555 // Ignore empty records. 6556 if (isEmptyRecord(getContext(), Ty, true)) 6557 return ABIArgInfo::getIgnore(); 6558 6559 if (IsAAPCS_VFP) { 6560 // Homogeneous Aggregates need to be expanded when we can fit the aggregate 6561 // into VFP registers. 6562 const Type *Base = nullptr; 6563 uint64_t Members = 0; 6564 if (isHomogeneousAggregate(Ty, Base, Members)) 6565 return classifyHomogeneousAggregate(Ty, Base, Members); 6566 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) { 6567 // WatchOS does have homogeneous aggregates. Note that we intentionally use 6568 // this convention even for a variadic function: the backend will use GPRs 6569 // if needed. 6570 const Type *Base = nullptr; 6571 uint64_t Members = 0; 6572 if (isHomogeneousAggregate(Ty, Base, Members)) { 6573 assert(Base && Members <= 4 && "unexpected homogeneous aggregate"); 6574 llvm::Type *Ty = 6575 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members); 6576 return ABIArgInfo::getDirect(Ty, 0, nullptr, false); 6577 } 6578 } 6579 6580 if (getABIKind() == ARMABIInfo::AAPCS16_VFP && 6581 getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(16)) { 6582 // WatchOS is adopting the 64-bit AAPCS rule on composite types: if they're 6583 // bigger than 128-bits, they get placed in space allocated by the caller, 6584 // and a pointer is passed. 6585 return ABIArgInfo::getIndirect( 6586 CharUnits::fromQuantity(getContext().getTypeAlign(Ty) / 8), false); 6587 } 6588 6589 // Support byval for ARM. 6590 // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at 6591 // most 8-byte. We realign the indirect argument if type alignment is bigger 6592 // than ABI alignment. 6593 uint64_t ABIAlign = 4; 6594 uint64_t TyAlign; 6595 if (getABIKind() == ARMABIInfo::AAPCS_VFP || 6596 getABIKind() == ARMABIInfo::AAPCS) { 6597 TyAlign = getContext().getTypeUnadjustedAlignInChars(Ty).getQuantity(); 6598 ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8); 6599 } else { 6600 TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity(); 6601 } 6602 if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) { 6603 assert(getABIKind() != ARMABIInfo::AAPCS16_VFP && "unexpected byval"); 6604 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign), 6605 /*ByVal=*/true, 6606 /*Realign=*/TyAlign > ABIAlign); 6607 } 6608 6609 // On RenderScript, coerce Aggregates <= 64 bytes to an integer array of 6610 // same size and alignment. 6611 if (getTarget().isRenderScriptTarget()) { 6612 return coerceToIntArray(Ty, getContext(), getVMContext()); 6613 } 6614 6615 // Otherwise, pass by coercing to a structure of the appropriate size. 6616 llvm::Type* ElemTy; 6617 unsigned SizeRegs; 6618 // FIXME: Try to match the types of the arguments more accurately where 6619 // we can. 6620 if (TyAlign <= 4) { 6621 ElemTy = llvm::Type::getInt32Ty(getVMContext()); 6622 SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32; 6623 } else { 6624 ElemTy = llvm::Type::getInt64Ty(getVMContext()); 6625 SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64; 6626 } 6627 6628 return ABIArgInfo::getDirect(llvm::ArrayType::get(ElemTy, SizeRegs)); 6629 } 6630 6631 static bool isIntegerLikeType(QualType Ty, ASTContext &Context, 6632 llvm::LLVMContext &VMContext) { 6633 // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure 6634 // is called integer-like if its size is less than or equal to one word, and 6635 // the offset of each of its addressable sub-fields is zero. 6636 6637 uint64_t Size = Context.getTypeSize(Ty); 6638 6639 // Check that the type fits in a word. 6640 if (Size > 32) 6641 return false; 6642 6643 // FIXME: Handle vector types! 6644 if (Ty->isVectorType()) 6645 return false; 6646 6647 // Float types are never treated as "integer like". 6648 if (Ty->isRealFloatingType()) 6649 return false; 6650 6651 // If this is a builtin or pointer type then it is ok. 6652 if (Ty->getAs<BuiltinType>() || Ty->isPointerType()) 6653 return true; 6654 6655 // Small complex integer types are "integer like". 6656 if (const ComplexType *CT = Ty->getAs<ComplexType>()) 6657 return isIntegerLikeType(CT->getElementType(), Context, VMContext); 6658 6659 // Single element and zero sized arrays should be allowed, by the definition 6660 // above, but they are not. 6661 6662 // Otherwise, it must be a record type. 6663 const RecordType *RT = Ty->getAs<RecordType>(); 6664 if (!RT) return false; 6665 6666 // Ignore records with flexible arrays. 6667 const RecordDecl *RD = RT->getDecl(); 6668 if (RD->hasFlexibleArrayMember()) 6669 return false; 6670 6671 // Check that all sub-fields are at offset 0, and are themselves "integer 6672 // like". 6673 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); 6674 6675 bool HadField = false; 6676 unsigned idx = 0; 6677 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 6678 i != e; ++i, ++idx) { 6679 const FieldDecl *FD = *i; 6680 6681 // Bit-fields are not addressable, we only need to verify they are "integer 6682 // like". We still have to disallow a subsequent non-bitfield, for example: 6683 // struct { int : 0; int x } 6684 // is non-integer like according to gcc. 6685 if (FD->isBitField()) { 6686 if (!RD->isUnion()) 6687 HadField = true; 6688 6689 if (!isIntegerLikeType(FD->getType(), Context, VMContext)) 6690 return false; 6691 6692 continue; 6693 } 6694 6695 // Check if this field is at offset 0. 6696 if (Layout.getFieldOffset(idx) != 0) 6697 return false; 6698 6699 if (!isIntegerLikeType(FD->getType(), Context, VMContext)) 6700 return false; 6701 6702 // Only allow at most one field in a structure. This doesn't match the 6703 // wording above, but follows gcc in situations with a field following an 6704 // empty structure. 6705 if (!RD->isUnion()) { 6706 if (HadField) 6707 return false; 6708 6709 HadField = true; 6710 } 6711 } 6712 6713 return true; 6714 } 6715 6716 ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy, bool isVariadic, 6717 unsigned functionCallConv) const { 6718 6719 // Variadic functions should always marshal to the base standard. 6720 bool IsAAPCS_VFP = 6721 !isVariadic && isEffectivelyAAPCS_VFP(functionCallConv, /* AAPCS16 */ true); 6722 6723 if (RetTy->isVoidType()) 6724 return ABIArgInfo::getIgnore(); 6725 6726 if (const VectorType *VT = RetTy->getAs<VectorType>()) { 6727 // Large vector types should be returned via memory. 6728 if (getContext().getTypeSize(RetTy) > 128) 6729 return getNaturalAlignIndirect(RetTy); 6730 // TODO: FP16/BF16 vectors should be converted to integer vectors 6731 // This check is similar to isIllegalVectorType - refactor? 6732 if ((!getTarget().hasLegalHalfType() && 6733 (VT->getElementType()->isFloat16Type() || 6734 VT->getElementType()->isHalfType())) || 6735 (IsFloatABISoftFP && 6736 VT->getElementType()->isBFloat16Type())) 6737 return coerceIllegalVector(RetTy); 6738 } 6739 6740 if (!isAggregateTypeForABI(RetTy)) { 6741 // Treat an enum type as its underlying type. 6742 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 6743 RetTy = EnumTy->getDecl()->getIntegerType(); 6744 6745 if (const auto *EIT = RetTy->getAs<ExtIntType>()) 6746 if (EIT->getNumBits() > 64) 6747 return getNaturalAlignIndirect(RetTy, /*ByVal=*/false); 6748 6749 return isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy) 6750 : ABIArgInfo::getDirect(); 6751 } 6752 6753 // Are we following APCS? 6754 if (getABIKind() == APCS) { 6755 if (isEmptyRecord(getContext(), RetTy, false)) 6756 return ABIArgInfo::getIgnore(); 6757 6758 // Complex types are all returned as packed integers. 6759 // 6760 // FIXME: Consider using 2 x vector types if the back end handles them 6761 // correctly. 6762 if (RetTy->isAnyComplexType()) 6763 return ABIArgInfo::getDirect(llvm::IntegerType::get( 6764 getVMContext(), getContext().getTypeSize(RetTy))); 6765 6766 // Integer like structures are returned in r0. 6767 if (isIntegerLikeType(RetTy, getContext(), getVMContext())) { 6768 // Return in the smallest viable integer type. 6769 uint64_t Size = getContext().getTypeSize(RetTy); 6770 if (Size <= 8) 6771 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext())); 6772 if (Size <= 16) 6773 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext())); 6774 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext())); 6775 } 6776 6777 // Otherwise return in memory. 6778 return getNaturalAlignIndirect(RetTy); 6779 } 6780 6781 // Otherwise this is an AAPCS variant. 6782 6783 if (isEmptyRecord(getContext(), RetTy, true)) 6784 return ABIArgInfo::getIgnore(); 6785 6786 // Check for homogeneous aggregates with AAPCS-VFP. 6787 if (IsAAPCS_VFP) { 6788 const Type *Base = nullptr; 6789 uint64_t Members = 0; 6790 if (isHomogeneousAggregate(RetTy, Base, Members)) 6791 return classifyHomogeneousAggregate(RetTy, Base, Members); 6792 } 6793 6794 // Aggregates <= 4 bytes are returned in r0; other aggregates 6795 // are returned indirectly. 6796 uint64_t Size = getContext().getTypeSize(RetTy); 6797 if (Size <= 32) { 6798 // On RenderScript, coerce Aggregates <= 4 bytes to an integer array of 6799 // same size and alignment. 6800 if (getTarget().isRenderScriptTarget()) { 6801 return coerceToIntArray(RetTy, getContext(), getVMContext()); 6802 } 6803 if (getDataLayout().isBigEndian()) 6804 // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4) 6805 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext())); 6806 6807 // Return in the smallest viable integer type. 6808 if (Size <= 8) 6809 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext())); 6810 if (Size <= 16) 6811 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext())); 6812 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext())); 6813 } else if (Size <= 128 && getABIKind() == AAPCS16_VFP) { 6814 llvm::Type *Int32Ty = llvm::Type::getInt32Ty(getVMContext()); 6815 llvm::Type *CoerceTy = 6816 llvm::ArrayType::get(Int32Ty, llvm::alignTo(Size, 32) / 32); 6817 return ABIArgInfo::getDirect(CoerceTy); 6818 } 6819 6820 return getNaturalAlignIndirect(RetTy); 6821 } 6822 6823 /// isIllegalVector - check whether Ty is an illegal vector type. 6824 bool ARMABIInfo::isIllegalVectorType(QualType Ty) const { 6825 if (const VectorType *VT = Ty->getAs<VectorType> ()) { 6826 // On targets that don't support half, fp16 or bfloat, they are expanded 6827 // into float, and we don't want the ABI to depend on whether or not they 6828 // are supported in hardware. Thus return false to coerce vectors of these 6829 // types into integer vectors. 6830 // We do not depend on hasLegalHalfType for bfloat as it is a 6831 // separate IR type. 6832 if ((!getTarget().hasLegalHalfType() && 6833 (VT->getElementType()->isFloat16Type() || 6834 VT->getElementType()->isHalfType())) || 6835 (IsFloatABISoftFP && 6836 VT->getElementType()->isBFloat16Type())) 6837 return true; 6838 if (isAndroid()) { 6839 // Android shipped using Clang 3.1, which supported a slightly different 6840 // vector ABI. The primary differences were that 3-element vector types 6841 // were legal, and so were sub 32-bit vectors (i.e. <2 x i8>). This path 6842 // accepts that legacy behavior for Android only. 6843 // Check whether VT is legal. 6844 unsigned NumElements = VT->getNumElements(); 6845 // NumElements should be power of 2 or equal to 3. 6846 if (!llvm::isPowerOf2_32(NumElements) && NumElements != 3) 6847 return true; 6848 } else { 6849 // Check whether VT is legal. 6850 unsigned NumElements = VT->getNumElements(); 6851 uint64_t Size = getContext().getTypeSize(VT); 6852 // NumElements should be power of 2. 6853 if (!llvm::isPowerOf2_32(NumElements)) 6854 return true; 6855 // Size should be greater than 32 bits. 6856 return Size <= 32; 6857 } 6858 } 6859 return false; 6860 } 6861 6862 /// Return true if a type contains any 16-bit floating point vectors 6863 bool ARMABIInfo::containsAnyFP16Vectors(QualType Ty) const { 6864 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) { 6865 uint64_t NElements = AT->getSize().getZExtValue(); 6866 if (NElements == 0) 6867 return false; 6868 return containsAnyFP16Vectors(AT->getElementType()); 6869 } else if (const RecordType *RT = Ty->getAs<RecordType>()) { 6870 const RecordDecl *RD = RT->getDecl(); 6871 6872 // If this is a C++ record, check the bases first. 6873 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 6874 if (llvm::any_of(CXXRD->bases(), [this](const CXXBaseSpecifier &B) { 6875 return containsAnyFP16Vectors(B.getType()); 6876 })) 6877 return true; 6878 6879 if (llvm::any_of(RD->fields(), [this](FieldDecl *FD) { 6880 return FD && containsAnyFP16Vectors(FD->getType()); 6881 })) 6882 return true; 6883 6884 return false; 6885 } else { 6886 if (const VectorType *VT = Ty->getAs<VectorType>()) 6887 return (VT->getElementType()->isFloat16Type() || 6888 VT->getElementType()->isBFloat16Type() || 6889 VT->getElementType()->isHalfType()); 6890 return false; 6891 } 6892 } 6893 6894 bool ARMABIInfo::isLegalVectorTypeForSwift(CharUnits vectorSize, 6895 llvm::Type *eltTy, 6896 unsigned numElts) const { 6897 if (!llvm::isPowerOf2_32(numElts)) 6898 return false; 6899 unsigned size = getDataLayout().getTypeStoreSizeInBits(eltTy); 6900 if (size > 64) 6901 return false; 6902 if (vectorSize.getQuantity() != 8 && 6903 (vectorSize.getQuantity() != 16 || numElts == 1)) 6904 return false; 6905 return true; 6906 } 6907 6908 bool ARMABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const { 6909 // Homogeneous aggregates for AAPCS-VFP must have base types of float, 6910 // double, or 64-bit or 128-bit vectors. 6911 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) { 6912 if (BT->getKind() == BuiltinType::Float || 6913 BT->getKind() == BuiltinType::Double || 6914 BT->getKind() == BuiltinType::LongDouble) 6915 return true; 6916 } else if (const VectorType *VT = Ty->getAs<VectorType>()) { 6917 unsigned VecSize = getContext().getTypeSize(VT); 6918 if (VecSize == 64 || VecSize == 128) 6919 return true; 6920 } 6921 return false; 6922 } 6923 6924 bool ARMABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base, 6925 uint64_t Members) const { 6926 return Members <= 4; 6927 } 6928 6929 bool ARMABIInfo::isEffectivelyAAPCS_VFP(unsigned callConvention, 6930 bool acceptHalf) const { 6931 // Give precedence to user-specified calling conventions. 6932 if (callConvention != llvm::CallingConv::C) 6933 return (callConvention == llvm::CallingConv::ARM_AAPCS_VFP); 6934 else 6935 return (getABIKind() == AAPCS_VFP) || 6936 (acceptHalf && (getABIKind() == AAPCS16_VFP)); 6937 } 6938 6939 Address ARMABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 6940 QualType Ty) const { 6941 CharUnits SlotSize = CharUnits::fromQuantity(4); 6942 6943 // Empty records are ignored for parameter passing purposes. 6944 if (isEmptyRecord(getContext(), Ty, true)) { 6945 Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize); 6946 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty)); 6947 return Addr; 6948 } 6949 6950 CharUnits TySize = getContext().getTypeSizeInChars(Ty); 6951 CharUnits TyAlignForABI = getContext().getTypeUnadjustedAlignInChars(Ty); 6952 6953 // Use indirect if size of the illegal vector is bigger than 16 bytes. 6954 bool IsIndirect = false; 6955 const Type *Base = nullptr; 6956 uint64_t Members = 0; 6957 if (TySize > CharUnits::fromQuantity(16) && isIllegalVectorType(Ty)) { 6958 IsIndirect = true; 6959 6960 // ARMv7k passes structs bigger than 16 bytes indirectly, in space 6961 // allocated by the caller. 6962 } else if (TySize > CharUnits::fromQuantity(16) && 6963 getABIKind() == ARMABIInfo::AAPCS16_VFP && 6964 !isHomogeneousAggregate(Ty, Base, Members)) { 6965 IsIndirect = true; 6966 6967 // Otherwise, bound the type's ABI alignment. 6968 // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for 6969 // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte. 6970 // Our callers should be prepared to handle an under-aligned address. 6971 } else if (getABIKind() == ARMABIInfo::AAPCS_VFP || 6972 getABIKind() == ARMABIInfo::AAPCS) { 6973 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4)); 6974 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(8)); 6975 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) { 6976 // ARMv7k allows type alignment up to 16 bytes. 6977 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4)); 6978 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(16)); 6979 } else { 6980 TyAlignForABI = CharUnits::fromQuantity(4); 6981 } 6982 6983 TypeInfoChars TyInfo(TySize, TyAlignForABI, AlignRequirementKind::None); 6984 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TyInfo, 6985 SlotSize, /*AllowHigherAlign*/ true); 6986 } 6987 6988 //===----------------------------------------------------------------------===// 6989 // NVPTX ABI Implementation 6990 //===----------------------------------------------------------------------===// 6991 6992 namespace { 6993 6994 class NVPTXTargetCodeGenInfo; 6995 6996 class NVPTXABIInfo : public ABIInfo { 6997 NVPTXTargetCodeGenInfo &CGInfo; 6998 6999 public: 7000 NVPTXABIInfo(CodeGenTypes &CGT, NVPTXTargetCodeGenInfo &Info) 7001 : ABIInfo(CGT), CGInfo(Info) {} 7002 7003 ABIArgInfo classifyReturnType(QualType RetTy) const; 7004 ABIArgInfo classifyArgumentType(QualType Ty) const; 7005 7006 void computeInfo(CGFunctionInfo &FI) const override; 7007 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 7008 QualType Ty) const override; 7009 bool isUnsupportedType(QualType T) const; 7010 ABIArgInfo coerceToIntArrayWithLimit(QualType Ty, unsigned MaxSize) const; 7011 }; 7012 7013 class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo { 7014 public: 7015 NVPTXTargetCodeGenInfo(CodeGenTypes &CGT) 7016 : TargetCodeGenInfo(std::make_unique<NVPTXABIInfo>(CGT, *this)) {} 7017 7018 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 7019 CodeGen::CodeGenModule &M) const override; 7020 bool shouldEmitStaticExternCAliases() const override; 7021 7022 llvm::Type *getCUDADeviceBuiltinSurfaceDeviceType() const override { 7023 // On the device side, surface reference is represented as an object handle 7024 // in 64-bit integer. 7025 return llvm::Type::getInt64Ty(getABIInfo().getVMContext()); 7026 } 7027 7028 llvm::Type *getCUDADeviceBuiltinTextureDeviceType() const override { 7029 // On the device side, texture reference is represented as an object handle 7030 // in 64-bit integer. 7031 return llvm::Type::getInt64Ty(getABIInfo().getVMContext()); 7032 } 7033 7034 bool emitCUDADeviceBuiltinSurfaceDeviceCopy(CodeGenFunction &CGF, LValue Dst, 7035 LValue Src) const override { 7036 emitBuiltinSurfTexDeviceCopy(CGF, Dst, Src); 7037 return true; 7038 } 7039 7040 bool emitCUDADeviceBuiltinTextureDeviceCopy(CodeGenFunction &CGF, LValue Dst, 7041 LValue Src) const override { 7042 emitBuiltinSurfTexDeviceCopy(CGF, Dst, Src); 7043 return true; 7044 } 7045 7046 private: 7047 // Adds a NamedMDNode with GV, Name, and Operand as operands, and adds the 7048 // resulting MDNode to the nvvm.annotations MDNode. 7049 static void addNVVMMetadata(llvm::GlobalValue *GV, StringRef Name, 7050 int Operand); 7051 7052 static void emitBuiltinSurfTexDeviceCopy(CodeGenFunction &CGF, LValue Dst, 7053 LValue Src) { 7054 llvm::Value *Handle = nullptr; 7055 llvm::Constant *C = 7056 llvm::dyn_cast<llvm::Constant>(Src.getAddress(CGF).getPointer()); 7057 // Lookup `addrspacecast` through the constant pointer if any. 7058 if (auto *ASC = llvm::dyn_cast_or_null<llvm::AddrSpaceCastOperator>(C)) 7059 C = llvm::cast<llvm::Constant>(ASC->getPointerOperand()); 7060 if (auto *GV = llvm::dyn_cast_or_null<llvm::GlobalVariable>(C)) { 7061 // Load the handle from the specific global variable using 7062 // `nvvm.texsurf.handle.internal` intrinsic. 7063 Handle = CGF.EmitRuntimeCall( 7064 CGF.CGM.getIntrinsic(llvm::Intrinsic::nvvm_texsurf_handle_internal, 7065 {GV->getType()}), 7066 {GV}, "texsurf_handle"); 7067 } else 7068 Handle = CGF.EmitLoadOfScalar(Src, SourceLocation()); 7069 CGF.EmitStoreOfScalar(Handle, Dst); 7070 } 7071 }; 7072 7073 /// Checks if the type is unsupported directly by the current target. 7074 bool NVPTXABIInfo::isUnsupportedType(QualType T) const { 7075 ASTContext &Context = getContext(); 7076 if (!Context.getTargetInfo().hasFloat16Type() && T->isFloat16Type()) 7077 return true; 7078 if (!Context.getTargetInfo().hasFloat128Type() && 7079 (T->isFloat128Type() || 7080 (T->isRealFloatingType() && Context.getTypeSize(T) == 128))) 7081 return true; 7082 if (const auto *EIT = T->getAs<ExtIntType>()) 7083 return EIT->getNumBits() > 7084 (Context.getTargetInfo().hasInt128Type() ? 128U : 64U); 7085 if (!Context.getTargetInfo().hasInt128Type() && T->isIntegerType() && 7086 Context.getTypeSize(T) > 64U) 7087 return true; 7088 if (const auto *AT = T->getAsArrayTypeUnsafe()) 7089 return isUnsupportedType(AT->getElementType()); 7090 const auto *RT = T->getAs<RecordType>(); 7091 if (!RT) 7092 return false; 7093 const RecordDecl *RD = RT->getDecl(); 7094 7095 // If this is a C++ record, check the bases first. 7096 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 7097 for (const CXXBaseSpecifier &I : CXXRD->bases()) 7098 if (isUnsupportedType(I.getType())) 7099 return true; 7100 7101 for (const FieldDecl *I : RD->fields()) 7102 if (isUnsupportedType(I->getType())) 7103 return true; 7104 return false; 7105 } 7106 7107 /// Coerce the given type into an array with maximum allowed size of elements. 7108 ABIArgInfo NVPTXABIInfo::coerceToIntArrayWithLimit(QualType Ty, 7109 unsigned MaxSize) const { 7110 // Alignment and Size are measured in bits. 7111 const uint64_t Size = getContext().getTypeSize(Ty); 7112 const uint64_t Alignment = getContext().getTypeAlign(Ty); 7113 const unsigned Div = std::min<unsigned>(MaxSize, Alignment); 7114 llvm::Type *IntType = llvm::Type::getIntNTy(getVMContext(), Div); 7115 const uint64_t NumElements = (Size + Div - 1) / Div; 7116 return ABIArgInfo::getDirect(llvm::ArrayType::get(IntType, NumElements)); 7117 } 7118 7119 ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const { 7120 if (RetTy->isVoidType()) 7121 return ABIArgInfo::getIgnore(); 7122 7123 if (getContext().getLangOpts().OpenMP && 7124 getContext().getLangOpts().OpenMPIsDevice && isUnsupportedType(RetTy)) 7125 return coerceToIntArrayWithLimit(RetTy, 64); 7126 7127 // note: this is different from default ABI 7128 if (!RetTy->isScalarType()) 7129 return ABIArgInfo::getDirect(); 7130 7131 // Treat an enum type as its underlying type. 7132 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 7133 RetTy = EnumTy->getDecl()->getIntegerType(); 7134 7135 return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy) 7136 : ABIArgInfo::getDirect()); 7137 } 7138 7139 ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const { 7140 // Treat an enum type as its underlying type. 7141 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 7142 Ty = EnumTy->getDecl()->getIntegerType(); 7143 7144 // Return aggregates type as indirect by value 7145 if (isAggregateTypeForABI(Ty)) { 7146 // Under CUDA device compilation, tex/surf builtin types are replaced with 7147 // object types and passed directly. 7148 if (getContext().getLangOpts().CUDAIsDevice) { 7149 if (Ty->isCUDADeviceBuiltinSurfaceType()) 7150 return ABIArgInfo::getDirect( 7151 CGInfo.getCUDADeviceBuiltinSurfaceDeviceType()); 7152 if (Ty->isCUDADeviceBuiltinTextureType()) 7153 return ABIArgInfo::getDirect( 7154 CGInfo.getCUDADeviceBuiltinTextureDeviceType()); 7155 } 7156 return getNaturalAlignIndirect(Ty, /* byval */ true); 7157 } 7158 7159 if (const auto *EIT = Ty->getAs<ExtIntType>()) { 7160 if ((EIT->getNumBits() > 128) || 7161 (!getContext().getTargetInfo().hasInt128Type() && 7162 EIT->getNumBits() > 64)) 7163 return getNaturalAlignIndirect(Ty, /* byval */ true); 7164 } 7165 7166 return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty) 7167 : ABIArgInfo::getDirect()); 7168 } 7169 7170 void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const { 7171 if (!getCXXABI().classifyReturnType(FI)) 7172 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 7173 for (auto &I : FI.arguments()) 7174 I.info = classifyArgumentType(I.type); 7175 7176 // Always honor user-specified calling convention. 7177 if (FI.getCallingConvention() != llvm::CallingConv::C) 7178 return; 7179 7180 FI.setEffectiveCallingConvention(getRuntimeCC()); 7181 } 7182 7183 Address NVPTXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 7184 QualType Ty) const { 7185 llvm_unreachable("NVPTX does not support varargs"); 7186 } 7187 7188 void NVPTXTargetCodeGenInfo::setTargetAttributes( 7189 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const { 7190 if (GV->isDeclaration()) 7191 return; 7192 const VarDecl *VD = dyn_cast_or_null<VarDecl>(D); 7193 if (VD) { 7194 if (M.getLangOpts().CUDA) { 7195 if (VD->getType()->isCUDADeviceBuiltinSurfaceType()) 7196 addNVVMMetadata(GV, "surface", 1); 7197 else if (VD->getType()->isCUDADeviceBuiltinTextureType()) 7198 addNVVMMetadata(GV, "texture", 1); 7199 return; 7200 } 7201 } 7202 7203 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D); 7204 if (!FD) return; 7205 7206 llvm::Function *F = cast<llvm::Function>(GV); 7207 7208 // Perform special handling in OpenCL mode 7209 if (M.getLangOpts().OpenCL) { 7210 // Use OpenCL function attributes to check for kernel functions 7211 // By default, all functions are device functions 7212 if (FD->hasAttr<OpenCLKernelAttr>()) { 7213 // OpenCL __kernel functions get kernel metadata 7214 // Create !{<func-ref>, metadata !"kernel", i32 1} node 7215 addNVVMMetadata(F, "kernel", 1); 7216 // And kernel functions are not subject to inlining 7217 F->addFnAttr(llvm::Attribute::NoInline); 7218 } 7219 } 7220 7221 // Perform special handling in CUDA mode. 7222 if (M.getLangOpts().CUDA) { 7223 // CUDA __global__ functions get a kernel metadata entry. Since 7224 // __global__ functions cannot be called from the device, we do not 7225 // need to set the noinline attribute. 7226 if (FD->hasAttr<CUDAGlobalAttr>()) { 7227 // Create !{<func-ref>, metadata !"kernel", i32 1} node 7228 addNVVMMetadata(F, "kernel", 1); 7229 } 7230 if (CUDALaunchBoundsAttr *Attr = FD->getAttr<CUDALaunchBoundsAttr>()) { 7231 // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node 7232 llvm::APSInt MaxThreads(32); 7233 MaxThreads = Attr->getMaxThreads()->EvaluateKnownConstInt(M.getContext()); 7234 if (MaxThreads > 0) 7235 addNVVMMetadata(F, "maxntidx", MaxThreads.getExtValue()); 7236 7237 // min blocks is an optional argument for CUDALaunchBoundsAttr. If it was 7238 // not specified in __launch_bounds__ or if the user specified a 0 value, 7239 // we don't have to add a PTX directive. 7240 if (Attr->getMinBlocks()) { 7241 llvm::APSInt MinBlocks(32); 7242 MinBlocks = Attr->getMinBlocks()->EvaluateKnownConstInt(M.getContext()); 7243 if (MinBlocks > 0) 7244 // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node 7245 addNVVMMetadata(F, "minctasm", MinBlocks.getExtValue()); 7246 } 7247 } 7248 } 7249 } 7250 7251 void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::GlobalValue *GV, 7252 StringRef Name, int Operand) { 7253 llvm::Module *M = GV->getParent(); 7254 llvm::LLVMContext &Ctx = M->getContext(); 7255 7256 // Get "nvvm.annotations" metadata node 7257 llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations"); 7258 7259 llvm::Metadata *MDVals[] = { 7260 llvm::ConstantAsMetadata::get(GV), llvm::MDString::get(Ctx, Name), 7261 llvm::ConstantAsMetadata::get( 7262 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand))}; 7263 // Append metadata to nvvm.annotations 7264 MD->addOperand(llvm::MDNode::get(Ctx, MDVals)); 7265 } 7266 7267 bool NVPTXTargetCodeGenInfo::shouldEmitStaticExternCAliases() const { 7268 return false; 7269 } 7270 } 7271 7272 //===----------------------------------------------------------------------===// 7273 // SystemZ ABI Implementation 7274 //===----------------------------------------------------------------------===// 7275 7276 namespace { 7277 7278 class SystemZABIInfo : public SwiftABIInfo { 7279 bool HasVector; 7280 bool IsSoftFloatABI; 7281 7282 public: 7283 SystemZABIInfo(CodeGenTypes &CGT, bool HV, bool SF) 7284 : SwiftABIInfo(CGT), HasVector(HV), IsSoftFloatABI(SF) {} 7285 7286 bool isPromotableIntegerTypeForABI(QualType Ty) const; 7287 bool isCompoundType(QualType Ty) const; 7288 bool isVectorArgumentType(QualType Ty) const; 7289 bool isFPArgumentType(QualType Ty) const; 7290 QualType GetSingleElementType(QualType Ty) const; 7291 7292 ABIArgInfo classifyReturnType(QualType RetTy) const; 7293 ABIArgInfo classifyArgumentType(QualType ArgTy) const; 7294 7295 void computeInfo(CGFunctionInfo &FI) const override { 7296 if (!getCXXABI().classifyReturnType(FI)) 7297 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 7298 for (auto &I : FI.arguments()) 7299 I.info = classifyArgumentType(I.type); 7300 } 7301 7302 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 7303 QualType Ty) const override; 7304 7305 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars, 7306 bool asReturnValue) const override { 7307 return occupiesMoreThan(CGT, scalars, /*total*/ 4); 7308 } 7309 bool isSwiftErrorInRegister() const override { 7310 return false; 7311 } 7312 }; 7313 7314 class SystemZTargetCodeGenInfo : public TargetCodeGenInfo { 7315 public: 7316 SystemZTargetCodeGenInfo(CodeGenTypes &CGT, bool HasVector, bool SoftFloatABI) 7317 : TargetCodeGenInfo( 7318 std::make_unique<SystemZABIInfo>(CGT, HasVector, SoftFloatABI)) {} 7319 7320 llvm::Value *testFPKind(llvm::Value *V, unsigned BuiltinID, 7321 CGBuilderTy &Builder, 7322 CodeGenModule &CGM) const override { 7323 assert(V->getType()->isFloatingPointTy() && "V should have an FP type."); 7324 // Only use TDC in constrained FP mode. 7325 if (!Builder.getIsFPConstrained()) 7326 return nullptr; 7327 7328 llvm::Type *Ty = V->getType(); 7329 if (Ty->isFloatTy() || Ty->isDoubleTy() || Ty->isFP128Ty()) { 7330 llvm::Module &M = CGM.getModule(); 7331 auto &Ctx = M.getContext(); 7332 llvm::Function *TDCFunc = 7333 llvm::Intrinsic::getDeclaration(&M, llvm::Intrinsic::s390_tdc, Ty); 7334 unsigned TDCBits = 0; 7335 switch (BuiltinID) { 7336 case Builtin::BI__builtin_isnan: 7337 TDCBits = 0xf; 7338 break; 7339 case Builtin::BIfinite: 7340 case Builtin::BI__finite: 7341 case Builtin::BIfinitef: 7342 case Builtin::BI__finitef: 7343 case Builtin::BIfinitel: 7344 case Builtin::BI__finitel: 7345 case Builtin::BI__builtin_isfinite: 7346 TDCBits = 0xfc0; 7347 break; 7348 case Builtin::BI__builtin_isinf: 7349 TDCBits = 0x30; 7350 break; 7351 default: 7352 break; 7353 } 7354 if (TDCBits) 7355 return Builder.CreateCall( 7356 TDCFunc, 7357 {V, llvm::ConstantInt::get(llvm::Type::getInt64Ty(Ctx), TDCBits)}); 7358 } 7359 return nullptr; 7360 } 7361 }; 7362 } 7363 7364 bool SystemZABIInfo::isPromotableIntegerTypeForABI(QualType Ty) const { 7365 // Treat an enum type as its underlying type. 7366 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 7367 Ty = EnumTy->getDecl()->getIntegerType(); 7368 7369 // Promotable integer types are required to be promoted by the ABI. 7370 if (ABIInfo::isPromotableIntegerTypeForABI(Ty)) 7371 return true; 7372 7373 if (const auto *EIT = Ty->getAs<ExtIntType>()) 7374 if (EIT->getNumBits() < 64) 7375 return true; 7376 7377 // 32-bit values must also be promoted. 7378 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) 7379 switch (BT->getKind()) { 7380 case BuiltinType::Int: 7381 case BuiltinType::UInt: 7382 return true; 7383 default: 7384 return false; 7385 } 7386 return false; 7387 } 7388 7389 bool SystemZABIInfo::isCompoundType(QualType Ty) const { 7390 return (Ty->isAnyComplexType() || 7391 Ty->isVectorType() || 7392 isAggregateTypeForABI(Ty)); 7393 } 7394 7395 bool SystemZABIInfo::isVectorArgumentType(QualType Ty) const { 7396 return (HasVector && 7397 Ty->isVectorType() && 7398 getContext().getTypeSize(Ty) <= 128); 7399 } 7400 7401 bool SystemZABIInfo::isFPArgumentType(QualType Ty) const { 7402 if (IsSoftFloatABI) 7403 return false; 7404 7405 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) 7406 switch (BT->getKind()) { 7407 case BuiltinType::Float: 7408 case BuiltinType::Double: 7409 return true; 7410 default: 7411 return false; 7412 } 7413 7414 return false; 7415 } 7416 7417 QualType SystemZABIInfo::GetSingleElementType(QualType Ty) const { 7418 const RecordType *RT = Ty->getAs<RecordType>(); 7419 7420 if (RT && RT->isStructureOrClassType()) { 7421 const RecordDecl *RD = RT->getDecl(); 7422 QualType Found; 7423 7424 // If this is a C++ record, check the bases first. 7425 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 7426 for (const auto &I : CXXRD->bases()) { 7427 QualType Base = I.getType(); 7428 7429 // Empty bases don't affect things either way. 7430 if (isEmptyRecord(getContext(), Base, true)) 7431 continue; 7432 7433 if (!Found.isNull()) 7434 return Ty; 7435 Found = GetSingleElementType(Base); 7436 } 7437 7438 // Check the fields. 7439 for (const auto *FD : RD->fields()) { 7440 // For compatibility with GCC, ignore empty bitfields in C++ mode. 7441 // Unlike isSingleElementStruct(), empty structure and array fields 7442 // do count. So do anonymous bitfields that aren't zero-sized. 7443 if (getContext().getLangOpts().CPlusPlus && 7444 FD->isZeroLengthBitField(getContext())) 7445 continue; 7446 // Like isSingleElementStruct(), ignore C++20 empty data members. 7447 if (FD->hasAttr<NoUniqueAddressAttr>() && 7448 isEmptyRecord(getContext(), FD->getType(), true)) 7449 continue; 7450 7451 // Unlike isSingleElementStruct(), arrays do not count. 7452 // Nested structures still do though. 7453 if (!Found.isNull()) 7454 return Ty; 7455 Found = GetSingleElementType(FD->getType()); 7456 } 7457 7458 // Unlike isSingleElementStruct(), trailing padding is allowed. 7459 // An 8-byte aligned struct s { float f; } is passed as a double. 7460 if (!Found.isNull()) 7461 return Found; 7462 } 7463 7464 return Ty; 7465 } 7466 7467 Address SystemZABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 7468 QualType Ty) const { 7469 // Assume that va_list type is correct; should be pointer to LLVM type: 7470 // struct { 7471 // i64 __gpr; 7472 // i64 __fpr; 7473 // i8 *__overflow_arg_area; 7474 // i8 *__reg_save_area; 7475 // }; 7476 7477 // Every non-vector argument occupies 8 bytes and is passed by preference 7478 // in either GPRs or FPRs. Vector arguments occupy 8 or 16 bytes and are 7479 // always passed on the stack. 7480 Ty = getContext().getCanonicalType(Ty); 7481 auto TyInfo = getContext().getTypeInfoInChars(Ty); 7482 llvm::Type *ArgTy = CGF.ConvertTypeForMem(Ty); 7483 llvm::Type *DirectTy = ArgTy; 7484 ABIArgInfo AI = classifyArgumentType(Ty); 7485 bool IsIndirect = AI.isIndirect(); 7486 bool InFPRs = false; 7487 bool IsVector = false; 7488 CharUnits UnpaddedSize; 7489 CharUnits DirectAlign; 7490 if (IsIndirect) { 7491 DirectTy = llvm::PointerType::getUnqual(DirectTy); 7492 UnpaddedSize = DirectAlign = CharUnits::fromQuantity(8); 7493 } else { 7494 if (AI.getCoerceToType()) 7495 ArgTy = AI.getCoerceToType(); 7496 InFPRs = (!IsSoftFloatABI && (ArgTy->isFloatTy() || ArgTy->isDoubleTy())); 7497 IsVector = ArgTy->isVectorTy(); 7498 UnpaddedSize = TyInfo.Width; 7499 DirectAlign = TyInfo.Align; 7500 } 7501 CharUnits PaddedSize = CharUnits::fromQuantity(8); 7502 if (IsVector && UnpaddedSize > PaddedSize) 7503 PaddedSize = CharUnits::fromQuantity(16); 7504 assert((UnpaddedSize <= PaddedSize) && "Invalid argument size."); 7505 7506 CharUnits Padding = (PaddedSize - UnpaddedSize); 7507 7508 llvm::Type *IndexTy = CGF.Int64Ty; 7509 llvm::Value *PaddedSizeV = 7510 llvm::ConstantInt::get(IndexTy, PaddedSize.getQuantity()); 7511 7512 if (IsVector) { 7513 // Work out the address of a vector argument on the stack. 7514 // Vector arguments are always passed in the high bits of a 7515 // single (8 byte) or double (16 byte) stack slot. 7516 Address OverflowArgAreaPtr = 7517 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr"); 7518 Address OverflowArgArea = 7519 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"), 7520 TyInfo.Align); 7521 Address MemAddr = 7522 CGF.Builder.CreateElementBitCast(OverflowArgArea, DirectTy, "mem_addr"); 7523 7524 // Update overflow_arg_area_ptr pointer 7525 llvm::Value *NewOverflowArgArea = 7526 CGF.Builder.CreateGEP(OverflowArgArea.getElementType(), 7527 OverflowArgArea.getPointer(), PaddedSizeV, 7528 "overflow_arg_area"); 7529 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr); 7530 7531 return MemAddr; 7532 } 7533 7534 assert(PaddedSize.getQuantity() == 8); 7535 7536 unsigned MaxRegs, RegCountField, RegSaveIndex; 7537 CharUnits RegPadding; 7538 if (InFPRs) { 7539 MaxRegs = 4; // Maximum of 4 FPR arguments 7540 RegCountField = 1; // __fpr 7541 RegSaveIndex = 16; // save offset for f0 7542 RegPadding = CharUnits(); // floats are passed in the high bits of an FPR 7543 } else { 7544 MaxRegs = 5; // Maximum of 5 GPR arguments 7545 RegCountField = 0; // __gpr 7546 RegSaveIndex = 2; // save offset for r2 7547 RegPadding = Padding; // values are passed in the low bits of a GPR 7548 } 7549 7550 Address RegCountPtr = 7551 CGF.Builder.CreateStructGEP(VAListAddr, RegCountField, "reg_count_ptr"); 7552 llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count"); 7553 llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs); 7554 llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV, 7555 "fits_in_regs"); 7556 7557 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg"); 7558 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem"); 7559 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end"); 7560 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock); 7561 7562 // Emit code to load the value if it was passed in registers. 7563 CGF.EmitBlock(InRegBlock); 7564 7565 // Work out the address of an argument register. 7566 llvm::Value *ScaledRegCount = 7567 CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count"); 7568 llvm::Value *RegBase = 7569 llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize.getQuantity() 7570 + RegPadding.getQuantity()); 7571 llvm::Value *RegOffset = 7572 CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset"); 7573 Address RegSaveAreaPtr = 7574 CGF.Builder.CreateStructGEP(VAListAddr, 3, "reg_save_area_ptr"); 7575 llvm::Value *RegSaveArea = 7576 CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area"); 7577 Address RawRegAddr(CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, RegOffset, 7578 "raw_reg_addr"), 7579 PaddedSize); 7580 Address RegAddr = 7581 CGF.Builder.CreateElementBitCast(RawRegAddr, DirectTy, "reg_addr"); 7582 7583 // Update the register count 7584 llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1); 7585 llvm::Value *NewRegCount = 7586 CGF.Builder.CreateAdd(RegCount, One, "reg_count"); 7587 CGF.Builder.CreateStore(NewRegCount, RegCountPtr); 7588 CGF.EmitBranch(ContBlock); 7589 7590 // Emit code to load the value if it was passed in memory. 7591 CGF.EmitBlock(InMemBlock); 7592 7593 // Work out the address of a stack argument. 7594 Address OverflowArgAreaPtr = 7595 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr"); 7596 Address OverflowArgArea = 7597 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"), 7598 PaddedSize); 7599 Address RawMemAddr = 7600 CGF.Builder.CreateConstByteGEP(OverflowArgArea, Padding, "raw_mem_addr"); 7601 Address MemAddr = 7602 CGF.Builder.CreateElementBitCast(RawMemAddr, DirectTy, "mem_addr"); 7603 7604 // Update overflow_arg_area_ptr pointer 7605 llvm::Value *NewOverflowArgArea = 7606 CGF.Builder.CreateGEP(OverflowArgArea.getElementType(), 7607 OverflowArgArea.getPointer(), PaddedSizeV, 7608 "overflow_arg_area"); 7609 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr); 7610 CGF.EmitBranch(ContBlock); 7611 7612 // Return the appropriate result. 7613 CGF.EmitBlock(ContBlock); 7614 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, 7615 MemAddr, InMemBlock, "va_arg.addr"); 7616 7617 if (IsIndirect) 7618 ResAddr = Address(CGF.Builder.CreateLoad(ResAddr, "indirect_arg"), 7619 TyInfo.Align); 7620 7621 return ResAddr; 7622 } 7623 7624 ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const { 7625 if (RetTy->isVoidType()) 7626 return ABIArgInfo::getIgnore(); 7627 if (isVectorArgumentType(RetTy)) 7628 return ABIArgInfo::getDirect(); 7629 if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64) 7630 return getNaturalAlignIndirect(RetTy); 7631 return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy) 7632 : ABIArgInfo::getDirect()); 7633 } 7634 7635 ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const { 7636 // Handle the generic C++ ABI. 7637 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 7638 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 7639 7640 // Integers and enums are extended to full register width. 7641 if (isPromotableIntegerTypeForABI(Ty)) 7642 return ABIArgInfo::getExtend(Ty); 7643 7644 // Handle vector types and vector-like structure types. Note that 7645 // as opposed to float-like structure types, we do not allow any 7646 // padding for vector-like structures, so verify the sizes match. 7647 uint64_t Size = getContext().getTypeSize(Ty); 7648 QualType SingleElementTy = GetSingleElementType(Ty); 7649 if (isVectorArgumentType(SingleElementTy) && 7650 getContext().getTypeSize(SingleElementTy) == Size) 7651 return ABIArgInfo::getDirect(CGT.ConvertType(SingleElementTy)); 7652 7653 // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly. 7654 if (Size != 8 && Size != 16 && Size != 32 && Size != 64) 7655 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 7656 7657 // Handle small structures. 7658 if (const RecordType *RT = Ty->getAs<RecordType>()) { 7659 // Structures with flexible arrays have variable length, so really 7660 // fail the size test above. 7661 const RecordDecl *RD = RT->getDecl(); 7662 if (RD->hasFlexibleArrayMember()) 7663 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 7664 7665 // The structure is passed as an unextended integer, a float, or a double. 7666 llvm::Type *PassTy; 7667 if (isFPArgumentType(SingleElementTy)) { 7668 assert(Size == 32 || Size == 64); 7669 if (Size == 32) 7670 PassTy = llvm::Type::getFloatTy(getVMContext()); 7671 else 7672 PassTy = llvm::Type::getDoubleTy(getVMContext()); 7673 } else 7674 PassTy = llvm::IntegerType::get(getVMContext(), Size); 7675 return ABIArgInfo::getDirect(PassTy); 7676 } 7677 7678 // Non-structure compounds are passed indirectly. 7679 if (isCompoundType(Ty)) 7680 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 7681 7682 return ABIArgInfo::getDirect(nullptr); 7683 } 7684 7685 //===----------------------------------------------------------------------===// 7686 // MSP430 ABI Implementation 7687 //===----------------------------------------------------------------------===// 7688 7689 namespace { 7690 7691 class MSP430ABIInfo : public DefaultABIInfo { 7692 static ABIArgInfo complexArgInfo() { 7693 ABIArgInfo Info = ABIArgInfo::getDirect(); 7694 Info.setCanBeFlattened(false); 7695 return Info; 7696 } 7697 7698 public: 7699 MSP430ABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {} 7700 7701 ABIArgInfo classifyReturnType(QualType RetTy) const { 7702 if (RetTy->isAnyComplexType()) 7703 return complexArgInfo(); 7704 7705 return DefaultABIInfo::classifyReturnType(RetTy); 7706 } 7707 7708 ABIArgInfo classifyArgumentType(QualType RetTy) const { 7709 if (RetTy->isAnyComplexType()) 7710 return complexArgInfo(); 7711 7712 return DefaultABIInfo::classifyArgumentType(RetTy); 7713 } 7714 7715 // Just copy the original implementations because 7716 // DefaultABIInfo::classify{Return,Argument}Type() are not virtual 7717 void computeInfo(CGFunctionInfo &FI) const override { 7718 if (!getCXXABI().classifyReturnType(FI)) 7719 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 7720 for (auto &I : FI.arguments()) 7721 I.info = classifyArgumentType(I.type); 7722 } 7723 7724 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 7725 QualType Ty) const override { 7726 return EmitVAArgInstr(CGF, VAListAddr, Ty, classifyArgumentType(Ty)); 7727 } 7728 }; 7729 7730 class MSP430TargetCodeGenInfo : public TargetCodeGenInfo { 7731 public: 7732 MSP430TargetCodeGenInfo(CodeGenTypes &CGT) 7733 : TargetCodeGenInfo(std::make_unique<MSP430ABIInfo>(CGT)) {} 7734 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 7735 CodeGen::CodeGenModule &M) const override; 7736 }; 7737 7738 } 7739 7740 void MSP430TargetCodeGenInfo::setTargetAttributes( 7741 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const { 7742 if (GV->isDeclaration()) 7743 return; 7744 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) { 7745 const auto *InterruptAttr = FD->getAttr<MSP430InterruptAttr>(); 7746 if (!InterruptAttr) 7747 return; 7748 7749 // Handle 'interrupt' attribute: 7750 llvm::Function *F = cast<llvm::Function>(GV); 7751 7752 // Step 1: Set ISR calling convention. 7753 F->setCallingConv(llvm::CallingConv::MSP430_INTR); 7754 7755 // Step 2: Add attributes goodness. 7756 F->addFnAttr(llvm::Attribute::NoInline); 7757 F->addFnAttr("interrupt", llvm::utostr(InterruptAttr->getNumber())); 7758 } 7759 } 7760 7761 //===----------------------------------------------------------------------===// 7762 // MIPS ABI Implementation. This works for both little-endian and 7763 // big-endian variants. 7764 //===----------------------------------------------------------------------===// 7765 7766 namespace { 7767 class MipsABIInfo : public ABIInfo { 7768 bool IsO32; 7769 unsigned MinABIStackAlignInBytes, StackAlignInBytes; 7770 void CoerceToIntArgs(uint64_t TySize, 7771 SmallVectorImpl<llvm::Type *> &ArgList) const; 7772 llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const; 7773 llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const; 7774 llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const; 7775 public: 7776 MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) : 7777 ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8), 7778 StackAlignInBytes(IsO32 ? 8 : 16) {} 7779 7780 ABIArgInfo classifyReturnType(QualType RetTy) const; 7781 ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const; 7782 void computeInfo(CGFunctionInfo &FI) const override; 7783 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 7784 QualType Ty) const override; 7785 ABIArgInfo extendType(QualType Ty) const; 7786 }; 7787 7788 class MIPSTargetCodeGenInfo : public TargetCodeGenInfo { 7789 unsigned SizeOfUnwindException; 7790 public: 7791 MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32) 7792 : TargetCodeGenInfo(std::make_unique<MipsABIInfo>(CGT, IsO32)), 7793 SizeOfUnwindException(IsO32 ? 24 : 32) {} 7794 7795 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override { 7796 return 29; 7797 } 7798 7799 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 7800 CodeGen::CodeGenModule &CGM) const override { 7801 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D); 7802 if (!FD) return; 7803 llvm::Function *Fn = cast<llvm::Function>(GV); 7804 7805 if (FD->hasAttr<MipsLongCallAttr>()) 7806 Fn->addFnAttr("long-call"); 7807 else if (FD->hasAttr<MipsShortCallAttr>()) 7808 Fn->addFnAttr("short-call"); 7809 7810 // Other attributes do not have a meaning for declarations. 7811 if (GV->isDeclaration()) 7812 return; 7813 7814 if (FD->hasAttr<Mips16Attr>()) { 7815 Fn->addFnAttr("mips16"); 7816 } 7817 else if (FD->hasAttr<NoMips16Attr>()) { 7818 Fn->addFnAttr("nomips16"); 7819 } 7820 7821 if (FD->hasAttr<MicroMipsAttr>()) 7822 Fn->addFnAttr("micromips"); 7823 else if (FD->hasAttr<NoMicroMipsAttr>()) 7824 Fn->addFnAttr("nomicromips"); 7825 7826 const MipsInterruptAttr *Attr = FD->getAttr<MipsInterruptAttr>(); 7827 if (!Attr) 7828 return; 7829 7830 const char *Kind; 7831 switch (Attr->getInterrupt()) { 7832 case MipsInterruptAttr::eic: Kind = "eic"; break; 7833 case MipsInterruptAttr::sw0: Kind = "sw0"; break; 7834 case MipsInterruptAttr::sw1: Kind = "sw1"; break; 7835 case MipsInterruptAttr::hw0: Kind = "hw0"; break; 7836 case MipsInterruptAttr::hw1: Kind = "hw1"; break; 7837 case MipsInterruptAttr::hw2: Kind = "hw2"; break; 7838 case MipsInterruptAttr::hw3: Kind = "hw3"; break; 7839 case MipsInterruptAttr::hw4: Kind = "hw4"; break; 7840 case MipsInterruptAttr::hw5: Kind = "hw5"; break; 7841 } 7842 7843 Fn->addFnAttr("interrupt", Kind); 7844 7845 } 7846 7847 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 7848 llvm::Value *Address) const override; 7849 7850 unsigned getSizeOfUnwindException() const override { 7851 return SizeOfUnwindException; 7852 } 7853 }; 7854 } 7855 7856 void MipsABIInfo::CoerceToIntArgs( 7857 uint64_t TySize, SmallVectorImpl<llvm::Type *> &ArgList) const { 7858 llvm::IntegerType *IntTy = 7859 llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8); 7860 7861 // Add (TySize / MinABIStackAlignInBytes) args of IntTy. 7862 for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N) 7863 ArgList.push_back(IntTy); 7864 7865 // If necessary, add one more integer type to ArgList. 7866 unsigned R = TySize % (MinABIStackAlignInBytes * 8); 7867 7868 if (R) 7869 ArgList.push_back(llvm::IntegerType::get(getVMContext(), R)); 7870 } 7871 7872 // In N32/64, an aligned double precision floating point field is passed in 7873 // a register. 7874 llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const { 7875 SmallVector<llvm::Type*, 8> ArgList, IntArgList; 7876 7877 if (IsO32) { 7878 CoerceToIntArgs(TySize, ArgList); 7879 return llvm::StructType::get(getVMContext(), ArgList); 7880 } 7881 7882 if (Ty->isComplexType()) 7883 return CGT.ConvertType(Ty); 7884 7885 const RecordType *RT = Ty->getAs<RecordType>(); 7886 7887 // Unions/vectors are passed in integer registers. 7888 if (!RT || !RT->isStructureOrClassType()) { 7889 CoerceToIntArgs(TySize, ArgList); 7890 return llvm::StructType::get(getVMContext(), ArgList); 7891 } 7892 7893 const RecordDecl *RD = RT->getDecl(); 7894 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD); 7895 assert(!(TySize % 8) && "Size of structure must be multiple of 8."); 7896 7897 uint64_t LastOffset = 0; 7898 unsigned idx = 0; 7899 llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64); 7900 7901 // Iterate over fields in the struct/class and check if there are any aligned 7902 // double fields. 7903 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 7904 i != e; ++i, ++idx) { 7905 const QualType Ty = i->getType(); 7906 const BuiltinType *BT = Ty->getAs<BuiltinType>(); 7907 7908 if (!BT || BT->getKind() != BuiltinType::Double) 7909 continue; 7910 7911 uint64_t Offset = Layout.getFieldOffset(idx); 7912 if (Offset % 64) // Ignore doubles that are not aligned. 7913 continue; 7914 7915 // Add ((Offset - LastOffset) / 64) args of type i64. 7916 for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j) 7917 ArgList.push_back(I64); 7918 7919 // Add double type. 7920 ArgList.push_back(llvm::Type::getDoubleTy(getVMContext())); 7921 LastOffset = Offset + 64; 7922 } 7923 7924 CoerceToIntArgs(TySize - LastOffset, IntArgList); 7925 ArgList.append(IntArgList.begin(), IntArgList.end()); 7926 7927 return llvm::StructType::get(getVMContext(), ArgList); 7928 } 7929 7930 llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset, 7931 uint64_t Offset) const { 7932 if (OrigOffset + MinABIStackAlignInBytes > Offset) 7933 return nullptr; 7934 7935 return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8); 7936 } 7937 7938 ABIArgInfo 7939 MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const { 7940 Ty = useFirstFieldIfTransparentUnion(Ty); 7941 7942 uint64_t OrigOffset = Offset; 7943 uint64_t TySize = getContext().getTypeSize(Ty); 7944 uint64_t Align = getContext().getTypeAlign(Ty) / 8; 7945 7946 Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes), 7947 (uint64_t)StackAlignInBytes); 7948 unsigned CurrOffset = llvm::alignTo(Offset, Align); 7949 Offset = CurrOffset + llvm::alignTo(TySize, Align * 8) / 8; 7950 7951 if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) { 7952 // Ignore empty aggregates. 7953 if (TySize == 0) 7954 return ABIArgInfo::getIgnore(); 7955 7956 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) { 7957 Offset = OrigOffset + MinABIStackAlignInBytes; 7958 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 7959 } 7960 7961 // If we have reached here, aggregates are passed directly by coercing to 7962 // another structure type. Padding is inserted if the offset of the 7963 // aggregate is unaligned. 7964 ABIArgInfo ArgInfo = 7965 ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0, 7966 getPaddingType(OrigOffset, CurrOffset)); 7967 ArgInfo.setInReg(true); 7968 return ArgInfo; 7969 } 7970 7971 // Treat an enum type as its underlying type. 7972 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 7973 Ty = EnumTy->getDecl()->getIntegerType(); 7974 7975 // Make sure we pass indirectly things that are too large. 7976 if (const auto *EIT = Ty->getAs<ExtIntType>()) 7977 if (EIT->getNumBits() > 128 || 7978 (EIT->getNumBits() > 64 && 7979 !getContext().getTargetInfo().hasInt128Type())) 7980 return getNaturalAlignIndirect(Ty); 7981 7982 // All integral types are promoted to the GPR width. 7983 if (Ty->isIntegralOrEnumerationType()) 7984 return extendType(Ty); 7985 7986 return ABIArgInfo::getDirect( 7987 nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset)); 7988 } 7989 7990 llvm::Type* 7991 MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const { 7992 const RecordType *RT = RetTy->getAs<RecordType>(); 7993 SmallVector<llvm::Type*, 8> RTList; 7994 7995 if (RT && RT->isStructureOrClassType()) { 7996 const RecordDecl *RD = RT->getDecl(); 7997 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD); 7998 unsigned FieldCnt = Layout.getFieldCount(); 7999 8000 // N32/64 returns struct/classes in floating point registers if the 8001 // following conditions are met: 8002 // 1. The size of the struct/class is no larger than 128-bit. 8003 // 2. The struct/class has one or two fields all of which are floating 8004 // point types. 8005 // 3. The offset of the first field is zero (this follows what gcc does). 8006 // 8007 // Any other composite results are returned in integer registers. 8008 // 8009 if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) { 8010 RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end(); 8011 for (; b != e; ++b) { 8012 const BuiltinType *BT = b->getType()->getAs<BuiltinType>(); 8013 8014 if (!BT || !BT->isFloatingPoint()) 8015 break; 8016 8017 RTList.push_back(CGT.ConvertType(b->getType())); 8018 } 8019 8020 if (b == e) 8021 return llvm::StructType::get(getVMContext(), RTList, 8022 RD->hasAttr<PackedAttr>()); 8023 8024 RTList.clear(); 8025 } 8026 } 8027 8028 CoerceToIntArgs(Size, RTList); 8029 return llvm::StructType::get(getVMContext(), RTList); 8030 } 8031 8032 ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const { 8033 uint64_t Size = getContext().getTypeSize(RetTy); 8034 8035 if (RetTy->isVoidType()) 8036 return ABIArgInfo::getIgnore(); 8037 8038 // O32 doesn't treat zero-sized structs differently from other structs. 8039 // However, N32/N64 ignores zero sized return values. 8040 if (!IsO32 && Size == 0) 8041 return ABIArgInfo::getIgnore(); 8042 8043 if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) { 8044 if (Size <= 128) { 8045 if (RetTy->isAnyComplexType()) 8046 return ABIArgInfo::getDirect(); 8047 8048 // O32 returns integer vectors in registers and N32/N64 returns all small 8049 // aggregates in registers. 8050 if (!IsO32 || 8051 (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) { 8052 ABIArgInfo ArgInfo = 8053 ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size)); 8054 ArgInfo.setInReg(true); 8055 return ArgInfo; 8056 } 8057 } 8058 8059 return getNaturalAlignIndirect(RetTy); 8060 } 8061 8062 // Treat an enum type as its underlying type. 8063 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 8064 RetTy = EnumTy->getDecl()->getIntegerType(); 8065 8066 // Make sure we pass indirectly things that are too large. 8067 if (const auto *EIT = RetTy->getAs<ExtIntType>()) 8068 if (EIT->getNumBits() > 128 || 8069 (EIT->getNumBits() > 64 && 8070 !getContext().getTargetInfo().hasInt128Type())) 8071 return getNaturalAlignIndirect(RetTy); 8072 8073 if (isPromotableIntegerTypeForABI(RetTy)) 8074 return ABIArgInfo::getExtend(RetTy); 8075 8076 if ((RetTy->isUnsignedIntegerOrEnumerationType() || 8077 RetTy->isSignedIntegerOrEnumerationType()) && Size == 32 && !IsO32) 8078 return ABIArgInfo::getSignExtend(RetTy); 8079 8080 return ABIArgInfo::getDirect(); 8081 } 8082 8083 void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const { 8084 ABIArgInfo &RetInfo = FI.getReturnInfo(); 8085 if (!getCXXABI().classifyReturnType(FI)) 8086 RetInfo = classifyReturnType(FI.getReturnType()); 8087 8088 // Check if a pointer to an aggregate is passed as a hidden argument. 8089 uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0; 8090 8091 for (auto &I : FI.arguments()) 8092 I.info = classifyArgumentType(I.type, Offset); 8093 } 8094 8095 Address MipsABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 8096 QualType OrigTy) const { 8097 QualType Ty = OrigTy; 8098 8099 // Integer arguments are promoted to 32-bit on O32 and 64-bit on N32/N64. 8100 // Pointers are also promoted in the same way but this only matters for N32. 8101 unsigned SlotSizeInBits = IsO32 ? 32 : 64; 8102 unsigned PtrWidth = getTarget().getPointerWidth(0); 8103 bool DidPromote = false; 8104 if ((Ty->isIntegerType() && 8105 getContext().getIntWidth(Ty) < SlotSizeInBits) || 8106 (Ty->isPointerType() && PtrWidth < SlotSizeInBits)) { 8107 DidPromote = true; 8108 Ty = getContext().getIntTypeForBitwidth(SlotSizeInBits, 8109 Ty->isSignedIntegerType()); 8110 } 8111 8112 auto TyInfo = getContext().getTypeInfoInChars(Ty); 8113 8114 // The alignment of things in the argument area is never larger than 8115 // StackAlignInBytes. 8116 TyInfo.Align = 8117 std::min(TyInfo.Align, CharUnits::fromQuantity(StackAlignInBytes)); 8118 8119 // MinABIStackAlignInBytes is the size of argument slots on the stack. 8120 CharUnits ArgSlotSize = CharUnits::fromQuantity(MinABIStackAlignInBytes); 8121 8122 Address Addr = emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false, 8123 TyInfo, ArgSlotSize, /*AllowHigherAlign*/ true); 8124 8125 8126 // If there was a promotion, "unpromote" into a temporary. 8127 // TODO: can we just use a pointer into a subset of the original slot? 8128 if (DidPromote) { 8129 Address Temp = CGF.CreateMemTemp(OrigTy, "vaarg.promotion-temp"); 8130 llvm::Value *Promoted = CGF.Builder.CreateLoad(Addr); 8131 8132 // Truncate down to the right width. 8133 llvm::Type *IntTy = (OrigTy->isIntegerType() ? Temp.getElementType() 8134 : CGF.IntPtrTy); 8135 llvm::Value *V = CGF.Builder.CreateTrunc(Promoted, IntTy); 8136 if (OrigTy->isPointerType()) 8137 V = CGF.Builder.CreateIntToPtr(V, Temp.getElementType()); 8138 8139 CGF.Builder.CreateStore(V, Temp); 8140 Addr = Temp; 8141 } 8142 8143 return Addr; 8144 } 8145 8146 ABIArgInfo MipsABIInfo::extendType(QualType Ty) const { 8147 int TySize = getContext().getTypeSize(Ty); 8148 8149 // MIPS64 ABI requires unsigned 32 bit integers to be sign extended. 8150 if (Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32) 8151 return ABIArgInfo::getSignExtend(Ty); 8152 8153 return ABIArgInfo::getExtend(Ty); 8154 } 8155 8156 bool 8157 MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 8158 llvm::Value *Address) const { 8159 // This information comes from gcc's implementation, which seems to 8160 // as canonical as it gets. 8161 8162 // Everything on MIPS is 4 bytes. Double-precision FP registers 8163 // are aliased to pairs of single-precision FP registers. 8164 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4); 8165 8166 // 0-31 are the general purpose registers, $0 - $31. 8167 // 32-63 are the floating-point registers, $f0 - $f31. 8168 // 64 and 65 are the multiply/divide registers, $hi and $lo. 8169 // 66 is the (notional, I think) register for signal-handler return. 8170 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65); 8171 8172 // 67-74 are the floating-point status registers, $fcc0 - $fcc7. 8173 // They are one bit wide and ignored here. 8174 8175 // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31. 8176 // (coprocessor 1 is the FP unit) 8177 // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31. 8178 // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31. 8179 // 176-181 are the DSP accumulator registers. 8180 AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181); 8181 return false; 8182 } 8183 8184 //===----------------------------------------------------------------------===// 8185 // M68k ABI Implementation 8186 //===----------------------------------------------------------------------===// 8187 8188 namespace { 8189 8190 class M68kTargetCodeGenInfo : public TargetCodeGenInfo { 8191 public: 8192 M68kTargetCodeGenInfo(CodeGenTypes &CGT) 8193 : TargetCodeGenInfo(std::make_unique<DefaultABIInfo>(CGT)) {} 8194 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 8195 CodeGen::CodeGenModule &M) const override; 8196 }; 8197 8198 } // namespace 8199 8200 void M68kTargetCodeGenInfo::setTargetAttributes( 8201 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const { 8202 if (const auto *FD = dyn_cast_or_null<FunctionDecl>(D)) { 8203 if (const auto *attr = FD->getAttr<M68kInterruptAttr>()) { 8204 // Handle 'interrupt' attribute: 8205 llvm::Function *F = cast<llvm::Function>(GV); 8206 8207 // Step 1: Set ISR calling convention. 8208 F->setCallingConv(llvm::CallingConv::M68k_INTR); 8209 8210 // Step 2: Add attributes goodness. 8211 F->addFnAttr(llvm::Attribute::NoInline); 8212 8213 // Step 3: Emit ISR vector alias. 8214 unsigned Num = attr->getNumber() / 2; 8215 llvm::GlobalAlias::create(llvm::Function::ExternalLinkage, 8216 "__isr_" + Twine(Num), F); 8217 } 8218 } 8219 } 8220 8221 //===----------------------------------------------------------------------===// 8222 // AVR ABI Implementation. Documented at 8223 // https://gcc.gnu.org/wiki/avr-gcc#Calling_Convention 8224 // https://gcc.gnu.org/wiki/avr-gcc#Reduced_Tiny 8225 //===----------------------------------------------------------------------===// 8226 8227 namespace { 8228 class AVRABIInfo : public DefaultABIInfo { 8229 public: 8230 AVRABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {} 8231 8232 ABIArgInfo classifyReturnType(QualType Ty) const { 8233 // A return struct with size less than or equal to 8 bytes is returned 8234 // directly via registers R18-R25. 8235 if (isAggregateTypeForABI(Ty) && getContext().getTypeSize(Ty) <= 64) 8236 return ABIArgInfo::getDirect(); 8237 else 8238 return DefaultABIInfo::classifyReturnType(Ty); 8239 } 8240 8241 // Just copy the original implementation of DefaultABIInfo::computeInfo(), 8242 // since DefaultABIInfo::classify{Return,Argument}Type() are not virtual. 8243 void computeInfo(CGFunctionInfo &FI) const override { 8244 if (!getCXXABI().classifyReturnType(FI)) 8245 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 8246 for (auto &I : FI.arguments()) 8247 I.info = classifyArgumentType(I.type); 8248 } 8249 }; 8250 8251 class AVRTargetCodeGenInfo : public TargetCodeGenInfo { 8252 public: 8253 AVRTargetCodeGenInfo(CodeGenTypes &CGT) 8254 : TargetCodeGenInfo(std::make_unique<AVRABIInfo>(CGT)) {} 8255 8256 LangAS getGlobalVarAddressSpace(CodeGenModule &CGM, 8257 const VarDecl *D) const override { 8258 // Check if a global/static variable is defined within address space 1 8259 // but not constant. 8260 LangAS AS = D->getType().getAddressSpace(); 8261 if (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 1 && 8262 !D->getType().isConstQualified()) 8263 CGM.getDiags().Report(D->getLocation(), 8264 diag::err_verify_nonconst_addrspace) 8265 << "__flash"; 8266 return TargetCodeGenInfo::getGlobalVarAddressSpace(CGM, D); 8267 } 8268 8269 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 8270 CodeGen::CodeGenModule &CGM) const override { 8271 if (GV->isDeclaration()) 8272 return; 8273 const auto *FD = dyn_cast_or_null<FunctionDecl>(D); 8274 if (!FD) return; 8275 auto *Fn = cast<llvm::Function>(GV); 8276 8277 if (FD->getAttr<AVRInterruptAttr>()) 8278 Fn->addFnAttr("interrupt"); 8279 8280 if (FD->getAttr<AVRSignalAttr>()) 8281 Fn->addFnAttr("signal"); 8282 } 8283 }; 8284 } 8285 8286 //===----------------------------------------------------------------------===// 8287 // TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults. 8288 // Currently subclassed only to implement custom OpenCL C function attribute 8289 // handling. 8290 //===----------------------------------------------------------------------===// 8291 8292 namespace { 8293 8294 class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo { 8295 public: 8296 TCETargetCodeGenInfo(CodeGenTypes &CGT) 8297 : DefaultTargetCodeGenInfo(CGT) {} 8298 8299 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 8300 CodeGen::CodeGenModule &M) const override; 8301 }; 8302 8303 void TCETargetCodeGenInfo::setTargetAttributes( 8304 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const { 8305 if (GV->isDeclaration()) 8306 return; 8307 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D); 8308 if (!FD) return; 8309 8310 llvm::Function *F = cast<llvm::Function>(GV); 8311 8312 if (M.getLangOpts().OpenCL) { 8313 if (FD->hasAttr<OpenCLKernelAttr>()) { 8314 // OpenCL C Kernel functions are not subject to inlining 8315 F->addFnAttr(llvm::Attribute::NoInline); 8316 const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>(); 8317 if (Attr) { 8318 // Convert the reqd_work_group_size() attributes to metadata. 8319 llvm::LLVMContext &Context = F->getContext(); 8320 llvm::NamedMDNode *OpenCLMetadata = 8321 M.getModule().getOrInsertNamedMetadata( 8322 "opencl.kernel_wg_size_info"); 8323 8324 SmallVector<llvm::Metadata *, 5> Operands; 8325 Operands.push_back(llvm::ConstantAsMetadata::get(F)); 8326 8327 Operands.push_back( 8328 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue( 8329 M.Int32Ty, llvm::APInt(32, Attr->getXDim())))); 8330 Operands.push_back( 8331 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue( 8332 M.Int32Ty, llvm::APInt(32, Attr->getYDim())))); 8333 Operands.push_back( 8334 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue( 8335 M.Int32Ty, llvm::APInt(32, Attr->getZDim())))); 8336 8337 // Add a boolean constant operand for "required" (true) or "hint" 8338 // (false) for implementing the work_group_size_hint attr later. 8339 // Currently always true as the hint is not yet implemented. 8340 Operands.push_back( 8341 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getTrue(Context))); 8342 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands)); 8343 } 8344 } 8345 } 8346 } 8347 8348 } 8349 8350 //===----------------------------------------------------------------------===// 8351 // Hexagon ABI Implementation 8352 //===----------------------------------------------------------------------===// 8353 8354 namespace { 8355 8356 class HexagonABIInfo : public DefaultABIInfo { 8357 public: 8358 HexagonABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {} 8359 8360 private: 8361 ABIArgInfo classifyReturnType(QualType RetTy) const; 8362 ABIArgInfo classifyArgumentType(QualType RetTy) const; 8363 ABIArgInfo classifyArgumentType(QualType RetTy, unsigned *RegsLeft) const; 8364 8365 void computeInfo(CGFunctionInfo &FI) const override; 8366 8367 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 8368 QualType Ty) const override; 8369 Address EmitVAArgFromMemory(CodeGenFunction &CFG, Address VAListAddr, 8370 QualType Ty) const; 8371 Address EmitVAArgForHexagon(CodeGenFunction &CFG, Address VAListAddr, 8372 QualType Ty) const; 8373 Address EmitVAArgForHexagonLinux(CodeGenFunction &CFG, Address VAListAddr, 8374 QualType Ty) const; 8375 }; 8376 8377 class HexagonTargetCodeGenInfo : public TargetCodeGenInfo { 8378 public: 8379 HexagonTargetCodeGenInfo(CodeGenTypes &CGT) 8380 : TargetCodeGenInfo(std::make_unique<HexagonABIInfo>(CGT)) {} 8381 8382 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 8383 return 29; 8384 } 8385 8386 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 8387 CodeGen::CodeGenModule &GCM) const override { 8388 if (GV->isDeclaration()) 8389 return; 8390 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D); 8391 if (!FD) 8392 return; 8393 } 8394 }; 8395 8396 } // namespace 8397 8398 void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const { 8399 unsigned RegsLeft = 6; 8400 if (!getCXXABI().classifyReturnType(FI)) 8401 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 8402 for (auto &I : FI.arguments()) 8403 I.info = classifyArgumentType(I.type, &RegsLeft); 8404 } 8405 8406 static bool HexagonAdjustRegsLeft(uint64_t Size, unsigned *RegsLeft) { 8407 assert(Size <= 64 && "Not expecting to pass arguments larger than 64 bits" 8408 " through registers"); 8409 8410 if (*RegsLeft == 0) 8411 return false; 8412 8413 if (Size <= 32) { 8414 (*RegsLeft)--; 8415 return true; 8416 } 8417 8418 if (2 <= (*RegsLeft & (~1U))) { 8419 *RegsLeft = (*RegsLeft & (~1U)) - 2; 8420 return true; 8421 } 8422 8423 // Next available register was r5 but candidate was greater than 32-bits so it 8424 // has to go on the stack. However we still consume r5 8425 if (*RegsLeft == 1) 8426 *RegsLeft = 0; 8427 8428 return false; 8429 } 8430 8431 ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty, 8432 unsigned *RegsLeft) const { 8433 if (!isAggregateTypeForABI(Ty)) { 8434 // Treat an enum type as its underlying type. 8435 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 8436 Ty = EnumTy->getDecl()->getIntegerType(); 8437 8438 uint64_t Size = getContext().getTypeSize(Ty); 8439 if (Size <= 64) 8440 HexagonAdjustRegsLeft(Size, RegsLeft); 8441 8442 if (Size > 64 && Ty->isExtIntType()) 8443 return getNaturalAlignIndirect(Ty, /*ByVal=*/true); 8444 8445 return isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty) 8446 : ABIArgInfo::getDirect(); 8447 } 8448 8449 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 8450 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 8451 8452 // Ignore empty records. 8453 if (isEmptyRecord(getContext(), Ty, true)) 8454 return ABIArgInfo::getIgnore(); 8455 8456 uint64_t Size = getContext().getTypeSize(Ty); 8457 unsigned Align = getContext().getTypeAlign(Ty); 8458 8459 if (Size > 64) 8460 return getNaturalAlignIndirect(Ty, /*ByVal=*/true); 8461 8462 if (HexagonAdjustRegsLeft(Size, RegsLeft)) 8463 Align = Size <= 32 ? 32 : 64; 8464 if (Size <= Align) { 8465 // Pass in the smallest viable integer type. 8466 if (!llvm::isPowerOf2_64(Size)) 8467 Size = llvm::NextPowerOf2(Size); 8468 return ABIArgInfo::getDirect(llvm::Type::getIntNTy(getVMContext(), Size)); 8469 } 8470 return DefaultABIInfo::classifyArgumentType(Ty); 8471 } 8472 8473 ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const { 8474 if (RetTy->isVoidType()) 8475 return ABIArgInfo::getIgnore(); 8476 8477 const TargetInfo &T = CGT.getTarget(); 8478 uint64_t Size = getContext().getTypeSize(RetTy); 8479 8480 if (RetTy->getAs<VectorType>()) { 8481 // HVX vectors are returned in vector registers or register pairs. 8482 if (T.hasFeature("hvx")) { 8483 assert(T.hasFeature("hvx-length64b") || T.hasFeature("hvx-length128b")); 8484 uint64_t VecSize = T.hasFeature("hvx-length64b") ? 64*8 : 128*8; 8485 if (Size == VecSize || Size == 2*VecSize) 8486 return ABIArgInfo::getDirectInReg(); 8487 } 8488 // Large vector types should be returned via memory. 8489 if (Size > 64) 8490 return getNaturalAlignIndirect(RetTy); 8491 } 8492 8493 if (!isAggregateTypeForABI(RetTy)) { 8494 // Treat an enum type as its underlying type. 8495 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 8496 RetTy = EnumTy->getDecl()->getIntegerType(); 8497 8498 if (Size > 64 && RetTy->isExtIntType()) 8499 return getNaturalAlignIndirect(RetTy, /*ByVal=*/false); 8500 8501 return isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy) 8502 : ABIArgInfo::getDirect(); 8503 } 8504 8505 if (isEmptyRecord(getContext(), RetTy, true)) 8506 return ABIArgInfo::getIgnore(); 8507 8508 // Aggregates <= 8 bytes are returned in registers, other aggregates 8509 // are returned indirectly. 8510 if (Size <= 64) { 8511 // Return in the smallest viable integer type. 8512 if (!llvm::isPowerOf2_64(Size)) 8513 Size = llvm::NextPowerOf2(Size); 8514 return ABIArgInfo::getDirect(llvm::Type::getIntNTy(getVMContext(), Size)); 8515 } 8516 return getNaturalAlignIndirect(RetTy, /*ByVal=*/true); 8517 } 8518 8519 Address HexagonABIInfo::EmitVAArgFromMemory(CodeGenFunction &CGF, 8520 Address VAListAddr, 8521 QualType Ty) const { 8522 // Load the overflow area pointer. 8523 Address __overflow_area_pointer_p = 8524 CGF.Builder.CreateStructGEP(VAListAddr, 2, "__overflow_area_pointer_p"); 8525 llvm::Value *__overflow_area_pointer = CGF.Builder.CreateLoad( 8526 __overflow_area_pointer_p, "__overflow_area_pointer"); 8527 8528 uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8; 8529 if (Align > 4) { 8530 // Alignment should be a power of 2. 8531 assert((Align & (Align - 1)) == 0 && "Alignment is not power of 2!"); 8532 8533 // overflow_arg_area = (overflow_arg_area + align - 1) & -align; 8534 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int64Ty, Align - 1); 8535 8536 // Add offset to the current pointer to access the argument. 8537 __overflow_area_pointer = 8538 CGF.Builder.CreateGEP(CGF.Int8Ty, __overflow_area_pointer, Offset); 8539 llvm::Value *AsInt = 8540 CGF.Builder.CreatePtrToInt(__overflow_area_pointer, CGF.Int32Ty); 8541 8542 // Create a mask which should be "AND"ed 8543 // with (overflow_arg_area + align - 1) 8544 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int32Ty, -(int)Align); 8545 __overflow_area_pointer = CGF.Builder.CreateIntToPtr( 8546 CGF.Builder.CreateAnd(AsInt, Mask), __overflow_area_pointer->getType(), 8547 "__overflow_area_pointer.align"); 8548 } 8549 8550 // Get the type of the argument from memory and bitcast 8551 // overflow area pointer to the argument type. 8552 llvm::Type *PTy = CGF.ConvertTypeForMem(Ty); 8553 Address AddrTyped = CGF.Builder.CreateBitCast( 8554 Address(__overflow_area_pointer, CharUnits::fromQuantity(Align)), 8555 llvm::PointerType::getUnqual(PTy)); 8556 8557 // Round up to the minimum stack alignment for varargs which is 4 bytes. 8558 uint64_t Offset = llvm::alignTo(CGF.getContext().getTypeSize(Ty) / 8, 4); 8559 8560 __overflow_area_pointer = CGF.Builder.CreateGEP( 8561 CGF.Int8Ty, __overflow_area_pointer, 8562 llvm::ConstantInt::get(CGF.Int32Ty, Offset), 8563 "__overflow_area_pointer.next"); 8564 CGF.Builder.CreateStore(__overflow_area_pointer, __overflow_area_pointer_p); 8565 8566 return AddrTyped; 8567 } 8568 8569 Address HexagonABIInfo::EmitVAArgForHexagon(CodeGenFunction &CGF, 8570 Address VAListAddr, 8571 QualType Ty) const { 8572 // FIXME: Need to handle alignment 8573 llvm::Type *BP = CGF.Int8PtrTy; 8574 llvm::Type *BPP = CGF.Int8PtrPtrTy; 8575 CGBuilderTy &Builder = CGF.Builder; 8576 Address VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap"); 8577 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur"); 8578 // Handle address alignment for type alignment > 32 bits 8579 uint64_t TyAlign = CGF.getContext().getTypeAlign(Ty) / 8; 8580 if (TyAlign > 4) { 8581 assert((TyAlign & (TyAlign - 1)) == 0 && "Alignment is not power of 2!"); 8582 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int32Ty); 8583 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt32(TyAlign - 1)); 8584 AddrAsInt = Builder.CreateAnd(AddrAsInt, Builder.getInt32(~(TyAlign - 1))); 8585 Addr = Builder.CreateIntToPtr(AddrAsInt, BP); 8586 } 8587 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty)); 8588 Address AddrTyped = Builder.CreateBitCast( 8589 Address(Addr, CharUnits::fromQuantity(TyAlign)), PTy); 8590 8591 uint64_t Offset = llvm::alignTo(CGF.getContext().getTypeSize(Ty) / 8, 4); 8592 llvm::Value *NextAddr = Builder.CreateGEP( 8593 CGF.Int8Ty, Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset), "ap.next"); 8594 Builder.CreateStore(NextAddr, VAListAddrAsBPP); 8595 8596 return AddrTyped; 8597 } 8598 8599 Address HexagonABIInfo::EmitVAArgForHexagonLinux(CodeGenFunction &CGF, 8600 Address VAListAddr, 8601 QualType Ty) const { 8602 int ArgSize = CGF.getContext().getTypeSize(Ty) / 8; 8603 8604 if (ArgSize > 8) 8605 return EmitVAArgFromMemory(CGF, VAListAddr, Ty); 8606 8607 // Here we have check if the argument is in register area or 8608 // in overflow area. 8609 // If the saved register area pointer + argsize rounded up to alignment > 8610 // saved register area end pointer, argument is in overflow area. 8611 unsigned RegsLeft = 6; 8612 Ty = CGF.getContext().getCanonicalType(Ty); 8613 (void)classifyArgumentType(Ty, &RegsLeft); 8614 8615 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg"); 8616 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg"); 8617 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack"); 8618 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end"); 8619 8620 // Get rounded size of the argument.GCC does not allow vararg of 8621 // size < 4 bytes. We follow the same logic here. 8622 ArgSize = (CGF.getContext().getTypeSize(Ty) <= 32) ? 4 : 8; 8623 int ArgAlign = (CGF.getContext().getTypeSize(Ty) <= 32) ? 4 : 8; 8624 8625 // Argument may be in saved register area 8626 CGF.EmitBlock(MaybeRegBlock); 8627 8628 // Load the current saved register area pointer. 8629 Address __current_saved_reg_area_pointer_p = CGF.Builder.CreateStructGEP( 8630 VAListAddr, 0, "__current_saved_reg_area_pointer_p"); 8631 llvm::Value *__current_saved_reg_area_pointer = CGF.Builder.CreateLoad( 8632 __current_saved_reg_area_pointer_p, "__current_saved_reg_area_pointer"); 8633 8634 // Load the saved register area end pointer. 8635 Address __saved_reg_area_end_pointer_p = CGF.Builder.CreateStructGEP( 8636 VAListAddr, 1, "__saved_reg_area_end_pointer_p"); 8637 llvm::Value *__saved_reg_area_end_pointer = CGF.Builder.CreateLoad( 8638 __saved_reg_area_end_pointer_p, "__saved_reg_area_end_pointer"); 8639 8640 // If the size of argument is > 4 bytes, check if the stack 8641 // location is aligned to 8 bytes 8642 if (ArgAlign > 4) { 8643 8644 llvm::Value *__current_saved_reg_area_pointer_int = 8645 CGF.Builder.CreatePtrToInt(__current_saved_reg_area_pointer, 8646 CGF.Int32Ty); 8647 8648 __current_saved_reg_area_pointer_int = CGF.Builder.CreateAdd( 8649 __current_saved_reg_area_pointer_int, 8650 llvm::ConstantInt::get(CGF.Int32Ty, (ArgAlign - 1)), 8651 "align_current_saved_reg_area_pointer"); 8652 8653 __current_saved_reg_area_pointer_int = 8654 CGF.Builder.CreateAnd(__current_saved_reg_area_pointer_int, 8655 llvm::ConstantInt::get(CGF.Int32Ty, -ArgAlign), 8656 "align_current_saved_reg_area_pointer"); 8657 8658 __current_saved_reg_area_pointer = 8659 CGF.Builder.CreateIntToPtr(__current_saved_reg_area_pointer_int, 8660 __current_saved_reg_area_pointer->getType(), 8661 "align_current_saved_reg_area_pointer"); 8662 } 8663 8664 llvm::Value *__new_saved_reg_area_pointer = 8665 CGF.Builder.CreateGEP(CGF.Int8Ty, __current_saved_reg_area_pointer, 8666 llvm::ConstantInt::get(CGF.Int32Ty, ArgSize), 8667 "__new_saved_reg_area_pointer"); 8668 8669 llvm::Value *UsingStack = 0; 8670 UsingStack = CGF.Builder.CreateICmpSGT(__new_saved_reg_area_pointer, 8671 __saved_reg_area_end_pointer); 8672 8673 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, InRegBlock); 8674 8675 // Argument in saved register area 8676 // Implement the block where argument is in register saved area 8677 CGF.EmitBlock(InRegBlock); 8678 8679 llvm::Type *PTy = CGF.ConvertType(Ty); 8680 llvm::Value *__saved_reg_area_p = CGF.Builder.CreateBitCast( 8681 __current_saved_reg_area_pointer, llvm::PointerType::getUnqual(PTy)); 8682 8683 CGF.Builder.CreateStore(__new_saved_reg_area_pointer, 8684 __current_saved_reg_area_pointer_p); 8685 8686 CGF.EmitBranch(ContBlock); 8687 8688 // Argument in overflow area 8689 // Implement the block where the argument is in overflow area. 8690 CGF.EmitBlock(OnStackBlock); 8691 8692 // Load the overflow area pointer 8693 Address __overflow_area_pointer_p = 8694 CGF.Builder.CreateStructGEP(VAListAddr, 2, "__overflow_area_pointer_p"); 8695 llvm::Value *__overflow_area_pointer = CGF.Builder.CreateLoad( 8696 __overflow_area_pointer_p, "__overflow_area_pointer"); 8697 8698 // Align the overflow area pointer according to the alignment of the argument 8699 if (ArgAlign > 4) { 8700 llvm::Value *__overflow_area_pointer_int = 8701 CGF.Builder.CreatePtrToInt(__overflow_area_pointer, CGF.Int32Ty); 8702 8703 __overflow_area_pointer_int = 8704 CGF.Builder.CreateAdd(__overflow_area_pointer_int, 8705 llvm::ConstantInt::get(CGF.Int32Ty, ArgAlign - 1), 8706 "align_overflow_area_pointer"); 8707 8708 __overflow_area_pointer_int = 8709 CGF.Builder.CreateAnd(__overflow_area_pointer_int, 8710 llvm::ConstantInt::get(CGF.Int32Ty, -ArgAlign), 8711 "align_overflow_area_pointer"); 8712 8713 __overflow_area_pointer = CGF.Builder.CreateIntToPtr( 8714 __overflow_area_pointer_int, __overflow_area_pointer->getType(), 8715 "align_overflow_area_pointer"); 8716 } 8717 8718 // Get the pointer for next argument in overflow area and store it 8719 // to overflow area pointer. 8720 llvm::Value *__new_overflow_area_pointer = CGF.Builder.CreateGEP( 8721 CGF.Int8Ty, __overflow_area_pointer, 8722 llvm::ConstantInt::get(CGF.Int32Ty, ArgSize), 8723 "__overflow_area_pointer.next"); 8724 8725 CGF.Builder.CreateStore(__new_overflow_area_pointer, 8726 __overflow_area_pointer_p); 8727 8728 CGF.Builder.CreateStore(__new_overflow_area_pointer, 8729 __current_saved_reg_area_pointer_p); 8730 8731 // Bitcast the overflow area pointer to the type of argument. 8732 llvm::Type *OverflowPTy = CGF.ConvertTypeForMem(Ty); 8733 llvm::Value *__overflow_area_p = CGF.Builder.CreateBitCast( 8734 __overflow_area_pointer, llvm::PointerType::getUnqual(OverflowPTy)); 8735 8736 CGF.EmitBranch(ContBlock); 8737 8738 // Get the correct pointer to load the variable argument 8739 // Implement the ContBlock 8740 CGF.EmitBlock(ContBlock); 8741 8742 llvm::Type *MemPTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty)); 8743 llvm::PHINode *ArgAddr = CGF.Builder.CreatePHI(MemPTy, 2, "vaarg.addr"); 8744 ArgAddr->addIncoming(__saved_reg_area_p, InRegBlock); 8745 ArgAddr->addIncoming(__overflow_area_p, OnStackBlock); 8746 8747 return Address(ArgAddr, CharUnits::fromQuantity(ArgAlign)); 8748 } 8749 8750 Address HexagonABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 8751 QualType Ty) const { 8752 8753 if (getTarget().getTriple().isMusl()) 8754 return EmitVAArgForHexagonLinux(CGF, VAListAddr, Ty); 8755 8756 return EmitVAArgForHexagon(CGF, VAListAddr, Ty); 8757 } 8758 8759 //===----------------------------------------------------------------------===// 8760 // Lanai ABI Implementation 8761 //===----------------------------------------------------------------------===// 8762 8763 namespace { 8764 class LanaiABIInfo : public DefaultABIInfo { 8765 public: 8766 LanaiABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {} 8767 8768 bool shouldUseInReg(QualType Ty, CCState &State) const; 8769 8770 void computeInfo(CGFunctionInfo &FI) const override { 8771 CCState State(FI); 8772 // Lanai uses 4 registers to pass arguments unless the function has the 8773 // regparm attribute set. 8774 if (FI.getHasRegParm()) { 8775 State.FreeRegs = FI.getRegParm(); 8776 } else { 8777 State.FreeRegs = 4; 8778 } 8779 8780 if (!getCXXABI().classifyReturnType(FI)) 8781 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 8782 for (auto &I : FI.arguments()) 8783 I.info = classifyArgumentType(I.type, State); 8784 } 8785 8786 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const; 8787 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const; 8788 }; 8789 } // end anonymous namespace 8790 8791 bool LanaiABIInfo::shouldUseInReg(QualType Ty, CCState &State) const { 8792 unsigned Size = getContext().getTypeSize(Ty); 8793 unsigned SizeInRegs = llvm::alignTo(Size, 32U) / 32U; 8794 8795 if (SizeInRegs == 0) 8796 return false; 8797 8798 if (SizeInRegs > State.FreeRegs) { 8799 State.FreeRegs = 0; 8800 return false; 8801 } 8802 8803 State.FreeRegs -= SizeInRegs; 8804 8805 return true; 8806 } 8807 8808 ABIArgInfo LanaiABIInfo::getIndirectResult(QualType Ty, bool ByVal, 8809 CCState &State) const { 8810 if (!ByVal) { 8811 if (State.FreeRegs) { 8812 --State.FreeRegs; // Non-byval indirects just use one pointer. 8813 return getNaturalAlignIndirectInReg(Ty); 8814 } 8815 return getNaturalAlignIndirect(Ty, false); 8816 } 8817 8818 // Compute the byval alignment. 8819 const unsigned MinABIStackAlignInBytes = 4; 8820 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8; 8821 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true, 8822 /*Realign=*/TypeAlign > 8823 MinABIStackAlignInBytes); 8824 } 8825 8826 ABIArgInfo LanaiABIInfo::classifyArgumentType(QualType Ty, 8827 CCState &State) const { 8828 // Check with the C++ ABI first. 8829 const RecordType *RT = Ty->getAs<RecordType>(); 8830 if (RT) { 8831 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()); 8832 if (RAA == CGCXXABI::RAA_Indirect) { 8833 return getIndirectResult(Ty, /*ByVal=*/false, State); 8834 } else if (RAA == CGCXXABI::RAA_DirectInMemory) { 8835 return getNaturalAlignIndirect(Ty, /*ByVal=*/true); 8836 } 8837 } 8838 8839 if (isAggregateTypeForABI(Ty)) { 8840 // Structures with flexible arrays are always indirect. 8841 if (RT && RT->getDecl()->hasFlexibleArrayMember()) 8842 return getIndirectResult(Ty, /*ByVal=*/true, State); 8843 8844 // Ignore empty structs/unions. 8845 if (isEmptyRecord(getContext(), Ty, true)) 8846 return ABIArgInfo::getIgnore(); 8847 8848 llvm::LLVMContext &LLVMContext = getVMContext(); 8849 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32; 8850 if (SizeInRegs <= State.FreeRegs) { 8851 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext); 8852 SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32); 8853 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements); 8854 State.FreeRegs -= SizeInRegs; 8855 return ABIArgInfo::getDirectInReg(Result); 8856 } else { 8857 State.FreeRegs = 0; 8858 } 8859 return getIndirectResult(Ty, true, State); 8860 } 8861 8862 // Treat an enum type as its underlying type. 8863 if (const auto *EnumTy = Ty->getAs<EnumType>()) 8864 Ty = EnumTy->getDecl()->getIntegerType(); 8865 8866 bool InReg = shouldUseInReg(Ty, State); 8867 8868 // Don't pass >64 bit integers in registers. 8869 if (const auto *EIT = Ty->getAs<ExtIntType>()) 8870 if (EIT->getNumBits() > 64) 8871 return getIndirectResult(Ty, /*ByVal=*/true, State); 8872 8873 if (isPromotableIntegerTypeForABI(Ty)) { 8874 if (InReg) 8875 return ABIArgInfo::getDirectInReg(); 8876 return ABIArgInfo::getExtend(Ty); 8877 } 8878 if (InReg) 8879 return ABIArgInfo::getDirectInReg(); 8880 return ABIArgInfo::getDirect(); 8881 } 8882 8883 namespace { 8884 class LanaiTargetCodeGenInfo : public TargetCodeGenInfo { 8885 public: 8886 LanaiTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT) 8887 : TargetCodeGenInfo(std::make_unique<LanaiABIInfo>(CGT)) {} 8888 }; 8889 } 8890 8891 //===----------------------------------------------------------------------===// 8892 // AMDGPU ABI Implementation 8893 //===----------------------------------------------------------------------===// 8894 8895 namespace { 8896 8897 class AMDGPUABIInfo final : public DefaultABIInfo { 8898 private: 8899 static const unsigned MaxNumRegsForArgsRet = 16; 8900 8901 unsigned numRegsForType(QualType Ty) const; 8902 8903 bool isHomogeneousAggregateBaseType(QualType Ty) const override; 8904 bool isHomogeneousAggregateSmallEnough(const Type *Base, 8905 uint64_t Members) const override; 8906 8907 // Coerce HIP scalar pointer arguments from generic pointers to global ones. 8908 llvm::Type *coerceKernelArgumentType(llvm::Type *Ty, unsigned FromAS, 8909 unsigned ToAS) const { 8910 // Single value types. 8911 if (Ty->isPointerTy() && Ty->getPointerAddressSpace() == FromAS) 8912 return llvm::PointerType::get( 8913 cast<llvm::PointerType>(Ty)->getElementType(), ToAS); 8914 return Ty; 8915 } 8916 8917 public: 8918 explicit AMDGPUABIInfo(CodeGen::CodeGenTypes &CGT) : 8919 DefaultABIInfo(CGT) {} 8920 8921 ABIArgInfo classifyReturnType(QualType RetTy) const; 8922 ABIArgInfo classifyKernelArgumentType(QualType Ty) const; 8923 ABIArgInfo classifyArgumentType(QualType Ty, unsigned &NumRegsLeft) const; 8924 8925 void computeInfo(CGFunctionInfo &FI) const override; 8926 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 8927 QualType Ty) const override; 8928 }; 8929 8930 bool AMDGPUABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const { 8931 return true; 8932 } 8933 8934 bool AMDGPUABIInfo::isHomogeneousAggregateSmallEnough( 8935 const Type *Base, uint64_t Members) const { 8936 uint32_t NumRegs = (getContext().getTypeSize(Base) + 31) / 32; 8937 8938 // Homogeneous Aggregates may occupy at most 16 registers. 8939 return Members * NumRegs <= MaxNumRegsForArgsRet; 8940 } 8941 8942 /// Estimate number of registers the type will use when passed in registers. 8943 unsigned AMDGPUABIInfo::numRegsForType(QualType Ty) const { 8944 unsigned NumRegs = 0; 8945 8946 if (const VectorType *VT = Ty->getAs<VectorType>()) { 8947 // Compute from the number of elements. The reported size is based on the 8948 // in-memory size, which includes the padding 4th element for 3-vectors. 8949 QualType EltTy = VT->getElementType(); 8950 unsigned EltSize = getContext().getTypeSize(EltTy); 8951 8952 // 16-bit element vectors should be passed as packed. 8953 if (EltSize == 16) 8954 return (VT->getNumElements() + 1) / 2; 8955 8956 unsigned EltNumRegs = (EltSize + 31) / 32; 8957 return EltNumRegs * VT->getNumElements(); 8958 } 8959 8960 if (const RecordType *RT = Ty->getAs<RecordType>()) { 8961 const RecordDecl *RD = RT->getDecl(); 8962 assert(!RD->hasFlexibleArrayMember()); 8963 8964 for (const FieldDecl *Field : RD->fields()) { 8965 QualType FieldTy = Field->getType(); 8966 NumRegs += numRegsForType(FieldTy); 8967 } 8968 8969 return NumRegs; 8970 } 8971 8972 return (getContext().getTypeSize(Ty) + 31) / 32; 8973 } 8974 8975 void AMDGPUABIInfo::computeInfo(CGFunctionInfo &FI) const { 8976 llvm::CallingConv::ID CC = FI.getCallingConvention(); 8977 8978 if (!getCXXABI().classifyReturnType(FI)) 8979 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 8980 8981 unsigned NumRegsLeft = MaxNumRegsForArgsRet; 8982 for (auto &Arg : FI.arguments()) { 8983 if (CC == llvm::CallingConv::AMDGPU_KERNEL) { 8984 Arg.info = classifyKernelArgumentType(Arg.type); 8985 } else { 8986 Arg.info = classifyArgumentType(Arg.type, NumRegsLeft); 8987 } 8988 } 8989 } 8990 8991 Address AMDGPUABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 8992 QualType Ty) const { 8993 llvm_unreachable("AMDGPU does not support varargs"); 8994 } 8995 8996 ABIArgInfo AMDGPUABIInfo::classifyReturnType(QualType RetTy) const { 8997 if (isAggregateTypeForABI(RetTy)) { 8998 // Records with non-trivial destructors/copy-constructors should not be 8999 // returned by value. 9000 if (!getRecordArgABI(RetTy, getCXXABI())) { 9001 // Ignore empty structs/unions. 9002 if (isEmptyRecord(getContext(), RetTy, true)) 9003 return ABIArgInfo::getIgnore(); 9004 9005 // Lower single-element structs to just return a regular value. 9006 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext())) 9007 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0))); 9008 9009 if (const RecordType *RT = RetTy->getAs<RecordType>()) { 9010 const RecordDecl *RD = RT->getDecl(); 9011 if (RD->hasFlexibleArrayMember()) 9012 return DefaultABIInfo::classifyReturnType(RetTy); 9013 } 9014 9015 // Pack aggregates <= 4 bytes into single VGPR or pair. 9016 uint64_t Size = getContext().getTypeSize(RetTy); 9017 if (Size <= 16) 9018 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext())); 9019 9020 if (Size <= 32) 9021 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext())); 9022 9023 if (Size <= 64) { 9024 llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext()); 9025 return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2)); 9026 } 9027 9028 if (numRegsForType(RetTy) <= MaxNumRegsForArgsRet) 9029 return ABIArgInfo::getDirect(); 9030 } 9031 } 9032 9033 // Otherwise just do the default thing. 9034 return DefaultABIInfo::classifyReturnType(RetTy); 9035 } 9036 9037 /// For kernels all parameters are really passed in a special buffer. It doesn't 9038 /// make sense to pass anything byval, so everything must be direct. 9039 ABIArgInfo AMDGPUABIInfo::classifyKernelArgumentType(QualType Ty) const { 9040 Ty = useFirstFieldIfTransparentUnion(Ty); 9041 9042 // TODO: Can we omit empty structs? 9043 9044 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext())) 9045 Ty = QualType(SeltTy, 0); 9046 9047 llvm::Type *OrigLTy = CGT.ConvertType(Ty); 9048 llvm::Type *LTy = OrigLTy; 9049 if (getContext().getLangOpts().HIP) { 9050 LTy = coerceKernelArgumentType( 9051 OrigLTy, /*FromAS=*/getContext().getTargetAddressSpace(LangAS::Default), 9052 /*ToAS=*/getContext().getTargetAddressSpace(LangAS::cuda_device)); 9053 } 9054 9055 // FIXME: Should also use this for OpenCL, but it requires addressing the 9056 // problem of kernels being called. 9057 // 9058 // FIXME: This doesn't apply the optimization of coercing pointers in structs 9059 // to global address space when using byref. This would require implementing a 9060 // new kind of coercion of the in-memory type when for indirect arguments. 9061 if (!getContext().getLangOpts().OpenCL && LTy == OrigLTy && 9062 isAggregateTypeForABI(Ty)) { 9063 return ABIArgInfo::getIndirectAliased( 9064 getContext().getTypeAlignInChars(Ty), 9065 getContext().getTargetAddressSpace(LangAS::opencl_constant), 9066 false /*Realign*/, nullptr /*Padding*/); 9067 } 9068 9069 // If we set CanBeFlattened to true, CodeGen will expand the struct to its 9070 // individual elements, which confuses the Clover OpenCL backend; therefore we 9071 // have to set it to false here. Other args of getDirect() are just defaults. 9072 return ABIArgInfo::getDirect(LTy, 0, nullptr, false); 9073 } 9074 9075 ABIArgInfo AMDGPUABIInfo::classifyArgumentType(QualType Ty, 9076 unsigned &NumRegsLeft) const { 9077 assert(NumRegsLeft <= MaxNumRegsForArgsRet && "register estimate underflow"); 9078 9079 Ty = useFirstFieldIfTransparentUnion(Ty); 9080 9081 if (isAggregateTypeForABI(Ty)) { 9082 // Records with non-trivial destructors/copy-constructors should not be 9083 // passed by value. 9084 if (auto RAA = getRecordArgABI(Ty, getCXXABI())) 9085 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 9086 9087 // Ignore empty structs/unions. 9088 if (isEmptyRecord(getContext(), Ty, true)) 9089 return ABIArgInfo::getIgnore(); 9090 9091 // Lower single-element structs to just pass a regular value. TODO: We 9092 // could do reasonable-size multiple-element structs too, using getExpand(), 9093 // though watch out for things like bitfields. 9094 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext())) 9095 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0))); 9096 9097 if (const RecordType *RT = Ty->getAs<RecordType>()) { 9098 const RecordDecl *RD = RT->getDecl(); 9099 if (RD->hasFlexibleArrayMember()) 9100 return DefaultABIInfo::classifyArgumentType(Ty); 9101 } 9102 9103 // Pack aggregates <= 8 bytes into single VGPR or pair. 9104 uint64_t Size = getContext().getTypeSize(Ty); 9105 if (Size <= 64) { 9106 unsigned NumRegs = (Size + 31) / 32; 9107 NumRegsLeft -= std::min(NumRegsLeft, NumRegs); 9108 9109 if (Size <= 16) 9110 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext())); 9111 9112 if (Size <= 32) 9113 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext())); 9114 9115 // XXX: Should this be i64 instead, and should the limit increase? 9116 llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext()); 9117 return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2)); 9118 } 9119 9120 if (NumRegsLeft > 0) { 9121 unsigned NumRegs = numRegsForType(Ty); 9122 if (NumRegsLeft >= NumRegs) { 9123 NumRegsLeft -= NumRegs; 9124 return ABIArgInfo::getDirect(); 9125 } 9126 } 9127 } 9128 9129 // Otherwise just do the default thing. 9130 ABIArgInfo ArgInfo = DefaultABIInfo::classifyArgumentType(Ty); 9131 if (!ArgInfo.isIndirect()) { 9132 unsigned NumRegs = numRegsForType(Ty); 9133 NumRegsLeft -= std::min(NumRegs, NumRegsLeft); 9134 } 9135 9136 return ArgInfo; 9137 } 9138 9139 class AMDGPUTargetCodeGenInfo : public TargetCodeGenInfo { 9140 public: 9141 AMDGPUTargetCodeGenInfo(CodeGenTypes &CGT) 9142 : TargetCodeGenInfo(std::make_unique<AMDGPUABIInfo>(CGT)) {} 9143 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 9144 CodeGen::CodeGenModule &M) const override; 9145 unsigned getOpenCLKernelCallingConv() const override; 9146 9147 llvm::Constant *getNullPointer(const CodeGen::CodeGenModule &CGM, 9148 llvm::PointerType *T, QualType QT) const override; 9149 9150 LangAS getASTAllocaAddressSpace() const override { 9151 return getLangASFromTargetAS( 9152 getABIInfo().getDataLayout().getAllocaAddrSpace()); 9153 } 9154 LangAS getGlobalVarAddressSpace(CodeGenModule &CGM, 9155 const VarDecl *D) const override; 9156 llvm::SyncScope::ID getLLVMSyncScopeID(const LangOptions &LangOpts, 9157 SyncScope Scope, 9158 llvm::AtomicOrdering Ordering, 9159 llvm::LLVMContext &Ctx) const override; 9160 llvm::Function * 9161 createEnqueuedBlockKernel(CodeGenFunction &CGF, 9162 llvm::Function *BlockInvokeFunc, 9163 llvm::Value *BlockLiteral) const override; 9164 bool shouldEmitStaticExternCAliases() const override; 9165 void setCUDAKernelCallingConvention(const FunctionType *&FT) const override; 9166 }; 9167 } 9168 9169 static bool requiresAMDGPUProtectedVisibility(const Decl *D, 9170 llvm::GlobalValue *GV) { 9171 if (GV->getVisibility() != llvm::GlobalValue::HiddenVisibility) 9172 return false; 9173 9174 return D->hasAttr<OpenCLKernelAttr>() || 9175 (isa<FunctionDecl>(D) && D->hasAttr<CUDAGlobalAttr>()) || 9176 (isa<VarDecl>(D) && 9177 (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>() || 9178 cast<VarDecl>(D)->getType()->isCUDADeviceBuiltinSurfaceType() || 9179 cast<VarDecl>(D)->getType()->isCUDADeviceBuiltinTextureType())); 9180 } 9181 9182 void AMDGPUTargetCodeGenInfo::setTargetAttributes( 9183 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const { 9184 if (requiresAMDGPUProtectedVisibility(D, GV)) { 9185 GV->setVisibility(llvm::GlobalValue::ProtectedVisibility); 9186 GV->setDSOLocal(true); 9187 } 9188 9189 if (GV->isDeclaration()) 9190 return; 9191 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D); 9192 if (!FD) 9193 return; 9194 9195 llvm::Function *F = cast<llvm::Function>(GV); 9196 9197 const auto *ReqdWGS = M.getLangOpts().OpenCL ? 9198 FD->getAttr<ReqdWorkGroupSizeAttr>() : nullptr; 9199 9200 9201 const bool IsOpenCLKernel = M.getLangOpts().OpenCL && 9202 FD->hasAttr<OpenCLKernelAttr>(); 9203 const bool IsHIPKernel = M.getLangOpts().HIP && 9204 FD->hasAttr<CUDAGlobalAttr>(); 9205 if ((IsOpenCLKernel || IsHIPKernel) && 9206 (M.getTriple().getOS() == llvm::Triple::AMDHSA)) 9207 F->addFnAttr("amdgpu-implicitarg-num-bytes", "56"); 9208 9209 if (IsHIPKernel) 9210 F->addFnAttr("uniform-work-group-size", "true"); 9211 9212 9213 const auto *FlatWGS = FD->getAttr<AMDGPUFlatWorkGroupSizeAttr>(); 9214 if (ReqdWGS || FlatWGS) { 9215 unsigned Min = 0; 9216 unsigned Max = 0; 9217 if (FlatWGS) { 9218 Min = FlatWGS->getMin() 9219 ->EvaluateKnownConstInt(M.getContext()) 9220 .getExtValue(); 9221 Max = FlatWGS->getMax() 9222 ->EvaluateKnownConstInt(M.getContext()) 9223 .getExtValue(); 9224 } 9225 if (ReqdWGS && Min == 0 && Max == 0) 9226 Min = Max = ReqdWGS->getXDim() * ReqdWGS->getYDim() * ReqdWGS->getZDim(); 9227 9228 if (Min != 0) { 9229 assert(Min <= Max && "Min must be less than or equal Max"); 9230 9231 std::string AttrVal = llvm::utostr(Min) + "," + llvm::utostr(Max); 9232 F->addFnAttr("amdgpu-flat-work-group-size", AttrVal); 9233 } else 9234 assert(Max == 0 && "Max must be zero"); 9235 } else if (IsOpenCLKernel || IsHIPKernel) { 9236 // By default, restrict the maximum size to a value specified by 9237 // --gpu-max-threads-per-block=n or its default value for HIP. 9238 const unsigned OpenCLDefaultMaxWorkGroupSize = 256; 9239 const unsigned DefaultMaxWorkGroupSize = 9240 IsOpenCLKernel ? OpenCLDefaultMaxWorkGroupSize 9241 : M.getLangOpts().GPUMaxThreadsPerBlock; 9242 std::string AttrVal = 9243 std::string("1,") + llvm::utostr(DefaultMaxWorkGroupSize); 9244 F->addFnAttr("amdgpu-flat-work-group-size", AttrVal); 9245 } 9246 9247 if (const auto *Attr = FD->getAttr<AMDGPUWavesPerEUAttr>()) { 9248 unsigned Min = 9249 Attr->getMin()->EvaluateKnownConstInt(M.getContext()).getExtValue(); 9250 unsigned Max = Attr->getMax() ? Attr->getMax() 9251 ->EvaluateKnownConstInt(M.getContext()) 9252 .getExtValue() 9253 : 0; 9254 9255 if (Min != 0) { 9256 assert((Max == 0 || Min <= Max) && "Min must be less than or equal Max"); 9257 9258 std::string AttrVal = llvm::utostr(Min); 9259 if (Max != 0) 9260 AttrVal = AttrVal + "," + llvm::utostr(Max); 9261 F->addFnAttr("amdgpu-waves-per-eu", AttrVal); 9262 } else 9263 assert(Max == 0 && "Max must be zero"); 9264 } 9265 9266 if (const auto *Attr = FD->getAttr<AMDGPUNumSGPRAttr>()) { 9267 unsigned NumSGPR = Attr->getNumSGPR(); 9268 9269 if (NumSGPR != 0) 9270 F->addFnAttr("amdgpu-num-sgpr", llvm::utostr(NumSGPR)); 9271 } 9272 9273 if (const auto *Attr = FD->getAttr<AMDGPUNumVGPRAttr>()) { 9274 uint32_t NumVGPR = Attr->getNumVGPR(); 9275 9276 if (NumVGPR != 0) 9277 F->addFnAttr("amdgpu-num-vgpr", llvm::utostr(NumVGPR)); 9278 } 9279 9280 if (M.getContext().getTargetInfo().allowAMDGPUUnsafeFPAtomics()) 9281 F->addFnAttr("amdgpu-unsafe-fp-atomics", "true"); 9282 9283 if (!getABIInfo().getCodeGenOpts().EmitIEEENaNCompliantInsts) 9284 F->addFnAttr("amdgpu-ieee", "false"); 9285 } 9286 9287 unsigned AMDGPUTargetCodeGenInfo::getOpenCLKernelCallingConv() const { 9288 return llvm::CallingConv::AMDGPU_KERNEL; 9289 } 9290 9291 // Currently LLVM assumes null pointers always have value 0, 9292 // which results in incorrectly transformed IR. Therefore, instead of 9293 // emitting null pointers in private and local address spaces, a null 9294 // pointer in generic address space is emitted which is casted to a 9295 // pointer in local or private address space. 9296 llvm::Constant *AMDGPUTargetCodeGenInfo::getNullPointer( 9297 const CodeGen::CodeGenModule &CGM, llvm::PointerType *PT, 9298 QualType QT) const { 9299 if (CGM.getContext().getTargetNullPointerValue(QT) == 0) 9300 return llvm::ConstantPointerNull::get(PT); 9301 9302 auto &Ctx = CGM.getContext(); 9303 auto NPT = llvm::PointerType::get(PT->getElementType(), 9304 Ctx.getTargetAddressSpace(LangAS::opencl_generic)); 9305 return llvm::ConstantExpr::getAddrSpaceCast( 9306 llvm::ConstantPointerNull::get(NPT), PT); 9307 } 9308 9309 LangAS 9310 AMDGPUTargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM, 9311 const VarDecl *D) const { 9312 assert(!CGM.getLangOpts().OpenCL && 9313 !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) && 9314 "Address space agnostic languages only"); 9315 LangAS DefaultGlobalAS = getLangASFromTargetAS( 9316 CGM.getContext().getTargetAddressSpace(LangAS::opencl_global)); 9317 if (!D) 9318 return DefaultGlobalAS; 9319 9320 LangAS AddrSpace = D->getType().getAddressSpace(); 9321 assert(AddrSpace == LangAS::Default || isTargetAddressSpace(AddrSpace)); 9322 if (AddrSpace != LangAS::Default) 9323 return AddrSpace; 9324 9325 if (CGM.isTypeConstant(D->getType(), false)) { 9326 if (auto ConstAS = CGM.getTarget().getConstantAddressSpace()) 9327 return ConstAS.getValue(); 9328 } 9329 return DefaultGlobalAS; 9330 } 9331 9332 llvm::SyncScope::ID 9333 AMDGPUTargetCodeGenInfo::getLLVMSyncScopeID(const LangOptions &LangOpts, 9334 SyncScope Scope, 9335 llvm::AtomicOrdering Ordering, 9336 llvm::LLVMContext &Ctx) const { 9337 std::string Name; 9338 switch (Scope) { 9339 case SyncScope::OpenCLWorkGroup: 9340 Name = "workgroup"; 9341 break; 9342 case SyncScope::OpenCLDevice: 9343 Name = "agent"; 9344 break; 9345 case SyncScope::OpenCLAllSVMDevices: 9346 Name = ""; 9347 break; 9348 case SyncScope::OpenCLSubGroup: 9349 Name = "wavefront"; 9350 } 9351 9352 if (Ordering != llvm::AtomicOrdering::SequentiallyConsistent) { 9353 if (!Name.empty()) 9354 Name = Twine(Twine(Name) + Twine("-")).str(); 9355 9356 Name = Twine(Twine(Name) + Twine("one-as")).str(); 9357 } 9358 9359 return Ctx.getOrInsertSyncScopeID(Name); 9360 } 9361 9362 bool AMDGPUTargetCodeGenInfo::shouldEmitStaticExternCAliases() const { 9363 return false; 9364 } 9365 9366 void AMDGPUTargetCodeGenInfo::setCUDAKernelCallingConvention( 9367 const FunctionType *&FT) const { 9368 FT = getABIInfo().getContext().adjustFunctionType( 9369 FT, FT->getExtInfo().withCallingConv(CC_OpenCLKernel)); 9370 } 9371 9372 //===----------------------------------------------------------------------===// 9373 // SPARC v8 ABI Implementation. 9374 // Based on the SPARC Compliance Definition version 2.4.1. 9375 // 9376 // Ensures that complex values are passed in registers. 9377 // 9378 namespace { 9379 class SparcV8ABIInfo : public DefaultABIInfo { 9380 public: 9381 SparcV8ABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {} 9382 9383 private: 9384 ABIArgInfo classifyReturnType(QualType RetTy) const; 9385 void computeInfo(CGFunctionInfo &FI) const override; 9386 }; 9387 } // end anonymous namespace 9388 9389 9390 ABIArgInfo 9391 SparcV8ABIInfo::classifyReturnType(QualType Ty) const { 9392 if (Ty->isAnyComplexType()) { 9393 return ABIArgInfo::getDirect(); 9394 } 9395 else { 9396 return DefaultABIInfo::classifyReturnType(Ty); 9397 } 9398 } 9399 9400 void SparcV8ABIInfo::computeInfo(CGFunctionInfo &FI) const { 9401 9402 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 9403 for (auto &Arg : FI.arguments()) 9404 Arg.info = classifyArgumentType(Arg.type); 9405 } 9406 9407 namespace { 9408 class SparcV8TargetCodeGenInfo : public TargetCodeGenInfo { 9409 public: 9410 SparcV8TargetCodeGenInfo(CodeGenTypes &CGT) 9411 : TargetCodeGenInfo(std::make_unique<SparcV8ABIInfo>(CGT)) {} 9412 }; 9413 } // end anonymous namespace 9414 9415 //===----------------------------------------------------------------------===// 9416 // SPARC v9 ABI Implementation. 9417 // Based on the SPARC Compliance Definition version 2.4.1. 9418 // 9419 // Function arguments a mapped to a nominal "parameter array" and promoted to 9420 // registers depending on their type. Each argument occupies 8 or 16 bytes in 9421 // the array, structs larger than 16 bytes are passed indirectly. 9422 // 9423 // One case requires special care: 9424 // 9425 // struct mixed { 9426 // int i; 9427 // float f; 9428 // }; 9429 // 9430 // When a struct mixed is passed by value, it only occupies 8 bytes in the 9431 // parameter array, but the int is passed in an integer register, and the float 9432 // is passed in a floating point register. This is represented as two arguments 9433 // with the LLVM IR inreg attribute: 9434 // 9435 // declare void f(i32 inreg %i, float inreg %f) 9436 // 9437 // The code generator will only allocate 4 bytes from the parameter array for 9438 // the inreg arguments. All other arguments are allocated a multiple of 8 9439 // bytes. 9440 // 9441 namespace { 9442 class SparcV9ABIInfo : public ABIInfo { 9443 public: 9444 SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {} 9445 9446 private: 9447 ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const; 9448 void computeInfo(CGFunctionInfo &FI) const override; 9449 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 9450 QualType Ty) const override; 9451 9452 // Coercion type builder for structs passed in registers. The coercion type 9453 // serves two purposes: 9454 // 9455 // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned' 9456 // in registers. 9457 // 2. Expose aligned floating point elements as first-level elements, so the 9458 // code generator knows to pass them in floating point registers. 9459 // 9460 // We also compute the InReg flag which indicates that the struct contains 9461 // aligned 32-bit floats. 9462 // 9463 struct CoerceBuilder { 9464 llvm::LLVMContext &Context; 9465 const llvm::DataLayout &DL; 9466 SmallVector<llvm::Type*, 8> Elems; 9467 uint64_t Size; 9468 bool InReg; 9469 9470 CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl) 9471 : Context(c), DL(dl), Size(0), InReg(false) {} 9472 9473 // Pad Elems with integers until Size is ToSize. 9474 void pad(uint64_t ToSize) { 9475 assert(ToSize >= Size && "Cannot remove elements"); 9476 if (ToSize == Size) 9477 return; 9478 9479 // Finish the current 64-bit word. 9480 uint64_t Aligned = llvm::alignTo(Size, 64); 9481 if (Aligned > Size && Aligned <= ToSize) { 9482 Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size)); 9483 Size = Aligned; 9484 } 9485 9486 // Add whole 64-bit words. 9487 while (Size + 64 <= ToSize) { 9488 Elems.push_back(llvm::Type::getInt64Ty(Context)); 9489 Size += 64; 9490 } 9491 9492 // Final in-word padding. 9493 if (Size < ToSize) { 9494 Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size)); 9495 Size = ToSize; 9496 } 9497 } 9498 9499 // Add a floating point element at Offset. 9500 void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) { 9501 // Unaligned floats are treated as integers. 9502 if (Offset % Bits) 9503 return; 9504 // The InReg flag is only required if there are any floats < 64 bits. 9505 if (Bits < 64) 9506 InReg = true; 9507 pad(Offset); 9508 Elems.push_back(Ty); 9509 Size = Offset + Bits; 9510 } 9511 9512 // Add a struct type to the coercion type, starting at Offset (in bits). 9513 void addStruct(uint64_t Offset, llvm::StructType *StrTy) { 9514 const llvm::StructLayout *Layout = DL.getStructLayout(StrTy); 9515 for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) { 9516 llvm::Type *ElemTy = StrTy->getElementType(i); 9517 uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i); 9518 switch (ElemTy->getTypeID()) { 9519 case llvm::Type::StructTyID: 9520 addStruct(ElemOffset, cast<llvm::StructType>(ElemTy)); 9521 break; 9522 case llvm::Type::FloatTyID: 9523 addFloat(ElemOffset, ElemTy, 32); 9524 break; 9525 case llvm::Type::DoubleTyID: 9526 addFloat(ElemOffset, ElemTy, 64); 9527 break; 9528 case llvm::Type::FP128TyID: 9529 addFloat(ElemOffset, ElemTy, 128); 9530 break; 9531 case llvm::Type::PointerTyID: 9532 if (ElemOffset % 64 == 0) { 9533 pad(ElemOffset); 9534 Elems.push_back(ElemTy); 9535 Size += 64; 9536 } 9537 break; 9538 default: 9539 break; 9540 } 9541 } 9542 } 9543 9544 // Check if Ty is a usable substitute for the coercion type. 9545 bool isUsableType(llvm::StructType *Ty) const { 9546 return llvm::makeArrayRef(Elems) == Ty->elements(); 9547 } 9548 9549 // Get the coercion type as a literal struct type. 9550 llvm::Type *getType() const { 9551 if (Elems.size() == 1) 9552 return Elems.front(); 9553 else 9554 return llvm::StructType::get(Context, Elems); 9555 } 9556 }; 9557 }; 9558 } // end anonymous namespace 9559 9560 ABIArgInfo 9561 SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const { 9562 if (Ty->isVoidType()) 9563 return ABIArgInfo::getIgnore(); 9564 9565 uint64_t Size = getContext().getTypeSize(Ty); 9566 9567 // Anything too big to fit in registers is passed with an explicit indirect 9568 // pointer / sret pointer. 9569 if (Size > SizeLimit) 9570 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 9571 9572 // Treat an enum type as its underlying type. 9573 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 9574 Ty = EnumTy->getDecl()->getIntegerType(); 9575 9576 // Integer types smaller than a register are extended. 9577 if (Size < 64 && Ty->isIntegerType()) 9578 return ABIArgInfo::getExtend(Ty); 9579 9580 if (const auto *EIT = Ty->getAs<ExtIntType>()) 9581 if (EIT->getNumBits() < 64) 9582 return ABIArgInfo::getExtend(Ty); 9583 9584 // Other non-aggregates go in registers. 9585 if (!isAggregateTypeForABI(Ty)) 9586 return ABIArgInfo::getDirect(); 9587 9588 // If a C++ object has either a non-trivial copy constructor or a non-trivial 9589 // destructor, it is passed with an explicit indirect pointer / sret pointer. 9590 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 9591 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 9592 9593 // This is a small aggregate type that should be passed in registers. 9594 // Build a coercion type from the LLVM struct type. 9595 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty)); 9596 if (!StrTy) 9597 return ABIArgInfo::getDirect(); 9598 9599 CoerceBuilder CB(getVMContext(), getDataLayout()); 9600 CB.addStruct(0, StrTy); 9601 CB.pad(llvm::alignTo(CB.DL.getTypeSizeInBits(StrTy), 64)); 9602 9603 // Try to use the original type for coercion. 9604 llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType(); 9605 9606 if (CB.InReg) 9607 return ABIArgInfo::getDirectInReg(CoerceTy); 9608 else 9609 return ABIArgInfo::getDirect(CoerceTy); 9610 } 9611 9612 Address SparcV9ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 9613 QualType Ty) const { 9614 ABIArgInfo AI = classifyType(Ty, 16 * 8); 9615 llvm::Type *ArgTy = CGT.ConvertType(Ty); 9616 if (AI.canHaveCoerceToType() && !AI.getCoerceToType()) 9617 AI.setCoerceToType(ArgTy); 9618 9619 CharUnits SlotSize = CharUnits::fromQuantity(8); 9620 9621 CGBuilderTy &Builder = CGF.Builder; 9622 Address Addr(Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize); 9623 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy); 9624 9625 auto TypeInfo = getContext().getTypeInfoInChars(Ty); 9626 9627 Address ArgAddr = Address::invalid(); 9628 CharUnits Stride; 9629 switch (AI.getKind()) { 9630 case ABIArgInfo::Expand: 9631 case ABIArgInfo::CoerceAndExpand: 9632 case ABIArgInfo::InAlloca: 9633 llvm_unreachable("Unsupported ABI kind for va_arg"); 9634 9635 case ABIArgInfo::Extend: { 9636 Stride = SlotSize; 9637 CharUnits Offset = SlotSize - TypeInfo.Width; 9638 ArgAddr = Builder.CreateConstInBoundsByteGEP(Addr, Offset, "extend"); 9639 break; 9640 } 9641 9642 case ABIArgInfo::Direct: { 9643 auto AllocSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType()); 9644 Stride = CharUnits::fromQuantity(AllocSize).alignTo(SlotSize); 9645 ArgAddr = Addr; 9646 break; 9647 } 9648 9649 case ABIArgInfo::Indirect: 9650 case ABIArgInfo::IndirectAliased: 9651 Stride = SlotSize; 9652 ArgAddr = Builder.CreateElementBitCast(Addr, ArgPtrTy, "indirect"); 9653 ArgAddr = Address(Builder.CreateLoad(ArgAddr, "indirect.arg"), 9654 TypeInfo.Align); 9655 break; 9656 9657 case ABIArgInfo::Ignore: 9658 return Address(llvm::UndefValue::get(ArgPtrTy), TypeInfo.Align); 9659 } 9660 9661 // Update VAList. 9662 Address NextPtr = Builder.CreateConstInBoundsByteGEP(Addr, Stride, "ap.next"); 9663 Builder.CreateStore(NextPtr.getPointer(), VAListAddr); 9664 9665 return Builder.CreateBitCast(ArgAddr, ArgPtrTy, "arg.addr"); 9666 } 9667 9668 void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const { 9669 FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8); 9670 for (auto &I : FI.arguments()) 9671 I.info = classifyType(I.type, 16 * 8); 9672 } 9673 9674 namespace { 9675 class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo { 9676 public: 9677 SparcV9TargetCodeGenInfo(CodeGenTypes &CGT) 9678 : TargetCodeGenInfo(std::make_unique<SparcV9ABIInfo>(CGT)) {} 9679 9680 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 9681 return 14; 9682 } 9683 9684 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 9685 llvm::Value *Address) const override; 9686 }; 9687 } // end anonymous namespace 9688 9689 bool 9690 SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 9691 llvm::Value *Address) const { 9692 // This is calculated from the LLVM and GCC tables and verified 9693 // against gcc output. AFAIK all ABIs use the same encoding. 9694 9695 CodeGen::CGBuilderTy &Builder = CGF.Builder; 9696 9697 llvm::IntegerType *i8 = CGF.Int8Ty; 9698 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4); 9699 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8); 9700 9701 // 0-31: the 8-byte general-purpose registers 9702 AssignToArrayRange(Builder, Address, Eight8, 0, 31); 9703 9704 // 32-63: f0-31, the 4-byte floating-point registers 9705 AssignToArrayRange(Builder, Address, Four8, 32, 63); 9706 9707 // Y = 64 9708 // PSR = 65 9709 // WIM = 66 9710 // TBR = 67 9711 // PC = 68 9712 // NPC = 69 9713 // FSR = 70 9714 // CSR = 71 9715 AssignToArrayRange(Builder, Address, Eight8, 64, 71); 9716 9717 // 72-87: d0-15, the 8-byte floating-point registers 9718 AssignToArrayRange(Builder, Address, Eight8, 72, 87); 9719 9720 return false; 9721 } 9722 9723 // ARC ABI implementation. 9724 namespace { 9725 9726 class ARCABIInfo : public DefaultABIInfo { 9727 public: 9728 using DefaultABIInfo::DefaultABIInfo; 9729 9730 private: 9731 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 9732 QualType Ty) const override; 9733 9734 void updateState(const ABIArgInfo &Info, QualType Ty, CCState &State) const { 9735 if (!State.FreeRegs) 9736 return; 9737 if (Info.isIndirect() && Info.getInReg()) 9738 State.FreeRegs--; 9739 else if (Info.isDirect() && Info.getInReg()) { 9740 unsigned sz = (getContext().getTypeSize(Ty) + 31) / 32; 9741 if (sz < State.FreeRegs) 9742 State.FreeRegs -= sz; 9743 else 9744 State.FreeRegs = 0; 9745 } 9746 } 9747 9748 void computeInfo(CGFunctionInfo &FI) const override { 9749 CCState State(FI); 9750 // ARC uses 8 registers to pass arguments. 9751 State.FreeRegs = 8; 9752 9753 if (!getCXXABI().classifyReturnType(FI)) 9754 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 9755 updateState(FI.getReturnInfo(), FI.getReturnType(), State); 9756 for (auto &I : FI.arguments()) { 9757 I.info = classifyArgumentType(I.type, State.FreeRegs); 9758 updateState(I.info, I.type, State); 9759 } 9760 } 9761 9762 ABIArgInfo getIndirectByRef(QualType Ty, bool HasFreeRegs) const; 9763 ABIArgInfo getIndirectByValue(QualType Ty) const; 9764 ABIArgInfo classifyArgumentType(QualType Ty, uint8_t FreeRegs) const; 9765 ABIArgInfo classifyReturnType(QualType RetTy) const; 9766 }; 9767 9768 class ARCTargetCodeGenInfo : public TargetCodeGenInfo { 9769 public: 9770 ARCTargetCodeGenInfo(CodeGenTypes &CGT) 9771 : TargetCodeGenInfo(std::make_unique<ARCABIInfo>(CGT)) {} 9772 }; 9773 9774 9775 ABIArgInfo ARCABIInfo::getIndirectByRef(QualType Ty, bool HasFreeRegs) const { 9776 return HasFreeRegs ? getNaturalAlignIndirectInReg(Ty) : 9777 getNaturalAlignIndirect(Ty, false); 9778 } 9779 9780 ABIArgInfo ARCABIInfo::getIndirectByValue(QualType Ty) const { 9781 // Compute the byval alignment. 9782 const unsigned MinABIStackAlignInBytes = 4; 9783 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8; 9784 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true, 9785 TypeAlign > MinABIStackAlignInBytes); 9786 } 9787 9788 Address ARCABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 9789 QualType Ty) const { 9790 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false, 9791 getContext().getTypeInfoInChars(Ty), 9792 CharUnits::fromQuantity(4), true); 9793 } 9794 9795 ABIArgInfo ARCABIInfo::classifyArgumentType(QualType Ty, 9796 uint8_t FreeRegs) const { 9797 // Handle the generic C++ ABI. 9798 const RecordType *RT = Ty->getAs<RecordType>(); 9799 if (RT) { 9800 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()); 9801 if (RAA == CGCXXABI::RAA_Indirect) 9802 return getIndirectByRef(Ty, FreeRegs > 0); 9803 9804 if (RAA == CGCXXABI::RAA_DirectInMemory) 9805 return getIndirectByValue(Ty); 9806 } 9807 9808 // Treat an enum type as its underlying type. 9809 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 9810 Ty = EnumTy->getDecl()->getIntegerType(); 9811 9812 auto SizeInRegs = llvm::alignTo(getContext().getTypeSize(Ty), 32) / 32; 9813 9814 if (isAggregateTypeForABI(Ty)) { 9815 // Structures with flexible arrays are always indirect. 9816 if (RT && RT->getDecl()->hasFlexibleArrayMember()) 9817 return getIndirectByValue(Ty); 9818 9819 // Ignore empty structs/unions. 9820 if (isEmptyRecord(getContext(), Ty, true)) 9821 return ABIArgInfo::getIgnore(); 9822 9823 llvm::LLVMContext &LLVMContext = getVMContext(); 9824 9825 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext); 9826 SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32); 9827 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements); 9828 9829 return FreeRegs >= SizeInRegs ? 9830 ABIArgInfo::getDirectInReg(Result) : 9831 ABIArgInfo::getDirect(Result, 0, nullptr, false); 9832 } 9833 9834 if (const auto *EIT = Ty->getAs<ExtIntType>()) 9835 if (EIT->getNumBits() > 64) 9836 return getIndirectByValue(Ty); 9837 9838 return isPromotableIntegerTypeForABI(Ty) 9839 ? (FreeRegs >= SizeInRegs ? ABIArgInfo::getExtendInReg(Ty) 9840 : ABIArgInfo::getExtend(Ty)) 9841 : (FreeRegs >= SizeInRegs ? ABIArgInfo::getDirectInReg() 9842 : ABIArgInfo::getDirect()); 9843 } 9844 9845 ABIArgInfo ARCABIInfo::classifyReturnType(QualType RetTy) const { 9846 if (RetTy->isAnyComplexType()) 9847 return ABIArgInfo::getDirectInReg(); 9848 9849 // Arguments of size > 4 registers are indirect. 9850 auto RetSize = llvm::alignTo(getContext().getTypeSize(RetTy), 32) / 32; 9851 if (RetSize > 4) 9852 return getIndirectByRef(RetTy, /*HasFreeRegs*/ true); 9853 9854 return DefaultABIInfo::classifyReturnType(RetTy); 9855 } 9856 9857 } // End anonymous namespace. 9858 9859 //===----------------------------------------------------------------------===// 9860 // XCore ABI Implementation 9861 //===----------------------------------------------------------------------===// 9862 9863 namespace { 9864 9865 /// A SmallStringEnc instance is used to build up the TypeString by passing 9866 /// it by reference between functions that append to it. 9867 typedef llvm::SmallString<128> SmallStringEnc; 9868 9869 /// TypeStringCache caches the meta encodings of Types. 9870 /// 9871 /// The reason for caching TypeStrings is two fold: 9872 /// 1. To cache a type's encoding for later uses; 9873 /// 2. As a means to break recursive member type inclusion. 9874 /// 9875 /// A cache Entry can have a Status of: 9876 /// NonRecursive: The type encoding is not recursive; 9877 /// Recursive: The type encoding is recursive; 9878 /// Incomplete: An incomplete TypeString; 9879 /// IncompleteUsed: An incomplete TypeString that has been used in a 9880 /// Recursive type encoding. 9881 /// 9882 /// A NonRecursive entry will have all of its sub-members expanded as fully 9883 /// as possible. Whilst it may contain types which are recursive, the type 9884 /// itself is not recursive and thus its encoding may be safely used whenever 9885 /// the type is encountered. 9886 /// 9887 /// A Recursive entry will have all of its sub-members expanded as fully as 9888 /// possible. The type itself is recursive and it may contain other types which 9889 /// are recursive. The Recursive encoding must not be used during the expansion 9890 /// of a recursive type's recursive branch. For simplicity the code uses 9891 /// IncompleteCount to reject all usage of Recursive encodings for member types. 9892 /// 9893 /// An Incomplete entry is always a RecordType and only encodes its 9894 /// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and 9895 /// are placed into the cache during type expansion as a means to identify and 9896 /// handle recursive inclusion of types as sub-members. If there is recursion 9897 /// the entry becomes IncompleteUsed. 9898 /// 9899 /// During the expansion of a RecordType's members: 9900 /// 9901 /// If the cache contains a NonRecursive encoding for the member type, the 9902 /// cached encoding is used; 9903 /// 9904 /// If the cache contains a Recursive encoding for the member type, the 9905 /// cached encoding is 'Swapped' out, as it may be incorrect, and... 9906 /// 9907 /// If the member is a RecordType, an Incomplete encoding is placed into the 9908 /// cache to break potential recursive inclusion of itself as a sub-member; 9909 /// 9910 /// Once a member RecordType has been expanded, its temporary incomplete 9911 /// entry is removed from the cache. If a Recursive encoding was swapped out 9912 /// it is swapped back in; 9913 /// 9914 /// If an incomplete entry is used to expand a sub-member, the incomplete 9915 /// entry is marked as IncompleteUsed. The cache keeps count of how many 9916 /// IncompleteUsed entries it currently contains in IncompleteUsedCount; 9917 /// 9918 /// If a member's encoding is found to be a NonRecursive or Recursive viz: 9919 /// IncompleteUsedCount==0, the member's encoding is added to the cache. 9920 /// Else the member is part of a recursive type and thus the recursion has 9921 /// been exited too soon for the encoding to be correct for the member. 9922 /// 9923 class TypeStringCache { 9924 enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed}; 9925 struct Entry { 9926 std::string Str; // The encoded TypeString for the type. 9927 enum Status State; // Information about the encoding in 'Str'. 9928 std::string Swapped; // A temporary place holder for a Recursive encoding 9929 // during the expansion of RecordType's members. 9930 }; 9931 std::map<const IdentifierInfo *, struct Entry> Map; 9932 unsigned IncompleteCount; // Number of Incomplete entries in the Map. 9933 unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map. 9934 public: 9935 TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {} 9936 void addIncomplete(const IdentifierInfo *ID, std::string StubEnc); 9937 bool removeIncomplete(const IdentifierInfo *ID); 9938 void addIfComplete(const IdentifierInfo *ID, StringRef Str, 9939 bool IsRecursive); 9940 StringRef lookupStr(const IdentifierInfo *ID); 9941 }; 9942 9943 /// TypeString encodings for enum & union fields must be order. 9944 /// FieldEncoding is a helper for this ordering process. 9945 class FieldEncoding { 9946 bool HasName; 9947 std::string Enc; 9948 public: 9949 FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {} 9950 StringRef str() { return Enc; } 9951 bool operator<(const FieldEncoding &rhs) const { 9952 if (HasName != rhs.HasName) return HasName; 9953 return Enc < rhs.Enc; 9954 } 9955 }; 9956 9957 class XCoreABIInfo : public DefaultABIInfo { 9958 public: 9959 XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {} 9960 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 9961 QualType Ty) const override; 9962 }; 9963 9964 class XCoreTargetCodeGenInfo : public TargetCodeGenInfo { 9965 mutable TypeStringCache TSC; 9966 void emitTargetMD(const Decl *D, llvm::GlobalValue *GV, 9967 const CodeGen::CodeGenModule &M) const; 9968 9969 public: 9970 XCoreTargetCodeGenInfo(CodeGenTypes &CGT) 9971 : TargetCodeGenInfo(std::make_unique<XCoreABIInfo>(CGT)) {} 9972 void emitTargetMetadata(CodeGen::CodeGenModule &CGM, 9973 const llvm::MapVector<GlobalDecl, StringRef> 9974 &MangledDeclNames) const override; 9975 }; 9976 9977 } // End anonymous namespace. 9978 9979 // TODO: this implementation is likely now redundant with the default 9980 // EmitVAArg. 9981 Address XCoreABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 9982 QualType Ty) const { 9983 CGBuilderTy &Builder = CGF.Builder; 9984 9985 // Get the VAList. 9986 CharUnits SlotSize = CharUnits::fromQuantity(4); 9987 Address AP(Builder.CreateLoad(VAListAddr), SlotSize); 9988 9989 // Handle the argument. 9990 ABIArgInfo AI = classifyArgumentType(Ty); 9991 CharUnits TypeAlign = getContext().getTypeAlignInChars(Ty); 9992 llvm::Type *ArgTy = CGT.ConvertType(Ty); 9993 if (AI.canHaveCoerceToType() && !AI.getCoerceToType()) 9994 AI.setCoerceToType(ArgTy); 9995 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy); 9996 9997 Address Val = Address::invalid(); 9998 CharUnits ArgSize = CharUnits::Zero(); 9999 switch (AI.getKind()) { 10000 case ABIArgInfo::Expand: 10001 case ABIArgInfo::CoerceAndExpand: 10002 case ABIArgInfo::InAlloca: 10003 llvm_unreachable("Unsupported ABI kind for va_arg"); 10004 case ABIArgInfo::Ignore: 10005 Val = Address(llvm::UndefValue::get(ArgPtrTy), TypeAlign); 10006 ArgSize = CharUnits::Zero(); 10007 break; 10008 case ABIArgInfo::Extend: 10009 case ABIArgInfo::Direct: 10010 Val = Builder.CreateBitCast(AP, ArgPtrTy); 10011 ArgSize = CharUnits::fromQuantity( 10012 getDataLayout().getTypeAllocSize(AI.getCoerceToType())); 10013 ArgSize = ArgSize.alignTo(SlotSize); 10014 break; 10015 case ABIArgInfo::Indirect: 10016 case ABIArgInfo::IndirectAliased: 10017 Val = Builder.CreateElementBitCast(AP, ArgPtrTy); 10018 Val = Address(Builder.CreateLoad(Val), TypeAlign); 10019 ArgSize = SlotSize; 10020 break; 10021 } 10022 10023 // Increment the VAList. 10024 if (!ArgSize.isZero()) { 10025 Address APN = Builder.CreateConstInBoundsByteGEP(AP, ArgSize); 10026 Builder.CreateStore(APN.getPointer(), VAListAddr); 10027 } 10028 10029 return Val; 10030 } 10031 10032 /// During the expansion of a RecordType, an incomplete TypeString is placed 10033 /// into the cache as a means to identify and break recursion. 10034 /// If there is a Recursive encoding in the cache, it is swapped out and will 10035 /// be reinserted by removeIncomplete(). 10036 /// All other types of encoding should have been used rather than arriving here. 10037 void TypeStringCache::addIncomplete(const IdentifierInfo *ID, 10038 std::string StubEnc) { 10039 if (!ID) 10040 return; 10041 Entry &E = Map[ID]; 10042 assert( (E.Str.empty() || E.State == Recursive) && 10043 "Incorrectly use of addIncomplete"); 10044 assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()"); 10045 E.Swapped.swap(E.Str); // swap out the Recursive 10046 E.Str.swap(StubEnc); 10047 E.State = Incomplete; 10048 ++IncompleteCount; 10049 } 10050 10051 /// Once the RecordType has been expanded, the temporary incomplete TypeString 10052 /// must be removed from the cache. 10053 /// If a Recursive was swapped out by addIncomplete(), it will be replaced. 10054 /// Returns true if the RecordType was defined recursively. 10055 bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) { 10056 if (!ID) 10057 return false; 10058 auto I = Map.find(ID); 10059 assert(I != Map.end() && "Entry not present"); 10060 Entry &E = I->second; 10061 assert( (E.State == Incomplete || 10062 E.State == IncompleteUsed) && 10063 "Entry must be an incomplete type"); 10064 bool IsRecursive = false; 10065 if (E.State == IncompleteUsed) { 10066 // We made use of our Incomplete encoding, thus we are recursive. 10067 IsRecursive = true; 10068 --IncompleteUsedCount; 10069 } 10070 if (E.Swapped.empty()) 10071 Map.erase(I); 10072 else { 10073 // Swap the Recursive back. 10074 E.Swapped.swap(E.Str); 10075 E.Swapped.clear(); 10076 E.State = Recursive; 10077 } 10078 --IncompleteCount; 10079 return IsRecursive; 10080 } 10081 10082 /// Add the encoded TypeString to the cache only if it is NonRecursive or 10083 /// Recursive (viz: all sub-members were expanded as fully as possible). 10084 void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str, 10085 bool IsRecursive) { 10086 if (!ID || IncompleteUsedCount) 10087 return; // No key or it is is an incomplete sub-type so don't add. 10088 Entry &E = Map[ID]; 10089 if (IsRecursive && !E.Str.empty()) { 10090 assert(E.State==Recursive && E.Str.size() == Str.size() && 10091 "This is not the same Recursive entry"); 10092 // The parent container was not recursive after all, so we could have used 10093 // this Recursive sub-member entry after all, but we assumed the worse when 10094 // we started viz: IncompleteCount!=0. 10095 return; 10096 } 10097 assert(E.Str.empty() && "Entry already present"); 10098 E.Str = Str.str(); 10099 E.State = IsRecursive? Recursive : NonRecursive; 10100 } 10101 10102 /// Return a cached TypeString encoding for the ID. If there isn't one, or we 10103 /// are recursively expanding a type (IncompleteCount != 0) and the cached 10104 /// encoding is Recursive, return an empty StringRef. 10105 StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) { 10106 if (!ID) 10107 return StringRef(); // We have no key. 10108 auto I = Map.find(ID); 10109 if (I == Map.end()) 10110 return StringRef(); // We have no encoding. 10111 Entry &E = I->second; 10112 if (E.State == Recursive && IncompleteCount) 10113 return StringRef(); // We don't use Recursive encodings for member types. 10114 10115 if (E.State == Incomplete) { 10116 // The incomplete type is being used to break out of recursion. 10117 E.State = IncompleteUsed; 10118 ++IncompleteUsedCount; 10119 } 10120 return E.Str; 10121 } 10122 10123 /// The XCore ABI includes a type information section that communicates symbol 10124 /// type information to the linker. The linker uses this information to verify 10125 /// safety/correctness of things such as array bound and pointers et al. 10126 /// The ABI only requires C (and XC) language modules to emit TypeStrings. 10127 /// This type information (TypeString) is emitted into meta data for all global 10128 /// symbols: definitions, declarations, functions & variables. 10129 /// 10130 /// The TypeString carries type, qualifier, name, size & value details. 10131 /// Please see 'Tools Development Guide' section 2.16.2 for format details: 10132 /// https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf 10133 /// The output is tested by test/CodeGen/xcore-stringtype.c. 10134 /// 10135 static bool getTypeString(SmallStringEnc &Enc, const Decl *D, 10136 const CodeGen::CodeGenModule &CGM, 10137 TypeStringCache &TSC); 10138 10139 /// XCore uses emitTargetMD to emit TypeString metadata for global symbols. 10140 void XCoreTargetCodeGenInfo::emitTargetMD( 10141 const Decl *D, llvm::GlobalValue *GV, 10142 const CodeGen::CodeGenModule &CGM) const { 10143 SmallStringEnc Enc; 10144 if (getTypeString(Enc, D, CGM, TSC)) { 10145 llvm::LLVMContext &Ctx = CGM.getModule().getContext(); 10146 llvm::Metadata *MDVals[] = {llvm::ConstantAsMetadata::get(GV), 10147 llvm::MDString::get(Ctx, Enc.str())}; 10148 llvm::NamedMDNode *MD = 10149 CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings"); 10150 MD->addOperand(llvm::MDNode::get(Ctx, MDVals)); 10151 } 10152 } 10153 10154 void XCoreTargetCodeGenInfo::emitTargetMetadata( 10155 CodeGen::CodeGenModule &CGM, 10156 const llvm::MapVector<GlobalDecl, StringRef> &MangledDeclNames) const { 10157 // Warning, new MangledDeclNames may be appended within this loop. 10158 // We rely on MapVector insertions adding new elements to the end 10159 // of the container. 10160 for (unsigned I = 0; I != MangledDeclNames.size(); ++I) { 10161 auto Val = *(MangledDeclNames.begin() + I); 10162 llvm::GlobalValue *GV = CGM.GetGlobalValue(Val.second); 10163 if (GV) { 10164 const Decl *D = Val.first.getDecl()->getMostRecentDecl(); 10165 emitTargetMD(D, GV, CGM); 10166 } 10167 } 10168 } 10169 //===----------------------------------------------------------------------===// 10170 // SPIR ABI Implementation 10171 //===----------------------------------------------------------------------===// 10172 10173 namespace { 10174 class SPIRABIInfo : public DefaultABIInfo { 10175 public: 10176 SPIRABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) { setCCs(); } 10177 10178 private: 10179 void setCCs(); 10180 }; 10181 } // end anonymous namespace 10182 namespace { 10183 class SPIRTargetCodeGenInfo : public TargetCodeGenInfo { 10184 public: 10185 SPIRTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT) 10186 : TargetCodeGenInfo(std::make_unique<SPIRABIInfo>(CGT)) {} 10187 10188 LangAS getASTAllocaAddressSpace() const override { 10189 return getLangASFromTargetAS( 10190 getABIInfo().getDataLayout().getAllocaAddrSpace()); 10191 } 10192 10193 unsigned getOpenCLKernelCallingConv() const override; 10194 }; 10195 10196 } // End anonymous namespace. 10197 void SPIRABIInfo::setCCs() { 10198 assert(getRuntimeCC() == llvm::CallingConv::C); 10199 RuntimeCC = llvm::CallingConv::SPIR_FUNC; 10200 } 10201 10202 namespace clang { 10203 namespace CodeGen { 10204 void computeSPIRKernelABIInfo(CodeGenModule &CGM, CGFunctionInfo &FI) { 10205 DefaultABIInfo SPIRABI(CGM.getTypes()); 10206 SPIRABI.computeInfo(FI); 10207 } 10208 } 10209 } 10210 10211 unsigned SPIRTargetCodeGenInfo::getOpenCLKernelCallingConv() const { 10212 return llvm::CallingConv::SPIR_KERNEL; 10213 } 10214 10215 static bool appendType(SmallStringEnc &Enc, QualType QType, 10216 const CodeGen::CodeGenModule &CGM, 10217 TypeStringCache &TSC); 10218 10219 /// Helper function for appendRecordType(). 10220 /// Builds a SmallVector containing the encoded field types in declaration 10221 /// order. 10222 static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE, 10223 const RecordDecl *RD, 10224 const CodeGen::CodeGenModule &CGM, 10225 TypeStringCache &TSC) { 10226 for (const auto *Field : RD->fields()) { 10227 SmallStringEnc Enc; 10228 Enc += "m("; 10229 Enc += Field->getName(); 10230 Enc += "){"; 10231 if (Field->isBitField()) { 10232 Enc += "b("; 10233 llvm::raw_svector_ostream OS(Enc); 10234 OS << Field->getBitWidthValue(CGM.getContext()); 10235 Enc += ':'; 10236 } 10237 if (!appendType(Enc, Field->getType(), CGM, TSC)) 10238 return false; 10239 if (Field->isBitField()) 10240 Enc += ')'; 10241 Enc += '}'; 10242 FE.emplace_back(!Field->getName().empty(), Enc); 10243 } 10244 return true; 10245 } 10246 10247 /// Appends structure and union types to Enc and adds encoding to cache. 10248 /// Recursively calls appendType (via extractFieldType) for each field. 10249 /// Union types have their fields ordered according to the ABI. 10250 static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT, 10251 const CodeGen::CodeGenModule &CGM, 10252 TypeStringCache &TSC, const IdentifierInfo *ID) { 10253 // Append the cached TypeString if we have one. 10254 StringRef TypeString = TSC.lookupStr(ID); 10255 if (!TypeString.empty()) { 10256 Enc += TypeString; 10257 return true; 10258 } 10259 10260 // Start to emit an incomplete TypeString. 10261 size_t Start = Enc.size(); 10262 Enc += (RT->isUnionType()? 'u' : 's'); 10263 Enc += '('; 10264 if (ID) 10265 Enc += ID->getName(); 10266 Enc += "){"; 10267 10268 // We collect all encoded fields and order as necessary. 10269 bool IsRecursive = false; 10270 const RecordDecl *RD = RT->getDecl()->getDefinition(); 10271 if (RD && !RD->field_empty()) { 10272 // An incomplete TypeString stub is placed in the cache for this RecordType 10273 // so that recursive calls to this RecordType will use it whilst building a 10274 // complete TypeString for this RecordType. 10275 SmallVector<FieldEncoding, 16> FE; 10276 std::string StubEnc(Enc.substr(Start).str()); 10277 StubEnc += '}'; // StubEnc now holds a valid incomplete TypeString. 10278 TSC.addIncomplete(ID, std::move(StubEnc)); 10279 if (!extractFieldType(FE, RD, CGM, TSC)) { 10280 (void) TSC.removeIncomplete(ID); 10281 return false; 10282 } 10283 IsRecursive = TSC.removeIncomplete(ID); 10284 // The ABI requires unions to be sorted but not structures. 10285 // See FieldEncoding::operator< for sort algorithm. 10286 if (RT->isUnionType()) 10287 llvm::sort(FE); 10288 // We can now complete the TypeString. 10289 unsigned E = FE.size(); 10290 for (unsigned I = 0; I != E; ++I) { 10291 if (I) 10292 Enc += ','; 10293 Enc += FE[I].str(); 10294 } 10295 } 10296 Enc += '}'; 10297 TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive); 10298 return true; 10299 } 10300 10301 /// Appends enum types to Enc and adds the encoding to the cache. 10302 static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET, 10303 TypeStringCache &TSC, 10304 const IdentifierInfo *ID) { 10305 // Append the cached TypeString if we have one. 10306 StringRef TypeString = TSC.lookupStr(ID); 10307 if (!TypeString.empty()) { 10308 Enc += TypeString; 10309 return true; 10310 } 10311 10312 size_t Start = Enc.size(); 10313 Enc += "e("; 10314 if (ID) 10315 Enc += ID->getName(); 10316 Enc += "){"; 10317 10318 // We collect all encoded enumerations and order them alphanumerically. 10319 if (const EnumDecl *ED = ET->getDecl()->getDefinition()) { 10320 SmallVector<FieldEncoding, 16> FE; 10321 for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E; 10322 ++I) { 10323 SmallStringEnc EnumEnc; 10324 EnumEnc += "m("; 10325 EnumEnc += I->getName(); 10326 EnumEnc += "){"; 10327 I->getInitVal().toString(EnumEnc); 10328 EnumEnc += '}'; 10329 FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc)); 10330 } 10331 llvm::sort(FE); 10332 unsigned E = FE.size(); 10333 for (unsigned I = 0; I != E; ++I) { 10334 if (I) 10335 Enc += ','; 10336 Enc += FE[I].str(); 10337 } 10338 } 10339 Enc += '}'; 10340 TSC.addIfComplete(ID, Enc.substr(Start), false); 10341 return true; 10342 } 10343 10344 /// Appends type's qualifier to Enc. 10345 /// This is done prior to appending the type's encoding. 10346 static void appendQualifier(SmallStringEnc &Enc, QualType QT) { 10347 // Qualifiers are emitted in alphabetical order. 10348 static const char *const Table[]={"","c:","r:","cr:","v:","cv:","rv:","crv:"}; 10349 int Lookup = 0; 10350 if (QT.isConstQualified()) 10351 Lookup += 1<<0; 10352 if (QT.isRestrictQualified()) 10353 Lookup += 1<<1; 10354 if (QT.isVolatileQualified()) 10355 Lookup += 1<<2; 10356 Enc += Table[Lookup]; 10357 } 10358 10359 /// Appends built-in types to Enc. 10360 static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) { 10361 const char *EncType; 10362 switch (BT->getKind()) { 10363 case BuiltinType::Void: 10364 EncType = "0"; 10365 break; 10366 case BuiltinType::Bool: 10367 EncType = "b"; 10368 break; 10369 case BuiltinType::Char_U: 10370 EncType = "uc"; 10371 break; 10372 case BuiltinType::UChar: 10373 EncType = "uc"; 10374 break; 10375 case BuiltinType::SChar: 10376 EncType = "sc"; 10377 break; 10378 case BuiltinType::UShort: 10379 EncType = "us"; 10380 break; 10381 case BuiltinType::Short: 10382 EncType = "ss"; 10383 break; 10384 case BuiltinType::UInt: 10385 EncType = "ui"; 10386 break; 10387 case BuiltinType::Int: 10388 EncType = "si"; 10389 break; 10390 case BuiltinType::ULong: 10391 EncType = "ul"; 10392 break; 10393 case BuiltinType::Long: 10394 EncType = "sl"; 10395 break; 10396 case BuiltinType::ULongLong: 10397 EncType = "ull"; 10398 break; 10399 case BuiltinType::LongLong: 10400 EncType = "sll"; 10401 break; 10402 case BuiltinType::Float: 10403 EncType = "ft"; 10404 break; 10405 case BuiltinType::Double: 10406 EncType = "d"; 10407 break; 10408 case BuiltinType::LongDouble: 10409 EncType = "ld"; 10410 break; 10411 default: 10412 return false; 10413 } 10414 Enc += EncType; 10415 return true; 10416 } 10417 10418 /// Appends a pointer encoding to Enc before calling appendType for the pointee. 10419 static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT, 10420 const CodeGen::CodeGenModule &CGM, 10421 TypeStringCache &TSC) { 10422 Enc += "p("; 10423 if (!appendType(Enc, PT->getPointeeType(), CGM, TSC)) 10424 return false; 10425 Enc += ')'; 10426 return true; 10427 } 10428 10429 /// Appends array encoding to Enc before calling appendType for the element. 10430 static bool appendArrayType(SmallStringEnc &Enc, QualType QT, 10431 const ArrayType *AT, 10432 const CodeGen::CodeGenModule &CGM, 10433 TypeStringCache &TSC, StringRef NoSizeEnc) { 10434 if (AT->getSizeModifier() != ArrayType::Normal) 10435 return false; 10436 Enc += "a("; 10437 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) 10438 CAT->getSize().toStringUnsigned(Enc); 10439 else 10440 Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "". 10441 Enc += ':'; 10442 // The Qualifiers should be attached to the type rather than the array. 10443 appendQualifier(Enc, QT); 10444 if (!appendType(Enc, AT->getElementType(), CGM, TSC)) 10445 return false; 10446 Enc += ')'; 10447 return true; 10448 } 10449 10450 /// Appends a function encoding to Enc, calling appendType for the return type 10451 /// and the arguments. 10452 static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT, 10453 const CodeGen::CodeGenModule &CGM, 10454 TypeStringCache &TSC) { 10455 Enc += "f{"; 10456 if (!appendType(Enc, FT->getReturnType(), CGM, TSC)) 10457 return false; 10458 Enc += "}("; 10459 if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) { 10460 // N.B. we are only interested in the adjusted param types. 10461 auto I = FPT->param_type_begin(); 10462 auto E = FPT->param_type_end(); 10463 if (I != E) { 10464 do { 10465 if (!appendType(Enc, *I, CGM, TSC)) 10466 return false; 10467 ++I; 10468 if (I != E) 10469 Enc += ','; 10470 } while (I != E); 10471 if (FPT->isVariadic()) 10472 Enc += ",va"; 10473 } else { 10474 if (FPT->isVariadic()) 10475 Enc += "va"; 10476 else 10477 Enc += '0'; 10478 } 10479 } 10480 Enc += ')'; 10481 return true; 10482 } 10483 10484 /// Handles the type's qualifier before dispatching a call to handle specific 10485 /// type encodings. 10486 static bool appendType(SmallStringEnc &Enc, QualType QType, 10487 const CodeGen::CodeGenModule &CGM, 10488 TypeStringCache &TSC) { 10489 10490 QualType QT = QType.getCanonicalType(); 10491 10492 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) 10493 // The Qualifiers should be attached to the type rather than the array. 10494 // Thus we don't call appendQualifier() here. 10495 return appendArrayType(Enc, QT, AT, CGM, TSC, ""); 10496 10497 appendQualifier(Enc, QT); 10498 10499 if (const BuiltinType *BT = QT->getAs<BuiltinType>()) 10500 return appendBuiltinType(Enc, BT); 10501 10502 if (const PointerType *PT = QT->getAs<PointerType>()) 10503 return appendPointerType(Enc, PT, CGM, TSC); 10504 10505 if (const EnumType *ET = QT->getAs<EnumType>()) 10506 return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier()); 10507 10508 if (const RecordType *RT = QT->getAsStructureType()) 10509 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier()); 10510 10511 if (const RecordType *RT = QT->getAsUnionType()) 10512 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier()); 10513 10514 if (const FunctionType *FT = QT->getAs<FunctionType>()) 10515 return appendFunctionType(Enc, FT, CGM, TSC); 10516 10517 return false; 10518 } 10519 10520 static bool getTypeString(SmallStringEnc &Enc, const Decl *D, 10521 const CodeGen::CodeGenModule &CGM, 10522 TypeStringCache &TSC) { 10523 if (!D) 10524 return false; 10525 10526 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 10527 if (FD->getLanguageLinkage() != CLanguageLinkage) 10528 return false; 10529 return appendType(Enc, FD->getType(), CGM, TSC); 10530 } 10531 10532 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 10533 if (VD->getLanguageLinkage() != CLanguageLinkage) 10534 return false; 10535 QualType QT = VD->getType().getCanonicalType(); 10536 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) { 10537 // Global ArrayTypes are given a size of '*' if the size is unknown. 10538 // The Qualifiers should be attached to the type rather than the array. 10539 // Thus we don't call appendQualifier() here. 10540 return appendArrayType(Enc, QT, AT, CGM, TSC, "*"); 10541 } 10542 return appendType(Enc, QT, CGM, TSC); 10543 } 10544 return false; 10545 } 10546 10547 //===----------------------------------------------------------------------===// 10548 // RISCV ABI Implementation 10549 //===----------------------------------------------------------------------===// 10550 10551 namespace { 10552 class RISCVABIInfo : public DefaultABIInfo { 10553 private: 10554 // Size of the integer ('x') registers in bits. 10555 unsigned XLen; 10556 // Size of the floating point ('f') registers in bits. Note that the target 10557 // ISA might have a wider FLen than the selected ABI (e.g. an RV32IF target 10558 // with soft float ABI has FLen==0). 10559 unsigned FLen; 10560 static const int NumArgGPRs = 8; 10561 static const int NumArgFPRs = 8; 10562 bool detectFPCCEligibleStructHelper(QualType Ty, CharUnits CurOff, 10563 llvm::Type *&Field1Ty, 10564 CharUnits &Field1Off, 10565 llvm::Type *&Field2Ty, 10566 CharUnits &Field2Off) const; 10567 10568 public: 10569 RISCVABIInfo(CodeGen::CodeGenTypes &CGT, unsigned XLen, unsigned FLen) 10570 : DefaultABIInfo(CGT), XLen(XLen), FLen(FLen) {} 10571 10572 // DefaultABIInfo's classifyReturnType and classifyArgumentType are 10573 // non-virtual, but computeInfo is virtual, so we overload it. 10574 void computeInfo(CGFunctionInfo &FI) const override; 10575 10576 ABIArgInfo classifyArgumentType(QualType Ty, bool IsFixed, int &ArgGPRsLeft, 10577 int &ArgFPRsLeft) const; 10578 ABIArgInfo classifyReturnType(QualType RetTy) const; 10579 10580 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 10581 QualType Ty) const override; 10582 10583 ABIArgInfo extendType(QualType Ty) const; 10584 10585 bool detectFPCCEligibleStruct(QualType Ty, llvm::Type *&Field1Ty, 10586 CharUnits &Field1Off, llvm::Type *&Field2Ty, 10587 CharUnits &Field2Off, int &NeededArgGPRs, 10588 int &NeededArgFPRs) const; 10589 ABIArgInfo coerceAndExpandFPCCEligibleStruct(llvm::Type *Field1Ty, 10590 CharUnits Field1Off, 10591 llvm::Type *Field2Ty, 10592 CharUnits Field2Off) const; 10593 }; 10594 } // end anonymous namespace 10595 10596 void RISCVABIInfo::computeInfo(CGFunctionInfo &FI) const { 10597 QualType RetTy = FI.getReturnType(); 10598 if (!getCXXABI().classifyReturnType(FI)) 10599 FI.getReturnInfo() = classifyReturnType(RetTy); 10600 10601 // IsRetIndirect is true if classifyArgumentType indicated the value should 10602 // be passed indirect, or if the type size is a scalar greater than 2*XLen 10603 // and not a complex type with elements <= FLen. e.g. fp128 is passed direct 10604 // in LLVM IR, relying on the backend lowering code to rewrite the argument 10605 // list and pass indirectly on RV32. 10606 bool IsRetIndirect = FI.getReturnInfo().getKind() == ABIArgInfo::Indirect; 10607 if (!IsRetIndirect && RetTy->isScalarType() && 10608 getContext().getTypeSize(RetTy) > (2 * XLen)) { 10609 if (RetTy->isComplexType() && FLen) { 10610 QualType EltTy = RetTy->castAs<ComplexType>()->getElementType(); 10611 IsRetIndirect = getContext().getTypeSize(EltTy) > FLen; 10612 } else { 10613 // This is a normal scalar > 2*XLen, such as fp128 on RV32. 10614 IsRetIndirect = true; 10615 } 10616 } 10617 10618 // We must track the number of GPRs used in order to conform to the RISC-V 10619 // ABI, as integer scalars passed in registers should have signext/zeroext 10620 // when promoted, but are anyext if passed on the stack. As GPR usage is 10621 // different for variadic arguments, we must also track whether we are 10622 // examining a vararg or not. 10623 int ArgGPRsLeft = IsRetIndirect ? NumArgGPRs - 1 : NumArgGPRs; 10624 int ArgFPRsLeft = FLen ? NumArgFPRs : 0; 10625 int NumFixedArgs = FI.getNumRequiredArgs(); 10626 10627 int ArgNum = 0; 10628 for (auto &ArgInfo : FI.arguments()) { 10629 bool IsFixed = ArgNum < NumFixedArgs; 10630 ArgInfo.info = 10631 classifyArgumentType(ArgInfo.type, IsFixed, ArgGPRsLeft, ArgFPRsLeft); 10632 ArgNum++; 10633 } 10634 } 10635 10636 // Returns true if the struct is a potential candidate for the floating point 10637 // calling convention. If this function returns true, the caller is 10638 // responsible for checking that if there is only a single field then that 10639 // field is a float. 10640 bool RISCVABIInfo::detectFPCCEligibleStructHelper(QualType Ty, CharUnits CurOff, 10641 llvm::Type *&Field1Ty, 10642 CharUnits &Field1Off, 10643 llvm::Type *&Field2Ty, 10644 CharUnits &Field2Off) const { 10645 bool IsInt = Ty->isIntegralOrEnumerationType(); 10646 bool IsFloat = Ty->isRealFloatingType(); 10647 10648 if (IsInt || IsFloat) { 10649 uint64_t Size = getContext().getTypeSize(Ty); 10650 if (IsInt && Size > XLen) 10651 return false; 10652 // Can't be eligible if larger than the FP registers. Half precision isn't 10653 // currently supported on RISC-V and the ABI hasn't been confirmed, so 10654 // default to the integer ABI in that case. 10655 if (IsFloat && (Size > FLen || Size < 32)) 10656 return false; 10657 // Can't be eligible if an integer type was already found (int+int pairs 10658 // are not eligible). 10659 if (IsInt && Field1Ty && Field1Ty->isIntegerTy()) 10660 return false; 10661 if (!Field1Ty) { 10662 Field1Ty = CGT.ConvertType(Ty); 10663 Field1Off = CurOff; 10664 return true; 10665 } 10666 if (!Field2Ty) { 10667 Field2Ty = CGT.ConvertType(Ty); 10668 Field2Off = CurOff; 10669 return true; 10670 } 10671 return false; 10672 } 10673 10674 if (auto CTy = Ty->getAs<ComplexType>()) { 10675 if (Field1Ty) 10676 return false; 10677 QualType EltTy = CTy->getElementType(); 10678 if (getContext().getTypeSize(EltTy) > FLen) 10679 return false; 10680 Field1Ty = CGT.ConvertType(EltTy); 10681 Field1Off = CurOff; 10682 Field2Ty = Field1Ty; 10683 Field2Off = Field1Off + getContext().getTypeSizeInChars(EltTy); 10684 return true; 10685 } 10686 10687 if (const ConstantArrayType *ATy = getContext().getAsConstantArrayType(Ty)) { 10688 uint64_t ArraySize = ATy->getSize().getZExtValue(); 10689 QualType EltTy = ATy->getElementType(); 10690 CharUnits EltSize = getContext().getTypeSizeInChars(EltTy); 10691 for (uint64_t i = 0; i < ArraySize; ++i) { 10692 bool Ret = detectFPCCEligibleStructHelper(EltTy, CurOff, Field1Ty, 10693 Field1Off, Field2Ty, Field2Off); 10694 if (!Ret) 10695 return false; 10696 CurOff += EltSize; 10697 } 10698 return true; 10699 } 10700 10701 if (const auto *RTy = Ty->getAs<RecordType>()) { 10702 // Structures with either a non-trivial destructor or a non-trivial 10703 // copy constructor are not eligible for the FP calling convention. 10704 if (getRecordArgABI(Ty, CGT.getCXXABI())) 10705 return false; 10706 if (isEmptyRecord(getContext(), Ty, true)) 10707 return true; 10708 const RecordDecl *RD = RTy->getDecl(); 10709 // Unions aren't eligible unless they're empty (which is caught above). 10710 if (RD->isUnion()) 10711 return false; 10712 int ZeroWidthBitFieldCount = 0; 10713 for (const FieldDecl *FD : RD->fields()) { 10714 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD); 10715 uint64_t FieldOffInBits = Layout.getFieldOffset(FD->getFieldIndex()); 10716 QualType QTy = FD->getType(); 10717 if (FD->isBitField()) { 10718 unsigned BitWidth = FD->getBitWidthValue(getContext()); 10719 // Allow a bitfield with a type greater than XLen as long as the 10720 // bitwidth is XLen or less. 10721 if (getContext().getTypeSize(QTy) > XLen && BitWidth <= XLen) 10722 QTy = getContext().getIntTypeForBitwidth(XLen, false); 10723 if (BitWidth == 0) { 10724 ZeroWidthBitFieldCount++; 10725 continue; 10726 } 10727 } 10728 10729 bool Ret = detectFPCCEligibleStructHelper( 10730 QTy, CurOff + getContext().toCharUnitsFromBits(FieldOffInBits), 10731 Field1Ty, Field1Off, Field2Ty, Field2Off); 10732 if (!Ret) 10733 return false; 10734 10735 // As a quirk of the ABI, zero-width bitfields aren't ignored for fp+fp 10736 // or int+fp structs, but are ignored for a struct with an fp field and 10737 // any number of zero-width bitfields. 10738 if (Field2Ty && ZeroWidthBitFieldCount > 0) 10739 return false; 10740 } 10741 return Field1Ty != nullptr; 10742 } 10743 10744 return false; 10745 } 10746 10747 // Determine if a struct is eligible for passing according to the floating 10748 // point calling convention (i.e., when flattened it contains a single fp 10749 // value, fp+fp, or int+fp of appropriate size). If so, NeededArgFPRs and 10750 // NeededArgGPRs are incremented appropriately. 10751 bool RISCVABIInfo::detectFPCCEligibleStruct(QualType Ty, llvm::Type *&Field1Ty, 10752 CharUnits &Field1Off, 10753 llvm::Type *&Field2Ty, 10754 CharUnits &Field2Off, 10755 int &NeededArgGPRs, 10756 int &NeededArgFPRs) const { 10757 Field1Ty = nullptr; 10758 Field2Ty = nullptr; 10759 NeededArgGPRs = 0; 10760 NeededArgFPRs = 0; 10761 bool IsCandidate = detectFPCCEligibleStructHelper( 10762 Ty, CharUnits::Zero(), Field1Ty, Field1Off, Field2Ty, Field2Off); 10763 // Not really a candidate if we have a single int but no float. 10764 if (Field1Ty && !Field2Ty && !Field1Ty->isFloatingPointTy()) 10765 return false; 10766 if (!IsCandidate) 10767 return false; 10768 if (Field1Ty && Field1Ty->isFloatingPointTy()) 10769 NeededArgFPRs++; 10770 else if (Field1Ty) 10771 NeededArgGPRs++; 10772 if (Field2Ty && Field2Ty->isFloatingPointTy()) 10773 NeededArgFPRs++; 10774 else if (Field2Ty) 10775 NeededArgGPRs++; 10776 return true; 10777 } 10778 10779 // Call getCoerceAndExpand for the two-element flattened struct described by 10780 // Field1Ty, Field1Off, Field2Ty, Field2Off. This method will create an 10781 // appropriate coerceToType and unpaddedCoerceToType. 10782 ABIArgInfo RISCVABIInfo::coerceAndExpandFPCCEligibleStruct( 10783 llvm::Type *Field1Ty, CharUnits Field1Off, llvm::Type *Field2Ty, 10784 CharUnits Field2Off) const { 10785 SmallVector<llvm::Type *, 3> CoerceElts; 10786 SmallVector<llvm::Type *, 2> UnpaddedCoerceElts; 10787 if (!Field1Off.isZero()) 10788 CoerceElts.push_back(llvm::ArrayType::get( 10789 llvm::Type::getInt8Ty(getVMContext()), Field1Off.getQuantity())); 10790 10791 CoerceElts.push_back(Field1Ty); 10792 UnpaddedCoerceElts.push_back(Field1Ty); 10793 10794 if (!Field2Ty) { 10795 return ABIArgInfo::getCoerceAndExpand( 10796 llvm::StructType::get(getVMContext(), CoerceElts, !Field1Off.isZero()), 10797 UnpaddedCoerceElts[0]); 10798 } 10799 10800 CharUnits Field2Align = 10801 CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(Field2Ty)); 10802 CharUnits Field1End = Field1Off + 10803 CharUnits::fromQuantity(getDataLayout().getTypeStoreSize(Field1Ty)); 10804 CharUnits Field2OffNoPadNoPack = Field1End.alignTo(Field2Align); 10805 10806 CharUnits Padding = CharUnits::Zero(); 10807 if (Field2Off > Field2OffNoPadNoPack) 10808 Padding = Field2Off - Field2OffNoPadNoPack; 10809 else if (Field2Off != Field2Align && Field2Off > Field1End) 10810 Padding = Field2Off - Field1End; 10811 10812 bool IsPacked = !Field2Off.isMultipleOf(Field2Align); 10813 10814 if (!Padding.isZero()) 10815 CoerceElts.push_back(llvm::ArrayType::get( 10816 llvm::Type::getInt8Ty(getVMContext()), Padding.getQuantity())); 10817 10818 CoerceElts.push_back(Field2Ty); 10819 UnpaddedCoerceElts.push_back(Field2Ty); 10820 10821 auto CoerceToType = 10822 llvm::StructType::get(getVMContext(), CoerceElts, IsPacked); 10823 auto UnpaddedCoerceToType = 10824 llvm::StructType::get(getVMContext(), UnpaddedCoerceElts, IsPacked); 10825 10826 return ABIArgInfo::getCoerceAndExpand(CoerceToType, UnpaddedCoerceToType); 10827 } 10828 10829 ABIArgInfo RISCVABIInfo::classifyArgumentType(QualType Ty, bool IsFixed, 10830 int &ArgGPRsLeft, 10831 int &ArgFPRsLeft) const { 10832 assert(ArgGPRsLeft <= NumArgGPRs && "Arg GPR tracking underflow"); 10833 Ty = useFirstFieldIfTransparentUnion(Ty); 10834 10835 // Structures with either a non-trivial destructor or a non-trivial 10836 // copy constructor are always passed indirectly. 10837 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) { 10838 if (ArgGPRsLeft) 10839 ArgGPRsLeft -= 1; 10840 return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA == 10841 CGCXXABI::RAA_DirectInMemory); 10842 } 10843 10844 // Ignore empty structs/unions. 10845 if (isEmptyRecord(getContext(), Ty, true)) 10846 return ABIArgInfo::getIgnore(); 10847 10848 uint64_t Size = getContext().getTypeSize(Ty); 10849 10850 // Pass floating point values via FPRs if possible. 10851 if (IsFixed && Ty->isFloatingType() && !Ty->isComplexType() && 10852 FLen >= Size && ArgFPRsLeft) { 10853 ArgFPRsLeft--; 10854 return ABIArgInfo::getDirect(); 10855 } 10856 10857 // Complex types for the hard float ABI must be passed direct rather than 10858 // using CoerceAndExpand. 10859 if (IsFixed && Ty->isComplexType() && FLen && ArgFPRsLeft >= 2) { 10860 QualType EltTy = Ty->castAs<ComplexType>()->getElementType(); 10861 if (getContext().getTypeSize(EltTy) <= FLen) { 10862 ArgFPRsLeft -= 2; 10863 return ABIArgInfo::getDirect(); 10864 } 10865 } 10866 10867 if (IsFixed && FLen && Ty->isStructureOrClassType()) { 10868 llvm::Type *Field1Ty = nullptr; 10869 llvm::Type *Field2Ty = nullptr; 10870 CharUnits Field1Off = CharUnits::Zero(); 10871 CharUnits Field2Off = CharUnits::Zero(); 10872 int NeededArgGPRs = 0; 10873 int NeededArgFPRs = 0; 10874 bool IsCandidate = 10875 detectFPCCEligibleStruct(Ty, Field1Ty, Field1Off, Field2Ty, Field2Off, 10876 NeededArgGPRs, NeededArgFPRs); 10877 if (IsCandidate && NeededArgGPRs <= ArgGPRsLeft && 10878 NeededArgFPRs <= ArgFPRsLeft) { 10879 ArgGPRsLeft -= NeededArgGPRs; 10880 ArgFPRsLeft -= NeededArgFPRs; 10881 return coerceAndExpandFPCCEligibleStruct(Field1Ty, Field1Off, Field2Ty, 10882 Field2Off); 10883 } 10884 } 10885 10886 uint64_t NeededAlign = getContext().getTypeAlign(Ty); 10887 bool MustUseStack = false; 10888 // Determine the number of GPRs needed to pass the current argument 10889 // according to the ABI. 2*XLen-aligned varargs are passed in "aligned" 10890 // register pairs, so may consume 3 registers. 10891 int NeededArgGPRs = 1; 10892 if (!IsFixed && NeededAlign == 2 * XLen) 10893 NeededArgGPRs = 2 + (ArgGPRsLeft % 2); 10894 else if (Size > XLen && Size <= 2 * XLen) 10895 NeededArgGPRs = 2; 10896 10897 if (NeededArgGPRs > ArgGPRsLeft) { 10898 MustUseStack = true; 10899 NeededArgGPRs = ArgGPRsLeft; 10900 } 10901 10902 ArgGPRsLeft -= NeededArgGPRs; 10903 10904 if (!isAggregateTypeForABI(Ty) && !Ty->isVectorType()) { 10905 // Treat an enum type as its underlying type. 10906 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 10907 Ty = EnumTy->getDecl()->getIntegerType(); 10908 10909 // All integral types are promoted to XLen width, unless passed on the 10910 // stack. 10911 if (Size < XLen && Ty->isIntegralOrEnumerationType() && !MustUseStack) { 10912 return extendType(Ty); 10913 } 10914 10915 if (const auto *EIT = Ty->getAs<ExtIntType>()) { 10916 if (EIT->getNumBits() < XLen && !MustUseStack) 10917 return extendType(Ty); 10918 if (EIT->getNumBits() > 128 || 10919 (!getContext().getTargetInfo().hasInt128Type() && 10920 EIT->getNumBits() > 64)) 10921 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 10922 } 10923 10924 return ABIArgInfo::getDirect(); 10925 } 10926 10927 // Aggregates which are <= 2*XLen will be passed in registers if possible, 10928 // so coerce to integers. 10929 if (Size <= 2 * XLen) { 10930 unsigned Alignment = getContext().getTypeAlign(Ty); 10931 10932 // Use a single XLen int if possible, 2*XLen if 2*XLen alignment is 10933 // required, and a 2-element XLen array if only XLen alignment is required. 10934 if (Size <= XLen) { 10935 return ABIArgInfo::getDirect( 10936 llvm::IntegerType::get(getVMContext(), XLen)); 10937 } else if (Alignment == 2 * XLen) { 10938 return ABIArgInfo::getDirect( 10939 llvm::IntegerType::get(getVMContext(), 2 * XLen)); 10940 } else { 10941 return ABIArgInfo::getDirect(llvm::ArrayType::get( 10942 llvm::IntegerType::get(getVMContext(), XLen), 2)); 10943 } 10944 } 10945 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 10946 } 10947 10948 ABIArgInfo RISCVABIInfo::classifyReturnType(QualType RetTy) const { 10949 if (RetTy->isVoidType()) 10950 return ABIArgInfo::getIgnore(); 10951 10952 int ArgGPRsLeft = 2; 10953 int ArgFPRsLeft = FLen ? 2 : 0; 10954 10955 // The rules for return and argument types are the same, so defer to 10956 // classifyArgumentType. 10957 return classifyArgumentType(RetTy, /*IsFixed=*/true, ArgGPRsLeft, 10958 ArgFPRsLeft); 10959 } 10960 10961 Address RISCVABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 10962 QualType Ty) const { 10963 CharUnits SlotSize = CharUnits::fromQuantity(XLen / 8); 10964 10965 // Empty records are ignored for parameter passing purposes. 10966 if (isEmptyRecord(getContext(), Ty, true)) { 10967 Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize); 10968 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty)); 10969 return Addr; 10970 } 10971 10972 auto TInfo = getContext().getTypeInfoInChars(Ty); 10973 10974 // Arguments bigger than 2*Xlen bytes are passed indirectly. 10975 bool IsIndirect = TInfo.Width > 2 * SlotSize; 10976 10977 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TInfo, 10978 SlotSize, /*AllowHigherAlign=*/true); 10979 } 10980 10981 ABIArgInfo RISCVABIInfo::extendType(QualType Ty) const { 10982 int TySize = getContext().getTypeSize(Ty); 10983 // RV64 ABI requires unsigned 32 bit integers to be sign extended. 10984 if (XLen == 64 && Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32) 10985 return ABIArgInfo::getSignExtend(Ty); 10986 return ABIArgInfo::getExtend(Ty); 10987 } 10988 10989 namespace { 10990 class RISCVTargetCodeGenInfo : public TargetCodeGenInfo { 10991 public: 10992 RISCVTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, unsigned XLen, 10993 unsigned FLen) 10994 : TargetCodeGenInfo(std::make_unique<RISCVABIInfo>(CGT, XLen, FLen)) {} 10995 10996 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 10997 CodeGen::CodeGenModule &CGM) const override { 10998 const auto *FD = dyn_cast_or_null<FunctionDecl>(D); 10999 if (!FD) return; 11000 11001 const auto *Attr = FD->getAttr<RISCVInterruptAttr>(); 11002 if (!Attr) 11003 return; 11004 11005 const char *Kind; 11006 switch (Attr->getInterrupt()) { 11007 case RISCVInterruptAttr::user: Kind = "user"; break; 11008 case RISCVInterruptAttr::supervisor: Kind = "supervisor"; break; 11009 case RISCVInterruptAttr::machine: Kind = "machine"; break; 11010 } 11011 11012 auto *Fn = cast<llvm::Function>(GV); 11013 11014 Fn->addFnAttr("interrupt", Kind); 11015 } 11016 }; 11017 } // namespace 11018 11019 //===----------------------------------------------------------------------===// 11020 // VE ABI Implementation. 11021 // 11022 namespace { 11023 class VEABIInfo : public DefaultABIInfo { 11024 public: 11025 VEABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {} 11026 11027 private: 11028 ABIArgInfo classifyReturnType(QualType RetTy) const; 11029 ABIArgInfo classifyArgumentType(QualType RetTy) const; 11030 void computeInfo(CGFunctionInfo &FI) const override; 11031 }; 11032 } // end anonymous namespace 11033 11034 ABIArgInfo VEABIInfo::classifyReturnType(QualType Ty) const { 11035 if (Ty->isAnyComplexType()) 11036 return ABIArgInfo::getDirect(); 11037 uint64_t Size = getContext().getTypeSize(Ty); 11038 if (Size < 64 && Ty->isIntegerType()) 11039 return ABIArgInfo::getExtend(Ty); 11040 return DefaultABIInfo::classifyReturnType(Ty); 11041 } 11042 11043 ABIArgInfo VEABIInfo::classifyArgumentType(QualType Ty) const { 11044 if (Ty->isAnyComplexType()) 11045 return ABIArgInfo::getDirect(); 11046 uint64_t Size = getContext().getTypeSize(Ty); 11047 if (Size < 64 && Ty->isIntegerType()) 11048 return ABIArgInfo::getExtend(Ty); 11049 return DefaultABIInfo::classifyArgumentType(Ty); 11050 } 11051 11052 void VEABIInfo::computeInfo(CGFunctionInfo &FI) const { 11053 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 11054 for (auto &Arg : FI.arguments()) 11055 Arg.info = classifyArgumentType(Arg.type); 11056 } 11057 11058 namespace { 11059 class VETargetCodeGenInfo : public TargetCodeGenInfo { 11060 public: 11061 VETargetCodeGenInfo(CodeGenTypes &CGT) 11062 : TargetCodeGenInfo(std::make_unique<VEABIInfo>(CGT)) {} 11063 // VE ABI requires the arguments of variadic and prototype-less functions 11064 // are passed in both registers and memory. 11065 bool isNoProtoCallVariadic(const CallArgList &args, 11066 const FunctionNoProtoType *fnType) const override { 11067 return true; 11068 } 11069 }; 11070 } // end anonymous namespace 11071 11072 //===----------------------------------------------------------------------===// 11073 // Driver code 11074 //===----------------------------------------------------------------------===// 11075 11076 bool CodeGenModule::supportsCOMDAT() const { 11077 return getTriple().supportsCOMDAT(); 11078 } 11079 11080 const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() { 11081 if (TheTargetCodeGenInfo) 11082 return *TheTargetCodeGenInfo; 11083 11084 // Helper to set the unique_ptr while still keeping the return value. 11085 auto SetCGInfo = [&](TargetCodeGenInfo *P) -> const TargetCodeGenInfo & { 11086 this->TheTargetCodeGenInfo.reset(P); 11087 return *P; 11088 }; 11089 11090 const llvm::Triple &Triple = getTarget().getTriple(); 11091 switch (Triple.getArch()) { 11092 default: 11093 return SetCGInfo(new DefaultTargetCodeGenInfo(Types)); 11094 11095 case llvm::Triple::le32: 11096 return SetCGInfo(new PNaClTargetCodeGenInfo(Types)); 11097 case llvm::Triple::m68k: 11098 return SetCGInfo(new M68kTargetCodeGenInfo(Types)); 11099 case llvm::Triple::mips: 11100 case llvm::Triple::mipsel: 11101 if (Triple.getOS() == llvm::Triple::NaCl) 11102 return SetCGInfo(new PNaClTargetCodeGenInfo(Types)); 11103 return SetCGInfo(new MIPSTargetCodeGenInfo(Types, true)); 11104 11105 case llvm::Triple::mips64: 11106 case llvm::Triple::mips64el: 11107 return SetCGInfo(new MIPSTargetCodeGenInfo(Types, false)); 11108 11109 case llvm::Triple::avr: 11110 return SetCGInfo(new AVRTargetCodeGenInfo(Types)); 11111 11112 case llvm::Triple::aarch64: 11113 case llvm::Triple::aarch64_32: 11114 case llvm::Triple::aarch64_be: { 11115 AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS; 11116 if (getTarget().getABI() == "darwinpcs") 11117 Kind = AArch64ABIInfo::DarwinPCS; 11118 else if (Triple.isOSWindows()) 11119 return SetCGInfo( 11120 new WindowsAArch64TargetCodeGenInfo(Types, AArch64ABIInfo::Win64)); 11121 11122 return SetCGInfo(new AArch64TargetCodeGenInfo(Types, Kind)); 11123 } 11124 11125 case llvm::Triple::wasm32: 11126 case llvm::Triple::wasm64: { 11127 WebAssemblyABIInfo::ABIKind Kind = WebAssemblyABIInfo::MVP; 11128 if (getTarget().getABI() == "experimental-mv") 11129 Kind = WebAssemblyABIInfo::ExperimentalMV; 11130 return SetCGInfo(new WebAssemblyTargetCodeGenInfo(Types, Kind)); 11131 } 11132 11133 case llvm::Triple::arm: 11134 case llvm::Triple::armeb: 11135 case llvm::Triple::thumb: 11136 case llvm::Triple::thumbeb: { 11137 if (Triple.getOS() == llvm::Triple::Win32) { 11138 return SetCGInfo( 11139 new WindowsARMTargetCodeGenInfo(Types, ARMABIInfo::AAPCS_VFP)); 11140 } 11141 11142 ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS; 11143 StringRef ABIStr = getTarget().getABI(); 11144 if (ABIStr == "apcs-gnu") 11145 Kind = ARMABIInfo::APCS; 11146 else if (ABIStr == "aapcs16") 11147 Kind = ARMABIInfo::AAPCS16_VFP; 11148 else if (CodeGenOpts.FloatABI == "hard" || 11149 (CodeGenOpts.FloatABI != "soft" && 11150 (Triple.getEnvironment() == llvm::Triple::GNUEABIHF || 11151 Triple.getEnvironment() == llvm::Triple::MuslEABIHF || 11152 Triple.getEnvironment() == llvm::Triple::EABIHF))) 11153 Kind = ARMABIInfo::AAPCS_VFP; 11154 11155 return SetCGInfo(new ARMTargetCodeGenInfo(Types, Kind)); 11156 } 11157 11158 case llvm::Triple::ppc: { 11159 if (Triple.isOSAIX()) 11160 return SetCGInfo(new AIXTargetCodeGenInfo(Types, /*Is64Bit*/ false)); 11161 11162 bool IsSoftFloat = 11163 CodeGenOpts.FloatABI == "soft" || getTarget().hasFeature("spe"); 11164 bool RetSmallStructInRegABI = 11165 PPC32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts); 11166 return SetCGInfo( 11167 new PPC32TargetCodeGenInfo(Types, IsSoftFloat, RetSmallStructInRegABI)); 11168 } 11169 case llvm::Triple::ppcle: { 11170 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft"; 11171 bool RetSmallStructInRegABI = 11172 PPC32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts); 11173 return SetCGInfo( 11174 new PPC32TargetCodeGenInfo(Types, IsSoftFloat, RetSmallStructInRegABI)); 11175 } 11176 case llvm::Triple::ppc64: 11177 if (Triple.isOSAIX()) 11178 return SetCGInfo(new AIXTargetCodeGenInfo(Types, /*Is64Bit*/ true)); 11179 11180 if (Triple.isOSBinFormatELF()) { 11181 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1; 11182 if (getTarget().getABI() == "elfv2") 11183 Kind = PPC64_SVR4_ABIInfo::ELFv2; 11184 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft"; 11185 11186 return SetCGInfo( 11187 new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, IsSoftFloat)); 11188 } 11189 return SetCGInfo(new PPC64TargetCodeGenInfo(Types)); 11190 case llvm::Triple::ppc64le: { 11191 assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!"); 11192 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2; 11193 if (getTarget().getABI() == "elfv1") 11194 Kind = PPC64_SVR4_ABIInfo::ELFv1; 11195 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft"; 11196 11197 return SetCGInfo( 11198 new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, IsSoftFloat)); 11199 } 11200 11201 case llvm::Triple::nvptx: 11202 case llvm::Triple::nvptx64: 11203 return SetCGInfo(new NVPTXTargetCodeGenInfo(Types)); 11204 11205 case llvm::Triple::msp430: 11206 return SetCGInfo(new MSP430TargetCodeGenInfo(Types)); 11207 11208 case llvm::Triple::riscv32: 11209 case llvm::Triple::riscv64: { 11210 StringRef ABIStr = getTarget().getABI(); 11211 unsigned XLen = getTarget().getPointerWidth(0); 11212 unsigned ABIFLen = 0; 11213 if (ABIStr.endswith("f")) 11214 ABIFLen = 32; 11215 else if (ABIStr.endswith("d")) 11216 ABIFLen = 64; 11217 return SetCGInfo(new RISCVTargetCodeGenInfo(Types, XLen, ABIFLen)); 11218 } 11219 11220 case llvm::Triple::systemz: { 11221 bool SoftFloat = CodeGenOpts.FloatABI == "soft"; 11222 bool HasVector = !SoftFloat && getTarget().getABI() == "vector"; 11223 return SetCGInfo(new SystemZTargetCodeGenInfo(Types, HasVector, SoftFloat)); 11224 } 11225 11226 case llvm::Triple::tce: 11227 case llvm::Triple::tcele: 11228 return SetCGInfo(new TCETargetCodeGenInfo(Types)); 11229 11230 case llvm::Triple::x86: { 11231 bool IsDarwinVectorABI = Triple.isOSDarwin(); 11232 bool RetSmallStructInRegABI = 11233 X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts); 11234 bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing(); 11235 11236 if (Triple.getOS() == llvm::Triple::Win32) { 11237 return SetCGInfo(new WinX86_32TargetCodeGenInfo( 11238 Types, IsDarwinVectorABI, RetSmallStructInRegABI, 11239 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters)); 11240 } else { 11241 return SetCGInfo(new X86_32TargetCodeGenInfo( 11242 Types, IsDarwinVectorABI, RetSmallStructInRegABI, 11243 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters, 11244 CodeGenOpts.FloatABI == "soft")); 11245 } 11246 } 11247 11248 case llvm::Triple::x86_64: { 11249 StringRef ABI = getTarget().getABI(); 11250 X86AVXABILevel AVXLevel = 11251 (ABI == "avx512" 11252 ? X86AVXABILevel::AVX512 11253 : ABI == "avx" ? X86AVXABILevel::AVX : X86AVXABILevel::None); 11254 11255 switch (Triple.getOS()) { 11256 case llvm::Triple::Win32: 11257 return SetCGInfo(new WinX86_64TargetCodeGenInfo(Types, AVXLevel)); 11258 default: 11259 return SetCGInfo(new X86_64TargetCodeGenInfo(Types, AVXLevel)); 11260 } 11261 } 11262 case llvm::Triple::hexagon: 11263 return SetCGInfo(new HexagonTargetCodeGenInfo(Types)); 11264 case llvm::Triple::lanai: 11265 return SetCGInfo(new LanaiTargetCodeGenInfo(Types)); 11266 case llvm::Triple::r600: 11267 return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types)); 11268 case llvm::Triple::amdgcn: 11269 return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types)); 11270 case llvm::Triple::sparc: 11271 return SetCGInfo(new SparcV8TargetCodeGenInfo(Types)); 11272 case llvm::Triple::sparcv9: 11273 return SetCGInfo(new SparcV9TargetCodeGenInfo(Types)); 11274 case llvm::Triple::xcore: 11275 return SetCGInfo(new XCoreTargetCodeGenInfo(Types)); 11276 case llvm::Triple::arc: 11277 return SetCGInfo(new ARCTargetCodeGenInfo(Types)); 11278 case llvm::Triple::spir: 11279 case llvm::Triple::spir64: 11280 return SetCGInfo(new SPIRTargetCodeGenInfo(Types)); 11281 case llvm::Triple::ve: 11282 return SetCGInfo(new VETargetCodeGenInfo(Types)); 11283 } 11284 } 11285 11286 /// Create an OpenCL kernel for an enqueued block. 11287 /// 11288 /// The kernel has the same function type as the block invoke function. Its 11289 /// name is the name of the block invoke function postfixed with "_kernel". 11290 /// It simply calls the block invoke function then returns. 11291 llvm::Function * 11292 TargetCodeGenInfo::createEnqueuedBlockKernel(CodeGenFunction &CGF, 11293 llvm::Function *Invoke, 11294 llvm::Value *BlockLiteral) const { 11295 auto *InvokeFT = Invoke->getFunctionType(); 11296 llvm::SmallVector<llvm::Type *, 2> ArgTys; 11297 for (auto &P : InvokeFT->params()) 11298 ArgTys.push_back(P); 11299 auto &C = CGF.getLLVMContext(); 11300 std::string Name = Invoke->getName().str() + "_kernel"; 11301 auto *FT = llvm::FunctionType::get(llvm::Type::getVoidTy(C), ArgTys, false); 11302 auto *F = llvm::Function::Create(FT, llvm::GlobalValue::InternalLinkage, Name, 11303 &CGF.CGM.getModule()); 11304 auto IP = CGF.Builder.saveIP(); 11305 auto *BB = llvm::BasicBlock::Create(C, "entry", F); 11306 auto &Builder = CGF.Builder; 11307 Builder.SetInsertPoint(BB); 11308 llvm::SmallVector<llvm::Value *, 2> Args; 11309 for (auto &A : F->args()) 11310 Args.push_back(&A); 11311 llvm::CallInst *call = Builder.CreateCall(Invoke, Args); 11312 call->setCallingConv(Invoke->getCallingConv()); 11313 Builder.CreateRetVoid(); 11314 Builder.restoreIP(IP); 11315 return F; 11316 } 11317 11318 /// Create an OpenCL kernel for an enqueued block. 11319 /// 11320 /// The type of the first argument (the block literal) is the struct type 11321 /// of the block literal instead of a pointer type. The first argument 11322 /// (block literal) is passed directly by value to the kernel. The kernel 11323 /// allocates the same type of struct on stack and stores the block literal 11324 /// to it and passes its pointer to the block invoke function. The kernel 11325 /// has "enqueued-block" function attribute and kernel argument metadata. 11326 llvm::Function *AMDGPUTargetCodeGenInfo::createEnqueuedBlockKernel( 11327 CodeGenFunction &CGF, llvm::Function *Invoke, 11328 llvm::Value *BlockLiteral) const { 11329 auto &Builder = CGF.Builder; 11330 auto &C = CGF.getLLVMContext(); 11331 11332 auto *BlockTy = BlockLiteral->getType()->getPointerElementType(); 11333 auto *InvokeFT = Invoke->getFunctionType(); 11334 llvm::SmallVector<llvm::Type *, 2> ArgTys; 11335 llvm::SmallVector<llvm::Metadata *, 8> AddressQuals; 11336 llvm::SmallVector<llvm::Metadata *, 8> AccessQuals; 11337 llvm::SmallVector<llvm::Metadata *, 8> ArgTypeNames; 11338 llvm::SmallVector<llvm::Metadata *, 8> ArgBaseTypeNames; 11339 llvm::SmallVector<llvm::Metadata *, 8> ArgTypeQuals; 11340 llvm::SmallVector<llvm::Metadata *, 8> ArgNames; 11341 11342 ArgTys.push_back(BlockTy); 11343 ArgTypeNames.push_back(llvm::MDString::get(C, "__block_literal")); 11344 AddressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(0))); 11345 ArgBaseTypeNames.push_back(llvm::MDString::get(C, "__block_literal")); 11346 ArgTypeQuals.push_back(llvm::MDString::get(C, "")); 11347 AccessQuals.push_back(llvm::MDString::get(C, "none")); 11348 ArgNames.push_back(llvm::MDString::get(C, "block_literal")); 11349 for (unsigned I = 1, E = InvokeFT->getNumParams(); I < E; ++I) { 11350 ArgTys.push_back(InvokeFT->getParamType(I)); 11351 ArgTypeNames.push_back(llvm::MDString::get(C, "void*")); 11352 AddressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(3))); 11353 AccessQuals.push_back(llvm::MDString::get(C, "none")); 11354 ArgBaseTypeNames.push_back(llvm::MDString::get(C, "void*")); 11355 ArgTypeQuals.push_back(llvm::MDString::get(C, "")); 11356 ArgNames.push_back( 11357 llvm::MDString::get(C, (Twine("local_arg") + Twine(I)).str())); 11358 } 11359 std::string Name = Invoke->getName().str() + "_kernel"; 11360 auto *FT = llvm::FunctionType::get(llvm::Type::getVoidTy(C), ArgTys, false); 11361 auto *F = llvm::Function::Create(FT, llvm::GlobalValue::InternalLinkage, Name, 11362 &CGF.CGM.getModule()); 11363 F->addFnAttr("enqueued-block"); 11364 auto IP = CGF.Builder.saveIP(); 11365 auto *BB = llvm::BasicBlock::Create(C, "entry", F); 11366 Builder.SetInsertPoint(BB); 11367 const auto BlockAlign = CGF.CGM.getDataLayout().getPrefTypeAlign(BlockTy); 11368 auto *BlockPtr = Builder.CreateAlloca(BlockTy, nullptr); 11369 BlockPtr->setAlignment(BlockAlign); 11370 Builder.CreateAlignedStore(F->arg_begin(), BlockPtr, BlockAlign); 11371 auto *Cast = Builder.CreatePointerCast(BlockPtr, InvokeFT->getParamType(0)); 11372 llvm::SmallVector<llvm::Value *, 2> Args; 11373 Args.push_back(Cast); 11374 for (auto I = F->arg_begin() + 1, E = F->arg_end(); I != E; ++I) 11375 Args.push_back(I); 11376 llvm::CallInst *call = Builder.CreateCall(Invoke, Args); 11377 call->setCallingConv(Invoke->getCallingConv()); 11378 Builder.CreateRetVoid(); 11379 Builder.restoreIP(IP); 11380 11381 F->setMetadata("kernel_arg_addr_space", llvm::MDNode::get(C, AddressQuals)); 11382 F->setMetadata("kernel_arg_access_qual", llvm::MDNode::get(C, AccessQuals)); 11383 F->setMetadata("kernel_arg_type", llvm::MDNode::get(C, ArgTypeNames)); 11384 F->setMetadata("kernel_arg_base_type", 11385 llvm::MDNode::get(C, ArgBaseTypeNames)); 11386 F->setMetadata("kernel_arg_type_qual", llvm::MDNode::get(C, ArgTypeQuals)); 11387 if (CGF.CGM.getCodeGenOpts().EmitOpenCLArgMetadata) 11388 F->setMetadata("kernel_arg_name", llvm::MDNode::get(C, ArgNames)); 11389 11390 return F; 11391 } 11392