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/CodeGen/CGFunctionInfo.h" 25 #include "clang/CodeGen/SwiftCallingConv.h" 26 #include "llvm/ADT/SmallBitVector.h" 27 #include "llvm/ADT/StringExtras.h" 28 #include "llvm/ADT/StringSwitch.h" 29 #include "llvm/ADT/Triple.h" 30 #include "llvm/ADT/Twine.h" 31 #include "llvm/IR/DataLayout.h" 32 #include "llvm/IR/IntrinsicsNVPTX.h" 33 #include "llvm/IR/Type.h" 34 #include "llvm/Support/raw_ostream.h" 35 #include <algorithm> // std::sort 36 37 using namespace clang; 38 using namespace CodeGen; 39 40 // Helper for coercing an aggregate argument or return value into an integer 41 // array of the same size (including padding) and alignment. This alternate 42 // coercion happens only for the RenderScript ABI and can be removed after 43 // runtimes that rely on it are no longer supported. 44 // 45 // RenderScript assumes that the size of the argument / return value in the IR 46 // is the same as the size of the corresponding qualified type. This helper 47 // coerces the aggregate type into an array of the same size (including 48 // padding). This coercion is used in lieu of expansion of struct members or 49 // other canonical coercions that return a coerced-type of larger size. 50 // 51 // Ty - The argument / return value type 52 // Context - The associated ASTContext 53 // LLVMContext - The associated LLVMContext 54 static ABIArgInfo coerceToIntArray(QualType Ty, 55 ASTContext &Context, 56 llvm::LLVMContext &LLVMContext) { 57 // Alignment and Size are measured in bits. 58 const uint64_t Size = Context.getTypeSize(Ty); 59 const uint64_t Alignment = Context.getTypeAlign(Ty); 60 llvm::Type *IntType = llvm::Type::getIntNTy(LLVMContext, Alignment); 61 const uint64_t NumElements = (Size + Alignment - 1) / Alignment; 62 return ABIArgInfo::getDirect(llvm::ArrayType::get(IntType, NumElements)); 63 } 64 65 static void AssignToArrayRange(CodeGen::CGBuilderTy &Builder, 66 llvm::Value *Array, 67 llvm::Value *Value, 68 unsigned FirstIndex, 69 unsigned LastIndex) { 70 // Alternatively, we could emit this as a loop in the source. 71 for (unsigned I = FirstIndex; I <= LastIndex; ++I) { 72 llvm::Value *Cell = 73 Builder.CreateConstInBoundsGEP1_32(Builder.getInt8Ty(), Array, I); 74 Builder.CreateAlignedStore(Value, Cell, CharUnits::One()); 75 } 76 } 77 78 static bool isAggregateTypeForABI(QualType T) { 79 return !CodeGenFunction::hasScalarEvaluationKind(T) || 80 T->isMemberFunctionPointerType(); 81 } 82 83 ABIArgInfo 84 ABIInfo::getNaturalAlignIndirect(QualType Ty, bool ByRef, bool Realign, 85 llvm::Type *Padding) const { 86 return ABIArgInfo::getIndirect(getContext().getTypeAlignInChars(Ty), 87 ByRef, Realign, Padding); 88 } 89 90 ABIArgInfo 91 ABIInfo::getNaturalAlignIndirectInReg(QualType Ty, bool Realign) const { 92 return ABIArgInfo::getIndirectInReg(getContext().getTypeAlignInChars(Ty), 93 /*ByRef*/ false, Realign); 94 } 95 96 Address ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr, 97 QualType Ty) const { 98 return Address::invalid(); 99 } 100 101 bool ABIInfo::isPromotableIntegerTypeForABI(QualType Ty) const { 102 if (Ty->isPromotableIntegerType()) 103 return true; 104 105 if (const auto *EIT = Ty->getAs<ExtIntType>()) 106 if (EIT->getNumBits() < getContext().getTypeSize(getContext().IntTy)) 107 return true; 108 109 return false; 110 } 111 112 ABIInfo::~ABIInfo() {} 113 114 /// Does the given lowering require more than the given number of 115 /// registers when expanded? 116 /// 117 /// This is intended to be the basis of a reasonable basic implementation 118 /// of should{Pass,Return}IndirectlyForSwift. 119 /// 120 /// For most targets, a limit of four total registers is reasonable; this 121 /// limits the amount of code required in order to move around the value 122 /// in case it wasn't produced immediately prior to the call by the caller 123 /// (or wasn't produced in exactly the right registers) or isn't used 124 /// immediately within the callee. But some targets may need to further 125 /// limit the register count due to an inability to support that many 126 /// return registers. 127 static bool occupiesMoreThan(CodeGenTypes &cgt, 128 ArrayRef<llvm::Type*> scalarTypes, 129 unsigned maxAllRegisters) { 130 unsigned intCount = 0, fpCount = 0; 131 for (llvm::Type *type : scalarTypes) { 132 if (type->isPointerTy()) { 133 intCount++; 134 } else if (auto intTy = dyn_cast<llvm::IntegerType>(type)) { 135 auto ptrWidth = cgt.getTarget().getPointerWidth(0); 136 intCount += (intTy->getBitWidth() + ptrWidth - 1) / ptrWidth; 137 } else { 138 assert(type->isVectorTy() || type->isFloatingPointTy()); 139 fpCount++; 140 } 141 } 142 143 return (intCount + fpCount > maxAllRegisters); 144 } 145 146 bool SwiftABIInfo::isLegalVectorTypeForSwift(CharUnits vectorSize, 147 llvm::Type *eltTy, 148 unsigned numElts) const { 149 // The default implementation of this assumes that the target guarantees 150 // 128-bit SIMD support but nothing more. 151 return (vectorSize.getQuantity() > 8 && vectorSize.getQuantity() <= 16); 152 } 153 154 static CGCXXABI::RecordArgABI getRecordArgABI(const RecordType *RT, 155 CGCXXABI &CXXABI) { 156 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 157 if (!RD) { 158 if (!RT->getDecl()->canPassInRegisters()) 159 return CGCXXABI::RAA_Indirect; 160 return CGCXXABI::RAA_Default; 161 } 162 return CXXABI.getRecordArgABI(RD); 163 } 164 165 static CGCXXABI::RecordArgABI getRecordArgABI(QualType T, 166 CGCXXABI &CXXABI) { 167 const RecordType *RT = T->getAs<RecordType>(); 168 if (!RT) 169 return CGCXXABI::RAA_Default; 170 return getRecordArgABI(RT, CXXABI); 171 } 172 173 static bool classifyReturnType(const CGCXXABI &CXXABI, CGFunctionInfo &FI, 174 const ABIInfo &Info) { 175 QualType Ty = FI.getReturnType(); 176 177 if (const auto *RT = Ty->getAs<RecordType>()) 178 if (!isa<CXXRecordDecl>(RT->getDecl()) && 179 !RT->getDecl()->canPassInRegisters()) { 180 FI.getReturnInfo() = Info.getNaturalAlignIndirect(Ty); 181 return true; 182 } 183 184 return CXXABI.classifyReturnType(FI); 185 } 186 187 /// Pass transparent unions as if they were the type of the first element. Sema 188 /// should ensure that all elements of the union have the same "machine type". 189 static QualType useFirstFieldIfTransparentUnion(QualType Ty) { 190 if (const RecordType *UT = Ty->getAsUnionType()) { 191 const RecordDecl *UD = UT->getDecl(); 192 if (UD->hasAttr<TransparentUnionAttr>()) { 193 assert(!UD->field_empty() && "sema created an empty transparent union"); 194 return UD->field_begin()->getType(); 195 } 196 } 197 return Ty; 198 } 199 200 CGCXXABI &ABIInfo::getCXXABI() const { 201 return CGT.getCXXABI(); 202 } 203 204 ASTContext &ABIInfo::getContext() const { 205 return CGT.getContext(); 206 } 207 208 llvm::LLVMContext &ABIInfo::getVMContext() const { 209 return CGT.getLLVMContext(); 210 } 211 212 const llvm::DataLayout &ABIInfo::getDataLayout() const { 213 return CGT.getDataLayout(); 214 } 215 216 const TargetInfo &ABIInfo::getTarget() const { 217 return CGT.getTarget(); 218 } 219 220 const CodeGenOptions &ABIInfo::getCodeGenOpts() const { 221 return CGT.getCodeGenOpts(); 222 } 223 224 bool ABIInfo::isAndroid() const { return getTarget().getTriple().isAndroid(); } 225 226 bool ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const { 227 return false; 228 } 229 230 bool ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base, 231 uint64_t Members) const { 232 return false; 233 } 234 235 LLVM_DUMP_METHOD void ABIArgInfo::dump() const { 236 raw_ostream &OS = llvm::errs(); 237 OS << "(ABIArgInfo Kind="; 238 switch (TheKind) { 239 case Direct: 240 OS << "Direct Type="; 241 if (llvm::Type *Ty = getCoerceToType()) 242 Ty->print(OS); 243 else 244 OS << "null"; 245 break; 246 case Extend: 247 OS << "Extend"; 248 break; 249 case Ignore: 250 OS << "Ignore"; 251 break; 252 case InAlloca: 253 OS << "InAlloca Offset=" << getInAllocaFieldIndex(); 254 break; 255 case Indirect: 256 OS << "Indirect Align=" << getIndirectAlign().getQuantity() 257 << " ByVal=" << getIndirectByVal() 258 << " Realign=" << getIndirectRealign(); 259 break; 260 case Expand: 261 OS << "Expand"; 262 break; 263 case CoerceAndExpand: 264 OS << "CoerceAndExpand Type="; 265 getCoerceAndExpandType()->print(OS); 266 break; 267 } 268 OS << ")\n"; 269 } 270 271 // Dynamically round a pointer up to a multiple of the given alignment. 272 static llvm::Value *emitRoundPointerUpToAlignment(CodeGenFunction &CGF, 273 llvm::Value *Ptr, 274 CharUnits Align) { 275 llvm::Value *PtrAsInt = Ptr; 276 // OverflowArgArea = (OverflowArgArea + Align - 1) & -Align; 277 PtrAsInt = CGF.Builder.CreatePtrToInt(PtrAsInt, CGF.IntPtrTy); 278 PtrAsInt = CGF.Builder.CreateAdd(PtrAsInt, 279 llvm::ConstantInt::get(CGF.IntPtrTy, Align.getQuantity() - 1)); 280 PtrAsInt = CGF.Builder.CreateAnd(PtrAsInt, 281 llvm::ConstantInt::get(CGF.IntPtrTy, -Align.getQuantity())); 282 PtrAsInt = CGF.Builder.CreateIntToPtr(PtrAsInt, 283 Ptr->getType(), 284 Ptr->getName() + ".aligned"); 285 return PtrAsInt; 286 } 287 288 /// Emit va_arg for a platform using the common void* representation, 289 /// where arguments are simply emitted in an array of slots on the stack. 290 /// 291 /// This version implements the core direct-value passing rules. 292 /// 293 /// \param SlotSize - The size and alignment of a stack slot. 294 /// Each argument will be allocated to a multiple of this number of 295 /// slots, and all the slots will be aligned to this value. 296 /// \param AllowHigherAlign - The slot alignment is not a cap; 297 /// an argument type with an alignment greater than the slot size 298 /// will be emitted on a higher-alignment address, potentially 299 /// leaving one or more empty slots behind as padding. If this 300 /// is false, the returned address might be less-aligned than 301 /// DirectAlign. 302 static Address emitVoidPtrDirectVAArg(CodeGenFunction &CGF, 303 Address VAListAddr, 304 llvm::Type *DirectTy, 305 CharUnits DirectSize, 306 CharUnits DirectAlign, 307 CharUnits SlotSize, 308 bool AllowHigherAlign) { 309 // Cast the element type to i8* if necessary. Some platforms define 310 // va_list as a struct containing an i8* instead of just an i8*. 311 if (VAListAddr.getElementType() != CGF.Int8PtrTy) 312 VAListAddr = CGF.Builder.CreateElementBitCast(VAListAddr, CGF.Int8PtrTy); 313 314 llvm::Value *Ptr = CGF.Builder.CreateLoad(VAListAddr, "argp.cur"); 315 316 // If the CC aligns values higher than the slot size, do so if needed. 317 Address Addr = Address::invalid(); 318 if (AllowHigherAlign && DirectAlign > SlotSize) { 319 Addr = Address(emitRoundPointerUpToAlignment(CGF, Ptr, DirectAlign), 320 DirectAlign); 321 } else { 322 Addr = Address(Ptr, SlotSize); 323 } 324 325 // Advance the pointer past the argument, then store that back. 326 CharUnits FullDirectSize = DirectSize.alignTo(SlotSize); 327 Address NextPtr = 328 CGF.Builder.CreateConstInBoundsByteGEP(Addr, FullDirectSize, "argp.next"); 329 CGF.Builder.CreateStore(NextPtr.getPointer(), VAListAddr); 330 331 // If the argument is smaller than a slot, and this is a big-endian 332 // target, the argument will be right-adjusted in its slot. 333 if (DirectSize < SlotSize && CGF.CGM.getDataLayout().isBigEndian() && 334 !DirectTy->isStructTy()) { 335 Addr = CGF.Builder.CreateConstInBoundsByteGEP(Addr, SlotSize - DirectSize); 336 } 337 338 Addr = CGF.Builder.CreateElementBitCast(Addr, DirectTy); 339 return Addr; 340 } 341 342 /// Emit va_arg for a platform using the common void* representation, 343 /// where arguments are simply emitted in an array of slots on the stack. 344 /// 345 /// \param IsIndirect - Values of this type are passed indirectly. 346 /// \param ValueInfo - The size and alignment of this type, generally 347 /// computed with getContext().getTypeInfoInChars(ValueTy). 348 /// \param SlotSizeAndAlign - The size and alignment of a stack slot. 349 /// Each argument will be allocated to a multiple of this number of 350 /// slots, and all the slots will be aligned to this value. 351 /// \param AllowHigherAlign - The slot alignment is not a cap; 352 /// an argument type with an alignment greater than the slot size 353 /// will be emitted on a higher-alignment address, potentially 354 /// leaving one or more empty slots behind as padding. 355 static Address emitVoidPtrVAArg(CodeGenFunction &CGF, Address VAListAddr, 356 QualType ValueTy, bool IsIndirect, 357 std::pair<CharUnits, CharUnits> ValueInfo, 358 CharUnits SlotSizeAndAlign, 359 bool AllowHigherAlign) { 360 // The size and alignment of the value that was passed directly. 361 CharUnits DirectSize, DirectAlign; 362 if (IsIndirect) { 363 DirectSize = CGF.getPointerSize(); 364 DirectAlign = CGF.getPointerAlign(); 365 } else { 366 DirectSize = ValueInfo.first; 367 DirectAlign = ValueInfo.second; 368 } 369 370 // Cast the address we've calculated to the right type. 371 llvm::Type *DirectTy = CGF.ConvertTypeForMem(ValueTy); 372 if (IsIndirect) 373 DirectTy = DirectTy->getPointerTo(0); 374 375 Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, DirectTy, 376 DirectSize, DirectAlign, 377 SlotSizeAndAlign, 378 AllowHigherAlign); 379 380 if (IsIndirect) { 381 Addr = Address(CGF.Builder.CreateLoad(Addr), ValueInfo.second); 382 } 383 384 return Addr; 385 386 } 387 388 static Address emitMergePHI(CodeGenFunction &CGF, 389 Address Addr1, llvm::BasicBlock *Block1, 390 Address Addr2, llvm::BasicBlock *Block2, 391 const llvm::Twine &Name = "") { 392 assert(Addr1.getType() == Addr2.getType()); 393 llvm::PHINode *PHI = CGF.Builder.CreatePHI(Addr1.getType(), 2, Name); 394 PHI->addIncoming(Addr1.getPointer(), Block1); 395 PHI->addIncoming(Addr2.getPointer(), Block2); 396 CharUnits Align = std::min(Addr1.getAlignment(), Addr2.getAlignment()); 397 return Address(PHI, Align); 398 } 399 400 TargetCodeGenInfo::~TargetCodeGenInfo() = default; 401 402 // If someone can figure out a general rule for this, that would be great. 403 // It's probably just doomed to be platform-dependent, though. 404 unsigned TargetCodeGenInfo::getSizeOfUnwindException() const { 405 // Verified for: 406 // x86-64 FreeBSD, Linux, Darwin 407 // x86-32 FreeBSD, Linux, Darwin 408 // PowerPC Linux, Darwin 409 // ARM Darwin (*not* EABI) 410 // AArch64 Linux 411 return 32; 412 } 413 414 bool TargetCodeGenInfo::isNoProtoCallVariadic(const CallArgList &args, 415 const FunctionNoProtoType *fnType) const { 416 // The following conventions are known to require this to be false: 417 // x86_stdcall 418 // MIPS 419 // For everything else, we just prefer false unless we opt out. 420 return false; 421 } 422 423 void 424 TargetCodeGenInfo::getDependentLibraryOption(llvm::StringRef Lib, 425 llvm::SmallString<24> &Opt) const { 426 // This assumes the user is passing a library name like "rt" instead of a 427 // filename like "librt.a/so", and that they don't care whether it's static or 428 // dynamic. 429 Opt = "-l"; 430 Opt += Lib; 431 } 432 433 unsigned TargetCodeGenInfo::getOpenCLKernelCallingConv() const { 434 // OpenCL kernels are called via an explicit runtime API with arguments 435 // set with clSetKernelArg(), not as normal sub-functions. 436 // Return SPIR_KERNEL by default as the kernel calling convention to 437 // ensure the fingerprint is fixed such way that each OpenCL argument 438 // gets one matching argument in the produced kernel function argument 439 // list to enable feasible implementation of clSetKernelArg() with 440 // aggregates etc. In case we would use the default C calling conv here, 441 // clSetKernelArg() might break depending on the target-specific 442 // conventions; different targets might split structs passed as values 443 // to multiple function arguments etc. 444 return llvm::CallingConv::SPIR_KERNEL; 445 } 446 447 llvm::Constant *TargetCodeGenInfo::getNullPointer(const CodeGen::CodeGenModule &CGM, 448 llvm::PointerType *T, QualType QT) const { 449 return llvm::ConstantPointerNull::get(T); 450 } 451 452 LangAS TargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM, 453 const VarDecl *D) const { 454 assert(!CGM.getLangOpts().OpenCL && 455 !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) && 456 "Address space agnostic languages only"); 457 return D ? D->getType().getAddressSpace() : LangAS::Default; 458 } 459 460 llvm::Value *TargetCodeGenInfo::performAddrSpaceCast( 461 CodeGen::CodeGenFunction &CGF, llvm::Value *Src, LangAS SrcAddr, 462 LangAS DestAddr, llvm::Type *DestTy, bool isNonNull) const { 463 // Since target may map different address spaces in AST to the same address 464 // space, an address space conversion may end up as a bitcast. 465 if (auto *C = dyn_cast<llvm::Constant>(Src)) 466 return performAddrSpaceCast(CGF.CGM, C, SrcAddr, DestAddr, DestTy); 467 // Try to preserve the source's name to make IR more readable. 468 return CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( 469 Src, DestTy, Src->hasName() ? Src->getName() + ".ascast" : ""); 470 } 471 472 llvm::Constant * 473 TargetCodeGenInfo::performAddrSpaceCast(CodeGenModule &CGM, llvm::Constant *Src, 474 LangAS SrcAddr, LangAS DestAddr, 475 llvm::Type *DestTy) const { 476 // Since target may map different address spaces in AST to the same address 477 // space, an address space conversion may end up as a bitcast. 478 return llvm::ConstantExpr::getPointerCast(Src, DestTy); 479 } 480 481 llvm::SyncScope::ID 482 TargetCodeGenInfo::getLLVMSyncScopeID(const LangOptions &LangOpts, 483 SyncScope Scope, 484 llvm::AtomicOrdering Ordering, 485 llvm::LLVMContext &Ctx) const { 486 return Ctx.getOrInsertSyncScopeID(""); /* default sync scope */ 487 } 488 489 static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays); 490 491 /// isEmptyField - Return true iff a the field is "empty", that is it 492 /// is an unnamed bit-field or an (array of) empty record(s). 493 static bool isEmptyField(ASTContext &Context, const FieldDecl *FD, 494 bool AllowArrays) { 495 if (FD->isUnnamedBitfield()) 496 return true; 497 498 QualType FT = FD->getType(); 499 500 // Constant arrays of empty records count as empty, strip them off. 501 // Constant arrays of zero length always count as empty. 502 bool WasArray = false; 503 if (AllowArrays) 504 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) { 505 if (AT->getSize() == 0) 506 return true; 507 FT = AT->getElementType(); 508 // The [[no_unique_address]] special case below does not apply to 509 // arrays of C++ empty records, so we need to remember this fact. 510 WasArray = true; 511 } 512 513 const RecordType *RT = FT->getAs<RecordType>(); 514 if (!RT) 515 return false; 516 517 // C++ record fields are never empty, at least in the Itanium ABI. 518 // 519 // FIXME: We should use a predicate for whether this behavior is true in the 520 // current ABI. 521 // 522 // The exception to the above rule are fields marked with the 523 // [[no_unique_address]] attribute (since C++20). Those do count as empty 524 // according to the Itanium ABI. The exception applies only to records, 525 // not arrays of records, so we must also check whether we stripped off an 526 // array type above. 527 if (isa<CXXRecordDecl>(RT->getDecl()) && 528 (WasArray || !FD->hasAttr<NoUniqueAddressAttr>())) 529 return false; 530 531 return isEmptyRecord(Context, FT, AllowArrays); 532 } 533 534 /// isEmptyRecord - Return true iff a structure contains only empty 535 /// fields. Note that a structure with a flexible array member is not 536 /// considered empty. 537 static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) { 538 const RecordType *RT = T->getAs<RecordType>(); 539 if (!RT) 540 return false; 541 const RecordDecl *RD = RT->getDecl(); 542 if (RD->hasFlexibleArrayMember()) 543 return false; 544 545 // If this is a C++ record, check the bases first. 546 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 547 for (const auto &I : CXXRD->bases()) 548 if (!isEmptyRecord(Context, I.getType(), true)) 549 return false; 550 551 for (const auto *I : RD->fields()) 552 if (!isEmptyField(Context, I, AllowArrays)) 553 return false; 554 return true; 555 } 556 557 /// isSingleElementStruct - Determine if a structure is a "single 558 /// element struct", i.e. it has exactly one non-empty field or 559 /// exactly one field which is itself a single element 560 /// struct. Structures with flexible array members are never 561 /// considered single element structs. 562 /// 563 /// \return The field declaration for the single non-empty field, if 564 /// it exists. 565 static const Type *isSingleElementStruct(QualType T, ASTContext &Context) { 566 const RecordType *RT = T->getAs<RecordType>(); 567 if (!RT) 568 return nullptr; 569 570 const RecordDecl *RD = RT->getDecl(); 571 if (RD->hasFlexibleArrayMember()) 572 return nullptr; 573 574 const Type *Found = nullptr; 575 576 // If this is a C++ record, check the bases first. 577 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 578 for (const auto &I : CXXRD->bases()) { 579 // Ignore empty records. 580 if (isEmptyRecord(Context, I.getType(), true)) 581 continue; 582 583 // If we already found an element then this isn't a single-element struct. 584 if (Found) 585 return nullptr; 586 587 // If this is non-empty and not a single element struct, the composite 588 // cannot be a single element struct. 589 Found = isSingleElementStruct(I.getType(), Context); 590 if (!Found) 591 return nullptr; 592 } 593 } 594 595 // Check for single element. 596 for (const auto *FD : RD->fields()) { 597 QualType FT = FD->getType(); 598 599 // Ignore empty fields. 600 if (isEmptyField(Context, FD, true)) 601 continue; 602 603 // If we already found an element then this isn't a single-element 604 // struct. 605 if (Found) 606 return nullptr; 607 608 // Treat single element arrays as the element. 609 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) { 610 if (AT->getSize().getZExtValue() != 1) 611 break; 612 FT = AT->getElementType(); 613 } 614 615 if (!isAggregateTypeForABI(FT)) { 616 Found = FT.getTypePtr(); 617 } else { 618 Found = isSingleElementStruct(FT, Context); 619 if (!Found) 620 return nullptr; 621 } 622 } 623 624 // We don't consider a struct a single-element struct if it has 625 // padding beyond the element type. 626 if (Found && Context.getTypeSize(Found) != Context.getTypeSize(T)) 627 return nullptr; 628 629 return Found; 630 } 631 632 namespace { 633 Address EmitVAArgInstr(CodeGenFunction &CGF, Address VAListAddr, QualType Ty, 634 const ABIArgInfo &AI) { 635 // This default implementation defers to the llvm backend's va_arg 636 // instruction. It can handle only passing arguments directly 637 // (typically only handled in the backend for primitive types), or 638 // aggregates passed indirectly by pointer (NOTE: if the "byval" 639 // flag has ABI impact in the callee, this implementation cannot 640 // work.) 641 642 // Only a few cases are covered here at the moment -- those needed 643 // by the default abi. 644 llvm::Value *Val; 645 646 if (AI.isIndirect()) { 647 assert(!AI.getPaddingType() && 648 "Unexpected PaddingType seen in arginfo in generic VAArg emitter!"); 649 assert( 650 !AI.getIndirectRealign() && 651 "Unexpected IndirectRealign seen in arginfo in generic VAArg emitter!"); 652 653 auto TyInfo = CGF.getContext().getTypeInfoInChars(Ty); 654 CharUnits TyAlignForABI = TyInfo.second; 655 656 llvm::Type *BaseTy = 657 llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty)); 658 llvm::Value *Addr = 659 CGF.Builder.CreateVAArg(VAListAddr.getPointer(), BaseTy); 660 return Address(Addr, TyAlignForABI); 661 } else { 662 assert((AI.isDirect() || AI.isExtend()) && 663 "Unexpected ArgInfo Kind in generic VAArg emitter!"); 664 665 assert(!AI.getInReg() && 666 "Unexpected InReg seen in arginfo in generic VAArg emitter!"); 667 assert(!AI.getPaddingType() && 668 "Unexpected PaddingType seen in arginfo in generic VAArg emitter!"); 669 assert(!AI.getDirectOffset() && 670 "Unexpected DirectOffset seen in arginfo in generic VAArg emitter!"); 671 assert(!AI.getCoerceToType() && 672 "Unexpected CoerceToType seen in arginfo in generic VAArg emitter!"); 673 674 Address Temp = CGF.CreateMemTemp(Ty, "varet"); 675 Val = CGF.Builder.CreateVAArg(VAListAddr.getPointer(), CGF.ConvertType(Ty)); 676 CGF.Builder.CreateStore(Val, Temp); 677 return Temp; 678 } 679 } 680 681 /// DefaultABIInfo - The default implementation for ABI specific 682 /// details. This implementation provides information which results in 683 /// self-consistent and sensible LLVM IR generation, but does not 684 /// conform to any particular ABI. 685 class DefaultABIInfo : public ABIInfo { 686 public: 687 DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {} 688 689 ABIArgInfo classifyReturnType(QualType RetTy) const; 690 ABIArgInfo classifyArgumentType(QualType RetTy) const; 691 692 void computeInfo(CGFunctionInfo &FI) const override { 693 if (!getCXXABI().classifyReturnType(FI)) 694 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 695 for (auto &I : FI.arguments()) 696 I.info = classifyArgumentType(I.type); 697 } 698 699 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 700 QualType Ty) const override { 701 return EmitVAArgInstr(CGF, VAListAddr, Ty, classifyArgumentType(Ty)); 702 } 703 }; 704 705 class DefaultTargetCodeGenInfo : public TargetCodeGenInfo { 706 public: 707 DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT) 708 : TargetCodeGenInfo(std::make_unique<DefaultABIInfo>(CGT)) {} 709 }; 710 711 ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const { 712 Ty = useFirstFieldIfTransparentUnion(Ty); 713 714 if (isAggregateTypeForABI(Ty)) { 715 // Records with non-trivial destructors/copy-constructors should not be 716 // passed by value. 717 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 718 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 719 720 return getNaturalAlignIndirect(Ty); 721 } 722 723 // Treat an enum type as its underlying type. 724 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 725 Ty = EnumTy->getDecl()->getIntegerType(); 726 727 ASTContext &Context = getContext(); 728 if (const auto *EIT = Ty->getAs<ExtIntType>()) 729 if (EIT->getNumBits() > 730 Context.getTypeSize(Context.getTargetInfo().hasInt128Type() 731 ? Context.Int128Ty 732 : Context.LongLongTy)) 733 return getNaturalAlignIndirect(Ty); 734 735 return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty) 736 : ABIArgInfo::getDirect()); 737 } 738 739 ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const { 740 if (RetTy->isVoidType()) 741 return ABIArgInfo::getIgnore(); 742 743 if (isAggregateTypeForABI(RetTy)) 744 return getNaturalAlignIndirect(RetTy); 745 746 // Treat an enum type as its underlying type. 747 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 748 RetTy = EnumTy->getDecl()->getIntegerType(); 749 750 if (const auto *EIT = RetTy->getAs<ExtIntType>()) 751 if (EIT->getNumBits() > 752 getContext().getTypeSize(getContext().getTargetInfo().hasInt128Type() 753 ? getContext().Int128Ty 754 : getContext().LongLongTy)) 755 return getNaturalAlignIndirect(RetTy); 756 757 return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy) 758 : ABIArgInfo::getDirect()); 759 } 760 761 //===----------------------------------------------------------------------===// 762 // WebAssembly ABI Implementation 763 // 764 // This is a very simple ABI that relies a lot on DefaultABIInfo. 765 //===----------------------------------------------------------------------===// 766 767 class WebAssemblyABIInfo final : public SwiftABIInfo { 768 public: 769 enum ABIKind { 770 MVP = 0, 771 ExperimentalMV = 1, 772 }; 773 774 private: 775 DefaultABIInfo defaultInfo; 776 ABIKind Kind; 777 778 public: 779 explicit WebAssemblyABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind) 780 : SwiftABIInfo(CGT), defaultInfo(CGT), Kind(Kind) {} 781 782 private: 783 ABIArgInfo classifyReturnType(QualType RetTy) const; 784 ABIArgInfo classifyArgumentType(QualType Ty) const; 785 786 // DefaultABIInfo's classifyReturnType and classifyArgumentType are 787 // non-virtual, but computeInfo and EmitVAArg are virtual, so we 788 // overload them. 789 void computeInfo(CGFunctionInfo &FI) const override { 790 if (!getCXXABI().classifyReturnType(FI)) 791 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 792 for (auto &Arg : FI.arguments()) 793 Arg.info = classifyArgumentType(Arg.type); 794 } 795 796 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 797 QualType Ty) const override; 798 799 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars, 800 bool asReturnValue) const override { 801 return occupiesMoreThan(CGT, scalars, /*total*/ 4); 802 } 803 804 bool isSwiftErrorInRegister() const override { 805 return false; 806 } 807 }; 808 809 class WebAssemblyTargetCodeGenInfo final : public TargetCodeGenInfo { 810 public: 811 explicit WebAssemblyTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, 812 WebAssemblyABIInfo::ABIKind K) 813 : TargetCodeGenInfo(std::make_unique<WebAssemblyABIInfo>(CGT, K)) {} 814 815 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 816 CodeGen::CodeGenModule &CGM) const override { 817 TargetCodeGenInfo::setTargetAttributes(D, GV, CGM); 818 if (const auto *FD = dyn_cast_or_null<FunctionDecl>(D)) { 819 if (const auto *Attr = FD->getAttr<WebAssemblyImportModuleAttr>()) { 820 llvm::Function *Fn = cast<llvm::Function>(GV); 821 llvm::AttrBuilder B; 822 B.addAttribute("wasm-import-module", Attr->getImportModule()); 823 Fn->addAttributes(llvm::AttributeList::FunctionIndex, B); 824 } 825 if (const auto *Attr = FD->getAttr<WebAssemblyImportNameAttr>()) { 826 llvm::Function *Fn = cast<llvm::Function>(GV); 827 llvm::AttrBuilder B; 828 B.addAttribute("wasm-import-name", Attr->getImportName()); 829 Fn->addAttributes(llvm::AttributeList::FunctionIndex, B); 830 } 831 if (const auto *Attr = FD->getAttr<WebAssemblyExportNameAttr>()) { 832 llvm::Function *Fn = cast<llvm::Function>(GV); 833 llvm::AttrBuilder B; 834 B.addAttribute("wasm-export-name", Attr->getExportName()); 835 Fn->addAttributes(llvm::AttributeList::FunctionIndex, B); 836 } 837 } 838 839 if (auto *FD = dyn_cast_or_null<FunctionDecl>(D)) { 840 llvm::Function *Fn = cast<llvm::Function>(GV); 841 if (!FD->doesThisDeclarationHaveABody() && !FD->hasPrototype()) 842 Fn->addFnAttr("no-prototype"); 843 } 844 } 845 }; 846 847 /// Classify argument of given type \p Ty. 848 ABIArgInfo WebAssemblyABIInfo::classifyArgumentType(QualType Ty) const { 849 Ty = useFirstFieldIfTransparentUnion(Ty); 850 851 if (isAggregateTypeForABI(Ty)) { 852 // Records with non-trivial destructors/copy-constructors should not be 853 // passed by value. 854 if (auto RAA = getRecordArgABI(Ty, getCXXABI())) 855 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 856 // Ignore empty structs/unions. 857 if (isEmptyRecord(getContext(), Ty, true)) 858 return ABIArgInfo::getIgnore(); 859 // Lower single-element structs to just pass a regular value. TODO: We 860 // could do reasonable-size multiple-element structs too, using getExpand(), 861 // though watch out for things like bitfields. 862 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext())) 863 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0))); 864 // For the experimental multivalue ABI, fully expand all other aggregates 865 if (Kind == ABIKind::ExperimentalMV) { 866 const RecordType *RT = Ty->getAs<RecordType>(); 867 assert(RT); 868 bool HasBitField = false; 869 for (auto *Field : RT->getDecl()->fields()) { 870 if (Field->isBitField()) { 871 HasBitField = true; 872 break; 873 } 874 } 875 if (!HasBitField) 876 return ABIArgInfo::getExpand(); 877 } 878 } 879 880 // Otherwise just do the default thing. 881 return defaultInfo.classifyArgumentType(Ty); 882 } 883 884 ABIArgInfo WebAssemblyABIInfo::classifyReturnType(QualType RetTy) const { 885 if (isAggregateTypeForABI(RetTy)) { 886 // Records with non-trivial destructors/copy-constructors should not be 887 // returned by value. 888 if (!getRecordArgABI(RetTy, getCXXABI())) { 889 // Ignore empty structs/unions. 890 if (isEmptyRecord(getContext(), RetTy, true)) 891 return ABIArgInfo::getIgnore(); 892 // Lower single-element structs to just return a regular value. TODO: We 893 // could do reasonable-size multiple-element structs too, using 894 // ABIArgInfo::getDirect(). 895 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext())) 896 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0))); 897 // For the experimental multivalue ABI, return all other aggregates 898 if (Kind == ABIKind::ExperimentalMV) 899 return ABIArgInfo::getDirect(); 900 } 901 } 902 903 // Otherwise just do the default thing. 904 return defaultInfo.classifyReturnType(RetTy); 905 } 906 907 Address WebAssemblyABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 908 QualType Ty) const { 909 bool IsIndirect = isAggregateTypeForABI(Ty) && 910 !isEmptyRecord(getContext(), Ty, true) && 911 !isSingleElementStruct(Ty, getContext()); 912 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, 913 getContext().getTypeInfoInChars(Ty), 914 CharUnits::fromQuantity(4), 915 /*AllowHigherAlign=*/true); 916 } 917 918 //===----------------------------------------------------------------------===// 919 // le32/PNaCl bitcode ABI Implementation 920 // 921 // This is a simplified version of the x86_32 ABI. Arguments and return values 922 // are always passed on the stack. 923 //===----------------------------------------------------------------------===// 924 925 class PNaClABIInfo : public ABIInfo { 926 public: 927 PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {} 928 929 ABIArgInfo classifyReturnType(QualType RetTy) const; 930 ABIArgInfo classifyArgumentType(QualType RetTy) const; 931 932 void computeInfo(CGFunctionInfo &FI) const override; 933 Address EmitVAArg(CodeGenFunction &CGF, 934 Address VAListAddr, QualType Ty) const override; 935 }; 936 937 class PNaClTargetCodeGenInfo : public TargetCodeGenInfo { 938 public: 939 PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT) 940 : TargetCodeGenInfo(std::make_unique<PNaClABIInfo>(CGT)) {} 941 }; 942 943 void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const { 944 if (!getCXXABI().classifyReturnType(FI)) 945 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 946 947 for (auto &I : FI.arguments()) 948 I.info = classifyArgumentType(I.type); 949 } 950 951 Address PNaClABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 952 QualType Ty) const { 953 // The PNaCL ABI is a bit odd, in that varargs don't use normal 954 // function classification. Structs get passed directly for varargs 955 // functions, through a rewriting transform in 956 // pnacl-llvm/lib/Transforms/NaCl/ExpandVarArgs.cpp, which allows 957 // this target to actually support a va_arg instructions with an 958 // aggregate type, unlike other targets. 959 return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect()); 960 } 961 962 /// Classify argument of given type \p Ty. 963 ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const { 964 if (isAggregateTypeForABI(Ty)) { 965 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 966 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 967 return getNaturalAlignIndirect(Ty); 968 } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) { 969 // Treat an enum type as its underlying type. 970 Ty = EnumTy->getDecl()->getIntegerType(); 971 } else if (Ty->isFloatingType()) { 972 // Floating-point types don't go inreg. 973 return ABIArgInfo::getDirect(); 974 } else if (const auto *EIT = Ty->getAs<ExtIntType>()) { 975 // Treat extended integers as integers if <=64, otherwise pass indirectly. 976 if (EIT->getNumBits() > 64) 977 return getNaturalAlignIndirect(Ty); 978 return ABIArgInfo::getDirect(); 979 } 980 981 return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty) 982 : ABIArgInfo::getDirect()); 983 } 984 985 ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const { 986 if (RetTy->isVoidType()) 987 return ABIArgInfo::getIgnore(); 988 989 // In the PNaCl ABI we always return records/structures on the stack. 990 if (isAggregateTypeForABI(RetTy)) 991 return getNaturalAlignIndirect(RetTy); 992 993 // Treat extended integers as integers if <=64, otherwise pass indirectly. 994 if (const auto *EIT = RetTy->getAs<ExtIntType>()) { 995 if (EIT->getNumBits() > 64) 996 return getNaturalAlignIndirect(RetTy); 997 return ABIArgInfo::getDirect(); 998 } 999 1000 // Treat an enum type as its underlying type. 1001 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 1002 RetTy = EnumTy->getDecl()->getIntegerType(); 1003 1004 return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy) 1005 : ABIArgInfo::getDirect()); 1006 } 1007 1008 /// IsX86_MMXType - Return true if this is an MMX type. 1009 bool IsX86_MMXType(llvm::Type *IRType) { 1010 // Return true if the type is an MMX type <2 x i32>, <4 x i16>, or <8 x i8>. 1011 return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 && 1012 cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() && 1013 IRType->getScalarSizeInBits() != 64; 1014 } 1015 1016 static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF, 1017 StringRef Constraint, 1018 llvm::Type* Ty) { 1019 bool IsMMXCons = llvm::StringSwitch<bool>(Constraint) 1020 .Cases("y", "&y", "^Ym", true) 1021 .Default(false); 1022 if (IsMMXCons && Ty->isVectorTy()) { 1023 if (cast<llvm::VectorType>(Ty)->getPrimitiveSizeInBits().getFixedSize() != 1024 64) { 1025 // Invalid MMX constraint 1026 return nullptr; 1027 } 1028 1029 return llvm::Type::getX86_MMXTy(CGF.getLLVMContext()); 1030 } 1031 1032 // No operation needed 1033 return Ty; 1034 } 1035 1036 /// Returns true if this type can be passed in SSE registers with the 1037 /// X86_VectorCall calling convention. Shared between x86_32 and x86_64. 1038 static bool isX86VectorTypeForVectorCall(ASTContext &Context, QualType Ty) { 1039 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) { 1040 if (BT->isFloatingPoint() && BT->getKind() != BuiltinType::Half) { 1041 if (BT->getKind() == BuiltinType::LongDouble) { 1042 if (&Context.getTargetInfo().getLongDoubleFormat() == 1043 &llvm::APFloat::x87DoubleExtended()) 1044 return false; 1045 } 1046 return true; 1047 } 1048 } else if (const VectorType *VT = Ty->getAs<VectorType>()) { 1049 // vectorcall can pass XMM, YMM, and ZMM vectors. We don't pass SSE1 MMX 1050 // registers specially. 1051 unsigned VecSize = Context.getTypeSize(VT); 1052 if (VecSize == 128 || VecSize == 256 || VecSize == 512) 1053 return true; 1054 } 1055 return false; 1056 } 1057 1058 /// Returns true if this aggregate is small enough to be passed in SSE registers 1059 /// in the X86_VectorCall calling convention. Shared between x86_32 and x86_64. 1060 static bool isX86VectorCallAggregateSmallEnough(uint64_t NumMembers) { 1061 return NumMembers <= 4; 1062 } 1063 1064 /// Returns a Homogeneous Vector Aggregate ABIArgInfo, used in X86. 1065 static ABIArgInfo getDirectX86Hva(llvm::Type* T = nullptr) { 1066 auto AI = ABIArgInfo::getDirect(T); 1067 AI.setInReg(true); 1068 AI.setCanBeFlattened(false); 1069 return AI; 1070 } 1071 1072 //===----------------------------------------------------------------------===// 1073 // X86-32 ABI Implementation 1074 //===----------------------------------------------------------------------===// 1075 1076 /// Similar to llvm::CCState, but for Clang. 1077 struct CCState { 1078 CCState(CGFunctionInfo &FI) 1079 : IsPreassigned(FI.arg_size()), CC(FI.getCallingConvention()) {} 1080 1081 llvm::SmallBitVector IsPreassigned; 1082 unsigned CC = CallingConv::CC_C; 1083 unsigned FreeRegs = 0; 1084 unsigned FreeSSERegs = 0; 1085 }; 1086 1087 enum { 1088 // Vectorcall only allows the first 6 parameters to be passed in registers. 1089 VectorcallMaxParamNumAsReg = 6 1090 }; 1091 1092 /// X86_32ABIInfo - The X86-32 ABI information. 1093 class X86_32ABIInfo : public SwiftABIInfo { 1094 enum Class { 1095 Integer, 1096 Float 1097 }; 1098 1099 static const unsigned MinABIStackAlignInBytes = 4; 1100 1101 bool IsDarwinVectorABI; 1102 bool IsRetSmallStructInRegABI; 1103 bool IsWin32StructABI; 1104 bool IsSoftFloatABI; 1105 bool IsMCUABI; 1106 unsigned DefaultNumRegisterParameters; 1107 1108 static bool isRegisterSize(unsigned Size) { 1109 return (Size == 8 || Size == 16 || Size == 32 || Size == 64); 1110 } 1111 1112 bool isHomogeneousAggregateBaseType(QualType Ty) const override { 1113 // FIXME: Assumes vectorcall is in use. 1114 return isX86VectorTypeForVectorCall(getContext(), Ty); 1115 } 1116 1117 bool isHomogeneousAggregateSmallEnough(const Type *Ty, 1118 uint64_t NumMembers) const override { 1119 // FIXME: Assumes vectorcall is in use. 1120 return isX86VectorCallAggregateSmallEnough(NumMembers); 1121 } 1122 1123 bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context) const; 1124 1125 /// getIndirectResult - Give a source type \arg Ty, return a suitable result 1126 /// such that the argument will be passed in memory. 1127 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const; 1128 1129 ABIArgInfo getIndirectReturnResult(QualType Ty, CCState &State) const; 1130 1131 /// Return the alignment to use for the given type on the stack. 1132 unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const; 1133 1134 Class classify(QualType Ty) const; 1135 ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const; 1136 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const; 1137 1138 /// Updates the number of available free registers, returns 1139 /// true if any registers were allocated. 1140 bool updateFreeRegs(QualType Ty, CCState &State) const; 1141 1142 bool shouldAggregateUseDirect(QualType Ty, CCState &State, bool &InReg, 1143 bool &NeedsPadding) const; 1144 bool shouldPrimitiveUseInReg(QualType Ty, CCState &State) const; 1145 1146 bool canExpandIndirectArgument(QualType Ty) const; 1147 1148 /// Rewrite the function info so that all memory arguments use 1149 /// inalloca. 1150 void rewriteWithInAlloca(CGFunctionInfo &FI) const; 1151 1152 void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields, 1153 CharUnits &StackOffset, ABIArgInfo &Info, 1154 QualType Type) const; 1155 void runVectorCallFirstPass(CGFunctionInfo &FI, CCState &State) const; 1156 1157 public: 1158 1159 void computeInfo(CGFunctionInfo &FI) const override; 1160 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 1161 QualType Ty) const override; 1162 1163 X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI, 1164 bool RetSmallStructInRegABI, bool Win32StructABI, 1165 unsigned NumRegisterParameters, bool SoftFloatABI) 1166 : SwiftABIInfo(CGT), IsDarwinVectorABI(DarwinVectorABI), 1167 IsRetSmallStructInRegABI(RetSmallStructInRegABI), 1168 IsWin32StructABI(Win32StructABI), 1169 IsSoftFloatABI(SoftFloatABI), 1170 IsMCUABI(CGT.getTarget().getTriple().isOSIAMCU()), 1171 DefaultNumRegisterParameters(NumRegisterParameters) {} 1172 1173 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars, 1174 bool asReturnValue) const override { 1175 // LLVM's x86-32 lowering currently only assigns up to three 1176 // integer registers and three fp registers. Oddly, it'll use up to 1177 // four vector registers for vectors, but those can overlap with the 1178 // scalar registers. 1179 return occupiesMoreThan(CGT, scalars, /*total*/ 3); 1180 } 1181 1182 bool isSwiftErrorInRegister() const override { 1183 // x86-32 lowering does not support passing swifterror in a register. 1184 return false; 1185 } 1186 }; 1187 1188 class X86_32TargetCodeGenInfo : public TargetCodeGenInfo { 1189 public: 1190 X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI, 1191 bool RetSmallStructInRegABI, bool Win32StructABI, 1192 unsigned NumRegisterParameters, bool SoftFloatABI) 1193 : TargetCodeGenInfo(std::make_unique<X86_32ABIInfo>( 1194 CGT, DarwinVectorABI, RetSmallStructInRegABI, Win32StructABI, 1195 NumRegisterParameters, SoftFloatABI)) {} 1196 1197 static bool isStructReturnInRegABI( 1198 const llvm::Triple &Triple, const CodeGenOptions &Opts); 1199 1200 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 1201 CodeGen::CodeGenModule &CGM) const override; 1202 1203 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override { 1204 // Darwin uses different dwarf register numbers for EH. 1205 if (CGM.getTarget().getTriple().isOSDarwin()) return 5; 1206 return 4; 1207 } 1208 1209 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 1210 llvm::Value *Address) const override; 1211 1212 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF, 1213 StringRef Constraint, 1214 llvm::Type* Ty) const override { 1215 return X86AdjustInlineAsmType(CGF, Constraint, Ty); 1216 } 1217 1218 void addReturnRegisterOutputs(CodeGenFunction &CGF, LValue ReturnValue, 1219 std::string &Constraints, 1220 std::vector<llvm::Type *> &ResultRegTypes, 1221 std::vector<llvm::Type *> &ResultTruncRegTypes, 1222 std::vector<LValue> &ResultRegDests, 1223 std::string &AsmString, 1224 unsigned NumOutputs) const override; 1225 1226 llvm::Constant * 1227 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override { 1228 unsigned Sig = (0xeb << 0) | // jmp rel8 1229 (0x06 << 8) | // .+0x08 1230 ('v' << 16) | 1231 ('2' << 24); 1232 return llvm::ConstantInt::get(CGM.Int32Ty, Sig); 1233 } 1234 1235 StringRef getARCRetainAutoreleasedReturnValueMarker() const override { 1236 return "movl\t%ebp, %ebp" 1237 "\t\t// marker for objc_retainAutoreleaseReturnValue"; 1238 } 1239 }; 1240 1241 } 1242 1243 /// Rewrite input constraint references after adding some output constraints. 1244 /// In the case where there is one output and one input and we add one output, 1245 /// we need to replace all operand references greater than or equal to 1: 1246 /// mov $0, $1 1247 /// mov eax, $1 1248 /// The result will be: 1249 /// mov $0, $2 1250 /// mov eax, $2 1251 static void rewriteInputConstraintReferences(unsigned FirstIn, 1252 unsigned NumNewOuts, 1253 std::string &AsmString) { 1254 std::string Buf; 1255 llvm::raw_string_ostream OS(Buf); 1256 size_t Pos = 0; 1257 while (Pos < AsmString.size()) { 1258 size_t DollarStart = AsmString.find('$', Pos); 1259 if (DollarStart == std::string::npos) 1260 DollarStart = AsmString.size(); 1261 size_t DollarEnd = AsmString.find_first_not_of('$', DollarStart); 1262 if (DollarEnd == std::string::npos) 1263 DollarEnd = AsmString.size(); 1264 OS << StringRef(&AsmString[Pos], DollarEnd - Pos); 1265 Pos = DollarEnd; 1266 size_t NumDollars = DollarEnd - DollarStart; 1267 if (NumDollars % 2 != 0 && Pos < AsmString.size()) { 1268 // We have an operand reference. 1269 size_t DigitStart = Pos; 1270 if (AsmString[DigitStart] == '{') { 1271 OS << '{'; 1272 ++DigitStart; 1273 } 1274 size_t DigitEnd = AsmString.find_first_not_of("0123456789", DigitStart); 1275 if (DigitEnd == std::string::npos) 1276 DigitEnd = AsmString.size(); 1277 StringRef OperandStr(&AsmString[DigitStart], DigitEnd - DigitStart); 1278 unsigned OperandIndex; 1279 if (!OperandStr.getAsInteger(10, OperandIndex)) { 1280 if (OperandIndex >= FirstIn) 1281 OperandIndex += NumNewOuts; 1282 OS << OperandIndex; 1283 } else { 1284 OS << OperandStr; 1285 } 1286 Pos = DigitEnd; 1287 } 1288 } 1289 AsmString = std::move(OS.str()); 1290 } 1291 1292 /// Add output constraints for EAX:EDX because they are return registers. 1293 void X86_32TargetCodeGenInfo::addReturnRegisterOutputs( 1294 CodeGenFunction &CGF, LValue ReturnSlot, std::string &Constraints, 1295 std::vector<llvm::Type *> &ResultRegTypes, 1296 std::vector<llvm::Type *> &ResultTruncRegTypes, 1297 std::vector<LValue> &ResultRegDests, std::string &AsmString, 1298 unsigned NumOutputs) const { 1299 uint64_t RetWidth = CGF.getContext().getTypeSize(ReturnSlot.getType()); 1300 1301 // Use the EAX constraint if the width is 32 or smaller and EAX:EDX if it is 1302 // larger. 1303 if (!Constraints.empty()) 1304 Constraints += ','; 1305 if (RetWidth <= 32) { 1306 Constraints += "={eax}"; 1307 ResultRegTypes.push_back(CGF.Int32Ty); 1308 } else { 1309 // Use the 'A' constraint for EAX:EDX. 1310 Constraints += "=A"; 1311 ResultRegTypes.push_back(CGF.Int64Ty); 1312 } 1313 1314 // Truncate EAX or EAX:EDX to an integer of the appropriate size. 1315 llvm::Type *CoerceTy = llvm::IntegerType::get(CGF.getLLVMContext(), RetWidth); 1316 ResultTruncRegTypes.push_back(CoerceTy); 1317 1318 // Coerce the integer by bitcasting the return slot pointer. 1319 ReturnSlot.setAddress(CGF.Builder.CreateBitCast(ReturnSlot.getAddress(CGF), 1320 CoerceTy->getPointerTo())); 1321 ResultRegDests.push_back(ReturnSlot); 1322 1323 rewriteInputConstraintReferences(NumOutputs, 1, AsmString); 1324 } 1325 1326 /// shouldReturnTypeInRegister - Determine if the given type should be 1327 /// returned in a register (for the Darwin and MCU ABI). 1328 bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty, 1329 ASTContext &Context) const { 1330 uint64_t Size = Context.getTypeSize(Ty); 1331 1332 // For i386, type must be register sized. 1333 // For the MCU ABI, it only needs to be <= 8-byte 1334 if ((IsMCUABI && Size > 64) || (!IsMCUABI && !isRegisterSize(Size))) 1335 return false; 1336 1337 if (Ty->isVectorType()) { 1338 // 64- and 128- bit vectors inside structures are not returned in 1339 // registers. 1340 if (Size == 64 || Size == 128) 1341 return false; 1342 1343 return true; 1344 } 1345 1346 // If this is a builtin, pointer, enum, complex type, member pointer, or 1347 // member function pointer it is ok. 1348 if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() || 1349 Ty->isAnyComplexType() || Ty->isEnumeralType() || 1350 Ty->isBlockPointerType() || Ty->isMemberPointerType()) 1351 return true; 1352 1353 // Arrays are treated like records. 1354 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) 1355 return shouldReturnTypeInRegister(AT->getElementType(), Context); 1356 1357 // Otherwise, it must be a record type. 1358 const RecordType *RT = Ty->getAs<RecordType>(); 1359 if (!RT) return false; 1360 1361 // FIXME: Traverse bases here too. 1362 1363 // Structure types are passed in register if all fields would be 1364 // passed in a register. 1365 for (const auto *FD : RT->getDecl()->fields()) { 1366 // Empty fields are ignored. 1367 if (isEmptyField(Context, FD, true)) 1368 continue; 1369 1370 // Check fields recursively. 1371 if (!shouldReturnTypeInRegister(FD->getType(), Context)) 1372 return false; 1373 } 1374 return true; 1375 } 1376 1377 static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) { 1378 // Treat complex types as the element type. 1379 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) 1380 Ty = CTy->getElementType(); 1381 1382 // Check for a type which we know has a simple scalar argument-passing 1383 // convention without any padding. (We're specifically looking for 32 1384 // and 64-bit integer and integer-equivalents, float, and double.) 1385 if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() && 1386 !Ty->isEnumeralType() && !Ty->isBlockPointerType()) 1387 return false; 1388 1389 uint64_t Size = Context.getTypeSize(Ty); 1390 return Size == 32 || Size == 64; 1391 } 1392 1393 static bool addFieldSizes(ASTContext &Context, const RecordDecl *RD, 1394 uint64_t &Size) { 1395 for (const auto *FD : RD->fields()) { 1396 // Scalar arguments on the stack get 4 byte alignment on x86. If the 1397 // argument is smaller than 32-bits, expanding the struct will create 1398 // alignment padding. 1399 if (!is32Or64BitBasicType(FD->getType(), Context)) 1400 return false; 1401 1402 // FIXME: Reject bit-fields wholesale; there are two problems, we don't know 1403 // how to expand them yet, and the predicate for telling if a bitfield still 1404 // counts as "basic" is more complicated than what we were doing previously. 1405 if (FD->isBitField()) 1406 return false; 1407 1408 Size += Context.getTypeSize(FD->getType()); 1409 } 1410 return true; 1411 } 1412 1413 static bool addBaseAndFieldSizes(ASTContext &Context, const CXXRecordDecl *RD, 1414 uint64_t &Size) { 1415 // Don't do this if there are any non-empty bases. 1416 for (const CXXBaseSpecifier &Base : RD->bases()) { 1417 if (!addBaseAndFieldSizes(Context, Base.getType()->getAsCXXRecordDecl(), 1418 Size)) 1419 return false; 1420 } 1421 if (!addFieldSizes(Context, RD, Size)) 1422 return false; 1423 return true; 1424 } 1425 1426 /// Test whether an argument type which is to be passed indirectly (on the 1427 /// stack) would have the equivalent layout if it was expanded into separate 1428 /// arguments. If so, we prefer to do the latter to avoid inhibiting 1429 /// optimizations. 1430 bool X86_32ABIInfo::canExpandIndirectArgument(QualType Ty) const { 1431 // We can only expand structure types. 1432 const RecordType *RT = Ty->getAs<RecordType>(); 1433 if (!RT) 1434 return false; 1435 const RecordDecl *RD = RT->getDecl(); 1436 uint64_t Size = 0; 1437 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 1438 if (!IsWin32StructABI) { 1439 // On non-Windows, we have to conservatively match our old bitcode 1440 // prototypes in order to be ABI-compatible at the bitcode level. 1441 if (!CXXRD->isCLike()) 1442 return false; 1443 } else { 1444 // Don't do this for dynamic classes. 1445 if (CXXRD->isDynamicClass()) 1446 return false; 1447 } 1448 if (!addBaseAndFieldSizes(getContext(), CXXRD, Size)) 1449 return false; 1450 } else { 1451 if (!addFieldSizes(getContext(), RD, Size)) 1452 return false; 1453 } 1454 1455 // We can do this if there was no alignment padding. 1456 return Size == getContext().getTypeSize(Ty); 1457 } 1458 1459 ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(QualType RetTy, CCState &State) const { 1460 // If the return value is indirect, then the hidden argument is consuming one 1461 // integer register. 1462 if (State.FreeRegs) { 1463 --State.FreeRegs; 1464 if (!IsMCUABI) 1465 return getNaturalAlignIndirectInReg(RetTy); 1466 } 1467 return getNaturalAlignIndirect(RetTy, /*ByVal=*/false); 1468 } 1469 1470 ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy, 1471 CCState &State) const { 1472 if (RetTy->isVoidType()) 1473 return ABIArgInfo::getIgnore(); 1474 1475 const Type *Base = nullptr; 1476 uint64_t NumElts = 0; 1477 if ((State.CC == llvm::CallingConv::X86_VectorCall || 1478 State.CC == llvm::CallingConv::X86_RegCall) && 1479 isHomogeneousAggregate(RetTy, Base, NumElts)) { 1480 // The LLVM struct type for such an aggregate should lower properly. 1481 return ABIArgInfo::getDirect(); 1482 } 1483 1484 if (const VectorType *VT = RetTy->getAs<VectorType>()) { 1485 // On Darwin, some vectors are returned in registers. 1486 if (IsDarwinVectorABI) { 1487 uint64_t Size = getContext().getTypeSize(RetTy); 1488 1489 // 128-bit vectors are a special case; they are returned in 1490 // registers and we need to make sure to pick a type the LLVM 1491 // backend will like. 1492 if (Size == 128) 1493 return ABIArgInfo::getDirect(llvm::FixedVectorType::get( 1494 llvm::Type::getInt64Ty(getVMContext()), 2)); 1495 1496 // Always return in register if it fits in a general purpose 1497 // register, or if it is 64 bits and has a single element. 1498 if ((Size == 8 || Size == 16 || Size == 32) || 1499 (Size == 64 && VT->getNumElements() == 1)) 1500 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 1501 Size)); 1502 1503 return getIndirectReturnResult(RetTy, State); 1504 } 1505 1506 return ABIArgInfo::getDirect(); 1507 } 1508 1509 if (isAggregateTypeForABI(RetTy)) { 1510 if (const RecordType *RT = RetTy->getAs<RecordType>()) { 1511 // Structures with flexible arrays are always indirect. 1512 if (RT->getDecl()->hasFlexibleArrayMember()) 1513 return getIndirectReturnResult(RetTy, State); 1514 } 1515 1516 // If specified, structs and unions are always indirect. 1517 if (!IsRetSmallStructInRegABI && !RetTy->isAnyComplexType()) 1518 return getIndirectReturnResult(RetTy, State); 1519 1520 // Ignore empty structs/unions. 1521 if (isEmptyRecord(getContext(), RetTy, true)) 1522 return ABIArgInfo::getIgnore(); 1523 1524 // Small structures which are register sized are generally returned 1525 // in a register. 1526 if (shouldReturnTypeInRegister(RetTy, getContext())) { 1527 uint64_t Size = getContext().getTypeSize(RetTy); 1528 1529 // As a special-case, if the struct is a "single-element" struct, and 1530 // the field is of type "float" or "double", return it in a 1531 // floating-point register. (MSVC does not apply this special case.) 1532 // We apply a similar transformation for pointer types to improve the 1533 // quality of the generated IR. 1534 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext())) 1535 if ((!IsWin32StructABI && SeltTy->isRealFloatingType()) 1536 || SeltTy->hasPointerRepresentation()) 1537 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0))); 1538 1539 // FIXME: We should be able to narrow this integer in cases with dead 1540 // padding. 1541 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size)); 1542 } 1543 1544 return getIndirectReturnResult(RetTy, State); 1545 } 1546 1547 // Treat an enum type as its underlying type. 1548 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 1549 RetTy = EnumTy->getDecl()->getIntegerType(); 1550 1551 if (const auto *EIT = RetTy->getAs<ExtIntType>()) 1552 if (EIT->getNumBits() > 64) 1553 return getIndirectReturnResult(RetTy, State); 1554 1555 return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy) 1556 : ABIArgInfo::getDirect()); 1557 } 1558 1559 static bool isSIMDVectorType(ASTContext &Context, QualType Ty) { 1560 return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128; 1561 } 1562 1563 static bool isRecordWithSIMDVectorType(ASTContext &Context, QualType Ty) { 1564 const RecordType *RT = Ty->getAs<RecordType>(); 1565 if (!RT) 1566 return 0; 1567 const RecordDecl *RD = RT->getDecl(); 1568 1569 // If this is a C++ record, check the bases first. 1570 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 1571 for (const auto &I : CXXRD->bases()) 1572 if (!isRecordWithSIMDVectorType(Context, I.getType())) 1573 return false; 1574 1575 for (const auto *i : RD->fields()) { 1576 QualType FT = i->getType(); 1577 1578 if (isSIMDVectorType(Context, FT)) 1579 return true; 1580 1581 if (isRecordWithSIMDVectorType(Context, FT)) 1582 return true; 1583 } 1584 1585 return false; 1586 } 1587 1588 unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty, 1589 unsigned Align) const { 1590 // Otherwise, if the alignment is less than or equal to the minimum ABI 1591 // alignment, just use the default; the backend will handle this. 1592 if (Align <= MinABIStackAlignInBytes) 1593 return 0; // Use default alignment. 1594 1595 // On non-Darwin, the stack type alignment is always 4. 1596 if (!IsDarwinVectorABI) { 1597 // Set explicit alignment, since we may need to realign the top. 1598 return MinABIStackAlignInBytes; 1599 } 1600 1601 // Otherwise, if the type contains an SSE vector type, the alignment is 16. 1602 if (Align >= 16 && (isSIMDVectorType(getContext(), Ty) || 1603 isRecordWithSIMDVectorType(getContext(), Ty))) 1604 return 16; 1605 1606 return MinABIStackAlignInBytes; 1607 } 1608 1609 ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal, 1610 CCState &State) const { 1611 if (!ByVal) { 1612 if (State.FreeRegs) { 1613 --State.FreeRegs; // Non-byval indirects just use one pointer. 1614 if (!IsMCUABI) 1615 return getNaturalAlignIndirectInReg(Ty); 1616 } 1617 return getNaturalAlignIndirect(Ty, false); 1618 } 1619 1620 // Compute the byval alignment. 1621 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8; 1622 unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign); 1623 if (StackAlign == 0) 1624 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true); 1625 1626 // If the stack alignment is less than the type alignment, realign the 1627 // argument. 1628 bool Realign = TypeAlign > StackAlign; 1629 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(StackAlign), 1630 /*ByVal=*/true, Realign); 1631 } 1632 1633 X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const { 1634 const Type *T = isSingleElementStruct(Ty, getContext()); 1635 if (!T) 1636 T = Ty.getTypePtr(); 1637 1638 if (const BuiltinType *BT = T->getAs<BuiltinType>()) { 1639 BuiltinType::Kind K = BT->getKind(); 1640 if (K == BuiltinType::Float || K == BuiltinType::Double) 1641 return Float; 1642 } 1643 return Integer; 1644 } 1645 1646 bool X86_32ABIInfo::updateFreeRegs(QualType Ty, CCState &State) const { 1647 if (!IsSoftFloatABI) { 1648 Class C = classify(Ty); 1649 if (C == Float) 1650 return false; 1651 } 1652 1653 unsigned Size = getContext().getTypeSize(Ty); 1654 unsigned SizeInRegs = (Size + 31) / 32; 1655 1656 if (SizeInRegs == 0) 1657 return false; 1658 1659 if (!IsMCUABI) { 1660 if (SizeInRegs > State.FreeRegs) { 1661 State.FreeRegs = 0; 1662 return false; 1663 } 1664 } else { 1665 // The MCU psABI allows passing parameters in-reg even if there are 1666 // earlier parameters that are passed on the stack. Also, 1667 // it does not allow passing >8-byte structs in-register, 1668 // even if there are 3 free registers available. 1669 if (SizeInRegs > State.FreeRegs || SizeInRegs > 2) 1670 return false; 1671 } 1672 1673 State.FreeRegs -= SizeInRegs; 1674 return true; 1675 } 1676 1677 bool X86_32ABIInfo::shouldAggregateUseDirect(QualType Ty, CCState &State, 1678 bool &InReg, 1679 bool &NeedsPadding) const { 1680 // On Windows, aggregates other than HFAs are never passed in registers, and 1681 // they do not consume register slots. Homogenous floating-point aggregates 1682 // (HFAs) have already been dealt with at this point. 1683 if (IsWin32StructABI && isAggregateTypeForABI(Ty)) 1684 return false; 1685 1686 NeedsPadding = false; 1687 InReg = !IsMCUABI; 1688 1689 if (!updateFreeRegs(Ty, State)) 1690 return false; 1691 1692 if (IsMCUABI) 1693 return true; 1694 1695 if (State.CC == llvm::CallingConv::X86_FastCall || 1696 State.CC == llvm::CallingConv::X86_VectorCall || 1697 State.CC == llvm::CallingConv::X86_RegCall) { 1698 if (getContext().getTypeSize(Ty) <= 32 && State.FreeRegs) 1699 NeedsPadding = true; 1700 1701 return false; 1702 } 1703 1704 return true; 1705 } 1706 1707 bool X86_32ABIInfo::shouldPrimitiveUseInReg(QualType Ty, CCState &State) const { 1708 if (!updateFreeRegs(Ty, State)) 1709 return false; 1710 1711 if (IsMCUABI) 1712 return false; 1713 1714 if (State.CC == llvm::CallingConv::X86_FastCall || 1715 State.CC == llvm::CallingConv::X86_VectorCall || 1716 State.CC == llvm::CallingConv::X86_RegCall) { 1717 if (getContext().getTypeSize(Ty) > 32) 1718 return false; 1719 1720 return (Ty->isIntegralOrEnumerationType() || Ty->isPointerType() || 1721 Ty->isReferenceType()); 1722 } 1723 1724 return true; 1725 } 1726 1727 void X86_32ABIInfo::runVectorCallFirstPass(CGFunctionInfo &FI, CCState &State) const { 1728 // Vectorcall x86 works subtly different than in x64, so the format is 1729 // a bit different than the x64 version. First, all vector types (not HVAs) 1730 // are assigned, with the first 6 ending up in the [XYZ]MM0-5 registers. 1731 // This differs from the x64 implementation, where the first 6 by INDEX get 1732 // registers. 1733 // In the second pass over the arguments, HVAs are passed in the remaining 1734 // vector registers if possible, or indirectly by address. The address will be 1735 // passed in ECX/EDX if available. Any other arguments are passed according to 1736 // the usual fastcall rules. 1737 MutableArrayRef<CGFunctionInfoArgInfo> Args = FI.arguments(); 1738 for (int I = 0, E = Args.size(); I < E; ++I) { 1739 const Type *Base = nullptr; 1740 uint64_t NumElts = 0; 1741 const QualType &Ty = Args[I].type; 1742 if ((Ty->isVectorType() || Ty->isBuiltinType()) && 1743 isHomogeneousAggregate(Ty, Base, NumElts)) { 1744 if (State.FreeSSERegs >= NumElts) { 1745 State.FreeSSERegs -= NumElts; 1746 Args[I].info = ABIArgInfo::getDirectInReg(); 1747 State.IsPreassigned.set(I); 1748 } 1749 } 1750 } 1751 } 1752 1753 ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty, 1754 CCState &State) const { 1755 // FIXME: Set alignment on indirect arguments. 1756 bool IsFastCall = State.CC == llvm::CallingConv::X86_FastCall; 1757 bool IsRegCall = State.CC == llvm::CallingConv::X86_RegCall; 1758 bool IsVectorCall = State.CC == llvm::CallingConv::X86_VectorCall; 1759 1760 Ty = useFirstFieldIfTransparentUnion(Ty); 1761 TypeInfo TI = getContext().getTypeInfo(Ty); 1762 1763 // Check with the C++ ABI first. 1764 const RecordType *RT = Ty->getAs<RecordType>(); 1765 if (RT) { 1766 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()); 1767 if (RAA == CGCXXABI::RAA_Indirect) { 1768 return getIndirectResult(Ty, false, State); 1769 } else if (RAA == CGCXXABI::RAA_DirectInMemory) { 1770 // The field index doesn't matter, we'll fix it up later. 1771 return ABIArgInfo::getInAlloca(/*FieldIndex=*/0); 1772 } 1773 } 1774 1775 // Regcall uses the concept of a homogenous vector aggregate, similar 1776 // to other targets. 1777 const Type *Base = nullptr; 1778 uint64_t NumElts = 0; 1779 if ((IsRegCall || IsVectorCall) && 1780 isHomogeneousAggregate(Ty, Base, NumElts)) { 1781 if (State.FreeSSERegs >= NumElts) { 1782 State.FreeSSERegs -= NumElts; 1783 1784 // Vectorcall passes HVAs directly and does not flatten them, but regcall 1785 // does. 1786 if (IsVectorCall) 1787 return getDirectX86Hva(); 1788 1789 if (Ty->isBuiltinType() || Ty->isVectorType()) 1790 return ABIArgInfo::getDirect(); 1791 return ABIArgInfo::getExpand(); 1792 } 1793 return getIndirectResult(Ty, /*ByVal=*/false, State); 1794 } 1795 1796 if (isAggregateTypeForABI(Ty)) { 1797 // Structures with flexible arrays are always indirect. 1798 // FIXME: This should not be byval! 1799 if (RT && RT->getDecl()->hasFlexibleArrayMember()) 1800 return getIndirectResult(Ty, true, State); 1801 1802 // Ignore empty structs/unions on non-Windows. 1803 if (!IsWin32StructABI && isEmptyRecord(getContext(), Ty, true)) 1804 return ABIArgInfo::getIgnore(); 1805 1806 llvm::LLVMContext &LLVMContext = getVMContext(); 1807 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext); 1808 bool NeedsPadding = false; 1809 bool InReg; 1810 if (shouldAggregateUseDirect(Ty, State, InReg, NeedsPadding)) { 1811 unsigned SizeInRegs = (TI.Width + 31) / 32; 1812 SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32); 1813 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements); 1814 if (InReg) 1815 return ABIArgInfo::getDirectInReg(Result); 1816 else 1817 return ABIArgInfo::getDirect(Result); 1818 } 1819 llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : nullptr; 1820 1821 // Pass over-aligned aggregates on Windows indirectly. This behavior was 1822 // added in MSVC 2015. 1823 if (IsWin32StructABI && TI.AlignIsRequired && TI.Align > 32) 1824 return getIndirectResult(Ty, /*ByVal=*/false, State); 1825 1826 // Expand small (<= 128-bit) record types when we know that the stack layout 1827 // of those arguments will match the struct. This is important because the 1828 // LLVM backend isn't smart enough to remove byval, which inhibits many 1829 // optimizations. 1830 // Don't do this for the MCU if there are still free integer registers 1831 // (see X86_64 ABI for full explanation). 1832 if (TI.Width <= 4 * 32 && (!IsMCUABI || State.FreeRegs == 0) && 1833 canExpandIndirectArgument(Ty)) 1834 return ABIArgInfo::getExpandWithPadding( 1835 IsFastCall || IsVectorCall || IsRegCall, PaddingType); 1836 1837 return getIndirectResult(Ty, true, State); 1838 } 1839 1840 if (const VectorType *VT = Ty->getAs<VectorType>()) { 1841 // On Windows, vectors are passed directly if registers are available, or 1842 // indirectly if not. This avoids the need to align argument memory. Pass 1843 // user-defined vector types larger than 512 bits indirectly for simplicity. 1844 if (IsWin32StructABI) { 1845 if (TI.Width <= 512 && State.FreeSSERegs > 0) { 1846 --State.FreeSSERegs; 1847 return ABIArgInfo::getDirectInReg(); 1848 } 1849 return getIndirectResult(Ty, /*ByVal=*/false, State); 1850 } 1851 1852 // On Darwin, some vectors are passed in memory, we handle this by passing 1853 // it as an i8/i16/i32/i64. 1854 if (IsDarwinVectorABI) { 1855 if ((TI.Width == 8 || TI.Width == 16 || TI.Width == 32) || 1856 (TI.Width == 64 && VT->getNumElements() == 1)) 1857 return ABIArgInfo::getDirect( 1858 llvm::IntegerType::get(getVMContext(), TI.Width)); 1859 } 1860 1861 if (IsX86_MMXType(CGT.ConvertType(Ty))) 1862 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64)); 1863 1864 return ABIArgInfo::getDirect(); 1865 } 1866 1867 1868 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 1869 Ty = EnumTy->getDecl()->getIntegerType(); 1870 1871 bool InReg = shouldPrimitiveUseInReg(Ty, State); 1872 1873 if (isPromotableIntegerTypeForABI(Ty)) { 1874 if (InReg) 1875 return ABIArgInfo::getExtendInReg(Ty); 1876 return ABIArgInfo::getExtend(Ty); 1877 } 1878 1879 if (const auto * EIT = Ty->getAs<ExtIntType>()) { 1880 if (EIT->getNumBits() <= 64) { 1881 if (InReg) 1882 return ABIArgInfo::getDirectInReg(); 1883 return ABIArgInfo::getDirect(); 1884 } 1885 return getIndirectResult(Ty, /*ByVal=*/false, State); 1886 } 1887 1888 if (InReg) 1889 return ABIArgInfo::getDirectInReg(); 1890 return ABIArgInfo::getDirect(); 1891 } 1892 1893 void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const { 1894 CCState State(FI); 1895 if (IsMCUABI) 1896 State.FreeRegs = 3; 1897 else if (State.CC == llvm::CallingConv::X86_FastCall) { 1898 State.FreeRegs = 2; 1899 State.FreeSSERegs = 3; 1900 } else if (State.CC == llvm::CallingConv::X86_VectorCall) { 1901 State.FreeRegs = 2; 1902 State.FreeSSERegs = 6; 1903 } else if (FI.getHasRegParm()) 1904 State.FreeRegs = FI.getRegParm(); 1905 else if (State.CC == llvm::CallingConv::X86_RegCall) { 1906 State.FreeRegs = 5; 1907 State.FreeSSERegs = 8; 1908 } else if (IsWin32StructABI) { 1909 // Since MSVC 2015, the first three SSE vectors have been passed in 1910 // registers. The rest are passed indirectly. 1911 State.FreeRegs = DefaultNumRegisterParameters; 1912 State.FreeSSERegs = 3; 1913 } else 1914 State.FreeRegs = DefaultNumRegisterParameters; 1915 1916 if (!::classifyReturnType(getCXXABI(), FI, *this)) { 1917 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), State); 1918 } else if (FI.getReturnInfo().isIndirect()) { 1919 // The C++ ABI is not aware of register usage, so we have to check if the 1920 // return value was sret and put it in a register ourselves if appropriate. 1921 if (State.FreeRegs) { 1922 --State.FreeRegs; // The sret parameter consumes a register. 1923 if (!IsMCUABI) 1924 FI.getReturnInfo().setInReg(true); 1925 } 1926 } 1927 1928 // The chain argument effectively gives us another free register. 1929 if (FI.isChainCall()) 1930 ++State.FreeRegs; 1931 1932 // For vectorcall, do a first pass over the arguments, assigning FP and vector 1933 // arguments to XMM registers as available. 1934 if (State.CC == llvm::CallingConv::X86_VectorCall) 1935 runVectorCallFirstPass(FI, State); 1936 1937 bool UsedInAlloca = false; 1938 MutableArrayRef<CGFunctionInfoArgInfo> Args = FI.arguments(); 1939 for (int I = 0, E = Args.size(); I < E; ++I) { 1940 // Skip arguments that have already been assigned. 1941 if (State.IsPreassigned.test(I)) 1942 continue; 1943 1944 Args[I].info = classifyArgumentType(Args[I].type, State); 1945 UsedInAlloca |= (Args[I].info.getKind() == ABIArgInfo::InAlloca); 1946 } 1947 1948 // If we needed to use inalloca for any argument, do a second pass and rewrite 1949 // all the memory arguments to use inalloca. 1950 if (UsedInAlloca) 1951 rewriteWithInAlloca(FI); 1952 } 1953 1954 void 1955 X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields, 1956 CharUnits &StackOffset, ABIArgInfo &Info, 1957 QualType Type) const { 1958 // Arguments are always 4-byte-aligned. 1959 CharUnits WordSize = CharUnits::fromQuantity(4); 1960 assert(StackOffset.isMultipleOf(WordSize) && "unaligned inalloca struct"); 1961 1962 // sret pointers and indirect things will require an extra pointer 1963 // indirection, unless they are byval. Most things are byval, and will not 1964 // require this indirection. 1965 bool IsIndirect = false; 1966 if (Info.isIndirect() && !Info.getIndirectByVal()) 1967 IsIndirect = true; 1968 Info = ABIArgInfo::getInAlloca(FrameFields.size(), IsIndirect); 1969 llvm::Type *LLTy = CGT.ConvertTypeForMem(Type); 1970 if (IsIndirect) 1971 LLTy = LLTy->getPointerTo(0); 1972 FrameFields.push_back(LLTy); 1973 StackOffset += IsIndirect ? WordSize : getContext().getTypeSizeInChars(Type); 1974 1975 // Insert padding bytes to respect alignment. 1976 CharUnits FieldEnd = StackOffset; 1977 StackOffset = FieldEnd.alignTo(WordSize); 1978 if (StackOffset != FieldEnd) { 1979 CharUnits NumBytes = StackOffset - FieldEnd; 1980 llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext()); 1981 Ty = llvm::ArrayType::get(Ty, NumBytes.getQuantity()); 1982 FrameFields.push_back(Ty); 1983 } 1984 } 1985 1986 static bool isArgInAlloca(const ABIArgInfo &Info) { 1987 // Leave ignored and inreg arguments alone. 1988 switch (Info.getKind()) { 1989 case ABIArgInfo::InAlloca: 1990 return true; 1991 case ABIArgInfo::Ignore: 1992 return false; 1993 case ABIArgInfo::Indirect: 1994 case ABIArgInfo::Direct: 1995 case ABIArgInfo::Extend: 1996 return !Info.getInReg(); 1997 case ABIArgInfo::Expand: 1998 case ABIArgInfo::CoerceAndExpand: 1999 // These are aggregate types which are never passed in registers when 2000 // inalloca is involved. 2001 return true; 2002 } 2003 llvm_unreachable("invalid enum"); 2004 } 2005 2006 void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const { 2007 assert(IsWin32StructABI && "inalloca only supported on win32"); 2008 2009 // Build a packed struct type for all of the arguments in memory. 2010 SmallVector<llvm::Type *, 6> FrameFields; 2011 2012 // The stack alignment is always 4. 2013 CharUnits StackAlign = CharUnits::fromQuantity(4); 2014 2015 CharUnits StackOffset; 2016 CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end(); 2017 2018 // Put 'this' into the struct before 'sret', if necessary. 2019 bool IsThisCall = 2020 FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall; 2021 ABIArgInfo &Ret = FI.getReturnInfo(); 2022 if (Ret.isIndirect() && Ret.isSRetAfterThis() && !IsThisCall && 2023 isArgInAlloca(I->info)) { 2024 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type); 2025 ++I; 2026 } 2027 2028 // Put the sret parameter into the inalloca struct if it's in memory. 2029 if (Ret.isIndirect() && !Ret.getInReg()) { 2030 addFieldToArgStruct(FrameFields, StackOffset, Ret, FI.getReturnType()); 2031 // On Windows, the hidden sret parameter is always returned in eax. 2032 Ret.setInAllocaSRet(IsWin32StructABI); 2033 } 2034 2035 // Skip the 'this' parameter in ecx. 2036 if (IsThisCall) 2037 ++I; 2038 2039 // Put arguments passed in memory into the struct. 2040 for (; I != E; ++I) { 2041 if (isArgInAlloca(I->info)) 2042 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type); 2043 } 2044 2045 FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields, 2046 /*isPacked=*/true), 2047 StackAlign); 2048 } 2049 2050 Address X86_32ABIInfo::EmitVAArg(CodeGenFunction &CGF, 2051 Address VAListAddr, QualType Ty) const { 2052 2053 auto TypeInfo = getContext().getTypeInfoInChars(Ty); 2054 2055 // x86-32 changes the alignment of certain arguments on the stack. 2056 // 2057 // Just messing with TypeInfo like this works because we never pass 2058 // anything indirectly. 2059 TypeInfo.second = CharUnits::fromQuantity( 2060 getTypeStackAlignInBytes(Ty, TypeInfo.second.getQuantity())); 2061 2062 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false, 2063 TypeInfo, CharUnits::fromQuantity(4), 2064 /*AllowHigherAlign*/ true); 2065 } 2066 2067 bool X86_32TargetCodeGenInfo::isStructReturnInRegABI( 2068 const llvm::Triple &Triple, const CodeGenOptions &Opts) { 2069 assert(Triple.getArch() == llvm::Triple::x86); 2070 2071 switch (Opts.getStructReturnConvention()) { 2072 case CodeGenOptions::SRCK_Default: 2073 break; 2074 case CodeGenOptions::SRCK_OnStack: // -fpcc-struct-return 2075 return false; 2076 case CodeGenOptions::SRCK_InRegs: // -freg-struct-return 2077 return true; 2078 } 2079 2080 if (Triple.isOSDarwin() || Triple.isOSIAMCU()) 2081 return true; 2082 2083 switch (Triple.getOS()) { 2084 case llvm::Triple::DragonFly: 2085 case llvm::Triple::FreeBSD: 2086 case llvm::Triple::OpenBSD: 2087 case llvm::Triple::Win32: 2088 return true; 2089 default: 2090 return false; 2091 } 2092 } 2093 2094 void X86_32TargetCodeGenInfo::setTargetAttributes( 2095 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const { 2096 if (GV->isDeclaration()) 2097 return; 2098 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) { 2099 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) { 2100 llvm::Function *Fn = cast<llvm::Function>(GV); 2101 Fn->addFnAttr("stackrealign"); 2102 } 2103 if (FD->hasAttr<AnyX86InterruptAttr>()) { 2104 llvm::Function *Fn = cast<llvm::Function>(GV); 2105 Fn->setCallingConv(llvm::CallingConv::X86_INTR); 2106 } 2107 } 2108 } 2109 2110 bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable( 2111 CodeGen::CodeGenFunction &CGF, 2112 llvm::Value *Address) const { 2113 CodeGen::CGBuilderTy &Builder = CGF.Builder; 2114 2115 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4); 2116 2117 // 0-7 are the eight integer registers; the order is different 2118 // on Darwin (for EH), but the range is the same. 2119 // 8 is %eip. 2120 AssignToArrayRange(Builder, Address, Four8, 0, 8); 2121 2122 if (CGF.CGM.getTarget().getTriple().isOSDarwin()) { 2123 // 12-16 are st(0..4). Not sure why we stop at 4. 2124 // These have size 16, which is sizeof(long double) on 2125 // platforms with 8-byte alignment for that type. 2126 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16); 2127 AssignToArrayRange(Builder, Address, Sixteen8, 12, 16); 2128 2129 } else { 2130 // 9 is %eflags, which doesn't get a size on Darwin for some 2131 // reason. 2132 Builder.CreateAlignedStore( 2133 Four8, Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, Address, 9), 2134 CharUnits::One()); 2135 2136 // 11-16 are st(0..5). Not sure why we stop at 5. 2137 // These have size 12, which is sizeof(long double) on 2138 // platforms with 4-byte alignment for that type. 2139 llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12); 2140 AssignToArrayRange(Builder, Address, Twelve8, 11, 16); 2141 } 2142 2143 return false; 2144 } 2145 2146 //===----------------------------------------------------------------------===// 2147 // X86-64 ABI Implementation 2148 //===----------------------------------------------------------------------===// 2149 2150 2151 namespace { 2152 /// The AVX ABI level for X86 targets. 2153 enum class X86AVXABILevel { 2154 None, 2155 AVX, 2156 AVX512 2157 }; 2158 2159 /// \p returns the size in bits of the largest (native) vector for \p AVXLevel. 2160 static unsigned getNativeVectorSizeForAVXABI(X86AVXABILevel AVXLevel) { 2161 switch (AVXLevel) { 2162 case X86AVXABILevel::AVX512: 2163 return 512; 2164 case X86AVXABILevel::AVX: 2165 return 256; 2166 case X86AVXABILevel::None: 2167 return 128; 2168 } 2169 llvm_unreachable("Unknown AVXLevel"); 2170 } 2171 2172 /// X86_64ABIInfo - The X86_64 ABI information. 2173 class X86_64ABIInfo : public SwiftABIInfo { 2174 enum Class { 2175 Integer = 0, 2176 SSE, 2177 SSEUp, 2178 X87, 2179 X87Up, 2180 ComplexX87, 2181 NoClass, 2182 Memory 2183 }; 2184 2185 /// merge - Implement the X86_64 ABI merging algorithm. 2186 /// 2187 /// Merge an accumulating classification \arg Accum with a field 2188 /// classification \arg Field. 2189 /// 2190 /// \param Accum - The accumulating classification. This should 2191 /// always be either NoClass or the result of a previous merge 2192 /// call. In addition, this should never be Memory (the caller 2193 /// should just return Memory for the aggregate). 2194 static Class merge(Class Accum, Class Field); 2195 2196 /// postMerge - Implement the X86_64 ABI post merging algorithm. 2197 /// 2198 /// Post merger cleanup, reduces a malformed Hi and Lo pair to 2199 /// final MEMORY or SSE classes when necessary. 2200 /// 2201 /// \param AggregateSize - The size of the current aggregate in 2202 /// the classification process. 2203 /// 2204 /// \param Lo - The classification for the parts of the type 2205 /// residing in the low word of the containing object. 2206 /// 2207 /// \param Hi - The classification for the parts of the type 2208 /// residing in the higher words of the containing object. 2209 /// 2210 void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const; 2211 2212 /// classify - Determine the x86_64 register classes in which the 2213 /// given type T should be passed. 2214 /// 2215 /// \param Lo - The classification for the parts of the type 2216 /// residing in the low word of the containing object. 2217 /// 2218 /// \param Hi - The classification for the parts of the type 2219 /// residing in the high word of the containing object. 2220 /// 2221 /// \param OffsetBase - The bit offset of this type in the 2222 /// containing object. Some parameters are classified different 2223 /// depending on whether they straddle an eightbyte boundary. 2224 /// 2225 /// \param isNamedArg - Whether the argument in question is a "named" 2226 /// argument, as used in AMD64-ABI 3.5.7. 2227 /// 2228 /// If a word is unused its result will be NoClass; if a type should 2229 /// be passed in Memory then at least the classification of \arg Lo 2230 /// will be Memory. 2231 /// 2232 /// The \arg Lo class will be NoClass iff the argument is ignored. 2233 /// 2234 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will 2235 /// also be ComplexX87. 2236 void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi, 2237 bool isNamedArg) const; 2238 2239 llvm::Type *GetByteVectorType(QualType Ty) const; 2240 llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType, 2241 unsigned IROffset, QualType SourceTy, 2242 unsigned SourceOffset) const; 2243 llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType, 2244 unsigned IROffset, QualType SourceTy, 2245 unsigned SourceOffset) const; 2246 2247 /// getIndirectResult - Give a source type \arg Ty, return a suitable result 2248 /// such that the argument will be returned in memory. 2249 ABIArgInfo getIndirectReturnResult(QualType Ty) const; 2250 2251 /// getIndirectResult - Give a source type \arg Ty, return a suitable result 2252 /// such that the argument will be passed in memory. 2253 /// 2254 /// \param freeIntRegs - The number of free integer registers remaining 2255 /// available. 2256 ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const; 2257 2258 ABIArgInfo classifyReturnType(QualType RetTy) const; 2259 2260 ABIArgInfo classifyArgumentType(QualType Ty, unsigned freeIntRegs, 2261 unsigned &neededInt, unsigned &neededSSE, 2262 bool isNamedArg) const; 2263 2264 ABIArgInfo classifyRegCallStructType(QualType Ty, unsigned &NeededInt, 2265 unsigned &NeededSSE) const; 2266 2267 ABIArgInfo classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt, 2268 unsigned &NeededSSE) const; 2269 2270 bool IsIllegalVectorType(QualType Ty) const; 2271 2272 /// The 0.98 ABI revision clarified a lot of ambiguities, 2273 /// unfortunately in ways that were not always consistent with 2274 /// certain previous compilers. In particular, platforms which 2275 /// required strict binary compatibility with older versions of GCC 2276 /// may need to exempt themselves. 2277 bool honorsRevision0_98() const { 2278 return !getTarget().getTriple().isOSDarwin(); 2279 } 2280 2281 /// GCC classifies <1 x long long> as SSE but some platform ABIs choose to 2282 /// classify it as INTEGER (for compatibility with older clang compilers). 2283 bool classifyIntegerMMXAsSSE() const { 2284 // Clang <= 3.8 did not do this. 2285 if (getContext().getLangOpts().getClangABICompat() <= 2286 LangOptions::ClangABI::Ver3_8) 2287 return false; 2288 2289 const llvm::Triple &Triple = getTarget().getTriple(); 2290 if (Triple.isOSDarwin() || Triple.getOS() == llvm::Triple::PS4) 2291 return false; 2292 if (Triple.isOSFreeBSD() && Triple.getOSMajorVersion() >= 10) 2293 return false; 2294 return true; 2295 } 2296 2297 // GCC classifies vectors of __int128 as memory. 2298 bool passInt128VectorsInMem() const { 2299 // Clang <= 9.0 did not do this. 2300 if (getContext().getLangOpts().getClangABICompat() <= 2301 LangOptions::ClangABI::Ver9) 2302 return false; 2303 2304 const llvm::Triple &T = getTarget().getTriple(); 2305 return T.isOSLinux() || T.isOSNetBSD(); 2306 } 2307 2308 X86AVXABILevel AVXLevel; 2309 // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on 2310 // 64-bit hardware. 2311 bool Has64BitPointers; 2312 2313 public: 2314 X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) : 2315 SwiftABIInfo(CGT), AVXLevel(AVXLevel), 2316 Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) { 2317 } 2318 2319 bool isPassedUsingAVXType(QualType type) const { 2320 unsigned neededInt, neededSSE; 2321 // The freeIntRegs argument doesn't matter here. 2322 ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE, 2323 /*isNamedArg*/true); 2324 if (info.isDirect()) { 2325 llvm::Type *ty = info.getCoerceToType(); 2326 if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty)) 2327 return vectorTy->getPrimitiveSizeInBits().getFixedSize() > 128; 2328 } 2329 return false; 2330 } 2331 2332 void computeInfo(CGFunctionInfo &FI) const override; 2333 2334 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 2335 QualType Ty) const override; 2336 Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr, 2337 QualType Ty) const override; 2338 2339 bool has64BitPointers() const { 2340 return Has64BitPointers; 2341 } 2342 2343 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars, 2344 bool asReturnValue) const override { 2345 return occupiesMoreThan(CGT, scalars, /*total*/ 4); 2346 } 2347 bool isSwiftErrorInRegister() const override { 2348 return true; 2349 } 2350 }; 2351 2352 /// WinX86_64ABIInfo - The Windows X86_64 ABI information. 2353 class WinX86_64ABIInfo : public SwiftABIInfo { 2354 public: 2355 WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) 2356 : SwiftABIInfo(CGT), AVXLevel(AVXLevel), 2357 IsMingw64(getTarget().getTriple().isWindowsGNUEnvironment()) {} 2358 2359 void computeInfo(CGFunctionInfo &FI) const override; 2360 2361 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 2362 QualType Ty) const override; 2363 2364 bool isHomogeneousAggregateBaseType(QualType Ty) const override { 2365 // FIXME: Assumes vectorcall is in use. 2366 return isX86VectorTypeForVectorCall(getContext(), Ty); 2367 } 2368 2369 bool isHomogeneousAggregateSmallEnough(const Type *Ty, 2370 uint64_t NumMembers) const override { 2371 // FIXME: Assumes vectorcall is in use. 2372 return isX86VectorCallAggregateSmallEnough(NumMembers); 2373 } 2374 2375 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type *> scalars, 2376 bool asReturnValue) const override { 2377 return occupiesMoreThan(CGT, scalars, /*total*/ 4); 2378 } 2379 2380 bool isSwiftErrorInRegister() const override { 2381 return true; 2382 } 2383 2384 private: 2385 ABIArgInfo classify(QualType Ty, unsigned &FreeSSERegs, bool IsReturnType, 2386 bool IsVectorCall, bool IsRegCall) const; 2387 ABIArgInfo reclassifyHvaArgType(QualType Ty, unsigned &FreeSSERegs, 2388 const ABIArgInfo ¤t) const; 2389 void computeVectorCallArgs(CGFunctionInfo &FI, unsigned FreeSSERegs, 2390 bool IsVectorCall, bool IsRegCall) const; 2391 2392 X86AVXABILevel AVXLevel; 2393 2394 bool IsMingw64; 2395 }; 2396 2397 class X86_64TargetCodeGenInfo : public TargetCodeGenInfo { 2398 public: 2399 X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) 2400 : TargetCodeGenInfo(std::make_unique<X86_64ABIInfo>(CGT, AVXLevel)) {} 2401 2402 const X86_64ABIInfo &getABIInfo() const { 2403 return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo()); 2404 } 2405 2406 /// Disable tail call on x86-64. The epilogue code before the tail jump blocks 2407 /// the autoreleaseRV/retainRV optimization. 2408 bool shouldSuppressTailCallsOfRetainAutoreleasedReturnValue() const override { 2409 return true; 2410 } 2411 2412 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override { 2413 return 7; 2414 } 2415 2416 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 2417 llvm::Value *Address) const override { 2418 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8); 2419 2420 // 0-15 are the 16 integer registers. 2421 // 16 is %rip. 2422 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16); 2423 return false; 2424 } 2425 2426 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF, 2427 StringRef Constraint, 2428 llvm::Type* Ty) const override { 2429 return X86AdjustInlineAsmType(CGF, Constraint, Ty); 2430 } 2431 2432 bool isNoProtoCallVariadic(const CallArgList &args, 2433 const FunctionNoProtoType *fnType) const override { 2434 // The default CC on x86-64 sets %al to the number of SSA 2435 // registers used, and GCC sets this when calling an unprototyped 2436 // function, so we override the default behavior. However, don't do 2437 // that when AVX types are involved: the ABI explicitly states it is 2438 // undefined, and it doesn't work in practice because of how the ABI 2439 // defines varargs anyway. 2440 if (fnType->getCallConv() == CC_C) { 2441 bool HasAVXType = false; 2442 for (CallArgList::const_iterator 2443 it = args.begin(), ie = args.end(); it != ie; ++it) { 2444 if (getABIInfo().isPassedUsingAVXType(it->Ty)) { 2445 HasAVXType = true; 2446 break; 2447 } 2448 } 2449 2450 if (!HasAVXType) 2451 return true; 2452 } 2453 2454 return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType); 2455 } 2456 2457 llvm::Constant * 2458 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override { 2459 unsigned Sig = (0xeb << 0) | // jmp rel8 2460 (0x06 << 8) | // .+0x08 2461 ('v' << 16) | 2462 ('2' << 24); 2463 return llvm::ConstantInt::get(CGM.Int32Ty, Sig); 2464 } 2465 2466 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 2467 CodeGen::CodeGenModule &CGM) const override { 2468 if (GV->isDeclaration()) 2469 return; 2470 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) { 2471 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) { 2472 llvm::Function *Fn = cast<llvm::Function>(GV); 2473 Fn->addFnAttr("stackrealign"); 2474 } 2475 if (FD->hasAttr<AnyX86InterruptAttr>()) { 2476 llvm::Function *Fn = cast<llvm::Function>(GV); 2477 Fn->setCallingConv(llvm::CallingConv::X86_INTR); 2478 } 2479 } 2480 } 2481 2482 void checkFunctionCallABI(CodeGenModule &CGM, SourceLocation CallLoc, 2483 const FunctionDecl *Caller, 2484 const FunctionDecl *Callee, 2485 const CallArgList &Args) const override; 2486 }; 2487 2488 static void initFeatureMaps(const ASTContext &Ctx, 2489 llvm::StringMap<bool> &CallerMap, 2490 const FunctionDecl *Caller, 2491 llvm::StringMap<bool> &CalleeMap, 2492 const FunctionDecl *Callee) { 2493 if (CalleeMap.empty() && CallerMap.empty()) { 2494 // The caller is potentially nullptr in the case where the call isn't in a 2495 // function. In this case, the getFunctionFeatureMap ensures we just get 2496 // the TU level setting (since it cannot be modified by 'target'.. 2497 Ctx.getFunctionFeatureMap(CallerMap, Caller); 2498 Ctx.getFunctionFeatureMap(CalleeMap, Callee); 2499 } 2500 } 2501 2502 static bool checkAVXParamFeature(DiagnosticsEngine &Diag, 2503 SourceLocation CallLoc, 2504 const llvm::StringMap<bool> &CallerMap, 2505 const llvm::StringMap<bool> &CalleeMap, 2506 QualType Ty, StringRef Feature, 2507 bool IsArgument) { 2508 bool CallerHasFeat = CallerMap.lookup(Feature); 2509 bool CalleeHasFeat = CalleeMap.lookup(Feature); 2510 if (!CallerHasFeat && !CalleeHasFeat) 2511 return Diag.Report(CallLoc, diag::warn_avx_calling_convention) 2512 << IsArgument << Ty << Feature; 2513 2514 // Mixing calling conventions here is very clearly an error. 2515 if (!CallerHasFeat || !CalleeHasFeat) 2516 return Diag.Report(CallLoc, diag::err_avx_calling_convention) 2517 << IsArgument << Ty << Feature; 2518 2519 // Else, both caller and callee have the required feature, so there is no need 2520 // to diagnose. 2521 return false; 2522 } 2523 2524 static bool checkAVXParam(DiagnosticsEngine &Diag, ASTContext &Ctx, 2525 SourceLocation CallLoc, 2526 const llvm::StringMap<bool> &CallerMap, 2527 const llvm::StringMap<bool> &CalleeMap, QualType Ty, 2528 bool IsArgument) { 2529 uint64_t Size = Ctx.getTypeSize(Ty); 2530 if (Size > 256) 2531 return checkAVXParamFeature(Diag, CallLoc, CallerMap, CalleeMap, Ty, 2532 "avx512f", IsArgument); 2533 2534 if (Size > 128) 2535 return checkAVXParamFeature(Diag, CallLoc, CallerMap, CalleeMap, Ty, "avx", 2536 IsArgument); 2537 2538 return false; 2539 } 2540 2541 void X86_64TargetCodeGenInfo::checkFunctionCallABI( 2542 CodeGenModule &CGM, SourceLocation CallLoc, const FunctionDecl *Caller, 2543 const FunctionDecl *Callee, const CallArgList &Args) const { 2544 llvm::StringMap<bool> CallerMap; 2545 llvm::StringMap<bool> CalleeMap; 2546 unsigned ArgIndex = 0; 2547 2548 // We need to loop through the actual call arguments rather than the the 2549 // function's parameters, in case this variadic. 2550 for (const CallArg &Arg : Args) { 2551 // The "avx" feature changes how vectors >128 in size are passed. "avx512f" 2552 // additionally changes how vectors >256 in size are passed. Like GCC, we 2553 // warn when a function is called with an argument where this will change. 2554 // Unlike GCC, we also error when it is an obvious ABI mismatch, that is, 2555 // the caller and callee features are mismatched. 2556 // Unfortunately, we cannot do this diagnostic in SEMA, since the callee can 2557 // change its ABI with attribute-target after this call. 2558 if (Arg.getType()->isVectorType() && 2559 CGM.getContext().getTypeSize(Arg.getType()) > 128) { 2560 initFeatureMaps(CGM.getContext(), CallerMap, Caller, CalleeMap, Callee); 2561 QualType Ty = Arg.getType(); 2562 // The CallArg seems to have desugared the type already, so for clearer 2563 // diagnostics, replace it with the type in the FunctionDecl if possible. 2564 if (ArgIndex < Callee->getNumParams()) 2565 Ty = Callee->getParamDecl(ArgIndex)->getType(); 2566 2567 if (checkAVXParam(CGM.getDiags(), CGM.getContext(), CallLoc, CallerMap, 2568 CalleeMap, Ty, /*IsArgument*/ true)) 2569 return; 2570 } 2571 ++ArgIndex; 2572 } 2573 2574 // Check return always, as we don't have a good way of knowing in codegen 2575 // whether this value is used, tail-called, etc. 2576 if (Callee->getReturnType()->isVectorType() && 2577 CGM.getContext().getTypeSize(Callee->getReturnType()) > 128) { 2578 initFeatureMaps(CGM.getContext(), CallerMap, Caller, CalleeMap, Callee); 2579 checkAVXParam(CGM.getDiags(), CGM.getContext(), CallLoc, CallerMap, 2580 CalleeMap, Callee->getReturnType(), 2581 /*IsArgument*/ false); 2582 } 2583 } 2584 2585 static std::string qualifyWindowsLibrary(llvm::StringRef Lib) { 2586 // If the argument does not end in .lib, automatically add the suffix. 2587 // If the argument contains a space, enclose it in quotes. 2588 // This matches the behavior of MSVC. 2589 bool Quote = (Lib.find(" ") != StringRef::npos); 2590 std::string ArgStr = Quote ? "\"" : ""; 2591 ArgStr += Lib; 2592 if (!Lib.endswith_lower(".lib") && !Lib.endswith_lower(".a")) 2593 ArgStr += ".lib"; 2594 ArgStr += Quote ? "\"" : ""; 2595 return ArgStr; 2596 } 2597 2598 class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo { 2599 public: 2600 WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, 2601 bool DarwinVectorABI, bool RetSmallStructInRegABI, bool Win32StructABI, 2602 unsigned NumRegisterParameters) 2603 : X86_32TargetCodeGenInfo(CGT, DarwinVectorABI, RetSmallStructInRegABI, 2604 Win32StructABI, NumRegisterParameters, false) {} 2605 2606 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 2607 CodeGen::CodeGenModule &CGM) const override; 2608 2609 void getDependentLibraryOption(llvm::StringRef Lib, 2610 llvm::SmallString<24> &Opt) const override { 2611 Opt = "/DEFAULTLIB:"; 2612 Opt += qualifyWindowsLibrary(Lib); 2613 } 2614 2615 void getDetectMismatchOption(llvm::StringRef Name, 2616 llvm::StringRef Value, 2617 llvm::SmallString<32> &Opt) const override { 2618 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\""; 2619 } 2620 }; 2621 2622 static void addStackProbeTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 2623 CodeGen::CodeGenModule &CGM) { 2624 if (llvm::Function *Fn = dyn_cast_or_null<llvm::Function>(GV)) { 2625 2626 if (CGM.getCodeGenOpts().StackProbeSize != 4096) 2627 Fn->addFnAttr("stack-probe-size", 2628 llvm::utostr(CGM.getCodeGenOpts().StackProbeSize)); 2629 if (CGM.getCodeGenOpts().NoStackArgProbe) 2630 Fn->addFnAttr("no-stack-arg-probe"); 2631 } 2632 } 2633 2634 void WinX86_32TargetCodeGenInfo::setTargetAttributes( 2635 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const { 2636 X86_32TargetCodeGenInfo::setTargetAttributes(D, GV, CGM); 2637 if (GV->isDeclaration()) 2638 return; 2639 addStackProbeTargetAttributes(D, GV, CGM); 2640 } 2641 2642 class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo { 2643 public: 2644 WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, 2645 X86AVXABILevel AVXLevel) 2646 : TargetCodeGenInfo(std::make_unique<WinX86_64ABIInfo>(CGT, AVXLevel)) {} 2647 2648 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 2649 CodeGen::CodeGenModule &CGM) const override; 2650 2651 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override { 2652 return 7; 2653 } 2654 2655 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 2656 llvm::Value *Address) const override { 2657 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8); 2658 2659 // 0-15 are the 16 integer registers. 2660 // 16 is %rip. 2661 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16); 2662 return false; 2663 } 2664 2665 void getDependentLibraryOption(llvm::StringRef Lib, 2666 llvm::SmallString<24> &Opt) const override { 2667 Opt = "/DEFAULTLIB:"; 2668 Opt += qualifyWindowsLibrary(Lib); 2669 } 2670 2671 void getDetectMismatchOption(llvm::StringRef Name, 2672 llvm::StringRef Value, 2673 llvm::SmallString<32> &Opt) const override { 2674 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\""; 2675 } 2676 }; 2677 2678 void WinX86_64TargetCodeGenInfo::setTargetAttributes( 2679 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const { 2680 TargetCodeGenInfo::setTargetAttributes(D, GV, CGM); 2681 if (GV->isDeclaration()) 2682 return; 2683 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) { 2684 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) { 2685 llvm::Function *Fn = cast<llvm::Function>(GV); 2686 Fn->addFnAttr("stackrealign"); 2687 } 2688 if (FD->hasAttr<AnyX86InterruptAttr>()) { 2689 llvm::Function *Fn = cast<llvm::Function>(GV); 2690 Fn->setCallingConv(llvm::CallingConv::X86_INTR); 2691 } 2692 } 2693 2694 addStackProbeTargetAttributes(D, GV, CGM); 2695 } 2696 } 2697 2698 void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo, 2699 Class &Hi) const { 2700 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done: 2701 // 2702 // (a) If one of the classes is Memory, the whole argument is passed in 2703 // memory. 2704 // 2705 // (b) If X87UP is not preceded by X87, the whole argument is passed in 2706 // memory. 2707 // 2708 // (c) If the size of the aggregate exceeds two eightbytes and the first 2709 // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole 2710 // argument is passed in memory. NOTE: This is necessary to keep the 2711 // ABI working for processors that don't support the __m256 type. 2712 // 2713 // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE. 2714 // 2715 // Some of these are enforced by the merging logic. Others can arise 2716 // only with unions; for example: 2717 // union { _Complex double; unsigned; } 2718 // 2719 // Note that clauses (b) and (c) were added in 0.98. 2720 // 2721 if (Hi == Memory) 2722 Lo = Memory; 2723 if (Hi == X87Up && Lo != X87 && honorsRevision0_98()) 2724 Lo = Memory; 2725 if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp)) 2726 Lo = Memory; 2727 if (Hi == SSEUp && Lo != SSE) 2728 Hi = SSE; 2729 } 2730 2731 X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) { 2732 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is 2733 // classified recursively so that always two fields are 2734 // considered. The resulting class is calculated according to 2735 // the classes of the fields in the eightbyte: 2736 // 2737 // (a) If both classes are equal, this is the resulting class. 2738 // 2739 // (b) If one of the classes is NO_CLASS, the resulting class is 2740 // the other class. 2741 // 2742 // (c) If one of the classes is MEMORY, the result is the MEMORY 2743 // class. 2744 // 2745 // (d) If one of the classes is INTEGER, the result is the 2746 // INTEGER. 2747 // 2748 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class, 2749 // MEMORY is used as class. 2750 // 2751 // (f) Otherwise class SSE is used. 2752 2753 // Accum should never be memory (we should have returned) or 2754 // ComplexX87 (because this cannot be passed in a structure). 2755 assert((Accum != Memory && Accum != ComplexX87) && 2756 "Invalid accumulated classification during merge."); 2757 if (Accum == Field || Field == NoClass) 2758 return Accum; 2759 if (Field == Memory) 2760 return Memory; 2761 if (Accum == NoClass) 2762 return Field; 2763 if (Accum == Integer || Field == Integer) 2764 return Integer; 2765 if (Field == X87 || Field == X87Up || Field == ComplexX87 || 2766 Accum == X87 || Accum == X87Up) 2767 return Memory; 2768 return SSE; 2769 } 2770 2771 void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase, 2772 Class &Lo, Class &Hi, bool isNamedArg) const { 2773 // FIXME: This code can be simplified by introducing a simple value class for 2774 // Class pairs with appropriate constructor methods for the various 2775 // situations. 2776 2777 // FIXME: Some of the split computations are wrong; unaligned vectors 2778 // shouldn't be passed in registers for example, so there is no chance they 2779 // can straddle an eightbyte. Verify & simplify. 2780 2781 Lo = Hi = NoClass; 2782 2783 Class &Current = OffsetBase < 64 ? Lo : Hi; 2784 Current = Memory; 2785 2786 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) { 2787 BuiltinType::Kind k = BT->getKind(); 2788 2789 if (k == BuiltinType::Void) { 2790 Current = NoClass; 2791 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) { 2792 Lo = Integer; 2793 Hi = Integer; 2794 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) { 2795 Current = Integer; 2796 } else if (k == BuiltinType::Float || k == BuiltinType::Double) { 2797 Current = SSE; 2798 } else if (k == BuiltinType::LongDouble) { 2799 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat(); 2800 if (LDF == &llvm::APFloat::IEEEquad()) { 2801 Lo = SSE; 2802 Hi = SSEUp; 2803 } else if (LDF == &llvm::APFloat::x87DoubleExtended()) { 2804 Lo = X87; 2805 Hi = X87Up; 2806 } else if (LDF == &llvm::APFloat::IEEEdouble()) { 2807 Current = SSE; 2808 } else 2809 llvm_unreachable("unexpected long double representation!"); 2810 } 2811 // FIXME: _Decimal32 and _Decimal64 are SSE. 2812 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp). 2813 return; 2814 } 2815 2816 if (const EnumType *ET = Ty->getAs<EnumType>()) { 2817 // Classify the underlying integer type. 2818 classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg); 2819 return; 2820 } 2821 2822 if (Ty->hasPointerRepresentation()) { 2823 Current = Integer; 2824 return; 2825 } 2826 2827 if (Ty->isMemberPointerType()) { 2828 if (Ty->isMemberFunctionPointerType()) { 2829 if (Has64BitPointers) { 2830 // If Has64BitPointers, this is an {i64, i64}, so classify both 2831 // Lo and Hi now. 2832 Lo = Hi = Integer; 2833 } else { 2834 // Otherwise, with 32-bit pointers, this is an {i32, i32}. If that 2835 // straddles an eightbyte boundary, Hi should be classified as well. 2836 uint64_t EB_FuncPtr = (OffsetBase) / 64; 2837 uint64_t EB_ThisAdj = (OffsetBase + 64 - 1) / 64; 2838 if (EB_FuncPtr != EB_ThisAdj) { 2839 Lo = Hi = Integer; 2840 } else { 2841 Current = Integer; 2842 } 2843 } 2844 } else { 2845 Current = Integer; 2846 } 2847 return; 2848 } 2849 2850 if (const VectorType *VT = Ty->getAs<VectorType>()) { 2851 uint64_t Size = getContext().getTypeSize(VT); 2852 if (Size == 1 || Size == 8 || Size == 16 || Size == 32) { 2853 // gcc passes the following as integer: 2854 // 4 bytes - <4 x char>, <2 x short>, <1 x int>, <1 x float> 2855 // 2 bytes - <2 x char>, <1 x short> 2856 // 1 byte - <1 x char> 2857 Current = Integer; 2858 2859 // If this type crosses an eightbyte boundary, it should be 2860 // split. 2861 uint64_t EB_Lo = (OffsetBase) / 64; 2862 uint64_t EB_Hi = (OffsetBase + Size - 1) / 64; 2863 if (EB_Lo != EB_Hi) 2864 Hi = Lo; 2865 } else if (Size == 64) { 2866 QualType ElementType = VT->getElementType(); 2867 2868 // gcc passes <1 x double> in memory. :( 2869 if (ElementType->isSpecificBuiltinType(BuiltinType::Double)) 2870 return; 2871 2872 // gcc passes <1 x long long> as SSE but clang used to unconditionally 2873 // pass them as integer. For platforms where clang is the de facto 2874 // platform compiler, we must continue to use integer. 2875 if (!classifyIntegerMMXAsSSE() && 2876 (ElementType->isSpecificBuiltinType(BuiltinType::LongLong) || 2877 ElementType->isSpecificBuiltinType(BuiltinType::ULongLong) || 2878 ElementType->isSpecificBuiltinType(BuiltinType::Long) || 2879 ElementType->isSpecificBuiltinType(BuiltinType::ULong))) 2880 Current = Integer; 2881 else 2882 Current = SSE; 2883 2884 // If this type crosses an eightbyte boundary, it should be 2885 // split. 2886 if (OffsetBase && OffsetBase != 64) 2887 Hi = Lo; 2888 } else if (Size == 128 || 2889 (isNamedArg && Size <= getNativeVectorSizeForAVXABI(AVXLevel))) { 2890 QualType ElementType = VT->getElementType(); 2891 2892 // gcc passes 256 and 512 bit <X x __int128> vectors in memory. :( 2893 if (passInt128VectorsInMem() && Size != 128 && 2894 (ElementType->isSpecificBuiltinType(BuiltinType::Int128) || 2895 ElementType->isSpecificBuiltinType(BuiltinType::UInt128))) 2896 return; 2897 2898 // Arguments of 256-bits are split into four eightbyte chunks. The 2899 // least significant one belongs to class SSE and all the others to class 2900 // SSEUP. The original Lo and Hi design considers that types can't be 2901 // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense. 2902 // This design isn't correct for 256-bits, but since there're no cases 2903 // where the upper parts would need to be inspected, avoid adding 2904 // complexity and just consider Hi to match the 64-256 part. 2905 // 2906 // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in 2907 // registers if they are "named", i.e. not part of the "..." of a 2908 // variadic function. 2909 // 2910 // Similarly, per 3.2.3. of the AVX512 draft, 512-bits ("named") args are 2911 // split into eight eightbyte chunks, one SSE and seven SSEUP. 2912 Lo = SSE; 2913 Hi = SSEUp; 2914 } 2915 return; 2916 } 2917 2918 if (const ComplexType *CT = Ty->getAs<ComplexType>()) { 2919 QualType ET = getContext().getCanonicalType(CT->getElementType()); 2920 2921 uint64_t Size = getContext().getTypeSize(Ty); 2922 if (ET->isIntegralOrEnumerationType()) { 2923 if (Size <= 64) 2924 Current = Integer; 2925 else if (Size <= 128) 2926 Lo = Hi = Integer; 2927 } else if (ET == getContext().FloatTy) { 2928 Current = SSE; 2929 } else if (ET == getContext().DoubleTy) { 2930 Lo = Hi = SSE; 2931 } else if (ET == getContext().LongDoubleTy) { 2932 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat(); 2933 if (LDF == &llvm::APFloat::IEEEquad()) 2934 Current = Memory; 2935 else if (LDF == &llvm::APFloat::x87DoubleExtended()) 2936 Current = ComplexX87; 2937 else if (LDF == &llvm::APFloat::IEEEdouble()) 2938 Lo = Hi = SSE; 2939 else 2940 llvm_unreachable("unexpected long double representation!"); 2941 } 2942 2943 // If this complex type crosses an eightbyte boundary then it 2944 // should be split. 2945 uint64_t EB_Real = (OffsetBase) / 64; 2946 uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64; 2947 if (Hi == NoClass && EB_Real != EB_Imag) 2948 Hi = Lo; 2949 2950 return; 2951 } 2952 2953 if (const auto *EITy = Ty->getAs<ExtIntType>()) { 2954 if (EITy->getNumBits() <= 64) 2955 Current = Integer; 2956 else if (EITy->getNumBits() <= 128) 2957 Lo = Hi = Integer; 2958 // Larger values need to get passed in memory. 2959 return; 2960 } 2961 2962 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) { 2963 // Arrays are treated like structures. 2964 2965 uint64_t Size = getContext().getTypeSize(Ty); 2966 2967 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger 2968 // than eight eightbytes, ..., it has class MEMORY. 2969 if (Size > 512) 2970 return; 2971 2972 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned 2973 // fields, it has class MEMORY. 2974 // 2975 // Only need to check alignment of array base. 2976 if (OffsetBase % getContext().getTypeAlign(AT->getElementType())) 2977 return; 2978 2979 // Otherwise implement simplified merge. We could be smarter about 2980 // this, but it isn't worth it and would be harder to verify. 2981 Current = NoClass; 2982 uint64_t EltSize = getContext().getTypeSize(AT->getElementType()); 2983 uint64_t ArraySize = AT->getSize().getZExtValue(); 2984 2985 // The only case a 256-bit wide vector could be used is when the array 2986 // contains a single 256-bit element. Since Lo and Hi logic isn't extended 2987 // to work for sizes wider than 128, early check and fallback to memory. 2988 // 2989 if (Size > 128 && 2990 (Size != EltSize || Size > getNativeVectorSizeForAVXABI(AVXLevel))) 2991 return; 2992 2993 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) { 2994 Class FieldLo, FieldHi; 2995 classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg); 2996 Lo = merge(Lo, FieldLo); 2997 Hi = merge(Hi, FieldHi); 2998 if (Lo == Memory || Hi == Memory) 2999 break; 3000 } 3001 3002 postMerge(Size, Lo, Hi); 3003 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification."); 3004 return; 3005 } 3006 3007 if (const RecordType *RT = Ty->getAs<RecordType>()) { 3008 uint64_t Size = getContext().getTypeSize(Ty); 3009 3010 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger 3011 // than eight eightbytes, ..., it has class MEMORY. 3012 if (Size > 512) 3013 return; 3014 3015 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial 3016 // copy constructor or a non-trivial destructor, it is passed by invisible 3017 // reference. 3018 if (getRecordArgABI(RT, getCXXABI())) 3019 return; 3020 3021 const RecordDecl *RD = RT->getDecl(); 3022 3023 // Assume variable sized types are passed in memory. 3024 if (RD->hasFlexibleArrayMember()) 3025 return; 3026 3027 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD); 3028 3029 // Reset Lo class, this will be recomputed. 3030 Current = NoClass; 3031 3032 // If this is a C++ record, classify the bases first. 3033 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 3034 for (const auto &I : CXXRD->bases()) { 3035 assert(!I.isVirtual() && !I.getType()->isDependentType() && 3036 "Unexpected base class!"); 3037 const auto *Base = 3038 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl()); 3039 3040 // Classify this field. 3041 // 3042 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a 3043 // single eightbyte, each is classified separately. Each eightbyte gets 3044 // initialized to class NO_CLASS. 3045 Class FieldLo, FieldHi; 3046 uint64_t Offset = 3047 OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base)); 3048 classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg); 3049 Lo = merge(Lo, FieldLo); 3050 Hi = merge(Hi, FieldHi); 3051 if (Lo == Memory || Hi == Memory) { 3052 postMerge(Size, Lo, Hi); 3053 return; 3054 } 3055 } 3056 } 3057 3058 // Classify the fields one at a time, merging the results. 3059 unsigned idx = 0; 3060 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 3061 i != e; ++i, ++idx) { 3062 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx); 3063 bool BitField = i->isBitField(); 3064 3065 // Ignore padding bit-fields. 3066 if (BitField && i->isUnnamedBitfield()) 3067 continue; 3068 3069 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than 3070 // four eightbytes, or it contains unaligned fields, it has class MEMORY. 3071 // 3072 // The only case a 256-bit wide vector could be used is when the struct 3073 // contains a single 256-bit element. Since Lo and Hi logic isn't extended 3074 // to work for sizes wider than 128, early check and fallback to memory. 3075 // 3076 if (Size > 128 && (Size != getContext().getTypeSize(i->getType()) || 3077 Size > getNativeVectorSizeForAVXABI(AVXLevel))) { 3078 Lo = Memory; 3079 postMerge(Size, Lo, Hi); 3080 return; 3081 } 3082 // Note, skip this test for bit-fields, see below. 3083 if (!BitField && Offset % getContext().getTypeAlign(i->getType())) { 3084 Lo = Memory; 3085 postMerge(Size, Lo, Hi); 3086 return; 3087 } 3088 3089 // Classify this field. 3090 // 3091 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate 3092 // exceeds a single eightbyte, each is classified 3093 // separately. Each eightbyte gets initialized to class 3094 // NO_CLASS. 3095 Class FieldLo, FieldHi; 3096 3097 // Bit-fields require special handling, they do not force the 3098 // structure to be passed in memory even if unaligned, and 3099 // therefore they can straddle an eightbyte. 3100 if (BitField) { 3101 assert(!i->isUnnamedBitfield()); 3102 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx); 3103 uint64_t Size = i->getBitWidthValue(getContext()); 3104 3105 uint64_t EB_Lo = Offset / 64; 3106 uint64_t EB_Hi = (Offset + Size - 1) / 64; 3107 3108 if (EB_Lo) { 3109 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes."); 3110 FieldLo = NoClass; 3111 FieldHi = Integer; 3112 } else { 3113 FieldLo = Integer; 3114 FieldHi = EB_Hi ? Integer : NoClass; 3115 } 3116 } else 3117 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg); 3118 Lo = merge(Lo, FieldLo); 3119 Hi = merge(Hi, FieldHi); 3120 if (Lo == Memory || Hi == Memory) 3121 break; 3122 } 3123 3124 postMerge(Size, Lo, Hi); 3125 } 3126 } 3127 3128 ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const { 3129 // If this is a scalar LLVM value then assume LLVM will pass it in the right 3130 // place naturally. 3131 if (!isAggregateTypeForABI(Ty)) { 3132 // Treat an enum type as its underlying type. 3133 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 3134 Ty = EnumTy->getDecl()->getIntegerType(); 3135 3136 if (Ty->isExtIntType()) 3137 return getNaturalAlignIndirect(Ty); 3138 3139 return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty) 3140 : ABIArgInfo::getDirect()); 3141 } 3142 3143 return getNaturalAlignIndirect(Ty); 3144 } 3145 3146 bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const { 3147 if (const VectorType *VecTy = Ty->getAs<VectorType>()) { 3148 uint64_t Size = getContext().getTypeSize(VecTy); 3149 unsigned LargestVector = getNativeVectorSizeForAVXABI(AVXLevel); 3150 if (Size <= 64 || Size > LargestVector) 3151 return true; 3152 QualType EltTy = VecTy->getElementType(); 3153 if (passInt128VectorsInMem() && 3154 (EltTy->isSpecificBuiltinType(BuiltinType::Int128) || 3155 EltTy->isSpecificBuiltinType(BuiltinType::UInt128))) 3156 return true; 3157 } 3158 3159 return false; 3160 } 3161 3162 ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty, 3163 unsigned freeIntRegs) const { 3164 // If this is a scalar LLVM value then assume LLVM will pass it in the right 3165 // place naturally. 3166 // 3167 // This assumption is optimistic, as there could be free registers available 3168 // when we need to pass this argument in memory, and LLVM could try to pass 3169 // the argument in the free register. This does not seem to happen currently, 3170 // but this code would be much safer if we could mark the argument with 3171 // 'onstack'. See PR12193. 3172 if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty) && 3173 !Ty->isExtIntType()) { 3174 // Treat an enum type as its underlying type. 3175 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 3176 Ty = EnumTy->getDecl()->getIntegerType(); 3177 3178 return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty) 3179 : ABIArgInfo::getDirect()); 3180 } 3181 3182 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 3183 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 3184 3185 // Compute the byval alignment. We specify the alignment of the byval in all 3186 // cases so that the mid-level optimizer knows the alignment of the byval. 3187 unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U); 3188 3189 // Attempt to avoid passing indirect results using byval when possible. This 3190 // is important for good codegen. 3191 // 3192 // We do this by coercing the value into a scalar type which the backend can 3193 // handle naturally (i.e., without using byval). 3194 // 3195 // For simplicity, we currently only do this when we have exhausted all of the 3196 // free integer registers. Doing this when there are free integer registers 3197 // would require more care, as we would have to ensure that the coerced value 3198 // did not claim the unused register. That would require either reording the 3199 // arguments to the function (so that any subsequent inreg values came first), 3200 // or only doing this optimization when there were no following arguments that 3201 // might be inreg. 3202 // 3203 // We currently expect it to be rare (particularly in well written code) for 3204 // arguments to be passed on the stack when there are still free integer 3205 // registers available (this would typically imply large structs being passed 3206 // by value), so this seems like a fair tradeoff for now. 3207 // 3208 // We can revisit this if the backend grows support for 'onstack' parameter 3209 // attributes. See PR12193. 3210 if (freeIntRegs == 0) { 3211 uint64_t Size = getContext().getTypeSize(Ty); 3212 3213 // If this type fits in an eightbyte, coerce it into the matching integral 3214 // type, which will end up on the stack (with alignment 8). 3215 if (Align == 8 && Size <= 64) 3216 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 3217 Size)); 3218 } 3219 3220 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(Align)); 3221 } 3222 3223 /// The ABI specifies that a value should be passed in a full vector XMM/YMM 3224 /// register. Pick an LLVM IR type that will be passed as a vector register. 3225 llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const { 3226 // Wrapper structs/arrays that only contain vectors are passed just like 3227 // vectors; strip them off if present. 3228 if (const Type *InnerTy = isSingleElementStruct(Ty, getContext())) 3229 Ty = QualType(InnerTy, 0); 3230 3231 llvm::Type *IRType = CGT.ConvertType(Ty); 3232 if (isa<llvm::VectorType>(IRType)) { 3233 // Don't pass vXi128 vectors in their native type, the backend can't 3234 // legalize them. 3235 if (passInt128VectorsInMem() && 3236 cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy(128)) { 3237 // Use a vXi64 vector. 3238 uint64_t Size = getContext().getTypeSize(Ty); 3239 return llvm::FixedVectorType::get(llvm::Type::getInt64Ty(getVMContext()), 3240 Size / 64); 3241 } 3242 3243 return IRType; 3244 } 3245 3246 if (IRType->getTypeID() == llvm::Type::FP128TyID) 3247 return IRType; 3248 3249 // We couldn't find the preferred IR vector type for 'Ty'. 3250 uint64_t Size = getContext().getTypeSize(Ty); 3251 assert((Size == 128 || Size == 256 || Size == 512) && "Invalid type found!"); 3252 3253 3254 // Return a LLVM IR vector type based on the size of 'Ty'. 3255 return llvm::FixedVectorType::get(llvm::Type::getDoubleTy(getVMContext()), 3256 Size / 64); 3257 } 3258 3259 /// BitsContainNoUserData - Return true if the specified [start,end) bit range 3260 /// is known to either be off the end of the specified type or being in 3261 /// alignment padding. The user type specified is known to be at most 128 bits 3262 /// in size, and have passed through X86_64ABIInfo::classify with a successful 3263 /// classification that put one of the two halves in the INTEGER class. 3264 /// 3265 /// It is conservatively correct to return false. 3266 static bool BitsContainNoUserData(QualType Ty, unsigned StartBit, 3267 unsigned EndBit, ASTContext &Context) { 3268 // If the bytes being queried are off the end of the type, there is no user 3269 // data hiding here. This handles analysis of builtins, vectors and other 3270 // types that don't contain interesting padding. 3271 unsigned TySize = (unsigned)Context.getTypeSize(Ty); 3272 if (TySize <= StartBit) 3273 return true; 3274 3275 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) { 3276 unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType()); 3277 unsigned NumElts = (unsigned)AT->getSize().getZExtValue(); 3278 3279 // Check each element to see if the element overlaps with the queried range. 3280 for (unsigned i = 0; i != NumElts; ++i) { 3281 // If the element is after the span we care about, then we're done.. 3282 unsigned EltOffset = i*EltSize; 3283 if (EltOffset >= EndBit) break; 3284 3285 unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0; 3286 if (!BitsContainNoUserData(AT->getElementType(), EltStart, 3287 EndBit-EltOffset, Context)) 3288 return false; 3289 } 3290 // If it overlaps no elements, then it is safe to process as padding. 3291 return true; 3292 } 3293 3294 if (const RecordType *RT = Ty->getAs<RecordType>()) { 3295 const RecordDecl *RD = RT->getDecl(); 3296 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); 3297 3298 // If this is a C++ record, check the bases first. 3299 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 3300 for (const auto &I : CXXRD->bases()) { 3301 assert(!I.isVirtual() && !I.getType()->isDependentType() && 3302 "Unexpected base class!"); 3303 const auto *Base = 3304 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl()); 3305 3306 // If the base is after the span we care about, ignore it. 3307 unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base)); 3308 if (BaseOffset >= EndBit) continue; 3309 3310 unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0; 3311 if (!BitsContainNoUserData(I.getType(), BaseStart, 3312 EndBit-BaseOffset, Context)) 3313 return false; 3314 } 3315 } 3316 3317 // Verify that no field has data that overlaps the region of interest. Yes 3318 // this could be sped up a lot by being smarter about queried fields, 3319 // however we're only looking at structs up to 16 bytes, so we don't care 3320 // much. 3321 unsigned idx = 0; 3322 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 3323 i != e; ++i, ++idx) { 3324 unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx); 3325 3326 // If we found a field after the region we care about, then we're done. 3327 if (FieldOffset >= EndBit) break; 3328 3329 unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0; 3330 if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset, 3331 Context)) 3332 return false; 3333 } 3334 3335 // If nothing in this record overlapped the area of interest, then we're 3336 // clean. 3337 return true; 3338 } 3339 3340 return false; 3341 } 3342 3343 /// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a 3344 /// float member at the specified offset. For example, {int,{float}} has a 3345 /// float at offset 4. It is conservatively correct for this routine to return 3346 /// false. 3347 static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset, 3348 const llvm::DataLayout &TD) { 3349 // Base case if we find a float. 3350 if (IROffset == 0 && IRType->isFloatTy()) 3351 return true; 3352 3353 // If this is a struct, recurse into the field at the specified offset. 3354 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) { 3355 const llvm::StructLayout *SL = TD.getStructLayout(STy); 3356 unsigned Elt = SL->getElementContainingOffset(IROffset); 3357 IROffset -= SL->getElementOffset(Elt); 3358 return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD); 3359 } 3360 3361 // If this is an array, recurse into the field at the specified offset. 3362 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) { 3363 llvm::Type *EltTy = ATy->getElementType(); 3364 unsigned EltSize = TD.getTypeAllocSize(EltTy); 3365 IROffset -= IROffset/EltSize*EltSize; 3366 return ContainsFloatAtOffset(EltTy, IROffset, TD); 3367 } 3368 3369 return false; 3370 } 3371 3372 3373 /// GetSSETypeAtOffset - Return a type that will be passed by the backend in the 3374 /// low 8 bytes of an XMM register, corresponding to the SSE class. 3375 llvm::Type *X86_64ABIInfo:: 3376 GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset, 3377 QualType SourceTy, unsigned SourceOffset) const { 3378 // The only three choices we have are either double, <2 x float>, or float. We 3379 // pass as float if the last 4 bytes is just padding. This happens for 3380 // structs that contain 3 floats. 3381 if (BitsContainNoUserData(SourceTy, SourceOffset*8+32, 3382 SourceOffset*8+64, getContext())) 3383 return llvm::Type::getFloatTy(getVMContext()); 3384 3385 // We want to pass as <2 x float> if the LLVM IR type contains a float at 3386 // offset+0 and offset+4. Walk the LLVM IR type to find out if this is the 3387 // case. 3388 if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) && 3389 ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout())) 3390 return llvm::FixedVectorType::get(llvm::Type::getFloatTy(getVMContext()), 3391 2); 3392 3393 return llvm::Type::getDoubleTy(getVMContext()); 3394 } 3395 3396 3397 /// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in 3398 /// an 8-byte GPR. This means that we either have a scalar or we are talking 3399 /// about the high or low part of an up-to-16-byte struct. This routine picks 3400 /// the best LLVM IR type to represent this, which may be i64 or may be anything 3401 /// else that the backend will pass in a GPR that works better (e.g. i8, %foo*, 3402 /// etc). 3403 /// 3404 /// PrefType is an LLVM IR type that corresponds to (part of) the IR type for 3405 /// the source type. IROffset is an offset in bytes into the LLVM IR type that 3406 /// the 8-byte value references. PrefType may be null. 3407 /// 3408 /// SourceTy is the source-level type for the entire argument. SourceOffset is 3409 /// an offset into this that we're processing (which is always either 0 or 8). 3410 /// 3411 llvm::Type *X86_64ABIInfo:: 3412 GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset, 3413 QualType SourceTy, unsigned SourceOffset) const { 3414 // If we're dealing with an un-offset LLVM IR type, then it means that we're 3415 // returning an 8-byte unit starting with it. See if we can safely use it. 3416 if (IROffset == 0) { 3417 // Pointers and int64's always fill the 8-byte unit. 3418 if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) || 3419 IRType->isIntegerTy(64)) 3420 return IRType; 3421 3422 // If we have a 1/2/4-byte integer, we can use it only if the rest of the 3423 // goodness in the source type is just tail padding. This is allowed to 3424 // kick in for struct {double,int} on the int, but not on 3425 // struct{double,int,int} because we wouldn't return the second int. We 3426 // have to do this analysis on the source type because we can't depend on 3427 // unions being lowered a specific way etc. 3428 if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) || 3429 IRType->isIntegerTy(32) || 3430 (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) { 3431 unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 : 3432 cast<llvm::IntegerType>(IRType)->getBitWidth(); 3433 3434 if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth, 3435 SourceOffset*8+64, getContext())) 3436 return IRType; 3437 } 3438 } 3439 3440 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) { 3441 // If this is a struct, recurse into the field at the specified offset. 3442 const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy); 3443 if (IROffset < SL->getSizeInBytes()) { 3444 unsigned FieldIdx = SL->getElementContainingOffset(IROffset); 3445 IROffset -= SL->getElementOffset(FieldIdx); 3446 3447 return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset, 3448 SourceTy, SourceOffset); 3449 } 3450 } 3451 3452 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) { 3453 llvm::Type *EltTy = ATy->getElementType(); 3454 unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy); 3455 unsigned EltOffset = IROffset/EltSize*EltSize; 3456 return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy, 3457 SourceOffset); 3458 } 3459 3460 // Okay, we don't have any better idea of what to pass, so we pass this in an 3461 // integer register that isn't too big to fit the rest of the struct. 3462 unsigned TySizeInBytes = 3463 (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity(); 3464 3465 assert(TySizeInBytes != SourceOffset && "Empty field?"); 3466 3467 // It is always safe to classify this as an integer type up to i64 that 3468 // isn't larger than the structure. 3469 return llvm::IntegerType::get(getVMContext(), 3470 std::min(TySizeInBytes-SourceOffset, 8U)*8); 3471 } 3472 3473 3474 /// GetX86_64ByValArgumentPair - Given a high and low type that can ideally 3475 /// be used as elements of a two register pair to pass or return, return a 3476 /// first class aggregate to represent them. For example, if the low part of 3477 /// a by-value argument should be passed as i32* and the high part as float, 3478 /// return {i32*, float}. 3479 static llvm::Type * 3480 GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi, 3481 const llvm::DataLayout &TD) { 3482 // In order to correctly satisfy the ABI, we need to the high part to start 3483 // at offset 8. If the high and low parts we inferred are both 4-byte types 3484 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have 3485 // the second element at offset 8. Check for this: 3486 unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo); 3487 unsigned HiAlign = TD.getABITypeAlignment(Hi); 3488 unsigned HiStart = llvm::alignTo(LoSize, HiAlign); 3489 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!"); 3490 3491 // To handle this, we have to increase the size of the low part so that the 3492 // second element will start at an 8 byte offset. We can't increase the size 3493 // of the second element because it might make us access off the end of the 3494 // struct. 3495 if (HiStart != 8) { 3496 // There are usually two sorts of types the ABI generation code can produce 3497 // for the low part of a pair that aren't 8 bytes in size: float or 3498 // i8/i16/i32. This can also include pointers when they are 32-bit (X32 and 3499 // NaCl). 3500 // Promote these to a larger type. 3501 if (Lo->isFloatTy()) 3502 Lo = llvm::Type::getDoubleTy(Lo->getContext()); 3503 else { 3504 assert((Lo->isIntegerTy() || Lo->isPointerTy()) 3505 && "Invalid/unknown lo type"); 3506 Lo = llvm::Type::getInt64Ty(Lo->getContext()); 3507 } 3508 } 3509 3510 llvm::StructType *Result = llvm::StructType::get(Lo, Hi); 3511 3512 // Verify that the second element is at an 8-byte offset. 3513 assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 && 3514 "Invalid x86-64 argument pair!"); 3515 return Result; 3516 } 3517 3518 ABIArgInfo X86_64ABIInfo:: 3519 classifyReturnType(QualType RetTy) const { 3520 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the 3521 // classification algorithm. 3522 X86_64ABIInfo::Class Lo, Hi; 3523 classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true); 3524 3525 // Check some invariants. 3526 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification."); 3527 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification."); 3528 3529 llvm::Type *ResType = nullptr; 3530 switch (Lo) { 3531 case NoClass: 3532 if (Hi == NoClass) 3533 return ABIArgInfo::getIgnore(); 3534 // If the low part is just padding, it takes no register, leave ResType 3535 // null. 3536 assert((Hi == SSE || Hi == Integer || Hi == X87Up) && 3537 "Unknown missing lo part"); 3538 break; 3539 3540 case SSEUp: 3541 case X87Up: 3542 llvm_unreachable("Invalid classification for lo word."); 3543 3544 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via 3545 // hidden argument. 3546 case Memory: 3547 return getIndirectReturnResult(RetTy); 3548 3549 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next 3550 // available register of the sequence %rax, %rdx is used. 3551 case Integer: 3552 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0); 3553 3554 // If we have a sign or zero extended integer, make sure to return Extend 3555 // so that the parameter gets the right LLVM IR attributes. 3556 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) { 3557 // Treat an enum type as its underlying type. 3558 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 3559 RetTy = EnumTy->getDecl()->getIntegerType(); 3560 3561 if (RetTy->isIntegralOrEnumerationType() && 3562 isPromotableIntegerTypeForABI(RetTy)) 3563 return ABIArgInfo::getExtend(RetTy); 3564 } 3565 break; 3566 3567 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next 3568 // available SSE register of the sequence %xmm0, %xmm1 is used. 3569 case SSE: 3570 ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0); 3571 break; 3572 3573 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is 3574 // returned on the X87 stack in %st0 as 80-bit x87 number. 3575 case X87: 3576 ResType = llvm::Type::getX86_FP80Ty(getVMContext()); 3577 break; 3578 3579 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real 3580 // part of the value is returned in %st0 and the imaginary part in 3581 // %st1. 3582 case ComplexX87: 3583 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification."); 3584 ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()), 3585 llvm::Type::getX86_FP80Ty(getVMContext())); 3586 break; 3587 } 3588 3589 llvm::Type *HighPart = nullptr; 3590 switch (Hi) { 3591 // Memory was handled previously and X87 should 3592 // never occur as a hi class. 3593 case Memory: 3594 case X87: 3595 llvm_unreachable("Invalid classification for hi word."); 3596 3597 case ComplexX87: // Previously handled. 3598 case NoClass: 3599 break; 3600 3601 case Integer: 3602 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8); 3603 if (Lo == NoClass) // Return HighPart at offset 8 in memory. 3604 return ABIArgInfo::getDirect(HighPart, 8); 3605 break; 3606 case SSE: 3607 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8); 3608 if (Lo == NoClass) // Return HighPart at offset 8 in memory. 3609 return ABIArgInfo::getDirect(HighPart, 8); 3610 break; 3611 3612 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte 3613 // is passed in the next available eightbyte chunk if the last used 3614 // vector register. 3615 // 3616 // SSEUP should always be preceded by SSE, just widen. 3617 case SSEUp: 3618 assert(Lo == SSE && "Unexpected SSEUp classification."); 3619 ResType = GetByteVectorType(RetTy); 3620 break; 3621 3622 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is 3623 // returned together with the previous X87 value in %st0. 3624 case X87Up: 3625 // If X87Up is preceded by X87, we don't need to do 3626 // anything. However, in some cases with unions it may not be 3627 // preceded by X87. In such situations we follow gcc and pass the 3628 // extra bits in an SSE reg. 3629 if (Lo != X87) { 3630 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8); 3631 if (Lo == NoClass) // Return HighPart at offset 8 in memory. 3632 return ABIArgInfo::getDirect(HighPart, 8); 3633 } 3634 break; 3635 } 3636 3637 // If a high part was specified, merge it together with the low part. It is 3638 // known to pass in the high eightbyte of the result. We do this by forming a 3639 // first class struct aggregate with the high and low part: {low, high} 3640 if (HighPart) 3641 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout()); 3642 3643 return ABIArgInfo::getDirect(ResType); 3644 } 3645 3646 ABIArgInfo X86_64ABIInfo::classifyArgumentType( 3647 QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE, 3648 bool isNamedArg) 3649 const 3650 { 3651 Ty = useFirstFieldIfTransparentUnion(Ty); 3652 3653 X86_64ABIInfo::Class Lo, Hi; 3654 classify(Ty, 0, Lo, Hi, isNamedArg); 3655 3656 // Check some invariants. 3657 // FIXME: Enforce these by construction. 3658 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification."); 3659 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification."); 3660 3661 neededInt = 0; 3662 neededSSE = 0; 3663 llvm::Type *ResType = nullptr; 3664 switch (Lo) { 3665 case NoClass: 3666 if (Hi == NoClass) 3667 return ABIArgInfo::getIgnore(); 3668 // If the low part is just padding, it takes no register, leave ResType 3669 // null. 3670 assert((Hi == SSE || Hi == Integer || Hi == X87Up) && 3671 "Unknown missing lo part"); 3672 break; 3673 3674 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument 3675 // on the stack. 3676 case Memory: 3677 3678 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or 3679 // COMPLEX_X87, it is passed in memory. 3680 case X87: 3681 case ComplexX87: 3682 if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect) 3683 ++neededInt; 3684 return getIndirectResult(Ty, freeIntRegs); 3685 3686 case SSEUp: 3687 case X87Up: 3688 llvm_unreachable("Invalid classification for lo word."); 3689 3690 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next 3691 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8 3692 // and %r9 is used. 3693 case Integer: 3694 ++neededInt; 3695 3696 // Pick an 8-byte type based on the preferred type. 3697 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0); 3698 3699 // If we have a sign or zero extended integer, make sure to return Extend 3700 // so that the parameter gets the right LLVM IR attributes. 3701 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) { 3702 // Treat an enum type as its underlying type. 3703 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 3704 Ty = EnumTy->getDecl()->getIntegerType(); 3705 3706 if (Ty->isIntegralOrEnumerationType() && 3707 isPromotableIntegerTypeForABI(Ty)) 3708 return ABIArgInfo::getExtend(Ty); 3709 } 3710 3711 break; 3712 3713 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next 3714 // available SSE register is used, the registers are taken in the 3715 // order from %xmm0 to %xmm7. 3716 case SSE: { 3717 llvm::Type *IRType = CGT.ConvertType(Ty); 3718 ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0); 3719 ++neededSSE; 3720 break; 3721 } 3722 } 3723 3724 llvm::Type *HighPart = nullptr; 3725 switch (Hi) { 3726 // Memory was handled previously, ComplexX87 and X87 should 3727 // never occur as hi classes, and X87Up must be preceded by X87, 3728 // which is passed in memory. 3729 case Memory: 3730 case X87: 3731 case ComplexX87: 3732 llvm_unreachable("Invalid classification for hi word."); 3733 3734 case NoClass: break; 3735 3736 case Integer: 3737 ++neededInt; 3738 // Pick an 8-byte type based on the preferred type. 3739 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8); 3740 3741 if (Lo == NoClass) // Pass HighPart at offset 8 in memory. 3742 return ABIArgInfo::getDirect(HighPart, 8); 3743 break; 3744 3745 // X87Up generally doesn't occur here (long double is passed in 3746 // memory), except in situations involving unions. 3747 case X87Up: 3748 case SSE: 3749 HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8); 3750 3751 if (Lo == NoClass) // Pass HighPart at offset 8 in memory. 3752 return ABIArgInfo::getDirect(HighPart, 8); 3753 3754 ++neededSSE; 3755 break; 3756 3757 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the 3758 // eightbyte is passed in the upper half of the last used SSE 3759 // register. This only happens when 128-bit vectors are passed. 3760 case SSEUp: 3761 assert(Lo == SSE && "Unexpected SSEUp classification"); 3762 ResType = GetByteVectorType(Ty); 3763 break; 3764 } 3765 3766 // If a high part was specified, merge it together with the low part. It is 3767 // known to pass in the high eightbyte of the result. We do this by forming a 3768 // first class struct aggregate with the high and low part: {low, high} 3769 if (HighPart) 3770 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout()); 3771 3772 return ABIArgInfo::getDirect(ResType); 3773 } 3774 3775 ABIArgInfo 3776 X86_64ABIInfo::classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt, 3777 unsigned &NeededSSE) const { 3778 auto RT = Ty->getAs<RecordType>(); 3779 assert(RT && "classifyRegCallStructType only valid with struct types"); 3780 3781 if (RT->getDecl()->hasFlexibleArrayMember()) 3782 return getIndirectReturnResult(Ty); 3783 3784 // Sum up bases 3785 if (auto CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl())) { 3786 if (CXXRD->isDynamicClass()) { 3787 NeededInt = NeededSSE = 0; 3788 return getIndirectReturnResult(Ty); 3789 } 3790 3791 for (const auto &I : CXXRD->bases()) 3792 if (classifyRegCallStructTypeImpl(I.getType(), NeededInt, NeededSSE) 3793 .isIndirect()) { 3794 NeededInt = NeededSSE = 0; 3795 return getIndirectReturnResult(Ty); 3796 } 3797 } 3798 3799 // Sum up members 3800 for (const auto *FD : RT->getDecl()->fields()) { 3801 if (FD->getType()->isRecordType() && !FD->getType()->isUnionType()) { 3802 if (classifyRegCallStructTypeImpl(FD->getType(), NeededInt, NeededSSE) 3803 .isIndirect()) { 3804 NeededInt = NeededSSE = 0; 3805 return getIndirectReturnResult(Ty); 3806 } 3807 } else { 3808 unsigned LocalNeededInt, LocalNeededSSE; 3809 if (classifyArgumentType(FD->getType(), UINT_MAX, LocalNeededInt, 3810 LocalNeededSSE, true) 3811 .isIndirect()) { 3812 NeededInt = NeededSSE = 0; 3813 return getIndirectReturnResult(Ty); 3814 } 3815 NeededInt += LocalNeededInt; 3816 NeededSSE += LocalNeededSSE; 3817 } 3818 } 3819 3820 return ABIArgInfo::getDirect(); 3821 } 3822 3823 ABIArgInfo X86_64ABIInfo::classifyRegCallStructType(QualType Ty, 3824 unsigned &NeededInt, 3825 unsigned &NeededSSE) const { 3826 3827 NeededInt = 0; 3828 NeededSSE = 0; 3829 3830 return classifyRegCallStructTypeImpl(Ty, NeededInt, NeededSSE); 3831 } 3832 3833 void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const { 3834 3835 const unsigned CallingConv = FI.getCallingConvention(); 3836 // It is possible to force Win64 calling convention on any x86_64 target by 3837 // using __attribute__((ms_abi)). In such case to correctly emit Win64 3838 // compatible code delegate this call to WinX86_64ABIInfo::computeInfo. 3839 if (CallingConv == llvm::CallingConv::Win64) { 3840 WinX86_64ABIInfo Win64ABIInfo(CGT, AVXLevel); 3841 Win64ABIInfo.computeInfo(FI); 3842 return; 3843 } 3844 3845 bool IsRegCall = CallingConv == llvm::CallingConv::X86_RegCall; 3846 3847 // Keep track of the number of assigned registers. 3848 unsigned FreeIntRegs = IsRegCall ? 11 : 6; 3849 unsigned FreeSSERegs = IsRegCall ? 16 : 8; 3850 unsigned NeededInt, NeededSSE; 3851 3852 if (!::classifyReturnType(getCXXABI(), FI, *this)) { 3853 if (IsRegCall && FI.getReturnType()->getTypePtr()->isRecordType() && 3854 !FI.getReturnType()->getTypePtr()->isUnionType()) { 3855 FI.getReturnInfo() = 3856 classifyRegCallStructType(FI.getReturnType(), NeededInt, NeededSSE); 3857 if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) { 3858 FreeIntRegs -= NeededInt; 3859 FreeSSERegs -= NeededSSE; 3860 } else { 3861 FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType()); 3862 } 3863 } else if (IsRegCall && FI.getReturnType()->getAs<ComplexType>() && 3864 getContext().getCanonicalType(FI.getReturnType() 3865 ->getAs<ComplexType>() 3866 ->getElementType()) == 3867 getContext().LongDoubleTy) 3868 // Complex Long Double Type is passed in Memory when Regcall 3869 // calling convention is used. 3870 FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType()); 3871 else 3872 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 3873 } 3874 3875 // If the return value is indirect, then the hidden argument is consuming one 3876 // integer register. 3877 if (FI.getReturnInfo().isIndirect()) 3878 --FreeIntRegs; 3879 3880 // The chain argument effectively gives us another free register. 3881 if (FI.isChainCall()) 3882 ++FreeIntRegs; 3883 3884 unsigned NumRequiredArgs = FI.getNumRequiredArgs(); 3885 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers 3886 // get assigned (in left-to-right order) for passing as follows... 3887 unsigned ArgNo = 0; 3888 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end(); 3889 it != ie; ++it, ++ArgNo) { 3890 bool IsNamedArg = ArgNo < NumRequiredArgs; 3891 3892 if (IsRegCall && it->type->isStructureOrClassType()) 3893 it->info = classifyRegCallStructType(it->type, NeededInt, NeededSSE); 3894 else 3895 it->info = classifyArgumentType(it->type, FreeIntRegs, NeededInt, 3896 NeededSSE, IsNamedArg); 3897 3898 // AMD64-ABI 3.2.3p3: If there are no registers available for any 3899 // eightbyte of an argument, the whole argument is passed on the 3900 // stack. If registers have already been assigned for some 3901 // eightbytes of such an argument, the assignments get reverted. 3902 if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) { 3903 FreeIntRegs -= NeededInt; 3904 FreeSSERegs -= NeededSSE; 3905 } else { 3906 it->info = getIndirectResult(it->type, FreeIntRegs); 3907 } 3908 } 3909 } 3910 3911 static Address EmitX86_64VAArgFromMemory(CodeGenFunction &CGF, 3912 Address VAListAddr, QualType Ty) { 3913 Address overflow_arg_area_p = 3914 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_p"); 3915 llvm::Value *overflow_arg_area = 3916 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area"); 3917 3918 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16 3919 // byte boundary if alignment needed by type exceeds 8 byte boundary. 3920 // It isn't stated explicitly in the standard, but in practice we use 3921 // alignment greater than 16 where necessary. 3922 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty); 3923 if (Align > CharUnits::fromQuantity(8)) { 3924 overflow_arg_area = emitRoundPointerUpToAlignment(CGF, overflow_arg_area, 3925 Align); 3926 } 3927 3928 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area. 3929 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty); 3930 llvm::Value *Res = 3931 CGF.Builder.CreateBitCast(overflow_arg_area, 3932 llvm::PointerType::getUnqual(LTy)); 3933 3934 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to: 3935 // l->overflow_arg_area + sizeof(type). 3936 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to 3937 // an 8 byte boundary. 3938 3939 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8; 3940 llvm::Value *Offset = 3941 llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7); 3942 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset, 3943 "overflow_arg_area.next"); 3944 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p); 3945 3946 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type. 3947 return Address(Res, Align); 3948 } 3949 3950 Address X86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 3951 QualType Ty) const { 3952 // Assume that va_list type is correct; should be pointer to LLVM type: 3953 // struct { 3954 // i32 gp_offset; 3955 // i32 fp_offset; 3956 // i8* overflow_arg_area; 3957 // i8* reg_save_area; 3958 // }; 3959 unsigned neededInt, neededSSE; 3960 3961 Ty = getContext().getCanonicalType(Ty); 3962 ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE, 3963 /*isNamedArg*/false); 3964 3965 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed 3966 // in the registers. If not go to step 7. 3967 if (!neededInt && !neededSSE) 3968 return EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty); 3969 3970 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of 3971 // general purpose registers needed to pass type and num_fp to hold 3972 // the number of floating point registers needed. 3973 3974 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into 3975 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or 3976 // l->fp_offset > 304 - num_fp * 16 go to step 7. 3977 // 3978 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of 3979 // register save space). 3980 3981 llvm::Value *InRegs = nullptr; 3982 Address gp_offset_p = Address::invalid(), fp_offset_p = Address::invalid(); 3983 llvm::Value *gp_offset = nullptr, *fp_offset = nullptr; 3984 if (neededInt) { 3985 gp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "gp_offset_p"); 3986 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset"); 3987 InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8); 3988 InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp"); 3989 } 3990 3991 if (neededSSE) { 3992 fp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 1, "fp_offset_p"); 3993 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset"); 3994 llvm::Value *FitsInFP = 3995 llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16); 3996 FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp"); 3997 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP; 3998 } 3999 4000 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg"); 4001 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem"); 4002 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end"); 4003 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock); 4004 4005 // Emit code to load the value if it was passed in registers. 4006 4007 CGF.EmitBlock(InRegBlock); 4008 4009 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with 4010 // an offset of l->gp_offset and/or l->fp_offset. This may require 4011 // copying to a temporary location in case the parameter is passed 4012 // in different register classes or requires an alignment greater 4013 // than 8 for general purpose registers and 16 for XMM registers. 4014 // 4015 // FIXME: This really results in shameful code when we end up needing to 4016 // collect arguments from different places; often what should result in a 4017 // simple assembling of a structure from scattered addresses has many more 4018 // loads than necessary. Can we clean this up? 4019 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty); 4020 llvm::Value *RegSaveArea = CGF.Builder.CreateLoad( 4021 CGF.Builder.CreateStructGEP(VAListAddr, 3), "reg_save_area"); 4022 4023 Address RegAddr = Address::invalid(); 4024 if (neededInt && neededSSE) { 4025 // FIXME: Cleanup. 4026 assert(AI.isDirect() && "Unexpected ABI info for mixed regs"); 4027 llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType()); 4028 Address Tmp = CGF.CreateMemTemp(Ty); 4029 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST); 4030 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs"); 4031 llvm::Type *TyLo = ST->getElementType(0); 4032 llvm::Type *TyHi = ST->getElementType(1); 4033 assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) && 4034 "Unexpected ABI info for mixed regs"); 4035 llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo); 4036 llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi); 4037 llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegSaveArea, gp_offset); 4038 llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegSaveArea, fp_offset); 4039 llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr; 4040 llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr; 4041 4042 // Copy the first element. 4043 // FIXME: Our choice of alignment here and below is probably pessimistic. 4044 llvm::Value *V = CGF.Builder.CreateAlignedLoad( 4045 TyLo, CGF.Builder.CreateBitCast(RegLoAddr, PTyLo), 4046 CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyLo))); 4047 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0)); 4048 4049 // Copy the second element. 4050 V = CGF.Builder.CreateAlignedLoad( 4051 TyHi, CGF.Builder.CreateBitCast(RegHiAddr, PTyHi), 4052 CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyHi))); 4053 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1)); 4054 4055 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy); 4056 } else if (neededInt) { 4057 RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, gp_offset), 4058 CharUnits::fromQuantity(8)); 4059 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy); 4060 4061 // Copy to a temporary if necessary to ensure the appropriate alignment. 4062 std::pair<CharUnits, CharUnits> SizeAlign = 4063 getContext().getTypeInfoInChars(Ty); 4064 uint64_t TySize = SizeAlign.first.getQuantity(); 4065 CharUnits TyAlign = SizeAlign.second; 4066 4067 // Copy into a temporary if the type is more aligned than the 4068 // register save area. 4069 if (TyAlign.getQuantity() > 8) { 4070 Address Tmp = CGF.CreateMemTemp(Ty); 4071 CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, false); 4072 RegAddr = Tmp; 4073 } 4074 4075 } else if (neededSSE == 1) { 4076 RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset), 4077 CharUnits::fromQuantity(16)); 4078 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy); 4079 } else { 4080 assert(neededSSE == 2 && "Invalid number of needed registers!"); 4081 // SSE registers are spaced 16 bytes apart in the register save 4082 // area, we need to collect the two eightbytes together. 4083 // The ABI isn't explicit about this, but it seems reasonable 4084 // to assume that the slots are 16-byte aligned, since the stack is 4085 // naturally 16-byte aligned and the prologue is expected to store 4086 // all the SSE registers to the RSA. 4087 Address RegAddrLo = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset), 4088 CharUnits::fromQuantity(16)); 4089 Address RegAddrHi = 4090 CGF.Builder.CreateConstInBoundsByteGEP(RegAddrLo, 4091 CharUnits::fromQuantity(16)); 4092 llvm::Type *ST = AI.canHaveCoerceToType() 4093 ? AI.getCoerceToType() 4094 : llvm::StructType::get(CGF.DoubleTy, CGF.DoubleTy); 4095 llvm::Value *V; 4096 Address Tmp = CGF.CreateMemTemp(Ty); 4097 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST); 4098 V = CGF.Builder.CreateLoad(CGF.Builder.CreateElementBitCast( 4099 RegAddrLo, ST->getStructElementType(0))); 4100 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0)); 4101 V = CGF.Builder.CreateLoad(CGF.Builder.CreateElementBitCast( 4102 RegAddrHi, ST->getStructElementType(1))); 4103 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1)); 4104 4105 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy); 4106 } 4107 4108 // AMD64-ABI 3.5.7p5: Step 5. Set: 4109 // l->gp_offset = l->gp_offset + num_gp * 8 4110 // l->fp_offset = l->fp_offset + num_fp * 16. 4111 if (neededInt) { 4112 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8); 4113 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset), 4114 gp_offset_p); 4115 } 4116 if (neededSSE) { 4117 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16); 4118 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset), 4119 fp_offset_p); 4120 } 4121 CGF.EmitBranch(ContBlock); 4122 4123 // Emit code to load the value if it was passed in memory. 4124 4125 CGF.EmitBlock(InMemBlock); 4126 Address MemAddr = EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty); 4127 4128 // Return the appropriate result. 4129 4130 CGF.EmitBlock(ContBlock); 4131 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, MemAddr, InMemBlock, 4132 "vaarg.addr"); 4133 return ResAddr; 4134 } 4135 4136 Address X86_64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr, 4137 QualType Ty) const { 4138 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false, 4139 CGF.getContext().getTypeInfoInChars(Ty), 4140 CharUnits::fromQuantity(8), 4141 /*allowHigherAlign*/ false); 4142 } 4143 4144 ABIArgInfo 4145 WinX86_64ABIInfo::reclassifyHvaArgType(QualType Ty, unsigned &FreeSSERegs, 4146 const ABIArgInfo ¤t) const { 4147 // Assumes vectorCall calling convention. 4148 const Type *Base = nullptr; 4149 uint64_t NumElts = 0; 4150 4151 if (!Ty->isBuiltinType() && !Ty->isVectorType() && 4152 isHomogeneousAggregate(Ty, Base, NumElts) && FreeSSERegs >= NumElts) { 4153 FreeSSERegs -= NumElts; 4154 return getDirectX86Hva(); 4155 } 4156 return current; 4157 } 4158 4159 ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, unsigned &FreeSSERegs, 4160 bool IsReturnType, bool IsVectorCall, 4161 bool IsRegCall) const { 4162 4163 if (Ty->isVoidType()) 4164 return ABIArgInfo::getIgnore(); 4165 4166 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 4167 Ty = EnumTy->getDecl()->getIntegerType(); 4168 4169 TypeInfo Info = getContext().getTypeInfo(Ty); 4170 uint64_t Width = Info.Width; 4171 CharUnits Align = getContext().toCharUnitsFromBits(Info.Align); 4172 4173 const RecordType *RT = Ty->getAs<RecordType>(); 4174 if (RT) { 4175 if (!IsReturnType) { 4176 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI())) 4177 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 4178 } 4179 4180 if (RT->getDecl()->hasFlexibleArrayMember()) 4181 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 4182 4183 } 4184 4185 const Type *Base = nullptr; 4186 uint64_t NumElts = 0; 4187 // vectorcall adds the concept of a homogenous vector aggregate, similar to 4188 // other targets. 4189 if ((IsVectorCall || IsRegCall) && 4190 isHomogeneousAggregate(Ty, Base, NumElts)) { 4191 if (IsRegCall) { 4192 if (FreeSSERegs >= NumElts) { 4193 FreeSSERegs -= NumElts; 4194 if (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType()) 4195 return ABIArgInfo::getDirect(); 4196 return ABIArgInfo::getExpand(); 4197 } 4198 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false); 4199 } else if (IsVectorCall) { 4200 if (FreeSSERegs >= NumElts && 4201 (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())) { 4202 FreeSSERegs -= NumElts; 4203 return ABIArgInfo::getDirect(); 4204 } else if (IsReturnType) { 4205 return ABIArgInfo::getExpand(); 4206 } else if (!Ty->isBuiltinType() && !Ty->isVectorType()) { 4207 // HVAs are delayed and reclassified in the 2nd step. 4208 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false); 4209 } 4210 } 4211 } 4212 4213 if (Ty->isMemberPointerType()) { 4214 // If the member pointer is represented by an LLVM int or ptr, pass it 4215 // directly. 4216 llvm::Type *LLTy = CGT.ConvertType(Ty); 4217 if (LLTy->isPointerTy() || LLTy->isIntegerTy()) 4218 return ABIArgInfo::getDirect(); 4219 } 4220 4221 if (RT || Ty->isAnyComplexType() || Ty->isMemberPointerType()) { 4222 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is 4223 // not 1, 2, 4, or 8 bytes, must be passed by reference." 4224 if (Width > 64 || !llvm::isPowerOf2_64(Width)) 4225 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 4226 4227 // Otherwise, coerce it to a small integer. 4228 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Width)); 4229 } 4230 4231 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) { 4232 switch (BT->getKind()) { 4233 case BuiltinType::Bool: 4234 // Bool type is always extended to the ABI, other builtin types are not 4235 // extended. 4236 return ABIArgInfo::getExtend(Ty); 4237 4238 case BuiltinType::LongDouble: 4239 // Mingw64 GCC uses the old 80 bit extended precision floating point 4240 // unit. It passes them indirectly through memory. 4241 if (IsMingw64) { 4242 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat(); 4243 if (LDF == &llvm::APFloat::x87DoubleExtended()) 4244 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false); 4245 } 4246 break; 4247 4248 case BuiltinType::Int128: 4249 case BuiltinType::UInt128: 4250 // If it's a parameter type, the normal ABI rule is that arguments larger 4251 // than 8 bytes are passed indirectly. GCC follows it. We follow it too, 4252 // even though it isn't particularly efficient. 4253 if (!IsReturnType) 4254 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false); 4255 4256 // Mingw64 GCC returns i128 in XMM0. Coerce to v2i64 to handle that. 4257 // Clang matches them for compatibility. 4258 return ABIArgInfo::getDirect(llvm::FixedVectorType::get( 4259 llvm::Type::getInt64Ty(getVMContext()), 2)); 4260 4261 default: 4262 break; 4263 } 4264 } 4265 4266 if (Ty->isExtIntType()) { 4267 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is 4268 // not 1, 2, 4, or 8 bytes, must be passed by reference." 4269 // However, non-power-of-two _ExtInts will be passed as 1,2,4 or 8 bytes 4270 // anyway as long is it fits in them, so we don't have to check the power of 4271 // 2. 4272 if (Width <= 64) 4273 return ABIArgInfo::getDirect(); 4274 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false); 4275 } 4276 4277 return ABIArgInfo::getDirect(); 4278 } 4279 4280 void WinX86_64ABIInfo::computeVectorCallArgs(CGFunctionInfo &FI, 4281 unsigned FreeSSERegs, 4282 bool IsVectorCall, 4283 bool IsRegCall) const { 4284 unsigned Count = 0; 4285 for (auto &I : FI.arguments()) { 4286 // Vectorcall in x64 only permits the first 6 arguments to be passed 4287 // as XMM/YMM registers. 4288 if (Count < VectorcallMaxParamNumAsReg) 4289 I.info = classify(I.type, FreeSSERegs, false, IsVectorCall, IsRegCall); 4290 else { 4291 // Since these cannot be passed in registers, pretend no registers 4292 // are left. 4293 unsigned ZeroSSERegsAvail = 0; 4294 I.info = classify(I.type, /*FreeSSERegs=*/ZeroSSERegsAvail, false, 4295 IsVectorCall, IsRegCall); 4296 } 4297 ++Count; 4298 } 4299 4300 for (auto &I : FI.arguments()) { 4301 I.info = reclassifyHvaArgType(I.type, FreeSSERegs, I.info); 4302 } 4303 } 4304 4305 void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const { 4306 const unsigned CC = FI.getCallingConvention(); 4307 bool IsVectorCall = CC == llvm::CallingConv::X86_VectorCall; 4308 bool IsRegCall = CC == llvm::CallingConv::X86_RegCall; 4309 4310 // If __attribute__((sysv_abi)) is in use, use the SysV argument 4311 // classification rules. 4312 if (CC == llvm::CallingConv::X86_64_SysV) { 4313 X86_64ABIInfo SysVABIInfo(CGT, AVXLevel); 4314 SysVABIInfo.computeInfo(FI); 4315 return; 4316 } 4317 4318 unsigned FreeSSERegs = 0; 4319 if (IsVectorCall) { 4320 // We can use up to 4 SSE return registers with vectorcall. 4321 FreeSSERegs = 4; 4322 } else if (IsRegCall) { 4323 // RegCall gives us 16 SSE registers. 4324 FreeSSERegs = 16; 4325 } 4326 4327 if (!getCXXABI().classifyReturnType(FI)) 4328 FI.getReturnInfo() = classify(FI.getReturnType(), FreeSSERegs, true, 4329 IsVectorCall, IsRegCall); 4330 4331 if (IsVectorCall) { 4332 // We can use up to 6 SSE register parameters with vectorcall. 4333 FreeSSERegs = 6; 4334 } else if (IsRegCall) { 4335 // RegCall gives us 16 SSE registers, we can reuse the return registers. 4336 FreeSSERegs = 16; 4337 } 4338 4339 if (IsVectorCall) { 4340 computeVectorCallArgs(FI, FreeSSERegs, IsVectorCall, IsRegCall); 4341 } else { 4342 for (auto &I : FI.arguments()) 4343 I.info = classify(I.type, FreeSSERegs, false, IsVectorCall, IsRegCall); 4344 } 4345 4346 } 4347 4348 Address WinX86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 4349 QualType Ty) const { 4350 4351 bool IsIndirect = false; 4352 4353 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is 4354 // not 1, 2, 4, or 8 bytes, must be passed by reference." 4355 if (isAggregateTypeForABI(Ty) || Ty->isMemberPointerType()) { 4356 uint64_t Width = getContext().getTypeSize(Ty); 4357 IsIndirect = Width > 64 || !llvm::isPowerOf2_64(Width); 4358 } 4359 4360 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, 4361 CGF.getContext().getTypeInfoInChars(Ty), 4362 CharUnits::fromQuantity(8), 4363 /*allowHigherAlign*/ false); 4364 } 4365 4366 static bool PPC_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 4367 llvm::Value *Address, bool Is64Bit, 4368 bool IsAIX) { 4369 // This is calculated from the LLVM and GCC tables and verified 4370 // against gcc output. AFAIK all PPC ABIs use the same encoding. 4371 4372 CodeGen::CGBuilderTy &Builder = CGF.Builder; 4373 4374 llvm::IntegerType *i8 = CGF.Int8Ty; 4375 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4); 4376 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8); 4377 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16); 4378 4379 // 0-31: r0-31, the 4-byte or 8-byte general-purpose registers 4380 AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 0, 31); 4381 4382 // 32-63: fp0-31, the 8-byte floating-point registers 4383 AssignToArrayRange(Builder, Address, Eight8, 32, 63); 4384 4385 // 64-67 are various 4-byte or 8-byte special-purpose registers: 4386 // 64: mq 4387 // 65: lr 4388 // 66: ctr 4389 // 67: ap 4390 AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 64, 67); 4391 4392 // 68-76 are various 4-byte special-purpose registers: 4393 // 68-75 cr0-7 4394 // 76: xer 4395 AssignToArrayRange(Builder, Address, Four8, 68, 76); 4396 4397 // 77-108: v0-31, the 16-byte vector registers 4398 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108); 4399 4400 // 109: vrsave 4401 // 110: vscr 4402 AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 109, 110); 4403 4404 // AIX does not utilize the rest of the registers. 4405 if (IsAIX) 4406 return false; 4407 4408 // 111: spe_acc 4409 // 112: spefscr 4410 // 113: sfp 4411 AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 111, 113); 4412 4413 if (!Is64Bit) 4414 return false; 4415 4416 // TODO: Need to verify if these registers are used on 64 bit AIX with Power8 4417 // or above CPU. 4418 // 64-bit only registers: 4419 // 114: tfhar 4420 // 115: tfiar 4421 // 116: texasr 4422 AssignToArrayRange(Builder, Address, Eight8, 114, 116); 4423 4424 return false; 4425 } 4426 4427 // AIX 4428 namespace { 4429 /// AIXABIInfo - The AIX XCOFF ABI information. 4430 class AIXABIInfo : public ABIInfo { 4431 const bool Is64Bit; 4432 const unsigned PtrByteSize; 4433 CharUnits getParamTypeAlignment(QualType Ty) const; 4434 4435 public: 4436 AIXABIInfo(CodeGen::CodeGenTypes &CGT, bool Is64Bit) 4437 : ABIInfo(CGT), Is64Bit(Is64Bit), PtrByteSize(Is64Bit ? 8 : 4) {} 4438 4439 bool isPromotableTypeForABI(QualType Ty) const; 4440 4441 ABIArgInfo classifyReturnType(QualType RetTy) const; 4442 ABIArgInfo classifyArgumentType(QualType Ty) const; 4443 4444 void computeInfo(CGFunctionInfo &FI) const override { 4445 if (!getCXXABI().classifyReturnType(FI)) 4446 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 4447 4448 for (auto &I : FI.arguments()) 4449 I.info = classifyArgumentType(I.type); 4450 } 4451 4452 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 4453 QualType Ty) const override; 4454 }; 4455 4456 class AIXTargetCodeGenInfo : public TargetCodeGenInfo { 4457 const bool Is64Bit; 4458 4459 public: 4460 AIXTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool Is64Bit) 4461 : TargetCodeGenInfo(std::make_unique<AIXABIInfo>(CGT, Is64Bit)), 4462 Is64Bit(Is64Bit) {} 4463 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 4464 return 1; // r1 is the dedicated stack pointer 4465 } 4466 4467 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 4468 llvm::Value *Address) const override; 4469 }; 4470 } // namespace 4471 4472 // Return true if the ABI requires Ty to be passed sign- or zero- 4473 // extended to 32/64 bits. 4474 bool AIXABIInfo::isPromotableTypeForABI(QualType Ty) const { 4475 // Treat an enum type as its underlying type. 4476 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 4477 Ty = EnumTy->getDecl()->getIntegerType(); 4478 4479 // Promotable integer types are required to be promoted by the ABI. 4480 if (Ty->isPromotableIntegerType()) 4481 return true; 4482 4483 if (!Is64Bit) 4484 return false; 4485 4486 // For 64 bit mode, in addition to the usual promotable integer types, we also 4487 // need to extend all 32-bit types, since the ABI requires promotion to 64 4488 // bits. 4489 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) 4490 switch (BT->getKind()) { 4491 case BuiltinType::Int: 4492 case BuiltinType::UInt: 4493 return true; 4494 default: 4495 break; 4496 } 4497 4498 return false; 4499 } 4500 4501 ABIArgInfo AIXABIInfo::classifyReturnType(QualType RetTy) const { 4502 if (RetTy->isAnyComplexType()) 4503 llvm::report_fatal_error("complex type is not supported on AIX yet"); 4504 4505 if (RetTy->isVectorType()) 4506 llvm::report_fatal_error("vector type is not supported on AIX yet"); 4507 4508 if (RetTy->isVoidType()) 4509 return ABIArgInfo::getIgnore(); 4510 4511 // TODO: Evaluate if AIX power alignment rule would have an impact on the 4512 // alignment here. 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 llvm::report_fatal_error("complex type is not supported on AIX yet"); 4525 4526 if (Ty->isVectorType()) 4527 llvm::report_fatal_error("vector type is not supported on AIX yet"); 4528 4529 // TODO: Evaluate if AIX power alignment rule would have an impact on the 4530 // alignment here. 4531 if (isAggregateTypeForABI(Ty)) { 4532 // Records with non-trivial destructors/copy-constructors should not be 4533 // passed by value. 4534 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 4535 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 4536 4537 CharUnits CCAlign = getParamTypeAlignment(Ty); 4538 CharUnits TyAlign = getContext().getTypeAlignInChars(Ty); 4539 4540 return ABIArgInfo::getIndirect(CCAlign, /*ByVal*/ true, 4541 /*Realign*/ TyAlign > CCAlign); 4542 } 4543 4544 return (isPromotableTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty) 4545 : ABIArgInfo::getDirect()); 4546 } 4547 4548 CharUnits AIXABIInfo::getParamTypeAlignment(QualType Ty) const { 4549 if (Ty->isAnyComplexType()) 4550 llvm::report_fatal_error("complex type is not supported on AIX yet"); 4551 4552 if (Ty->isVectorType()) 4553 llvm::report_fatal_error("vector type is not supported on AIX yet"); 4554 4555 // If the structure contains a vector type, the alignment is 16. 4556 if (isRecordWithSIMDVectorType(getContext(), Ty)) 4557 return CharUnits::fromQuantity(16); 4558 4559 return CharUnits::fromQuantity(PtrByteSize); 4560 } 4561 4562 Address AIXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 4563 QualType Ty) const { 4564 if (Ty->isAnyComplexType()) 4565 llvm::report_fatal_error("complex type is not supported on AIX yet"); 4566 4567 if (Ty->isVectorType()) 4568 llvm::report_fatal_error("vector type is not supported on AIX yet"); 4569 4570 auto TypeInfo = getContext().getTypeInfoInChars(Ty); 4571 TypeInfo.second = getParamTypeAlignment(Ty); 4572 4573 CharUnits SlotSize = CharUnits::fromQuantity(PtrByteSize); 4574 4575 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false, TypeInfo, 4576 SlotSize, /*AllowHigher*/ true); 4577 } 4578 4579 bool AIXTargetCodeGenInfo::initDwarfEHRegSizeTable( 4580 CodeGen::CodeGenFunction &CGF, llvm::Value *Address) const { 4581 return PPC_initDwarfEHRegSizeTable(CGF, Address, Is64Bit, /*IsAIX*/ true); 4582 } 4583 4584 // PowerPC-32 4585 namespace { 4586 /// PPC32_SVR4_ABIInfo - The 32-bit PowerPC ELF (SVR4) ABI information. 4587 class PPC32_SVR4_ABIInfo : public DefaultABIInfo { 4588 bool IsSoftFloatABI; 4589 bool IsRetSmallStructInRegABI; 4590 4591 CharUnits getParamTypeAlignment(QualType Ty) const; 4592 4593 public: 4594 PPC32_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, bool SoftFloatABI, 4595 bool RetSmallStructInRegABI) 4596 : DefaultABIInfo(CGT), IsSoftFloatABI(SoftFloatABI), 4597 IsRetSmallStructInRegABI(RetSmallStructInRegABI) {} 4598 4599 ABIArgInfo classifyReturnType(QualType RetTy) const; 4600 4601 void computeInfo(CGFunctionInfo &FI) const override { 4602 if (!getCXXABI().classifyReturnType(FI)) 4603 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 4604 for (auto &I : FI.arguments()) 4605 I.info = classifyArgumentType(I.type); 4606 } 4607 4608 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 4609 QualType Ty) const override; 4610 }; 4611 4612 class PPC32TargetCodeGenInfo : public TargetCodeGenInfo { 4613 public: 4614 PPC32TargetCodeGenInfo(CodeGenTypes &CGT, bool SoftFloatABI, 4615 bool RetSmallStructInRegABI) 4616 : TargetCodeGenInfo(std::make_unique<PPC32_SVR4_ABIInfo>( 4617 CGT, SoftFloatABI, RetSmallStructInRegABI)) {} 4618 4619 static bool isStructReturnInRegABI(const llvm::Triple &Triple, 4620 const CodeGenOptions &Opts); 4621 4622 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 4623 // This is recovered from gcc output. 4624 return 1; // r1 is the dedicated stack pointer 4625 } 4626 4627 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 4628 llvm::Value *Address) const override; 4629 }; 4630 } 4631 4632 CharUnits PPC32_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const { 4633 // Complex types are passed just like their elements. 4634 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) 4635 Ty = CTy->getElementType(); 4636 4637 if (Ty->isVectorType()) 4638 return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16 4639 : 4); 4640 4641 // For single-element float/vector structs, we consider the whole type 4642 // to have the same alignment requirements as its single element. 4643 const Type *AlignTy = nullptr; 4644 if (const Type *EltType = isSingleElementStruct(Ty, getContext())) { 4645 const BuiltinType *BT = EltType->getAs<BuiltinType>(); 4646 if ((EltType->isVectorType() && getContext().getTypeSize(EltType) == 128) || 4647 (BT && BT->isFloatingPoint())) 4648 AlignTy = EltType; 4649 } 4650 4651 if (AlignTy) 4652 return CharUnits::fromQuantity(AlignTy->isVectorType() ? 16 : 4); 4653 return CharUnits::fromQuantity(4); 4654 } 4655 4656 ABIArgInfo PPC32_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const { 4657 uint64_t Size; 4658 4659 // -msvr4-struct-return puts small aggregates in GPR3 and GPR4. 4660 if (isAggregateTypeForABI(RetTy) && IsRetSmallStructInRegABI && 4661 (Size = getContext().getTypeSize(RetTy)) <= 64) { 4662 // System V ABI (1995), page 3-22, specified: 4663 // > A structure or union whose size is less than or equal to 8 bytes 4664 // > shall be returned in r3 and r4, as if it were first stored in the 4665 // > 8-byte aligned memory area and then the low addressed word were 4666 // > loaded into r3 and the high-addressed word into r4. Bits beyond 4667 // > the last member of the structure or union are not defined. 4668 // 4669 // GCC for big-endian PPC32 inserts the pad before the first member, 4670 // not "beyond the last member" of the struct. To stay compatible 4671 // with GCC, we coerce the struct to an integer of the same size. 4672 // LLVM will extend it and return i32 in r3, or i64 in r3:r4. 4673 if (Size == 0) 4674 return ABIArgInfo::getIgnore(); 4675 else { 4676 llvm::Type *CoerceTy = llvm::Type::getIntNTy(getVMContext(), Size); 4677 return ABIArgInfo::getDirect(CoerceTy); 4678 } 4679 } 4680 4681 return DefaultABIInfo::classifyReturnType(RetTy); 4682 } 4683 4684 // TODO: this implementation is now likely redundant with 4685 // DefaultABIInfo::EmitVAArg. 4686 Address PPC32_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAList, 4687 QualType Ty) const { 4688 if (getTarget().getTriple().isOSDarwin()) { 4689 auto TI = getContext().getTypeInfoInChars(Ty); 4690 TI.second = getParamTypeAlignment(Ty); 4691 4692 CharUnits SlotSize = CharUnits::fromQuantity(4); 4693 return emitVoidPtrVAArg(CGF, VAList, Ty, 4694 classifyArgumentType(Ty).isIndirect(), TI, SlotSize, 4695 /*AllowHigherAlign=*/true); 4696 } 4697 4698 const unsigned OverflowLimit = 8; 4699 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) { 4700 // TODO: Implement this. For now ignore. 4701 (void)CTy; 4702 return Address::invalid(); // FIXME? 4703 } 4704 4705 // struct __va_list_tag { 4706 // unsigned char gpr; 4707 // unsigned char fpr; 4708 // unsigned short reserved; 4709 // void *overflow_arg_area; 4710 // void *reg_save_area; 4711 // }; 4712 4713 bool isI64 = Ty->isIntegerType() && getContext().getTypeSize(Ty) == 64; 4714 bool isInt = 4715 Ty->isIntegerType() || Ty->isPointerType() || Ty->isAggregateType(); 4716 bool isF64 = Ty->isFloatingType() && getContext().getTypeSize(Ty) == 64; 4717 4718 // All aggregates are passed indirectly? That doesn't seem consistent 4719 // with the argument-lowering code. 4720 bool isIndirect = Ty->isAggregateType(); 4721 4722 CGBuilderTy &Builder = CGF.Builder; 4723 4724 // The calling convention either uses 1-2 GPRs or 1 FPR. 4725 Address NumRegsAddr = Address::invalid(); 4726 if (isInt || IsSoftFloatABI) { 4727 NumRegsAddr = Builder.CreateStructGEP(VAList, 0, "gpr"); 4728 } else { 4729 NumRegsAddr = Builder.CreateStructGEP(VAList, 1, "fpr"); 4730 } 4731 4732 llvm::Value *NumRegs = Builder.CreateLoad(NumRegsAddr, "numUsedRegs"); 4733 4734 // "Align" the register count when TY is i64. 4735 if (isI64 || (isF64 && IsSoftFloatABI)) { 4736 NumRegs = Builder.CreateAdd(NumRegs, Builder.getInt8(1)); 4737 NumRegs = Builder.CreateAnd(NumRegs, Builder.getInt8((uint8_t) ~1U)); 4738 } 4739 4740 llvm::Value *CC = 4741 Builder.CreateICmpULT(NumRegs, Builder.getInt8(OverflowLimit), "cond"); 4742 4743 llvm::BasicBlock *UsingRegs = CGF.createBasicBlock("using_regs"); 4744 llvm::BasicBlock *UsingOverflow = CGF.createBasicBlock("using_overflow"); 4745 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont"); 4746 4747 Builder.CreateCondBr(CC, UsingRegs, UsingOverflow); 4748 4749 llvm::Type *DirectTy = CGF.ConvertType(Ty); 4750 if (isIndirect) DirectTy = DirectTy->getPointerTo(0); 4751 4752 // Case 1: consume registers. 4753 Address RegAddr = Address::invalid(); 4754 { 4755 CGF.EmitBlock(UsingRegs); 4756 4757 Address RegSaveAreaPtr = Builder.CreateStructGEP(VAList, 4); 4758 RegAddr = Address(Builder.CreateLoad(RegSaveAreaPtr), 4759 CharUnits::fromQuantity(8)); 4760 assert(RegAddr.getElementType() == CGF.Int8Ty); 4761 4762 // Floating-point registers start after the general-purpose registers. 4763 if (!(isInt || IsSoftFloatABI)) { 4764 RegAddr = Builder.CreateConstInBoundsByteGEP(RegAddr, 4765 CharUnits::fromQuantity(32)); 4766 } 4767 4768 // Get the address of the saved value by scaling the number of 4769 // registers we've used by the number of 4770 CharUnits RegSize = CharUnits::fromQuantity((isInt || IsSoftFloatABI) ? 4 : 8); 4771 llvm::Value *RegOffset = 4772 Builder.CreateMul(NumRegs, Builder.getInt8(RegSize.getQuantity())); 4773 RegAddr = Address(Builder.CreateInBoundsGEP(CGF.Int8Ty, 4774 RegAddr.getPointer(), RegOffset), 4775 RegAddr.getAlignment().alignmentOfArrayElement(RegSize)); 4776 RegAddr = Builder.CreateElementBitCast(RegAddr, DirectTy); 4777 4778 // Increase the used-register count. 4779 NumRegs = 4780 Builder.CreateAdd(NumRegs, 4781 Builder.getInt8((isI64 || (isF64 && IsSoftFloatABI)) ? 2 : 1)); 4782 Builder.CreateStore(NumRegs, NumRegsAddr); 4783 4784 CGF.EmitBranch(Cont); 4785 } 4786 4787 // Case 2: consume space in the overflow area. 4788 Address MemAddr = Address::invalid(); 4789 { 4790 CGF.EmitBlock(UsingOverflow); 4791 4792 Builder.CreateStore(Builder.getInt8(OverflowLimit), NumRegsAddr); 4793 4794 // Everything in the overflow area is rounded up to a size of at least 4. 4795 CharUnits OverflowAreaAlign = CharUnits::fromQuantity(4); 4796 4797 CharUnits Size; 4798 if (!isIndirect) { 4799 auto TypeInfo = CGF.getContext().getTypeInfoInChars(Ty); 4800 Size = TypeInfo.first.alignTo(OverflowAreaAlign); 4801 } else { 4802 Size = CGF.getPointerSize(); 4803 } 4804 4805 Address OverflowAreaAddr = Builder.CreateStructGEP(VAList, 3); 4806 Address OverflowArea(Builder.CreateLoad(OverflowAreaAddr, "argp.cur"), 4807 OverflowAreaAlign); 4808 // Round up address of argument to alignment 4809 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty); 4810 if (Align > OverflowAreaAlign) { 4811 llvm::Value *Ptr = OverflowArea.getPointer(); 4812 OverflowArea = Address(emitRoundPointerUpToAlignment(CGF, Ptr, Align), 4813 Align); 4814 } 4815 4816 MemAddr = Builder.CreateElementBitCast(OverflowArea, DirectTy); 4817 4818 // Increase the overflow area. 4819 OverflowArea = Builder.CreateConstInBoundsByteGEP(OverflowArea, Size); 4820 Builder.CreateStore(OverflowArea.getPointer(), OverflowAreaAddr); 4821 CGF.EmitBranch(Cont); 4822 } 4823 4824 CGF.EmitBlock(Cont); 4825 4826 // Merge the cases with a phi. 4827 Address Result = emitMergePHI(CGF, RegAddr, UsingRegs, MemAddr, UsingOverflow, 4828 "vaarg.addr"); 4829 4830 // Load the pointer if the argument was passed indirectly. 4831 if (isIndirect) { 4832 Result = Address(Builder.CreateLoad(Result, "aggr"), 4833 getContext().getTypeAlignInChars(Ty)); 4834 } 4835 4836 return Result; 4837 } 4838 4839 bool PPC32TargetCodeGenInfo::isStructReturnInRegABI( 4840 const llvm::Triple &Triple, const CodeGenOptions &Opts) { 4841 assert(Triple.getArch() == llvm::Triple::ppc); 4842 4843 switch (Opts.getStructReturnConvention()) { 4844 case CodeGenOptions::SRCK_Default: 4845 break; 4846 case CodeGenOptions::SRCK_OnStack: // -maix-struct-return 4847 return false; 4848 case CodeGenOptions::SRCK_InRegs: // -msvr4-struct-return 4849 return true; 4850 } 4851 4852 if (Triple.isOSBinFormatELF() && !Triple.isOSLinux()) 4853 return true; 4854 4855 return false; 4856 } 4857 4858 bool 4859 PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 4860 llvm::Value *Address) const { 4861 return PPC_initDwarfEHRegSizeTable(CGF, Address, /*Is64Bit*/ false, 4862 /*IsAIX*/ false); 4863 } 4864 4865 // PowerPC-64 4866 4867 namespace { 4868 /// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information. 4869 class PPC64_SVR4_ABIInfo : public SwiftABIInfo { 4870 public: 4871 enum ABIKind { 4872 ELFv1 = 0, 4873 ELFv2 4874 }; 4875 4876 private: 4877 static const unsigned GPRBits = 64; 4878 ABIKind Kind; 4879 bool HasQPX; 4880 bool IsSoftFloatABI; 4881 4882 // A vector of float or double will be promoted to <4 x f32> or <4 x f64> and 4883 // will be passed in a QPX register. 4884 bool IsQPXVectorTy(const Type *Ty) const { 4885 if (!HasQPX) 4886 return false; 4887 4888 if (const VectorType *VT = Ty->getAs<VectorType>()) { 4889 unsigned NumElements = VT->getNumElements(); 4890 if (NumElements == 1) 4891 return false; 4892 4893 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double)) { 4894 if (getContext().getTypeSize(Ty) <= 256) 4895 return true; 4896 } else if (VT->getElementType()-> 4897 isSpecificBuiltinType(BuiltinType::Float)) { 4898 if (getContext().getTypeSize(Ty) <= 128) 4899 return true; 4900 } 4901 } 4902 4903 return false; 4904 } 4905 4906 bool IsQPXVectorTy(QualType Ty) const { 4907 return IsQPXVectorTy(Ty.getTypePtr()); 4908 } 4909 4910 public: 4911 PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind, bool HasQPX, 4912 bool SoftFloatABI) 4913 : SwiftABIInfo(CGT), Kind(Kind), HasQPX(HasQPX), 4914 IsSoftFloatABI(SoftFloatABI) {} 4915 4916 bool isPromotableTypeForABI(QualType Ty) const; 4917 CharUnits getParamTypeAlignment(QualType Ty) const; 4918 4919 ABIArgInfo classifyReturnType(QualType RetTy) const; 4920 ABIArgInfo classifyArgumentType(QualType Ty) const; 4921 4922 bool isHomogeneousAggregateBaseType(QualType Ty) const override; 4923 bool isHomogeneousAggregateSmallEnough(const Type *Ty, 4924 uint64_t Members) const override; 4925 4926 // TODO: We can add more logic to computeInfo to improve performance. 4927 // Example: For aggregate arguments that fit in a register, we could 4928 // use getDirectInReg (as is done below for structs containing a single 4929 // floating-point value) to avoid pushing them to memory on function 4930 // entry. This would require changing the logic in PPCISelLowering 4931 // when lowering the parameters in the caller and args in the callee. 4932 void computeInfo(CGFunctionInfo &FI) const override { 4933 if (!getCXXABI().classifyReturnType(FI)) 4934 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 4935 for (auto &I : FI.arguments()) { 4936 // We rely on the default argument classification for the most part. 4937 // One exception: An aggregate containing a single floating-point 4938 // or vector item must be passed in a register if one is available. 4939 const Type *T = isSingleElementStruct(I.type, getContext()); 4940 if (T) { 4941 const BuiltinType *BT = T->getAs<BuiltinType>(); 4942 if (IsQPXVectorTy(T) || 4943 (T->isVectorType() && getContext().getTypeSize(T) == 128) || 4944 (BT && BT->isFloatingPoint())) { 4945 QualType QT(T, 0); 4946 I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT)); 4947 continue; 4948 } 4949 } 4950 I.info = classifyArgumentType(I.type); 4951 } 4952 } 4953 4954 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 4955 QualType Ty) const override; 4956 4957 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars, 4958 bool asReturnValue) const override { 4959 return occupiesMoreThan(CGT, scalars, /*total*/ 4); 4960 } 4961 4962 bool isSwiftErrorInRegister() const override { 4963 return false; 4964 } 4965 }; 4966 4967 class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo { 4968 4969 public: 4970 PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT, 4971 PPC64_SVR4_ABIInfo::ABIKind Kind, bool HasQPX, 4972 bool SoftFloatABI) 4973 : TargetCodeGenInfo(std::make_unique<PPC64_SVR4_ABIInfo>( 4974 CGT, Kind, HasQPX, SoftFloatABI)) {} 4975 4976 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 4977 // This is recovered from gcc output. 4978 return 1; // r1 is the dedicated stack pointer 4979 } 4980 4981 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 4982 llvm::Value *Address) const override; 4983 }; 4984 4985 class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo { 4986 public: 4987 PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {} 4988 4989 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 4990 // This is recovered from gcc output. 4991 return 1; // r1 is the dedicated stack pointer 4992 } 4993 4994 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 4995 llvm::Value *Address) const override; 4996 }; 4997 4998 } 4999 5000 // Return true if the ABI requires Ty to be passed sign- or zero- 5001 // extended to 64 bits. 5002 bool 5003 PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const { 5004 // Treat an enum type as its underlying type. 5005 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 5006 Ty = EnumTy->getDecl()->getIntegerType(); 5007 5008 // Promotable integer types are required to be promoted by the ABI. 5009 if (isPromotableIntegerTypeForABI(Ty)) 5010 return true; 5011 5012 // In addition to the usual promotable integer types, we also need to 5013 // extend all 32-bit types, since the ABI requires promotion to 64 bits. 5014 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) 5015 switch (BT->getKind()) { 5016 case BuiltinType::Int: 5017 case BuiltinType::UInt: 5018 return true; 5019 default: 5020 break; 5021 } 5022 5023 if (const auto *EIT = Ty->getAs<ExtIntType>()) 5024 if (EIT->getNumBits() < 64) 5025 return true; 5026 5027 return false; 5028 } 5029 5030 /// isAlignedParamType - Determine whether a type requires 16-byte or 5031 /// higher alignment in the parameter area. Always returns at least 8. 5032 CharUnits PPC64_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const { 5033 // Complex types are passed just like their elements. 5034 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) 5035 Ty = CTy->getElementType(); 5036 5037 // Only vector types of size 16 bytes need alignment (larger types are 5038 // passed via reference, smaller types are not aligned). 5039 if (IsQPXVectorTy(Ty)) { 5040 if (getContext().getTypeSize(Ty) > 128) 5041 return CharUnits::fromQuantity(32); 5042 5043 return CharUnits::fromQuantity(16); 5044 } else if (Ty->isVectorType()) { 5045 return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16 : 8); 5046 } 5047 5048 // For single-element float/vector structs, we consider the whole type 5049 // to have the same alignment requirements as its single element. 5050 const Type *AlignAsType = nullptr; 5051 const Type *EltType = isSingleElementStruct(Ty, getContext()); 5052 if (EltType) { 5053 const BuiltinType *BT = EltType->getAs<BuiltinType>(); 5054 if (IsQPXVectorTy(EltType) || (EltType->isVectorType() && 5055 getContext().getTypeSize(EltType) == 128) || 5056 (BT && BT->isFloatingPoint())) 5057 AlignAsType = EltType; 5058 } 5059 5060 // Likewise for ELFv2 homogeneous aggregates. 5061 const Type *Base = nullptr; 5062 uint64_t Members = 0; 5063 if (!AlignAsType && Kind == ELFv2 && 5064 isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members)) 5065 AlignAsType = Base; 5066 5067 // With special case aggregates, only vector base types need alignment. 5068 if (AlignAsType && IsQPXVectorTy(AlignAsType)) { 5069 if (getContext().getTypeSize(AlignAsType) > 128) 5070 return CharUnits::fromQuantity(32); 5071 5072 return CharUnits::fromQuantity(16); 5073 } else if (AlignAsType) { 5074 return CharUnits::fromQuantity(AlignAsType->isVectorType() ? 16 : 8); 5075 } 5076 5077 // Otherwise, we only need alignment for any aggregate type that 5078 // has an alignment requirement of >= 16 bytes. 5079 if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128) { 5080 if (HasQPX && getContext().getTypeAlign(Ty) >= 256) 5081 return CharUnits::fromQuantity(32); 5082 return CharUnits::fromQuantity(16); 5083 } 5084 5085 return CharUnits::fromQuantity(8); 5086 } 5087 5088 /// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous 5089 /// aggregate. Base is set to the base element type, and Members is set 5090 /// to the number of base elements. 5091 bool ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base, 5092 uint64_t &Members) const { 5093 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) { 5094 uint64_t NElements = AT->getSize().getZExtValue(); 5095 if (NElements == 0) 5096 return false; 5097 if (!isHomogeneousAggregate(AT->getElementType(), Base, Members)) 5098 return false; 5099 Members *= NElements; 5100 } else if (const RecordType *RT = Ty->getAs<RecordType>()) { 5101 const RecordDecl *RD = RT->getDecl(); 5102 if (RD->hasFlexibleArrayMember()) 5103 return false; 5104 5105 Members = 0; 5106 5107 // If this is a C++ record, check the bases first. 5108 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 5109 for (const auto &I : CXXRD->bases()) { 5110 // Ignore empty records. 5111 if (isEmptyRecord(getContext(), I.getType(), true)) 5112 continue; 5113 5114 uint64_t FldMembers; 5115 if (!isHomogeneousAggregate(I.getType(), Base, FldMembers)) 5116 return false; 5117 5118 Members += FldMembers; 5119 } 5120 } 5121 5122 for (const auto *FD : RD->fields()) { 5123 // Ignore (non-zero arrays of) empty records. 5124 QualType FT = FD->getType(); 5125 while (const ConstantArrayType *AT = 5126 getContext().getAsConstantArrayType(FT)) { 5127 if (AT->getSize().getZExtValue() == 0) 5128 return false; 5129 FT = AT->getElementType(); 5130 } 5131 if (isEmptyRecord(getContext(), FT, true)) 5132 continue; 5133 5134 // For compatibility with GCC, ignore empty bitfields in C++ mode. 5135 if (getContext().getLangOpts().CPlusPlus && 5136 FD->isZeroLengthBitField(getContext())) 5137 continue; 5138 5139 uint64_t FldMembers; 5140 if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers)) 5141 return false; 5142 5143 Members = (RD->isUnion() ? 5144 std::max(Members, FldMembers) : Members + FldMembers); 5145 } 5146 5147 if (!Base) 5148 return false; 5149 5150 // Ensure there is no padding. 5151 if (getContext().getTypeSize(Base) * Members != 5152 getContext().getTypeSize(Ty)) 5153 return false; 5154 } else { 5155 Members = 1; 5156 if (const ComplexType *CT = Ty->getAs<ComplexType>()) { 5157 Members = 2; 5158 Ty = CT->getElementType(); 5159 } 5160 5161 // Most ABIs only support float, double, and some vector type widths. 5162 if (!isHomogeneousAggregateBaseType(Ty)) 5163 return false; 5164 5165 // The base type must be the same for all members. Types that 5166 // agree in both total size and mode (float vs. vector) are 5167 // treated as being equivalent here. 5168 const Type *TyPtr = Ty.getTypePtr(); 5169 if (!Base) { 5170 Base = TyPtr; 5171 // If it's a non-power-of-2 vector, its size is already a power-of-2, 5172 // so make sure to widen it explicitly. 5173 if (const VectorType *VT = Base->getAs<VectorType>()) { 5174 QualType EltTy = VT->getElementType(); 5175 unsigned NumElements = 5176 getContext().getTypeSize(VT) / getContext().getTypeSize(EltTy); 5177 Base = getContext() 5178 .getVectorType(EltTy, NumElements, VT->getVectorKind()) 5179 .getTypePtr(); 5180 } 5181 } 5182 5183 if (Base->isVectorType() != TyPtr->isVectorType() || 5184 getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr)) 5185 return false; 5186 } 5187 return Members > 0 && isHomogeneousAggregateSmallEnough(Base, Members); 5188 } 5189 5190 bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const { 5191 // Homogeneous aggregates for ELFv2 must have base types of float, 5192 // double, long double, or 128-bit vectors. 5193 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) { 5194 if (BT->getKind() == BuiltinType::Float || 5195 BT->getKind() == BuiltinType::Double || 5196 BT->getKind() == BuiltinType::LongDouble || 5197 (getContext().getTargetInfo().hasFloat128Type() && 5198 (BT->getKind() == BuiltinType::Float128))) { 5199 if (IsSoftFloatABI) 5200 return false; 5201 return true; 5202 } 5203 } 5204 if (const VectorType *VT = Ty->getAs<VectorType>()) { 5205 if (getContext().getTypeSize(VT) == 128 || IsQPXVectorTy(Ty)) 5206 return true; 5207 } 5208 return false; 5209 } 5210 5211 bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateSmallEnough( 5212 const Type *Base, uint64_t Members) const { 5213 // Vector and fp128 types require one register, other floating point types 5214 // require one or two registers depending on their size. 5215 uint32_t NumRegs = 5216 ((getContext().getTargetInfo().hasFloat128Type() && 5217 Base->isFloat128Type()) || 5218 Base->isVectorType()) ? 1 5219 : (getContext().getTypeSize(Base) + 63) / 64; 5220 5221 // Homogeneous Aggregates may occupy at most 8 registers. 5222 return Members * NumRegs <= 8; 5223 } 5224 5225 ABIArgInfo 5226 PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const { 5227 Ty = useFirstFieldIfTransparentUnion(Ty); 5228 5229 if (Ty->isAnyComplexType()) 5230 return ABIArgInfo::getDirect(); 5231 5232 // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes) 5233 // or via reference (larger than 16 bytes). 5234 if (Ty->isVectorType() && !IsQPXVectorTy(Ty)) { 5235 uint64_t Size = getContext().getTypeSize(Ty); 5236 if (Size > 128) 5237 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 5238 else if (Size < 128) { 5239 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size); 5240 return ABIArgInfo::getDirect(CoerceTy); 5241 } 5242 } 5243 5244 if (const auto *EIT = Ty->getAs<ExtIntType>()) 5245 if (EIT->getNumBits() > 128) 5246 return getNaturalAlignIndirect(Ty, /*ByVal=*/true); 5247 5248 if (isAggregateTypeForABI(Ty)) { 5249 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 5250 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 5251 5252 uint64_t ABIAlign = getParamTypeAlignment(Ty).getQuantity(); 5253 uint64_t TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity(); 5254 5255 // ELFv2 homogeneous aggregates are passed as array types. 5256 const Type *Base = nullptr; 5257 uint64_t Members = 0; 5258 if (Kind == ELFv2 && 5259 isHomogeneousAggregate(Ty, Base, Members)) { 5260 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0)); 5261 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members); 5262 return ABIArgInfo::getDirect(CoerceTy); 5263 } 5264 5265 // If an aggregate may end up fully in registers, we do not 5266 // use the ByVal method, but pass the aggregate as array. 5267 // This is usually beneficial since we avoid forcing the 5268 // back-end to store the argument to memory. 5269 uint64_t Bits = getContext().getTypeSize(Ty); 5270 if (Bits > 0 && Bits <= 8 * GPRBits) { 5271 llvm::Type *CoerceTy; 5272 5273 // Types up to 8 bytes are passed as integer type (which will be 5274 // properly aligned in the argument save area doubleword). 5275 if (Bits <= GPRBits) 5276 CoerceTy = 5277 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8)); 5278 // Larger types are passed as arrays, with the base type selected 5279 // according to the required alignment in the save area. 5280 else { 5281 uint64_t RegBits = ABIAlign * 8; 5282 uint64_t NumRegs = llvm::alignTo(Bits, RegBits) / RegBits; 5283 llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits); 5284 CoerceTy = llvm::ArrayType::get(RegTy, NumRegs); 5285 } 5286 5287 return ABIArgInfo::getDirect(CoerceTy); 5288 } 5289 5290 // All other aggregates are passed ByVal. 5291 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign), 5292 /*ByVal=*/true, 5293 /*Realign=*/TyAlign > ABIAlign); 5294 } 5295 5296 return (isPromotableTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty) 5297 : ABIArgInfo::getDirect()); 5298 } 5299 5300 ABIArgInfo 5301 PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const { 5302 if (RetTy->isVoidType()) 5303 return ABIArgInfo::getIgnore(); 5304 5305 if (RetTy->isAnyComplexType()) 5306 return ABIArgInfo::getDirect(); 5307 5308 // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes) 5309 // or via reference (larger than 16 bytes). 5310 if (RetTy->isVectorType() && !IsQPXVectorTy(RetTy)) { 5311 uint64_t Size = getContext().getTypeSize(RetTy); 5312 if (Size > 128) 5313 return getNaturalAlignIndirect(RetTy); 5314 else if (Size < 128) { 5315 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size); 5316 return ABIArgInfo::getDirect(CoerceTy); 5317 } 5318 } 5319 5320 if (const auto *EIT = RetTy->getAs<ExtIntType>()) 5321 if (EIT->getNumBits() > 128) 5322 return getNaturalAlignIndirect(RetTy, /*ByVal=*/false); 5323 5324 if (isAggregateTypeForABI(RetTy)) { 5325 // ELFv2 homogeneous aggregates are returned as array types. 5326 const Type *Base = nullptr; 5327 uint64_t Members = 0; 5328 if (Kind == ELFv2 && 5329 isHomogeneousAggregate(RetTy, Base, Members)) { 5330 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0)); 5331 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members); 5332 return ABIArgInfo::getDirect(CoerceTy); 5333 } 5334 5335 // ELFv2 small aggregates are returned in up to two registers. 5336 uint64_t Bits = getContext().getTypeSize(RetTy); 5337 if (Kind == ELFv2 && Bits <= 2 * GPRBits) { 5338 if (Bits == 0) 5339 return ABIArgInfo::getIgnore(); 5340 5341 llvm::Type *CoerceTy; 5342 if (Bits > GPRBits) { 5343 CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits); 5344 CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy); 5345 } else 5346 CoerceTy = 5347 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8)); 5348 return ABIArgInfo::getDirect(CoerceTy); 5349 } 5350 5351 // All other aggregates are returned indirectly. 5352 return getNaturalAlignIndirect(RetTy); 5353 } 5354 5355 return (isPromotableTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy) 5356 : ABIArgInfo::getDirect()); 5357 } 5358 5359 // Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine. 5360 Address PPC64_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 5361 QualType Ty) const { 5362 auto TypeInfo = getContext().getTypeInfoInChars(Ty); 5363 TypeInfo.second = getParamTypeAlignment(Ty); 5364 5365 CharUnits SlotSize = CharUnits::fromQuantity(8); 5366 5367 // If we have a complex type and the base type is smaller than 8 bytes, 5368 // the ABI calls for the real and imaginary parts to be right-adjusted 5369 // in separate doublewords. However, Clang expects us to produce a 5370 // pointer to a structure with the two parts packed tightly. So generate 5371 // loads of the real and imaginary parts relative to the va_list pointer, 5372 // and store them to a temporary structure. 5373 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) { 5374 CharUnits EltSize = TypeInfo.first / 2; 5375 if (EltSize < SlotSize) { 5376 Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, CGF.Int8Ty, 5377 SlotSize * 2, SlotSize, 5378 SlotSize, /*AllowHigher*/ true); 5379 5380 Address RealAddr = Addr; 5381 Address ImagAddr = RealAddr; 5382 if (CGF.CGM.getDataLayout().isBigEndian()) { 5383 RealAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, 5384 SlotSize - EltSize); 5385 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(ImagAddr, 5386 2 * SlotSize - EltSize); 5387 } else { 5388 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, SlotSize); 5389 } 5390 5391 llvm::Type *EltTy = CGF.ConvertTypeForMem(CTy->getElementType()); 5392 RealAddr = CGF.Builder.CreateElementBitCast(RealAddr, EltTy); 5393 ImagAddr = CGF.Builder.CreateElementBitCast(ImagAddr, EltTy); 5394 llvm::Value *Real = CGF.Builder.CreateLoad(RealAddr, ".vareal"); 5395 llvm::Value *Imag = CGF.Builder.CreateLoad(ImagAddr, ".vaimag"); 5396 5397 Address Temp = CGF.CreateMemTemp(Ty, "vacplx"); 5398 CGF.EmitStoreOfComplex({Real, Imag}, CGF.MakeAddrLValue(Temp, Ty), 5399 /*init*/ true); 5400 return Temp; 5401 } 5402 } 5403 5404 // Otherwise, just use the general rule. 5405 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false, 5406 TypeInfo, SlotSize, /*AllowHigher*/ true); 5407 } 5408 5409 bool 5410 PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable( 5411 CodeGen::CodeGenFunction &CGF, 5412 llvm::Value *Address) const { 5413 return PPC_initDwarfEHRegSizeTable(CGF, Address, /*Is64Bit*/ true, 5414 /*IsAIX*/ false); 5415 } 5416 5417 bool 5418 PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 5419 llvm::Value *Address) const { 5420 return PPC_initDwarfEHRegSizeTable(CGF, Address, /*Is64Bit*/ true, 5421 /*IsAIX*/ false); 5422 } 5423 5424 //===----------------------------------------------------------------------===// 5425 // AArch64 ABI Implementation 5426 //===----------------------------------------------------------------------===// 5427 5428 namespace { 5429 5430 class AArch64ABIInfo : public SwiftABIInfo { 5431 public: 5432 enum ABIKind { 5433 AAPCS = 0, 5434 DarwinPCS, 5435 Win64 5436 }; 5437 5438 private: 5439 ABIKind Kind; 5440 5441 public: 5442 AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind) 5443 : SwiftABIInfo(CGT), Kind(Kind) {} 5444 5445 private: 5446 ABIKind getABIKind() const { return Kind; } 5447 bool isDarwinPCS() const { return Kind == DarwinPCS; } 5448 5449 ABIArgInfo classifyReturnType(QualType RetTy, bool IsVariadic) const; 5450 ABIArgInfo classifyArgumentType(QualType RetTy) const; 5451 bool isHomogeneousAggregateBaseType(QualType Ty) const override; 5452 bool isHomogeneousAggregateSmallEnough(const Type *Ty, 5453 uint64_t Members) const override; 5454 5455 bool isIllegalVectorType(QualType Ty) const; 5456 5457 void computeInfo(CGFunctionInfo &FI) const override { 5458 if (!::classifyReturnType(getCXXABI(), FI, *this)) 5459 FI.getReturnInfo() = 5460 classifyReturnType(FI.getReturnType(), FI.isVariadic()); 5461 5462 for (auto &it : FI.arguments()) 5463 it.info = classifyArgumentType(it.type); 5464 } 5465 5466 Address EmitDarwinVAArg(Address VAListAddr, QualType Ty, 5467 CodeGenFunction &CGF) const; 5468 5469 Address EmitAAPCSVAArg(Address VAListAddr, QualType Ty, 5470 CodeGenFunction &CGF) const; 5471 5472 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 5473 QualType Ty) const override { 5474 return Kind == Win64 ? EmitMSVAArg(CGF, VAListAddr, Ty) 5475 : isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF) 5476 : EmitAAPCSVAArg(VAListAddr, Ty, CGF); 5477 } 5478 5479 Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr, 5480 QualType Ty) const override; 5481 5482 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars, 5483 bool asReturnValue) const override { 5484 return occupiesMoreThan(CGT, scalars, /*total*/ 4); 5485 } 5486 bool isSwiftErrorInRegister() const override { 5487 return true; 5488 } 5489 5490 bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy, 5491 unsigned elts) const override; 5492 5493 bool allowBFloatArgsAndRet() const override { 5494 return getTarget().hasBFloat16Type(); 5495 } 5496 }; 5497 5498 class AArch64TargetCodeGenInfo : public TargetCodeGenInfo { 5499 public: 5500 AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind) 5501 : TargetCodeGenInfo(std::make_unique<AArch64ABIInfo>(CGT, Kind)) {} 5502 5503 StringRef getARCRetainAutoreleasedReturnValueMarker() const override { 5504 return "mov\tfp, fp\t\t// marker for objc_retainAutoreleaseReturnValue"; 5505 } 5506 5507 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 5508 return 31; 5509 } 5510 5511 bool doesReturnSlotInterfereWithArgs() const override { return false; } 5512 5513 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 5514 CodeGen::CodeGenModule &CGM) const override { 5515 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D); 5516 if (!FD) 5517 return; 5518 5519 LangOptions::SignReturnAddressScopeKind Scope = 5520 CGM.getLangOpts().getSignReturnAddressScope(); 5521 LangOptions::SignReturnAddressKeyKind Key = 5522 CGM.getLangOpts().getSignReturnAddressKey(); 5523 bool BranchTargetEnforcement = CGM.getLangOpts().BranchTargetEnforcement; 5524 if (const auto *TA = FD->getAttr<TargetAttr>()) { 5525 ParsedTargetAttr Attr = TA->parse(); 5526 if (!Attr.BranchProtection.empty()) { 5527 TargetInfo::BranchProtectionInfo BPI; 5528 StringRef Error; 5529 (void)CGM.getTarget().validateBranchProtection(Attr.BranchProtection, 5530 BPI, Error); 5531 assert(Error.empty()); 5532 Scope = BPI.SignReturnAddr; 5533 Key = BPI.SignKey; 5534 BranchTargetEnforcement = BPI.BranchTargetEnforcement; 5535 } 5536 } 5537 5538 auto *Fn = cast<llvm::Function>(GV); 5539 if (Scope != LangOptions::SignReturnAddressScopeKind::None) { 5540 Fn->addFnAttr("sign-return-address", 5541 Scope == LangOptions::SignReturnAddressScopeKind::All 5542 ? "all" 5543 : "non-leaf"); 5544 5545 Fn->addFnAttr("sign-return-address-key", 5546 Key == LangOptions::SignReturnAddressKeyKind::AKey 5547 ? "a_key" 5548 : "b_key"); 5549 } 5550 5551 if (BranchTargetEnforcement) 5552 Fn->addFnAttr("branch-target-enforcement"); 5553 } 5554 }; 5555 5556 class WindowsAArch64TargetCodeGenInfo : public AArch64TargetCodeGenInfo { 5557 public: 5558 WindowsAArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind K) 5559 : AArch64TargetCodeGenInfo(CGT, K) {} 5560 5561 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 5562 CodeGen::CodeGenModule &CGM) const override; 5563 5564 void getDependentLibraryOption(llvm::StringRef Lib, 5565 llvm::SmallString<24> &Opt) const override { 5566 Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib); 5567 } 5568 5569 void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value, 5570 llvm::SmallString<32> &Opt) const override { 5571 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\""; 5572 } 5573 }; 5574 5575 void WindowsAArch64TargetCodeGenInfo::setTargetAttributes( 5576 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const { 5577 AArch64TargetCodeGenInfo::setTargetAttributes(D, GV, CGM); 5578 if (GV->isDeclaration()) 5579 return; 5580 addStackProbeTargetAttributes(D, GV, CGM); 5581 } 5582 } 5583 5584 ABIArgInfo AArch64ABIInfo::classifyArgumentType(QualType Ty) const { 5585 Ty = useFirstFieldIfTransparentUnion(Ty); 5586 5587 // Handle illegal vector types here. 5588 if (isIllegalVectorType(Ty)) { 5589 uint64_t Size = getContext().getTypeSize(Ty); 5590 // Android promotes <2 x i8> to i16, not i32 5591 if (isAndroid() && (Size <= 16)) { 5592 llvm::Type *ResType = llvm::Type::getInt16Ty(getVMContext()); 5593 return ABIArgInfo::getDirect(ResType); 5594 } 5595 if (Size <= 32) { 5596 llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext()); 5597 return ABIArgInfo::getDirect(ResType); 5598 } 5599 if (Size == 64) { 5600 auto *ResType = 5601 llvm::FixedVectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2); 5602 return ABIArgInfo::getDirect(ResType); 5603 } 5604 if (Size == 128) { 5605 auto *ResType = 5606 llvm::FixedVectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4); 5607 return ABIArgInfo::getDirect(ResType); 5608 } 5609 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 5610 } 5611 5612 if (!isAggregateTypeForABI(Ty)) { 5613 // Treat an enum type as its underlying type. 5614 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 5615 Ty = EnumTy->getDecl()->getIntegerType(); 5616 5617 if (const auto *EIT = Ty->getAs<ExtIntType>()) 5618 if (EIT->getNumBits() > 128) 5619 return getNaturalAlignIndirect(Ty); 5620 5621 return (isPromotableIntegerTypeForABI(Ty) && isDarwinPCS() 5622 ? ABIArgInfo::getExtend(Ty) 5623 : ABIArgInfo::getDirect()); 5624 } 5625 5626 // Structures with either a non-trivial destructor or a non-trivial 5627 // copy constructor are always indirect. 5628 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) { 5629 return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA == 5630 CGCXXABI::RAA_DirectInMemory); 5631 } 5632 5633 // Empty records are always ignored on Darwin, but actually passed in C++ mode 5634 // elsewhere for GNU compatibility. 5635 uint64_t Size = getContext().getTypeSize(Ty); 5636 bool IsEmpty = isEmptyRecord(getContext(), Ty, true); 5637 if (IsEmpty || Size == 0) { 5638 if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS()) 5639 return ABIArgInfo::getIgnore(); 5640 5641 // GNU C mode. The only argument that gets ignored is an empty one with size 5642 // 0. 5643 if (IsEmpty && Size == 0) 5644 return ABIArgInfo::getIgnore(); 5645 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext())); 5646 } 5647 5648 // Homogeneous Floating-point Aggregates (HFAs) need to be expanded. 5649 const Type *Base = nullptr; 5650 uint64_t Members = 0; 5651 if (isHomogeneousAggregate(Ty, Base, Members)) { 5652 return ABIArgInfo::getDirect( 5653 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members)); 5654 } 5655 5656 // Aggregates <= 16 bytes are passed directly in registers or on the stack. 5657 if (Size <= 128) { 5658 // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of 5659 // same size and alignment. 5660 if (getTarget().isRenderScriptTarget()) { 5661 return coerceToIntArray(Ty, getContext(), getVMContext()); 5662 } 5663 unsigned Alignment; 5664 if (Kind == AArch64ABIInfo::AAPCS) { 5665 Alignment = getContext().getTypeUnadjustedAlign(Ty); 5666 Alignment = Alignment < 128 ? 64 : 128; 5667 } else { 5668 Alignment = std::max(getContext().getTypeAlign(Ty), 5669 (unsigned)getTarget().getPointerWidth(0)); 5670 } 5671 Size = llvm::alignTo(Size, Alignment); 5672 5673 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment. 5674 // For aggregates with 16-byte alignment, we use i128. 5675 llvm::Type *BaseTy = llvm::Type::getIntNTy(getVMContext(), Alignment); 5676 return ABIArgInfo::getDirect( 5677 Size == Alignment ? BaseTy 5678 : llvm::ArrayType::get(BaseTy, Size / Alignment)); 5679 } 5680 5681 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 5682 } 5683 5684 ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy, 5685 bool IsVariadic) const { 5686 if (RetTy->isVoidType()) 5687 return ABIArgInfo::getIgnore(); 5688 5689 // Large vector types should be returned via memory. 5690 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128) 5691 return getNaturalAlignIndirect(RetTy); 5692 5693 if (!isAggregateTypeForABI(RetTy)) { 5694 // Treat an enum type as its underlying type. 5695 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 5696 RetTy = EnumTy->getDecl()->getIntegerType(); 5697 5698 if (const auto *EIT = RetTy->getAs<ExtIntType>()) 5699 if (EIT->getNumBits() > 128) 5700 return getNaturalAlignIndirect(RetTy); 5701 5702 return (isPromotableIntegerTypeForABI(RetTy) && isDarwinPCS() 5703 ? ABIArgInfo::getExtend(RetTy) 5704 : ABIArgInfo::getDirect()); 5705 } 5706 5707 uint64_t Size = getContext().getTypeSize(RetTy); 5708 if (isEmptyRecord(getContext(), RetTy, true) || Size == 0) 5709 return ABIArgInfo::getIgnore(); 5710 5711 const Type *Base = nullptr; 5712 uint64_t Members = 0; 5713 if (isHomogeneousAggregate(RetTy, Base, Members) && 5714 !(getTarget().getTriple().getArch() == llvm::Triple::aarch64_32 && 5715 IsVariadic)) 5716 // Homogeneous Floating-point Aggregates (HFAs) are returned directly. 5717 return ABIArgInfo::getDirect(); 5718 5719 // Aggregates <= 16 bytes are returned directly in registers or on the stack. 5720 if (Size <= 128) { 5721 // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of 5722 // same size and alignment. 5723 if (getTarget().isRenderScriptTarget()) { 5724 return coerceToIntArray(RetTy, getContext(), getVMContext()); 5725 } 5726 unsigned Alignment = getContext().getTypeAlign(RetTy); 5727 Size = llvm::alignTo(Size, 64); // round up to multiple of 8 bytes 5728 5729 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment. 5730 // For aggregates with 16-byte alignment, we use i128. 5731 if (Alignment < 128 && Size == 128) { 5732 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext()); 5733 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64)); 5734 } 5735 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size)); 5736 } 5737 5738 return getNaturalAlignIndirect(RetTy); 5739 } 5740 5741 /// isIllegalVectorType - check whether the vector type is legal for AArch64. 5742 bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const { 5743 if (const VectorType *VT = Ty->getAs<VectorType>()) { 5744 // Check whether VT is legal. 5745 unsigned NumElements = VT->getNumElements(); 5746 uint64_t Size = getContext().getTypeSize(VT); 5747 // NumElements should be power of 2. 5748 if (!llvm::isPowerOf2_32(NumElements)) 5749 return true; 5750 5751 // arm64_32 has to be compatible with the ARM logic here, which allows huge 5752 // vectors for some reason. 5753 llvm::Triple Triple = getTarget().getTriple(); 5754 if (Triple.getArch() == llvm::Triple::aarch64_32 && 5755 Triple.isOSBinFormatMachO()) 5756 return Size <= 32; 5757 5758 return Size != 64 && (Size != 128 || NumElements == 1); 5759 } 5760 return false; 5761 } 5762 5763 bool AArch64ABIInfo::isLegalVectorTypeForSwift(CharUnits totalSize, 5764 llvm::Type *eltTy, 5765 unsigned elts) const { 5766 if (!llvm::isPowerOf2_32(elts)) 5767 return false; 5768 if (totalSize.getQuantity() != 8 && 5769 (totalSize.getQuantity() != 16 || elts == 1)) 5770 return false; 5771 return true; 5772 } 5773 5774 bool AArch64ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const { 5775 // Homogeneous aggregates for AAPCS64 must have base types of a floating 5776 // point type or a short-vector type. This is the same as the 32-bit ABI, 5777 // but with the difference that any floating-point type is allowed, 5778 // including __fp16. 5779 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) { 5780 if (BT->isFloatingPoint()) 5781 return true; 5782 } else if (const VectorType *VT = Ty->getAs<VectorType>()) { 5783 unsigned VecSize = getContext().getTypeSize(VT); 5784 if (VecSize == 64 || VecSize == 128) 5785 return true; 5786 } 5787 return false; 5788 } 5789 5790 bool AArch64ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base, 5791 uint64_t Members) const { 5792 return Members <= 4; 5793 } 5794 5795 Address AArch64ABIInfo::EmitAAPCSVAArg(Address VAListAddr, 5796 QualType Ty, 5797 CodeGenFunction &CGF) const { 5798 ABIArgInfo AI = classifyArgumentType(Ty); 5799 bool IsIndirect = AI.isIndirect(); 5800 5801 llvm::Type *BaseTy = CGF.ConvertType(Ty); 5802 if (IsIndirect) 5803 BaseTy = llvm::PointerType::getUnqual(BaseTy); 5804 else if (AI.getCoerceToType()) 5805 BaseTy = AI.getCoerceToType(); 5806 5807 unsigned NumRegs = 1; 5808 if (llvm::ArrayType *ArrTy = dyn_cast<llvm::ArrayType>(BaseTy)) { 5809 BaseTy = ArrTy->getElementType(); 5810 NumRegs = ArrTy->getNumElements(); 5811 } 5812 bool IsFPR = BaseTy->isFloatingPointTy() || BaseTy->isVectorTy(); 5813 5814 // The AArch64 va_list type and handling is specified in the Procedure Call 5815 // Standard, section B.4: 5816 // 5817 // struct { 5818 // void *__stack; 5819 // void *__gr_top; 5820 // void *__vr_top; 5821 // int __gr_offs; 5822 // int __vr_offs; 5823 // }; 5824 5825 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg"); 5826 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg"); 5827 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack"); 5828 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end"); 5829 5830 CharUnits TySize = getContext().getTypeSizeInChars(Ty); 5831 CharUnits TyAlign = getContext().getTypeUnadjustedAlignInChars(Ty); 5832 5833 Address reg_offs_p = Address::invalid(); 5834 llvm::Value *reg_offs = nullptr; 5835 int reg_top_index; 5836 int RegSize = IsIndirect ? 8 : TySize.getQuantity(); 5837 if (!IsFPR) { 5838 // 3 is the field number of __gr_offs 5839 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 3, "gr_offs_p"); 5840 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs"); 5841 reg_top_index = 1; // field number for __gr_top 5842 RegSize = llvm::alignTo(RegSize, 8); 5843 } else { 5844 // 4 is the field number of __vr_offs. 5845 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 4, "vr_offs_p"); 5846 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs"); 5847 reg_top_index = 2; // field number for __vr_top 5848 RegSize = 16 * NumRegs; 5849 } 5850 5851 //======================================= 5852 // Find out where argument was passed 5853 //======================================= 5854 5855 // If reg_offs >= 0 we're already using the stack for this type of 5856 // argument. We don't want to keep updating reg_offs (in case it overflows, 5857 // though anyone passing 2GB of arguments, each at most 16 bytes, deserves 5858 // whatever they get). 5859 llvm::Value *UsingStack = nullptr; 5860 UsingStack = CGF.Builder.CreateICmpSGE( 5861 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0)); 5862 5863 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock); 5864 5865 // Otherwise, at least some kind of argument could go in these registers, the 5866 // question is whether this particular type is too big. 5867 CGF.EmitBlock(MaybeRegBlock); 5868 5869 // Integer arguments may need to correct register alignment (for example a 5870 // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we 5871 // align __gr_offs to calculate the potential address. 5872 if (!IsFPR && !IsIndirect && TyAlign.getQuantity() > 8) { 5873 int Align = TyAlign.getQuantity(); 5874 5875 reg_offs = CGF.Builder.CreateAdd( 5876 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1), 5877 "align_regoffs"); 5878 reg_offs = CGF.Builder.CreateAnd( 5879 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align), 5880 "aligned_regoffs"); 5881 } 5882 5883 // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list. 5884 // The fact that this is done unconditionally reflects the fact that 5885 // allocating an argument to the stack also uses up all the remaining 5886 // registers of the appropriate kind. 5887 llvm::Value *NewOffset = nullptr; 5888 NewOffset = CGF.Builder.CreateAdd( 5889 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs"); 5890 CGF.Builder.CreateStore(NewOffset, reg_offs_p); 5891 5892 // Now we're in a position to decide whether this argument really was in 5893 // registers or not. 5894 llvm::Value *InRegs = nullptr; 5895 InRegs = CGF.Builder.CreateICmpSLE( 5896 NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg"); 5897 5898 CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock); 5899 5900 //======================================= 5901 // Argument was in registers 5902 //======================================= 5903 5904 // Now we emit the code for if the argument was originally passed in 5905 // registers. First start the appropriate block: 5906 CGF.EmitBlock(InRegBlock); 5907 5908 llvm::Value *reg_top = nullptr; 5909 Address reg_top_p = 5910 CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index, "reg_top_p"); 5911 reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top"); 5912 Address BaseAddr(CGF.Builder.CreateInBoundsGEP(reg_top, reg_offs), 5913 CharUnits::fromQuantity(IsFPR ? 16 : 8)); 5914 Address RegAddr = Address::invalid(); 5915 llvm::Type *MemTy = CGF.ConvertTypeForMem(Ty); 5916 5917 if (IsIndirect) { 5918 // If it's been passed indirectly (actually a struct), whatever we find from 5919 // stored registers or on the stack will actually be a struct **. 5920 MemTy = llvm::PointerType::getUnqual(MemTy); 5921 } 5922 5923 const Type *Base = nullptr; 5924 uint64_t NumMembers = 0; 5925 bool IsHFA = isHomogeneousAggregate(Ty, Base, NumMembers); 5926 if (IsHFA && NumMembers > 1) { 5927 // Homogeneous aggregates passed in registers will have their elements split 5928 // and stored 16-bytes apart regardless of size (they're notionally in qN, 5929 // qN+1, ...). We reload and store into a temporary local variable 5930 // contiguously. 5931 assert(!IsIndirect && "Homogeneous aggregates should be passed directly"); 5932 auto BaseTyInfo = getContext().getTypeInfoInChars(QualType(Base, 0)); 5933 llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0)); 5934 llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers); 5935 Address Tmp = CGF.CreateTempAlloca(HFATy, 5936 std::max(TyAlign, BaseTyInfo.second)); 5937 5938 // On big-endian platforms, the value will be right-aligned in its slot. 5939 int Offset = 0; 5940 if (CGF.CGM.getDataLayout().isBigEndian() && 5941 BaseTyInfo.first.getQuantity() < 16) 5942 Offset = 16 - BaseTyInfo.first.getQuantity(); 5943 5944 for (unsigned i = 0; i < NumMembers; ++i) { 5945 CharUnits BaseOffset = CharUnits::fromQuantity(16 * i + Offset); 5946 Address LoadAddr = 5947 CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, BaseOffset); 5948 LoadAddr = CGF.Builder.CreateElementBitCast(LoadAddr, BaseTy); 5949 5950 Address StoreAddr = CGF.Builder.CreateConstArrayGEP(Tmp, i); 5951 5952 llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr); 5953 CGF.Builder.CreateStore(Elem, StoreAddr); 5954 } 5955 5956 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, MemTy); 5957 } else { 5958 // Otherwise the object is contiguous in memory. 5959 5960 // It might be right-aligned in its slot. 5961 CharUnits SlotSize = BaseAddr.getAlignment(); 5962 if (CGF.CGM.getDataLayout().isBigEndian() && !IsIndirect && 5963 (IsHFA || !isAggregateTypeForABI(Ty)) && 5964 TySize < SlotSize) { 5965 CharUnits Offset = SlotSize - TySize; 5966 BaseAddr = CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, Offset); 5967 } 5968 5969 RegAddr = CGF.Builder.CreateElementBitCast(BaseAddr, MemTy); 5970 } 5971 5972 CGF.EmitBranch(ContBlock); 5973 5974 //======================================= 5975 // Argument was on the stack 5976 //======================================= 5977 CGF.EmitBlock(OnStackBlock); 5978 5979 Address stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "stack_p"); 5980 llvm::Value *OnStackPtr = CGF.Builder.CreateLoad(stack_p, "stack"); 5981 5982 // Again, stack arguments may need realignment. In this case both integer and 5983 // floating-point ones might be affected. 5984 if (!IsIndirect && TyAlign.getQuantity() > 8) { 5985 int Align = TyAlign.getQuantity(); 5986 5987 OnStackPtr = CGF.Builder.CreatePtrToInt(OnStackPtr, CGF.Int64Ty); 5988 5989 OnStackPtr = CGF.Builder.CreateAdd( 5990 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1), 5991 "align_stack"); 5992 OnStackPtr = CGF.Builder.CreateAnd( 5993 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, -Align), 5994 "align_stack"); 5995 5996 OnStackPtr = CGF.Builder.CreateIntToPtr(OnStackPtr, CGF.Int8PtrTy); 5997 } 5998 Address OnStackAddr(OnStackPtr, 5999 std::max(CharUnits::fromQuantity(8), TyAlign)); 6000 6001 // All stack slots are multiples of 8 bytes. 6002 CharUnits StackSlotSize = CharUnits::fromQuantity(8); 6003 CharUnits StackSize; 6004 if (IsIndirect) 6005 StackSize = StackSlotSize; 6006 else 6007 StackSize = TySize.alignTo(StackSlotSize); 6008 6009 llvm::Value *StackSizeC = CGF.Builder.getSize(StackSize); 6010 llvm::Value *NewStack = 6011 CGF.Builder.CreateInBoundsGEP(OnStackPtr, StackSizeC, "new_stack"); 6012 6013 // Write the new value of __stack for the next call to va_arg 6014 CGF.Builder.CreateStore(NewStack, stack_p); 6015 6016 if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) && 6017 TySize < StackSlotSize) { 6018 CharUnits Offset = StackSlotSize - TySize; 6019 OnStackAddr = CGF.Builder.CreateConstInBoundsByteGEP(OnStackAddr, Offset); 6020 } 6021 6022 OnStackAddr = CGF.Builder.CreateElementBitCast(OnStackAddr, MemTy); 6023 6024 CGF.EmitBranch(ContBlock); 6025 6026 //======================================= 6027 // Tidy up 6028 //======================================= 6029 CGF.EmitBlock(ContBlock); 6030 6031 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, 6032 OnStackAddr, OnStackBlock, "vaargs.addr"); 6033 6034 if (IsIndirect) 6035 return Address(CGF.Builder.CreateLoad(ResAddr, "vaarg.addr"), 6036 TyAlign); 6037 6038 return ResAddr; 6039 } 6040 6041 Address AArch64ABIInfo::EmitDarwinVAArg(Address VAListAddr, QualType Ty, 6042 CodeGenFunction &CGF) const { 6043 // The backend's lowering doesn't support va_arg for aggregates or 6044 // illegal vector types. Lower VAArg here for these cases and use 6045 // the LLVM va_arg instruction for everything else. 6046 if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty)) 6047 return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect()); 6048 6049 uint64_t PointerSize = getTarget().getPointerWidth(0) / 8; 6050 CharUnits SlotSize = CharUnits::fromQuantity(PointerSize); 6051 6052 // Empty records are ignored for parameter passing purposes. 6053 if (isEmptyRecord(getContext(), Ty, true)) { 6054 Address Addr(CGF.Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize); 6055 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty)); 6056 return Addr; 6057 } 6058 6059 // The size of the actual thing passed, which might end up just 6060 // being a pointer for indirect types. 6061 auto TyInfo = getContext().getTypeInfoInChars(Ty); 6062 6063 // Arguments bigger than 16 bytes which aren't homogeneous 6064 // aggregates should be passed indirectly. 6065 bool IsIndirect = false; 6066 if (TyInfo.first.getQuantity() > 16) { 6067 const Type *Base = nullptr; 6068 uint64_t Members = 0; 6069 IsIndirect = !isHomogeneousAggregate(Ty, Base, Members); 6070 } 6071 6072 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, 6073 TyInfo, SlotSize, /*AllowHigherAlign*/ true); 6074 } 6075 6076 Address AArch64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr, 6077 QualType Ty) const { 6078 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false, 6079 CGF.getContext().getTypeInfoInChars(Ty), 6080 CharUnits::fromQuantity(8), 6081 /*allowHigherAlign*/ false); 6082 } 6083 6084 //===----------------------------------------------------------------------===// 6085 // ARM ABI Implementation 6086 //===----------------------------------------------------------------------===// 6087 6088 namespace { 6089 6090 class ARMABIInfo : public SwiftABIInfo { 6091 public: 6092 enum ABIKind { 6093 APCS = 0, 6094 AAPCS = 1, 6095 AAPCS_VFP = 2, 6096 AAPCS16_VFP = 3, 6097 }; 6098 6099 private: 6100 ABIKind Kind; 6101 bool IsFloatABISoftFP; 6102 6103 public: 6104 ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind) 6105 : SwiftABIInfo(CGT), Kind(_Kind) { 6106 setCCs(); 6107 IsFloatABISoftFP = CGT.getCodeGenOpts().FloatABI == "softfp" || 6108 CGT.getCodeGenOpts().FloatABI == ""; // default 6109 } 6110 6111 bool isEABI() const { 6112 switch (getTarget().getTriple().getEnvironment()) { 6113 case llvm::Triple::Android: 6114 case llvm::Triple::EABI: 6115 case llvm::Triple::EABIHF: 6116 case llvm::Triple::GNUEABI: 6117 case llvm::Triple::GNUEABIHF: 6118 case llvm::Triple::MuslEABI: 6119 case llvm::Triple::MuslEABIHF: 6120 return true; 6121 default: 6122 return false; 6123 } 6124 } 6125 6126 bool isEABIHF() const { 6127 switch (getTarget().getTriple().getEnvironment()) { 6128 case llvm::Triple::EABIHF: 6129 case llvm::Triple::GNUEABIHF: 6130 case llvm::Triple::MuslEABIHF: 6131 return true; 6132 default: 6133 return false; 6134 } 6135 } 6136 6137 ABIKind getABIKind() const { return Kind; } 6138 6139 bool allowBFloatArgsAndRet() const override { 6140 return !IsFloatABISoftFP && getTarget().hasBFloat16Type(); 6141 } 6142 6143 private: 6144 ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic, 6145 unsigned functionCallConv) const; 6146 ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic, 6147 unsigned functionCallConv) const; 6148 ABIArgInfo classifyHomogeneousAggregate(QualType Ty, const Type *Base, 6149 uint64_t Members) const; 6150 ABIArgInfo coerceIllegalVector(QualType Ty) const; 6151 bool isIllegalVectorType(QualType Ty) const; 6152 bool containsAnyFP16Vectors(QualType Ty) const; 6153 6154 bool isHomogeneousAggregateBaseType(QualType Ty) const override; 6155 bool isHomogeneousAggregateSmallEnough(const Type *Ty, 6156 uint64_t Members) const override; 6157 6158 bool isEffectivelyAAPCS_VFP(unsigned callConvention, bool acceptHalf) const; 6159 6160 void computeInfo(CGFunctionInfo &FI) const override; 6161 6162 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 6163 QualType Ty) const override; 6164 6165 llvm::CallingConv::ID getLLVMDefaultCC() const; 6166 llvm::CallingConv::ID getABIDefaultCC() const; 6167 void setCCs(); 6168 6169 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars, 6170 bool asReturnValue) const override { 6171 return occupiesMoreThan(CGT, scalars, /*total*/ 4); 6172 } 6173 bool isSwiftErrorInRegister() const override { 6174 return true; 6175 } 6176 bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy, 6177 unsigned elts) const override; 6178 }; 6179 6180 class ARMTargetCodeGenInfo : public TargetCodeGenInfo { 6181 public: 6182 ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K) 6183 : TargetCodeGenInfo(std::make_unique<ARMABIInfo>(CGT, K)) {} 6184 6185 const ARMABIInfo &getABIInfo() const { 6186 return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo()); 6187 } 6188 6189 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 6190 return 13; 6191 } 6192 6193 StringRef getARCRetainAutoreleasedReturnValueMarker() const override { 6194 return "mov\tr7, r7\t\t// marker for objc_retainAutoreleaseReturnValue"; 6195 } 6196 6197 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 6198 llvm::Value *Address) const override { 6199 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4); 6200 6201 // 0-15 are the 16 integer registers. 6202 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15); 6203 return false; 6204 } 6205 6206 unsigned getSizeOfUnwindException() const override { 6207 if (getABIInfo().isEABI()) return 88; 6208 return TargetCodeGenInfo::getSizeOfUnwindException(); 6209 } 6210 6211 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 6212 CodeGen::CodeGenModule &CGM) const override { 6213 if (GV->isDeclaration()) 6214 return; 6215 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D); 6216 if (!FD) 6217 return; 6218 6219 const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>(); 6220 if (!Attr) 6221 return; 6222 6223 const char *Kind; 6224 switch (Attr->getInterrupt()) { 6225 case ARMInterruptAttr::Generic: Kind = ""; break; 6226 case ARMInterruptAttr::IRQ: Kind = "IRQ"; break; 6227 case ARMInterruptAttr::FIQ: Kind = "FIQ"; break; 6228 case ARMInterruptAttr::SWI: Kind = "SWI"; break; 6229 case ARMInterruptAttr::ABORT: Kind = "ABORT"; break; 6230 case ARMInterruptAttr::UNDEF: Kind = "UNDEF"; break; 6231 } 6232 6233 llvm::Function *Fn = cast<llvm::Function>(GV); 6234 6235 Fn->addFnAttr("interrupt", Kind); 6236 6237 ARMABIInfo::ABIKind ABI = cast<ARMABIInfo>(getABIInfo()).getABIKind(); 6238 if (ABI == ARMABIInfo::APCS) 6239 return; 6240 6241 // AAPCS guarantees that sp will be 8-byte aligned on any public interface, 6242 // however this is not necessarily true on taking any interrupt. Instruct 6243 // the backend to perform a realignment as part of the function prologue. 6244 llvm::AttrBuilder B; 6245 B.addStackAlignmentAttr(8); 6246 Fn->addAttributes(llvm::AttributeList::FunctionIndex, B); 6247 } 6248 }; 6249 6250 class WindowsARMTargetCodeGenInfo : public ARMTargetCodeGenInfo { 6251 public: 6252 WindowsARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K) 6253 : ARMTargetCodeGenInfo(CGT, K) {} 6254 6255 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 6256 CodeGen::CodeGenModule &CGM) const override; 6257 6258 void getDependentLibraryOption(llvm::StringRef Lib, 6259 llvm::SmallString<24> &Opt) const override { 6260 Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib); 6261 } 6262 6263 void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value, 6264 llvm::SmallString<32> &Opt) const override { 6265 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\""; 6266 } 6267 }; 6268 6269 void WindowsARMTargetCodeGenInfo::setTargetAttributes( 6270 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const { 6271 ARMTargetCodeGenInfo::setTargetAttributes(D, GV, CGM); 6272 if (GV->isDeclaration()) 6273 return; 6274 addStackProbeTargetAttributes(D, GV, CGM); 6275 } 6276 } 6277 6278 void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const { 6279 if (!::classifyReturnType(getCXXABI(), FI, *this)) 6280 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), FI.isVariadic(), 6281 FI.getCallingConvention()); 6282 6283 for (auto &I : FI.arguments()) 6284 I.info = classifyArgumentType(I.type, FI.isVariadic(), 6285 FI.getCallingConvention()); 6286 6287 6288 // Always honor user-specified calling convention. 6289 if (FI.getCallingConvention() != llvm::CallingConv::C) 6290 return; 6291 6292 llvm::CallingConv::ID cc = getRuntimeCC(); 6293 if (cc != llvm::CallingConv::C) 6294 FI.setEffectiveCallingConvention(cc); 6295 } 6296 6297 /// Return the default calling convention that LLVM will use. 6298 llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const { 6299 // The default calling convention that LLVM will infer. 6300 if (isEABIHF() || getTarget().getTriple().isWatchABI()) 6301 return llvm::CallingConv::ARM_AAPCS_VFP; 6302 else if (isEABI()) 6303 return llvm::CallingConv::ARM_AAPCS; 6304 else 6305 return llvm::CallingConv::ARM_APCS; 6306 } 6307 6308 /// Return the calling convention that our ABI would like us to use 6309 /// as the C calling convention. 6310 llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const { 6311 switch (getABIKind()) { 6312 case APCS: return llvm::CallingConv::ARM_APCS; 6313 case AAPCS: return llvm::CallingConv::ARM_AAPCS; 6314 case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP; 6315 case AAPCS16_VFP: return llvm::CallingConv::ARM_AAPCS_VFP; 6316 } 6317 llvm_unreachable("bad ABI kind"); 6318 } 6319 6320 void ARMABIInfo::setCCs() { 6321 assert(getRuntimeCC() == llvm::CallingConv::C); 6322 6323 // Don't muddy up the IR with a ton of explicit annotations if 6324 // they'd just match what LLVM will infer from the triple. 6325 llvm::CallingConv::ID abiCC = getABIDefaultCC(); 6326 if (abiCC != getLLVMDefaultCC()) 6327 RuntimeCC = abiCC; 6328 } 6329 6330 ABIArgInfo ARMABIInfo::coerceIllegalVector(QualType Ty) const { 6331 uint64_t Size = getContext().getTypeSize(Ty); 6332 if (Size <= 32) { 6333 llvm::Type *ResType = 6334 llvm::Type::getInt32Ty(getVMContext()); 6335 return ABIArgInfo::getDirect(ResType); 6336 } 6337 if (Size == 64 || Size == 128) { 6338 auto *ResType = llvm::FixedVectorType::get( 6339 llvm::Type::getInt32Ty(getVMContext()), Size / 32); 6340 return ABIArgInfo::getDirect(ResType); 6341 } 6342 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 6343 } 6344 6345 ABIArgInfo ARMABIInfo::classifyHomogeneousAggregate(QualType Ty, 6346 const Type *Base, 6347 uint64_t Members) const { 6348 assert(Base && "Base class should be set for homogeneous aggregate"); 6349 // Base can be a floating-point or a vector. 6350 if (const VectorType *VT = Base->getAs<VectorType>()) { 6351 // FP16 vectors should be converted to integer vectors 6352 if (!getTarget().hasLegalHalfType() && containsAnyFP16Vectors(Ty)) { 6353 uint64_t Size = getContext().getTypeSize(VT); 6354 auto *NewVecTy = llvm::FixedVectorType::get( 6355 llvm::Type::getInt32Ty(getVMContext()), Size / 32); 6356 llvm::Type *Ty = llvm::ArrayType::get(NewVecTy, Members); 6357 return ABIArgInfo::getDirect(Ty, 0, nullptr, false); 6358 } 6359 } 6360 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false); 6361 } 6362 6363 ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty, bool isVariadic, 6364 unsigned functionCallConv) const { 6365 // 6.1.2.1 The following argument types are VFP CPRCs: 6366 // A single-precision floating-point type (including promoted 6367 // half-precision types); A double-precision floating-point type; 6368 // A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate 6369 // with a Base Type of a single- or double-precision floating-point type, 6370 // 64-bit containerized vectors or 128-bit containerized vectors with one 6371 // to four Elements. 6372 // Variadic functions should always marshal to the base standard. 6373 bool IsAAPCS_VFP = 6374 !isVariadic && isEffectivelyAAPCS_VFP(functionCallConv, /* AAPCS16 */ false); 6375 6376 Ty = useFirstFieldIfTransparentUnion(Ty); 6377 6378 // Handle illegal vector types here. 6379 if (isIllegalVectorType(Ty)) 6380 return coerceIllegalVector(Ty); 6381 6382 if (!isAggregateTypeForABI(Ty)) { 6383 // Treat an enum type as its underlying type. 6384 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) { 6385 Ty = EnumTy->getDecl()->getIntegerType(); 6386 } 6387 6388 if (const auto *EIT = Ty->getAs<ExtIntType>()) 6389 if (EIT->getNumBits() > 64) 6390 return getNaturalAlignIndirect(Ty, /*ByVal=*/true); 6391 6392 return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty) 6393 : ABIArgInfo::getDirect()); 6394 } 6395 6396 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) { 6397 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 6398 } 6399 6400 // Ignore empty records. 6401 if (isEmptyRecord(getContext(), Ty, true)) 6402 return ABIArgInfo::getIgnore(); 6403 6404 if (IsAAPCS_VFP) { 6405 // Homogeneous Aggregates need to be expanded when we can fit the aggregate 6406 // into VFP registers. 6407 const Type *Base = nullptr; 6408 uint64_t Members = 0; 6409 if (isHomogeneousAggregate(Ty, Base, Members)) 6410 return classifyHomogeneousAggregate(Ty, Base, Members); 6411 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) { 6412 // WatchOS does have homogeneous aggregates. Note that we intentionally use 6413 // this convention even for a variadic function: the backend will use GPRs 6414 // if needed. 6415 const Type *Base = nullptr; 6416 uint64_t Members = 0; 6417 if (isHomogeneousAggregate(Ty, Base, Members)) { 6418 assert(Base && Members <= 4 && "unexpected homogeneous aggregate"); 6419 llvm::Type *Ty = 6420 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members); 6421 return ABIArgInfo::getDirect(Ty, 0, nullptr, false); 6422 } 6423 } 6424 6425 if (getABIKind() == ARMABIInfo::AAPCS16_VFP && 6426 getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(16)) { 6427 // WatchOS is adopting the 64-bit AAPCS rule on composite types: if they're 6428 // bigger than 128-bits, they get placed in space allocated by the caller, 6429 // and a pointer is passed. 6430 return ABIArgInfo::getIndirect( 6431 CharUnits::fromQuantity(getContext().getTypeAlign(Ty) / 8), false); 6432 } 6433 6434 // Support byval for ARM. 6435 // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at 6436 // most 8-byte. We realign the indirect argument if type alignment is bigger 6437 // than ABI alignment. 6438 uint64_t ABIAlign = 4; 6439 uint64_t TyAlign; 6440 if (getABIKind() == ARMABIInfo::AAPCS_VFP || 6441 getABIKind() == ARMABIInfo::AAPCS) { 6442 TyAlign = getContext().getTypeUnadjustedAlignInChars(Ty).getQuantity(); 6443 ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8); 6444 } else { 6445 TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity(); 6446 } 6447 if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) { 6448 assert(getABIKind() != ARMABIInfo::AAPCS16_VFP && "unexpected byval"); 6449 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign), 6450 /*ByVal=*/true, 6451 /*Realign=*/TyAlign > ABIAlign); 6452 } 6453 6454 // On RenderScript, coerce Aggregates <= 64 bytes to an integer array of 6455 // same size and alignment. 6456 if (getTarget().isRenderScriptTarget()) { 6457 return coerceToIntArray(Ty, getContext(), getVMContext()); 6458 } 6459 6460 // Otherwise, pass by coercing to a structure of the appropriate size. 6461 llvm::Type* ElemTy; 6462 unsigned SizeRegs; 6463 // FIXME: Try to match the types of the arguments more accurately where 6464 // we can. 6465 if (TyAlign <= 4) { 6466 ElemTy = llvm::Type::getInt32Ty(getVMContext()); 6467 SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32; 6468 } else { 6469 ElemTy = llvm::Type::getInt64Ty(getVMContext()); 6470 SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64; 6471 } 6472 6473 return ABIArgInfo::getDirect(llvm::ArrayType::get(ElemTy, SizeRegs)); 6474 } 6475 6476 static bool isIntegerLikeType(QualType Ty, ASTContext &Context, 6477 llvm::LLVMContext &VMContext) { 6478 // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure 6479 // is called integer-like if its size is less than or equal to one word, and 6480 // the offset of each of its addressable sub-fields is zero. 6481 6482 uint64_t Size = Context.getTypeSize(Ty); 6483 6484 // Check that the type fits in a word. 6485 if (Size > 32) 6486 return false; 6487 6488 // FIXME: Handle vector types! 6489 if (Ty->isVectorType()) 6490 return false; 6491 6492 // Float types are never treated as "integer like". 6493 if (Ty->isRealFloatingType()) 6494 return false; 6495 6496 // If this is a builtin or pointer type then it is ok. 6497 if (Ty->getAs<BuiltinType>() || Ty->isPointerType()) 6498 return true; 6499 6500 // Small complex integer types are "integer like". 6501 if (const ComplexType *CT = Ty->getAs<ComplexType>()) 6502 return isIntegerLikeType(CT->getElementType(), Context, VMContext); 6503 6504 // Single element and zero sized arrays should be allowed, by the definition 6505 // above, but they are not. 6506 6507 // Otherwise, it must be a record type. 6508 const RecordType *RT = Ty->getAs<RecordType>(); 6509 if (!RT) return false; 6510 6511 // Ignore records with flexible arrays. 6512 const RecordDecl *RD = RT->getDecl(); 6513 if (RD->hasFlexibleArrayMember()) 6514 return false; 6515 6516 // Check that all sub-fields are at offset 0, and are themselves "integer 6517 // like". 6518 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); 6519 6520 bool HadField = false; 6521 unsigned idx = 0; 6522 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 6523 i != e; ++i, ++idx) { 6524 const FieldDecl *FD = *i; 6525 6526 // Bit-fields are not addressable, we only need to verify they are "integer 6527 // like". We still have to disallow a subsequent non-bitfield, for example: 6528 // struct { int : 0; int x } 6529 // is non-integer like according to gcc. 6530 if (FD->isBitField()) { 6531 if (!RD->isUnion()) 6532 HadField = true; 6533 6534 if (!isIntegerLikeType(FD->getType(), Context, VMContext)) 6535 return false; 6536 6537 continue; 6538 } 6539 6540 // Check if this field is at offset 0. 6541 if (Layout.getFieldOffset(idx) != 0) 6542 return false; 6543 6544 if (!isIntegerLikeType(FD->getType(), Context, VMContext)) 6545 return false; 6546 6547 // Only allow at most one field in a structure. This doesn't match the 6548 // wording above, but follows gcc in situations with a field following an 6549 // empty structure. 6550 if (!RD->isUnion()) { 6551 if (HadField) 6552 return false; 6553 6554 HadField = true; 6555 } 6556 } 6557 6558 return true; 6559 } 6560 6561 ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy, bool isVariadic, 6562 unsigned functionCallConv) const { 6563 6564 // Variadic functions should always marshal to the base standard. 6565 bool IsAAPCS_VFP = 6566 !isVariadic && isEffectivelyAAPCS_VFP(functionCallConv, /* AAPCS16 */ true); 6567 6568 if (RetTy->isVoidType()) 6569 return ABIArgInfo::getIgnore(); 6570 6571 if (const VectorType *VT = RetTy->getAs<VectorType>()) { 6572 // Large vector types should be returned via memory. 6573 if (getContext().getTypeSize(RetTy) > 128) 6574 return getNaturalAlignIndirect(RetTy); 6575 // TODO: FP16/BF16 vectors should be converted to integer vectors 6576 // This check is similar to isIllegalVectorType - refactor? 6577 if ((!getTarget().hasLegalHalfType() && 6578 (VT->getElementType()->isFloat16Type() || 6579 VT->getElementType()->isHalfType())) || 6580 (IsFloatABISoftFP && 6581 VT->getElementType()->isBFloat16Type())) 6582 return coerceIllegalVector(RetTy); 6583 } 6584 6585 if (!isAggregateTypeForABI(RetTy)) { 6586 // Treat an enum type as its underlying type. 6587 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 6588 RetTy = EnumTy->getDecl()->getIntegerType(); 6589 6590 if (const auto *EIT = RetTy->getAs<ExtIntType>()) 6591 if (EIT->getNumBits() > 64) 6592 return getNaturalAlignIndirect(RetTy, /*ByVal=*/false); 6593 6594 return isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy) 6595 : ABIArgInfo::getDirect(); 6596 } 6597 6598 // Are we following APCS? 6599 if (getABIKind() == APCS) { 6600 if (isEmptyRecord(getContext(), RetTy, false)) 6601 return ABIArgInfo::getIgnore(); 6602 6603 // Complex types are all returned as packed integers. 6604 // 6605 // FIXME: Consider using 2 x vector types if the back end handles them 6606 // correctly. 6607 if (RetTy->isAnyComplexType()) 6608 return ABIArgInfo::getDirect(llvm::IntegerType::get( 6609 getVMContext(), getContext().getTypeSize(RetTy))); 6610 6611 // Integer like structures are returned in r0. 6612 if (isIntegerLikeType(RetTy, getContext(), getVMContext())) { 6613 // Return in the smallest viable integer type. 6614 uint64_t Size = getContext().getTypeSize(RetTy); 6615 if (Size <= 8) 6616 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext())); 6617 if (Size <= 16) 6618 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext())); 6619 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext())); 6620 } 6621 6622 // Otherwise return in memory. 6623 return getNaturalAlignIndirect(RetTy); 6624 } 6625 6626 // Otherwise this is an AAPCS variant. 6627 6628 if (isEmptyRecord(getContext(), RetTy, true)) 6629 return ABIArgInfo::getIgnore(); 6630 6631 // Check for homogeneous aggregates with AAPCS-VFP. 6632 if (IsAAPCS_VFP) { 6633 const Type *Base = nullptr; 6634 uint64_t Members = 0; 6635 if (isHomogeneousAggregate(RetTy, Base, Members)) 6636 return classifyHomogeneousAggregate(RetTy, Base, Members); 6637 } 6638 6639 // Aggregates <= 4 bytes are returned in r0; other aggregates 6640 // are returned indirectly. 6641 uint64_t Size = getContext().getTypeSize(RetTy); 6642 if (Size <= 32) { 6643 // On RenderScript, coerce Aggregates <= 4 bytes to an integer array of 6644 // same size and alignment. 6645 if (getTarget().isRenderScriptTarget()) { 6646 return coerceToIntArray(RetTy, getContext(), getVMContext()); 6647 } 6648 if (getDataLayout().isBigEndian()) 6649 // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4) 6650 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext())); 6651 6652 // Return in the smallest viable integer type. 6653 if (Size <= 8) 6654 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext())); 6655 if (Size <= 16) 6656 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext())); 6657 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext())); 6658 } else if (Size <= 128 && getABIKind() == AAPCS16_VFP) { 6659 llvm::Type *Int32Ty = llvm::Type::getInt32Ty(getVMContext()); 6660 llvm::Type *CoerceTy = 6661 llvm::ArrayType::get(Int32Ty, llvm::alignTo(Size, 32) / 32); 6662 return ABIArgInfo::getDirect(CoerceTy); 6663 } 6664 6665 return getNaturalAlignIndirect(RetTy); 6666 } 6667 6668 /// isIllegalVector - check whether Ty is an illegal vector type. 6669 bool ARMABIInfo::isIllegalVectorType(QualType Ty) const { 6670 if (const VectorType *VT = Ty->getAs<VectorType> ()) { 6671 // On targets that don't support half, fp16 or bfloat, they are expanded 6672 // into float, and we don't want the ABI to depend on whether or not they 6673 // are supported in hardware. Thus return false to coerce vectors of these 6674 // types into integer vectors. 6675 // We do not depend on hasLegalHalfType for bfloat as it is a 6676 // separate IR type. 6677 if ((!getTarget().hasLegalHalfType() && 6678 (VT->getElementType()->isFloat16Type() || 6679 VT->getElementType()->isHalfType())) || 6680 (IsFloatABISoftFP && 6681 VT->getElementType()->isBFloat16Type())) 6682 return true; 6683 if (isAndroid()) { 6684 // Android shipped using Clang 3.1, which supported a slightly different 6685 // vector ABI. The primary differences were that 3-element vector types 6686 // were legal, and so were sub 32-bit vectors (i.e. <2 x i8>). This path 6687 // accepts that legacy behavior for Android only. 6688 // Check whether VT is legal. 6689 unsigned NumElements = VT->getNumElements(); 6690 // NumElements should be power of 2 or equal to 3. 6691 if (!llvm::isPowerOf2_32(NumElements) && NumElements != 3) 6692 return true; 6693 } else { 6694 // Check whether VT is legal. 6695 unsigned NumElements = VT->getNumElements(); 6696 uint64_t Size = getContext().getTypeSize(VT); 6697 // NumElements should be power of 2. 6698 if (!llvm::isPowerOf2_32(NumElements)) 6699 return true; 6700 // Size should be greater than 32 bits. 6701 return Size <= 32; 6702 } 6703 } 6704 return false; 6705 } 6706 6707 /// Return true if a type contains any 16-bit floating point vectors 6708 bool ARMABIInfo::containsAnyFP16Vectors(QualType Ty) const { 6709 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) { 6710 uint64_t NElements = AT->getSize().getZExtValue(); 6711 if (NElements == 0) 6712 return false; 6713 return containsAnyFP16Vectors(AT->getElementType()); 6714 } else if (const RecordType *RT = Ty->getAs<RecordType>()) { 6715 const RecordDecl *RD = RT->getDecl(); 6716 6717 // If this is a C++ record, check the bases first. 6718 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 6719 if (llvm::any_of(CXXRD->bases(), [this](const CXXBaseSpecifier &B) { 6720 return containsAnyFP16Vectors(B.getType()); 6721 })) 6722 return true; 6723 6724 if (llvm::any_of(RD->fields(), [this](FieldDecl *FD) { 6725 return FD && containsAnyFP16Vectors(FD->getType()); 6726 })) 6727 return true; 6728 6729 return false; 6730 } else { 6731 if (const VectorType *VT = Ty->getAs<VectorType>()) 6732 return (VT->getElementType()->isFloat16Type() || 6733 VT->getElementType()->isBFloat16Type() || 6734 VT->getElementType()->isHalfType()); 6735 return false; 6736 } 6737 } 6738 6739 bool ARMABIInfo::isLegalVectorTypeForSwift(CharUnits vectorSize, 6740 llvm::Type *eltTy, 6741 unsigned numElts) const { 6742 if (!llvm::isPowerOf2_32(numElts)) 6743 return false; 6744 unsigned size = getDataLayout().getTypeStoreSizeInBits(eltTy); 6745 if (size > 64) 6746 return false; 6747 if (vectorSize.getQuantity() != 8 && 6748 (vectorSize.getQuantity() != 16 || numElts == 1)) 6749 return false; 6750 return true; 6751 } 6752 6753 bool ARMABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const { 6754 // Homogeneous aggregates for AAPCS-VFP must have base types of float, 6755 // double, or 64-bit or 128-bit vectors. 6756 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) { 6757 if (BT->getKind() == BuiltinType::Float || 6758 BT->getKind() == BuiltinType::Double || 6759 BT->getKind() == BuiltinType::LongDouble) 6760 return true; 6761 } else if (const VectorType *VT = Ty->getAs<VectorType>()) { 6762 unsigned VecSize = getContext().getTypeSize(VT); 6763 if (VecSize == 64 || VecSize == 128) 6764 return true; 6765 } 6766 return false; 6767 } 6768 6769 bool ARMABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base, 6770 uint64_t Members) const { 6771 return Members <= 4; 6772 } 6773 6774 bool ARMABIInfo::isEffectivelyAAPCS_VFP(unsigned callConvention, 6775 bool acceptHalf) const { 6776 // Give precedence to user-specified calling conventions. 6777 if (callConvention != llvm::CallingConv::C) 6778 return (callConvention == llvm::CallingConv::ARM_AAPCS_VFP); 6779 else 6780 return (getABIKind() == AAPCS_VFP) || 6781 (acceptHalf && (getABIKind() == AAPCS16_VFP)); 6782 } 6783 6784 Address ARMABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 6785 QualType Ty) const { 6786 CharUnits SlotSize = CharUnits::fromQuantity(4); 6787 6788 // Empty records are ignored for parameter passing purposes. 6789 if (isEmptyRecord(getContext(), Ty, true)) { 6790 Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize); 6791 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty)); 6792 return Addr; 6793 } 6794 6795 CharUnits TySize = getContext().getTypeSizeInChars(Ty); 6796 CharUnits TyAlignForABI = getContext().getTypeUnadjustedAlignInChars(Ty); 6797 6798 // Use indirect if size of the illegal vector is bigger than 16 bytes. 6799 bool IsIndirect = false; 6800 const Type *Base = nullptr; 6801 uint64_t Members = 0; 6802 if (TySize > CharUnits::fromQuantity(16) && isIllegalVectorType(Ty)) { 6803 IsIndirect = true; 6804 6805 // ARMv7k passes structs bigger than 16 bytes indirectly, in space 6806 // allocated by the caller. 6807 } else if (TySize > CharUnits::fromQuantity(16) && 6808 getABIKind() == ARMABIInfo::AAPCS16_VFP && 6809 !isHomogeneousAggregate(Ty, Base, Members)) { 6810 IsIndirect = true; 6811 6812 // Otherwise, bound the type's ABI alignment. 6813 // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for 6814 // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte. 6815 // Our callers should be prepared to handle an under-aligned address. 6816 } else if (getABIKind() == ARMABIInfo::AAPCS_VFP || 6817 getABIKind() == ARMABIInfo::AAPCS) { 6818 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4)); 6819 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(8)); 6820 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) { 6821 // ARMv7k allows type alignment up to 16 bytes. 6822 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4)); 6823 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(16)); 6824 } else { 6825 TyAlignForABI = CharUnits::fromQuantity(4); 6826 } 6827 6828 std::pair<CharUnits, CharUnits> TyInfo = { TySize, TyAlignForABI }; 6829 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TyInfo, 6830 SlotSize, /*AllowHigherAlign*/ true); 6831 } 6832 6833 //===----------------------------------------------------------------------===// 6834 // NVPTX ABI Implementation 6835 //===----------------------------------------------------------------------===// 6836 6837 namespace { 6838 6839 class NVPTXTargetCodeGenInfo; 6840 6841 class NVPTXABIInfo : public ABIInfo { 6842 NVPTXTargetCodeGenInfo &CGInfo; 6843 6844 public: 6845 NVPTXABIInfo(CodeGenTypes &CGT, NVPTXTargetCodeGenInfo &Info) 6846 : ABIInfo(CGT), CGInfo(Info) {} 6847 6848 ABIArgInfo classifyReturnType(QualType RetTy) const; 6849 ABIArgInfo classifyArgumentType(QualType Ty) const; 6850 6851 void computeInfo(CGFunctionInfo &FI) const override; 6852 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 6853 QualType Ty) const override; 6854 bool isUnsupportedType(QualType T) const; 6855 ABIArgInfo coerceToIntArrayWithLimit(QualType Ty, unsigned MaxSize) const; 6856 }; 6857 6858 class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo { 6859 public: 6860 NVPTXTargetCodeGenInfo(CodeGenTypes &CGT) 6861 : TargetCodeGenInfo(std::make_unique<NVPTXABIInfo>(CGT, *this)) {} 6862 6863 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 6864 CodeGen::CodeGenModule &M) const override; 6865 bool shouldEmitStaticExternCAliases() const override; 6866 6867 llvm::Type *getCUDADeviceBuiltinSurfaceDeviceType() const override { 6868 // On the device side, surface reference is represented as an object handle 6869 // in 64-bit integer. 6870 return llvm::Type::getInt64Ty(getABIInfo().getVMContext()); 6871 } 6872 6873 llvm::Type *getCUDADeviceBuiltinTextureDeviceType() const override { 6874 // On the device side, texture reference is represented as an object handle 6875 // in 64-bit integer. 6876 return llvm::Type::getInt64Ty(getABIInfo().getVMContext()); 6877 } 6878 6879 bool emitCUDADeviceBuiltinSurfaceDeviceCopy(CodeGenFunction &CGF, LValue Dst, 6880 LValue Src) const override { 6881 emitBuiltinSurfTexDeviceCopy(CGF, Dst, Src); 6882 return true; 6883 } 6884 6885 bool emitCUDADeviceBuiltinTextureDeviceCopy(CodeGenFunction &CGF, LValue Dst, 6886 LValue Src) const override { 6887 emitBuiltinSurfTexDeviceCopy(CGF, Dst, Src); 6888 return true; 6889 } 6890 6891 private: 6892 // Adds a NamedMDNode with GV, Name, and Operand as operands, and adds the 6893 // resulting MDNode to the nvvm.annotations MDNode. 6894 static void addNVVMMetadata(llvm::GlobalValue *GV, StringRef Name, 6895 int Operand); 6896 6897 static void emitBuiltinSurfTexDeviceCopy(CodeGenFunction &CGF, LValue Dst, 6898 LValue Src) { 6899 llvm::Value *Handle = nullptr; 6900 llvm::Constant *C = 6901 llvm::dyn_cast<llvm::Constant>(Src.getAddress(CGF).getPointer()); 6902 // Lookup `addrspacecast` through the constant pointer if any. 6903 if (auto *ASC = llvm::dyn_cast_or_null<llvm::AddrSpaceCastOperator>(C)) 6904 C = llvm::cast<llvm::Constant>(ASC->getPointerOperand()); 6905 if (auto *GV = llvm::dyn_cast_or_null<llvm::GlobalVariable>(C)) { 6906 // Load the handle from the specific global variable using 6907 // `nvvm.texsurf.handle.internal` intrinsic. 6908 Handle = CGF.EmitRuntimeCall( 6909 CGF.CGM.getIntrinsic(llvm::Intrinsic::nvvm_texsurf_handle_internal, 6910 {GV->getType()}), 6911 {GV}, "texsurf_handle"); 6912 } else 6913 Handle = CGF.EmitLoadOfScalar(Src, SourceLocation()); 6914 CGF.EmitStoreOfScalar(Handle, Dst); 6915 } 6916 }; 6917 6918 /// Checks if the type is unsupported directly by the current target. 6919 bool NVPTXABIInfo::isUnsupportedType(QualType T) const { 6920 ASTContext &Context = getContext(); 6921 if (!Context.getTargetInfo().hasFloat16Type() && T->isFloat16Type()) 6922 return true; 6923 if (!Context.getTargetInfo().hasFloat128Type() && 6924 (T->isFloat128Type() || 6925 (T->isRealFloatingType() && Context.getTypeSize(T) == 128))) 6926 return true; 6927 if (const auto *EIT = T->getAs<ExtIntType>()) 6928 return EIT->getNumBits() > 6929 (Context.getTargetInfo().hasInt128Type() ? 128U : 64U); 6930 if (!Context.getTargetInfo().hasInt128Type() && T->isIntegerType() && 6931 Context.getTypeSize(T) > 64U) 6932 return true; 6933 if (const auto *AT = T->getAsArrayTypeUnsafe()) 6934 return isUnsupportedType(AT->getElementType()); 6935 const auto *RT = T->getAs<RecordType>(); 6936 if (!RT) 6937 return false; 6938 const RecordDecl *RD = RT->getDecl(); 6939 6940 // If this is a C++ record, check the bases first. 6941 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 6942 for (const CXXBaseSpecifier &I : CXXRD->bases()) 6943 if (isUnsupportedType(I.getType())) 6944 return true; 6945 6946 for (const FieldDecl *I : RD->fields()) 6947 if (isUnsupportedType(I->getType())) 6948 return true; 6949 return false; 6950 } 6951 6952 /// Coerce the given type into an array with maximum allowed size of elements. 6953 ABIArgInfo NVPTXABIInfo::coerceToIntArrayWithLimit(QualType Ty, 6954 unsigned MaxSize) const { 6955 // Alignment and Size are measured in bits. 6956 const uint64_t Size = getContext().getTypeSize(Ty); 6957 const uint64_t Alignment = getContext().getTypeAlign(Ty); 6958 const unsigned Div = std::min<unsigned>(MaxSize, Alignment); 6959 llvm::Type *IntType = llvm::Type::getIntNTy(getVMContext(), Div); 6960 const uint64_t NumElements = (Size + Div - 1) / Div; 6961 return ABIArgInfo::getDirect(llvm::ArrayType::get(IntType, NumElements)); 6962 } 6963 6964 ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const { 6965 if (RetTy->isVoidType()) 6966 return ABIArgInfo::getIgnore(); 6967 6968 if (getContext().getLangOpts().OpenMP && 6969 getContext().getLangOpts().OpenMPIsDevice && isUnsupportedType(RetTy)) 6970 return coerceToIntArrayWithLimit(RetTy, 64); 6971 6972 // note: this is different from default ABI 6973 if (!RetTy->isScalarType()) 6974 return ABIArgInfo::getDirect(); 6975 6976 // Treat an enum type as its underlying type. 6977 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 6978 RetTy = EnumTy->getDecl()->getIntegerType(); 6979 6980 return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy) 6981 : ABIArgInfo::getDirect()); 6982 } 6983 6984 ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const { 6985 // Treat an enum type as its underlying type. 6986 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 6987 Ty = EnumTy->getDecl()->getIntegerType(); 6988 6989 // Return aggregates type as indirect by value 6990 if (isAggregateTypeForABI(Ty)) { 6991 // Under CUDA device compilation, tex/surf builtin types are replaced with 6992 // object types and passed directly. 6993 if (getContext().getLangOpts().CUDAIsDevice) { 6994 if (Ty->isCUDADeviceBuiltinSurfaceType()) 6995 return ABIArgInfo::getDirect( 6996 CGInfo.getCUDADeviceBuiltinSurfaceDeviceType()); 6997 if (Ty->isCUDADeviceBuiltinTextureType()) 6998 return ABIArgInfo::getDirect( 6999 CGInfo.getCUDADeviceBuiltinTextureDeviceType()); 7000 } 7001 return getNaturalAlignIndirect(Ty, /* byval */ true); 7002 } 7003 7004 if (const auto *EIT = Ty->getAs<ExtIntType>()) { 7005 if ((EIT->getNumBits() > 128) || 7006 (!getContext().getTargetInfo().hasInt128Type() && 7007 EIT->getNumBits() > 64)) 7008 return getNaturalAlignIndirect(Ty, /* byval */ true); 7009 } 7010 7011 return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty) 7012 : ABIArgInfo::getDirect()); 7013 } 7014 7015 void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const { 7016 if (!getCXXABI().classifyReturnType(FI)) 7017 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 7018 for (auto &I : FI.arguments()) 7019 I.info = classifyArgumentType(I.type); 7020 7021 // Always honor user-specified calling convention. 7022 if (FI.getCallingConvention() != llvm::CallingConv::C) 7023 return; 7024 7025 FI.setEffectiveCallingConvention(getRuntimeCC()); 7026 } 7027 7028 Address NVPTXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 7029 QualType Ty) const { 7030 llvm_unreachable("NVPTX does not support varargs"); 7031 } 7032 7033 void NVPTXTargetCodeGenInfo::setTargetAttributes( 7034 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const { 7035 if (GV->isDeclaration()) 7036 return; 7037 const VarDecl *VD = dyn_cast_or_null<VarDecl>(D); 7038 if (VD) { 7039 if (M.getLangOpts().CUDA) { 7040 if (VD->getType()->isCUDADeviceBuiltinSurfaceType()) 7041 addNVVMMetadata(GV, "surface", 1); 7042 else if (VD->getType()->isCUDADeviceBuiltinTextureType()) 7043 addNVVMMetadata(GV, "texture", 1); 7044 return; 7045 } 7046 } 7047 7048 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D); 7049 if (!FD) return; 7050 7051 llvm::Function *F = cast<llvm::Function>(GV); 7052 7053 // Perform special handling in OpenCL mode 7054 if (M.getLangOpts().OpenCL) { 7055 // Use OpenCL function attributes to check for kernel functions 7056 // By default, all functions are device functions 7057 if (FD->hasAttr<OpenCLKernelAttr>()) { 7058 // OpenCL __kernel functions get kernel metadata 7059 // Create !{<func-ref>, metadata !"kernel", i32 1} node 7060 addNVVMMetadata(F, "kernel", 1); 7061 // And kernel functions are not subject to inlining 7062 F->addFnAttr(llvm::Attribute::NoInline); 7063 } 7064 } 7065 7066 // Perform special handling in CUDA mode. 7067 if (M.getLangOpts().CUDA) { 7068 // CUDA __global__ functions get a kernel metadata entry. Since 7069 // __global__ functions cannot be called from the device, we do not 7070 // need to set the noinline attribute. 7071 if (FD->hasAttr<CUDAGlobalAttr>()) { 7072 // Create !{<func-ref>, metadata !"kernel", i32 1} node 7073 addNVVMMetadata(F, "kernel", 1); 7074 } 7075 if (CUDALaunchBoundsAttr *Attr = FD->getAttr<CUDALaunchBoundsAttr>()) { 7076 // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node 7077 llvm::APSInt MaxThreads(32); 7078 MaxThreads = Attr->getMaxThreads()->EvaluateKnownConstInt(M.getContext()); 7079 if (MaxThreads > 0) 7080 addNVVMMetadata(F, "maxntidx", MaxThreads.getExtValue()); 7081 7082 // min blocks is an optional argument for CUDALaunchBoundsAttr. If it was 7083 // not specified in __launch_bounds__ or if the user specified a 0 value, 7084 // we don't have to add a PTX directive. 7085 if (Attr->getMinBlocks()) { 7086 llvm::APSInt MinBlocks(32); 7087 MinBlocks = Attr->getMinBlocks()->EvaluateKnownConstInt(M.getContext()); 7088 if (MinBlocks > 0) 7089 // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node 7090 addNVVMMetadata(F, "minctasm", MinBlocks.getExtValue()); 7091 } 7092 } 7093 } 7094 } 7095 7096 void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::GlobalValue *GV, 7097 StringRef Name, int Operand) { 7098 llvm::Module *M = GV->getParent(); 7099 llvm::LLVMContext &Ctx = M->getContext(); 7100 7101 // Get "nvvm.annotations" metadata node 7102 llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations"); 7103 7104 llvm::Metadata *MDVals[] = { 7105 llvm::ConstantAsMetadata::get(GV), llvm::MDString::get(Ctx, Name), 7106 llvm::ConstantAsMetadata::get( 7107 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand))}; 7108 // Append metadata to nvvm.annotations 7109 MD->addOperand(llvm::MDNode::get(Ctx, MDVals)); 7110 } 7111 7112 bool NVPTXTargetCodeGenInfo::shouldEmitStaticExternCAliases() const { 7113 return false; 7114 } 7115 } 7116 7117 //===----------------------------------------------------------------------===// 7118 // SystemZ ABI Implementation 7119 //===----------------------------------------------------------------------===// 7120 7121 namespace { 7122 7123 class SystemZABIInfo : public SwiftABIInfo { 7124 bool HasVector; 7125 bool IsSoftFloatABI; 7126 7127 public: 7128 SystemZABIInfo(CodeGenTypes &CGT, bool HV, bool SF) 7129 : SwiftABIInfo(CGT), HasVector(HV), IsSoftFloatABI(SF) {} 7130 7131 bool isPromotableIntegerTypeForABI(QualType Ty) const; 7132 bool isCompoundType(QualType Ty) const; 7133 bool isVectorArgumentType(QualType Ty) const; 7134 bool isFPArgumentType(QualType Ty) const; 7135 QualType GetSingleElementType(QualType Ty) const; 7136 7137 ABIArgInfo classifyReturnType(QualType RetTy) const; 7138 ABIArgInfo classifyArgumentType(QualType ArgTy) const; 7139 7140 void computeInfo(CGFunctionInfo &FI) const override { 7141 if (!getCXXABI().classifyReturnType(FI)) 7142 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 7143 for (auto &I : FI.arguments()) 7144 I.info = classifyArgumentType(I.type); 7145 } 7146 7147 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 7148 QualType Ty) const override; 7149 7150 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars, 7151 bool asReturnValue) const override { 7152 return occupiesMoreThan(CGT, scalars, /*total*/ 4); 7153 } 7154 bool isSwiftErrorInRegister() const override { 7155 return false; 7156 } 7157 }; 7158 7159 class SystemZTargetCodeGenInfo : public TargetCodeGenInfo { 7160 public: 7161 SystemZTargetCodeGenInfo(CodeGenTypes &CGT, bool HasVector, bool SoftFloatABI) 7162 : TargetCodeGenInfo( 7163 std::make_unique<SystemZABIInfo>(CGT, HasVector, SoftFloatABI)) {} 7164 }; 7165 7166 } 7167 7168 bool SystemZABIInfo::isPromotableIntegerTypeForABI(QualType Ty) const { 7169 // Treat an enum type as its underlying type. 7170 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 7171 Ty = EnumTy->getDecl()->getIntegerType(); 7172 7173 // Promotable integer types are required to be promoted by the ABI. 7174 if (ABIInfo::isPromotableIntegerTypeForABI(Ty)) 7175 return true; 7176 7177 if (const auto *EIT = Ty->getAs<ExtIntType>()) 7178 if (EIT->getNumBits() < 64) 7179 return true; 7180 7181 // 32-bit values must also be promoted. 7182 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) 7183 switch (BT->getKind()) { 7184 case BuiltinType::Int: 7185 case BuiltinType::UInt: 7186 return true; 7187 default: 7188 return false; 7189 } 7190 return false; 7191 } 7192 7193 bool SystemZABIInfo::isCompoundType(QualType Ty) const { 7194 return (Ty->isAnyComplexType() || 7195 Ty->isVectorType() || 7196 isAggregateTypeForABI(Ty)); 7197 } 7198 7199 bool SystemZABIInfo::isVectorArgumentType(QualType Ty) const { 7200 return (HasVector && 7201 Ty->isVectorType() && 7202 getContext().getTypeSize(Ty) <= 128); 7203 } 7204 7205 bool SystemZABIInfo::isFPArgumentType(QualType Ty) const { 7206 if (IsSoftFloatABI) 7207 return false; 7208 7209 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) 7210 switch (BT->getKind()) { 7211 case BuiltinType::Float: 7212 case BuiltinType::Double: 7213 return true; 7214 default: 7215 return false; 7216 } 7217 7218 return false; 7219 } 7220 7221 QualType SystemZABIInfo::GetSingleElementType(QualType Ty) const { 7222 const RecordType *RT = Ty->getAs<RecordType>(); 7223 7224 if (RT && RT->isStructureOrClassType()) { 7225 const RecordDecl *RD = RT->getDecl(); 7226 QualType Found; 7227 7228 // If this is a C++ record, check the bases first. 7229 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 7230 for (const auto &I : CXXRD->bases()) { 7231 QualType Base = I.getType(); 7232 7233 // Empty bases don't affect things either way. 7234 if (isEmptyRecord(getContext(), Base, true)) 7235 continue; 7236 7237 if (!Found.isNull()) 7238 return Ty; 7239 Found = GetSingleElementType(Base); 7240 } 7241 7242 // Check the fields. 7243 for (const auto *FD : RD->fields()) { 7244 // For compatibility with GCC, ignore empty bitfields in C++ mode. 7245 // Unlike isSingleElementStruct(), empty structure and array fields 7246 // do count. So do anonymous bitfields that aren't zero-sized. 7247 if (getContext().getLangOpts().CPlusPlus && 7248 FD->isZeroLengthBitField(getContext())) 7249 continue; 7250 // Like isSingleElementStruct(), ignore C++20 empty data members. 7251 if (FD->hasAttr<NoUniqueAddressAttr>() && 7252 isEmptyRecord(getContext(), FD->getType(), true)) 7253 continue; 7254 7255 // Unlike isSingleElementStruct(), arrays do not count. 7256 // Nested structures still do though. 7257 if (!Found.isNull()) 7258 return Ty; 7259 Found = GetSingleElementType(FD->getType()); 7260 } 7261 7262 // Unlike isSingleElementStruct(), trailing padding is allowed. 7263 // An 8-byte aligned struct s { float f; } is passed as a double. 7264 if (!Found.isNull()) 7265 return Found; 7266 } 7267 7268 return Ty; 7269 } 7270 7271 Address SystemZABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 7272 QualType Ty) const { 7273 // Assume that va_list type is correct; should be pointer to LLVM type: 7274 // struct { 7275 // i64 __gpr; 7276 // i64 __fpr; 7277 // i8 *__overflow_arg_area; 7278 // i8 *__reg_save_area; 7279 // }; 7280 7281 // Every non-vector argument occupies 8 bytes and is passed by preference 7282 // in either GPRs or FPRs. Vector arguments occupy 8 or 16 bytes and are 7283 // always passed on the stack. 7284 Ty = getContext().getCanonicalType(Ty); 7285 auto TyInfo = getContext().getTypeInfoInChars(Ty); 7286 llvm::Type *ArgTy = CGF.ConvertTypeForMem(Ty); 7287 llvm::Type *DirectTy = ArgTy; 7288 ABIArgInfo AI = classifyArgumentType(Ty); 7289 bool IsIndirect = AI.isIndirect(); 7290 bool InFPRs = false; 7291 bool IsVector = false; 7292 CharUnits UnpaddedSize; 7293 CharUnits DirectAlign; 7294 if (IsIndirect) { 7295 DirectTy = llvm::PointerType::getUnqual(DirectTy); 7296 UnpaddedSize = DirectAlign = CharUnits::fromQuantity(8); 7297 } else { 7298 if (AI.getCoerceToType()) 7299 ArgTy = AI.getCoerceToType(); 7300 InFPRs = (!IsSoftFloatABI && (ArgTy->isFloatTy() || ArgTy->isDoubleTy())); 7301 IsVector = ArgTy->isVectorTy(); 7302 UnpaddedSize = TyInfo.first; 7303 DirectAlign = TyInfo.second; 7304 } 7305 CharUnits PaddedSize = CharUnits::fromQuantity(8); 7306 if (IsVector && UnpaddedSize > PaddedSize) 7307 PaddedSize = CharUnits::fromQuantity(16); 7308 assert((UnpaddedSize <= PaddedSize) && "Invalid argument size."); 7309 7310 CharUnits Padding = (PaddedSize - UnpaddedSize); 7311 7312 llvm::Type *IndexTy = CGF.Int64Ty; 7313 llvm::Value *PaddedSizeV = 7314 llvm::ConstantInt::get(IndexTy, PaddedSize.getQuantity()); 7315 7316 if (IsVector) { 7317 // Work out the address of a vector argument on the stack. 7318 // Vector arguments are always passed in the high bits of a 7319 // single (8 byte) or double (16 byte) stack slot. 7320 Address OverflowArgAreaPtr = 7321 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr"); 7322 Address OverflowArgArea = 7323 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"), 7324 TyInfo.second); 7325 Address MemAddr = 7326 CGF.Builder.CreateElementBitCast(OverflowArgArea, DirectTy, "mem_addr"); 7327 7328 // Update overflow_arg_area_ptr pointer 7329 llvm::Value *NewOverflowArgArea = 7330 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV, 7331 "overflow_arg_area"); 7332 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr); 7333 7334 return MemAddr; 7335 } 7336 7337 assert(PaddedSize.getQuantity() == 8); 7338 7339 unsigned MaxRegs, RegCountField, RegSaveIndex; 7340 CharUnits RegPadding; 7341 if (InFPRs) { 7342 MaxRegs = 4; // Maximum of 4 FPR arguments 7343 RegCountField = 1; // __fpr 7344 RegSaveIndex = 16; // save offset for f0 7345 RegPadding = CharUnits(); // floats are passed in the high bits of an FPR 7346 } else { 7347 MaxRegs = 5; // Maximum of 5 GPR arguments 7348 RegCountField = 0; // __gpr 7349 RegSaveIndex = 2; // save offset for r2 7350 RegPadding = Padding; // values are passed in the low bits of a GPR 7351 } 7352 7353 Address RegCountPtr = 7354 CGF.Builder.CreateStructGEP(VAListAddr, RegCountField, "reg_count_ptr"); 7355 llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count"); 7356 llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs); 7357 llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV, 7358 "fits_in_regs"); 7359 7360 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg"); 7361 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem"); 7362 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end"); 7363 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock); 7364 7365 // Emit code to load the value if it was passed in registers. 7366 CGF.EmitBlock(InRegBlock); 7367 7368 // Work out the address of an argument register. 7369 llvm::Value *ScaledRegCount = 7370 CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count"); 7371 llvm::Value *RegBase = 7372 llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize.getQuantity() 7373 + RegPadding.getQuantity()); 7374 llvm::Value *RegOffset = 7375 CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset"); 7376 Address RegSaveAreaPtr = 7377 CGF.Builder.CreateStructGEP(VAListAddr, 3, "reg_save_area_ptr"); 7378 llvm::Value *RegSaveArea = 7379 CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area"); 7380 Address RawRegAddr(CGF.Builder.CreateGEP(RegSaveArea, RegOffset, 7381 "raw_reg_addr"), 7382 PaddedSize); 7383 Address RegAddr = 7384 CGF.Builder.CreateElementBitCast(RawRegAddr, DirectTy, "reg_addr"); 7385 7386 // Update the register count 7387 llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1); 7388 llvm::Value *NewRegCount = 7389 CGF.Builder.CreateAdd(RegCount, One, "reg_count"); 7390 CGF.Builder.CreateStore(NewRegCount, RegCountPtr); 7391 CGF.EmitBranch(ContBlock); 7392 7393 // Emit code to load the value if it was passed in memory. 7394 CGF.EmitBlock(InMemBlock); 7395 7396 // Work out the address of a stack argument. 7397 Address OverflowArgAreaPtr = 7398 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr"); 7399 Address OverflowArgArea = 7400 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"), 7401 PaddedSize); 7402 Address RawMemAddr = 7403 CGF.Builder.CreateConstByteGEP(OverflowArgArea, Padding, "raw_mem_addr"); 7404 Address MemAddr = 7405 CGF.Builder.CreateElementBitCast(RawMemAddr, DirectTy, "mem_addr"); 7406 7407 // Update overflow_arg_area_ptr pointer 7408 llvm::Value *NewOverflowArgArea = 7409 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV, 7410 "overflow_arg_area"); 7411 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr); 7412 CGF.EmitBranch(ContBlock); 7413 7414 // Return the appropriate result. 7415 CGF.EmitBlock(ContBlock); 7416 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, 7417 MemAddr, InMemBlock, "va_arg.addr"); 7418 7419 if (IsIndirect) 7420 ResAddr = Address(CGF.Builder.CreateLoad(ResAddr, "indirect_arg"), 7421 TyInfo.second); 7422 7423 return ResAddr; 7424 } 7425 7426 ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const { 7427 if (RetTy->isVoidType()) 7428 return ABIArgInfo::getIgnore(); 7429 if (isVectorArgumentType(RetTy)) 7430 return ABIArgInfo::getDirect(); 7431 if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64) 7432 return getNaturalAlignIndirect(RetTy); 7433 return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy) 7434 : ABIArgInfo::getDirect()); 7435 } 7436 7437 ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const { 7438 // Handle the generic C++ ABI. 7439 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 7440 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 7441 7442 // Integers and enums are extended to full register width. 7443 if (isPromotableIntegerTypeForABI(Ty)) 7444 return ABIArgInfo::getExtend(Ty); 7445 7446 // Handle vector types and vector-like structure types. Note that 7447 // as opposed to float-like structure types, we do not allow any 7448 // padding for vector-like structures, so verify the sizes match. 7449 uint64_t Size = getContext().getTypeSize(Ty); 7450 QualType SingleElementTy = GetSingleElementType(Ty); 7451 if (isVectorArgumentType(SingleElementTy) && 7452 getContext().getTypeSize(SingleElementTy) == Size) 7453 return ABIArgInfo::getDirect(CGT.ConvertType(SingleElementTy)); 7454 7455 // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly. 7456 if (Size != 8 && Size != 16 && Size != 32 && Size != 64) 7457 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 7458 7459 // Handle small structures. 7460 if (const RecordType *RT = Ty->getAs<RecordType>()) { 7461 // Structures with flexible arrays have variable length, so really 7462 // fail the size test above. 7463 const RecordDecl *RD = RT->getDecl(); 7464 if (RD->hasFlexibleArrayMember()) 7465 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 7466 7467 // The structure is passed as an unextended integer, a float, or a double. 7468 llvm::Type *PassTy; 7469 if (isFPArgumentType(SingleElementTy)) { 7470 assert(Size == 32 || Size == 64); 7471 if (Size == 32) 7472 PassTy = llvm::Type::getFloatTy(getVMContext()); 7473 else 7474 PassTy = llvm::Type::getDoubleTy(getVMContext()); 7475 } else 7476 PassTy = llvm::IntegerType::get(getVMContext(), Size); 7477 return ABIArgInfo::getDirect(PassTy); 7478 } 7479 7480 // Non-structure compounds are passed indirectly. 7481 if (isCompoundType(Ty)) 7482 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 7483 7484 return ABIArgInfo::getDirect(nullptr); 7485 } 7486 7487 //===----------------------------------------------------------------------===// 7488 // MSP430 ABI Implementation 7489 //===----------------------------------------------------------------------===// 7490 7491 namespace { 7492 7493 class MSP430ABIInfo : public DefaultABIInfo { 7494 static ABIArgInfo complexArgInfo() { 7495 ABIArgInfo Info = ABIArgInfo::getDirect(); 7496 Info.setCanBeFlattened(false); 7497 return Info; 7498 } 7499 7500 public: 7501 MSP430ABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {} 7502 7503 ABIArgInfo classifyReturnType(QualType RetTy) const { 7504 if (RetTy->isAnyComplexType()) 7505 return complexArgInfo(); 7506 7507 return DefaultABIInfo::classifyReturnType(RetTy); 7508 } 7509 7510 ABIArgInfo classifyArgumentType(QualType RetTy) const { 7511 if (RetTy->isAnyComplexType()) 7512 return complexArgInfo(); 7513 7514 return DefaultABIInfo::classifyArgumentType(RetTy); 7515 } 7516 7517 // Just copy the original implementations because 7518 // DefaultABIInfo::classify{Return,Argument}Type() are not virtual 7519 void computeInfo(CGFunctionInfo &FI) const override { 7520 if (!getCXXABI().classifyReturnType(FI)) 7521 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 7522 for (auto &I : FI.arguments()) 7523 I.info = classifyArgumentType(I.type); 7524 } 7525 7526 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 7527 QualType Ty) const override { 7528 return EmitVAArgInstr(CGF, VAListAddr, Ty, classifyArgumentType(Ty)); 7529 } 7530 }; 7531 7532 class MSP430TargetCodeGenInfo : public TargetCodeGenInfo { 7533 public: 7534 MSP430TargetCodeGenInfo(CodeGenTypes &CGT) 7535 : TargetCodeGenInfo(std::make_unique<MSP430ABIInfo>(CGT)) {} 7536 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 7537 CodeGen::CodeGenModule &M) const override; 7538 }; 7539 7540 } 7541 7542 void MSP430TargetCodeGenInfo::setTargetAttributes( 7543 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const { 7544 if (GV->isDeclaration()) 7545 return; 7546 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) { 7547 const auto *InterruptAttr = FD->getAttr<MSP430InterruptAttr>(); 7548 if (!InterruptAttr) 7549 return; 7550 7551 // Handle 'interrupt' attribute: 7552 llvm::Function *F = cast<llvm::Function>(GV); 7553 7554 // Step 1: Set ISR calling convention. 7555 F->setCallingConv(llvm::CallingConv::MSP430_INTR); 7556 7557 // Step 2: Add attributes goodness. 7558 F->addFnAttr(llvm::Attribute::NoInline); 7559 F->addFnAttr("interrupt", llvm::utostr(InterruptAttr->getNumber())); 7560 } 7561 } 7562 7563 //===----------------------------------------------------------------------===// 7564 // MIPS ABI Implementation. This works for both little-endian and 7565 // big-endian variants. 7566 //===----------------------------------------------------------------------===// 7567 7568 namespace { 7569 class MipsABIInfo : public ABIInfo { 7570 bool IsO32; 7571 unsigned MinABIStackAlignInBytes, StackAlignInBytes; 7572 void CoerceToIntArgs(uint64_t TySize, 7573 SmallVectorImpl<llvm::Type *> &ArgList) const; 7574 llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const; 7575 llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const; 7576 llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const; 7577 public: 7578 MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) : 7579 ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8), 7580 StackAlignInBytes(IsO32 ? 8 : 16) {} 7581 7582 ABIArgInfo classifyReturnType(QualType RetTy) const; 7583 ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const; 7584 void computeInfo(CGFunctionInfo &FI) const override; 7585 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 7586 QualType Ty) const override; 7587 ABIArgInfo extendType(QualType Ty) const; 7588 }; 7589 7590 class MIPSTargetCodeGenInfo : public TargetCodeGenInfo { 7591 unsigned SizeOfUnwindException; 7592 public: 7593 MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32) 7594 : TargetCodeGenInfo(std::make_unique<MipsABIInfo>(CGT, IsO32)), 7595 SizeOfUnwindException(IsO32 ? 24 : 32) {} 7596 7597 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override { 7598 return 29; 7599 } 7600 7601 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 7602 CodeGen::CodeGenModule &CGM) const override { 7603 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D); 7604 if (!FD) return; 7605 llvm::Function *Fn = cast<llvm::Function>(GV); 7606 7607 if (FD->hasAttr<MipsLongCallAttr>()) 7608 Fn->addFnAttr("long-call"); 7609 else if (FD->hasAttr<MipsShortCallAttr>()) 7610 Fn->addFnAttr("short-call"); 7611 7612 // Other attributes do not have a meaning for declarations. 7613 if (GV->isDeclaration()) 7614 return; 7615 7616 if (FD->hasAttr<Mips16Attr>()) { 7617 Fn->addFnAttr("mips16"); 7618 } 7619 else if (FD->hasAttr<NoMips16Attr>()) { 7620 Fn->addFnAttr("nomips16"); 7621 } 7622 7623 if (FD->hasAttr<MicroMipsAttr>()) 7624 Fn->addFnAttr("micromips"); 7625 else if (FD->hasAttr<NoMicroMipsAttr>()) 7626 Fn->addFnAttr("nomicromips"); 7627 7628 const MipsInterruptAttr *Attr = FD->getAttr<MipsInterruptAttr>(); 7629 if (!Attr) 7630 return; 7631 7632 const char *Kind; 7633 switch (Attr->getInterrupt()) { 7634 case MipsInterruptAttr::eic: Kind = "eic"; break; 7635 case MipsInterruptAttr::sw0: Kind = "sw0"; break; 7636 case MipsInterruptAttr::sw1: Kind = "sw1"; break; 7637 case MipsInterruptAttr::hw0: Kind = "hw0"; break; 7638 case MipsInterruptAttr::hw1: Kind = "hw1"; break; 7639 case MipsInterruptAttr::hw2: Kind = "hw2"; break; 7640 case MipsInterruptAttr::hw3: Kind = "hw3"; break; 7641 case MipsInterruptAttr::hw4: Kind = "hw4"; break; 7642 case MipsInterruptAttr::hw5: Kind = "hw5"; break; 7643 } 7644 7645 Fn->addFnAttr("interrupt", Kind); 7646 7647 } 7648 7649 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 7650 llvm::Value *Address) const override; 7651 7652 unsigned getSizeOfUnwindException() const override { 7653 return SizeOfUnwindException; 7654 } 7655 }; 7656 } 7657 7658 void MipsABIInfo::CoerceToIntArgs( 7659 uint64_t TySize, SmallVectorImpl<llvm::Type *> &ArgList) const { 7660 llvm::IntegerType *IntTy = 7661 llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8); 7662 7663 // Add (TySize / MinABIStackAlignInBytes) args of IntTy. 7664 for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N) 7665 ArgList.push_back(IntTy); 7666 7667 // If necessary, add one more integer type to ArgList. 7668 unsigned R = TySize % (MinABIStackAlignInBytes * 8); 7669 7670 if (R) 7671 ArgList.push_back(llvm::IntegerType::get(getVMContext(), R)); 7672 } 7673 7674 // In N32/64, an aligned double precision floating point field is passed in 7675 // a register. 7676 llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const { 7677 SmallVector<llvm::Type*, 8> ArgList, IntArgList; 7678 7679 if (IsO32) { 7680 CoerceToIntArgs(TySize, ArgList); 7681 return llvm::StructType::get(getVMContext(), ArgList); 7682 } 7683 7684 if (Ty->isComplexType()) 7685 return CGT.ConvertType(Ty); 7686 7687 const RecordType *RT = Ty->getAs<RecordType>(); 7688 7689 // Unions/vectors are passed in integer registers. 7690 if (!RT || !RT->isStructureOrClassType()) { 7691 CoerceToIntArgs(TySize, ArgList); 7692 return llvm::StructType::get(getVMContext(), ArgList); 7693 } 7694 7695 const RecordDecl *RD = RT->getDecl(); 7696 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD); 7697 assert(!(TySize % 8) && "Size of structure must be multiple of 8."); 7698 7699 uint64_t LastOffset = 0; 7700 unsigned idx = 0; 7701 llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64); 7702 7703 // Iterate over fields in the struct/class and check if there are any aligned 7704 // double fields. 7705 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 7706 i != e; ++i, ++idx) { 7707 const QualType Ty = i->getType(); 7708 const BuiltinType *BT = Ty->getAs<BuiltinType>(); 7709 7710 if (!BT || BT->getKind() != BuiltinType::Double) 7711 continue; 7712 7713 uint64_t Offset = Layout.getFieldOffset(idx); 7714 if (Offset % 64) // Ignore doubles that are not aligned. 7715 continue; 7716 7717 // Add ((Offset - LastOffset) / 64) args of type i64. 7718 for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j) 7719 ArgList.push_back(I64); 7720 7721 // Add double type. 7722 ArgList.push_back(llvm::Type::getDoubleTy(getVMContext())); 7723 LastOffset = Offset + 64; 7724 } 7725 7726 CoerceToIntArgs(TySize - LastOffset, IntArgList); 7727 ArgList.append(IntArgList.begin(), IntArgList.end()); 7728 7729 return llvm::StructType::get(getVMContext(), ArgList); 7730 } 7731 7732 llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset, 7733 uint64_t Offset) const { 7734 if (OrigOffset + MinABIStackAlignInBytes > Offset) 7735 return nullptr; 7736 7737 return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8); 7738 } 7739 7740 ABIArgInfo 7741 MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const { 7742 Ty = useFirstFieldIfTransparentUnion(Ty); 7743 7744 uint64_t OrigOffset = Offset; 7745 uint64_t TySize = getContext().getTypeSize(Ty); 7746 uint64_t Align = getContext().getTypeAlign(Ty) / 8; 7747 7748 Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes), 7749 (uint64_t)StackAlignInBytes); 7750 unsigned CurrOffset = llvm::alignTo(Offset, Align); 7751 Offset = CurrOffset + llvm::alignTo(TySize, Align * 8) / 8; 7752 7753 if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) { 7754 // Ignore empty aggregates. 7755 if (TySize == 0) 7756 return ABIArgInfo::getIgnore(); 7757 7758 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) { 7759 Offset = OrigOffset + MinABIStackAlignInBytes; 7760 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 7761 } 7762 7763 // If we have reached here, aggregates are passed directly by coercing to 7764 // another structure type. Padding is inserted if the offset of the 7765 // aggregate is unaligned. 7766 ABIArgInfo ArgInfo = 7767 ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0, 7768 getPaddingType(OrigOffset, CurrOffset)); 7769 ArgInfo.setInReg(true); 7770 return ArgInfo; 7771 } 7772 7773 // Treat an enum type as its underlying type. 7774 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 7775 Ty = EnumTy->getDecl()->getIntegerType(); 7776 7777 // Make sure we pass indirectly things that are too large. 7778 if (const auto *EIT = Ty->getAs<ExtIntType>()) 7779 if (EIT->getNumBits() > 128 || 7780 (EIT->getNumBits() > 64 && 7781 !getContext().getTargetInfo().hasInt128Type())) 7782 return getNaturalAlignIndirect(Ty); 7783 7784 // All integral types are promoted to the GPR width. 7785 if (Ty->isIntegralOrEnumerationType()) 7786 return extendType(Ty); 7787 7788 return ABIArgInfo::getDirect( 7789 nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset)); 7790 } 7791 7792 llvm::Type* 7793 MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const { 7794 const RecordType *RT = RetTy->getAs<RecordType>(); 7795 SmallVector<llvm::Type*, 8> RTList; 7796 7797 if (RT && RT->isStructureOrClassType()) { 7798 const RecordDecl *RD = RT->getDecl(); 7799 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD); 7800 unsigned FieldCnt = Layout.getFieldCount(); 7801 7802 // N32/64 returns struct/classes in floating point registers if the 7803 // following conditions are met: 7804 // 1. The size of the struct/class is no larger than 128-bit. 7805 // 2. The struct/class has one or two fields all of which are floating 7806 // point types. 7807 // 3. The offset of the first field is zero (this follows what gcc does). 7808 // 7809 // Any other composite results are returned in integer registers. 7810 // 7811 if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) { 7812 RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end(); 7813 for (; b != e; ++b) { 7814 const BuiltinType *BT = b->getType()->getAs<BuiltinType>(); 7815 7816 if (!BT || !BT->isFloatingPoint()) 7817 break; 7818 7819 RTList.push_back(CGT.ConvertType(b->getType())); 7820 } 7821 7822 if (b == e) 7823 return llvm::StructType::get(getVMContext(), RTList, 7824 RD->hasAttr<PackedAttr>()); 7825 7826 RTList.clear(); 7827 } 7828 } 7829 7830 CoerceToIntArgs(Size, RTList); 7831 return llvm::StructType::get(getVMContext(), RTList); 7832 } 7833 7834 ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const { 7835 uint64_t Size = getContext().getTypeSize(RetTy); 7836 7837 if (RetTy->isVoidType()) 7838 return ABIArgInfo::getIgnore(); 7839 7840 // O32 doesn't treat zero-sized structs differently from other structs. 7841 // However, N32/N64 ignores zero sized return values. 7842 if (!IsO32 && Size == 0) 7843 return ABIArgInfo::getIgnore(); 7844 7845 if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) { 7846 if (Size <= 128) { 7847 if (RetTy->isAnyComplexType()) 7848 return ABIArgInfo::getDirect(); 7849 7850 // O32 returns integer vectors in registers and N32/N64 returns all small 7851 // aggregates in registers. 7852 if (!IsO32 || 7853 (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) { 7854 ABIArgInfo ArgInfo = 7855 ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size)); 7856 ArgInfo.setInReg(true); 7857 return ArgInfo; 7858 } 7859 } 7860 7861 return getNaturalAlignIndirect(RetTy); 7862 } 7863 7864 // Treat an enum type as its underlying type. 7865 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 7866 RetTy = EnumTy->getDecl()->getIntegerType(); 7867 7868 // Make sure we pass indirectly things that are too large. 7869 if (const auto *EIT = RetTy->getAs<ExtIntType>()) 7870 if (EIT->getNumBits() > 128 || 7871 (EIT->getNumBits() > 64 && 7872 !getContext().getTargetInfo().hasInt128Type())) 7873 return getNaturalAlignIndirect(RetTy); 7874 7875 if (isPromotableIntegerTypeForABI(RetTy)) 7876 return ABIArgInfo::getExtend(RetTy); 7877 7878 if ((RetTy->isUnsignedIntegerOrEnumerationType() || 7879 RetTy->isSignedIntegerOrEnumerationType()) && Size == 32 && !IsO32) 7880 return ABIArgInfo::getSignExtend(RetTy); 7881 7882 return ABIArgInfo::getDirect(); 7883 } 7884 7885 void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const { 7886 ABIArgInfo &RetInfo = FI.getReturnInfo(); 7887 if (!getCXXABI().classifyReturnType(FI)) 7888 RetInfo = classifyReturnType(FI.getReturnType()); 7889 7890 // Check if a pointer to an aggregate is passed as a hidden argument. 7891 uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0; 7892 7893 for (auto &I : FI.arguments()) 7894 I.info = classifyArgumentType(I.type, Offset); 7895 } 7896 7897 Address MipsABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 7898 QualType OrigTy) const { 7899 QualType Ty = OrigTy; 7900 7901 // Integer arguments are promoted to 32-bit on O32 and 64-bit on N32/N64. 7902 // Pointers are also promoted in the same way but this only matters for N32. 7903 unsigned SlotSizeInBits = IsO32 ? 32 : 64; 7904 unsigned PtrWidth = getTarget().getPointerWidth(0); 7905 bool DidPromote = false; 7906 if ((Ty->isIntegerType() && 7907 getContext().getIntWidth(Ty) < SlotSizeInBits) || 7908 (Ty->isPointerType() && PtrWidth < SlotSizeInBits)) { 7909 DidPromote = true; 7910 Ty = getContext().getIntTypeForBitwidth(SlotSizeInBits, 7911 Ty->isSignedIntegerType()); 7912 } 7913 7914 auto TyInfo = getContext().getTypeInfoInChars(Ty); 7915 7916 // The alignment of things in the argument area is never larger than 7917 // StackAlignInBytes. 7918 TyInfo.second = 7919 std::min(TyInfo.second, CharUnits::fromQuantity(StackAlignInBytes)); 7920 7921 // MinABIStackAlignInBytes is the size of argument slots on the stack. 7922 CharUnits ArgSlotSize = CharUnits::fromQuantity(MinABIStackAlignInBytes); 7923 7924 Address Addr = emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false, 7925 TyInfo, ArgSlotSize, /*AllowHigherAlign*/ true); 7926 7927 7928 // If there was a promotion, "unpromote" into a temporary. 7929 // TODO: can we just use a pointer into a subset of the original slot? 7930 if (DidPromote) { 7931 Address Temp = CGF.CreateMemTemp(OrigTy, "vaarg.promotion-temp"); 7932 llvm::Value *Promoted = CGF.Builder.CreateLoad(Addr); 7933 7934 // Truncate down to the right width. 7935 llvm::Type *IntTy = (OrigTy->isIntegerType() ? Temp.getElementType() 7936 : CGF.IntPtrTy); 7937 llvm::Value *V = CGF.Builder.CreateTrunc(Promoted, IntTy); 7938 if (OrigTy->isPointerType()) 7939 V = CGF.Builder.CreateIntToPtr(V, Temp.getElementType()); 7940 7941 CGF.Builder.CreateStore(V, Temp); 7942 Addr = Temp; 7943 } 7944 7945 return Addr; 7946 } 7947 7948 ABIArgInfo MipsABIInfo::extendType(QualType Ty) const { 7949 int TySize = getContext().getTypeSize(Ty); 7950 7951 // MIPS64 ABI requires unsigned 32 bit integers to be sign extended. 7952 if (Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32) 7953 return ABIArgInfo::getSignExtend(Ty); 7954 7955 return ABIArgInfo::getExtend(Ty); 7956 } 7957 7958 bool 7959 MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 7960 llvm::Value *Address) const { 7961 // This information comes from gcc's implementation, which seems to 7962 // as canonical as it gets. 7963 7964 // Everything on MIPS is 4 bytes. Double-precision FP registers 7965 // are aliased to pairs of single-precision FP registers. 7966 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4); 7967 7968 // 0-31 are the general purpose registers, $0 - $31. 7969 // 32-63 are the floating-point registers, $f0 - $f31. 7970 // 64 and 65 are the multiply/divide registers, $hi and $lo. 7971 // 66 is the (notional, I think) register for signal-handler return. 7972 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65); 7973 7974 // 67-74 are the floating-point status registers, $fcc0 - $fcc7. 7975 // They are one bit wide and ignored here. 7976 7977 // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31. 7978 // (coprocessor 1 is the FP unit) 7979 // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31. 7980 // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31. 7981 // 176-181 are the DSP accumulator registers. 7982 AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181); 7983 return false; 7984 } 7985 7986 //===----------------------------------------------------------------------===// 7987 // AVR ABI Implementation. 7988 //===----------------------------------------------------------------------===// 7989 7990 namespace { 7991 class AVRTargetCodeGenInfo : public TargetCodeGenInfo { 7992 public: 7993 AVRTargetCodeGenInfo(CodeGenTypes &CGT) 7994 : TargetCodeGenInfo(std::make_unique<DefaultABIInfo>(CGT)) {} 7995 7996 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 7997 CodeGen::CodeGenModule &CGM) const override { 7998 if (GV->isDeclaration()) 7999 return; 8000 const auto *FD = dyn_cast_or_null<FunctionDecl>(D); 8001 if (!FD) return; 8002 auto *Fn = cast<llvm::Function>(GV); 8003 8004 if (FD->getAttr<AVRInterruptAttr>()) 8005 Fn->addFnAttr("interrupt"); 8006 8007 if (FD->getAttr<AVRSignalAttr>()) 8008 Fn->addFnAttr("signal"); 8009 } 8010 }; 8011 } 8012 8013 //===----------------------------------------------------------------------===// 8014 // TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults. 8015 // Currently subclassed only to implement custom OpenCL C function attribute 8016 // handling. 8017 //===----------------------------------------------------------------------===// 8018 8019 namespace { 8020 8021 class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo { 8022 public: 8023 TCETargetCodeGenInfo(CodeGenTypes &CGT) 8024 : DefaultTargetCodeGenInfo(CGT) {} 8025 8026 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 8027 CodeGen::CodeGenModule &M) const override; 8028 }; 8029 8030 void TCETargetCodeGenInfo::setTargetAttributes( 8031 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const { 8032 if (GV->isDeclaration()) 8033 return; 8034 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D); 8035 if (!FD) return; 8036 8037 llvm::Function *F = cast<llvm::Function>(GV); 8038 8039 if (M.getLangOpts().OpenCL) { 8040 if (FD->hasAttr<OpenCLKernelAttr>()) { 8041 // OpenCL C Kernel functions are not subject to inlining 8042 F->addFnAttr(llvm::Attribute::NoInline); 8043 const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>(); 8044 if (Attr) { 8045 // Convert the reqd_work_group_size() attributes to metadata. 8046 llvm::LLVMContext &Context = F->getContext(); 8047 llvm::NamedMDNode *OpenCLMetadata = 8048 M.getModule().getOrInsertNamedMetadata( 8049 "opencl.kernel_wg_size_info"); 8050 8051 SmallVector<llvm::Metadata *, 5> Operands; 8052 Operands.push_back(llvm::ConstantAsMetadata::get(F)); 8053 8054 Operands.push_back( 8055 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue( 8056 M.Int32Ty, llvm::APInt(32, Attr->getXDim())))); 8057 Operands.push_back( 8058 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue( 8059 M.Int32Ty, llvm::APInt(32, Attr->getYDim())))); 8060 Operands.push_back( 8061 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue( 8062 M.Int32Ty, llvm::APInt(32, Attr->getZDim())))); 8063 8064 // Add a boolean constant operand for "required" (true) or "hint" 8065 // (false) for implementing the work_group_size_hint attr later. 8066 // Currently always true as the hint is not yet implemented. 8067 Operands.push_back( 8068 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getTrue(Context))); 8069 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands)); 8070 } 8071 } 8072 } 8073 } 8074 8075 } 8076 8077 //===----------------------------------------------------------------------===// 8078 // Hexagon ABI Implementation 8079 //===----------------------------------------------------------------------===// 8080 8081 namespace { 8082 8083 class HexagonABIInfo : public DefaultABIInfo { 8084 public: 8085 HexagonABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {} 8086 8087 private: 8088 ABIArgInfo classifyReturnType(QualType RetTy) const; 8089 ABIArgInfo classifyArgumentType(QualType RetTy) const; 8090 ABIArgInfo classifyArgumentType(QualType RetTy, unsigned *RegsLeft) const; 8091 8092 void computeInfo(CGFunctionInfo &FI) const override; 8093 8094 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 8095 QualType Ty) const override; 8096 Address EmitVAArgFromMemory(CodeGenFunction &CFG, Address VAListAddr, 8097 QualType Ty) const; 8098 Address EmitVAArgForHexagon(CodeGenFunction &CFG, Address VAListAddr, 8099 QualType Ty) const; 8100 Address EmitVAArgForHexagonLinux(CodeGenFunction &CFG, Address VAListAddr, 8101 QualType Ty) const; 8102 }; 8103 8104 class HexagonTargetCodeGenInfo : public TargetCodeGenInfo { 8105 public: 8106 HexagonTargetCodeGenInfo(CodeGenTypes &CGT) 8107 : TargetCodeGenInfo(std::make_unique<HexagonABIInfo>(CGT)) {} 8108 8109 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 8110 return 29; 8111 } 8112 8113 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 8114 CodeGen::CodeGenModule &GCM) const override { 8115 if (GV->isDeclaration()) 8116 return; 8117 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D); 8118 if (!FD) 8119 return; 8120 } 8121 }; 8122 8123 } // namespace 8124 8125 void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const { 8126 unsigned RegsLeft = 6; 8127 if (!getCXXABI().classifyReturnType(FI)) 8128 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 8129 for (auto &I : FI.arguments()) 8130 I.info = classifyArgumentType(I.type, &RegsLeft); 8131 } 8132 8133 static bool HexagonAdjustRegsLeft(uint64_t Size, unsigned *RegsLeft) { 8134 assert(Size <= 64 && "Not expecting to pass arguments larger than 64 bits" 8135 " through registers"); 8136 8137 if (*RegsLeft == 0) 8138 return false; 8139 8140 if (Size <= 32) { 8141 (*RegsLeft)--; 8142 return true; 8143 } 8144 8145 if (2 <= (*RegsLeft & (~1U))) { 8146 *RegsLeft = (*RegsLeft & (~1U)) - 2; 8147 return true; 8148 } 8149 8150 // Next available register was r5 but candidate was greater than 32-bits so it 8151 // has to go on the stack. However we still consume r5 8152 if (*RegsLeft == 1) 8153 *RegsLeft = 0; 8154 8155 return false; 8156 } 8157 8158 ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty, 8159 unsigned *RegsLeft) const { 8160 if (!isAggregateTypeForABI(Ty)) { 8161 // Treat an enum type as its underlying type. 8162 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 8163 Ty = EnumTy->getDecl()->getIntegerType(); 8164 8165 uint64_t Size = getContext().getTypeSize(Ty); 8166 if (Size <= 64) 8167 HexagonAdjustRegsLeft(Size, RegsLeft); 8168 8169 if (Size > 64 && Ty->isExtIntType()) 8170 return getNaturalAlignIndirect(Ty, /*ByVal=*/true); 8171 8172 return isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty) 8173 : ABIArgInfo::getDirect(); 8174 } 8175 8176 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 8177 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 8178 8179 // Ignore empty records. 8180 if (isEmptyRecord(getContext(), Ty, true)) 8181 return ABIArgInfo::getIgnore(); 8182 8183 uint64_t Size = getContext().getTypeSize(Ty); 8184 unsigned Align = getContext().getTypeAlign(Ty); 8185 8186 if (Size > 64) 8187 return getNaturalAlignIndirect(Ty, /*ByVal=*/true); 8188 8189 if (HexagonAdjustRegsLeft(Size, RegsLeft)) 8190 Align = Size <= 32 ? 32 : 64; 8191 if (Size <= Align) { 8192 // Pass in the smallest viable integer type. 8193 if (!llvm::isPowerOf2_64(Size)) 8194 Size = llvm::NextPowerOf2(Size); 8195 return ABIArgInfo::getDirect(llvm::Type::getIntNTy(getVMContext(), Size)); 8196 } 8197 return DefaultABIInfo::classifyArgumentType(Ty); 8198 } 8199 8200 ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const { 8201 if (RetTy->isVoidType()) 8202 return ABIArgInfo::getIgnore(); 8203 8204 const TargetInfo &T = CGT.getTarget(); 8205 uint64_t Size = getContext().getTypeSize(RetTy); 8206 8207 if (RetTy->getAs<VectorType>()) { 8208 // HVX vectors are returned in vector registers or register pairs. 8209 if (T.hasFeature("hvx")) { 8210 assert(T.hasFeature("hvx-length64b") || T.hasFeature("hvx-length128b")); 8211 uint64_t VecSize = T.hasFeature("hvx-length64b") ? 64*8 : 128*8; 8212 if (Size == VecSize || Size == 2*VecSize) 8213 return ABIArgInfo::getDirectInReg(); 8214 } 8215 // Large vector types should be returned via memory. 8216 if (Size > 64) 8217 return getNaturalAlignIndirect(RetTy); 8218 } 8219 8220 if (!isAggregateTypeForABI(RetTy)) { 8221 // Treat an enum type as its underlying type. 8222 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 8223 RetTy = EnumTy->getDecl()->getIntegerType(); 8224 8225 if (Size > 64 && RetTy->isExtIntType()) 8226 return getNaturalAlignIndirect(RetTy, /*ByVal=*/false); 8227 8228 return isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy) 8229 : ABIArgInfo::getDirect(); 8230 } 8231 8232 if (isEmptyRecord(getContext(), RetTy, true)) 8233 return ABIArgInfo::getIgnore(); 8234 8235 // Aggregates <= 8 bytes are returned in registers, other aggregates 8236 // are returned indirectly. 8237 if (Size <= 64) { 8238 // Return in the smallest viable integer type. 8239 if (!llvm::isPowerOf2_64(Size)) 8240 Size = llvm::NextPowerOf2(Size); 8241 return ABIArgInfo::getDirect(llvm::Type::getIntNTy(getVMContext(), Size)); 8242 } 8243 return getNaturalAlignIndirect(RetTy, /*ByVal=*/true); 8244 } 8245 8246 Address HexagonABIInfo::EmitVAArgFromMemory(CodeGenFunction &CGF, 8247 Address VAListAddr, 8248 QualType Ty) const { 8249 // Load the overflow area pointer. 8250 Address __overflow_area_pointer_p = 8251 CGF.Builder.CreateStructGEP(VAListAddr, 2, "__overflow_area_pointer_p"); 8252 llvm::Value *__overflow_area_pointer = CGF.Builder.CreateLoad( 8253 __overflow_area_pointer_p, "__overflow_area_pointer"); 8254 8255 uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8; 8256 if (Align > 4) { 8257 // Alignment should be a power of 2. 8258 assert((Align & (Align - 1)) == 0 && "Alignment is not power of 2!"); 8259 8260 // overflow_arg_area = (overflow_arg_area + align - 1) & -align; 8261 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int64Ty, Align - 1); 8262 8263 // Add offset to the current pointer to access the argument. 8264 __overflow_area_pointer = 8265 CGF.Builder.CreateGEP(__overflow_area_pointer, Offset); 8266 llvm::Value *AsInt = 8267 CGF.Builder.CreatePtrToInt(__overflow_area_pointer, CGF.Int32Ty); 8268 8269 // Create a mask which should be "AND"ed 8270 // with (overflow_arg_area + align - 1) 8271 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int32Ty, -(int)Align); 8272 __overflow_area_pointer = CGF.Builder.CreateIntToPtr( 8273 CGF.Builder.CreateAnd(AsInt, Mask), __overflow_area_pointer->getType(), 8274 "__overflow_area_pointer.align"); 8275 } 8276 8277 // Get the type of the argument from memory and bitcast 8278 // overflow area pointer to the argument type. 8279 llvm::Type *PTy = CGF.ConvertTypeForMem(Ty); 8280 Address AddrTyped = CGF.Builder.CreateBitCast( 8281 Address(__overflow_area_pointer, CharUnits::fromQuantity(Align)), 8282 llvm::PointerType::getUnqual(PTy)); 8283 8284 // Round up to the minimum stack alignment for varargs which is 4 bytes. 8285 uint64_t Offset = llvm::alignTo(CGF.getContext().getTypeSize(Ty) / 8, 4); 8286 8287 __overflow_area_pointer = CGF.Builder.CreateGEP( 8288 __overflow_area_pointer, llvm::ConstantInt::get(CGF.Int32Ty, Offset), 8289 "__overflow_area_pointer.next"); 8290 CGF.Builder.CreateStore(__overflow_area_pointer, __overflow_area_pointer_p); 8291 8292 return AddrTyped; 8293 } 8294 8295 Address HexagonABIInfo::EmitVAArgForHexagon(CodeGenFunction &CGF, 8296 Address VAListAddr, 8297 QualType Ty) const { 8298 // FIXME: Need to handle alignment 8299 llvm::Type *BP = CGF.Int8PtrTy; 8300 llvm::Type *BPP = CGF.Int8PtrPtrTy; 8301 CGBuilderTy &Builder = CGF.Builder; 8302 Address VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap"); 8303 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur"); 8304 // Handle address alignment for type alignment > 32 bits 8305 uint64_t TyAlign = CGF.getContext().getTypeAlign(Ty) / 8; 8306 if (TyAlign > 4) { 8307 assert((TyAlign & (TyAlign - 1)) == 0 && "Alignment is not power of 2!"); 8308 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int32Ty); 8309 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt32(TyAlign - 1)); 8310 AddrAsInt = Builder.CreateAnd(AddrAsInt, Builder.getInt32(~(TyAlign - 1))); 8311 Addr = Builder.CreateIntToPtr(AddrAsInt, BP); 8312 } 8313 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty)); 8314 Address AddrTyped = Builder.CreateBitCast( 8315 Address(Addr, CharUnits::fromQuantity(TyAlign)), PTy); 8316 8317 uint64_t Offset = llvm::alignTo(CGF.getContext().getTypeSize(Ty) / 8, 4); 8318 llvm::Value *NextAddr = Builder.CreateGEP( 8319 Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset), "ap.next"); 8320 Builder.CreateStore(NextAddr, VAListAddrAsBPP); 8321 8322 return AddrTyped; 8323 } 8324 8325 Address HexagonABIInfo::EmitVAArgForHexagonLinux(CodeGenFunction &CGF, 8326 Address VAListAddr, 8327 QualType Ty) const { 8328 int ArgSize = CGF.getContext().getTypeSize(Ty) / 8; 8329 8330 if (ArgSize > 8) 8331 return EmitVAArgFromMemory(CGF, VAListAddr, Ty); 8332 8333 // Here we have check if the argument is in register area or 8334 // in overflow area. 8335 // If the saved register area pointer + argsize rounded up to alignment > 8336 // saved register area end pointer, argument is in overflow area. 8337 unsigned RegsLeft = 6; 8338 Ty = CGF.getContext().getCanonicalType(Ty); 8339 (void)classifyArgumentType(Ty, &RegsLeft); 8340 8341 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg"); 8342 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg"); 8343 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack"); 8344 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end"); 8345 8346 // Get rounded size of the argument.GCC does not allow vararg of 8347 // size < 4 bytes. We follow the same logic here. 8348 ArgSize = (CGF.getContext().getTypeSize(Ty) <= 32) ? 4 : 8; 8349 int ArgAlign = (CGF.getContext().getTypeSize(Ty) <= 32) ? 4 : 8; 8350 8351 // Argument may be in saved register area 8352 CGF.EmitBlock(MaybeRegBlock); 8353 8354 // Load the current saved register area pointer. 8355 Address __current_saved_reg_area_pointer_p = CGF.Builder.CreateStructGEP( 8356 VAListAddr, 0, "__current_saved_reg_area_pointer_p"); 8357 llvm::Value *__current_saved_reg_area_pointer = CGF.Builder.CreateLoad( 8358 __current_saved_reg_area_pointer_p, "__current_saved_reg_area_pointer"); 8359 8360 // Load the saved register area end pointer. 8361 Address __saved_reg_area_end_pointer_p = CGF.Builder.CreateStructGEP( 8362 VAListAddr, 1, "__saved_reg_area_end_pointer_p"); 8363 llvm::Value *__saved_reg_area_end_pointer = CGF.Builder.CreateLoad( 8364 __saved_reg_area_end_pointer_p, "__saved_reg_area_end_pointer"); 8365 8366 // If the size of argument is > 4 bytes, check if the stack 8367 // location is aligned to 8 bytes 8368 if (ArgAlign > 4) { 8369 8370 llvm::Value *__current_saved_reg_area_pointer_int = 8371 CGF.Builder.CreatePtrToInt(__current_saved_reg_area_pointer, 8372 CGF.Int32Ty); 8373 8374 __current_saved_reg_area_pointer_int = CGF.Builder.CreateAdd( 8375 __current_saved_reg_area_pointer_int, 8376 llvm::ConstantInt::get(CGF.Int32Ty, (ArgAlign - 1)), 8377 "align_current_saved_reg_area_pointer"); 8378 8379 __current_saved_reg_area_pointer_int = 8380 CGF.Builder.CreateAnd(__current_saved_reg_area_pointer_int, 8381 llvm::ConstantInt::get(CGF.Int32Ty, -ArgAlign), 8382 "align_current_saved_reg_area_pointer"); 8383 8384 __current_saved_reg_area_pointer = 8385 CGF.Builder.CreateIntToPtr(__current_saved_reg_area_pointer_int, 8386 __current_saved_reg_area_pointer->getType(), 8387 "align_current_saved_reg_area_pointer"); 8388 } 8389 8390 llvm::Value *__new_saved_reg_area_pointer = 8391 CGF.Builder.CreateGEP(__current_saved_reg_area_pointer, 8392 llvm::ConstantInt::get(CGF.Int32Ty, ArgSize), 8393 "__new_saved_reg_area_pointer"); 8394 8395 llvm::Value *UsingStack = 0; 8396 UsingStack = CGF.Builder.CreateICmpSGT(__new_saved_reg_area_pointer, 8397 __saved_reg_area_end_pointer); 8398 8399 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, InRegBlock); 8400 8401 // Argument in saved register area 8402 // Implement the block where argument is in register saved area 8403 CGF.EmitBlock(InRegBlock); 8404 8405 llvm::Type *PTy = CGF.ConvertType(Ty); 8406 llvm::Value *__saved_reg_area_p = CGF.Builder.CreateBitCast( 8407 __current_saved_reg_area_pointer, llvm::PointerType::getUnqual(PTy)); 8408 8409 CGF.Builder.CreateStore(__new_saved_reg_area_pointer, 8410 __current_saved_reg_area_pointer_p); 8411 8412 CGF.EmitBranch(ContBlock); 8413 8414 // Argument in overflow area 8415 // Implement the block where the argument is in overflow area. 8416 CGF.EmitBlock(OnStackBlock); 8417 8418 // Load the overflow area pointer 8419 Address __overflow_area_pointer_p = 8420 CGF.Builder.CreateStructGEP(VAListAddr, 2, "__overflow_area_pointer_p"); 8421 llvm::Value *__overflow_area_pointer = CGF.Builder.CreateLoad( 8422 __overflow_area_pointer_p, "__overflow_area_pointer"); 8423 8424 // Align the overflow area pointer according to the alignment of the argument 8425 if (ArgAlign > 4) { 8426 llvm::Value *__overflow_area_pointer_int = 8427 CGF.Builder.CreatePtrToInt(__overflow_area_pointer, CGF.Int32Ty); 8428 8429 __overflow_area_pointer_int = 8430 CGF.Builder.CreateAdd(__overflow_area_pointer_int, 8431 llvm::ConstantInt::get(CGF.Int32Ty, ArgAlign - 1), 8432 "align_overflow_area_pointer"); 8433 8434 __overflow_area_pointer_int = 8435 CGF.Builder.CreateAnd(__overflow_area_pointer_int, 8436 llvm::ConstantInt::get(CGF.Int32Ty, -ArgAlign), 8437 "align_overflow_area_pointer"); 8438 8439 __overflow_area_pointer = CGF.Builder.CreateIntToPtr( 8440 __overflow_area_pointer_int, __overflow_area_pointer->getType(), 8441 "align_overflow_area_pointer"); 8442 } 8443 8444 // Get the pointer for next argument in overflow area and store it 8445 // to overflow area pointer. 8446 llvm::Value *__new_overflow_area_pointer = CGF.Builder.CreateGEP( 8447 __overflow_area_pointer, llvm::ConstantInt::get(CGF.Int32Ty, ArgSize), 8448 "__overflow_area_pointer.next"); 8449 8450 CGF.Builder.CreateStore(__new_overflow_area_pointer, 8451 __overflow_area_pointer_p); 8452 8453 CGF.Builder.CreateStore(__new_overflow_area_pointer, 8454 __current_saved_reg_area_pointer_p); 8455 8456 // Bitcast the overflow area pointer to the type of argument. 8457 llvm::Type *OverflowPTy = CGF.ConvertTypeForMem(Ty); 8458 llvm::Value *__overflow_area_p = CGF.Builder.CreateBitCast( 8459 __overflow_area_pointer, llvm::PointerType::getUnqual(OverflowPTy)); 8460 8461 CGF.EmitBranch(ContBlock); 8462 8463 // Get the correct pointer to load the variable argument 8464 // Implement the ContBlock 8465 CGF.EmitBlock(ContBlock); 8466 8467 llvm::Type *MemPTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty)); 8468 llvm::PHINode *ArgAddr = CGF.Builder.CreatePHI(MemPTy, 2, "vaarg.addr"); 8469 ArgAddr->addIncoming(__saved_reg_area_p, InRegBlock); 8470 ArgAddr->addIncoming(__overflow_area_p, OnStackBlock); 8471 8472 return Address(ArgAddr, CharUnits::fromQuantity(ArgAlign)); 8473 } 8474 8475 Address HexagonABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 8476 QualType Ty) const { 8477 8478 if (getTarget().getTriple().isMusl()) 8479 return EmitVAArgForHexagonLinux(CGF, VAListAddr, Ty); 8480 8481 return EmitVAArgForHexagon(CGF, VAListAddr, Ty); 8482 } 8483 8484 //===----------------------------------------------------------------------===// 8485 // Lanai ABI Implementation 8486 //===----------------------------------------------------------------------===// 8487 8488 namespace { 8489 class LanaiABIInfo : public DefaultABIInfo { 8490 public: 8491 LanaiABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {} 8492 8493 bool shouldUseInReg(QualType Ty, CCState &State) const; 8494 8495 void computeInfo(CGFunctionInfo &FI) const override { 8496 CCState State(FI); 8497 // Lanai uses 4 registers to pass arguments unless the function has the 8498 // regparm attribute set. 8499 if (FI.getHasRegParm()) { 8500 State.FreeRegs = FI.getRegParm(); 8501 } else { 8502 State.FreeRegs = 4; 8503 } 8504 8505 if (!getCXXABI().classifyReturnType(FI)) 8506 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 8507 for (auto &I : FI.arguments()) 8508 I.info = classifyArgumentType(I.type, State); 8509 } 8510 8511 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const; 8512 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const; 8513 }; 8514 } // end anonymous namespace 8515 8516 bool LanaiABIInfo::shouldUseInReg(QualType Ty, CCState &State) const { 8517 unsigned Size = getContext().getTypeSize(Ty); 8518 unsigned SizeInRegs = llvm::alignTo(Size, 32U) / 32U; 8519 8520 if (SizeInRegs == 0) 8521 return false; 8522 8523 if (SizeInRegs > State.FreeRegs) { 8524 State.FreeRegs = 0; 8525 return false; 8526 } 8527 8528 State.FreeRegs -= SizeInRegs; 8529 8530 return true; 8531 } 8532 8533 ABIArgInfo LanaiABIInfo::getIndirectResult(QualType Ty, bool ByVal, 8534 CCState &State) const { 8535 if (!ByVal) { 8536 if (State.FreeRegs) { 8537 --State.FreeRegs; // Non-byval indirects just use one pointer. 8538 return getNaturalAlignIndirectInReg(Ty); 8539 } 8540 return getNaturalAlignIndirect(Ty, false); 8541 } 8542 8543 // Compute the byval alignment. 8544 const unsigned MinABIStackAlignInBytes = 4; 8545 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8; 8546 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true, 8547 /*Realign=*/TypeAlign > 8548 MinABIStackAlignInBytes); 8549 } 8550 8551 ABIArgInfo LanaiABIInfo::classifyArgumentType(QualType Ty, 8552 CCState &State) const { 8553 // Check with the C++ ABI first. 8554 const RecordType *RT = Ty->getAs<RecordType>(); 8555 if (RT) { 8556 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()); 8557 if (RAA == CGCXXABI::RAA_Indirect) { 8558 return getIndirectResult(Ty, /*ByVal=*/false, State); 8559 } else if (RAA == CGCXXABI::RAA_DirectInMemory) { 8560 return getNaturalAlignIndirect(Ty, /*ByRef=*/true); 8561 } 8562 } 8563 8564 if (isAggregateTypeForABI(Ty)) { 8565 // Structures with flexible arrays are always indirect. 8566 if (RT && RT->getDecl()->hasFlexibleArrayMember()) 8567 return getIndirectResult(Ty, /*ByVal=*/true, State); 8568 8569 // Ignore empty structs/unions. 8570 if (isEmptyRecord(getContext(), Ty, true)) 8571 return ABIArgInfo::getIgnore(); 8572 8573 llvm::LLVMContext &LLVMContext = getVMContext(); 8574 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32; 8575 if (SizeInRegs <= State.FreeRegs) { 8576 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext); 8577 SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32); 8578 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements); 8579 State.FreeRegs -= SizeInRegs; 8580 return ABIArgInfo::getDirectInReg(Result); 8581 } else { 8582 State.FreeRegs = 0; 8583 } 8584 return getIndirectResult(Ty, true, State); 8585 } 8586 8587 // Treat an enum type as its underlying type. 8588 if (const auto *EnumTy = Ty->getAs<EnumType>()) 8589 Ty = EnumTy->getDecl()->getIntegerType(); 8590 8591 bool InReg = shouldUseInReg(Ty, State); 8592 8593 // Don't pass >64 bit integers in registers. 8594 if (const auto *EIT = Ty->getAs<ExtIntType>()) 8595 if (EIT->getNumBits() > 64) 8596 return getIndirectResult(Ty, /*ByVal=*/true, State); 8597 8598 if (isPromotableIntegerTypeForABI(Ty)) { 8599 if (InReg) 8600 return ABIArgInfo::getDirectInReg(); 8601 return ABIArgInfo::getExtend(Ty); 8602 } 8603 if (InReg) 8604 return ABIArgInfo::getDirectInReg(); 8605 return ABIArgInfo::getDirect(); 8606 } 8607 8608 namespace { 8609 class LanaiTargetCodeGenInfo : public TargetCodeGenInfo { 8610 public: 8611 LanaiTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT) 8612 : TargetCodeGenInfo(std::make_unique<LanaiABIInfo>(CGT)) {} 8613 }; 8614 } 8615 8616 //===----------------------------------------------------------------------===// 8617 // AMDGPU ABI Implementation 8618 //===----------------------------------------------------------------------===// 8619 8620 namespace { 8621 8622 class AMDGPUABIInfo final : public DefaultABIInfo { 8623 private: 8624 static const unsigned MaxNumRegsForArgsRet = 16; 8625 8626 unsigned numRegsForType(QualType Ty) const; 8627 8628 bool isHomogeneousAggregateBaseType(QualType Ty) const override; 8629 bool isHomogeneousAggregateSmallEnough(const Type *Base, 8630 uint64_t Members) const override; 8631 8632 // Coerce HIP pointer arguments from generic pointers to global ones. 8633 llvm::Type *coerceKernelArgumentType(llvm::Type *Ty, unsigned FromAS, 8634 unsigned ToAS) const { 8635 // Structure types. 8636 if (auto STy = dyn_cast<llvm::StructType>(Ty)) { 8637 SmallVector<llvm::Type *, 8> EltTys; 8638 bool Changed = false; 8639 for (auto T : STy->elements()) { 8640 auto NT = coerceKernelArgumentType(T, FromAS, ToAS); 8641 EltTys.push_back(NT); 8642 Changed |= (NT != T); 8643 } 8644 // Skip if there is no change in element types. 8645 if (!Changed) 8646 return STy; 8647 if (STy->hasName()) 8648 return llvm::StructType::create( 8649 EltTys, (STy->getName() + ".coerce").str(), STy->isPacked()); 8650 return llvm::StructType::get(getVMContext(), EltTys, STy->isPacked()); 8651 } 8652 // Array types. 8653 if (auto ATy = dyn_cast<llvm::ArrayType>(Ty)) { 8654 auto T = ATy->getElementType(); 8655 auto NT = coerceKernelArgumentType(T, FromAS, ToAS); 8656 // Skip if there is no change in that element type. 8657 if (NT == T) 8658 return ATy; 8659 return llvm::ArrayType::get(NT, ATy->getNumElements()); 8660 } 8661 // Single value types. 8662 if (Ty->isPointerTy() && Ty->getPointerAddressSpace() == FromAS) 8663 return llvm::PointerType::get( 8664 cast<llvm::PointerType>(Ty)->getElementType(), ToAS); 8665 return Ty; 8666 } 8667 8668 public: 8669 explicit AMDGPUABIInfo(CodeGen::CodeGenTypes &CGT) : 8670 DefaultABIInfo(CGT) {} 8671 8672 ABIArgInfo classifyReturnType(QualType RetTy) const; 8673 ABIArgInfo classifyKernelArgumentType(QualType Ty) const; 8674 ABIArgInfo classifyArgumentType(QualType Ty, unsigned &NumRegsLeft) const; 8675 8676 void computeInfo(CGFunctionInfo &FI) const override; 8677 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 8678 QualType Ty) const override; 8679 }; 8680 8681 bool AMDGPUABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const { 8682 return true; 8683 } 8684 8685 bool AMDGPUABIInfo::isHomogeneousAggregateSmallEnough( 8686 const Type *Base, uint64_t Members) const { 8687 uint32_t NumRegs = (getContext().getTypeSize(Base) + 31) / 32; 8688 8689 // Homogeneous Aggregates may occupy at most 16 registers. 8690 return Members * NumRegs <= MaxNumRegsForArgsRet; 8691 } 8692 8693 /// Estimate number of registers the type will use when passed in registers. 8694 unsigned AMDGPUABIInfo::numRegsForType(QualType Ty) const { 8695 unsigned NumRegs = 0; 8696 8697 if (const VectorType *VT = Ty->getAs<VectorType>()) { 8698 // Compute from the number of elements. The reported size is based on the 8699 // in-memory size, which includes the padding 4th element for 3-vectors. 8700 QualType EltTy = VT->getElementType(); 8701 unsigned EltSize = getContext().getTypeSize(EltTy); 8702 8703 // 16-bit element vectors should be passed as packed. 8704 if (EltSize == 16) 8705 return (VT->getNumElements() + 1) / 2; 8706 8707 unsigned EltNumRegs = (EltSize + 31) / 32; 8708 return EltNumRegs * VT->getNumElements(); 8709 } 8710 8711 if (const RecordType *RT = Ty->getAs<RecordType>()) { 8712 const RecordDecl *RD = RT->getDecl(); 8713 assert(!RD->hasFlexibleArrayMember()); 8714 8715 for (const FieldDecl *Field : RD->fields()) { 8716 QualType FieldTy = Field->getType(); 8717 NumRegs += numRegsForType(FieldTy); 8718 } 8719 8720 return NumRegs; 8721 } 8722 8723 return (getContext().getTypeSize(Ty) + 31) / 32; 8724 } 8725 8726 void AMDGPUABIInfo::computeInfo(CGFunctionInfo &FI) const { 8727 llvm::CallingConv::ID CC = FI.getCallingConvention(); 8728 8729 if (!getCXXABI().classifyReturnType(FI)) 8730 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 8731 8732 unsigned NumRegsLeft = MaxNumRegsForArgsRet; 8733 for (auto &Arg : FI.arguments()) { 8734 if (CC == llvm::CallingConv::AMDGPU_KERNEL) { 8735 Arg.info = classifyKernelArgumentType(Arg.type); 8736 } else { 8737 Arg.info = classifyArgumentType(Arg.type, NumRegsLeft); 8738 } 8739 } 8740 } 8741 8742 Address AMDGPUABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 8743 QualType Ty) const { 8744 llvm_unreachable("AMDGPU does not support varargs"); 8745 } 8746 8747 ABIArgInfo AMDGPUABIInfo::classifyReturnType(QualType RetTy) const { 8748 if (isAggregateTypeForABI(RetTy)) { 8749 // Records with non-trivial destructors/copy-constructors should not be 8750 // returned by value. 8751 if (!getRecordArgABI(RetTy, getCXXABI())) { 8752 // Ignore empty structs/unions. 8753 if (isEmptyRecord(getContext(), RetTy, true)) 8754 return ABIArgInfo::getIgnore(); 8755 8756 // Lower single-element structs to just return a regular value. 8757 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext())) 8758 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0))); 8759 8760 if (const RecordType *RT = RetTy->getAs<RecordType>()) { 8761 const RecordDecl *RD = RT->getDecl(); 8762 if (RD->hasFlexibleArrayMember()) 8763 return DefaultABIInfo::classifyReturnType(RetTy); 8764 } 8765 8766 // Pack aggregates <= 4 bytes into single VGPR or pair. 8767 uint64_t Size = getContext().getTypeSize(RetTy); 8768 if (Size <= 16) 8769 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext())); 8770 8771 if (Size <= 32) 8772 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext())); 8773 8774 if (Size <= 64) { 8775 llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext()); 8776 return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2)); 8777 } 8778 8779 if (numRegsForType(RetTy) <= MaxNumRegsForArgsRet) 8780 return ABIArgInfo::getDirect(); 8781 } 8782 } 8783 8784 // Otherwise just do the default thing. 8785 return DefaultABIInfo::classifyReturnType(RetTy); 8786 } 8787 8788 /// For kernels all parameters are really passed in a special buffer. It doesn't 8789 /// make sense to pass anything byval, so everything must be direct. 8790 ABIArgInfo AMDGPUABIInfo::classifyKernelArgumentType(QualType Ty) const { 8791 Ty = useFirstFieldIfTransparentUnion(Ty); 8792 8793 // TODO: Can we omit empty structs? 8794 8795 llvm::Type *LTy = nullptr; 8796 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext())) 8797 LTy = CGT.ConvertType(QualType(SeltTy, 0)); 8798 8799 if (getContext().getLangOpts().HIP) { 8800 if (!LTy) 8801 LTy = CGT.ConvertType(Ty); 8802 LTy = coerceKernelArgumentType( 8803 LTy, /*FromAS=*/getContext().getTargetAddressSpace(LangAS::Default), 8804 /*ToAS=*/getContext().getTargetAddressSpace(LangAS::cuda_device)); 8805 } 8806 8807 // If we set CanBeFlattened to true, CodeGen will expand the struct to its 8808 // individual elements, which confuses the Clover OpenCL backend; therefore we 8809 // have to set it to false here. Other args of getDirect() are just defaults. 8810 return ABIArgInfo::getDirect(LTy, 0, nullptr, false); 8811 } 8812 8813 ABIArgInfo AMDGPUABIInfo::classifyArgumentType(QualType Ty, 8814 unsigned &NumRegsLeft) const { 8815 assert(NumRegsLeft <= MaxNumRegsForArgsRet && "register estimate underflow"); 8816 8817 Ty = useFirstFieldIfTransparentUnion(Ty); 8818 8819 if (isAggregateTypeForABI(Ty)) { 8820 // Records with non-trivial destructors/copy-constructors should not be 8821 // passed by value. 8822 if (auto RAA = getRecordArgABI(Ty, getCXXABI())) 8823 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 8824 8825 // Ignore empty structs/unions. 8826 if (isEmptyRecord(getContext(), Ty, true)) 8827 return ABIArgInfo::getIgnore(); 8828 8829 // Lower single-element structs to just pass a regular value. TODO: We 8830 // could do reasonable-size multiple-element structs too, using getExpand(), 8831 // though watch out for things like bitfields. 8832 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext())) 8833 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0))); 8834 8835 if (const RecordType *RT = Ty->getAs<RecordType>()) { 8836 const RecordDecl *RD = RT->getDecl(); 8837 if (RD->hasFlexibleArrayMember()) 8838 return DefaultABIInfo::classifyArgumentType(Ty); 8839 } 8840 8841 // Pack aggregates <= 8 bytes into single VGPR or pair. 8842 uint64_t Size = getContext().getTypeSize(Ty); 8843 if (Size <= 64) { 8844 unsigned NumRegs = (Size + 31) / 32; 8845 NumRegsLeft -= std::min(NumRegsLeft, NumRegs); 8846 8847 if (Size <= 16) 8848 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext())); 8849 8850 if (Size <= 32) 8851 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext())); 8852 8853 // XXX: Should this be i64 instead, and should the limit increase? 8854 llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext()); 8855 return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2)); 8856 } 8857 8858 if (NumRegsLeft > 0) { 8859 unsigned NumRegs = numRegsForType(Ty); 8860 if (NumRegsLeft >= NumRegs) { 8861 NumRegsLeft -= NumRegs; 8862 return ABIArgInfo::getDirect(); 8863 } 8864 } 8865 } 8866 8867 // Otherwise just do the default thing. 8868 ABIArgInfo ArgInfo = DefaultABIInfo::classifyArgumentType(Ty); 8869 if (!ArgInfo.isIndirect()) { 8870 unsigned NumRegs = numRegsForType(Ty); 8871 NumRegsLeft -= std::min(NumRegs, NumRegsLeft); 8872 } 8873 8874 return ArgInfo; 8875 } 8876 8877 class AMDGPUTargetCodeGenInfo : public TargetCodeGenInfo { 8878 public: 8879 AMDGPUTargetCodeGenInfo(CodeGenTypes &CGT) 8880 : TargetCodeGenInfo(std::make_unique<AMDGPUABIInfo>(CGT)) {} 8881 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 8882 CodeGen::CodeGenModule &M) const override; 8883 unsigned getOpenCLKernelCallingConv() const override; 8884 8885 llvm::Constant *getNullPointer(const CodeGen::CodeGenModule &CGM, 8886 llvm::PointerType *T, QualType QT) const override; 8887 8888 LangAS getASTAllocaAddressSpace() const override { 8889 return getLangASFromTargetAS( 8890 getABIInfo().getDataLayout().getAllocaAddrSpace()); 8891 } 8892 LangAS getGlobalVarAddressSpace(CodeGenModule &CGM, 8893 const VarDecl *D) const override; 8894 llvm::SyncScope::ID getLLVMSyncScopeID(const LangOptions &LangOpts, 8895 SyncScope Scope, 8896 llvm::AtomicOrdering Ordering, 8897 llvm::LLVMContext &Ctx) const override; 8898 llvm::Function * 8899 createEnqueuedBlockKernel(CodeGenFunction &CGF, 8900 llvm::Function *BlockInvokeFunc, 8901 llvm::Value *BlockLiteral) const override; 8902 bool shouldEmitStaticExternCAliases() const override; 8903 void setCUDAKernelCallingConvention(const FunctionType *&FT) const override; 8904 }; 8905 } 8906 8907 static bool requiresAMDGPUProtectedVisibility(const Decl *D, 8908 llvm::GlobalValue *GV) { 8909 if (GV->getVisibility() != llvm::GlobalValue::HiddenVisibility) 8910 return false; 8911 8912 return D->hasAttr<OpenCLKernelAttr>() || 8913 (isa<FunctionDecl>(D) && D->hasAttr<CUDAGlobalAttr>()) || 8914 (isa<VarDecl>(D) && 8915 (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>() || 8916 cast<VarDecl>(D)->getType()->isCUDADeviceBuiltinSurfaceType() || 8917 cast<VarDecl>(D)->getType()->isCUDADeviceBuiltinTextureType())); 8918 } 8919 8920 void AMDGPUTargetCodeGenInfo::setTargetAttributes( 8921 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const { 8922 if (requiresAMDGPUProtectedVisibility(D, GV)) { 8923 GV->setVisibility(llvm::GlobalValue::ProtectedVisibility); 8924 GV->setDSOLocal(true); 8925 } 8926 8927 if (GV->isDeclaration()) 8928 return; 8929 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D); 8930 if (!FD) 8931 return; 8932 8933 llvm::Function *F = cast<llvm::Function>(GV); 8934 8935 const auto *ReqdWGS = M.getLangOpts().OpenCL ? 8936 FD->getAttr<ReqdWorkGroupSizeAttr>() : nullptr; 8937 8938 8939 const bool IsOpenCLKernel = M.getLangOpts().OpenCL && 8940 FD->hasAttr<OpenCLKernelAttr>(); 8941 const bool IsHIPKernel = M.getLangOpts().HIP && 8942 FD->hasAttr<CUDAGlobalAttr>(); 8943 if ((IsOpenCLKernel || IsHIPKernel) && 8944 (M.getTriple().getOS() == llvm::Triple::AMDHSA)) 8945 F->addFnAttr("amdgpu-implicitarg-num-bytes", "56"); 8946 8947 if (IsHIPKernel) 8948 F->addFnAttr("uniform-work-group-size", "true"); 8949 8950 8951 const auto *FlatWGS = FD->getAttr<AMDGPUFlatWorkGroupSizeAttr>(); 8952 if (ReqdWGS || FlatWGS) { 8953 unsigned Min = 0; 8954 unsigned Max = 0; 8955 if (FlatWGS) { 8956 Min = FlatWGS->getMin() 8957 ->EvaluateKnownConstInt(M.getContext()) 8958 .getExtValue(); 8959 Max = FlatWGS->getMax() 8960 ->EvaluateKnownConstInt(M.getContext()) 8961 .getExtValue(); 8962 } 8963 if (ReqdWGS && Min == 0 && Max == 0) 8964 Min = Max = ReqdWGS->getXDim() * ReqdWGS->getYDim() * ReqdWGS->getZDim(); 8965 8966 if (Min != 0) { 8967 assert(Min <= Max && "Min must be less than or equal Max"); 8968 8969 std::string AttrVal = llvm::utostr(Min) + "," + llvm::utostr(Max); 8970 F->addFnAttr("amdgpu-flat-work-group-size", AttrVal); 8971 } else 8972 assert(Max == 0 && "Max must be zero"); 8973 } else if (IsOpenCLKernel || IsHIPKernel) { 8974 // By default, restrict the maximum size to a value specified by 8975 // --gpu-max-threads-per-block=n or its default value for HIP. 8976 const unsigned OpenCLDefaultMaxWorkGroupSize = 256; 8977 const unsigned DefaultMaxWorkGroupSize = 8978 IsOpenCLKernel ? OpenCLDefaultMaxWorkGroupSize 8979 : M.getLangOpts().GPUMaxThreadsPerBlock; 8980 std::string AttrVal = 8981 std::string("1,") + llvm::utostr(DefaultMaxWorkGroupSize); 8982 F->addFnAttr("amdgpu-flat-work-group-size", AttrVal); 8983 } 8984 8985 if (const auto *Attr = FD->getAttr<AMDGPUWavesPerEUAttr>()) { 8986 unsigned Min = 8987 Attr->getMin()->EvaluateKnownConstInt(M.getContext()).getExtValue(); 8988 unsigned Max = Attr->getMax() ? Attr->getMax() 8989 ->EvaluateKnownConstInt(M.getContext()) 8990 .getExtValue() 8991 : 0; 8992 8993 if (Min != 0) { 8994 assert((Max == 0 || Min <= Max) && "Min must be less than or equal Max"); 8995 8996 std::string AttrVal = llvm::utostr(Min); 8997 if (Max != 0) 8998 AttrVal = AttrVal + "," + llvm::utostr(Max); 8999 F->addFnAttr("amdgpu-waves-per-eu", AttrVal); 9000 } else 9001 assert(Max == 0 && "Max must be zero"); 9002 } 9003 9004 if (const auto *Attr = FD->getAttr<AMDGPUNumSGPRAttr>()) { 9005 unsigned NumSGPR = Attr->getNumSGPR(); 9006 9007 if (NumSGPR != 0) 9008 F->addFnAttr("amdgpu-num-sgpr", llvm::utostr(NumSGPR)); 9009 } 9010 9011 if (const auto *Attr = FD->getAttr<AMDGPUNumVGPRAttr>()) { 9012 uint32_t NumVGPR = Attr->getNumVGPR(); 9013 9014 if (NumVGPR != 0) 9015 F->addFnAttr("amdgpu-num-vgpr", llvm::utostr(NumVGPR)); 9016 } 9017 } 9018 9019 unsigned AMDGPUTargetCodeGenInfo::getOpenCLKernelCallingConv() const { 9020 return llvm::CallingConv::AMDGPU_KERNEL; 9021 } 9022 9023 // Currently LLVM assumes null pointers always have value 0, 9024 // which results in incorrectly transformed IR. Therefore, instead of 9025 // emitting null pointers in private and local address spaces, a null 9026 // pointer in generic address space is emitted which is casted to a 9027 // pointer in local or private address space. 9028 llvm::Constant *AMDGPUTargetCodeGenInfo::getNullPointer( 9029 const CodeGen::CodeGenModule &CGM, llvm::PointerType *PT, 9030 QualType QT) const { 9031 if (CGM.getContext().getTargetNullPointerValue(QT) == 0) 9032 return llvm::ConstantPointerNull::get(PT); 9033 9034 auto &Ctx = CGM.getContext(); 9035 auto NPT = llvm::PointerType::get(PT->getElementType(), 9036 Ctx.getTargetAddressSpace(LangAS::opencl_generic)); 9037 return llvm::ConstantExpr::getAddrSpaceCast( 9038 llvm::ConstantPointerNull::get(NPT), PT); 9039 } 9040 9041 LangAS 9042 AMDGPUTargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM, 9043 const VarDecl *D) const { 9044 assert(!CGM.getLangOpts().OpenCL && 9045 !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) && 9046 "Address space agnostic languages only"); 9047 LangAS DefaultGlobalAS = getLangASFromTargetAS( 9048 CGM.getContext().getTargetAddressSpace(LangAS::opencl_global)); 9049 if (!D) 9050 return DefaultGlobalAS; 9051 9052 LangAS AddrSpace = D->getType().getAddressSpace(); 9053 assert(AddrSpace == LangAS::Default || isTargetAddressSpace(AddrSpace)); 9054 if (AddrSpace != LangAS::Default) 9055 return AddrSpace; 9056 9057 if (CGM.isTypeConstant(D->getType(), false)) { 9058 if (auto ConstAS = CGM.getTarget().getConstantAddressSpace()) 9059 return ConstAS.getValue(); 9060 } 9061 return DefaultGlobalAS; 9062 } 9063 9064 llvm::SyncScope::ID 9065 AMDGPUTargetCodeGenInfo::getLLVMSyncScopeID(const LangOptions &LangOpts, 9066 SyncScope Scope, 9067 llvm::AtomicOrdering Ordering, 9068 llvm::LLVMContext &Ctx) const { 9069 std::string Name; 9070 switch (Scope) { 9071 case SyncScope::OpenCLWorkGroup: 9072 Name = "workgroup"; 9073 break; 9074 case SyncScope::OpenCLDevice: 9075 Name = "agent"; 9076 break; 9077 case SyncScope::OpenCLAllSVMDevices: 9078 Name = ""; 9079 break; 9080 case SyncScope::OpenCLSubGroup: 9081 Name = "wavefront"; 9082 } 9083 9084 if (Ordering != llvm::AtomicOrdering::SequentiallyConsistent) { 9085 if (!Name.empty()) 9086 Name = Twine(Twine(Name) + Twine("-")).str(); 9087 9088 Name = Twine(Twine(Name) + Twine("one-as")).str(); 9089 } 9090 9091 return Ctx.getOrInsertSyncScopeID(Name); 9092 } 9093 9094 bool AMDGPUTargetCodeGenInfo::shouldEmitStaticExternCAliases() const { 9095 return false; 9096 } 9097 9098 void AMDGPUTargetCodeGenInfo::setCUDAKernelCallingConvention( 9099 const FunctionType *&FT) const { 9100 FT = getABIInfo().getContext().adjustFunctionType( 9101 FT, FT->getExtInfo().withCallingConv(CC_OpenCLKernel)); 9102 } 9103 9104 //===----------------------------------------------------------------------===// 9105 // SPARC v8 ABI Implementation. 9106 // Based on the SPARC Compliance Definition version 2.4.1. 9107 // 9108 // Ensures that complex values are passed in registers. 9109 // 9110 namespace { 9111 class SparcV8ABIInfo : public DefaultABIInfo { 9112 public: 9113 SparcV8ABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {} 9114 9115 private: 9116 ABIArgInfo classifyReturnType(QualType RetTy) const; 9117 void computeInfo(CGFunctionInfo &FI) const override; 9118 }; 9119 } // end anonymous namespace 9120 9121 9122 ABIArgInfo 9123 SparcV8ABIInfo::classifyReturnType(QualType Ty) const { 9124 if (Ty->isAnyComplexType()) { 9125 return ABIArgInfo::getDirect(); 9126 } 9127 else { 9128 return DefaultABIInfo::classifyReturnType(Ty); 9129 } 9130 } 9131 9132 void SparcV8ABIInfo::computeInfo(CGFunctionInfo &FI) const { 9133 9134 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 9135 for (auto &Arg : FI.arguments()) 9136 Arg.info = classifyArgumentType(Arg.type); 9137 } 9138 9139 namespace { 9140 class SparcV8TargetCodeGenInfo : public TargetCodeGenInfo { 9141 public: 9142 SparcV8TargetCodeGenInfo(CodeGenTypes &CGT) 9143 : TargetCodeGenInfo(std::make_unique<SparcV8ABIInfo>(CGT)) {} 9144 }; 9145 } // end anonymous namespace 9146 9147 //===----------------------------------------------------------------------===// 9148 // SPARC v9 ABI Implementation. 9149 // Based on the SPARC Compliance Definition version 2.4.1. 9150 // 9151 // Function arguments a mapped to a nominal "parameter array" and promoted to 9152 // registers depending on their type. Each argument occupies 8 or 16 bytes in 9153 // the array, structs larger than 16 bytes are passed indirectly. 9154 // 9155 // One case requires special care: 9156 // 9157 // struct mixed { 9158 // int i; 9159 // float f; 9160 // }; 9161 // 9162 // When a struct mixed is passed by value, it only occupies 8 bytes in the 9163 // parameter array, but the int is passed in an integer register, and the float 9164 // is passed in a floating point register. This is represented as two arguments 9165 // with the LLVM IR inreg attribute: 9166 // 9167 // declare void f(i32 inreg %i, float inreg %f) 9168 // 9169 // The code generator will only allocate 4 bytes from the parameter array for 9170 // the inreg arguments. All other arguments are allocated a multiple of 8 9171 // bytes. 9172 // 9173 namespace { 9174 class SparcV9ABIInfo : public ABIInfo { 9175 public: 9176 SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {} 9177 9178 private: 9179 ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const; 9180 void computeInfo(CGFunctionInfo &FI) const override; 9181 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 9182 QualType Ty) const override; 9183 9184 // Coercion type builder for structs passed in registers. The coercion type 9185 // serves two purposes: 9186 // 9187 // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned' 9188 // in registers. 9189 // 2. Expose aligned floating point elements as first-level elements, so the 9190 // code generator knows to pass them in floating point registers. 9191 // 9192 // We also compute the InReg flag which indicates that the struct contains 9193 // aligned 32-bit floats. 9194 // 9195 struct CoerceBuilder { 9196 llvm::LLVMContext &Context; 9197 const llvm::DataLayout &DL; 9198 SmallVector<llvm::Type*, 8> Elems; 9199 uint64_t Size; 9200 bool InReg; 9201 9202 CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl) 9203 : Context(c), DL(dl), Size(0), InReg(false) {} 9204 9205 // Pad Elems with integers until Size is ToSize. 9206 void pad(uint64_t ToSize) { 9207 assert(ToSize >= Size && "Cannot remove elements"); 9208 if (ToSize == Size) 9209 return; 9210 9211 // Finish the current 64-bit word. 9212 uint64_t Aligned = llvm::alignTo(Size, 64); 9213 if (Aligned > Size && Aligned <= ToSize) { 9214 Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size)); 9215 Size = Aligned; 9216 } 9217 9218 // Add whole 64-bit words. 9219 while (Size + 64 <= ToSize) { 9220 Elems.push_back(llvm::Type::getInt64Ty(Context)); 9221 Size += 64; 9222 } 9223 9224 // Final in-word padding. 9225 if (Size < ToSize) { 9226 Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size)); 9227 Size = ToSize; 9228 } 9229 } 9230 9231 // Add a floating point element at Offset. 9232 void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) { 9233 // Unaligned floats are treated as integers. 9234 if (Offset % Bits) 9235 return; 9236 // The InReg flag is only required if there are any floats < 64 bits. 9237 if (Bits < 64) 9238 InReg = true; 9239 pad(Offset); 9240 Elems.push_back(Ty); 9241 Size = Offset + Bits; 9242 } 9243 9244 // Add a struct type to the coercion type, starting at Offset (in bits). 9245 void addStruct(uint64_t Offset, llvm::StructType *StrTy) { 9246 const llvm::StructLayout *Layout = DL.getStructLayout(StrTy); 9247 for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) { 9248 llvm::Type *ElemTy = StrTy->getElementType(i); 9249 uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i); 9250 switch (ElemTy->getTypeID()) { 9251 case llvm::Type::StructTyID: 9252 addStruct(ElemOffset, cast<llvm::StructType>(ElemTy)); 9253 break; 9254 case llvm::Type::FloatTyID: 9255 addFloat(ElemOffset, ElemTy, 32); 9256 break; 9257 case llvm::Type::DoubleTyID: 9258 addFloat(ElemOffset, ElemTy, 64); 9259 break; 9260 case llvm::Type::FP128TyID: 9261 addFloat(ElemOffset, ElemTy, 128); 9262 break; 9263 case llvm::Type::PointerTyID: 9264 if (ElemOffset % 64 == 0) { 9265 pad(ElemOffset); 9266 Elems.push_back(ElemTy); 9267 Size += 64; 9268 } 9269 break; 9270 default: 9271 break; 9272 } 9273 } 9274 } 9275 9276 // Check if Ty is a usable substitute for the coercion type. 9277 bool isUsableType(llvm::StructType *Ty) const { 9278 return llvm::makeArrayRef(Elems) == Ty->elements(); 9279 } 9280 9281 // Get the coercion type as a literal struct type. 9282 llvm::Type *getType() const { 9283 if (Elems.size() == 1) 9284 return Elems.front(); 9285 else 9286 return llvm::StructType::get(Context, Elems); 9287 } 9288 }; 9289 }; 9290 } // end anonymous namespace 9291 9292 ABIArgInfo 9293 SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const { 9294 if (Ty->isVoidType()) 9295 return ABIArgInfo::getIgnore(); 9296 9297 uint64_t Size = getContext().getTypeSize(Ty); 9298 9299 // Anything too big to fit in registers is passed with an explicit indirect 9300 // pointer / sret pointer. 9301 if (Size > SizeLimit) 9302 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 9303 9304 // Treat an enum type as its underlying type. 9305 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 9306 Ty = EnumTy->getDecl()->getIntegerType(); 9307 9308 // Integer types smaller than a register are extended. 9309 if (Size < 64 && Ty->isIntegerType()) 9310 return ABIArgInfo::getExtend(Ty); 9311 9312 if (const auto *EIT = Ty->getAs<ExtIntType>()) 9313 if (EIT->getNumBits() < 64) 9314 return ABIArgInfo::getExtend(Ty); 9315 9316 // Other non-aggregates go in registers. 9317 if (!isAggregateTypeForABI(Ty)) 9318 return ABIArgInfo::getDirect(); 9319 9320 // If a C++ object has either a non-trivial copy constructor or a non-trivial 9321 // destructor, it is passed with an explicit indirect pointer / sret pointer. 9322 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 9323 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 9324 9325 // This is a small aggregate type that should be passed in registers. 9326 // Build a coercion type from the LLVM struct type. 9327 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty)); 9328 if (!StrTy) 9329 return ABIArgInfo::getDirect(); 9330 9331 CoerceBuilder CB(getVMContext(), getDataLayout()); 9332 CB.addStruct(0, StrTy); 9333 CB.pad(llvm::alignTo(CB.DL.getTypeSizeInBits(StrTy), 64)); 9334 9335 // Try to use the original type for coercion. 9336 llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType(); 9337 9338 if (CB.InReg) 9339 return ABIArgInfo::getDirectInReg(CoerceTy); 9340 else 9341 return ABIArgInfo::getDirect(CoerceTy); 9342 } 9343 9344 Address SparcV9ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 9345 QualType Ty) const { 9346 ABIArgInfo AI = classifyType(Ty, 16 * 8); 9347 llvm::Type *ArgTy = CGT.ConvertType(Ty); 9348 if (AI.canHaveCoerceToType() && !AI.getCoerceToType()) 9349 AI.setCoerceToType(ArgTy); 9350 9351 CharUnits SlotSize = CharUnits::fromQuantity(8); 9352 9353 CGBuilderTy &Builder = CGF.Builder; 9354 Address Addr(Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize); 9355 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy); 9356 9357 auto TypeInfo = getContext().getTypeInfoInChars(Ty); 9358 9359 Address ArgAddr = Address::invalid(); 9360 CharUnits Stride; 9361 switch (AI.getKind()) { 9362 case ABIArgInfo::Expand: 9363 case ABIArgInfo::CoerceAndExpand: 9364 case ABIArgInfo::InAlloca: 9365 llvm_unreachable("Unsupported ABI kind for va_arg"); 9366 9367 case ABIArgInfo::Extend: { 9368 Stride = SlotSize; 9369 CharUnits Offset = SlotSize - TypeInfo.first; 9370 ArgAddr = Builder.CreateConstInBoundsByteGEP(Addr, Offset, "extend"); 9371 break; 9372 } 9373 9374 case ABIArgInfo::Direct: { 9375 auto AllocSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType()); 9376 Stride = CharUnits::fromQuantity(AllocSize).alignTo(SlotSize); 9377 ArgAddr = Addr; 9378 break; 9379 } 9380 9381 case ABIArgInfo::Indirect: 9382 Stride = SlotSize; 9383 ArgAddr = Builder.CreateElementBitCast(Addr, ArgPtrTy, "indirect"); 9384 ArgAddr = Address(Builder.CreateLoad(ArgAddr, "indirect.arg"), 9385 TypeInfo.second); 9386 break; 9387 9388 case ABIArgInfo::Ignore: 9389 return Address(llvm::UndefValue::get(ArgPtrTy), TypeInfo.second); 9390 } 9391 9392 // Update VAList. 9393 Address NextPtr = Builder.CreateConstInBoundsByteGEP(Addr, Stride, "ap.next"); 9394 Builder.CreateStore(NextPtr.getPointer(), VAListAddr); 9395 9396 return Builder.CreateBitCast(ArgAddr, ArgPtrTy, "arg.addr"); 9397 } 9398 9399 void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const { 9400 FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8); 9401 for (auto &I : FI.arguments()) 9402 I.info = classifyType(I.type, 16 * 8); 9403 } 9404 9405 namespace { 9406 class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo { 9407 public: 9408 SparcV9TargetCodeGenInfo(CodeGenTypes &CGT) 9409 : TargetCodeGenInfo(std::make_unique<SparcV9ABIInfo>(CGT)) {} 9410 9411 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 9412 return 14; 9413 } 9414 9415 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 9416 llvm::Value *Address) const override; 9417 }; 9418 } // end anonymous namespace 9419 9420 bool 9421 SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 9422 llvm::Value *Address) const { 9423 // This is calculated from the LLVM and GCC tables and verified 9424 // against gcc output. AFAIK all ABIs use the same encoding. 9425 9426 CodeGen::CGBuilderTy &Builder = CGF.Builder; 9427 9428 llvm::IntegerType *i8 = CGF.Int8Ty; 9429 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4); 9430 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8); 9431 9432 // 0-31: the 8-byte general-purpose registers 9433 AssignToArrayRange(Builder, Address, Eight8, 0, 31); 9434 9435 // 32-63: f0-31, the 4-byte floating-point registers 9436 AssignToArrayRange(Builder, Address, Four8, 32, 63); 9437 9438 // Y = 64 9439 // PSR = 65 9440 // WIM = 66 9441 // TBR = 67 9442 // PC = 68 9443 // NPC = 69 9444 // FSR = 70 9445 // CSR = 71 9446 AssignToArrayRange(Builder, Address, Eight8, 64, 71); 9447 9448 // 72-87: d0-15, the 8-byte floating-point registers 9449 AssignToArrayRange(Builder, Address, Eight8, 72, 87); 9450 9451 return false; 9452 } 9453 9454 // ARC ABI implementation. 9455 namespace { 9456 9457 class ARCABIInfo : public DefaultABIInfo { 9458 public: 9459 using DefaultABIInfo::DefaultABIInfo; 9460 9461 private: 9462 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 9463 QualType Ty) const override; 9464 9465 void updateState(const ABIArgInfo &Info, QualType Ty, CCState &State) const { 9466 if (!State.FreeRegs) 9467 return; 9468 if (Info.isIndirect() && Info.getInReg()) 9469 State.FreeRegs--; 9470 else if (Info.isDirect() && Info.getInReg()) { 9471 unsigned sz = (getContext().getTypeSize(Ty) + 31) / 32; 9472 if (sz < State.FreeRegs) 9473 State.FreeRegs -= sz; 9474 else 9475 State.FreeRegs = 0; 9476 } 9477 } 9478 9479 void computeInfo(CGFunctionInfo &FI) const override { 9480 CCState State(FI); 9481 // ARC uses 8 registers to pass arguments. 9482 State.FreeRegs = 8; 9483 9484 if (!getCXXABI().classifyReturnType(FI)) 9485 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 9486 updateState(FI.getReturnInfo(), FI.getReturnType(), State); 9487 for (auto &I : FI.arguments()) { 9488 I.info = classifyArgumentType(I.type, State.FreeRegs); 9489 updateState(I.info, I.type, State); 9490 } 9491 } 9492 9493 ABIArgInfo getIndirectByRef(QualType Ty, bool HasFreeRegs) const; 9494 ABIArgInfo getIndirectByValue(QualType Ty) const; 9495 ABIArgInfo classifyArgumentType(QualType Ty, uint8_t FreeRegs) const; 9496 ABIArgInfo classifyReturnType(QualType RetTy) const; 9497 }; 9498 9499 class ARCTargetCodeGenInfo : public TargetCodeGenInfo { 9500 public: 9501 ARCTargetCodeGenInfo(CodeGenTypes &CGT) 9502 : TargetCodeGenInfo(std::make_unique<ARCABIInfo>(CGT)) {} 9503 }; 9504 9505 9506 ABIArgInfo ARCABIInfo::getIndirectByRef(QualType Ty, bool HasFreeRegs) const { 9507 return HasFreeRegs ? getNaturalAlignIndirectInReg(Ty) : 9508 getNaturalAlignIndirect(Ty, false); 9509 } 9510 9511 ABIArgInfo ARCABIInfo::getIndirectByValue(QualType Ty) const { 9512 // Compute the byval alignment. 9513 const unsigned MinABIStackAlignInBytes = 4; 9514 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8; 9515 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true, 9516 TypeAlign > MinABIStackAlignInBytes); 9517 } 9518 9519 Address ARCABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 9520 QualType Ty) const { 9521 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false, 9522 getContext().getTypeInfoInChars(Ty), 9523 CharUnits::fromQuantity(4), true); 9524 } 9525 9526 ABIArgInfo ARCABIInfo::classifyArgumentType(QualType Ty, 9527 uint8_t FreeRegs) const { 9528 // Handle the generic C++ ABI. 9529 const RecordType *RT = Ty->getAs<RecordType>(); 9530 if (RT) { 9531 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()); 9532 if (RAA == CGCXXABI::RAA_Indirect) 9533 return getIndirectByRef(Ty, FreeRegs > 0); 9534 9535 if (RAA == CGCXXABI::RAA_DirectInMemory) 9536 return getIndirectByValue(Ty); 9537 } 9538 9539 // Treat an enum type as its underlying type. 9540 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 9541 Ty = EnumTy->getDecl()->getIntegerType(); 9542 9543 auto SizeInRegs = llvm::alignTo(getContext().getTypeSize(Ty), 32) / 32; 9544 9545 if (isAggregateTypeForABI(Ty)) { 9546 // Structures with flexible arrays are always indirect. 9547 if (RT && RT->getDecl()->hasFlexibleArrayMember()) 9548 return getIndirectByValue(Ty); 9549 9550 // Ignore empty structs/unions. 9551 if (isEmptyRecord(getContext(), Ty, true)) 9552 return ABIArgInfo::getIgnore(); 9553 9554 llvm::LLVMContext &LLVMContext = getVMContext(); 9555 9556 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext); 9557 SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32); 9558 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements); 9559 9560 return FreeRegs >= SizeInRegs ? 9561 ABIArgInfo::getDirectInReg(Result) : 9562 ABIArgInfo::getDirect(Result, 0, nullptr, false); 9563 } 9564 9565 if (const auto *EIT = Ty->getAs<ExtIntType>()) 9566 if (EIT->getNumBits() > 64) 9567 return getIndirectByValue(Ty); 9568 9569 return isPromotableIntegerTypeForABI(Ty) 9570 ? (FreeRegs >= SizeInRegs ? ABIArgInfo::getExtendInReg(Ty) 9571 : ABIArgInfo::getExtend(Ty)) 9572 : (FreeRegs >= SizeInRegs ? ABIArgInfo::getDirectInReg() 9573 : ABIArgInfo::getDirect()); 9574 } 9575 9576 ABIArgInfo ARCABIInfo::classifyReturnType(QualType RetTy) const { 9577 if (RetTy->isAnyComplexType()) 9578 return ABIArgInfo::getDirectInReg(); 9579 9580 // Arguments of size > 4 registers are indirect. 9581 auto RetSize = llvm::alignTo(getContext().getTypeSize(RetTy), 32) / 32; 9582 if (RetSize > 4) 9583 return getIndirectByRef(RetTy, /*HasFreeRegs*/ true); 9584 9585 return DefaultABIInfo::classifyReturnType(RetTy); 9586 } 9587 9588 } // End anonymous namespace. 9589 9590 //===----------------------------------------------------------------------===// 9591 // XCore ABI Implementation 9592 //===----------------------------------------------------------------------===// 9593 9594 namespace { 9595 9596 /// A SmallStringEnc instance is used to build up the TypeString by passing 9597 /// it by reference between functions that append to it. 9598 typedef llvm::SmallString<128> SmallStringEnc; 9599 9600 /// TypeStringCache caches the meta encodings of Types. 9601 /// 9602 /// The reason for caching TypeStrings is two fold: 9603 /// 1. To cache a type's encoding for later uses; 9604 /// 2. As a means to break recursive member type inclusion. 9605 /// 9606 /// A cache Entry can have a Status of: 9607 /// NonRecursive: The type encoding is not recursive; 9608 /// Recursive: The type encoding is recursive; 9609 /// Incomplete: An incomplete TypeString; 9610 /// IncompleteUsed: An incomplete TypeString that has been used in a 9611 /// Recursive type encoding. 9612 /// 9613 /// A NonRecursive entry will have all of its sub-members expanded as fully 9614 /// as possible. Whilst it may contain types which are recursive, the type 9615 /// itself is not recursive and thus its encoding may be safely used whenever 9616 /// the type is encountered. 9617 /// 9618 /// A Recursive entry will have all of its sub-members expanded as fully as 9619 /// possible. The type itself is recursive and it may contain other types which 9620 /// are recursive. The Recursive encoding must not be used during the expansion 9621 /// of a recursive type's recursive branch. For simplicity the code uses 9622 /// IncompleteCount to reject all usage of Recursive encodings for member types. 9623 /// 9624 /// An Incomplete entry is always a RecordType and only encodes its 9625 /// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and 9626 /// are placed into the cache during type expansion as a means to identify and 9627 /// handle recursive inclusion of types as sub-members. If there is recursion 9628 /// the entry becomes IncompleteUsed. 9629 /// 9630 /// During the expansion of a RecordType's members: 9631 /// 9632 /// If the cache contains a NonRecursive encoding for the member type, the 9633 /// cached encoding is used; 9634 /// 9635 /// If the cache contains a Recursive encoding for the member type, the 9636 /// cached encoding is 'Swapped' out, as it may be incorrect, and... 9637 /// 9638 /// If the member is a RecordType, an Incomplete encoding is placed into the 9639 /// cache to break potential recursive inclusion of itself as a sub-member; 9640 /// 9641 /// Once a member RecordType has been expanded, its temporary incomplete 9642 /// entry is removed from the cache. If a Recursive encoding was swapped out 9643 /// it is swapped back in; 9644 /// 9645 /// If an incomplete entry is used to expand a sub-member, the incomplete 9646 /// entry is marked as IncompleteUsed. The cache keeps count of how many 9647 /// IncompleteUsed entries it currently contains in IncompleteUsedCount; 9648 /// 9649 /// If a member's encoding is found to be a NonRecursive or Recursive viz: 9650 /// IncompleteUsedCount==0, the member's encoding is added to the cache. 9651 /// Else the member is part of a recursive type and thus the recursion has 9652 /// been exited too soon for the encoding to be correct for the member. 9653 /// 9654 class TypeStringCache { 9655 enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed}; 9656 struct Entry { 9657 std::string Str; // The encoded TypeString for the type. 9658 enum Status State; // Information about the encoding in 'Str'. 9659 std::string Swapped; // A temporary place holder for a Recursive encoding 9660 // during the expansion of RecordType's members. 9661 }; 9662 std::map<const IdentifierInfo *, struct Entry> Map; 9663 unsigned IncompleteCount; // Number of Incomplete entries in the Map. 9664 unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map. 9665 public: 9666 TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {} 9667 void addIncomplete(const IdentifierInfo *ID, std::string StubEnc); 9668 bool removeIncomplete(const IdentifierInfo *ID); 9669 void addIfComplete(const IdentifierInfo *ID, StringRef Str, 9670 bool IsRecursive); 9671 StringRef lookupStr(const IdentifierInfo *ID); 9672 }; 9673 9674 /// TypeString encodings for enum & union fields must be order. 9675 /// FieldEncoding is a helper for this ordering process. 9676 class FieldEncoding { 9677 bool HasName; 9678 std::string Enc; 9679 public: 9680 FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {} 9681 StringRef str() { return Enc; } 9682 bool operator<(const FieldEncoding &rhs) const { 9683 if (HasName != rhs.HasName) return HasName; 9684 return Enc < rhs.Enc; 9685 } 9686 }; 9687 9688 class XCoreABIInfo : public DefaultABIInfo { 9689 public: 9690 XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {} 9691 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 9692 QualType Ty) const override; 9693 }; 9694 9695 class XCoreTargetCodeGenInfo : public TargetCodeGenInfo { 9696 mutable TypeStringCache TSC; 9697 void emitTargetMD(const Decl *D, llvm::GlobalValue *GV, 9698 const CodeGen::CodeGenModule &M) const; 9699 9700 public: 9701 XCoreTargetCodeGenInfo(CodeGenTypes &CGT) 9702 : TargetCodeGenInfo(std::make_unique<XCoreABIInfo>(CGT)) {} 9703 void emitTargetMetadata(CodeGen::CodeGenModule &CGM, 9704 const llvm::MapVector<GlobalDecl, StringRef> 9705 &MangledDeclNames) const override; 9706 }; 9707 9708 } // End anonymous namespace. 9709 9710 // TODO: this implementation is likely now redundant with the default 9711 // EmitVAArg. 9712 Address XCoreABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 9713 QualType Ty) const { 9714 CGBuilderTy &Builder = CGF.Builder; 9715 9716 // Get the VAList. 9717 CharUnits SlotSize = CharUnits::fromQuantity(4); 9718 Address AP(Builder.CreateLoad(VAListAddr), SlotSize); 9719 9720 // Handle the argument. 9721 ABIArgInfo AI = classifyArgumentType(Ty); 9722 CharUnits TypeAlign = getContext().getTypeAlignInChars(Ty); 9723 llvm::Type *ArgTy = CGT.ConvertType(Ty); 9724 if (AI.canHaveCoerceToType() && !AI.getCoerceToType()) 9725 AI.setCoerceToType(ArgTy); 9726 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy); 9727 9728 Address Val = Address::invalid(); 9729 CharUnits ArgSize = CharUnits::Zero(); 9730 switch (AI.getKind()) { 9731 case ABIArgInfo::Expand: 9732 case ABIArgInfo::CoerceAndExpand: 9733 case ABIArgInfo::InAlloca: 9734 llvm_unreachable("Unsupported ABI kind for va_arg"); 9735 case ABIArgInfo::Ignore: 9736 Val = Address(llvm::UndefValue::get(ArgPtrTy), TypeAlign); 9737 ArgSize = CharUnits::Zero(); 9738 break; 9739 case ABIArgInfo::Extend: 9740 case ABIArgInfo::Direct: 9741 Val = Builder.CreateBitCast(AP, ArgPtrTy); 9742 ArgSize = CharUnits::fromQuantity( 9743 getDataLayout().getTypeAllocSize(AI.getCoerceToType())); 9744 ArgSize = ArgSize.alignTo(SlotSize); 9745 break; 9746 case ABIArgInfo::Indirect: 9747 Val = Builder.CreateElementBitCast(AP, ArgPtrTy); 9748 Val = Address(Builder.CreateLoad(Val), TypeAlign); 9749 ArgSize = SlotSize; 9750 break; 9751 } 9752 9753 // Increment the VAList. 9754 if (!ArgSize.isZero()) { 9755 Address APN = Builder.CreateConstInBoundsByteGEP(AP, ArgSize); 9756 Builder.CreateStore(APN.getPointer(), VAListAddr); 9757 } 9758 9759 return Val; 9760 } 9761 9762 /// During the expansion of a RecordType, an incomplete TypeString is placed 9763 /// into the cache as a means to identify and break recursion. 9764 /// If there is a Recursive encoding in the cache, it is swapped out and will 9765 /// be reinserted by removeIncomplete(). 9766 /// All other types of encoding should have been used rather than arriving here. 9767 void TypeStringCache::addIncomplete(const IdentifierInfo *ID, 9768 std::string StubEnc) { 9769 if (!ID) 9770 return; 9771 Entry &E = Map[ID]; 9772 assert( (E.Str.empty() || E.State == Recursive) && 9773 "Incorrectly use of addIncomplete"); 9774 assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()"); 9775 E.Swapped.swap(E.Str); // swap out the Recursive 9776 E.Str.swap(StubEnc); 9777 E.State = Incomplete; 9778 ++IncompleteCount; 9779 } 9780 9781 /// Once the RecordType has been expanded, the temporary incomplete TypeString 9782 /// must be removed from the cache. 9783 /// If a Recursive was swapped out by addIncomplete(), it will be replaced. 9784 /// Returns true if the RecordType was defined recursively. 9785 bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) { 9786 if (!ID) 9787 return false; 9788 auto I = Map.find(ID); 9789 assert(I != Map.end() && "Entry not present"); 9790 Entry &E = I->second; 9791 assert( (E.State == Incomplete || 9792 E.State == IncompleteUsed) && 9793 "Entry must be an incomplete type"); 9794 bool IsRecursive = false; 9795 if (E.State == IncompleteUsed) { 9796 // We made use of our Incomplete encoding, thus we are recursive. 9797 IsRecursive = true; 9798 --IncompleteUsedCount; 9799 } 9800 if (E.Swapped.empty()) 9801 Map.erase(I); 9802 else { 9803 // Swap the Recursive back. 9804 E.Swapped.swap(E.Str); 9805 E.Swapped.clear(); 9806 E.State = Recursive; 9807 } 9808 --IncompleteCount; 9809 return IsRecursive; 9810 } 9811 9812 /// Add the encoded TypeString to the cache only if it is NonRecursive or 9813 /// Recursive (viz: all sub-members were expanded as fully as possible). 9814 void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str, 9815 bool IsRecursive) { 9816 if (!ID || IncompleteUsedCount) 9817 return; // No key or it is is an incomplete sub-type so don't add. 9818 Entry &E = Map[ID]; 9819 if (IsRecursive && !E.Str.empty()) { 9820 assert(E.State==Recursive && E.Str.size() == Str.size() && 9821 "This is not the same Recursive entry"); 9822 // The parent container was not recursive after all, so we could have used 9823 // this Recursive sub-member entry after all, but we assumed the worse when 9824 // we started viz: IncompleteCount!=0. 9825 return; 9826 } 9827 assert(E.Str.empty() && "Entry already present"); 9828 E.Str = Str.str(); 9829 E.State = IsRecursive? Recursive : NonRecursive; 9830 } 9831 9832 /// Return a cached TypeString encoding for the ID. If there isn't one, or we 9833 /// are recursively expanding a type (IncompleteCount != 0) and the cached 9834 /// encoding is Recursive, return an empty StringRef. 9835 StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) { 9836 if (!ID) 9837 return StringRef(); // We have no key. 9838 auto I = Map.find(ID); 9839 if (I == Map.end()) 9840 return StringRef(); // We have no encoding. 9841 Entry &E = I->second; 9842 if (E.State == Recursive && IncompleteCount) 9843 return StringRef(); // We don't use Recursive encodings for member types. 9844 9845 if (E.State == Incomplete) { 9846 // The incomplete type is being used to break out of recursion. 9847 E.State = IncompleteUsed; 9848 ++IncompleteUsedCount; 9849 } 9850 return E.Str; 9851 } 9852 9853 /// The XCore ABI includes a type information section that communicates symbol 9854 /// type information to the linker. The linker uses this information to verify 9855 /// safety/correctness of things such as array bound and pointers et al. 9856 /// The ABI only requires C (and XC) language modules to emit TypeStrings. 9857 /// This type information (TypeString) is emitted into meta data for all global 9858 /// symbols: definitions, declarations, functions & variables. 9859 /// 9860 /// The TypeString carries type, qualifier, name, size & value details. 9861 /// Please see 'Tools Development Guide' section 2.16.2 for format details: 9862 /// https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf 9863 /// The output is tested by test/CodeGen/xcore-stringtype.c. 9864 /// 9865 static bool getTypeString(SmallStringEnc &Enc, const Decl *D, 9866 const CodeGen::CodeGenModule &CGM, 9867 TypeStringCache &TSC); 9868 9869 /// XCore uses emitTargetMD to emit TypeString metadata for global symbols. 9870 void XCoreTargetCodeGenInfo::emitTargetMD( 9871 const Decl *D, llvm::GlobalValue *GV, 9872 const CodeGen::CodeGenModule &CGM) const { 9873 SmallStringEnc Enc; 9874 if (getTypeString(Enc, D, CGM, TSC)) { 9875 llvm::LLVMContext &Ctx = CGM.getModule().getContext(); 9876 llvm::Metadata *MDVals[] = {llvm::ConstantAsMetadata::get(GV), 9877 llvm::MDString::get(Ctx, Enc.str())}; 9878 llvm::NamedMDNode *MD = 9879 CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings"); 9880 MD->addOperand(llvm::MDNode::get(Ctx, MDVals)); 9881 } 9882 } 9883 9884 void XCoreTargetCodeGenInfo::emitTargetMetadata( 9885 CodeGen::CodeGenModule &CGM, 9886 const llvm::MapVector<GlobalDecl, StringRef> &MangledDeclNames) const { 9887 // Warning, new MangledDeclNames may be appended within this loop. 9888 // We rely on MapVector insertions adding new elements to the end 9889 // of the container. 9890 for (unsigned I = 0; I != MangledDeclNames.size(); ++I) { 9891 auto Val = *(MangledDeclNames.begin() + I); 9892 llvm::GlobalValue *GV = CGM.GetGlobalValue(Val.second); 9893 if (GV) { 9894 const Decl *D = Val.first.getDecl()->getMostRecentDecl(); 9895 emitTargetMD(D, GV, CGM); 9896 } 9897 } 9898 } 9899 //===----------------------------------------------------------------------===// 9900 // SPIR ABI Implementation 9901 //===----------------------------------------------------------------------===// 9902 9903 namespace { 9904 class SPIRTargetCodeGenInfo : public TargetCodeGenInfo { 9905 public: 9906 SPIRTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT) 9907 : TargetCodeGenInfo(std::make_unique<DefaultABIInfo>(CGT)) {} 9908 unsigned getOpenCLKernelCallingConv() const override; 9909 }; 9910 9911 } // End anonymous namespace. 9912 9913 namespace clang { 9914 namespace CodeGen { 9915 void computeSPIRKernelABIInfo(CodeGenModule &CGM, CGFunctionInfo &FI) { 9916 DefaultABIInfo SPIRABI(CGM.getTypes()); 9917 SPIRABI.computeInfo(FI); 9918 } 9919 } 9920 } 9921 9922 unsigned SPIRTargetCodeGenInfo::getOpenCLKernelCallingConv() const { 9923 return llvm::CallingConv::SPIR_KERNEL; 9924 } 9925 9926 static bool appendType(SmallStringEnc &Enc, QualType QType, 9927 const CodeGen::CodeGenModule &CGM, 9928 TypeStringCache &TSC); 9929 9930 /// Helper function for appendRecordType(). 9931 /// Builds a SmallVector containing the encoded field types in declaration 9932 /// order. 9933 static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE, 9934 const RecordDecl *RD, 9935 const CodeGen::CodeGenModule &CGM, 9936 TypeStringCache &TSC) { 9937 for (const auto *Field : RD->fields()) { 9938 SmallStringEnc Enc; 9939 Enc += "m("; 9940 Enc += Field->getName(); 9941 Enc += "){"; 9942 if (Field->isBitField()) { 9943 Enc += "b("; 9944 llvm::raw_svector_ostream OS(Enc); 9945 OS << Field->getBitWidthValue(CGM.getContext()); 9946 Enc += ':'; 9947 } 9948 if (!appendType(Enc, Field->getType(), CGM, TSC)) 9949 return false; 9950 if (Field->isBitField()) 9951 Enc += ')'; 9952 Enc += '}'; 9953 FE.emplace_back(!Field->getName().empty(), Enc); 9954 } 9955 return true; 9956 } 9957 9958 /// Appends structure and union types to Enc and adds encoding to cache. 9959 /// Recursively calls appendType (via extractFieldType) for each field. 9960 /// Union types have their fields ordered according to the ABI. 9961 static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT, 9962 const CodeGen::CodeGenModule &CGM, 9963 TypeStringCache &TSC, const IdentifierInfo *ID) { 9964 // Append the cached TypeString if we have one. 9965 StringRef TypeString = TSC.lookupStr(ID); 9966 if (!TypeString.empty()) { 9967 Enc += TypeString; 9968 return true; 9969 } 9970 9971 // Start to emit an incomplete TypeString. 9972 size_t Start = Enc.size(); 9973 Enc += (RT->isUnionType()? 'u' : 's'); 9974 Enc += '('; 9975 if (ID) 9976 Enc += ID->getName(); 9977 Enc += "){"; 9978 9979 // We collect all encoded fields and order as necessary. 9980 bool IsRecursive = false; 9981 const RecordDecl *RD = RT->getDecl()->getDefinition(); 9982 if (RD && !RD->field_empty()) { 9983 // An incomplete TypeString stub is placed in the cache for this RecordType 9984 // so that recursive calls to this RecordType will use it whilst building a 9985 // complete TypeString for this RecordType. 9986 SmallVector<FieldEncoding, 16> FE; 9987 std::string StubEnc(Enc.substr(Start).str()); 9988 StubEnc += '}'; // StubEnc now holds a valid incomplete TypeString. 9989 TSC.addIncomplete(ID, std::move(StubEnc)); 9990 if (!extractFieldType(FE, RD, CGM, TSC)) { 9991 (void) TSC.removeIncomplete(ID); 9992 return false; 9993 } 9994 IsRecursive = TSC.removeIncomplete(ID); 9995 // The ABI requires unions to be sorted but not structures. 9996 // See FieldEncoding::operator< for sort algorithm. 9997 if (RT->isUnionType()) 9998 llvm::sort(FE); 9999 // We can now complete the TypeString. 10000 unsigned E = FE.size(); 10001 for (unsigned I = 0; I != E; ++I) { 10002 if (I) 10003 Enc += ','; 10004 Enc += FE[I].str(); 10005 } 10006 } 10007 Enc += '}'; 10008 TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive); 10009 return true; 10010 } 10011 10012 /// Appends enum types to Enc and adds the encoding to the cache. 10013 static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET, 10014 TypeStringCache &TSC, 10015 const IdentifierInfo *ID) { 10016 // Append the cached TypeString if we have one. 10017 StringRef TypeString = TSC.lookupStr(ID); 10018 if (!TypeString.empty()) { 10019 Enc += TypeString; 10020 return true; 10021 } 10022 10023 size_t Start = Enc.size(); 10024 Enc += "e("; 10025 if (ID) 10026 Enc += ID->getName(); 10027 Enc += "){"; 10028 10029 // We collect all encoded enumerations and order them alphanumerically. 10030 if (const EnumDecl *ED = ET->getDecl()->getDefinition()) { 10031 SmallVector<FieldEncoding, 16> FE; 10032 for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E; 10033 ++I) { 10034 SmallStringEnc EnumEnc; 10035 EnumEnc += "m("; 10036 EnumEnc += I->getName(); 10037 EnumEnc += "){"; 10038 I->getInitVal().toString(EnumEnc); 10039 EnumEnc += '}'; 10040 FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc)); 10041 } 10042 llvm::sort(FE); 10043 unsigned E = FE.size(); 10044 for (unsigned I = 0; I != E; ++I) { 10045 if (I) 10046 Enc += ','; 10047 Enc += FE[I].str(); 10048 } 10049 } 10050 Enc += '}'; 10051 TSC.addIfComplete(ID, Enc.substr(Start), false); 10052 return true; 10053 } 10054 10055 /// Appends type's qualifier to Enc. 10056 /// This is done prior to appending the type's encoding. 10057 static void appendQualifier(SmallStringEnc &Enc, QualType QT) { 10058 // Qualifiers are emitted in alphabetical order. 10059 static const char *const Table[]={"","c:","r:","cr:","v:","cv:","rv:","crv:"}; 10060 int Lookup = 0; 10061 if (QT.isConstQualified()) 10062 Lookup += 1<<0; 10063 if (QT.isRestrictQualified()) 10064 Lookup += 1<<1; 10065 if (QT.isVolatileQualified()) 10066 Lookup += 1<<2; 10067 Enc += Table[Lookup]; 10068 } 10069 10070 /// Appends built-in types to Enc. 10071 static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) { 10072 const char *EncType; 10073 switch (BT->getKind()) { 10074 case BuiltinType::Void: 10075 EncType = "0"; 10076 break; 10077 case BuiltinType::Bool: 10078 EncType = "b"; 10079 break; 10080 case BuiltinType::Char_U: 10081 EncType = "uc"; 10082 break; 10083 case BuiltinType::UChar: 10084 EncType = "uc"; 10085 break; 10086 case BuiltinType::SChar: 10087 EncType = "sc"; 10088 break; 10089 case BuiltinType::UShort: 10090 EncType = "us"; 10091 break; 10092 case BuiltinType::Short: 10093 EncType = "ss"; 10094 break; 10095 case BuiltinType::UInt: 10096 EncType = "ui"; 10097 break; 10098 case BuiltinType::Int: 10099 EncType = "si"; 10100 break; 10101 case BuiltinType::ULong: 10102 EncType = "ul"; 10103 break; 10104 case BuiltinType::Long: 10105 EncType = "sl"; 10106 break; 10107 case BuiltinType::ULongLong: 10108 EncType = "ull"; 10109 break; 10110 case BuiltinType::LongLong: 10111 EncType = "sll"; 10112 break; 10113 case BuiltinType::Float: 10114 EncType = "ft"; 10115 break; 10116 case BuiltinType::Double: 10117 EncType = "d"; 10118 break; 10119 case BuiltinType::LongDouble: 10120 EncType = "ld"; 10121 break; 10122 default: 10123 return false; 10124 } 10125 Enc += EncType; 10126 return true; 10127 } 10128 10129 /// Appends a pointer encoding to Enc before calling appendType for the pointee. 10130 static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT, 10131 const CodeGen::CodeGenModule &CGM, 10132 TypeStringCache &TSC) { 10133 Enc += "p("; 10134 if (!appendType(Enc, PT->getPointeeType(), CGM, TSC)) 10135 return false; 10136 Enc += ')'; 10137 return true; 10138 } 10139 10140 /// Appends array encoding to Enc before calling appendType for the element. 10141 static bool appendArrayType(SmallStringEnc &Enc, QualType QT, 10142 const ArrayType *AT, 10143 const CodeGen::CodeGenModule &CGM, 10144 TypeStringCache &TSC, StringRef NoSizeEnc) { 10145 if (AT->getSizeModifier() != ArrayType::Normal) 10146 return false; 10147 Enc += "a("; 10148 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) 10149 CAT->getSize().toStringUnsigned(Enc); 10150 else 10151 Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "". 10152 Enc += ':'; 10153 // The Qualifiers should be attached to the type rather than the array. 10154 appendQualifier(Enc, QT); 10155 if (!appendType(Enc, AT->getElementType(), CGM, TSC)) 10156 return false; 10157 Enc += ')'; 10158 return true; 10159 } 10160 10161 /// Appends a function encoding to Enc, calling appendType for the return type 10162 /// and the arguments. 10163 static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT, 10164 const CodeGen::CodeGenModule &CGM, 10165 TypeStringCache &TSC) { 10166 Enc += "f{"; 10167 if (!appendType(Enc, FT->getReturnType(), CGM, TSC)) 10168 return false; 10169 Enc += "}("; 10170 if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) { 10171 // N.B. we are only interested in the adjusted param types. 10172 auto I = FPT->param_type_begin(); 10173 auto E = FPT->param_type_end(); 10174 if (I != E) { 10175 do { 10176 if (!appendType(Enc, *I, CGM, TSC)) 10177 return false; 10178 ++I; 10179 if (I != E) 10180 Enc += ','; 10181 } while (I != E); 10182 if (FPT->isVariadic()) 10183 Enc += ",va"; 10184 } else { 10185 if (FPT->isVariadic()) 10186 Enc += "va"; 10187 else 10188 Enc += '0'; 10189 } 10190 } 10191 Enc += ')'; 10192 return true; 10193 } 10194 10195 /// Handles the type's qualifier before dispatching a call to handle specific 10196 /// type encodings. 10197 static bool appendType(SmallStringEnc &Enc, QualType QType, 10198 const CodeGen::CodeGenModule &CGM, 10199 TypeStringCache &TSC) { 10200 10201 QualType QT = QType.getCanonicalType(); 10202 10203 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) 10204 // The Qualifiers should be attached to the type rather than the array. 10205 // Thus we don't call appendQualifier() here. 10206 return appendArrayType(Enc, QT, AT, CGM, TSC, ""); 10207 10208 appendQualifier(Enc, QT); 10209 10210 if (const BuiltinType *BT = QT->getAs<BuiltinType>()) 10211 return appendBuiltinType(Enc, BT); 10212 10213 if (const PointerType *PT = QT->getAs<PointerType>()) 10214 return appendPointerType(Enc, PT, CGM, TSC); 10215 10216 if (const EnumType *ET = QT->getAs<EnumType>()) 10217 return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier()); 10218 10219 if (const RecordType *RT = QT->getAsStructureType()) 10220 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier()); 10221 10222 if (const RecordType *RT = QT->getAsUnionType()) 10223 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier()); 10224 10225 if (const FunctionType *FT = QT->getAs<FunctionType>()) 10226 return appendFunctionType(Enc, FT, CGM, TSC); 10227 10228 return false; 10229 } 10230 10231 static bool getTypeString(SmallStringEnc &Enc, const Decl *D, 10232 const CodeGen::CodeGenModule &CGM, 10233 TypeStringCache &TSC) { 10234 if (!D) 10235 return false; 10236 10237 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 10238 if (FD->getLanguageLinkage() != CLanguageLinkage) 10239 return false; 10240 return appendType(Enc, FD->getType(), CGM, TSC); 10241 } 10242 10243 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 10244 if (VD->getLanguageLinkage() != CLanguageLinkage) 10245 return false; 10246 QualType QT = VD->getType().getCanonicalType(); 10247 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) { 10248 // Global ArrayTypes are given a size of '*' if the size is unknown. 10249 // The Qualifiers should be attached to the type rather than the array. 10250 // Thus we don't call appendQualifier() here. 10251 return appendArrayType(Enc, QT, AT, CGM, TSC, "*"); 10252 } 10253 return appendType(Enc, QT, CGM, TSC); 10254 } 10255 return false; 10256 } 10257 10258 //===----------------------------------------------------------------------===// 10259 // RISCV ABI Implementation 10260 //===----------------------------------------------------------------------===// 10261 10262 namespace { 10263 class RISCVABIInfo : public DefaultABIInfo { 10264 private: 10265 // Size of the integer ('x') registers in bits. 10266 unsigned XLen; 10267 // Size of the floating point ('f') registers in bits. Note that the target 10268 // ISA might have a wider FLen than the selected ABI (e.g. an RV32IF target 10269 // with soft float ABI has FLen==0). 10270 unsigned FLen; 10271 static const int NumArgGPRs = 8; 10272 static const int NumArgFPRs = 8; 10273 bool detectFPCCEligibleStructHelper(QualType Ty, CharUnits CurOff, 10274 llvm::Type *&Field1Ty, 10275 CharUnits &Field1Off, 10276 llvm::Type *&Field2Ty, 10277 CharUnits &Field2Off) const; 10278 10279 public: 10280 RISCVABIInfo(CodeGen::CodeGenTypes &CGT, unsigned XLen, unsigned FLen) 10281 : DefaultABIInfo(CGT), XLen(XLen), FLen(FLen) {} 10282 10283 // DefaultABIInfo's classifyReturnType and classifyArgumentType are 10284 // non-virtual, but computeInfo is virtual, so we overload it. 10285 void computeInfo(CGFunctionInfo &FI) const override; 10286 10287 ABIArgInfo classifyArgumentType(QualType Ty, bool IsFixed, int &ArgGPRsLeft, 10288 int &ArgFPRsLeft) const; 10289 ABIArgInfo classifyReturnType(QualType RetTy) const; 10290 10291 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 10292 QualType Ty) const override; 10293 10294 ABIArgInfo extendType(QualType Ty) const; 10295 10296 bool detectFPCCEligibleStruct(QualType Ty, llvm::Type *&Field1Ty, 10297 CharUnits &Field1Off, llvm::Type *&Field2Ty, 10298 CharUnits &Field2Off, int &NeededArgGPRs, 10299 int &NeededArgFPRs) const; 10300 ABIArgInfo coerceAndExpandFPCCEligibleStruct(llvm::Type *Field1Ty, 10301 CharUnits Field1Off, 10302 llvm::Type *Field2Ty, 10303 CharUnits Field2Off) const; 10304 }; 10305 } // end anonymous namespace 10306 10307 void RISCVABIInfo::computeInfo(CGFunctionInfo &FI) const { 10308 QualType RetTy = FI.getReturnType(); 10309 if (!getCXXABI().classifyReturnType(FI)) 10310 FI.getReturnInfo() = classifyReturnType(RetTy); 10311 10312 // IsRetIndirect is true if classifyArgumentType indicated the value should 10313 // be passed indirect, or if the type size is a scalar greater than 2*XLen 10314 // and not a complex type with elements <= FLen. e.g. fp128 is passed direct 10315 // in LLVM IR, relying on the backend lowering code to rewrite the argument 10316 // list and pass indirectly on RV32. 10317 bool IsRetIndirect = FI.getReturnInfo().getKind() == ABIArgInfo::Indirect; 10318 if (!IsRetIndirect && RetTy->isScalarType() && 10319 getContext().getTypeSize(RetTy) > (2 * XLen)) { 10320 if (RetTy->isComplexType() && FLen) { 10321 QualType EltTy = RetTy->getAs<ComplexType>()->getElementType(); 10322 IsRetIndirect = getContext().getTypeSize(EltTy) > FLen; 10323 } else { 10324 // This is a normal scalar > 2*XLen, such as fp128 on RV32. 10325 IsRetIndirect = true; 10326 } 10327 } 10328 10329 // We must track the number of GPRs used in order to conform to the RISC-V 10330 // ABI, as integer scalars passed in registers should have signext/zeroext 10331 // when promoted, but are anyext if passed on the stack. As GPR usage is 10332 // different for variadic arguments, we must also track whether we are 10333 // examining a vararg or not. 10334 int ArgGPRsLeft = IsRetIndirect ? NumArgGPRs - 1 : NumArgGPRs; 10335 int ArgFPRsLeft = FLen ? NumArgFPRs : 0; 10336 int NumFixedArgs = FI.getNumRequiredArgs(); 10337 10338 int ArgNum = 0; 10339 for (auto &ArgInfo : FI.arguments()) { 10340 bool IsFixed = ArgNum < NumFixedArgs; 10341 ArgInfo.info = 10342 classifyArgumentType(ArgInfo.type, IsFixed, ArgGPRsLeft, ArgFPRsLeft); 10343 ArgNum++; 10344 } 10345 } 10346 10347 // Returns true if the struct is a potential candidate for the floating point 10348 // calling convention. If this function returns true, the caller is 10349 // responsible for checking that if there is only a single field then that 10350 // field is a float. 10351 bool RISCVABIInfo::detectFPCCEligibleStructHelper(QualType Ty, CharUnits CurOff, 10352 llvm::Type *&Field1Ty, 10353 CharUnits &Field1Off, 10354 llvm::Type *&Field2Ty, 10355 CharUnits &Field2Off) const { 10356 bool IsInt = Ty->isIntegralOrEnumerationType(); 10357 bool IsFloat = Ty->isRealFloatingType(); 10358 10359 if (IsInt || IsFloat) { 10360 uint64_t Size = getContext().getTypeSize(Ty); 10361 if (IsInt && Size > XLen) 10362 return false; 10363 // Can't be eligible if larger than the FP registers. Half precision isn't 10364 // currently supported on RISC-V and the ABI hasn't been confirmed, so 10365 // default to the integer ABI in that case. 10366 if (IsFloat && (Size > FLen || Size < 32)) 10367 return false; 10368 // Can't be eligible if an integer type was already found (int+int pairs 10369 // are not eligible). 10370 if (IsInt && Field1Ty && Field1Ty->isIntegerTy()) 10371 return false; 10372 if (!Field1Ty) { 10373 Field1Ty = CGT.ConvertType(Ty); 10374 Field1Off = CurOff; 10375 return true; 10376 } 10377 if (!Field2Ty) { 10378 Field2Ty = CGT.ConvertType(Ty); 10379 Field2Off = CurOff; 10380 return true; 10381 } 10382 return false; 10383 } 10384 10385 if (auto CTy = Ty->getAs<ComplexType>()) { 10386 if (Field1Ty) 10387 return false; 10388 QualType EltTy = CTy->getElementType(); 10389 if (getContext().getTypeSize(EltTy) > FLen) 10390 return false; 10391 Field1Ty = CGT.ConvertType(EltTy); 10392 Field1Off = CurOff; 10393 assert(CurOff.isZero() && "Unexpected offset for first field"); 10394 Field2Ty = Field1Ty; 10395 Field2Off = Field1Off + getContext().getTypeSizeInChars(EltTy); 10396 return true; 10397 } 10398 10399 if (const ConstantArrayType *ATy = getContext().getAsConstantArrayType(Ty)) { 10400 uint64_t ArraySize = ATy->getSize().getZExtValue(); 10401 QualType EltTy = ATy->getElementType(); 10402 CharUnits EltSize = getContext().getTypeSizeInChars(EltTy); 10403 for (uint64_t i = 0; i < ArraySize; ++i) { 10404 bool Ret = detectFPCCEligibleStructHelper(EltTy, CurOff, Field1Ty, 10405 Field1Off, Field2Ty, Field2Off); 10406 if (!Ret) 10407 return false; 10408 CurOff += EltSize; 10409 } 10410 return true; 10411 } 10412 10413 if (const auto *RTy = Ty->getAs<RecordType>()) { 10414 // Structures with either a non-trivial destructor or a non-trivial 10415 // copy constructor are not eligible for the FP calling convention. 10416 if (getRecordArgABI(Ty, CGT.getCXXABI())) 10417 return false; 10418 if (isEmptyRecord(getContext(), Ty, true)) 10419 return true; 10420 const RecordDecl *RD = RTy->getDecl(); 10421 // Unions aren't eligible unless they're empty (which is caught above). 10422 if (RD->isUnion()) 10423 return false; 10424 int ZeroWidthBitFieldCount = 0; 10425 for (const FieldDecl *FD : RD->fields()) { 10426 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD); 10427 uint64_t FieldOffInBits = Layout.getFieldOffset(FD->getFieldIndex()); 10428 QualType QTy = FD->getType(); 10429 if (FD->isBitField()) { 10430 unsigned BitWidth = FD->getBitWidthValue(getContext()); 10431 // Allow a bitfield with a type greater than XLen as long as the 10432 // bitwidth is XLen or less. 10433 if (getContext().getTypeSize(QTy) > XLen && BitWidth <= XLen) 10434 QTy = getContext().getIntTypeForBitwidth(XLen, false); 10435 if (BitWidth == 0) { 10436 ZeroWidthBitFieldCount++; 10437 continue; 10438 } 10439 } 10440 10441 bool Ret = detectFPCCEligibleStructHelper( 10442 QTy, CurOff + getContext().toCharUnitsFromBits(FieldOffInBits), 10443 Field1Ty, Field1Off, Field2Ty, Field2Off); 10444 if (!Ret) 10445 return false; 10446 10447 // As a quirk of the ABI, zero-width bitfields aren't ignored for fp+fp 10448 // or int+fp structs, but are ignored for a struct with an fp field and 10449 // any number of zero-width bitfields. 10450 if (Field2Ty && ZeroWidthBitFieldCount > 0) 10451 return false; 10452 } 10453 return Field1Ty != nullptr; 10454 } 10455 10456 return false; 10457 } 10458 10459 // Determine if a struct is eligible for passing according to the floating 10460 // point calling convention (i.e., when flattened it contains a single fp 10461 // value, fp+fp, or int+fp of appropriate size). If so, NeededArgFPRs and 10462 // NeededArgGPRs are incremented appropriately. 10463 bool RISCVABIInfo::detectFPCCEligibleStruct(QualType Ty, llvm::Type *&Field1Ty, 10464 CharUnits &Field1Off, 10465 llvm::Type *&Field2Ty, 10466 CharUnits &Field2Off, 10467 int &NeededArgGPRs, 10468 int &NeededArgFPRs) const { 10469 Field1Ty = nullptr; 10470 Field2Ty = nullptr; 10471 NeededArgGPRs = 0; 10472 NeededArgFPRs = 0; 10473 bool IsCandidate = detectFPCCEligibleStructHelper( 10474 Ty, CharUnits::Zero(), Field1Ty, Field1Off, Field2Ty, Field2Off); 10475 // Not really a candidate if we have a single int but no float. 10476 if (Field1Ty && !Field2Ty && !Field1Ty->isFloatingPointTy()) 10477 return false; 10478 if (!IsCandidate) 10479 return false; 10480 if (Field1Ty && Field1Ty->isFloatingPointTy()) 10481 NeededArgFPRs++; 10482 else if (Field1Ty) 10483 NeededArgGPRs++; 10484 if (Field2Ty && Field2Ty->isFloatingPointTy()) 10485 NeededArgFPRs++; 10486 else if (Field2Ty) 10487 NeededArgGPRs++; 10488 return IsCandidate; 10489 } 10490 10491 // Call getCoerceAndExpand for the two-element flattened struct described by 10492 // Field1Ty, Field1Off, Field2Ty, Field2Off. This method will create an 10493 // appropriate coerceToType and unpaddedCoerceToType. 10494 ABIArgInfo RISCVABIInfo::coerceAndExpandFPCCEligibleStruct( 10495 llvm::Type *Field1Ty, CharUnits Field1Off, llvm::Type *Field2Ty, 10496 CharUnits Field2Off) const { 10497 SmallVector<llvm::Type *, 3> CoerceElts; 10498 SmallVector<llvm::Type *, 2> UnpaddedCoerceElts; 10499 if (!Field1Off.isZero()) 10500 CoerceElts.push_back(llvm::ArrayType::get( 10501 llvm::Type::getInt8Ty(getVMContext()), Field1Off.getQuantity())); 10502 10503 CoerceElts.push_back(Field1Ty); 10504 UnpaddedCoerceElts.push_back(Field1Ty); 10505 10506 if (!Field2Ty) { 10507 return ABIArgInfo::getCoerceAndExpand( 10508 llvm::StructType::get(getVMContext(), CoerceElts, !Field1Off.isZero()), 10509 UnpaddedCoerceElts[0]); 10510 } 10511 10512 CharUnits Field2Align = 10513 CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(Field2Ty)); 10514 CharUnits Field1Size = 10515 CharUnits::fromQuantity(getDataLayout().getTypeStoreSize(Field1Ty)); 10516 CharUnits Field2OffNoPadNoPack = Field1Size.alignTo(Field2Align); 10517 10518 CharUnits Padding = CharUnits::Zero(); 10519 if (Field2Off > Field2OffNoPadNoPack) 10520 Padding = Field2Off - Field2OffNoPadNoPack; 10521 else if (Field2Off != Field2Align && Field2Off > Field1Size) 10522 Padding = Field2Off - Field1Size; 10523 10524 bool IsPacked = !Field2Off.isMultipleOf(Field2Align); 10525 10526 if (!Padding.isZero()) 10527 CoerceElts.push_back(llvm::ArrayType::get( 10528 llvm::Type::getInt8Ty(getVMContext()), Padding.getQuantity())); 10529 10530 CoerceElts.push_back(Field2Ty); 10531 UnpaddedCoerceElts.push_back(Field2Ty); 10532 10533 auto CoerceToType = 10534 llvm::StructType::get(getVMContext(), CoerceElts, IsPacked); 10535 auto UnpaddedCoerceToType = 10536 llvm::StructType::get(getVMContext(), UnpaddedCoerceElts, IsPacked); 10537 10538 return ABIArgInfo::getCoerceAndExpand(CoerceToType, UnpaddedCoerceToType); 10539 } 10540 10541 ABIArgInfo RISCVABIInfo::classifyArgumentType(QualType Ty, bool IsFixed, 10542 int &ArgGPRsLeft, 10543 int &ArgFPRsLeft) const { 10544 assert(ArgGPRsLeft <= NumArgGPRs && "Arg GPR tracking underflow"); 10545 Ty = useFirstFieldIfTransparentUnion(Ty); 10546 10547 // Structures with either a non-trivial destructor or a non-trivial 10548 // copy constructor are always passed indirectly. 10549 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) { 10550 if (ArgGPRsLeft) 10551 ArgGPRsLeft -= 1; 10552 return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA == 10553 CGCXXABI::RAA_DirectInMemory); 10554 } 10555 10556 // Ignore empty structs/unions. 10557 if (isEmptyRecord(getContext(), Ty, true)) 10558 return ABIArgInfo::getIgnore(); 10559 10560 uint64_t Size = getContext().getTypeSize(Ty); 10561 10562 // Pass floating point values via FPRs if possible. 10563 if (IsFixed && Ty->isFloatingType() && !Ty->isComplexType() && 10564 FLen >= Size && ArgFPRsLeft) { 10565 ArgFPRsLeft--; 10566 return ABIArgInfo::getDirect(); 10567 } 10568 10569 // Complex types for the hard float ABI must be passed direct rather than 10570 // using CoerceAndExpand. 10571 if (IsFixed && Ty->isComplexType() && FLen && ArgFPRsLeft >= 2) { 10572 QualType EltTy = Ty->castAs<ComplexType>()->getElementType(); 10573 if (getContext().getTypeSize(EltTy) <= FLen) { 10574 ArgFPRsLeft -= 2; 10575 return ABIArgInfo::getDirect(); 10576 } 10577 } 10578 10579 if (IsFixed && FLen && Ty->isStructureOrClassType()) { 10580 llvm::Type *Field1Ty = nullptr; 10581 llvm::Type *Field2Ty = nullptr; 10582 CharUnits Field1Off = CharUnits::Zero(); 10583 CharUnits Field2Off = CharUnits::Zero(); 10584 int NeededArgGPRs; 10585 int NeededArgFPRs; 10586 bool IsCandidate = 10587 detectFPCCEligibleStruct(Ty, Field1Ty, Field1Off, Field2Ty, Field2Off, 10588 NeededArgGPRs, NeededArgFPRs); 10589 if (IsCandidate && NeededArgGPRs <= ArgGPRsLeft && 10590 NeededArgFPRs <= ArgFPRsLeft) { 10591 ArgGPRsLeft -= NeededArgGPRs; 10592 ArgFPRsLeft -= NeededArgFPRs; 10593 return coerceAndExpandFPCCEligibleStruct(Field1Ty, Field1Off, Field2Ty, 10594 Field2Off); 10595 } 10596 } 10597 10598 uint64_t NeededAlign = getContext().getTypeAlign(Ty); 10599 bool MustUseStack = false; 10600 // Determine the number of GPRs needed to pass the current argument 10601 // according to the ABI. 2*XLen-aligned varargs are passed in "aligned" 10602 // register pairs, so may consume 3 registers. 10603 int NeededArgGPRs = 1; 10604 if (!IsFixed && NeededAlign == 2 * XLen) 10605 NeededArgGPRs = 2 + (ArgGPRsLeft % 2); 10606 else if (Size > XLen && Size <= 2 * XLen) 10607 NeededArgGPRs = 2; 10608 10609 if (NeededArgGPRs > ArgGPRsLeft) { 10610 MustUseStack = true; 10611 NeededArgGPRs = ArgGPRsLeft; 10612 } 10613 10614 ArgGPRsLeft -= NeededArgGPRs; 10615 10616 if (!isAggregateTypeForABI(Ty) && !Ty->isVectorType()) { 10617 // Treat an enum type as its underlying type. 10618 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 10619 Ty = EnumTy->getDecl()->getIntegerType(); 10620 10621 // All integral types are promoted to XLen width, unless passed on the 10622 // stack. 10623 if (Size < XLen && Ty->isIntegralOrEnumerationType() && !MustUseStack) { 10624 return extendType(Ty); 10625 } 10626 10627 if (const auto *EIT = Ty->getAs<ExtIntType>()) { 10628 if (EIT->getNumBits() < XLen && !MustUseStack) 10629 return extendType(Ty); 10630 if (EIT->getNumBits() > 128 || 10631 (!getContext().getTargetInfo().hasInt128Type() && 10632 EIT->getNumBits() > 64)) 10633 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 10634 } 10635 10636 return ABIArgInfo::getDirect(); 10637 } 10638 10639 // Aggregates which are <= 2*XLen will be passed in registers if possible, 10640 // so coerce to integers. 10641 if (Size <= 2 * XLen) { 10642 unsigned Alignment = getContext().getTypeAlign(Ty); 10643 10644 // Use a single XLen int if possible, 2*XLen if 2*XLen alignment is 10645 // required, and a 2-element XLen array if only XLen alignment is required. 10646 if (Size <= XLen) { 10647 return ABIArgInfo::getDirect( 10648 llvm::IntegerType::get(getVMContext(), XLen)); 10649 } else if (Alignment == 2 * XLen) { 10650 return ABIArgInfo::getDirect( 10651 llvm::IntegerType::get(getVMContext(), 2 * XLen)); 10652 } else { 10653 return ABIArgInfo::getDirect(llvm::ArrayType::get( 10654 llvm::IntegerType::get(getVMContext(), XLen), 2)); 10655 } 10656 } 10657 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 10658 } 10659 10660 ABIArgInfo RISCVABIInfo::classifyReturnType(QualType RetTy) const { 10661 if (RetTy->isVoidType()) 10662 return ABIArgInfo::getIgnore(); 10663 10664 int ArgGPRsLeft = 2; 10665 int ArgFPRsLeft = FLen ? 2 : 0; 10666 10667 // The rules for return and argument types are the same, so defer to 10668 // classifyArgumentType. 10669 return classifyArgumentType(RetTy, /*IsFixed=*/true, ArgGPRsLeft, 10670 ArgFPRsLeft); 10671 } 10672 10673 Address RISCVABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 10674 QualType Ty) const { 10675 CharUnits SlotSize = CharUnits::fromQuantity(XLen / 8); 10676 10677 // Empty records are ignored for parameter passing purposes. 10678 if (isEmptyRecord(getContext(), Ty, true)) { 10679 Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize); 10680 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty)); 10681 return Addr; 10682 } 10683 10684 std::pair<CharUnits, CharUnits> SizeAndAlign = 10685 getContext().getTypeInfoInChars(Ty); 10686 10687 // Arguments bigger than 2*Xlen bytes are passed indirectly. 10688 bool IsIndirect = SizeAndAlign.first > 2 * SlotSize; 10689 10690 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, SizeAndAlign, 10691 SlotSize, /*AllowHigherAlign=*/true); 10692 } 10693 10694 ABIArgInfo RISCVABIInfo::extendType(QualType Ty) const { 10695 int TySize = getContext().getTypeSize(Ty); 10696 // RV64 ABI requires unsigned 32 bit integers to be sign extended. 10697 if (XLen == 64 && Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32) 10698 return ABIArgInfo::getSignExtend(Ty); 10699 return ABIArgInfo::getExtend(Ty); 10700 } 10701 10702 namespace { 10703 class RISCVTargetCodeGenInfo : public TargetCodeGenInfo { 10704 public: 10705 RISCVTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, unsigned XLen, 10706 unsigned FLen) 10707 : TargetCodeGenInfo(std::make_unique<RISCVABIInfo>(CGT, XLen, FLen)) {} 10708 10709 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 10710 CodeGen::CodeGenModule &CGM) const override { 10711 const auto *FD = dyn_cast_or_null<FunctionDecl>(D); 10712 if (!FD) return; 10713 10714 const auto *Attr = FD->getAttr<RISCVInterruptAttr>(); 10715 if (!Attr) 10716 return; 10717 10718 const char *Kind; 10719 switch (Attr->getInterrupt()) { 10720 case RISCVInterruptAttr::user: Kind = "user"; break; 10721 case RISCVInterruptAttr::supervisor: Kind = "supervisor"; break; 10722 case RISCVInterruptAttr::machine: Kind = "machine"; break; 10723 } 10724 10725 auto *Fn = cast<llvm::Function>(GV); 10726 10727 Fn->addFnAttr("interrupt", Kind); 10728 } 10729 }; 10730 } // namespace 10731 10732 //===----------------------------------------------------------------------===// 10733 // VE ABI Implementation. 10734 // 10735 namespace { 10736 class VEABIInfo : public DefaultABIInfo { 10737 public: 10738 VEABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {} 10739 10740 private: 10741 ABIArgInfo classifyReturnType(QualType RetTy) const; 10742 ABIArgInfo classifyArgumentType(QualType RetTy) const; 10743 void computeInfo(CGFunctionInfo &FI) const override; 10744 }; 10745 } // end anonymous namespace 10746 10747 ABIArgInfo VEABIInfo::classifyReturnType(QualType Ty) const { 10748 if (Ty->isAnyComplexType()) { 10749 return ABIArgInfo::getDirect(); 10750 } 10751 return DefaultABIInfo::classifyReturnType(Ty); 10752 } 10753 10754 ABIArgInfo VEABIInfo::classifyArgumentType(QualType Ty) const { 10755 if (Ty->isAnyComplexType()) { 10756 return ABIArgInfo::getDirect(); 10757 } 10758 return DefaultABIInfo::classifyArgumentType(Ty); 10759 } 10760 10761 void VEABIInfo::computeInfo(CGFunctionInfo &FI) const { 10762 10763 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 10764 for (auto &Arg : FI.arguments()) 10765 Arg.info = classifyArgumentType(Arg.type); 10766 } 10767 10768 namespace { 10769 class VETargetCodeGenInfo : public TargetCodeGenInfo { 10770 public: 10771 VETargetCodeGenInfo(CodeGenTypes &CGT) 10772 : TargetCodeGenInfo(std::make_unique<VEABIInfo>(CGT)) {} 10773 // VE ABI requires the arguments of variadic and prototype-less functions 10774 // are passed in both registers and memory. 10775 bool isNoProtoCallVariadic(const CallArgList &args, 10776 const FunctionNoProtoType *fnType) const override { 10777 return true; 10778 } 10779 }; 10780 } // end anonymous namespace 10781 10782 //===----------------------------------------------------------------------===// 10783 // Driver code 10784 //===----------------------------------------------------------------------===// 10785 10786 bool CodeGenModule::supportsCOMDAT() const { 10787 return getTriple().supportsCOMDAT(); 10788 } 10789 10790 const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() { 10791 if (TheTargetCodeGenInfo) 10792 return *TheTargetCodeGenInfo; 10793 10794 // Helper to set the unique_ptr while still keeping the return value. 10795 auto SetCGInfo = [&](TargetCodeGenInfo *P) -> const TargetCodeGenInfo & { 10796 this->TheTargetCodeGenInfo.reset(P); 10797 return *P; 10798 }; 10799 10800 const llvm::Triple &Triple = getTarget().getTriple(); 10801 switch (Triple.getArch()) { 10802 default: 10803 return SetCGInfo(new DefaultTargetCodeGenInfo(Types)); 10804 10805 case llvm::Triple::le32: 10806 return SetCGInfo(new PNaClTargetCodeGenInfo(Types)); 10807 case llvm::Triple::mips: 10808 case llvm::Triple::mipsel: 10809 if (Triple.getOS() == llvm::Triple::NaCl) 10810 return SetCGInfo(new PNaClTargetCodeGenInfo(Types)); 10811 return SetCGInfo(new MIPSTargetCodeGenInfo(Types, true)); 10812 10813 case llvm::Triple::mips64: 10814 case llvm::Triple::mips64el: 10815 return SetCGInfo(new MIPSTargetCodeGenInfo(Types, false)); 10816 10817 case llvm::Triple::avr: 10818 return SetCGInfo(new AVRTargetCodeGenInfo(Types)); 10819 10820 case llvm::Triple::aarch64: 10821 case llvm::Triple::aarch64_32: 10822 case llvm::Triple::aarch64_be: { 10823 AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS; 10824 if (getTarget().getABI() == "darwinpcs") 10825 Kind = AArch64ABIInfo::DarwinPCS; 10826 else if (Triple.isOSWindows()) 10827 return SetCGInfo( 10828 new WindowsAArch64TargetCodeGenInfo(Types, AArch64ABIInfo::Win64)); 10829 10830 return SetCGInfo(new AArch64TargetCodeGenInfo(Types, Kind)); 10831 } 10832 10833 case llvm::Triple::wasm32: 10834 case llvm::Triple::wasm64: { 10835 WebAssemblyABIInfo::ABIKind Kind = WebAssemblyABIInfo::MVP; 10836 if (getTarget().getABI() == "experimental-mv") 10837 Kind = WebAssemblyABIInfo::ExperimentalMV; 10838 return SetCGInfo(new WebAssemblyTargetCodeGenInfo(Types, Kind)); 10839 } 10840 10841 case llvm::Triple::arm: 10842 case llvm::Triple::armeb: 10843 case llvm::Triple::thumb: 10844 case llvm::Triple::thumbeb: { 10845 if (Triple.getOS() == llvm::Triple::Win32) { 10846 return SetCGInfo( 10847 new WindowsARMTargetCodeGenInfo(Types, ARMABIInfo::AAPCS_VFP)); 10848 } 10849 10850 ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS; 10851 StringRef ABIStr = getTarget().getABI(); 10852 if (ABIStr == "apcs-gnu") 10853 Kind = ARMABIInfo::APCS; 10854 else if (ABIStr == "aapcs16") 10855 Kind = ARMABIInfo::AAPCS16_VFP; 10856 else if (CodeGenOpts.FloatABI == "hard" || 10857 (CodeGenOpts.FloatABI != "soft" && 10858 (Triple.getEnvironment() == llvm::Triple::GNUEABIHF || 10859 Triple.getEnvironment() == llvm::Triple::MuslEABIHF || 10860 Triple.getEnvironment() == llvm::Triple::EABIHF))) 10861 Kind = ARMABIInfo::AAPCS_VFP; 10862 10863 return SetCGInfo(new ARMTargetCodeGenInfo(Types, Kind)); 10864 } 10865 10866 case llvm::Triple::ppc: { 10867 if (Triple.isOSAIX()) 10868 return SetCGInfo(new AIXTargetCodeGenInfo(Types, /*Is64Bit*/ false)); 10869 10870 bool IsSoftFloat = 10871 CodeGenOpts.FloatABI == "soft" || getTarget().hasFeature("spe"); 10872 bool RetSmallStructInRegABI = 10873 PPC32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts); 10874 return SetCGInfo( 10875 new PPC32TargetCodeGenInfo(Types, IsSoftFloat, RetSmallStructInRegABI)); 10876 } 10877 case llvm::Triple::ppc64: 10878 if (Triple.isOSAIX()) 10879 return SetCGInfo(new AIXTargetCodeGenInfo(Types, /*Is64Bit*/ true)); 10880 10881 if (Triple.isOSBinFormatELF()) { 10882 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1; 10883 if (getTarget().getABI() == "elfv2") 10884 Kind = PPC64_SVR4_ABIInfo::ELFv2; 10885 bool HasQPX = getTarget().getABI() == "elfv1-qpx"; 10886 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft"; 10887 10888 return SetCGInfo(new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX, 10889 IsSoftFloat)); 10890 } 10891 return SetCGInfo(new PPC64TargetCodeGenInfo(Types)); 10892 case llvm::Triple::ppc64le: { 10893 assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!"); 10894 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2; 10895 if (getTarget().getABI() == "elfv1" || getTarget().getABI() == "elfv1-qpx") 10896 Kind = PPC64_SVR4_ABIInfo::ELFv1; 10897 bool HasQPX = getTarget().getABI() == "elfv1-qpx"; 10898 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft"; 10899 10900 return SetCGInfo(new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX, 10901 IsSoftFloat)); 10902 } 10903 10904 case llvm::Triple::nvptx: 10905 case llvm::Triple::nvptx64: 10906 return SetCGInfo(new NVPTXTargetCodeGenInfo(Types)); 10907 10908 case llvm::Triple::msp430: 10909 return SetCGInfo(new MSP430TargetCodeGenInfo(Types)); 10910 10911 case llvm::Triple::riscv32: 10912 case llvm::Triple::riscv64: { 10913 StringRef ABIStr = getTarget().getABI(); 10914 unsigned XLen = getTarget().getPointerWidth(0); 10915 unsigned ABIFLen = 0; 10916 if (ABIStr.endswith("f")) 10917 ABIFLen = 32; 10918 else if (ABIStr.endswith("d")) 10919 ABIFLen = 64; 10920 return SetCGInfo(new RISCVTargetCodeGenInfo(Types, XLen, ABIFLen)); 10921 } 10922 10923 case llvm::Triple::systemz: { 10924 bool SoftFloat = CodeGenOpts.FloatABI == "soft"; 10925 bool HasVector = !SoftFloat && getTarget().getABI() == "vector"; 10926 return SetCGInfo(new SystemZTargetCodeGenInfo(Types, HasVector, SoftFloat)); 10927 } 10928 10929 case llvm::Triple::tce: 10930 case llvm::Triple::tcele: 10931 return SetCGInfo(new TCETargetCodeGenInfo(Types)); 10932 10933 case llvm::Triple::x86: { 10934 bool IsDarwinVectorABI = Triple.isOSDarwin(); 10935 bool RetSmallStructInRegABI = 10936 X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts); 10937 bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing(); 10938 10939 if (Triple.getOS() == llvm::Triple::Win32) { 10940 return SetCGInfo(new WinX86_32TargetCodeGenInfo( 10941 Types, IsDarwinVectorABI, RetSmallStructInRegABI, 10942 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters)); 10943 } else { 10944 return SetCGInfo(new X86_32TargetCodeGenInfo( 10945 Types, IsDarwinVectorABI, RetSmallStructInRegABI, 10946 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters, 10947 CodeGenOpts.FloatABI == "soft")); 10948 } 10949 } 10950 10951 case llvm::Triple::x86_64: { 10952 StringRef ABI = getTarget().getABI(); 10953 X86AVXABILevel AVXLevel = 10954 (ABI == "avx512" 10955 ? X86AVXABILevel::AVX512 10956 : ABI == "avx" ? X86AVXABILevel::AVX : X86AVXABILevel::None); 10957 10958 switch (Triple.getOS()) { 10959 case llvm::Triple::Win32: 10960 return SetCGInfo(new WinX86_64TargetCodeGenInfo(Types, AVXLevel)); 10961 default: 10962 return SetCGInfo(new X86_64TargetCodeGenInfo(Types, AVXLevel)); 10963 } 10964 } 10965 case llvm::Triple::hexagon: 10966 return SetCGInfo(new HexagonTargetCodeGenInfo(Types)); 10967 case llvm::Triple::lanai: 10968 return SetCGInfo(new LanaiTargetCodeGenInfo(Types)); 10969 case llvm::Triple::r600: 10970 return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types)); 10971 case llvm::Triple::amdgcn: 10972 return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types)); 10973 case llvm::Triple::sparc: 10974 return SetCGInfo(new SparcV8TargetCodeGenInfo(Types)); 10975 case llvm::Triple::sparcv9: 10976 return SetCGInfo(new SparcV9TargetCodeGenInfo(Types)); 10977 case llvm::Triple::xcore: 10978 return SetCGInfo(new XCoreTargetCodeGenInfo(Types)); 10979 case llvm::Triple::arc: 10980 return SetCGInfo(new ARCTargetCodeGenInfo(Types)); 10981 case llvm::Triple::spir: 10982 case llvm::Triple::spir64: 10983 return SetCGInfo(new SPIRTargetCodeGenInfo(Types)); 10984 case llvm::Triple::ve: 10985 return SetCGInfo(new VETargetCodeGenInfo(Types)); 10986 } 10987 } 10988 10989 /// Create an OpenCL kernel for an enqueued block. 10990 /// 10991 /// The kernel has the same function type as the block invoke function. Its 10992 /// name is the name of the block invoke function postfixed with "_kernel". 10993 /// It simply calls the block invoke function then returns. 10994 llvm::Function * 10995 TargetCodeGenInfo::createEnqueuedBlockKernel(CodeGenFunction &CGF, 10996 llvm::Function *Invoke, 10997 llvm::Value *BlockLiteral) const { 10998 auto *InvokeFT = Invoke->getFunctionType(); 10999 llvm::SmallVector<llvm::Type *, 2> ArgTys; 11000 for (auto &P : InvokeFT->params()) 11001 ArgTys.push_back(P); 11002 auto &C = CGF.getLLVMContext(); 11003 std::string Name = Invoke->getName().str() + "_kernel"; 11004 auto *FT = llvm::FunctionType::get(llvm::Type::getVoidTy(C), ArgTys, false); 11005 auto *F = llvm::Function::Create(FT, llvm::GlobalValue::InternalLinkage, Name, 11006 &CGF.CGM.getModule()); 11007 auto IP = CGF.Builder.saveIP(); 11008 auto *BB = llvm::BasicBlock::Create(C, "entry", F); 11009 auto &Builder = CGF.Builder; 11010 Builder.SetInsertPoint(BB); 11011 llvm::SmallVector<llvm::Value *, 2> Args; 11012 for (auto &A : F->args()) 11013 Args.push_back(&A); 11014 Builder.CreateCall(Invoke, Args); 11015 Builder.CreateRetVoid(); 11016 Builder.restoreIP(IP); 11017 return F; 11018 } 11019 11020 /// Create an OpenCL kernel for an enqueued block. 11021 /// 11022 /// The type of the first argument (the block literal) is the struct type 11023 /// of the block literal instead of a pointer type. The first argument 11024 /// (block literal) is passed directly by value to the kernel. The kernel 11025 /// allocates the same type of struct on stack and stores the block literal 11026 /// to it and passes its pointer to the block invoke function. The kernel 11027 /// has "enqueued-block" function attribute and kernel argument metadata. 11028 llvm::Function *AMDGPUTargetCodeGenInfo::createEnqueuedBlockKernel( 11029 CodeGenFunction &CGF, llvm::Function *Invoke, 11030 llvm::Value *BlockLiteral) const { 11031 auto &Builder = CGF.Builder; 11032 auto &C = CGF.getLLVMContext(); 11033 11034 auto *BlockTy = BlockLiteral->getType()->getPointerElementType(); 11035 auto *InvokeFT = Invoke->getFunctionType(); 11036 llvm::SmallVector<llvm::Type *, 2> ArgTys; 11037 llvm::SmallVector<llvm::Metadata *, 8> AddressQuals; 11038 llvm::SmallVector<llvm::Metadata *, 8> AccessQuals; 11039 llvm::SmallVector<llvm::Metadata *, 8> ArgTypeNames; 11040 llvm::SmallVector<llvm::Metadata *, 8> ArgBaseTypeNames; 11041 llvm::SmallVector<llvm::Metadata *, 8> ArgTypeQuals; 11042 llvm::SmallVector<llvm::Metadata *, 8> ArgNames; 11043 11044 ArgTys.push_back(BlockTy); 11045 ArgTypeNames.push_back(llvm::MDString::get(C, "__block_literal")); 11046 AddressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(0))); 11047 ArgBaseTypeNames.push_back(llvm::MDString::get(C, "__block_literal")); 11048 ArgTypeQuals.push_back(llvm::MDString::get(C, "")); 11049 AccessQuals.push_back(llvm::MDString::get(C, "none")); 11050 ArgNames.push_back(llvm::MDString::get(C, "block_literal")); 11051 for (unsigned I = 1, E = InvokeFT->getNumParams(); I < E; ++I) { 11052 ArgTys.push_back(InvokeFT->getParamType(I)); 11053 ArgTypeNames.push_back(llvm::MDString::get(C, "void*")); 11054 AddressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(3))); 11055 AccessQuals.push_back(llvm::MDString::get(C, "none")); 11056 ArgBaseTypeNames.push_back(llvm::MDString::get(C, "void*")); 11057 ArgTypeQuals.push_back(llvm::MDString::get(C, "")); 11058 ArgNames.push_back( 11059 llvm::MDString::get(C, (Twine("local_arg") + Twine(I)).str())); 11060 } 11061 std::string Name = Invoke->getName().str() + "_kernel"; 11062 auto *FT = llvm::FunctionType::get(llvm::Type::getVoidTy(C), ArgTys, false); 11063 auto *F = llvm::Function::Create(FT, llvm::GlobalValue::InternalLinkage, Name, 11064 &CGF.CGM.getModule()); 11065 F->addFnAttr("enqueued-block"); 11066 auto IP = CGF.Builder.saveIP(); 11067 auto *BB = llvm::BasicBlock::Create(C, "entry", F); 11068 Builder.SetInsertPoint(BB); 11069 const auto BlockAlign = CGF.CGM.getDataLayout().getPrefTypeAlign(BlockTy); 11070 auto *BlockPtr = Builder.CreateAlloca(BlockTy, nullptr); 11071 BlockPtr->setAlignment(BlockAlign); 11072 Builder.CreateAlignedStore(F->arg_begin(), BlockPtr, BlockAlign); 11073 auto *Cast = Builder.CreatePointerCast(BlockPtr, InvokeFT->getParamType(0)); 11074 llvm::SmallVector<llvm::Value *, 2> Args; 11075 Args.push_back(Cast); 11076 for (auto I = F->arg_begin() + 1, E = F->arg_end(); I != E; ++I) 11077 Args.push_back(I); 11078 Builder.CreateCall(Invoke, Args); 11079 Builder.CreateRetVoid(); 11080 Builder.restoreIP(IP); 11081 11082 F->setMetadata("kernel_arg_addr_space", llvm::MDNode::get(C, AddressQuals)); 11083 F->setMetadata("kernel_arg_access_qual", llvm::MDNode::get(C, AccessQuals)); 11084 F->setMetadata("kernel_arg_type", llvm::MDNode::get(C, ArgTypeNames)); 11085 F->setMetadata("kernel_arg_base_type", 11086 llvm::MDNode::get(C, ArgBaseTypeNames)); 11087 F->setMetadata("kernel_arg_type_qual", llvm::MDNode::get(C, ArgTypeQuals)); 11088 if (CGF.CGM.getCodeGenOpts().EmitOpenCLArgMetadata) 11089 F->setMetadata("kernel_arg_name", llvm::MDNode::get(C, ArgNames)); 11090 11091 return F; 11092 } 11093