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 emitMergePHI(CodeGenFunction &CGF, 396 Address Addr1, llvm::BasicBlock *Block1, 397 Address Addr2, llvm::BasicBlock *Block2, 398 const llvm::Twine &Name = "") { 399 assert(Addr1.getType() == Addr2.getType()); 400 llvm::PHINode *PHI = CGF.Builder.CreatePHI(Addr1.getType(), 2, Name); 401 PHI->addIncoming(Addr1.getPointer(), Block1); 402 PHI->addIncoming(Addr2.getPointer(), Block2); 403 CharUnits Align = std::min(Addr1.getAlignment(), Addr2.getAlignment()); 404 return Address(PHI, Align); 405 } 406 407 TargetCodeGenInfo::~TargetCodeGenInfo() = default; 408 409 // If someone can figure out a general rule for this, that would be great. 410 // It's probably just doomed to be platform-dependent, though. 411 unsigned TargetCodeGenInfo::getSizeOfUnwindException() const { 412 // Verified for: 413 // x86-64 FreeBSD, Linux, Darwin 414 // x86-32 FreeBSD, Linux, Darwin 415 // PowerPC Linux, Darwin 416 // ARM Darwin (*not* EABI) 417 // AArch64 Linux 418 return 32; 419 } 420 421 bool TargetCodeGenInfo::isNoProtoCallVariadic(const CallArgList &args, 422 const FunctionNoProtoType *fnType) const { 423 // The following conventions are known to require this to be false: 424 // x86_stdcall 425 // MIPS 426 // For everything else, we just prefer false unless we opt out. 427 return false; 428 } 429 430 void 431 TargetCodeGenInfo::getDependentLibraryOption(llvm::StringRef Lib, 432 llvm::SmallString<24> &Opt) const { 433 // This assumes the user is passing a library name like "rt" instead of a 434 // filename like "librt.a/so", and that they don't care whether it's static or 435 // dynamic. 436 Opt = "-l"; 437 Opt += Lib; 438 } 439 440 unsigned TargetCodeGenInfo::getOpenCLKernelCallingConv() const { 441 // OpenCL kernels are called via an explicit runtime API with arguments 442 // set with clSetKernelArg(), not as normal sub-functions. 443 // Return SPIR_KERNEL by default as the kernel calling convention to 444 // ensure the fingerprint is fixed such way that each OpenCL argument 445 // gets one matching argument in the produced kernel function argument 446 // list to enable feasible implementation of clSetKernelArg() with 447 // aggregates etc. In case we would use the default C calling conv here, 448 // clSetKernelArg() might break depending on the target-specific 449 // conventions; different targets might split structs passed as values 450 // to multiple function arguments etc. 451 return llvm::CallingConv::SPIR_KERNEL; 452 } 453 454 llvm::Constant *TargetCodeGenInfo::getNullPointer(const CodeGen::CodeGenModule &CGM, 455 llvm::PointerType *T, QualType QT) const { 456 return llvm::ConstantPointerNull::get(T); 457 } 458 459 LangAS TargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM, 460 const VarDecl *D) const { 461 assert(!CGM.getLangOpts().OpenCL && 462 !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) && 463 "Address space agnostic languages only"); 464 return D ? D->getType().getAddressSpace() : LangAS::Default; 465 } 466 467 llvm::Value *TargetCodeGenInfo::performAddrSpaceCast( 468 CodeGen::CodeGenFunction &CGF, llvm::Value *Src, LangAS SrcAddr, 469 LangAS DestAddr, llvm::Type *DestTy, bool isNonNull) const { 470 // Since target may map different address spaces in AST to the same address 471 // space, an address space conversion may end up as a bitcast. 472 if (auto *C = dyn_cast<llvm::Constant>(Src)) 473 return performAddrSpaceCast(CGF.CGM, C, SrcAddr, DestAddr, DestTy); 474 // Try to preserve the source's name to make IR more readable. 475 return CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( 476 Src, DestTy, Src->hasName() ? Src->getName() + ".ascast" : ""); 477 } 478 479 llvm::Constant * 480 TargetCodeGenInfo::performAddrSpaceCast(CodeGenModule &CGM, llvm::Constant *Src, 481 LangAS SrcAddr, LangAS DestAddr, 482 llvm::Type *DestTy) const { 483 // Since target may map different address spaces in AST to the same address 484 // space, an address space conversion may end up as a bitcast. 485 return llvm::ConstantExpr::getPointerCast(Src, DestTy); 486 } 487 488 llvm::SyncScope::ID 489 TargetCodeGenInfo::getLLVMSyncScopeID(const LangOptions &LangOpts, 490 SyncScope Scope, 491 llvm::AtomicOrdering Ordering, 492 llvm::LLVMContext &Ctx) const { 493 return Ctx.getOrInsertSyncScopeID(""); /* default sync scope */ 494 } 495 496 static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays); 497 498 /// isEmptyField - Return true iff a the field is "empty", that is it 499 /// is an unnamed bit-field or an (array of) empty record(s). 500 static bool isEmptyField(ASTContext &Context, const FieldDecl *FD, 501 bool AllowArrays) { 502 if (FD->isUnnamedBitfield()) 503 return true; 504 505 QualType FT = FD->getType(); 506 507 // Constant arrays of empty records count as empty, strip them off. 508 // Constant arrays of zero length always count as empty. 509 bool WasArray = false; 510 if (AllowArrays) 511 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) { 512 if (AT->getSize() == 0) 513 return true; 514 FT = AT->getElementType(); 515 // The [[no_unique_address]] special case below does not apply to 516 // arrays of C++ empty records, so we need to remember this fact. 517 WasArray = true; 518 } 519 520 const RecordType *RT = FT->getAs<RecordType>(); 521 if (!RT) 522 return false; 523 524 // C++ record fields are never empty, at least in the Itanium ABI. 525 // 526 // FIXME: We should use a predicate for whether this behavior is true in the 527 // current ABI. 528 // 529 // The exception to the above rule are fields marked with the 530 // [[no_unique_address]] attribute (since C++20). Those do count as empty 531 // according to the Itanium ABI. The exception applies only to records, 532 // not arrays of records, so we must also check whether we stripped off an 533 // array type above. 534 if (isa<CXXRecordDecl>(RT->getDecl()) && 535 (WasArray || !FD->hasAttr<NoUniqueAddressAttr>())) 536 return false; 537 538 return isEmptyRecord(Context, FT, AllowArrays); 539 } 540 541 /// isEmptyRecord - Return true iff a structure contains only empty 542 /// fields. Note that a structure with a flexible array member is not 543 /// considered empty. 544 static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) { 545 const RecordType *RT = T->getAs<RecordType>(); 546 if (!RT) 547 return false; 548 const RecordDecl *RD = RT->getDecl(); 549 if (RD->hasFlexibleArrayMember()) 550 return false; 551 552 // If this is a C++ record, check the bases first. 553 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 554 for (const auto &I : CXXRD->bases()) 555 if (!isEmptyRecord(Context, I.getType(), true)) 556 return false; 557 558 for (const auto *I : RD->fields()) 559 if (!isEmptyField(Context, I, AllowArrays)) 560 return false; 561 return true; 562 } 563 564 /// isSingleElementStruct - Determine if a structure is a "single 565 /// element struct", i.e. it has exactly one non-empty field or 566 /// exactly one field which is itself a single element 567 /// struct. Structures with flexible array members are never 568 /// considered single element structs. 569 /// 570 /// \return The field declaration for the single non-empty field, if 571 /// it exists. 572 static const Type *isSingleElementStruct(QualType T, ASTContext &Context) { 573 const RecordType *RT = T->getAs<RecordType>(); 574 if (!RT) 575 return nullptr; 576 577 const RecordDecl *RD = RT->getDecl(); 578 if (RD->hasFlexibleArrayMember()) 579 return nullptr; 580 581 const Type *Found = nullptr; 582 583 // If this is a C++ record, check the bases first. 584 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 585 for (const auto &I : CXXRD->bases()) { 586 // Ignore empty records. 587 if (isEmptyRecord(Context, I.getType(), true)) 588 continue; 589 590 // If we already found an element then this isn't a single-element struct. 591 if (Found) 592 return nullptr; 593 594 // If this is non-empty and not a single element struct, the composite 595 // cannot be a single element struct. 596 Found = isSingleElementStruct(I.getType(), Context); 597 if (!Found) 598 return nullptr; 599 } 600 } 601 602 // Check for single element. 603 for (const auto *FD : RD->fields()) { 604 QualType FT = FD->getType(); 605 606 // Ignore empty fields. 607 if (isEmptyField(Context, FD, true)) 608 continue; 609 610 // If we already found an element then this isn't a single-element 611 // struct. 612 if (Found) 613 return nullptr; 614 615 // Treat single element arrays as the element. 616 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) { 617 if (AT->getSize().getZExtValue() != 1) 618 break; 619 FT = AT->getElementType(); 620 } 621 622 if (!isAggregateTypeForABI(FT)) { 623 Found = FT.getTypePtr(); 624 } else { 625 Found = isSingleElementStruct(FT, Context); 626 if (!Found) 627 return nullptr; 628 } 629 } 630 631 // We don't consider a struct a single-element struct if it has 632 // padding beyond the element type. 633 if (Found && Context.getTypeSize(Found) != Context.getTypeSize(T)) 634 return nullptr; 635 636 return Found; 637 } 638 639 namespace { 640 Address EmitVAArgInstr(CodeGenFunction &CGF, Address VAListAddr, QualType Ty, 641 const ABIArgInfo &AI) { 642 // This default implementation defers to the llvm backend's va_arg 643 // instruction. It can handle only passing arguments directly 644 // (typically only handled in the backend for primitive types), or 645 // aggregates passed indirectly by pointer (NOTE: if the "byval" 646 // flag has ABI impact in the callee, this implementation cannot 647 // work.) 648 649 // Only a few cases are covered here at the moment -- those needed 650 // by the default abi. 651 llvm::Value *Val; 652 653 if (AI.isIndirect()) { 654 assert(!AI.getPaddingType() && 655 "Unexpected PaddingType seen in arginfo in generic VAArg emitter!"); 656 assert( 657 !AI.getIndirectRealign() && 658 "Unexpected IndirectRealign seen in arginfo in generic VAArg emitter!"); 659 660 auto TyInfo = CGF.getContext().getTypeInfoInChars(Ty); 661 CharUnits TyAlignForABI = TyInfo.Align; 662 663 llvm::Type *BaseTy = 664 llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty)); 665 llvm::Value *Addr = 666 CGF.Builder.CreateVAArg(VAListAddr.getPointer(), BaseTy); 667 return Address(Addr, TyAlignForABI); 668 } else { 669 assert((AI.isDirect() || AI.isExtend()) && 670 "Unexpected ArgInfo Kind in generic VAArg emitter!"); 671 672 assert(!AI.getInReg() && 673 "Unexpected InReg seen in arginfo in generic VAArg emitter!"); 674 assert(!AI.getPaddingType() && 675 "Unexpected PaddingType seen in arginfo in generic VAArg emitter!"); 676 assert(!AI.getDirectOffset() && 677 "Unexpected DirectOffset seen in arginfo in generic VAArg emitter!"); 678 assert(!AI.getCoerceToType() && 679 "Unexpected CoerceToType seen in arginfo in generic VAArg emitter!"); 680 681 Address Temp = CGF.CreateMemTemp(Ty, "varet"); 682 Val = CGF.Builder.CreateVAArg(VAListAddr.getPointer(), CGF.ConvertType(Ty)); 683 CGF.Builder.CreateStore(Val, Temp); 684 return Temp; 685 } 686 } 687 688 /// DefaultABIInfo - The default implementation for ABI specific 689 /// details. This implementation provides information which results in 690 /// self-consistent and sensible LLVM IR generation, but does not 691 /// conform to any particular ABI. 692 class DefaultABIInfo : public ABIInfo { 693 public: 694 DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {} 695 696 ABIArgInfo classifyReturnType(QualType RetTy) const; 697 ABIArgInfo classifyArgumentType(QualType RetTy) const; 698 699 void computeInfo(CGFunctionInfo &FI) const override { 700 if (!getCXXABI().classifyReturnType(FI)) 701 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 702 for (auto &I : FI.arguments()) 703 I.info = classifyArgumentType(I.type); 704 } 705 706 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 707 QualType Ty) const override { 708 return EmitVAArgInstr(CGF, VAListAddr, Ty, classifyArgumentType(Ty)); 709 } 710 }; 711 712 class DefaultTargetCodeGenInfo : public TargetCodeGenInfo { 713 public: 714 DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT) 715 : TargetCodeGenInfo(std::make_unique<DefaultABIInfo>(CGT)) {} 716 }; 717 718 ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const { 719 Ty = useFirstFieldIfTransparentUnion(Ty); 720 721 if (isAggregateTypeForABI(Ty)) { 722 // Records with non-trivial destructors/copy-constructors should not be 723 // passed by value. 724 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 725 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 726 727 return getNaturalAlignIndirect(Ty); 728 } 729 730 // Treat an enum type as its underlying type. 731 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 732 Ty = EnumTy->getDecl()->getIntegerType(); 733 734 ASTContext &Context = getContext(); 735 if (const auto *EIT = Ty->getAs<ExtIntType>()) 736 if (EIT->getNumBits() > 737 Context.getTypeSize(Context.getTargetInfo().hasInt128Type() 738 ? Context.Int128Ty 739 : Context.LongLongTy)) 740 return getNaturalAlignIndirect(Ty); 741 742 return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty) 743 : ABIArgInfo::getDirect()); 744 } 745 746 ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const { 747 if (RetTy->isVoidType()) 748 return ABIArgInfo::getIgnore(); 749 750 if (isAggregateTypeForABI(RetTy)) 751 return getNaturalAlignIndirect(RetTy); 752 753 // Treat an enum type as its underlying type. 754 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 755 RetTy = EnumTy->getDecl()->getIntegerType(); 756 757 if (const auto *EIT = RetTy->getAs<ExtIntType>()) 758 if (EIT->getNumBits() > 759 getContext().getTypeSize(getContext().getTargetInfo().hasInt128Type() 760 ? getContext().Int128Ty 761 : getContext().LongLongTy)) 762 return getNaturalAlignIndirect(RetTy); 763 764 return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy) 765 : ABIArgInfo::getDirect()); 766 } 767 768 //===----------------------------------------------------------------------===// 769 // WebAssembly ABI Implementation 770 // 771 // This is a very simple ABI that relies a lot on DefaultABIInfo. 772 //===----------------------------------------------------------------------===// 773 774 class WebAssemblyABIInfo final : public SwiftABIInfo { 775 public: 776 enum ABIKind { 777 MVP = 0, 778 ExperimentalMV = 1, 779 }; 780 781 private: 782 DefaultABIInfo defaultInfo; 783 ABIKind Kind; 784 785 public: 786 explicit WebAssemblyABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind) 787 : SwiftABIInfo(CGT), defaultInfo(CGT), Kind(Kind) {} 788 789 private: 790 ABIArgInfo classifyReturnType(QualType RetTy) const; 791 ABIArgInfo classifyArgumentType(QualType Ty) const; 792 793 // DefaultABIInfo's classifyReturnType and classifyArgumentType are 794 // non-virtual, but computeInfo and EmitVAArg are virtual, so we 795 // overload them. 796 void computeInfo(CGFunctionInfo &FI) const override { 797 if (!getCXXABI().classifyReturnType(FI)) 798 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 799 for (auto &Arg : FI.arguments()) 800 Arg.info = classifyArgumentType(Arg.type); 801 } 802 803 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 804 QualType Ty) const override; 805 806 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars, 807 bool asReturnValue) const override { 808 return occupiesMoreThan(CGT, scalars, /*total*/ 4); 809 } 810 811 bool isSwiftErrorInRegister() const override { 812 return false; 813 } 814 }; 815 816 class WebAssemblyTargetCodeGenInfo final : public TargetCodeGenInfo { 817 public: 818 explicit WebAssemblyTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, 819 WebAssemblyABIInfo::ABIKind K) 820 : TargetCodeGenInfo(std::make_unique<WebAssemblyABIInfo>(CGT, K)) {} 821 822 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 823 CodeGen::CodeGenModule &CGM) const override { 824 TargetCodeGenInfo::setTargetAttributes(D, GV, CGM); 825 if (const auto *FD = dyn_cast_or_null<FunctionDecl>(D)) { 826 if (const auto *Attr = FD->getAttr<WebAssemblyImportModuleAttr>()) { 827 llvm::Function *Fn = cast<llvm::Function>(GV); 828 llvm::AttrBuilder B; 829 B.addAttribute("wasm-import-module", Attr->getImportModule()); 830 Fn->addAttributes(llvm::AttributeList::FunctionIndex, B); 831 } 832 if (const auto *Attr = FD->getAttr<WebAssemblyImportNameAttr>()) { 833 llvm::Function *Fn = cast<llvm::Function>(GV); 834 llvm::AttrBuilder B; 835 B.addAttribute("wasm-import-name", Attr->getImportName()); 836 Fn->addAttributes(llvm::AttributeList::FunctionIndex, B); 837 } 838 if (const auto *Attr = FD->getAttr<WebAssemblyExportNameAttr>()) { 839 llvm::Function *Fn = cast<llvm::Function>(GV); 840 llvm::AttrBuilder B; 841 B.addAttribute("wasm-export-name", Attr->getExportName()); 842 Fn->addAttributes(llvm::AttributeList::FunctionIndex, B); 843 } 844 } 845 846 if (auto *FD = dyn_cast_or_null<FunctionDecl>(D)) { 847 llvm::Function *Fn = cast<llvm::Function>(GV); 848 if (!FD->doesThisDeclarationHaveABody() && !FD->hasPrototype()) 849 Fn->addFnAttr("no-prototype"); 850 } 851 } 852 }; 853 854 /// Classify argument of given type \p Ty. 855 ABIArgInfo WebAssemblyABIInfo::classifyArgumentType(QualType Ty) const { 856 Ty = useFirstFieldIfTransparentUnion(Ty); 857 858 if (isAggregateTypeForABI(Ty)) { 859 // Records with non-trivial destructors/copy-constructors should not be 860 // passed by value. 861 if (auto RAA = getRecordArgABI(Ty, getCXXABI())) 862 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 863 // Ignore empty structs/unions. 864 if (isEmptyRecord(getContext(), Ty, true)) 865 return ABIArgInfo::getIgnore(); 866 // Lower single-element structs to just pass a regular value. TODO: We 867 // could do reasonable-size multiple-element structs too, using getExpand(), 868 // though watch out for things like bitfields. 869 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext())) 870 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0))); 871 // For the experimental multivalue ABI, fully expand all other aggregates 872 if (Kind == ABIKind::ExperimentalMV) { 873 const RecordType *RT = Ty->getAs<RecordType>(); 874 assert(RT); 875 bool HasBitField = false; 876 for (auto *Field : RT->getDecl()->fields()) { 877 if (Field->isBitField()) { 878 HasBitField = true; 879 break; 880 } 881 } 882 if (!HasBitField) 883 return ABIArgInfo::getExpand(); 884 } 885 } 886 887 // Otherwise just do the default thing. 888 return defaultInfo.classifyArgumentType(Ty); 889 } 890 891 ABIArgInfo WebAssemblyABIInfo::classifyReturnType(QualType RetTy) const { 892 if (isAggregateTypeForABI(RetTy)) { 893 // Records with non-trivial destructors/copy-constructors should not be 894 // returned by value. 895 if (!getRecordArgABI(RetTy, getCXXABI())) { 896 // Ignore empty structs/unions. 897 if (isEmptyRecord(getContext(), RetTy, true)) 898 return ABIArgInfo::getIgnore(); 899 // Lower single-element structs to just return a regular value. TODO: We 900 // could do reasonable-size multiple-element structs too, using 901 // ABIArgInfo::getDirect(). 902 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext())) 903 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0))); 904 // For the experimental multivalue ABI, return all other aggregates 905 if (Kind == ABIKind::ExperimentalMV) 906 return ABIArgInfo::getDirect(); 907 } 908 } 909 910 // Otherwise just do the default thing. 911 return defaultInfo.classifyReturnType(RetTy); 912 } 913 914 Address WebAssemblyABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 915 QualType Ty) const { 916 bool IsIndirect = isAggregateTypeForABI(Ty) && 917 !isEmptyRecord(getContext(), Ty, true) && 918 !isSingleElementStruct(Ty, getContext()); 919 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, 920 getContext().getTypeInfoInChars(Ty), 921 CharUnits::fromQuantity(4), 922 /*AllowHigherAlign=*/true); 923 } 924 925 //===----------------------------------------------------------------------===// 926 // le32/PNaCl bitcode ABI Implementation 927 // 928 // This is a simplified version of the x86_32 ABI. Arguments and return values 929 // are always passed on the stack. 930 //===----------------------------------------------------------------------===// 931 932 class PNaClABIInfo : public ABIInfo { 933 public: 934 PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {} 935 936 ABIArgInfo classifyReturnType(QualType RetTy) const; 937 ABIArgInfo classifyArgumentType(QualType RetTy) const; 938 939 void computeInfo(CGFunctionInfo &FI) const override; 940 Address EmitVAArg(CodeGenFunction &CGF, 941 Address VAListAddr, QualType Ty) const override; 942 }; 943 944 class PNaClTargetCodeGenInfo : public TargetCodeGenInfo { 945 public: 946 PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT) 947 : TargetCodeGenInfo(std::make_unique<PNaClABIInfo>(CGT)) {} 948 }; 949 950 void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const { 951 if (!getCXXABI().classifyReturnType(FI)) 952 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 953 954 for (auto &I : FI.arguments()) 955 I.info = classifyArgumentType(I.type); 956 } 957 958 Address PNaClABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 959 QualType Ty) const { 960 // The PNaCL ABI is a bit odd, in that varargs don't use normal 961 // function classification. Structs get passed directly for varargs 962 // functions, through a rewriting transform in 963 // pnacl-llvm/lib/Transforms/NaCl/ExpandVarArgs.cpp, which allows 964 // this target to actually support a va_arg instructions with an 965 // aggregate type, unlike other targets. 966 return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect()); 967 } 968 969 /// Classify argument of given type \p Ty. 970 ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const { 971 if (isAggregateTypeForABI(Ty)) { 972 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 973 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 974 return getNaturalAlignIndirect(Ty); 975 } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) { 976 // Treat an enum type as its underlying type. 977 Ty = EnumTy->getDecl()->getIntegerType(); 978 } else if (Ty->isFloatingType()) { 979 // Floating-point types don't go inreg. 980 return ABIArgInfo::getDirect(); 981 } else if (const auto *EIT = Ty->getAs<ExtIntType>()) { 982 // Treat extended integers as integers if <=64, otherwise pass indirectly. 983 if (EIT->getNumBits() > 64) 984 return getNaturalAlignIndirect(Ty); 985 return ABIArgInfo::getDirect(); 986 } 987 988 return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty) 989 : ABIArgInfo::getDirect()); 990 } 991 992 ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const { 993 if (RetTy->isVoidType()) 994 return ABIArgInfo::getIgnore(); 995 996 // In the PNaCl ABI we always return records/structures on the stack. 997 if (isAggregateTypeForABI(RetTy)) 998 return getNaturalAlignIndirect(RetTy); 999 1000 // Treat extended integers as integers if <=64, otherwise pass indirectly. 1001 if (const auto *EIT = RetTy->getAs<ExtIntType>()) { 1002 if (EIT->getNumBits() > 64) 1003 return getNaturalAlignIndirect(RetTy); 1004 return ABIArgInfo::getDirect(); 1005 } 1006 1007 // Treat an enum type as its underlying type. 1008 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 1009 RetTy = EnumTy->getDecl()->getIntegerType(); 1010 1011 return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy) 1012 : ABIArgInfo::getDirect()); 1013 } 1014 1015 /// IsX86_MMXType - Return true if this is an MMX type. 1016 bool IsX86_MMXType(llvm::Type *IRType) { 1017 // Return true if the type is an MMX type <2 x i32>, <4 x i16>, or <8 x i8>. 1018 return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 && 1019 cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() && 1020 IRType->getScalarSizeInBits() != 64; 1021 } 1022 1023 static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF, 1024 StringRef Constraint, 1025 llvm::Type* Ty) { 1026 bool IsMMXCons = llvm::StringSwitch<bool>(Constraint) 1027 .Cases("y", "&y", "^Ym", true) 1028 .Default(false); 1029 if (IsMMXCons && Ty->isVectorTy()) { 1030 if (cast<llvm::VectorType>(Ty)->getPrimitiveSizeInBits().getFixedSize() != 1031 64) { 1032 // Invalid MMX constraint 1033 return nullptr; 1034 } 1035 1036 return llvm::Type::getX86_MMXTy(CGF.getLLVMContext()); 1037 } 1038 1039 // No operation needed 1040 return Ty; 1041 } 1042 1043 /// Returns true if this type can be passed in SSE registers with the 1044 /// X86_VectorCall calling convention. Shared between x86_32 and x86_64. 1045 static bool isX86VectorTypeForVectorCall(ASTContext &Context, QualType Ty) { 1046 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) { 1047 if (BT->isFloatingPoint() && BT->getKind() != BuiltinType::Half) { 1048 if (BT->getKind() == BuiltinType::LongDouble) { 1049 if (&Context.getTargetInfo().getLongDoubleFormat() == 1050 &llvm::APFloat::x87DoubleExtended()) 1051 return false; 1052 } 1053 return true; 1054 } 1055 } else if (const VectorType *VT = Ty->getAs<VectorType>()) { 1056 // vectorcall can pass XMM, YMM, and ZMM vectors. We don't pass SSE1 MMX 1057 // registers specially. 1058 unsigned VecSize = Context.getTypeSize(VT); 1059 if (VecSize == 128 || VecSize == 256 || VecSize == 512) 1060 return true; 1061 } 1062 return false; 1063 } 1064 1065 /// Returns true if this aggregate is small enough to be passed in SSE registers 1066 /// in the X86_VectorCall calling convention. Shared between x86_32 and x86_64. 1067 static bool isX86VectorCallAggregateSmallEnough(uint64_t NumMembers) { 1068 return NumMembers <= 4; 1069 } 1070 1071 /// Returns a Homogeneous Vector Aggregate ABIArgInfo, used in X86. 1072 static ABIArgInfo getDirectX86Hva(llvm::Type* T = nullptr) { 1073 auto AI = ABIArgInfo::getDirect(T); 1074 AI.setInReg(true); 1075 AI.setCanBeFlattened(false); 1076 return AI; 1077 } 1078 1079 //===----------------------------------------------------------------------===// 1080 // X86-32 ABI Implementation 1081 //===----------------------------------------------------------------------===// 1082 1083 /// Similar to llvm::CCState, but for Clang. 1084 struct CCState { 1085 CCState(CGFunctionInfo &FI) 1086 : IsPreassigned(FI.arg_size()), CC(FI.getCallingConvention()) {} 1087 1088 llvm::SmallBitVector IsPreassigned; 1089 unsigned CC = CallingConv::CC_C; 1090 unsigned FreeRegs = 0; 1091 unsigned FreeSSERegs = 0; 1092 }; 1093 1094 /// X86_32ABIInfo - The X86-32 ABI information. 1095 class X86_32ABIInfo : public SwiftABIInfo { 1096 enum Class { 1097 Integer, 1098 Float 1099 }; 1100 1101 static const unsigned MinABIStackAlignInBytes = 4; 1102 1103 bool IsDarwinVectorABI; 1104 bool IsRetSmallStructInRegABI; 1105 bool IsWin32StructABI; 1106 bool IsSoftFloatABI; 1107 bool IsMCUABI; 1108 unsigned DefaultNumRegisterParameters; 1109 1110 static bool isRegisterSize(unsigned Size) { 1111 return (Size == 8 || Size == 16 || Size == 32 || Size == 64); 1112 } 1113 1114 bool isHomogeneousAggregateBaseType(QualType Ty) const override { 1115 // FIXME: Assumes vectorcall is in use. 1116 return isX86VectorTypeForVectorCall(getContext(), Ty); 1117 } 1118 1119 bool isHomogeneousAggregateSmallEnough(const Type *Ty, 1120 uint64_t NumMembers) const override { 1121 // FIXME: Assumes vectorcall is in use. 1122 return isX86VectorCallAggregateSmallEnough(NumMembers); 1123 } 1124 1125 bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context) const; 1126 1127 /// getIndirectResult - Give a source type \arg Ty, return a suitable result 1128 /// such that the argument will be passed in memory. 1129 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const; 1130 1131 ABIArgInfo getIndirectReturnResult(QualType Ty, CCState &State) const; 1132 1133 /// Return the alignment to use for the given type on the stack. 1134 unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const; 1135 1136 Class classify(QualType Ty) const; 1137 ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const; 1138 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const; 1139 1140 /// Updates the number of available free registers, returns 1141 /// true if any registers were allocated. 1142 bool updateFreeRegs(QualType Ty, CCState &State) const; 1143 1144 bool shouldAggregateUseDirect(QualType Ty, CCState &State, bool &InReg, 1145 bool &NeedsPadding) const; 1146 bool shouldPrimitiveUseInReg(QualType Ty, CCState &State) const; 1147 1148 bool canExpandIndirectArgument(QualType Ty) const; 1149 1150 /// Rewrite the function info so that all memory arguments use 1151 /// inalloca. 1152 void rewriteWithInAlloca(CGFunctionInfo &FI) const; 1153 1154 void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields, 1155 CharUnits &StackOffset, ABIArgInfo &Info, 1156 QualType Type) const; 1157 void runVectorCallFirstPass(CGFunctionInfo &FI, CCState &State) const; 1158 1159 public: 1160 1161 void computeInfo(CGFunctionInfo &FI) const override; 1162 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 1163 QualType Ty) const override; 1164 1165 X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI, 1166 bool RetSmallStructInRegABI, bool Win32StructABI, 1167 unsigned NumRegisterParameters, bool SoftFloatABI) 1168 : SwiftABIInfo(CGT), IsDarwinVectorABI(DarwinVectorABI), 1169 IsRetSmallStructInRegABI(RetSmallStructInRegABI), 1170 IsWin32StructABI(Win32StructABI), 1171 IsSoftFloatABI(SoftFloatABI), 1172 IsMCUABI(CGT.getTarget().getTriple().isOSIAMCU()), 1173 DefaultNumRegisterParameters(NumRegisterParameters) {} 1174 1175 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars, 1176 bool asReturnValue) const override { 1177 // LLVM's x86-32 lowering currently only assigns up to three 1178 // integer registers and three fp registers. Oddly, it'll use up to 1179 // four vector registers for vectors, but those can overlap with the 1180 // scalar registers. 1181 return occupiesMoreThan(CGT, scalars, /*total*/ 3); 1182 } 1183 1184 bool isSwiftErrorInRegister() const override { 1185 // x86-32 lowering does not support passing swifterror in a register. 1186 return false; 1187 } 1188 }; 1189 1190 class X86_32TargetCodeGenInfo : public TargetCodeGenInfo { 1191 public: 1192 X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI, 1193 bool RetSmallStructInRegABI, bool Win32StructABI, 1194 unsigned NumRegisterParameters, bool SoftFloatABI) 1195 : TargetCodeGenInfo(std::make_unique<X86_32ABIInfo>( 1196 CGT, DarwinVectorABI, RetSmallStructInRegABI, Win32StructABI, 1197 NumRegisterParameters, SoftFloatABI)) {} 1198 1199 static bool isStructReturnInRegABI( 1200 const llvm::Triple &Triple, const CodeGenOptions &Opts); 1201 1202 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 1203 CodeGen::CodeGenModule &CGM) const override; 1204 1205 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override { 1206 // Darwin uses different dwarf register numbers for EH. 1207 if (CGM.getTarget().getTriple().isOSDarwin()) return 5; 1208 return 4; 1209 } 1210 1211 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 1212 llvm::Value *Address) const override; 1213 1214 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF, 1215 StringRef Constraint, 1216 llvm::Type* Ty) const override { 1217 return X86AdjustInlineAsmType(CGF, Constraint, Ty); 1218 } 1219 1220 void addReturnRegisterOutputs(CodeGenFunction &CGF, LValue ReturnValue, 1221 std::string &Constraints, 1222 std::vector<llvm::Type *> &ResultRegTypes, 1223 std::vector<llvm::Type *> &ResultTruncRegTypes, 1224 std::vector<LValue> &ResultRegDests, 1225 std::string &AsmString, 1226 unsigned NumOutputs) const override; 1227 1228 llvm::Constant * 1229 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override { 1230 unsigned Sig = (0xeb << 0) | // jmp rel8 1231 (0x06 << 8) | // .+0x08 1232 ('v' << 16) | 1233 ('2' << 24); 1234 return llvm::ConstantInt::get(CGM.Int32Ty, Sig); 1235 } 1236 1237 StringRef getARCRetainAutoreleasedReturnValueMarker() const override { 1238 return "movl\t%ebp, %ebp" 1239 "\t\t// marker for objc_retainAutoreleaseReturnValue"; 1240 } 1241 }; 1242 1243 } 1244 1245 /// Rewrite input constraint references after adding some output constraints. 1246 /// In the case where there is one output and one input and we add one output, 1247 /// we need to replace all operand references greater than or equal to 1: 1248 /// mov $0, $1 1249 /// mov eax, $1 1250 /// The result will be: 1251 /// mov $0, $2 1252 /// mov eax, $2 1253 static void rewriteInputConstraintReferences(unsigned FirstIn, 1254 unsigned NumNewOuts, 1255 std::string &AsmString) { 1256 std::string Buf; 1257 llvm::raw_string_ostream OS(Buf); 1258 size_t Pos = 0; 1259 while (Pos < AsmString.size()) { 1260 size_t DollarStart = AsmString.find('$', Pos); 1261 if (DollarStart == std::string::npos) 1262 DollarStart = AsmString.size(); 1263 size_t DollarEnd = AsmString.find_first_not_of('$', DollarStart); 1264 if (DollarEnd == std::string::npos) 1265 DollarEnd = AsmString.size(); 1266 OS << StringRef(&AsmString[Pos], DollarEnd - Pos); 1267 Pos = DollarEnd; 1268 size_t NumDollars = DollarEnd - DollarStart; 1269 if (NumDollars % 2 != 0 && Pos < AsmString.size()) { 1270 // We have an operand reference. 1271 size_t DigitStart = Pos; 1272 if (AsmString[DigitStart] == '{') { 1273 OS << '{'; 1274 ++DigitStart; 1275 } 1276 size_t DigitEnd = AsmString.find_first_not_of("0123456789", DigitStart); 1277 if (DigitEnd == std::string::npos) 1278 DigitEnd = AsmString.size(); 1279 StringRef OperandStr(&AsmString[DigitStart], DigitEnd - DigitStart); 1280 unsigned OperandIndex; 1281 if (!OperandStr.getAsInteger(10, OperandIndex)) { 1282 if (OperandIndex >= FirstIn) 1283 OperandIndex += NumNewOuts; 1284 OS << OperandIndex; 1285 } else { 1286 OS << OperandStr; 1287 } 1288 Pos = DigitEnd; 1289 } 1290 } 1291 AsmString = std::move(OS.str()); 1292 } 1293 1294 /// Add output constraints for EAX:EDX because they are return registers. 1295 void X86_32TargetCodeGenInfo::addReturnRegisterOutputs( 1296 CodeGenFunction &CGF, LValue ReturnSlot, std::string &Constraints, 1297 std::vector<llvm::Type *> &ResultRegTypes, 1298 std::vector<llvm::Type *> &ResultTruncRegTypes, 1299 std::vector<LValue> &ResultRegDests, std::string &AsmString, 1300 unsigned NumOutputs) const { 1301 uint64_t RetWidth = CGF.getContext().getTypeSize(ReturnSlot.getType()); 1302 1303 // Use the EAX constraint if the width is 32 or smaller and EAX:EDX if it is 1304 // larger. 1305 if (!Constraints.empty()) 1306 Constraints += ','; 1307 if (RetWidth <= 32) { 1308 Constraints += "={eax}"; 1309 ResultRegTypes.push_back(CGF.Int32Ty); 1310 } else { 1311 // Use the 'A' constraint for EAX:EDX. 1312 Constraints += "=A"; 1313 ResultRegTypes.push_back(CGF.Int64Ty); 1314 } 1315 1316 // Truncate EAX or EAX:EDX to an integer of the appropriate size. 1317 llvm::Type *CoerceTy = llvm::IntegerType::get(CGF.getLLVMContext(), RetWidth); 1318 ResultTruncRegTypes.push_back(CoerceTy); 1319 1320 // Coerce the integer by bitcasting the return slot pointer. 1321 ReturnSlot.setAddress(CGF.Builder.CreateBitCast(ReturnSlot.getAddress(CGF), 1322 CoerceTy->getPointerTo())); 1323 ResultRegDests.push_back(ReturnSlot); 1324 1325 rewriteInputConstraintReferences(NumOutputs, 1, AsmString); 1326 } 1327 1328 /// shouldReturnTypeInRegister - Determine if the given type should be 1329 /// returned in a register (for the Darwin and MCU ABI). 1330 bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty, 1331 ASTContext &Context) const { 1332 uint64_t Size = Context.getTypeSize(Ty); 1333 1334 // For i386, type must be register sized. 1335 // For the MCU ABI, it only needs to be <= 8-byte 1336 if ((IsMCUABI && Size > 64) || (!IsMCUABI && !isRegisterSize(Size))) 1337 return false; 1338 1339 if (Ty->isVectorType()) { 1340 // 64- and 128- bit vectors inside structures are not returned in 1341 // registers. 1342 if (Size == 64 || Size == 128) 1343 return false; 1344 1345 return true; 1346 } 1347 1348 // If this is a builtin, pointer, enum, complex type, member pointer, or 1349 // member function pointer it is ok. 1350 if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() || 1351 Ty->isAnyComplexType() || Ty->isEnumeralType() || 1352 Ty->isBlockPointerType() || Ty->isMemberPointerType()) 1353 return true; 1354 1355 // Arrays are treated like records. 1356 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) 1357 return shouldReturnTypeInRegister(AT->getElementType(), Context); 1358 1359 // Otherwise, it must be a record type. 1360 const RecordType *RT = Ty->getAs<RecordType>(); 1361 if (!RT) return false; 1362 1363 // FIXME: Traverse bases here too. 1364 1365 // Structure types are passed in register if all fields would be 1366 // passed in a register. 1367 for (const auto *FD : RT->getDecl()->fields()) { 1368 // Empty fields are ignored. 1369 if (isEmptyField(Context, FD, true)) 1370 continue; 1371 1372 // Check fields recursively. 1373 if (!shouldReturnTypeInRegister(FD->getType(), Context)) 1374 return false; 1375 } 1376 return true; 1377 } 1378 1379 static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) { 1380 // Treat complex types as the element type. 1381 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) 1382 Ty = CTy->getElementType(); 1383 1384 // Check for a type which we know has a simple scalar argument-passing 1385 // convention without any padding. (We're specifically looking for 32 1386 // and 64-bit integer and integer-equivalents, float, and double.) 1387 if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() && 1388 !Ty->isEnumeralType() && !Ty->isBlockPointerType()) 1389 return false; 1390 1391 uint64_t Size = Context.getTypeSize(Ty); 1392 return Size == 32 || Size == 64; 1393 } 1394 1395 static bool addFieldSizes(ASTContext &Context, const RecordDecl *RD, 1396 uint64_t &Size) { 1397 for (const auto *FD : RD->fields()) { 1398 // Scalar arguments on the stack get 4 byte alignment on x86. If the 1399 // argument is smaller than 32-bits, expanding the struct will create 1400 // alignment padding. 1401 if (!is32Or64BitBasicType(FD->getType(), Context)) 1402 return false; 1403 1404 // FIXME: Reject bit-fields wholesale; there are two problems, we don't know 1405 // how to expand them yet, and the predicate for telling if a bitfield still 1406 // counts as "basic" is more complicated than what we were doing previously. 1407 if (FD->isBitField()) 1408 return false; 1409 1410 Size += Context.getTypeSize(FD->getType()); 1411 } 1412 return true; 1413 } 1414 1415 static bool addBaseAndFieldSizes(ASTContext &Context, const CXXRecordDecl *RD, 1416 uint64_t &Size) { 1417 // Don't do this if there are any non-empty bases. 1418 for (const CXXBaseSpecifier &Base : RD->bases()) { 1419 if (!addBaseAndFieldSizes(Context, Base.getType()->getAsCXXRecordDecl(), 1420 Size)) 1421 return false; 1422 } 1423 if (!addFieldSizes(Context, RD, Size)) 1424 return false; 1425 return true; 1426 } 1427 1428 /// Test whether an argument type which is to be passed indirectly (on the 1429 /// stack) would have the equivalent layout if it was expanded into separate 1430 /// arguments. If so, we prefer to do the latter to avoid inhibiting 1431 /// optimizations. 1432 bool X86_32ABIInfo::canExpandIndirectArgument(QualType Ty) const { 1433 // We can only expand structure types. 1434 const RecordType *RT = Ty->getAs<RecordType>(); 1435 if (!RT) 1436 return false; 1437 const RecordDecl *RD = RT->getDecl(); 1438 uint64_t Size = 0; 1439 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 1440 if (!IsWin32StructABI) { 1441 // On non-Windows, we have to conservatively match our old bitcode 1442 // prototypes in order to be ABI-compatible at the bitcode level. 1443 if (!CXXRD->isCLike()) 1444 return false; 1445 } else { 1446 // Don't do this for dynamic classes. 1447 if (CXXRD->isDynamicClass()) 1448 return false; 1449 } 1450 if (!addBaseAndFieldSizes(getContext(), CXXRD, Size)) 1451 return false; 1452 } else { 1453 if (!addFieldSizes(getContext(), RD, Size)) 1454 return false; 1455 } 1456 1457 // We can do this if there was no alignment padding. 1458 return Size == getContext().getTypeSize(Ty); 1459 } 1460 1461 ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(QualType RetTy, CCState &State) const { 1462 // If the return value is indirect, then the hidden argument is consuming one 1463 // integer register. 1464 if (State.FreeRegs) { 1465 --State.FreeRegs; 1466 if (!IsMCUABI) 1467 return getNaturalAlignIndirectInReg(RetTy); 1468 } 1469 return getNaturalAlignIndirect(RetTy, /*ByVal=*/false); 1470 } 1471 1472 ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy, 1473 CCState &State) const { 1474 if (RetTy->isVoidType()) 1475 return ABIArgInfo::getIgnore(); 1476 1477 const Type *Base = nullptr; 1478 uint64_t NumElts = 0; 1479 if ((State.CC == llvm::CallingConv::X86_VectorCall || 1480 State.CC == llvm::CallingConv::X86_RegCall) && 1481 isHomogeneousAggregate(RetTy, Base, NumElts)) { 1482 // The LLVM struct type for such an aggregate should lower properly. 1483 return ABIArgInfo::getDirect(); 1484 } 1485 1486 if (const VectorType *VT = RetTy->getAs<VectorType>()) { 1487 // On Darwin, some vectors are returned in registers. 1488 if (IsDarwinVectorABI) { 1489 uint64_t Size = getContext().getTypeSize(RetTy); 1490 1491 // 128-bit vectors are a special case; they are returned in 1492 // registers and we need to make sure to pick a type the LLVM 1493 // backend will like. 1494 if (Size == 128) 1495 return ABIArgInfo::getDirect(llvm::FixedVectorType::get( 1496 llvm::Type::getInt64Ty(getVMContext()), 2)); 1497 1498 // Always return in register if it fits in a general purpose 1499 // register, or if it is 64 bits and has a single element. 1500 if ((Size == 8 || Size == 16 || Size == 32) || 1501 (Size == 64 && VT->getNumElements() == 1)) 1502 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 1503 Size)); 1504 1505 return getIndirectReturnResult(RetTy, State); 1506 } 1507 1508 return ABIArgInfo::getDirect(); 1509 } 1510 1511 if (isAggregateTypeForABI(RetTy)) { 1512 if (const RecordType *RT = RetTy->getAs<RecordType>()) { 1513 // Structures with flexible arrays are always indirect. 1514 if (RT->getDecl()->hasFlexibleArrayMember()) 1515 return getIndirectReturnResult(RetTy, State); 1516 } 1517 1518 // If specified, structs and unions are always indirect. 1519 if (!IsRetSmallStructInRegABI && !RetTy->isAnyComplexType()) 1520 return getIndirectReturnResult(RetTy, State); 1521 1522 // Ignore empty structs/unions. 1523 if (isEmptyRecord(getContext(), RetTy, true)) 1524 return ABIArgInfo::getIgnore(); 1525 1526 // Small structures which are register sized are generally returned 1527 // in a register. 1528 if (shouldReturnTypeInRegister(RetTy, getContext())) { 1529 uint64_t Size = getContext().getTypeSize(RetTy); 1530 1531 // As a special-case, if the struct is a "single-element" struct, and 1532 // the field is of type "float" or "double", return it in a 1533 // floating-point register. (MSVC does not apply this special case.) 1534 // We apply a similar transformation for pointer types to improve the 1535 // quality of the generated IR. 1536 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext())) 1537 if ((!IsWin32StructABI && SeltTy->isRealFloatingType()) 1538 || SeltTy->hasPointerRepresentation()) 1539 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0))); 1540 1541 // FIXME: We should be able to narrow this integer in cases with dead 1542 // padding. 1543 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size)); 1544 } 1545 1546 return getIndirectReturnResult(RetTy, State); 1547 } 1548 1549 // Treat an enum type as its underlying type. 1550 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 1551 RetTy = EnumTy->getDecl()->getIntegerType(); 1552 1553 if (const auto *EIT = RetTy->getAs<ExtIntType>()) 1554 if (EIT->getNumBits() > 64) 1555 return getIndirectReturnResult(RetTy, State); 1556 1557 return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy) 1558 : ABIArgInfo::getDirect()); 1559 } 1560 1561 static bool isSIMDVectorType(ASTContext &Context, QualType Ty) { 1562 return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128; 1563 } 1564 1565 static bool isRecordWithSIMDVectorType(ASTContext &Context, QualType Ty) { 1566 const RecordType *RT = Ty->getAs<RecordType>(); 1567 if (!RT) 1568 return 0; 1569 const RecordDecl *RD = RT->getDecl(); 1570 1571 // If this is a C++ record, check the bases first. 1572 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 1573 for (const auto &I : CXXRD->bases()) 1574 if (!isRecordWithSIMDVectorType(Context, I.getType())) 1575 return false; 1576 1577 for (const auto *i : RD->fields()) { 1578 QualType FT = i->getType(); 1579 1580 if (isSIMDVectorType(Context, FT)) 1581 return true; 1582 1583 if (isRecordWithSIMDVectorType(Context, FT)) 1584 return true; 1585 } 1586 1587 return false; 1588 } 1589 1590 unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty, 1591 unsigned Align) const { 1592 // Otherwise, if the alignment is less than or equal to the minimum ABI 1593 // alignment, just use the default; the backend will handle this. 1594 if (Align <= MinABIStackAlignInBytes) 1595 return 0; // Use default alignment. 1596 1597 // On non-Darwin, the stack type alignment is always 4. 1598 if (!IsDarwinVectorABI) { 1599 // Set explicit alignment, since we may need to realign the top. 1600 return MinABIStackAlignInBytes; 1601 } 1602 1603 // Otherwise, if the type contains an SSE vector type, the alignment is 16. 1604 if (Align >= 16 && (isSIMDVectorType(getContext(), Ty) || 1605 isRecordWithSIMDVectorType(getContext(), Ty))) 1606 return 16; 1607 1608 return MinABIStackAlignInBytes; 1609 } 1610 1611 ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal, 1612 CCState &State) const { 1613 if (!ByVal) { 1614 if (State.FreeRegs) { 1615 --State.FreeRegs; // Non-byval indirects just use one pointer. 1616 if (!IsMCUABI) 1617 return getNaturalAlignIndirectInReg(Ty); 1618 } 1619 return getNaturalAlignIndirect(Ty, false); 1620 } 1621 1622 // Compute the byval alignment. 1623 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8; 1624 unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign); 1625 if (StackAlign == 0) 1626 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true); 1627 1628 // If the stack alignment is less than the type alignment, realign the 1629 // argument. 1630 bool Realign = TypeAlign > StackAlign; 1631 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(StackAlign), 1632 /*ByVal=*/true, Realign); 1633 } 1634 1635 X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const { 1636 const Type *T = isSingleElementStruct(Ty, getContext()); 1637 if (!T) 1638 T = Ty.getTypePtr(); 1639 1640 if (const BuiltinType *BT = T->getAs<BuiltinType>()) { 1641 BuiltinType::Kind K = BT->getKind(); 1642 if (K == BuiltinType::Float || K == BuiltinType::Double) 1643 return Float; 1644 } 1645 return Integer; 1646 } 1647 1648 bool X86_32ABIInfo::updateFreeRegs(QualType Ty, CCState &State) const { 1649 if (!IsSoftFloatABI) { 1650 Class C = classify(Ty); 1651 if (C == Float) 1652 return false; 1653 } 1654 1655 unsigned Size = getContext().getTypeSize(Ty); 1656 unsigned SizeInRegs = (Size + 31) / 32; 1657 1658 if (SizeInRegs == 0) 1659 return false; 1660 1661 if (!IsMCUABI) { 1662 if (SizeInRegs > State.FreeRegs) { 1663 State.FreeRegs = 0; 1664 return false; 1665 } 1666 } else { 1667 // The MCU psABI allows passing parameters in-reg even if there are 1668 // earlier parameters that are passed on the stack. Also, 1669 // it does not allow passing >8-byte structs in-register, 1670 // even if there are 3 free registers available. 1671 if (SizeInRegs > State.FreeRegs || SizeInRegs > 2) 1672 return false; 1673 } 1674 1675 State.FreeRegs -= SizeInRegs; 1676 return true; 1677 } 1678 1679 bool X86_32ABIInfo::shouldAggregateUseDirect(QualType Ty, CCState &State, 1680 bool &InReg, 1681 bool &NeedsPadding) const { 1682 // On Windows, aggregates other than HFAs are never passed in registers, and 1683 // they do not consume register slots. Homogenous floating-point aggregates 1684 // (HFAs) have already been dealt with at this point. 1685 if (IsWin32StructABI && isAggregateTypeForABI(Ty)) 1686 return false; 1687 1688 NeedsPadding = false; 1689 InReg = !IsMCUABI; 1690 1691 if (!updateFreeRegs(Ty, State)) 1692 return false; 1693 1694 if (IsMCUABI) 1695 return true; 1696 1697 if (State.CC == llvm::CallingConv::X86_FastCall || 1698 State.CC == llvm::CallingConv::X86_VectorCall || 1699 State.CC == llvm::CallingConv::X86_RegCall) { 1700 if (getContext().getTypeSize(Ty) <= 32 && State.FreeRegs) 1701 NeedsPadding = true; 1702 1703 return false; 1704 } 1705 1706 return true; 1707 } 1708 1709 bool X86_32ABIInfo::shouldPrimitiveUseInReg(QualType Ty, CCState &State) const { 1710 if (!updateFreeRegs(Ty, State)) 1711 return false; 1712 1713 if (IsMCUABI) 1714 return false; 1715 1716 if (State.CC == llvm::CallingConv::X86_FastCall || 1717 State.CC == llvm::CallingConv::X86_VectorCall || 1718 State.CC == llvm::CallingConv::X86_RegCall) { 1719 if (getContext().getTypeSize(Ty) > 32) 1720 return false; 1721 1722 return (Ty->isIntegralOrEnumerationType() || Ty->isPointerType() || 1723 Ty->isReferenceType()); 1724 } 1725 1726 return true; 1727 } 1728 1729 void X86_32ABIInfo::runVectorCallFirstPass(CGFunctionInfo &FI, CCState &State) const { 1730 // Vectorcall x86 works subtly different than in x64, so the format is 1731 // a bit different than the x64 version. First, all vector types (not HVAs) 1732 // are assigned, with the first 6 ending up in the [XYZ]MM0-5 registers. 1733 // This differs from the x64 implementation, where the first 6 by INDEX get 1734 // registers. 1735 // In the second pass over the arguments, HVAs are passed in the remaining 1736 // vector registers if possible, or indirectly by address. The address will be 1737 // passed in ECX/EDX if available. Any other arguments are passed according to 1738 // the usual fastcall rules. 1739 MutableArrayRef<CGFunctionInfoArgInfo> Args = FI.arguments(); 1740 for (int I = 0, E = Args.size(); I < E; ++I) { 1741 const Type *Base = nullptr; 1742 uint64_t NumElts = 0; 1743 const QualType &Ty = Args[I].type; 1744 if ((Ty->isVectorType() || Ty->isBuiltinType()) && 1745 isHomogeneousAggregate(Ty, Base, NumElts)) { 1746 if (State.FreeSSERegs >= NumElts) { 1747 State.FreeSSERegs -= NumElts; 1748 Args[I].info = ABIArgInfo::getDirectInReg(); 1749 State.IsPreassigned.set(I); 1750 } 1751 } 1752 } 1753 } 1754 1755 ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty, 1756 CCState &State) const { 1757 // FIXME: Set alignment on indirect arguments. 1758 bool IsFastCall = State.CC == llvm::CallingConv::X86_FastCall; 1759 bool IsRegCall = State.CC == llvm::CallingConv::X86_RegCall; 1760 bool IsVectorCall = State.CC == llvm::CallingConv::X86_VectorCall; 1761 1762 Ty = useFirstFieldIfTransparentUnion(Ty); 1763 TypeInfo TI = getContext().getTypeInfo(Ty); 1764 1765 // Check with the C++ ABI first. 1766 const RecordType *RT = Ty->getAs<RecordType>(); 1767 if (RT) { 1768 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()); 1769 if (RAA == CGCXXABI::RAA_Indirect) { 1770 return getIndirectResult(Ty, false, State); 1771 } else if (RAA == CGCXXABI::RAA_DirectInMemory) { 1772 // The field index doesn't matter, we'll fix it up later. 1773 return ABIArgInfo::getInAlloca(/*FieldIndex=*/0); 1774 } 1775 } 1776 1777 // Regcall uses the concept of a homogenous vector aggregate, similar 1778 // to other targets. 1779 const Type *Base = nullptr; 1780 uint64_t NumElts = 0; 1781 if ((IsRegCall || IsVectorCall) && 1782 isHomogeneousAggregate(Ty, Base, NumElts)) { 1783 if (State.FreeSSERegs >= NumElts) { 1784 State.FreeSSERegs -= NumElts; 1785 1786 // Vectorcall passes HVAs directly and does not flatten them, but regcall 1787 // does. 1788 if (IsVectorCall) 1789 return getDirectX86Hva(); 1790 1791 if (Ty->isBuiltinType() || Ty->isVectorType()) 1792 return ABIArgInfo::getDirect(); 1793 return ABIArgInfo::getExpand(); 1794 } 1795 return getIndirectResult(Ty, /*ByVal=*/false, State); 1796 } 1797 1798 if (isAggregateTypeForABI(Ty)) { 1799 // Structures with flexible arrays are always indirect. 1800 // FIXME: This should not be byval! 1801 if (RT && RT->getDecl()->hasFlexibleArrayMember()) 1802 return getIndirectResult(Ty, true, State); 1803 1804 // Ignore empty structs/unions on non-Windows. 1805 if (!IsWin32StructABI && isEmptyRecord(getContext(), Ty, true)) 1806 return ABIArgInfo::getIgnore(); 1807 1808 llvm::LLVMContext &LLVMContext = getVMContext(); 1809 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext); 1810 bool NeedsPadding = false; 1811 bool InReg; 1812 if (shouldAggregateUseDirect(Ty, State, InReg, NeedsPadding)) { 1813 unsigned SizeInRegs = (TI.Width + 31) / 32; 1814 SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32); 1815 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements); 1816 if (InReg) 1817 return ABIArgInfo::getDirectInReg(Result); 1818 else 1819 return ABIArgInfo::getDirect(Result); 1820 } 1821 llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : nullptr; 1822 1823 // Pass over-aligned aggregates on Windows indirectly. This behavior was 1824 // added in MSVC 2015. 1825 if (IsWin32StructABI && TI.AlignIsRequired && TI.Align > 32) 1826 return getIndirectResult(Ty, /*ByVal=*/false, State); 1827 1828 // Expand small (<= 128-bit) record types when we know that the stack layout 1829 // of those arguments will match the struct. This is important because the 1830 // LLVM backend isn't smart enough to remove byval, which inhibits many 1831 // optimizations. 1832 // Don't do this for the MCU if there are still free integer registers 1833 // (see X86_64 ABI for full explanation). 1834 if (TI.Width <= 4 * 32 && (!IsMCUABI || State.FreeRegs == 0) && 1835 canExpandIndirectArgument(Ty)) 1836 return ABIArgInfo::getExpandWithPadding( 1837 IsFastCall || IsVectorCall || IsRegCall, PaddingType); 1838 1839 return getIndirectResult(Ty, true, State); 1840 } 1841 1842 if (const VectorType *VT = Ty->getAs<VectorType>()) { 1843 // On Windows, vectors are passed directly if registers are available, or 1844 // indirectly if not. This avoids the need to align argument memory. Pass 1845 // user-defined vector types larger than 512 bits indirectly for simplicity. 1846 if (IsWin32StructABI) { 1847 if (TI.Width <= 512 && State.FreeSSERegs > 0) { 1848 --State.FreeSSERegs; 1849 return ABIArgInfo::getDirectInReg(); 1850 } 1851 return getIndirectResult(Ty, /*ByVal=*/false, State); 1852 } 1853 1854 // On Darwin, some vectors are passed in memory, we handle this by passing 1855 // it as an i8/i16/i32/i64. 1856 if (IsDarwinVectorABI) { 1857 if ((TI.Width == 8 || TI.Width == 16 || TI.Width == 32) || 1858 (TI.Width == 64 && VT->getNumElements() == 1)) 1859 return ABIArgInfo::getDirect( 1860 llvm::IntegerType::get(getVMContext(), TI.Width)); 1861 } 1862 1863 if (IsX86_MMXType(CGT.ConvertType(Ty))) 1864 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64)); 1865 1866 return ABIArgInfo::getDirect(); 1867 } 1868 1869 1870 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 1871 Ty = EnumTy->getDecl()->getIntegerType(); 1872 1873 bool InReg = shouldPrimitiveUseInReg(Ty, State); 1874 1875 if (isPromotableIntegerTypeForABI(Ty)) { 1876 if (InReg) 1877 return ABIArgInfo::getExtendInReg(Ty); 1878 return ABIArgInfo::getExtend(Ty); 1879 } 1880 1881 if (const auto * EIT = Ty->getAs<ExtIntType>()) { 1882 if (EIT->getNumBits() <= 64) { 1883 if (InReg) 1884 return ABIArgInfo::getDirectInReg(); 1885 return ABIArgInfo::getDirect(); 1886 } 1887 return getIndirectResult(Ty, /*ByVal=*/false, State); 1888 } 1889 1890 if (InReg) 1891 return ABIArgInfo::getDirectInReg(); 1892 return ABIArgInfo::getDirect(); 1893 } 1894 1895 void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const { 1896 CCState State(FI); 1897 if (IsMCUABI) 1898 State.FreeRegs = 3; 1899 else if (State.CC == llvm::CallingConv::X86_FastCall) { 1900 State.FreeRegs = 2; 1901 State.FreeSSERegs = 3; 1902 } else if (State.CC == llvm::CallingConv::X86_VectorCall) { 1903 State.FreeRegs = 2; 1904 State.FreeSSERegs = 6; 1905 } else if (FI.getHasRegParm()) 1906 State.FreeRegs = FI.getRegParm(); 1907 else if (State.CC == llvm::CallingConv::X86_RegCall) { 1908 State.FreeRegs = 5; 1909 State.FreeSSERegs = 8; 1910 } else if (IsWin32StructABI) { 1911 // Since MSVC 2015, the first three SSE vectors have been passed in 1912 // registers. The rest are passed indirectly. 1913 State.FreeRegs = DefaultNumRegisterParameters; 1914 State.FreeSSERegs = 3; 1915 } else 1916 State.FreeRegs = DefaultNumRegisterParameters; 1917 1918 if (!::classifyReturnType(getCXXABI(), FI, *this)) { 1919 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), State); 1920 } else if (FI.getReturnInfo().isIndirect()) { 1921 // The C++ ABI is not aware of register usage, so we have to check if the 1922 // return value was sret and put it in a register ourselves if appropriate. 1923 if (State.FreeRegs) { 1924 --State.FreeRegs; // The sret parameter consumes a register. 1925 if (!IsMCUABI) 1926 FI.getReturnInfo().setInReg(true); 1927 } 1928 } 1929 1930 // The chain argument effectively gives us another free register. 1931 if (FI.isChainCall()) 1932 ++State.FreeRegs; 1933 1934 // For vectorcall, do a first pass over the arguments, assigning FP and vector 1935 // arguments to XMM registers as available. 1936 if (State.CC == llvm::CallingConv::X86_VectorCall) 1937 runVectorCallFirstPass(FI, State); 1938 1939 bool UsedInAlloca = false; 1940 MutableArrayRef<CGFunctionInfoArgInfo> Args = FI.arguments(); 1941 for (int I = 0, E = Args.size(); I < E; ++I) { 1942 // Skip arguments that have already been assigned. 1943 if (State.IsPreassigned.test(I)) 1944 continue; 1945 1946 Args[I].info = classifyArgumentType(Args[I].type, State); 1947 UsedInAlloca |= (Args[I].info.getKind() == ABIArgInfo::InAlloca); 1948 } 1949 1950 // If we needed to use inalloca for any argument, do a second pass and rewrite 1951 // all the memory arguments to use inalloca. 1952 if (UsedInAlloca) 1953 rewriteWithInAlloca(FI); 1954 } 1955 1956 void 1957 X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields, 1958 CharUnits &StackOffset, ABIArgInfo &Info, 1959 QualType Type) const { 1960 // Arguments are always 4-byte-aligned. 1961 CharUnits WordSize = CharUnits::fromQuantity(4); 1962 assert(StackOffset.isMultipleOf(WordSize) && "unaligned inalloca struct"); 1963 1964 // sret pointers and indirect things will require an extra pointer 1965 // indirection, unless they are byval. Most things are byval, and will not 1966 // require this indirection. 1967 bool IsIndirect = false; 1968 if (Info.isIndirect() && !Info.getIndirectByVal()) 1969 IsIndirect = true; 1970 Info = ABIArgInfo::getInAlloca(FrameFields.size(), IsIndirect); 1971 llvm::Type *LLTy = CGT.ConvertTypeForMem(Type); 1972 if (IsIndirect) 1973 LLTy = LLTy->getPointerTo(0); 1974 FrameFields.push_back(LLTy); 1975 StackOffset += IsIndirect ? WordSize : getContext().getTypeSizeInChars(Type); 1976 1977 // Insert padding bytes to respect alignment. 1978 CharUnits FieldEnd = StackOffset; 1979 StackOffset = FieldEnd.alignTo(WordSize); 1980 if (StackOffset != FieldEnd) { 1981 CharUnits NumBytes = StackOffset - FieldEnd; 1982 llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext()); 1983 Ty = llvm::ArrayType::get(Ty, NumBytes.getQuantity()); 1984 FrameFields.push_back(Ty); 1985 } 1986 } 1987 1988 static bool isArgInAlloca(const ABIArgInfo &Info) { 1989 // Leave ignored and inreg arguments alone. 1990 switch (Info.getKind()) { 1991 case ABIArgInfo::InAlloca: 1992 return true; 1993 case ABIArgInfo::Ignore: 1994 case ABIArgInfo::IndirectAliased: 1995 return false; 1996 case ABIArgInfo::Indirect: 1997 case ABIArgInfo::Direct: 1998 case ABIArgInfo::Extend: 1999 return !Info.getInReg(); 2000 case ABIArgInfo::Expand: 2001 case ABIArgInfo::CoerceAndExpand: 2002 // These are aggregate types which are never passed in registers when 2003 // inalloca is involved. 2004 return true; 2005 } 2006 llvm_unreachable("invalid enum"); 2007 } 2008 2009 void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const { 2010 assert(IsWin32StructABI && "inalloca only supported on win32"); 2011 2012 // Build a packed struct type for all of the arguments in memory. 2013 SmallVector<llvm::Type *, 6> FrameFields; 2014 2015 // The stack alignment is always 4. 2016 CharUnits StackAlign = CharUnits::fromQuantity(4); 2017 2018 CharUnits StackOffset; 2019 CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end(); 2020 2021 // Put 'this' into the struct before 'sret', if necessary. 2022 bool IsThisCall = 2023 FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall; 2024 ABIArgInfo &Ret = FI.getReturnInfo(); 2025 if (Ret.isIndirect() && Ret.isSRetAfterThis() && !IsThisCall && 2026 isArgInAlloca(I->info)) { 2027 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type); 2028 ++I; 2029 } 2030 2031 // Put the sret parameter into the inalloca struct if it's in memory. 2032 if (Ret.isIndirect() && !Ret.getInReg()) { 2033 addFieldToArgStruct(FrameFields, StackOffset, Ret, FI.getReturnType()); 2034 // On Windows, the hidden sret parameter is always returned in eax. 2035 Ret.setInAllocaSRet(IsWin32StructABI); 2036 } 2037 2038 // Skip the 'this' parameter in ecx. 2039 if (IsThisCall) 2040 ++I; 2041 2042 // Put arguments passed in memory into the struct. 2043 for (; I != E; ++I) { 2044 if (isArgInAlloca(I->info)) 2045 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type); 2046 } 2047 2048 FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields, 2049 /*isPacked=*/true), 2050 StackAlign); 2051 } 2052 2053 Address X86_32ABIInfo::EmitVAArg(CodeGenFunction &CGF, 2054 Address VAListAddr, QualType Ty) const { 2055 2056 auto TypeInfo = getContext().getTypeInfoInChars(Ty); 2057 2058 // x86-32 changes the alignment of certain arguments on the stack. 2059 // 2060 // Just messing with TypeInfo like this works because we never pass 2061 // anything indirectly. 2062 TypeInfo.Align = CharUnits::fromQuantity( 2063 getTypeStackAlignInBytes(Ty, TypeInfo.Align.getQuantity())); 2064 2065 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false, 2066 TypeInfo, CharUnits::fromQuantity(4), 2067 /*AllowHigherAlign*/ true); 2068 } 2069 2070 bool X86_32TargetCodeGenInfo::isStructReturnInRegABI( 2071 const llvm::Triple &Triple, const CodeGenOptions &Opts) { 2072 assert(Triple.getArch() == llvm::Triple::x86); 2073 2074 switch (Opts.getStructReturnConvention()) { 2075 case CodeGenOptions::SRCK_Default: 2076 break; 2077 case CodeGenOptions::SRCK_OnStack: // -fpcc-struct-return 2078 return false; 2079 case CodeGenOptions::SRCK_InRegs: // -freg-struct-return 2080 return true; 2081 } 2082 2083 if (Triple.isOSDarwin() || Triple.isOSIAMCU()) 2084 return true; 2085 2086 switch (Triple.getOS()) { 2087 case llvm::Triple::DragonFly: 2088 case llvm::Triple::FreeBSD: 2089 case llvm::Triple::OpenBSD: 2090 case llvm::Triple::Win32: 2091 return true; 2092 default: 2093 return false; 2094 } 2095 } 2096 2097 static void addX86InterruptAttrs(const FunctionDecl *FD, llvm::GlobalValue *GV, 2098 CodeGen::CodeGenModule &CGM) { 2099 if (!FD->hasAttr<AnyX86InterruptAttr>()) 2100 return; 2101 2102 llvm::Function *Fn = cast<llvm::Function>(GV); 2103 Fn->setCallingConv(llvm::CallingConv::X86_INTR); 2104 if (FD->getNumParams() == 0) 2105 return; 2106 2107 auto PtrTy = cast<PointerType>(FD->getParamDecl(0)->getType()); 2108 llvm::Type *ByValTy = CGM.getTypes().ConvertType(PtrTy->getPointeeType()); 2109 llvm::Attribute NewAttr = llvm::Attribute::getWithByValType( 2110 Fn->getContext(), ByValTy); 2111 Fn->addParamAttr(0, NewAttr); 2112 } 2113 2114 void X86_32TargetCodeGenInfo::setTargetAttributes( 2115 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const { 2116 if (GV->isDeclaration()) 2117 return; 2118 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) { 2119 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) { 2120 llvm::Function *Fn = cast<llvm::Function>(GV); 2121 Fn->addFnAttr("stackrealign"); 2122 } 2123 2124 addX86InterruptAttrs(FD, GV, CGM); 2125 } 2126 } 2127 2128 bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable( 2129 CodeGen::CodeGenFunction &CGF, 2130 llvm::Value *Address) const { 2131 CodeGen::CGBuilderTy &Builder = CGF.Builder; 2132 2133 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4); 2134 2135 // 0-7 are the eight integer registers; the order is different 2136 // on Darwin (for EH), but the range is the same. 2137 // 8 is %eip. 2138 AssignToArrayRange(Builder, Address, Four8, 0, 8); 2139 2140 if (CGF.CGM.getTarget().getTriple().isOSDarwin()) { 2141 // 12-16 are st(0..4). Not sure why we stop at 4. 2142 // These have size 16, which is sizeof(long double) on 2143 // platforms with 8-byte alignment for that type. 2144 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16); 2145 AssignToArrayRange(Builder, Address, Sixteen8, 12, 16); 2146 2147 } else { 2148 // 9 is %eflags, which doesn't get a size on Darwin for some 2149 // reason. 2150 Builder.CreateAlignedStore( 2151 Four8, Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, Address, 9), 2152 CharUnits::One()); 2153 2154 // 11-16 are st(0..5). Not sure why we stop at 5. 2155 // These have size 12, which is sizeof(long double) on 2156 // platforms with 4-byte alignment for that type. 2157 llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12); 2158 AssignToArrayRange(Builder, Address, Twelve8, 11, 16); 2159 } 2160 2161 return false; 2162 } 2163 2164 //===----------------------------------------------------------------------===// 2165 // X86-64 ABI Implementation 2166 //===----------------------------------------------------------------------===// 2167 2168 2169 namespace { 2170 /// The AVX ABI level for X86 targets. 2171 enum class X86AVXABILevel { 2172 None, 2173 AVX, 2174 AVX512 2175 }; 2176 2177 /// \p returns the size in bits of the largest (native) vector for \p AVXLevel. 2178 static unsigned getNativeVectorSizeForAVXABI(X86AVXABILevel AVXLevel) { 2179 switch (AVXLevel) { 2180 case X86AVXABILevel::AVX512: 2181 return 512; 2182 case X86AVXABILevel::AVX: 2183 return 256; 2184 case X86AVXABILevel::None: 2185 return 128; 2186 } 2187 llvm_unreachable("Unknown AVXLevel"); 2188 } 2189 2190 /// X86_64ABIInfo - The X86_64 ABI information. 2191 class X86_64ABIInfo : public SwiftABIInfo { 2192 enum Class { 2193 Integer = 0, 2194 SSE, 2195 SSEUp, 2196 X87, 2197 X87Up, 2198 ComplexX87, 2199 NoClass, 2200 Memory 2201 }; 2202 2203 /// merge - Implement the X86_64 ABI merging algorithm. 2204 /// 2205 /// Merge an accumulating classification \arg Accum with a field 2206 /// classification \arg Field. 2207 /// 2208 /// \param Accum - The accumulating classification. This should 2209 /// always be either NoClass or the result of a previous merge 2210 /// call. In addition, this should never be Memory (the caller 2211 /// should just return Memory for the aggregate). 2212 static Class merge(Class Accum, Class Field); 2213 2214 /// postMerge - Implement the X86_64 ABI post merging algorithm. 2215 /// 2216 /// Post merger cleanup, reduces a malformed Hi and Lo pair to 2217 /// final MEMORY or SSE classes when necessary. 2218 /// 2219 /// \param AggregateSize - The size of the current aggregate in 2220 /// the classification process. 2221 /// 2222 /// \param Lo - The classification for the parts of the type 2223 /// residing in the low word of the containing object. 2224 /// 2225 /// \param Hi - The classification for the parts of the type 2226 /// residing in the higher words of the containing object. 2227 /// 2228 void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const; 2229 2230 /// classify - Determine the x86_64 register classes in which the 2231 /// given type T should be passed. 2232 /// 2233 /// \param Lo - The classification for the parts of the type 2234 /// residing in the low word of the containing object. 2235 /// 2236 /// \param Hi - The classification for the parts of the type 2237 /// residing in the high word of the containing object. 2238 /// 2239 /// \param OffsetBase - The bit offset of this type in the 2240 /// containing object. Some parameters are classified different 2241 /// depending on whether they straddle an eightbyte boundary. 2242 /// 2243 /// \param isNamedArg - Whether the argument in question is a "named" 2244 /// argument, as used in AMD64-ABI 3.5.7. 2245 /// 2246 /// If a word is unused its result will be NoClass; if a type should 2247 /// be passed in Memory then at least the classification of \arg Lo 2248 /// will be Memory. 2249 /// 2250 /// The \arg Lo class will be NoClass iff the argument is ignored. 2251 /// 2252 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will 2253 /// also be ComplexX87. 2254 void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi, 2255 bool isNamedArg) const; 2256 2257 llvm::Type *GetByteVectorType(QualType Ty) const; 2258 llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType, 2259 unsigned IROffset, QualType SourceTy, 2260 unsigned SourceOffset) const; 2261 llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType, 2262 unsigned IROffset, QualType SourceTy, 2263 unsigned SourceOffset) const; 2264 2265 /// getIndirectResult - Give a source type \arg Ty, return a suitable result 2266 /// such that the argument will be returned in memory. 2267 ABIArgInfo getIndirectReturnResult(QualType Ty) const; 2268 2269 /// getIndirectResult - Give a source type \arg Ty, return a suitable result 2270 /// such that the argument will be passed in memory. 2271 /// 2272 /// \param freeIntRegs - The number of free integer registers remaining 2273 /// available. 2274 ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const; 2275 2276 ABIArgInfo classifyReturnType(QualType RetTy) const; 2277 2278 ABIArgInfo classifyArgumentType(QualType Ty, unsigned freeIntRegs, 2279 unsigned &neededInt, unsigned &neededSSE, 2280 bool isNamedArg) const; 2281 2282 ABIArgInfo classifyRegCallStructType(QualType Ty, unsigned &NeededInt, 2283 unsigned &NeededSSE) const; 2284 2285 ABIArgInfo classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt, 2286 unsigned &NeededSSE) const; 2287 2288 bool IsIllegalVectorType(QualType Ty) const; 2289 2290 /// The 0.98 ABI revision clarified a lot of ambiguities, 2291 /// unfortunately in ways that were not always consistent with 2292 /// certain previous compilers. In particular, platforms which 2293 /// required strict binary compatibility with older versions of GCC 2294 /// may need to exempt themselves. 2295 bool honorsRevision0_98() const { 2296 return !getTarget().getTriple().isOSDarwin(); 2297 } 2298 2299 /// GCC classifies <1 x long long> as SSE but some platform ABIs choose to 2300 /// classify it as INTEGER (for compatibility with older clang compilers). 2301 bool classifyIntegerMMXAsSSE() const { 2302 // Clang <= 3.8 did not do this. 2303 if (getContext().getLangOpts().getClangABICompat() <= 2304 LangOptions::ClangABI::Ver3_8) 2305 return false; 2306 2307 const llvm::Triple &Triple = getTarget().getTriple(); 2308 if (Triple.isOSDarwin() || Triple.getOS() == llvm::Triple::PS4) 2309 return false; 2310 if (Triple.isOSFreeBSD() && Triple.getOSMajorVersion() >= 10) 2311 return false; 2312 return true; 2313 } 2314 2315 // GCC classifies vectors of __int128 as memory. 2316 bool passInt128VectorsInMem() const { 2317 // Clang <= 9.0 did not do this. 2318 if (getContext().getLangOpts().getClangABICompat() <= 2319 LangOptions::ClangABI::Ver9) 2320 return false; 2321 2322 const llvm::Triple &T = getTarget().getTriple(); 2323 return T.isOSLinux() || T.isOSNetBSD(); 2324 } 2325 2326 X86AVXABILevel AVXLevel; 2327 // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on 2328 // 64-bit hardware. 2329 bool Has64BitPointers; 2330 2331 public: 2332 X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) : 2333 SwiftABIInfo(CGT), AVXLevel(AVXLevel), 2334 Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) { 2335 } 2336 2337 bool isPassedUsingAVXType(QualType type) const { 2338 unsigned neededInt, neededSSE; 2339 // The freeIntRegs argument doesn't matter here. 2340 ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE, 2341 /*isNamedArg*/true); 2342 if (info.isDirect()) { 2343 llvm::Type *ty = info.getCoerceToType(); 2344 if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty)) 2345 return vectorTy->getPrimitiveSizeInBits().getFixedSize() > 128; 2346 } 2347 return false; 2348 } 2349 2350 void computeInfo(CGFunctionInfo &FI) const override; 2351 2352 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 2353 QualType Ty) const override; 2354 Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr, 2355 QualType Ty) const override; 2356 2357 bool has64BitPointers() const { 2358 return Has64BitPointers; 2359 } 2360 2361 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars, 2362 bool asReturnValue) const override { 2363 return occupiesMoreThan(CGT, scalars, /*total*/ 4); 2364 } 2365 bool isSwiftErrorInRegister() const override { 2366 return true; 2367 } 2368 }; 2369 2370 /// WinX86_64ABIInfo - The Windows X86_64 ABI information. 2371 class WinX86_64ABIInfo : public SwiftABIInfo { 2372 public: 2373 WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) 2374 : SwiftABIInfo(CGT), AVXLevel(AVXLevel), 2375 IsMingw64(getTarget().getTriple().isWindowsGNUEnvironment()) {} 2376 2377 void computeInfo(CGFunctionInfo &FI) const override; 2378 2379 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 2380 QualType Ty) const override; 2381 2382 bool isHomogeneousAggregateBaseType(QualType Ty) const override { 2383 // FIXME: Assumes vectorcall is in use. 2384 return isX86VectorTypeForVectorCall(getContext(), Ty); 2385 } 2386 2387 bool isHomogeneousAggregateSmallEnough(const Type *Ty, 2388 uint64_t NumMembers) const override { 2389 // FIXME: Assumes vectorcall is in use. 2390 return isX86VectorCallAggregateSmallEnough(NumMembers); 2391 } 2392 2393 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type *> scalars, 2394 bool asReturnValue) const override { 2395 return occupiesMoreThan(CGT, scalars, /*total*/ 4); 2396 } 2397 2398 bool isSwiftErrorInRegister() const override { 2399 return true; 2400 } 2401 2402 private: 2403 ABIArgInfo classify(QualType Ty, unsigned &FreeSSERegs, bool IsReturnType, 2404 bool IsVectorCall, bool IsRegCall) const; 2405 ABIArgInfo reclassifyHvaArgForVectorCall(QualType Ty, unsigned &FreeSSERegs, 2406 const ABIArgInfo ¤t) const; 2407 2408 X86AVXABILevel AVXLevel; 2409 2410 bool IsMingw64; 2411 }; 2412 2413 class X86_64TargetCodeGenInfo : public TargetCodeGenInfo { 2414 public: 2415 X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) 2416 : TargetCodeGenInfo(std::make_unique<X86_64ABIInfo>(CGT, AVXLevel)) {} 2417 2418 const X86_64ABIInfo &getABIInfo() const { 2419 return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo()); 2420 } 2421 2422 /// Disable tail call on x86-64. The epilogue code before the tail jump blocks 2423 /// autoreleaseRV/retainRV and autoreleaseRV/unsafeClaimRV optimizations. 2424 bool markARCOptimizedReturnCallsAsNoTail() const override { return true; } 2425 2426 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override { 2427 return 7; 2428 } 2429 2430 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 2431 llvm::Value *Address) const override { 2432 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8); 2433 2434 // 0-15 are the 16 integer registers. 2435 // 16 is %rip. 2436 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16); 2437 return false; 2438 } 2439 2440 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF, 2441 StringRef Constraint, 2442 llvm::Type* Ty) const override { 2443 return X86AdjustInlineAsmType(CGF, Constraint, Ty); 2444 } 2445 2446 bool isNoProtoCallVariadic(const CallArgList &args, 2447 const FunctionNoProtoType *fnType) const override { 2448 // The default CC on x86-64 sets %al to the number of SSA 2449 // registers used, and GCC sets this when calling an unprototyped 2450 // function, so we override the default behavior. However, don't do 2451 // that when AVX types are involved: the ABI explicitly states it is 2452 // undefined, and it doesn't work in practice because of how the ABI 2453 // defines varargs anyway. 2454 if (fnType->getCallConv() == CC_C) { 2455 bool HasAVXType = false; 2456 for (CallArgList::const_iterator 2457 it = args.begin(), ie = args.end(); it != ie; ++it) { 2458 if (getABIInfo().isPassedUsingAVXType(it->Ty)) { 2459 HasAVXType = true; 2460 break; 2461 } 2462 } 2463 2464 if (!HasAVXType) 2465 return true; 2466 } 2467 2468 return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType); 2469 } 2470 2471 llvm::Constant * 2472 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override { 2473 unsigned Sig = (0xeb << 0) | // jmp rel8 2474 (0x06 << 8) | // .+0x08 2475 ('v' << 16) | 2476 ('2' << 24); 2477 return llvm::ConstantInt::get(CGM.Int32Ty, Sig); 2478 } 2479 2480 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 2481 CodeGen::CodeGenModule &CGM) const override { 2482 if (GV->isDeclaration()) 2483 return; 2484 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) { 2485 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) { 2486 llvm::Function *Fn = cast<llvm::Function>(GV); 2487 Fn->addFnAttr("stackrealign"); 2488 } 2489 2490 addX86InterruptAttrs(FD, GV, CGM); 2491 } 2492 } 2493 2494 void checkFunctionCallABI(CodeGenModule &CGM, SourceLocation CallLoc, 2495 const FunctionDecl *Caller, 2496 const FunctionDecl *Callee, 2497 const CallArgList &Args) const override; 2498 }; 2499 2500 static void initFeatureMaps(const ASTContext &Ctx, 2501 llvm::StringMap<bool> &CallerMap, 2502 const FunctionDecl *Caller, 2503 llvm::StringMap<bool> &CalleeMap, 2504 const FunctionDecl *Callee) { 2505 if (CalleeMap.empty() && CallerMap.empty()) { 2506 // The caller is potentially nullptr in the case where the call isn't in a 2507 // function. In this case, the getFunctionFeatureMap ensures we just get 2508 // the TU level setting (since it cannot be modified by 'target'.. 2509 Ctx.getFunctionFeatureMap(CallerMap, Caller); 2510 Ctx.getFunctionFeatureMap(CalleeMap, Callee); 2511 } 2512 } 2513 2514 static bool checkAVXParamFeature(DiagnosticsEngine &Diag, 2515 SourceLocation CallLoc, 2516 const llvm::StringMap<bool> &CallerMap, 2517 const llvm::StringMap<bool> &CalleeMap, 2518 QualType Ty, StringRef Feature, 2519 bool IsArgument) { 2520 bool CallerHasFeat = CallerMap.lookup(Feature); 2521 bool CalleeHasFeat = CalleeMap.lookup(Feature); 2522 if (!CallerHasFeat && !CalleeHasFeat) 2523 return Diag.Report(CallLoc, diag::warn_avx_calling_convention) 2524 << IsArgument << Ty << Feature; 2525 2526 // Mixing calling conventions here is very clearly an error. 2527 if (!CallerHasFeat || !CalleeHasFeat) 2528 return Diag.Report(CallLoc, diag::err_avx_calling_convention) 2529 << IsArgument << Ty << Feature; 2530 2531 // Else, both caller and callee have the required feature, so there is no need 2532 // to diagnose. 2533 return false; 2534 } 2535 2536 static bool checkAVXParam(DiagnosticsEngine &Diag, ASTContext &Ctx, 2537 SourceLocation CallLoc, 2538 const llvm::StringMap<bool> &CallerMap, 2539 const llvm::StringMap<bool> &CalleeMap, QualType Ty, 2540 bool IsArgument) { 2541 uint64_t Size = Ctx.getTypeSize(Ty); 2542 if (Size > 256) 2543 return checkAVXParamFeature(Diag, CallLoc, CallerMap, CalleeMap, Ty, 2544 "avx512f", IsArgument); 2545 2546 if (Size > 128) 2547 return checkAVXParamFeature(Diag, CallLoc, CallerMap, CalleeMap, Ty, "avx", 2548 IsArgument); 2549 2550 return false; 2551 } 2552 2553 void X86_64TargetCodeGenInfo::checkFunctionCallABI( 2554 CodeGenModule &CGM, SourceLocation CallLoc, const FunctionDecl *Caller, 2555 const FunctionDecl *Callee, const CallArgList &Args) const { 2556 llvm::StringMap<bool> CallerMap; 2557 llvm::StringMap<bool> CalleeMap; 2558 unsigned ArgIndex = 0; 2559 2560 // We need to loop through the actual call arguments rather than the the 2561 // function's parameters, in case this variadic. 2562 for (const CallArg &Arg : Args) { 2563 // The "avx" feature changes how vectors >128 in size are passed. "avx512f" 2564 // additionally changes how vectors >256 in size are passed. Like GCC, we 2565 // warn when a function is called with an argument where this will change. 2566 // Unlike GCC, we also error when it is an obvious ABI mismatch, that is, 2567 // the caller and callee features are mismatched. 2568 // Unfortunately, we cannot do this diagnostic in SEMA, since the callee can 2569 // change its ABI with attribute-target after this call. 2570 if (Arg.getType()->isVectorType() && 2571 CGM.getContext().getTypeSize(Arg.getType()) > 128) { 2572 initFeatureMaps(CGM.getContext(), CallerMap, Caller, CalleeMap, Callee); 2573 QualType Ty = Arg.getType(); 2574 // The CallArg seems to have desugared the type already, so for clearer 2575 // diagnostics, replace it with the type in the FunctionDecl if possible. 2576 if (ArgIndex < Callee->getNumParams()) 2577 Ty = Callee->getParamDecl(ArgIndex)->getType(); 2578 2579 if (checkAVXParam(CGM.getDiags(), CGM.getContext(), CallLoc, CallerMap, 2580 CalleeMap, Ty, /*IsArgument*/ true)) 2581 return; 2582 } 2583 ++ArgIndex; 2584 } 2585 2586 // Check return always, as we don't have a good way of knowing in codegen 2587 // whether this value is used, tail-called, etc. 2588 if (Callee->getReturnType()->isVectorType() && 2589 CGM.getContext().getTypeSize(Callee->getReturnType()) > 128) { 2590 initFeatureMaps(CGM.getContext(), CallerMap, Caller, CalleeMap, Callee); 2591 checkAVXParam(CGM.getDiags(), CGM.getContext(), CallLoc, CallerMap, 2592 CalleeMap, Callee->getReturnType(), 2593 /*IsArgument*/ false); 2594 } 2595 } 2596 2597 static std::string qualifyWindowsLibrary(llvm::StringRef Lib) { 2598 // If the argument does not end in .lib, automatically add the suffix. 2599 // If the argument contains a space, enclose it in quotes. 2600 // This matches the behavior of MSVC. 2601 bool Quote = (Lib.find(' ') != StringRef::npos); 2602 std::string ArgStr = Quote ? "\"" : ""; 2603 ArgStr += Lib; 2604 if (!Lib.endswith_lower(".lib") && !Lib.endswith_lower(".a")) 2605 ArgStr += ".lib"; 2606 ArgStr += Quote ? "\"" : ""; 2607 return ArgStr; 2608 } 2609 2610 class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo { 2611 public: 2612 WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, 2613 bool DarwinVectorABI, bool RetSmallStructInRegABI, bool Win32StructABI, 2614 unsigned NumRegisterParameters) 2615 : X86_32TargetCodeGenInfo(CGT, DarwinVectorABI, RetSmallStructInRegABI, 2616 Win32StructABI, NumRegisterParameters, false) {} 2617 2618 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 2619 CodeGen::CodeGenModule &CGM) const override; 2620 2621 void getDependentLibraryOption(llvm::StringRef Lib, 2622 llvm::SmallString<24> &Opt) const override { 2623 Opt = "/DEFAULTLIB:"; 2624 Opt += qualifyWindowsLibrary(Lib); 2625 } 2626 2627 void getDetectMismatchOption(llvm::StringRef Name, 2628 llvm::StringRef Value, 2629 llvm::SmallString<32> &Opt) const override { 2630 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\""; 2631 } 2632 }; 2633 2634 static void addStackProbeTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 2635 CodeGen::CodeGenModule &CGM) { 2636 if (llvm::Function *Fn = dyn_cast_or_null<llvm::Function>(GV)) { 2637 2638 if (CGM.getCodeGenOpts().StackProbeSize != 4096) 2639 Fn->addFnAttr("stack-probe-size", 2640 llvm::utostr(CGM.getCodeGenOpts().StackProbeSize)); 2641 if (CGM.getCodeGenOpts().NoStackArgProbe) 2642 Fn->addFnAttr("no-stack-arg-probe"); 2643 } 2644 } 2645 2646 void WinX86_32TargetCodeGenInfo::setTargetAttributes( 2647 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const { 2648 X86_32TargetCodeGenInfo::setTargetAttributes(D, GV, CGM); 2649 if (GV->isDeclaration()) 2650 return; 2651 addStackProbeTargetAttributes(D, GV, CGM); 2652 } 2653 2654 class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo { 2655 public: 2656 WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, 2657 X86AVXABILevel AVXLevel) 2658 : TargetCodeGenInfo(std::make_unique<WinX86_64ABIInfo>(CGT, AVXLevel)) {} 2659 2660 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 2661 CodeGen::CodeGenModule &CGM) const override; 2662 2663 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override { 2664 return 7; 2665 } 2666 2667 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 2668 llvm::Value *Address) const override { 2669 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8); 2670 2671 // 0-15 are the 16 integer registers. 2672 // 16 is %rip. 2673 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16); 2674 return false; 2675 } 2676 2677 void getDependentLibraryOption(llvm::StringRef Lib, 2678 llvm::SmallString<24> &Opt) const override { 2679 Opt = "/DEFAULTLIB:"; 2680 Opt += qualifyWindowsLibrary(Lib); 2681 } 2682 2683 void getDetectMismatchOption(llvm::StringRef Name, 2684 llvm::StringRef Value, 2685 llvm::SmallString<32> &Opt) const override { 2686 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\""; 2687 } 2688 }; 2689 2690 void WinX86_64TargetCodeGenInfo::setTargetAttributes( 2691 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const { 2692 TargetCodeGenInfo::setTargetAttributes(D, GV, CGM); 2693 if (GV->isDeclaration()) 2694 return; 2695 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) { 2696 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) { 2697 llvm::Function *Fn = cast<llvm::Function>(GV); 2698 Fn->addFnAttr("stackrealign"); 2699 } 2700 2701 addX86InterruptAttrs(FD, GV, CGM); 2702 } 2703 2704 addStackProbeTargetAttributes(D, GV, CGM); 2705 } 2706 } 2707 2708 void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo, 2709 Class &Hi) const { 2710 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done: 2711 // 2712 // (a) If one of the classes is Memory, the whole argument is passed in 2713 // memory. 2714 // 2715 // (b) If X87UP is not preceded by X87, the whole argument is passed in 2716 // memory. 2717 // 2718 // (c) If the size of the aggregate exceeds two eightbytes and the first 2719 // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole 2720 // argument is passed in memory. NOTE: This is necessary to keep the 2721 // ABI working for processors that don't support the __m256 type. 2722 // 2723 // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE. 2724 // 2725 // Some of these are enforced by the merging logic. Others can arise 2726 // only with unions; for example: 2727 // union { _Complex double; unsigned; } 2728 // 2729 // Note that clauses (b) and (c) were added in 0.98. 2730 // 2731 if (Hi == Memory) 2732 Lo = Memory; 2733 if (Hi == X87Up && Lo != X87 && honorsRevision0_98()) 2734 Lo = Memory; 2735 if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp)) 2736 Lo = Memory; 2737 if (Hi == SSEUp && Lo != SSE) 2738 Hi = SSE; 2739 } 2740 2741 X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) { 2742 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is 2743 // classified recursively so that always two fields are 2744 // considered. The resulting class is calculated according to 2745 // the classes of the fields in the eightbyte: 2746 // 2747 // (a) If both classes are equal, this is the resulting class. 2748 // 2749 // (b) If one of the classes is NO_CLASS, the resulting class is 2750 // the other class. 2751 // 2752 // (c) If one of the classes is MEMORY, the result is the MEMORY 2753 // class. 2754 // 2755 // (d) If one of the classes is INTEGER, the result is the 2756 // INTEGER. 2757 // 2758 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class, 2759 // MEMORY is used as class. 2760 // 2761 // (f) Otherwise class SSE is used. 2762 2763 // Accum should never be memory (we should have returned) or 2764 // ComplexX87 (because this cannot be passed in a structure). 2765 assert((Accum != Memory && Accum != ComplexX87) && 2766 "Invalid accumulated classification during merge."); 2767 if (Accum == Field || Field == NoClass) 2768 return Accum; 2769 if (Field == Memory) 2770 return Memory; 2771 if (Accum == NoClass) 2772 return Field; 2773 if (Accum == Integer || Field == Integer) 2774 return Integer; 2775 if (Field == X87 || Field == X87Up || Field == ComplexX87 || 2776 Accum == X87 || Accum == X87Up) 2777 return Memory; 2778 return SSE; 2779 } 2780 2781 void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase, 2782 Class &Lo, Class &Hi, bool isNamedArg) const { 2783 // FIXME: This code can be simplified by introducing a simple value class for 2784 // Class pairs with appropriate constructor methods for the various 2785 // situations. 2786 2787 // FIXME: Some of the split computations are wrong; unaligned vectors 2788 // shouldn't be passed in registers for example, so there is no chance they 2789 // can straddle an eightbyte. Verify & simplify. 2790 2791 Lo = Hi = NoClass; 2792 2793 Class &Current = OffsetBase < 64 ? Lo : Hi; 2794 Current = Memory; 2795 2796 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) { 2797 BuiltinType::Kind k = BT->getKind(); 2798 2799 if (k == BuiltinType::Void) { 2800 Current = NoClass; 2801 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) { 2802 Lo = Integer; 2803 Hi = Integer; 2804 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) { 2805 Current = Integer; 2806 } else if (k == BuiltinType::Float || k == BuiltinType::Double) { 2807 Current = SSE; 2808 } else if (k == BuiltinType::LongDouble) { 2809 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat(); 2810 if (LDF == &llvm::APFloat::IEEEquad()) { 2811 Lo = SSE; 2812 Hi = SSEUp; 2813 } else if (LDF == &llvm::APFloat::x87DoubleExtended()) { 2814 Lo = X87; 2815 Hi = X87Up; 2816 } else if (LDF == &llvm::APFloat::IEEEdouble()) { 2817 Current = SSE; 2818 } else 2819 llvm_unreachable("unexpected long double representation!"); 2820 } 2821 // FIXME: _Decimal32 and _Decimal64 are SSE. 2822 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp). 2823 return; 2824 } 2825 2826 if (const EnumType *ET = Ty->getAs<EnumType>()) { 2827 // Classify the underlying integer type. 2828 classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg); 2829 return; 2830 } 2831 2832 if (Ty->hasPointerRepresentation()) { 2833 Current = Integer; 2834 return; 2835 } 2836 2837 if (Ty->isMemberPointerType()) { 2838 if (Ty->isMemberFunctionPointerType()) { 2839 if (Has64BitPointers) { 2840 // If Has64BitPointers, this is an {i64, i64}, so classify both 2841 // Lo and Hi now. 2842 Lo = Hi = Integer; 2843 } else { 2844 // Otherwise, with 32-bit pointers, this is an {i32, i32}. If that 2845 // straddles an eightbyte boundary, Hi should be classified as well. 2846 uint64_t EB_FuncPtr = (OffsetBase) / 64; 2847 uint64_t EB_ThisAdj = (OffsetBase + 64 - 1) / 64; 2848 if (EB_FuncPtr != EB_ThisAdj) { 2849 Lo = Hi = Integer; 2850 } else { 2851 Current = Integer; 2852 } 2853 } 2854 } else { 2855 Current = Integer; 2856 } 2857 return; 2858 } 2859 2860 if (const VectorType *VT = Ty->getAs<VectorType>()) { 2861 uint64_t Size = getContext().getTypeSize(VT); 2862 if (Size == 1 || Size == 8 || Size == 16 || Size == 32) { 2863 // gcc passes the following as integer: 2864 // 4 bytes - <4 x char>, <2 x short>, <1 x int>, <1 x float> 2865 // 2 bytes - <2 x char>, <1 x short> 2866 // 1 byte - <1 x char> 2867 Current = Integer; 2868 2869 // If this type crosses an eightbyte boundary, it should be 2870 // split. 2871 uint64_t EB_Lo = (OffsetBase) / 64; 2872 uint64_t EB_Hi = (OffsetBase + Size - 1) / 64; 2873 if (EB_Lo != EB_Hi) 2874 Hi = Lo; 2875 } else if (Size == 64) { 2876 QualType ElementType = VT->getElementType(); 2877 2878 // gcc passes <1 x double> in memory. :( 2879 if (ElementType->isSpecificBuiltinType(BuiltinType::Double)) 2880 return; 2881 2882 // gcc passes <1 x long long> as SSE but clang used to unconditionally 2883 // pass them as integer. For platforms where clang is the de facto 2884 // platform compiler, we must continue to use integer. 2885 if (!classifyIntegerMMXAsSSE() && 2886 (ElementType->isSpecificBuiltinType(BuiltinType::LongLong) || 2887 ElementType->isSpecificBuiltinType(BuiltinType::ULongLong) || 2888 ElementType->isSpecificBuiltinType(BuiltinType::Long) || 2889 ElementType->isSpecificBuiltinType(BuiltinType::ULong))) 2890 Current = Integer; 2891 else 2892 Current = SSE; 2893 2894 // If this type crosses an eightbyte boundary, it should be 2895 // split. 2896 if (OffsetBase && OffsetBase != 64) 2897 Hi = Lo; 2898 } else if (Size == 128 || 2899 (isNamedArg && Size <= getNativeVectorSizeForAVXABI(AVXLevel))) { 2900 QualType ElementType = VT->getElementType(); 2901 2902 // gcc passes 256 and 512 bit <X x __int128> vectors in memory. :( 2903 if (passInt128VectorsInMem() && Size != 128 && 2904 (ElementType->isSpecificBuiltinType(BuiltinType::Int128) || 2905 ElementType->isSpecificBuiltinType(BuiltinType::UInt128))) 2906 return; 2907 2908 // Arguments of 256-bits are split into four eightbyte chunks. The 2909 // least significant one belongs to class SSE and all the others to class 2910 // SSEUP. The original Lo and Hi design considers that types can't be 2911 // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense. 2912 // This design isn't correct for 256-bits, but since there're no cases 2913 // where the upper parts would need to be inspected, avoid adding 2914 // complexity and just consider Hi to match the 64-256 part. 2915 // 2916 // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in 2917 // registers if they are "named", i.e. not part of the "..." of a 2918 // variadic function. 2919 // 2920 // Similarly, per 3.2.3. of the AVX512 draft, 512-bits ("named") args are 2921 // split into eight eightbyte chunks, one SSE and seven SSEUP. 2922 Lo = SSE; 2923 Hi = SSEUp; 2924 } 2925 return; 2926 } 2927 2928 if (const ComplexType *CT = Ty->getAs<ComplexType>()) { 2929 QualType ET = getContext().getCanonicalType(CT->getElementType()); 2930 2931 uint64_t Size = getContext().getTypeSize(Ty); 2932 if (ET->isIntegralOrEnumerationType()) { 2933 if (Size <= 64) 2934 Current = Integer; 2935 else if (Size <= 128) 2936 Lo = Hi = Integer; 2937 } else if (ET == getContext().FloatTy) { 2938 Current = SSE; 2939 } else if (ET == getContext().DoubleTy) { 2940 Lo = Hi = SSE; 2941 } else if (ET == getContext().LongDoubleTy) { 2942 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat(); 2943 if (LDF == &llvm::APFloat::IEEEquad()) 2944 Current = Memory; 2945 else if (LDF == &llvm::APFloat::x87DoubleExtended()) 2946 Current = ComplexX87; 2947 else if (LDF == &llvm::APFloat::IEEEdouble()) 2948 Lo = Hi = SSE; 2949 else 2950 llvm_unreachable("unexpected long double representation!"); 2951 } 2952 2953 // If this complex type crosses an eightbyte boundary then it 2954 // should be split. 2955 uint64_t EB_Real = (OffsetBase) / 64; 2956 uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64; 2957 if (Hi == NoClass && EB_Real != EB_Imag) 2958 Hi = Lo; 2959 2960 return; 2961 } 2962 2963 if (const auto *EITy = Ty->getAs<ExtIntType>()) { 2964 if (EITy->getNumBits() <= 64) 2965 Current = Integer; 2966 else if (EITy->getNumBits() <= 128) 2967 Lo = Hi = Integer; 2968 // Larger values need to get passed in memory. 2969 return; 2970 } 2971 2972 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) { 2973 // Arrays are treated like structures. 2974 2975 uint64_t Size = getContext().getTypeSize(Ty); 2976 2977 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger 2978 // than eight eightbytes, ..., it has class MEMORY. 2979 if (Size > 512) 2980 return; 2981 2982 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned 2983 // fields, it has class MEMORY. 2984 // 2985 // Only need to check alignment of array base. 2986 if (OffsetBase % getContext().getTypeAlign(AT->getElementType())) 2987 return; 2988 2989 // Otherwise implement simplified merge. We could be smarter about 2990 // this, but it isn't worth it and would be harder to verify. 2991 Current = NoClass; 2992 uint64_t EltSize = getContext().getTypeSize(AT->getElementType()); 2993 uint64_t ArraySize = AT->getSize().getZExtValue(); 2994 2995 // The only case a 256-bit wide vector could be used is when the array 2996 // contains a single 256-bit element. Since Lo and Hi logic isn't extended 2997 // to work for sizes wider than 128, early check and fallback to memory. 2998 // 2999 if (Size > 128 && 3000 (Size != EltSize || Size > getNativeVectorSizeForAVXABI(AVXLevel))) 3001 return; 3002 3003 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) { 3004 Class FieldLo, FieldHi; 3005 classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg); 3006 Lo = merge(Lo, FieldLo); 3007 Hi = merge(Hi, FieldHi); 3008 if (Lo == Memory || Hi == Memory) 3009 break; 3010 } 3011 3012 postMerge(Size, Lo, Hi); 3013 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification."); 3014 return; 3015 } 3016 3017 if (const RecordType *RT = Ty->getAs<RecordType>()) { 3018 uint64_t Size = getContext().getTypeSize(Ty); 3019 3020 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger 3021 // than eight eightbytes, ..., it has class MEMORY. 3022 if (Size > 512) 3023 return; 3024 3025 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial 3026 // copy constructor or a non-trivial destructor, it is passed by invisible 3027 // reference. 3028 if (getRecordArgABI(RT, getCXXABI())) 3029 return; 3030 3031 const RecordDecl *RD = RT->getDecl(); 3032 3033 // Assume variable sized types are passed in memory. 3034 if (RD->hasFlexibleArrayMember()) 3035 return; 3036 3037 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD); 3038 3039 // Reset Lo class, this will be recomputed. 3040 Current = NoClass; 3041 3042 // If this is a C++ record, classify the bases first. 3043 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 3044 for (const auto &I : CXXRD->bases()) { 3045 assert(!I.isVirtual() && !I.getType()->isDependentType() && 3046 "Unexpected base class!"); 3047 const auto *Base = 3048 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl()); 3049 3050 // Classify this field. 3051 // 3052 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a 3053 // single eightbyte, each is classified separately. Each eightbyte gets 3054 // initialized to class NO_CLASS. 3055 Class FieldLo, FieldHi; 3056 uint64_t Offset = 3057 OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base)); 3058 classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg); 3059 Lo = merge(Lo, FieldLo); 3060 Hi = merge(Hi, FieldHi); 3061 if (Lo == Memory || Hi == Memory) { 3062 postMerge(Size, Lo, Hi); 3063 return; 3064 } 3065 } 3066 } 3067 3068 // Classify the fields one at a time, merging the results. 3069 unsigned idx = 0; 3070 bool UseClang11Compat = getContext().getLangOpts().getClangABICompat() <= 3071 LangOptions::ClangABI::Ver11 || 3072 getContext().getTargetInfo().getTriple().isPS4(); 3073 bool IsUnion = RT->isUnionType() && !UseClang11Compat; 3074 3075 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 3076 i != e; ++i, ++idx) { 3077 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx); 3078 bool BitField = i->isBitField(); 3079 3080 // Ignore padding bit-fields. 3081 if (BitField && i->isUnnamedBitfield()) 3082 continue; 3083 3084 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than 3085 // eight eightbytes, or it contains unaligned fields, it has class MEMORY. 3086 // 3087 // The only case a 256-bit or a 512-bit wide vector could be used is when 3088 // the struct contains a single 256-bit or 512-bit element. Early check 3089 // and fallback to memory. 3090 // 3091 // FIXME: Extended the Lo and Hi logic properly to work for size wider 3092 // than 128. 3093 if (Size > 128 && 3094 ((!IsUnion && Size != getContext().getTypeSize(i->getType())) || 3095 Size > getNativeVectorSizeForAVXABI(AVXLevel))) { 3096 Lo = Memory; 3097 postMerge(Size, Lo, Hi); 3098 return; 3099 } 3100 // Note, skip this test for bit-fields, see below. 3101 if (!BitField && Offset % getContext().getTypeAlign(i->getType())) { 3102 Lo = Memory; 3103 postMerge(Size, Lo, Hi); 3104 return; 3105 } 3106 3107 // Classify this field. 3108 // 3109 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate 3110 // exceeds a single eightbyte, each is classified 3111 // separately. Each eightbyte gets initialized to class 3112 // NO_CLASS. 3113 Class FieldLo, FieldHi; 3114 3115 // Bit-fields require special handling, they do not force the 3116 // structure to be passed in memory even if unaligned, and 3117 // therefore they can straddle an eightbyte. 3118 if (BitField) { 3119 assert(!i->isUnnamedBitfield()); 3120 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx); 3121 uint64_t Size = i->getBitWidthValue(getContext()); 3122 3123 uint64_t EB_Lo = Offset / 64; 3124 uint64_t EB_Hi = (Offset + Size - 1) / 64; 3125 3126 if (EB_Lo) { 3127 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes."); 3128 FieldLo = NoClass; 3129 FieldHi = Integer; 3130 } else { 3131 FieldLo = Integer; 3132 FieldHi = EB_Hi ? Integer : NoClass; 3133 } 3134 } else 3135 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg); 3136 Lo = merge(Lo, FieldLo); 3137 Hi = merge(Hi, FieldHi); 3138 if (Lo == Memory || Hi == Memory) 3139 break; 3140 } 3141 3142 postMerge(Size, Lo, Hi); 3143 } 3144 } 3145 3146 ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const { 3147 // If this is a scalar LLVM value then assume LLVM will pass it in the right 3148 // place naturally. 3149 if (!isAggregateTypeForABI(Ty)) { 3150 // Treat an enum type as its underlying type. 3151 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 3152 Ty = EnumTy->getDecl()->getIntegerType(); 3153 3154 if (Ty->isExtIntType()) 3155 return getNaturalAlignIndirect(Ty); 3156 3157 return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty) 3158 : ABIArgInfo::getDirect()); 3159 } 3160 3161 return getNaturalAlignIndirect(Ty); 3162 } 3163 3164 bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const { 3165 if (const VectorType *VecTy = Ty->getAs<VectorType>()) { 3166 uint64_t Size = getContext().getTypeSize(VecTy); 3167 unsigned LargestVector = getNativeVectorSizeForAVXABI(AVXLevel); 3168 if (Size <= 64 || Size > LargestVector) 3169 return true; 3170 QualType EltTy = VecTy->getElementType(); 3171 if (passInt128VectorsInMem() && 3172 (EltTy->isSpecificBuiltinType(BuiltinType::Int128) || 3173 EltTy->isSpecificBuiltinType(BuiltinType::UInt128))) 3174 return true; 3175 } 3176 3177 return false; 3178 } 3179 3180 ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty, 3181 unsigned freeIntRegs) const { 3182 // If this is a scalar LLVM value then assume LLVM will pass it in the right 3183 // place naturally. 3184 // 3185 // This assumption is optimistic, as there could be free registers available 3186 // when we need to pass this argument in memory, and LLVM could try to pass 3187 // the argument in the free register. This does not seem to happen currently, 3188 // but this code would be much safer if we could mark the argument with 3189 // 'onstack'. See PR12193. 3190 if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty) && 3191 !Ty->isExtIntType()) { 3192 // Treat an enum type as its underlying type. 3193 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 3194 Ty = EnumTy->getDecl()->getIntegerType(); 3195 3196 return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty) 3197 : ABIArgInfo::getDirect()); 3198 } 3199 3200 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 3201 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 3202 3203 // Compute the byval alignment. We specify the alignment of the byval in all 3204 // cases so that the mid-level optimizer knows the alignment of the byval. 3205 unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U); 3206 3207 // Attempt to avoid passing indirect results using byval when possible. This 3208 // is important for good codegen. 3209 // 3210 // We do this by coercing the value into a scalar type which the backend can 3211 // handle naturally (i.e., without using byval). 3212 // 3213 // For simplicity, we currently only do this when we have exhausted all of the 3214 // free integer registers. Doing this when there are free integer registers 3215 // would require more care, as we would have to ensure that the coerced value 3216 // did not claim the unused register. That would require either reording the 3217 // arguments to the function (so that any subsequent inreg values came first), 3218 // or only doing this optimization when there were no following arguments that 3219 // might be inreg. 3220 // 3221 // We currently expect it to be rare (particularly in well written code) for 3222 // arguments to be passed on the stack when there are still free integer 3223 // registers available (this would typically imply large structs being passed 3224 // by value), so this seems like a fair tradeoff for now. 3225 // 3226 // We can revisit this if the backend grows support for 'onstack' parameter 3227 // attributes. See PR12193. 3228 if (freeIntRegs == 0) { 3229 uint64_t Size = getContext().getTypeSize(Ty); 3230 3231 // If this type fits in an eightbyte, coerce it into the matching integral 3232 // type, which will end up on the stack (with alignment 8). 3233 if (Align == 8 && Size <= 64) 3234 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 3235 Size)); 3236 } 3237 3238 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(Align)); 3239 } 3240 3241 /// The ABI specifies that a value should be passed in a full vector XMM/YMM 3242 /// register. Pick an LLVM IR type that will be passed as a vector register. 3243 llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const { 3244 // Wrapper structs/arrays that only contain vectors are passed just like 3245 // vectors; strip them off if present. 3246 if (const Type *InnerTy = isSingleElementStruct(Ty, getContext())) 3247 Ty = QualType(InnerTy, 0); 3248 3249 llvm::Type *IRType = CGT.ConvertType(Ty); 3250 if (isa<llvm::VectorType>(IRType)) { 3251 // Don't pass vXi128 vectors in their native type, the backend can't 3252 // legalize them. 3253 if (passInt128VectorsInMem() && 3254 cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy(128)) { 3255 // Use a vXi64 vector. 3256 uint64_t Size = getContext().getTypeSize(Ty); 3257 return llvm::FixedVectorType::get(llvm::Type::getInt64Ty(getVMContext()), 3258 Size / 64); 3259 } 3260 3261 return IRType; 3262 } 3263 3264 if (IRType->getTypeID() == llvm::Type::FP128TyID) 3265 return IRType; 3266 3267 // We couldn't find the preferred IR vector type for 'Ty'. 3268 uint64_t Size = getContext().getTypeSize(Ty); 3269 assert((Size == 128 || Size == 256 || Size == 512) && "Invalid type found!"); 3270 3271 3272 // Return a LLVM IR vector type based on the size of 'Ty'. 3273 return llvm::FixedVectorType::get(llvm::Type::getDoubleTy(getVMContext()), 3274 Size / 64); 3275 } 3276 3277 /// BitsContainNoUserData - Return true if the specified [start,end) bit range 3278 /// is known to either be off the end of the specified type or being in 3279 /// alignment padding. The user type specified is known to be at most 128 bits 3280 /// in size, and have passed through X86_64ABIInfo::classify with a successful 3281 /// classification that put one of the two halves in the INTEGER class. 3282 /// 3283 /// It is conservatively correct to return false. 3284 static bool BitsContainNoUserData(QualType Ty, unsigned StartBit, 3285 unsigned EndBit, ASTContext &Context) { 3286 // If the bytes being queried are off the end of the type, there is no user 3287 // data hiding here. This handles analysis of builtins, vectors and other 3288 // types that don't contain interesting padding. 3289 unsigned TySize = (unsigned)Context.getTypeSize(Ty); 3290 if (TySize <= StartBit) 3291 return true; 3292 3293 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) { 3294 unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType()); 3295 unsigned NumElts = (unsigned)AT->getSize().getZExtValue(); 3296 3297 // Check each element to see if the element overlaps with the queried range. 3298 for (unsigned i = 0; i != NumElts; ++i) { 3299 // If the element is after the span we care about, then we're done.. 3300 unsigned EltOffset = i*EltSize; 3301 if (EltOffset >= EndBit) break; 3302 3303 unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0; 3304 if (!BitsContainNoUserData(AT->getElementType(), EltStart, 3305 EndBit-EltOffset, Context)) 3306 return false; 3307 } 3308 // If it overlaps no elements, then it is safe to process as padding. 3309 return true; 3310 } 3311 3312 if (const RecordType *RT = Ty->getAs<RecordType>()) { 3313 const RecordDecl *RD = RT->getDecl(); 3314 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); 3315 3316 // If this is a C++ record, check the bases first. 3317 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 3318 for (const auto &I : CXXRD->bases()) { 3319 assert(!I.isVirtual() && !I.getType()->isDependentType() && 3320 "Unexpected base class!"); 3321 const auto *Base = 3322 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl()); 3323 3324 // If the base is after the span we care about, ignore it. 3325 unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base)); 3326 if (BaseOffset >= EndBit) continue; 3327 3328 unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0; 3329 if (!BitsContainNoUserData(I.getType(), BaseStart, 3330 EndBit-BaseOffset, Context)) 3331 return false; 3332 } 3333 } 3334 3335 // Verify that no field has data that overlaps the region of interest. Yes 3336 // this could be sped up a lot by being smarter about queried fields, 3337 // however we're only looking at structs up to 16 bytes, so we don't care 3338 // much. 3339 unsigned idx = 0; 3340 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 3341 i != e; ++i, ++idx) { 3342 unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx); 3343 3344 // If we found a field after the region we care about, then we're done. 3345 if (FieldOffset >= EndBit) break; 3346 3347 unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0; 3348 if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset, 3349 Context)) 3350 return false; 3351 } 3352 3353 // If nothing in this record overlapped the area of interest, then we're 3354 // clean. 3355 return true; 3356 } 3357 3358 return false; 3359 } 3360 3361 /// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a 3362 /// float member at the specified offset. For example, {int,{float}} has a 3363 /// float at offset 4. It is conservatively correct for this routine to return 3364 /// false. 3365 static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset, 3366 const llvm::DataLayout &TD) { 3367 // Base case if we find a float. 3368 if (IROffset == 0 && IRType->isFloatTy()) 3369 return true; 3370 3371 // If this is a struct, recurse into the field at the specified offset. 3372 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) { 3373 const llvm::StructLayout *SL = TD.getStructLayout(STy); 3374 unsigned Elt = SL->getElementContainingOffset(IROffset); 3375 IROffset -= SL->getElementOffset(Elt); 3376 return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD); 3377 } 3378 3379 // If this is an array, recurse into the field at the specified offset. 3380 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) { 3381 llvm::Type *EltTy = ATy->getElementType(); 3382 unsigned EltSize = TD.getTypeAllocSize(EltTy); 3383 IROffset -= IROffset/EltSize*EltSize; 3384 return ContainsFloatAtOffset(EltTy, IROffset, TD); 3385 } 3386 3387 return false; 3388 } 3389 3390 3391 /// GetSSETypeAtOffset - Return a type that will be passed by the backend in the 3392 /// low 8 bytes of an XMM register, corresponding to the SSE class. 3393 llvm::Type *X86_64ABIInfo:: 3394 GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset, 3395 QualType SourceTy, unsigned SourceOffset) const { 3396 // The only three choices we have are either double, <2 x float>, or float. We 3397 // pass as float if the last 4 bytes is just padding. This happens for 3398 // structs that contain 3 floats. 3399 if (BitsContainNoUserData(SourceTy, SourceOffset*8+32, 3400 SourceOffset*8+64, getContext())) 3401 return llvm::Type::getFloatTy(getVMContext()); 3402 3403 // We want to pass as <2 x float> if the LLVM IR type contains a float at 3404 // offset+0 and offset+4. Walk the LLVM IR type to find out if this is the 3405 // case. 3406 if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) && 3407 ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout())) 3408 return llvm::FixedVectorType::get(llvm::Type::getFloatTy(getVMContext()), 3409 2); 3410 3411 return llvm::Type::getDoubleTy(getVMContext()); 3412 } 3413 3414 3415 /// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in 3416 /// an 8-byte GPR. This means that we either have a scalar or we are talking 3417 /// about the high or low part of an up-to-16-byte struct. This routine picks 3418 /// the best LLVM IR type to represent this, which may be i64 or may be anything 3419 /// else that the backend will pass in a GPR that works better (e.g. i8, %foo*, 3420 /// etc). 3421 /// 3422 /// PrefType is an LLVM IR type that corresponds to (part of) the IR type for 3423 /// the source type. IROffset is an offset in bytes into the LLVM IR type that 3424 /// the 8-byte value references. PrefType may be null. 3425 /// 3426 /// SourceTy is the source-level type for the entire argument. SourceOffset is 3427 /// an offset into this that we're processing (which is always either 0 or 8). 3428 /// 3429 llvm::Type *X86_64ABIInfo:: 3430 GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset, 3431 QualType SourceTy, unsigned SourceOffset) const { 3432 // If we're dealing with an un-offset LLVM IR type, then it means that we're 3433 // returning an 8-byte unit starting with it. See if we can safely use it. 3434 if (IROffset == 0) { 3435 // Pointers and int64's always fill the 8-byte unit. 3436 if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) || 3437 IRType->isIntegerTy(64)) 3438 return IRType; 3439 3440 // If we have a 1/2/4-byte integer, we can use it only if the rest of the 3441 // goodness in the source type is just tail padding. This is allowed to 3442 // kick in for struct {double,int} on the int, but not on 3443 // struct{double,int,int} because we wouldn't return the second int. We 3444 // have to do this analysis on the source type because we can't depend on 3445 // unions being lowered a specific way etc. 3446 if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) || 3447 IRType->isIntegerTy(32) || 3448 (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) { 3449 unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 : 3450 cast<llvm::IntegerType>(IRType)->getBitWidth(); 3451 3452 if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth, 3453 SourceOffset*8+64, getContext())) 3454 return IRType; 3455 } 3456 } 3457 3458 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) { 3459 // If this is a struct, recurse into the field at the specified offset. 3460 const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy); 3461 if (IROffset < SL->getSizeInBytes()) { 3462 unsigned FieldIdx = SL->getElementContainingOffset(IROffset); 3463 IROffset -= SL->getElementOffset(FieldIdx); 3464 3465 return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset, 3466 SourceTy, SourceOffset); 3467 } 3468 } 3469 3470 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) { 3471 llvm::Type *EltTy = ATy->getElementType(); 3472 unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy); 3473 unsigned EltOffset = IROffset/EltSize*EltSize; 3474 return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy, 3475 SourceOffset); 3476 } 3477 3478 // Okay, we don't have any better idea of what to pass, so we pass this in an 3479 // integer register that isn't too big to fit the rest of the struct. 3480 unsigned TySizeInBytes = 3481 (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity(); 3482 3483 assert(TySizeInBytes != SourceOffset && "Empty field?"); 3484 3485 // It is always safe to classify this as an integer type up to i64 that 3486 // isn't larger than the structure. 3487 return llvm::IntegerType::get(getVMContext(), 3488 std::min(TySizeInBytes-SourceOffset, 8U)*8); 3489 } 3490 3491 3492 /// GetX86_64ByValArgumentPair - Given a high and low type that can ideally 3493 /// be used as elements of a two register pair to pass or return, return a 3494 /// first class aggregate to represent them. For example, if the low part of 3495 /// a by-value argument should be passed as i32* and the high part as float, 3496 /// return {i32*, float}. 3497 static llvm::Type * 3498 GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi, 3499 const llvm::DataLayout &TD) { 3500 // In order to correctly satisfy the ABI, we need to the high part to start 3501 // at offset 8. If the high and low parts we inferred are both 4-byte types 3502 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have 3503 // the second element at offset 8. Check for this: 3504 unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo); 3505 unsigned HiAlign = TD.getABITypeAlignment(Hi); 3506 unsigned HiStart = llvm::alignTo(LoSize, HiAlign); 3507 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!"); 3508 3509 // To handle this, we have to increase the size of the low part so that the 3510 // second element will start at an 8 byte offset. We can't increase the size 3511 // of the second element because it might make us access off the end of the 3512 // struct. 3513 if (HiStart != 8) { 3514 // There are usually two sorts of types the ABI generation code can produce 3515 // for the low part of a pair that aren't 8 bytes in size: float or 3516 // i8/i16/i32. This can also include pointers when they are 32-bit (X32 and 3517 // NaCl). 3518 // Promote these to a larger type. 3519 if (Lo->isFloatTy()) 3520 Lo = llvm::Type::getDoubleTy(Lo->getContext()); 3521 else { 3522 assert((Lo->isIntegerTy() || Lo->isPointerTy()) 3523 && "Invalid/unknown lo type"); 3524 Lo = llvm::Type::getInt64Ty(Lo->getContext()); 3525 } 3526 } 3527 3528 llvm::StructType *Result = llvm::StructType::get(Lo, Hi); 3529 3530 // Verify that the second element is at an 8-byte offset. 3531 assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 && 3532 "Invalid x86-64 argument pair!"); 3533 return Result; 3534 } 3535 3536 ABIArgInfo X86_64ABIInfo:: 3537 classifyReturnType(QualType RetTy) const { 3538 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the 3539 // classification algorithm. 3540 X86_64ABIInfo::Class Lo, Hi; 3541 classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true); 3542 3543 // Check some invariants. 3544 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification."); 3545 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification."); 3546 3547 llvm::Type *ResType = nullptr; 3548 switch (Lo) { 3549 case NoClass: 3550 if (Hi == NoClass) 3551 return ABIArgInfo::getIgnore(); 3552 // If the low part is just padding, it takes no register, leave ResType 3553 // null. 3554 assert((Hi == SSE || Hi == Integer || Hi == X87Up) && 3555 "Unknown missing lo part"); 3556 break; 3557 3558 case SSEUp: 3559 case X87Up: 3560 llvm_unreachable("Invalid classification for lo word."); 3561 3562 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via 3563 // hidden argument. 3564 case Memory: 3565 return getIndirectReturnResult(RetTy); 3566 3567 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next 3568 // available register of the sequence %rax, %rdx is used. 3569 case Integer: 3570 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0); 3571 3572 // If we have a sign or zero extended integer, make sure to return Extend 3573 // so that the parameter gets the right LLVM IR attributes. 3574 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) { 3575 // Treat an enum type as its underlying type. 3576 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 3577 RetTy = EnumTy->getDecl()->getIntegerType(); 3578 3579 if (RetTy->isIntegralOrEnumerationType() && 3580 isPromotableIntegerTypeForABI(RetTy)) 3581 return ABIArgInfo::getExtend(RetTy); 3582 } 3583 break; 3584 3585 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next 3586 // available SSE register of the sequence %xmm0, %xmm1 is used. 3587 case SSE: 3588 ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0); 3589 break; 3590 3591 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is 3592 // returned on the X87 stack in %st0 as 80-bit x87 number. 3593 case X87: 3594 ResType = llvm::Type::getX86_FP80Ty(getVMContext()); 3595 break; 3596 3597 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real 3598 // part of the value is returned in %st0 and the imaginary part in 3599 // %st1. 3600 case ComplexX87: 3601 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification."); 3602 ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()), 3603 llvm::Type::getX86_FP80Ty(getVMContext())); 3604 break; 3605 } 3606 3607 llvm::Type *HighPart = nullptr; 3608 switch (Hi) { 3609 // Memory was handled previously and X87 should 3610 // never occur as a hi class. 3611 case Memory: 3612 case X87: 3613 llvm_unreachable("Invalid classification for hi word."); 3614 3615 case ComplexX87: // Previously handled. 3616 case NoClass: 3617 break; 3618 3619 case Integer: 3620 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8); 3621 if (Lo == NoClass) // Return HighPart at offset 8 in memory. 3622 return ABIArgInfo::getDirect(HighPart, 8); 3623 break; 3624 case SSE: 3625 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8); 3626 if (Lo == NoClass) // Return HighPart at offset 8 in memory. 3627 return ABIArgInfo::getDirect(HighPart, 8); 3628 break; 3629 3630 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte 3631 // is passed in the next available eightbyte chunk if the last used 3632 // vector register. 3633 // 3634 // SSEUP should always be preceded by SSE, just widen. 3635 case SSEUp: 3636 assert(Lo == SSE && "Unexpected SSEUp classification."); 3637 ResType = GetByteVectorType(RetTy); 3638 break; 3639 3640 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is 3641 // returned together with the previous X87 value in %st0. 3642 case X87Up: 3643 // If X87Up is preceded by X87, we don't need to do 3644 // anything. However, in some cases with unions it may not be 3645 // preceded by X87. In such situations we follow gcc and pass the 3646 // extra bits in an SSE reg. 3647 if (Lo != X87) { 3648 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8); 3649 if (Lo == NoClass) // Return HighPart at offset 8 in memory. 3650 return ABIArgInfo::getDirect(HighPart, 8); 3651 } 3652 break; 3653 } 3654 3655 // If a high part was specified, merge it together with the low part. It is 3656 // known to pass in the high eightbyte of the result. We do this by forming a 3657 // first class struct aggregate with the high and low part: {low, high} 3658 if (HighPart) 3659 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout()); 3660 3661 return ABIArgInfo::getDirect(ResType); 3662 } 3663 3664 ABIArgInfo X86_64ABIInfo::classifyArgumentType( 3665 QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE, 3666 bool isNamedArg) 3667 const 3668 { 3669 Ty = useFirstFieldIfTransparentUnion(Ty); 3670 3671 X86_64ABIInfo::Class Lo, Hi; 3672 classify(Ty, 0, Lo, Hi, isNamedArg); 3673 3674 // Check some invariants. 3675 // FIXME: Enforce these by construction. 3676 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification."); 3677 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification."); 3678 3679 neededInt = 0; 3680 neededSSE = 0; 3681 llvm::Type *ResType = nullptr; 3682 switch (Lo) { 3683 case NoClass: 3684 if (Hi == NoClass) 3685 return ABIArgInfo::getIgnore(); 3686 // If the low part is just padding, it takes no register, leave ResType 3687 // null. 3688 assert((Hi == SSE || Hi == Integer || Hi == X87Up) && 3689 "Unknown missing lo part"); 3690 break; 3691 3692 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument 3693 // on the stack. 3694 case Memory: 3695 3696 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or 3697 // COMPLEX_X87, it is passed in memory. 3698 case X87: 3699 case ComplexX87: 3700 if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect) 3701 ++neededInt; 3702 return getIndirectResult(Ty, freeIntRegs); 3703 3704 case SSEUp: 3705 case X87Up: 3706 llvm_unreachable("Invalid classification for lo word."); 3707 3708 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next 3709 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8 3710 // and %r9 is used. 3711 case Integer: 3712 ++neededInt; 3713 3714 // Pick an 8-byte type based on the preferred type. 3715 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0); 3716 3717 // If we have a sign or zero extended integer, make sure to return Extend 3718 // so that the parameter gets the right LLVM IR attributes. 3719 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) { 3720 // Treat an enum type as its underlying type. 3721 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 3722 Ty = EnumTy->getDecl()->getIntegerType(); 3723 3724 if (Ty->isIntegralOrEnumerationType() && 3725 isPromotableIntegerTypeForABI(Ty)) 3726 return ABIArgInfo::getExtend(Ty); 3727 } 3728 3729 break; 3730 3731 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next 3732 // available SSE register is used, the registers are taken in the 3733 // order from %xmm0 to %xmm7. 3734 case SSE: { 3735 llvm::Type *IRType = CGT.ConvertType(Ty); 3736 ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0); 3737 ++neededSSE; 3738 break; 3739 } 3740 } 3741 3742 llvm::Type *HighPart = nullptr; 3743 switch (Hi) { 3744 // Memory was handled previously, ComplexX87 and X87 should 3745 // never occur as hi classes, and X87Up must be preceded by X87, 3746 // which is passed in memory. 3747 case Memory: 3748 case X87: 3749 case ComplexX87: 3750 llvm_unreachable("Invalid classification for hi word."); 3751 3752 case NoClass: break; 3753 3754 case Integer: 3755 ++neededInt; 3756 // Pick an 8-byte type based on the preferred type. 3757 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8); 3758 3759 if (Lo == NoClass) // Pass HighPart at offset 8 in memory. 3760 return ABIArgInfo::getDirect(HighPart, 8); 3761 break; 3762 3763 // X87Up generally doesn't occur here (long double is passed in 3764 // memory), except in situations involving unions. 3765 case X87Up: 3766 case SSE: 3767 HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8); 3768 3769 if (Lo == NoClass) // Pass HighPart at offset 8 in memory. 3770 return ABIArgInfo::getDirect(HighPart, 8); 3771 3772 ++neededSSE; 3773 break; 3774 3775 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the 3776 // eightbyte is passed in the upper half of the last used SSE 3777 // register. This only happens when 128-bit vectors are passed. 3778 case SSEUp: 3779 assert(Lo == SSE && "Unexpected SSEUp classification"); 3780 ResType = GetByteVectorType(Ty); 3781 break; 3782 } 3783 3784 // If a high part was specified, merge it together with the low part. It is 3785 // known to pass in the high eightbyte of the result. We do this by forming a 3786 // first class struct aggregate with the high and low part: {low, high} 3787 if (HighPart) 3788 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout()); 3789 3790 return ABIArgInfo::getDirect(ResType); 3791 } 3792 3793 ABIArgInfo 3794 X86_64ABIInfo::classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt, 3795 unsigned &NeededSSE) const { 3796 auto RT = Ty->getAs<RecordType>(); 3797 assert(RT && "classifyRegCallStructType only valid with struct types"); 3798 3799 if (RT->getDecl()->hasFlexibleArrayMember()) 3800 return getIndirectReturnResult(Ty); 3801 3802 // Sum up bases 3803 if (auto CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl())) { 3804 if (CXXRD->isDynamicClass()) { 3805 NeededInt = NeededSSE = 0; 3806 return getIndirectReturnResult(Ty); 3807 } 3808 3809 for (const auto &I : CXXRD->bases()) 3810 if (classifyRegCallStructTypeImpl(I.getType(), NeededInt, NeededSSE) 3811 .isIndirect()) { 3812 NeededInt = NeededSSE = 0; 3813 return getIndirectReturnResult(Ty); 3814 } 3815 } 3816 3817 // Sum up members 3818 for (const auto *FD : RT->getDecl()->fields()) { 3819 if (FD->getType()->isRecordType() && !FD->getType()->isUnionType()) { 3820 if (classifyRegCallStructTypeImpl(FD->getType(), NeededInt, NeededSSE) 3821 .isIndirect()) { 3822 NeededInt = NeededSSE = 0; 3823 return getIndirectReturnResult(Ty); 3824 } 3825 } else { 3826 unsigned LocalNeededInt, LocalNeededSSE; 3827 if (classifyArgumentType(FD->getType(), UINT_MAX, LocalNeededInt, 3828 LocalNeededSSE, true) 3829 .isIndirect()) { 3830 NeededInt = NeededSSE = 0; 3831 return getIndirectReturnResult(Ty); 3832 } 3833 NeededInt += LocalNeededInt; 3834 NeededSSE += LocalNeededSSE; 3835 } 3836 } 3837 3838 return ABIArgInfo::getDirect(); 3839 } 3840 3841 ABIArgInfo X86_64ABIInfo::classifyRegCallStructType(QualType Ty, 3842 unsigned &NeededInt, 3843 unsigned &NeededSSE) const { 3844 3845 NeededInt = 0; 3846 NeededSSE = 0; 3847 3848 return classifyRegCallStructTypeImpl(Ty, NeededInt, NeededSSE); 3849 } 3850 3851 void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const { 3852 3853 const unsigned CallingConv = FI.getCallingConvention(); 3854 // It is possible to force Win64 calling convention on any x86_64 target by 3855 // using __attribute__((ms_abi)). In such case to correctly emit Win64 3856 // compatible code delegate this call to WinX86_64ABIInfo::computeInfo. 3857 if (CallingConv == llvm::CallingConv::Win64) { 3858 WinX86_64ABIInfo Win64ABIInfo(CGT, AVXLevel); 3859 Win64ABIInfo.computeInfo(FI); 3860 return; 3861 } 3862 3863 bool IsRegCall = CallingConv == llvm::CallingConv::X86_RegCall; 3864 3865 // Keep track of the number of assigned registers. 3866 unsigned FreeIntRegs = IsRegCall ? 11 : 6; 3867 unsigned FreeSSERegs = IsRegCall ? 16 : 8; 3868 unsigned NeededInt, NeededSSE; 3869 3870 if (!::classifyReturnType(getCXXABI(), FI, *this)) { 3871 if (IsRegCall && FI.getReturnType()->getTypePtr()->isRecordType() && 3872 !FI.getReturnType()->getTypePtr()->isUnionType()) { 3873 FI.getReturnInfo() = 3874 classifyRegCallStructType(FI.getReturnType(), NeededInt, NeededSSE); 3875 if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) { 3876 FreeIntRegs -= NeededInt; 3877 FreeSSERegs -= NeededSSE; 3878 } else { 3879 FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType()); 3880 } 3881 } else if (IsRegCall && FI.getReturnType()->getAs<ComplexType>() && 3882 getContext().getCanonicalType(FI.getReturnType() 3883 ->getAs<ComplexType>() 3884 ->getElementType()) == 3885 getContext().LongDoubleTy) 3886 // Complex Long Double Type is passed in Memory when Regcall 3887 // calling convention is used. 3888 FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType()); 3889 else 3890 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 3891 } 3892 3893 // If the return value is indirect, then the hidden argument is consuming one 3894 // integer register. 3895 if (FI.getReturnInfo().isIndirect()) 3896 --FreeIntRegs; 3897 3898 // The chain argument effectively gives us another free register. 3899 if (FI.isChainCall()) 3900 ++FreeIntRegs; 3901 3902 unsigned NumRequiredArgs = FI.getNumRequiredArgs(); 3903 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers 3904 // get assigned (in left-to-right order) for passing as follows... 3905 unsigned ArgNo = 0; 3906 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end(); 3907 it != ie; ++it, ++ArgNo) { 3908 bool IsNamedArg = ArgNo < NumRequiredArgs; 3909 3910 if (IsRegCall && it->type->isStructureOrClassType()) 3911 it->info = classifyRegCallStructType(it->type, NeededInt, NeededSSE); 3912 else 3913 it->info = classifyArgumentType(it->type, FreeIntRegs, NeededInt, 3914 NeededSSE, IsNamedArg); 3915 3916 // AMD64-ABI 3.2.3p3: If there are no registers available for any 3917 // eightbyte of an argument, the whole argument is passed on the 3918 // stack. If registers have already been assigned for some 3919 // eightbytes of such an argument, the assignments get reverted. 3920 if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) { 3921 FreeIntRegs -= NeededInt; 3922 FreeSSERegs -= NeededSSE; 3923 } else { 3924 it->info = getIndirectResult(it->type, FreeIntRegs); 3925 } 3926 } 3927 } 3928 3929 static Address EmitX86_64VAArgFromMemory(CodeGenFunction &CGF, 3930 Address VAListAddr, QualType Ty) { 3931 Address overflow_arg_area_p = 3932 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_p"); 3933 llvm::Value *overflow_arg_area = 3934 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area"); 3935 3936 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16 3937 // byte boundary if alignment needed by type exceeds 8 byte boundary. 3938 // It isn't stated explicitly in the standard, but in practice we use 3939 // alignment greater than 16 where necessary. 3940 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty); 3941 if (Align > CharUnits::fromQuantity(8)) { 3942 overflow_arg_area = emitRoundPointerUpToAlignment(CGF, overflow_arg_area, 3943 Align); 3944 } 3945 3946 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area. 3947 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty); 3948 llvm::Value *Res = 3949 CGF.Builder.CreateBitCast(overflow_arg_area, 3950 llvm::PointerType::getUnqual(LTy)); 3951 3952 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to: 3953 // l->overflow_arg_area + sizeof(type). 3954 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to 3955 // an 8 byte boundary. 3956 3957 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8; 3958 llvm::Value *Offset = 3959 llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7); 3960 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset, 3961 "overflow_arg_area.next"); 3962 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p); 3963 3964 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type. 3965 return Address(Res, Align); 3966 } 3967 3968 Address X86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 3969 QualType Ty) const { 3970 // Assume that va_list type is correct; should be pointer to LLVM type: 3971 // struct { 3972 // i32 gp_offset; 3973 // i32 fp_offset; 3974 // i8* overflow_arg_area; 3975 // i8* reg_save_area; 3976 // }; 3977 unsigned neededInt, neededSSE; 3978 3979 Ty = getContext().getCanonicalType(Ty); 3980 ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE, 3981 /*isNamedArg*/false); 3982 3983 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed 3984 // in the registers. If not go to step 7. 3985 if (!neededInt && !neededSSE) 3986 return EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty); 3987 3988 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of 3989 // general purpose registers needed to pass type and num_fp to hold 3990 // the number of floating point registers needed. 3991 3992 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into 3993 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or 3994 // l->fp_offset > 304 - num_fp * 16 go to step 7. 3995 // 3996 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of 3997 // register save space). 3998 3999 llvm::Value *InRegs = nullptr; 4000 Address gp_offset_p = Address::invalid(), fp_offset_p = Address::invalid(); 4001 llvm::Value *gp_offset = nullptr, *fp_offset = nullptr; 4002 if (neededInt) { 4003 gp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "gp_offset_p"); 4004 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset"); 4005 InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8); 4006 InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp"); 4007 } 4008 4009 if (neededSSE) { 4010 fp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 1, "fp_offset_p"); 4011 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset"); 4012 llvm::Value *FitsInFP = 4013 llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16); 4014 FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp"); 4015 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP; 4016 } 4017 4018 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg"); 4019 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem"); 4020 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end"); 4021 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock); 4022 4023 // Emit code to load the value if it was passed in registers. 4024 4025 CGF.EmitBlock(InRegBlock); 4026 4027 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with 4028 // an offset of l->gp_offset and/or l->fp_offset. This may require 4029 // copying to a temporary location in case the parameter is passed 4030 // in different register classes or requires an alignment greater 4031 // than 8 for general purpose registers and 16 for XMM registers. 4032 // 4033 // FIXME: This really results in shameful code when we end up needing to 4034 // collect arguments from different places; often what should result in a 4035 // simple assembling of a structure from scattered addresses has many more 4036 // loads than necessary. Can we clean this up? 4037 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty); 4038 llvm::Value *RegSaveArea = CGF.Builder.CreateLoad( 4039 CGF.Builder.CreateStructGEP(VAListAddr, 3), "reg_save_area"); 4040 4041 Address RegAddr = Address::invalid(); 4042 if (neededInt && neededSSE) { 4043 // FIXME: Cleanup. 4044 assert(AI.isDirect() && "Unexpected ABI info for mixed regs"); 4045 llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType()); 4046 Address Tmp = CGF.CreateMemTemp(Ty); 4047 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST); 4048 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs"); 4049 llvm::Type *TyLo = ST->getElementType(0); 4050 llvm::Type *TyHi = ST->getElementType(1); 4051 assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) && 4052 "Unexpected ABI info for mixed regs"); 4053 llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo); 4054 llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi); 4055 llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegSaveArea, gp_offset); 4056 llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegSaveArea, fp_offset); 4057 llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr; 4058 llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr; 4059 4060 // Copy the first element. 4061 // FIXME: Our choice of alignment here and below is probably pessimistic. 4062 llvm::Value *V = CGF.Builder.CreateAlignedLoad( 4063 TyLo, CGF.Builder.CreateBitCast(RegLoAddr, PTyLo), 4064 CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyLo))); 4065 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0)); 4066 4067 // Copy the second element. 4068 V = CGF.Builder.CreateAlignedLoad( 4069 TyHi, CGF.Builder.CreateBitCast(RegHiAddr, PTyHi), 4070 CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyHi))); 4071 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1)); 4072 4073 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy); 4074 } else if (neededInt) { 4075 RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, gp_offset), 4076 CharUnits::fromQuantity(8)); 4077 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy); 4078 4079 // Copy to a temporary if necessary to ensure the appropriate alignment. 4080 auto TInfo = getContext().getTypeInfoInChars(Ty); 4081 uint64_t TySize = TInfo.Width.getQuantity(); 4082 CharUnits TyAlign = TInfo.Align; 4083 4084 // Copy into a temporary if the type is more aligned than the 4085 // register save area. 4086 if (TyAlign.getQuantity() > 8) { 4087 Address Tmp = CGF.CreateMemTemp(Ty); 4088 CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, false); 4089 RegAddr = Tmp; 4090 } 4091 4092 } else if (neededSSE == 1) { 4093 RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset), 4094 CharUnits::fromQuantity(16)); 4095 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy); 4096 } else { 4097 assert(neededSSE == 2 && "Invalid number of needed registers!"); 4098 // SSE registers are spaced 16 bytes apart in the register save 4099 // area, we need to collect the two eightbytes together. 4100 // The ABI isn't explicit about this, but it seems reasonable 4101 // to assume that the slots are 16-byte aligned, since the stack is 4102 // naturally 16-byte aligned and the prologue is expected to store 4103 // all the SSE registers to the RSA. 4104 Address RegAddrLo = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset), 4105 CharUnits::fromQuantity(16)); 4106 Address RegAddrHi = 4107 CGF.Builder.CreateConstInBoundsByteGEP(RegAddrLo, 4108 CharUnits::fromQuantity(16)); 4109 llvm::Type *ST = AI.canHaveCoerceToType() 4110 ? AI.getCoerceToType() 4111 : llvm::StructType::get(CGF.DoubleTy, CGF.DoubleTy); 4112 llvm::Value *V; 4113 Address Tmp = CGF.CreateMemTemp(Ty); 4114 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST); 4115 V = CGF.Builder.CreateLoad(CGF.Builder.CreateElementBitCast( 4116 RegAddrLo, ST->getStructElementType(0))); 4117 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0)); 4118 V = CGF.Builder.CreateLoad(CGF.Builder.CreateElementBitCast( 4119 RegAddrHi, ST->getStructElementType(1))); 4120 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1)); 4121 4122 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy); 4123 } 4124 4125 // AMD64-ABI 3.5.7p5: Step 5. Set: 4126 // l->gp_offset = l->gp_offset + num_gp * 8 4127 // l->fp_offset = l->fp_offset + num_fp * 16. 4128 if (neededInt) { 4129 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8); 4130 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset), 4131 gp_offset_p); 4132 } 4133 if (neededSSE) { 4134 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16); 4135 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset), 4136 fp_offset_p); 4137 } 4138 CGF.EmitBranch(ContBlock); 4139 4140 // Emit code to load the value if it was passed in memory. 4141 4142 CGF.EmitBlock(InMemBlock); 4143 Address MemAddr = EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty); 4144 4145 // Return the appropriate result. 4146 4147 CGF.EmitBlock(ContBlock); 4148 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, MemAddr, InMemBlock, 4149 "vaarg.addr"); 4150 return ResAddr; 4151 } 4152 4153 Address X86_64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr, 4154 QualType Ty) const { 4155 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false, 4156 CGF.getContext().getTypeInfoInChars(Ty), 4157 CharUnits::fromQuantity(8), 4158 /*allowHigherAlign*/ false); 4159 } 4160 4161 ABIArgInfo WinX86_64ABIInfo::reclassifyHvaArgForVectorCall( 4162 QualType Ty, unsigned &FreeSSERegs, const ABIArgInfo ¤t) const { 4163 const Type *Base = nullptr; 4164 uint64_t NumElts = 0; 4165 4166 if (!Ty->isBuiltinType() && !Ty->isVectorType() && 4167 isHomogeneousAggregate(Ty, Base, NumElts) && FreeSSERegs >= NumElts) { 4168 FreeSSERegs -= NumElts; 4169 return getDirectX86Hva(); 4170 } 4171 return current; 4172 } 4173 4174 ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, unsigned &FreeSSERegs, 4175 bool IsReturnType, bool IsVectorCall, 4176 bool IsRegCall) const { 4177 4178 if (Ty->isVoidType()) 4179 return ABIArgInfo::getIgnore(); 4180 4181 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 4182 Ty = EnumTy->getDecl()->getIntegerType(); 4183 4184 TypeInfo Info = getContext().getTypeInfo(Ty); 4185 uint64_t Width = Info.Width; 4186 CharUnits Align = getContext().toCharUnitsFromBits(Info.Align); 4187 4188 const RecordType *RT = Ty->getAs<RecordType>(); 4189 if (RT) { 4190 if (!IsReturnType) { 4191 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI())) 4192 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 4193 } 4194 4195 if (RT->getDecl()->hasFlexibleArrayMember()) 4196 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 4197 4198 } 4199 4200 const Type *Base = nullptr; 4201 uint64_t NumElts = 0; 4202 // vectorcall adds the concept of a homogenous vector aggregate, similar to 4203 // other targets. 4204 if ((IsVectorCall || IsRegCall) && 4205 isHomogeneousAggregate(Ty, Base, NumElts)) { 4206 if (IsRegCall) { 4207 if (FreeSSERegs >= NumElts) { 4208 FreeSSERegs -= NumElts; 4209 if (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType()) 4210 return ABIArgInfo::getDirect(); 4211 return ABIArgInfo::getExpand(); 4212 } 4213 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false); 4214 } else if (IsVectorCall) { 4215 if (FreeSSERegs >= NumElts && 4216 (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())) { 4217 FreeSSERegs -= NumElts; 4218 return ABIArgInfo::getDirect(); 4219 } else if (IsReturnType) { 4220 return ABIArgInfo::getExpand(); 4221 } else if (!Ty->isBuiltinType() && !Ty->isVectorType()) { 4222 // HVAs are delayed and reclassified in the 2nd step. 4223 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false); 4224 } 4225 } 4226 } 4227 4228 if (Ty->isMemberPointerType()) { 4229 // If the member pointer is represented by an LLVM int or ptr, pass it 4230 // directly. 4231 llvm::Type *LLTy = CGT.ConvertType(Ty); 4232 if (LLTy->isPointerTy() || LLTy->isIntegerTy()) 4233 return ABIArgInfo::getDirect(); 4234 } 4235 4236 if (RT || Ty->isAnyComplexType() || Ty->isMemberPointerType()) { 4237 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is 4238 // not 1, 2, 4, or 8 bytes, must be passed by reference." 4239 if (Width > 64 || !llvm::isPowerOf2_64(Width)) 4240 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 4241 4242 // Otherwise, coerce it to a small integer. 4243 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Width)); 4244 } 4245 4246 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) { 4247 switch (BT->getKind()) { 4248 case BuiltinType::Bool: 4249 // Bool type is always extended to the ABI, other builtin types are not 4250 // extended. 4251 return ABIArgInfo::getExtend(Ty); 4252 4253 case BuiltinType::LongDouble: 4254 // Mingw64 GCC uses the old 80 bit extended precision floating point 4255 // unit. It passes them indirectly through memory. 4256 if (IsMingw64) { 4257 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat(); 4258 if (LDF == &llvm::APFloat::x87DoubleExtended()) 4259 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false); 4260 } 4261 break; 4262 4263 case BuiltinType::Int128: 4264 case BuiltinType::UInt128: 4265 // If it's a parameter type, the normal ABI rule is that arguments larger 4266 // than 8 bytes are passed indirectly. GCC follows it. We follow it too, 4267 // even though it isn't particularly efficient. 4268 if (!IsReturnType) 4269 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false); 4270 4271 // Mingw64 GCC returns i128 in XMM0. Coerce to v2i64 to handle that. 4272 // Clang matches them for compatibility. 4273 return ABIArgInfo::getDirect(llvm::FixedVectorType::get( 4274 llvm::Type::getInt64Ty(getVMContext()), 2)); 4275 4276 default: 4277 break; 4278 } 4279 } 4280 4281 if (Ty->isExtIntType()) { 4282 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is 4283 // not 1, 2, 4, or 8 bytes, must be passed by reference." 4284 // However, non-power-of-two _ExtInts will be passed as 1,2,4 or 8 bytes 4285 // anyway as long is it fits in them, so we don't have to check the power of 4286 // 2. 4287 if (Width <= 64) 4288 return ABIArgInfo::getDirect(); 4289 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false); 4290 } 4291 4292 return ABIArgInfo::getDirect(); 4293 } 4294 4295 void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const { 4296 const unsigned CC = FI.getCallingConvention(); 4297 bool IsVectorCall = CC == llvm::CallingConv::X86_VectorCall; 4298 bool IsRegCall = CC == llvm::CallingConv::X86_RegCall; 4299 4300 // If __attribute__((sysv_abi)) is in use, use the SysV argument 4301 // classification rules. 4302 if (CC == llvm::CallingConv::X86_64_SysV) { 4303 X86_64ABIInfo SysVABIInfo(CGT, AVXLevel); 4304 SysVABIInfo.computeInfo(FI); 4305 return; 4306 } 4307 4308 unsigned FreeSSERegs = 0; 4309 if (IsVectorCall) { 4310 // We can use up to 4 SSE return registers with vectorcall. 4311 FreeSSERegs = 4; 4312 } else if (IsRegCall) { 4313 // RegCall gives us 16 SSE registers. 4314 FreeSSERegs = 16; 4315 } 4316 4317 if (!getCXXABI().classifyReturnType(FI)) 4318 FI.getReturnInfo() = classify(FI.getReturnType(), FreeSSERegs, true, 4319 IsVectorCall, IsRegCall); 4320 4321 if (IsVectorCall) { 4322 // We can use up to 6 SSE register parameters with vectorcall. 4323 FreeSSERegs = 6; 4324 } else if (IsRegCall) { 4325 // RegCall gives us 16 SSE registers, we can reuse the return registers. 4326 FreeSSERegs = 16; 4327 } 4328 4329 unsigned ArgNum = 0; 4330 unsigned ZeroSSERegs = 0; 4331 for (auto &I : FI.arguments()) { 4332 // Vectorcall in x64 only permits the first 6 arguments to be passed as 4333 // XMM/YMM registers. After the sixth argument, pretend no vector 4334 // registers are left. 4335 unsigned *MaybeFreeSSERegs = 4336 (IsVectorCall && ArgNum >= 6) ? &ZeroSSERegs : &FreeSSERegs; 4337 I.info = 4338 classify(I.type, *MaybeFreeSSERegs, false, IsVectorCall, IsRegCall); 4339 ++ArgNum; 4340 } 4341 4342 if (IsVectorCall) { 4343 // For vectorcall, assign aggregate HVAs to any free vector registers in a 4344 // second pass. 4345 for (auto &I : FI.arguments()) 4346 I.info = reclassifyHvaArgForVectorCall(I.type, FreeSSERegs, I.info); 4347 } 4348 } 4349 4350 Address WinX86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 4351 QualType Ty) const { 4352 4353 bool IsIndirect = false; 4354 4355 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is 4356 // not 1, 2, 4, or 8 bytes, must be passed by reference." 4357 if (isAggregateTypeForABI(Ty) || Ty->isMemberPointerType()) { 4358 uint64_t Width = getContext().getTypeSize(Ty); 4359 IsIndirect = Width > 64 || !llvm::isPowerOf2_64(Width); 4360 } 4361 4362 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, 4363 CGF.getContext().getTypeInfoInChars(Ty), 4364 CharUnits::fromQuantity(8), 4365 /*allowHigherAlign*/ false); 4366 } 4367 4368 static bool PPC_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 4369 llvm::Value *Address, bool Is64Bit, 4370 bool IsAIX) { 4371 // This is calculated from the LLVM and GCC tables and verified 4372 // against gcc output. AFAIK all PPC ABIs use the same encoding. 4373 4374 CodeGen::CGBuilderTy &Builder = CGF.Builder; 4375 4376 llvm::IntegerType *i8 = CGF.Int8Ty; 4377 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4); 4378 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8); 4379 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16); 4380 4381 // 0-31: r0-31, the 4-byte or 8-byte general-purpose registers 4382 AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 0, 31); 4383 4384 // 32-63: fp0-31, the 8-byte floating-point registers 4385 AssignToArrayRange(Builder, Address, Eight8, 32, 63); 4386 4387 // 64-67 are various 4-byte or 8-byte special-purpose registers: 4388 // 64: mq 4389 // 65: lr 4390 // 66: ctr 4391 // 67: ap 4392 AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 64, 67); 4393 4394 // 68-76 are various 4-byte special-purpose registers: 4395 // 68-75 cr0-7 4396 // 76: xer 4397 AssignToArrayRange(Builder, Address, Four8, 68, 76); 4398 4399 // 77-108: v0-31, the 16-byte vector registers 4400 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108); 4401 4402 // 109: vrsave 4403 // 110: vscr 4404 AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 109, 110); 4405 4406 // AIX does not utilize the rest of the registers. 4407 if (IsAIX) 4408 return false; 4409 4410 // 111: spe_acc 4411 // 112: spefscr 4412 // 113: sfp 4413 AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 111, 113); 4414 4415 if (!Is64Bit) 4416 return false; 4417 4418 // TODO: Need to verify if these registers are used on 64 bit AIX with Power8 4419 // or above CPU. 4420 // 64-bit only registers: 4421 // 114: tfhar 4422 // 115: tfiar 4423 // 116: texasr 4424 AssignToArrayRange(Builder, Address, Eight8, 114, 116); 4425 4426 return false; 4427 } 4428 4429 // AIX 4430 namespace { 4431 /// AIXABIInfo - The AIX XCOFF ABI information. 4432 class AIXABIInfo : public ABIInfo { 4433 const bool Is64Bit; 4434 const unsigned PtrByteSize; 4435 CharUnits getParamTypeAlignment(QualType Ty) const; 4436 4437 public: 4438 AIXABIInfo(CodeGen::CodeGenTypes &CGT, bool Is64Bit) 4439 : ABIInfo(CGT), Is64Bit(Is64Bit), PtrByteSize(Is64Bit ? 8 : 4) {} 4440 4441 bool isPromotableTypeForABI(QualType Ty) const; 4442 4443 ABIArgInfo classifyReturnType(QualType RetTy) const; 4444 ABIArgInfo classifyArgumentType(QualType Ty) const; 4445 4446 void computeInfo(CGFunctionInfo &FI) const override { 4447 if (!getCXXABI().classifyReturnType(FI)) 4448 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 4449 4450 for (auto &I : FI.arguments()) 4451 I.info = classifyArgumentType(I.type); 4452 } 4453 4454 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 4455 QualType Ty) const override; 4456 }; 4457 4458 class AIXTargetCodeGenInfo : public TargetCodeGenInfo { 4459 const bool Is64Bit; 4460 4461 public: 4462 AIXTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool Is64Bit) 4463 : TargetCodeGenInfo(std::make_unique<AIXABIInfo>(CGT, Is64Bit)), 4464 Is64Bit(Is64Bit) {} 4465 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 4466 return 1; // r1 is the dedicated stack pointer 4467 } 4468 4469 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 4470 llvm::Value *Address) const override; 4471 }; 4472 } // namespace 4473 4474 // Return true if the ABI requires Ty to be passed sign- or zero- 4475 // extended to 32/64 bits. 4476 bool AIXABIInfo::isPromotableTypeForABI(QualType Ty) const { 4477 // Treat an enum type as its underlying type. 4478 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 4479 Ty = EnumTy->getDecl()->getIntegerType(); 4480 4481 // Promotable integer types are required to be promoted by the ABI. 4482 if (Ty->isPromotableIntegerType()) 4483 return true; 4484 4485 if (!Is64Bit) 4486 return false; 4487 4488 // For 64 bit mode, in addition to the usual promotable integer types, we also 4489 // need to extend all 32-bit types, since the ABI requires promotion to 64 4490 // bits. 4491 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) 4492 switch (BT->getKind()) { 4493 case BuiltinType::Int: 4494 case BuiltinType::UInt: 4495 return true; 4496 default: 4497 break; 4498 } 4499 4500 return false; 4501 } 4502 4503 ABIArgInfo AIXABIInfo::classifyReturnType(QualType RetTy) const { 4504 if (RetTy->isAnyComplexType()) 4505 return ABIArgInfo::getDirect(); 4506 4507 if (RetTy->isVectorType()) 4508 return ABIArgInfo::getDirect(); 4509 4510 if (RetTy->isVoidType()) 4511 return ABIArgInfo::getIgnore(); 4512 4513 if (isAggregateTypeForABI(RetTy)) 4514 return getNaturalAlignIndirect(RetTy); 4515 4516 return (isPromotableTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy) 4517 : ABIArgInfo::getDirect()); 4518 } 4519 4520 ABIArgInfo AIXABIInfo::classifyArgumentType(QualType Ty) const { 4521 Ty = useFirstFieldIfTransparentUnion(Ty); 4522 4523 if (Ty->isAnyComplexType()) 4524 return ABIArgInfo::getDirect(); 4525 4526 if (Ty->isVectorType()) 4527 return ABIArgInfo::getDirect(); 4528 4529 if (isAggregateTypeForABI(Ty)) { 4530 // Records with non-trivial destructors/copy-constructors should not be 4531 // passed by value. 4532 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 4533 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 4534 4535 CharUnits CCAlign = getParamTypeAlignment(Ty); 4536 CharUnits TyAlign = getContext().getTypeAlignInChars(Ty); 4537 4538 return ABIArgInfo::getIndirect(CCAlign, /*ByVal*/ true, 4539 /*Realign*/ TyAlign > CCAlign); 4540 } 4541 4542 return (isPromotableTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty) 4543 : ABIArgInfo::getDirect()); 4544 } 4545 4546 CharUnits AIXABIInfo::getParamTypeAlignment(QualType Ty) const { 4547 // Complex types are passed just like their elements. 4548 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) 4549 Ty = CTy->getElementType(); 4550 4551 if (Ty->isVectorType()) 4552 return CharUnits::fromQuantity(16); 4553 4554 // If the structure contains a vector type, the alignment is 16. 4555 if (isRecordWithSIMDVectorType(getContext(), Ty)) 4556 return CharUnits::fromQuantity(16); 4557 4558 return CharUnits::fromQuantity(PtrByteSize); 4559 } 4560 4561 Address AIXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 4562 QualType Ty) const { 4563 if (Ty->isAnyComplexType()) 4564 llvm::report_fatal_error("complex type is not supported on AIX yet"); 4565 4566 auto TypeInfo = getContext().getTypeInfoInChars(Ty); 4567 TypeInfo.Align = getParamTypeAlignment(Ty); 4568 4569 CharUnits SlotSize = CharUnits::fromQuantity(PtrByteSize); 4570 4571 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false, TypeInfo, 4572 SlotSize, /*AllowHigher*/ true); 4573 } 4574 4575 bool AIXTargetCodeGenInfo::initDwarfEHRegSizeTable( 4576 CodeGen::CodeGenFunction &CGF, llvm::Value *Address) const { 4577 return PPC_initDwarfEHRegSizeTable(CGF, Address, Is64Bit, /*IsAIX*/ true); 4578 } 4579 4580 // PowerPC-32 4581 namespace { 4582 /// PPC32_SVR4_ABIInfo - The 32-bit PowerPC ELF (SVR4) ABI information. 4583 class PPC32_SVR4_ABIInfo : public DefaultABIInfo { 4584 bool IsSoftFloatABI; 4585 bool IsRetSmallStructInRegABI; 4586 4587 CharUnits getParamTypeAlignment(QualType Ty) const; 4588 4589 public: 4590 PPC32_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, bool SoftFloatABI, 4591 bool RetSmallStructInRegABI) 4592 : DefaultABIInfo(CGT), IsSoftFloatABI(SoftFloatABI), 4593 IsRetSmallStructInRegABI(RetSmallStructInRegABI) {} 4594 4595 ABIArgInfo classifyReturnType(QualType RetTy) const; 4596 4597 void computeInfo(CGFunctionInfo &FI) const override { 4598 if (!getCXXABI().classifyReturnType(FI)) 4599 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 4600 for (auto &I : FI.arguments()) 4601 I.info = classifyArgumentType(I.type); 4602 } 4603 4604 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 4605 QualType Ty) const override; 4606 }; 4607 4608 class PPC32TargetCodeGenInfo : public TargetCodeGenInfo { 4609 public: 4610 PPC32TargetCodeGenInfo(CodeGenTypes &CGT, bool SoftFloatABI, 4611 bool RetSmallStructInRegABI) 4612 : TargetCodeGenInfo(std::make_unique<PPC32_SVR4_ABIInfo>( 4613 CGT, SoftFloatABI, RetSmallStructInRegABI)) {} 4614 4615 static bool isStructReturnInRegABI(const llvm::Triple &Triple, 4616 const CodeGenOptions &Opts); 4617 4618 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 4619 // This is recovered from gcc output. 4620 return 1; // r1 is the dedicated stack pointer 4621 } 4622 4623 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 4624 llvm::Value *Address) const override; 4625 }; 4626 } 4627 4628 CharUnits PPC32_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const { 4629 // Complex types are passed just like their elements. 4630 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) 4631 Ty = CTy->getElementType(); 4632 4633 if (Ty->isVectorType()) 4634 return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16 4635 : 4); 4636 4637 // For single-element float/vector structs, we consider the whole type 4638 // to have the same alignment requirements as its single element. 4639 const Type *AlignTy = nullptr; 4640 if (const Type *EltType = isSingleElementStruct(Ty, getContext())) { 4641 const BuiltinType *BT = EltType->getAs<BuiltinType>(); 4642 if ((EltType->isVectorType() && getContext().getTypeSize(EltType) == 128) || 4643 (BT && BT->isFloatingPoint())) 4644 AlignTy = EltType; 4645 } 4646 4647 if (AlignTy) 4648 return CharUnits::fromQuantity(AlignTy->isVectorType() ? 16 : 4); 4649 return CharUnits::fromQuantity(4); 4650 } 4651 4652 ABIArgInfo PPC32_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const { 4653 uint64_t Size; 4654 4655 // -msvr4-struct-return puts small aggregates in GPR3 and GPR4. 4656 if (isAggregateTypeForABI(RetTy) && IsRetSmallStructInRegABI && 4657 (Size = getContext().getTypeSize(RetTy)) <= 64) { 4658 // System V ABI (1995), page 3-22, specified: 4659 // > A structure or union whose size is less than or equal to 8 bytes 4660 // > shall be returned in r3 and r4, as if it were first stored in the 4661 // > 8-byte aligned memory area and then the low addressed word were 4662 // > loaded into r3 and the high-addressed word into r4. Bits beyond 4663 // > the last member of the structure or union are not defined. 4664 // 4665 // GCC for big-endian PPC32 inserts the pad before the first member, 4666 // not "beyond the last member" of the struct. To stay compatible 4667 // with GCC, we coerce the struct to an integer of the same size. 4668 // LLVM will extend it and return i32 in r3, or i64 in r3:r4. 4669 if (Size == 0) 4670 return ABIArgInfo::getIgnore(); 4671 else { 4672 llvm::Type *CoerceTy = llvm::Type::getIntNTy(getVMContext(), Size); 4673 return ABIArgInfo::getDirect(CoerceTy); 4674 } 4675 } 4676 4677 return DefaultABIInfo::classifyReturnType(RetTy); 4678 } 4679 4680 // TODO: this implementation is now likely redundant with 4681 // DefaultABIInfo::EmitVAArg. 4682 Address PPC32_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAList, 4683 QualType Ty) const { 4684 if (getTarget().getTriple().isOSDarwin()) { 4685 auto TI = getContext().getTypeInfoInChars(Ty); 4686 TI.Align = getParamTypeAlignment(Ty); 4687 4688 CharUnits SlotSize = CharUnits::fromQuantity(4); 4689 return emitVoidPtrVAArg(CGF, VAList, Ty, 4690 classifyArgumentType(Ty).isIndirect(), TI, SlotSize, 4691 /*AllowHigherAlign=*/true); 4692 } 4693 4694 const unsigned OverflowLimit = 8; 4695 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) { 4696 // TODO: Implement this. For now ignore. 4697 (void)CTy; 4698 return Address::invalid(); // FIXME? 4699 } 4700 4701 // struct __va_list_tag { 4702 // unsigned char gpr; 4703 // unsigned char fpr; 4704 // unsigned short reserved; 4705 // void *overflow_arg_area; 4706 // void *reg_save_area; 4707 // }; 4708 4709 bool isI64 = Ty->isIntegerType() && getContext().getTypeSize(Ty) == 64; 4710 bool isInt = !Ty->isFloatingType(); 4711 bool isF64 = Ty->isFloatingType() && getContext().getTypeSize(Ty) == 64; 4712 4713 // All aggregates are passed indirectly? That doesn't seem consistent 4714 // with the argument-lowering code. 4715 bool isIndirect = isAggregateTypeForABI(Ty); 4716 4717 CGBuilderTy &Builder = CGF.Builder; 4718 4719 // The calling convention either uses 1-2 GPRs or 1 FPR. 4720 Address NumRegsAddr = Address::invalid(); 4721 if (isInt || IsSoftFloatABI) { 4722 NumRegsAddr = Builder.CreateStructGEP(VAList, 0, "gpr"); 4723 } else { 4724 NumRegsAddr = Builder.CreateStructGEP(VAList, 1, "fpr"); 4725 } 4726 4727 llvm::Value *NumRegs = Builder.CreateLoad(NumRegsAddr, "numUsedRegs"); 4728 4729 // "Align" the register count when TY is i64. 4730 if (isI64 || (isF64 && IsSoftFloatABI)) { 4731 NumRegs = Builder.CreateAdd(NumRegs, Builder.getInt8(1)); 4732 NumRegs = Builder.CreateAnd(NumRegs, Builder.getInt8((uint8_t) ~1U)); 4733 } 4734 4735 llvm::Value *CC = 4736 Builder.CreateICmpULT(NumRegs, Builder.getInt8(OverflowLimit), "cond"); 4737 4738 llvm::BasicBlock *UsingRegs = CGF.createBasicBlock("using_regs"); 4739 llvm::BasicBlock *UsingOverflow = CGF.createBasicBlock("using_overflow"); 4740 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont"); 4741 4742 Builder.CreateCondBr(CC, UsingRegs, UsingOverflow); 4743 4744 llvm::Type *DirectTy = CGF.ConvertType(Ty); 4745 if (isIndirect) DirectTy = DirectTy->getPointerTo(0); 4746 4747 // Case 1: consume registers. 4748 Address RegAddr = Address::invalid(); 4749 { 4750 CGF.EmitBlock(UsingRegs); 4751 4752 Address RegSaveAreaPtr = Builder.CreateStructGEP(VAList, 4); 4753 RegAddr = Address(Builder.CreateLoad(RegSaveAreaPtr), 4754 CharUnits::fromQuantity(8)); 4755 assert(RegAddr.getElementType() == CGF.Int8Ty); 4756 4757 // Floating-point registers start after the general-purpose registers. 4758 if (!(isInt || IsSoftFloatABI)) { 4759 RegAddr = Builder.CreateConstInBoundsByteGEP(RegAddr, 4760 CharUnits::fromQuantity(32)); 4761 } 4762 4763 // Get the address of the saved value by scaling the number of 4764 // registers we've used by the number of 4765 CharUnits RegSize = CharUnits::fromQuantity((isInt || IsSoftFloatABI) ? 4 : 8); 4766 llvm::Value *RegOffset = 4767 Builder.CreateMul(NumRegs, Builder.getInt8(RegSize.getQuantity())); 4768 RegAddr = Address(Builder.CreateInBoundsGEP(CGF.Int8Ty, 4769 RegAddr.getPointer(), RegOffset), 4770 RegAddr.getAlignment().alignmentOfArrayElement(RegSize)); 4771 RegAddr = Builder.CreateElementBitCast(RegAddr, DirectTy); 4772 4773 // Increase the used-register count. 4774 NumRegs = 4775 Builder.CreateAdd(NumRegs, 4776 Builder.getInt8((isI64 || (isF64 && IsSoftFloatABI)) ? 2 : 1)); 4777 Builder.CreateStore(NumRegs, NumRegsAddr); 4778 4779 CGF.EmitBranch(Cont); 4780 } 4781 4782 // Case 2: consume space in the overflow area. 4783 Address MemAddr = Address::invalid(); 4784 { 4785 CGF.EmitBlock(UsingOverflow); 4786 4787 Builder.CreateStore(Builder.getInt8(OverflowLimit), NumRegsAddr); 4788 4789 // Everything in the overflow area is rounded up to a size of at least 4. 4790 CharUnits OverflowAreaAlign = CharUnits::fromQuantity(4); 4791 4792 CharUnits Size; 4793 if (!isIndirect) { 4794 auto TypeInfo = CGF.getContext().getTypeInfoInChars(Ty); 4795 Size = TypeInfo.Width.alignTo(OverflowAreaAlign); 4796 } else { 4797 Size = CGF.getPointerSize(); 4798 } 4799 4800 Address OverflowAreaAddr = Builder.CreateStructGEP(VAList, 3); 4801 Address OverflowArea(Builder.CreateLoad(OverflowAreaAddr, "argp.cur"), 4802 OverflowAreaAlign); 4803 // Round up address of argument to alignment 4804 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty); 4805 if (Align > OverflowAreaAlign) { 4806 llvm::Value *Ptr = OverflowArea.getPointer(); 4807 OverflowArea = Address(emitRoundPointerUpToAlignment(CGF, Ptr, Align), 4808 Align); 4809 } 4810 4811 MemAddr = Builder.CreateElementBitCast(OverflowArea, DirectTy); 4812 4813 // Increase the overflow area. 4814 OverflowArea = Builder.CreateConstInBoundsByteGEP(OverflowArea, Size); 4815 Builder.CreateStore(OverflowArea.getPointer(), OverflowAreaAddr); 4816 CGF.EmitBranch(Cont); 4817 } 4818 4819 CGF.EmitBlock(Cont); 4820 4821 // Merge the cases with a phi. 4822 Address Result = emitMergePHI(CGF, RegAddr, UsingRegs, MemAddr, UsingOverflow, 4823 "vaarg.addr"); 4824 4825 // Load the pointer if the argument was passed indirectly. 4826 if (isIndirect) { 4827 Result = Address(Builder.CreateLoad(Result, "aggr"), 4828 getContext().getTypeAlignInChars(Ty)); 4829 } 4830 4831 return Result; 4832 } 4833 4834 bool PPC32TargetCodeGenInfo::isStructReturnInRegABI( 4835 const llvm::Triple &Triple, const CodeGenOptions &Opts) { 4836 assert(Triple.isPPC32()); 4837 4838 switch (Opts.getStructReturnConvention()) { 4839 case CodeGenOptions::SRCK_Default: 4840 break; 4841 case CodeGenOptions::SRCK_OnStack: // -maix-struct-return 4842 return false; 4843 case CodeGenOptions::SRCK_InRegs: // -msvr4-struct-return 4844 return true; 4845 } 4846 4847 if (Triple.isOSBinFormatELF() && !Triple.isOSLinux()) 4848 return true; 4849 4850 return false; 4851 } 4852 4853 bool 4854 PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 4855 llvm::Value *Address) const { 4856 return PPC_initDwarfEHRegSizeTable(CGF, Address, /*Is64Bit*/ false, 4857 /*IsAIX*/ false); 4858 } 4859 4860 // PowerPC-64 4861 4862 namespace { 4863 /// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information. 4864 class PPC64_SVR4_ABIInfo : public SwiftABIInfo { 4865 public: 4866 enum ABIKind { 4867 ELFv1 = 0, 4868 ELFv2 4869 }; 4870 4871 private: 4872 static const unsigned GPRBits = 64; 4873 ABIKind Kind; 4874 bool IsSoftFloatABI; 4875 4876 public: 4877 PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind, 4878 bool SoftFloatABI) 4879 : SwiftABIInfo(CGT), Kind(Kind), IsSoftFloatABI(SoftFloatABI) {} 4880 4881 bool isPromotableTypeForABI(QualType Ty) const; 4882 CharUnits getParamTypeAlignment(QualType Ty) const; 4883 4884 ABIArgInfo classifyReturnType(QualType RetTy) const; 4885 ABIArgInfo classifyArgumentType(QualType Ty) const; 4886 4887 bool isHomogeneousAggregateBaseType(QualType Ty) const override; 4888 bool isHomogeneousAggregateSmallEnough(const Type *Ty, 4889 uint64_t Members) const override; 4890 4891 // TODO: We can add more logic to computeInfo to improve performance. 4892 // Example: For aggregate arguments that fit in a register, we could 4893 // use getDirectInReg (as is done below for structs containing a single 4894 // floating-point value) to avoid pushing them to memory on function 4895 // entry. This would require changing the logic in PPCISelLowering 4896 // when lowering the parameters in the caller and args in the callee. 4897 void computeInfo(CGFunctionInfo &FI) const override { 4898 if (!getCXXABI().classifyReturnType(FI)) 4899 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 4900 for (auto &I : FI.arguments()) { 4901 // We rely on the default argument classification for the most part. 4902 // One exception: An aggregate containing a single floating-point 4903 // or vector item must be passed in a register if one is available. 4904 const Type *T = isSingleElementStruct(I.type, getContext()); 4905 if (T) { 4906 const BuiltinType *BT = T->getAs<BuiltinType>(); 4907 if ((T->isVectorType() && getContext().getTypeSize(T) == 128) || 4908 (BT && BT->isFloatingPoint())) { 4909 QualType QT(T, 0); 4910 I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT)); 4911 continue; 4912 } 4913 } 4914 I.info = classifyArgumentType(I.type); 4915 } 4916 } 4917 4918 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 4919 QualType Ty) const override; 4920 4921 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars, 4922 bool asReturnValue) const override { 4923 return occupiesMoreThan(CGT, scalars, /*total*/ 4); 4924 } 4925 4926 bool isSwiftErrorInRegister() const override { 4927 return false; 4928 } 4929 }; 4930 4931 class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo { 4932 4933 public: 4934 PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT, 4935 PPC64_SVR4_ABIInfo::ABIKind Kind, 4936 bool SoftFloatABI) 4937 : TargetCodeGenInfo( 4938 std::make_unique<PPC64_SVR4_ABIInfo>(CGT, Kind, SoftFloatABI)) {} 4939 4940 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 4941 // This is recovered from gcc output. 4942 return 1; // r1 is the dedicated stack pointer 4943 } 4944 4945 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 4946 llvm::Value *Address) const override; 4947 }; 4948 4949 class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo { 4950 public: 4951 PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {} 4952 4953 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 4954 // This is recovered from gcc output. 4955 return 1; // r1 is the dedicated stack pointer 4956 } 4957 4958 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 4959 llvm::Value *Address) const override; 4960 }; 4961 4962 } 4963 4964 // Return true if the ABI requires Ty to be passed sign- or zero- 4965 // extended to 64 bits. 4966 bool 4967 PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const { 4968 // Treat an enum type as its underlying type. 4969 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 4970 Ty = EnumTy->getDecl()->getIntegerType(); 4971 4972 // Promotable integer types are required to be promoted by the ABI. 4973 if (isPromotableIntegerTypeForABI(Ty)) 4974 return true; 4975 4976 // In addition to the usual promotable integer types, we also need to 4977 // extend all 32-bit types, since the ABI requires promotion to 64 bits. 4978 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) 4979 switch (BT->getKind()) { 4980 case BuiltinType::Int: 4981 case BuiltinType::UInt: 4982 return true; 4983 default: 4984 break; 4985 } 4986 4987 if (const auto *EIT = Ty->getAs<ExtIntType>()) 4988 if (EIT->getNumBits() < 64) 4989 return true; 4990 4991 return false; 4992 } 4993 4994 /// isAlignedParamType - Determine whether a type requires 16-byte or 4995 /// higher alignment in the parameter area. Always returns at least 8. 4996 CharUnits PPC64_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const { 4997 // Complex types are passed just like their elements. 4998 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) 4999 Ty = CTy->getElementType(); 5000 5001 // Only vector types of size 16 bytes need alignment (larger types are 5002 // passed via reference, smaller types are not aligned). 5003 if (Ty->isVectorType()) { 5004 return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16 : 8); 5005 } else if (Ty->isRealFloatingType() && 5006 &getContext().getFloatTypeSemantics(Ty) == 5007 &llvm::APFloat::IEEEquad()) { 5008 // According to ABI document section 'Optional Save Areas': If extended 5009 // precision floating-point values in IEEE BINARY 128 QUADRUPLE PRECISION 5010 // format are supported, map them to a single quadword, quadword aligned. 5011 return CharUnits::fromQuantity(16); 5012 } 5013 5014 // For single-element float/vector structs, we consider the whole type 5015 // to have the same alignment requirements as its single element. 5016 const Type *AlignAsType = nullptr; 5017 const Type *EltType = isSingleElementStruct(Ty, getContext()); 5018 if (EltType) { 5019 const BuiltinType *BT = EltType->getAs<BuiltinType>(); 5020 if ((EltType->isVectorType() && getContext().getTypeSize(EltType) == 128) || 5021 (BT && BT->isFloatingPoint())) 5022 AlignAsType = EltType; 5023 } 5024 5025 // Likewise for ELFv2 homogeneous aggregates. 5026 const Type *Base = nullptr; 5027 uint64_t Members = 0; 5028 if (!AlignAsType && Kind == ELFv2 && 5029 isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members)) 5030 AlignAsType = Base; 5031 5032 // With special case aggregates, only vector base types need alignment. 5033 if (AlignAsType) { 5034 return CharUnits::fromQuantity(AlignAsType->isVectorType() ? 16 : 8); 5035 } 5036 5037 // Otherwise, we only need alignment for any aggregate type that 5038 // has an alignment requirement of >= 16 bytes. 5039 if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128) { 5040 return CharUnits::fromQuantity(16); 5041 } 5042 5043 return CharUnits::fromQuantity(8); 5044 } 5045 5046 /// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous 5047 /// aggregate. Base is set to the base element type, and Members is set 5048 /// to the number of base elements. 5049 bool ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base, 5050 uint64_t &Members) const { 5051 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) { 5052 uint64_t NElements = AT->getSize().getZExtValue(); 5053 if (NElements == 0) 5054 return false; 5055 if (!isHomogeneousAggregate(AT->getElementType(), Base, Members)) 5056 return false; 5057 Members *= NElements; 5058 } else if (const RecordType *RT = Ty->getAs<RecordType>()) { 5059 const RecordDecl *RD = RT->getDecl(); 5060 if (RD->hasFlexibleArrayMember()) 5061 return false; 5062 5063 Members = 0; 5064 5065 // If this is a C++ record, check the properties of the record such as 5066 // bases and ABI specific restrictions 5067 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 5068 if (!getCXXABI().isPermittedToBeHomogeneousAggregate(CXXRD)) 5069 return false; 5070 5071 for (const auto &I : CXXRD->bases()) { 5072 // Ignore empty records. 5073 if (isEmptyRecord(getContext(), I.getType(), true)) 5074 continue; 5075 5076 uint64_t FldMembers; 5077 if (!isHomogeneousAggregate(I.getType(), Base, FldMembers)) 5078 return false; 5079 5080 Members += FldMembers; 5081 } 5082 } 5083 5084 for (const auto *FD : RD->fields()) { 5085 // Ignore (non-zero arrays of) empty records. 5086 QualType FT = FD->getType(); 5087 while (const ConstantArrayType *AT = 5088 getContext().getAsConstantArrayType(FT)) { 5089 if (AT->getSize().getZExtValue() == 0) 5090 return false; 5091 FT = AT->getElementType(); 5092 } 5093 if (isEmptyRecord(getContext(), FT, true)) 5094 continue; 5095 5096 // For compatibility with GCC, ignore empty bitfields in C++ mode. 5097 if (getContext().getLangOpts().CPlusPlus && 5098 FD->isZeroLengthBitField(getContext())) 5099 continue; 5100 5101 uint64_t FldMembers; 5102 if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers)) 5103 return false; 5104 5105 Members = (RD->isUnion() ? 5106 std::max(Members, FldMembers) : Members + FldMembers); 5107 } 5108 5109 if (!Base) 5110 return false; 5111 5112 // Ensure there is no padding. 5113 if (getContext().getTypeSize(Base) * Members != 5114 getContext().getTypeSize(Ty)) 5115 return false; 5116 } else { 5117 Members = 1; 5118 if (const ComplexType *CT = Ty->getAs<ComplexType>()) { 5119 Members = 2; 5120 Ty = CT->getElementType(); 5121 } 5122 5123 // Most ABIs only support float, double, and some vector type widths. 5124 if (!isHomogeneousAggregateBaseType(Ty)) 5125 return false; 5126 5127 // The base type must be the same for all members. Types that 5128 // agree in both total size and mode (float vs. vector) are 5129 // treated as being equivalent here. 5130 const Type *TyPtr = Ty.getTypePtr(); 5131 if (!Base) { 5132 Base = TyPtr; 5133 // If it's a non-power-of-2 vector, its size is already a power-of-2, 5134 // so make sure to widen it explicitly. 5135 if (const VectorType *VT = Base->getAs<VectorType>()) { 5136 QualType EltTy = VT->getElementType(); 5137 unsigned NumElements = 5138 getContext().getTypeSize(VT) / getContext().getTypeSize(EltTy); 5139 Base = getContext() 5140 .getVectorType(EltTy, NumElements, VT->getVectorKind()) 5141 .getTypePtr(); 5142 } 5143 } 5144 5145 if (Base->isVectorType() != TyPtr->isVectorType() || 5146 getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr)) 5147 return false; 5148 } 5149 return Members > 0 && isHomogeneousAggregateSmallEnough(Base, Members); 5150 } 5151 5152 bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const { 5153 // Homogeneous aggregates for ELFv2 must have base types of float, 5154 // double, long double, or 128-bit vectors. 5155 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) { 5156 if (BT->getKind() == BuiltinType::Float || 5157 BT->getKind() == BuiltinType::Double || 5158 BT->getKind() == BuiltinType::LongDouble || 5159 (getContext().getTargetInfo().hasFloat128Type() && 5160 (BT->getKind() == BuiltinType::Float128))) { 5161 if (IsSoftFloatABI) 5162 return false; 5163 return true; 5164 } 5165 } 5166 if (const VectorType *VT = Ty->getAs<VectorType>()) { 5167 if (getContext().getTypeSize(VT) == 128) 5168 return true; 5169 } 5170 return false; 5171 } 5172 5173 bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateSmallEnough( 5174 const Type *Base, uint64_t Members) const { 5175 // Vector and fp128 types require one register, other floating point types 5176 // require one or two registers depending on their size. 5177 uint32_t NumRegs = 5178 ((getContext().getTargetInfo().hasFloat128Type() && 5179 Base->isFloat128Type()) || 5180 Base->isVectorType()) ? 1 5181 : (getContext().getTypeSize(Base) + 63) / 64; 5182 5183 // Homogeneous Aggregates may occupy at most 8 registers. 5184 return Members * NumRegs <= 8; 5185 } 5186 5187 ABIArgInfo 5188 PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const { 5189 Ty = useFirstFieldIfTransparentUnion(Ty); 5190 5191 if (Ty->isAnyComplexType()) 5192 return ABIArgInfo::getDirect(); 5193 5194 // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes) 5195 // or via reference (larger than 16 bytes). 5196 if (Ty->isVectorType()) { 5197 uint64_t Size = getContext().getTypeSize(Ty); 5198 if (Size > 128) 5199 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 5200 else if (Size < 128) { 5201 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size); 5202 return ABIArgInfo::getDirect(CoerceTy); 5203 } 5204 } 5205 5206 if (const auto *EIT = Ty->getAs<ExtIntType>()) 5207 if (EIT->getNumBits() > 128) 5208 return getNaturalAlignIndirect(Ty, /*ByVal=*/true); 5209 5210 if (isAggregateTypeForABI(Ty)) { 5211 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 5212 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 5213 5214 uint64_t ABIAlign = getParamTypeAlignment(Ty).getQuantity(); 5215 uint64_t TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity(); 5216 5217 // ELFv2 homogeneous aggregates are passed as array types. 5218 const Type *Base = nullptr; 5219 uint64_t Members = 0; 5220 if (Kind == ELFv2 && 5221 isHomogeneousAggregate(Ty, Base, Members)) { 5222 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0)); 5223 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members); 5224 return ABIArgInfo::getDirect(CoerceTy); 5225 } 5226 5227 // If an aggregate may end up fully in registers, we do not 5228 // use the ByVal method, but pass the aggregate as array. 5229 // This is usually beneficial since we avoid forcing the 5230 // back-end to store the argument to memory. 5231 uint64_t Bits = getContext().getTypeSize(Ty); 5232 if (Bits > 0 && Bits <= 8 * GPRBits) { 5233 llvm::Type *CoerceTy; 5234 5235 // Types up to 8 bytes are passed as integer type (which will be 5236 // properly aligned in the argument save area doubleword). 5237 if (Bits <= GPRBits) 5238 CoerceTy = 5239 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8)); 5240 // Larger types are passed as arrays, with the base type selected 5241 // according to the required alignment in the save area. 5242 else { 5243 uint64_t RegBits = ABIAlign * 8; 5244 uint64_t NumRegs = llvm::alignTo(Bits, RegBits) / RegBits; 5245 llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits); 5246 CoerceTy = llvm::ArrayType::get(RegTy, NumRegs); 5247 } 5248 5249 return ABIArgInfo::getDirect(CoerceTy); 5250 } 5251 5252 // All other aggregates are passed ByVal. 5253 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign), 5254 /*ByVal=*/true, 5255 /*Realign=*/TyAlign > ABIAlign); 5256 } 5257 5258 return (isPromotableTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty) 5259 : ABIArgInfo::getDirect()); 5260 } 5261 5262 ABIArgInfo 5263 PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const { 5264 if (RetTy->isVoidType()) 5265 return ABIArgInfo::getIgnore(); 5266 5267 if (RetTy->isAnyComplexType()) 5268 return ABIArgInfo::getDirect(); 5269 5270 // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes) 5271 // or via reference (larger than 16 bytes). 5272 if (RetTy->isVectorType()) { 5273 uint64_t Size = getContext().getTypeSize(RetTy); 5274 if (Size > 128) 5275 return getNaturalAlignIndirect(RetTy); 5276 else if (Size < 128) { 5277 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size); 5278 return ABIArgInfo::getDirect(CoerceTy); 5279 } 5280 } 5281 5282 if (const auto *EIT = RetTy->getAs<ExtIntType>()) 5283 if (EIT->getNumBits() > 128) 5284 return getNaturalAlignIndirect(RetTy, /*ByVal=*/false); 5285 5286 if (isAggregateTypeForABI(RetTy)) { 5287 // ELFv2 homogeneous aggregates are returned as array types. 5288 const Type *Base = nullptr; 5289 uint64_t Members = 0; 5290 if (Kind == ELFv2 && 5291 isHomogeneousAggregate(RetTy, Base, Members)) { 5292 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0)); 5293 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members); 5294 return ABIArgInfo::getDirect(CoerceTy); 5295 } 5296 5297 // ELFv2 small aggregates are returned in up to two registers. 5298 uint64_t Bits = getContext().getTypeSize(RetTy); 5299 if (Kind == ELFv2 && Bits <= 2 * GPRBits) { 5300 if (Bits == 0) 5301 return ABIArgInfo::getIgnore(); 5302 5303 llvm::Type *CoerceTy; 5304 if (Bits > GPRBits) { 5305 CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits); 5306 CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy); 5307 } else 5308 CoerceTy = 5309 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8)); 5310 return ABIArgInfo::getDirect(CoerceTy); 5311 } 5312 5313 // All other aggregates are returned indirectly. 5314 return getNaturalAlignIndirect(RetTy); 5315 } 5316 5317 return (isPromotableTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy) 5318 : ABIArgInfo::getDirect()); 5319 } 5320 5321 // Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine. 5322 Address PPC64_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 5323 QualType Ty) const { 5324 auto TypeInfo = getContext().getTypeInfoInChars(Ty); 5325 TypeInfo.Align = getParamTypeAlignment(Ty); 5326 5327 CharUnits SlotSize = CharUnits::fromQuantity(8); 5328 5329 // If we have a complex type and the base type is smaller than 8 bytes, 5330 // the ABI calls for the real and imaginary parts to be right-adjusted 5331 // in separate doublewords. However, Clang expects us to produce a 5332 // pointer to a structure with the two parts packed tightly. So generate 5333 // loads of the real and imaginary parts relative to the va_list pointer, 5334 // and store them to a temporary structure. 5335 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) { 5336 CharUnits EltSize = TypeInfo.Width / 2; 5337 if (EltSize < SlotSize) { 5338 Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, CGF.Int8Ty, 5339 SlotSize * 2, SlotSize, 5340 SlotSize, /*AllowHigher*/ true); 5341 5342 Address RealAddr = Addr; 5343 Address ImagAddr = RealAddr; 5344 if (CGF.CGM.getDataLayout().isBigEndian()) { 5345 RealAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, 5346 SlotSize - EltSize); 5347 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(ImagAddr, 5348 2 * SlotSize - EltSize); 5349 } else { 5350 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, SlotSize); 5351 } 5352 5353 llvm::Type *EltTy = CGF.ConvertTypeForMem(CTy->getElementType()); 5354 RealAddr = CGF.Builder.CreateElementBitCast(RealAddr, EltTy); 5355 ImagAddr = CGF.Builder.CreateElementBitCast(ImagAddr, EltTy); 5356 llvm::Value *Real = CGF.Builder.CreateLoad(RealAddr, ".vareal"); 5357 llvm::Value *Imag = CGF.Builder.CreateLoad(ImagAddr, ".vaimag"); 5358 5359 Address Temp = CGF.CreateMemTemp(Ty, "vacplx"); 5360 CGF.EmitStoreOfComplex({Real, Imag}, CGF.MakeAddrLValue(Temp, Ty), 5361 /*init*/ true); 5362 return Temp; 5363 } 5364 } 5365 5366 // Otherwise, just use the general rule. 5367 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false, 5368 TypeInfo, SlotSize, /*AllowHigher*/ true); 5369 } 5370 5371 bool 5372 PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable( 5373 CodeGen::CodeGenFunction &CGF, 5374 llvm::Value *Address) const { 5375 return PPC_initDwarfEHRegSizeTable(CGF, Address, /*Is64Bit*/ true, 5376 /*IsAIX*/ false); 5377 } 5378 5379 bool 5380 PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 5381 llvm::Value *Address) const { 5382 return PPC_initDwarfEHRegSizeTable(CGF, Address, /*Is64Bit*/ true, 5383 /*IsAIX*/ false); 5384 } 5385 5386 //===----------------------------------------------------------------------===// 5387 // AArch64 ABI Implementation 5388 //===----------------------------------------------------------------------===// 5389 5390 namespace { 5391 5392 class AArch64ABIInfo : public SwiftABIInfo { 5393 public: 5394 enum ABIKind { 5395 AAPCS = 0, 5396 DarwinPCS, 5397 Win64 5398 }; 5399 5400 private: 5401 ABIKind Kind; 5402 5403 public: 5404 AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind) 5405 : SwiftABIInfo(CGT), Kind(Kind) {} 5406 5407 private: 5408 ABIKind getABIKind() const { return Kind; } 5409 bool isDarwinPCS() const { return Kind == DarwinPCS; } 5410 5411 ABIArgInfo classifyReturnType(QualType RetTy, bool IsVariadic) const; 5412 ABIArgInfo classifyArgumentType(QualType RetTy) const; 5413 ABIArgInfo coerceIllegalVector(QualType Ty) const; 5414 bool isHomogeneousAggregateBaseType(QualType Ty) const override; 5415 bool isHomogeneousAggregateSmallEnough(const Type *Ty, 5416 uint64_t Members) const override; 5417 5418 bool isIllegalVectorType(QualType Ty) const; 5419 5420 void computeInfo(CGFunctionInfo &FI) const override { 5421 if (!::classifyReturnType(getCXXABI(), FI, *this)) 5422 FI.getReturnInfo() = 5423 classifyReturnType(FI.getReturnType(), FI.isVariadic()); 5424 5425 for (auto &it : FI.arguments()) 5426 it.info = classifyArgumentType(it.type); 5427 } 5428 5429 Address EmitDarwinVAArg(Address VAListAddr, QualType Ty, 5430 CodeGenFunction &CGF) const; 5431 5432 Address EmitAAPCSVAArg(Address VAListAddr, QualType Ty, 5433 CodeGenFunction &CGF) const; 5434 5435 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 5436 QualType Ty) const override { 5437 llvm::Type *BaseTy = CGF.ConvertType(Ty); 5438 if (isa<llvm::ScalableVectorType>(BaseTy)) 5439 llvm::report_fatal_error("Passing SVE types to variadic functions is " 5440 "currently not supported"); 5441 5442 return Kind == Win64 ? EmitMSVAArg(CGF, VAListAddr, Ty) 5443 : isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF) 5444 : EmitAAPCSVAArg(VAListAddr, Ty, CGF); 5445 } 5446 5447 Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr, 5448 QualType Ty) const override; 5449 5450 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars, 5451 bool asReturnValue) const override { 5452 return occupiesMoreThan(CGT, scalars, /*total*/ 4); 5453 } 5454 bool isSwiftErrorInRegister() const override { 5455 return true; 5456 } 5457 5458 bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy, 5459 unsigned elts) const override; 5460 5461 bool allowBFloatArgsAndRet() const override { 5462 return getTarget().hasBFloat16Type(); 5463 } 5464 }; 5465 5466 class AArch64TargetCodeGenInfo : public TargetCodeGenInfo { 5467 public: 5468 AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind) 5469 : TargetCodeGenInfo(std::make_unique<AArch64ABIInfo>(CGT, Kind)) {} 5470 5471 StringRef getARCRetainAutoreleasedReturnValueMarker() const override { 5472 return "mov\tfp, fp\t\t// marker for objc_retainAutoreleaseReturnValue"; 5473 } 5474 5475 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 5476 return 31; 5477 } 5478 5479 bool doesReturnSlotInterfereWithArgs() const override { return false; } 5480 5481 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 5482 CodeGen::CodeGenModule &CGM) const override { 5483 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D); 5484 if (!FD) 5485 return; 5486 5487 const auto *TA = FD->getAttr<TargetAttr>(); 5488 if (TA == nullptr) 5489 return; 5490 5491 ParsedTargetAttr Attr = TA->parse(); 5492 if (Attr.BranchProtection.empty()) 5493 return; 5494 5495 TargetInfo::BranchProtectionInfo BPI; 5496 StringRef Error; 5497 (void)CGM.getTarget().validateBranchProtection(Attr.BranchProtection, 5498 BPI, Error); 5499 assert(Error.empty()); 5500 5501 auto *Fn = cast<llvm::Function>(GV); 5502 static const char *SignReturnAddrStr[] = {"none", "non-leaf", "all"}; 5503 Fn->addFnAttr("sign-return-address", SignReturnAddrStr[static_cast<int>(BPI.SignReturnAddr)]); 5504 5505 if (BPI.SignReturnAddr != LangOptions::SignReturnAddressScopeKind::None) { 5506 Fn->addFnAttr("sign-return-address-key", 5507 BPI.SignKey == LangOptions::SignReturnAddressKeyKind::AKey 5508 ? "a_key" 5509 : "b_key"); 5510 } 5511 5512 Fn->addFnAttr("branch-target-enforcement", 5513 BPI.BranchTargetEnforcement ? "true" : "false"); 5514 } 5515 }; 5516 5517 class WindowsAArch64TargetCodeGenInfo : public AArch64TargetCodeGenInfo { 5518 public: 5519 WindowsAArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind K) 5520 : AArch64TargetCodeGenInfo(CGT, K) {} 5521 5522 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 5523 CodeGen::CodeGenModule &CGM) const override; 5524 5525 void getDependentLibraryOption(llvm::StringRef Lib, 5526 llvm::SmallString<24> &Opt) const override { 5527 Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib); 5528 } 5529 5530 void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value, 5531 llvm::SmallString<32> &Opt) const override { 5532 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\""; 5533 } 5534 }; 5535 5536 void WindowsAArch64TargetCodeGenInfo::setTargetAttributes( 5537 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const { 5538 AArch64TargetCodeGenInfo::setTargetAttributes(D, GV, CGM); 5539 if (GV->isDeclaration()) 5540 return; 5541 addStackProbeTargetAttributes(D, GV, CGM); 5542 } 5543 } 5544 5545 ABIArgInfo AArch64ABIInfo::coerceIllegalVector(QualType Ty) const { 5546 assert(Ty->isVectorType() && "expected vector type!"); 5547 5548 const auto *VT = Ty->castAs<VectorType>(); 5549 if (VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector) { 5550 assert(VT->getElementType()->isBuiltinType() && "expected builtin type!"); 5551 assert(VT->getElementType()->castAs<BuiltinType>()->getKind() == 5552 BuiltinType::UChar && 5553 "unexpected builtin type for SVE predicate!"); 5554 return ABIArgInfo::getDirect(llvm::ScalableVectorType::get( 5555 llvm::Type::getInt1Ty(getVMContext()), 16)); 5556 } 5557 5558 if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector) { 5559 assert(VT->getElementType()->isBuiltinType() && "expected builtin type!"); 5560 5561 const auto *BT = VT->getElementType()->castAs<BuiltinType>(); 5562 llvm::ScalableVectorType *ResType = nullptr; 5563 switch (BT->getKind()) { 5564 default: 5565 llvm_unreachable("unexpected builtin type for SVE vector!"); 5566 case BuiltinType::SChar: 5567 case BuiltinType::UChar: 5568 ResType = llvm::ScalableVectorType::get( 5569 llvm::Type::getInt8Ty(getVMContext()), 16); 5570 break; 5571 case BuiltinType::Short: 5572 case BuiltinType::UShort: 5573 ResType = llvm::ScalableVectorType::get( 5574 llvm::Type::getInt16Ty(getVMContext()), 8); 5575 break; 5576 case BuiltinType::Int: 5577 case BuiltinType::UInt: 5578 ResType = llvm::ScalableVectorType::get( 5579 llvm::Type::getInt32Ty(getVMContext()), 4); 5580 break; 5581 case BuiltinType::Long: 5582 case BuiltinType::ULong: 5583 ResType = llvm::ScalableVectorType::get( 5584 llvm::Type::getInt64Ty(getVMContext()), 2); 5585 break; 5586 case BuiltinType::Half: 5587 ResType = llvm::ScalableVectorType::get( 5588 llvm::Type::getHalfTy(getVMContext()), 8); 5589 break; 5590 case BuiltinType::Float: 5591 ResType = llvm::ScalableVectorType::get( 5592 llvm::Type::getFloatTy(getVMContext()), 4); 5593 break; 5594 case BuiltinType::Double: 5595 ResType = llvm::ScalableVectorType::get( 5596 llvm::Type::getDoubleTy(getVMContext()), 2); 5597 break; 5598 case BuiltinType::BFloat16: 5599 ResType = llvm::ScalableVectorType::get( 5600 llvm::Type::getBFloatTy(getVMContext()), 8); 5601 break; 5602 } 5603 return ABIArgInfo::getDirect(ResType); 5604 } 5605 5606 uint64_t Size = getContext().getTypeSize(Ty); 5607 // Android promotes <2 x i8> to i16, not i32 5608 if (isAndroid() && (Size <= 16)) { 5609 llvm::Type *ResType = llvm::Type::getInt16Ty(getVMContext()); 5610 return ABIArgInfo::getDirect(ResType); 5611 } 5612 if (Size <= 32) { 5613 llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext()); 5614 return ABIArgInfo::getDirect(ResType); 5615 } 5616 if (Size == 64) { 5617 auto *ResType = 5618 llvm::FixedVectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2); 5619 return ABIArgInfo::getDirect(ResType); 5620 } 5621 if (Size == 128) { 5622 auto *ResType = 5623 llvm::FixedVectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4); 5624 return ABIArgInfo::getDirect(ResType); 5625 } 5626 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 5627 } 5628 5629 ABIArgInfo AArch64ABIInfo::classifyArgumentType(QualType Ty) const { 5630 Ty = useFirstFieldIfTransparentUnion(Ty); 5631 5632 // Handle illegal vector types here. 5633 if (isIllegalVectorType(Ty)) 5634 return coerceIllegalVector(Ty); 5635 5636 if (!isAggregateTypeForABI(Ty)) { 5637 // Treat an enum type as its underlying type. 5638 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 5639 Ty = EnumTy->getDecl()->getIntegerType(); 5640 5641 if (const auto *EIT = Ty->getAs<ExtIntType>()) 5642 if (EIT->getNumBits() > 128) 5643 return getNaturalAlignIndirect(Ty); 5644 5645 return (isPromotableIntegerTypeForABI(Ty) && isDarwinPCS() 5646 ? ABIArgInfo::getExtend(Ty) 5647 : ABIArgInfo::getDirect()); 5648 } 5649 5650 // Structures with either a non-trivial destructor or a non-trivial 5651 // copy constructor are always indirect. 5652 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) { 5653 return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA == 5654 CGCXXABI::RAA_DirectInMemory); 5655 } 5656 5657 // Empty records are always ignored on Darwin, but actually passed in C++ mode 5658 // elsewhere for GNU compatibility. 5659 uint64_t Size = getContext().getTypeSize(Ty); 5660 bool IsEmpty = isEmptyRecord(getContext(), Ty, true); 5661 if (IsEmpty || Size == 0) { 5662 if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS()) 5663 return ABIArgInfo::getIgnore(); 5664 5665 // GNU C mode. The only argument that gets ignored is an empty one with size 5666 // 0. 5667 if (IsEmpty && Size == 0) 5668 return ABIArgInfo::getIgnore(); 5669 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext())); 5670 } 5671 5672 // Homogeneous Floating-point Aggregates (HFAs) need to be expanded. 5673 const Type *Base = nullptr; 5674 uint64_t Members = 0; 5675 if (isHomogeneousAggregate(Ty, Base, Members)) { 5676 return ABIArgInfo::getDirect( 5677 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members)); 5678 } 5679 5680 // Aggregates <= 16 bytes are passed directly in registers or on the stack. 5681 if (Size <= 128) { 5682 // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of 5683 // same size and alignment. 5684 if (getTarget().isRenderScriptTarget()) { 5685 return coerceToIntArray(Ty, getContext(), getVMContext()); 5686 } 5687 unsigned Alignment; 5688 if (Kind == AArch64ABIInfo::AAPCS) { 5689 Alignment = getContext().getTypeUnadjustedAlign(Ty); 5690 Alignment = Alignment < 128 ? 64 : 128; 5691 } else { 5692 Alignment = std::max(getContext().getTypeAlign(Ty), 5693 (unsigned)getTarget().getPointerWidth(0)); 5694 } 5695 Size = llvm::alignTo(Size, Alignment); 5696 5697 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment. 5698 // For aggregates with 16-byte alignment, we use i128. 5699 llvm::Type *BaseTy = llvm::Type::getIntNTy(getVMContext(), Alignment); 5700 return ABIArgInfo::getDirect( 5701 Size == Alignment ? BaseTy 5702 : llvm::ArrayType::get(BaseTy, Size / Alignment)); 5703 } 5704 5705 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 5706 } 5707 5708 ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy, 5709 bool IsVariadic) const { 5710 if (RetTy->isVoidType()) 5711 return ABIArgInfo::getIgnore(); 5712 5713 if (const auto *VT = RetTy->getAs<VectorType>()) { 5714 if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector || 5715 VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector) 5716 return coerceIllegalVector(RetTy); 5717 } 5718 5719 // Large vector types should be returned via memory. 5720 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128) 5721 return getNaturalAlignIndirect(RetTy); 5722 5723 if (!isAggregateTypeForABI(RetTy)) { 5724 // Treat an enum type as its underlying type. 5725 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 5726 RetTy = EnumTy->getDecl()->getIntegerType(); 5727 5728 if (const auto *EIT = RetTy->getAs<ExtIntType>()) 5729 if (EIT->getNumBits() > 128) 5730 return getNaturalAlignIndirect(RetTy); 5731 5732 return (isPromotableIntegerTypeForABI(RetTy) && isDarwinPCS() 5733 ? ABIArgInfo::getExtend(RetTy) 5734 : ABIArgInfo::getDirect()); 5735 } 5736 5737 uint64_t Size = getContext().getTypeSize(RetTy); 5738 if (isEmptyRecord(getContext(), RetTy, true) || Size == 0) 5739 return ABIArgInfo::getIgnore(); 5740 5741 const Type *Base = nullptr; 5742 uint64_t Members = 0; 5743 if (isHomogeneousAggregate(RetTy, Base, Members) && 5744 !(getTarget().getTriple().getArch() == llvm::Triple::aarch64_32 && 5745 IsVariadic)) 5746 // Homogeneous Floating-point Aggregates (HFAs) are returned directly. 5747 return ABIArgInfo::getDirect(); 5748 5749 // Aggregates <= 16 bytes are returned directly in registers or on the stack. 5750 if (Size <= 128) { 5751 // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of 5752 // same size and alignment. 5753 if (getTarget().isRenderScriptTarget()) { 5754 return coerceToIntArray(RetTy, getContext(), getVMContext()); 5755 } 5756 unsigned Alignment = getContext().getTypeAlign(RetTy); 5757 Size = llvm::alignTo(Size, 64); // round up to multiple of 8 bytes 5758 5759 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment. 5760 // For aggregates with 16-byte alignment, we use i128. 5761 if (Alignment < 128 && Size == 128) { 5762 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext()); 5763 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64)); 5764 } 5765 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size)); 5766 } 5767 5768 return getNaturalAlignIndirect(RetTy); 5769 } 5770 5771 /// isIllegalVectorType - check whether the vector type is legal for AArch64. 5772 bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const { 5773 if (const VectorType *VT = Ty->getAs<VectorType>()) { 5774 // Check whether VT is a fixed-length SVE vector. These types are 5775 // represented as scalable vectors in function args/return and must be 5776 // coerced from fixed vectors. 5777 if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector || 5778 VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector) 5779 return true; 5780 5781 // Check whether VT is legal. 5782 unsigned NumElements = VT->getNumElements(); 5783 uint64_t Size = getContext().getTypeSize(VT); 5784 // NumElements should be power of 2. 5785 if (!llvm::isPowerOf2_32(NumElements)) 5786 return true; 5787 5788 // arm64_32 has to be compatible with the ARM logic here, which allows huge 5789 // vectors for some reason. 5790 llvm::Triple Triple = getTarget().getTriple(); 5791 if (Triple.getArch() == llvm::Triple::aarch64_32 && 5792 Triple.isOSBinFormatMachO()) 5793 return Size <= 32; 5794 5795 return Size != 64 && (Size != 128 || NumElements == 1); 5796 } 5797 return false; 5798 } 5799 5800 bool AArch64ABIInfo::isLegalVectorTypeForSwift(CharUnits totalSize, 5801 llvm::Type *eltTy, 5802 unsigned elts) const { 5803 if (!llvm::isPowerOf2_32(elts)) 5804 return false; 5805 if (totalSize.getQuantity() != 8 && 5806 (totalSize.getQuantity() != 16 || elts == 1)) 5807 return false; 5808 return true; 5809 } 5810 5811 bool AArch64ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const { 5812 // Homogeneous aggregates for AAPCS64 must have base types of a floating 5813 // point type or a short-vector type. This is the same as the 32-bit ABI, 5814 // but with the difference that any floating-point type is allowed, 5815 // including __fp16. 5816 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) { 5817 if (BT->isFloatingPoint()) 5818 return true; 5819 } else if (const VectorType *VT = Ty->getAs<VectorType>()) { 5820 unsigned VecSize = getContext().getTypeSize(VT); 5821 if (VecSize == 64 || VecSize == 128) 5822 return true; 5823 } 5824 return false; 5825 } 5826 5827 bool AArch64ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base, 5828 uint64_t Members) const { 5829 return Members <= 4; 5830 } 5831 5832 Address AArch64ABIInfo::EmitAAPCSVAArg(Address VAListAddr, 5833 QualType Ty, 5834 CodeGenFunction &CGF) const { 5835 ABIArgInfo AI = classifyArgumentType(Ty); 5836 bool IsIndirect = AI.isIndirect(); 5837 5838 llvm::Type *BaseTy = CGF.ConvertType(Ty); 5839 if (IsIndirect) 5840 BaseTy = llvm::PointerType::getUnqual(BaseTy); 5841 else if (AI.getCoerceToType()) 5842 BaseTy = AI.getCoerceToType(); 5843 5844 unsigned NumRegs = 1; 5845 if (llvm::ArrayType *ArrTy = dyn_cast<llvm::ArrayType>(BaseTy)) { 5846 BaseTy = ArrTy->getElementType(); 5847 NumRegs = ArrTy->getNumElements(); 5848 } 5849 bool IsFPR = BaseTy->isFloatingPointTy() || BaseTy->isVectorTy(); 5850 5851 // The AArch64 va_list type and handling is specified in the Procedure Call 5852 // Standard, section B.4: 5853 // 5854 // struct { 5855 // void *__stack; 5856 // void *__gr_top; 5857 // void *__vr_top; 5858 // int __gr_offs; 5859 // int __vr_offs; 5860 // }; 5861 5862 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg"); 5863 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg"); 5864 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack"); 5865 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end"); 5866 5867 CharUnits TySize = getContext().getTypeSizeInChars(Ty); 5868 CharUnits TyAlign = getContext().getTypeUnadjustedAlignInChars(Ty); 5869 5870 Address reg_offs_p = Address::invalid(); 5871 llvm::Value *reg_offs = nullptr; 5872 int reg_top_index; 5873 int RegSize = IsIndirect ? 8 : TySize.getQuantity(); 5874 if (!IsFPR) { 5875 // 3 is the field number of __gr_offs 5876 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 3, "gr_offs_p"); 5877 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs"); 5878 reg_top_index = 1; // field number for __gr_top 5879 RegSize = llvm::alignTo(RegSize, 8); 5880 } else { 5881 // 4 is the field number of __vr_offs. 5882 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 4, "vr_offs_p"); 5883 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs"); 5884 reg_top_index = 2; // field number for __vr_top 5885 RegSize = 16 * NumRegs; 5886 } 5887 5888 //======================================= 5889 // Find out where argument was passed 5890 //======================================= 5891 5892 // If reg_offs >= 0 we're already using the stack for this type of 5893 // argument. We don't want to keep updating reg_offs (in case it overflows, 5894 // though anyone passing 2GB of arguments, each at most 16 bytes, deserves 5895 // whatever they get). 5896 llvm::Value *UsingStack = nullptr; 5897 UsingStack = CGF.Builder.CreateICmpSGE( 5898 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0)); 5899 5900 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock); 5901 5902 // Otherwise, at least some kind of argument could go in these registers, the 5903 // question is whether this particular type is too big. 5904 CGF.EmitBlock(MaybeRegBlock); 5905 5906 // Integer arguments may need to correct register alignment (for example a 5907 // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we 5908 // align __gr_offs to calculate the potential address. 5909 if (!IsFPR && !IsIndirect && TyAlign.getQuantity() > 8) { 5910 int Align = TyAlign.getQuantity(); 5911 5912 reg_offs = CGF.Builder.CreateAdd( 5913 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1), 5914 "align_regoffs"); 5915 reg_offs = CGF.Builder.CreateAnd( 5916 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align), 5917 "aligned_regoffs"); 5918 } 5919 5920 // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list. 5921 // The fact that this is done unconditionally reflects the fact that 5922 // allocating an argument to the stack also uses up all the remaining 5923 // registers of the appropriate kind. 5924 llvm::Value *NewOffset = nullptr; 5925 NewOffset = CGF.Builder.CreateAdd( 5926 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs"); 5927 CGF.Builder.CreateStore(NewOffset, reg_offs_p); 5928 5929 // Now we're in a position to decide whether this argument really was in 5930 // registers or not. 5931 llvm::Value *InRegs = nullptr; 5932 InRegs = CGF.Builder.CreateICmpSLE( 5933 NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg"); 5934 5935 CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock); 5936 5937 //======================================= 5938 // Argument was in registers 5939 //======================================= 5940 5941 // Now we emit the code for if the argument was originally passed in 5942 // registers. First start the appropriate block: 5943 CGF.EmitBlock(InRegBlock); 5944 5945 llvm::Value *reg_top = nullptr; 5946 Address reg_top_p = 5947 CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index, "reg_top_p"); 5948 reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top"); 5949 Address BaseAddr(CGF.Builder.CreateInBoundsGEP(CGF.Int8Ty, reg_top, reg_offs), 5950 CharUnits::fromQuantity(IsFPR ? 16 : 8)); 5951 Address RegAddr = Address::invalid(); 5952 llvm::Type *MemTy = CGF.ConvertTypeForMem(Ty); 5953 5954 if (IsIndirect) { 5955 // If it's been passed indirectly (actually a struct), whatever we find from 5956 // stored registers or on the stack will actually be a struct **. 5957 MemTy = llvm::PointerType::getUnqual(MemTy); 5958 } 5959 5960 const Type *Base = nullptr; 5961 uint64_t NumMembers = 0; 5962 bool IsHFA = isHomogeneousAggregate(Ty, Base, NumMembers); 5963 if (IsHFA && NumMembers > 1) { 5964 // Homogeneous aggregates passed in registers will have their elements split 5965 // and stored 16-bytes apart regardless of size (they're notionally in qN, 5966 // qN+1, ...). We reload and store into a temporary local variable 5967 // contiguously. 5968 assert(!IsIndirect && "Homogeneous aggregates should be passed directly"); 5969 auto BaseTyInfo = getContext().getTypeInfoInChars(QualType(Base, 0)); 5970 llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0)); 5971 llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers); 5972 Address Tmp = CGF.CreateTempAlloca(HFATy, 5973 std::max(TyAlign, BaseTyInfo.Align)); 5974 5975 // On big-endian platforms, the value will be right-aligned in its slot. 5976 int Offset = 0; 5977 if (CGF.CGM.getDataLayout().isBigEndian() && 5978 BaseTyInfo.Width.getQuantity() < 16) 5979 Offset = 16 - BaseTyInfo.Width.getQuantity(); 5980 5981 for (unsigned i = 0; i < NumMembers; ++i) { 5982 CharUnits BaseOffset = CharUnits::fromQuantity(16 * i + Offset); 5983 Address LoadAddr = 5984 CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, BaseOffset); 5985 LoadAddr = CGF.Builder.CreateElementBitCast(LoadAddr, BaseTy); 5986 5987 Address StoreAddr = CGF.Builder.CreateConstArrayGEP(Tmp, i); 5988 5989 llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr); 5990 CGF.Builder.CreateStore(Elem, StoreAddr); 5991 } 5992 5993 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, MemTy); 5994 } else { 5995 // Otherwise the object is contiguous in memory. 5996 5997 // It might be right-aligned in its slot. 5998 CharUnits SlotSize = BaseAddr.getAlignment(); 5999 if (CGF.CGM.getDataLayout().isBigEndian() && !IsIndirect && 6000 (IsHFA || !isAggregateTypeForABI(Ty)) && 6001 TySize < SlotSize) { 6002 CharUnits Offset = SlotSize - TySize; 6003 BaseAddr = CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, Offset); 6004 } 6005 6006 RegAddr = CGF.Builder.CreateElementBitCast(BaseAddr, MemTy); 6007 } 6008 6009 CGF.EmitBranch(ContBlock); 6010 6011 //======================================= 6012 // Argument was on the stack 6013 //======================================= 6014 CGF.EmitBlock(OnStackBlock); 6015 6016 Address stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "stack_p"); 6017 llvm::Value *OnStackPtr = CGF.Builder.CreateLoad(stack_p, "stack"); 6018 6019 // Again, stack arguments may need realignment. In this case both integer and 6020 // floating-point ones might be affected. 6021 if (!IsIndirect && TyAlign.getQuantity() > 8) { 6022 int Align = TyAlign.getQuantity(); 6023 6024 OnStackPtr = CGF.Builder.CreatePtrToInt(OnStackPtr, CGF.Int64Ty); 6025 6026 OnStackPtr = CGF.Builder.CreateAdd( 6027 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1), 6028 "align_stack"); 6029 OnStackPtr = CGF.Builder.CreateAnd( 6030 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, -Align), 6031 "align_stack"); 6032 6033 OnStackPtr = CGF.Builder.CreateIntToPtr(OnStackPtr, CGF.Int8PtrTy); 6034 } 6035 Address OnStackAddr(OnStackPtr, 6036 std::max(CharUnits::fromQuantity(8), TyAlign)); 6037 6038 // All stack slots are multiples of 8 bytes. 6039 CharUnits StackSlotSize = CharUnits::fromQuantity(8); 6040 CharUnits StackSize; 6041 if (IsIndirect) 6042 StackSize = StackSlotSize; 6043 else 6044 StackSize = TySize.alignTo(StackSlotSize); 6045 6046 llvm::Value *StackSizeC = CGF.Builder.getSize(StackSize); 6047 llvm::Value *NewStack = CGF.Builder.CreateInBoundsGEP( 6048 CGF.Int8Ty, OnStackPtr, StackSizeC, "new_stack"); 6049 6050 // Write the new value of __stack for the next call to va_arg 6051 CGF.Builder.CreateStore(NewStack, stack_p); 6052 6053 if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) && 6054 TySize < StackSlotSize) { 6055 CharUnits Offset = StackSlotSize - TySize; 6056 OnStackAddr = CGF.Builder.CreateConstInBoundsByteGEP(OnStackAddr, Offset); 6057 } 6058 6059 OnStackAddr = CGF.Builder.CreateElementBitCast(OnStackAddr, MemTy); 6060 6061 CGF.EmitBranch(ContBlock); 6062 6063 //======================================= 6064 // Tidy up 6065 //======================================= 6066 CGF.EmitBlock(ContBlock); 6067 6068 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, 6069 OnStackAddr, OnStackBlock, "vaargs.addr"); 6070 6071 if (IsIndirect) 6072 return Address(CGF.Builder.CreateLoad(ResAddr, "vaarg.addr"), 6073 TyAlign); 6074 6075 return ResAddr; 6076 } 6077 6078 Address AArch64ABIInfo::EmitDarwinVAArg(Address VAListAddr, QualType Ty, 6079 CodeGenFunction &CGF) const { 6080 // The backend's lowering doesn't support va_arg for aggregates or 6081 // illegal vector types. Lower VAArg here for these cases and use 6082 // the LLVM va_arg instruction for everything else. 6083 if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty)) 6084 return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect()); 6085 6086 uint64_t PointerSize = getTarget().getPointerWidth(0) / 8; 6087 CharUnits SlotSize = CharUnits::fromQuantity(PointerSize); 6088 6089 // Empty records are ignored for parameter passing purposes. 6090 if (isEmptyRecord(getContext(), Ty, true)) { 6091 Address Addr(CGF.Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize); 6092 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty)); 6093 return Addr; 6094 } 6095 6096 // The size of the actual thing passed, which might end up just 6097 // being a pointer for indirect types. 6098 auto TyInfo = getContext().getTypeInfoInChars(Ty); 6099 6100 // Arguments bigger than 16 bytes which aren't homogeneous 6101 // aggregates should be passed indirectly. 6102 bool IsIndirect = false; 6103 if (TyInfo.Width.getQuantity() > 16) { 6104 const Type *Base = nullptr; 6105 uint64_t Members = 0; 6106 IsIndirect = !isHomogeneousAggregate(Ty, Base, Members); 6107 } 6108 6109 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, 6110 TyInfo, SlotSize, /*AllowHigherAlign*/ true); 6111 } 6112 6113 Address AArch64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr, 6114 QualType Ty) const { 6115 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false, 6116 CGF.getContext().getTypeInfoInChars(Ty), 6117 CharUnits::fromQuantity(8), 6118 /*allowHigherAlign*/ false); 6119 } 6120 6121 //===----------------------------------------------------------------------===// 6122 // ARM ABI Implementation 6123 //===----------------------------------------------------------------------===// 6124 6125 namespace { 6126 6127 class ARMABIInfo : public SwiftABIInfo { 6128 public: 6129 enum ABIKind { 6130 APCS = 0, 6131 AAPCS = 1, 6132 AAPCS_VFP = 2, 6133 AAPCS16_VFP = 3, 6134 }; 6135 6136 private: 6137 ABIKind Kind; 6138 bool IsFloatABISoftFP; 6139 6140 public: 6141 ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind) 6142 : SwiftABIInfo(CGT), Kind(_Kind) { 6143 setCCs(); 6144 IsFloatABISoftFP = CGT.getCodeGenOpts().FloatABI == "softfp" || 6145 CGT.getCodeGenOpts().FloatABI == ""; // default 6146 } 6147 6148 bool isEABI() const { 6149 switch (getTarget().getTriple().getEnvironment()) { 6150 case llvm::Triple::Android: 6151 case llvm::Triple::EABI: 6152 case llvm::Triple::EABIHF: 6153 case llvm::Triple::GNUEABI: 6154 case llvm::Triple::GNUEABIHF: 6155 case llvm::Triple::MuslEABI: 6156 case llvm::Triple::MuslEABIHF: 6157 return true; 6158 default: 6159 return false; 6160 } 6161 } 6162 6163 bool isEABIHF() const { 6164 switch (getTarget().getTriple().getEnvironment()) { 6165 case llvm::Triple::EABIHF: 6166 case llvm::Triple::GNUEABIHF: 6167 case llvm::Triple::MuslEABIHF: 6168 return true; 6169 default: 6170 return false; 6171 } 6172 } 6173 6174 ABIKind getABIKind() const { return Kind; } 6175 6176 bool allowBFloatArgsAndRet() const override { 6177 return !IsFloatABISoftFP && getTarget().hasBFloat16Type(); 6178 } 6179 6180 private: 6181 ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic, 6182 unsigned functionCallConv) const; 6183 ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic, 6184 unsigned functionCallConv) const; 6185 ABIArgInfo classifyHomogeneousAggregate(QualType Ty, const Type *Base, 6186 uint64_t Members) const; 6187 ABIArgInfo coerceIllegalVector(QualType Ty) const; 6188 bool isIllegalVectorType(QualType Ty) const; 6189 bool containsAnyFP16Vectors(QualType Ty) const; 6190 6191 bool isHomogeneousAggregateBaseType(QualType Ty) const override; 6192 bool isHomogeneousAggregateSmallEnough(const Type *Ty, 6193 uint64_t Members) const override; 6194 6195 bool isEffectivelyAAPCS_VFP(unsigned callConvention, bool acceptHalf) const; 6196 6197 void computeInfo(CGFunctionInfo &FI) const override; 6198 6199 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 6200 QualType Ty) const override; 6201 6202 llvm::CallingConv::ID getLLVMDefaultCC() const; 6203 llvm::CallingConv::ID getABIDefaultCC() const; 6204 void setCCs(); 6205 6206 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars, 6207 bool asReturnValue) const override { 6208 return occupiesMoreThan(CGT, scalars, /*total*/ 4); 6209 } 6210 bool isSwiftErrorInRegister() const override { 6211 return true; 6212 } 6213 bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy, 6214 unsigned elts) const override; 6215 }; 6216 6217 class ARMTargetCodeGenInfo : public TargetCodeGenInfo { 6218 public: 6219 ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K) 6220 : TargetCodeGenInfo(std::make_unique<ARMABIInfo>(CGT, K)) {} 6221 6222 const ARMABIInfo &getABIInfo() const { 6223 return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo()); 6224 } 6225 6226 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 6227 return 13; 6228 } 6229 6230 StringRef getARCRetainAutoreleasedReturnValueMarker() const override { 6231 return "mov\tr7, r7\t\t// marker for objc_retainAutoreleaseReturnValue"; 6232 } 6233 6234 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 6235 llvm::Value *Address) const override { 6236 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4); 6237 6238 // 0-15 are the 16 integer registers. 6239 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15); 6240 return false; 6241 } 6242 6243 unsigned getSizeOfUnwindException() const override { 6244 if (getABIInfo().isEABI()) return 88; 6245 return TargetCodeGenInfo::getSizeOfUnwindException(); 6246 } 6247 6248 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 6249 CodeGen::CodeGenModule &CGM) const override { 6250 if (GV->isDeclaration()) 6251 return; 6252 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D); 6253 if (!FD) 6254 return; 6255 6256 const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>(); 6257 if (!Attr) 6258 return; 6259 6260 const char *Kind; 6261 switch (Attr->getInterrupt()) { 6262 case ARMInterruptAttr::Generic: Kind = ""; break; 6263 case ARMInterruptAttr::IRQ: Kind = "IRQ"; break; 6264 case ARMInterruptAttr::FIQ: Kind = "FIQ"; break; 6265 case ARMInterruptAttr::SWI: Kind = "SWI"; break; 6266 case ARMInterruptAttr::ABORT: Kind = "ABORT"; break; 6267 case ARMInterruptAttr::UNDEF: Kind = "UNDEF"; break; 6268 } 6269 6270 llvm::Function *Fn = cast<llvm::Function>(GV); 6271 6272 Fn->addFnAttr("interrupt", Kind); 6273 6274 ARMABIInfo::ABIKind ABI = cast<ARMABIInfo>(getABIInfo()).getABIKind(); 6275 if (ABI == ARMABIInfo::APCS) 6276 return; 6277 6278 // AAPCS guarantees that sp will be 8-byte aligned on any public interface, 6279 // however this is not necessarily true on taking any interrupt. Instruct 6280 // the backend to perform a realignment as part of the function prologue. 6281 llvm::AttrBuilder B; 6282 B.addStackAlignmentAttr(8); 6283 Fn->addAttributes(llvm::AttributeList::FunctionIndex, B); 6284 } 6285 }; 6286 6287 class WindowsARMTargetCodeGenInfo : public ARMTargetCodeGenInfo { 6288 public: 6289 WindowsARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K) 6290 : ARMTargetCodeGenInfo(CGT, K) {} 6291 6292 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 6293 CodeGen::CodeGenModule &CGM) const override; 6294 6295 void getDependentLibraryOption(llvm::StringRef Lib, 6296 llvm::SmallString<24> &Opt) const override { 6297 Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib); 6298 } 6299 6300 void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value, 6301 llvm::SmallString<32> &Opt) const override { 6302 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\""; 6303 } 6304 }; 6305 6306 void WindowsARMTargetCodeGenInfo::setTargetAttributes( 6307 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const { 6308 ARMTargetCodeGenInfo::setTargetAttributes(D, GV, CGM); 6309 if (GV->isDeclaration()) 6310 return; 6311 addStackProbeTargetAttributes(D, GV, CGM); 6312 } 6313 } 6314 6315 void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const { 6316 if (!::classifyReturnType(getCXXABI(), FI, *this)) 6317 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), FI.isVariadic(), 6318 FI.getCallingConvention()); 6319 6320 for (auto &I : FI.arguments()) 6321 I.info = classifyArgumentType(I.type, FI.isVariadic(), 6322 FI.getCallingConvention()); 6323 6324 6325 // Always honor user-specified calling convention. 6326 if (FI.getCallingConvention() != llvm::CallingConv::C) 6327 return; 6328 6329 llvm::CallingConv::ID cc = getRuntimeCC(); 6330 if (cc != llvm::CallingConv::C) 6331 FI.setEffectiveCallingConvention(cc); 6332 } 6333 6334 /// Return the default calling convention that LLVM will use. 6335 llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const { 6336 // The default calling convention that LLVM will infer. 6337 if (isEABIHF() || getTarget().getTriple().isWatchABI()) 6338 return llvm::CallingConv::ARM_AAPCS_VFP; 6339 else if (isEABI()) 6340 return llvm::CallingConv::ARM_AAPCS; 6341 else 6342 return llvm::CallingConv::ARM_APCS; 6343 } 6344 6345 /// Return the calling convention that our ABI would like us to use 6346 /// as the C calling convention. 6347 llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const { 6348 switch (getABIKind()) { 6349 case APCS: return llvm::CallingConv::ARM_APCS; 6350 case AAPCS: return llvm::CallingConv::ARM_AAPCS; 6351 case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP; 6352 case AAPCS16_VFP: return llvm::CallingConv::ARM_AAPCS_VFP; 6353 } 6354 llvm_unreachable("bad ABI kind"); 6355 } 6356 6357 void ARMABIInfo::setCCs() { 6358 assert(getRuntimeCC() == llvm::CallingConv::C); 6359 6360 // Don't muddy up the IR with a ton of explicit annotations if 6361 // they'd just match what LLVM will infer from the triple. 6362 llvm::CallingConv::ID abiCC = getABIDefaultCC(); 6363 if (abiCC != getLLVMDefaultCC()) 6364 RuntimeCC = abiCC; 6365 } 6366 6367 ABIArgInfo ARMABIInfo::coerceIllegalVector(QualType Ty) const { 6368 uint64_t Size = getContext().getTypeSize(Ty); 6369 if (Size <= 32) { 6370 llvm::Type *ResType = 6371 llvm::Type::getInt32Ty(getVMContext()); 6372 return ABIArgInfo::getDirect(ResType); 6373 } 6374 if (Size == 64 || Size == 128) { 6375 auto *ResType = llvm::FixedVectorType::get( 6376 llvm::Type::getInt32Ty(getVMContext()), Size / 32); 6377 return ABIArgInfo::getDirect(ResType); 6378 } 6379 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 6380 } 6381 6382 ABIArgInfo ARMABIInfo::classifyHomogeneousAggregate(QualType Ty, 6383 const Type *Base, 6384 uint64_t Members) const { 6385 assert(Base && "Base class should be set for homogeneous aggregate"); 6386 // Base can be a floating-point or a vector. 6387 if (const VectorType *VT = Base->getAs<VectorType>()) { 6388 // FP16 vectors should be converted to integer vectors 6389 if (!getTarget().hasLegalHalfType() && containsAnyFP16Vectors(Ty)) { 6390 uint64_t Size = getContext().getTypeSize(VT); 6391 auto *NewVecTy = llvm::FixedVectorType::get( 6392 llvm::Type::getInt32Ty(getVMContext()), Size / 32); 6393 llvm::Type *Ty = llvm::ArrayType::get(NewVecTy, Members); 6394 return ABIArgInfo::getDirect(Ty, 0, nullptr, false); 6395 } 6396 } 6397 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false); 6398 } 6399 6400 ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty, bool isVariadic, 6401 unsigned functionCallConv) const { 6402 // 6.1.2.1 The following argument types are VFP CPRCs: 6403 // A single-precision floating-point type (including promoted 6404 // half-precision types); A double-precision floating-point type; 6405 // A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate 6406 // with a Base Type of a single- or double-precision floating-point type, 6407 // 64-bit containerized vectors or 128-bit containerized vectors with one 6408 // to four Elements. 6409 // Variadic functions should always marshal to the base standard. 6410 bool IsAAPCS_VFP = 6411 !isVariadic && isEffectivelyAAPCS_VFP(functionCallConv, /* AAPCS16 */ false); 6412 6413 Ty = useFirstFieldIfTransparentUnion(Ty); 6414 6415 // Handle illegal vector types here. 6416 if (isIllegalVectorType(Ty)) 6417 return coerceIllegalVector(Ty); 6418 6419 if (!isAggregateTypeForABI(Ty)) { 6420 // Treat an enum type as its underlying type. 6421 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) { 6422 Ty = EnumTy->getDecl()->getIntegerType(); 6423 } 6424 6425 if (const auto *EIT = Ty->getAs<ExtIntType>()) 6426 if (EIT->getNumBits() > 64) 6427 return getNaturalAlignIndirect(Ty, /*ByVal=*/true); 6428 6429 return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty) 6430 : ABIArgInfo::getDirect()); 6431 } 6432 6433 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) { 6434 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 6435 } 6436 6437 // Ignore empty records. 6438 if (isEmptyRecord(getContext(), Ty, true)) 6439 return ABIArgInfo::getIgnore(); 6440 6441 if (IsAAPCS_VFP) { 6442 // Homogeneous Aggregates need to be expanded when we can fit the aggregate 6443 // into VFP registers. 6444 const Type *Base = nullptr; 6445 uint64_t Members = 0; 6446 if (isHomogeneousAggregate(Ty, Base, Members)) 6447 return classifyHomogeneousAggregate(Ty, Base, Members); 6448 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) { 6449 // WatchOS does have homogeneous aggregates. Note that we intentionally use 6450 // this convention even for a variadic function: the backend will use GPRs 6451 // if needed. 6452 const Type *Base = nullptr; 6453 uint64_t Members = 0; 6454 if (isHomogeneousAggregate(Ty, Base, Members)) { 6455 assert(Base && Members <= 4 && "unexpected homogeneous aggregate"); 6456 llvm::Type *Ty = 6457 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members); 6458 return ABIArgInfo::getDirect(Ty, 0, nullptr, false); 6459 } 6460 } 6461 6462 if (getABIKind() == ARMABIInfo::AAPCS16_VFP && 6463 getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(16)) { 6464 // WatchOS is adopting the 64-bit AAPCS rule on composite types: if they're 6465 // bigger than 128-bits, they get placed in space allocated by the caller, 6466 // and a pointer is passed. 6467 return ABIArgInfo::getIndirect( 6468 CharUnits::fromQuantity(getContext().getTypeAlign(Ty) / 8), false); 6469 } 6470 6471 // Support byval for ARM. 6472 // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at 6473 // most 8-byte. We realign the indirect argument if type alignment is bigger 6474 // than ABI alignment. 6475 uint64_t ABIAlign = 4; 6476 uint64_t TyAlign; 6477 if (getABIKind() == ARMABIInfo::AAPCS_VFP || 6478 getABIKind() == ARMABIInfo::AAPCS) { 6479 TyAlign = getContext().getTypeUnadjustedAlignInChars(Ty).getQuantity(); 6480 ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8); 6481 } else { 6482 TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity(); 6483 } 6484 if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) { 6485 assert(getABIKind() != ARMABIInfo::AAPCS16_VFP && "unexpected byval"); 6486 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign), 6487 /*ByVal=*/true, 6488 /*Realign=*/TyAlign > ABIAlign); 6489 } 6490 6491 // On RenderScript, coerce Aggregates <= 64 bytes to an integer array of 6492 // same size and alignment. 6493 if (getTarget().isRenderScriptTarget()) { 6494 return coerceToIntArray(Ty, getContext(), getVMContext()); 6495 } 6496 6497 // Otherwise, pass by coercing to a structure of the appropriate size. 6498 llvm::Type* ElemTy; 6499 unsigned SizeRegs; 6500 // FIXME: Try to match the types of the arguments more accurately where 6501 // we can. 6502 if (TyAlign <= 4) { 6503 ElemTy = llvm::Type::getInt32Ty(getVMContext()); 6504 SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32; 6505 } else { 6506 ElemTy = llvm::Type::getInt64Ty(getVMContext()); 6507 SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64; 6508 } 6509 6510 return ABIArgInfo::getDirect(llvm::ArrayType::get(ElemTy, SizeRegs)); 6511 } 6512 6513 static bool isIntegerLikeType(QualType Ty, ASTContext &Context, 6514 llvm::LLVMContext &VMContext) { 6515 // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure 6516 // is called integer-like if its size is less than or equal to one word, and 6517 // the offset of each of its addressable sub-fields is zero. 6518 6519 uint64_t Size = Context.getTypeSize(Ty); 6520 6521 // Check that the type fits in a word. 6522 if (Size > 32) 6523 return false; 6524 6525 // FIXME: Handle vector types! 6526 if (Ty->isVectorType()) 6527 return false; 6528 6529 // Float types are never treated as "integer like". 6530 if (Ty->isRealFloatingType()) 6531 return false; 6532 6533 // If this is a builtin or pointer type then it is ok. 6534 if (Ty->getAs<BuiltinType>() || Ty->isPointerType()) 6535 return true; 6536 6537 // Small complex integer types are "integer like". 6538 if (const ComplexType *CT = Ty->getAs<ComplexType>()) 6539 return isIntegerLikeType(CT->getElementType(), Context, VMContext); 6540 6541 // Single element and zero sized arrays should be allowed, by the definition 6542 // above, but they are not. 6543 6544 // Otherwise, it must be a record type. 6545 const RecordType *RT = Ty->getAs<RecordType>(); 6546 if (!RT) return false; 6547 6548 // Ignore records with flexible arrays. 6549 const RecordDecl *RD = RT->getDecl(); 6550 if (RD->hasFlexibleArrayMember()) 6551 return false; 6552 6553 // Check that all sub-fields are at offset 0, and are themselves "integer 6554 // like". 6555 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); 6556 6557 bool HadField = false; 6558 unsigned idx = 0; 6559 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 6560 i != e; ++i, ++idx) { 6561 const FieldDecl *FD = *i; 6562 6563 // Bit-fields are not addressable, we only need to verify they are "integer 6564 // like". We still have to disallow a subsequent non-bitfield, for example: 6565 // struct { int : 0; int x } 6566 // is non-integer like according to gcc. 6567 if (FD->isBitField()) { 6568 if (!RD->isUnion()) 6569 HadField = true; 6570 6571 if (!isIntegerLikeType(FD->getType(), Context, VMContext)) 6572 return false; 6573 6574 continue; 6575 } 6576 6577 // Check if this field is at offset 0. 6578 if (Layout.getFieldOffset(idx) != 0) 6579 return false; 6580 6581 if (!isIntegerLikeType(FD->getType(), Context, VMContext)) 6582 return false; 6583 6584 // Only allow at most one field in a structure. This doesn't match the 6585 // wording above, but follows gcc in situations with a field following an 6586 // empty structure. 6587 if (!RD->isUnion()) { 6588 if (HadField) 6589 return false; 6590 6591 HadField = true; 6592 } 6593 } 6594 6595 return true; 6596 } 6597 6598 ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy, bool isVariadic, 6599 unsigned functionCallConv) const { 6600 6601 // Variadic functions should always marshal to the base standard. 6602 bool IsAAPCS_VFP = 6603 !isVariadic && isEffectivelyAAPCS_VFP(functionCallConv, /* AAPCS16 */ true); 6604 6605 if (RetTy->isVoidType()) 6606 return ABIArgInfo::getIgnore(); 6607 6608 if (const VectorType *VT = RetTy->getAs<VectorType>()) { 6609 // Large vector types should be returned via memory. 6610 if (getContext().getTypeSize(RetTy) > 128) 6611 return getNaturalAlignIndirect(RetTy); 6612 // TODO: FP16/BF16 vectors should be converted to integer vectors 6613 // This check is similar to isIllegalVectorType - refactor? 6614 if ((!getTarget().hasLegalHalfType() && 6615 (VT->getElementType()->isFloat16Type() || 6616 VT->getElementType()->isHalfType())) || 6617 (IsFloatABISoftFP && 6618 VT->getElementType()->isBFloat16Type())) 6619 return coerceIllegalVector(RetTy); 6620 } 6621 6622 if (!isAggregateTypeForABI(RetTy)) { 6623 // Treat an enum type as its underlying type. 6624 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 6625 RetTy = EnumTy->getDecl()->getIntegerType(); 6626 6627 if (const auto *EIT = RetTy->getAs<ExtIntType>()) 6628 if (EIT->getNumBits() > 64) 6629 return getNaturalAlignIndirect(RetTy, /*ByVal=*/false); 6630 6631 return isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy) 6632 : ABIArgInfo::getDirect(); 6633 } 6634 6635 // Are we following APCS? 6636 if (getABIKind() == APCS) { 6637 if (isEmptyRecord(getContext(), RetTy, false)) 6638 return ABIArgInfo::getIgnore(); 6639 6640 // Complex types are all returned as packed integers. 6641 // 6642 // FIXME: Consider using 2 x vector types if the back end handles them 6643 // correctly. 6644 if (RetTy->isAnyComplexType()) 6645 return ABIArgInfo::getDirect(llvm::IntegerType::get( 6646 getVMContext(), getContext().getTypeSize(RetTy))); 6647 6648 // Integer like structures are returned in r0. 6649 if (isIntegerLikeType(RetTy, getContext(), getVMContext())) { 6650 // Return in the smallest viable integer type. 6651 uint64_t Size = getContext().getTypeSize(RetTy); 6652 if (Size <= 8) 6653 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext())); 6654 if (Size <= 16) 6655 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext())); 6656 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext())); 6657 } 6658 6659 // Otherwise return in memory. 6660 return getNaturalAlignIndirect(RetTy); 6661 } 6662 6663 // Otherwise this is an AAPCS variant. 6664 6665 if (isEmptyRecord(getContext(), RetTy, true)) 6666 return ABIArgInfo::getIgnore(); 6667 6668 // Check for homogeneous aggregates with AAPCS-VFP. 6669 if (IsAAPCS_VFP) { 6670 const Type *Base = nullptr; 6671 uint64_t Members = 0; 6672 if (isHomogeneousAggregate(RetTy, Base, Members)) 6673 return classifyHomogeneousAggregate(RetTy, Base, Members); 6674 } 6675 6676 // Aggregates <= 4 bytes are returned in r0; other aggregates 6677 // are returned indirectly. 6678 uint64_t Size = getContext().getTypeSize(RetTy); 6679 if (Size <= 32) { 6680 // On RenderScript, coerce Aggregates <= 4 bytes to an integer array of 6681 // same size and alignment. 6682 if (getTarget().isRenderScriptTarget()) { 6683 return coerceToIntArray(RetTy, getContext(), getVMContext()); 6684 } 6685 if (getDataLayout().isBigEndian()) 6686 // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4) 6687 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext())); 6688 6689 // Return in the smallest viable integer type. 6690 if (Size <= 8) 6691 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext())); 6692 if (Size <= 16) 6693 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext())); 6694 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext())); 6695 } else if (Size <= 128 && getABIKind() == AAPCS16_VFP) { 6696 llvm::Type *Int32Ty = llvm::Type::getInt32Ty(getVMContext()); 6697 llvm::Type *CoerceTy = 6698 llvm::ArrayType::get(Int32Ty, llvm::alignTo(Size, 32) / 32); 6699 return ABIArgInfo::getDirect(CoerceTy); 6700 } 6701 6702 return getNaturalAlignIndirect(RetTy); 6703 } 6704 6705 /// isIllegalVector - check whether Ty is an illegal vector type. 6706 bool ARMABIInfo::isIllegalVectorType(QualType Ty) const { 6707 if (const VectorType *VT = Ty->getAs<VectorType> ()) { 6708 // On targets that don't support half, fp16 or bfloat, they are expanded 6709 // into float, and we don't want the ABI to depend on whether or not they 6710 // are supported in hardware. Thus return false to coerce vectors of these 6711 // types into integer vectors. 6712 // We do not depend on hasLegalHalfType for bfloat as it is a 6713 // separate IR type. 6714 if ((!getTarget().hasLegalHalfType() && 6715 (VT->getElementType()->isFloat16Type() || 6716 VT->getElementType()->isHalfType())) || 6717 (IsFloatABISoftFP && 6718 VT->getElementType()->isBFloat16Type())) 6719 return true; 6720 if (isAndroid()) { 6721 // Android shipped using Clang 3.1, which supported a slightly different 6722 // vector ABI. The primary differences were that 3-element vector types 6723 // were legal, and so were sub 32-bit vectors (i.e. <2 x i8>). This path 6724 // accepts that legacy behavior for Android only. 6725 // Check whether VT is legal. 6726 unsigned NumElements = VT->getNumElements(); 6727 // NumElements should be power of 2 or equal to 3. 6728 if (!llvm::isPowerOf2_32(NumElements) && NumElements != 3) 6729 return true; 6730 } else { 6731 // Check whether VT is legal. 6732 unsigned NumElements = VT->getNumElements(); 6733 uint64_t Size = getContext().getTypeSize(VT); 6734 // NumElements should be power of 2. 6735 if (!llvm::isPowerOf2_32(NumElements)) 6736 return true; 6737 // Size should be greater than 32 bits. 6738 return Size <= 32; 6739 } 6740 } 6741 return false; 6742 } 6743 6744 /// Return true if a type contains any 16-bit floating point vectors 6745 bool ARMABIInfo::containsAnyFP16Vectors(QualType Ty) const { 6746 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) { 6747 uint64_t NElements = AT->getSize().getZExtValue(); 6748 if (NElements == 0) 6749 return false; 6750 return containsAnyFP16Vectors(AT->getElementType()); 6751 } else if (const RecordType *RT = Ty->getAs<RecordType>()) { 6752 const RecordDecl *RD = RT->getDecl(); 6753 6754 // If this is a C++ record, check the bases first. 6755 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 6756 if (llvm::any_of(CXXRD->bases(), [this](const CXXBaseSpecifier &B) { 6757 return containsAnyFP16Vectors(B.getType()); 6758 })) 6759 return true; 6760 6761 if (llvm::any_of(RD->fields(), [this](FieldDecl *FD) { 6762 return FD && containsAnyFP16Vectors(FD->getType()); 6763 })) 6764 return true; 6765 6766 return false; 6767 } else { 6768 if (const VectorType *VT = Ty->getAs<VectorType>()) 6769 return (VT->getElementType()->isFloat16Type() || 6770 VT->getElementType()->isBFloat16Type() || 6771 VT->getElementType()->isHalfType()); 6772 return false; 6773 } 6774 } 6775 6776 bool ARMABIInfo::isLegalVectorTypeForSwift(CharUnits vectorSize, 6777 llvm::Type *eltTy, 6778 unsigned numElts) const { 6779 if (!llvm::isPowerOf2_32(numElts)) 6780 return false; 6781 unsigned size = getDataLayout().getTypeStoreSizeInBits(eltTy); 6782 if (size > 64) 6783 return false; 6784 if (vectorSize.getQuantity() != 8 && 6785 (vectorSize.getQuantity() != 16 || numElts == 1)) 6786 return false; 6787 return true; 6788 } 6789 6790 bool ARMABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const { 6791 // Homogeneous aggregates for AAPCS-VFP must have base types of float, 6792 // double, or 64-bit or 128-bit vectors. 6793 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) { 6794 if (BT->getKind() == BuiltinType::Float || 6795 BT->getKind() == BuiltinType::Double || 6796 BT->getKind() == BuiltinType::LongDouble) 6797 return true; 6798 } else if (const VectorType *VT = Ty->getAs<VectorType>()) { 6799 unsigned VecSize = getContext().getTypeSize(VT); 6800 if (VecSize == 64 || VecSize == 128) 6801 return true; 6802 } 6803 return false; 6804 } 6805 6806 bool ARMABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base, 6807 uint64_t Members) const { 6808 return Members <= 4; 6809 } 6810 6811 bool ARMABIInfo::isEffectivelyAAPCS_VFP(unsigned callConvention, 6812 bool acceptHalf) const { 6813 // Give precedence to user-specified calling conventions. 6814 if (callConvention != llvm::CallingConv::C) 6815 return (callConvention == llvm::CallingConv::ARM_AAPCS_VFP); 6816 else 6817 return (getABIKind() == AAPCS_VFP) || 6818 (acceptHalf && (getABIKind() == AAPCS16_VFP)); 6819 } 6820 6821 Address ARMABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 6822 QualType Ty) const { 6823 CharUnits SlotSize = CharUnits::fromQuantity(4); 6824 6825 // Empty records are ignored for parameter passing purposes. 6826 if (isEmptyRecord(getContext(), Ty, true)) { 6827 Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize); 6828 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty)); 6829 return Addr; 6830 } 6831 6832 CharUnits TySize = getContext().getTypeSizeInChars(Ty); 6833 CharUnits TyAlignForABI = getContext().getTypeUnadjustedAlignInChars(Ty); 6834 6835 // Use indirect if size of the illegal vector is bigger than 16 bytes. 6836 bool IsIndirect = false; 6837 const Type *Base = nullptr; 6838 uint64_t Members = 0; 6839 if (TySize > CharUnits::fromQuantity(16) && isIllegalVectorType(Ty)) { 6840 IsIndirect = true; 6841 6842 // ARMv7k passes structs bigger than 16 bytes indirectly, in space 6843 // allocated by the caller. 6844 } else if (TySize > CharUnits::fromQuantity(16) && 6845 getABIKind() == ARMABIInfo::AAPCS16_VFP && 6846 !isHomogeneousAggregate(Ty, Base, Members)) { 6847 IsIndirect = true; 6848 6849 // Otherwise, bound the type's ABI alignment. 6850 // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for 6851 // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte. 6852 // Our callers should be prepared to handle an under-aligned address. 6853 } else if (getABIKind() == ARMABIInfo::AAPCS_VFP || 6854 getABIKind() == ARMABIInfo::AAPCS) { 6855 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4)); 6856 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(8)); 6857 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) { 6858 // ARMv7k allows type alignment up to 16 bytes. 6859 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4)); 6860 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(16)); 6861 } else { 6862 TyAlignForABI = CharUnits::fromQuantity(4); 6863 } 6864 6865 TypeInfoChars TyInfo(TySize, TyAlignForABI, false); 6866 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TyInfo, 6867 SlotSize, /*AllowHigherAlign*/ true); 6868 } 6869 6870 //===----------------------------------------------------------------------===// 6871 // NVPTX ABI Implementation 6872 //===----------------------------------------------------------------------===// 6873 6874 namespace { 6875 6876 class NVPTXTargetCodeGenInfo; 6877 6878 class NVPTXABIInfo : public ABIInfo { 6879 NVPTXTargetCodeGenInfo &CGInfo; 6880 6881 public: 6882 NVPTXABIInfo(CodeGenTypes &CGT, NVPTXTargetCodeGenInfo &Info) 6883 : ABIInfo(CGT), CGInfo(Info) {} 6884 6885 ABIArgInfo classifyReturnType(QualType RetTy) const; 6886 ABIArgInfo classifyArgumentType(QualType Ty) const; 6887 6888 void computeInfo(CGFunctionInfo &FI) const override; 6889 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 6890 QualType Ty) const override; 6891 bool isUnsupportedType(QualType T) const; 6892 ABIArgInfo coerceToIntArrayWithLimit(QualType Ty, unsigned MaxSize) const; 6893 }; 6894 6895 class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo { 6896 public: 6897 NVPTXTargetCodeGenInfo(CodeGenTypes &CGT) 6898 : TargetCodeGenInfo(std::make_unique<NVPTXABIInfo>(CGT, *this)) {} 6899 6900 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 6901 CodeGen::CodeGenModule &M) const override; 6902 bool shouldEmitStaticExternCAliases() const override; 6903 6904 llvm::Type *getCUDADeviceBuiltinSurfaceDeviceType() const override { 6905 // On the device side, surface reference is represented as an object handle 6906 // in 64-bit integer. 6907 return llvm::Type::getInt64Ty(getABIInfo().getVMContext()); 6908 } 6909 6910 llvm::Type *getCUDADeviceBuiltinTextureDeviceType() const override { 6911 // On the device side, texture reference is represented as an object handle 6912 // in 64-bit integer. 6913 return llvm::Type::getInt64Ty(getABIInfo().getVMContext()); 6914 } 6915 6916 bool emitCUDADeviceBuiltinSurfaceDeviceCopy(CodeGenFunction &CGF, LValue Dst, 6917 LValue Src) const override { 6918 emitBuiltinSurfTexDeviceCopy(CGF, Dst, Src); 6919 return true; 6920 } 6921 6922 bool emitCUDADeviceBuiltinTextureDeviceCopy(CodeGenFunction &CGF, LValue Dst, 6923 LValue Src) const override { 6924 emitBuiltinSurfTexDeviceCopy(CGF, Dst, Src); 6925 return true; 6926 } 6927 6928 private: 6929 // Adds a NamedMDNode with GV, Name, and Operand as operands, and adds the 6930 // resulting MDNode to the nvvm.annotations MDNode. 6931 static void addNVVMMetadata(llvm::GlobalValue *GV, StringRef Name, 6932 int Operand); 6933 6934 static void emitBuiltinSurfTexDeviceCopy(CodeGenFunction &CGF, LValue Dst, 6935 LValue Src) { 6936 llvm::Value *Handle = nullptr; 6937 llvm::Constant *C = 6938 llvm::dyn_cast<llvm::Constant>(Src.getAddress(CGF).getPointer()); 6939 // Lookup `addrspacecast` through the constant pointer if any. 6940 if (auto *ASC = llvm::dyn_cast_or_null<llvm::AddrSpaceCastOperator>(C)) 6941 C = llvm::cast<llvm::Constant>(ASC->getPointerOperand()); 6942 if (auto *GV = llvm::dyn_cast_or_null<llvm::GlobalVariable>(C)) { 6943 // Load the handle from the specific global variable using 6944 // `nvvm.texsurf.handle.internal` intrinsic. 6945 Handle = CGF.EmitRuntimeCall( 6946 CGF.CGM.getIntrinsic(llvm::Intrinsic::nvvm_texsurf_handle_internal, 6947 {GV->getType()}), 6948 {GV}, "texsurf_handle"); 6949 } else 6950 Handle = CGF.EmitLoadOfScalar(Src, SourceLocation()); 6951 CGF.EmitStoreOfScalar(Handle, Dst); 6952 } 6953 }; 6954 6955 /// Checks if the type is unsupported directly by the current target. 6956 bool NVPTXABIInfo::isUnsupportedType(QualType T) const { 6957 ASTContext &Context = getContext(); 6958 if (!Context.getTargetInfo().hasFloat16Type() && T->isFloat16Type()) 6959 return true; 6960 if (!Context.getTargetInfo().hasFloat128Type() && 6961 (T->isFloat128Type() || 6962 (T->isRealFloatingType() && Context.getTypeSize(T) == 128))) 6963 return true; 6964 if (const auto *EIT = T->getAs<ExtIntType>()) 6965 return EIT->getNumBits() > 6966 (Context.getTargetInfo().hasInt128Type() ? 128U : 64U); 6967 if (!Context.getTargetInfo().hasInt128Type() && T->isIntegerType() && 6968 Context.getTypeSize(T) > 64U) 6969 return true; 6970 if (const auto *AT = T->getAsArrayTypeUnsafe()) 6971 return isUnsupportedType(AT->getElementType()); 6972 const auto *RT = T->getAs<RecordType>(); 6973 if (!RT) 6974 return false; 6975 const RecordDecl *RD = RT->getDecl(); 6976 6977 // If this is a C++ record, check the bases first. 6978 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 6979 for (const CXXBaseSpecifier &I : CXXRD->bases()) 6980 if (isUnsupportedType(I.getType())) 6981 return true; 6982 6983 for (const FieldDecl *I : RD->fields()) 6984 if (isUnsupportedType(I->getType())) 6985 return true; 6986 return false; 6987 } 6988 6989 /// Coerce the given type into an array with maximum allowed size of elements. 6990 ABIArgInfo NVPTXABIInfo::coerceToIntArrayWithLimit(QualType Ty, 6991 unsigned MaxSize) const { 6992 // Alignment and Size are measured in bits. 6993 const uint64_t Size = getContext().getTypeSize(Ty); 6994 const uint64_t Alignment = getContext().getTypeAlign(Ty); 6995 const unsigned Div = std::min<unsigned>(MaxSize, Alignment); 6996 llvm::Type *IntType = llvm::Type::getIntNTy(getVMContext(), Div); 6997 const uint64_t NumElements = (Size + Div - 1) / Div; 6998 return ABIArgInfo::getDirect(llvm::ArrayType::get(IntType, NumElements)); 6999 } 7000 7001 ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const { 7002 if (RetTy->isVoidType()) 7003 return ABIArgInfo::getIgnore(); 7004 7005 if (getContext().getLangOpts().OpenMP && 7006 getContext().getLangOpts().OpenMPIsDevice && isUnsupportedType(RetTy)) 7007 return coerceToIntArrayWithLimit(RetTy, 64); 7008 7009 // note: this is different from default ABI 7010 if (!RetTy->isScalarType()) 7011 return ABIArgInfo::getDirect(); 7012 7013 // Treat an enum type as its underlying type. 7014 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 7015 RetTy = EnumTy->getDecl()->getIntegerType(); 7016 7017 return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy) 7018 : ABIArgInfo::getDirect()); 7019 } 7020 7021 ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const { 7022 // Treat an enum type as its underlying type. 7023 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 7024 Ty = EnumTy->getDecl()->getIntegerType(); 7025 7026 // Return aggregates type as indirect by value 7027 if (isAggregateTypeForABI(Ty)) { 7028 // Under CUDA device compilation, tex/surf builtin types are replaced with 7029 // object types and passed directly. 7030 if (getContext().getLangOpts().CUDAIsDevice) { 7031 if (Ty->isCUDADeviceBuiltinSurfaceType()) 7032 return ABIArgInfo::getDirect( 7033 CGInfo.getCUDADeviceBuiltinSurfaceDeviceType()); 7034 if (Ty->isCUDADeviceBuiltinTextureType()) 7035 return ABIArgInfo::getDirect( 7036 CGInfo.getCUDADeviceBuiltinTextureDeviceType()); 7037 } 7038 return getNaturalAlignIndirect(Ty, /* byval */ true); 7039 } 7040 7041 if (const auto *EIT = Ty->getAs<ExtIntType>()) { 7042 if ((EIT->getNumBits() > 128) || 7043 (!getContext().getTargetInfo().hasInt128Type() && 7044 EIT->getNumBits() > 64)) 7045 return getNaturalAlignIndirect(Ty, /* byval */ true); 7046 } 7047 7048 return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty) 7049 : ABIArgInfo::getDirect()); 7050 } 7051 7052 void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const { 7053 if (!getCXXABI().classifyReturnType(FI)) 7054 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 7055 for (auto &I : FI.arguments()) 7056 I.info = classifyArgumentType(I.type); 7057 7058 // Always honor user-specified calling convention. 7059 if (FI.getCallingConvention() != llvm::CallingConv::C) 7060 return; 7061 7062 FI.setEffectiveCallingConvention(getRuntimeCC()); 7063 } 7064 7065 Address NVPTXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 7066 QualType Ty) const { 7067 llvm_unreachable("NVPTX does not support varargs"); 7068 } 7069 7070 void NVPTXTargetCodeGenInfo::setTargetAttributes( 7071 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const { 7072 if (GV->isDeclaration()) 7073 return; 7074 const VarDecl *VD = dyn_cast_or_null<VarDecl>(D); 7075 if (VD) { 7076 if (M.getLangOpts().CUDA) { 7077 if (VD->getType()->isCUDADeviceBuiltinSurfaceType()) 7078 addNVVMMetadata(GV, "surface", 1); 7079 else if (VD->getType()->isCUDADeviceBuiltinTextureType()) 7080 addNVVMMetadata(GV, "texture", 1); 7081 return; 7082 } 7083 } 7084 7085 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D); 7086 if (!FD) return; 7087 7088 llvm::Function *F = cast<llvm::Function>(GV); 7089 7090 // Perform special handling in OpenCL mode 7091 if (M.getLangOpts().OpenCL) { 7092 // Use OpenCL function attributes to check for kernel functions 7093 // By default, all functions are device functions 7094 if (FD->hasAttr<OpenCLKernelAttr>()) { 7095 // OpenCL __kernel functions get kernel metadata 7096 // Create !{<func-ref>, metadata !"kernel", i32 1} node 7097 addNVVMMetadata(F, "kernel", 1); 7098 // And kernel functions are not subject to inlining 7099 F->addFnAttr(llvm::Attribute::NoInline); 7100 } 7101 } 7102 7103 // Perform special handling in CUDA mode. 7104 if (M.getLangOpts().CUDA) { 7105 // CUDA __global__ functions get a kernel metadata entry. Since 7106 // __global__ functions cannot be called from the device, we do not 7107 // need to set the noinline attribute. 7108 if (FD->hasAttr<CUDAGlobalAttr>()) { 7109 // Create !{<func-ref>, metadata !"kernel", i32 1} node 7110 addNVVMMetadata(F, "kernel", 1); 7111 } 7112 if (CUDALaunchBoundsAttr *Attr = FD->getAttr<CUDALaunchBoundsAttr>()) { 7113 // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node 7114 llvm::APSInt MaxThreads(32); 7115 MaxThreads = Attr->getMaxThreads()->EvaluateKnownConstInt(M.getContext()); 7116 if (MaxThreads > 0) 7117 addNVVMMetadata(F, "maxntidx", MaxThreads.getExtValue()); 7118 7119 // min blocks is an optional argument for CUDALaunchBoundsAttr. If it was 7120 // not specified in __launch_bounds__ or if the user specified a 0 value, 7121 // we don't have to add a PTX directive. 7122 if (Attr->getMinBlocks()) { 7123 llvm::APSInt MinBlocks(32); 7124 MinBlocks = Attr->getMinBlocks()->EvaluateKnownConstInt(M.getContext()); 7125 if (MinBlocks > 0) 7126 // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node 7127 addNVVMMetadata(F, "minctasm", MinBlocks.getExtValue()); 7128 } 7129 } 7130 } 7131 } 7132 7133 void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::GlobalValue *GV, 7134 StringRef Name, int Operand) { 7135 llvm::Module *M = GV->getParent(); 7136 llvm::LLVMContext &Ctx = M->getContext(); 7137 7138 // Get "nvvm.annotations" metadata node 7139 llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations"); 7140 7141 llvm::Metadata *MDVals[] = { 7142 llvm::ConstantAsMetadata::get(GV), llvm::MDString::get(Ctx, Name), 7143 llvm::ConstantAsMetadata::get( 7144 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand))}; 7145 // Append metadata to nvvm.annotations 7146 MD->addOperand(llvm::MDNode::get(Ctx, MDVals)); 7147 } 7148 7149 bool NVPTXTargetCodeGenInfo::shouldEmitStaticExternCAliases() const { 7150 return false; 7151 } 7152 } 7153 7154 //===----------------------------------------------------------------------===// 7155 // SystemZ ABI Implementation 7156 //===----------------------------------------------------------------------===// 7157 7158 namespace { 7159 7160 class SystemZABIInfo : public SwiftABIInfo { 7161 bool HasVector; 7162 bool IsSoftFloatABI; 7163 7164 public: 7165 SystemZABIInfo(CodeGenTypes &CGT, bool HV, bool SF) 7166 : SwiftABIInfo(CGT), HasVector(HV), IsSoftFloatABI(SF) {} 7167 7168 bool isPromotableIntegerTypeForABI(QualType Ty) const; 7169 bool isCompoundType(QualType Ty) const; 7170 bool isVectorArgumentType(QualType Ty) const; 7171 bool isFPArgumentType(QualType Ty) const; 7172 QualType GetSingleElementType(QualType Ty) const; 7173 7174 ABIArgInfo classifyReturnType(QualType RetTy) const; 7175 ABIArgInfo classifyArgumentType(QualType ArgTy) const; 7176 7177 void computeInfo(CGFunctionInfo &FI) const override { 7178 if (!getCXXABI().classifyReturnType(FI)) 7179 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 7180 for (auto &I : FI.arguments()) 7181 I.info = classifyArgumentType(I.type); 7182 } 7183 7184 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 7185 QualType Ty) const override; 7186 7187 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars, 7188 bool asReturnValue) const override { 7189 return occupiesMoreThan(CGT, scalars, /*total*/ 4); 7190 } 7191 bool isSwiftErrorInRegister() const override { 7192 return false; 7193 } 7194 }; 7195 7196 class SystemZTargetCodeGenInfo : public TargetCodeGenInfo { 7197 public: 7198 SystemZTargetCodeGenInfo(CodeGenTypes &CGT, bool HasVector, bool SoftFloatABI) 7199 : TargetCodeGenInfo( 7200 std::make_unique<SystemZABIInfo>(CGT, HasVector, SoftFloatABI)) {} 7201 7202 llvm::Value *testFPKind(llvm::Value *V, unsigned BuiltinID, 7203 CGBuilderTy &Builder, 7204 CodeGenModule &CGM) const override { 7205 assert(V->getType()->isFloatingPointTy() && "V should have an FP type."); 7206 // Only use TDC in constrained FP mode. 7207 if (!Builder.getIsFPConstrained()) 7208 return nullptr; 7209 7210 llvm::Type *Ty = V->getType(); 7211 if (Ty->isFloatTy() || Ty->isDoubleTy() || Ty->isFP128Ty()) { 7212 llvm::Module &M = CGM.getModule(); 7213 auto &Ctx = M.getContext(); 7214 llvm::Function *TDCFunc = 7215 llvm::Intrinsic::getDeclaration(&M, llvm::Intrinsic::s390_tdc, Ty); 7216 unsigned TDCBits = 0; 7217 switch (BuiltinID) { 7218 case Builtin::BI__builtin_isnan: 7219 TDCBits = 0xf; 7220 break; 7221 case Builtin::BIfinite: 7222 case Builtin::BI__finite: 7223 case Builtin::BIfinitef: 7224 case Builtin::BI__finitef: 7225 case Builtin::BIfinitel: 7226 case Builtin::BI__finitel: 7227 case Builtin::BI__builtin_isfinite: 7228 TDCBits = 0xfc0; 7229 break; 7230 case Builtin::BI__builtin_isinf: 7231 TDCBits = 0x30; 7232 break; 7233 default: 7234 break; 7235 } 7236 if (TDCBits) 7237 return Builder.CreateCall( 7238 TDCFunc, 7239 {V, llvm::ConstantInt::get(llvm::Type::getInt64Ty(Ctx), TDCBits)}); 7240 } 7241 return nullptr; 7242 } 7243 }; 7244 } 7245 7246 bool SystemZABIInfo::isPromotableIntegerTypeForABI(QualType Ty) const { 7247 // Treat an enum type as its underlying type. 7248 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 7249 Ty = EnumTy->getDecl()->getIntegerType(); 7250 7251 // Promotable integer types are required to be promoted by the ABI. 7252 if (ABIInfo::isPromotableIntegerTypeForABI(Ty)) 7253 return true; 7254 7255 if (const auto *EIT = Ty->getAs<ExtIntType>()) 7256 if (EIT->getNumBits() < 64) 7257 return true; 7258 7259 // 32-bit values must also be promoted. 7260 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) 7261 switch (BT->getKind()) { 7262 case BuiltinType::Int: 7263 case BuiltinType::UInt: 7264 return true; 7265 default: 7266 return false; 7267 } 7268 return false; 7269 } 7270 7271 bool SystemZABIInfo::isCompoundType(QualType Ty) const { 7272 return (Ty->isAnyComplexType() || 7273 Ty->isVectorType() || 7274 isAggregateTypeForABI(Ty)); 7275 } 7276 7277 bool SystemZABIInfo::isVectorArgumentType(QualType Ty) const { 7278 return (HasVector && 7279 Ty->isVectorType() && 7280 getContext().getTypeSize(Ty) <= 128); 7281 } 7282 7283 bool SystemZABIInfo::isFPArgumentType(QualType Ty) const { 7284 if (IsSoftFloatABI) 7285 return false; 7286 7287 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) 7288 switch (BT->getKind()) { 7289 case BuiltinType::Float: 7290 case BuiltinType::Double: 7291 return true; 7292 default: 7293 return false; 7294 } 7295 7296 return false; 7297 } 7298 7299 QualType SystemZABIInfo::GetSingleElementType(QualType Ty) const { 7300 const RecordType *RT = Ty->getAs<RecordType>(); 7301 7302 if (RT && RT->isStructureOrClassType()) { 7303 const RecordDecl *RD = RT->getDecl(); 7304 QualType Found; 7305 7306 // If this is a C++ record, check the bases first. 7307 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 7308 for (const auto &I : CXXRD->bases()) { 7309 QualType Base = I.getType(); 7310 7311 // Empty bases don't affect things either way. 7312 if (isEmptyRecord(getContext(), Base, true)) 7313 continue; 7314 7315 if (!Found.isNull()) 7316 return Ty; 7317 Found = GetSingleElementType(Base); 7318 } 7319 7320 // Check the fields. 7321 for (const auto *FD : RD->fields()) { 7322 // For compatibility with GCC, ignore empty bitfields in C++ mode. 7323 // Unlike isSingleElementStruct(), empty structure and array fields 7324 // do count. So do anonymous bitfields that aren't zero-sized. 7325 if (getContext().getLangOpts().CPlusPlus && 7326 FD->isZeroLengthBitField(getContext())) 7327 continue; 7328 // Like isSingleElementStruct(), ignore C++20 empty data members. 7329 if (FD->hasAttr<NoUniqueAddressAttr>() && 7330 isEmptyRecord(getContext(), FD->getType(), true)) 7331 continue; 7332 7333 // Unlike isSingleElementStruct(), arrays do not count. 7334 // Nested structures still do though. 7335 if (!Found.isNull()) 7336 return Ty; 7337 Found = GetSingleElementType(FD->getType()); 7338 } 7339 7340 // Unlike isSingleElementStruct(), trailing padding is allowed. 7341 // An 8-byte aligned struct s { float f; } is passed as a double. 7342 if (!Found.isNull()) 7343 return Found; 7344 } 7345 7346 return Ty; 7347 } 7348 7349 Address SystemZABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 7350 QualType Ty) const { 7351 // Assume that va_list type is correct; should be pointer to LLVM type: 7352 // struct { 7353 // i64 __gpr; 7354 // i64 __fpr; 7355 // i8 *__overflow_arg_area; 7356 // i8 *__reg_save_area; 7357 // }; 7358 7359 // Every non-vector argument occupies 8 bytes and is passed by preference 7360 // in either GPRs or FPRs. Vector arguments occupy 8 or 16 bytes and are 7361 // always passed on the stack. 7362 Ty = getContext().getCanonicalType(Ty); 7363 auto TyInfo = getContext().getTypeInfoInChars(Ty); 7364 llvm::Type *ArgTy = CGF.ConvertTypeForMem(Ty); 7365 llvm::Type *DirectTy = ArgTy; 7366 ABIArgInfo AI = classifyArgumentType(Ty); 7367 bool IsIndirect = AI.isIndirect(); 7368 bool InFPRs = false; 7369 bool IsVector = false; 7370 CharUnits UnpaddedSize; 7371 CharUnits DirectAlign; 7372 if (IsIndirect) { 7373 DirectTy = llvm::PointerType::getUnqual(DirectTy); 7374 UnpaddedSize = DirectAlign = CharUnits::fromQuantity(8); 7375 } else { 7376 if (AI.getCoerceToType()) 7377 ArgTy = AI.getCoerceToType(); 7378 InFPRs = (!IsSoftFloatABI && (ArgTy->isFloatTy() || ArgTy->isDoubleTy())); 7379 IsVector = ArgTy->isVectorTy(); 7380 UnpaddedSize = TyInfo.Width; 7381 DirectAlign = TyInfo.Align; 7382 } 7383 CharUnits PaddedSize = CharUnits::fromQuantity(8); 7384 if (IsVector && UnpaddedSize > PaddedSize) 7385 PaddedSize = CharUnits::fromQuantity(16); 7386 assert((UnpaddedSize <= PaddedSize) && "Invalid argument size."); 7387 7388 CharUnits Padding = (PaddedSize - UnpaddedSize); 7389 7390 llvm::Type *IndexTy = CGF.Int64Ty; 7391 llvm::Value *PaddedSizeV = 7392 llvm::ConstantInt::get(IndexTy, PaddedSize.getQuantity()); 7393 7394 if (IsVector) { 7395 // Work out the address of a vector argument on the stack. 7396 // Vector arguments are always passed in the high bits of a 7397 // single (8 byte) or double (16 byte) stack slot. 7398 Address OverflowArgAreaPtr = 7399 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr"); 7400 Address OverflowArgArea = 7401 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"), 7402 TyInfo.Align); 7403 Address MemAddr = 7404 CGF.Builder.CreateElementBitCast(OverflowArgArea, DirectTy, "mem_addr"); 7405 7406 // Update overflow_arg_area_ptr pointer 7407 llvm::Value *NewOverflowArgArea = 7408 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV, 7409 "overflow_arg_area"); 7410 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr); 7411 7412 return MemAddr; 7413 } 7414 7415 assert(PaddedSize.getQuantity() == 8); 7416 7417 unsigned MaxRegs, RegCountField, RegSaveIndex; 7418 CharUnits RegPadding; 7419 if (InFPRs) { 7420 MaxRegs = 4; // Maximum of 4 FPR arguments 7421 RegCountField = 1; // __fpr 7422 RegSaveIndex = 16; // save offset for f0 7423 RegPadding = CharUnits(); // floats are passed in the high bits of an FPR 7424 } else { 7425 MaxRegs = 5; // Maximum of 5 GPR arguments 7426 RegCountField = 0; // __gpr 7427 RegSaveIndex = 2; // save offset for r2 7428 RegPadding = Padding; // values are passed in the low bits of a GPR 7429 } 7430 7431 Address RegCountPtr = 7432 CGF.Builder.CreateStructGEP(VAListAddr, RegCountField, "reg_count_ptr"); 7433 llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count"); 7434 llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs); 7435 llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV, 7436 "fits_in_regs"); 7437 7438 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg"); 7439 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem"); 7440 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end"); 7441 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock); 7442 7443 // Emit code to load the value if it was passed in registers. 7444 CGF.EmitBlock(InRegBlock); 7445 7446 // Work out the address of an argument register. 7447 llvm::Value *ScaledRegCount = 7448 CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count"); 7449 llvm::Value *RegBase = 7450 llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize.getQuantity() 7451 + RegPadding.getQuantity()); 7452 llvm::Value *RegOffset = 7453 CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset"); 7454 Address RegSaveAreaPtr = 7455 CGF.Builder.CreateStructGEP(VAListAddr, 3, "reg_save_area_ptr"); 7456 llvm::Value *RegSaveArea = 7457 CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area"); 7458 Address RawRegAddr(CGF.Builder.CreateGEP(RegSaveArea, RegOffset, 7459 "raw_reg_addr"), 7460 PaddedSize); 7461 Address RegAddr = 7462 CGF.Builder.CreateElementBitCast(RawRegAddr, DirectTy, "reg_addr"); 7463 7464 // Update the register count 7465 llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1); 7466 llvm::Value *NewRegCount = 7467 CGF.Builder.CreateAdd(RegCount, One, "reg_count"); 7468 CGF.Builder.CreateStore(NewRegCount, RegCountPtr); 7469 CGF.EmitBranch(ContBlock); 7470 7471 // Emit code to load the value if it was passed in memory. 7472 CGF.EmitBlock(InMemBlock); 7473 7474 // Work out the address of a stack argument. 7475 Address OverflowArgAreaPtr = 7476 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr"); 7477 Address OverflowArgArea = 7478 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"), 7479 PaddedSize); 7480 Address RawMemAddr = 7481 CGF.Builder.CreateConstByteGEP(OverflowArgArea, Padding, "raw_mem_addr"); 7482 Address MemAddr = 7483 CGF.Builder.CreateElementBitCast(RawMemAddr, DirectTy, "mem_addr"); 7484 7485 // Update overflow_arg_area_ptr pointer 7486 llvm::Value *NewOverflowArgArea = 7487 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV, 7488 "overflow_arg_area"); 7489 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr); 7490 CGF.EmitBranch(ContBlock); 7491 7492 // Return the appropriate result. 7493 CGF.EmitBlock(ContBlock); 7494 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, 7495 MemAddr, InMemBlock, "va_arg.addr"); 7496 7497 if (IsIndirect) 7498 ResAddr = Address(CGF.Builder.CreateLoad(ResAddr, "indirect_arg"), 7499 TyInfo.Align); 7500 7501 return ResAddr; 7502 } 7503 7504 ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const { 7505 if (RetTy->isVoidType()) 7506 return ABIArgInfo::getIgnore(); 7507 if (isVectorArgumentType(RetTy)) 7508 return ABIArgInfo::getDirect(); 7509 if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64) 7510 return getNaturalAlignIndirect(RetTy); 7511 return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy) 7512 : ABIArgInfo::getDirect()); 7513 } 7514 7515 ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const { 7516 // Handle the generic C++ ABI. 7517 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 7518 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 7519 7520 // Integers and enums are extended to full register width. 7521 if (isPromotableIntegerTypeForABI(Ty)) 7522 return ABIArgInfo::getExtend(Ty); 7523 7524 // Handle vector types and vector-like structure types. Note that 7525 // as opposed to float-like structure types, we do not allow any 7526 // padding for vector-like structures, so verify the sizes match. 7527 uint64_t Size = getContext().getTypeSize(Ty); 7528 QualType SingleElementTy = GetSingleElementType(Ty); 7529 if (isVectorArgumentType(SingleElementTy) && 7530 getContext().getTypeSize(SingleElementTy) == Size) 7531 return ABIArgInfo::getDirect(CGT.ConvertType(SingleElementTy)); 7532 7533 // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly. 7534 if (Size != 8 && Size != 16 && Size != 32 && Size != 64) 7535 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 7536 7537 // Handle small structures. 7538 if (const RecordType *RT = Ty->getAs<RecordType>()) { 7539 // Structures with flexible arrays have variable length, so really 7540 // fail the size test above. 7541 const RecordDecl *RD = RT->getDecl(); 7542 if (RD->hasFlexibleArrayMember()) 7543 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 7544 7545 // The structure is passed as an unextended integer, a float, or a double. 7546 llvm::Type *PassTy; 7547 if (isFPArgumentType(SingleElementTy)) { 7548 assert(Size == 32 || Size == 64); 7549 if (Size == 32) 7550 PassTy = llvm::Type::getFloatTy(getVMContext()); 7551 else 7552 PassTy = llvm::Type::getDoubleTy(getVMContext()); 7553 } else 7554 PassTy = llvm::IntegerType::get(getVMContext(), Size); 7555 return ABIArgInfo::getDirect(PassTy); 7556 } 7557 7558 // Non-structure compounds are passed indirectly. 7559 if (isCompoundType(Ty)) 7560 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 7561 7562 return ABIArgInfo::getDirect(nullptr); 7563 } 7564 7565 //===----------------------------------------------------------------------===// 7566 // MSP430 ABI Implementation 7567 //===----------------------------------------------------------------------===// 7568 7569 namespace { 7570 7571 class MSP430ABIInfo : public DefaultABIInfo { 7572 static ABIArgInfo complexArgInfo() { 7573 ABIArgInfo Info = ABIArgInfo::getDirect(); 7574 Info.setCanBeFlattened(false); 7575 return Info; 7576 } 7577 7578 public: 7579 MSP430ABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {} 7580 7581 ABIArgInfo classifyReturnType(QualType RetTy) const { 7582 if (RetTy->isAnyComplexType()) 7583 return complexArgInfo(); 7584 7585 return DefaultABIInfo::classifyReturnType(RetTy); 7586 } 7587 7588 ABIArgInfo classifyArgumentType(QualType RetTy) const { 7589 if (RetTy->isAnyComplexType()) 7590 return complexArgInfo(); 7591 7592 return DefaultABIInfo::classifyArgumentType(RetTy); 7593 } 7594 7595 // Just copy the original implementations because 7596 // DefaultABIInfo::classify{Return,Argument}Type() are not virtual 7597 void computeInfo(CGFunctionInfo &FI) const override { 7598 if (!getCXXABI().classifyReturnType(FI)) 7599 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 7600 for (auto &I : FI.arguments()) 7601 I.info = classifyArgumentType(I.type); 7602 } 7603 7604 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 7605 QualType Ty) const override { 7606 return EmitVAArgInstr(CGF, VAListAddr, Ty, classifyArgumentType(Ty)); 7607 } 7608 }; 7609 7610 class MSP430TargetCodeGenInfo : public TargetCodeGenInfo { 7611 public: 7612 MSP430TargetCodeGenInfo(CodeGenTypes &CGT) 7613 : TargetCodeGenInfo(std::make_unique<MSP430ABIInfo>(CGT)) {} 7614 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 7615 CodeGen::CodeGenModule &M) const override; 7616 }; 7617 7618 } 7619 7620 void MSP430TargetCodeGenInfo::setTargetAttributes( 7621 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const { 7622 if (GV->isDeclaration()) 7623 return; 7624 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) { 7625 const auto *InterruptAttr = FD->getAttr<MSP430InterruptAttr>(); 7626 if (!InterruptAttr) 7627 return; 7628 7629 // Handle 'interrupt' attribute: 7630 llvm::Function *F = cast<llvm::Function>(GV); 7631 7632 // Step 1: Set ISR calling convention. 7633 F->setCallingConv(llvm::CallingConv::MSP430_INTR); 7634 7635 // Step 2: Add attributes goodness. 7636 F->addFnAttr(llvm::Attribute::NoInline); 7637 F->addFnAttr("interrupt", llvm::utostr(InterruptAttr->getNumber())); 7638 } 7639 } 7640 7641 //===----------------------------------------------------------------------===// 7642 // MIPS ABI Implementation. This works for both little-endian and 7643 // big-endian variants. 7644 //===----------------------------------------------------------------------===// 7645 7646 namespace { 7647 class MipsABIInfo : public ABIInfo { 7648 bool IsO32; 7649 unsigned MinABIStackAlignInBytes, StackAlignInBytes; 7650 void CoerceToIntArgs(uint64_t TySize, 7651 SmallVectorImpl<llvm::Type *> &ArgList) const; 7652 llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const; 7653 llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const; 7654 llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const; 7655 public: 7656 MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) : 7657 ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8), 7658 StackAlignInBytes(IsO32 ? 8 : 16) {} 7659 7660 ABIArgInfo classifyReturnType(QualType RetTy) const; 7661 ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const; 7662 void computeInfo(CGFunctionInfo &FI) const override; 7663 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 7664 QualType Ty) const override; 7665 ABIArgInfo extendType(QualType Ty) const; 7666 }; 7667 7668 class MIPSTargetCodeGenInfo : public TargetCodeGenInfo { 7669 unsigned SizeOfUnwindException; 7670 public: 7671 MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32) 7672 : TargetCodeGenInfo(std::make_unique<MipsABIInfo>(CGT, IsO32)), 7673 SizeOfUnwindException(IsO32 ? 24 : 32) {} 7674 7675 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override { 7676 return 29; 7677 } 7678 7679 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 7680 CodeGen::CodeGenModule &CGM) const override { 7681 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D); 7682 if (!FD) return; 7683 llvm::Function *Fn = cast<llvm::Function>(GV); 7684 7685 if (FD->hasAttr<MipsLongCallAttr>()) 7686 Fn->addFnAttr("long-call"); 7687 else if (FD->hasAttr<MipsShortCallAttr>()) 7688 Fn->addFnAttr("short-call"); 7689 7690 // Other attributes do not have a meaning for declarations. 7691 if (GV->isDeclaration()) 7692 return; 7693 7694 if (FD->hasAttr<Mips16Attr>()) { 7695 Fn->addFnAttr("mips16"); 7696 } 7697 else if (FD->hasAttr<NoMips16Attr>()) { 7698 Fn->addFnAttr("nomips16"); 7699 } 7700 7701 if (FD->hasAttr<MicroMipsAttr>()) 7702 Fn->addFnAttr("micromips"); 7703 else if (FD->hasAttr<NoMicroMipsAttr>()) 7704 Fn->addFnAttr("nomicromips"); 7705 7706 const MipsInterruptAttr *Attr = FD->getAttr<MipsInterruptAttr>(); 7707 if (!Attr) 7708 return; 7709 7710 const char *Kind; 7711 switch (Attr->getInterrupt()) { 7712 case MipsInterruptAttr::eic: Kind = "eic"; break; 7713 case MipsInterruptAttr::sw0: Kind = "sw0"; break; 7714 case MipsInterruptAttr::sw1: Kind = "sw1"; break; 7715 case MipsInterruptAttr::hw0: Kind = "hw0"; break; 7716 case MipsInterruptAttr::hw1: Kind = "hw1"; break; 7717 case MipsInterruptAttr::hw2: Kind = "hw2"; break; 7718 case MipsInterruptAttr::hw3: Kind = "hw3"; break; 7719 case MipsInterruptAttr::hw4: Kind = "hw4"; break; 7720 case MipsInterruptAttr::hw5: Kind = "hw5"; break; 7721 } 7722 7723 Fn->addFnAttr("interrupt", Kind); 7724 7725 } 7726 7727 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 7728 llvm::Value *Address) const override; 7729 7730 unsigned getSizeOfUnwindException() const override { 7731 return SizeOfUnwindException; 7732 } 7733 }; 7734 } 7735 7736 void MipsABIInfo::CoerceToIntArgs( 7737 uint64_t TySize, SmallVectorImpl<llvm::Type *> &ArgList) const { 7738 llvm::IntegerType *IntTy = 7739 llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8); 7740 7741 // Add (TySize / MinABIStackAlignInBytes) args of IntTy. 7742 for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N) 7743 ArgList.push_back(IntTy); 7744 7745 // If necessary, add one more integer type to ArgList. 7746 unsigned R = TySize % (MinABIStackAlignInBytes * 8); 7747 7748 if (R) 7749 ArgList.push_back(llvm::IntegerType::get(getVMContext(), R)); 7750 } 7751 7752 // In N32/64, an aligned double precision floating point field is passed in 7753 // a register. 7754 llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const { 7755 SmallVector<llvm::Type*, 8> ArgList, IntArgList; 7756 7757 if (IsO32) { 7758 CoerceToIntArgs(TySize, ArgList); 7759 return llvm::StructType::get(getVMContext(), ArgList); 7760 } 7761 7762 if (Ty->isComplexType()) 7763 return CGT.ConvertType(Ty); 7764 7765 const RecordType *RT = Ty->getAs<RecordType>(); 7766 7767 // Unions/vectors are passed in integer registers. 7768 if (!RT || !RT->isStructureOrClassType()) { 7769 CoerceToIntArgs(TySize, ArgList); 7770 return llvm::StructType::get(getVMContext(), ArgList); 7771 } 7772 7773 const RecordDecl *RD = RT->getDecl(); 7774 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD); 7775 assert(!(TySize % 8) && "Size of structure must be multiple of 8."); 7776 7777 uint64_t LastOffset = 0; 7778 unsigned idx = 0; 7779 llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64); 7780 7781 // Iterate over fields in the struct/class and check if there are any aligned 7782 // double fields. 7783 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 7784 i != e; ++i, ++idx) { 7785 const QualType Ty = i->getType(); 7786 const BuiltinType *BT = Ty->getAs<BuiltinType>(); 7787 7788 if (!BT || BT->getKind() != BuiltinType::Double) 7789 continue; 7790 7791 uint64_t Offset = Layout.getFieldOffset(idx); 7792 if (Offset % 64) // Ignore doubles that are not aligned. 7793 continue; 7794 7795 // Add ((Offset - LastOffset) / 64) args of type i64. 7796 for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j) 7797 ArgList.push_back(I64); 7798 7799 // Add double type. 7800 ArgList.push_back(llvm::Type::getDoubleTy(getVMContext())); 7801 LastOffset = Offset + 64; 7802 } 7803 7804 CoerceToIntArgs(TySize - LastOffset, IntArgList); 7805 ArgList.append(IntArgList.begin(), IntArgList.end()); 7806 7807 return llvm::StructType::get(getVMContext(), ArgList); 7808 } 7809 7810 llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset, 7811 uint64_t Offset) const { 7812 if (OrigOffset + MinABIStackAlignInBytes > Offset) 7813 return nullptr; 7814 7815 return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8); 7816 } 7817 7818 ABIArgInfo 7819 MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const { 7820 Ty = useFirstFieldIfTransparentUnion(Ty); 7821 7822 uint64_t OrigOffset = Offset; 7823 uint64_t TySize = getContext().getTypeSize(Ty); 7824 uint64_t Align = getContext().getTypeAlign(Ty) / 8; 7825 7826 Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes), 7827 (uint64_t)StackAlignInBytes); 7828 unsigned CurrOffset = llvm::alignTo(Offset, Align); 7829 Offset = CurrOffset + llvm::alignTo(TySize, Align * 8) / 8; 7830 7831 if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) { 7832 // Ignore empty aggregates. 7833 if (TySize == 0) 7834 return ABIArgInfo::getIgnore(); 7835 7836 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) { 7837 Offset = OrigOffset + MinABIStackAlignInBytes; 7838 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 7839 } 7840 7841 // If we have reached here, aggregates are passed directly by coercing to 7842 // another structure type. Padding is inserted if the offset of the 7843 // aggregate is unaligned. 7844 ABIArgInfo ArgInfo = 7845 ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0, 7846 getPaddingType(OrigOffset, CurrOffset)); 7847 ArgInfo.setInReg(true); 7848 return ArgInfo; 7849 } 7850 7851 // Treat an enum type as its underlying type. 7852 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 7853 Ty = EnumTy->getDecl()->getIntegerType(); 7854 7855 // Make sure we pass indirectly things that are too large. 7856 if (const auto *EIT = Ty->getAs<ExtIntType>()) 7857 if (EIT->getNumBits() > 128 || 7858 (EIT->getNumBits() > 64 && 7859 !getContext().getTargetInfo().hasInt128Type())) 7860 return getNaturalAlignIndirect(Ty); 7861 7862 // All integral types are promoted to the GPR width. 7863 if (Ty->isIntegralOrEnumerationType()) 7864 return extendType(Ty); 7865 7866 return ABIArgInfo::getDirect( 7867 nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset)); 7868 } 7869 7870 llvm::Type* 7871 MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const { 7872 const RecordType *RT = RetTy->getAs<RecordType>(); 7873 SmallVector<llvm::Type*, 8> RTList; 7874 7875 if (RT && RT->isStructureOrClassType()) { 7876 const RecordDecl *RD = RT->getDecl(); 7877 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD); 7878 unsigned FieldCnt = Layout.getFieldCount(); 7879 7880 // N32/64 returns struct/classes in floating point registers if the 7881 // following conditions are met: 7882 // 1. The size of the struct/class is no larger than 128-bit. 7883 // 2. The struct/class has one or two fields all of which are floating 7884 // point types. 7885 // 3. The offset of the first field is zero (this follows what gcc does). 7886 // 7887 // Any other composite results are returned in integer registers. 7888 // 7889 if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) { 7890 RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end(); 7891 for (; b != e; ++b) { 7892 const BuiltinType *BT = b->getType()->getAs<BuiltinType>(); 7893 7894 if (!BT || !BT->isFloatingPoint()) 7895 break; 7896 7897 RTList.push_back(CGT.ConvertType(b->getType())); 7898 } 7899 7900 if (b == e) 7901 return llvm::StructType::get(getVMContext(), RTList, 7902 RD->hasAttr<PackedAttr>()); 7903 7904 RTList.clear(); 7905 } 7906 } 7907 7908 CoerceToIntArgs(Size, RTList); 7909 return llvm::StructType::get(getVMContext(), RTList); 7910 } 7911 7912 ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const { 7913 uint64_t Size = getContext().getTypeSize(RetTy); 7914 7915 if (RetTy->isVoidType()) 7916 return ABIArgInfo::getIgnore(); 7917 7918 // O32 doesn't treat zero-sized structs differently from other structs. 7919 // However, N32/N64 ignores zero sized return values. 7920 if (!IsO32 && Size == 0) 7921 return ABIArgInfo::getIgnore(); 7922 7923 if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) { 7924 if (Size <= 128) { 7925 if (RetTy->isAnyComplexType()) 7926 return ABIArgInfo::getDirect(); 7927 7928 // O32 returns integer vectors in registers and N32/N64 returns all small 7929 // aggregates in registers. 7930 if (!IsO32 || 7931 (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) { 7932 ABIArgInfo ArgInfo = 7933 ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size)); 7934 ArgInfo.setInReg(true); 7935 return ArgInfo; 7936 } 7937 } 7938 7939 return getNaturalAlignIndirect(RetTy); 7940 } 7941 7942 // Treat an enum type as its underlying type. 7943 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 7944 RetTy = EnumTy->getDecl()->getIntegerType(); 7945 7946 // Make sure we pass indirectly things that are too large. 7947 if (const auto *EIT = RetTy->getAs<ExtIntType>()) 7948 if (EIT->getNumBits() > 128 || 7949 (EIT->getNumBits() > 64 && 7950 !getContext().getTargetInfo().hasInt128Type())) 7951 return getNaturalAlignIndirect(RetTy); 7952 7953 if (isPromotableIntegerTypeForABI(RetTy)) 7954 return ABIArgInfo::getExtend(RetTy); 7955 7956 if ((RetTy->isUnsignedIntegerOrEnumerationType() || 7957 RetTy->isSignedIntegerOrEnumerationType()) && Size == 32 && !IsO32) 7958 return ABIArgInfo::getSignExtend(RetTy); 7959 7960 return ABIArgInfo::getDirect(); 7961 } 7962 7963 void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const { 7964 ABIArgInfo &RetInfo = FI.getReturnInfo(); 7965 if (!getCXXABI().classifyReturnType(FI)) 7966 RetInfo = classifyReturnType(FI.getReturnType()); 7967 7968 // Check if a pointer to an aggregate is passed as a hidden argument. 7969 uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0; 7970 7971 for (auto &I : FI.arguments()) 7972 I.info = classifyArgumentType(I.type, Offset); 7973 } 7974 7975 Address MipsABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 7976 QualType OrigTy) const { 7977 QualType Ty = OrigTy; 7978 7979 // Integer arguments are promoted to 32-bit on O32 and 64-bit on N32/N64. 7980 // Pointers are also promoted in the same way but this only matters for N32. 7981 unsigned SlotSizeInBits = IsO32 ? 32 : 64; 7982 unsigned PtrWidth = getTarget().getPointerWidth(0); 7983 bool DidPromote = false; 7984 if ((Ty->isIntegerType() && 7985 getContext().getIntWidth(Ty) < SlotSizeInBits) || 7986 (Ty->isPointerType() && PtrWidth < SlotSizeInBits)) { 7987 DidPromote = true; 7988 Ty = getContext().getIntTypeForBitwidth(SlotSizeInBits, 7989 Ty->isSignedIntegerType()); 7990 } 7991 7992 auto TyInfo = getContext().getTypeInfoInChars(Ty); 7993 7994 // The alignment of things in the argument area is never larger than 7995 // StackAlignInBytes. 7996 TyInfo.Align = 7997 std::min(TyInfo.Align, CharUnits::fromQuantity(StackAlignInBytes)); 7998 7999 // MinABIStackAlignInBytes is the size of argument slots on the stack. 8000 CharUnits ArgSlotSize = CharUnits::fromQuantity(MinABIStackAlignInBytes); 8001 8002 Address Addr = emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false, 8003 TyInfo, ArgSlotSize, /*AllowHigherAlign*/ true); 8004 8005 8006 // If there was a promotion, "unpromote" into a temporary. 8007 // TODO: can we just use a pointer into a subset of the original slot? 8008 if (DidPromote) { 8009 Address Temp = CGF.CreateMemTemp(OrigTy, "vaarg.promotion-temp"); 8010 llvm::Value *Promoted = CGF.Builder.CreateLoad(Addr); 8011 8012 // Truncate down to the right width. 8013 llvm::Type *IntTy = (OrigTy->isIntegerType() ? Temp.getElementType() 8014 : CGF.IntPtrTy); 8015 llvm::Value *V = CGF.Builder.CreateTrunc(Promoted, IntTy); 8016 if (OrigTy->isPointerType()) 8017 V = CGF.Builder.CreateIntToPtr(V, Temp.getElementType()); 8018 8019 CGF.Builder.CreateStore(V, Temp); 8020 Addr = Temp; 8021 } 8022 8023 return Addr; 8024 } 8025 8026 ABIArgInfo MipsABIInfo::extendType(QualType Ty) const { 8027 int TySize = getContext().getTypeSize(Ty); 8028 8029 // MIPS64 ABI requires unsigned 32 bit integers to be sign extended. 8030 if (Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32) 8031 return ABIArgInfo::getSignExtend(Ty); 8032 8033 return ABIArgInfo::getExtend(Ty); 8034 } 8035 8036 bool 8037 MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 8038 llvm::Value *Address) const { 8039 // This information comes from gcc's implementation, which seems to 8040 // as canonical as it gets. 8041 8042 // Everything on MIPS is 4 bytes. Double-precision FP registers 8043 // are aliased to pairs of single-precision FP registers. 8044 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4); 8045 8046 // 0-31 are the general purpose registers, $0 - $31. 8047 // 32-63 are the floating-point registers, $f0 - $f31. 8048 // 64 and 65 are the multiply/divide registers, $hi and $lo. 8049 // 66 is the (notional, I think) register for signal-handler return. 8050 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65); 8051 8052 // 67-74 are the floating-point status registers, $fcc0 - $fcc7. 8053 // They are one bit wide and ignored here. 8054 8055 // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31. 8056 // (coprocessor 1 is the FP unit) 8057 // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31. 8058 // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31. 8059 // 176-181 are the DSP accumulator registers. 8060 AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181); 8061 return false; 8062 } 8063 8064 //===----------------------------------------------------------------------===// 8065 // M68k ABI Implementation 8066 //===----------------------------------------------------------------------===// 8067 8068 namespace { 8069 8070 class M68kTargetCodeGenInfo : public TargetCodeGenInfo { 8071 public: 8072 M68kTargetCodeGenInfo(CodeGenTypes &CGT) 8073 : TargetCodeGenInfo(std::make_unique<DefaultABIInfo>(CGT)) {} 8074 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 8075 CodeGen::CodeGenModule &M) const override; 8076 }; 8077 8078 } // namespace 8079 8080 void M68kTargetCodeGenInfo::setTargetAttributes( 8081 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const { 8082 if (const auto *FD = dyn_cast_or_null<FunctionDecl>(D)) { 8083 if (const auto *attr = FD->getAttr<M68kInterruptAttr>()) { 8084 // Handle 'interrupt' attribute: 8085 llvm::Function *F = cast<llvm::Function>(GV); 8086 8087 // Step 1: Set ISR calling convention. 8088 F->setCallingConv(llvm::CallingConv::M68k_INTR); 8089 8090 // Step 2: Add attributes goodness. 8091 F->addFnAttr(llvm::Attribute::NoInline); 8092 8093 // Step 3: Emit ISR vector alias. 8094 unsigned Num = attr->getNumber() / 2; 8095 llvm::GlobalAlias::create(llvm::Function::ExternalLinkage, 8096 "__isr_" + Twine(Num), F); 8097 } 8098 } 8099 } 8100 8101 //===----------------------------------------------------------------------===// 8102 // AVR ABI Implementation. 8103 //===----------------------------------------------------------------------===// 8104 8105 namespace { 8106 class AVRTargetCodeGenInfo : public TargetCodeGenInfo { 8107 public: 8108 AVRTargetCodeGenInfo(CodeGenTypes &CGT) 8109 : TargetCodeGenInfo(std::make_unique<DefaultABIInfo>(CGT)) {} 8110 8111 LangAS getGlobalVarAddressSpace(CodeGenModule &CGM, 8112 const VarDecl *D) const override { 8113 // Check if a global/static variable is defined within address space 1 8114 // but not constant. 8115 LangAS AS = D->getType().getAddressSpace(); 8116 if (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 1 && 8117 !D->getType().isConstQualified()) 8118 CGM.getDiags().Report(D->getLocation(), 8119 diag::err_verify_nonconst_addrspace) 8120 << "__flash"; 8121 return TargetCodeGenInfo::getGlobalVarAddressSpace(CGM, D); 8122 } 8123 8124 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 8125 CodeGen::CodeGenModule &CGM) const override { 8126 if (GV->isDeclaration()) 8127 return; 8128 const auto *FD = dyn_cast_or_null<FunctionDecl>(D); 8129 if (!FD) return; 8130 auto *Fn = cast<llvm::Function>(GV); 8131 8132 if (FD->getAttr<AVRInterruptAttr>()) 8133 Fn->addFnAttr("interrupt"); 8134 8135 if (FD->getAttr<AVRSignalAttr>()) 8136 Fn->addFnAttr("signal"); 8137 } 8138 }; 8139 } 8140 8141 //===----------------------------------------------------------------------===// 8142 // TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults. 8143 // Currently subclassed only to implement custom OpenCL C function attribute 8144 // handling. 8145 //===----------------------------------------------------------------------===// 8146 8147 namespace { 8148 8149 class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo { 8150 public: 8151 TCETargetCodeGenInfo(CodeGenTypes &CGT) 8152 : DefaultTargetCodeGenInfo(CGT) {} 8153 8154 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 8155 CodeGen::CodeGenModule &M) const override; 8156 }; 8157 8158 void TCETargetCodeGenInfo::setTargetAttributes( 8159 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const { 8160 if (GV->isDeclaration()) 8161 return; 8162 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D); 8163 if (!FD) return; 8164 8165 llvm::Function *F = cast<llvm::Function>(GV); 8166 8167 if (M.getLangOpts().OpenCL) { 8168 if (FD->hasAttr<OpenCLKernelAttr>()) { 8169 // OpenCL C Kernel functions are not subject to inlining 8170 F->addFnAttr(llvm::Attribute::NoInline); 8171 const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>(); 8172 if (Attr) { 8173 // Convert the reqd_work_group_size() attributes to metadata. 8174 llvm::LLVMContext &Context = F->getContext(); 8175 llvm::NamedMDNode *OpenCLMetadata = 8176 M.getModule().getOrInsertNamedMetadata( 8177 "opencl.kernel_wg_size_info"); 8178 8179 SmallVector<llvm::Metadata *, 5> Operands; 8180 Operands.push_back(llvm::ConstantAsMetadata::get(F)); 8181 8182 Operands.push_back( 8183 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue( 8184 M.Int32Ty, llvm::APInt(32, Attr->getXDim())))); 8185 Operands.push_back( 8186 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue( 8187 M.Int32Ty, llvm::APInt(32, Attr->getYDim())))); 8188 Operands.push_back( 8189 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue( 8190 M.Int32Ty, llvm::APInt(32, Attr->getZDim())))); 8191 8192 // Add a boolean constant operand for "required" (true) or "hint" 8193 // (false) for implementing the work_group_size_hint attr later. 8194 // Currently always true as the hint is not yet implemented. 8195 Operands.push_back( 8196 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getTrue(Context))); 8197 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands)); 8198 } 8199 } 8200 } 8201 } 8202 8203 } 8204 8205 //===----------------------------------------------------------------------===// 8206 // Hexagon ABI Implementation 8207 //===----------------------------------------------------------------------===// 8208 8209 namespace { 8210 8211 class HexagonABIInfo : public DefaultABIInfo { 8212 public: 8213 HexagonABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {} 8214 8215 private: 8216 ABIArgInfo classifyReturnType(QualType RetTy) const; 8217 ABIArgInfo classifyArgumentType(QualType RetTy) const; 8218 ABIArgInfo classifyArgumentType(QualType RetTy, unsigned *RegsLeft) const; 8219 8220 void computeInfo(CGFunctionInfo &FI) const override; 8221 8222 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 8223 QualType Ty) const override; 8224 Address EmitVAArgFromMemory(CodeGenFunction &CFG, Address VAListAddr, 8225 QualType Ty) const; 8226 Address EmitVAArgForHexagon(CodeGenFunction &CFG, Address VAListAddr, 8227 QualType Ty) const; 8228 Address EmitVAArgForHexagonLinux(CodeGenFunction &CFG, Address VAListAddr, 8229 QualType Ty) const; 8230 }; 8231 8232 class HexagonTargetCodeGenInfo : public TargetCodeGenInfo { 8233 public: 8234 HexagonTargetCodeGenInfo(CodeGenTypes &CGT) 8235 : TargetCodeGenInfo(std::make_unique<HexagonABIInfo>(CGT)) {} 8236 8237 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 8238 return 29; 8239 } 8240 8241 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 8242 CodeGen::CodeGenModule &GCM) const override { 8243 if (GV->isDeclaration()) 8244 return; 8245 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D); 8246 if (!FD) 8247 return; 8248 } 8249 }; 8250 8251 } // namespace 8252 8253 void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const { 8254 unsigned RegsLeft = 6; 8255 if (!getCXXABI().classifyReturnType(FI)) 8256 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 8257 for (auto &I : FI.arguments()) 8258 I.info = classifyArgumentType(I.type, &RegsLeft); 8259 } 8260 8261 static bool HexagonAdjustRegsLeft(uint64_t Size, unsigned *RegsLeft) { 8262 assert(Size <= 64 && "Not expecting to pass arguments larger than 64 bits" 8263 " through registers"); 8264 8265 if (*RegsLeft == 0) 8266 return false; 8267 8268 if (Size <= 32) { 8269 (*RegsLeft)--; 8270 return true; 8271 } 8272 8273 if (2 <= (*RegsLeft & (~1U))) { 8274 *RegsLeft = (*RegsLeft & (~1U)) - 2; 8275 return true; 8276 } 8277 8278 // Next available register was r5 but candidate was greater than 32-bits so it 8279 // has to go on the stack. However we still consume r5 8280 if (*RegsLeft == 1) 8281 *RegsLeft = 0; 8282 8283 return false; 8284 } 8285 8286 ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty, 8287 unsigned *RegsLeft) const { 8288 if (!isAggregateTypeForABI(Ty)) { 8289 // Treat an enum type as its underlying type. 8290 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 8291 Ty = EnumTy->getDecl()->getIntegerType(); 8292 8293 uint64_t Size = getContext().getTypeSize(Ty); 8294 if (Size <= 64) 8295 HexagonAdjustRegsLeft(Size, RegsLeft); 8296 8297 if (Size > 64 && Ty->isExtIntType()) 8298 return getNaturalAlignIndirect(Ty, /*ByVal=*/true); 8299 8300 return isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty) 8301 : ABIArgInfo::getDirect(); 8302 } 8303 8304 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 8305 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 8306 8307 // Ignore empty records. 8308 if (isEmptyRecord(getContext(), Ty, true)) 8309 return ABIArgInfo::getIgnore(); 8310 8311 uint64_t Size = getContext().getTypeSize(Ty); 8312 unsigned Align = getContext().getTypeAlign(Ty); 8313 8314 if (Size > 64) 8315 return getNaturalAlignIndirect(Ty, /*ByVal=*/true); 8316 8317 if (HexagonAdjustRegsLeft(Size, RegsLeft)) 8318 Align = Size <= 32 ? 32 : 64; 8319 if (Size <= Align) { 8320 // Pass in the smallest viable integer type. 8321 if (!llvm::isPowerOf2_64(Size)) 8322 Size = llvm::NextPowerOf2(Size); 8323 return ABIArgInfo::getDirect(llvm::Type::getIntNTy(getVMContext(), Size)); 8324 } 8325 return DefaultABIInfo::classifyArgumentType(Ty); 8326 } 8327 8328 ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const { 8329 if (RetTy->isVoidType()) 8330 return ABIArgInfo::getIgnore(); 8331 8332 const TargetInfo &T = CGT.getTarget(); 8333 uint64_t Size = getContext().getTypeSize(RetTy); 8334 8335 if (RetTy->getAs<VectorType>()) { 8336 // HVX vectors are returned in vector registers or register pairs. 8337 if (T.hasFeature("hvx")) { 8338 assert(T.hasFeature("hvx-length64b") || T.hasFeature("hvx-length128b")); 8339 uint64_t VecSize = T.hasFeature("hvx-length64b") ? 64*8 : 128*8; 8340 if (Size == VecSize || Size == 2*VecSize) 8341 return ABIArgInfo::getDirectInReg(); 8342 } 8343 // Large vector types should be returned via memory. 8344 if (Size > 64) 8345 return getNaturalAlignIndirect(RetTy); 8346 } 8347 8348 if (!isAggregateTypeForABI(RetTy)) { 8349 // Treat an enum type as its underlying type. 8350 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 8351 RetTy = EnumTy->getDecl()->getIntegerType(); 8352 8353 if (Size > 64 && RetTy->isExtIntType()) 8354 return getNaturalAlignIndirect(RetTy, /*ByVal=*/false); 8355 8356 return isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy) 8357 : ABIArgInfo::getDirect(); 8358 } 8359 8360 if (isEmptyRecord(getContext(), RetTy, true)) 8361 return ABIArgInfo::getIgnore(); 8362 8363 // Aggregates <= 8 bytes are returned in registers, other aggregates 8364 // are returned indirectly. 8365 if (Size <= 64) { 8366 // Return in the smallest viable integer type. 8367 if (!llvm::isPowerOf2_64(Size)) 8368 Size = llvm::NextPowerOf2(Size); 8369 return ABIArgInfo::getDirect(llvm::Type::getIntNTy(getVMContext(), Size)); 8370 } 8371 return getNaturalAlignIndirect(RetTy, /*ByVal=*/true); 8372 } 8373 8374 Address HexagonABIInfo::EmitVAArgFromMemory(CodeGenFunction &CGF, 8375 Address VAListAddr, 8376 QualType Ty) const { 8377 // Load the overflow area pointer. 8378 Address __overflow_area_pointer_p = 8379 CGF.Builder.CreateStructGEP(VAListAddr, 2, "__overflow_area_pointer_p"); 8380 llvm::Value *__overflow_area_pointer = CGF.Builder.CreateLoad( 8381 __overflow_area_pointer_p, "__overflow_area_pointer"); 8382 8383 uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8; 8384 if (Align > 4) { 8385 // Alignment should be a power of 2. 8386 assert((Align & (Align - 1)) == 0 && "Alignment is not power of 2!"); 8387 8388 // overflow_arg_area = (overflow_arg_area + align - 1) & -align; 8389 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int64Ty, Align - 1); 8390 8391 // Add offset to the current pointer to access the argument. 8392 __overflow_area_pointer = 8393 CGF.Builder.CreateGEP(__overflow_area_pointer, Offset); 8394 llvm::Value *AsInt = 8395 CGF.Builder.CreatePtrToInt(__overflow_area_pointer, CGF.Int32Ty); 8396 8397 // Create a mask which should be "AND"ed 8398 // with (overflow_arg_area + align - 1) 8399 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int32Ty, -(int)Align); 8400 __overflow_area_pointer = CGF.Builder.CreateIntToPtr( 8401 CGF.Builder.CreateAnd(AsInt, Mask), __overflow_area_pointer->getType(), 8402 "__overflow_area_pointer.align"); 8403 } 8404 8405 // Get the type of the argument from memory and bitcast 8406 // overflow area pointer to the argument type. 8407 llvm::Type *PTy = CGF.ConvertTypeForMem(Ty); 8408 Address AddrTyped = CGF.Builder.CreateBitCast( 8409 Address(__overflow_area_pointer, CharUnits::fromQuantity(Align)), 8410 llvm::PointerType::getUnqual(PTy)); 8411 8412 // Round up to the minimum stack alignment for varargs which is 4 bytes. 8413 uint64_t Offset = llvm::alignTo(CGF.getContext().getTypeSize(Ty) / 8, 4); 8414 8415 __overflow_area_pointer = CGF.Builder.CreateGEP( 8416 __overflow_area_pointer, llvm::ConstantInt::get(CGF.Int32Ty, Offset), 8417 "__overflow_area_pointer.next"); 8418 CGF.Builder.CreateStore(__overflow_area_pointer, __overflow_area_pointer_p); 8419 8420 return AddrTyped; 8421 } 8422 8423 Address HexagonABIInfo::EmitVAArgForHexagon(CodeGenFunction &CGF, 8424 Address VAListAddr, 8425 QualType Ty) const { 8426 // FIXME: Need to handle alignment 8427 llvm::Type *BP = CGF.Int8PtrTy; 8428 llvm::Type *BPP = CGF.Int8PtrPtrTy; 8429 CGBuilderTy &Builder = CGF.Builder; 8430 Address VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap"); 8431 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur"); 8432 // Handle address alignment for type alignment > 32 bits 8433 uint64_t TyAlign = CGF.getContext().getTypeAlign(Ty) / 8; 8434 if (TyAlign > 4) { 8435 assert((TyAlign & (TyAlign - 1)) == 0 && "Alignment is not power of 2!"); 8436 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int32Ty); 8437 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt32(TyAlign - 1)); 8438 AddrAsInt = Builder.CreateAnd(AddrAsInt, Builder.getInt32(~(TyAlign - 1))); 8439 Addr = Builder.CreateIntToPtr(AddrAsInt, BP); 8440 } 8441 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty)); 8442 Address AddrTyped = Builder.CreateBitCast( 8443 Address(Addr, CharUnits::fromQuantity(TyAlign)), PTy); 8444 8445 uint64_t Offset = llvm::alignTo(CGF.getContext().getTypeSize(Ty) / 8, 4); 8446 llvm::Value *NextAddr = Builder.CreateGEP( 8447 Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset), "ap.next"); 8448 Builder.CreateStore(NextAddr, VAListAddrAsBPP); 8449 8450 return AddrTyped; 8451 } 8452 8453 Address HexagonABIInfo::EmitVAArgForHexagonLinux(CodeGenFunction &CGF, 8454 Address VAListAddr, 8455 QualType Ty) const { 8456 int ArgSize = CGF.getContext().getTypeSize(Ty) / 8; 8457 8458 if (ArgSize > 8) 8459 return EmitVAArgFromMemory(CGF, VAListAddr, Ty); 8460 8461 // Here we have check if the argument is in register area or 8462 // in overflow area. 8463 // If the saved register area pointer + argsize rounded up to alignment > 8464 // saved register area end pointer, argument is in overflow area. 8465 unsigned RegsLeft = 6; 8466 Ty = CGF.getContext().getCanonicalType(Ty); 8467 (void)classifyArgumentType(Ty, &RegsLeft); 8468 8469 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg"); 8470 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg"); 8471 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack"); 8472 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end"); 8473 8474 // Get rounded size of the argument.GCC does not allow vararg of 8475 // size < 4 bytes. We follow the same logic here. 8476 ArgSize = (CGF.getContext().getTypeSize(Ty) <= 32) ? 4 : 8; 8477 int ArgAlign = (CGF.getContext().getTypeSize(Ty) <= 32) ? 4 : 8; 8478 8479 // Argument may be in saved register area 8480 CGF.EmitBlock(MaybeRegBlock); 8481 8482 // Load the current saved register area pointer. 8483 Address __current_saved_reg_area_pointer_p = CGF.Builder.CreateStructGEP( 8484 VAListAddr, 0, "__current_saved_reg_area_pointer_p"); 8485 llvm::Value *__current_saved_reg_area_pointer = CGF.Builder.CreateLoad( 8486 __current_saved_reg_area_pointer_p, "__current_saved_reg_area_pointer"); 8487 8488 // Load the saved register area end pointer. 8489 Address __saved_reg_area_end_pointer_p = CGF.Builder.CreateStructGEP( 8490 VAListAddr, 1, "__saved_reg_area_end_pointer_p"); 8491 llvm::Value *__saved_reg_area_end_pointer = CGF.Builder.CreateLoad( 8492 __saved_reg_area_end_pointer_p, "__saved_reg_area_end_pointer"); 8493 8494 // If the size of argument is > 4 bytes, check if the stack 8495 // location is aligned to 8 bytes 8496 if (ArgAlign > 4) { 8497 8498 llvm::Value *__current_saved_reg_area_pointer_int = 8499 CGF.Builder.CreatePtrToInt(__current_saved_reg_area_pointer, 8500 CGF.Int32Ty); 8501 8502 __current_saved_reg_area_pointer_int = CGF.Builder.CreateAdd( 8503 __current_saved_reg_area_pointer_int, 8504 llvm::ConstantInt::get(CGF.Int32Ty, (ArgAlign - 1)), 8505 "align_current_saved_reg_area_pointer"); 8506 8507 __current_saved_reg_area_pointer_int = 8508 CGF.Builder.CreateAnd(__current_saved_reg_area_pointer_int, 8509 llvm::ConstantInt::get(CGF.Int32Ty, -ArgAlign), 8510 "align_current_saved_reg_area_pointer"); 8511 8512 __current_saved_reg_area_pointer = 8513 CGF.Builder.CreateIntToPtr(__current_saved_reg_area_pointer_int, 8514 __current_saved_reg_area_pointer->getType(), 8515 "align_current_saved_reg_area_pointer"); 8516 } 8517 8518 llvm::Value *__new_saved_reg_area_pointer = 8519 CGF.Builder.CreateGEP(__current_saved_reg_area_pointer, 8520 llvm::ConstantInt::get(CGF.Int32Ty, ArgSize), 8521 "__new_saved_reg_area_pointer"); 8522 8523 llvm::Value *UsingStack = 0; 8524 UsingStack = CGF.Builder.CreateICmpSGT(__new_saved_reg_area_pointer, 8525 __saved_reg_area_end_pointer); 8526 8527 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, InRegBlock); 8528 8529 // Argument in saved register area 8530 // Implement the block where argument is in register saved area 8531 CGF.EmitBlock(InRegBlock); 8532 8533 llvm::Type *PTy = CGF.ConvertType(Ty); 8534 llvm::Value *__saved_reg_area_p = CGF.Builder.CreateBitCast( 8535 __current_saved_reg_area_pointer, llvm::PointerType::getUnqual(PTy)); 8536 8537 CGF.Builder.CreateStore(__new_saved_reg_area_pointer, 8538 __current_saved_reg_area_pointer_p); 8539 8540 CGF.EmitBranch(ContBlock); 8541 8542 // Argument in overflow area 8543 // Implement the block where the argument is in overflow area. 8544 CGF.EmitBlock(OnStackBlock); 8545 8546 // Load the overflow area pointer 8547 Address __overflow_area_pointer_p = 8548 CGF.Builder.CreateStructGEP(VAListAddr, 2, "__overflow_area_pointer_p"); 8549 llvm::Value *__overflow_area_pointer = CGF.Builder.CreateLoad( 8550 __overflow_area_pointer_p, "__overflow_area_pointer"); 8551 8552 // Align the overflow area pointer according to the alignment of the argument 8553 if (ArgAlign > 4) { 8554 llvm::Value *__overflow_area_pointer_int = 8555 CGF.Builder.CreatePtrToInt(__overflow_area_pointer, CGF.Int32Ty); 8556 8557 __overflow_area_pointer_int = 8558 CGF.Builder.CreateAdd(__overflow_area_pointer_int, 8559 llvm::ConstantInt::get(CGF.Int32Ty, ArgAlign - 1), 8560 "align_overflow_area_pointer"); 8561 8562 __overflow_area_pointer_int = 8563 CGF.Builder.CreateAnd(__overflow_area_pointer_int, 8564 llvm::ConstantInt::get(CGF.Int32Ty, -ArgAlign), 8565 "align_overflow_area_pointer"); 8566 8567 __overflow_area_pointer = CGF.Builder.CreateIntToPtr( 8568 __overflow_area_pointer_int, __overflow_area_pointer->getType(), 8569 "align_overflow_area_pointer"); 8570 } 8571 8572 // Get the pointer for next argument in overflow area and store it 8573 // to overflow area pointer. 8574 llvm::Value *__new_overflow_area_pointer = CGF.Builder.CreateGEP( 8575 __overflow_area_pointer, llvm::ConstantInt::get(CGF.Int32Ty, ArgSize), 8576 "__overflow_area_pointer.next"); 8577 8578 CGF.Builder.CreateStore(__new_overflow_area_pointer, 8579 __overflow_area_pointer_p); 8580 8581 CGF.Builder.CreateStore(__new_overflow_area_pointer, 8582 __current_saved_reg_area_pointer_p); 8583 8584 // Bitcast the overflow area pointer to the type of argument. 8585 llvm::Type *OverflowPTy = CGF.ConvertTypeForMem(Ty); 8586 llvm::Value *__overflow_area_p = CGF.Builder.CreateBitCast( 8587 __overflow_area_pointer, llvm::PointerType::getUnqual(OverflowPTy)); 8588 8589 CGF.EmitBranch(ContBlock); 8590 8591 // Get the correct pointer to load the variable argument 8592 // Implement the ContBlock 8593 CGF.EmitBlock(ContBlock); 8594 8595 llvm::Type *MemPTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty)); 8596 llvm::PHINode *ArgAddr = CGF.Builder.CreatePHI(MemPTy, 2, "vaarg.addr"); 8597 ArgAddr->addIncoming(__saved_reg_area_p, InRegBlock); 8598 ArgAddr->addIncoming(__overflow_area_p, OnStackBlock); 8599 8600 return Address(ArgAddr, CharUnits::fromQuantity(ArgAlign)); 8601 } 8602 8603 Address HexagonABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 8604 QualType Ty) const { 8605 8606 if (getTarget().getTriple().isMusl()) 8607 return EmitVAArgForHexagonLinux(CGF, VAListAddr, Ty); 8608 8609 return EmitVAArgForHexagon(CGF, VAListAddr, Ty); 8610 } 8611 8612 //===----------------------------------------------------------------------===// 8613 // Lanai ABI Implementation 8614 //===----------------------------------------------------------------------===// 8615 8616 namespace { 8617 class LanaiABIInfo : public DefaultABIInfo { 8618 public: 8619 LanaiABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {} 8620 8621 bool shouldUseInReg(QualType Ty, CCState &State) const; 8622 8623 void computeInfo(CGFunctionInfo &FI) const override { 8624 CCState State(FI); 8625 // Lanai uses 4 registers to pass arguments unless the function has the 8626 // regparm attribute set. 8627 if (FI.getHasRegParm()) { 8628 State.FreeRegs = FI.getRegParm(); 8629 } else { 8630 State.FreeRegs = 4; 8631 } 8632 8633 if (!getCXXABI().classifyReturnType(FI)) 8634 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 8635 for (auto &I : FI.arguments()) 8636 I.info = classifyArgumentType(I.type, State); 8637 } 8638 8639 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const; 8640 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const; 8641 }; 8642 } // end anonymous namespace 8643 8644 bool LanaiABIInfo::shouldUseInReg(QualType Ty, CCState &State) const { 8645 unsigned Size = getContext().getTypeSize(Ty); 8646 unsigned SizeInRegs = llvm::alignTo(Size, 32U) / 32U; 8647 8648 if (SizeInRegs == 0) 8649 return false; 8650 8651 if (SizeInRegs > State.FreeRegs) { 8652 State.FreeRegs = 0; 8653 return false; 8654 } 8655 8656 State.FreeRegs -= SizeInRegs; 8657 8658 return true; 8659 } 8660 8661 ABIArgInfo LanaiABIInfo::getIndirectResult(QualType Ty, bool ByVal, 8662 CCState &State) const { 8663 if (!ByVal) { 8664 if (State.FreeRegs) { 8665 --State.FreeRegs; // Non-byval indirects just use one pointer. 8666 return getNaturalAlignIndirectInReg(Ty); 8667 } 8668 return getNaturalAlignIndirect(Ty, false); 8669 } 8670 8671 // Compute the byval alignment. 8672 const unsigned MinABIStackAlignInBytes = 4; 8673 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8; 8674 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true, 8675 /*Realign=*/TypeAlign > 8676 MinABIStackAlignInBytes); 8677 } 8678 8679 ABIArgInfo LanaiABIInfo::classifyArgumentType(QualType Ty, 8680 CCState &State) const { 8681 // Check with the C++ ABI first. 8682 const RecordType *RT = Ty->getAs<RecordType>(); 8683 if (RT) { 8684 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()); 8685 if (RAA == CGCXXABI::RAA_Indirect) { 8686 return getIndirectResult(Ty, /*ByVal=*/false, State); 8687 } else if (RAA == CGCXXABI::RAA_DirectInMemory) { 8688 return getNaturalAlignIndirect(Ty, /*ByVal=*/true); 8689 } 8690 } 8691 8692 if (isAggregateTypeForABI(Ty)) { 8693 // Structures with flexible arrays are always indirect. 8694 if (RT && RT->getDecl()->hasFlexibleArrayMember()) 8695 return getIndirectResult(Ty, /*ByVal=*/true, State); 8696 8697 // Ignore empty structs/unions. 8698 if (isEmptyRecord(getContext(), Ty, true)) 8699 return ABIArgInfo::getIgnore(); 8700 8701 llvm::LLVMContext &LLVMContext = getVMContext(); 8702 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32; 8703 if (SizeInRegs <= State.FreeRegs) { 8704 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext); 8705 SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32); 8706 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements); 8707 State.FreeRegs -= SizeInRegs; 8708 return ABIArgInfo::getDirectInReg(Result); 8709 } else { 8710 State.FreeRegs = 0; 8711 } 8712 return getIndirectResult(Ty, true, State); 8713 } 8714 8715 // Treat an enum type as its underlying type. 8716 if (const auto *EnumTy = Ty->getAs<EnumType>()) 8717 Ty = EnumTy->getDecl()->getIntegerType(); 8718 8719 bool InReg = shouldUseInReg(Ty, State); 8720 8721 // Don't pass >64 bit integers in registers. 8722 if (const auto *EIT = Ty->getAs<ExtIntType>()) 8723 if (EIT->getNumBits() > 64) 8724 return getIndirectResult(Ty, /*ByVal=*/true, State); 8725 8726 if (isPromotableIntegerTypeForABI(Ty)) { 8727 if (InReg) 8728 return ABIArgInfo::getDirectInReg(); 8729 return ABIArgInfo::getExtend(Ty); 8730 } 8731 if (InReg) 8732 return ABIArgInfo::getDirectInReg(); 8733 return ABIArgInfo::getDirect(); 8734 } 8735 8736 namespace { 8737 class LanaiTargetCodeGenInfo : public TargetCodeGenInfo { 8738 public: 8739 LanaiTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT) 8740 : TargetCodeGenInfo(std::make_unique<LanaiABIInfo>(CGT)) {} 8741 }; 8742 } 8743 8744 //===----------------------------------------------------------------------===// 8745 // AMDGPU ABI Implementation 8746 //===----------------------------------------------------------------------===// 8747 8748 namespace { 8749 8750 class AMDGPUABIInfo final : public DefaultABIInfo { 8751 private: 8752 static const unsigned MaxNumRegsForArgsRet = 16; 8753 8754 unsigned numRegsForType(QualType Ty) const; 8755 8756 bool isHomogeneousAggregateBaseType(QualType Ty) const override; 8757 bool isHomogeneousAggregateSmallEnough(const Type *Base, 8758 uint64_t Members) const override; 8759 8760 // Coerce HIP scalar pointer arguments from generic pointers to global ones. 8761 llvm::Type *coerceKernelArgumentType(llvm::Type *Ty, unsigned FromAS, 8762 unsigned ToAS) const { 8763 // Single value types. 8764 if (Ty->isPointerTy() && Ty->getPointerAddressSpace() == FromAS) 8765 return llvm::PointerType::get( 8766 cast<llvm::PointerType>(Ty)->getElementType(), ToAS); 8767 return Ty; 8768 } 8769 8770 public: 8771 explicit AMDGPUABIInfo(CodeGen::CodeGenTypes &CGT) : 8772 DefaultABIInfo(CGT) {} 8773 8774 ABIArgInfo classifyReturnType(QualType RetTy) const; 8775 ABIArgInfo classifyKernelArgumentType(QualType Ty) const; 8776 ABIArgInfo classifyArgumentType(QualType Ty, unsigned &NumRegsLeft) const; 8777 8778 void computeInfo(CGFunctionInfo &FI) const override; 8779 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 8780 QualType Ty) const override; 8781 }; 8782 8783 bool AMDGPUABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const { 8784 return true; 8785 } 8786 8787 bool AMDGPUABIInfo::isHomogeneousAggregateSmallEnough( 8788 const Type *Base, uint64_t Members) const { 8789 uint32_t NumRegs = (getContext().getTypeSize(Base) + 31) / 32; 8790 8791 // Homogeneous Aggregates may occupy at most 16 registers. 8792 return Members * NumRegs <= MaxNumRegsForArgsRet; 8793 } 8794 8795 /// Estimate number of registers the type will use when passed in registers. 8796 unsigned AMDGPUABIInfo::numRegsForType(QualType Ty) const { 8797 unsigned NumRegs = 0; 8798 8799 if (const VectorType *VT = Ty->getAs<VectorType>()) { 8800 // Compute from the number of elements. The reported size is based on the 8801 // in-memory size, which includes the padding 4th element for 3-vectors. 8802 QualType EltTy = VT->getElementType(); 8803 unsigned EltSize = getContext().getTypeSize(EltTy); 8804 8805 // 16-bit element vectors should be passed as packed. 8806 if (EltSize == 16) 8807 return (VT->getNumElements() + 1) / 2; 8808 8809 unsigned EltNumRegs = (EltSize + 31) / 32; 8810 return EltNumRegs * VT->getNumElements(); 8811 } 8812 8813 if (const RecordType *RT = Ty->getAs<RecordType>()) { 8814 const RecordDecl *RD = RT->getDecl(); 8815 assert(!RD->hasFlexibleArrayMember()); 8816 8817 for (const FieldDecl *Field : RD->fields()) { 8818 QualType FieldTy = Field->getType(); 8819 NumRegs += numRegsForType(FieldTy); 8820 } 8821 8822 return NumRegs; 8823 } 8824 8825 return (getContext().getTypeSize(Ty) + 31) / 32; 8826 } 8827 8828 void AMDGPUABIInfo::computeInfo(CGFunctionInfo &FI) const { 8829 llvm::CallingConv::ID CC = FI.getCallingConvention(); 8830 8831 if (!getCXXABI().classifyReturnType(FI)) 8832 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 8833 8834 unsigned NumRegsLeft = MaxNumRegsForArgsRet; 8835 for (auto &Arg : FI.arguments()) { 8836 if (CC == llvm::CallingConv::AMDGPU_KERNEL) { 8837 Arg.info = classifyKernelArgumentType(Arg.type); 8838 } else { 8839 Arg.info = classifyArgumentType(Arg.type, NumRegsLeft); 8840 } 8841 } 8842 } 8843 8844 Address AMDGPUABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 8845 QualType Ty) const { 8846 llvm_unreachable("AMDGPU does not support varargs"); 8847 } 8848 8849 ABIArgInfo AMDGPUABIInfo::classifyReturnType(QualType RetTy) const { 8850 if (isAggregateTypeForABI(RetTy)) { 8851 // Records with non-trivial destructors/copy-constructors should not be 8852 // returned by value. 8853 if (!getRecordArgABI(RetTy, getCXXABI())) { 8854 // Ignore empty structs/unions. 8855 if (isEmptyRecord(getContext(), RetTy, true)) 8856 return ABIArgInfo::getIgnore(); 8857 8858 // Lower single-element structs to just return a regular value. 8859 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext())) 8860 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0))); 8861 8862 if (const RecordType *RT = RetTy->getAs<RecordType>()) { 8863 const RecordDecl *RD = RT->getDecl(); 8864 if (RD->hasFlexibleArrayMember()) 8865 return DefaultABIInfo::classifyReturnType(RetTy); 8866 } 8867 8868 // Pack aggregates <= 4 bytes into single VGPR or pair. 8869 uint64_t Size = getContext().getTypeSize(RetTy); 8870 if (Size <= 16) 8871 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext())); 8872 8873 if (Size <= 32) 8874 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext())); 8875 8876 if (Size <= 64) { 8877 llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext()); 8878 return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2)); 8879 } 8880 8881 if (numRegsForType(RetTy) <= MaxNumRegsForArgsRet) 8882 return ABIArgInfo::getDirect(); 8883 } 8884 } 8885 8886 // Otherwise just do the default thing. 8887 return DefaultABIInfo::classifyReturnType(RetTy); 8888 } 8889 8890 /// For kernels all parameters are really passed in a special buffer. It doesn't 8891 /// make sense to pass anything byval, so everything must be direct. 8892 ABIArgInfo AMDGPUABIInfo::classifyKernelArgumentType(QualType Ty) const { 8893 Ty = useFirstFieldIfTransparentUnion(Ty); 8894 8895 // TODO: Can we omit empty structs? 8896 8897 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext())) 8898 Ty = QualType(SeltTy, 0); 8899 8900 llvm::Type *OrigLTy = CGT.ConvertType(Ty); 8901 llvm::Type *LTy = OrigLTy; 8902 if (getContext().getLangOpts().HIP) { 8903 LTy = coerceKernelArgumentType( 8904 OrigLTy, /*FromAS=*/getContext().getTargetAddressSpace(LangAS::Default), 8905 /*ToAS=*/getContext().getTargetAddressSpace(LangAS::cuda_device)); 8906 } 8907 8908 // FIXME: Should also use this for OpenCL, but it requires addressing the 8909 // problem of kernels being called. 8910 // 8911 // FIXME: This doesn't apply the optimization of coercing pointers in structs 8912 // to global address space when using byref. This would require implementing a 8913 // new kind of coercion of the in-memory type when for indirect arguments. 8914 if (!getContext().getLangOpts().OpenCL && LTy == OrigLTy && 8915 isAggregateTypeForABI(Ty)) { 8916 return ABIArgInfo::getIndirectAliased( 8917 getContext().getTypeAlignInChars(Ty), 8918 getContext().getTargetAddressSpace(LangAS::opencl_constant), 8919 false /*Realign*/, nullptr /*Padding*/); 8920 } 8921 8922 // If we set CanBeFlattened to true, CodeGen will expand the struct to its 8923 // individual elements, which confuses the Clover OpenCL backend; therefore we 8924 // have to set it to false here. Other args of getDirect() are just defaults. 8925 return ABIArgInfo::getDirect(LTy, 0, nullptr, false); 8926 } 8927 8928 ABIArgInfo AMDGPUABIInfo::classifyArgumentType(QualType Ty, 8929 unsigned &NumRegsLeft) const { 8930 assert(NumRegsLeft <= MaxNumRegsForArgsRet && "register estimate underflow"); 8931 8932 Ty = useFirstFieldIfTransparentUnion(Ty); 8933 8934 if (isAggregateTypeForABI(Ty)) { 8935 // Records with non-trivial destructors/copy-constructors should not be 8936 // passed by value. 8937 if (auto RAA = getRecordArgABI(Ty, getCXXABI())) 8938 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 8939 8940 // Ignore empty structs/unions. 8941 if (isEmptyRecord(getContext(), Ty, true)) 8942 return ABIArgInfo::getIgnore(); 8943 8944 // Lower single-element structs to just pass a regular value. TODO: We 8945 // could do reasonable-size multiple-element structs too, using getExpand(), 8946 // though watch out for things like bitfields. 8947 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext())) 8948 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0))); 8949 8950 if (const RecordType *RT = Ty->getAs<RecordType>()) { 8951 const RecordDecl *RD = RT->getDecl(); 8952 if (RD->hasFlexibleArrayMember()) 8953 return DefaultABIInfo::classifyArgumentType(Ty); 8954 } 8955 8956 // Pack aggregates <= 8 bytes into single VGPR or pair. 8957 uint64_t Size = getContext().getTypeSize(Ty); 8958 if (Size <= 64) { 8959 unsigned NumRegs = (Size + 31) / 32; 8960 NumRegsLeft -= std::min(NumRegsLeft, NumRegs); 8961 8962 if (Size <= 16) 8963 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext())); 8964 8965 if (Size <= 32) 8966 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext())); 8967 8968 // XXX: Should this be i64 instead, and should the limit increase? 8969 llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext()); 8970 return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2)); 8971 } 8972 8973 if (NumRegsLeft > 0) { 8974 unsigned NumRegs = numRegsForType(Ty); 8975 if (NumRegsLeft >= NumRegs) { 8976 NumRegsLeft -= NumRegs; 8977 return ABIArgInfo::getDirect(); 8978 } 8979 } 8980 } 8981 8982 // Otherwise just do the default thing. 8983 ABIArgInfo ArgInfo = DefaultABIInfo::classifyArgumentType(Ty); 8984 if (!ArgInfo.isIndirect()) { 8985 unsigned NumRegs = numRegsForType(Ty); 8986 NumRegsLeft -= std::min(NumRegs, NumRegsLeft); 8987 } 8988 8989 return ArgInfo; 8990 } 8991 8992 class AMDGPUTargetCodeGenInfo : public TargetCodeGenInfo { 8993 public: 8994 AMDGPUTargetCodeGenInfo(CodeGenTypes &CGT) 8995 : TargetCodeGenInfo(std::make_unique<AMDGPUABIInfo>(CGT)) {} 8996 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 8997 CodeGen::CodeGenModule &M) const override; 8998 unsigned getOpenCLKernelCallingConv() const override; 8999 9000 llvm::Constant *getNullPointer(const CodeGen::CodeGenModule &CGM, 9001 llvm::PointerType *T, QualType QT) const override; 9002 9003 LangAS getASTAllocaAddressSpace() const override { 9004 return getLangASFromTargetAS( 9005 getABIInfo().getDataLayout().getAllocaAddrSpace()); 9006 } 9007 LangAS getGlobalVarAddressSpace(CodeGenModule &CGM, 9008 const VarDecl *D) const override; 9009 llvm::SyncScope::ID getLLVMSyncScopeID(const LangOptions &LangOpts, 9010 SyncScope Scope, 9011 llvm::AtomicOrdering Ordering, 9012 llvm::LLVMContext &Ctx) const override; 9013 llvm::Function * 9014 createEnqueuedBlockKernel(CodeGenFunction &CGF, 9015 llvm::Function *BlockInvokeFunc, 9016 llvm::Value *BlockLiteral) const override; 9017 bool shouldEmitStaticExternCAliases() const override; 9018 void setCUDAKernelCallingConvention(const FunctionType *&FT) const override; 9019 }; 9020 } 9021 9022 static bool requiresAMDGPUProtectedVisibility(const Decl *D, 9023 llvm::GlobalValue *GV) { 9024 if (GV->getVisibility() != llvm::GlobalValue::HiddenVisibility) 9025 return false; 9026 9027 return D->hasAttr<OpenCLKernelAttr>() || 9028 (isa<FunctionDecl>(D) && D->hasAttr<CUDAGlobalAttr>()) || 9029 (isa<VarDecl>(D) && 9030 (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>() || 9031 cast<VarDecl>(D)->getType()->isCUDADeviceBuiltinSurfaceType() || 9032 cast<VarDecl>(D)->getType()->isCUDADeviceBuiltinTextureType())); 9033 } 9034 9035 void AMDGPUTargetCodeGenInfo::setTargetAttributes( 9036 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const { 9037 if (requiresAMDGPUProtectedVisibility(D, GV)) { 9038 GV->setVisibility(llvm::GlobalValue::ProtectedVisibility); 9039 GV->setDSOLocal(true); 9040 } 9041 9042 if (GV->isDeclaration()) 9043 return; 9044 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D); 9045 if (!FD) 9046 return; 9047 9048 llvm::Function *F = cast<llvm::Function>(GV); 9049 9050 const auto *ReqdWGS = M.getLangOpts().OpenCL ? 9051 FD->getAttr<ReqdWorkGroupSizeAttr>() : nullptr; 9052 9053 9054 const bool IsOpenCLKernel = M.getLangOpts().OpenCL && 9055 FD->hasAttr<OpenCLKernelAttr>(); 9056 const bool IsHIPKernel = M.getLangOpts().HIP && 9057 FD->hasAttr<CUDAGlobalAttr>(); 9058 if ((IsOpenCLKernel || IsHIPKernel) && 9059 (M.getTriple().getOS() == llvm::Triple::AMDHSA)) 9060 F->addFnAttr("amdgpu-implicitarg-num-bytes", "56"); 9061 9062 if (IsHIPKernel) 9063 F->addFnAttr("uniform-work-group-size", "true"); 9064 9065 9066 const auto *FlatWGS = FD->getAttr<AMDGPUFlatWorkGroupSizeAttr>(); 9067 if (ReqdWGS || FlatWGS) { 9068 unsigned Min = 0; 9069 unsigned Max = 0; 9070 if (FlatWGS) { 9071 Min = FlatWGS->getMin() 9072 ->EvaluateKnownConstInt(M.getContext()) 9073 .getExtValue(); 9074 Max = FlatWGS->getMax() 9075 ->EvaluateKnownConstInt(M.getContext()) 9076 .getExtValue(); 9077 } 9078 if (ReqdWGS && Min == 0 && Max == 0) 9079 Min = Max = ReqdWGS->getXDim() * ReqdWGS->getYDim() * ReqdWGS->getZDim(); 9080 9081 if (Min != 0) { 9082 assert(Min <= Max && "Min must be less than or equal Max"); 9083 9084 std::string AttrVal = llvm::utostr(Min) + "," + llvm::utostr(Max); 9085 F->addFnAttr("amdgpu-flat-work-group-size", AttrVal); 9086 } else 9087 assert(Max == 0 && "Max must be zero"); 9088 } else if (IsOpenCLKernel || IsHIPKernel) { 9089 // By default, restrict the maximum size to a value specified by 9090 // --gpu-max-threads-per-block=n or its default value for HIP. 9091 const unsigned OpenCLDefaultMaxWorkGroupSize = 256; 9092 const unsigned DefaultMaxWorkGroupSize = 9093 IsOpenCLKernel ? OpenCLDefaultMaxWorkGroupSize 9094 : M.getLangOpts().GPUMaxThreadsPerBlock; 9095 std::string AttrVal = 9096 std::string("1,") + llvm::utostr(DefaultMaxWorkGroupSize); 9097 F->addFnAttr("amdgpu-flat-work-group-size", AttrVal); 9098 } 9099 9100 if (const auto *Attr = FD->getAttr<AMDGPUWavesPerEUAttr>()) { 9101 unsigned Min = 9102 Attr->getMin()->EvaluateKnownConstInt(M.getContext()).getExtValue(); 9103 unsigned Max = Attr->getMax() ? Attr->getMax() 9104 ->EvaluateKnownConstInt(M.getContext()) 9105 .getExtValue() 9106 : 0; 9107 9108 if (Min != 0) { 9109 assert((Max == 0 || Min <= Max) && "Min must be less than or equal Max"); 9110 9111 std::string AttrVal = llvm::utostr(Min); 9112 if (Max != 0) 9113 AttrVal = AttrVal + "," + llvm::utostr(Max); 9114 F->addFnAttr("amdgpu-waves-per-eu", AttrVal); 9115 } else 9116 assert(Max == 0 && "Max must be zero"); 9117 } 9118 9119 if (const auto *Attr = FD->getAttr<AMDGPUNumSGPRAttr>()) { 9120 unsigned NumSGPR = Attr->getNumSGPR(); 9121 9122 if (NumSGPR != 0) 9123 F->addFnAttr("amdgpu-num-sgpr", llvm::utostr(NumSGPR)); 9124 } 9125 9126 if (const auto *Attr = FD->getAttr<AMDGPUNumVGPRAttr>()) { 9127 uint32_t NumVGPR = Attr->getNumVGPR(); 9128 9129 if (NumVGPR != 0) 9130 F->addFnAttr("amdgpu-num-vgpr", llvm::utostr(NumVGPR)); 9131 } 9132 9133 if (M.getContext().getTargetInfo().allowAMDGPUUnsafeFPAtomics()) 9134 F->addFnAttr("amdgpu-unsafe-fp-atomics", "true"); 9135 } 9136 9137 unsigned AMDGPUTargetCodeGenInfo::getOpenCLKernelCallingConv() const { 9138 return llvm::CallingConv::AMDGPU_KERNEL; 9139 } 9140 9141 // Currently LLVM assumes null pointers always have value 0, 9142 // which results in incorrectly transformed IR. Therefore, instead of 9143 // emitting null pointers in private and local address spaces, a null 9144 // pointer in generic address space is emitted which is casted to a 9145 // pointer in local or private address space. 9146 llvm::Constant *AMDGPUTargetCodeGenInfo::getNullPointer( 9147 const CodeGen::CodeGenModule &CGM, llvm::PointerType *PT, 9148 QualType QT) const { 9149 if (CGM.getContext().getTargetNullPointerValue(QT) == 0) 9150 return llvm::ConstantPointerNull::get(PT); 9151 9152 auto &Ctx = CGM.getContext(); 9153 auto NPT = llvm::PointerType::get(PT->getElementType(), 9154 Ctx.getTargetAddressSpace(LangAS::opencl_generic)); 9155 return llvm::ConstantExpr::getAddrSpaceCast( 9156 llvm::ConstantPointerNull::get(NPT), PT); 9157 } 9158 9159 LangAS 9160 AMDGPUTargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM, 9161 const VarDecl *D) const { 9162 assert(!CGM.getLangOpts().OpenCL && 9163 !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) && 9164 "Address space agnostic languages only"); 9165 LangAS DefaultGlobalAS = getLangASFromTargetAS( 9166 CGM.getContext().getTargetAddressSpace(LangAS::opencl_global)); 9167 if (!D) 9168 return DefaultGlobalAS; 9169 9170 LangAS AddrSpace = D->getType().getAddressSpace(); 9171 assert(AddrSpace == LangAS::Default || isTargetAddressSpace(AddrSpace)); 9172 if (AddrSpace != LangAS::Default) 9173 return AddrSpace; 9174 9175 if (CGM.isTypeConstant(D->getType(), false)) { 9176 if (auto ConstAS = CGM.getTarget().getConstantAddressSpace()) 9177 return ConstAS.getValue(); 9178 } 9179 return DefaultGlobalAS; 9180 } 9181 9182 llvm::SyncScope::ID 9183 AMDGPUTargetCodeGenInfo::getLLVMSyncScopeID(const LangOptions &LangOpts, 9184 SyncScope Scope, 9185 llvm::AtomicOrdering Ordering, 9186 llvm::LLVMContext &Ctx) const { 9187 std::string Name; 9188 switch (Scope) { 9189 case SyncScope::OpenCLWorkGroup: 9190 Name = "workgroup"; 9191 break; 9192 case SyncScope::OpenCLDevice: 9193 Name = "agent"; 9194 break; 9195 case SyncScope::OpenCLAllSVMDevices: 9196 Name = ""; 9197 break; 9198 case SyncScope::OpenCLSubGroup: 9199 Name = "wavefront"; 9200 } 9201 9202 if (Ordering != llvm::AtomicOrdering::SequentiallyConsistent) { 9203 if (!Name.empty()) 9204 Name = Twine(Twine(Name) + Twine("-")).str(); 9205 9206 Name = Twine(Twine(Name) + Twine("one-as")).str(); 9207 } 9208 9209 return Ctx.getOrInsertSyncScopeID(Name); 9210 } 9211 9212 bool AMDGPUTargetCodeGenInfo::shouldEmitStaticExternCAliases() const { 9213 return false; 9214 } 9215 9216 void AMDGPUTargetCodeGenInfo::setCUDAKernelCallingConvention( 9217 const FunctionType *&FT) const { 9218 FT = getABIInfo().getContext().adjustFunctionType( 9219 FT, FT->getExtInfo().withCallingConv(CC_OpenCLKernel)); 9220 } 9221 9222 //===----------------------------------------------------------------------===// 9223 // SPARC v8 ABI Implementation. 9224 // Based on the SPARC Compliance Definition version 2.4.1. 9225 // 9226 // Ensures that complex values are passed in registers. 9227 // 9228 namespace { 9229 class SparcV8ABIInfo : public DefaultABIInfo { 9230 public: 9231 SparcV8ABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {} 9232 9233 private: 9234 ABIArgInfo classifyReturnType(QualType RetTy) const; 9235 void computeInfo(CGFunctionInfo &FI) const override; 9236 }; 9237 } // end anonymous namespace 9238 9239 9240 ABIArgInfo 9241 SparcV8ABIInfo::classifyReturnType(QualType Ty) const { 9242 if (Ty->isAnyComplexType()) { 9243 return ABIArgInfo::getDirect(); 9244 } 9245 else { 9246 return DefaultABIInfo::classifyReturnType(Ty); 9247 } 9248 } 9249 9250 void SparcV8ABIInfo::computeInfo(CGFunctionInfo &FI) const { 9251 9252 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 9253 for (auto &Arg : FI.arguments()) 9254 Arg.info = classifyArgumentType(Arg.type); 9255 } 9256 9257 namespace { 9258 class SparcV8TargetCodeGenInfo : public TargetCodeGenInfo { 9259 public: 9260 SparcV8TargetCodeGenInfo(CodeGenTypes &CGT) 9261 : TargetCodeGenInfo(std::make_unique<SparcV8ABIInfo>(CGT)) {} 9262 }; 9263 } // end anonymous namespace 9264 9265 //===----------------------------------------------------------------------===// 9266 // SPARC v9 ABI Implementation. 9267 // Based on the SPARC Compliance Definition version 2.4.1. 9268 // 9269 // Function arguments a mapped to a nominal "parameter array" and promoted to 9270 // registers depending on their type. Each argument occupies 8 or 16 bytes in 9271 // the array, structs larger than 16 bytes are passed indirectly. 9272 // 9273 // One case requires special care: 9274 // 9275 // struct mixed { 9276 // int i; 9277 // float f; 9278 // }; 9279 // 9280 // When a struct mixed is passed by value, it only occupies 8 bytes in the 9281 // parameter array, but the int is passed in an integer register, and the float 9282 // is passed in a floating point register. This is represented as two arguments 9283 // with the LLVM IR inreg attribute: 9284 // 9285 // declare void f(i32 inreg %i, float inreg %f) 9286 // 9287 // The code generator will only allocate 4 bytes from the parameter array for 9288 // the inreg arguments. All other arguments are allocated a multiple of 8 9289 // bytes. 9290 // 9291 namespace { 9292 class SparcV9ABIInfo : public ABIInfo { 9293 public: 9294 SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {} 9295 9296 private: 9297 ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const; 9298 void computeInfo(CGFunctionInfo &FI) const override; 9299 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 9300 QualType Ty) const override; 9301 9302 // Coercion type builder for structs passed in registers. The coercion type 9303 // serves two purposes: 9304 // 9305 // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned' 9306 // in registers. 9307 // 2. Expose aligned floating point elements as first-level elements, so the 9308 // code generator knows to pass them in floating point registers. 9309 // 9310 // We also compute the InReg flag which indicates that the struct contains 9311 // aligned 32-bit floats. 9312 // 9313 struct CoerceBuilder { 9314 llvm::LLVMContext &Context; 9315 const llvm::DataLayout &DL; 9316 SmallVector<llvm::Type*, 8> Elems; 9317 uint64_t Size; 9318 bool InReg; 9319 9320 CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl) 9321 : Context(c), DL(dl), Size(0), InReg(false) {} 9322 9323 // Pad Elems with integers until Size is ToSize. 9324 void pad(uint64_t ToSize) { 9325 assert(ToSize >= Size && "Cannot remove elements"); 9326 if (ToSize == Size) 9327 return; 9328 9329 // Finish the current 64-bit word. 9330 uint64_t Aligned = llvm::alignTo(Size, 64); 9331 if (Aligned > Size && Aligned <= ToSize) { 9332 Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size)); 9333 Size = Aligned; 9334 } 9335 9336 // Add whole 64-bit words. 9337 while (Size + 64 <= ToSize) { 9338 Elems.push_back(llvm::Type::getInt64Ty(Context)); 9339 Size += 64; 9340 } 9341 9342 // Final in-word padding. 9343 if (Size < ToSize) { 9344 Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size)); 9345 Size = ToSize; 9346 } 9347 } 9348 9349 // Add a floating point element at Offset. 9350 void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) { 9351 // Unaligned floats are treated as integers. 9352 if (Offset % Bits) 9353 return; 9354 // The InReg flag is only required if there are any floats < 64 bits. 9355 if (Bits < 64) 9356 InReg = true; 9357 pad(Offset); 9358 Elems.push_back(Ty); 9359 Size = Offset + Bits; 9360 } 9361 9362 // Add a struct type to the coercion type, starting at Offset (in bits). 9363 void addStruct(uint64_t Offset, llvm::StructType *StrTy) { 9364 const llvm::StructLayout *Layout = DL.getStructLayout(StrTy); 9365 for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) { 9366 llvm::Type *ElemTy = StrTy->getElementType(i); 9367 uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i); 9368 switch (ElemTy->getTypeID()) { 9369 case llvm::Type::StructTyID: 9370 addStruct(ElemOffset, cast<llvm::StructType>(ElemTy)); 9371 break; 9372 case llvm::Type::FloatTyID: 9373 addFloat(ElemOffset, ElemTy, 32); 9374 break; 9375 case llvm::Type::DoubleTyID: 9376 addFloat(ElemOffset, ElemTy, 64); 9377 break; 9378 case llvm::Type::FP128TyID: 9379 addFloat(ElemOffset, ElemTy, 128); 9380 break; 9381 case llvm::Type::PointerTyID: 9382 if (ElemOffset % 64 == 0) { 9383 pad(ElemOffset); 9384 Elems.push_back(ElemTy); 9385 Size += 64; 9386 } 9387 break; 9388 default: 9389 break; 9390 } 9391 } 9392 } 9393 9394 // Check if Ty is a usable substitute for the coercion type. 9395 bool isUsableType(llvm::StructType *Ty) const { 9396 return llvm::makeArrayRef(Elems) == Ty->elements(); 9397 } 9398 9399 // Get the coercion type as a literal struct type. 9400 llvm::Type *getType() const { 9401 if (Elems.size() == 1) 9402 return Elems.front(); 9403 else 9404 return llvm::StructType::get(Context, Elems); 9405 } 9406 }; 9407 }; 9408 } // end anonymous namespace 9409 9410 ABIArgInfo 9411 SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const { 9412 if (Ty->isVoidType()) 9413 return ABIArgInfo::getIgnore(); 9414 9415 uint64_t Size = getContext().getTypeSize(Ty); 9416 9417 // Anything too big to fit in registers is passed with an explicit indirect 9418 // pointer / sret pointer. 9419 if (Size > SizeLimit) 9420 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 9421 9422 // Treat an enum type as its underlying type. 9423 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 9424 Ty = EnumTy->getDecl()->getIntegerType(); 9425 9426 // Integer types smaller than a register are extended. 9427 if (Size < 64 && Ty->isIntegerType()) 9428 return ABIArgInfo::getExtend(Ty); 9429 9430 if (const auto *EIT = Ty->getAs<ExtIntType>()) 9431 if (EIT->getNumBits() < 64) 9432 return ABIArgInfo::getExtend(Ty); 9433 9434 // Other non-aggregates go in registers. 9435 if (!isAggregateTypeForABI(Ty)) 9436 return ABIArgInfo::getDirect(); 9437 9438 // If a C++ object has either a non-trivial copy constructor or a non-trivial 9439 // destructor, it is passed with an explicit indirect pointer / sret pointer. 9440 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 9441 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 9442 9443 // This is a small aggregate type that should be passed in registers. 9444 // Build a coercion type from the LLVM struct type. 9445 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty)); 9446 if (!StrTy) 9447 return ABIArgInfo::getDirect(); 9448 9449 CoerceBuilder CB(getVMContext(), getDataLayout()); 9450 CB.addStruct(0, StrTy); 9451 CB.pad(llvm::alignTo(CB.DL.getTypeSizeInBits(StrTy), 64)); 9452 9453 // Try to use the original type for coercion. 9454 llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType(); 9455 9456 if (CB.InReg) 9457 return ABIArgInfo::getDirectInReg(CoerceTy); 9458 else 9459 return ABIArgInfo::getDirect(CoerceTy); 9460 } 9461 9462 Address SparcV9ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 9463 QualType Ty) const { 9464 ABIArgInfo AI = classifyType(Ty, 16 * 8); 9465 llvm::Type *ArgTy = CGT.ConvertType(Ty); 9466 if (AI.canHaveCoerceToType() && !AI.getCoerceToType()) 9467 AI.setCoerceToType(ArgTy); 9468 9469 CharUnits SlotSize = CharUnits::fromQuantity(8); 9470 9471 CGBuilderTy &Builder = CGF.Builder; 9472 Address Addr(Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize); 9473 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy); 9474 9475 auto TypeInfo = getContext().getTypeInfoInChars(Ty); 9476 9477 Address ArgAddr = Address::invalid(); 9478 CharUnits Stride; 9479 switch (AI.getKind()) { 9480 case ABIArgInfo::Expand: 9481 case ABIArgInfo::CoerceAndExpand: 9482 case ABIArgInfo::InAlloca: 9483 llvm_unreachable("Unsupported ABI kind for va_arg"); 9484 9485 case ABIArgInfo::Extend: { 9486 Stride = SlotSize; 9487 CharUnits Offset = SlotSize - TypeInfo.Width; 9488 ArgAddr = Builder.CreateConstInBoundsByteGEP(Addr, Offset, "extend"); 9489 break; 9490 } 9491 9492 case ABIArgInfo::Direct: { 9493 auto AllocSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType()); 9494 Stride = CharUnits::fromQuantity(AllocSize).alignTo(SlotSize); 9495 ArgAddr = Addr; 9496 break; 9497 } 9498 9499 case ABIArgInfo::Indirect: 9500 case ABIArgInfo::IndirectAliased: 9501 Stride = SlotSize; 9502 ArgAddr = Builder.CreateElementBitCast(Addr, ArgPtrTy, "indirect"); 9503 ArgAddr = Address(Builder.CreateLoad(ArgAddr, "indirect.arg"), 9504 TypeInfo.Align); 9505 break; 9506 9507 case ABIArgInfo::Ignore: 9508 return Address(llvm::UndefValue::get(ArgPtrTy), TypeInfo.Align); 9509 } 9510 9511 // Update VAList. 9512 Address NextPtr = Builder.CreateConstInBoundsByteGEP(Addr, Stride, "ap.next"); 9513 Builder.CreateStore(NextPtr.getPointer(), VAListAddr); 9514 9515 return Builder.CreateBitCast(ArgAddr, ArgPtrTy, "arg.addr"); 9516 } 9517 9518 void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const { 9519 FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8); 9520 for (auto &I : FI.arguments()) 9521 I.info = classifyType(I.type, 16 * 8); 9522 } 9523 9524 namespace { 9525 class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo { 9526 public: 9527 SparcV9TargetCodeGenInfo(CodeGenTypes &CGT) 9528 : TargetCodeGenInfo(std::make_unique<SparcV9ABIInfo>(CGT)) {} 9529 9530 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 9531 return 14; 9532 } 9533 9534 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 9535 llvm::Value *Address) const override; 9536 }; 9537 } // end anonymous namespace 9538 9539 bool 9540 SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 9541 llvm::Value *Address) const { 9542 // This is calculated from the LLVM and GCC tables and verified 9543 // against gcc output. AFAIK all ABIs use the same encoding. 9544 9545 CodeGen::CGBuilderTy &Builder = CGF.Builder; 9546 9547 llvm::IntegerType *i8 = CGF.Int8Ty; 9548 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4); 9549 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8); 9550 9551 // 0-31: the 8-byte general-purpose registers 9552 AssignToArrayRange(Builder, Address, Eight8, 0, 31); 9553 9554 // 32-63: f0-31, the 4-byte floating-point registers 9555 AssignToArrayRange(Builder, Address, Four8, 32, 63); 9556 9557 // Y = 64 9558 // PSR = 65 9559 // WIM = 66 9560 // TBR = 67 9561 // PC = 68 9562 // NPC = 69 9563 // FSR = 70 9564 // CSR = 71 9565 AssignToArrayRange(Builder, Address, Eight8, 64, 71); 9566 9567 // 72-87: d0-15, the 8-byte floating-point registers 9568 AssignToArrayRange(Builder, Address, Eight8, 72, 87); 9569 9570 return false; 9571 } 9572 9573 // ARC ABI implementation. 9574 namespace { 9575 9576 class ARCABIInfo : public DefaultABIInfo { 9577 public: 9578 using DefaultABIInfo::DefaultABIInfo; 9579 9580 private: 9581 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 9582 QualType Ty) const override; 9583 9584 void updateState(const ABIArgInfo &Info, QualType Ty, CCState &State) const { 9585 if (!State.FreeRegs) 9586 return; 9587 if (Info.isIndirect() && Info.getInReg()) 9588 State.FreeRegs--; 9589 else if (Info.isDirect() && Info.getInReg()) { 9590 unsigned sz = (getContext().getTypeSize(Ty) + 31) / 32; 9591 if (sz < State.FreeRegs) 9592 State.FreeRegs -= sz; 9593 else 9594 State.FreeRegs = 0; 9595 } 9596 } 9597 9598 void computeInfo(CGFunctionInfo &FI) const override { 9599 CCState State(FI); 9600 // ARC uses 8 registers to pass arguments. 9601 State.FreeRegs = 8; 9602 9603 if (!getCXXABI().classifyReturnType(FI)) 9604 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 9605 updateState(FI.getReturnInfo(), FI.getReturnType(), State); 9606 for (auto &I : FI.arguments()) { 9607 I.info = classifyArgumentType(I.type, State.FreeRegs); 9608 updateState(I.info, I.type, State); 9609 } 9610 } 9611 9612 ABIArgInfo getIndirectByRef(QualType Ty, bool HasFreeRegs) const; 9613 ABIArgInfo getIndirectByValue(QualType Ty) const; 9614 ABIArgInfo classifyArgumentType(QualType Ty, uint8_t FreeRegs) const; 9615 ABIArgInfo classifyReturnType(QualType RetTy) const; 9616 }; 9617 9618 class ARCTargetCodeGenInfo : public TargetCodeGenInfo { 9619 public: 9620 ARCTargetCodeGenInfo(CodeGenTypes &CGT) 9621 : TargetCodeGenInfo(std::make_unique<ARCABIInfo>(CGT)) {} 9622 }; 9623 9624 9625 ABIArgInfo ARCABIInfo::getIndirectByRef(QualType Ty, bool HasFreeRegs) const { 9626 return HasFreeRegs ? getNaturalAlignIndirectInReg(Ty) : 9627 getNaturalAlignIndirect(Ty, false); 9628 } 9629 9630 ABIArgInfo ARCABIInfo::getIndirectByValue(QualType Ty) const { 9631 // Compute the byval alignment. 9632 const unsigned MinABIStackAlignInBytes = 4; 9633 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8; 9634 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true, 9635 TypeAlign > MinABIStackAlignInBytes); 9636 } 9637 9638 Address ARCABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 9639 QualType Ty) const { 9640 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false, 9641 getContext().getTypeInfoInChars(Ty), 9642 CharUnits::fromQuantity(4), true); 9643 } 9644 9645 ABIArgInfo ARCABIInfo::classifyArgumentType(QualType Ty, 9646 uint8_t FreeRegs) const { 9647 // Handle the generic C++ ABI. 9648 const RecordType *RT = Ty->getAs<RecordType>(); 9649 if (RT) { 9650 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()); 9651 if (RAA == CGCXXABI::RAA_Indirect) 9652 return getIndirectByRef(Ty, FreeRegs > 0); 9653 9654 if (RAA == CGCXXABI::RAA_DirectInMemory) 9655 return getIndirectByValue(Ty); 9656 } 9657 9658 // Treat an enum type as its underlying type. 9659 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 9660 Ty = EnumTy->getDecl()->getIntegerType(); 9661 9662 auto SizeInRegs = llvm::alignTo(getContext().getTypeSize(Ty), 32) / 32; 9663 9664 if (isAggregateTypeForABI(Ty)) { 9665 // Structures with flexible arrays are always indirect. 9666 if (RT && RT->getDecl()->hasFlexibleArrayMember()) 9667 return getIndirectByValue(Ty); 9668 9669 // Ignore empty structs/unions. 9670 if (isEmptyRecord(getContext(), Ty, true)) 9671 return ABIArgInfo::getIgnore(); 9672 9673 llvm::LLVMContext &LLVMContext = getVMContext(); 9674 9675 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext); 9676 SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32); 9677 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements); 9678 9679 return FreeRegs >= SizeInRegs ? 9680 ABIArgInfo::getDirectInReg(Result) : 9681 ABIArgInfo::getDirect(Result, 0, nullptr, false); 9682 } 9683 9684 if (const auto *EIT = Ty->getAs<ExtIntType>()) 9685 if (EIT->getNumBits() > 64) 9686 return getIndirectByValue(Ty); 9687 9688 return isPromotableIntegerTypeForABI(Ty) 9689 ? (FreeRegs >= SizeInRegs ? ABIArgInfo::getExtendInReg(Ty) 9690 : ABIArgInfo::getExtend(Ty)) 9691 : (FreeRegs >= SizeInRegs ? ABIArgInfo::getDirectInReg() 9692 : ABIArgInfo::getDirect()); 9693 } 9694 9695 ABIArgInfo ARCABIInfo::classifyReturnType(QualType RetTy) const { 9696 if (RetTy->isAnyComplexType()) 9697 return ABIArgInfo::getDirectInReg(); 9698 9699 // Arguments of size > 4 registers are indirect. 9700 auto RetSize = llvm::alignTo(getContext().getTypeSize(RetTy), 32) / 32; 9701 if (RetSize > 4) 9702 return getIndirectByRef(RetTy, /*HasFreeRegs*/ true); 9703 9704 return DefaultABIInfo::classifyReturnType(RetTy); 9705 } 9706 9707 } // End anonymous namespace. 9708 9709 //===----------------------------------------------------------------------===// 9710 // XCore ABI Implementation 9711 //===----------------------------------------------------------------------===// 9712 9713 namespace { 9714 9715 /// A SmallStringEnc instance is used to build up the TypeString by passing 9716 /// it by reference between functions that append to it. 9717 typedef llvm::SmallString<128> SmallStringEnc; 9718 9719 /// TypeStringCache caches the meta encodings of Types. 9720 /// 9721 /// The reason for caching TypeStrings is two fold: 9722 /// 1. To cache a type's encoding for later uses; 9723 /// 2. As a means to break recursive member type inclusion. 9724 /// 9725 /// A cache Entry can have a Status of: 9726 /// NonRecursive: The type encoding is not recursive; 9727 /// Recursive: The type encoding is recursive; 9728 /// Incomplete: An incomplete TypeString; 9729 /// IncompleteUsed: An incomplete TypeString that has been used in a 9730 /// Recursive type encoding. 9731 /// 9732 /// A NonRecursive entry will have all of its sub-members expanded as fully 9733 /// as possible. Whilst it may contain types which are recursive, the type 9734 /// itself is not recursive and thus its encoding may be safely used whenever 9735 /// the type is encountered. 9736 /// 9737 /// A Recursive entry will have all of its sub-members expanded as fully as 9738 /// possible. The type itself is recursive and it may contain other types which 9739 /// are recursive. The Recursive encoding must not be used during the expansion 9740 /// of a recursive type's recursive branch. For simplicity the code uses 9741 /// IncompleteCount to reject all usage of Recursive encodings for member types. 9742 /// 9743 /// An Incomplete entry is always a RecordType and only encodes its 9744 /// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and 9745 /// are placed into the cache during type expansion as a means to identify and 9746 /// handle recursive inclusion of types as sub-members. If there is recursion 9747 /// the entry becomes IncompleteUsed. 9748 /// 9749 /// During the expansion of a RecordType's members: 9750 /// 9751 /// If the cache contains a NonRecursive encoding for the member type, the 9752 /// cached encoding is used; 9753 /// 9754 /// If the cache contains a Recursive encoding for the member type, the 9755 /// cached encoding is 'Swapped' out, as it may be incorrect, and... 9756 /// 9757 /// If the member is a RecordType, an Incomplete encoding is placed into the 9758 /// cache to break potential recursive inclusion of itself as a sub-member; 9759 /// 9760 /// Once a member RecordType has been expanded, its temporary incomplete 9761 /// entry is removed from the cache. If a Recursive encoding was swapped out 9762 /// it is swapped back in; 9763 /// 9764 /// If an incomplete entry is used to expand a sub-member, the incomplete 9765 /// entry is marked as IncompleteUsed. The cache keeps count of how many 9766 /// IncompleteUsed entries it currently contains in IncompleteUsedCount; 9767 /// 9768 /// If a member's encoding is found to be a NonRecursive or Recursive viz: 9769 /// IncompleteUsedCount==0, the member's encoding is added to the cache. 9770 /// Else the member is part of a recursive type and thus the recursion has 9771 /// been exited too soon for the encoding to be correct for the member. 9772 /// 9773 class TypeStringCache { 9774 enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed}; 9775 struct Entry { 9776 std::string Str; // The encoded TypeString for the type. 9777 enum Status State; // Information about the encoding in 'Str'. 9778 std::string Swapped; // A temporary place holder for a Recursive encoding 9779 // during the expansion of RecordType's members. 9780 }; 9781 std::map<const IdentifierInfo *, struct Entry> Map; 9782 unsigned IncompleteCount; // Number of Incomplete entries in the Map. 9783 unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map. 9784 public: 9785 TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {} 9786 void addIncomplete(const IdentifierInfo *ID, std::string StubEnc); 9787 bool removeIncomplete(const IdentifierInfo *ID); 9788 void addIfComplete(const IdentifierInfo *ID, StringRef Str, 9789 bool IsRecursive); 9790 StringRef lookupStr(const IdentifierInfo *ID); 9791 }; 9792 9793 /// TypeString encodings for enum & union fields must be order. 9794 /// FieldEncoding is a helper for this ordering process. 9795 class FieldEncoding { 9796 bool HasName; 9797 std::string Enc; 9798 public: 9799 FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {} 9800 StringRef str() { return Enc; } 9801 bool operator<(const FieldEncoding &rhs) const { 9802 if (HasName != rhs.HasName) return HasName; 9803 return Enc < rhs.Enc; 9804 } 9805 }; 9806 9807 class XCoreABIInfo : public DefaultABIInfo { 9808 public: 9809 XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {} 9810 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 9811 QualType Ty) const override; 9812 }; 9813 9814 class XCoreTargetCodeGenInfo : public TargetCodeGenInfo { 9815 mutable TypeStringCache TSC; 9816 void emitTargetMD(const Decl *D, llvm::GlobalValue *GV, 9817 const CodeGen::CodeGenModule &M) const; 9818 9819 public: 9820 XCoreTargetCodeGenInfo(CodeGenTypes &CGT) 9821 : TargetCodeGenInfo(std::make_unique<XCoreABIInfo>(CGT)) {} 9822 void emitTargetMetadata(CodeGen::CodeGenModule &CGM, 9823 const llvm::MapVector<GlobalDecl, StringRef> 9824 &MangledDeclNames) const override; 9825 }; 9826 9827 } // End anonymous namespace. 9828 9829 // TODO: this implementation is likely now redundant with the default 9830 // EmitVAArg. 9831 Address XCoreABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 9832 QualType Ty) const { 9833 CGBuilderTy &Builder = CGF.Builder; 9834 9835 // Get the VAList. 9836 CharUnits SlotSize = CharUnits::fromQuantity(4); 9837 Address AP(Builder.CreateLoad(VAListAddr), SlotSize); 9838 9839 // Handle the argument. 9840 ABIArgInfo AI = classifyArgumentType(Ty); 9841 CharUnits TypeAlign = getContext().getTypeAlignInChars(Ty); 9842 llvm::Type *ArgTy = CGT.ConvertType(Ty); 9843 if (AI.canHaveCoerceToType() && !AI.getCoerceToType()) 9844 AI.setCoerceToType(ArgTy); 9845 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy); 9846 9847 Address Val = Address::invalid(); 9848 CharUnits ArgSize = CharUnits::Zero(); 9849 switch (AI.getKind()) { 9850 case ABIArgInfo::Expand: 9851 case ABIArgInfo::CoerceAndExpand: 9852 case ABIArgInfo::InAlloca: 9853 llvm_unreachable("Unsupported ABI kind for va_arg"); 9854 case ABIArgInfo::Ignore: 9855 Val = Address(llvm::UndefValue::get(ArgPtrTy), TypeAlign); 9856 ArgSize = CharUnits::Zero(); 9857 break; 9858 case ABIArgInfo::Extend: 9859 case ABIArgInfo::Direct: 9860 Val = Builder.CreateBitCast(AP, ArgPtrTy); 9861 ArgSize = CharUnits::fromQuantity( 9862 getDataLayout().getTypeAllocSize(AI.getCoerceToType())); 9863 ArgSize = ArgSize.alignTo(SlotSize); 9864 break; 9865 case ABIArgInfo::Indirect: 9866 case ABIArgInfo::IndirectAliased: 9867 Val = Builder.CreateElementBitCast(AP, ArgPtrTy); 9868 Val = Address(Builder.CreateLoad(Val), TypeAlign); 9869 ArgSize = SlotSize; 9870 break; 9871 } 9872 9873 // Increment the VAList. 9874 if (!ArgSize.isZero()) { 9875 Address APN = Builder.CreateConstInBoundsByteGEP(AP, ArgSize); 9876 Builder.CreateStore(APN.getPointer(), VAListAddr); 9877 } 9878 9879 return Val; 9880 } 9881 9882 /// During the expansion of a RecordType, an incomplete TypeString is placed 9883 /// into the cache as a means to identify and break recursion. 9884 /// If there is a Recursive encoding in the cache, it is swapped out and will 9885 /// be reinserted by removeIncomplete(). 9886 /// All other types of encoding should have been used rather than arriving here. 9887 void TypeStringCache::addIncomplete(const IdentifierInfo *ID, 9888 std::string StubEnc) { 9889 if (!ID) 9890 return; 9891 Entry &E = Map[ID]; 9892 assert( (E.Str.empty() || E.State == Recursive) && 9893 "Incorrectly use of addIncomplete"); 9894 assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()"); 9895 E.Swapped.swap(E.Str); // swap out the Recursive 9896 E.Str.swap(StubEnc); 9897 E.State = Incomplete; 9898 ++IncompleteCount; 9899 } 9900 9901 /// Once the RecordType has been expanded, the temporary incomplete TypeString 9902 /// must be removed from the cache. 9903 /// If a Recursive was swapped out by addIncomplete(), it will be replaced. 9904 /// Returns true if the RecordType was defined recursively. 9905 bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) { 9906 if (!ID) 9907 return false; 9908 auto I = Map.find(ID); 9909 assert(I != Map.end() && "Entry not present"); 9910 Entry &E = I->second; 9911 assert( (E.State == Incomplete || 9912 E.State == IncompleteUsed) && 9913 "Entry must be an incomplete type"); 9914 bool IsRecursive = false; 9915 if (E.State == IncompleteUsed) { 9916 // We made use of our Incomplete encoding, thus we are recursive. 9917 IsRecursive = true; 9918 --IncompleteUsedCount; 9919 } 9920 if (E.Swapped.empty()) 9921 Map.erase(I); 9922 else { 9923 // Swap the Recursive back. 9924 E.Swapped.swap(E.Str); 9925 E.Swapped.clear(); 9926 E.State = Recursive; 9927 } 9928 --IncompleteCount; 9929 return IsRecursive; 9930 } 9931 9932 /// Add the encoded TypeString to the cache only if it is NonRecursive or 9933 /// Recursive (viz: all sub-members were expanded as fully as possible). 9934 void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str, 9935 bool IsRecursive) { 9936 if (!ID || IncompleteUsedCount) 9937 return; // No key or it is is an incomplete sub-type so don't add. 9938 Entry &E = Map[ID]; 9939 if (IsRecursive && !E.Str.empty()) { 9940 assert(E.State==Recursive && E.Str.size() == Str.size() && 9941 "This is not the same Recursive entry"); 9942 // The parent container was not recursive after all, so we could have used 9943 // this Recursive sub-member entry after all, but we assumed the worse when 9944 // we started viz: IncompleteCount!=0. 9945 return; 9946 } 9947 assert(E.Str.empty() && "Entry already present"); 9948 E.Str = Str.str(); 9949 E.State = IsRecursive? Recursive : NonRecursive; 9950 } 9951 9952 /// Return a cached TypeString encoding for the ID. If there isn't one, or we 9953 /// are recursively expanding a type (IncompleteCount != 0) and the cached 9954 /// encoding is Recursive, return an empty StringRef. 9955 StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) { 9956 if (!ID) 9957 return StringRef(); // We have no key. 9958 auto I = Map.find(ID); 9959 if (I == Map.end()) 9960 return StringRef(); // We have no encoding. 9961 Entry &E = I->second; 9962 if (E.State == Recursive && IncompleteCount) 9963 return StringRef(); // We don't use Recursive encodings for member types. 9964 9965 if (E.State == Incomplete) { 9966 // The incomplete type is being used to break out of recursion. 9967 E.State = IncompleteUsed; 9968 ++IncompleteUsedCount; 9969 } 9970 return E.Str; 9971 } 9972 9973 /// The XCore ABI includes a type information section that communicates symbol 9974 /// type information to the linker. The linker uses this information to verify 9975 /// safety/correctness of things such as array bound and pointers et al. 9976 /// The ABI only requires C (and XC) language modules to emit TypeStrings. 9977 /// This type information (TypeString) is emitted into meta data for all global 9978 /// symbols: definitions, declarations, functions & variables. 9979 /// 9980 /// The TypeString carries type, qualifier, name, size & value details. 9981 /// Please see 'Tools Development Guide' section 2.16.2 for format details: 9982 /// https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf 9983 /// The output is tested by test/CodeGen/xcore-stringtype.c. 9984 /// 9985 static bool getTypeString(SmallStringEnc &Enc, const Decl *D, 9986 const CodeGen::CodeGenModule &CGM, 9987 TypeStringCache &TSC); 9988 9989 /// XCore uses emitTargetMD to emit TypeString metadata for global symbols. 9990 void XCoreTargetCodeGenInfo::emitTargetMD( 9991 const Decl *D, llvm::GlobalValue *GV, 9992 const CodeGen::CodeGenModule &CGM) const { 9993 SmallStringEnc Enc; 9994 if (getTypeString(Enc, D, CGM, TSC)) { 9995 llvm::LLVMContext &Ctx = CGM.getModule().getContext(); 9996 llvm::Metadata *MDVals[] = {llvm::ConstantAsMetadata::get(GV), 9997 llvm::MDString::get(Ctx, Enc.str())}; 9998 llvm::NamedMDNode *MD = 9999 CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings"); 10000 MD->addOperand(llvm::MDNode::get(Ctx, MDVals)); 10001 } 10002 } 10003 10004 void XCoreTargetCodeGenInfo::emitTargetMetadata( 10005 CodeGen::CodeGenModule &CGM, 10006 const llvm::MapVector<GlobalDecl, StringRef> &MangledDeclNames) const { 10007 // Warning, new MangledDeclNames may be appended within this loop. 10008 // We rely on MapVector insertions adding new elements to the end 10009 // of the container. 10010 for (unsigned I = 0; I != MangledDeclNames.size(); ++I) { 10011 auto Val = *(MangledDeclNames.begin() + I); 10012 llvm::GlobalValue *GV = CGM.GetGlobalValue(Val.second); 10013 if (GV) { 10014 const Decl *D = Val.first.getDecl()->getMostRecentDecl(); 10015 emitTargetMD(D, GV, CGM); 10016 } 10017 } 10018 } 10019 //===----------------------------------------------------------------------===// 10020 // SPIR ABI Implementation 10021 //===----------------------------------------------------------------------===// 10022 10023 namespace { 10024 class SPIRABIInfo : public DefaultABIInfo { 10025 public: 10026 SPIRABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) { setCCs(); } 10027 10028 private: 10029 void setCCs(); 10030 }; 10031 } // end anonymous namespace 10032 namespace { 10033 class SPIRTargetCodeGenInfo : public TargetCodeGenInfo { 10034 public: 10035 SPIRTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT) 10036 : TargetCodeGenInfo(std::make_unique<SPIRABIInfo>(CGT)) {} 10037 unsigned getOpenCLKernelCallingConv() const override; 10038 }; 10039 10040 } // End anonymous namespace. 10041 void SPIRABIInfo::setCCs() { 10042 assert(getRuntimeCC() == llvm::CallingConv::C); 10043 RuntimeCC = llvm::CallingConv::SPIR_FUNC; 10044 } 10045 10046 namespace clang { 10047 namespace CodeGen { 10048 void computeSPIRKernelABIInfo(CodeGenModule &CGM, CGFunctionInfo &FI) { 10049 DefaultABIInfo SPIRABI(CGM.getTypes()); 10050 SPIRABI.computeInfo(FI); 10051 } 10052 } 10053 } 10054 10055 unsigned SPIRTargetCodeGenInfo::getOpenCLKernelCallingConv() const { 10056 return llvm::CallingConv::SPIR_KERNEL; 10057 } 10058 10059 static bool appendType(SmallStringEnc &Enc, QualType QType, 10060 const CodeGen::CodeGenModule &CGM, 10061 TypeStringCache &TSC); 10062 10063 /// Helper function for appendRecordType(). 10064 /// Builds a SmallVector containing the encoded field types in declaration 10065 /// order. 10066 static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE, 10067 const RecordDecl *RD, 10068 const CodeGen::CodeGenModule &CGM, 10069 TypeStringCache &TSC) { 10070 for (const auto *Field : RD->fields()) { 10071 SmallStringEnc Enc; 10072 Enc += "m("; 10073 Enc += Field->getName(); 10074 Enc += "){"; 10075 if (Field->isBitField()) { 10076 Enc += "b("; 10077 llvm::raw_svector_ostream OS(Enc); 10078 OS << Field->getBitWidthValue(CGM.getContext()); 10079 Enc += ':'; 10080 } 10081 if (!appendType(Enc, Field->getType(), CGM, TSC)) 10082 return false; 10083 if (Field->isBitField()) 10084 Enc += ')'; 10085 Enc += '}'; 10086 FE.emplace_back(!Field->getName().empty(), Enc); 10087 } 10088 return true; 10089 } 10090 10091 /// Appends structure and union types to Enc and adds encoding to cache. 10092 /// Recursively calls appendType (via extractFieldType) for each field. 10093 /// Union types have their fields ordered according to the ABI. 10094 static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT, 10095 const CodeGen::CodeGenModule &CGM, 10096 TypeStringCache &TSC, const IdentifierInfo *ID) { 10097 // Append the cached TypeString if we have one. 10098 StringRef TypeString = TSC.lookupStr(ID); 10099 if (!TypeString.empty()) { 10100 Enc += TypeString; 10101 return true; 10102 } 10103 10104 // Start to emit an incomplete TypeString. 10105 size_t Start = Enc.size(); 10106 Enc += (RT->isUnionType()? 'u' : 's'); 10107 Enc += '('; 10108 if (ID) 10109 Enc += ID->getName(); 10110 Enc += "){"; 10111 10112 // We collect all encoded fields and order as necessary. 10113 bool IsRecursive = false; 10114 const RecordDecl *RD = RT->getDecl()->getDefinition(); 10115 if (RD && !RD->field_empty()) { 10116 // An incomplete TypeString stub is placed in the cache for this RecordType 10117 // so that recursive calls to this RecordType will use it whilst building a 10118 // complete TypeString for this RecordType. 10119 SmallVector<FieldEncoding, 16> FE; 10120 std::string StubEnc(Enc.substr(Start).str()); 10121 StubEnc += '}'; // StubEnc now holds a valid incomplete TypeString. 10122 TSC.addIncomplete(ID, std::move(StubEnc)); 10123 if (!extractFieldType(FE, RD, CGM, TSC)) { 10124 (void) TSC.removeIncomplete(ID); 10125 return false; 10126 } 10127 IsRecursive = TSC.removeIncomplete(ID); 10128 // The ABI requires unions to be sorted but not structures. 10129 // See FieldEncoding::operator< for sort algorithm. 10130 if (RT->isUnionType()) 10131 llvm::sort(FE); 10132 // We can now complete the TypeString. 10133 unsigned E = FE.size(); 10134 for (unsigned I = 0; I != E; ++I) { 10135 if (I) 10136 Enc += ','; 10137 Enc += FE[I].str(); 10138 } 10139 } 10140 Enc += '}'; 10141 TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive); 10142 return true; 10143 } 10144 10145 /// Appends enum types to Enc and adds the encoding to the cache. 10146 static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET, 10147 TypeStringCache &TSC, 10148 const IdentifierInfo *ID) { 10149 // Append the cached TypeString if we have one. 10150 StringRef TypeString = TSC.lookupStr(ID); 10151 if (!TypeString.empty()) { 10152 Enc += TypeString; 10153 return true; 10154 } 10155 10156 size_t Start = Enc.size(); 10157 Enc += "e("; 10158 if (ID) 10159 Enc += ID->getName(); 10160 Enc += "){"; 10161 10162 // We collect all encoded enumerations and order them alphanumerically. 10163 if (const EnumDecl *ED = ET->getDecl()->getDefinition()) { 10164 SmallVector<FieldEncoding, 16> FE; 10165 for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E; 10166 ++I) { 10167 SmallStringEnc EnumEnc; 10168 EnumEnc += "m("; 10169 EnumEnc += I->getName(); 10170 EnumEnc += "){"; 10171 I->getInitVal().toString(EnumEnc); 10172 EnumEnc += '}'; 10173 FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc)); 10174 } 10175 llvm::sort(FE); 10176 unsigned E = FE.size(); 10177 for (unsigned I = 0; I != E; ++I) { 10178 if (I) 10179 Enc += ','; 10180 Enc += FE[I].str(); 10181 } 10182 } 10183 Enc += '}'; 10184 TSC.addIfComplete(ID, Enc.substr(Start), false); 10185 return true; 10186 } 10187 10188 /// Appends type's qualifier to Enc. 10189 /// This is done prior to appending the type's encoding. 10190 static void appendQualifier(SmallStringEnc &Enc, QualType QT) { 10191 // Qualifiers are emitted in alphabetical order. 10192 static const char *const Table[]={"","c:","r:","cr:","v:","cv:","rv:","crv:"}; 10193 int Lookup = 0; 10194 if (QT.isConstQualified()) 10195 Lookup += 1<<0; 10196 if (QT.isRestrictQualified()) 10197 Lookup += 1<<1; 10198 if (QT.isVolatileQualified()) 10199 Lookup += 1<<2; 10200 Enc += Table[Lookup]; 10201 } 10202 10203 /// Appends built-in types to Enc. 10204 static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) { 10205 const char *EncType; 10206 switch (BT->getKind()) { 10207 case BuiltinType::Void: 10208 EncType = "0"; 10209 break; 10210 case BuiltinType::Bool: 10211 EncType = "b"; 10212 break; 10213 case BuiltinType::Char_U: 10214 EncType = "uc"; 10215 break; 10216 case BuiltinType::UChar: 10217 EncType = "uc"; 10218 break; 10219 case BuiltinType::SChar: 10220 EncType = "sc"; 10221 break; 10222 case BuiltinType::UShort: 10223 EncType = "us"; 10224 break; 10225 case BuiltinType::Short: 10226 EncType = "ss"; 10227 break; 10228 case BuiltinType::UInt: 10229 EncType = "ui"; 10230 break; 10231 case BuiltinType::Int: 10232 EncType = "si"; 10233 break; 10234 case BuiltinType::ULong: 10235 EncType = "ul"; 10236 break; 10237 case BuiltinType::Long: 10238 EncType = "sl"; 10239 break; 10240 case BuiltinType::ULongLong: 10241 EncType = "ull"; 10242 break; 10243 case BuiltinType::LongLong: 10244 EncType = "sll"; 10245 break; 10246 case BuiltinType::Float: 10247 EncType = "ft"; 10248 break; 10249 case BuiltinType::Double: 10250 EncType = "d"; 10251 break; 10252 case BuiltinType::LongDouble: 10253 EncType = "ld"; 10254 break; 10255 default: 10256 return false; 10257 } 10258 Enc += EncType; 10259 return true; 10260 } 10261 10262 /// Appends a pointer encoding to Enc before calling appendType for the pointee. 10263 static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT, 10264 const CodeGen::CodeGenModule &CGM, 10265 TypeStringCache &TSC) { 10266 Enc += "p("; 10267 if (!appendType(Enc, PT->getPointeeType(), CGM, TSC)) 10268 return false; 10269 Enc += ')'; 10270 return true; 10271 } 10272 10273 /// Appends array encoding to Enc before calling appendType for the element. 10274 static bool appendArrayType(SmallStringEnc &Enc, QualType QT, 10275 const ArrayType *AT, 10276 const CodeGen::CodeGenModule &CGM, 10277 TypeStringCache &TSC, StringRef NoSizeEnc) { 10278 if (AT->getSizeModifier() != ArrayType::Normal) 10279 return false; 10280 Enc += "a("; 10281 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) 10282 CAT->getSize().toStringUnsigned(Enc); 10283 else 10284 Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "". 10285 Enc += ':'; 10286 // The Qualifiers should be attached to the type rather than the array. 10287 appendQualifier(Enc, QT); 10288 if (!appendType(Enc, AT->getElementType(), CGM, TSC)) 10289 return false; 10290 Enc += ')'; 10291 return true; 10292 } 10293 10294 /// Appends a function encoding to Enc, calling appendType for the return type 10295 /// and the arguments. 10296 static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT, 10297 const CodeGen::CodeGenModule &CGM, 10298 TypeStringCache &TSC) { 10299 Enc += "f{"; 10300 if (!appendType(Enc, FT->getReturnType(), CGM, TSC)) 10301 return false; 10302 Enc += "}("; 10303 if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) { 10304 // N.B. we are only interested in the adjusted param types. 10305 auto I = FPT->param_type_begin(); 10306 auto E = FPT->param_type_end(); 10307 if (I != E) { 10308 do { 10309 if (!appendType(Enc, *I, CGM, TSC)) 10310 return false; 10311 ++I; 10312 if (I != E) 10313 Enc += ','; 10314 } while (I != E); 10315 if (FPT->isVariadic()) 10316 Enc += ",va"; 10317 } else { 10318 if (FPT->isVariadic()) 10319 Enc += "va"; 10320 else 10321 Enc += '0'; 10322 } 10323 } 10324 Enc += ')'; 10325 return true; 10326 } 10327 10328 /// Handles the type's qualifier before dispatching a call to handle specific 10329 /// type encodings. 10330 static bool appendType(SmallStringEnc &Enc, QualType QType, 10331 const CodeGen::CodeGenModule &CGM, 10332 TypeStringCache &TSC) { 10333 10334 QualType QT = QType.getCanonicalType(); 10335 10336 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) 10337 // The Qualifiers should be attached to the type rather than the array. 10338 // Thus we don't call appendQualifier() here. 10339 return appendArrayType(Enc, QT, AT, CGM, TSC, ""); 10340 10341 appendQualifier(Enc, QT); 10342 10343 if (const BuiltinType *BT = QT->getAs<BuiltinType>()) 10344 return appendBuiltinType(Enc, BT); 10345 10346 if (const PointerType *PT = QT->getAs<PointerType>()) 10347 return appendPointerType(Enc, PT, CGM, TSC); 10348 10349 if (const EnumType *ET = QT->getAs<EnumType>()) 10350 return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier()); 10351 10352 if (const RecordType *RT = QT->getAsStructureType()) 10353 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier()); 10354 10355 if (const RecordType *RT = QT->getAsUnionType()) 10356 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier()); 10357 10358 if (const FunctionType *FT = QT->getAs<FunctionType>()) 10359 return appendFunctionType(Enc, FT, CGM, TSC); 10360 10361 return false; 10362 } 10363 10364 static bool getTypeString(SmallStringEnc &Enc, const Decl *D, 10365 const CodeGen::CodeGenModule &CGM, 10366 TypeStringCache &TSC) { 10367 if (!D) 10368 return false; 10369 10370 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 10371 if (FD->getLanguageLinkage() != CLanguageLinkage) 10372 return false; 10373 return appendType(Enc, FD->getType(), CGM, TSC); 10374 } 10375 10376 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 10377 if (VD->getLanguageLinkage() != CLanguageLinkage) 10378 return false; 10379 QualType QT = VD->getType().getCanonicalType(); 10380 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) { 10381 // Global ArrayTypes are given a size of '*' if the size is unknown. 10382 // The Qualifiers should be attached to the type rather than the array. 10383 // Thus we don't call appendQualifier() here. 10384 return appendArrayType(Enc, QT, AT, CGM, TSC, "*"); 10385 } 10386 return appendType(Enc, QT, CGM, TSC); 10387 } 10388 return false; 10389 } 10390 10391 //===----------------------------------------------------------------------===// 10392 // RISCV ABI Implementation 10393 //===----------------------------------------------------------------------===// 10394 10395 namespace { 10396 class RISCVABIInfo : public DefaultABIInfo { 10397 private: 10398 // Size of the integer ('x') registers in bits. 10399 unsigned XLen; 10400 // Size of the floating point ('f') registers in bits. Note that the target 10401 // ISA might have a wider FLen than the selected ABI (e.g. an RV32IF target 10402 // with soft float ABI has FLen==0). 10403 unsigned FLen; 10404 static const int NumArgGPRs = 8; 10405 static const int NumArgFPRs = 8; 10406 bool detectFPCCEligibleStructHelper(QualType Ty, CharUnits CurOff, 10407 llvm::Type *&Field1Ty, 10408 CharUnits &Field1Off, 10409 llvm::Type *&Field2Ty, 10410 CharUnits &Field2Off) const; 10411 10412 public: 10413 RISCVABIInfo(CodeGen::CodeGenTypes &CGT, unsigned XLen, unsigned FLen) 10414 : DefaultABIInfo(CGT), XLen(XLen), FLen(FLen) {} 10415 10416 // DefaultABIInfo's classifyReturnType and classifyArgumentType are 10417 // non-virtual, but computeInfo is virtual, so we overload it. 10418 void computeInfo(CGFunctionInfo &FI) const override; 10419 10420 ABIArgInfo classifyArgumentType(QualType Ty, bool IsFixed, int &ArgGPRsLeft, 10421 int &ArgFPRsLeft) const; 10422 ABIArgInfo classifyReturnType(QualType RetTy) const; 10423 10424 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 10425 QualType Ty) const override; 10426 10427 ABIArgInfo extendType(QualType Ty) const; 10428 10429 bool detectFPCCEligibleStruct(QualType Ty, llvm::Type *&Field1Ty, 10430 CharUnits &Field1Off, llvm::Type *&Field2Ty, 10431 CharUnits &Field2Off, int &NeededArgGPRs, 10432 int &NeededArgFPRs) const; 10433 ABIArgInfo coerceAndExpandFPCCEligibleStruct(llvm::Type *Field1Ty, 10434 CharUnits Field1Off, 10435 llvm::Type *Field2Ty, 10436 CharUnits Field2Off) const; 10437 }; 10438 } // end anonymous namespace 10439 10440 void RISCVABIInfo::computeInfo(CGFunctionInfo &FI) const { 10441 QualType RetTy = FI.getReturnType(); 10442 if (!getCXXABI().classifyReturnType(FI)) 10443 FI.getReturnInfo() = classifyReturnType(RetTy); 10444 10445 // IsRetIndirect is true if classifyArgumentType indicated the value should 10446 // be passed indirect, or if the type size is a scalar greater than 2*XLen 10447 // and not a complex type with elements <= FLen. e.g. fp128 is passed direct 10448 // in LLVM IR, relying on the backend lowering code to rewrite the argument 10449 // list and pass indirectly on RV32. 10450 bool IsRetIndirect = FI.getReturnInfo().getKind() == ABIArgInfo::Indirect; 10451 if (!IsRetIndirect && RetTy->isScalarType() && 10452 getContext().getTypeSize(RetTy) > (2 * XLen)) { 10453 if (RetTy->isComplexType() && FLen) { 10454 QualType EltTy = RetTy->castAs<ComplexType>()->getElementType(); 10455 IsRetIndirect = getContext().getTypeSize(EltTy) > FLen; 10456 } else { 10457 // This is a normal scalar > 2*XLen, such as fp128 on RV32. 10458 IsRetIndirect = true; 10459 } 10460 } 10461 10462 // We must track the number of GPRs used in order to conform to the RISC-V 10463 // ABI, as integer scalars passed in registers should have signext/zeroext 10464 // when promoted, but are anyext if passed on the stack. As GPR usage is 10465 // different for variadic arguments, we must also track whether we are 10466 // examining a vararg or not. 10467 int ArgGPRsLeft = IsRetIndirect ? NumArgGPRs - 1 : NumArgGPRs; 10468 int ArgFPRsLeft = FLen ? NumArgFPRs : 0; 10469 int NumFixedArgs = FI.getNumRequiredArgs(); 10470 10471 int ArgNum = 0; 10472 for (auto &ArgInfo : FI.arguments()) { 10473 bool IsFixed = ArgNum < NumFixedArgs; 10474 ArgInfo.info = 10475 classifyArgumentType(ArgInfo.type, IsFixed, ArgGPRsLeft, ArgFPRsLeft); 10476 ArgNum++; 10477 } 10478 } 10479 10480 // Returns true if the struct is a potential candidate for the floating point 10481 // calling convention. If this function returns true, the caller is 10482 // responsible for checking that if there is only a single field then that 10483 // field is a float. 10484 bool RISCVABIInfo::detectFPCCEligibleStructHelper(QualType Ty, CharUnits CurOff, 10485 llvm::Type *&Field1Ty, 10486 CharUnits &Field1Off, 10487 llvm::Type *&Field2Ty, 10488 CharUnits &Field2Off) const { 10489 bool IsInt = Ty->isIntegralOrEnumerationType(); 10490 bool IsFloat = Ty->isRealFloatingType(); 10491 10492 if (IsInt || IsFloat) { 10493 uint64_t Size = getContext().getTypeSize(Ty); 10494 if (IsInt && Size > XLen) 10495 return false; 10496 // Can't be eligible if larger than the FP registers. Half precision isn't 10497 // currently supported on RISC-V and the ABI hasn't been confirmed, so 10498 // default to the integer ABI in that case. 10499 if (IsFloat && (Size > FLen || Size < 32)) 10500 return false; 10501 // Can't be eligible if an integer type was already found (int+int pairs 10502 // are not eligible). 10503 if (IsInt && Field1Ty && Field1Ty->isIntegerTy()) 10504 return false; 10505 if (!Field1Ty) { 10506 Field1Ty = CGT.ConvertType(Ty); 10507 Field1Off = CurOff; 10508 return true; 10509 } 10510 if (!Field2Ty) { 10511 Field2Ty = CGT.ConvertType(Ty); 10512 Field2Off = CurOff; 10513 return true; 10514 } 10515 return false; 10516 } 10517 10518 if (auto CTy = Ty->getAs<ComplexType>()) { 10519 if (Field1Ty) 10520 return false; 10521 QualType EltTy = CTy->getElementType(); 10522 if (getContext().getTypeSize(EltTy) > FLen) 10523 return false; 10524 Field1Ty = CGT.ConvertType(EltTy); 10525 Field1Off = CurOff; 10526 Field2Ty = Field1Ty; 10527 Field2Off = Field1Off + getContext().getTypeSizeInChars(EltTy); 10528 return true; 10529 } 10530 10531 if (const ConstantArrayType *ATy = getContext().getAsConstantArrayType(Ty)) { 10532 uint64_t ArraySize = ATy->getSize().getZExtValue(); 10533 QualType EltTy = ATy->getElementType(); 10534 CharUnits EltSize = getContext().getTypeSizeInChars(EltTy); 10535 for (uint64_t i = 0; i < ArraySize; ++i) { 10536 bool Ret = detectFPCCEligibleStructHelper(EltTy, CurOff, Field1Ty, 10537 Field1Off, Field2Ty, Field2Off); 10538 if (!Ret) 10539 return false; 10540 CurOff += EltSize; 10541 } 10542 return true; 10543 } 10544 10545 if (const auto *RTy = Ty->getAs<RecordType>()) { 10546 // Structures with either a non-trivial destructor or a non-trivial 10547 // copy constructor are not eligible for the FP calling convention. 10548 if (getRecordArgABI(Ty, CGT.getCXXABI())) 10549 return false; 10550 if (isEmptyRecord(getContext(), Ty, true)) 10551 return true; 10552 const RecordDecl *RD = RTy->getDecl(); 10553 // Unions aren't eligible unless they're empty (which is caught above). 10554 if (RD->isUnion()) 10555 return false; 10556 int ZeroWidthBitFieldCount = 0; 10557 for (const FieldDecl *FD : RD->fields()) { 10558 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD); 10559 uint64_t FieldOffInBits = Layout.getFieldOffset(FD->getFieldIndex()); 10560 QualType QTy = FD->getType(); 10561 if (FD->isBitField()) { 10562 unsigned BitWidth = FD->getBitWidthValue(getContext()); 10563 // Allow a bitfield with a type greater than XLen as long as the 10564 // bitwidth is XLen or less. 10565 if (getContext().getTypeSize(QTy) > XLen && BitWidth <= XLen) 10566 QTy = getContext().getIntTypeForBitwidth(XLen, false); 10567 if (BitWidth == 0) { 10568 ZeroWidthBitFieldCount++; 10569 continue; 10570 } 10571 } 10572 10573 bool Ret = detectFPCCEligibleStructHelper( 10574 QTy, CurOff + getContext().toCharUnitsFromBits(FieldOffInBits), 10575 Field1Ty, Field1Off, Field2Ty, Field2Off); 10576 if (!Ret) 10577 return false; 10578 10579 // As a quirk of the ABI, zero-width bitfields aren't ignored for fp+fp 10580 // or int+fp structs, but are ignored for a struct with an fp field and 10581 // any number of zero-width bitfields. 10582 if (Field2Ty && ZeroWidthBitFieldCount > 0) 10583 return false; 10584 } 10585 return Field1Ty != nullptr; 10586 } 10587 10588 return false; 10589 } 10590 10591 // Determine if a struct is eligible for passing according to the floating 10592 // point calling convention (i.e., when flattened it contains a single fp 10593 // value, fp+fp, or int+fp of appropriate size). If so, NeededArgFPRs and 10594 // NeededArgGPRs are incremented appropriately. 10595 bool RISCVABIInfo::detectFPCCEligibleStruct(QualType Ty, llvm::Type *&Field1Ty, 10596 CharUnits &Field1Off, 10597 llvm::Type *&Field2Ty, 10598 CharUnits &Field2Off, 10599 int &NeededArgGPRs, 10600 int &NeededArgFPRs) const { 10601 Field1Ty = nullptr; 10602 Field2Ty = nullptr; 10603 NeededArgGPRs = 0; 10604 NeededArgFPRs = 0; 10605 bool IsCandidate = detectFPCCEligibleStructHelper( 10606 Ty, CharUnits::Zero(), Field1Ty, Field1Off, Field2Ty, Field2Off); 10607 // Not really a candidate if we have a single int but no float. 10608 if (Field1Ty && !Field2Ty && !Field1Ty->isFloatingPointTy()) 10609 return false; 10610 if (!IsCandidate) 10611 return false; 10612 if (Field1Ty && Field1Ty->isFloatingPointTy()) 10613 NeededArgFPRs++; 10614 else if (Field1Ty) 10615 NeededArgGPRs++; 10616 if (Field2Ty && Field2Ty->isFloatingPointTy()) 10617 NeededArgFPRs++; 10618 else if (Field2Ty) 10619 NeededArgGPRs++; 10620 return true; 10621 } 10622 10623 // Call getCoerceAndExpand for the two-element flattened struct described by 10624 // Field1Ty, Field1Off, Field2Ty, Field2Off. This method will create an 10625 // appropriate coerceToType and unpaddedCoerceToType. 10626 ABIArgInfo RISCVABIInfo::coerceAndExpandFPCCEligibleStruct( 10627 llvm::Type *Field1Ty, CharUnits Field1Off, llvm::Type *Field2Ty, 10628 CharUnits Field2Off) const { 10629 SmallVector<llvm::Type *, 3> CoerceElts; 10630 SmallVector<llvm::Type *, 2> UnpaddedCoerceElts; 10631 if (!Field1Off.isZero()) 10632 CoerceElts.push_back(llvm::ArrayType::get( 10633 llvm::Type::getInt8Ty(getVMContext()), Field1Off.getQuantity())); 10634 10635 CoerceElts.push_back(Field1Ty); 10636 UnpaddedCoerceElts.push_back(Field1Ty); 10637 10638 if (!Field2Ty) { 10639 return ABIArgInfo::getCoerceAndExpand( 10640 llvm::StructType::get(getVMContext(), CoerceElts, !Field1Off.isZero()), 10641 UnpaddedCoerceElts[0]); 10642 } 10643 10644 CharUnits Field2Align = 10645 CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(Field2Ty)); 10646 CharUnits Field1End = Field1Off + 10647 CharUnits::fromQuantity(getDataLayout().getTypeStoreSize(Field1Ty)); 10648 CharUnits Field2OffNoPadNoPack = Field1End.alignTo(Field2Align); 10649 10650 CharUnits Padding = CharUnits::Zero(); 10651 if (Field2Off > Field2OffNoPadNoPack) 10652 Padding = Field2Off - Field2OffNoPadNoPack; 10653 else if (Field2Off != Field2Align && Field2Off > Field1End) 10654 Padding = Field2Off - Field1End; 10655 10656 bool IsPacked = !Field2Off.isMultipleOf(Field2Align); 10657 10658 if (!Padding.isZero()) 10659 CoerceElts.push_back(llvm::ArrayType::get( 10660 llvm::Type::getInt8Ty(getVMContext()), Padding.getQuantity())); 10661 10662 CoerceElts.push_back(Field2Ty); 10663 UnpaddedCoerceElts.push_back(Field2Ty); 10664 10665 auto CoerceToType = 10666 llvm::StructType::get(getVMContext(), CoerceElts, IsPacked); 10667 auto UnpaddedCoerceToType = 10668 llvm::StructType::get(getVMContext(), UnpaddedCoerceElts, IsPacked); 10669 10670 return ABIArgInfo::getCoerceAndExpand(CoerceToType, UnpaddedCoerceToType); 10671 } 10672 10673 ABIArgInfo RISCVABIInfo::classifyArgumentType(QualType Ty, bool IsFixed, 10674 int &ArgGPRsLeft, 10675 int &ArgFPRsLeft) const { 10676 assert(ArgGPRsLeft <= NumArgGPRs && "Arg GPR tracking underflow"); 10677 Ty = useFirstFieldIfTransparentUnion(Ty); 10678 10679 // Structures with either a non-trivial destructor or a non-trivial 10680 // copy constructor are always passed indirectly. 10681 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) { 10682 if (ArgGPRsLeft) 10683 ArgGPRsLeft -= 1; 10684 return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA == 10685 CGCXXABI::RAA_DirectInMemory); 10686 } 10687 10688 // Ignore empty structs/unions. 10689 if (isEmptyRecord(getContext(), Ty, true)) 10690 return ABIArgInfo::getIgnore(); 10691 10692 uint64_t Size = getContext().getTypeSize(Ty); 10693 10694 // Pass floating point values via FPRs if possible. 10695 if (IsFixed && Ty->isFloatingType() && !Ty->isComplexType() && 10696 FLen >= Size && ArgFPRsLeft) { 10697 ArgFPRsLeft--; 10698 return ABIArgInfo::getDirect(); 10699 } 10700 10701 // Complex types for the hard float ABI must be passed direct rather than 10702 // using CoerceAndExpand. 10703 if (IsFixed && Ty->isComplexType() && FLen && ArgFPRsLeft >= 2) { 10704 QualType EltTy = Ty->castAs<ComplexType>()->getElementType(); 10705 if (getContext().getTypeSize(EltTy) <= FLen) { 10706 ArgFPRsLeft -= 2; 10707 return ABIArgInfo::getDirect(); 10708 } 10709 } 10710 10711 if (IsFixed && FLen && Ty->isStructureOrClassType()) { 10712 llvm::Type *Field1Ty = nullptr; 10713 llvm::Type *Field2Ty = nullptr; 10714 CharUnits Field1Off = CharUnits::Zero(); 10715 CharUnits Field2Off = CharUnits::Zero(); 10716 int NeededArgGPRs = 0; 10717 int NeededArgFPRs = 0; 10718 bool IsCandidate = 10719 detectFPCCEligibleStruct(Ty, Field1Ty, Field1Off, Field2Ty, Field2Off, 10720 NeededArgGPRs, NeededArgFPRs); 10721 if (IsCandidate && NeededArgGPRs <= ArgGPRsLeft && 10722 NeededArgFPRs <= ArgFPRsLeft) { 10723 ArgGPRsLeft -= NeededArgGPRs; 10724 ArgFPRsLeft -= NeededArgFPRs; 10725 return coerceAndExpandFPCCEligibleStruct(Field1Ty, Field1Off, Field2Ty, 10726 Field2Off); 10727 } 10728 } 10729 10730 uint64_t NeededAlign = getContext().getTypeAlign(Ty); 10731 bool MustUseStack = false; 10732 // Determine the number of GPRs needed to pass the current argument 10733 // according to the ABI. 2*XLen-aligned varargs are passed in "aligned" 10734 // register pairs, so may consume 3 registers. 10735 int NeededArgGPRs = 1; 10736 if (!IsFixed && NeededAlign == 2 * XLen) 10737 NeededArgGPRs = 2 + (ArgGPRsLeft % 2); 10738 else if (Size > XLen && Size <= 2 * XLen) 10739 NeededArgGPRs = 2; 10740 10741 if (NeededArgGPRs > ArgGPRsLeft) { 10742 MustUseStack = true; 10743 NeededArgGPRs = ArgGPRsLeft; 10744 } 10745 10746 ArgGPRsLeft -= NeededArgGPRs; 10747 10748 if (!isAggregateTypeForABI(Ty) && !Ty->isVectorType()) { 10749 // Treat an enum type as its underlying type. 10750 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 10751 Ty = EnumTy->getDecl()->getIntegerType(); 10752 10753 // All integral types are promoted to XLen width, unless passed on the 10754 // stack. 10755 if (Size < XLen && Ty->isIntegralOrEnumerationType() && !MustUseStack) { 10756 return extendType(Ty); 10757 } 10758 10759 if (const auto *EIT = Ty->getAs<ExtIntType>()) { 10760 if (EIT->getNumBits() < XLen && !MustUseStack) 10761 return extendType(Ty); 10762 if (EIT->getNumBits() > 128 || 10763 (!getContext().getTargetInfo().hasInt128Type() && 10764 EIT->getNumBits() > 64)) 10765 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 10766 } 10767 10768 return ABIArgInfo::getDirect(); 10769 } 10770 10771 // Aggregates which are <= 2*XLen will be passed in registers if possible, 10772 // so coerce to integers. 10773 if (Size <= 2 * XLen) { 10774 unsigned Alignment = getContext().getTypeAlign(Ty); 10775 10776 // Use a single XLen int if possible, 2*XLen if 2*XLen alignment is 10777 // required, and a 2-element XLen array if only XLen alignment is required. 10778 if (Size <= XLen) { 10779 return ABIArgInfo::getDirect( 10780 llvm::IntegerType::get(getVMContext(), XLen)); 10781 } else if (Alignment == 2 * XLen) { 10782 return ABIArgInfo::getDirect( 10783 llvm::IntegerType::get(getVMContext(), 2 * XLen)); 10784 } else { 10785 return ABIArgInfo::getDirect(llvm::ArrayType::get( 10786 llvm::IntegerType::get(getVMContext(), XLen), 2)); 10787 } 10788 } 10789 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 10790 } 10791 10792 ABIArgInfo RISCVABIInfo::classifyReturnType(QualType RetTy) const { 10793 if (RetTy->isVoidType()) 10794 return ABIArgInfo::getIgnore(); 10795 10796 int ArgGPRsLeft = 2; 10797 int ArgFPRsLeft = FLen ? 2 : 0; 10798 10799 // The rules for return and argument types are the same, so defer to 10800 // classifyArgumentType. 10801 return classifyArgumentType(RetTy, /*IsFixed=*/true, ArgGPRsLeft, 10802 ArgFPRsLeft); 10803 } 10804 10805 Address RISCVABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 10806 QualType Ty) const { 10807 CharUnits SlotSize = CharUnits::fromQuantity(XLen / 8); 10808 10809 // Empty records are ignored for parameter passing purposes. 10810 if (isEmptyRecord(getContext(), Ty, true)) { 10811 Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize); 10812 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty)); 10813 return Addr; 10814 } 10815 10816 auto TInfo = getContext().getTypeInfoInChars(Ty); 10817 10818 // Arguments bigger than 2*Xlen bytes are passed indirectly. 10819 bool IsIndirect = TInfo.Width > 2 * SlotSize; 10820 10821 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TInfo, 10822 SlotSize, /*AllowHigherAlign=*/true); 10823 } 10824 10825 ABIArgInfo RISCVABIInfo::extendType(QualType Ty) const { 10826 int TySize = getContext().getTypeSize(Ty); 10827 // RV64 ABI requires unsigned 32 bit integers to be sign extended. 10828 if (XLen == 64 && Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32) 10829 return ABIArgInfo::getSignExtend(Ty); 10830 return ABIArgInfo::getExtend(Ty); 10831 } 10832 10833 namespace { 10834 class RISCVTargetCodeGenInfo : public TargetCodeGenInfo { 10835 public: 10836 RISCVTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, unsigned XLen, 10837 unsigned FLen) 10838 : TargetCodeGenInfo(std::make_unique<RISCVABIInfo>(CGT, XLen, FLen)) {} 10839 10840 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 10841 CodeGen::CodeGenModule &CGM) const override { 10842 const auto *FD = dyn_cast_or_null<FunctionDecl>(D); 10843 if (!FD) return; 10844 10845 const auto *Attr = FD->getAttr<RISCVInterruptAttr>(); 10846 if (!Attr) 10847 return; 10848 10849 const char *Kind; 10850 switch (Attr->getInterrupt()) { 10851 case RISCVInterruptAttr::user: Kind = "user"; break; 10852 case RISCVInterruptAttr::supervisor: Kind = "supervisor"; break; 10853 case RISCVInterruptAttr::machine: Kind = "machine"; break; 10854 } 10855 10856 auto *Fn = cast<llvm::Function>(GV); 10857 10858 Fn->addFnAttr("interrupt", Kind); 10859 } 10860 }; 10861 } // namespace 10862 10863 //===----------------------------------------------------------------------===// 10864 // VE ABI Implementation. 10865 // 10866 namespace { 10867 class VEABIInfo : public DefaultABIInfo { 10868 public: 10869 VEABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {} 10870 10871 private: 10872 ABIArgInfo classifyReturnType(QualType RetTy) const; 10873 ABIArgInfo classifyArgumentType(QualType RetTy) const; 10874 void computeInfo(CGFunctionInfo &FI) const override; 10875 }; 10876 } // end anonymous namespace 10877 10878 ABIArgInfo VEABIInfo::classifyReturnType(QualType Ty) const { 10879 if (Ty->isAnyComplexType()) 10880 return ABIArgInfo::getDirect(); 10881 uint64_t Size = getContext().getTypeSize(Ty); 10882 if (Size < 64 && Ty->isIntegerType()) 10883 return ABIArgInfo::getExtend(Ty); 10884 return DefaultABIInfo::classifyReturnType(Ty); 10885 } 10886 10887 ABIArgInfo VEABIInfo::classifyArgumentType(QualType Ty) const { 10888 if (Ty->isAnyComplexType()) 10889 return ABIArgInfo::getDirect(); 10890 uint64_t Size = getContext().getTypeSize(Ty); 10891 if (Size < 64 && Ty->isIntegerType()) 10892 return ABIArgInfo::getExtend(Ty); 10893 return DefaultABIInfo::classifyArgumentType(Ty); 10894 } 10895 10896 void VEABIInfo::computeInfo(CGFunctionInfo &FI) const { 10897 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 10898 for (auto &Arg : FI.arguments()) 10899 Arg.info = classifyArgumentType(Arg.type); 10900 } 10901 10902 namespace { 10903 class VETargetCodeGenInfo : public TargetCodeGenInfo { 10904 public: 10905 VETargetCodeGenInfo(CodeGenTypes &CGT) 10906 : TargetCodeGenInfo(std::make_unique<VEABIInfo>(CGT)) {} 10907 // VE ABI requires the arguments of variadic and prototype-less functions 10908 // are passed in both registers and memory. 10909 bool isNoProtoCallVariadic(const CallArgList &args, 10910 const FunctionNoProtoType *fnType) const override { 10911 return true; 10912 } 10913 }; 10914 } // end anonymous namespace 10915 10916 //===----------------------------------------------------------------------===// 10917 // Driver code 10918 //===----------------------------------------------------------------------===// 10919 10920 bool CodeGenModule::supportsCOMDAT() const { 10921 return getTriple().supportsCOMDAT(); 10922 } 10923 10924 const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() { 10925 if (TheTargetCodeGenInfo) 10926 return *TheTargetCodeGenInfo; 10927 10928 // Helper to set the unique_ptr while still keeping the return value. 10929 auto SetCGInfo = [&](TargetCodeGenInfo *P) -> const TargetCodeGenInfo & { 10930 this->TheTargetCodeGenInfo.reset(P); 10931 return *P; 10932 }; 10933 10934 const llvm::Triple &Triple = getTarget().getTriple(); 10935 switch (Triple.getArch()) { 10936 default: 10937 return SetCGInfo(new DefaultTargetCodeGenInfo(Types)); 10938 10939 case llvm::Triple::le32: 10940 return SetCGInfo(new PNaClTargetCodeGenInfo(Types)); 10941 case llvm::Triple::m68k: 10942 return SetCGInfo(new M68kTargetCodeGenInfo(Types)); 10943 case llvm::Triple::mips: 10944 case llvm::Triple::mipsel: 10945 if (Triple.getOS() == llvm::Triple::NaCl) 10946 return SetCGInfo(new PNaClTargetCodeGenInfo(Types)); 10947 return SetCGInfo(new MIPSTargetCodeGenInfo(Types, true)); 10948 10949 case llvm::Triple::mips64: 10950 case llvm::Triple::mips64el: 10951 return SetCGInfo(new MIPSTargetCodeGenInfo(Types, false)); 10952 10953 case llvm::Triple::avr: 10954 return SetCGInfo(new AVRTargetCodeGenInfo(Types)); 10955 10956 case llvm::Triple::aarch64: 10957 case llvm::Triple::aarch64_32: 10958 case llvm::Triple::aarch64_be: { 10959 AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS; 10960 if (getTarget().getABI() == "darwinpcs") 10961 Kind = AArch64ABIInfo::DarwinPCS; 10962 else if (Triple.isOSWindows()) 10963 return SetCGInfo( 10964 new WindowsAArch64TargetCodeGenInfo(Types, AArch64ABIInfo::Win64)); 10965 10966 return SetCGInfo(new AArch64TargetCodeGenInfo(Types, Kind)); 10967 } 10968 10969 case llvm::Triple::wasm32: 10970 case llvm::Triple::wasm64: { 10971 WebAssemblyABIInfo::ABIKind Kind = WebAssemblyABIInfo::MVP; 10972 if (getTarget().getABI() == "experimental-mv") 10973 Kind = WebAssemblyABIInfo::ExperimentalMV; 10974 return SetCGInfo(new WebAssemblyTargetCodeGenInfo(Types, Kind)); 10975 } 10976 10977 case llvm::Triple::arm: 10978 case llvm::Triple::armeb: 10979 case llvm::Triple::thumb: 10980 case llvm::Triple::thumbeb: { 10981 if (Triple.getOS() == llvm::Triple::Win32) { 10982 return SetCGInfo( 10983 new WindowsARMTargetCodeGenInfo(Types, ARMABIInfo::AAPCS_VFP)); 10984 } 10985 10986 ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS; 10987 StringRef ABIStr = getTarget().getABI(); 10988 if (ABIStr == "apcs-gnu") 10989 Kind = ARMABIInfo::APCS; 10990 else if (ABIStr == "aapcs16") 10991 Kind = ARMABIInfo::AAPCS16_VFP; 10992 else if (CodeGenOpts.FloatABI == "hard" || 10993 (CodeGenOpts.FloatABI != "soft" && 10994 (Triple.getEnvironment() == llvm::Triple::GNUEABIHF || 10995 Triple.getEnvironment() == llvm::Triple::MuslEABIHF || 10996 Triple.getEnvironment() == llvm::Triple::EABIHF))) 10997 Kind = ARMABIInfo::AAPCS_VFP; 10998 10999 return SetCGInfo(new ARMTargetCodeGenInfo(Types, Kind)); 11000 } 11001 11002 case llvm::Triple::ppc: { 11003 if (Triple.isOSAIX()) 11004 return SetCGInfo(new AIXTargetCodeGenInfo(Types, /*Is64Bit*/ false)); 11005 11006 bool IsSoftFloat = 11007 CodeGenOpts.FloatABI == "soft" || getTarget().hasFeature("spe"); 11008 bool RetSmallStructInRegABI = 11009 PPC32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts); 11010 return SetCGInfo( 11011 new PPC32TargetCodeGenInfo(Types, IsSoftFloat, RetSmallStructInRegABI)); 11012 } 11013 case llvm::Triple::ppcle: { 11014 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft"; 11015 bool RetSmallStructInRegABI = 11016 PPC32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts); 11017 return SetCGInfo( 11018 new PPC32TargetCodeGenInfo(Types, IsSoftFloat, RetSmallStructInRegABI)); 11019 } 11020 case llvm::Triple::ppc64: 11021 if (Triple.isOSAIX()) 11022 return SetCGInfo(new AIXTargetCodeGenInfo(Types, /*Is64Bit*/ true)); 11023 11024 if (Triple.isOSBinFormatELF()) { 11025 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1; 11026 if (getTarget().getABI() == "elfv2") 11027 Kind = PPC64_SVR4_ABIInfo::ELFv2; 11028 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft"; 11029 11030 return SetCGInfo( 11031 new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, IsSoftFloat)); 11032 } 11033 return SetCGInfo(new PPC64TargetCodeGenInfo(Types)); 11034 case llvm::Triple::ppc64le: { 11035 assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!"); 11036 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2; 11037 if (getTarget().getABI() == "elfv1") 11038 Kind = PPC64_SVR4_ABIInfo::ELFv1; 11039 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft"; 11040 11041 return SetCGInfo( 11042 new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, IsSoftFloat)); 11043 } 11044 11045 case llvm::Triple::nvptx: 11046 case llvm::Triple::nvptx64: 11047 return SetCGInfo(new NVPTXTargetCodeGenInfo(Types)); 11048 11049 case llvm::Triple::msp430: 11050 return SetCGInfo(new MSP430TargetCodeGenInfo(Types)); 11051 11052 case llvm::Triple::riscv32: 11053 case llvm::Triple::riscv64: { 11054 StringRef ABIStr = getTarget().getABI(); 11055 unsigned XLen = getTarget().getPointerWidth(0); 11056 unsigned ABIFLen = 0; 11057 if (ABIStr.endswith("f")) 11058 ABIFLen = 32; 11059 else if (ABIStr.endswith("d")) 11060 ABIFLen = 64; 11061 return SetCGInfo(new RISCVTargetCodeGenInfo(Types, XLen, ABIFLen)); 11062 } 11063 11064 case llvm::Triple::systemz: { 11065 bool SoftFloat = CodeGenOpts.FloatABI == "soft"; 11066 bool HasVector = !SoftFloat && getTarget().getABI() == "vector"; 11067 return SetCGInfo(new SystemZTargetCodeGenInfo(Types, HasVector, SoftFloat)); 11068 } 11069 11070 case llvm::Triple::tce: 11071 case llvm::Triple::tcele: 11072 return SetCGInfo(new TCETargetCodeGenInfo(Types)); 11073 11074 case llvm::Triple::x86: { 11075 bool IsDarwinVectorABI = Triple.isOSDarwin(); 11076 bool RetSmallStructInRegABI = 11077 X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts); 11078 bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing(); 11079 11080 if (Triple.getOS() == llvm::Triple::Win32) { 11081 return SetCGInfo(new WinX86_32TargetCodeGenInfo( 11082 Types, IsDarwinVectorABI, RetSmallStructInRegABI, 11083 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters)); 11084 } else { 11085 return SetCGInfo(new X86_32TargetCodeGenInfo( 11086 Types, IsDarwinVectorABI, RetSmallStructInRegABI, 11087 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters, 11088 CodeGenOpts.FloatABI == "soft")); 11089 } 11090 } 11091 11092 case llvm::Triple::x86_64: { 11093 StringRef ABI = getTarget().getABI(); 11094 X86AVXABILevel AVXLevel = 11095 (ABI == "avx512" 11096 ? X86AVXABILevel::AVX512 11097 : ABI == "avx" ? X86AVXABILevel::AVX : X86AVXABILevel::None); 11098 11099 switch (Triple.getOS()) { 11100 case llvm::Triple::Win32: 11101 return SetCGInfo(new WinX86_64TargetCodeGenInfo(Types, AVXLevel)); 11102 default: 11103 return SetCGInfo(new X86_64TargetCodeGenInfo(Types, AVXLevel)); 11104 } 11105 } 11106 case llvm::Triple::hexagon: 11107 return SetCGInfo(new HexagonTargetCodeGenInfo(Types)); 11108 case llvm::Triple::lanai: 11109 return SetCGInfo(new LanaiTargetCodeGenInfo(Types)); 11110 case llvm::Triple::r600: 11111 return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types)); 11112 case llvm::Triple::amdgcn: 11113 return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types)); 11114 case llvm::Triple::sparc: 11115 return SetCGInfo(new SparcV8TargetCodeGenInfo(Types)); 11116 case llvm::Triple::sparcv9: 11117 return SetCGInfo(new SparcV9TargetCodeGenInfo(Types)); 11118 case llvm::Triple::xcore: 11119 return SetCGInfo(new XCoreTargetCodeGenInfo(Types)); 11120 case llvm::Triple::arc: 11121 return SetCGInfo(new ARCTargetCodeGenInfo(Types)); 11122 case llvm::Triple::spir: 11123 case llvm::Triple::spir64: 11124 return SetCGInfo(new SPIRTargetCodeGenInfo(Types)); 11125 case llvm::Triple::ve: 11126 return SetCGInfo(new VETargetCodeGenInfo(Types)); 11127 } 11128 } 11129 11130 /// Create an OpenCL kernel for an enqueued block. 11131 /// 11132 /// The kernel has the same function type as the block invoke function. Its 11133 /// name is the name of the block invoke function postfixed with "_kernel". 11134 /// It simply calls the block invoke function then returns. 11135 llvm::Function * 11136 TargetCodeGenInfo::createEnqueuedBlockKernel(CodeGenFunction &CGF, 11137 llvm::Function *Invoke, 11138 llvm::Value *BlockLiteral) const { 11139 auto *InvokeFT = Invoke->getFunctionType(); 11140 llvm::SmallVector<llvm::Type *, 2> ArgTys; 11141 for (auto &P : InvokeFT->params()) 11142 ArgTys.push_back(P); 11143 auto &C = CGF.getLLVMContext(); 11144 std::string Name = Invoke->getName().str() + "_kernel"; 11145 auto *FT = llvm::FunctionType::get(llvm::Type::getVoidTy(C), ArgTys, false); 11146 auto *F = llvm::Function::Create(FT, llvm::GlobalValue::InternalLinkage, Name, 11147 &CGF.CGM.getModule()); 11148 auto IP = CGF.Builder.saveIP(); 11149 auto *BB = llvm::BasicBlock::Create(C, "entry", F); 11150 auto &Builder = CGF.Builder; 11151 Builder.SetInsertPoint(BB); 11152 llvm::SmallVector<llvm::Value *, 2> Args; 11153 for (auto &A : F->args()) 11154 Args.push_back(&A); 11155 llvm::CallInst *call = Builder.CreateCall(Invoke, Args); 11156 call->setCallingConv(Invoke->getCallingConv()); 11157 Builder.CreateRetVoid(); 11158 Builder.restoreIP(IP); 11159 return F; 11160 } 11161 11162 /// Create an OpenCL kernel for an enqueued block. 11163 /// 11164 /// The type of the first argument (the block literal) is the struct type 11165 /// of the block literal instead of a pointer type. The first argument 11166 /// (block literal) is passed directly by value to the kernel. The kernel 11167 /// allocates the same type of struct on stack and stores the block literal 11168 /// to it and passes its pointer to the block invoke function. The kernel 11169 /// has "enqueued-block" function attribute and kernel argument metadata. 11170 llvm::Function *AMDGPUTargetCodeGenInfo::createEnqueuedBlockKernel( 11171 CodeGenFunction &CGF, llvm::Function *Invoke, 11172 llvm::Value *BlockLiteral) const { 11173 auto &Builder = CGF.Builder; 11174 auto &C = CGF.getLLVMContext(); 11175 11176 auto *BlockTy = BlockLiteral->getType()->getPointerElementType(); 11177 auto *InvokeFT = Invoke->getFunctionType(); 11178 llvm::SmallVector<llvm::Type *, 2> ArgTys; 11179 llvm::SmallVector<llvm::Metadata *, 8> AddressQuals; 11180 llvm::SmallVector<llvm::Metadata *, 8> AccessQuals; 11181 llvm::SmallVector<llvm::Metadata *, 8> ArgTypeNames; 11182 llvm::SmallVector<llvm::Metadata *, 8> ArgBaseTypeNames; 11183 llvm::SmallVector<llvm::Metadata *, 8> ArgTypeQuals; 11184 llvm::SmallVector<llvm::Metadata *, 8> ArgNames; 11185 11186 ArgTys.push_back(BlockTy); 11187 ArgTypeNames.push_back(llvm::MDString::get(C, "__block_literal")); 11188 AddressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(0))); 11189 ArgBaseTypeNames.push_back(llvm::MDString::get(C, "__block_literal")); 11190 ArgTypeQuals.push_back(llvm::MDString::get(C, "")); 11191 AccessQuals.push_back(llvm::MDString::get(C, "none")); 11192 ArgNames.push_back(llvm::MDString::get(C, "block_literal")); 11193 for (unsigned I = 1, E = InvokeFT->getNumParams(); I < E; ++I) { 11194 ArgTys.push_back(InvokeFT->getParamType(I)); 11195 ArgTypeNames.push_back(llvm::MDString::get(C, "void*")); 11196 AddressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(3))); 11197 AccessQuals.push_back(llvm::MDString::get(C, "none")); 11198 ArgBaseTypeNames.push_back(llvm::MDString::get(C, "void*")); 11199 ArgTypeQuals.push_back(llvm::MDString::get(C, "")); 11200 ArgNames.push_back( 11201 llvm::MDString::get(C, (Twine("local_arg") + Twine(I)).str())); 11202 } 11203 std::string Name = Invoke->getName().str() + "_kernel"; 11204 auto *FT = llvm::FunctionType::get(llvm::Type::getVoidTy(C), ArgTys, false); 11205 auto *F = llvm::Function::Create(FT, llvm::GlobalValue::InternalLinkage, Name, 11206 &CGF.CGM.getModule()); 11207 F->addFnAttr("enqueued-block"); 11208 auto IP = CGF.Builder.saveIP(); 11209 auto *BB = llvm::BasicBlock::Create(C, "entry", F); 11210 Builder.SetInsertPoint(BB); 11211 const auto BlockAlign = CGF.CGM.getDataLayout().getPrefTypeAlign(BlockTy); 11212 auto *BlockPtr = Builder.CreateAlloca(BlockTy, nullptr); 11213 BlockPtr->setAlignment(BlockAlign); 11214 Builder.CreateAlignedStore(F->arg_begin(), BlockPtr, BlockAlign); 11215 auto *Cast = Builder.CreatePointerCast(BlockPtr, InvokeFT->getParamType(0)); 11216 llvm::SmallVector<llvm::Value *, 2> Args; 11217 Args.push_back(Cast); 11218 for (auto I = F->arg_begin() + 1, E = F->arg_end(); I != E; ++I) 11219 Args.push_back(I); 11220 llvm::CallInst *call = Builder.CreateCall(Invoke, Args); 11221 call->setCallingConv(Invoke->getCallingConv()); 11222 Builder.CreateRetVoid(); 11223 Builder.restoreIP(IP); 11224 11225 F->setMetadata("kernel_arg_addr_space", llvm::MDNode::get(C, AddressQuals)); 11226 F->setMetadata("kernel_arg_access_qual", llvm::MDNode::get(C, AccessQuals)); 11227 F->setMetadata("kernel_arg_type", llvm::MDNode::get(C, ArgTypeNames)); 11228 F->setMetadata("kernel_arg_base_type", 11229 llvm::MDNode::get(C, ArgBaseTypeNames)); 11230 F->setMetadata("kernel_arg_type_qual", llvm::MDNode::get(C, ArgTypeQuals)); 11231 if (CGF.CGM.getCodeGenOpts().EmitOpenCLArgMetadata) 11232 F->setMetadata("kernel_arg_name", llvm::MDNode::get(C, ArgNames)); 11233 11234 return F; 11235 } 11236