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/CodeGen/CGFunctionInfo.h" 24 #include "clang/CodeGen/SwiftCallingConv.h" 25 #include "llvm/ADT/SmallBitVector.h" 26 #include "llvm/ADT/StringExtras.h" 27 #include "llvm/ADT/StringSwitch.h" 28 #include "llvm/ADT/Triple.h" 29 #include "llvm/ADT/Twine.h" 30 #include "llvm/IR/DataLayout.h" 31 #include "llvm/IR/IntrinsicsNVPTX.h" 32 #include "llvm/IR/Type.h" 33 #include "llvm/Support/raw_ostream.h" 34 #include <algorithm> // std::sort 35 36 using namespace clang; 37 using namespace CodeGen; 38 39 // Helper for coercing an aggregate argument or return value into an integer 40 // array of the same size (including padding) and alignment. This alternate 41 // coercion happens only for the RenderScript ABI and can be removed after 42 // runtimes that rely on it are no longer supported. 43 // 44 // RenderScript assumes that the size of the argument / return value in the IR 45 // is the same as the size of the corresponding qualified type. This helper 46 // coerces the aggregate type into an array of the same size (including 47 // padding). This coercion is used in lieu of expansion of struct members or 48 // other canonical coercions that return a coerced-type of larger size. 49 // 50 // Ty - The argument / return value type 51 // Context - The associated ASTContext 52 // LLVMContext - The associated LLVMContext 53 static ABIArgInfo coerceToIntArray(QualType Ty, 54 ASTContext &Context, 55 llvm::LLVMContext &LLVMContext) { 56 // Alignment and Size are measured in bits. 57 const uint64_t Size = Context.getTypeSize(Ty); 58 const uint64_t Alignment = Context.getTypeAlign(Ty); 59 llvm::Type *IntType = llvm::Type::getIntNTy(LLVMContext, Alignment); 60 const uint64_t NumElements = (Size + Alignment - 1) / Alignment; 61 return ABIArgInfo::getDirect(llvm::ArrayType::get(IntType, NumElements)); 62 } 63 64 static void AssignToArrayRange(CodeGen::CGBuilderTy &Builder, 65 llvm::Value *Array, 66 llvm::Value *Value, 67 unsigned FirstIndex, 68 unsigned LastIndex) { 69 // Alternatively, we could emit this as a loop in the source. 70 for (unsigned I = FirstIndex; I <= LastIndex; ++I) { 71 llvm::Value *Cell = 72 Builder.CreateConstInBoundsGEP1_32(Builder.getInt8Ty(), Array, I); 73 Builder.CreateAlignedStore(Value, Cell, CharUnits::One()); 74 } 75 } 76 77 static bool isAggregateTypeForABI(QualType T) { 78 return !CodeGenFunction::hasScalarEvaluationKind(T) || 79 T->isMemberFunctionPointerType(); 80 } 81 82 ABIArgInfo 83 ABIInfo::getNaturalAlignIndirect(QualType Ty, bool ByRef, bool Realign, 84 llvm::Type *Padding) const { 85 return ABIArgInfo::getIndirect(getContext().getTypeAlignInChars(Ty), 86 ByRef, Realign, Padding); 87 } 88 89 ABIArgInfo 90 ABIInfo::getNaturalAlignIndirectInReg(QualType Ty, bool Realign) const { 91 return ABIArgInfo::getIndirectInReg(getContext().getTypeAlignInChars(Ty), 92 /*ByRef*/ false, Realign); 93 } 94 95 Address ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr, 96 QualType Ty) const { 97 return Address::invalid(); 98 } 99 100 ABIInfo::~ABIInfo() {} 101 102 /// Does the given lowering require more than the given number of 103 /// registers when expanded? 104 /// 105 /// This is intended to be the basis of a reasonable basic implementation 106 /// of should{Pass,Return}IndirectlyForSwift. 107 /// 108 /// For most targets, a limit of four total registers is reasonable; this 109 /// limits the amount of code required in order to move around the value 110 /// in case it wasn't produced immediately prior to the call by the caller 111 /// (or wasn't produced in exactly the right registers) or isn't used 112 /// immediately within the callee. But some targets may need to further 113 /// limit the register count due to an inability to support that many 114 /// return registers. 115 static bool occupiesMoreThan(CodeGenTypes &cgt, 116 ArrayRef<llvm::Type*> scalarTypes, 117 unsigned maxAllRegisters) { 118 unsigned intCount = 0, fpCount = 0; 119 for (llvm::Type *type : scalarTypes) { 120 if (type->isPointerTy()) { 121 intCount++; 122 } else if (auto intTy = dyn_cast<llvm::IntegerType>(type)) { 123 auto ptrWidth = cgt.getTarget().getPointerWidth(0); 124 intCount += (intTy->getBitWidth() + ptrWidth - 1) / ptrWidth; 125 } else { 126 assert(type->isVectorTy() || type->isFloatingPointTy()); 127 fpCount++; 128 } 129 } 130 131 return (intCount + fpCount > maxAllRegisters); 132 } 133 134 bool SwiftABIInfo::isLegalVectorTypeForSwift(CharUnits vectorSize, 135 llvm::Type *eltTy, 136 unsigned numElts) const { 137 // The default implementation of this assumes that the target guarantees 138 // 128-bit SIMD support but nothing more. 139 return (vectorSize.getQuantity() > 8 && vectorSize.getQuantity() <= 16); 140 } 141 142 static CGCXXABI::RecordArgABI getRecordArgABI(const RecordType *RT, 143 CGCXXABI &CXXABI) { 144 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 145 if (!RD) { 146 if (!RT->getDecl()->canPassInRegisters()) 147 return CGCXXABI::RAA_Indirect; 148 return CGCXXABI::RAA_Default; 149 } 150 return CXXABI.getRecordArgABI(RD); 151 } 152 153 static CGCXXABI::RecordArgABI getRecordArgABI(QualType T, 154 CGCXXABI &CXXABI) { 155 const RecordType *RT = T->getAs<RecordType>(); 156 if (!RT) 157 return CGCXXABI::RAA_Default; 158 return getRecordArgABI(RT, CXXABI); 159 } 160 161 static bool classifyReturnType(const CGCXXABI &CXXABI, CGFunctionInfo &FI, 162 const ABIInfo &Info) { 163 QualType Ty = FI.getReturnType(); 164 165 if (const auto *RT = Ty->getAs<RecordType>()) 166 if (!isa<CXXRecordDecl>(RT->getDecl()) && 167 !RT->getDecl()->canPassInRegisters()) { 168 FI.getReturnInfo() = Info.getNaturalAlignIndirect(Ty); 169 return true; 170 } 171 172 return CXXABI.classifyReturnType(FI); 173 } 174 175 /// Pass transparent unions as if they were the type of the first element. Sema 176 /// should ensure that all elements of the union have the same "machine type". 177 static QualType useFirstFieldIfTransparentUnion(QualType Ty) { 178 if (const RecordType *UT = Ty->getAsUnionType()) { 179 const RecordDecl *UD = UT->getDecl(); 180 if (UD->hasAttr<TransparentUnionAttr>()) { 181 assert(!UD->field_empty() && "sema created an empty transparent union"); 182 return UD->field_begin()->getType(); 183 } 184 } 185 return Ty; 186 } 187 188 CGCXXABI &ABIInfo::getCXXABI() const { 189 return CGT.getCXXABI(); 190 } 191 192 ASTContext &ABIInfo::getContext() const { 193 return CGT.getContext(); 194 } 195 196 llvm::LLVMContext &ABIInfo::getVMContext() const { 197 return CGT.getLLVMContext(); 198 } 199 200 const llvm::DataLayout &ABIInfo::getDataLayout() const { 201 return CGT.getDataLayout(); 202 } 203 204 const TargetInfo &ABIInfo::getTarget() const { 205 return CGT.getTarget(); 206 } 207 208 const CodeGenOptions &ABIInfo::getCodeGenOpts() const { 209 return CGT.getCodeGenOpts(); 210 } 211 212 bool ABIInfo::isAndroid() const { return getTarget().getTriple().isAndroid(); } 213 214 bool ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const { 215 return false; 216 } 217 218 bool ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base, 219 uint64_t Members) const { 220 return false; 221 } 222 223 LLVM_DUMP_METHOD void ABIArgInfo::dump() const { 224 raw_ostream &OS = llvm::errs(); 225 OS << "(ABIArgInfo Kind="; 226 switch (TheKind) { 227 case Direct: 228 OS << "Direct Type="; 229 if (llvm::Type *Ty = getCoerceToType()) 230 Ty->print(OS); 231 else 232 OS << "null"; 233 break; 234 case Extend: 235 OS << "Extend"; 236 break; 237 case Ignore: 238 OS << "Ignore"; 239 break; 240 case InAlloca: 241 OS << "InAlloca Offset=" << getInAllocaFieldIndex(); 242 break; 243 case Indirect: 244 OS << "Indirect Align=" << getIndirectAlign().getQuantity() 245 << " ByVal=" << getIndirectByVal() 246 << " Realign=" << getIndirectRealign(); 247 break; 248 case Expand: 249 OS << "Expand"; 250 break; 251 case CoerceAndExpand: 252 OS << "CoerceAndExpand Type="; 253 getCoerceAndExpandType()->print(OS); 254 break; 255 } 256 OS << ")\n"; 257 } 258 259 // Dynamically round a pointer up to a multiple of the given alignment. 260 static llvm::Value *emitRoundPointerUpToAlignment(CodeGenFunction &CGF, 261 llvm::Value *Ptr, 262 CharUnits Align) { 263 llvm::Value *PtrAsInt = Ptr; 264 // OverflowArgArea = (OverflowArgArea + Align - 1) & -Align; 265 PtrAsInt = CGF.Builder.CreatePtrToInt(PtrAsInt, CGF.IntPtrTy); 266 PtrAsInt = CGF.Builder.CreateAdd(PtrAsInt, 267 llvm::ConstantInt::get(CGF.IntPtrTy, Align.getQuantity() - 1)); 268 PtrAsInt = CGF.Builder.CreateAnd(PtrAsInt, 269 llvm::ConstantInt::get(CGF.IntPtrTy, -Align.getQuantity())); 270 PtrAsInt = CGF.Builder.CreateIntToPtr(PtrAsInt, 271 Ptr->getType(), 272 Ptr->getName() + ".aligned"); 273 return PtrAsInt; 274 } 275 276 /// Emit va_arg for a platform using the common void* representation, 277 /// where arguments are simply emitted in an array of slots on the stack. 278 /// 279 /// This version implements the core direct-value passing rules. 280 /// 281 /// \param SlotSize - The size and alignment of a stack slot. 282 /// Each argument will be allocated to a multiple of this number of 283 /// slots, and all the slots will be aligned to this value. 284 /// \param AllowHigherAlign - The slot alignment is not a cap; 285 /// an argument type with an alignment greater than the slot size 286 /// will be emitted on a higher-alignment address, potentially 287 /// leaving one or more empty slots behind as padding. If this 288 /// is false, the returned address might be less-aligned than 289 /// DirectAlign. 290 static Address emitVoidPtrDirectVAArg(CodeGenFunction &CGF, 291 Address VAListAddr, 292 llvm::Type *DirectTy, 293 CharUnits DirectSize, 294 CharUnits DirectAlign, 295 CharUnits SlotSize, 296 bool AllowHigherAlign) { 297 // Cast the element type to i8* if necessary. Some platforms define 298 // va_list as a struct containing an i8* instead of just an i8*. 299 if (VAListAddr.getElementType() != CGF.Int8PtrTy) 300 VAListAddr = CGF.Builder.CreateElementBitCast(VAListAddr, CGF.Int8PtrTy); 301 302 llvm::Value *Ptr = CGF.Builder.CreateLoad(VAListAddr, "argp.cur"); 303 304 // If the CC aligns values higher than the slot size, do so if needed. 305 Address Addr = Address::invalid(); 306 if (AllowHigherAlign && DirectAlign > SlotSize) { 307 Addr = Address(emitRoundPointerUpToAlignment(CGF, Ptr, DirectAlign), 308 DirectAlign); 309 } else { 310 Addr = Address(Ptr, SlotSize); 311 } 312 313 // Advance the pointer past the argument, then store that back. 314 CharUnits FullDirectSize = DirectSize.alignTo(SlotSize); 315 Address NextPtr = 316 CGF.Builder.CreateConstInBoundsByteGEP(Addr, FullDirectSize, "argp.next"); 317 CGF.Builder.CreateStore(NextPtr.getPointer(), VAListAddr); 318 319 // If the argument is smaller than a slot, and this is a big-endian 320 // target, the argument will be right-adjusted in its slot. 321 if (DirectSize < SlotSize && CGF.CGM.getDataLayout().isBigEndian() && 322 !DirectTy->isStructTy()) { 323 Addr = CGF.Builder.CreateConstInBoundsByteGEP(Addr, SlotSize - DirectSize); 324 } 325 326 Addr = CGF.Builder.CreateElementBitCast(Addr, DirectTy); 327 return Addr; 328 } 329 330 /// Emit va_arg for a platform using the common void* representation, 331 /// where arguments are simply emitted in an array of slots on the stack. 332 /// 333 /// \param IsIndirect - Values of this type are passed indirectly. 334 /// \param ValueInfo - The size and alignment of this type, generally 335 /// computed with getContext().getTypeInfoInChars(ValueTy). 336 /// \param SlotSizeAndAlign - The size and alignment of a stack slot. 337 /// Each argument will be allocated to a multiple of this number of 338 /// slots, and all the slots will be aligned to this value. 339 /// \param AllowHigherAlign - The slot alignment is not a cap; 340 /// an argument type with an alignment greater than the slot size 341 /// will be emitted on a higher-alignment address, potentially 342 /// leaving one or more empty slots behind as padding. 343 static Address emitVoidPtrVAArg(CodeGenFunction &CGF, Address VAListAddr, 344 QualType ValueTy, bool IsIndirect, 345 std::pair<CharUnits, CharUnits> ValueInfo, 346 CharUnits SlotSizeAndAlign, 347 bool AllowHigherAlign) { 348 // The size and alignment of the value that was passed directly. 349 CharUnits DirectSize, DirectAlign; 350 if (IsIndirect) { 351 DirectSize = CGF.getPointerSize(); 352 DirectAlign = CGF.getPointerAlign(); 353 } else { 354 DirectSize = ValueInfo.first; 355 DirectAlign = ValueInfo.second; 356 } 357 358 // Cast the address we've calculated to the right type. 359 llvm::Type *DirectTy = CGF.ConvertTypeForMem(ValueTy); 360 if (IsIndirect) 361 DirectTy = DirectTy->getPointerTo(0); 362 363 Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, DirectTy, 364 DirectSize, DirectAlign, 365 SlotSizeAndAlign, 366 AllowHigherAlign); 367 368 if (IsIndirect) { 369 Addr = Address(CGF.Builder.CreateLoad(Addr), ValueInfo.second); 370 } 371 372 return Addr; 373 374 } 375 376 static Address emitMergePHI(CodeGenFunction &CGF, 377 Address Addr1, llvm::BasicBlock *Block1, 378 Address Addr2, llvm::BasicBlock *Block2, 379 const llvm::Twine &Name = "") { 380 assert(Addr1.getType() == Addr2.getType()); 381 llvm::PHINode *PHI = CGF.Builder.CreatePHI(Addr1.getType(), 2, Name); 382 PHI->addIncoming(Addr1.getPointer(), Block1); 383 PHI->addIncoming(Addr2.getPointer(), Block2); 384 CharUnits Align = std::min(Addr1.getAlignment(), Addr2.getAlignment()); 385 return Address(PHI, Align); 386 } 387 388 TargetCodeGenInfo::~TargetCodeGenInfo() = default; 389 390 // If someone can figure out a general rule for this, that would be great. 391 // It's probably just doomed to be platform-dependent, though. 392 unsigned TargetCodeGenInfo::getSizeOfUnwindException() const { 393 // Verified for: 394 // x86-64 FreeBSD, Linux, Darwin 395 // x86-32 FreeBSD, Linux, Darwin 396 // PowerPC Linux, Darwin 397 // ARM Darwin (*not* EABI) 398 // AArch64 Linux 399 return 32; 400 } 401 402 bool TargetCodeGenInfo::isNoProtoCallVariadic(const CallArgList &args, 403 const FunctionNoProtoType *fnType) const { 404 // The following conventions are known to require this to be false: 405 // x86_stdcall 406 // MIPS 407 // For everything else, we just prefer false unless we opt out. 408 return false; 409 } 410 411 void 412 TargetCodeGenInfo::getDependentLibraryOption(llvm::StringRef Lib, 413 llvm::SmallString<24> &Opt) const { 414 // This assumes the user is passing a library name like "rt" instead of a 415 // filename like "librt.a/so", and that they don't care whether it's static or 416 // dynamic. 417 Opt = "-l"; 418 Opt += Lib; 419 } 420 421 unsigned TargetCodeGenInfo::getOpenCLKernelCallingConv() const { 422 // OpenCL kernels are called via an explicit runtime API with arguments 423 // set with clSetKernelArg(), not as normal sub-functions. 424 // Return SPIR_KERNEL by default as the kernel calling convention to 425 // ensure the fingerprint is fixed such way that each OpenCL argument 426 // gets one matching argument in the produced kernel function argument 427 // list to enable feasible implementation of clSetKernelArg() with 428 // aggregates etc. In case we would use the default C calling conv here, 429 // clSetKernelArg() might break depending on the target-specific 430 // conventions; different targets might split structs passed as values 431 // to multiple function arguments etc. 432 return llvm::CallingConv::SPIR_KERNEL; 433 } 434 435 llvm::Constant *TargetCodeGenInfo::getNullPointer(const CodeGen::CodeGenModule &CGM, 436 llvm::PointerType *T, QualType QT) const { 437 return llvm::ConstantPointerNull::get(T); 438 } 439 440 LangAS TargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM, 441 const VarDecl *D) const { 442 assert(!CGM.getLangOpts().OpenCL && 443 !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) && 444 "Address space agnostic languages only"); 445 return D ? D->getType().getAddressSpace() : LangAS::Default; 446 } 447 448 llvm::Value *TargetCodeGenInfo::performAddrSpaceCast( 449 CodeGen::CodeGenFunction &CGF, llvm::Value *Src, LangAS SrcAddr, 450 LangAS DestAddr, llvm::Type *DestTy, bool isNonNull) const { 451 // Since target may map different address spaces in AST to the same address 452 // space, an address space conversion may end up as a bitcast. 453 if (auto *C = dyn_cast<llvm::Constant>(Src)) 454 return performAddrSpaceCast(CGF.CGM, C, SrcAddr, DestAddr, DestTy); 455 // Try to preserve the source's name to make IR more readable. 456 return CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( 457 Src, DestTy, Src->hasName() ? Src->getName() + ".ascast" : ""); 458 } 459 460 llvm::Constant * 461 TargetCodeGenInfo::performAddrSpaceCast(CodeGenModule &CGM, llvm::Constant *Src, 462 LangAS SrcAddr, LangAS DestAddr, 463 llvm::Type *DestTy) const { 464 // Since target may map different address spaces in AST to the same address 465 // space, an address space conversion may end up as a bitcast. 466 return llvm::ConstantExpr::getPointerCast(Src, DestTy); 467 } 468 469 llvm::SyncScope::ID 470 TargetCodeGenInfo::getLLVMSyncScopeID(const LangOptions &LangOpts, 471 SyncScope Scope, 472 llvm::AtomicOrdering Ordering, 473 llvm::LLVMContext &Ctx) const { 474 return Ctx.getOrInsertSyncScopeID(""); /* default sync scope */ 475 } 476 477 static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays); 478 479 /// isEmptyField - Return true iff a the field is "empty", that is it 480 /// is an unnamed bit-field or an (array of) empty record(s). 481 static bool isEmptyField(ASTContext &Context, const FieldDecl *FD, 482 bool AllowArrays) { 483 if (FD->isUnnamedBitfield()) 484 return true; 485 486 QualType FT = FD->getType(); 487 488 // Constant arrays of empty records count as empty, strip them off. 489 // Constant arrays of zero length always count as empty. 490 if (AllowArrays) 491 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) { 492 if (AT->getSize() == 0) 493 return true; 494 FT = AT->getElementType(); 495 } 496 497 const RecordType *RT = FT->getAs<RecordType>(); 498 if (!RT) 499 return false; 500 501 // C++ record fields are never empty, at least in the Itanium ABI. 502 // 503 // FIXME: We should use a predicate for whether this behavior is true in the 504 // current ABI. 505 if (isa<CXXRecordDecl>(RT->getDecl())) 506 return false; 507 508 return isEmptyRecord(Context, FT, AllowArrays); 509 } 510 511 /// isEmptyRecord - Return true iff a structure contains only empty 512 /// fields. Note that a structure with a flexible array member is not 513 /// considered empty. 514 static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) { 515 const RecordType *RT = T->getAs<RecordType>(); 516 if (!RT) 517 return false; 518 const RecordDecl *RD = RT->getDecl(); 519 if (RD->hasFlexibleArrayMember()) 520 return false; 521 522 // If this is a C++ record, check the bases first. 523 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 524 for (const auto &I : CXXRD->bases()) 525 if (!isEmptyRecord(Context, I.getType(), true)) 526 return false; 527 528 for (const auto *I : RD->fields()) 529 if (!isEmptyField(Context, I, AllowArrays)) 530 return false; 531 return true; 532 } 533 534 /// isSingleElementStruct - Determine if a structure is a "single 535 /// element struct", i.e. it has exactly one non-empty field or 536 /// exactly one field which is itself a single element 537 /// struct. Structures with flexible array members are never 538 /// considered single element structs. 539 /// 540 /// \return The field declaration for the single non-empty field, if 541 /// it exists. 542 static const Type *isSingleElementStruct(QualType T, ASTContext &Context) { 543 const RecordType *RT = T->getAs<RecordType>(); 544 if (!RT) 545 return nullptr; 546 547 const RecordDecl *RD = RT->getDecl(); 548 if (RD->hasFlexibleArrayMember()) 549 return nullptr; 550 551 const Type *Found = nullptr; 552 553 // If this is a C++ record, check the bases first. 554 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 555 for (const auto &I : CXXRD->bases()) { 556 // Ignore empty records. 557 if (isEmptyRecord(Context, I.getType(), true)) 558 continue; 559 560 // If we already found an element then this isn't a single-element struct. 561 if (Found) 562 return nullptr; 563 564 // If this is non-empty and not a single element struct, the composite 565 // cannot be a single element struct. 566 Found = isSingleElementStruct(I.getType(), Context); 567 if (!Found) 568 return nullptr; 569 } 570 } 571 572 // Check for single element. 573 for (const auto *FD : RD->fields()) { 574 QualType FT = FD->getType(); 575 576 // Ignore empty fields. 577 if (isEmptyField(Context, FD, true)) 578 continue; 579 580 // If we already found an element then this isn't a single-element 581 // struct. 582 if (Found) 583 return nullptr; 584 585 // Treat single element arrays as the element. 586 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) { 587 if (AT->getSize().getZExtValue() != 1) 588 break; 589 FT = AT->getElementType(); 590 } 591 592 if (!isAggregateTypeForABI(FT)) { 593 Found = FT.getTypePtr(); 594 } else { 595 Found = isSingleElementStruct(FT, Context); 596 if (!Found) 597 return nullptr; 598 } 599 } 600 601 // We don't consider a struct a single-element struct if it has 602 // padding beyond the element type. 603 if (Found && Context.getTypeSize(Found) != Context.getTypeSize(T)) 604 return nullptr; 605 606 return Found; 607 } 608 609 namespace { 610 Address EmitVAArgInstr(CodeGenFunction &CGF, Address VAListAddr, QualType Ty, 611 const ABIArgInfo &AI) { 612 // This default implementation defers to the llvm backend's va_arg 613 // instruction. It can handle only passing arguments directly 614 // (typically only handled in the backend for primitive types), or 615 // aggregates passed indirectly by pointer (NOTE: if the "byval" 616 // flag has ABI impact in the callee, this implementation cannot 617 // work.) 618 619 // Only a few cases are covered here at the moment -- those needed 620 // by the default abi. 621 llvm::Value *Val; 622 623 if (AI.isIndirect()) { 624 assert(!AI.getPaddingType() && 625 "Unexpected PaddingType seen in arginfo in generic VAArg emitter!"); 626 assert( 627 !AI.getIndirectRealign() && 628 "Unexpected IndirectRealign seen in arginfo in generic VAArg emitter!"); 629 630 auto TyInfo = CGF.getContext().getTypeInfoInChars(Ty); 631 CharUnits TyAlignForABI = TyInfo.second; 632 633 llvm::Type *BaseTy = 634 llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty)); 635 llvm::Value *Addr = 636 CGF.Builder.CreateVAArg(VAListAddr.getPointer(), BaseTy); 637 return Address(Addr, TyAlignForABI); 638 } else { 639 assert((AI.isDirect() || AI.isExtend()) && 640 "Unexpected ArgInfo Kind in generic VAArg emitter!"); 641 642 assert(!AI.getInReg() && 643 "Unexpected InReg seen in arginfo in generic VAArg emitter!"); 644 assert(!AI.getPaddingType() && 645 "Unexpected PaddingType seen in arginfo in generic VAArg emitter!"); 646 assert(!AI.getDirectOffset() && 647 "Unexpected DirectOffset seen in arginfo in generic VAArg emitter!"); 648 assert(!AI.getCoerceToType() && 649 "Unexpected CoerceToType seen in arginfo in generic VAArg emitter!"); 650 651 Address Temp = CGF.CreateMemTemp(Ty, "varet"); 652 Val = CGF.Builder.CreateVAArg(VAListAddr.getPointer(), CGF.ConvertType(Ty)); 653 CGF.Builder.CreateStore(Val, Temp); 654 return Temp; 655 } 656 } 657 658 /// DefaultABIInfo - The default implementation for ABI specific 659 /// details. This implementation provides information which results in 660 /// self-consistent and sensible LLVM IR generation, but does not 661 /// conform to any particular ABI. 662 class DefaultABIInfo : public ABIInfo { 663 public: 664 DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {} 665 666 ABIArgInfo classifyReturnType(QualType RetTy) const; 667 ABIArgInfo classifyArgumentType(QualType RetTy) const; 668 669 void computeInfo(CGFunctionInfo &FI) const override { 670 if (!getCXXABI().classifyReturnType(FI)) 671 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 672 for (auto &I : FI.arguments()) 673 I.info = classifyArgumentType(I.type); 674 } 675 676 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 677 QualType Ty) const override { 678 return EmitVAArgInstr(CGF, VAListAddr, Ty, classifyArgumentType(Ty)); 679 } 680 }; 681 682 class DefaultTargetCodeGenInfo : public TargetCodeGenInfo { 683 public: 684 DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT) 685 : TargetCodeGenInfo(std::make_unique<DefaultABIInfo>(CGT)) {} 686 }; 687 688 ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const { 689 Ty = useFirstFieldIfTransparentUnion(Ty); 690 691 if (isAggregateTypeForABI(Ty)) { 692 // Records with non-trivial destructors/copy-constructors should not be 693 // passed by value. 694 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 695 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 696 697 return getNaturalAlignIndirect(Ty); 698 } 699 700 // Treat an enum type as its underlying type. 701 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 702 Ty = EnumTy->getDecl()->getIntegerType(); 703 704 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty) 705 : ABIArgInfo::getDirect()); 706 } 707 708 ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const { 709 if (RetTy->isVoidType()) 710 return ABIArgInfo::getIgnore(); 711 712 if (isAggregateTypeForABI(RetTy)) 713 return getNaturalAlignIndirect(RetTy); 714 715 // Treat an enum type as its underlying type. 716 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 717 RetTy = EnumTy->getDecl()->getIntegerType(); 718 719 return (RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy) 720 : ABIArgInfo::getDirect()); 721 } 722 723 //===----------------------------------------------------------------------===// 724 // WebAssembly ABI Implementation 725 // 726 // This is a very simple ABI that relies a lot on DefaultABIInfo. 727 //===----------------------------------------------------------------------===// 728 729 class WebAssemblyABIInfo final : public SwiftABIInfo { 730 public: 731 enum ABIKind { 732 MVP = 0, 733 ExperimentalMV = 1, 734 }; 735 736 private: 737 DefaultABIInfo defaultInfo; 738 ABIKind Kind; 739 740 public: 741 explicit WebAssemblyABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind) 742 : SwiftABIInfo(CGT), defaultInfo(CGT), Kind(Kind) {} 743 744 private: 745 ABIArgInfo classifyReturnType(QualType RetTy) const; 746 ABIArgInfo classifyArgumentType(QualType Ty) const; 747 748 // DefaultABIInfo's classifyReturnType and classifyArgumentType are 749 // non-virtual, but computeInfo and EmitVAArg are virtual, so we 750 // overload them. 751 void computeInfo(CGFunctionInfo &FI) const override { 752 if (!getCXXABI().classifyReturnType(FI)) 753 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 754 for (auto &Arg : FI.arguments()) 755 Arg.info = classifyArgumentType(Arg.type); 756 } 757 758 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 759 QualType Ty) const override; 760 761 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars, 762 bool asReturnValue) const override { 763 return occupiesMoreThan(CGT, scalars, /*total*/ 4); 764 } 765 766 bool isSwiftErrorInRegister() const override { 767 return false; 768 } 769 }; 770 771 class WebAssemblyTargetCodeGenInfo final : public TargetCodeGenInfo { 772 public: 773 explicit WebAssemblyTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, 774 WebAssemblyABIInfo::ABIKind K) 775 : TargetCodeGenInfo(std::make_unique<WebAssemblyABIInfo>(CGT, K)) {} 776 777 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 778 CodeGen::CodeGenModule &CGM) const override { 779 TargetCodeGenInfo::setTargetAttributes(D, GV, CGM); 780 if (const auto *FD = dyn_cast_or_null<FunctionDecl>(D)) { 781 if (const auto *Attr = FD->getAttr<WebAssemblyImportModuleAttr>()) { 782 llvm::Function *Fn = cast<llvm::Function>(GV); 783 llvm::AttrBuilder B; 784 B.addAttribute("wasm-import-module", Attr->getImportModule()); 785 Fn->addAttributes(llvm::AttributeList::FunctionIndex, B); 786 } 787 if (const auto *Attr = FD->getAttr<WebAssemblyImportNameAttr>()) { 788 llvm::Function *Fn = cast<llvm::Function>(GV); 789 llvm::AttrBuilder B; 790 B.addAttribute("wasm-import-name", Attr->getImportName()); 791 Fn->addAttributes(llvm::AttributeList::FunctionIndex, B); 792 } 793 if (const auto *Attr = FD->getAttr<WebAssemblyExportNameAttr>()) { 794 llvm::Function *Fn = cast<llvm::Function>(GV); 795 llvm::AttrBuilder B; 796 B.addAttribute("wasm-export-name", Attr->getExportName()); 797 Fn->addAttributes(llvm::AttributeList::FunctionIndex, B); 798 } 799 } 800 801 if (auto *FD = dyn_cast_or_null<FunctionDecl>(D)) { 802 llvm::Function *Fn = cast<llvm::Function>(GV); 803 if (!FD->doesThisDeclarationHaveABody() && !FD->hasPrototype()) 804 Fn->addFnAttr("no-prototype"); 805 } 806 } 807 }; 808 809 /// Classify argument of given type \p Ty. 810 ABIArgInfo WebAssemblyABIInfo::classifyArgumentType(QualType Ty) const { 811 Ty = useFirstFieldIfTransparentUnion(Ty); 812 813 if (isAggregateTypeForABI(Ty)) { 814 // Records with non-trivial destructors/copy-constructors should not be 815 // passed by value. 816 if (auto RAA = getRecordArgABI(Ty, getCXXABI())) 817 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 818 // Ignore empty structs/unions. 819 if (isEmptyRecord(getContext(), Ty, true)) 820 return ABIArgInfo::getIgnore(); 821 // Lower single-element structs to just pass a regular value. TODO: We 822 // could do reasonable-size multiple-element structs too, using getExpand(), 823 // though watch out for things like bitfields. 824 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext())) 825 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0))); 826 // For the experimental multivalue ABI, fully expand all other aggregates 827 if (Kind == ABIKind::ExperimentalMV) { 828 const RecordType *RT = Ty->getAs<RecordType>(); 829 assert(RT); 830 bool HasBitField = false; 831 for (auto *Field : RT->getDecl()->fields()) { 832 if (Field->isBitField()) { 833 HasBitField = true; 834 break; 835 } 836 } 837 if (!HasBitField) 838 return ABIArgInfo::getExpand(); 839 } 840 } 841 842 // Otherwise just do the default thing. 843 return defaultInfo.classifyArgumentType(Ty); 844 } 845 846 ABIArgInfo WebAssemblyABIInfo::classifyReturnType(QualType RetTy) const { 847 if (isAggregateTypeForABI(RetTy)) { 848 // Records with non-trivial destructors/copy-constructors should not be 849 // returned by value. 850 if (!getRecordArgABI(RetTy, getCXXABI())) { 851 // Ignore empty structs/unions. 852 if (isEmptyRecord(getContext(), RetTy, true)) 853 return ABIArgInfo::getIgnore(); 854 // Lower single-element structs to just return a regular value. TODO: We 855 // could do reasonable-size multiple-element structs too, using 856 // ABIArgInfo::getDirect(). 857 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext())) 858 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0))); 859 // For the experimental multivalue ABI, return all other aggregates 860 if (Kind == ABIKind::ExperimentalMV) 861 return ABIArgInfo::getDirect(); 862 } 863 } 864 865 // Otherwise just do the default thing. 866 return defaultInfo.classifyReturnType(RetTy); 867 } 868 869 Address WebAssemblyABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 870 QualType Ty) const { 871 bool IsIndirect = isAggregateTypeForABI(Ty) && 872 !isEmptyRecord(getContext(), Ty, true) && 873 !isSingleElementStruct(Ty, getContext()); 874 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, 875 getContext().getTypeInfoInChars(Ty), 876 CharUnits::fromQuantity(4), 877 /*AllowHigherAlign=*/true); 878 } 879 880 //===----------------------------------------------------------------------===// 881 // le32/PNaCl bitcode ABI Implementation 882 // 883 // This is a simplified version of the x86_32 ABI. Arguments and return values 884 // are always passed on the stack. 885 //===----------------------------------------------------------------------===// 886 887 class PNaClABIInfo : public ABIInfo { 888 public: 889 PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {} 890 891 ABIArgInfo classifyReturnType(QualType RetTy) const; 892 ABIArgInfo classifyArgumentType(QualType RetTy) const; 893 894 void computeInfo(CGFunctionInfo &FI) const override; 895 Address EmitVAArg(CodeGenFunction &CGF, 896 Address VAListAddr, QualType Ty) const override; 897 }; 898 899 class PNaClTargetCodeGenInfo : public TargetCodeGenInfo { 900 public: 901 PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT) 902 : TargetCodeGenInfo(std::make_unique<PNaClABIInfo>(CGT)) {} 903 }; 904 905 void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const { 906 if (!getCXXABI().classifyReturnType(FI)) 907 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 908 909 for (auto &I : FI.arguments()) 910 I.info = classifyArgumentType(I.type); 911 } 912 913 Address PNaClABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 914 QualType Ty) const { 915 // The PNaCL ABI is a bit odd, in that varargs don't use normal 916 // function classification. Structs get passed directly for varargs 917 // functions, through a rewriting transform in 918 // pnacl-llvm/lib/Transforms/NaCl/ExpandVarArgs.cpp, which allows 919 // this target to actually support a va_arg instructions with an 920 // aggregate type, unlike other targets. 921 return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect()); 922 } 923 924 /// Classify argument of given type \p Ty. 925 ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const { 926 if (isAggregateTypeForABI(Ty)) { 927 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 928 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 929 return getNaturalAlignIndirect(Ty); 930 } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) { 931 // Treat an enum type as its underlying type. 932 Ty = EnumTy->getDecl()->getIntegerType(); 933 } else if (Ty->isFloatingType()) { 934 // Floating-point types don't go inreg. 935 return ABIArgInfo::getDirect(); 936 } 937 938 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty) 939 : ABIArgInfo::getDirect()); 940 } 941 942 ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const { 943 if (RetTy->isVoidType()) 944 return ABIArgInfo::getIgnore(); 945 946 // In the PNaCl ABI we always return records/structures on the stack. 947 if (isAggregateTypeForABI(RetTy)) 948 return getNaturalAlignIndirect(RetTy); 949 950 // Treat an enum type as its underlying type. 951 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 952 RetTy = EnumTy->getDecl()->getIntegerType(); 953 954 return (RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy) 955 : ABIArgInfo::getDirect()); 956 } 957 958 /// IsX86_MMXType - Return true if this is an MMX type. 959 bool IsX86_MMXType(llvm::Type *IRType) { 960 // Return true if the type is an MMX type <2 x i32>, <4 x i16>, or <8 x i8>. 961 return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 && 962 cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() && 963 IRType->getScalarSizeInBits() != 64; 964 } 965 966 static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF, 967 StringRef Constraint, 968 llvm::Type* Ty) { 969 bool IsMMXCons = llvm::StringSwitch<bool>(Constraint) 970 .Cases("y", "&y", "^Ym", true) 971 .Default(false); 972 if (IsMMXCons && Ty->isVectorTy()) { 973 if (cast<llvm::VectorType>(Ty)->getPrimitiveSizeInBits().getFixedSize() != 974 64) { 975 // Invalid MMX constraint 976 return nullptr; 977 } 978 979 return llvm::Type::getX86_MMXTy(CGF.getLLVMContext()); 980 } 981 982 // No operation needed 983 return Ty; 984 } 985 986 /// Returns true if this type can be passed in SSE registers with the 987 /// X86_VectorCall calling convention. Shared between x86_32 and x86_64. 988 static bool isX86VectorTypeForVectorCall(ASTContext &Context, QualType Ty) { 989 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) { 990 if (BT->isFloatingPoint() && BT->getKind() != BuiltinType::Half) { 991 if (BT->getKind() == BuiltinType::LongDouble) { 992 if (&Context.getTargetInfo().getLongDoubleFormat() == 993 &llvm::APFloat::x87DoubleExtended()) 994 return false; 995 } 996 return true; 997 } 998 } else if (const VectorType *VT = Ty->getAs<VectorType>()) { 999 // vectorcall can pass XMM, YMM, and ZMM vectors. We don't pass SSE1 MMX 1000 // registers specially. 1001 unsigned VecSize = Context.getTypeSize(VT); 1002 if (VecSize == 128 || VecSize == 256 || VecSize == 512) 1003 return true; 1004 } 1005 return false; 1006 } 1007 1008 /// Returns true if this aggregate is small enough to be passed in SSE registers 1009 /// in the X86_VectorCall calling convention. Shared between x86_32 and x86_64. 1010 static bool isX86VectorCallAggregateSmallEnough(uint64_t NumMembers) { 1011 return NumMembers <= 4; 1012 } 1013 1014 /// Returns a Homogeneous Vector Aggregate ABIArgInfo, used in X86. 1015 static ABIArgInfo getDirectX86Hva(llvm::Type* T = nullptr) { 1016 auto AI = ABIArgInfo::getDirect(T); 1017 AI.setInReg(true); 1018 AI.setCanBeFlattened(false); 1019 return AI; 1020 } 1021 1022 //===----------------------------------------------------------------------===// 1023 // X86-32 ABI Implementation 1024 //===----------------------------------------------------------------------===// 1025 1026 /// Similar to llvm::CCState, but for Clang. 1027 struct CCState { 1028 CCState(CGFunctionInfo &FI) 1029 : IsPreassigned(FI.arg_size()), CC(FI.getCallingConvention()) {} 1030 1031 llvm::SmallBitVector IsPreassigned; 1032 unsigned CC = CallingConv::CC_C; 1033 unsigned FreeRegs = 0; 1034 unsigned FreeSSERegs = 0; 1035 }; 1036 1037 enum { 1038 // Vectorcall only allows the first 6 parameters to be passed in registers. 1039 VectorcallMaxParamNumAsReg = 6 1040 }; 1041 1042 /// X86_32ABIInfo - The X86-32 ABI information. 1043 class X86_32ABIInfo : public SwiftABIInfo { 1044 enum Class { 1045 Integer, 1046 Float 1047 }; 1048 1049 static const unsigned MinABIStackAlignInBytes = 4; 1050 1051 bool IsDarwinVectorABI; 1052 bool IsRetSmallStructInRegABI; 1053 bool IsWin32StructABI; 1054 bool IsSoftFloatABI; 1055 bool IsMCUABI; 1056 unsigned DefaultNumRegisterParameters; 1057 1058 static bool isRegisterSize(unsigned Size) { 1059 return (Size == 8 || Size == 16 || Size == 32 || Size == 64); 1060 } 1061 1062 bool isHomogeneousAggregateBaseType(QualType Ty) const override { 1063 // FIXME: Assumes vectorcall is in use. 1064 return isX86VectorTypeForVectorCall(getContext(), Ty); 1065 } 1066 1067 bool isHomogeneousAggregateSmallEnough(const Type *Ty, 1068 uint64_t NumMembers) const override { 1069 // FIXME: Assumes vectorcall is in use. 1070 return isX86VectorCallAggregateSmallEnough(NumMembers); 1071 } 1072 1073 bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context) const; 1074 1075 /// getIndirectResult - Give a source type \arg Ty, return a suitable result 1076 /// such that the argument will be passed in memory. 1077 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const; 1078 1079 ABIArgInfo getIndirectReturnResult(QualType Ty, CCState &State) const; 1080 1081 /// Return the alignment to use for the given type on the stack. 1082 unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const; 1083 1084 Class classify(QualType Ty) const; 1085 ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const; 1086 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const; 1087 1088 /// Updates the number of available free registers, returns 1089 /// true if any registers were allocated. 1090 bool updateFreeRegs(QualType Ty, CCState &State) const; 1091 1092 bool shouldAggregateUseDirect(QualType Ty, CCState &State, bool &InReg, 1093 bool &NeedsPadding) const; 1094 bool shouldPrimitiveUseInReg(QualType Ty, CCState &State) const; 1095 1096 bool canExpandIndirectArgument(QualType Ty) const; 1097 1098 /// Rewrite the function info so that all memory arguments use 1099 /// inalloca. 1100 void rewriteWithInAlloca(CGFunctionInfo &FI) const; 1101 1102 void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields, 1103 CharUnits &StackOffset, ABIArgInfo &Info, 1104 QualType Type) const; 1105 void runVectorCallFirstPass(CGFunctionInfo &FI, CCState &State) const; 1106 1107 public: 1108 1109 void computeInfo(CGFunctionInfo &FI) const override; 1110 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 1111 QualType Ty) const override; 1112 1113 X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI, 1114 bool RetSmallStructInRegABI, bool Win32StructABI, 1115 unsigned NumRegisterParameters, bool SoftFloatABI) 1116 : SwiftABIInfo(CGT), IsDarwinVectorABI(DarwinVectorABI), 1117 IsRetSmallStructInRegABI(RetSmallStructInRegABI), 1118 IsWin32StructABI(Win32StructABI), 1119 IsSoftFloatABI(SoftFloatABI), 1120 IsMCUABI(CGT.getTarget().getTriple().isOSIAMCU()), 1121 DefaultNumRegisterParameters(NumRegisterParameters) {} 1122 1123 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars, 1124 bool asReturnValue) const override { 1125 // LLVM's x86-32 lowering currently only assigns up to three 1126 // integer registers and three fp registers. Oddly, it'll use up to 1127 // four vector registers for vectors, but those can overlap with the 1128 // scalar registers. 1129 return occupiesMoreThan(CGT, scalars, /*total*/ 3); 1130 } 1131 1132 bool isSwiftErrorInRegister() const override { 1133 // x86-32 lowering does not support passing swifterror in a register. 1134 return false; 1135 } 1136 }; 1137 1138 class X86_32TargetCodeGenInfo : public TargetCodeGenInfo { 1139 public: 1140 X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI, 1141 bool RetSmallStructInRegABI, bool Win32StructABI, 1142 unsigned NumRegisterParameters, bool SoftFloatABI) 1143 : TargetCodeGenInfo(std::make_unique<X86_32ABIInfo>( 1144 CGT, DarwinVectorABI, RetSmallStructInRegABI, Win32StructABI, 1145 NumRegisterParameters, SoftFloatABI)) {} 1146 1147 static bool isStructReturnInRegABI( 1148 const llvm::Triple &Triple, const CodeGenOptions &Opts); 1149 1150 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 1151 CodeGen::CodeGenModule &CGM) const override; 1152 1153 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override { 1154 // Darwin uses different dwarf register numbers for EH. 1155 if (CGM.getTarget().getTriple().isOSDarwin()) return 5; 1156 return 4; 1157 } 1158 1159 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 1160 llvm::Value *Address) const override; 1161 1162 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF, 1163 StringRef Constraint, 1164 llvm::Type* Ty) const override { 1165 return X86AdjustInlineAsmType(CGF, Constraint, Ty); 1166 } 1167 1168 void addReturnRegisterOutputs(CodeGenFunction &CGF, LValue ReturnValue, 1169 std::string &Constraints, 1170 std::vector<llvm::Type *> &ResultRegTypes, 1171 std::vector<llvm::Type *> &ResultTruncRegTypes, 1172 std::vector<LValue> &ResultRegDests, 1173 std::string &AsmString, 1174 unsigned NumOutputs) const override; 1175 1176 llvm::Constant * 1177 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override { 1178 unsigned Sig = (0xeb << 0) | // jmp rel8 1179 (0x06 << 8) | // .+0x08 1180 ('v' << 16) | 1181 ('2' << 24); 1182 return llvm::ConstantInt::get(CGM.Int32Ty, Sig); 1183 } 1184 1185 StringRef getARCRetainAutoreleasedReturnValueMarker() const override { 1186 return "movl\t%ebp, %ebp" 1187 "\t\t// marker for objc_retainAutoreleaseReturnValue"; 1188 } 1189 }; 1190 1191 } 1192 1193 /// Rewrite input constraint references after adding some output constraints. 1194 /// In the case where there is one output and one input and we add one output, 1195 /// we need to replace all operand references greater than or equal to 1: 1196 /// mov $0, $1 1197 /// mov eax, $1 1198 /// The result will be: 1199 /// mov $0, $2 1200 /// mov eax, $2 1201 static void rewriteInputConstraintReferences(unsigned FirstIn, 1202 unsigned NumNewOuts, 1203 std::string &AsmString) { 1204 std::string Buf; 1205 llvm::raw_string_ostream OS(Buf); 1206 size_t Pos = 0; 1207 while (Pos < AsmString.size()) { 1208 size_t DollarStart = AsmString.find('$', Pos); 1209 if (DollarStart == std::string::npos) 1210 DollarStart = AsmString.size(); 1211 size_t DollarEnd = AsmString.find_first_not_of('$', DollarStart); 1212 if (DollarEnd == std::string::npos) 1213 DollarEnd = AsmString.size(); 1214 OS << StringRef(&AsmString[Pos], DollarEnd - Pos); 1215 Pos = DollarEnd; 1216 size_t NumDollars = DollarEnd - DollarStart; 1217 if (NumDollars % 2 != 0 && Pos < AsmString.size()) { 1218 // We have an operand reference. 1219 size_t DigitStart = Pos; 1220 if (AsmString[DigitStart] == '{') { 1221 OS << '{'; 1222 ++DigitStart; 1223 } 1224 size_t DigitEnd = AsmString.find_first_not_of("0123456789", DigitStart); 1225 if (DigitEnd == std::string::npos) 1226 DigitEnd = AsmString.size(); 1227 StringRef OperandStr(&AsmString[DigitStart], DigitEnd - DigitStart); 1228 unsigned OperandIndex; 1229 if (!OperandStr.getAsInteger(10, OperandIndex)) { 1230 if (OperandIndex >= FirstIn) 1231 OperandIndex += NumNewOuts; 1232 OS << OperandIndex; 1233 } else { 1234 OS << OperandStr; 1235 } 1236 Pos = DigitEnd; 1237 } 1238 } 1239 AsmString = std::move(OS.str()); 1240 } 1241 1242 /// Add output constraints for EAX:EDX because they are return registers. 1243 void X86_32TargetCodeGenInfo::addReturnRegisterOutputs( 1244 CodeGenFunction &CGF, LValue ReturnSlot, std::string &Constraints, 1245 std::vector<llvm::Type *> &ResultRegTypes, 1246 std::vector<llvm::Type *> &ResultTruncRegTypes, 1247 std::vector<LValue> &ResultRegDests, std::string &AsmString, 1248 unsigned NumOutputs) const { 1249 uint64_t RetWidth = CGF.getContext().getTypeSize(ReturnSlot.getType()); 1250 1251 // Use the EAX constraint if the width is 32 or smaller and EAX:EDX if it is 1252 // larger. 1253 if (!Constraints.empty()) 1254 Constraints += ','; 1255 if (RetWidth <= 32) { 1256 Constraints += "={eax}"; 1257 ResultRegTypes.push_back(CGF.Int32Ty); 1258 } else { 1259 // Use the 'A' constraint for EAX:EDX. 1260 Constraints += "=A"; 1261 ResultRegTypes.push_back(CGF.Int64Ty); 1262 } 1263 1264 // Truncate EAX or EAX:EDX to an integer of the appropriate size. 1265 llvm::Type *CoerceTy = llvm::IntegerType::get(CGF.getLLVMContext(), RetWidth); 1266 ResultTruncRegTypes.push_back(CoerceTy); 1267 1268 // Coerce the integer by bitcasting the return slot pointer. 1269 ReturnSlot.setAddress(CGF.Builder.CreateBitCast(ReturnSlot.getAddress(CGF), 1270 CoerceTy->getPointerTo())); 1271 ResultRegDests.push_back(ReturnSlot); 1272 1273 rewriteInputConstraintReferences(NumOutputs, 1, AsmString); 1274 } 1275 1276 /// shouldReturnTypeInRegister - Determine if the given type should be 1277 /// returned in a register (for the Darwin and MCU ABI). 1278 bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty, 1279 ASTContext &Context) const { 1280 uint64_t Size = Context.getTypeSize(Ty); 1281 1282 // For i386, type must be register sized. 1283 // For the MCU ABI, it only needs to be <= 8-byte 1284 if ((IsMCUABI && Size > 64) || (!IsMCUABI && !isRegisterSize(Size))) 1285 return false; 1286 1287 if (Ty->isVectorType()) { 1288 // 64- and 128- bit vectors inside structures are not returned in 1289 // registers. 1290 if (Size == 64 || Size == 128) 1291 return false; 1292 1293 return true; 1294 } 1295 1296 // If this is a builtin, pointer, enum, complex type, member pointer, or 1297 // member function pointer it is ok. 1298 if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() || 1299 Ty->isAnyComplexType() || Ty->isEnumeralType() || 1300 Ty->isBlockPointerType() || Ty->isMemberPointerType()) 1301 return true; 1302 1303 // Arrays are treated like records. 1304 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) 1305 return shouldReturnTypeInRegister(AT->getElementType(), Context); 1306 1307 // Otherwise, it must be a record type. 1308 const RecordType *RT = Ty->getAs<RecordType>(); 1309 if (!RT) return false; 1310 1311 // FIXME: Traverse bases here too. 1312 1313 // Structure types are passed in register if all fields would be 1314 // passed in a register. 1315 for (const auto *FD : RT->getDecl()->fields()) { 1316 // Empty fields are ignored. 1317 if (isEmptyField(Context, FD, true)) 1318 continue; 1319 1320 // Check fields recursively. 1321 if (!shouldReturnTypeInRegister(FD->getType(), Context)) 1322 return false; 1323 } 1324 return true; 1325 } 1326 1327 static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) { 1328 // Treat complex types as the element type. 1329 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) 1330 Ty = CTy->getElementType(); 1331 1332 // Check for a type which we know has a simple scalar argument-passing 1333 // convention without any padding. (We're specifically looking for 32 1334 // and 64-bit integer and integer-equivalents, float, and double.) 1335 if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() && 1336 !Ty->isEnumeralType() && !Ty->isBlockPointerType()) 1337 return false; 1338 1339 uint64_t Size = Context.getTypeSize(Ty); 1340 return Size == 32 || Size == 64; 1341 } 1342 1343 static bool addFieldSizes(ASTContext &Context, const RecordDecl *RD, 1344 uint64_t &Size) { 1345 for (const auto *FD : RD->fields()) { 1346 // Scalar arguments on the stack get 4 byte alignment on x86. If the 1347 // argument is smaller than 32-bits, expanding the struct will create 1348 // alignment padding. 1349 if (!is32Or64BitBasicType(FD->getType(), Context)) 1350 return false; 1351 1352 // FIXME: Reject bit-fields wholesale; there are two problems, we don't know 1353 // how to expand them yet, and the predicate for telling if a bitfield still 1354 // counts as "basic" is more complicated than what we were doing previously. 1355 if (FD->isBitField()) 1356 return false; 1357 1358 Size += Context.getTypeSize(FD->getType()); 1359 } 1360 return true; 1361 } 1362 1363 static bool addBaseAndFieldSizes(ASTContext &Context, const CXXRecordDecl *RD, 1364 uint64_t &Size) { 1365 // Don't do this if there are any non-empty bases. 1366 for (const CXXBaseSpecifier &Base : RD->bases()) { 1367 if (!addBaseAndFieldSizes(Context, Base.getType()->getAsCXXRecordDecl(), 1368 Size)) 1369 return false; 1370 } 1371 if (!addFieldSizes(Context, RD, Size)) 1372 return false; 1373 return true; 1374 } 1375 1376 /// Test whether an argument type which is to be passed indirectly (on the 1377 /// stack) would have the equivalent layout if it was expanded into separate 1378 /// arguments. If so, we prefer to do the latter to avoid inhibiting 1379 /// optimizations. 1380 bool X86_32ABIInfo::canExpandIndirectArgument(QualType Ty) const { 1381 // We can only expand structure types. 1382 const RecordType *RT = Ty->getAs<RecordType>(); 1383 if (!RT) 1384 return false; 1385 const RecordDecl *RD = RT->getDecl(); 1386 uint64_t Size = 0; 1387 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 1388 if (!IsWin32StructABI) { 1389 // On non-Windows, we have to conservatively match our old bitcode 1390 // prototypes in order to be ABI-compatible at the bitcode level. 1391 if (!CXXRD->isCLike()) 1392 return false; 1393 } else { 1394 // Don't do this for dynamic classes. 1395 if (CXXRD->isDynamicClass()) 1396 return false; 1397 } 1398 if (!addBaseAndFieldSizes(getContext(), CXXRD, Size)) 1399 return false; 1400 } else { 1401 if (!addFieldSizes(getContext(), RD, Size)) 1402 return false; 1403 } 1404 1405 // We can do this if there was no alignment padding. 1406 return Size == getContext().getTypeSize(Ty); 1407 } 1408 1409 ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(QualType RetTy, CCState &State) const { 1410 // If the return value is indirect, then the hidden argument is consuming one 1411 // integer register. 1412 if (State.FreeRegs) { 1413 --State.FreeRegs; 1414 if (!IsMCUABI) 1415 return getNaturalAlignIndirectInReg(RetTy); 1416 } 1417 return getNaturalAlignIndirect(RetTy, /*ByVal=*/false); 1418 } 1419 1420 ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy, 1421 CCState &State) const { 1422 if (RetTy->isVoidType()) 1423 return ABIArgInfo::getIgnore(); 1424 1425 const Type *Base = nullptr; 1426 uint64_t NumElts = 0; 1427 if ((State.CC == llvm::CallingConv::X86_VectorCall || 1428 State.CC == llvm::CallingConv::X86_RegCall) && 1429 isHomogeneousAggregate(RetTy, Base, NumElts)) { 1430 // The LLVM struct type for such an aggregate should lower properly. 1431 return ABIArgInfo::getDirect(); 1432 } 1433 1434 if (const VectorType *VT = RetTy->getAs<VectorType>()) { 1435 // On Darwin, some vectors are returned in registers. 1436 if (IsDarwinVectorABI) { 1437 uint64_t Size = getContext().getTypeSize(RetTy); 1438 1439 // 128-bit vectors are a special case; they are returned in 1440 // registers and we need to make sure to pick a type the LLVM 1441 // backend will like. 1442 if (Size == 128) 1443 return ABIArgInfo::getDirect(llvm::VectorType::get( 1444 llvm::Type::getInt64Ty(getVMContext()), 2)); 1445 1446 // Always return in register if it fits in a general purpose 1447 // register, or if it is 64 bits and has a single element. 1448 if ((Size == 8 || Size == 16 || Size == 32) || 1449 (Size == 64 && VT->getNumElements() == 1)) 1450 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 1451 Size)); 1452 1453 return getIndirectReturnResult(RetTy, State); 1454 } 1455 1456 return ABIArgInfo::getDirect(); 1457 } 1458 1459 if (isAggregateTypeForABI(RetTy)) { 1460 if (const RecordType *RT = RetTy->getAs<RecordType>()) { 1461 // Structures with flexible arrays are always indirect. 1462 if (RT->getDecl()->hasFlexibleArrayMember()) 1463 return getIndirectReturnResult(RetTy, State); 1464 } 1465 1466 // If specified, structs and unions are always indirect. 1467 if (!IsRetSmallStructInRegABI && !RetTy->isAnyComplexType()) 1468 return getIndirectReturnResult(RetTy, State); 1469 1470 // Ignore empty structs/unions. 1471 if (isEmptyRecord(getContext(), RetTy, true)) 1472 return ABIArgInfo::getIgnore(); 1473 1474 // Small structures which are register sized are generally returned 1475 // in a register. 1476 if (shouldReturnTypeInRegister(RetTy, getContext())) { 1477 uint64_t Size = getContext().getTypeSize(RetTy); 1478 1479 // As a special-case, if the struct is a "single-element" struct, and 1480 // the field is of type "float" or "double", return it in a 1481 // floating-point register. (MSVC does not apply this special case.) 1482 // We apply a similar transformation for pointer types to improve the 1483 // quality of the generated IR. 1484 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext())) 1485 if ((!IsWin32StructABI && SeltTy->isRealFloatingType()) 1486 || SeltTy->hasPointerRepresentation()) 1487 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0))); 1488 1489 // FIXME: We should be able to narrow this integer in cases with dead 1490 // padding. 1491 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size)); 1492 } 1493 1494 return getIndirectReturnResult(RetTy, State); 1495 } 1496 1497 // Treat an enum type as its underlying type. 1498 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 1499 RetTy = EnumTy->getDecl()->getIntegerType(); 1500 1501 return (RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy) 1502 : ABIArgInfo::getDirect()); 1503 } 1504 1505 static bool isSSEVectorType(ASTContext &Context, QualType Ty) { 1506 return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128; 1507 } 1508 1509 static bool isRecordWithSSEVectorType(ASTContext &Context, QualType Ty) { 1510 const RecordType *RT = Ty->getAs<RecordType>(); 1511 if (!RT) 1512 return 0; 1513 const RecordDecl *RD = RT->getDecl(); 1514 1515 // If this is a C++ record, check the bases first. 1516 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 1517 for (const auto &I : CXXRD->bases()) 1518 if (!isRecordWithSSEVectorType(Context, I.getType())) 1519 return false; 1520 1521 for (const auto *i : RD->fields()) { 1522 QualType FT = i->getType(); 1523 1524 if (isSSEVectorType(Context, FT)) 1525 return true; 1526 1527 if (isRecordWithSSEVectorType(Context, FT)) 1528 return true; 1529 } 1530 1531 return false; 1532 } 1533 1534 unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty, 1535 unsigned Align) const { 1536 // Otherwise, if the alignment is less than or equal to the minimum ABI 1537 // alignment, just use the default; the backend will handle this. 1538 if (Align <= MinABIStackAlignInBytes) 1539 return 0; // Use default alignment. 1540 1541 // On non-Darwin, the stack type alignment is always 4. 1542 if (!IsDarwinVectorABI) { 1543 // Set explicit alignment, since we may need to realign the top. 1544 return MinABIStackAlignInBytes; 1545 } 1546 1547 // Otherwise, if the type contains an SSE vector type, the alignment is 16. 1548 if (Align >= 16 && (isSSEVectorType(getContext(), Ty) || 1549 isRecordWithSSEVectorType(getContext(), Ty))) 1550 return 16; 1551 1552 return MinABIStackAlignInBytes; 1553 } 1554 1555 ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal, 1556 CCState &State) const { 1557 if (!ByVal) { 1558 if (State.FreeRegs) { 1559 --State.FreeRegs; // Non-byval indirects just use one pointer. 1560 if (!IsMCUABI) 1561 return getNaturalAlignIndirectInReg(Ty); 1562 } 1563 return getNaturalAlignIndirect(Ty, false); 1564 } 1565 1566 // Compute the byval alignment. 1567 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8; 1568 unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign); 1569 if (StackAlign == 0) 1570 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true); 1571 1572 // If the stack alignment is less than the type alignment, realign the 1573 // argument. 1574 bool Realign = TypeAlign > StackAlign; 1575 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(StackAlign), 1576 /*ByVal=*/true, Realign); 1577 } 1578 1579 X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const { 1580 const Type *T = isSingleElementStruct(Ty, getContext()); 1581 if (!T) 1582 T = Ty.getTypePtr(); 1583 1584 if (const BuiltinType *BT = T->getAs<BuiltinType>()) { 1585 BuiltinType::Kind K = BT->getKind(); 1586 if (K == BuiltinType::Float || K == BuiltinType::Double) 1587 return Float; 1588 } 1589 return Integer; 1590 } 1591 1592 bool X86_32ABIInfo::updateFreeRegs(QualType Ty, CCState &State) const { 1593 if (!IsSoftFloatABI) { 1594 Class C = classify(Ty); 1595 if (C == Float) 1596 return false; 1597 } 1598 1599 unsigned Size = getContext().getTypeSize(Ty); 1600 unsigned SizeInRegs = (Size + 31) / 32; 1601 1602 if (SizeInRegs == 0) 1603 return false; 1604 1605 if (!IsMCUABI) { 1606 if (SizeInRegs > State.FreeRegs) { 1607 State.FreeRegs = 0; 1608 return false; 1609 } 1610 } else { 1611 // The MCU psABI allows passing parameters in-reg even if there are 1612 // earlier parameters that are passed on the stack. Also, 1613 // it does not allow passing >8-byte structs in-register, 1614 // even if there are 3 free registers available. 1615 if (SizeInRegs > State.FreeRegs || SizeInRegs > 2) 1616 return false; 1617 } 1618 1619 State.FreeRegs -= SizeInRegs; 1620 return true; 1621 } 1622 1623 bool X86_32ABIInfo::shouldAggregateUseDirect(QualType Ty, CCState &State, 1624 bool &InReg, 1625 bool &NeedsPadding) const { 1626 // On Windows, aggregates other than HFAs are never passed in registers, and 1627 // they do not consume register slots. Homogenous floating-point aggregates 1628 // (HFAs) have already been dealt with at this point. 1629 if (IsWin32StructABI && isAggregateTypeForABI(Ty)) 1630 return false; 1631 1632 NeedsPadding = false; 1633 InReg = !IsMCUABI; 1634 1635 if (!updateFreeRegs(Ty, State)) 1636 return false; 1637 1638 if (IsMCUABI) 1639 return true; 1640 1641 if (State.CC == llvm::CallingConv::X86_FastCall || 1642 State.CC == llvm::CallingConv::X86_VectorCall || 1643 State.CC == llvm::CallingConv::X86_RegCall) { 1644 if (getContext().getTypeSize(Ty) <= 32 && State.FreeRegs) 1645 NeedsPadding = true; 1646 1647 return false; 1648 } 1649 1650 return true; 1651 } 1652 1653 bool X86_32ABIInfo::shouldPrimitiveUseInReg(QualType Ty, CCState &State) const { 1654 if (!updateFreeRegs(Ty, State)) 1655 return false; 1656 1657 if (IsMCUABI) 1658 return false; 1659 1660 if (State.CC == llvm::CallingConv::X86_FastCall || 1661 State.CC == llvm::CallingConv::X86_VectorCall || 1662 State.CC == llvm::CallingConv::X86_RegCall) { 1663 if (getContext().getTypeSize(Ty) > 32) 1664 return false; 1665 1666 return (Ty->isIntegralOrEnumerationType() || Ty->isPointerType() || 1667 Ty->isReferenceType()); 1668 } 1669 1670 return true; 1671 } 1672 1673 void X86_32ABIInfo::runVectorCallFirstPass(CGFunctionInfo &FI, CCState &State) const { 1674 // Vectorcall x86 works subtly different than in x64, so the format is 1675 // a bit different than the x64 version. First, all vector types (not HVAs) 1676 // are assigned, with the first 6 ending up in the [XYZ]MM0-5 registers. 1677 // This differs from the x64 implementation, where the first 6 by INDEX get 1678 // registers. 1679 // In the second pass over the arguments, HVAs are passed in the remaining 1680 // vector registers if possible, or indirectly by address. The address will be 1681 // passed in ECX/EDX if available. Any other arguments are passed according to 1682 // the usual fastcall rules. 1683 MutableArrayRef<CGFunctionInfoArgInfo> Args = FI.arguments(); 1684 for (int I = 0, E = Args.size(); I < E; ++I) { 1685 const Type *Base = nullptr; 1686 uint64_t NumElts = 0; 1687 const QualType &Ty = Args[I].type; 1688 if ((Ty->isVectorType() || Ty->isBuiltinType()) && 1689 isHomogeneousAggregate(Ty, Base, NumElts)) { 1690 if (State.FreeSSERegs >= NumElts) { 1691 State.FreeSSERegs -= NumElts; 1692 Args[I].info = ABIArgInfo::getDirectInReg(); 1693 State.IsPreassigned.set(I); 1694 } 1695 } 1696 } 1697 } 1698 1699 ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty, 1700 CCState &State) const { 1701 // FIXME: Set alignment on indirect arguments. 1702 bool IsFastCall = State.CC == llvm::CallingConv::X86_FastCall; 1703 bool IsRegCall = State.CC == llvm::CallingConv::X86_RegCall; 1704 bool IsVectorCall = State.CC == llvm::CallingConv::X86_VectorCall; 1705 1706 Ty = useFirstFieldIfTransparentUnion(Ty); 1707 TypeInfo TI = getContext().getTypeInfo(Ty); 1708 1709 // Check with the C++ ABI first. 1710 const RecordType *RT = Ty->getAs<RecordType>(); 1711 if (RT) { 1712 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()); 1713 if (RAA == CGCXXABI::RAA_Indirect) { 1714 return getIndirectResult(Ty, false, State); 1715 } else if (RAA == CGCXXABI::RAA_DirectInMemory) { 1716 // The field index doesn't matter, we'll fix it up later. 1717 return ABIArgInfo::getInAlloca(/*FieldIndex=*/0); 1718 } 1719 } 1720 1721 // Regcall uses the concept of a homogenous vector aggregate, similar 1722 // to other targets. 1723 const Type *Base = nullptr; 1724 uint64_t NumElts = 0; 1725 if ((IsRegCall || IsVectorCall) && 1726 isHomogeneousAggregate(Ty, Base, NumElts)) { 1727 if (State.FreeSSERegs >= NumElts) { 1728 State.FreeSSERegs -= NumElts; 1729 1730 // Vectorcall passes HVAs directly and does not flatten them, but regcall 1731 // does. 1732 if (IsVectorCall) 1733 return getDirectX86Hva(); 1734 1735 if (Ty->isBuiltinType() || Ty->isVectorType()) 1736 return ABIArgInfo::getDirect(); 1737 return ABIArgInfo::getExpand(); 1738 } 1739 return getIndirectResult(Ty, /*ByVal=*/false, State); 1740 } 1741 1742 if (isAggregateTypeForABI(Ty)) { 1743 // Structures with flexible arrays are always indirect. 1744 // FIXME: This should not be byval! 1745 if (RT && RT->getDecl()->hasFlexibleArrayMember()) 1746 return getIndirectResult(Ty, true, State); 1747 1748 // Ignore empty structs/unions on non-Windows. 1749 if (!IsWin32StructABI && isEmptyRecord(getContext(), Ty, true)) 1750 return ABIArgInfo::getIgnore(); 1751 1752 llvm::LLVMContext &LLVMContext = getVMContext(); 1753 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext); 1754 bool NeedsPadding = false; 1755 bool InReg; 1756 if (shouldAggregateUseDirect(Ty, State, InReg, NeedsPadding)) { 1757 unsigned SizeInRegs = (TI.Width + 31) / 32; 1758 SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32); 1759 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements); 1760 if (InReg) 1761 return ABIArgInfo::getDirectInReg(Result); 1762 else 1763 return ABIArgInfo::getDirect(Result); 1764 } 1765 llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : nullptr; 1766 1767 // Pass over-aligned aggregates on Windows indirectly. This behavior was 1768 // added in MSVC 2015. 1769 if (IsWin32StructABI && TI.AlignIsRequired && TI.Align > 32) 1770 return getIndirectResult(Ty, /*ByVal=*/false, State); 1771 1772 // Expand small (<= 128-bit) record types when we know that the stack layout 1773 // of those arguments will match the struct. This is important because the 1774 // LLVM backend isn't smart enough to remove byval, which inhibits many 1775 // optimizations. 1776 // Don't do this for the MCU if there are still free integer registers 1777 // (see X86_64 ABI for full explanation). 1778 if (TI.Width <= 4 * 32 && (!IsMCUABI || State.FreeRegs == 0) && 1779 canExpandIndirectArgument(Ty)) 1780 return ABIArgInfo::getExpandWithPadding( 1781 IsFastCall || IsVectorCall || IsRegCall, PaddingType); 1782 1783 return getIndirectResult(Ty, true, State); 1784 } 1785 1786 if (const VectorType *VT = Ty->getAs<VectorType>()) { 1787 // On Windows, vectors are passed directly if registers are available, or 1788 // indirectly if not. This avoids the need to align argument memory. Pass 1789 // user-defined vector types larger than 512 bits indirectly for simplicity. 1790 if (IsWin32StructABI) { 1791 if (TI.Width <= 512 && State.FreeSSERegs > 0) { 1792 --State.FreeSSERegs; 1793 return ABIArgInfo::getDirectInReg(); 1794 } 1795 return getIndirectResult(Ty, /*ByVal=*/false, State); 1796 } 1797 1798 // On Darwin, some vectors are passed in memory, we handle this by passing 1799 // it as an i8/i16/i32/i64. 1800 if (IsDarwinVectorABI) { 1801 if ((TI.Width == 8 || TI.Width == 16 || TI.Width == 32) || 1802 (TI.Width == 64 && VT->getNumElements() == 1)) 1803 return ABIArgInfo::getDirect( 1804 llvm::IntegerType::get(getVMContext(), TI.Width)); 1805 } 1806 1807 if (IsX86_MMXType(CGT.ConvertType(Ty))) 1808 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64)); 1809 1810 return ABIArgInfo::getDirect(); 1811 } 1812 1813 1814 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 1815 Ty = EnumTy->getDecl()->getIntegerType(); 1816 1817 bool InReg = shouldPrimitiveUseInReg(Ty, State); 1818 1819 if (Ty->isPromotableIntegerType()) { 1820 if (InReg) 1821 return ABIArgInfo::getExtendInReg(Ty); 1822 return ABIArgInfo::getExtend(Ty); 1823 } 1824 1825 if (const auto * EIT = Ty->getAs<ExtIntType>()) { 1826 if (EIT->getNumBits() <= 64) { 1827 if (InReg) 1828 return ABIArgInfo::getDirectInReg(); 1829 return ABIArgInfo::getDirect(); 1830 } 1831 return getIndirectResult(Ty, /*ByVal=*/false, State); 1832 } 1833 1834 if (InReg) 1835 return ABIArgInfo::getDirectInReg(); 1836 return ABIArgInfo::getDirect(); 1837 } 1838 1839 void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const { 1840 CCState State(FI); 1841 if (IsMCUABI) 1842 State.FreeRegs = 3; 1843 else if (State.CC == llvm::CallingConv::X86_FastCall) { 1844 State.FreeRegs = 2; 1845 State.FreeSSERegs = 3; 1846 } else if (State.CC == llvm::CallingConv::X86_VectorCall) { 1847 State.FreeRegs = 2; 1848 State.FreeSSERegs = 6; 1849 } else if (FI.getHasRegParm()) 1850 State.FreeRegs = FI.getRegParm(); 1851 else if (State.CC == llvm::CallingConv::X86_RegCall) { 1852 State.FreeRegs = 5; 1853 State.FreeSSERegs = 8; 1854 } else if (IsWin32StructABI) { 1855 // Since MSVC 2015, the first three SSE vectors have been passed in 1856 // registers. The rest are passed indirectly. 1857 State.FreeRegs = DefaultNumRegisterParameters; 1858 State.FreeSSERegs = 3; 1859 } else 1860 State.FreeRegs = DefaultNumRegisterParameters; 1861 1862 if (!::classifyReturnType(getCXXABI(), FI, *this)) { 1863 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), State); 1864 } else if (FI.getReturnInfo().isIndirect()) { 1865 // The C++ ABI is not aware of register usage, so we have to check if the 1866 // return value was sret and put it in a register ourselves if appropriate. 1867 if (State.FreeRegs) { 1868 --State.FreeRegs; // The sret parameter consumes a register. 1869 if (!IsMCUABI) 1870 FI.getReturnInfo().setInReg(true); 1871 } 1872 } 1873 1874 // The chain argument effectively gives us another free register. 1875 if (FI.isChainCall()) 1876 ++State.FreeRegs; 1877 1878 // For vectorcall, do a first pass over the arguments, assigning FP and vector 1879 // arguments to XMM registers as available. 1880 if (State.CC == llvm::CallingConv::X86_VectorCall) 1881 runVectorCallFirstPass(FI, State); 1882 1883 bool UsedInAlloca = false; 1884 MutableArrayRef<CGFunctionInfoArgInfo> Args = FI.arguments(); 1885 for (int I = 0, E = Args.size(); I < E; ++I) { 1886 // Skip arguments that have already been assigned. 1887 if (State.IsPreassigned.test(I)) 1888 continue; 1889 1890 Args[I].info = classifyArgumentType(Args[I].type, State); 1891 UsedInAlloca |= (Args[I].info.getKind() == ABIArgInfo::InAlloca); 1892 } 1893 1894 // If we needed to use inalloca for any argument, do a second pass and rewrite 1895 // all the memory arguments to use inalloca. 1896 if (UsedInAlloca) 1897 rewriteWithInAlloca(FI); 1898 } 1899 1900 void 1901 X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields, 1902 CharUnits &StackOffset, ABIArgInfo &Info, 1903 QualType Type) const { 1904 // Arguments are always 4-byte-aligned. 1905 CharUnits WordSize = CharUnits::fromQuantity(4); 1906 assert(StackOffset.isMultipleOf(WordSize) && "unaligned inalloca struct"); 1907 1908 // sret pointers and indirect things will require an extra pointer 1909 // indirection, unless they are byval. Most things are byval, and will not 1910 // require this indirection. 1911 bool IsIndirect = false; 1912 if (Info.isIndirect() && !Info.getIndirectByVal()) 1913 IsIndirect = true; 1914 Info = ABIArgInfo::getInAlloca(FrameFields.size(), IsIndirect); 1915 llvm::Type *LLTy = CGT.ConvertTypeForMem(Type); 1916 if (IsIndirect) 1917 LLTy = LLTy->getPointerTo(0); 1918 FrameFields.push_back(LLTy); 1919 StackOffset += IsIndirect ? WordSize : getContext().getTypeSizeInChars(Type); 1920 1921 // Insert padding bytes to respect alignment. 1922 CharUnits FieldEnd = StackOffset; 1923 StackOffset = FieldEnd.alignTo(WordSize); 1924 if (StackOffset != FieldEnd) { 1925 CharUnits NumBytes = StackOffset - FieldEnd; 1926 llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext()); 1927 Ty = llvm::ArrayType::get(Ty, NumBytes.getQuantity()); 1928 FrameFields.push_back(Ty); 1929 } 1930 } 1931 1932 static bool isArgInAlloca(const ABIArgInfo &Info) { 1933 // Leave ignored and inreg arguments alone. 1934 switch (Info.getKind()) { 1935 case ABIArgInfo::InAlloca: 1936 return true; 1937 case ABIArgInfo::Ignore: 1938 return false; 1939 case ABIArgInfo::Indirect: 1940 case ABIArgInfo::Direct: 1941 case ABIArgInfo::Extend: 1942 return !Info.getInReg(); 1943 case ABIArgInfo::Expand: 1944 case ABIArgInfo::CoerceAndExpand: 1945 // These are aggregate types which are never passed in registers when 1946 // inalloca is involved. 1947 return true; 1948 } 1949 llvm_unreachable("invalid enum"); 1950 } 1951 1952 void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const { 1953 assert(IsWin32StructABI && "inalloca only supported on win32"); 1954 1955 // Build a packed struct type for all of the arguments in memory. 1956 SmallVector<llvm::Type *, 6> FrameFields; 1957 1958 // The stack alignment is always 4. 1959 CharUnits StackAlign = CharUnits::fromQuantity(4); 1960 1961 CharUnits StackOffset; 1962 CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end(); 1963 1964 // Put 'this' into the struct before 'sret', if necessary. 1965 bool IsThisCall = 1966 FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall; 1967 ABIArgInfo &Ret = FI.getReturnInfo(); 1968 if (Ret.isIndirect() && Ret.isSRetAfterThis() && !IsThisCall && 1969 isArgInAlloca(I->info)) { 1970 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type); 1971 ++I; 1972 } 1973 1974 // Put the sret parameter into the inalloca struct if it's in memory. 1975 if (Ret.isIndirect() && !Ret.getInReg()) { 1976 addFieldToArgStruct(FrameFields, StackOffset, Ret, FI.getReturnType()); 1977 // On Windows, the hidden sret parameter is always returned in eax. 1978 Ret.setInAllocaSRet(IsWin32StructABI); 1979 } 1980 1981 // Skip the 'this' parameter in ecx. 1982 if (IsThisCall) 1983 ++I; 1984 1985 // Put arguments passed in memory into the struct. 1986 for (; I != E; ++I) { 1987 if (isArgInAlloca(I->info)) 1988 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type); 1989 } 1990 1991 FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields, 1992 /*isPacked=*/true), 1993 StackAlign); 1994 } 1995 1996 Address X86_32ABIInfo::EmitVAArg(CodeGenFunction &CGF, 1997 Address VAListAddr, QualType Ty) const { 1998 1999 auto TypeInfo = getContext().getTypeInfoInChars(Ty); 2000 2001 // x86-32 changes the alignment of certain arguments on the stack. 2002 // 2003 // Just messing with TypeInfo like this works because we never pass 2004 // anything indirectly. 2005 TypeInfo.second = CharUnits::fromQuantity( 2006 getTypeStackAlignInBytes(Ty, TypeInfo.second.getQuantity())); 2007 2008 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false, 2009 TypeInfo, CharUnits::fromQuantity(4), 2010 /*AllowHigherAlign*/ true); 2011 } 2012 2013 bool X86_32TargetCodeGenInfo::isStructReturnInRegABI( 2014 const llvm::Triple &Triple, const CodeGenOptions &Opts) { 2015 assert(Triple.getArch() == llvm::Triple::x86); 2016 2017 switch (Opts.getStructReturnConvention()) { 2018 case CodeGenOptions::SRCK_Default: 2019 break; 2020 case CodeGenOptions::SRCK_OnStack: // -fpcc-struct-return 2021 return false; 2022 case CodeGenOptions::SRCK_InRegs: // -freg-struct-return 2023 return true; 2024 } 2025 2026 if (Triple.isOSDarwin() || Triple.isOSIAMCU()) 2027 return true; 2028 2029 switch (Triple.getOS()) { 2030 case llvm::Triple::DragonFly: 2031 case llvm::Triple::FreeBSD: 2032 case llvm::Triple::OpenBSD: 2033 case llvm::Triple::Win32: 2034 return true; 2035 default: 2036 return false; 2037 } 2038 } 2039 2040 void X86_32TargetCodeGenInfo::setTargetAttributes( 2041 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const { 2042 if (GV->isDeclaration()) 2043 return; 2044 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) { 2045 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) { 2046 llvm::Function *Fn = cast<llvm::Function>(GV); 2047 Fn->addFnAttr("stackrealign"); 2048 } 2049 if (FD->hasAttr<AnyX86InterruptAttr>()) { 2050 llvm::Function *Fn = cast<llvm::Function>(GV); 2051 Fn->setCallingConv(llvm::CallingConv::X86_INTR); 2052 } 2053 } 2054 } 2055 2056 bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable( 2057 CodeGen::CodeGenFunction &CGF, 2058 llvm::Value *Address) const { 2059 CodeGen::CGBuilderTy &Builder = CGF.Builder; 2060 2061 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4); 2062 2063 // 0-7 are the eight integer registers; the order is different 2064 // on Darwin (for EH), but the range is the same. 2065 // 8 is %eip. 2066 AssignToArrayRange(Builder, Address, Four8, 0, 8); 2067 2068 if (CGF.CGM.getTarget().getTriple().isOSDarwin()) { 2069 // 12-16 are st(0..4). Not sure why we stop at 4. 2070 // These have size 16, which is sizeof(long double) on 2071 // platforms with 8-byte alignment for that type. 2072 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16); 2073 AssignToArrayRange(Builder, Address, Sixteen8, 12, 16); 2074 2075 } else { 2076 // 9 is %eflags, which doesn't get a size on Darwin for some 2077 // reason. 2078 Builder.CreateAlignedStore( 2079 Four8, Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, Address, 9), 2080 CharUnits::One()); 2081 2082 // 11-16 are st(0..5). Not sure why we stop at 5. 2083 // These have size 12, which is sizeof(long double) on 2084 // platforms with 4-byte alignment for that type. 2085 llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12); 2086 AssignToArrayRange(Builder, Address, Twelve8, 11, 16); 2087 } 2088 2089 return false; 2090 } 2091 2092 //===----------------------------------------------------------------------===// 2093 // X86-64 ABI Implementation 2094 //===----------------------------------------------------------------------===// 2095 2096 2097 namespace { 2098 /// The AVX ABI level for X86 targets. 2099 enum class X86AVXABILevel { 2100 None, 2101 AVX, 2102 AVX512 2103 }; 2104 2105 /// \p returns the size in bits of the largest (native) vector for \p AVXLevel. 2106 static unsigned getNativeVectorSizeForAVXABI(X86AVXABILevel AVXLevel) { 2107 switch (AVXLevel) { 2108 case X86AVXABILevel::AVX512: 2109 return 512; 2110 case X86AVXABILevel::AVX: 2111 return 256; 2112 case X86AVXABILevel::None: 2113 return 128; 2114 } 2115 llvm_unreachable("Unknown AVXLevel"); 2116 } 2117 2118 /// X86_64ABIInfo - The X86_64 ABI information. 2119 class X86_64ABIInfo : public SwiftABIInfo { 2120 enum Class { 2121 Integer = 0, 2122 SSE, 2123 SSEUp, 2124 X87, 2125 X87Up, 2126 ComplexX87, 2127 NoClass, 2128 Memory 2129 }; 2130 2131 /// merge - Implement the X86_64 ABI merging algorithm. 2132 /// 2133 /// Merge an accumulating classification \arg Accum with a field 2134 /// classification \arg Field. 2135 /// 2136 /// \param Accum - The accumulating classification. This should 2137 /// always be either NoClass or the result of a previous merge 2138 /// call. In addition, this should never be Memory (the caller 2139 /// should just return Memory for the aggregate). 2140 static Class merge(Class Accum, Class Field); 2141 2142 /// postMerge - Implement the X86_64 ABI post merging algorithm. 2143 /// 2144 /// Post merger cleanup, reduces a malformed Hi and Lo pair to 2145 /// final MEMORY or SSE classes when necessary. 2146 /// 2147 /// \param AggregateSize - The size of the current aggregate in 2148 /// the classification process. 2149 /// 2150 /// \param Lo - The classification for the parts of the type 2151 /// residing in the low word of the containing object. 2152 /// 2153 /// \param Hi - The classification for the parts of the type 2154 /// residing in the higher words of the containing object. 2155 /// 2156 void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const; 2157 2158 /// classify - Determine the x86_64 register classes in which the 2159 /// given type T should be passed. 2160 /// 2161 /// \param Lo - The classification for the parts of the type 2162 /// residing in the low word of the containing object. 2163 /// 2164 /// \param Hi - The classification for the parts of the type 2165 /// residing in the high word of the containing object. 2166 /// 2167 /// \param OffsetBase - The bit offset of this type in the 2168 /// containing object. Some parameters are classified different 2169 /// depending on whether they straddle an eightbyte boundary. 2170 /// 2171 /// \param isNamedArg - Whether the argument in question is a "named" 2172 /// argument, as used in AMD64-ABI 3.5.7. 2173 /// 2174 /// If a word is unused its result will be NoClass; if a type should 2175 /// be passed in Memory then at least the classification of \arg Lo 2176 /// will be Memory. 2177 /// 2178 /// The \arg Lo class will be NoClass iff the argument is ignored. 2179 /// 2180 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will 2181 /// also be ComplexX87. 2182 void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi, 2183 bool isNamedArg) const; 2184 2185 llvm::Type *GetByteVectorType(QualType Ty) const; 2186 llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType, 2187 unsigned IROffset, QualType SourceTy, 2188 unsigned SourceOffset) const; 2189 llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType, 2190 unsigned IROffset, QualType SourceTy, 2191 unsigned SourceOffset) const; 2192 2193 /// getIndirectResult - Give a source type \arg Ty, return a suitable result 2194 /// such that the argument will be returned in memory. 2195 ABIArgInfo getIndirectReturnResult(QualType Ty) const; 2196 2197 /// getIndirectResult - Give a source type \arg Ty, return a suitable result 2198 /// such that the argument will be passed in memory. 2199 /// 2200 /// \param freeIntRegs - The number of free integer registers remaining 2201 /// available. 2202 ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const; 2203 2204 ABIArgInfo classifyReturnType(QualType RetTy) const; 2205 2206 ABIArgInfo classifyArgumentType(QualType Ty, unsigned freeIntRegs, 2207 unsigned &neededInt, unsigned &neededSSE, 2208 bool isNamedArg) const; 2209 2210 ABIArgInfo classifyRegCallStructType(QualType Ty, unsigned &NeededInt, 2211 unsigned &NeededSSE) const; 2212 2213 ABIArgInfo classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt, 2214 unsigned &NeededSSE) const; 2215 2216 bool IsIllegalVectorType(QualType Ty) const; 2217 2218 /// The 0.98 ABI revision clarified a lot of ambiguities, 2219 /// unfortunately in ways that were not always consistent with 2220 /// certain previous compilers. In particular, platforms which 2221 /// required strict binary compatibility with older versions of GCC 2222 /// may need to exempt themselves. 2223 bool honorsRevision0_98() const { 2224 return !getTarget().getTriple().isOSDarwin(); 2225 } 2226 2227 /// GCC classifies <1 x long long> as SSE but some platform ABIs choose to 2228 /// classify it as INTEGER (for compatibility with older clang compilers). 2229 bool classifyIntegerMMXAsSSE() const { 2230 // Clang <= 3.8 did not do this. 2231 if (getContext().getLangOpts().getClangABICompat() <= 2232 LangOptions::ClangABI::Ver3_8) 2233 return false; 2234 2235 const llvm::Triple &Triple = getTarget().getTriple(); 2236 if (Triple.isOSDarwin() || Triple.getOS() == llvm::Triple::PS4) 2237 return false; 2238 if (Triple.isOSFreeBSD() && Triple.getOSMajorVersion() >= 10) 2239 return false; 2240 return true; 2241 } 2242 2243 // GCC classifies vectors of __int128 as memory. 2244 bool passInt128VectorsInMem() const { 2245 // Clang <= 9.0 did not do this. 2246 if (getContext().getLangOpts().getClangABICompat() <= 2247 LangOptions::ClangABI::Ver9) 2248 return false; 2249 2250 const llvm::Triple &T = getTarget().getTriple(); 2251 return T.isOSLinux() || T.isOSNetBSD(); 2252 } 2253 2254 X86AVXABILevel AVXLevel; 2255 // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on 2256 // 64-bit hardware. 2257 bool Has64BitPointers; 2258 2259 public: 2260 X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) : 2261 SwiftABIInfo(CGT), AVXLevel(AVXLevel), 2262 Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) { 2263 } 2264 2265 bool isPassedUsingAVXType(QualType type) const { 2266 unsigned neededInt, neededSSE; 2267 // The freeIntRegs argument doesn't matter here. 2268 ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE, 2269 /*isNamedArg*/true); 2270 if (info.isDirect()) { 2271 llvm::Type *ty = info.getCoerceToType(); 2272 if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty)) 2273 return vectorTy->getPrimitiveSizeInBits().getFixedSize() > 128; 2274 } 2275 return false; 2276 } 2277 2278 void computeInfo(CGFunctionInfo &FI) const override; 2279 2280 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 2281 QualType Ty) const override; 2282 Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr, 2283 QualType Ty) const override; 2284 2285 bool has64BitPointers() const { 2286 return Has64BitPointers; 2287 } 2288 2289 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars, 2290 bool asReturnValue) const override { 2291 return occupiesMoreThan(CGT, scalars, /*total*/ 4); 2292 } 2293 bool isSwiftErrorInRegister() const override { 2294 return true; 2295 } 2296 }; 2297 2298 /// WinX86_64ABIInfo - The Windows X86_64 ABI information. 2299 class WinX86_64ABIInfo : public SwiftABIInfo { 2300 public: 2301 WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) 2302 : SwiftABIInfo(CGT), AVXLevel(AVXLevel), 2303 IsMingw64(getTarget().getTriple().isWindowsGNUEnvironment()) {} 2304 2305 void computeInfo(CGFunctionInfo &FI) const override; 2306 2307 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 2308 QualType Ty) const override; 2309 2310 bool isHomogeneousAggregateBaseType(QualType Ty) const override { 2311 // FIXME: Assumes vectorcall is in use. 2312 return isX86VectorTypeForVectorCall(getContext(), Ty); 2313 } 2314 2315 bool isHomogeneousAggregateSmallEnough(const Type *Ty, 2316 uint64_t NumMembers) const override { 2317 // FIXME: Assumes vectorcall is in use. 2318 return isX86VectorCallAggregateSmallEnough(NumMembers); 2319 } 2320 2321 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type *> scalars, 2322 bool asReturnValue) const override { 2323 return occupiesMoreThan(CGT, scalars, /*total*/ 4); 2324 } 2325 2326 bool isSwiftErrorInRegister() const override { 2327 return true; 2328 } 2329 2330 private: 2331 ABIArgInfo classify(QualType Ty, unsigned &FreeSSERegs, bool IsReturnType, 2332 bool IsVectorCall, bool IsRegCall) const; 2333 ABIArgInfo reclassifyHvaArgType(QualType Ty, unsigned &FreeSSERegs, 2334 const ABIArgInfo ¤t) const; 2335 void computeVectorCallArgs(CGFunctionInfo &FI, unsigned FreeSSERegs, 2336 bool IsVectorCall, bool IsRegCall) const; 2337 2338 X86AVXABILevel AVXLevel; 2339 2340 bool IsMingw64; 2341 }; 2342 2343 class X86_64TargetCodeGenInfo : public TargetCodeGenInfo { 2344 public: 2345 X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) 2346 : TargetCodeGenInfo(std::make_unique<X86_64ABIInfo>(CGT, AVXLevel)) {} 2347 2348 const X86_64ABIInfo &getABIInfo() const { 2349 return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo()); 2350 } 2351 2352 /// Disable tail call on x86-64. The epilogue code before the tail jump blocks 2353 /// the autoreleaseRV/retainRV optimization. 2354 bool shouldSuppressTailCallsOfRetainAutoreleasedReturnValue() const override { 2355 return true; 2356 } 2357 2358 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override { 2359 return 7; 2360 } 2361 2362 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 2363 llvm::Value *Address) const override { 2364 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8); 2365 2366 // 0-15 are the 16 integer registers. 2367 // 16 is %rip. 2368 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16); 2369 return false; 2370 } 2371 2372 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF, 2373 StringRef Constraint, 2374 llvm::Type* Ty) const override { 2375 return X86AdjustInlineAsmType(CGF, Constraint, Ty); 2376 } 2377 2378 bool isNoProtoCallVariadic(const CallArgList &args, 2379 const FunctionNoProtoType *fnType) const override { 2380 // The default CC on x86-64 sets %al to the number of SSA 2381 // registers used, and GCC sets this when calling an unprototyped 2382 // function, so we override the default behavior. However, don't do 2383 // that when AVX types are involved: the ABI explicitly states it is 2384 // undefined, and it doesn't work in practice because of how the ABI 2385 // defines varargs anyway. 2386 if (fnType->getCallConv() == CC_C) { 2387 bool HasAVXType = false; 2388 for (CallArgList::const_iterator 2389 it = args.begin(), ie = args.end(); it != ie; ++it) { 2390 if (getABIInfo().isPassedUsingAVXType(it->Ty)) { 2391 HasAVXType = true; 2392 break; 2393 } 2394 } 2395 2396 if (!HasAVXType) 2397 return true; 2398 } 2399 2400 return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType); 2401 } 2402 2403 llvm::Constant * 2404 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override { 2405 unsigned Sig = (0xeb << 0) | // jmp rel8 2406 (0x06 << 8) | // .+0x08 2407 ('v' << 16) | 2408 ('2' << 24); 2409 return llvm::ConstantInt::get(CGM.Int32Ty, Sig); 2410 } 2411 2412 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 2413 CodeGen::CodeGenModule &CGM) const override { 2414 if (GV->isDeclaration()) 2415 return; 2416 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) { 2417 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) { 2418 llvm::Function *Fn = cast<llvm::Function>(GV); 2419 Fn->addFnAttr("stackrealign"); 2420 } 2421 if (FD->hasAttr<AnyX86InterruptAttr>()) { 2422 llvm::Function *Fn = cast<llvm::Function>(GV); 2423 Fn->setCallingConv(llvm::CallingConv::X86_INTR); 2424 } 2425 } 2426 } 2427 }; 2428 2429 static std::string qualifyWindowsLibrary(llvm::StringRef Lib) { 2430 // If the argument does not end in .lib, automatically add the suffix. 2431 // If the argument contains a space, enclose it in quotes. 2432 // This matches the behavior of MSVC. 2433 bool Quote = (Lib.find(" ") != StringRef::npos); 2434 std::string ArgStr = Quote ? "\"" : ""; 2435 ArgStr += Lib; 2436 if (!Lib.endswith_lower(".lib") && !Lib.endswith_lower(".a")) 2437 ArgStr += ".lib"; 2438 ArgStr += Quote ? "\"" : ""; 2439 return ArgStr; 2440 } 2441 2442 class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo { 2443 public: 2444 WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, 2445 bool DarwinVectorABI, bool RetSmallStructInRegABI, bool Win32StructABI, 2446 unsigned NumRegisterParameters) 2447 : X86_32TargetCodeGenInfo(CGT, DarwinVectorABI, RetSmallStructInRegABI, 2448 Win32StructABI, NumRegisterParameters, false) {} 2449 2450 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 2451 CodeGen::CodeGenModule &CGM) const override; 2452 2453 void getDependentLibraryOption(llvm::StringRef Lib, 2454 llvm::SmallString<24> &Opt) const override { 2455 Opt = "/DEFAULTLIB:"; 2456 Opt += qualifyWindowsLibrary(Lib); 2457 } 2458 2459 void getDetectMismatchOption(llvm::StringRef Name, 2460 llvm::StringRef Value, 2461 llvm::SmallString<32> &Opt) const override { 2462 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\""; 2463 } 2464 }; 2465 2466 static void addStackProbeTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 2467 CodeGen::CodeGenModule &CGM) { 2468 if (llvm::Function *Fn = dyn_cast_or_null<llvm::Function>(GV)) { 2469 2470 if (CGM.getCodeGenOpts().StackProbeSize != 4096) 2471 Fn->addFnAttr("stack-probe-size", 2472 llvm::utostr(CGM.getCodeGenOpts().StackProbeSize)); 2473 if (CGM.getCodeGenOpts().NoStackArgProbe) 2474 Fn->addFnAttr("no-stack-arg-probe"); 2475 } 2476 } 2477 2478 void WinX86_32TargetCodeGenInfo::setTargetAttributes( 2479 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const { 2480 X86_32TargetCodeGenInfo::setTargetAttributes(D, GV, CGM); 2481 if (GV->isDeclaration()) 2482 return; 2483 addStackProbeTargetAttributes(D, GV, CGM); 2484 } 2485 2486 class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo { 2487 public: 2488 WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, 2489 X86AVXABILevel AVXLevel) 2490 : TargetCodeGenInfo(std::make_unique<WinX86_64ABIInfo>(CGT, AVXLevel)) {} 2491 2492 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 2493 CodeGen::CodeGenModule &CGM) const override; 2494 2495 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override { 2496 return 7; 2497 } 2498 2499 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 2500 llvm::Value *Address) const override { 2501 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8); 2502 2503 // 0-15 are the 16 integer registers. 2504 // 16 is %rip. 2505 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16); 2506 return false; 2507 } 2508 2509 void getDependentLibraryOption(llvm::StringRef Lib, 2510 llvm::SmallString<24> &Opt) const override { 2511 Opt = "/DEFAULTLIB:"; 2512 Opt += qualifyWindowsLibrary(Lib); 2513 } 2514 2515 void getDetectMismatchOption(llvm::StringRef Name, 2516 llvm::StringRef Value, 2517 llvm::SmallString<32> &Opt) const override { 2518 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\""; 2519 } 2520 }; 2521 2522 void WinX86_64TargetCodeGenInfo::setTargetAttributes( 2523 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const { 2524 TargetCodeGenInfo::setTargetAttributes(D, GV, CGM); 2525 if (GV->isDeclaration()) 2526 return; 2527 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) { 2528 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) { 2529 llvm::Function *Fn = cast<llvm::Function>(GV); 2530 Fn->addFnAttr("stackrealign"); 2531 } 2532 if (FD->hasAttr<AnyX86InterruptAttr>()) { 2533 llvm::Function *Fn = cast<llvm::Function>(GV); 2534 Fn->setCallingConv(llvm::CallingConv::X86_INTR); 2535 } 2536 } 2537 2538 addStackProbeTargetAttributes(D, GV, CGM); 2539 } 2540 } 2541 2542 void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo, 2543 Class &Hi) const { 2544 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done: 2545 // 2546 // (a) If one of the classes is Memory, the whole argument is passed in 2547 // memory. 2548 // 2549 // (b) If X87UP is not preceded by X87, the whole argument is passed in 2550 // memory. 2551 // 2552 // (c) If the size of the aggregate exceeds two eightbytes and the first 2553 // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole 2554 // argument is passed in memory. NOTE: This is necessary to keep the 2555 // ABI working for processors that don't support the __m256 type. 2556 // 2557 // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE. 2558 // 2559 // Some of these are enforced by the merging logic. Others can arise 2560 // only with unions; for example: 2561 // union { _Complex double; unsigned; } 2562 // 2563 // Note that clauses (b) and (c) were added in 0.98. 2564 // 2565 if (Hi == Memory) 2566 Lo = Memory; 2567 if (Hi == X87Up && Lo != X87 && honorsRevision0_98()) 2568 Lo = Memory; 2569 if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp)) 2570 Lo = Memory; 2571 if (Hi == SSEUp && Lo != SSE) 2572 Hi = SSE; 2573 } 2574 2575 X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) { 2576 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is 2577 // classified recursively so that always two fields are 2578 // considered. The resulting class is calculated according to 2579 // the classes of the fields in the eightbyte: 2580 // 2581 // (a) If both classes are equal, this is the resulting class. 2582 // 2583 // (b) If one of the classes is NO_CLASS, the resulting class is 2584 // the other class. 2585 // 2586 // (c) If one of the classes is MEMORY, the result is the MEMORY 2587 // class. 2588 // 2589 // (d) If one of the classes is INTEGER, the result is the 2590 // INTEGER. 2591 // 2592 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class, 2593 // MEMORY is used as class. 2594 // 2595 // (f) Otherwise class SSE is used. 2596 2597 // Accum should never be memory (we should have returned) or 2598 // ComplexX87 (because this cannot be passed in a structure). 2599 assert((Accum != Memory && Accum != ComplexX87) && 2600 "Invalid accumulated classification during merge."); 2601 if (Accum == Field || Field == NoClass) 2602 return Accum; 2603 if (Field == Memory) 2604 return Memory; 2605 if (Accum == NoClass) 2606 return Field; 2607 if (Accum == Integer || Field == Integer) 2608 return Integer; 2609 if (Field == X87 || Field == X87Up || Field == ComplexX87 || 2610 Accum == X87 || Accum == X87Up) 2611 return Memory; 2612 return SSE; 2613 } 2614 2615 void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase, 2616 Class &Lo, Class &Hi, bool isNamedArg) const { 2617 // FIXME: This code can be simplified by introducing a simple value class for 2618 // Class pairs with appropriate constructor methods for the various 2619 // situations. 2620 2621 // FIXME: Some of the split computations are wrong; unaligned vectors 2622 // shouldn't be passed in registers for example, so there is no chance they 2623 // can straddle an eightbyte. Verify & simplify. 2624 2625 Lo = Hi = NoClass; 2626 2627 Class &Current = OffsetBase < 64 ? Lo : Hi; 2628 Current = Memory; 2629 2630 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) { 2631 BuiltinType::Kind k = BT->getKind(); 2632 2633 if (k == BuiltinType::Void) { 2634 Current = NoClass; 2635 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) { 2636 Lo = Integer; 2637 Hi = Integer; 2638 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) { 2639 Current = Integer; 2640 } else if (k == BuiltinType::Float || k == BuiltinType::Double) { 2641 Current = SSE; 2642 } else if (k == BuiltinType::LongDouble) { 2643 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat(); 2644 if (LDF == &llvm::APFloat::IEEEquad()) { 2645 Lo = SSE; 2646 Hi = SSEUp; 2647 } else if (LDF == &llvm::APFloat::x87DoubleExtended()) { 2648 Lo = X87; 2649 Hi = X87Up; 2650 } else if (LDF == &llvm::APFloat::IEEEdouble()) { 2651 Current = SSE; 2652 } else 2653 llvm_unreachable("unexpected long double representation!"); 2654 } 2655 // FIXME: _Decimal32 and _Decimal64 are SSE. 2656 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp). 2657 return; 2658 } 2659 2660 if (const EnumType *ET = Ty->getAs<EnumType>()) { 2661 // Classify the underlying integer type. 2662 classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg); 2663 return; 2664 } 2665 2666 if (Ty->hasPointerRepresentation()) { 2667 Current = Integer; 2668 return; 2669 } 2670 2671 if (Ty->isMemberPointerType()) { 2672 if (Ty->isMemberFunctionPointerType()) { 2673 if (Has64BitPointers) { 2674 // If Has64BitPointers, this is an {i64, i64}, so classify both 2675 // Lo and Hi now. 2676 Lo = Hi = Integer; 2677 } else { 2678 // Otherwise, with 32-bit pointers, this is an {i32, i32}. If that 2679 // straddles an eightbyte boundary, Hi should be classified as well. 2680 uint64_t EB_FuncPtr = (OffsetBase) / 64; 2681 uint64_t EB_ThisAdj = (OffsetBase + 64 - 1) / 64; 2682 if (EB_FuncPtr != EB_ThisAdj) { 2683 Lo = Hi = Integer; 2684 } else { 2685 Current = Integer; 2686 } 2687 } 2688 } else { 2689 Current = Integer; 2690 } 2691 return; 2692 } 2693 2694 if (const VectorType *VT = Ty->getAs<VectorType>()) { 2695 uint64_t Size = getContext().getTypeSize(VT); 2696 if (Size == 1 || Size == 8 || Size == 16 || Size == 32) { 2697 // gcc passes the following as integer: 2698 // 4 bytes - <4 x char>, <2 x short>, <1 x int>, <1 x float> 2699 // 2 bytes - <2 x char>, <1 x short> 2700 // 1 byte - <1 x char> 2701 Current = Integer; 2702 2703 // If this type crosses an eightbyte boundary, it should be 2704 // split. 2705 uint64_t EB_Lo = (OffsetBase) / 64; 2706 uint64_t EB_Hi = (OffsetBase + Size - 1) / 64; 2707 if (EB_Lo != EB_Hi) 2708 Hi = Lo; 2709 } else if (Size == 64) { 2710 QualType ElementType = VT->getElementType(); 2711 2712 // gcc passes <1 x double> in memory. :( 2713 if (ElementType->isSpecificBuiltinType(BuiltinType::Double)) 2714 return; 2715 2716 // gcc passes <1 x long long> as SSE but clang used to unconditionally 2717 // pass them as integer. For platforms where clang is the de facto 2718 // platform compiler, we must continue to use integer. 2719 if (!classifyIntegerMMXAsSSE() && 2720 (ElementType->isSpecificBuiltinType(BuiltinType::LongLong) || 2721 ElementType->isSpecificBuiltinType(BuiltinType::ULongLong) || 2722 ElementType->isSpecificBuiltinType(BuiltinType::Long) || 2723 ElementType->isSpecificBuiltinType(BuiltinType::ULong))) 2724 Current = Integer; 2725 else 2726 Current = SSE; 2727 2728 // If this type crosses an eightbyte boundary, it should be 2729 // split. 2730 if (OffsetBase && OffsetBase != 64) 2731 Hi = Lo; 2732 } else if (Size == 128 || 2733 (isNamedArg && Size <= getNativeVectorSizeForAVXABI(AVXLevel))) { 2734 QualType ElementType = VT->getElementType(); 2735 2736 // gcc passes 256 and 512 bit <X x __int128> vectors in memory. :( 2737 if (passInt128VectorsInMem() && Size != 128 && 2738 (ElementType->isSpecificBuiltinType(BuiltinType::Int128) || 2739 ElementType->isSpecificBuiltinType(BuiltinType::UInt128))) 2740 return; 2741 2742 // Arguments of 256-bits are split into four eightbyte chunks. The 2743 // least significant one belongs to class SSE and all the others to class 2744 // SSEUP. The original Lo and Hi design considers that types can't be 2745 // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense. 2746 // This design isn't correct for 256-bits, but since there're no cases 2747 // where the upper parts would need to be inspected, avoid adding 2748 // complexity and just consider Hi to match the 64-256 part. 2749 // 2750 // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in 2751 // registers if they are "named", i.e. not part of the "..." of a 2752 // variadic function. 2753 // 2754 // Similarly, per 3.2.3. of the AVX512 draft, 512-bits ("named") args are 2755 // split into eight eightbyte chunks, one SSE and seven SSEUP. 2756 Lo = SSE; 2757 Hi = SSEUp; 2758 } 2759 return; 2760 } 2761 2762 if (const ComplexType *CT = Ty->getAs<ComplexType>()) { 2763 QualType ET = getContext().getCanonicalType(CT->getElementType()); 2764 2765 uint64_t Size = getContext().getTypeSize(Ty); 2766 if (ET->isIntegralOrEnumerationType()) { 2767 if (Size <= 64) 2768 Current = Integer; 2769 else if (Size <= 128) 2770 Lo = Hi = Integer; 2771 } else if (ET == getContext().FloatTy) { 2772 Current = SSE; 2773 } else if (ET == getContext().DoubleTy) { 2774 Lo = Hi = SSE; 2775 } else if (ET == getContext().LongDoubleTy) { 2776 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat(); 2777 if (LDF == &llvm::APFloat::IEEEquad()) 2778 Current = Memory; 2779 else if (LDF == &llvm::APFloat::x87DoubleExtended()) 2780 Current = ComplexX87; 2781 else if (LDF == &llvm::APFloat::IEEEdouble()) 2782 Lo = Hi = SSE; 2783 else 2784 llvm_unreachable("unexpected long double representation!"); 2785 } 2786 2787 // If this complex type crosses an eightbyte boundary then it 2788 // should be split. 2789 uint64_t EB_Real = (OffsetBase) / 64; 2790 uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64; 2791 if (Hi == NoClass && EB_Real != EB_Imag) 2792 Hi = Lo; 2793 2794 return; 2795 } 2796 2797 if (const auto *EITy = Ty->getAs<ExtIntType>()) { 2798 if (EITy->getNumBits() <= 64) 2799 Current = Integer; 2800 else if (EITy->getNumBits() <= 128) 2801 Lo = Hi = Integer; 2802 // Larger values need to get passed in memory. 2803 return; 2804 } 2805 2806 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) { 2807 // Arrays are treated like structures. 2808 2809 uint64_t Size = getContext().getTypeSize(Ty); 2810 2811 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger 2812 // than eight eightbytes, ..., it has class MEMORY. 2813 if (Size > 512) 2814 return; 2815 2816 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned 2817 // fields, it has class MEMORY. 2818 // 2819 // Only need to check alignment of array base. 2820 if (OffsetBase % getContext().getTypeAlign(AT->getElementType())) 2821 return; 2822 2823 // Otherwise implement simplified merge. We could be smarter about 2824 // this, but it isn't worth it and would be harder to verify. 2825 Current = NoClass; 2826 uint64_t EltSize = getContext().getTypeSize(AT->getElementType()); 2827 uint64_t ArraySize = AT->getSize().getZExtValue(); 2828 2829 // The only case a 256-bit wide vector could be used is when the array 2830 // contains a single 256-bit element. Since Lo and Hi logic isn't extended 2831 // to work for sizes wider than 128, early check and fallback to memory. 2832 // 2833 if (Size > 128 && 2834 (Size != EltSize || Size > getNativeVectorSizeForAVXABI(AVXLevel))) 2835 return; 2836 2837 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) { 2838 Class FieldLo, FieldHi; 2839 classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg); 2840 Lo = merge(Lo, FieldLo); 2841 Hi = merge(Hi, FieldHi); 2842 if (Lo == Memory || Hi == Memory) 2843 break; 2844 } 2845 2846 postMerge(Size, Lo, Hi); 2847 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification."); 2848 return; 2849 } 2850 2851 if (const RecordType *RT = Ty->getAs<RecordType>()) { 2852 uint64_t Size = getContext().getTypeSize(Ty); 2853 2854 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger 2855 // than eight eightbytes, ..., it has class MEMORY. 2856 if (Size > 512) 2857 return; 2858 2859 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial 2860 // copy constructor or a non-trivial destructor, it is passed by invisible 2861 // reference. 2862 if (getRecordArgABI(RT, getCXXABI())) 2863 return; 2864 2865 const RecordDecl *RD = RT->getDecl(); 2866 2867 // Assume variable sized types are passed in memory. 2868 if (RD->hasFlexibleArrayMember()) 2869 return; 2870 2871 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD); 2872 2873 // Reset Lo class, this will be recomputed. 2874 Current = NoClass; 2875 2876 // If this is a C++ record, classify the bases first. 2877 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 2878 for (const auto &I : CXXRD->bases()) { 2879 assert(!I.isVirtual() && !I.getType()->isDependentType() && 2880 "Unexpected base class!"); 2881 const auto *Base = 2882 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl()); 2883 2884 // Classify this field. 2885 // 2886 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a 2887 // single eightbyte, each is classified separately. Each eightbyte gets 2888 // initialized to class NO_CLASS. 2889 Class FieldLo, FieldHi; 2890 uint64_t Offset = 2891 OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base)); 2892 classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg); 2893 Lo = merge(Lo, FieldLo); 2894 Hi = merge(Hi, FieldHi); 2895 if (Lo == Memory || Hi == Memory) { 2896 postMerge(Size, Lo, Hi); 2897 return; 2898 } 2899 } 2900 } 2901 2902 // Classify the fields one at a time, merging the results. 2903 unsigned idx = 0; 2904 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 2905 i != e; ++i, ++idx) { 2906 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx); 2907 bool BitField = i->isBitField(); 2908 2909 // Ignore padding bit-fields. 2910 if (BitField && i->isUnnamedBitfield()) 2911 continue; 2912 2913 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than 2914 // four eightbytes, or it contains unaligned fields, it has class MEMORY. 2915 // 2916 // The only case a 256-bit wide vector could be used is when the struct 2917 // contains a single 256-bit element. Since Lo and Hi logic isn't extended 2918 // to work for sizes wider than 128, early check and fallback to memory. 2919 // 2920 if (Size > 128 && (Size != getContext().getTypeSize(i->getType()) || 2921 Size > getNativeVectorSizeForAVXABI(AVXLevel))) { 2922 Lo = Memory; 2923 postMerge(Size, Lo, Hi); 2924 return; 2925 } 2926 // Note, skip this test for bit-fields, see below. 2927 if (!BitField && Offset % getContext().getTypeAlign(i->getType())) { 2928 Lo = Memory; 2929 postMerge(Size, Lo, Hi); 2930 return; 2931 } 2932 2933 // Classify this field. 2934 // 2935 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate 2936 // exceeds a single eightbyte, each is classified 2937 // separately. Each eightbyte gets initialized to class 2938 // NO_CLASS. 2939 Class FieldLo, FieldHi; 2940 2941 // Bit-fields require special handling, they do not force the 2942 // structure to be passed in memory even if unaligned, and 2943 // therefore they can straddle an eightbyte. 2944 if (BitField) { 2945 assert(!i->isUnnamedBitfield()); 2946 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx); 2947 uint64_t Size = i->getBitWidthValue(getContext()); 2948 2949 uint64_t EB_Lo = Offset / 64; 2950 uint64_t EB_Hi = (Offset + Size - 1) / 64; 2951 2952 if (EB_Lo) { 2953 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes."); 2954 FieldLo = NoClass; 2955 FieldHi = Integer; 2956 } else { 2957 FieldLo = Integer; 2958 FieldHi = EB_Hi ? Integer : NoClass; 2959 } 2960 } else 2961 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg); 2962 Lo = merge(Lo, FieldLo); 2963 Hi = merge(Hi, FieldHi); 2964 if (Lo == Memory || Hi == Memory) 2965 break; 2966 } 2967 2968 postMerge(Size, Lo, Hi); 2969 } 2970 } 2971 2972 ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const { 2973 // If this is a scalar LLVM value then assume LLVM will pass it in the right 2974 // place naturally. 2975 if (!isAggregateTypeForABI(Ty)) { 2976 // Treat an enum type as its underlying type. 2977 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 2978 Ty = EnumTy->getDecl()->getIntegerType(); 2979 2980 if (!Ty->isExtIntType()) 2981 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty) 2982 : ABIArgInfo::getDirect()); 2983 } 2984 2985 return getNaturalAlignIndirect(Ty); 2986 } 2987 2988 bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const { 2989 if (const VectorType *VecTy = Ty->getAs<VectorType>()) { 2990 uint64_t Size = getContext().getTypeSize(VecTy); 2991 unsigned LargestVector = getNativeVectorSizeForAVXABI(AVXLevel); 2992 if (Size <= 64 || Size > LargestVector) 2993 return true; 2994 QualType EltTy = VecTy->getElementType(); 2995 if (passInt128VectorsInMem() && 2996 (EltTy->isSpecificBuiltinType(BuiltinType::Int128) || 2997 EltTy->isSpecificBuiltinType(BuiltinType::UInt128))) 2998 return true; 2999 } 3000 3001 return false; 3002 } 3003 3004 ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty, 3005 unsigned freeIntRegs) const { 3006 // If this is a scalar LLVM value then assume LLVM will pass it in the right 3007 // place naturally. 3008 // 3009 // This assumption is optimistic, as there could be free registers available 3010 // when we need to pass this argument in memory, and LLVM could try to pass 3011 // the argument in the free register. This does not seem to happen currently, 3012 // but this code would be much safer if we could mark the argument with 3013 // 'onstack'. See PR12193. 3014 if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty) && 3015 !Ty->isExtIntType()) { 3016 // Treat an enum type as its underlying type. 3017 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 3018 Ty = EnumTy->getDecl()->getIntegerType(); 3019 3020 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty) 3021 : ABIArgInfo::getDirect()); 3022 } 3023 3024 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 3025 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 3026 3027 // Compute the byval alignment. We specify the alignment of the byval in all 3028 // cases so that the mid-level optimizer knows the alignment of the byval. 3029 unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U); 3030 3031 // Attempt to avoid passing indirect results using byval when possible. This 3032 // is important for good codegen. 3033 // 3034 // We do this by coercing the value into a scalar type which the backend can 3035 // handle naturally (i.e., without using byval). 3036 // 3037 // For simplicity, we currently only do this when we have exhausted all of the 3038 // free integer registers. Doing this when there are free integer registers 3039 // would require more care, as we would have to ensure that the coerced value 3040 // did not claim the unused register. That would require either reording the 3041 // arguments to the function (so that any subsequent inreg values came first), 3042 // or only doing this optimization when there were no following arguments that 3043 // might be inreg. 3044 // 3045 // We currently expect it to be rare (particularly in well written code) for 3046 // arguments to be passed on the stack when there are still free integer 3047 // registers available (this would typically imply large structs being passed 3048 // by value), so this seems like a fair tradeoff for now. 3049 // 3050 // We can revisit this if the backend grows support for 'onstack' parameter 3051 // attributes. See PR12193. 3052 if (freeIntRegs == 0) { 3053 uint64_t Size = getContext().getTypeSize(Ty); 3054 3055 // If this type fits in an eightbyte, coerce it into the matching integral 3056 // type, which will end up on the stack (with alignment 8). 3057 if (Align == 8 && Size <= 64) 3058 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 3059 Size)); 3060 } 3061 3062 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(Align)); 3063 } 3064 3065 /// The ABI specifies that a value should be passed in a full vector XMM/YMM 3066 /// register. Pick an LLVM IR type that will be passed as a vector register. 3067 llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const { 3068 // Wrapper structs/arrays that only contain vectors are passed just like 3069 // vectors; strip them off if present. 3070 if (const Type *InnerTy = isSingleElementStruct(Ty, getContext())) 3071 Ty = QualType(InnerTy, 0); 3072 3073 llvm::Type *IRType = CGT.ConvertType(Ty); 3074 if (isa<llvm::VectorType>(IRType)) { 3075 // Don't pass vXi128 vectors in their native type, the backend can't 3076 // legalize them. 3077 if (passInt128VectorsInMem() && 3078 cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy(128)) { 3079 // Use a vXi64 vector. 3080 uint64_t Size = getContext().getTypeSize(Ty); 3081 return llvm::VectorType::get(llvm::Type::getInt64Ty(getVMContext()), 3082 Size / 64); 3083 } 3084 3085 return IRType; 3086 } 3087 3088 if (IRType->getTypeID() == llvm::Type::FP128TyID) 3089 return IRType; 3090 3091 // We couldn't find the preferred IR vector type for 'Ty'. 3092 uint64_t Size = getContext().getTypeSize(Ty); 3093 assert((Size == 128 || Size == 256 || Size == 512) && "Invalid type found!"); 3094 3095 3096 // Return a LLVM IR vector type based on the size of 'Ty'. 3097 return llvm::VectorType::get(llvm::Type::getDoubleTy(getVMContext()), 3098 Size / 64); 3099 } 3100 3101 /// BitsContainNoUserData - Return true if the specified [start,end) bit range 3102 /// is known to either be off the end of the specified type or being in 3103 /// alignment padding. The user type specified is known to be at most 128 bits 3104 /// in size, and have passed through X86_64ABIInfo::classify with a successful 3105 /// classification that put one of the two halves in the INTEGER class. 3106 /// 3107 /// It is conservatively correct to return false. 3108 static bool BitsContainNoUserData(QualType Ty, unsigned StartBit, 3109 unsigned EndBit, ASTContext &Context) { 3110 // If the bytes being queried are off the end of the type, there is no user 3111 // data hiding here. This handles analysis of builtins, vectors and other 3112 // types that don't contain interesting padding. 3113 unsigned TySize = (unsigned)Context.getTypeSize(Ty); 3114 if (TySize <= StartBit) 3115 return true; 3116 3117 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) { 3118 unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType()); 3119 unsigned NumElts = (unsigned)AT->getSize().getZExtValue(); 3120 3121 // Check each element to see if the element overlaps with the queried range. 3122 for (unsigned i = 0; i != NumElts; ++i) { 3123 // If the element is after the span we care about, then we're done.. 3124 unsigned EltOffset = i*EltSize; 3125 if (EltOffset >= EndBit) break; 3126 3127 unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0; 3128 if (!BitsContainNoUserData(AT->getElementType(), EltStart, 3129 EndBit-EltOffset, Context)) 3130 return false; 3131 } 3132 // If it overlaps no elements, then it is safe to process as padding. 3133 return true; 3134 } 3135 3136 if (const RecordType *RT = Ty->getAs<RecordType>()) { 3137 const RecordDecl *RD = RT->getDecl(); 3138 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); 3139 3140 // If this is a C++ record, check the bases first. 3141 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 3142 for (const auto &I : CXXRD->bases()) { 3143 assert(!I.isVirtual() && !I.getType()->isDependentType() && 3144 "Unexpected base class!"); 3145 const auto *Base = 3146 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl()); 3147 3148 // If the base is after the span we care about, ignore it. 3149 unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base)); 3150 if (BaseOffset >= EndBit) continue; 3151 3152 unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0; 3153 if (!BitsContainNoUserData(I.getType(), BaseStart, 3154 EndBit-BaseOffset, Context)) 3155 return false; 3156 } 3157 } 3158 3159 // Verify that no field has data that overlaps the region of interest. Yes 3160 // this could be sped up a lot by being smarter about queried fields, 3161 // however we're only looking at structs up to 16 bytes, so we don't care 3162 // much. 3163 unsigned idx = 0; 3164 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 3165 i != e; ++i, ++idx) { 3166 unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx); 3167 3168 // If we found a field after the region we care about, then we're done. 3169 if (FieldOffset >= EndBit) break; 3170 3171 unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0; 3172 if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset, 3173 Context)) 3174 return false; 3175 } 3176 3177 // If nothing in this record overlapped the area of interest, then we're 3178 // clean. 3179 return true; 3180 } 3181 3182 return false; 3183 } 3184 3185 /// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a 3186 /// float member at the specified offset. For example, {int,{float}} has a 3187 /// float at offset 4. It is conservatively correct for this routine to return 3188 /// false. 3189 static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset, 3190 const llvm::DataLayout &TD) { 3191 // Base case if we find a float. 3192 if (IROffset == 0 && IRType->isFloatTy()) 3193 return true; 3194 3195 // If this is a struct, recurse into the field at the specified offset. 3196 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) { 3197 const llvm::StructLayout *SL = TD.getStructLayout(STy); 3198 unsigned Elt = SL->getElementContainingOffset(IROffset); 3199 IROffset -= SL->getElementOffset(Elt); 3200 return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD); 3201 } 3202 3203 // If this is an array, recurse into the field at the specified offset. 3204 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) { 3205 llvm::Type *EltTy = ATy->getElementType(); 3206 unsigned EltSize = TD.getTypeAllocSize(EltTy); 3207 IROffset -= IROffset/EltSize*EltSize; 3208 return ContainsFloatAtOffset(EltTy, IROffset, TD); 3209 } 3210 3211 return false; 3212 } 3213 3214 3215 /// GetSSETypeAtOffset - Return a type that will be passed by the backend in the 3216 /// low 8 bytes of an XMM register, corresponding to the SSE class. 3217 llvm::Type *X86_64ABIInfo:: 3218 GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset, 3219 QualType SourceTy, unsigned SourceOffset) const { 3220 // The only three choices we have are either double, <2 x float>, or float. We 3221 // pass as float if the last 4 bytes is just padding. This happens for 3222 // structs that contain 3 floats. 3223 if (BitsContainNoUserData(SourceTy, SourceOffset*8+32, 3224 SourceOffset*8+64, getContext())) 3225 return llvm::Type::getFloatTy(getVMContext()); 3226 3227 // We want to pass as <2 x float> if the LLVM IR type contains a float at 3228 // offset+0 and offset+4. Walk the LLVM IR type to find out if this is the 3229 // case. 3230 if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) && 3231 ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout())) 3232 return llvm::VectorType::get(llvm::Type::getFloatTy(getVMContext()), 2); 3233 3234 return llvm::Type::getDoubleTy(getVMContext()); 3235 } 3236 3237 3238 /// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in 3239 /// an 8-byte GPR. This means that we either have a scalar or we are talking 3240 /// about the high or low part of an up-to-16-byte struct. This routine picks 3241 /// the best LLVM IR type to represent this, which may be i64 or may be anything 3242 /// else that the backend will pass in a GPR that works better (e.g. i8, %foo*, 3243 /// etc). 3244 /// 3245 /// PrefType is an LLVM IR type that corresponds to (part of) the IR type for 3246 /// the source type. IROffset is an offset in bytes into the LLVM IR type that 3247 /// the 8-byte value references. PrefType may be null. 3248 /// 3249 /// SourceTy is the source-level type for the entire argument. SourceOffset is 3250 /// an offset into this that we're processing (which is always either 0 or 8). 3251 /// 3252 llvm::Type *X86_64ABIInfo:: 3253 GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset, 3254 QualType SourceTy, unsigned SourceOffset) const { 3255 // If we're dealing with an un-offset LLVM IR type, then it means that we're 3256 // returning an 8-byte unit starting with it. See if we can safely use it. 3257 if (IROffset == 0) { 3258 // Pointers and int64's always fill the 8-byte unit. 3259 if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) || 3260 IRType->isIntegerTy(64)) 3261 return IRType; 3262 3263 // If we have a 1/2/4-byte integer, we can use it only if the rest of the 3264 // goodness in the source type is just tail padding. This is allowed to 3265 // kick in for struct {double,int} on the int, but not on 3266 // struct{double,int,int} because we wouldn't return the second int. We 3267 // have to do this analysis on the source type because we can't depend on 3268 // unions being lowered a specific way etc. 3269 if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) || 3270 IRType->isIntegerTy(32) || 3271 (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) { 3272 unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 : 3273 cast<llvm::IntegerType>(IRType)->getBitWidth(); 3274 3275 if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth, 3276 SourceOffset*8+64, getContext())) 3277 return IRType; 3278 } 3279 } 3280 3281 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) { 3282 // If this is a struct, recurse into the field at the specified offset. 3283 const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy); 3284 if (IROffset < SL->getSizeInBytes()) { 3285 unsigned FieldIdx = SL->getElementContainingOffset(IROffset); 3286 IROffset -= SL->getElementOffset(FieldIdx); 3287 3288 return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset, 3289 SourceTy, SourceOffset); 3290 } 3291 } 3292 3293 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) { 3294 llvm::Type *EltTy = ATy->getElementType(); 3295 unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy); 3296 unsigned EltOffset = IROffset/EltSize*EltSize; 3297 return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy, 3298 SourceOffset); 3299 } 3300 3301 // Okay, we don't have any better idea of what to pass, so we pass this in an 3302 // integer register that isn't too big to fit the rest of the struct. 3303 unsigned TySizeInBytes = 3304 (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity(); 3305 3306 assert(TySizeInBytes != SourceOffset && "Empty field?"); 3307 3308 // It is always safe to classify this as an integer type up to i64 that 3309 // isn't larger than the structure. 3310 return llvm::IntegerType::get(getVMContext(), 3311 std::min(TySizeInBytes-SourceOffset, 8U)*8); 3312 } 3313 3314 3315 /// GetX86_64ByValArgumentPair - Given a high and low type that can ideally 3316 /// be used as elements of a two register pair to pass or return, return a 3317 /// first class aggregate to represent them. For example, if the low part of 3318 /// a by-value argument should be passed as i32* and the high part as float, 3319 /// return {i32*, float}. 3320 static llvm::Type * 3321 GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi, 3322 const llvm::DataLayout &TD) { 3323 // In order to correctly satisfy the ABI, we need to the high part to start 3324 // at offset 8. If the high and low parts we inferred are both 4-byte types 3325 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have 3326 // the second element at offset 8. Check for this: 3327 unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo); 3328 unsigned HiAlign = TD.getABITypeAlignment(Hi); 3329 unsigned HiStart = llvm::alignTo(LoSize, HiAlign); 3330 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!"); 3331 3332 // To handle this, we have to increase the size of the low part so that the 3333 // second element will start at an 8 byte offset. We can't increase the size 3334 // of the second element because it might make us access off the end of the 3335 // struct. 3336 if (HiStart != 8) { 3337 // There are usually two sorts of types the ABI generation code can produce 3338 // for the low part of a pair that aren't 8 bytes in size: float or 3339 // i8/i16/i32. This can also include pointers when they are 32-bit (X32 and 3340 // NaCl). 3341 // Promote these to a larger type. 3342 if (Lo->isFloatTy()) 3343 Lo = llvm::Type::getDoubleTy(Lo->getContext()); 3344 else { 3345 assert((Lo->isIntegerTy() || Lo->isPointerTy()) 3346 && "Invalid/unknown lo type"); 3347 Lo = llvm::Type::getInt64Ty(Lo->getContext()); 3348 } 3349 } 3350 3351 llvm::StructType *Result = llvm::StructType::get(Lo, Hi); 3352 3353 // Verify that the second element is at an 8-byte offset. 3354 assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 && 3355 "Invalid x86-64 argument pair!"); 3356 return Result; 3357 } 3358 3359 ABIArgInfo X86_64ABIInfo:: 3360 classifyReturnType(QualType RetTy) const { 3361 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the 3362 // classification algorithm. 3363 X86_64ABIInfo::Class Lo, Hi; 3364 classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true); 3365 3366 // Check some invariants. 3367 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification."); 3368 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification."); 3369 3370 llvm::Type *ResType = nullptr; 3371 switch (Lo) { 3372 case NoClass: 3373 if (Hi == NoClass) 3374 return ABIArgInfo::getIgnore(); 3375 // If the low part is just padding, it takes no register, leave ResType 3376 // null. 3377 assert((Hi == SSE || Hi == Integer || Hi == X87Up) && 3378 "Unknown missing lo part"); 3379 break; 3380 3381 case SSEUp: 3382 case X87Up: 3383 llvm_unreachable("Invalid classification for lo word."); 3384 3385 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via 3386 // hidden argument. 3387 case Memory: 3388 return getIndirectReturnResult(RetTy); 3389 3390 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next 3391 // available register of the sequence %rax, %rdx is used. 3392 case Integer: 3393 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0); 3394 3395 // If we have a sign or zero extended integer, make sure to return Extend 3396 // so that the parameter gets the right LLVM IR attributes. 3397 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) { 3398 // Treat an enum type as its underlying type. 3399 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 3400 RetTy = EnumTy->getDecl()->getIntegerType(); 3401 3402 if (RetTy->isIntegralOrEnumerationType() && 3403 RetTy->isPromotableIntegerType()) 3404 return ABIArgInfo::getExtend(RetTy); 3405 } 3406 break; 3407 3408 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next 3409 // available SSE register of the sequence %xmm0, %xmm1 is used. 3410 case SSE: 3411 ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0); 3412 break; 3413 3414 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is 3415 // returned on the X87 stack in %st0 as 80-bit x87 number. 3416 case X87: 3417 ResType = llvm::Type::getX86_FP80Ty(getVMContext()); 3418 break; 3419 3420 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real 3421 // part of the value is returned in %st0 and the imaginary part in 3422 // %st1. 3423 case ComplexX87: 3424 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification."); 3425 ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()), 3426 llvm::Type::getX86_FP80Ty(getVMContext())); 3427 break; 3428 } 3429 3430 llvm::Type *HighPart = nullptr; 3431 switch (Hi) { 3432 // Memory was handled previously and X87 should 3433 // never occur as a hi class. 3434 case Memory: 3435 case X87: 3436 llvm_unreachable("Invalid classification for hi word."); 3437 3438 case ComplexX87: // Previously handled. 3439 case NoClass: 3440 break; 3441 3442 case Integer: 3443 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8); 3444 if (Lo == NoClass) // Return HighPart at offset 8 in memory. 3445 return ABIArgInfo::getDirect(HighPart, 8); 3446 break; 3447 case SSE: 3448 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8); 3449 if (Lo == NoClass) // Return HighPart at offset 8 in memory. 3450 return ABIArgInfo::getDirect(HighPart, 8); 3451 break; 3452 3453 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte 3454 // is passed in the next available eightbyte chunk if the last used 3455 // vector register. 3456 // 3457 // SSEUP should always be preceded by SSE, just widen. 3458 case SSEUp: 3459 assert(Lo == SSE && "Unexpected SSEUp classification."); 3460 ResType = GetByteVectorType(RetTy); 3461 break; 3462 3463 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is 3464 // returned together with the previous X87 value in %st0. 3465 case X87Up: 3466 // If X87Up is preceded by X87, we don't need to do 3467 // anything. However, in some cases with unions it may not be 3468 // preceded by X87. In such situations we follow gcc and pass the 3469 // extra bits in an SSE reg. 3470 if (Lo != X87) { 3471 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8); 3472 if (Lo == NoClass) // Return HighPart at offset 8 in memory. 3473 return ABIArgInfo::getDirect(HighPart, 8); 3474 } 3475 break; 3476 } 3477 3478 // If a high part was specified, merge it together with the low part. It is 3479 // known to pass in the high eightbyte of the result. We do this by forming a 3480 // first class struct aggregate with the high and low part: {low, high} 3481 if (HighPart) 3482 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout()); 3483 3484 return ABIArgInfo::getDirect(ResType); 3485 } 3486 3487 ABIArgInfo X86_64ABIInfo::classifyArgumentType( 3488 QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE, 3489 bool isNamedArg) 3490 const 3491 { 3492 Ty = useFirstFieldIfTransparentUnion(Ty); 3493 3494 X86_64ABIInfo::Class Lo, Hi; 3495 classify(Ty, 0, Lo, Hi, isNamedArg); 3496 3497 // Check some invariants. 3498 // FIXME: Enforce these by construction. 3499 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification."); 3500 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification."); 3501 3502 neededInt = 0; 3503 neededSSE = 0; 3504 llvm::Type *ResType = nullptr; 3505 switch (Lo) { 3506 case NoClass: 3507 if (Hi == NoClass) 3508 return ABIArgInfo::getIgnore(); 3509 // If the low part is just padding, it takes no register, leave ResType 3510 // null. 3511 assert((Hi == SSE || Hi == Integer || Hi == X87Up) && 3512 "Unknown missing lo part"); 3513 break; 3514 3515 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument 3516 // on the stack. 3517 case Memory: 3518 3519 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or 3520 // COMPLEX_X87, it is passed in memory. 3521 case X87: 3522 case ComplexX87: 3523 if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect) 3524 ++neededInt; 3525 return getIndirectResult(Ty, freeIntRegs); 3526 3527 case SSEUp: 3528 case X87Up: 3529 llvm_unreachable("Invalid classification for lo word."); 3530 3531 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next 3532 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8 3533 // and %r9 is used. 3534 case Integer: 3535 ++neededInt; 3536 3537 // Pick an 8-byte type based on the preferred type. 3538 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0); 3539 3540 // If we have a sign or zero extended integer, make sure to return Extend 3541 // so that the parameter gets the right LLVM IR attributes. 3542 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) { 3543 // Treat an enum type as its underlying type. 3544 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 3545 Ty = EnumTy->getDecl()->getIntegerType(); 3546 3547 if (Ty->isIntegralOrEnumerationType() && 3548 Ty->isPromotableIntegerType()) 3549 return ABIArgInfo::getExtend(Ty); 3550 } 3551 3552 break; 3553 3554 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next 3555 // available SSE register is used, the registers are taken in the 3556 // order from %xmm0 to %xmm7. 3557 case SSE: { 3558 llvm::Type *IRType = CGT.ConvertType(Ty); 3559 ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0); 3560 ++neededSSE; 3561 break; 3562 } 3563 } 3564 3565 llvm::Type *HighPart = nullptr; 3566 switch (Hi) { 3567 // Memory was handled previously, ComplexX87 and X87 should 3568 // never occur as hi classes, and X87Up must be preceded by X87, 3569 // which is passed in memory. 3570 case Memory: 3571 case X87: 3572 case ComplexX87: 3573 llvm_unreachable("Invalid classification for hi word."); 3574 3575 case NoClass: break; 3576 3577 case Integer: 3578 ++neededInt; 3579 // Pick an 8-byte type based on the preferred type. 3580 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8); 3581 3582 if (Lo == NoClass) // Pass HighPart at offset 8 in memory. 3583 return ABIArgInfo::getDirect(HighPart, 8); 3584 break; 3585 3586 // X87Up generally doesn't occur here (long double is passed in 3587 // memory), except in situations involving unions. 3588 case X87Up: 3589 case SSE: 3590 HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8); 3591 3592 if (Lo == NoClass) // Pass HighPart at offset 8 in memory. 3593 return ABIArgInfo::getDirect(HighPart, 8); 3594 3595 ++neededSSE; 3596 break; 3597 3598 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the 3599 // eightbyte is passed in the upper half of the last used SSE 3600 // register. This only happens when 128-bit vectors are passed. 3601 case SSEUp: 3602 assert(Lo == SSE && "Unexpected SSEUp classification"); 3603 ResType = GetByteVectorType(Ty); 3604 break; 3605 } 3606 3607 // If a high part was specified, merge it together with the low part. It is 3608 // known to pass in the high eightbyte of the result. We do this by forming a 3609 // first class struct aggregate with the high and low part: {low, high} 3610 if (HighPart) 3611 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout()); 3612 3613 return ABIArgInfo::getDirect(ResType); 3614 } 3615 3616 ABIArgInfo 3617 X86_64ABIInfo::classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt, 3618 unsigned &NeededSSE) const { 3619 auto RT = Ty->getAs<RecordType>(); 3620 assert(RT && "classifyRegCallStructType only valid with struct types"); 3621 3622 if (RT->getDecl()->hasFlexibleArrayMember()) 3623 return getIndirectReturnResult(Ty); 3624 3625 // Sum up bases 3626 if (auto CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl())) { 3627 if (CXXRD->isDynamicClass()) { 3628 NeededInt = NeededSSE = 0; 3629 return getIndirectReturnResult(Ty); 3630 } 3631 3632 for (const auto &I : CXXRD->bases()) 3633 if (classifyRegCallStructTypeImpl(I.getType(), NeededInt, NeededSSE) 3634 .isIndirect()) { 3635 NeededInt = NeededSSE = 0; 3636 return getIndirectReturnResult(Ty); 3637 } 3638 } 3639 3640 // Sum up members 3641 for (const auto *FD : RT->getDecl()->fields()) { 3642 if (FD->getType()->isRecordType() && !FD->getType()->isUnionType()) { 3643 if (classifyRegCallStructTypeImpl(FD->getType(), NeededInt, NeededSSE) 3644 .isIndirect()) { 3645 NeededInt = NeededSSE = 0; 3646 return getIndirectReturnResult(Ty); 3647 } 3648 } else { 3649 unsigned LocalNeededInt, LocalNeededSSE; 3650 if (classifyArgumentType(FD->getType(), UINT_MAX, LocalNeededInt, 3651 LocalNeededSSE, true) 3652 .isIndirect()) { 3653 NeededInt = NeededSSE = 0; 3654 return getIndirectReturnResult(Ty); 3655 } 3656 NeededInt += LocalNeededInt; 3657 NeededSSE += LocalNeededSSE; 3658 } 3659 } 3660 3661 return ABIArgInfo::getDirect(); 3662 } 3663 3664 ABIArgInfo X86_64ABIInfo::classifyRegCallStructType(QualType Ty, 3665 unsigned &NeededInt, 3666 unsigned &NeededSSE) const { 3667 3668 NeededInt = 0; 3669 NeededSSE = 0; 3670 3671 return classifyRegCallStructTypeImpl(Ty, NeededInt, NeededSSE); 3672 } 3673 3674 void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const { 3675 3676 const unsigned CallingConv = FI.getCallingConvention(); 3677 // It is possible to force Win64 calling convention on any x86_64 target by 3678 // using __attribute__((ms_abi)). In such case to correctly emit Win64 3679 // compatible code delegate this call to WinX86_64ABIInfo::computeInfo. 3680 if (CallingConv == llvm::CallingConv::Win64) { 3681 WinX86_64ABIInfo Win64ABIInfo(CGT, AVXLevel); 3682 Win64ABIInfo.computeInfo(FI); 3683 return; 3684 } 3685 3686 bool IsRegCall = CallingConv == llvm::CallingConv::X86_RegCall; 3687 3688 // Keep track of the number of assigned registers. 3689 unsigned FreeIntRegs = IsRegCall ? 11 : 6; 3690 unsigned FreeSSERegs = IsRegCall ? 16 : 8; 3691 unsigned NeededInt, NeededSSE; 3692 3693 if (!::classifyReturnType(getCXXABI(), FI, *this)) { 3694 if (IsRegCall && FI.getReturnType()->getTypePtr()->isRecordType() && 3695 !FI.getReturnType()->getTypePtr()->isUnionType()) { 3696 FI.getReturnInfo() = 3697 classifyRegCallStructType(FI.getReturnType(), NeededInt, NeededSSE); 3698 if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) { 3699 FreeIntRegs -= NeededInt; 3700 FreeSSERegs -= NeededSSE; 3701 } else { 3702 FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType()); 3703 } 3704 } else if (IsRegCall && FI.getReturnType()->getAs<ComplexType>()) { 3705 // Complex Long Double Type is passed in Memory when Regcall 3706 // calling convention is used. 3707 const ComplexType *CT = FI.getReturnType()->getAs<ComplexType>(); 3708 if (getContext().getCanonicalType(CT->getElementType()) == 3709 getContext().LongDoubleTy) 3710 FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType()); 3711 } else 3712 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 3713 } 3714 3715 // If the return value is indirect, then the hidden argument is consuming one 3716 // integer register. 3717 if (FI.getReturnInfo().isIndirect()) 3718 --FreeIntRegs; 3719 3720 // The chain argument effectively gives us another free register. 3721 if (FI.isChainCall()) 3722 ++FreeIntRegs; 3723 3724 unsigned NumRequiredArgs = FI.getNumRequiredArgs(); 3725 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers 3726 // get assigned (in left-to-right order) for passing as follows... 3727 unsigned ArgNo = 0; 3728 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end(); 3729 it != ie; ++it, ++ArgNo) { 3730 bool IsNamedArg = ArgNo < NumRequiredArgs; 3731 3732 if (IsRegCall && it->type->isStructureOrClassType()) 3733 it->info = classifyRegCallStructType(it->type, NeededInt, NeededSSE); 3734 else 3735 it->info = classifyArgumentType(it->type, FreeIntRegs, NeededInt, 3736 NeededSSE, IsNamedArg); 3737 3738 // AMD64-ABI 3.2.3p3: If there are no registers available for any 3739 // eightbyte of an argument, the whole argument is passed on the 3740 // stack. If registers have already been assigned for some 3741 // eightbytes of such an argument, the assignments get reverted. 3742 if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) { 3743 FreeIntRegs -= NeededInt; 3744 FreeSSERegs -= NeededSSE; 3745 } else { 3746 it->info = getIndirectResult(it->type, FreeIntRegs); 3747 } 3748 } 3749 } 3750 3751 static Address EmitX86_64VAArgFromMemory(CodeGenFunction &CGF, 3752 Address VAListAddr, QualType Ty) { 3753 Address overflow_arg_area_p = 3754 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_p"); 3755 llvm::Value *overflow_arg_area = 3756 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area"); 3757 3758 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16 3759 // byte boundary if alignment needed by type exceeds 8 byte boundary. 3760 // It isn't stated explicitly in the standard, but in practice we use 3761 // alignment greater than 16 where necessary. 3762 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty); 3763 if (Align > CharUnits::fromQuantity(8)) { 3764 overflow_arg_area = emitRoundPointerUpToAlignment(CGF, overflow_arg_area, 3765 Align); 3766 } 3767 3768 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area. 3769 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty); 3770 llvm::Value *Res = 3771 CGF.Builder.CreateBitCast(overflow_arg_area, 3772 llvm::PointerType::getUnqual(LTy)); 3773 3774 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to: 3775 // l->overflow_arg_area + sizeof(type). 3776 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to 3777 // an 8 byte boundary. 3778 3779 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8; 3780 llvm::Value *Offset = 3781 llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7); 3782 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset, 3783 "overflow_arg_area.next"); 3784 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p); 3785 3786 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type. 3787 return Address(Res, Align); 3788 } 3789 3790 Address X86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 3791 QualType Ty) const { 3792 // Assume that va_list type is correct; should be pointer to LLVM type: 3793 // struct { 3794 // i32 gp_offset; 3795 // i32 fp_offset; 3796 // i8* overflow_arg_area; 3797 // i8* reg_save_area; 3798 // }; 3799 unsigned neededInt, neededSSE; 3800 3801 Ty = getContext().getCanonicalType(Ty); 3802 ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE, 3803 /*isNamedArg*/false); 3804 3805 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed 3806 // in the registers. If not go to step 7. 3807 if (!neededInt && !neededSSE) 3808 return EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty); 3809 3810 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of 3811 // general purpose registers needed to pass type and num_fp to hold 3812 // the number of floating point registers needed. 3813 3814 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into 3815 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or 3816 // l->fp_offset > 304 - num_fp * 16 go to step 7. 3817 // 3818 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of 3819 // register save space). 3820 3821 llvm::Value *InRegs = nullptr; 3822 Address gp_offset_p = Address::invalid(), fp_offset_p = Address::invalid(); 3823 llvm::Value *gp_offset = nullptr, *fp_offset = nullptr; 3824 if (neededInt) { 3825 gp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "gp_offset_p"); 3826 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset"); 3827 InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8); 3828 InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp"); 3829 } 3830 3831 if (neededSSE) { 3832 fp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 1, "fp_offset_p"); 3833 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset"); 3834 llvm::Value *FitsInFP = 3835 llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16); 3836 FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp"); 3837 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP; 3838 } 3839 3840 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg"); 3841 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem"); 3842 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end"); 3843 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock); 3844 3845 // Emit code to load the value if it was passed in registers. 3846 3847 CGF.EmitBlock(InRegBlock); 3848 3849 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with 3850 // an offset of l->gp_offset and/or l->fp_offset. This may require 3851 // copying to a temporary location in case the parameter is passed 3852 // in different register classes or requires an alignment greater 3853 // than 8 for general purpose registers and 16 for XMM registers. 3854 // 3855 // FIXME: This really results in shameful code when we end up needing to 3856 // collect arguments from different places; often what should result in a 3857 // simple assembling of a structure from scattered addresses has many more 3858 // loads than necessary. Can we clean this up? 3859 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty); 3860 llvm::Value *RegSaveArea = CGF.Builder.CreateLoad( 3861 CGF.Builder.CreateStructGEP(VAListAddr, 3), "reg_save_area"); 3862 3863 Address RegAddr = Address::invalid(); 3864 if (neededInt && neededSSE) { 3865 // FIXME: Cleanup. 3866 assert(AI.isDirect() && "Unexpected ABI info for mixed regs"); 3867 llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType()); 3868 Address Tmp = CGF.CreateMemTemp(Ty); 3869 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST); 3870 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs"); 3871 llvm::Type *TyLo = ST->getElementType(0); 3872 llvm::Type *TyHi = ST->getElementType(1); 3873 assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) && 3874 "Unexpected ABI info for mixed regs"); 3875 llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo); 3876 llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi); 3877 llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegSaveArea, gp_offset); 3878 llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegSaveArea, fp_offset); 3879 llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr; 3880 llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr; 3881 3882 // Copy the first element. 3883 // FIXME: Our choice of alignment here and below is probably pessimistic. 3884 llvm::Value *V = CGF.Builder.CreateAlignedLoad( 3885 TyLo, CGF.Builder.CreateBitCast(RegLoAddr, PTyLo), 3886 CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyLo))); 3887 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0)); 3888 3889 // Copy the second element. 3890 V = CGF.Builder.CreateAlignedLoad( 3891 TyHi, CGF.Builder.CreateBitCast(RegHiAddr, PTyHi), 3892 CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyHi))); 3893 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1)); 3894 3895 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy); 3896 } else if (neededInt) { 3897 RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, gp_offset), 3898 CharUnits::fromQuantity(8)); 3899 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy); 3900 3901 // Copy to a temporary if necessary to ensure the appropriate alignment. 3902 std::pair<CharUnits, CharUnits> SizeAlign = 3903 getContext().getTypeInfoInChars(Ty); 3904 uint64_t TySize = SizeAlign.first.getQuantity(); 3905 CharUnits TyAlign = SizeAlign.second; 3906 3907 // Copy into a temporary if the type is more aligned than the 3908 // register save area. 3909 if (TyAlign.getQuantity() > 8) { 3910 Address Tmp = CGF.CreateMemTemp(Ty); 3911 CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, false); 3912 RegAddr = Tmp; 3913 } 3914 3915 } else if (neededSSE == 1) { 3916 RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset), 3917 CharUnits::fromQuantity(16)); 3918 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy); 3919 } else { 3920 assert(neededSSE == 2 && "Invalid number of needed registers!"); 3921 // SSE registers are spaced 16 bytes apart in the register save 3922 // area, we need to collect the two eightbytes together. 3923 // The ABI isn't explicit about this, but it seems reasonable 3924 // to assume that the slots are 16-byte aligned, since the stack is 3925 // naturally 16-byte aligned and the prologue is expected to store 3926 // all the SSE registers to the RSA. 3927 Address RegAddrLo = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset), 3928 CharUnits::fromQuantity(16)); 3929 Address RegAddrHi = 3930 CGF.Builder.CreateConstInBoundsByteGEP(RegAddrLo, 3931 CharUnits::fromQuantity(16)); 3932 llvm::Type *ST = AI.canHaveCoerceToType() 3933 ? AI.getCoerceToType() 3934 : llvm::StructType::get(CGF.DoubleTy, CGF.DoubleTy); 3935 llvm::Value *V; 3936 Address Tmp = CGF.CreateMemTemp(Ty); 3937 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST); 3938 V = CGF.Builder.CreateLoad(CGF.Builder.CreateElementBitCast( 3939 RegAddrLo, ST->getStructElementType(0))); 3940 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0)); 3941 V = CGF.Builder.CreateLoad(CGF.Builder.CreateElementBitCast( 3942 RegAddrHi, ST->getStructElementType(1))); 3943 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1)); 3944 3945 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy); 3946 } 3947 3948 // AMD64-ABI 3.5.7p5: Step 5. Set: 3949 // l->gp_offset = l->gp_offset + num_gp * 8 3950 // l->fp_offset = l->fp_offset + num_fp * 16. 3951 if (neededInt) { 3952 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8); 3953 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset), 3954 gp_offset_p); 3955 } 3956 if (neededSSE) { 3957 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16); 3958 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset), 3959 fp_offset_p); 3960 } 3961 CGF.EmitBranch(ContBlock); 3962 3963 // Emit code to load the value if it was passed in memory. 3964 3965 CGF.EmitBlock(InMemBlock); 3966 Address MemAddr = EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty); 3967 3968 // Return the appropriate result. 3969 3970 CGF.EmitBlock(ContBlock); 3971 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, MemAddr, InMemBlock, 3972 "vaarg.addr"); 3973 return ResAddr; 3974 } 3975 3976 Address X86_64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr, 3977 QualType Ty) const { 3978 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false, 3979 CGF.getContext().getTypeInfoInChars(Ty), 3980 CharUnits::fromQuantity(8), 3981 /*allowHigherAlign*/ false); 3982 } 3983 3984 ABIArgInfo 3985 WinX86_64ABIInfo::reclassifyHvaArgType(QualType Ty, unsigned &FreeSSERegs, 3986 const ABIArgInfo ¤t) const { 3987 // Assumes vectorCall calling convention. 3988 const Type *Base = nullptr; 3989 uint64_t NumElts = 0; 3990 3991 if (!Ty->isBuiltinType() && !Ty->isVectorType() && 3992 isHomogeneousAggregate(Ty, Base, NumElts) && FreeSSERegs >= NumElts) { 3993 FreeSSERegs -= NumElts; 3994 return getDirectX86Hva(); 3995 } 3996 return current; 3997 } 3998 3999 ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, unsigned &FreeSSERegs, 4000 bool IsReturnType, bool IsVectorCall, 4001 bool IsRegCall) const { 4002 4003 if (Ty->isVoidType()) 4004 return ABIArgInfo::getIgnore(); 4005 4006 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 4007 Ty = EnumTy->getDecl()->getIntegerType(); 4008 4009 TypeInfo Info = getContext().getTypeInfo(Ty); 4010 uint64_t Width = Info.Width; 4011 CharUnits Align = getContext().toCharUnitsFromBits(Info.Align); 4012 4013 const RecordType *RT = Ty->getAs<RecordType>(); 4014 if (RT) { 4015 if (!IsReturnType) { 4016 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI())) 4017 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 4018 } 4019 4020 if (RT->getDecl()->hasFlexibleArrayMember()) 4021 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 4022 4023 } 4024 4025 const Type *Base = nullptr; 4026 uint64_t NumElts = 0; 4027 // vectorcall adds the concept of a homogenous vector aggregate, similar to 4028 // other targets. 4029 if ((IsVectorCall || IsRegCall) && 4030 isHomogeneousAggregate(Ty, Base, NumElts)) { 4031 if (IsRegCall) { 4032 if (FreeSSERegs >= NumElts) { 4033 FreeSSERegs -= NumElts; 4034 if (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType()) 4035 return ABIArgInfo::getDirect(); 4036 return ABIArgInfo::getExpand(); 4037 } 4038 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false); 4039 } else if (IsVectorCall) { 4040 if (FreeSSERegs >= NumElts && 4041 (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())) { 4042 FreeSSERegs -= NumElts; 4043 return ABIArgInfo::getDirect(); 4044 } else if (IsReturnType) { 4045 return ABIArgInfo::getExpand(); 4046 } else if (!Ty->isBuiltinType() && !Ty->isVectorType()) { 4047 // HVAs are delayed and reclassified in the 2nd step. 4048 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false); 4049 } 4050 } 4051 } 4052 4053 if (Ty->isMemberPointerType()) { 4054 // If the member pointer is represented by an LLVM int or ptr, pass it 4055 // directly. 4056 llvm::Type *LLTy = CGT.ConvertType(Ty); 4057 if (LLTy->isPointerTy() || LLTy->isIntegerTy()) 4058 return ABIArgInfo::getDirect(); 4059 } 4060 4061 if (RT || Ty->isAnyComplexType() || Ty->isMemberPointerType()) { 4062 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is 4063 // not 1, 2, 4, or 8 bytes, must be passed by reference." 4064 if (Width > 64 || !llvm::isPowerOf2_64(Width)) 4065 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 4066 4067 // Otherwise, coerce it to a small integer. 4068 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Width)); 4069 } 4070 4071 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) { 4072 switch (BT->getKind()) { 4073 case BuiltinType::Bool: 4074 // Bool type is always extended to the ABI, other builtin types are not 4075 // extended. 4076 return ABIArgInfo::getExtend(Ty); 4077 4078 case BuiltinType::LongDouble: 4079 // Mingw64 GCC uses the old 80 bit extended precision floating point 4080 // unit. It passes them indirectly through memory. 4081 if (IsMingw64) { 4082 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat(); 4083 if (LDF == &llvm::APFloat::x87DoubleExtended()) 4084 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false); 4085 } 4086 break; 4087 4088 case BuiltinType::Int128: 4089 case BuiltinType::UInt128: 4090 // If it's a parameter type, the normal ABI rule is that arguments larger 4091 // than 8 bytes are passed indirectly. GCC follows it. We follow it too, 4092 // even though it isn't particularly efficient. 4093 if (!IsReturnType) 4094 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false); 4095 4096 // Mingw64 GCC returns i128 in XMM0. Coerce to v2i64 to handle that. 4097 // Clang matches them for compatibility. 4098 return ABIArgInfo::getDirect( 4099 llvm::VectorType::get(llvm::Type::getInt64Ty(getVMContext()), 2)); 4100 4101 default: 4102 break; 4103 } 4104 } 4105 4106 if (Ty->isExtIntType()) { 4107 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is 4108 // not 1, 2, 4, or 8 bytes, must be passed by reference." 4109 // However, non-power-of-two _ExtInts will be passed as 1,2,4 or 8 bytes 4110 // anyway as long is it fits in them, so we don't have to check the power of 4111 // 2. 4112 if (Width <= 64) 4113 return ABIArgInfo::getDirect(); 4114 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false); 4115 } 4116 4117 return ABIArgInfo::getDirect(); 4118 } 4119 4120 void WinX86_64ABIInfo::computeVectorCallArgs(CGFunctionInfo &FI, 4121 unsigned FreeSSERegs, 4122 bool IsVectorCall, 4123 bool IsRegCall) const { 4124 unsigned Count = 0; 4125 for (auto &I : FI.arguments()) { 4126 // Vectorcall in x64 only permits the first 6 arguments to be passed 4127 // as XMM/YMM registers. 4128 if (Count < VectorcallMaxParamNumAsReg) 4129 I.info = classify(I.type, FreeSSERegs, false, IsVectorCall, IsRegCall); 4130 else { 4131 // Since these cannot be passed in registers, pretend no registers 4132 // are left. 4133 unsigned ZeroSSERegsAvail = 0; 4134 I.info = classify(I.type, /*FreeSSERegs=*/ZeroSSERegsAvail, false, 4135 IsVectorCall, IsRegCall); 4136 } 4137 ++Count; 4138 } 4139 4140 for (auto &I : FI.arguments()) { 4141 I.info = reclassifyHvaArgType(I.type, FreeSSERegs, I.info); 4142 } 4143 } 4144 4145 void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const { 4146 const unsigned CC = FI.getCallingConvention(); 4147 bool IsVectorCall = CC == llvm::CallingConv::X86_VectorCall; 4148 bool IsRegCall = CC == llvm::CallingConv::X86_RegCall; 4149 4150 // If __attribute__((sysv_abi)) is in use, use the SysV argument 4151 // classification rules. 4152 if (CC == llvm::CallingConv::X86_64_SysV) { 4153 X86_64ABIInfo SysVABIInfo(CGT, AVXLevel); 4154 SysVABIInfo.computeInfo(FI); 4155 return; 4156 } 4157 4158 unsigned FreeSSERegs = 0; 4159 if (IsVectorCall) { 4160 // We can use up to 4 SSE return registers with vectorcall. 4161 FreeSSERegs = 4; 4162 } else if (IsRegCall) { 4163 // RegCall gives us 16 SSE registers. 4164 FreeSSERegs = 16; 4165 } 4166 4167 if (!getCXXABI().classifyReturnType(FI)) 4168 FI.getReturnInfo() = classify(FI.getReturnType(), FreeSSERegs, true, 4169 IsVectorCall, IsRegCall); 4170 4171 if (IsVectorCall) { 4172 // We can use up to 6 SSE register parameters with vectorcall. 4173 FreeSSERegs = 6; 4174 } else if (IsRegCall) { 4175 // RegCall gives us 16 SSE registers, we can reuse the return registers. 4176 FreeSSERegs = 16; 4177 } 4178 4179 if (IsVectorCall) { 4180 computeVectorCallArgs(FI, FreeSSERegs, IsVectorCall, IsRegCall); 4181 } else { 4182 for (auto &I : FI.arguments()) 4183 I.info = classify(I.type, FreeSSERegs, false, IsVectorCall, IsRegCall); 4184 } 4185 4186 } 4187 4188 Address WinX86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 4189 QualType Ty) const { 4190 4191 bool IsIndirect = false; 4192 4193 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is 4194 // not 1, 2, 4, or 8 bytes, must be passed by reference." 4195 if (isAggregateTypeForABI(Ty) || Ty->isMemberPointerType()) { 4196 uint64_t Width = getContext().getTypeSize(Ty); 4197 IsIndirect = Width > 64 || !llvm::isPowerOf2_64(Width); 4198 } 4199 4200 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, 4201 CGF.getContext().getTypeInfoInChars(Ty), 4202 CharUnits::fromQuantity(8), 4203 /*allowHigherAlign*/ false); 4204 } 4205 4206 // PowerPC-32 4207 namespace { 4208 /// PPC32_SVR4_ABIInfo - The 32-bit PowerPC ELF (SVR4) ABI information. 4209 class PPC32_SVR4_ABIInfo : public DefaultABIInfo { 4210 bool IsSoftFloatABI; 4211 bool IsRetSmallStructInRegABI; 4212 4213 CharUnits getParamTypeAlignment(QualType Ty) const; 4214 4215 public: 4216 PPC32_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, bool SoftFloatABI, 4217 bool RetSmallStructInRegABI) 4218 : DefaultABIInfo(CGT), IsSoftFloatABI(SoftFloatABI), 4219 IsRetSmallStructInRegABI(RetSmallStructInRegABI) {} 4220 4221 ABIArgInfo classifyReturnType(QualType RetTy) const; 4222 4223 void computeInfo(CGFunctionInfo &FI) const override { 4224 if (!getCXXABI().classifyReturnType(FI)) 4225 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 4226 for (auto &I : FI.arguments()) 4227 I.info = classifyArgumentType(I.type); 4228 } 4229 4230 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 4231 QualType Ty) const override; 4232 }; 4233 4234 class PPC32TargetCodeGenInfo : public TargetCodeGenInfo { 4235 public: 4236 PPC32TargetCodeGenInfo(CodeGenTypes &CGT, bool SoftFloatABI, 4237 bool RetSmallStructInRegABI) 4238 : TargetCodeGenInfo(std::make_unique<PPC32_SVR4_ABIInfo>( 4239 CGT, SoftFloatABI, RetSmallStructInRegABI)) {} 4240 4241 static bool isStructReturnInRegABI(const llvm::Triple &Triple, 4242 const CodeGenOptions &Opts); 4243 4244 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 4245 // This is recovered from gcc output. 4246 return 1; // r1 is the dedicated stack pointer 4247 } 4248 4249 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 4250 llvm::Value *Address) const override; 4251 }; 4252 } 4253 4254 CharUnits PPC32_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const { 4255 // Complex types are passed just like their elements. 4256 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) 4257 Ty = CTy->getElementType(); 4258 4259 if (Ty->isVectorType()) 4260 return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16 4261 : 4); 4262 4263 // For single-element float/vector structs, we consider the whole type 4264 // to have the same alignment requirements as its single element. 4265 const Type *AlignTy = nullptr; 4266 if (const Type *EltType = isSingleElementStruct(Ty, getContext())) { 4267 const BuiltinType *BT = EltType->getAs<BuiltinType>(); 4268 if ((EltType->isVectorType() && getContext().getTypeSize(EltType) == 128) || 4269 (BT && BT->isFloatingPoint())) 4270 AlignTy = EltType; 4271 } 4272 4273 if (AlignTy) 4274 return CharUnits::fromQuantity(AlignTy->isVectorType() ? 16 : 4); 4275 return CharUnits::fromQuantity(4); 4276 } 4277 4278 ABIArgInfo PPC32_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const { 4279 uint64_t Size; 4280 4281 // -msvr4-struct-return puts small aggregates in GPR3 and GPR4. 4282 if (isAggregateTypeForABI(RetTy) && IsRetSmallStructInRegABI && 4283 (Size = getContext().getTypeSize(RetTy)) <= 64) { 4284 // System V ABI (1995), page 3-22, specified: 4285 // > A structure or union whose size is less than or equal to 8 bytes 4286 // > shall be returned in r3 and r4, as if it were first stored in the 4287 // > 8-byte aligned memory area and then the low addressed word were 4288 // > loaded into r3 and the high-addressed word into r4. Bits beyond 4289 // > the last member of the structure or union are not defined. 4290 // 4291 // GCC for big-endian PPC32 inserts the pad before the first member, 4292 // not "beyond the last member" of the struct. To stay compatible 4293 // with GCC, we coerce the struct to an integer of the same size. 4294 // LLVM will extend it and return i32 in r3, or i64 in r3:r4. 4295 if (Size == 0) 4296 return ABIArgInfo::getIgnore(); 4297 else { 4298 llvm::Type *CoerceTy = llvm::Type::getIntNTy(getVMContext(), Size); 4299 return ABIArgInfo::getDirect(CoerceTy); 4300 } 4301 } 4302 4303 return DefaultABIInfo::classifyReturnType(RetTy); 4304 } 4305 4306 // TODO: this implementation is now likely redundant with 4307 // DefaultABIInfo::EmitVAArg. 4308 Address PPC32_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAList, 4309 QualType Ty) const { 4310 if (getTarget().getTriple().isOSDarwin()) { 4311 auto TI = getContext().getTypeInfoInChars(Ty); 4312 TI.second = getParamTypeAlignment(Ty); 4313 4314 CharUnits SlotSize = CharUnits::fromQuantity(4); 4315 return emitVoidPtrVAArg(CGF, VAList, Ty, 4316 classifyArgumentType(Ty).isIndirect(), TI, SlotSize, 4317 /*AllowHigherAlign=*/true); 4318 } 4319 4320 const unsigned OverflowLimit = 8; 4321 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) { 4322 // TODO: Implement this. For now ignore. 4323 (void)CTy; 4324 return Address::invalid(); // FIXME? 4325 } 4326 4327 // struct __va_list_tag { 4328 // unsigned char gpr; 4329 // unsigned char fpr; 4330 // unsigned short reserved; 4331 // void *overflow_arg_area; 4332 // void *reg_save_area; 4333 // }; 4334 4335 bool isI64 = Ty->isIntegerType() && getContext().getTypeSize(Ty) == 64; 4336 bool isInt = 4337 Ty->isIntegerType() || Ty->isPointerType() || Ty->isAggregateType(); 4338 bool isF64 = Ty->isFloatingType() && getContext().getTypeSize(Ty) == 64; 4339 4340 // All aggregates are passed indirectly? That doesn't seem consistent 4341 // with the argument-lowering code. 4342 bool isIndirect = Ty->isAggregateType(); 4343 4344 CGBuilderTy &Builder = CGF.Builder; 4345 4346 // The calling convention either uses 1-2 GPRs or 1 FPR. 4347 Address NumRegsAddr = Address::invalid(); 4348 if (isInt || IsSoftFloatABI) { 4349 NumRegsAddr = Builder.CreateStructGEP(VAList, 0, "gpr"); 4350 } else { 4351 NumRegsAddr = Builder.CreateStructGEP(VAList, 1, "fpr"); 4352 } 4353 4354 llvm::Value *NumRegs = Builder.CreateLoad(NumRegsAddr, "numUsedRegs"); 4355 4356 // "Align" the register count when TY is i64. 4357 if (isI64 || (isF64 && IsSoftFloatABI)) { 4358 NumRegs = Builder.CreateAdd(NumRegs, Builder.getInt8(1)); 4359 NumRegs = Builder.CreateAnd(NumRegs, Builder.getInt8((uint8_t) ~1U)); 4360 } 4361 4362 llvm::Value *CC = 4363 Builder.CreateICmpULT(NumRegs, Builder.getInt8(OverflowLimit), "cond"); 4364 4365 llvm::BasicBlock *UsingRegs = CGF.createBasicBlock("using_regs"); 4366 llvm::BasicBlock *UsingOverflow = CGF.createBasicBlock("using_overflow"); 4367 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont"); 4368 4369 Builder.CreateCondBr(CC, UsingRegs, UsingOverflow); 4370 4371 llvm::Type *DirectTy = CGF.ConvertType(Ty); 4372 if (isIndirect) DirectTy = DirectTy->getPointerTo(0); 4373 4374 // Case 1: consume registers. 4375 Address RegAddr = Address::invalid(); 4376 { 4377 CGF.EmitBlock(UsingRegs); 4378 4379 Address RegSaveAreaPtr = Builder.CreateStructGEP(VAList, 4); 4380 RegAddr = Address(Builder.CreateLoad(RegSaveAreaPtr), 4381 CharUnits::fromQuantity(8)); 4382 assert(RegAddr.getElementType() == CGF.Int8Ty); 4383 4384 // Floating-point registers start after the general-purpose registers. 4385 if (!(isInt || IsSoftFloatABI)) { 4386 RegAddr = Builder.CreateConstInBoundsByteGEP(RegAddr, 4387 CharUnits::fromQuantity(32)); 4388 } 4389 4390 // Get the address of the saved value by scaling the number of 4391 // registers we've used by the number of 4392 CharUnits RegSize = CharUnits::fromQuantity((isInt || IsSoftFloatABI) ? 4 : 8); 4393 llvm::Value *RegOffset = 4394 Builder.CreateMul(NumRegs, Builder.getInt8(RegSize.getQuantity())); 4395 RegAddr = Address(Builder.CreateInBoundsGEP(CGF.Int8Ty, 4396 RegAddr.getPointer(), RegOffset), 4397 RegAddr.getAlignment().alignmentOfArrayElement(RegSize)); 4398 RegAddr = Builder.CreateElementBitCast(RegAddr, DirectTy); 4399 4400 // Increase the used-register count. 4401 NumRegs = 4402 Builder.CreateAdd(NumRegs, 4403 Builder.getInt8((isI64 || (isF64 && IsSoftFloatABI)) ? 2 : 1)); 4404 Builder.CreateStore(NumRegs, NumRegsAddr); 4405 4406 CGF.EmitBranch(Cont); 4407 } 4408 4409 // Case 2: consume space in the overflow area. 4410 Address MemAddr = Address::invalid(); 4411 { 4412 CGF.EmitBlock(UsingOverflow); 4413 4414 Builder.CreateStore(Builder.getInt8(OverflowLimit), NumRegsAddr); 4415 4416 // Everything in the overflow area is rounded up to a size of at least 4. 4417 CharUnits OverflowAreaAlign = CharUnits::fromQuantity(4); 4418 4419 CharUnits Size; 4420 if (!isIndirect) { 4421 auto TypeInfo = CGF.getContext().getTypeInfoInChars(Ty); 4422 Size = TypeInfo.first.alignTo(OverflowAreaAlign); 4423 } else { 4424 Size = CGF.getPointerSize(); 4425 } 4426 4427 Address OverflowAreaAddr = Builder.CreateStructGEP(VAList, 3); 4428 Address OverflowArea(Builder.CreateLoad(OverflowAreaAddr, "argp.cur"), 4429 OverflowAreaAlign); 4430 // Round up address of argument to alignment 4431 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty); 4432 if (Align > OverflowAreaAlign) { 4433 llvm::Value *Ptr = OverflowArea.getPointer(); 4434 OverflowArea = Address(emitRoundPointerUpToAlignment(CGF, Ptr, Align), 4435 Align); 4436 } 4437 4438 MemAddr = Builder.CreateElementBitCast(OverflowArea, DirectTy); 4439 4440 // Increase the overflow area. 4441 OverflowArea = Builder.CreateConstInBoundsByteGEP(OverflowArea, Size); 4442 Builder.CreateStore(OverflowArea.getPointer(), OverflowAreaAddr); 4443 CGF.EmitBranch(Cont); 4444 } 4445 4446 CGF.EmitBlock(Cont); 4447 4448 // Merge the cases with a phi. 4449 Address Result = emitMergePHI(CGF, RegAddr, UsingRegs, MemAddr, UsingOverflow, 4450 "vaarg.addr"); 4451 4452 // Load the pointer if the argument was passed indirectly. 4453 if (isIndirect) { 4454 Result = Address(Builder.CreateLoad(Result, "aggr"), 4455 getContext().getTypeAlignInChars(Ty)); 4456 } 4457 4458 return Result; 4459 } 4460 4461 bool PPC32TargetCodeGenInfo::isStructReturnInRegABI( 4462 const llvm::Triple &Triple, const CodeGenOptions &Opts) { 4463 assert(Triple.getArch() == llvm::Triple::ppc); 4464 4465 switch (Opts.getStructReturnConvention()) { 4466 case CodeGenOptions::SRCK_Default: 4467 break; 4468 case CodeGenOptions::SRCK_OnStack: // -maix-struct-return 4469 return false; 4470 case CodeGenOptions::SRCK_InRegs: // -msvr4-struct-return 4471 return true; 4472 } 4473 4474 if (Triple.isOSBinFormatELF() && !Triple.isOSLinux()) 4475 return true; 4476 4477 return false; 4478 } 4479 4480 bool 4481 PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 4482 llvm::Value *Address) const { 4483 // This is calculated from the LLVM and GCC tables and verified 4484 // against gcc output. AFAIK all ABIs use the same encoding. 4485 4486 CodeGen::CGBuilderTy &Builder = CGF.Builder; 4487 4488 llvm::IntegerType *i8 = CGF.Int8Ty; 4489 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4); 4490 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8); 4491 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16); 4492 4493 // 0-31: r0-31, the 4-byte general-purpose registers 4494 AssignToArrayRange(Builder, Address, Four8, 0, 31); 4495 4496 // 32-63: fp0-31, the 8-byte floating-point registers 4497 AssignToArrayRange(Builder, Address, Eight8, 32, 63); 4498 4499 // 64-76 are various 4-byte special-purpose registers: 4500 // 64: mq 4501 // 65: lr 4502 // 66: ctr 4503 // 67: ap 4504 // 68-75 cr0-7 4505 // 76: xer 4506 AssignToArrayRange(Builder, Address, Four8, 64, 76); 4507 4508 // 77-108: v0-31, the 16-byte vector registers 4509 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108); 4510 4511 // 109: vrsave 4512 // 110: vscr 4513 // 111: spe_acc 4514 // 112: spefscr 4515 // 113: sfp 4516 AssignToArrayRange(Builder, Address, Four8, 109, 113); 4517 4518 return false; 4519 } 4520 4521 // PowerPC-64 4522 4523 namespace { 4524 /// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information. 4525 class PPC64_SVR4_ABIInfo : public SwiftABIInfo { 4526 public: 4527 enum ABIKind { 4528 ELFv1 = 0, 4529 ELFv2 4530 }; 4531 4532 private: 4533 static const unsigned GPRBits = 64; 4534 ABIKind Kind; 4535 bool HasQPX; 4536 bool IsSoftFloatABI; 4537 4538 // A vector of float or double will be promoted to <4 x f32> or <4 x f64> and 4539 // will be passed in a QPX register. 4540 bool IsQPXVectorTy(const Type *Ty) const { 4541 if (!HasQPX) 4542 return false; 4543 4544 if (const VectorType *VT = Ty->getAs<VectorType>()) { 4545 unsigned NumElements = VT->getNumElements(); 4546 if (NumElements == 1) 4547 return false; 4548 4549 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double)) { 4550 if (getContext().getTypeSize(Ty) <= 256) 4551 return true; 4552 } else if (VT->getElementType()-> 4553 isSpecificBuiltinType(BuiltinType::Float)) { 4554 if (getContext().getTypeSize(Ty) <= 128) 4555 return true; 4556 } 4557 } 4558 4559 return false; 4560 } 4561 4562 bool IsQPXVectorTy(QualType Ty) const { 4563 return IsQPXVectorTy(Ty.getTypePtr()); 4564 } 4565 4566 public: 4567 PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind, bool HasQPX, 4568 bool SoftFloatABI) 4569 : SwiftABIInfo(CGT), Kind(Kind), HasQPX(HasQPX), 4570 IsSoftFloatABI(SoftFloatABI) {} 4571 4572 bool isPromotableTypeForABI(QualType Ty) const; 4573 CharUnits getParamTypeAlignment(QualType Ty) const; 4574 4575 ABIArgInfo classifyReturnType(QualType RetTy) const; 4576 ABIArgInfo classifyArgumentType(QualType Ty) const; 4577 4578 bool isHomogeneousAggregateBaseType(QualType Ty) const override; 4579 bool isHomogeneousAggregateSmallEnough(const Type *Ty, 4580 uint64_t Members) const override; 4581 4582 // TODO: We can add more logic to computeInfo to improve performance. 4583 // Example: For aggregate arguments that fit in a register, we could 4584 // use getDirectInReg (as is done below for structs containing a single 4585 // floating-point value) to avoid pushing them to memory on function 4586 // entry. This would require changing the logic in PPCISelLowering 4587 // when lowering the parameters in the caller and args in the callee. 4588 void computeInfo(CGFunctionInfo &FI) const override { 4589 if (!getCXXABI().classifyReturnType(FI)) 4590 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 4591 for (auto &I : FI.arguments()) { 4592 // We rely on the default argument classification for the most part. 4593 // One exception: An aggregate containing a single floating-point 4594 // or vector item must be passed in a register if one is available. 4595 const Type *T = isSingleElementStruct(I.type, getContext()); 4596 if (T) { 4597 const BuiltinType *BT = T->getAs<BuiltinType>(); 4598 if (IsQPXVectorTy(T) || 4599 (T->isVectorType() && getContext().getTypeSize(T) == 128) || 4600 (BT && BT->isFloatingPoint())) { 4601 QualType QT(T, 0); 4602 I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT)); 4603 continue; 4604 } 4605 } 4606 I.info = classifyArgumentType(I.type); 4607 } 4608 } 4609 4610 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 4611 QualType Ty) const override; 4612 4613 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars, 4614 bool asReturnValue) const override { 4615 return occupiesMoreThan(CGT, scalars, /*total*/ 4); 4616 } 4617 4618 bool isSwiftErrorInRegister() const override { 4619 return false; 4620 } 4621 }; 4622 4623 class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo { 4624 4625 public: 4626 PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT, 4627 PPC64_SVR4_ABIInfo::ABIKind Kind, bool HasQPX, 4628 bool SoftFloatABI) 4629 : TargetCodeGenInfo(std::make_unique<PPC64_SVR4_ABIInfo>( 4630 CGT, Kind, HasQPX, SoftFloatABI)) {} 4631 4632 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 4633 // This is recovered from gcc output. 4634 return 1; // r1 is the dedicated stack pointer 4635 } 4636 4637 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 4638 llvm::Value *Address) const override; 4639 }; 4640 4641 class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo { 4642 public: 4643 PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {} 4644 4645 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 4646 // This is recovered from gcc output. 4647 return 1; // r1 is the dedicated stack pointer 4648 } 4649 4650 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 4651 llvm::Value *Address) const override; 4652 }; 4653 4654 } 4655 4656 // Return true if the ABI requires Ty to be passed sign- or zero- 4657 // extended to 64 bits. 4658 bool 4659 PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const { 4660 // Treat an enum type as its underlying type. 4661 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 4662 Ty = EnumTy->getDecl()->getIntegerType(); 4663 4664 // Promotable integer types are required to be promoted by the ABI. 4665 if (Ty->isPromotableIntegerType()) 4666 return true; 4667 4668 // In addition to the usual promotable integer types, we also need to 4669 // extend all 32-bit types, since the ABI requires promotion to 64 bits. 4670 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) 4671 switch (BT->getKind()) { 4672 case BuiltinType::Int: 4673 case BuiltinType::UInt: 4674 return true; 4675 default: 4676 break; 4677 } 4678 4679 return false; 4680 } 4681 4682 /// isAlignedParamType - Determine whether a type requires 16-byte or 4683 /// higher alignment in the parameter area. Always returns at least 8. 4684 CharUnits PPC64_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const { 4685 // Complex types are passed just like their elements. 4686 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) 4687 Ty = CTy->getElementType(); 4688 4689 // Only vector types of size 16 bytes need alignment (larger types are 4690 // passed via reference, smaller types are not aligned). 4691 if (IsQPXVectorTy(Ty)) { 4692 if (getContext().getTypeSize(Ty) > 128) 4693 return CharUnits::fromQuantity(32); 4694 4695 return CharUnits::fromQuantity(16); 4696 } else if (Ty->isVectorType()) { 4697 return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16 : 8); 4698 } 4699 4700 // For single-element float/vector structs, we consider the whole type 4701 // to have the same alignment requirements as its single element. 4702 const Type *AlignAsType = nullptr; 4703 const Type *EltType = isSingleElementStruct(Ty, getContext()); 4704 if (EltType) { 4705 const BuiltinType *BT = EltType->getAs<BuiltinType>(); 4706 if (IsQPXVectorTy(EltType) || (EltType->isVectorType() && 4707 getContext().getTypeSize(EltType) == 128) || 4708 (BT && BT->isFloatingPoint())) 4709 AlignAsType = EltType; 4710 } 4711 4712 // Likewise for ELFv2 homogeneous aggregates. 4713 const Type *Base = nullptr; 4714 uint64_t Members = 0; 4715 if (!AlignAsType && Kind == ELFv2 && 4716 isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members)) 4717 AlignAsType = Base; 4718 4719 // With special case aggregates, only vector base types need alignment. 4720 if (AlignAsType && IsQPXVectorTy(AlignAsType)) { 4721 if (getContext().getTypeSize(AlignAsType) > 128) 4722 return CharUnits::fromQuantity(32); 4723 4724 return CharUnits::fromQuantity(16); 4725 } else if (AlignAsType) { 4726 return CharUnits::fromQuantity(AlignAsType->isVectorType() ? 16 : 8); 4727 } 4728 4729 // Otherwise, we only need alignment for any aggregate type that 4730 // has an alignment requirement of >= 16 bytes. 4731 if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128) { 4732 if (HasQPX && getContext().getTypeAlign(Ty) >= 256) 4733 return CharUnits::fromQuantity(32); 4734 return CharUnits::fromQuantity(16); 4735 } 4736 4737 return CharUnits::fromQuantity(8); 4738 } 4739 4740 /// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous 4741 /// aggregate. Base is set to the base element type, and Members is set 4742 /// to the number of base elements. 4743 bool ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base, 4744 uint64_t &Members) const { 4745 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) { 4746 uint64_t NElements = AT->getSize().getZExtValue(); 4747 if (NElements == 0) 4748 return false; 4749 if (!isHomogeneousAggregate(AT->getElementType(), Base, Members)) 4750 return false; 4751 Members *= NElements; 4752 } else if (const RecordType *RT = Ty->getAs<RecordType>()) { 4753 const RecordDecl *RD = RT->getDecl(); 4754 if (RD->hasFlexibleArrayMember()) 4755 return false; 4756 4757 Members = 0; 4758 4759 // If this is a C++ record, check the bases first. 4760 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 4761 for (const auto &I : CXXRD->bases()) { 4762 // Ignore empty records. 4763 if (isEmptyRecord(getContext(), I.getType(), true)) 4764 continue; 4765 4766 uint64_t FldMembers; 4767 if (!isHomogeneousAggregate(I.getType(), Base, FldMembers)) 4768 return false; 4769 4770 Members += FldMembers; 4771 } 4772 } 4773 4774 for (const auto *FD : RD->fields()) { 4775 // Ignore (non-zero arrays of) empty records. 4776 QualType FT = FD->getType(); 4777 while (const ConstantArrayType *AT = 4778 getContext().getAsConstantArrayType(FT)) { 4779 if (AT->getSize().getZExtValue() == 0) 4780 return false; 4781 FT = AT->getElementType(); 4782 } 4783 if (isEmptyRecord(getContext(), FT, true)) 4784 continue; 4785 4786 // For compatibility with GCC, ignore empty bitfields in C++ mode. 4787 if (getContext().getLangOpts().CPlusPlus && 4788 FD->isZeroLengthBitField(getContext())) 4789 continue; 4790 4791 uint64_t FldMembers; 4792 if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers)) 4793 return false; 4794 4795 Members = (RD->isUnion() ? 4796 std::max(Members, FldMembers) : Members + FldMembers); 4797 } 4798 4799 if (!Base) 4800 return false; 4801 4802 // Ensure there is no padding. 4803 if (getContext().getTypeSize(Base) * Members != 4804 getContext().getTypeSize(Ty)) 4805 return false; 4806 } else { 4807 Members = 1; 4808 if (const ComplexType *CT = Ty->getAs<ComplexType>()) { 4809 Members = 2; 4810 Ty = CT->getElementType(); 4811 } 4812 4813 // Most ABIs only support float, double, and some vector type widths. 4814 if (!isHomogeneousAggregateBaseType(Ty)) 4815 return false; 4816 4817 // The base type must be the same for all members. Types that 4818 // agree in both total size and mode (float vs. vector) are 4819 // treated as being equivalent here. 4820 const Type *TyPtr = Ty.getTypePtr(); 4821 if (!Base) { 4822 Base = TyPtr; 4823 // If it's a non-power-of-2 vector, its size is already a power-of-2, 4824 // so make sure to widen it explicitly. 4825 if (const VectorType *VT = Base->getAs<VectorType>()) { 4826 QualType EltTy = VT->getElementType(); 4827 unsigned NumElements = 4828 getContext().getTypeSize(VT) / getContext().getTypeSize(EltTy); 4829 Base = getContext() 4830 .getVectorType(EltTy, NumElements, VT->getVectorKind()) 4831 .getTypePtr(); 4832 } 4833 } 4834 4835 if (Base->isVectorType() != TyPtr->isVectorType() || 4836 getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr)) 4837 return false; 4838 } 4839 return Members > 0 && isHomogeneousAggregateSmallEnough(Base, Members); 4840 } 4841 4842 bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const { 4843 // Homogeneous aggregates for ELFv2 must have base types of float, 4844 // double, long double, or 128-bit vectors. 4845 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) { 4846 if (BT->getKind() == BuiltinType::Float || 4847 BT->getKind() == BuiltinType::Double || 4848 BT->getKind() == BuiltinType::LongDouble || 4849 (getContext().getTargetInfo().hasFloat128Type() && 4850 (BT->getKind() == BuiltinType::Float128))) { 4851 if (IsSoftFloatABI) 4852 return false; 4853 return true; 4854 } 4855 } 4856 if (const VectorType *VT = Ty->getAs<VectorType>()) { 4857 if (getContext().getTypeSize(VT) == 128 || IsQPXVectorTy(Ty)) 4858 return true; 4859 } 4860 return false; 4861 } 4862 4863 bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateSmallEnough( 4864 const Type *Base, uint64_t Members) const { 4865 // Vector and fp128 types require one register, other floating point types 4866 // require one or two registers depending on their size. 4867 uint32_t NumRegs = 4868 ((getContext().getTargetInfo().hasFloat128Type() && 4869 Base->isFloat128Type()) || 4870 Base->isVectorType()) ? 1 4871 : (getContext().getTypeSize(Base) + 63) / 64; 4872 4873 // Homogeneous Aggregates may occupy at most 8 registers. 4874 return Members * NumRegs <= 8; 4875 } 4876 4877 ABIArgInfo 4878 PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const { 4879 Ty = useFirstFieldIfTransparentUnion(Ty); 4880 4881 if (Ty->isAnyComplexType()) 4882 return ABIArgInfo::getDirect(); 4883 4884 // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes) 4885 // or via reference (larger than 16 bytes). 4886 if (Ty->isVectorType() && !IsQPXVectorTy(Ty)) { 4887 uint64_t Size = getContext().getTypeSize(Ty); 4888 if (Size > 128) 4889 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 4890 else if (Size < 128) { 4891 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size); 4892 return ABIArgInfo::getDirect(CoerceTy); 4893 } 4894 } 4895 4896 if (isAggregateTypeForABI(Ty)) { 4897 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 4898 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 4899 4900 uint64_t ABIAlign = getParamTypeAlignment(Ty).getQuantity(); 4901 uint64_t TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity(); 4902 4903 // ELFv2 homogeneous aggregates are passed as array types. 4904 const Type *Base = nullptr; 4905 uint64_t Members = 0; 4906 if (Kind == ELFv2 && 4907 isHomogeneousAggregate(Ty, Base, Members)) { 4908 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0)); 4909 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members); 4910 return ABIArgInfo::getDirect(CoerceTy); 4911 } 4912 4913 // If an aggregate may end up fully in registers, we do not 4914 // use the ByVal method, but pass the aggregate as array. 4915 // This is usually beneficial since we avoid forcing the 4916 // back-end to store the argument to memory. 4917 uint64_t Bits = getContext().getTypeSize(Ty); 4918 if (Bits > 0 && Bits <= 8 * GPRBits) { 4919 llvm::Type *CoerceTy; 4920 4921 // Types up to 8 bytes are passed as integer type (which will be 4922 // properly aligned in the argument save area doubleword). 4923 if (Bits <= GPRBits) 4924 CoerceTy = 4925 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8)); 4926 // Larger types are passed as arrays, with the base type selected 4927 // according to the required alignment in the save area. 4928 else { 4929 uint64_t RegBits = ABIAlign * 8; 4930 uint64_t NumRegs = llvm::alignTo(Bits, RegBits) / RegBits; 4931 llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits); 4932 CoerceTy = llvm::ArrayType::get(RegTy, NumRegs); 4933 } 4934 4935 return ABIArgInfo::getDirect(CoerceTy); 4936 } 4937 4938 // All other aggregates are passed ByVal. 4939 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign), 4940 /*ByVal=*/true, 4941 /*Realign=*/TyAlign > ABIAlign); 4942 } 4943 4944 return (isPromotableTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty) 4945 : ABIArgInfo::getDirect()); 4946 } 4947 4948 ABIArgInfo 4949 PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const { 4950 if (RetTy->isVoidType()) 4951 return ABIArgInfo::getIgnore(); 4952 4953 if (RetTy->isAnyComplexType()) 4954 return ABIArgInfo::getDirect(); 4955 4956 // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes) 4957 // or via reference (larger than 16 bytes). 4958 if (RetTy->isVectorType() && !IsQPXVectorTy(RetTy)) { 4959 uint64_t Size = getContext().getTypeSize(RetTy); 4960 if (Size > 128) 4961 return getNaturalAlignIndirect(RetTy); 4962 else if (Size < 128) { 4963 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size); 4964 return ABIArgInfo::getDirect(CoerceTy); 4965 } 4966 } 4967 4968 if (isAggregateTypeForABI(RetTy)) { 4969 // ELFv2 homogeneous aggregates are returned as array types. 4970 const Type *Base = nullptr; 4971 uint64_t Members = 0; 4972 if (Kind == ELFv2 && 4973 isHomogeneousAggregate(RetTy, Base, Members)) { 4974 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0)); 4975 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members); 4976 return ABIArgInfo::getDirect(CoerceTy); 4977 } 4978 4979 // ELFv2 small aggregates are returned in up to two registers. 4980 uint64_t Bits = getContext().getTypeSize(RetTy); 4981 if (Kind == ELFv2 && Bits <= 2 * GPRBits) { 4982 if (Bits == 0) 4983 return ABIArgInfo::getIgnore(); 4984 4985 llvm::Type *CoerceTy; 4986 if (Bits > GPRBits) { 4987 CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits); 4988 CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy); 4989 } else 4990 CoerceTy = 4991 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8)); 4992 return ABIArgInfo::getDirect(CoerceTy); 4993 } 4994 4995 // All other aggregates are returned indirectly. 4996 return getNaturalAlignIndirect(RetTy); 4997 } 4998 4999 return (isPromotableTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy) 5000 : ABIArgInfo::getDirect()); 5001 } 5002 5003 // Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine. 5004 Address PPC64_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 5005 QualType Ty) const { 5006 auto TypeInfo = getContext().getTypeInfoInChars(Ty); 5007 TypeInfo.second = getParamTypeAlignment(Ty); 5008 5009 CharUnits SlotSize = CharUnits::fromQuantity(8); 5010 5011 // If we have a complex type and the base type is smaller than 8 bytes, 5012 // the ABI calls for the real and imaginary parts to be right-adjusted 5013 // in separate doublewords. However, Clang expects us to produce a 5014 // pointer to a structure with the two parts packed tightly. So generate 5015 // loads of the real and imaginary parts relative to the va_list pointer, 5016 // and store them to a temporary structure. 5017 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) { 5018 CharUnits EltSize = TypeInfo.first / 2; 5019 if (EltSize < SlotSize) { 5020 Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, CGF.Int8Ty, 5021 SlotSize * 2, SlotSize, 5022 SlotSize, /*AllowHigher*/ true); 5023 5024 Address RealAddr = Addr; 5025 Address ImagAddr = RealAddr; 5026 if (CGF.CGM.getDataLayout().isBigEndian()) { 5027 RealAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, 5028 SlotSize - EltSize); 5029 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(ImagAddr, 5030 2 * SlotSize - EltSize); 5031 } else { 5032 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, SlotSize); 5033 } 5034 5035 llvm::Type *EltTy = CGF.ConvertTypeForMem(CTy->getElementType()); 5036 RealAddr = CGF.Builder.CreateElementBitCast(RealAddr, EltTy); 5037 ImagAddr = CGF.Builder.CreateElementBitCast(ImagAddr, EltTy); 5038 llvm::Value *Real = CGF.Builder.CreateLoad(RealAddr, ".vareal"); 5039 llvm::Value *Imag = CGF.Builder.CreateLoad(ImagAddr, ".vaimag"); 5040 5041 Address Temp = CGF.CreateMemTemp(Ty, "vacplx"); 5042 CGF.EmitStoreOfComplex({Real, Imag}, CGF.MakeAddrLValue(Temp, Ty), 5043 /*init*/ true); 5044 return Temp; 5045 } 5046 } 5047 5048 // Otherwise, just use the general rule. 5049 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false, 5050 TypeInfo, SlotSize, /*AllowHigher*/ true); 5051 } 5052 5053 static bool 5054 PPC64_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 5055 llvm::Value *Address) { 5056 // This is calculated from the LLVM and GCC tables and verified 5057 // against gcc output. AFAIK all ABIs use the same encoding. 5058 5059 CodeGen::CGBuilderTy &Builder = CGF.Builder; 5060 5061 llvm::IntegerType *i8 = CGF.Int8Ty; 5062 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4); 5063 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8); 5064 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16); 5065 5066 // 0-31: r0-31, the 8-byte general-purpose registers 5067 AssignToArrayRange(Builder, Address, Eight8, 0, 31); 5068 5069 // 32-63: fp0-31, the 8-byte floating-point registers 5070 AssignToArrayRange(Builder, Address, Eight8, 32, 63); 5071 5072 // 64-67 are various 8-byte special-purpose registers: 5073 // 64: mq 5074 // 65: lr 5075 // 66: ctr 5076 // 67: ap 5077 AssignToArrayRange(Builder, Address, Eight8, 64, 67); 5078 5079 // 68-76 are various 4-byte special-purpose registers: 5080 // 68-75 cr0-7 5081 // 76: xer 5082 AssignToArrayRange(Builder, Address, Four8, 68, 76); 5083 5084 // 77-108: v0-31, the 16-byte vector registers 5085 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108); 5086 5087 // 109: vrsave 5088 // 110: vscr 5089 // 111: spe_acc 5090 // 112: spefscr 5091 // 113: sfp 5092 // 114: tfhar 5093 // 115: tfiar 5094 // 116: texasr 5095 AssignToArrayRange(Builder, Address, Eight8, 109, 116); 5096 5097 return false; 5098 } 5099 5100 bool 5101 PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable( 5102 CodeGen::CodeGenFunction &CGF, 5103 llvm::Value *Address) const { 5104 5105 return PPC64_initDwarfEHRegSizeTable(CGF, Address); 5106 } 5107 5108 bool 5109 PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 5110 llvm::Value *Address) const { 5111 5112 return PPC64_initDwarfEHRegSizeTable(CGF, Address); 5113 } 5114 5115 //===----------------------------------------------------------------------===// 5116 // AArch64 ABI Implementation 5117 //===----------------------------------------------------------------------===// 5118 5119 namespace { 5120 5121 class AArch64ABIInfo : public SwiftABIInfo { 5122 public: 5123 enum ABIKind { 5124 AAPCS = 0, 5125 DarwinPCS, 5126 Win64 5127 }; 5128 5129 private: 5130 ABIKind Kind; 5131 5132 public: 5133 AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind) 5134 : SwiftABIInfo(CGT), Kind(Kind) {} 5135 5136 private: 5137 ABIKind getABIKind() const { return Kind; } 5138 bool isDarwinPCS() const { return Kind == DarwinPCS; } 5139 5140 ABIArgInfo classifyReturnType(QualType RetTy, bool IsVariadic) const; 5141 ABIArgInfo classifyArgumentType(QualType RetTy) const; 5142 bool isHomogeneousAggregateBaseType(QualType Ty) const override; 5143 bool isHomogeneousAggregateSmallEnough(const Type *Ty, 5144 uint64_t Members) const override; 5145 5146 bool isIllegalVectorType(QualType Ty) const; 5147 5148 void computeInfo(CGFunctionInfo &FI) const override { 5149 if (!::classifyReturnType(getCXXABI(), FI, *this)) 5150 FI.getReturnInfo() = 5151 classifyReturnType(FI.getReturnType(), FI.isVariadic()); 5152 5153 for (auto &it : FI.arguments()) 5154 it.info = classifyArgumentType(it.type); 5155 } 5156 5157 Address EmitDarwinVAArg(Address VAListAddr, QualType Ty, 5158 CodeGenFunction &CGF) const; 5159 5160 Address EmitAAPCSVAArg(Address VAListAddr, QualType Ty, 5161 CodeGenFunction &CGF) const; 5162 5163 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 5164 QualType Ty) const override { 5165 return Kind == Win64 ? EmitMSVAArg(CGF, VAListAddr, Ty) 5166 : isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF) 5167 : EmitAAPCSVAArg(VAListAddr, Ty, CGF); 5168 } 5169 5170 Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr, 5171 QualType Ty) const override; 5172 5173 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars, 5174 bool asReturnValue) const override { 5175 return occupiesMoreThan(CGT, scalars, /*total*/ 4); 5176 } 5177 bool isSwiftErrorInRegister() const override { 5178 return true; 5179 } 5180 5181 bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy, 5182 unsigned elts) const override; 5183 }; 5184 5185 class AArch64TargetCodeGenInfo : public TargetCodeGenInfo { 5186 public: 5187 AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind) 5188 : TargetCodeGenInfo(std::make_unique<AArch64ABIInfo>(CGT, Kind)) {} 5189 5190 StringRef getARCRetainAutoreleasedReturnValueMarker() const override { 5191 return "mov\tfp, fp\t\t// marker for objc_retainAutoreleaseReturnValue"; 5192 } 5193 5194 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 5195 return 31; 5196 } 5197 5198 bool doesReturnSlotInterfereWithArgs() const override { return false; } 5199 5200 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 5201 CodeGen::CodeGenModule &CGM) const override { 5202 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D); 5203 if (!FD) 5204 return; 5205 5206 LangOptions::SignReturnAddressScopeKind Scope = 5207 CGM.getLangOpts().getSignReturnAddressScope(); 5208 LangOptions::SignReturnAddressKeyKind Key = 5209 CGM.getLangOpts().getSignReturnAddressKey(); 5210 bool BranchTargetEnforcement = CGM.getLangOpts().BranchTargetEnforcement; 5211 if (const auto *TA = FD->getAttr<TargetAttr>()) { 5212 ParsedTargetAttr Attr = TA->parse(); 5213 if (!Attr.BranchProtection.empty()) { 5214 TargetInfo::BranchProtectionInfo BPI; 5215 StringRef Error; 5216 (void)CGM.getTarget().validateBranchProtection(Attr.BranchProtection, 5217 BPI, Error); 5218 assert(Error.empty()); 5219 Scope = BPI.SignReturnAddr; 5220 Key = BPI.SignKey; 5221 BranchTargetEnforcement = BPI.BranchTargetEnforcement; 5222 } 5223 } 5224 5225 auto *Fn = cast<llvm::Function>(GV); 5226 if (Scope != LangOptions::SignReturnAddressScopeKind::None) { 5227 Fn->addFnAttr("sign-return-address", 5228 Scope == LangOptions::SignReturnAddressScopeKind::All 5229 ? "all" 5230 : "non-leaf"); 5231 5232 Fn->addFnAttr("sign-return-address-key", 5233 Key == LangOptions::SignReturnAddressKeyKind::AKey 5234 ? "a_key" 5235 : "b_key"); 5236 } 5237 5238 if (BranchTargetEnforcement) 5239 Fn->addFnAttr("branch-target-enforcement"); 5240 } 5241 }; 5242 5243 class WindowsAArch64TargetCodeGenInfo : public AArch64TargetCodeGenInfo { 5244 public: 5245 WindowsAArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind K) 5246 : AArch64TargetCodeGenInfo(CGT, K) {} 5247 5248 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 5249 CodeGen::CodeGenModule &CGM) const override; 5250 5251 void getDependentLibraryOption(llvm::StringRef Lib, 5252 llvm::SmallString<24> &Opt) const override { 5253 Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib); 5254 } 5255 5256 void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value, 5257 llvm::SmallString<32> &Opt) const override { 5258 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\""; 5259 } 5260 }; 5261 5262 void WindowsAArch64TargetCodeGenInfo::setTargetAttributes( 5263 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const { 5264 AArch64TargetCodeGenInfo::setTargetAttributes(D, GV, CGM); 5265 if (GV->isDeclaration()) 5266 return; 5267 addStackProbeTargetAttributes(D, GV, CGM); 5268 } 5269 } 5270 5271 ABIArgInfo AArch64ABIInfo::classifyArgumentType(QualType Ty) const { 5272 Ty = useFirstFieldIfTransparentUnion(Ty); 5273 5274 // Handle illegal vector types here. 5275 if (isIllegalVectorType(Ty)) { 5276 uint64_t Size = getContext().getTypeSize(Ty); 5277 // Android promotes <2 x i8> to i16, not i32 5278 if (isAndroid() && (Size <= 16)) { 5279 llvm::Type *ResType = llvm::Type::getInt16Ty(getVMContext()); 5280 return ABIArgInfo::getDirect(ResType); 5281 } 5282 if (Size <= 32) { 5283 llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext()); 5284 return ABIArgInfo::getDirect(ResType); 5285 } 5286 if (Size == 64) { 5287 llvm::Type *ResType = 5288 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2); 5289 return ABIArgInfo::getDirect(ResType); 5290 } 5291 if (Size == 128) { 5292 llvm::Type *ResType = 5293 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4); 5294 return ABIArgInfo::getDirect(ResType); 5295 } 5296 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 5297 } 5298 5299 if (!isAggregateTypeForABI(Ty)) { 5300 // Treat an enum type as its underlying type. 5301 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 5302 Ty = EnumTy->getDecl()->getIntegerType(); 5303 5304 return (Ty->isPromotableIntegerType() && isDarwinPCS() 5305 ? ABIArgInfo::getExtend(Ty) 5306 : ABIArgInfo::getDirect()); 5307 } 5308 5309 // Structures with either a non-trivial destructor or a non-trivial 5310 // copy constructor are always indirect. 5311 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) { 5312 return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA == 5313 CGCXXABI::RAA_DirectInMemory); 5314 } 5315 5316 // Empty records are always ignored on Darwin, but actually passed in C++ mode 5317 // elsewhere for GNU compatibility. 5318 uint64_t Size = getContext().getTypeSize(Ty); 5319 bool IsEmpty = isEmptyRecord(getContext(), Ty, true); 5320 if (IsEmpty || Size == 0) { 5321 if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS()) 5322 return ABIArgInfo::getIgnore(); 5323 5324 // GNU C mode. The only argument that gets ignored is an empty one with size 5325 // 0. 5326 if (IsEmpty && Size == 0) 5327 return ABIArgInfo::getIgnore(); 5328 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext())); 5329 } 5330 5331 // Homogeneous Floating-point Aggregates (HFAs) need to be expanded. 5332 const Type *Base = nullptr; 5333 uint64_t Members = 0; 5334 if (isHomogeneousAggregate(Ty, Base, Members)) { 5335 return ABIArgInfo::getDirect( 5336 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members)); 5337 } 5338 5339 // Aggregates <= 16 bytes are passed directly in registers or on the stack. 5340 if (Size <= 128) { 5341 // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of 5342 // same size and alignment. 5343 if (getTarget().isRenderScriptTarget()) { 5344 return coerceToIntArray(Ty, getContext(), getVMContext()); 5345 } 5346 unsigned Alignment; 5347 if (Kind == AArch64ABIInfo::AAPCS) { 5348 Alignment = getContext().getTypeUnadjustedAlign(Ty); 5349 Alignment = Alignment < 128 ? 64 : 128; 5350 } else { 5351 Alignment = std::max(getContext().getTypeAlign(Ty), 5352 (unsigned)getTarget().getPointerWidth(0)); 5353 } 5354 Size = llvm::alignTo(Size, Alignment); 5355 5356 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment. 5357 // For aggregates with 16-byte alignment, we use i128. 5358 llvm::Type *BaseTy = llvm::Type::getIntNTy(getVMContext(), Alignment); 5359 return ABIArgInfo::getDirect( 5360 Size == Alignment ? BaseTy 5361 : llvm::ArrayType::get(BaseTy, Size / Alignment)); 5362 } 5363 5364 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 5365 } 5366 5367 ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy, 5368 bool IsVariadic) const { 5369 if (RetTy->isVoidType()) 5370 return ABIArgInfo::getIgnore(); 5371 5372 // Large vector types should be returned via memory. 5373 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128) 5374 return getNaturalAlignIndirect(RetTy); 5375 5376 if (!isAggregateTypeForABI(RetTy)) { 5377 // Treat an enum type as its underlying type. 5378 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 5379 RetTy = EnumTy->getDecl()->getIntegerType(); 5380 5381 return (RetTy->isPromotableIntegerType() && isDarwinPCS() 5382 ? ABIArgInfo::getExtend(RetTy) 5383 : ABIArgInfo::getDirect()); 5384 } 5385 5386 uint64_t Size = getContext().getTypeSize(RetTy); 5387 if (isEmptyRecord(getContext(), RetTy, true) || Size == 0) 5388 return ABIArgInfo::getIgnore(); 5389 5390 const Type *Base = nullptr; 5391 uint64_t Members = 0; 5392 if (isHomogeneousAggregate(RetTy, Base, Members) && 5393 !(getTarget().getTriple().getArch() == llvm::Triple::aarch64_32 && 5394 IsVariadic)) 5395 // Homogeneous Floating-point Aggregates (HFAs) are returned directly. 5396 return ABIArgInfo::getDirect(); 5397 5398 // Aggregates <= 16 bytes are returned directly in registers or on the stack. 5399 if (Size <= 128) { 5400 // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of 5401 // same size and alignment. 5402 if (getTarget().isRenderScriptTarget()) { 5403 return coerceToIntArray(RetTy, getContext(), getVMContext()); 5404 } 5405 unsigned Alignment = getContext().getTypeAlign(RetTy); 5406 Size = llvm::alignTo(Size, 64); // round up to multiple of 8 bytes 5407 5408 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment. 5409 // For aggregates with 16-byte alignment, we use i128. 5410 if (Alignment < 128 && Size == 128) { 5411 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext()); 5412 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64)); 5413 } 5414 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size)); 5415 } 5416 5417 return getNaturalAlignIndirect(RetTy); 5418 } 5419 5420 /// isIllegalVectorType - check whether the vector type is legal for AArch64. 5421 bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const { 5422 if (const VectorType *VT = Ty->getAs<VectorType>()) { 5423 // Check whether VT is legal. 5424 unsigned NumElements = VT->getNumElements(); 5425 uint64_t Size = getContext().getTypeSize(VT); 5426 // NumElements should be power of 2. 5427 if (!llvm::isPowerOf2_32(NumElements)) 5428 return true; 5429 5430 // arm64_32 has to be compatible with the ARM logic here, which allows huge 5431 // vectors for some reason. 5432 llvm::Triple Triple = getTarget().getTriple(); 5433 if (Triple.getArch() == llvm::Triple::aarch64_32 && 5434 Triple.isOSBinFormatMachO()) 5435 return Size <= 32; 5436 5437 return Size != 64 && (Size != 128 || NumElements == 1); 5438 } 5439 return false; 5440 } 5441 5442 bool AArch64ABIInfo::isLegalVectorTypeForSwift(CharUnits totalSize, 5443 llvm::Type *eltTy, 5444 unsigned elts) const { 5445 if (!llvm::isPowerOf2_32(elts)) 5446 return false; 5447 if (totalSize.getQuantity() != 8 && 5448 (totalSize.getQuantity() != 16 || elts == 1)) 5449 return false; 5450 return true; 5451 } 5452 5453 bool AArch64ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const { 5454 // Homogeneous aggregates for AAPCS64 must have base types of a floating 5455 // point type or a short-vector type. This is the same as the 32-bit ABI, 5456 // but with the difference that any floating-point type is allowed, 5457 // including __fp16. 5458 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) { 5459 if (BT->isFloatingPoint()) 5460 return true; 5461 } else if (const VectorType *VT = Ty->getAs<VectorType>()) { 5462 unsigned VecSize = getContext().getTypeSize(VT); 5463 if (VecSize == 64 || VecSize == 128) 5464 return true; 5465 } 5466 return false; 5467 } 5468 5469 bool AArch64ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base, 5470 uint64_t Members) const { 5471 return Members <= 4; 5472 } 5473 5474 Address AArch64ABIInfo::EmitAAPCSVAArg(Address VAListAddr, 5475 QualType Ty, 5476 CodeGenFunction &CGF) const { 5477 ABIArgInfo AI = classifyArgumentType(Ty); 5478 bool IsIndirect = AI.isIndirect(); 5479 5480 llvm::Type *BaseTy = CGF.ConvertType(Ty); 5481 if (IsIndirect) 5482 BaseTy = llvm::PointerType::getUnqual(BaseTy); 5483 else if (AI.getCoerceToType()) 5484 BaseTy = AI.getCoerceToType(); 5485 5486 unsigned NumRegs = 1; 5487 if (llvm::ArrayType *ArrTy = dyn_cast<llvm::ArrayType>(BaseTy)) { 5488 BaseTy = ArrTy->getElementType(); 5489 NumRegs = ArrTy->getNumElements(); 5490 } 5491 bool IsFPR = BaseTy->isFloatingPointTy() || BaseTy->isVectorTy(); 5492 5493 // The AArch64 va_list type and handling is specified in the Procedure Call 5494 // Standard, section B.4: 5495 // 5496 // struct { 5497 // void *__stack; 5498 // void *__gr_top; 5499 // void *__vr_top; 5500 // int __gr_offs; 5501 // int __vr_offs; 5502 // }; 5503 5504 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg"); 5505 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg"); 5506 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack"); 5507 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end"); 5508 5509 CharUnits TySize = getContext().getTypeSizeInChars(Ty); 5510 CharUnits TyAlign = getContext().getTypeUnadjustedAlignInChars(Ty); 5511 5512 Address reg_offs_p = Address::invalid(); 5513 llvm::Value *reg_offs = nullptr; 5514 int reg_top_index; 5515 int RegSize = IsIndirect ? 8 : TySize.getQuantity(); 5516 if (!IsFPR) { 5517 // 3 is the field number of __gr_offs 5518 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 3, "gr_offs_p"); 5519 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs"); 5520 reg_top_index = 1; // field number for __gr_top 5521 RegSize = llvm::alignTo(RegSize, 8); 5522 } else { 5523 // 4 is the field number of __vr_offs. 5524 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 4, "vr_offs_p"); 5525 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs"); 5526 reg_top_index = 2; // field number for __vr_top 5527 RegSize = 16 * NumRegs; 5528 } 5529 5530 //======================================= 5531 // Find out where argument was passed 5532 //======================================= 5533 5534 // If reg_offs >= 0 we're already using the stack for this type of 5535 // argument. We don't want to keep updating reg_offs (in case it overflows, 5536 // though anyone passing 2GB of arguments, each at most 16 bytes, deserves 5537 // whatever they get). 5538 llvm::Value *UsingStack = nullptr; 5539 UsingStack = CGF.Builder.CreateICmpSGE( 5540 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0)); 5541 5542 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock); 5543 5544 // Otherwise, at least some kind of argument could go in these registers, the 5545 // question is whether this particular type is too big. 5546 CGF.EmitBlock(MaybeRegBlock); 5547 5548 // Integer arguments may need to correct register alignment (for example a 5549 // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we 5550 // align __gr_offs to calculate the potential address. 5551 if (!IsFPR && !IsIndirect && TyAlign.getQuantity() > 8) { 5552 int Align = TyAlign.getQuantity(); 5553 5554 reg_offs = CGF.Builder.CreateAdd( 5555 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1), 5556 "align_regoffs"); 5557 reg_offs = CGF.Builder.CreateAnd( 5558 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align), 5559 "aligned_regoffs"); 5560 } 5561 5562 // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list. 5563 // The fact that this is done unconditionally reflects the fact that 5564 // allocating an argument to the stack also uses up all the remaining 5565 // registers of the appropriate kind. 5566 llvm::Value *NewOffset = nullptr; 5567 NewOffset = CGF.Builder.CreateAdd( 5568 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs"); 5569 CGF.Builder.CreateStore(NewOffset, reg_offs_p); 5570 5571 // Now we're in a position to decide whether this argument really was in 5572 // registers or not. 5573 llvm::Value *InRegs = nullptr; 5574 InRegs = CGF.Builder.CreateICmpSLE( 5575 NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg"); 5576 5577 CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock); 5578 5579 //======================================= 5580 // Argument was in registers 5581 //======================================= 5582 5583 // Now we emit the code for if the argument was originally passed in 5584 // registers. First start the appropriate block: 5585 CGF.EmitBlock(InRegBlock); 5586 5587 llvm::Value *reg_top = nullptr; 5588 Address reg_top_p = 5589 CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index, "reg_top_p"); 5590 reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top"); 5591 Address BaseAddr(CGF.Builder.CreateInBoundsGEP(reg_top, reg_offs), 5592 CharUnits::fromQuantity(IsFPR ? 16 : 8)); 5593 Address RegAddr = Address::invalid(); 5594 llvm::Type *MemTy = CGF.ConvertTypeForMem(Ty); 5595 5596 if (IsIndirect) { 5597 // If it's been passed indirectly (actually a struct), whatever we find from 5598 // stored registers or on the stack will actually be a struct **. 5599 MemTy = llvm::PointerType::getUnqual(MemTy); 5600 } 5601 5602 const Type *Base = nullptr; 5603 uint64_t NumMembers = 0; 5604 bool IsHFA = isHomogeneousAggregate(Ty, Base, NumMembers); 5605 if (IsHFA && NumMembers > 1) { 5606 // Homogeneous aggregates passed in registers will have their elements split 5607 // and stored 16-bytes apart regardless of size (they're notionally in qN, 5608 // qN+1, ...). We reload and store into a temporary local variable 5609 // contiguously. 5610 assert(!IsIndirect && "Homogeneous aggregates should be passed directly"); 5611 auto BaseTyInfo = getContext().getTypeInfoInChars(QualType(Base, 0)); 5612 llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0)); 5613 llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers); 5614 Address Tmp = CGF.CreateTempAlloca(HFATy, 5615 std::max(TyAlign, BaseTyInfo.second)); 5616 5617 // On big-endian platforms, the value will be right-aligned in its slot. 5618 int Offset = 0; 5619 if (CGF.CGM.getDataLayout().isBigEndian() && 5620 BaseTyInfo.first.getQuantity() < 16) 5621 Offset = 16 - BaseTyInfo.first.getQuantity(); 5622 5623 for (unsigned i = 0; i < NumMembers; ++i) { 5624 CharUnits BaseOffset = CharUnits::fromQuantity(16 * i + Offset); 5625 Address LoadAddr = 5626 CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, BaseOffset); 5627 LoadAddr = CGF.Builder.CreateElementBitCast(LoadAddr, BaseTy); 5628 5629 Address StoreAddr = CGF.Builder.CreateConstArrayGEP(Tmp, i); 5630 5631 llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr); 5632 CGF.Builder.CreateStore(Elem, StoreAddr); 5633 } 5634 5635 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, MemTy); 5636 } else { 5637 // Otherwise the object is contiguous in memory. 5638 5639 // It might be right-aligned in its slot. 5640 CharUnits SlotSize = BaseAddr.getAlignment(); 5641 if (CGF.CGM.getDataLayout().isBigEndian() && !IsIndirect && 5642 (IsHFA || !isAggregateTypeForABI(Ty)) && 5643 TySize < SlotSize) { 5644 CharUnits Offset = SlotSize - TySize; 5645 BaseAddr = CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, Offset); 5646 } 5647 5648 RegAddr = CGF.Builder.CreateElementBitCast(BaseAddr, MemTy); 5649 } 5650 5651 CGF.EmitBranch(ContBlock); 5652 5653 //======================================= 5654 // Argument was on the stack 5655 //======================================= 5656 CGF.EmitBlock(OnStackBlock); 5657 5658 Address stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "stack_p"); 5659 llvm::Value *OnStackPtr = CGF.Builder.CreateLoad(stack_p, "stack"); 5660 5661 // Again, stack arguments may need realignment. In this case both integer and 5662 // floating-point ones might be affected. 5663 if (!IsIndirect && TyAlign.getQuantity() > 8) { 5664 int Align = TyAlign.getQuantity(); 5665 5666 OnStackPtr = CGF.Builder.CreatePtrToInt(OnStackPtr, CGF.Int64Ty); 5667 5668 OnStackPtr = CGF.Builder.CreateAdd( 5669 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1), 5670 "align_stack"); 5671 OnStackPtr = CGF.Builder.CreateAnd( 5672 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, -Align), 5673 "align_stack"); 5674 5675 OnStackPtr = CGF.Builder.CreateIntToPtr(OnStackPtr, CGF.Int8PtrTy); 5676 } 5677 Address OnStackAddr(OnStackPtr, 5678 std::max(CharUnits::fromQuantity(8), TyAlign)); 5679 5680 // All stack slots are multiples of 8 bytes. 5681 CharUnits StackSlotSize = CharUnits::fromQuantity(8); 5682 CharUnits StackSize; 5683 if (IsIndirect) 5684 StackSize = StackSlotSize; 5685 else 5686 StackSize = TySize.alignTo(StackSlotSize); 5687 5688 llvm::Value *StackSizeC = CGF.Builder.getSize(StackSize); 5689 llvm::Value *NewStack = 5690 CGF.Builder.CreateInBoundsGEP(OnStackPtr, StackSizeC, "new_stack"); 5691 5692 // Write the new value of __stack for the next call to va_arg 5693 CGF.Builder.CreateStore(NewStack, stack_p); 5694 5695 if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) && 5696 TySize < StackSlotSize) { 5697 CharUnits Offset = StackSlotSize - TySize; 5698 OnStackAddr = CGF.Builder.CreateConstInBoundsByteGEP(OnStackAddr, Offset); 5699 } 5700 5701 OnStackAddr = CGF.Builder.CreateElementBitCast(OnStackAddr, MemTy); 5702 5703 CGF.EmitBranch(ContBlock); 5704 5705 //======================================= 5706 // Tidy up 5707 //======================================= 5708 CGF.EmitBlock(ContBlock); 5709 5710 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, 5711 OnStackAddr, OnStackBlock, "vaargs.addr"); 5712 5713 if (IsIndirect) 5714 return Address(CGF.Builder.CreateLoad(ResAddr, "vaarg.addr"), 5715 TyAlign); 5716 5717 return ResAddr; 5718 } 5719 5720 Address AArch64ABIInfo::EmitDarwinVAArg(Address VAListAddr, QualType Ty, 5721 CodeGenFunction &CGF) const { 5722 // The backend's lowering doesn't support va_arg for aggregates or 5723 // illegal vector types. Lower VAArg here for these cases and use 5724 // the LLVM va_arg instruction for everything else. 5725 if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty)) 5726 return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect()); 5727 5728 uint64_t PointerSize = getTarget().getPointerWidth(0) / 8; 5729 CharUnits SlotSize = CharUnits::fromQuantity(PointerSize); 5730 5731 // Empty records are ignored for parameter passing purposes. 5732 if (isEmptyRecord(getContext(), Ty, true)) { 5733 Address Addr(CGF.Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize); 5734 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty)); 5735 return Addr; 5736 } 5737 5738 // The size of the actual thing passed, which might end up just 5739 // being a pointer for indirect types. 5740 auto TyInfo = getContext().getTypeInfoInChars(Ty); 5741 5742 // Arguments bigger than 16 bytes which aren't homogeneous 5743 // aggregates should be passed indirectly. 5744 bool IsIndirect = false; 5745 if (TyInfo.first.getQuantity() > 16) { 5746 const Type *Base = nullptr; 5747 uint64_t Members = 0; 5748 IsIndirect = !isHomogeneousAggregate(Ty, Base, Members); 5749 } 5750 5751 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, 5752 TyInfo, SlotSize, /*AllowHigherAlign*/ true); 5753 } 5754 5755 Address AArch64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr, 5756 QualType Ty) const { 5757 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false, 5758 CGF.getContext().getTypeInfoInChars(Ty), 5759 CharUnits::fromQuantity(8), 5760 /*allowHigherAlign*/ false); 5761 } 5762 5763 //===----------------------------------------------------------------------===// 5764 // ARM ABI Implementation 5765 //===----------------------------------------------------------------------===// 5766 5767 namespace { 5768 5769 class ARMABIInfo : public SwiftABIInfo { 5770 public: 5771 enum ABIKind { 5772 APCS = 0, 5773 AAPCS = 1, 5774 AAPCS_VFP = 2, 5775 AAPCS16_VFP = 3, 5776 }; 5777 5778 private: 5779 ABIKind Kind; 5780 5781 public: 5782 ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind) 5783 : SwiftABIInfo(CGT), Kind(_Kind) { 5784 setCCs(); 5785 } 5786 5787 bool isEABI() const { 5788 switch (getTarget().getTriple().getEnvironment()) { 5789 case llvm::Triple::Android: 5790 case llvm::Triple::EABI: 5791 case llvm::Triple::EABIHF: 5792 case llvm::Triple::GNUEABI: 5793 case llvm::Triple::GNUEABIHF: 5794 case llvm::Triple::MuslEABI: 5795 case llvm::Triple::MuslEABIHF: 5796 return true; 5797 default: 5798 return false; 5799 } 5800 } 5801 5802 bool isEABIHF() const { 5803 switch (getTarget().getTriple().getEnvironment()) { 5804 case llvm::Triple::EABIHF: 5805 case llvm::Triple::GNUEABIHF: 5806 case llvm::Triple::MuslEABIHF: 5807 return true; 5808 default: 5809 return false; 5810 } 5811 } 5812 5813 ABIKind getABIKind() const { return Kind; } 5814 5815 private: 5816 ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic, 5817 unsigned functionCallConv) const; 5818 ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic, 5819 unsigned functionCallConv) const; 5820 ABIArgInfo classifyHomogeneousAggregate(QualType Ty, const Type *Base, 5821 uint64_t Members) const; 5822 ABIArgInfo coerceIllegalVector(QualType Ty) const; 5823 bool isIllegalVectorType(QualType Ty) const; 5824 bool containsAnyFP16Vectors(QualType Ty) const; 5825 5826 bool isHomogeneousAggregateBaseType(QualType Ty) const override; 5827 bool isHomogeneousAggregateSmallEnough(const Type *Ty, 5828 uint64_t Members) const override; 5829 5830 bool isEffectivelyAAPCS_VFP(unsigned callConvention, bool acceptHalf) const; 5831 5832 void computeInfo(CGFunctionInfo &FI) const override; 5833 5834 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 5835 QualType Ty) const override; 5836 5837 llvm::CallingConv::ID getLLVMDefaultCC() const; 5838 llvm::CallingConv::ID getABIDefaultCC() const; 5839 void setCCs(); 5840 5841 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars, 5842 bool asReturnValue) const override { 5843 return occupiesMoreThan(CGT, scalars, /*total*/ 4); 5844 } 5845 bool isSwiftErrorInRegister() const override { 5846 return true; 5847 } 5848 bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy, 5849 unsigned elts) const override; 5850 }; 5851 5852 class ARMTargetCodeGenInfo : public TargetCodeGenInfo { 5853 public: 5854 ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K) 5855 : TargetCodeGenInfo(std::make_unique<ARMABIInfo>(CGT, K)) {} 5856 5857 const ARMABIInfo &getABIInfo() const { 5858 return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo()); 5859 } 5860 5861 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 5862 return 13; 5863 } 5864 5865 StringRef getARCRetainAutoreleasedReturnValueMarker() const override { 5866 return "mov\tr7, r7\t\t// marker for objc_retainAutoreleaseReturnValue"; 5867 } 5868 5869 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 5870 llvm::Value *Address) const override { 5871 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4); 5872 5873 // 0-15 are the 16 integer registers. 5874 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15); 5875 return false; 5876 } 5877 5878 unsigned getSizeOfUnwindException() const override { 5879 if (getABIInfo().isEABI()) return 88; 5880 return TargetCodeGenInfo::getSizeOfUnwindException(); 5881 } 5882 5883 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 5884 CodeGen::CodeGenModule &CGM) const override { 5885 if (GV->isDeclaration()) 5886 return; 5887 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D); 5888 if (!FD) 5889 return; 5890 5891 const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>(); 5892 if (!Attr) 5893 return; 5894 5895 const char *Kind; 5896 switch (Attr->getInterrupt()) { 5897 case ARMInterruptAttr::Generic: Kind = ""; break; 5898 case ARMInterruptAttr::IRQ: Kind = "IRQ"; break; 5899 case ARMInterruptAttr::FIQ: Kind = "FIQ"; break; 5900 case ARMInterruptAttr::SWI: Kind = "SWI"; break; 5901 case ARMInterruptAttr::ABORT: Kind = "ABORT"; break; 5902 case ARMInterruptAttr::UNDEF: Kind = "UNDEF"; break; 5903 } 5904 5905 llvm::Function *Fn = cast<llvm::Function>(GV); 5906 5907 Fn->addFnAttr("interrupt", Kind); 5908 5909 ARMABIInfo::ABIKind ABI = cast<ARMABIInfo>(getABIInfo()).getABIKind(); 5910 if (ABI == ARMABIInfo::APCS) 5911 return; 5912 5913 // AAPCS guarantees that sp will be 8-byte aligned on any public interface, 5914 // however this is not necessarily true on taking any interrupt. Instruct 5915 // the backend to perform a realignment as part of the function prologue. 5916 llvm::AttrBuilder B; 5917 B.addStackAlignmentAttr(8); 5918 Fn->addAttributes(llvm::AttributeList::FunctionIndex, B); 5919 } 5920 }; 5921 5922 class WindowsARMTargetCodeGenInfo : public ARMTargetCodeGenInfo { 5923 public: 5924 WindowsARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K) 5925 : ARMTargetCodeGenInfo(CGT, K) {} 5926 5927 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 5928 CodeGen::CodeGenModule &CGM) const override; 5929 5930 void getDependentLibraryOption(llvm::StringRef Lib, 5931 llvm::SmallString<24> &Opt) const override { 5932 Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib); 5933 } 5934 5935 void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value, 5936 llvm::SmallString<32> &Opt) const override { 5937 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\""; 5938 } 5939 }; 5940 5941 void WindowsARMTargetCodeGenInfo::setTargetAttributes( 5942 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const { 5943 ARMTargetCodeGenInfo::setTargetAttributes(D, GV, CGM); 5944 if (GV->isDeclaration()) 5945 return; 5946 addStackProbeTargetAttributes(D, GV, CGM); 5947 } 5948 } 5949 5950 void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const { 5951 if (!::classifyReturnType(getCXXABI(), FI, *this)) 5952 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), FI.isVariadic(), 5953 FI.getCallingConvention()); 5954 5955 for (auto &I : FI.arguments()) 5956 I.info = classifyArgumentType(I.type, FI.isVariadic(), 5957 FI.getCallingConvention()); 5958 5959 5960 // Always honor user-specified calling convention. 5961 if (FI.getCallingConvention() != llvm::CallingConv::C) 5962 return; 5963 5964 llvm::CallingConv::ID cc = getRuntimeCC(); 5965 if (cc != llvm::CallingConv::C) 5966 FI.setEffectiveCallingConvention(cc); 5967 } 5968 5969 /// Return the default calling convention that LLVM will use. 5970 llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const { 5971 // The default calling convention that LLVM will infer. 5972 if (isEABIHF() || getTarget().getTriple().isWatchABI()) 5973 return llvm::CallingConv::ARM_AAPCS_VFP; 5974 else if (isEABI()) 5975 return llvm::CallingConv::ARM_AAPCS; 5976 else 5977 return llvm::CallingConv::ARM_APCS; 5978 } 5979 5980 /// Return the calling convention that our ABI would like us to use 5981 /// as the C calling convention. 5982 llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const { 5983 switch (getABIKind()) { 5984 case APCS: return llvm::CallingConv::ARM_APCS; 5985 case AAPCS: return llvm::CallingConv::ARM_AAPCS; 5986 case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP; 5987 case AAPCS16_VFP: return llvm::CallingConv::ARM_AAPCS_VFP; 5988 } 5989 llvm_unreachable("bad ABI kind"); 5990 } 5991 5992 void ARMABIInfo::setCCs() { 5993 assert(getRuntimeCC() == llvm::CallingConv::C); 5994 5995 // Don't muddy up the IR with a ton of explicit annotations if 5996 // they'd just match what LLVM will infer from the triple. 5997 llvm::CallingConv::ID abiCC = getABIDefaultCC(); 5998 if (abiCC != getLLVMDefaultCC()) 5999 RuntimeCC = abiCC; 6000 } 6001 6002 ABIArgInfo ARMABIInfo::coerceIllegalVector(QualType Ty) const { 6003 uint64_t Size = getContext().getTypeSize(Ty); 6004 if (Size <= 32) { 6005 llvm::Type *ResType = 6006 llvm::Type::getInt32Ty(getVMContext()); 6007 return ABIArgInfo::getDirect(ResType); 6008 } 6009 if (Size == 64 || Size == 128) { 6010 llvm::Type *ResType = llvm::VectorType::get( 6011 llvm::Type::getInt32Ty(getVMContext()), Size / 32); 6012 return ABIArgInfo::getDirect(ResType); 6013 } 6014 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 6015 } 6016 6017 ABIArgInfo ARMABIInfo::classifyHomogeneousAggregate(QualType Ty, 6018 const Type *Base, 6019 uint64_t Members) const { 6020 assert(Base && "Base class should be set for homogeneous aggregate"); 6021 // Base can be a floating-point or a vector. 6022 if (const VectorType *VT = Base->getAs<VectorType>()) { 6023 // FP16 vectors should be converted to integer vectors 6024 if (!getTarget().hasLegalHalfType() && containsAnyFP16Vectors(Ty)) { 6025 uint64_t Size = getContext().getTypeSize(VT); 6026 llvm::Type *NewVecTy = llvm::VectorType::get( 6027 llvm::Type::getInt32Ty(getVMContext()), Size / 32); 6028 llvm::Type *Ty = llvm::ArrayType::get(NewVecTy, Members); 6029 return ABIArgInfo::getDirect(Ty, 0, nullptr, false); 6030 } 6031 } 6032 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false); 6033 } 6034 6035 ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty, bool isVariadic, 6036 unsigned functionCallConv) const { 6037 // 6.1.2.1 The following argument types are VFP CPRCs: 6038 // A single-precision floating-point type (including promoted 6039 // half-precision types); A double-precision floating-point type; 6040 // A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate 6041 // with a Base Type of a single- or double-precision floating-point type, 6042 // 64-bit containerized vectors or 128-bit containerized vectors with one 6043 // to four Elements. 6044 // Variadic functions should always marshal to the base standard. 6045 bool IsAAPCS_VFP = 6046 !isVariadic && isEffectivelyAAPCS_VFP(functionCallConv, /* AAPCS16 */ false); 6047 6048 Ty = useFirstFieldIfTransparentUnion(Ty); 6049 6050 // Handle illegal vector types here. 6051 if (isIllegalVectorType(Ty)) 6052 return coerceIllegalVector(Ty); 6053 6054 // _Float16 and __fp16 get passed as if it were an int or float, but with 6055 // the top 16 bits unspecified. This is not done for OpenCL as it handles the 6056 // half type natively, and does not need to interwork with AAPCS code. 6057 if ((Ty->isFloat16Type() || Ty->isHalfType()) && 6058 !getContext().getLangOpts().NativeHalfArgsAndReturns) { 6059 llvm::Type *ResType = IsAAPCS_VFP ? 6060 llvm::Type::getFloatTy(getVMContext()) : 6061 llvm::Type::getInt32Ty(getVMContext()); 6062 return ABIArgInfo::getDirect(ResType); 6063 } 6064 6065 if (!isAggregateTypeForABI(Ty)) { 6066 // Treat an enum type as its underlying type. 6067 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) { 6068 Ty = EnumTy->getDecl()->getIntegerType(); 6069 } 6070 6071 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty) 6072 : ABIArgInfo::getDirect()); 6073 } 6074 6075 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) { 6076 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 6077 } 6078 6079 // Ignore empty records. 6080 if (isEmptyRecord(getContext(), Ty, true)) 6081 return ABIArgInfo::getIgnore(); 6082 6083 if (IsAAPCS_VFP) { 6084 // Homogeneous Aggregates need to be expanded when we can fit the aggregate 6085 // into VFP registers. 6086 const Type *Base = nullptr; 6087 uint64_t Members = 0; 6088 if (isHomogeneousAggregate(Ty, Base, Members)) 6089 return classifyHomogeneousAggregate(Ty, Base, Members); 6090 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) { 6091 // WatchOS does have homogeneous aggregates. Note that we intentionally use 6092 // this convention even for a variadic function: the backend will use GPRs 6093 // if needed. 6094 const Type *Base = nullptr; 6095 uint64_t Members = 0; 6096 if (isHomogeneousAggregate(Ty, Base, Members)) { 6097 assert(Base && Members <= 4 && "unexpected homogeneous aggregate"); 6098 llvm::Type *Ty = 6099 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members); 6100 return ABIArgInfo::getDirect(Ty, 0, nullptr, false); 6101 } 6102 } 6103 6104 if (getABIKind() == ARMABIInfo::AAPCS16_VFP && 6105 getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(16)) { 6106 // WatchOS is adopting the 64-bit AAPCS rule on composite types: if they're 6107 // bigger than 128-bits, they get placed in space allocated by the caller, 6108 // and a pointer is passed. 6109 return ABIArgInfo::getIndirect( 6110 CharUnits::fromQuantity(getContext().getTypeAlign(Ty) / 8), false); 6111 } 6112 6113 // Support byval for ARM. 6114 // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at 6115 // most 8-byte. We realign the indirect argument if type alignment is bigger 6116 // than ABI alignment. 6117 uint64_t ABIAlign = 4; 6118 uint64_t TyAlign; 6119 if (getABIKind() == ARMABIInfo::AAPCS_VFP || 6120 getABIKind() == ARMABIInfo::AAPCS) { 6121 TyAlign = getContext().getTypeUnadjustedAlignInChars(Ty).getQuantity(); 6122 ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8); 6123 } else { 6124 TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity(); 6125 } 6126 if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) { 6127 assert(getABIKind() != ARMABIInfo::AAPCS16_VFP && "unexpected byval"); 6128 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign), 6129 /*ByVal=*/true, 6130 /*Realign=*/TyAlign > ABIAlign); 6131 } 6132 6133 // On RenderScript, coerce Aggregates <= 64 bytes to an integer array of 6134 // same size and alignment. 6135 if (getTarget().isRenderScriptTarget()) { 6136 return coerceToIntArray(Ty, getContext(), getVMContext()); 6137 } 6138 6139 // Otherwise, pass by coercing to a structure of the appropriate size. 6140 llvm::Type* ElemTy; 6141 unsigned SizeRegs; 6142 // FIXME: Try to match the types of the arguments more accurately where 6143 // we can. 6144 if (TyAlign <= 4) { 6145 ElemTy = llvm::Type::getInt32Ty(getVMContext()); 6146 SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32; 6147 } else { 6148 ElemTy = llvm::Type::getInt64Ty(getVMContext()); 6149 SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64; 6150 } 6151 6152 return ABIArgInfo::getDirect(llvm::ArrayType::get(ElemTy, SizeRegs)); 6153 } 6154 6155 static bool isIntegerLikeType(QualType Ty, ASTContext &Context, 6156 llvm::LLVMContext &VMContext) { 6157 // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure 6158 // is called integer-like if its size is less than or equal to one word, and 6159 // the offset of each of its addressable sub-fields is zero. 6160 6161 uint64_t Size = Context.getTypeSize(Ty); 6162 6163 // Check that the type fits in a word. 6164 if (Size > 32) 6165 return false; 6166 6167 // FIXME: Handle vector types! 6168 if (Ty->isVectorType()) 6169 return false; 6170 6171 // Float types are never treated as "integer like". 6172 if (Ty->isRealFloatingType()) 6173 return false; 6174 6175 // If this is a builtin or pointer type then it is ok. 6176 if (Ty->getAs<BuiltinType>() || Ty->isPointerType()) 6177 return true; 6178 6179 // Small complex integer types are "integer like". 6180 if (const ComplexType *CT = Ty->getAs<ComplexType>()) 6181 return isIntegerLikeType(CT->getElementType(), Context, VMContext); 6182 6183 // Single element and zero sized arrays should be allowed, by the definition 6184 // above, but they are not. 6185 6186 // Otherwise, it must be a record type. 6187 const RecordType *RT = Ty->getAs<RecordType>(); 6188 if (!RT) return false; 6189 6190 // Ignore records with flexible arrays. 6191 const RecordDecl *RD = RT->getDecl(); 6192 if (RD->hasFlexibleArrayMember()) 6193 return false; 6194 6195 // Check that all sub-fields are at offset 0, and are themselves "integer 6196 // like". 6197 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); 6198 6199 bool HadField = false; 6200 unsigned idx = 0; 6201 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 6202 i != e; ++i, ++idx) { 6203 const FieldDecl *FD = *i; 6204 6205 // Bit-fields are not addressable, we only need to verify they are "integer 6206 // like". We still have to disallow a subsequent non-bitfield, for example: 6207 // struct { int : 0; int x } 6208 // is non-integer like according to gcc. 6209 if (FD->isBitField()) { 6210 if (!RD->isUnion()) 6211 HadField = true; 6212 6213 if (!isIntegerLikeType(FD->getType(), Context, VMContext)) 6214 return false; 6215 6216 continue; 6217 } 6218 6219 // Check if this field is at offset 0. 6220 if (Layout.getFieldOffset(idx) != 0) 6221 return false; 6222 6223 if (!isIntegerLikeType(FD->getType(), Context, VMContext)) 6224 return false; 6225 6226 // Only allow at most one field in a structure. This doesn't match the 6227 // wording above, but follows gcc in situations with a field following an 6228 // empty structure. 6229 if (!RD->isUnion()) { 6230 if (HadField) 6231 return false; 6232 6233 HadField = true; 6234 } 6235 } 6236 6237 return true; 6238 } 6239 6240 ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy, bool isVariadic, 6241 unsigned functionCallConv) const { 6242 6243 // Variadic functions should always marshal to the base standard. 6244 bool IsAAPCS_VFP = 6245 !isVariadic && isEffectivelyAAPCS_VFP(functionCallConv, /* AAPCS16 */ true); 6246 6247 if (RetTy->isVoidType()) 6248 return ABIArgInfo::getIgnore(); 6249 6250 if (const VectorType *VT = RetTy->getAs<VectorType>()) { 6251 // Large vector types should be returned via memory. 6252 if (getContext().getTypeSize(RetTy) > 128) 6253 return getNaturalAlignIndirect(RetTy); 6254 // FP16 vectors should be converted to integer vectors 6255 if (!getTarget().hasLegalHalfType() && 6256 (VT->getElementType()->isFloat16Type() || 6257 VT->getElementType()->isHalfType())) 6258 return coerceIllegalVector(RetTy); 6259 } 6260 6261 // _Float16 and __fp16 get returned as if it were an int or float, but with 6262 // the top 16 bits unspecified. This is not done for OpenCL as it handles the 6263 // half type natively, and does not need to interwork with AAPCS code. 6264 if ((RetTy->isFloat16Type() || RetTy->isHalfType()) && 6265 !getContext().getLangOpts().NativeHalfArgsAndReturns) { 6266 llvm::Type *ResType = IsAAPCS_VFP ? 6267 llvm::Type::getFloatTy(getVMContext()) : 6268 llvm::Type::getInt32Ty(getVMContext()); 6269 return ABIArgInfo::getDirect(ResType); 6270 } 6271 6272 if (!isAggregateTypeForABI(RetTy)) { 6273 // Treat an enum type as its underlying type. 6274 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 6275 RetTy = EnumTy->getDecl()->getIntegerType(); 6276 6277 return RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy) 6278 : ABIArgInfo::getDirect(); 6279 } 6280 6281 // Are we following APCS? 6282 if (getABIKind() == APCS) { 6283 if (isEmptyRecord(getContext(), RetTy, false)) 6284 return ABIArgInfo::getIgnore(); 6285 6286 // Complex types are all returned as packed integers. 6287 // 6288 // FIXME: Consider using 2 x vector types if the back end handles them 6289 // correctly. 6290 if (RetTy->isAnyComplexType()) 6291 return ABIArgInfo::getDirect(llvm::IntegerType::get( 6292 getVMContext(), getContext().getTypeSize(RetTy))); 6293 6294 // Integer like structures are returned in r0. 6295 if (isIntegerLikeType(RetTy, getContext(), getVMContext())) { 6296 // Return in the smallest viable integer type. 6297 uint64_t Size = getContext().getTypeSize(RetTy); 6298 if (Size <= 8) 6299 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext())); 6300 if (Size <= 16) 6301 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext())); 6302 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext())); 6303 } 6304 6305 // Otherwise return in memory. 6306 return getNaturalAlignIndirect(RetTy); 6307 } 6308 6309 // Otherwise this is an AAPCS variant. 6310 6311 if (isEmptyRecord(getContext(), RetTy, true)) 6312 return ABIArgInfo::getIgnore(); 6313 6314 // Check for homogeneous aggregates with AAPCS-VFP. 6315 if (IsAAPCS_VFP) { 6316 const Type *Base = nullptr; 6317 uint64_t Members = 0; 6318 if (isHomogeneousAggregate(RetTy, Base, Members)) 6319 return classifyHomogeneousAggregate(RetTy, Base, Members); 6320 } 6321 6322 // Aggregates <= 4 bytes are returned in r0; other aggregates 6323 // are returned indirectly. 6324 uint64_t Size = getContext().getTypeSize(RetTy); 6325 if (Size <= 32) { 6326 // On RenderScript, coerce Aggregates <= 4 bytes to an integer array of 6327 // same size and alignment. 6328 if (getTarget().isRenderScriptTarget()) { 6329 return coerceToIntArray(RetTy, getContext(), getVMContext()); 6330 } 6331 if (getDataLayout().isBigEndian()) 6332 // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4) 6333 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext())); 6334 6335 // Return in the smallest viable integer type. 6336 if (Size <= 8) 6337 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext())); 6338 if (Size <= 16) 6339 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext())); 6340 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext())); 6341 } else if (Size <= 128 && getABIKind() == AAPCS16_VFP) { 6342 llvm::Type *Int32Ty = llvm::Type::getInt32Ty(getVMContext()); 6343 llvm::Type *CoerceTy = 6344 llvm::ArrayType::get(Int32Ty, llvm::alignTo(Size, 32) / 32); 6345 return ABIArgInfo::getDirect(CoerceTy); 6346 } 6347 6348 return getNaturalAlignIndirect(RetTy); 6349 } 6350 6351 /// isIllegalVector - check whether Ty is an illegal vector type. 6352 bool ARMABIInfo::isIllegalVectorType(QualType Ty) const { 6353 if (const VectorType *VT = Ty->getAs<VectorType> ()) { 6354 // On targets that don't support FP16, FP16 is expanded into float, and we 6355 // don't want the ABI to depend on whether or not FP16 is supported in 6356 // hardware. Thus return false to coerce FP16 vectors into integer vectors. 6357 if (!getTarget().hasLegalHalfType() && 6358 (VT->getElementType()->isFloat16Type() || 6359 VT->getElementType()->isHalfType())) 6360 return true; 6361 if (isAndroid()) { 6362 // Android shipped using Clang 3.1, which supported a slightly different 6363 // vector ABI. The primary differences were that 3-element vector types 6364 // were legal, and so were sub 32-bit vectors (i.e. <2 x i8>). This path 6365 // accepts that legacy behavior for Android only. 6366 // Check whether VT is legal. 6367 unsigned NumElements = VT->getNumElements(); 6368 // NumElements should be power of 2 or equal to 3. 6369 if (!llvm::isPowerOf2_32(NumElements) && NumElements != 3) 6370 return true; 6371 } else { 6372 // Check whether VT is legal. 6373 unsigned NumElements = VT->getNumElements(); 6374 uint64_t Size = getContext().getTypeSize(VT); 6375 // NumElements should be power of 2. 6376 if (!llvm::isPowerOf2_32(NumElements)) 6377 return true; 6378 // Size should be greater than 32 bits. 6379 return Size <= 32; 6380 } 6381 } 6382 return false; 6383 } 6384 6385 /// Return true if a type contains any 16-bit floating point vectors 6386 bool ARMABIInfo::containsAnyFP16Vectors(QualType Ty) const { 6387 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) { 6388 uint64_t NElements = AT->getSize().getZExtValue(); 6389 if (NElements == 0) 6390 return false; 6391 return containsAnyFP16Vectors(AT->getElementType()); 6392 } else if (const RecordType *RT = Ty->getAs<RecordType>()) { 6393 const RecordDecl *RD = RT->getDecl(); 6394 6395 // If this is a C++ record, check the bases first. 6396 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 6397 if (llvm::any_of(CXXRD->bases(), [this](const CXXBaseSpecifier &B) { 6398 return containsAnyFP16Vectors(B.getType()); 6399 })) 6400 return true; 6401 6402 if (llvm::any_of(RD->fields(), [this](FieldDecl *FD) { 6403 return FD && containsAnyFP16Vectors(FD->getType()); 6404 })) 6405 return true; 6406 6407 return false; 6408 } else { 6409 if (const VectorType *VT = Ty->getAs<VectorType>()) 6410 return (VT->getElementType()->isFloat16Type() || 6411 VT->getElementType()->isHalfType()); 6412 return false; 6413 } 6414 } 6415 6416 bool ARMABIInfo::isLegalVectorTypeForSwift(CharUnits vectorSize, 6417 llvm::Type *eltTy, 6418 unsigned numElts) const { 6419 if (!llvm::isPowerOf2_32(numElts)) 6420 return false; 6421 unsigned size = getDataLayout().getTypeStoreSizeInBits(eltTy); 6422 if (size > 64) 6423 return false; 6424 if (vectorSize.getQuantity() != 8 && 6425 (vectorSize.getQuantity() != 16 || numElts == 1)) 6426 return false; 6427 return true; 6428 } 6429 6430 bool ARMABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const { 6431 // Homogeneous aggregates for AAPCS-VFP must have base types of float, 6432 // double, or 64-bit or 128-bit vectors. 6433 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) { 6434 if (BT->getKind() == BuiltinType::Float || 6435 BT->getKind() == BuiltinType::Double || 6436 BT->getKind() == BuiltinType::LongDouble) 6437 return true; 6438 } else if (const VectorType *VT = Ty->getAs<VectorType>()) { 6439 unsigned VecSize = getContext().getTypeSize(VT); 6440 if (VecSize == 64 || VecSize == 128) 6441 return true; 6442 } 6443 return false; 6444 } 6445 6446 bool ARMABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base, 6447 uint64_t Members) const { 6448 return Members <= 4; 6449 } 6450 6451 bool ARMABIInfo::isEffectivelyAAPCS_VFP(unsigned callConvention, 6452 bool acceptHalf) const { 6453 // Give precedence to user-specified calling conventions. 6454 if (callConvention != llvm::CallingConv::C) 6455 return (callConvention == llvm::CallingConv::ARM_AAPCS_VFP); 6456 else 6457 return (getABIKind() == AAPCS_VFP) || 6458 (acceptHalf && (getABIKind() == AAPCS16_VFP)); 6459 } 6460 6461 Address ARMABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 6462 QualType Ty) const { 6463 CharUnits SlotSize = CharUnits::fromQuantity(4); 6464 6465 // Empty records are ignored for parameter passing purposes. 6466 if (isEmptyRecord(getContext(), Ty, true)) { 6467 Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize); 6468 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty)); 6469 return Addr; 6470 } 6471 6472 CharUnits TySize = getContext().getTypeSizeInChars(Ty); 6473 CharUnits TyAlignForABI = getContext().getTypeUnadjustedAlignInChars(Ty); 6474 6475 // Use indirect if size of the illegal vector is bigger than 16 bytes. 6476 bool IsIndirect = false; 6477 const Type *Base = nullptr; 6478 uint64_t Members = 0; 6479 if (TySize > CharUnits::fromQuantity(16) && isIllegalVectorType(Ty)) { 6480 IsIndirect = true; 6481 6482 // ARMv7k passes structs bigger than 16 bytes indirectly, in space 6483 // allocated by the caller. 6484 } else if (TySize > CharUnits::fromQuantity(16) && 6485 getABIKind() == ARMABIInfo::AAPCS16_VFP && 6486 !isHomogeneousAggregate(Ty, Base, Members)) { 6487 IsIndirect = true; 6488 6489 // Otherwise, bound the type's ABI alignment. 6490 // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for 6491 // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte. 6492 // Our callers should be prepared to handle an under-aligned address. 6493 } else if (getABIKind() == ARMABIInfo::AAPCS_VFP || 6494 getABIKind() == ARMABIInfo::AAPCS) { 6495 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4)); 6496 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(8)); 6497 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) { 6498 // ARMv7k allows type alignment up to 16 bytes. 6499 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4)); 6500 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(16)); 6501 } else { 6502 TyAlignForABI = CharUnits::fromQuantity(4); 6503 } 6504 6505 std::pair<CharUnits, CharUnits> TyInfo = { TySize, TyAlignForABI }; 6506 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TyInfo, 6507 SlotSize, /*AllowHigherAlign*/ true); 6508 } 6509 6510 //===----------------------------------------------------------------------===// 6511 // NVPTX ABI Implementation 6512 //===----------------------------------------------------------------------===// 6513 6514 namespace { 6515 6516 class NVPTXTargetCodeGenInfo; 6517 6518 class NVPTXABIInfo : public ABIInfo { 6519 NVPTXTargetCodeGenInfo &CGInfo; 6520 6521 public: 6522 NVPTXABIInfo(CodeGenTypes &CGT, NVPTXTargetCodeGenInfo &Info) 6523 : ABIInfo(CGT), CGInfo(Info) {} 6524 6525 ABIArgInfo classifyReturnType(QualType RetTy) const; 6526 ABIArgInfo classifyArgumentType(QualType Ty) const; 6527 6528 void computeInfo(CGFunctionInfo &FI) const override; 6529 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 6530 QualType Ty) const override; 6531 }; 6532 6533 class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo { 6534 public: 6535 NVPTXTargetCodeGenInfo(CodeGenTypes &CGT) 6536 : TargetCodeGenInfo(std::make_unique<NVPTXABIInfo>(CGT, *this)) {} 6537 6538 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 6539 CodeGen::CodeGenModule &M) const override; 6540 bool shouldEmitStaticExternCAliases() const override; 6541 6542 llvm::Type *getCUDADeviceBuiltinSurfaceDeviceType() const override { 6543 // On the device side, surface reference is represented as an object handle 6544 // in 64-bit integer. 6545 return llvm::Type::getInt64Ty(getABIInfo().getVMContext()); 6546 } 6547 6548 llvm::Type *getCUDADeviceBuiltinTextureDeviceType() const override { 6549 // On the device side, texture reference is represented as an object handle 6550 // in 64-bit integer. 6551 return llvm::Type::getInt64Ty(getABIInfo().getVMContext()); 6552 } 6553 6554 bool emitCUDADeviceBuiltinSurfaceDeviceCopy(CodeGenFunction &CGF, LValue Dst, 6555 LValue Src) const override { 6556 emitBuiltinSurfTexDeviceCopy(CGF, Dst, Src); 6557 return true; 6558 } 6559 6560 bool emitCUDADeviceBuiltinTextureDeviceCopy(CodeGenFunction &CGF, LValue Dst, 6561 LValue Src) const override { 6562 emitBuiltinSurfTexDeviceCopy(CGF, Dst, Src); 6563 return true; 6564 } 6565 6566 private: 6567 // Adds a NamedMDNode with GV, Name, and Operand as operands, and adds the 6568 // resulting MDNode to the nvvm.annotations MDNode. 6569 static void addNVVMMetadata(llvm::GlobalValue *GV, StringRef Name, 6570 int Operand); 6571 6572 static void emitBuiltinSurfTexDeviceCopy(CodeGenFunction &CGF, LValue Dst, 6573 LValue Src) { 6574 llvm::Value *Handle = nullptr; 6575 llvm::Constant *C = 6576 llvm::dyn_cast<llvm::Constant>(Src.getAddress(CGF).getPointer()); 6577 // Lookup `addrspacecast` through the constant pointer if any. 6578 if (auto *ASC = llvm::dyn_cast_or_null<llvm::AddrSpaceCastOperator>(C)) 6579 C = llvm::cast<llvm::Constant>(ASC->getPointerOperand()); 6580 if (auto *GV = llvm::dyn_cast_or_null<llvm::GlobalVariable>(C)) { 6581 // Load the handle from the specific global variable using 6582 // `nvvm.texsurf.handle.internal` intrinsic. 6583 Handle = CGF.EmitRuntimeCall( 6584 CGF.CGM.getIntrinsic(llvm::Intrinsic::nvvm_texsurf_handle_internal, 6585 {GV->getType()}), 6586 {GV}, "texsurf_handle"); 6587 } else 6588 Handle = CGF.EmitLoadOfScalar(Src, SourceLocation()); 6589 CGF.EmitStoreOfScalar(Handle, Dst); 6590 } 6591 }; 6592 6593 /// Checks if the type is unsupported directly by the current target. 6594 static bool isUnsupportedType(ASTContext &Context, QualType T) { 6595 if (!Context.getTargetInfo().hasFloat16Type() && T->isFloat16Type()) 6596 return true; 6597 if (!Context.getTargetInfo().hasFloat128Type() && 6598 (T->isFloat128Type() || 6599 (T->isRealFloatingType() && Context.getTypeSize(T) == 128))) 6600 return true; 6601 if (!Context.getTargetInfo().hasInt128Type() && T->isIntegerType() && 6602 Context.getTypeSize(T) > 64) 6603 return true; 6604 if (const auto *AT = T->getAsArrayTypeUnsafe()) 6605 return isUnsupportedType(Context, AT->getElementType()); 6606 const auto *RT = T->getAs<RecordType>(); 6607 if (!RT) 6608 return false; 6609 const RecordDecl *RD = RT->getDecl(); 6610 6611 // If this is a C++ record, check the bases first. 6612 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 6613 for (const CXXBaseSpecifier &I : CXXRD->bases()) 6614 if (isUnsupportedType(Context, I.getType())) 6615 return true; 6616 6617 for (const FieldDecl *I : RD->fields()) 6618 if (isUnsupportedType(Context, I->getType())) 6619 return true; 6620 return false; 6621 } 6622 6623 /// Coerce the given type into an array with maximum allowed size of elements. 6624 static ABIArgInfo coerceToIntArrayWithLimit(QualType Ty, ASTContext &Context, 6625 llvm::LLVMContext &LLVMContext, 6626 unsigned MaxSize) { 6627 // Alignment and Size are measured in bits. 6628 const uint64_t Size = Context.getTypeSize(Ty); 6629 const uint64_t Alignment = Context.getTypeAlign(Ty); 6630 const unsigned Div = std::min<unsigned>(MaxSize, Alignment); 6631 llvm::Type *IntType = llvm::Type::getIntNTy(LLVMContext, Div); 6632 const uint64_t NumElements = (Size + Div - 1) / Div; 6633 return ABIArgInfo::getDirect(llvm::ArrayType::get(IntType, NumElements)); 6634 } 6635 6636 ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const { 6637 if (RetTy->isVoidType()) 6638 return ABIArgInfo::getIgnore(); 6639 6640 if (getContext().getLangOpts().OpenMP && 6641 getContext().getLangOpts().OpenMPIsDevice && 6642 isUnsupportedType(getContext(), RetTy)) 6643 return coerceToIntArrayWithLimit(RetTy, getContext(), getVMContext(), 64); 6644 6645 // note: this is different from default ABI 6646 if (!RetTy->isScalarType()) 6647 return ABIArgInfo::getDirect(); 6648 6649 // Treat an enum type as its underlying type. 6650 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 6651 RetTy = EnumTy->getDecl()->getIntegerType(); 6652 6653 return (RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy) 6654 : ABIArgInfo::getDirect()); 6655 } 6656 6657 ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const { 6658 // Treat an enum type as its underlying type. 6659 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 6660 Ty = EnumTy->getDecl()->getIntegerType(); 6661 6662 // Return aggregates type as indirect by value 6663 if (isAggregateTypeForABI(Ty)) { 6664 // Under CUDA device compilation, tex/surf builtin types are replaced with 6665 // object types and passed directly. 6666 if (getContext().getLangOpts().CUDAIsDevice) { 6667 if (Ty->isCUDADeviceBuiltinSurfaceType()) 6668 return ABIArgInfo::getDirect( 6669 CGInfo.getCUDADeviceBuiltinSurfaceDeviceType()); 6670 if (Ty->isCUDADeviceBuiltinTextureType()) 6671 return ABIArgInfo::getDirect( 6672 CGInfo.getCUDADeviceBuiltinTextureDeviceType()); 6673 } 6674 return getNaturalAlignIndirect(Ty, /* byval */ true); 6675 } 6676 6677 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty) 6678 : ABIArgInfo::getDirect()); 6679 } 6680 6681 void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const { 6682 if (!getCXXABI().classifyReturnType(FI)) 6683 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 6684 for (auto &I : FI.arguments()) 6685 I.info = classifyArgumentType(I.type); 6686 6687 // Always honor user-specified calling convention. 6688 if (FI.getCallingConvention() != llvm::CallingConv::C) 6689 return; 6690 6691 FI.setEffectiveCallingConvention(getRuntimeCC()); 6692 } 6693 6694 Address NVPTXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 6695 QualType Ty) const { 6696 llvm_unreachable("NVPTX does not support varargs"); 6697 } 6698 6699 void NVPTXTargetCodeGenInfo::setTargetAttributes( 6700 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const { 6701 if (GV->isDeclaration()) 6702 return; 6703 const VarDecl *VD = dyn_cast_or_null<VarDecl>(D); 6704 if (VD) { 6705 if (M.getLangOpts().CUDA) { 6706 if (VD->getType()->isCUDADeviceBuiltinSurfaceType()) 6707 addNVVMMetadata(GV, "surface", 1); 6708 else if (VD->getType()->isCUDADeviceBuiltinTextureType()) 6709 addNVVMMetadata(GV, "texture", 1); 6710 return; 6711 } 6712 } 6713 6714 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D); 6715 if (!FD) return; 6716 6717 llvm::Function *F = cast<llvm::Function>(GV); 6718 6719 // Perform special handling in OpenCL mode 6720 if (M.getLangOpts().OpenCL) { 6721 // Use OpenCL function attributes to check for kernel functions 6722 // By default, all functions are device functions 6723 if (FD->hasAttr<OpenCLKernelAttr>()) { 6724 // OpenCL __kernel functions get kernel metadata 6725 // Create !{<func-ref>, metadata !"kernel", i32 1} node 6726 addNVVMMetadata(F, "kernel", 1); 6727 // And kernel functions are not subject to inlining 6728 F->addFnAttr(llvm::Attribute::NoInline); 6729 } 6730 } 6731 6732 // Perform special handling in CUDA mode. 6733 if (M.getLangOpts().CUDA) { 6734 // CUDA __global__ functions get a kernel metadata entry. Since 6735 // __global__ functions cannot be called from the device, we do not 6736 // need to set the noinline attribute. 6737 if (FD->hasAttr<CUDAGlobalAttr>()) { 6738 // Create !{<func-ref>, metadata !"kernel", i32 1} node 6739 addNVVMMetadata(F, "kernel", 1); 6740 } 6741 if (CUDALaunchBoundsAttr *Attr = FD->getAttr<CUDALaunchBoundsAttr>()) { 6742 // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node 6743 llvm::APSInt MaxThreads(32); 6744 MaxThreads = Attr->getMaxThreads()->EvaluateKnownConstInt(M.getContext()); 6745 if (MaxThreads > 0) 6746 addNVVMMetadata(F, "maxntidx", MaxThreads.getExtValue()); 6747 6748 // min blocks is an optional argument for CUDALaunchBoundsAttr. If it was 6749 // not specified in __launch_bounds__ or if the user specified a 0 value, 6750 // we don't have to add a PTX directive. 6751 if (Attr->getMinBlocks()) { 6752 llvm::APSInt MinBlocks(32); 6753 MinBlocks = Attr->getMinBlocks()->EvaluateKnownConstInt(M.getContext()); 6754 if (MinBlocks > 0) 6755 // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node 6756 addNVVMMetadata(F, "minctasm", MinBlocks.getExtValue()); 6757 } 6758 } 6759 } 6760 } 6761 6762 void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::GlobalValue *GV, 6763 StringRef Name, int Operand) { 6764 llvm::Module *M = GV->getParent(); 6765 llvm::LLVMContext &Ctx = M->getContext(); 6766 6767 // Get "nvvm.annotations" metadata node 6768 llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations"); 6769 6770 llvm::Metadata *MDVals[] = { 6771 llvm::ConstantAsMetadata::get(GV), llvm::MDString::get(Ctx, Name), 6772 llvm::ConstantAsMetadata::get( 6773 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand))}; 6774 // Append metadata to nvvm.annotations 6775 MD->addOperand(llvm::MDNode::get(Ctx, MDVals)); 6776 } 6777 6778 bool NVPTXTargetCodeGenInfo::shouldEmitStaticExternCAliases() const { 6779 return false; 6780 } 6781 } 6782 6783 //===----------------------------------------------------------------------===// 6784 // SystemZ ABI Implementation 6785 //===----------------------------------------------------------------------===// 6786 6787 namespace { 6788 6789 class SystemZABIInfo : public SwiftABIInfo { 6790 bool HasVector; 6791 bool IsSoftFloatABI; 6792 6793 public: 6794 SystemZABIInfo(CodeGenTypes &CGT, bool HV, bool SF) 6795 : SwiftABIInfo(CGT), HasVector(HV), IsSoftFloatABI(SF) {} 6796 6797 bool isPromotableIntegerType(QualType Ty) const; 6798 bool isCompoundType(QualType Ty) const; 6799 bool isVectorArgumentType(QualType Ty) const; 6800 bool isFPArgumentType(QualType Ty) const; 6801 QualType GetSingleElementType(QualType Ty) const; 6802 6803 ABIArgInfo classifyReturnType(QualType RetTy) const; 6804 ABIArgInfo classifyArgumentType(QualType ArgTy) const; 6805 6806 void computeInfo(CGFunctionInfo &FI) const override { 6807 if (!getCXXABI().classifyReturnType(FI)) 6808 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 6809 for (auto &I : FI.arguments()) 6810 I.info = classifyArgumentType(I.type); 6811 } 6812 6813 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 6814 QualType Ty) const override; 6815 6816 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars, 6817 bool asReturnValue) const override { 6818 return occupiesMoreThan(CGT, scalars, /*total*/ 4); 6819 } 6820 bool isSwiftErrorInRegister() const override { 6821 return false; 6822 } 6823 }; 6824 6825 class SystemZTargetCodeGenInfo : public TargetCodeGenInfo { 6826 public: 6827 SystemZTargetCodeGenInfo(CodeGenTypes &CGT, bool HasVector, bool SoftFloatABI) 6828 : TargetCodeGenInfo( 6829 std::make_unique<SystemZABIInfo>(CGT, HasVector, SoftFloatABI)) {} 6830 }; 6831 6832 } 6833 6834 bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const { 6835 // Treat an enum type as its underlying type. 6836 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 6837 Ty = EnumTy->getDecl()->getIntegerType(); 6838 6839 // Promotable integer types are required to be promoted by the ABI. 6840 if (Ty->isPromotableIntegerType()) 6841 return true; 6842 6843 // 32-bit values must also be promoted. 6844 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) 6845 switch (BT->getKind()) { 6846 case BuiltinType::Int: 6847 case BuiltinType::UInt: 6848 return true; 6849 default: 6850 return false; 6851 } 6852 return false; 6853 } 6854 6855 bool SystemZABIInfo::isCompoundType(QualType Ty) const { 6856 return (Ty->isAnyComplexType() || 6857 Ty->isVectorType() || 6858 isAggregateTypeForABI(Ty)); 6859 } 6860 6861 bool SystemZABIInfo::isVectorArgumentType(QualType Ty) const { 6862 return (HasVector && 6863 Ty->isVectorType() && 6864 getContext().getTypeSize(Ty) <= 128); 6865 } 6866 6867 bool SystemZABIInfo::isFPArgumentType(QualType Ty) const { 6868 if (IsSoftFloatABI) 6869 return false; 6870 6871 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) 6872 switch (BT->getKind()) { 6873 case BuiltinType::Float: 6874 case BuiltinType::Double: 6875 return true; 6876 default: 6877 return false; 6878 } 6879 6880 return false; 6881 } 6882 6883 QualType SystemZABIInfo::GetSingleElementType(QualType Ty) const { 6884 if (const RecordType *RT = Ty->getAsStructureType()) { 6885 const RecordDecl *RD = RT->getDecl(); 6886 QualType Found; 6887 6888 // If this is a C++ record, check the bases first. 6889 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 6890 for (const auto &I : CXXRD->bases()) { 6891 QualType Base = I.getType(); 6892 6893 // Empty bases don't affect things either way. 6894 if (isEmptyRecord(getContext(), Base, true)) 6895 continue; 6896 6897 if (!Found.isNull()) 6898 return Ty; 6899 Found = GetSingleElementType(Base); 6900 } 6901 6902 // Check the fields. 6903 for (const auto *FD : RD->fields()) { 6904 // For compatibility with GCC, ignore empty bitfields in C++ mode. 6905 // Unlike isSingleElementStruct(), empty structure and array fields 6906 // do count. So do anonymous bitfields that aren't zero-sized. 6907 if (getContext().getLangOpts().CPlusPlus && 6908 FD->isZeroLengthBitField(getContext())) 6909 continue; 6910 6911 // Unlike isSingleElementStruct(), arrays do not count. 6912 // Nested structures still do though. 6913 if (!Found.isNull()) 6914 return Ty; 6915 Found = GetSingleElementType(FD->getType()); 6916 } 6917 6918 // Unlike isSingleElementStruct(), trailing padding is allowed. 6919 // An 8-byte aligned struct s { float f; } is passed as a double. 6920 if (!Found.isNull()) 6921 return Found; 6922 } 6923 6924 return Ty; 6925 } 6926 6927 Address SystemZABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 6928 QualType Ty) const { 6929 // Assume that va_list type is correct; should be pointer to LLVM type: 6930 // struct { 6931 // i64 __gpr; 6932 // i64 __fpr; 6933 // i8 *__overflow_arg_area; 6934 // i8 *__reg_save_area; 6935 // }; 6936 6937 // Every non-vector argument occupies 8 bytes and is passed by preference 6938 // in either GPRs or FPRs. Vector arguments occupy 8 or 16 bytes and are 6939 // always passed on the stack. 6940 Ty = getContext().getCanonicalType(Ty); 6941 auto TyInfo = getContext().getTypeInfoInChars(Ty); 6942 llvm::Type *ArgTy = CGF.ConvertTypeForMem(Ty); 6943 llvm::Type *DirectTy = ArgTy; 6944 ABIArgInfo AI = classifyArgumentType(Ty); 6945 bool IsIndirect = AI.isIndirect(); 6946 bool InFPRs = false; 6947 bool IsVector = false; 6948 CharUnits UnpaddedSize; 6949 CharUnits DirectAlign; 6950 if (IsIndirect) { 6951 DirectTy = llvm::PointerType::getUnqual(DirectTy); 6952 UnpaddedSize = DirectAlign = CharUnits::fromQuantity(8); 6953 } else { 6954 if (AI.getCoerceToType()) 6955 ArgTy = AI.getCoerceToType(); 6956 InFPRs = (!IsSoftFloatABI && (ArgTy->isFloatTy() || ArgTy->isDoubleTy())); 6957 IsVector = ArgTy->isVectorTy(); 6958 UnpaddedSize = TyInfo.first; 6959 DirectAlign = TyInfo.second; 6960 } 6961 CharUnits PaddedSize = CharUnits::fromQuantity(8); 6962 if (IsVector && UnpaddedSize > PaddedSize) 6963 PaddedSize = CharUnits::fromQuantity(16); 6964 assert((UnpaddedSize <= PaddedSize) && "Invalid argument size."); 6965 6966 CharUnits Padding = (PaddedSize - UnpaddedSize); 6967 6968 llvm::Type *IndexTy = CGF.Int64Ty; 6969 llvm::Value *PaddedSizeV = 6970 llvm::ConstantInt::get(IndexTy, PaddedSize.getQuantity()); 6971 6972 if (IsVector) { 6973 // Work out the address of a vector argument on the stack. 6974 // Vector arguments are always passed in the high bits of a 6975 // single (8 byte) or double (16 byte) stack slot. 6976 Address OverflowArgAreaPtr = 6977 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr"); 6978 Address OverflowArgArea = 6979 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"), 6980 TyInfo.second); 6981 Address MemAddr = 6982 CGF.Builder.CreateElementBitCast(OverflowArgArea, DirectTy, "mem_addr"); 6983 6984 // Update overflow_arg_area_ptr pointer 6985 llvm::Value *NewOverflowArgArea = 6986 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV, 6987 "overflow_arg_area"); 6988 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr); 6989 6990 return MemAddr; 6991 } 6992 6993 assert(PaddedSize.getQuantity() == 8); 6994 6995 unsigned MaxRegs, RegCountField, RegSaveIndex; 6996 CharUnits RegPadding; 6997 if (InFPRs) { 6998 MaxRegs = 4; // Maximum of 4 FPR arguments 6999 RegCountField = 1; // __fpr 7000 RegSaveIndex = 16; // save offset for f0 7001 RegPadding = CharUnits(); // floats are passed in the high bits of an FPR 7002 } else { 7003 MaxRegs = 5; // Maximum of 5 GPR arguments 7004 RegCountField = 0; // __gpr 7005 RegSaveIndex = 2; // save offset for r2 7006 RegPadding = Padding; // values are passed in the low bits of a GPR 7007 } 7008 7009 Address RegCountPtr = 7010 CGF.Builder.CreateStructGEP(VAListAddr, RegCountField, "reg_count_ptr"); 7011 llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count"); 7012 llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs); 7013 llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV, 7014 "fits_in_regs"); 7015 7016 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg"); 7017 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem"); 7018 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end"); 7019 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock); 7020 7021 // Emit code to load the value if it was passed in registers. 7022 CGF.EmitBlock(InRegBlock); 7023 7024 // Work out the address of an argument register. 7025 llvm::Value *ScaledRegCount = 7026 CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count"); 7027 llvm::Value *RegBase = 7028 llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize.getQuantity() 7029 + RegPadding.getQuantity()); 7030 llvm::Value *RegOffset = 7031 CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset"); 7032 Address RegSaveAreaPtr = 7033 CGF.Builder.CreateStructGEP(VAListAddr, 3, "reg_save_area_ptr"); 7034 llvm::Value *RegSaveArea = 7035 CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area"); 7036 Address RawRegAddr(CGF.Builder.CreateGEP(RegSaveArea, RegOffset, 7037 "raw_reg_addr"), 7038 PaddedSize); 7039 Address RegAddr = 7040 CGF.Builder.CreateElementBitCast(RawRegAddr, DirectTy, "reg_addr"); 7041 7042 // Update the register count 7043 llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1); 7044 llvm::Value *NewRegCount = 7045 CGF.Builder.CreateAdd(RegCount, One, "reg_count"); 7046 CGF.Builder.CreateStore(NewRegCount, RegCountPtr); 7047 CGF.EmitBranch(ContBlock); 7048 7049 // Emit code to load the value if it was passed in memory. 7050 CGF.EmitBlock(InMemBlock); 7051 7052 // Work out the address of a stack argument. 7053 Address OverflowArgAreaPtr = 7054 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr"); 7055 Address OverflowArgArea = 7056 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"), 7057 PaddedSize); 7058 Address RawMemAddr = 7059 CGF.Builder.CreateConstByteGEP(OverflowArgArea, Padding, "raw_mem_addr"); 7060 Address MemAddr = 7061 CGF.Builder.CreateElementBitCast(RawMemAddr, DirectTy, "mem_addr"); 7062 7063 // Update overflow_arg_area_ptr pointer 7064 llvm::Value *NewOverflowArgArea = 7065 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV, 7066 "overflow_arg_area"); 7067 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr); 7068 CGF.EmitBranch(ContBlock); 7069 7070 // Return the appropriate result. 7071 CGF.EmitBlock(ContBlock); 7072 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, 7073 MemAddr, InMemBlock, "va_arg.addr"); 7074 7075 if (IsIndirect) 7076 ResAddr = Address(CGF.Builder.CreateLoad(ResAddr, "indirect_arg"), 7077 TyInfo.second); 7078 7079 return ResAddr; 7080 } 7081 7082 ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const { 7083 if (RetTy->isVoidType()) 7084 return ABIArgInfo::getIgnore(); 7085 if (isVectorArgumentType(RetTy)) 7086 return ABIArgInfo::getDirect(); 7087 if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64) 7088 return getNaturalAlignIndirect(RetTy); 7089 return (isPromotableIntegerType(RetTy) ? ABIArgInfo::getExtend(RetTy) 7090 : ABIArgInfo::getDirect()); 7091 } 7092 7093 ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const { 7094 // Handle the generic C++ ABI. 7095 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 7096 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 7097 7098 // Integers and enums are extended to full register width. 7099 if (isPromotableIntegerType(Ty)) 7100 return ABIArgInfo::getExtend(Ty); 7101 7102 // Handle vector types and vector-like structure types. Note that 7103 // as opposed to float-like structure types, we do not allow any 7104 // padding for vector-like structures, so verify the sizes match. 7105 uint64_t Size = getContext().getTypeSize(Ty); 7106 QualType SingleElementTy = GetSingleElementType(Ty); 7107 if (isVectorArgumentType(SingleElementTy) && 7108 getContext().getTypeSize(SingleElementTy) == Size) 7109 return ABIArgInfo::getDirect(CGT.ConvertType(SingleElementTy)); 7110 7111 // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly. 7112 if (Size != 8 && Size != 16 && Size != 32 && Size != 64) 7113 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 7114 7115 // Handle small structures. 7116 if (const RecordType *RT = Ty->getAs<RecordType>()) { 7117 // Structures with flexible arrays have variable length, so really 7118 // fail the size test above. 7119 const RecordDecl *RD = RT->getDecl(); 7120 if (RD->hasFlexibleArrayMember()) 7121 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 7122 7123 // The structure is passed as an unextended integer, a float, or a double. 7124 llvm::Type *PassTy; 7125 if (isFPArgumentType(SingleElementTy)) { 7126 assert(Size == 32 || Size == 64); 7127 if (Size == 32) 7128 PassTy = llvm::Type::getFloatTy(getVMContext()); 7129 else 7130 PassTy = llvm::Type::getDoubleTy(getVMContext()); 7131 } else 7132 PassTy = llvm::IntegerType::get(getVMContext(), Size); 7133 return ABIArgInfo::getDirect(PassTy); 7134 } 7135 7136 // Non-structure compounds are passed indirectly. 7137 if (isCompoundType(Ty)) 7138 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 7139 7140 return ABIArgInfo::getDirect(nullptr); 7141 } 7142 7143 //===----------------------------------------------------------------------===// 7144 // MSP430 ABI Implementation 7145 //===----------------------------------------------------------------------===// 7146 7147 namespace { 7148 7149 class MSP430TargetCodeGenInfo : public TargetCodeGenInfo { 7150 public: 7151 MSP430TargetCodeGenInfo(CodeGenTypes &CGT) 7152 : TargetCodeGenInfo(std::make_unique<DefaultABIInfo>(CGT)) {} 7153 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 7154 CodeGen::CodeGenModule &M) const override; 7155 }; 7156 7157 } 7158 7159 void MSP430TargetCodeGenInfo::setTargetAttributes( 7160 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const { 7161 if (GV->isDeclaration()) 7162 return; 7163 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) { 7164 const auto *InterruptAttr = FD->getAttr<MSP430InterruptAttr>(); 7165 if (!InterruptAttr) 7166 return; 7167 7168 // Handle 'interrupt' attribute: 7169 llvm::Function *F = cast<llvm::Function>(GV); 7170 7171 // Step 1: Set ISR calling convention. 7172 F->setCallingConv(llvm::CallingConv::MSP430_INTR); 7173 7174 // Step 2: Add attributes goodness. 7175 F->addFnAttr(llvm::Attribute::NoInline); 7176 F->addFnAttr("interrupt", llvm::utostr(InterruptAttr->getNumber())); 7177 } 7178 } 7179 7180 //===----------------------------------------------------------------------===// 7181 // MIPS ABI Implementation. This works for both little-endian and 7182 // big-endian variants. 7183 //===----------------------------------------------------------------------===// 7184 7185 namespace { 7186 class MipsABIInfo : public ABIInfo { 7187 bool IsO32; 7188 unsigned MinABIStackAlignInBytes, StackAlignInBytes; 7189 void CoerceToIntArgs(uint64_t TySize, 7190 SmallVectorImpl<llvm::Type *> &ArgList) const; 7191 llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const; 7192 llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const; 7193 llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const; 7194 public: 7195 MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) : 7196 ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8), 7197 StackAlignInBytes(IsO32 ? 8 : 16) {} 7198 7199 ABIArgInfo classifyReturnType(QualType RetTy) const; 7200 ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const; 7201 void computeInfo(CGFunctionInfo &FI) const override; 7202 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 7203 QualType Ty) const override; 7204 ABIArgInfo extendType(QualType Ty) const; 7205 }; 7206 7207 class MIPSTargetCodeGenInfo : public TargetCodeGenInfo { 7208 unsigned SizeOfUnwindException; 7209 public: 7210 MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32) 7211 : TargetCodeGenInfo(std::make_unique<MipsABIInfo>(CGT, IsO32)), 7212 SizeOfUnwindException(IsO32 ? 24 : 32) {} 7213 7214 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override { 7215 return 29; 7216 } 7217 7218 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 7219 CodeGen::CodeGenModule &CGM) const override { 7220 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D); 7221 if (!FD) return; 7222 llvm::Function *Fn = cast<llvm::Function>(GV); 7223 7224 if (FD->hasAttr<MipsLongCallAttr>()) 7225 Fn->addFnAttr("long-call"); 7226 else if (FD->hasAttr<MipsShortCallAttr>()) 7227 Fn->addFnAttr("short-call"); 7228 7229 // Other attributes do not have a meaning for declarations. 7230 if (GV->isDeclaration()) 7231 return; 7232 7233 if (FD->hasAttr<Mips16Attr>()) { 7234 Fn->addFnAttr("mips16"); 7235 } 7236 else if (FD->hasAttr<NoMips16Attr>()) { 7237 Fn->addFnAttr("nomips16"); 7238 } 7239 7240 if (FD->hasAttr<MicroMipsAttr>()) 7241 Fn->addFnAttr("micromips"); 7242 else if (FD->hasAttr<NoMicroMipsAttr>()) 7243 Fn->addFnAttr("nomicromips"); 7244 7245 const MipsInterruptAttr *Attr = FD->getAttr<MipsInterruptAttr>(); 7246 if (!Attr) 7247 return; 7248 7249 const char *Kind; 7250 switch (Attr->getInterrupt()) { 7251 case MipsInterruptAttr::eic: Kind = "eic"; break; 7252 case MipsInterruptAttr::sw0: Kind = "sw0"; break; 7253 case MipsInterruptAttr::sw1: Kind = "sw1"; break; 7254 case MipsInterruptAttr::hw0: Kind = "hw0"; break; 7255 case MipsInterruptAttr::hw1: Kind = "hw1"; break; 7256 case MipsInterruptAttr::hw2: Kind = "hw2"; break; 7257 case MipsInterruptAttr::hw3: Kind = "hw3"; break; 7258 case MipsInterruptAttr::hw4: Kind = "hw4"; break; 7259 case MipsInterruptAttr::hw5: Kind = "hw5"; break; 7260 } 7261 7262 Fn->addFnAttr("interrupt", Kind); 7263 7264 } 7265 7266 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 7267 llvm::Value *Address) const override; 7268 7269 unsigned getSizeOfUnwindException() const override { 7270 return SizeOfUnwindException; 7271 } 7272 }; 7273 } 7274 7275 void MipsABIInfo::CoerceToIntArgs( 7276 uint64_t TySize, SmallVectorImpl<llvm::Type *> &ArgList) const { 7277 llvm::IntegerType *IntTy = 7278 llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8); 7279 7280 // Add (TySize / MinABIStackAlignInBytes) args of IntTy. 7281 for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N) 7282 ArgList.push_back(IntTy); 7283 7284 // If necessary, add one more integer type to ArgList. 7285 unsigned R = TySize % (MinABIStackAlignInBytes * 8); 7286 7287 if (R) 7288 ArgList.push_back(llvm::IntegerType::get(getVMContext(), R)); 7289 } 7290 7291 // In N32/64, an aligned double precision floating point field is passed in 7292 // a register. 7293 llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const { 7294 SmallVector<llvm::Type*, 8> ArgList, IntArgList; 7295 7296 if (IsO32) { 7297 CoerceToIntArgs(TySize, ArgList); 7298 return llvm::StructType::get(getVMContext(), ArgList); 7299 } 7300 7301 if (Ty->isComplexType()) 7302 return CGT.ConvertType(Ty); 7303 7304 const RecordType *RT = Ty->getAs<RecordType>(); 7305 7306 // Unions/vectors are passed in integer registers. 7307 if (!RT || !RT->isStructureOrClassType()) { 7308 CoerceToIntArgs(TySize, ArgList); 7309 return llvm::StructType::get(getVMContext(), ArgList); 7310 } 7311 7312 const RecordDecl *RD = RT->getDecl(); 7313 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD); 7314 assert(!(TySize % 8) && "Size of structure must be multiple of 8."); 7315 7316 uint64_t LastOffset = 0; 7317 unsigned idx = 0; 7318 llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64); 7319 7320 // Iterate over fields in the struct/class and check if there are any aligned 7321 // double fields. 7322 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 7323 i != e; ++i, ++idx) { 7324 const QualType Ty = i->getType(); 7325 const BuiltinType *BT = Ty->getAs<BuiltinType>(); 7326 7327 if (!BT || BT->getKind() != BuiltinType::Double) 7328 continue; 7329 7330 uint64_t Offset = Layout.getFieldOffset(idx); 7331 if (Offset % 64) // Ignore doubles that are not aligned. 7332 continue; 7333 7334 // Add ((Offset - LastOffset) / 64) args of type i64. 7335 for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j) 7336 ArgList.push_back(I64); 7337 7338 // Add double type. 7339 ArgList.push_back(llvm::Type::getDoubleTy(getVMContext())); 7340 LastOffset = Offset + 64; 7341 } 7342 7343 CoerceToIntArgs(TySize - LastOffset, IntArgList); 7344 ArgList.append(IntArgList.begin(), IntArgList.end()); 7345 7346 return llvm::StructType::get(getVMContext(), ArgList); 7347 } 7348 7349 llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset, 7350 uint64_t Offset) const { 7351 if (OrigOffset + MinABIStackAlignInBytes > Offset) 7352 return nullptr; 7353 7354 return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8); 7355 } 7356 7357 ABIArgInfo 7358 MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const { 7359 Ty = useFirstFieldIfTransparentUnion(Ty); 7360 7361 uint64_t OrigOffset = Offset; 7362 uint64_t TySize = getContext().getTypeSize(Ty); 7363 uint64_t Align = getContext().getTypeAlign(Ty) / 8; 7364 7365 Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes), 7366 (uint64_t)StackAlignInBytes); 7367 unsigned CurrOffset = llvm::alignTo(Offset, Align); 7368 Offset = CurrOffset + llvm::alignTo(TySize, Align * 8) / 8; 7369 7370 if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) { 7371 // Ignore empty aggregates. 7372 if (TySize == 0) 7373 return ABIArgInfo::getIgnore(); 7374 7375 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) { 7376 Offset = OrigOffset + MinABIStackAlignInBytes; 7377 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 7378 } 7379 7380 // If we have reached here, aggregates are passed directly by coercing to 7381 // another structure type. Padding is inserted if the offset of the 7382 // aggregate is unaligned. 7383 ABIArgInfo ArgInfo = 7384 ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0, 7385 getPaddingType(OrigOffset, CurrOffset)); 7386 ArgInfo.setInReg(true); 7387 return ArgInfo; 7388 } 7389 7390 // Treat an enum type as its underlying type. 7391 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 7392 Ty = EnumTy->getDecl()->getIntegerType(); 7393 7394 // All integral types are promoted to the GPR width. 7395 if (Ty->isIntegralOrEnumerationType()) 7396 return extendType(Ty); 7397 7398 return ABIArgInfo::getDirect( 7399 nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset)); 7400 } 7401 7402 llvm::Type* 7403 MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const { 7404 const RecordType *RT = RetTy->getAs<RecordType>(); 7405 SmallVector<llvm::Type*, 8> RTList; 7406 7407 if (RT && RT->isStructureOrClassType()) { 7408 const RecordDecl *RD = RT->getDecl(); 7409 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD); 7410 unsigned FieldCnt = Layout.getFieldCount(); 7411 7412 // N32/64 returns struct/classes in floating point registers if the 7413 // following conditions are met: 7414 // 1. The size of the struct/class is no larger than 128-bit. 7415 // 2. The struct/class has one or two fields all of which are floating 7416 // point types. 7417 // 3. The offset of the first field is zero (this follows what gcc does). 7418 // 7419 // Any other composite results are returned in integer registers. 7420 // 7421 if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) { 7422 RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end(); 7423 for (; b != e; ++b) { 7424 const BuiltinType *BT = b->getType()->getAs<BuiltinType>(); 7425 7426 if (!BT || !BT->isFloatingPoint()) 7427 break; 7428 7429 RTList.push_back(CGT.ConvertType(b->getType())); 7430 } 7431 7432 if (b == e) 7433 return llvm::StructType::get(getVMContext(), RTList, 7434 RD->hasAttr<PackedAttr>()); 7435 7436 RTList.clear(); 7437 } 7438 } 7439 7440 CoerceToIntArgs(Size, RTList); 7441 return llvm::StructType::get(getVMContext(), RTList); 7442 } 7443 7444 ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const { 7445 uint64_t Size = getContext().getTypeSize(RetTy); 7446 7447 if (RetTy->isVoidType()) 7448 return ABIArgInfo::getIgnore(); 7449 7450 // O32 doesn't treat zero-sized structs differently from other structs. 7451 // However, N32/N64 ignores zero sized return values. 7452 if (!IsO32 && Size == 0) 7453 return ABIArgInfo::getIgnore(); 7454 7455 if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) { 7456 if (Size <= 128) { 7457 if (RetTy->isAnyComplexType()) 7458 return ABIArgInfo::getDirect(); 7459 7460 // O32 returns integer vectors in registers and N32/N64 returns all small 7461 // aggregates in registers. 7462 if (!IsO32 || 7463 (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) { 7464 ABIArgInfo ArgInfo = 7465 ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size)); 7466 ArgInfo.setInReg(true); 7467 return ArgInfo; 7468 } 7469 } 7470 7471 return getNaturalAlignIndirect(RetTy); 7472 } 7473 7474 // Treat an enum type as its underlying type. 7475 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 7476 RetTy = EnumTy->getDecl()->getIntegerType(); 7477 7478 if (RetTy->isPromotableIntegerType()) 7479 return ABIArgInfo::getExtend(RetTy); 7480 7481 if ((RetTy->isUnsignedIntegerOrEnumerationType() || 7482 RetTy->isSignedIntegerOrEnumerationType()) && Size == 32 && !IsO32) 7483 return ABIArgInfo::getSignExtend(RetTy); 7484 7485 return ABIArgInfo::getDirect(); 7486 } 7487 7488 void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const { 7489 ABIArgInfo &RetInfo = FI.getReturnInfo(); 7490 if (!getCXXABI().classifyReturnType(FI)) 7491 RetInfo = classifyReturnType(FI.getReturnType()); 7492 7493 // Check if a pointer to an aggregate is passed as a hidden argument. 7494 uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0; 7495 7496 for (auto &I : FI.arguments()) 7497 I.info = classifyArgumentType(I.type, Offset); 7498 } 7499 7500 Address MipsABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 7501 QualType OrigTy) const { 7502 QualType Ty = OrigTy; 7503 7504 // Integer arguments are promoted to 32-bit on O32 and 64-bit on N32/N64. 7505 // Pointers are also promoted in the same way but this only matters for N32. 7506 unsigned SlotSizeInBits = IsO32 ? 32 : 64; 7507 unsigned PtrWidth = getTarget().getPointerWidth(0); 7508 bool DidPromote = false; 7509 if ((Ty->isIntegerType() && 7510 getContext().getIntWidth(Ty) < SlotSizeInBits) || 7511 (Ty->isPointerType() && PtrWidth < SlotSizeInBits)) { 7512 DidPromote = true; 7513 Ty = getContext().getIntTypeForBitwidth(SlotSizeInBits, 7514 Ty->isSignedIntegerType()); 7515 } 7516 7517 auto TyInfo = getContext().getTypeInfoInChars(Ty); 7518 7519 // The alignment of things in the argument area is never larger than 7520 // StackAlignInBytes. 7521 TyInfo.second = 7522 std::min(TyInfo.second, CharUnits::fromQuantity(StackAlignInBytes)); 7523 7524 // MinABIStackAlignInBytes is the size of argument slots on the stack. 7525 CharUnits ArgSlotSize = CharUnits::fromQuantity(MinABIStackAlignInBytes); 7526 7527 Address Addr = emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false, 7528 TyInfo, ArgSlotSize, /*AllowHigherAlign*/ true); 7529 7530 7531 // If there was a promotion, "unpromote" into a temporary. 7532 // TODO: can we just use a pointer into a subset of the original slot? 7533 if (DidPromote) { 7534 Address Temp = CGF.CreateMemTemp(OrigTy, "vaarg.promotion-temp"); 7535 llvm::Value *Promoted = CGF.Builder.CreateLoad(Addr); 7536 7537 // Truncate down to the right width. 7538 llvm::Type *IntTy = (OrigTy->isIntegerType() ? Temp.getElementType() 7539 : CGF.IntPtrTy); 7540 llvm::Value *V = CGF.Builder.CreateTrunc(Promoted, IntTy); 7541 if (OrigTy->isPointerType()) 7542 V = CGF.Builder.CreateIntToPtr(V, Temp.getElementType()); 7543 7544 CGF.Builder.CreateStore(V, Temp); 7545 Addr = Temp; 7546 } 7547 7548 return Addr; 7549 } 7550 7551 ABIArgInfo MipsABIInfo::extendType(QualType Ty) const { 7552 int TySize = getContext().getTypeSize(Ty); 7553 7554 // MIPS64 ABI requires unsigned 32 bit integers to be sign extended. 7555 if (Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32) 7556 return ABIArgInfo::getSignExtend(Ty); 7557 7558 return ABIArgInfo::getExtend(Ty); 7559 } 7560 7561 bool 7562 MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 7563 llvm::Value *Address) const { 7564 // This information comes from gcc's implementation, which seems to 7565 // as canonical as it gets. 7566 7567 // Everything on MIPS is 4 bytes. Double-precision FP registers 7568 // are aliased to pairs of single-precision FP registers. 7569 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4); 7570 7571 // 0-31 are the general purpose registers, $0 - $31. 7572 // 32-63 are the floating-point registers, $f0 - $f31. 7573 // 64 and 65 are the multiply/divide registers, $hi and $lo. 7574 // 66 is the (notional, I think) register for signal-handler return. 7575 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65); 7576 7577 // 67-74 are the floating-point status registers, $fcc0 - $fcc7. 7578 // They are one bit wide and ignored here. 7579 7580 // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31. 7581 // (coprocessor 1 is the FP unit) 7582 // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31. 7583 // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31. 7584 // 176-181 are the DSP accumulator registers. 7585 AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181); 7586 return false; 7587 } 7588 7589 //===----------------------------------------------------------------------===// 7590 // AVR ABI Implementation. 7591 //===----------------------------------------------------------------------===// 7592 7593 namespace { 7594 class AVRTargetCodeGenInfo : public TargetCodeGenInfo { 7595 public: 7596 AVRTargetCodeGenInfo(CodeGenTypes &CGT) 7597 : TargetCodeGenInfo(std::make_unique<DefaultABIInfo>(CGT)) {} 7598 7599 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 7600 CodeGen::CodeGenModule &CGM) const override { 7601 if (GV->isDeclaration()) 7602 return; 7603 const auto *FD = dyn_cast_or_null<FunctionDecl>(D); 7604 if (!FD) return; 7605 auto *Fn = cast<llvm::Function>(GV); 7606 7607 if (FD->getAttr<AVRInterruptAttr>()) 7608 Fn->addFnAttr("interrupt"); 7609 7610 if (FD->getAttr<AVRSignalAttr>()) 7611 Fn->addFnAttr("signal"); 7612 } 7613 }; 7614 } 7615 7616 //===----------------------------------------------------------------------===// 7617 // TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults. 7618 // Currently subclassed only to implement custom OpenCL C function attribute 7619 // handling. 7620 //===----------------------------------------------------------------------===// 7621 7622 namespace { 7623 7624 class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo { 7625 public: 7626 TCETargetCodeGenInfo(CodeGenTypes &CGT) 7627 : DefaultTargetCodeGenInfo(CGT) {} 7628 7629 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 7630 CodeGen::CodeGenModule &M) const override; 7631 }; 7632 7633 void TCETargetCodeGenInfo::setTargetAttributes( 7634 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const { 7635 if (GV->isDeclaration()) 7636 return; 7637 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D); 7638 if (!FD) return; 7639 7640 llvm::Function *F = cast<llvm::Function>(GV); 7641 7642 if (M.getLangOpts().OpenCL) { 7643 if (FD->hasAttr<OpenCLKernelAttr>()) { 7644 // OpenCL C Kernel functions are not subject to inlining 7645 F->addFnAttr(llvm::Attribute::NoInline); 7646 const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>(); 7647 if (Attr) { 7648 // Convert the reqd_work_group_size() attributes to metadata. 7649 llvm::LLVMContext &Context = F->getContext(); 7650 llvm::NamedMDNode *OpenCLMetadata = 7651 M.getModule().getOrInsertNamedMetadata( 7652 "opencl.kernel_wg_size_info"); 7653 7654 SmallVector<llvm::Metadata *, 5> Operands; 7655 Operands.push_back(llvm::ConstantAsMetadata::get(F)); 7656 7657 Operands.push_back( 7658 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue( 7659 M.Int32Ty, llvm::APInt(32, Attr->getXDim())))); 7660 Operands.push_back( 7661 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue( 7662 M.Int32Ty, llvm::APInt(32, Attr->getYDim())))); 7663 Operands.push_back( 7664 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue( 7665 M.Int32Ty, llvm::APInt(32, Attr->getZDim())))); 7666 7667 // Add a boolean constant operand for "required" (true) or "hint" 7668 // (false) for implementing the work_group_size_hint attr later. 7669 // Currently always true as the hint is not yet implemented. 7670 Operands.push_back( 7671 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getTrue(Context))); 7672 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands)); 7673 } 7674 } 7675 } 7676 } 7677 7678 } 7679 7680 //===----------------------------------------------------------------------===// 7681 // Hexagon ABI Implementation 7682 //===----------------------------------------------------------------------===// 7683 7684 namespace { 7685 7686 class HexagonABIInfo : public DefaultABIInfo { 7687 public: 7688 HexagonABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {} 7689 7690 private: 7691 ABIArgInfo classifyReturnType(QualType RetTy) const; 7692 ABIArgInfo classifyArgumentType(QualType RetTy) const; 7693 ABIArgInfo classifyArgumentType(QualType RetTy, unsigned *RegsLeft) const; 7694 7695 void computeInfo(CGFunctionInfo &FI) const override; 7696 7697 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 7698 QualType Ty) const override; 7699 Address EmitVAArgFromMemory(CodeGenFunction &CFG, Address VAListAddr, 7700 QualType Ty) const; 7701 Address EmitVAArgForHexagon(CodeGenFunction &CFG, Address VAListAddr, 7702 QualType Ty) const; 7703 Address EmitVAArgForHexagonLinux(CodeGenFunction &CFG, Address VAListAddr, 7704 QualType Ty) const; 7705 }; 7706 7707 class HexagonTargetCodeGenInfo : public TargetCodeGenInfo { 7708 public: 7709 HexagonTargetCodeGenInfo(CodeGenTypes &CGT) 7710 : TargetCodeGenInfo(std::make_unique<HexagonABIInfo>(CGT)) {} 7711 7712 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 7713 return 29; 7714 } 7715 7716 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 7717 CodeGen::CodeGenModule &GCM) const override { 7718 if (GV->isDeclaration()) 7719 return; 7720 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D); 7721 if (!FD) 7722 return; 7723 } 7724 }; 7725 7726 } // namespace 7727 7728 void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const { 7729 unsigned RegsLeft = 6; 7730 if (!getCXXABI().classifyReturnType(FI)) 7731 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 7732 for (auto &I : FI.arguments()) 7733 I.info = classifyArgumentType(I.type, &RegsLeft); 7734 } 7735 7736 static bool HexagonAdjustRegsLeft(uint64_t Size, unsigned *RegsLeft) { 7737 assert(Size <= 64 && "Not expecting to pass arguments larger than 64 bits" 7738 " through registers"); 7739 7740 if (*RegsLeft == 0) 7741 return false; 7742 7743 if (Size <= 32) { 7744 (*RegsLeft)--; 7745 return true; 7746 } 7747 7748 if (2 <= (*RegsLeft & (~1U))) { 7749 *RegsLeft = (*RegsLeft & (~1U)) - 2; 7750 return true; 7751 } 7752 7753 // Next available register was r5 but candidate was greater than 32-bits so it 7754 // has to go on the stack. However we still consume r5 7755 if (*RegsLeft == 1) 7756 *RegsLeft = 0; 7757 7758 return false; 7759 } 7760 7761 ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty, 7762 unsigned *RegsLeft) const { 7763 if (!isAggregateTypeForABI(Ty)) { 7764 // Treat an enum type as its underlying type. 7765 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 7766 Ty = EnumTy->getDecl()->getIntegerType(); 7767 7768 uint64_t Size = getContext().getTypeSize(Ty); 7769 if (Size <= 64) 7770 HexagonAdjustRegsLeft(Size, RegsLeft); 7771 7772 return Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty) 7773 : ABIArgInfo::getDirect(); 7774 } 7775 7776 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 7777 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 7778 7779 // Ignore empty records. 7780 if (isEmptyRecord(getContext(), Ty, true)) 7781 return ABIArgInfo::getIgnore(); 7782 7783 uint64_t Size = getContext().getTypeSize(Ty); 7784 unsigned Align = getContext().getTypeAlign(Ty); 7785 7786 if (Size > 64) 7787 return getNaturalAlignIndirect(Ty, /*ByVal=*/true); 7788 7789 if (HexagonAdjustRegsLeft(Size, RegsLeft)) 7790 Align = Size <= 32 ? 32 : 64; 7791 if (Size <= Align) { 7792 // Pass in the smallest viable integer type. 7793 if (!llvm::isPowerOf2_64(Size)) 7794 Size = llvm::NextPowerOf2(Size); 7795 return ABIArgInfo::getDirect(llvm::Type::getIntNTy(getVMContext(), Size)); 7796 } 7797 return DefaultABIInfo::classifyArgumentType(Ty); 7798 } 7799 7800 ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const { 7801 if (RetTy->isVoidType()) 7802 return ABIArgInfo::getIgnore(); 7803 7804 const TargetInfo &T = CGT.getTarget(); 7805 uint64_t Size = getContext().getTypeSize(RetTy); 7806 7807 if (RetTy->getAs<VectorType>()) { 7808 // HVX vectors are returned in vector registers or register pairs. 7809 if (T.hasFeature("hvx")) { 7810 assert(T.hasFeature("hvx-length64b") || T.hasFeature("hvx-length128b")); 7811 uint64_t VecSize = T.hasFeature("hvx-length64b") ? 64*8 : 128*8; 7812 if (Size == VecSize || Size == 2*VecSize) 7813 return ABIArgInfo::getDirectInReg(); 7814 } 7815 // Large vector types should be returned via memory. 7816 if (Size > 64) 7817 return getNaturalAlignIndirect(RetTy); 7818 } 7819 7820 if (!isAggregateTypeForABI(RetTy)) { 7821 // Treat an enum type as its underlying type. 7822 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 7823 RetTy = EnumTy->getDecl()->getIntegerType(); 7824 7825 return RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy) 7826 : ABIArgInfo::getDirect(); 7827 } 7828 7829 if (isEmptyRecord(getContext(), RetTy, true)) 7830 return ABIArgInfo::getIgnore(); 7831 7832 // Aggregates <= 8 bytes are returned in registers, other aggregates 7833 // are returned indirectly. 7834 if (Size <= 64) { 7835 // Return in the smallest viable integer type. 7836 if (!llvm::isPowerOf2_64(Size)) 7837 Size = llvm::NextPowerOf2(Size); 7838 return ABIArgInfo::getDirect(llvm::Type::getIntNTy(getVMContext(), Size)); 7839 } 7840 return getNaturalAlignIndirect(RetTy, /*ByVal=*/true); 7841 } 7842 7843 Address HexagonABIInfo::EmitVAArgFromMemory(CodeGenFunction &CGF, 7844 Address VAListAddr, 7845 QualType Ty) const { 7846 // Load the overflow area pointer. 7847 Address __overflow_area_pointer_p = 7848 CGF.Builder.CreateStructGEP(VAListAddr, 2, "__overflow_area_pointer_p"); 7849 llvm::Value *__overflow_area_pointer = CGF.Builder.CreateLoad( 7850 __overflow_area_pointer_p, "__overflow_area_pointer"); 7851 7852 uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8; 7853 if (Align > 4) { 7854 // Alignment should be a power of 2. 7855 assert((Align & (Align - 1)) == 0 && "Alignment is not power of 2!"); 7856 7857 // overflow_arg_area = (overflow_arg_area + align - 1) & -align; 7858 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int64Ty, Align - 1); 7859 7860 // Add offset to the current pointer to access the argument. 7861 __overflow_area_pointer = 7862 CGF.Builder.CreateGEP(__overflow_area_pointer, Offset); 7863 llvm::Value *AsInt = 7864 CGF.Builder.CreatePtrToInt(__overflow_area_pointer, CGF.Int32Ty); 7865 7866 // Create a mask which should be "AND"ed 7867 // with (overflow_arg_area + align - 1) 7868 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int32Ty, -(int)Align); 7869 __overflow_area_pointer = CGF.Builder.CreateIntToPtr( 7870 CGF.Builder.CreateAnd(AsInt, Mask), __overflow_area_pointer->getType(), 7871 "__overflow_area_pointer.align"); 7872 } 7873 7874 // Get the type of the argument from memory and bitcast 7875 // overflow area pointer to the argument type. 7876 llvm::Type *PTy = CGF.ConvertTypeForMem(Ty); 7877 Address AddrTyped = CGF.Builder.CreateBitCast( 7878 Address(__overflow_area_pointer, CharUnits::fromQuantity(Align)), 7879 llvm::PointerType::getUnqual(PTy)); 7880 7881 // Round up to the minimum stack alignment for varargs which is 4 bytes. 7882 uint64_t Offset = llvm::alignTo(CGF.getContext().getTypeSize(Ty) / 8, 4); 7883 7884 __overflow_area_pointer = CGF.Builder.CreateGEP( 7885 __overflow_area_pointer, llvm::ConstantInt::get(CGF.Int32Ty, Offset), 7886 "__overflow_area_pointer.next"); 7887 CGF.Builder.CreateStore(__overflow_area_pointer, __overflow_area_pointer_p); 7888 7889 return AddrTyped; 7890 } 7891 7892 Address HexagonABIInfo::EmitVAArgForHexagon(CodeGenFunction &CGF, 7893 Address VAListAddr, 7894 QualType Ty) const { 7895 // FIXME: Need to handle alignment 7896 llvm::Type *BP = CGF.Int8PtrTy; 7897 llvm::Type *BPP = CGF.Int8PtrPtrTy; 7898 CGBuilderTy &Builder = CGF.Builder; 7899 Address VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap"); 7900 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur"); 7901 // Handle address alignment for type alignment > 32 bits 7902 uint64_t TyAlign = CGF.getContext().getTypeAlign(Ty) / 8; 7903 if (TyAlign > 4) { 7904 assert((TyAlign & (TyAlign - 1)) == 0 && "Alignment is not power of 2!"); 7905 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int32Ty); 7906 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt32(TyAlign - 1)); 7907 AddrAsInt = Builder.CreateAnd(AddrAsInt, Builder.getInt32(~(TyAlign - 1))); 7908 Addr = Builder.CreateIntToPtr(AddrAsInt, BP); 7909 } 7910 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty)); 7911 Address AddrTyped = Builder.CreateBitCast( 7912 Address(Addr, CharUnits::fromQuantity(TyAlign)), PTy); 7913 7914 uint64_t Offset = llvm::alignTo(CGF.getContext().getTypeSize(Ty) / 8, 4); 7915 llvm::Value *NextAddr = Builder.CreateGEP( 7916 Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset), "ap.next"); 7917 Builder.CreateStore(NextAddr, VAListAddrAsBPP); 7918 7919 return AddrTyped; 7920 } 7921 7922 Address HexagonABIInfo::EmitVAArgForHexagonLinux(CodeGenFunction &CGF, 7923 Address VAListAddr, 7924 QualType Ty) const { 7925 int ArgSize = CGF.getContext().getTypeSize(Ty) / 8; 7926 7927 if (ArgSize > 8) 7928 return EmitVAArgFromMemory(CGF, VAListAddr, Ty); 7929 7930 // Here we have check if the argument is in register area or 7931 // in overflow area. 7932 // If the saved register area pointer + argsize rounded up to alignment > 7933 // saved register area end pointer, argument is in overflow area. 7934 unsigned RegsLeft = 6; 7935 Ty = CGF.getContext().getCanonicalType(Ty); 7936 (void)classifyArgumentType(Ty, &RegsLeft); 7937 7938 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg"); 7939 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg"); 7940 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack"); 7941 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end"); 7942 7943 // Get rounded size of the argument.GCC does not allow vararg of 7944 // size < 4 bytes. We follow the same logic here. 7945 ArgSize = (CGF.getContext().getTypeSize(Ty) <= 32) ? 4 : 8; 7946 int ArgAlign = (CGF.getContext().getTypeSize(Ty) <= 32) ? 4 : 8; 7947 7948 // Argument may be in saved register area 7949 CGF.EmitBlock(MaybeRegBlock); 7950 7951 // Load the current saved register area pointer. 7952 Address __current_saved_reg_area_pointer_p = CGF.Builder.CreateStructGEP( 7953 VAListAddr, 0, "__current_saved_reg_area_pointer_p"); 7954 llvm::Value *__current_saved_reg_area_pointer = CGF.Builder.CreateLoad( 7955 __current_saved_reg_area_pointer_p, "__current_saved_reg_area_pointer"); 7956 7957 // Load the saved register area end pointer. 7958 Address __saved_reg_area_end_pointer_p = CGF.Builder.CreateStructGEP( 7959 VAListAddr, 1, "__saved_reg_area_end_pointer_p"); 7960 llvm::Value *__saved_reg_area_end_pointer = CGF.Builder.CreateLoad( 7961 __saved_reg_area_end_pointer_p, "__saved_reg_area_end_pointer"); 7962 7963 // If the size of argument is > 4 bytes, check if the stack 7964 // location is aligned to 8 bytes 7965 if (ArgAlign > 4) { 7966 7967 llvm::Value *__current_saved_reg_area_pointer_int = 7968 CGF.Builder.CreatePtrToInt(__current_saved_reg_area_pointer, 7969 CGF.Int32Ty); 7970 7971 __current_saved_reg_area_pointer_int = CGF.Builder.CreateAdd( 7972 __current_saved_reg_area_pointer_int, 7973 llvm::ConstantInt::get(CGF.Int32Ty, (ArgAlign - 1)), 7974 "align_current_saved_reg_area_pointer"); 7975 7976 __current_saved_reg_area_pointer_int = 7977 CGF.Builder.CreateAnd(__current_saved_reg_area_pointer_int, 7978 llvm::ConstantInt::get(CGF.Int32Ty, -ArgAlign), 7979 "align_current_saved_reg_area_pointer"); 7980 7981 __current_saved_reg_area_pointer = 7982 CGF.Builder.CreateIntToPtr(__current_saved_reg_area_pointer_int, 7983 __current_saved_reg_area_pointer->getType(), 7984 "align_current_saved_reg_area_pointer"); 7985 } 7986 7987 llvm::Value *__new_saved_reg_area_pointer = 7988 CGF.Builder.CreateGEP(__current_saved_reg_area_pointer, 7989 llvm::ConstantInt::get(CGF.Int32Ty, ArgSize), 7990 "__new_saved_reg_area_pointer"); 7991 7992 llvm::Value *UsingStack = 0; 7993 UsingStack = CGF.Builder.CreateICmpSGT(__new_saved_reg_area_pointer, 7994 __saved_reg_area_end_pointer); 7995 7996 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, InRegBlock); 7997 7998 // Argument in saved register area 7999 // Implement the block where argument is in register saved area 8000 CGF.EmitBlock(InRegBlock); 8001 8002 llvm::Type *PTy = CGF.ConvertType(Ty); 8003 llvm::Value *__saved_reg_area_p = CGF.Builder.CreateBitCast( 8004 __current_saved_reg_area_pointer, llvm::PointerType::getUnqual(PTy)); 8005 8006 CGF.Builder.CreateStore(__new_saved_reg_area_pointer, 8007 __current_saved_reg_area_pointer_p); 8008 8009 CGF.EmitBranch(ContBlock); 8010 8011 // Argument in overflow area 8012 // Implement the block where the argument is in overflow area. 8013 CGF.EmitBlock(OnStackBlock); 8014 8015 // Load the overflow area pointer 8016 Address __overflow_area_pointer_p = 8017 CGF.Builder.CreateStructGEP(VAListAddr, 2, "__overflow_area_pointer_p"); 8018 llvm::Value *__overflow_area_pointer = CGF.Builder.CreateLoad( 8019 __overflow_area_pointer_p, "__overflow_area_pointer"); 8020 8021 // Align the overflow area pointer according to the alignment of the argument 8022 if (ArgAlign > 4) { 8023 llvm::Value *__overflow_area_pointer_int = 8024 CGF.Builder.CreatePtrToInt(__overflow_area_pointer, CGF.Int32Ty); 8025 8026 __overflow_area_pointer_int = 8027 CGF.Builder.CreateAdd(__overflow_area_pointer_int, 8028 llvm::ConstantInt::get(CGF.Int32Ty, ArgAlign - 1), 8029 "align_overflow_area_pointer"); 8030 8031 __overflow_area_pointer_int = 8032 CGF.Builder.CreateAnd(__overflow_area_pointer_int, 8033 llvm::ConstantInt::get(CGF.Int32Ty, -ArgAlign), 8034 "align_overflow_area_pointer"); 8035 8036 __overflow_area_pointer = CGF.Builder.CreateIntToPtr( 8037 __overflow_area_pointer_int, __overflow_area_pointer->getType(), 8038 "align_overflow_area_pointer"); 8039 } 8040 8041 // Get the pointer for next argument in overflow area and store it 8042 // to overflow area pointer. 8043 llvm::Value *__new_overflow_area_pointer = CGF.Builder.CreateGEP( 8044 __overflow_area_pointer, llvm::ConstantInt::get(CGF.Int32Ty, ArgSize), 8045 "__overflow_area_pointer.next"); 8046 8047 CGF.Builder.CreateStore(__new_overflow_area_pointer, 8048 __overflow_area_pointer_p); 8049 8050 CGF.Builder.CreateStore(__new_overflow_area_pointer, 8051 __current_saved_reg_area_pointer_p); 8052 8053 // Bitcast the overflow area pointer to the type of argument. 8054 llvm::Type *OverflowPTy = CGF.ConvertTypeForMem(Ty); 8055 llvm::Value *__overflow_area_p = CGF.Builder.CreateBitCast( 8056 __overflow_area_pointer, llvm::PointerType::getUnqual(OverflowPTy)); 8057 8058 CGF.EmitBranch(ContBlock); 8059 8060 // Get the correct pointer to load the variable argument 8061 // Implement the ContBlock 8062 CGF.EmitBlock(ContBlock); 8063 8064 llvm::Type *MemPTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty)); 8065 llvm::PHINode *ArgAddr = CGF.Builder.CreatePHI(MemPTy, 2, "vaarg.addr"); 8066 ArgAddr->addIncoming(__saved_reg_area_p, InRegBlock); 8067 ArgAddr->addIncoming(__overflow_area_p, OnStackBlock); 8068 8069 return Address(ArgAddr, CharUnits::fromQuantity(ArgAlign)); 8070 } 8071 8072 Address HexagonABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 8073 QualType Ty) const { 8074 8075 if (getTarget().getTriple().isMusl()) 8076 return EmitVAArgForHexagonLinux(CGF, VAListAddr, Ty); 8077 8078 return EmitVAArgForHexagon(CGF, VAListAddr, Ty); 8079 } 8080 8081 //===----------------------------------------------------------------------===// 8082 // Lanai ABI Implementation 8083 //===----------------------------------------------------------------------===// 8084 8085 namespace { 8086 class LanaiABIInfo : public DefaultABIInfo { 8087 public: 8088 LanaiABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {} 8089 8090 bool shouldUseInReg(QualType Ty, CCState &State) const; 8091 8092 void computeInfo(CGFunctionInfo &FI) const override { 8093 CCState State(FI); 8094 // Lanai uses 4 registers to pass arguments unless the function has the 8095 // regparm attribute set. 8096 if (FI.getHasRegParm()) { 8097 State.FreeRegs = FI.getRegParm(); 8098 } else { 8099 State.FreeRegs = 4; 8100 } 8101 8102 if (!getCXXABI().classifyReturnType(FI)) 8103 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 8104 for (auto &I : FI.arguments()) 8105 I.info = classifyArgumentType(I.type, State); 8106 } 8107 8108 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const; 8109 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const; 8110 }; 8111 } // end anonymous namespace 8112 8113 bool LanaiABIInfo::shouldUseInReg(QualType Ty, CCState &State) const { 8114 unsigned Size = getContext().getTypeSize(Ty); 8115 unsigned SizeInRegs = llvm::alignTo(Size, 32U) / 32U; 8116 8117 if (SizeInRegs == 0) 8118 return false; 8119 8120 if (SizeInRegs > State.FreeRegs) { 8121 State.FreeRegs = 0; 8122 return false; 8123 } 8124 8125 State.FreeRegs -= SizeInRegs; 8126 8127 return true; 8128 } 8129 8130 ABIArgInfo LanaiABIInfo::getIndirectResult(QualType Ty, bool ByVal, 8131 CCState &State) const { 8132 if (!ByVal) { 8133 if (State.FreeRegs) { 8134 --State.FreeRegs; // Non-byval indirects just use one pointer. 8135 return getNaturalAlignIndirectInReg(Ty); 8136 } 8137 return getNaturalAlignIndirect(Ty, false); 8138 } 8139 8140 // Compute the byval alignment. 8141 const unsigned MinABIStackAlignInBytes = 4; 8142 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8; 8143 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true, 8144 /*Realign=*/TypeAlign > 8145 MinABIStackAlignInBytes); 8146 } 8147 8148 ABIArgInfo LanaiABIInfo::classifyArgumentType(QualType Ty, 8149 CCState &State) const { 8150 // Check with the C++ ABI first. 8151 const RecordType *RT = Ty->getAs<RecordType>(); 8152 if (RT) { 8153 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()); 8154 if (RAA == CGCXXABI::RAA_Indirect) { 8155 return getIndirectResult(Ty, /*ByVal=*/false, State); 8156 } else if (RAA == CGCXXABI::RAA_DirectInMemory) { 8157 return getNaturalAlignIndirect(Ty, /*ByRef=*/true); 8158 } 8159 } 8160 8161 if (isAggregateTypeForABI(Ty)) { 8162 // Structures with flexible arrays are always indirect. 8163 if (RT && RT->getDecl()->hasFlexibleArrayMember()) 8164 return getIndirectResult(Ty, /*ByVal=*/true, State); 8165 8166 // Ignore empty structs/unions. 8167 if (isEmptyRecord(getContext(), Ty, true)) 8168 return ABIArgInfo::getIgnore(); 8169 8170 llvm::LLVMContext &LLVMContext = getVMContext(); 8171 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32; 8172 if (SizeInRegs <= State.FreeRegs) { 8173 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext); 8174 SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32); 8175 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements); 8176 State.FreeRegs -= SizeInRegs; 8177 return ABIArgInfo::getDirectInReg(Result); 8178 } else { 8179 State.FreeRegs = 0; 8180 } 8181 return getIndirectResult(Ty, true, State); 8182 } 8183 8184 // Treat an enum type as its underlying type. 8185 if (const auto *EnumTy = Ty->getAs<EnumType>()) 8186 Ty = EnumTy->getDecl()->getIntegerType(); 8187 8188 bool InReg = shouldUseInReg(Ty, State); 8189 if (Ty->isPromotableIntegerType()) { 8190 if (InReg) 8191 return ABIArgInfo::getDirectInReg(); 8192 return ABIArgInfo::getExtend(Ty); 8193 } 8194 if (InReg) 8195 return ABIArgInfo::getDirectInReg(); 8196 return ABIArgInfo::getDirect(); 8197 } 8198 8199 namespace { 8200 class LanaiTargetCodeGenInfo : public TargetCodeGenInfo { 8201 public: 8202 LanaiTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT) 8203 : TargetCodeGenInfo(std::make_unique<LanaiABIInfo>(CGT)) {} 8204 }; 8205 } 8206 8207 //===----------------------------------------------------------------------===// 8208 // AMDGPU ABI Implementation 8209 //===----------------------------------------------------------------------===// 8210 8211 namespace { 8212 8213 class AMDGPUABIInfo final : public DefaultABIInfo { 8214 private: 8215 static const unsigned MaxNumRegsForArgsRet = 16; 8216 8217 unsigned numRegsForType(QualType Ty) const; 8218 8219 bool isHomogeneousAggregateBaseType(QualType Ty) const override; 8220 bool isHomogeneousAggregateSmallEnough(const Type *Base, 8221 uint64_t Members) const override; 8222 8223 // Coerce HIP pointer arguments from generic pointers to global ones. 8224 llvm::Type *coerceKernelArgumentType(llvm::Type *Ty, unsigned FromAS, 8225 unsigned ToAS) const { 8226 // Structure types. 8227 if (auto STy = dyn_cast<llvm::StructType>(Ty)) { 8228 SmallVector<llvm::Type *, 8> EltTys; 8229 bool Changed = false; 8230 for (auto T : STy->elements()) { 8231 auto NT = coerceKernelArgumentType(T, FromAS, ToAS); 8232 EltTys.push_back(NT); 8233 Changed |= (NT != T); 8234 } 8235 // Skip if there is no change in element types. 8236 if (!Changed) 8237 return STy; 8238 if (STy->hasName()) 8239 return llvm::StructType::create( 8240 EltTys, (STy->getName() + ".coerce").str(), STy->isPacked()); 8241 return llvm::StructType::get(getVMContext(), EltTys, STy->isPacked()); 8242 } 8243 // Arrary types. 8244 if (auto ATy = dyn_cast<llvm::ArrayType>(Ty)) { 8245 auto T = ATy->getElementType(); 8246 auto NT = coerceKernelArgumentType(T, FromAS, ToAS); 8247 // Skip if there is no change in that element type. 8248 if (NT == T) 8249 return ATy; 8250 return llvm::ArrayType::get(NT, ATy->getNumElements()); 8251 } 8252 // Single value types. 8253 if (Ty->isPointerTy() && Ty->getPointerAddressSpace() == FromAS) 8254 return llvm::PointerType::get( 8255 cast<llvm::PointerType>(Ty)->getElementType(), ToAS); 8256 return Ty; 8257 } 8258 8259 public: 8260 explicit AMDGPUABIInfo(CodeGen::CodeGenTypes &CGT) : 8261 DefaultABIInfo(CGT) {} 8262 8263 ABIArgInfo classifyReturnType(QualType RetTy) const; 8264 ABIArgInfo classifyKernelArgumentType(QualType Ty) const; 8265 ABIArgInfo classifyArgumentType(QualType Ty, unsigned &NumRegsLeft) const; 8266 8267 void computeInfo(CGFunctionInfo &FI) const override; 8268 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 8269 QualType Ty) const override; 8270 }; 8271 8272 bool AMDGPUABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const { 8273 return true; 8274 } 8275 8276 bool AMDGPUABIInfo::isHomogeneousAggregateSmallEnough( 8277 const Type *Base, uint64_t Members) const { 8278 uint32_t NumRegs = (getContext().getTypeSize(Base) + 31) / 32; 8279 8280 // Homogeneous Aggregates may occupy at most 16 registers. 8281 return Members * NumRegs <= MaxNumRegsForArgsRet; 8282 } 8283 8284 /// Estimate number of registers the type will use when passed in registers. 8285 unsigned AMDGPUABIInfo::numRegsForType(QualType Ty) const { 8286 unsigned NumRegs = 0; 8287 8288 if (const VectorType *VT = Ty->getAs<VectorType>()) { 8289 // Compute from the number of elements. The reported size is based on the 8290 // in-memory size, which includes the padding 4th element for 3-vectors. 8291 QualType EltTy = VT->getElementType(); 8292 unsigned EltSize = getContext().getTypeSize(EltTy); 8293 8294 // 16-bit element vectors should be passed as packed. 8295 if (EltSize == 16) 8296 return (VT->getNumElements() + 1) / 2; 8297 8298 unsigned EltNumRegs = (EltSize + 31) / 32; 8299 return EltNumRegs * VT->getNumElements(); 8300 } 8301 8302 if (const RecordType *RT = Ty->getAs<RecordType>()) { 8303 const RecordDecl *RD = RT->getDecl(); 8304 assert(!RD->hasFlexibleArrayMember()); 8305 8306 for (const FieldDecl *Field : RD->fields()) { 8307 QualType FieldTy = Field->getType(); 8308 NumRegs += numRegsForType(FieldTy); 8309 } 8310 8311 return NumRegs; 8312 } 8313 8314 return (getContext().getTypeSize(Ty) + 31) / 32; 8315 } 8316 8317 void AMDGPUABIInfo::computeInfo(CGFunctionInfo &FI) const { 8318 llvm::CallingConv::ID CC = FI.getCallingConvention(); 8319 8320 if (!getCXXABI().classifyReturnType(FI)) 8321 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 8322 8323 unsigned NumRegsLeft = MaxNumRegsForArgsRet; 8324 for (auto &Arg : FI.arguments()) { 8325 if (CC == llvm::CallingConv::AMDGPU_KERNEL) { 8326 Arg.info = classifyKernelArgumentType(Arg.type); 8327 } else { 8328 Arg.info = classifyArgumentType(Arg.type, NumRegsLeft); 8329 } 8330 } 8331 } 8332 8333 Address AMDGPUABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 8334 QualType Ty) const { 8335 llvm_unreachable("AMDGPU does not support varargs"); 8336 } 8337 8338 ABIArgInfo AMDGPUABIInfo::classifyReturnType(QualType RetTy) const { 8339 if (isAggregateTypeForABI(RetTy)) { 8340 // Records with non-trivial destructors/copy-constructors should not be 8341 // returned by value. 8342 if (!getRecordArgABI(RetTy, getCXXABI())) { 8343 // Ignore empty structs/unions. 8344 if (isEmptyRecord(getContext(), RetTy, true)) 8345 return ABIArgInfo::getIgnore(); 8346 8347 // Lower single-element structs to just return a regular value. 8348 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext())) 8349 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0))); 8350 8351 if (const RecordType *RT = RetTy->getAs<RecordType>()) { 8352 const RecordDecl *RD = RT->getDecl(); 8353 if (RD->hasFlexibleArrayMember()) 8354 return DefaultABIInfo::classifyReturnType(RetTy); 8355 } 8356 8357 // Pack aggregates <= 4 bytes into single VGPR or pair. 8358 uint64_t Size = getContext().getTypeSize(RetTy); 8359 if (Size <= 16) 8360 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext())); 8361 8362 if (Size <= 32) 8363 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext())); 8364 8365 if (Size <= 64) { 8366 llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext()); 8367 return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2)); 8368 } 8369 8370 if (numRegsForType(RetTy) <= MaxNumRegsForArgsRet) 8371 return ABIArgInfo::getDirect(); 8372 } 8373 } 8374 8375 // Otherwise just do the default thing. 8376 return DefaultABIInfo::classifyReturnType(RetTy); 8377 } 8378 8379 /// For kernels all parameters are really passed in a special buffer. It doesn't 8380 /// make sense to pass anything byval, so everything must be direct. 8381 ABIArgInfo AMDGPUABIInfo::classifyKernelArgumentType(QualType Ty) const { 8382 Ty = useFirstFieldIfTransparentUnion(Ty); 8383 8384 // TODO: Can we omit empty structs? 8385 8386 llvm::Type *LTy = nullptr; 8387 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext())) 8388 LTy = CGT.ConvertType(QualType(SeltTy, 0)); 8389 8390 if (getContext().getLangOpts().HIP) { 8391 if (!LTy) 8392 LTy = CGT.ConvertType(Ty); 8393 LTy = coerceKernelArgumentType( 8394 LTy, /*FromAS=*/getContext().getTargetAddressSpace(LangAS::Default), 8395 /*ToAS=*/getContext().getTargetAddressSpace(LangAS::cuda_device)); 8396 } 8397 8398 // If we set CanBeFlattened to true, CodeGen will expand the struct to its 8399 // individual elements, which confuses the Clover OpenCL backend; therefore we 8400 // have to set it to false here. Other args of getDirect() are just defaults. 8401 return ABIArgInfo::getDirect(LTy, 0, nullptr, false); 8402 } 8403 8404 ABIArgInfo AMDGPUABIInfo::classifyArgumentType(QualType Ty, 8405 unsigned &NumRegsLeft) const { 8406 assert(NumRegsLeft <= MaxNumRegsForArgsRet && "register estimate underflow"); 8407 8408 Ty = useFirstFieldIfTransparentUnion(Ty); 8409 8410 if (isAggregateTypeForABI(Ty)) { 8411 // Records with non-trivial destructors/copy-constructors should not be 8412 // passed by value. 8413 if (auto RAA = getRecordArgABI(Ty, getCXXABI())) 8414 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 8415 8416 // Ignore empty structs/unions. 8417 if (isEmptyRecord(getContext(), Ty, true)) 8418 return ABIArgInfo::getIgnore(); 8419 8420 // Lower single-element structs to just pass a regular value. TODO: We 8421 // could do reasonable-size multiple-element structs too, using getExpand(), 8422 // though watch out for things like bitfields. 8423 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext())) 8424 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0))); 8425 8426 if (const RecordType *RT = Ty->getAs<RecordType>()) { 8427 const RecordDecl *RD = RT->getDecl(); 8428 if (RD->hasFlexibleArrayMember()) 8429 return DefaultABIInfo::classifyArgumentType(Ty); 8430 } 8431 8432 // Pack aggregates <= 8 bytes into single VGPR or pair. 8433 uint64_t Size = getContext().getTypeSize(Ty); 8434 if (Size <= 64) { 8435 unsigned NumRegs = (Size + 31) / 32; 8436 NumRegsLeft -= std::min(NumRegsLeft, NumRegs); 8437 8438 if (Size <= 16) 8439 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext())); 8440 8441 if (Size <= 32) 8442 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext())); 8443 8444 // XXX: Should this be i64 instead, and should the limit increase? 8445 llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext()); 8446 return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2)); 8447 } 8448 8449 if (NumRegsLeft > 0) { 8450 unsigned NumRegs = numRegsForType(Ty); 8451 if (NumRegsLeft >= NumRegs) { 8452 NumRegsLeft -= NumRegs; 8453 return ABIArgInfo::getDirect(); 8454 } 8455 } 8456 } 8457 8458 // Otherwise just do the default thing. 8459 ABIArgInfo ArgInfo = DefaultABIInfo::classifyArgumentType(Ty); 8460 if (!ArgInfo.isIndirect()) { 8461 unsigned NumRegs = numRegsForType(Ty); 8462 NumRegsLeft -= std::min(NumRegs, NumRegsLeft); 8463 } 8464 8465 return ArgInfo; 8466 } 8467 8468 class AMDGPUTargetCodeGenInfo : public TargetCodeGenInfo { 8469 public: 8470 AMDGPUTargetCodeGenInfo(CodeGenTypes &CGT) 8471 : TargetCodeGenInfo(std::make_unique<AMDGPUABIInfo>(CGT)) {} 8472 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 8473 CodeGen::CodeGenModule &M) const override; 8474 unsigned getOpenCLKernelCallingConv() const override; 8475 8476 llvm::Constant *getNullPointer(const CodeGen::CodeGenModule &CGM, 8477 llvm::PointerType *T, QualType QT) const override; 8478 8479 LangAS getASTAllocaAddressSpace() const override { 8480 return getLangASFromTargetAS( 8481 getABIInfo().getDataLayout().getAllocaAddrSpace()); 8482 } 8483 LangAS getGlobalVarAddressSpace(CodeGenModule &CGM, 8484 const VarDecl *D) const override; 8485 llvm::SyncScope::ID getLLVMSyncScopeID(const LangOptions &LangOpts, 8486 SyncScope Scope, 8487 llvm::AtomicOrdering Ordering, 8488 llvm::LLVMContext &Ctx) const override; 8489 llvm::Function * 8490 createEnqueuedBlockKernel(CodeGenFunction &CGF, 8491 llvm::Function *BlockInvokeFunc, 8492 llvm::Value *BlockLiteral) const override; 8493 bool shouldEmitStaticExternCAliases() const override; 8494 void setCUDAKernelCallingConvention(const FunctionType *&FT) const override; 8495 }; 8496 } 8497 8498 static bool requiresAMDGPUProtectedVisibility(const Decl *D, 8499 llvm::GlobalValue *GV) { 8500 if (GV->getVisibility() != llvm::GlobalValue::HiddenVisibility) 8501 return false; 8502 8503 return D->hasAttr<OpenCLKernelAttr>() || 8504 (isa<FunctionDecl>(D) && D->hasAttr<CUDAGlobalAttr>()) || 8505 (isa<VarDecl>(D) && 8506 (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>() || 8507 cast<VarDecl>(D)->getType()->isCUDADeviceBuiltinSurfaceType() || 8508 cast<VarDecl>(D)->getType()->isCUDADeviceBuiltinTextureType())); 8509 } 8510 8511 void AMDGPUTargetCodeGenInfo::setTargetAttributes( 8512 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const { 8513 if (requiresAMDGPUProtectedVisibility(D, GV)) { 8514 GV->setVisibility(llvm::GlobalValue::ProtectedVisibility); 8515 GV->setDSOLocal(true); 8516 } 8517 8518 if (GV->isDeclaration()) 8519 return; 8520 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D); 8521 if (!FD) 8522 return; 8523 8524 llvm::Function *F = cast<llvm::Function>(GV); 8525 8526 const auto *ReqdWGS = M.getLangOpts().OpenCL ? 8527 FD->getAttr<ReqdWorkGroupSizeAttr>() : nullptr; 8528 8529 8530 const bool IsOpenCLKernel = M.getLangOpts().OpenCL && 8531 FD->hasAttr<OpenCLKernelAttr>(); 8532 const bool IsHIPKernel = M.getLangOpts().HIP && 8533 FD->hasAttr<CUDAGlobalAttr>(); 8534 if ((IsOpenCLKernel || IsHIPKernel) && 8535 (M.getTriple().getOS() == llvm::Triple::AMDHSA)) 8536 F->addFnAttr("amdgpu-implicitarg-num-bytes", "56"); 8537 8538 if (IsHIPKernel) 8539 F->addFnAttr("uniform-work-group-size", "true"); 8540 8541 8542 const auto *FlatWGS = FD->getAttr<AMDGPUFlatWorkGroupSizeAttr>(); 8543 if (ReqdWGS || FlatWGS) { 8544 unsigned Min = 0; 8545 unsigned Max = 0; 8546 if (FlatWGS) { 8547 Min = FlatWGS->getMin() 8548 ->EvaluateKnownConstInt(M.getContext()) 8549 .getExtValue(); 8550 Max = FlatWGS->getMax() 8551 ->EvaluateKnownConstInt(M.getContext()) 8552 .getExtValue(); 8553 } 8554 if (ReqdWGS && Min == 0 && Max == 0) 8555 Min = Max = ReqdWGS->getXDim() * ReqdWGS->getYDim() * ReqdWGS->getZDim(); 8556 8557 if (Min != 0) { 8558 assert(Min <= Max && "Min must be less than or equal Max"); 8559 8560 std::string AttrVal = llvm::utostr(Min) + "," + llvm::utostr(Max); 8561 F->addFnAttr("amdgpu-flat-work-group-size", AttrVal); 8562 } else 8563 assert(Max == 0 && "Max must be zero"); 8564 } else if (IsOpenCLKernel || IsHIPKernel) { 8565 // By default, restrict the maximum size to a value specified by 8566 // --gpu-max-threads-per-block=n or its default value. 8567 std::string AttrVal = 8568 std::string("1,") + llvm::utostr(M.getLangOpts().GPUMaxThreadsPerBlock); 8569 F->addFnAttr("amdgpu-flat-work-group-size", AttrVal); 8570 } 8571 8572 if (const auto *Attr = FD->getAttr<AMDGPUWavesPerEUAttr>()) { 8573 unsigned Min = 8574 Attr->getMin()->EvaluateKnownConstInt(M.getContext()).getExtValue(); 8575 unsigned Max = Attr->getMax() ? Attr->getMax() 8576 ->EvaluateKnownConstInt(M.getContext()) 8577 .getExtValue() 8578 : 0; 8579 8580 if (Min != 0) { 8581 assert((Max == 0 || Min <= Max) && "Min must be less than or equal Max"); 8582 8583 std::string AttrVal = llvm::utostr(Min); 8584 if (Max != 0) 8585 AttrVal = AttrVal + "," + llvm::utostr(Max); 8586 F->addFnAttr("amdgpu-waves-per-eu", AttrVal); 8587 } else 8588 assert(Max == 0 && "Max must be zero"); 8589 } 8590 8591 if (const auto *Attr = FD->getAttr<AMDGPUNumSGPRAttr>()) { 8592 unsigned NumSGPR = Attr->getNumSGPR(); 8593 8594 if (NumSGPR != 0) 8595 F->addFnAttr("amdgpu-num-sgpr", llvm::utostr(NumSGPR)); 8596 } 8597 8598 if (const auto *Attr = FD->getAttr<AMDGPUNumVGPRAttr>()) { 8599 uint32_t NumVGPR = Attr->getNumVGPR(); 8600 8601 if (NumVGPR != 0) 8602 F->addFnAttr("amdgpu-num-vgpr", llvm::utostr(NumVGPR)); 8603 } 8604 } 8605 8606 unsigned AMDGPUTargetCodeGenInfo::getOpenCLKernelCallingConv() const { 8607 return llvm::CallingConv::AMDGPU_KERNEL; 8608 } 8609 8610 // Currently LLVM assumes null pointers always have value 0, 8611 // which results in incorrectly transformed IR. Therefore, instead of 8612 // emitting null pointers in private and local address spaces, a null 8613 // pointer in generic address space is emitted which is casted to a 8614 // pointer in local or private address space. 8615 llvm::Constant *AMDGPUTargetCodeGenInfo::getNullPointer( 8616 const CodeGen::CodeGenModule &CGM, llvm::PointerType *PT, 8617 QualType QT) const { 8618 if (CGM.getContext().getTargetNullPointerValue(QT) == 0) 8619 return llvm::ConstantPointerNull::get(PT); 8620 8621 auto &Ctx = CGM.getContext(); 8622 auto NPT = llvm::PointerType::get(PT->getElementType(), 8623 Ctx.getTargetAddressSpace(LangAS::opencl_generic)); 8624 return llvm::ConstantExpr::getAddrSpaceCast( 8625 llvm::ConstantPointerNull::get(NPT), PT); 8626 } 8627 8628 LangAS 8629 AMDGPUTargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM, 8630 const VarDecl *D) const { 8631 assert(!CGM.getLangOpts().OpenCL && 8632 !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) && 8633 "Address space agnostic languages only"); 8634 LangAS DefaultGlobalAS = getLangASFromTargetAS( 8635 CGM.getContext().getTargetAddressSpace(LangAS::opencl_global)); 8636 if (!D) 8637 return DefaultGlobalAS; 8638 8639 LangAS AddrSpace = D->getType().getAddressSpace(); 8640 assert(AddrSpace == LangAS::Default || isTargetAddressSpace(AddrSpace)); 8641 if (AddrSpace != LangAS::Default) 8642 return AddrSpace; 8643 8644 if (CGM.isTypeConstant(D->getType(), false)) { 8645 if (auto ConstAS = CGM.getTarget().getConstantAddressSpace()) 8646 return ConstAS.getValue(); 8647 } 8648 return DefaultGlobalAS; 8649 } 8650 8651 llvm::SyncScope::ID 8652 AMDGPUTargetCodeGenInfo::getLLVMSyncScopeID(const LangOptions &LangOpts, 8653 SyncScope Scope, 8654 llvm::AtomicOrdering Ordering, 8655 llvm::LLVMContext &Ctx) const { 8656 std::string Name; 8657 switch (Scope) { 8658 case SyncScope::OpenCLWorkGroup: 8659 Name = "workgroup"; 8660 break; 8661 case SyncScope::OpenCLDevice: 8662 Name = "agent"; 8663 break; 8664 case SyncScope::OpenCLAllSVMDevices: 8665 Name = ""; 8666 break; 8667 case SyncScope::OpenCLSubGroup: 8668 Name = "wavefront"; 8669 } 8670 8671 if (Ordering != llvm::AtomicOrdering::SequentiallyConsistent) { 8672 if (!Name.empty()) 8673 Name = Twine(Twine(Name) + Twine("-")).str(); 8674 8675 Name = Twine(Twine(Name) + Twine("one-as")).str(); 8676 } 8677 8678 return Ctx.getOrInsertSyncScopeID(Name); 8679 } 8680 8681 bool AMDGPUTargetCodeGenInfo::shouldEmitStaticExternCAliases() const { 8682 return false; 8683 } 8684 8685 void AMDGPUTargetCodeGenInfo::setCUDAKernelCallingConvention( 8686 const FunctionType *&FT) const { 8687 FT = getABIInfo().getContext().adjustFunctionType( 8688 FT, FT->getExtInfo().withCallingConv(CC_OpenCLKernel)); 8689 } 8690 8691 //===----------------------------------------------------------------------===// 8692 // SPARC v8 ABI Implementation. 8693 // Based on the SPARC Compliance Definition version 2.4.1. 8694 // 8695 // Ensures that complex values are passed in registers. 8696 // 8697 namespace { 8698 class SparcV8ABIInfo : public DefaultABIInfo { 8699 public: 8700 SparcV8ABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {} 8701 8702 private: 8703 ABIArgInfo classifyReturnType(QualType RetTy) const; 8704 void computeInfo(CGFunctionInfo &FI) const override; 8705 }; 8706 } // end anonymous namespace 8707 8708 8709 ABIArgInfo 8710 SparcV8ABIInfo::classifyReturnType(QualType Ty) const { 8711 if (Ty->isAnyComplexType()) { 8712 return ABIArgInfo::getDirect(); 8713 } 8714 else { 8715 return DefaultABIInfo::classifyReturnType(Ty); 8716 } 8717 } 8718 8719 void SparcV8ABIInfo::computeInfo(CGFunctionInfo &FI) const { 8720 8721 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 8722 for (auto &Arg : FI.arguments()) 8723 Arg.info = classifyArgumentType(Arg.type); 8724 } 8725 8726 namespace { 8727 class SparcV8TargetCodeGenInfo : public TargetCodeGenInfo { 8728 public: 8729 SparcV8TargetCodeGenInfo(CodeGenTypes &CGT) 8730 : TargetCodeGenInfo(std::make_unique<SparcV8ABIInfo>(CGT)) {} 8731 }; 8732 } // end anonymous namespace 8733 8734 //===----------------------------------------------------------------------===// 8735 // SPARC v9 ABI Implementation. 8736 // Based on the SPARC Compliance Definition version 2.4.1. 8737 // 8738 // Function arguments a mapped to a nominal "parameter array" and promoted to 8739 // registers depending on their type. Each argument occupies 8 or 16 bytes in 8740 // the array, structs larger than 16 bytes are passed indirectly. 8741 // 8742 // One case requires special care: 8743 // 8744 // struct mixed { 8745 // int i; 8746 // float f; 8747 // }; 8748 // 8749 // When a struct mixed is passed by value, it only occupies 8 bytes in the 8750 // parameter array, but the int is passed in an integer register, and the float 8751 // is passed in a floating point register. This is represented as two arguments 8752 // with the LLVM IR inreg attribute: 8753 // 8754 // declare void f(i32 inreg %i, float inreg %f) 8755 // 8756 // The code generator will only allocate 4 bytes from the parameter array for 8757 // the inreg arguments. All other arguments are allocated a multiple of 8 8758 // bytes. 8759 // 8760 namespace { 8761 class SparcV9ABIInfo : public ABIInfo { 8762 public: 8763 SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {} 8764 8765 private: 8766 ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const; 8767 void computeInfo(CGFunctionInfo &FI) const override; 8768 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 8769 QualType Ty) const override; 8770 8771 // Coercion type builder for structs passed in registers. The coercion type 8772 // serves two purposes: 8773 // 8774 // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned' 8775 // in registers. 8776 // 2. Expose aligned floating point elements as first-level elements, so the 8777 // code generator knows to pass them in floating point registers. 8778 // 8779 // We also compute the InReg flag which indicates that the struct contains 8780 // aligned 32-bit floats. 8781 // 8782 struct CoerceBuilder { 8783 llvm::LLVMContext &Context; 8784 const llvm::DataLayout &DL; 8785 SmallVector<llvm::Type*, 8> Elems; 8786 uint64_t Size; 8787 bool InReg; 8788 8789 CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl) 8790 : Context(c), DL(dl), Size(0), InReg(false) {} 8791 8792 // Pad Elems with integers until Size is ToSize. 8793 void pad(uint64_t ToSize) { 8794 assert(ToSize >= Size && "Cannot remove elements"); 8795 if (ToSize == Size) 8796 return; 8797 8798 // Finish the current 64-bit word. 8799 uint64_t Aligned = llvm::alignTo(Size, 64); 8800 if (Aligned > Size && Aligned <= ToSize) { 8801 Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size)); 8802 Size = Aligned; 8803 } 8804 8805 // Add whole 64-bit words. 8806 while (Size + 64 <= ToSize) { 8807 Elems.push_back(llvm::Type::getInt64Ty(Context)); 8808 Size += 64; 8809 } 8810 8811 // Final in-word padding. 8812 if (Size < ToSize) { 8813 Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size)); 8814 Size = ToSize; 8815 } 8816 } 8817 8818 // Add a floating point element at Offset. 8819 void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) { 8820 // Unaligned floats are treated as integers. 8821 if (Offset % Bits) 8822 return; 8823 // The InReg flag is only required if there are any floats < 64 bits. 8824 if (Bits < 64) 8825 InReg = true; 8826 pad(Offset); 8827 Elems.push_back(Ty); 8828 Size = Offset + Bits; 8829 } 8830 8831 // Add a struct type to the coercion type, starting at Offset (in bits). 8832 void addStruct(uint64_t Offset, llvm::StructType *StrTy) { 8833 const llvm::StructLayout *Layout = DL.getStructLayout(StrTy); 8834 for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) { 8835 llvm::Type *ElemTy = StrTy->getElementType(i); 8836 uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i); 8837 switch (ElemTy->getTypeID()) { 8838 case llvm::Type::StructTyID: 8839 addStruct(ElemOffset, cast<llvm::StructType>(ElemTy)); 8840 break; 8841 case llvm::Type::FloatTyID: 8842 addFloat(ElemOffset, ElemTy, 32); 8843 break; 8844 case llvm::Type::DoubleTyID: 8845 addFloat(ElemOffset, ElemTy, 64); 8846 break; 8847 case llvm::Type::FP128TyID: 8848 addFloat(ElemOffset, ElemTy, 128); 8849 break; 8850 case llvm::Type::PointerTyID: 8851 if (ElemOffset % 64 == 0) { 8852 pad(ElemOffset); 8853 Elems.push_back(ElemTy); 8854 Size += 64; 8855 } 8856 break; 8857 default: 8858 break; 8859 } 8860 } 8861 } 8862 8863 // Check if Ty is a usable substitute for the coercion type. 8864 bool isUsableType(llvm::StructType *Ty) const { 8865 return llvm::makeArrayRef(Elems) == Ty->elements(); 8866 } 8867 8868 // Get the coercion type as a literal struct type. 8869 llvm::Type *getType() const { 8870 if (Elems.size() == 1) 8871 return Elems.front(); 8872 else 8873 return llvm::StructType::get(Context, Elems); 8874 } 8875 }; 8876 }; 8877 } // end anonymous namespace 8878 8879 ABIArgInfo 8880 SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const { 8881 if (Ty->isVoidType()) 8882 return ABIArgInfo::getIgnore(); 8883 8884 uint64_t Size = getContext().getTypeSize(Ty); 8885 8886 // Anything too big to fit in registers is passed with an explicit indirect 8887 // pointer / sret pointer. 8888 if (Size > SizeLimit) 8889 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 8890 8891 // Treat an enum type as its underlying type. 8892 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 8893 Ty = EnumTy->getDecl()->getIntegerType(); 8894 8895 // Integer types smaller than a register are extended. 8896 if (Size < 64 && Ty->isIntegerType()) 8897 return ABIArgInfo::getExtend(Ty); 8898 8899 // Other non-aggregates go in registers. 8900 if (!isAggregateTypeForABI(Ty)) 8901 return ABIArgInfo::getDirect(); 8902 8903 // If a C++ object has either a non-trivial copy constructor or a non-trivial 8904 // destructor, it is passed with an explicit indirect pointer / sret pointer. 8905 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 8906 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 8907 8908 // This is a small aggregate type that should be passed in registers. 8909 // Build a coercion type from the LLVM struct type. 8910 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty)); 8911 if (!StrTy) 8912 return ABIArgInfo::getDirect(); 8913 8914 CoerceBuilder CB(getVMContext(), getDataLayout()); 8915 CB.addStruct(0, StrTy); 8916 CB.pad(llvm::alignTo(CB.DL.getTypeSizeInBits(StrTy), 64)); 8917 8918 // Try to use the original type for coercion. 8919 llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType(); 8920 8921 if (CB.InReg) 8922 return ABIArgInfo::getDirectInReg(CoerceTy); 8923 else 8924 return ABIArgInfo::getDirect(CoerceTy); 8925 } 8926 8927 Address SparcV9ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 8928 QualType Ty) const { 8929 ABIArgInfo AI = classifyType(Ty, 16 * 8); 8930 llvm::Type *ArgTy = CGT.ConvertType(Ty); 8931 if (AI.canHaveCoerceToType() && !AI.getCoerceToType()) 8932 AI.setCoerceToType(ArgTy); 8933 8934 CharUnits SlotSize = CharUnits::fromQuantity(8); 8935 8936 CGBuilderTy &Builder = CGF.Builder; 8937 Address Addr(Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize); 8938 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy); 8939 8940 auto TypeInfo = getContext().getTypeInfoInChars(Ty); 8941 8942 Address ArgAddr = Address::invalid(); 8943 CharUnits Stride; 8944 switch (AI.getKind()) { 8945 case ABIArgInfo::Expand: 8946 case ABIArgInfo::CoerceAndExpand: 8947 case ABIArgInfo::InAlloca: 8948 llvm_unreachable("Unsupported ABI kind for va_arg"); 8949 8950 case ABIArgInfo::Extend: { 8951 Stride = SlotSize; 8952 CharUnits Offset = SlotSize - TypeInfo.first; 8953 ArgAddr = Builder.CreateConstInBoundsByteGEP(Addr, Offset, "extend"); 8954 break; 8955 } 8956 8957 case ABIArgInfo::Direct: { 8958 auto AllocSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType()); 8959 Stride = CharUnits::fromQuantity(AllocSize).alignTo(SlotSize); 8960 ArgAddr = Addr; 8961 break; 8962 } 8963 8964 case ABIArgInfo::Indirect: 8965 Stride = SlotSize; 8966 ArgAddr = Builder.CreateElementBitCast(Addr, ArgPtrTy, "indirect"); 8967 ArgAddr = Address(Builder.CreateLoad(ArgAddr, "indirect.arg"), 8968 TypeInfo.second); 8969 break; 8970 8971 case ABIArgInfo::Ignore: 8972 return Address(llvm::UndefValue::get(ArgPtrTy), TypeInfo.second); 8973 } 8974 8975 // Update VAList. 8976 Address NextPtr = Builder.CreateConstInBoundsByteGEP(Addr, Stride, "ap.next"); 8977 Builder.CreateStore(NextPtr.getPointer(), VAListAddr); 8978 8979 return Builder.CreateBitCast(ArgAddr, ArgPtrTy, "arg.addr"); 8980 } 8981 8982 void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const { 8983 FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8); 8984 for (auto &I : FI.arguments()) 8985 I.info = classifyType(I.type, 16 * 8); 8986 } 8987 8988 namespace { 8989 class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo { 8990 public: 8991 SparcV9TargetCodeGenInfo(CodeGenTypes &CGT) 8992 : TargetCodeGenInfo(std::make_unique<SparcV9ABIInfo>(CGT)) {} 8993 8994 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 8995 return 14; 8996 } 8997 8998 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 8999 llvm::Value *Address) const override; 9000 }; 9001 } // end anonymous namespace 9002 9003 bool 9004 SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 9005 llvm::Value *Address) const { 9006 // This is calculated from the LLVM and GCC tables and verified 9007 // against gcc output. AFAIK all ABIs use the same encoding. 9008 9009 CodeGen::CGBuilderTy &Builder = CGF.Builder; 9010 9011 llvm::IntegerType *i8 = CGF.Int8Ty; 9012 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4); 9013 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8); 9014 9015 // 0-31: the 8-byte general-purpose registers 9016 AssignToArrayRange(Builder, Address, Eight8, 0, 31); 9017 9018 // 32-63: f0-31, the 4-byte floating-point registers 9019 AssignToArrayRange(Builder, Address, Four8, 32, 63); 9020 9021 // Y = 64 9022 // PSR = 65 9023 // WIM = 66 9024 // TBR = 67 9025 // PC = 68 9026 // NPC = 69 9027 // FSR = 70 9028 // CSR = 71 9029 AssignToArrayRange(Builder, Address, Eight8, 64, 71); 9030 9031 // 72-87: d0-15, the 8-byte floating-point registers 9032 AssignToArrayRange(Builder, Address, Eight8, 72, 87); 9033 9034 return false; 9035 } 9036 9037 // ARC ABI implementation. 9038 namespace { 9039 9040 class ARCABIInfo : public DefaultABIInfo { 9041 public: 9042 using DefaultABIInfo::DefaultABIInfo; 9043 9044 private: 9045 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 9046 QualType Ty) const override; 9047 9048 void updateState(const ABIArgInfo &Info, QualType Ty, CCState &State) const { 9049 if (!State.FreeRegs) 9050 return; 9051 if (Info.isIndirect() && Info.getInReg()) 9052 State.FreeRegs--; 9053 else if (Info.isDirect() && Info.getInReg()) { 9054 unsigned sz = (getContext().getTypeSize(Ty) + 31) / 32; 9055 if (sz < State.FreeRegs) 9056 State.FreeRegs -= sz; 9057 else 9058 State.FreeRegs = 0; 9059 } 9060 } 9061 9062 void computeInfo(CGFunctionInfo &FI) const override { 9063 CCState State(FI); 9064 // ARC uses 8 registers to pass arguments. 9065 State.FreeRegs = 8; 9066 9067 if (!getCXXABI().classifyReturnType(FI)) 9068 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 9069 updateState(FI.getReturnInfo(), FI.getReturnType(), State); 9070 for (auto &I : FI.arguments()) { 9071 I.info = classifyArgumentType(I.type, State.FreeRegs); 9072 updateState(I.info, I.type, State); 9073 } 9074 } 9075 9076 ABIArgInfo getIndirectByRef(QualType Ty, bool HasFreeRegs) const; 9077 ABIArgInfo getIndirectByValue(QualType Ty) const; 9078 ABIArgInfo classifyArgumentType(QualType Ty, uint8_t FreeRegs) const; 9079 ABIArgInfo classifyReturnType(QualType RetTy) const; 9080 }; 9081 9082 class ARCTargetCodeGenInfo : public TargetCodeGenInfo { 9083 public: 9084 ARCTargetCodeGenInfo(CodeGenTypes &CGT) 9085 : TargetCodeGenInfo(std::make_unique<ARCABIInfo>(CGT)) {} 9086 }; 9087 9088 9089 ABIArgInfo ARCABIInfo::getIndirectByRef(QualType Ty, bool HasFreeRegs) const { 9090 return HasFreeRegs ? getNaturalAlignIndirectInReg(Ty) : 9091 getNaturalAlignIndirect(Ty, false); 9092 } 9093 9094 ABIArgInfo ARCABIInfo::getIndirectByValue(QualType Ty) const { 9095 // Compute the byval alignment. 9096 const unsigned MinABIStackAlignInBytes = 4; 9097 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8; 9098 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true, 9099 TypeAlign > MinABIStackAlignInBytes); 9100 } 9101 9102 Address ARCABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 9103 QualType Ty) const { 9104 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false, 9105 getContext().getTypeInfoInChars(Ty), 9106 CharUnits::fromQuantity(4), true); 9107 } 9108 9109 ABIArgInfo ARCABIInfo::classifyArgumentType(QualType Ty, 9110 uint8_t FreeRegs) const { 9111 // Handle the generic C++ ABI. 9112 const RecordType *RT = Ty->getAs<RecordType>(); 9113 if (RT) { 9114 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()); 9115 if (RAA == CGCXXABI::RAA_Indirect) 9116 return getIndirectByRef(Ty, FreeRegs > 0); 9117 9118 if (RAA == CGCXXABI::RAA_DirectInMemory) 9119 return getIndirectByValue(Ty); 9120 } 9121 9122 // Treat an enum type as its underlying type. 9123 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 9124 Ty = EnumTy->getDecl()->getIntegerType(); 9125 9126 auto SizeInRegs = llvm::alignTo(getContext().getTypeSize(Ty), 32) / 32; 9127 9128 if (isAggregateTypeForABI(Ty)) { 9129 // Structures with flexible arrays are always indirect. 9130 if (RT && RT->getDecl()->hasFlexibleArrayMember()) 9131 return getIndirectByValue(Ty); 9132 9133 // Ignore empty structs/unions. 9134 if (isEmptyRecord(getContext(), Ty, true)) 9135 return ABIArgInfo::getIgnore(); 9136 9137 llvm::LLVMContext &LLVMContext = getVMContext(); 9138 9139 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext); 9140 SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32); 9141 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements); 9142 9143 return FreeRegs >= SizeInRegs ? 9144 ABIArgInfo::getDirectInReg(Result) : 9145 ABIArgInfo::getDirect(Result, 0, nullptr, false); 9146 } 9147 9148 return Ty->isPromotableIntegerType() ? 9149 (FreeRegs >= SizeInRegs ? ABIArgInfo::getExtendInReg(Ty) : 9150 ABIArgInfo::getExtend(Ty)) : 9151 (FreeRegs >= SizeInRegs ? ABIArgInfo::getDirectInReg() : 9152 ABIArgInfo::getDirect()); 9153 } 9154 9155 ABIArgInfo ARCABIInfo::classifyReturnType(QualType RetTy) const { 9156 if (RetTy->isAnyComplexType()) 9157 return ABIArgInfo::getDirectInReg(); 9158 9159 // Arguments of size > 4 registers are indirect. 9160 auto RetSize = llvm::alignTo(getContext().getTypeSize(RetTy), 32) / 32; 9161 if (RetSize > 4) 9162 return getIndirectByRef(RetTy, /*HasFreeRegs*/ true); 9163 9164 return DefaultABIInfo::classifyReturnType(RetTy); 9165 } 9166 9167 } // End anonymous namespace. 9168 9169 //===----------------------------------------------------------------------===// 9170 // XCore ABI Implementation 9171 //===----------------------------------------------------------------------===// 9172 9173 namespace { 9174 9175 /// A SmallStringEnc instance is used to build up the TypeString by passing 9176 /// it by reference between functions that append to it. 9177 typedef llvm::SmallString<128> SmallStringEnc; 9178 9179 /// TypeStringCache caches the meta encodings of Types. 9180 /// 9181 /// The reason for caching TypeStrings is two fold: 9182 /// 1. To cache a type's encoding for later uses; 9183 /// 2. As a means to break recursive member type inclusion. 9184 /// 9185 /// A cache Entry can have a Status of: 9186 /// NonRecursive: The type encoding is not recursive; 9187 /// Recursive: The type encoding is recursive; 9188 /// Incomplete: An incomplete TypeString; 9189 /// IncompleteUsed: An incomplete TypeString that has been used in a 9190 /// Recursive type encoding. 9191 /// 9192 /// A NonRecursive entry will have all of its sub-members expanded as fully 9193 /// as possible. Whilst it may contain types which are recursive, the type 9194 /// itself is not recursive and thus its encoding may be safely used whenever 9195 /// the type is encountered. 9196 /// 9197 /// A Recursive entry will have all of its sub-members expanded as fully as 9198 /// possible. The type itself is recursive and it may contain other types which 9199 /// are recursive. The Recursive encoding must not be used during the expansion 9200 /// of a recursive type's recursive branch. For simplicity the code uses 9201 /// IncompleteCount to reject all usage of Recursive encodings for member types. 9202 /// 9203 /// An Incomplete entry is always a RecordType and only encodes its 9204 /// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and 9205 /// are placed into the cache during type expansion as a means to identify and 9206 /// handle recursive inclusion of types as sub-members. If there is recursion 9207 /// the entry becomes IncompleteUsed. 9208 /// 9209 /// During the expansion of a RecordType's members: 9210 /// 9211 /// If the cache contains a NonRecursive encoding for the member type, the 9212 /// cached encoding is used; 9213 /// 9214 /// If the cache contains a Recursive encoding for the member type, the 9215 /// cached encoding is 'Swapped' out, as it may be incorrect, and... 9216 /// 9217 /// If the member is a RecordType, an Incomplete encoding is placed into the 9218 /// cache to break potential recursive inclusion of itself as a sub-member; 9219 /// 9220 /// Once a member RecordType has been expanded, its temporary incomplete 9221 /// entry is removed from the cache. If a Recursive encoding was swapped out 9222 /// it is swapped back in; 9223 /// 9224 /// If an incomplete entry is used to expand a sub-member, the incomplete 9225 /// entry is marked as IncompleteUsed. The cache keeps count of how many 9226 /// IncompleteUsed entries it currently contains in IncompleteUsedCount; 9227 /// 9228 /// If a member's encoding is found to be a NonRecursive or Recursive viz: 9229 /// IncompleteUsedCount==0, the member's encoding is added to the cache. 9230 /// Else the member is part of a recursive type and thus the recursion has 9231 /// been exited too soon for the encoding to be correct for the member. 9232 /// 9233 class TypeStringCache { 9234 enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed}; 9235 struct Entry { 9236 std::string Str; // The encoded TypeString for the type. 9237 enum Status State; // Information about the encoding in 'Str'. 9238 std::string Swapped; // A temporary place holder for a Recursive encoding 9239 // during the expansion of RecordType's members. 9240 }; 9241 std::map<const IdentifierInfo *, struct Entry> Map; 9242 unsigned IncompleteCount; // Number of Incomplete entries in the Map. 9243 unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map. 9244 public: 9245 TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {} 9246 void addIncomplete(const IdentifierInfo *ID, std::string StubEnc); 9247 bool removeIncomplete(const IdentifierInfo *ID); 9248 void addIfComplete(const IdentifierInfo *ID, StringRef Str, 9249 bool IsRecursive); 9250 StringRef lookupStr(const IdentifierInfo *ID); 9251 }; 9252 9253 /// TypeString encodings for enum & union fields must be order. 9254 /// FieldEncoding is a helper for this ordering process. 9255 class FieldEncoding { 9256 bool HasName; 9257 std::string Enc; 9258 public: 9259 FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {} 9260 StringRef str() { return Enc; } 9261 bool operator<(const FieldEncoding &rhs) const { 9262 if (HasName != rhs.HasName) return HasName; 9263 return Enc < rhs.Enc; 9264 } 9265 }; 9266 9267 class XCoreABIInfo : public DefaultABIInfo { 9268 public: 9269 XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {} 9270 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 9271 QualType Ty) const override; 9272 }; 9273 9274 class XCoreTargetCodeGenInfo : public TargetCodeGenInfo { 9275 mutable TypeStringCache TSC; 9276 public: 9277 XCoreTargetCodeGenInfo(CodeGenTypes &CGT) 9278 : TargetCodeGenInfo(std::make_unique<XCoreABIInfo>(CGT)) {} 9279 void emitTargetMD(const Decl *D, llvm::GlobalValue *GV, 9280 CodeGen::CodeGenModule &M) const override; 9281 }; 9282 9283 } // End anonymous namespace. 9284 9285 // TODO: this implementation is likely now redundant with the default 9286 // EmitVAArg. 9287 Address XCoreABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 9288 QualType Ty) const { 9289 CGBuilderTy &Builder = CGF.Builder; 9290 9291 // Get the VAList. 9292 CharUnits SlotSize = CharUnits::fromQuantity(4); 9293 Address AP(Builder.CreateLoad(VAListAddr), SlotSize); 9294 9295 // Handle the argument. 9296 ABIArgInfo AI = classifyArgumentType(Ty); 9297 CharUnits TypeAlign = getContext().getTypeAlignInChars(Ty); 9298 llvm::Type *ArgTy = CGT.ConvertType(Ty); 9299 if (AI.canHaveCoerceToType() && !AI.getCoerceToType()) 9300 AI.setCoerceToType(ArgTy); 9301 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy); 9302 9303 Address Val = Address::invalid(); 9304 CharUnits ArgSize = CharUnits::Zero(); 9305 switch (AI.getKind()) { 9306 case ABIArgInfo::Expand: 9307 case ABIArgInfo::CoerceAndExpand: 9308 case ABIArgInfo::InAlloca: 9309 llvm_unreachable("Unsupported ABI kind for va_arg"); 9310 case ABIArgInfo::Ignore: 9311 Val = Address(llvm::UndefValue::get(ArgPtrTy), TypeAlign); 9312 ArgSize = CharUnits::Zero(); 9313 break; 9314 case ABIArgInfo::Extend: 9315 case ABIArgInfo::Direct: 9316 Val = Builder.CreateBitCast(AP, ArgPtrTy); 9317 ArgSize = CharUnits::fromQuantity( 9318 getDataLayout().getTypeAllocSize(AI.getCoerceToType())); 9319 ArgSize = ArgSize.alignTo(SlotSize); 9320 break; 9321 case ABIArgInfo::Indirect: 9322 Val = Builder.CreateElementBitCast(AP, ArgPtrTy); 9323 Val = Address(Builder.CreateLoad(Val), TypeAlign); 9324 ArgSize = SlotSize; 9325 break; 9326 } 9327 9328 // Increment the VAList. 9329 if (!ArgSize.isZero()) { 9330 Address APN = Builder.CreateConstInBoundsByteGEP(AP, ArgSize); 9331 Builder.CreateStore(APN.getPointer(), VAListAddr); 9332 } 9333 9334 return Val; 9335 } 9336 9337 /// During the expansion of a RecordType, an incomplete TypeString is placed 9338 /// into the cache as a means to identify and break recursion. 9339 /// If there is a Recursive encoding in the cache, it is swapped out and will 9340 /// be reinserted by removeIncomplete(). 9341 /// All other types of encoding should have been used rather than arriving here. 9342 void TypeStringCache::addIncomplete(const IdentifierInfo *ID, 9343 std::string StubEnc) { 9344 if (!ID) 9345 return; 9346 Entry &E = Map[ID]; 9347 assert( (E.Str.empty() || E.State == Recursive) && 9348 "Incorrectly use of addIncomplete"); 9349 assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()"); 9350 E.Swapped.swap(E.Str); // swap out the Recursive 9351 E.Str.swap(StubEnc); 9352 E.State = Incomplete; 9353 ++IncompleteCount; 9354 } 9355 9356 /// Once the RecordType has been expanded, the temporary incomplete TypeString 9357 /// must be removed from the cache. 9358 /// If a Recursive was swapped out by addIncomplete(), it will be replaced. 9359 /// Returns true if the RecordType was defined recursively. 9360 bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) { 9361 if (!ID) 9362 return false; 9363 auto I = Map.find(ID); 9364 assert(I != Map.end() && "Entry not present"); 9365 Entry &E = I->second; 9366 assert( (E.State == Incomplete || 9367 E.State == IncompleteUsed) && 9368 "Entry must be an incomplete type"); 9369 bool IsRecursive = false; 9370 if (E.State == IncompleteUsed) { 9371 // We made use of our Incomplete encoding, thus we are recursive. 9372 IsRecursive = true; 9373 --IncompleteUsedCount; 9374 } 9375 if (E.Swapped.empty()) 9376 Map.erase(I); 9377 else { 9378 // Swap the Recursive back. 9379 E.Swapped.swap(E.Str); 9380 E.Swapped.clear(); 9381 E.State = Recursive; 9382 } 9383 --IncompleteCount; 9384 return IsRecursive; 9385 } 9386 9387 /// Add the encoded TypeString to the cache only if it is NonRecursive or 9388 /// Recursive (viz: all sub-members were expanded as fully as possible). 9389 void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str, 9390 bool IsRecursive) { 9391 if (!ID || IncompleteUsedCount) 9392 return; // No key or it is is an incomplete sub-type so don't add. 9393 Entry &E = Map[ID]; 9394 if (IsRecursive && !E.Str.empty()) { 9395 assert(E.State==Recursive && E.Str.size() == Str.size() && 9396 "This is not the same Recursive entry"); 9397 // The parent container was not recursive after all, so we could have used 9398 // this Recursive sub-member entry after all, but we assumed the worse when 9399 // we started viz: IncompleteCount!=0. 9400 return; 9401 } 9402 assert(E.Str.empty() && "Entry already present"); 9403 E.Str = Str.str(); 9404 E.State = IsRecursive? Recursive : NonRecursive; 9405 } 9406 9407 /// Return a cached TypeString encoding for the ID. If there isn't one, or we 9408 /// are recursively expanding a type (IncompleteCount != 0) and the cached 9409 /// encoding is Recursive, return an empty StringRef. 9410 StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) { 9411 if (!ID) 9412 return StringRef(); // We have no key. 9413 auto I = Map.find(ID); 9414 if (I == Map.end()) 9415 return StringRef(); // We have no encoding. 9416 Entry &E = I->second; 9417 if (E.State == Recursive && IncompleteCount) 9418 return StringRef(); // We don't use Recursive encodings for member types. 9419 9420 if (E.State == Incomplete) { 9421 // The incomplete type is being used to break out of recursion. 9422 E.State = IncompleteUsed; 9423 ++IncompleteUsedCount; 9424 } 9425 return E.Str; 9426 } 9427 9428 /// The XCore ABI includes a type information section that communicates symbol 9429 /// type information to the linker. The linker uses this information to verify 9430 /// safety/correctness of things such as array bound and pointers et al. 9431 /// The ABI only requires C (and XC) language modules to emit TypeStrings. 9432 /// This type information (TypeString) is emitted into meta data for all global 9433 /// symbols: definitions, declarations, functions & variables. 9434 /// 9435 /// The TypeString carries type, qualifier, name, size & value details. 9436 /// Please see 'Tools Development Guide' section 2.16.2 for format details: 9437 /// https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf 9438 /// The output is tested by test/CodeGen/xcore-stringtype.c. 9439 /// 9440 static bool getTypeString(SmallStringEnc &Enc, const Decl *D, 9441 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC); 9442 9443 /// XCore uses emitTargetMD to emit TypeString metadata for global symbols. 9444 void XCoreTargetCodeGenInfo::emitTargetMD(const Decl *D, llvm::GlobalValue *GV, 9445 CodeGen::CodeGenModule &CGM) const { 9446 SmallStringEnc Enc; 9447 if (getTypeString(Enc, D, CGM, TSC)) { 9448 llvm::LLVMContext &Ctx = CGM.getModule().getContext(); 9449 llvm::Metadata *MDVals[] = {llvm::ConstantAsMetadata::get(GV), 9450 llvm::MDString::get(Ctx, Enc.str())}; 9451 llvm::NamedMDNode *MD = 9452 CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings"); 9453 MD->addOperand(llvm::MDNode::get(Ctx, MDVals)); 9454 } 9455 } 9456 9457 //===----------------------------------------------------------------------===// 9458 // SPIR ABI Implementation 9459 //===----------------------------------------------------------------------===// 9460 9461 namespace { 9462 class SPIRTargetCodeGenInfo : public TargetCodeGenInfo { 9463 public: 9464 SPIRTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT) 9465 : TargetCodeGenInfo(std::make_unique<DefaultABIInfo>(CGT)) {} 9466 unsigned getOpenCLKernelCallingConv() const override; 9467 }; 9468 9469 } // End anonymous namespace. 9470 9471 namespace clang { 9472 namespace CodeGen { 9473 void computeSPIRKernelABIInfo(CodeGenModule &CGM, CGFunctionInfo &FI) { 9474 DefaultABIInfo SPIRABI(CGM.getTypes()); 9475 SPIRABI.computeInfo(FI); 9476 } 9477 } 9478 } 9479 9480 unsigned SPIRTargetCodeGenInfo::getOpenCLKernelCallingConv() const { 9481 return llvm::CallingConv::SPIR_KERNEL; 9482 } 9483 9484 static bool appendType(SmallStringEnc &Enc, QualType QType, 9485 const CodeGen::CodeGenModule &CGM, 9486 TypeStringCache &TSC); 9487 9488 /// Helper function for appendRecordType(). 9489 /// Builds a SmallVector containing the encoded field types in declaration 9490 /// order. 9491 static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE, 9492 const RecordDecl *RD, 9493 const CodeGen::CodeGenModule &CGM, 9494 TypeStringCache &TSC) { 9495 for (const auto *Field : RD->fields()) { 9496 SmallStringEnc Enc; 9497 Enc += "m("; 9498 Enc += Field->getName(); 9499 Enc += "){"; 9500 if (Field->isBitField()) { 9501 Enc += "b("; 9502 llvm::raw_svector_ostream OS(Enc); 9503 OS << Field->getBitWidthValue(CGM.getContext()); 9504 Enc += ':'; 9505 } 9506 if (!appendType(Enc, Field->getType(), CGM, TSC)) 9507 return false; 9508 if (Field->isBitField()) 9509 Enc += ')'; 9510 Enc += '}'; 9511 FE.emplace_back(!Field->getName().empty(), Enc); 9512 } 9513 return true; 9514 } 9515 9516 /// Appends structure and union types to Enc and adds encoding to cache. 9517 /// Recursively calls appendType (via extractFieldType) for each field. 9518 /// Union types have their fields ordered according to the ABI. 9519 static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT, 9520 const CodeGen::CodeGenModule &CGM, 9521 TypeStringCache &TSC, const IdentifierInfo *ID) { 9522 // Append the cached TypeString if we have one. 9523 StringRef TypeString = TSC.lookupStr(ID); 9524 if (!TypeString.empty()) { 9525 Enc += TypeString; 9526 return true; 9527 } 9528 9529 // Start to emit an incomplete TypeString. 9530 size_t Start = Enc.size(); 9531 Enc += (RT->isUnionType()? 'u' : 's'); 9532 Enc += '('; 9533 if (ID) 9534 Enc += ID->getName(); 9535 Enc += "){"; 9536 9537 // We collect all encoded fields and order as necessary. 9538 bool IsRecursive = false; 9539 const RecordDecl *RD = RT->getDecl()->getDefinition(); 9540 if (RD && !RD->field_empty()) { 9541 // An incomplete TypeString stub is placed in the cache for this RecordType 9542 // so that recursive calls to this RecordType will use it whilst building a 9543 // complete TypeString for this RecordType. 9544 SmallVector<FieldEncoding, 16> FE; 9545 std::string StubEnc(Enc.substr(Start).str()); 9546 StubEnc += '}'; // StubEnc now holds a valid incomplete TypeString. 9547 TSC.addIncomplete(ID, std::move(StubEnc)); 9548 if (!extractFieldType(FE, RD, CGM, TSC)) { 9549 (void) TSC.removeIncomplete(ID); 9550 return false; 9551 } 9552 IsRecursive = TSC.removeIncomplete(ID); 9553 // The ABI requires unions to be sorted but not structures. 9554 // See FieldEncoding::operator< for sort algorithm. 9555 if (RT->isUnionType()) 9556 llvm::sort(FE); 9557 // We can now complete the TypeString. 9558 unsigned E = FE.size(); 9559 for (unsigned I = 0; I != E; ++I) { 9560 if (I) 9561 Enc += ','; 9562 Enc += FE[I].str(); 9563 } 9564 } 9565 Enc += '}'; 9566 TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive); 9567 return true; 9568 } 9569 9570 /// Appends enum types to Enc and adds the encoding to the cache. 9571 static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET, 9572 TypeStringCache &TSC, 9573 const IdentifierInfo *ID) { 9574 // Append the cached TypeString if we have one. 9575 StringRef TypeString = TSC.lookupStr(ID); 9576 if (!TypeString.empty()) { 9577 Enc += TypeString; 9578 return true; 9579 } 9580 9581 size_t Start = Enc.size(); 9582 Enc += "e("; 9583 if (ID) 9584 Enc += ID->getName(); 9585 Enc += "){"; 9586 9587 // We collect all encoded enumerations and order them alphanumerically. 9588 if (const EnumDecl *ED = ET->getDecl()->getDefinition()) { 9589 SmallVector<FieldEncoding, 16> FE; 9590 for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E; 9591 ++I) { 9592 SmallStringEnc EnumEnc; 9593 EnumEnc += "m("; 9594 EnumEnc += I->getName(); 9595 EnumEnc += "){"; 9596 I->getInitVal().toString(EnumEnc); 9597 EnumEnc += '}'; 9598 FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc)); 9599 } 9600 llvm::sort(FE); 9601 unsigned E = FE.size(); 9602 for (unsigned I = 0; I != E; ++I) { 9603 if (I) 9604 Enc += ','; 9605 Enc += FE[I].str(); 9606 } 9607 } 9608 Enc += '}'; 9609 TSC.addIfComplete(ID, Enc.substr(Start), false); 9610 return true; 9611 } 9612 9613 /// Appends type's qualifier to Enc. 9614 /// This is done prior to appending the type's encoding. 9615 static void appendQualifier(SmallStringEnc &Enc, QualType QT) { 9616 // Qualifiers are emitted in alphabetical order. 9617 static const char *const Table[]={"","c:","r:","cr:","v:","cv:","rv:","crv:"}; 9618 int Lookup = 0; 9619 if (QT.isConstQualified()) 9620 Lookup += 1<<0; 9621 if (QT.isRestrictQualified()) 9622 Lookup += 1<<1; 9623 if (QT.isVolatileQualified()) 9624 Lookup += 1<<2; 9625 Enc += Table[Lookup]; 9626 } 9627 9628 /// Appends built-in types to Enc. 9629 static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) { 9630 const char *EncType; 9631 switch (BT->getKind()) { 9632 case BuiltinType::Void: 9633 EncType = "0"; 9634 break; 9635 case BuiltinType::Bool: 9636 EncType = "b"; 9637 break; 9638 case BuiltinType::Char_U: 9639 EncType = "uc"; 9640 break; 9641 case BuiltinType::UChar: 9642 EncType = "uc"; 9643 break; 9644 case BuiltinType::SChar: 9645 EncType = "sc"; 9646 break; 9647 case BuiltinType::UShort: 9648 EncType = "us"; 9649 break; 9650 case BuiltinType::Short: 9651 EncType = "ss"; 9652 break; 9653 case BuiltinType::UInt: 9654 EncType = "ui"; 9655 break; 9656 case BuiltinType::Int: 9657 EncType = "si"; 9658 break; 9659 case BuiltinType::ULong: 9660 EncType = "ul"; 9661 break; 9662 case BuiltinType::Long: 9663 EncType = "sl"; 9664 break; 9665 case BuiltinType::ULongLong: 9666 EncType = "ull"; 9667 break; 9668 case BuiltinType::LongLong: 9669 EncType = "sll"; 9670 break; 9671 case BuiltinType::Float: 9672 EncType = "ft"; 9673 break; 9674 case BuiltinType::Double: 9675 EncType = "d"; 9676 break; 9677 case BuiltinType::LongDouble: 9678 EncType = "ld"; 9679 break; 9680 default: 9681 return false; 9682 } 9683 Enc += EncType; 9684 return true; 9685 } 9686 9687 /// Appends a pointer encoding to Enc before calling appendType for the pointee. 9688 static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT, 9689 const CodeGen::CodeGenModule &CGM, 9690 TypeStringCache &TSC) { 9691 Enc += "p("; 9692 if (!appendType(Enc, PT->getPointeeType(), CGM, TSC)) 9693 return false; 9694 Enc += ')'; 9695 return true; 9696 } 9697 9698 /// Appends array encoding to Enc before calling appendType for the element. 9699 static bool appendArrayType(SmallStringEnc &Enc, QualType QT, 9700 const ArrayType *AT, 9701 const CodeGen::CodeGenModule &CGM, 9702 TypeStringCache &TSC, StringRef NoSizeEnc) { 9703 if (AT->getSizeModifier() != ArrayType::Normal) 9704 return false; 9705 Enc += "a("; 9706 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) 9707 CAT->getSize().toStringUnsigned(Enc); 9708 else 9709 Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "". 9710 Enc += ':'; 9711 // The Qualifiers should be attached to the type rather than the array. 9712 appendQualifier(Enc, QT); 9713 if (!appendType(Enc, AT->getElementType(), CGM, TSC)) 9714 return false; 9715 Enc += ')'; 9716 return true; 9717 } 9718 9719 /// Appends a function encoding to Enc, calling appendType for the return type 9720 /// and the arguments. 9721 static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT, 9722 const CodeGen::CodeGenModule &CGM, 9723 TypeStringCache &TSC) { 9724 Enc += "f{"; 9725 if (!appendType(Enc, FT->getReturnType(), CGM, TSC)) 9726 return false; 9727 Enc += "}("; 9728 if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) { 9729 // N.B. we are only interested in the adjusted param types. 9730 auto I = FPT->param_type_begin(); 9731 auto E = FPT->param_type_end(); 9732 if (I != E) { 9733 do { 9734 if (!appendType(Enc, *I, CGM, TSC)) 9735 return false; 9736 ++I; 9737 if (I != E) 9738 Enc += ','; 9739 } while (I != E); 9740 if (FPT->isVariadic()) 9741 Enc += ",va"; 9742 } else { 9743 if (FPT->isVariadic()) 9744 Enc += "va"; 9745 else 9746 Enc += '0'; 9747 } 9748 } 9749 Enc += ')'; 9750 return true; 9751 } 9752 9753 /// Handles the type's qualifier before dispatching a call to handle specific 9754 /// type encodings. 9755 static bool appendType(SmallStringEnc &Enc, QualType QType, 9756 const CodeGen::CodeGenModule &CGM, 9757 TypeStringCache &TSC) { 9758 9759 QualType QT = QType.getCanonicalType(); 9760 9761 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) 9762 // The Qualifiers should be attached to the type rather than the array. 9763 // Thus we don't call appendQualifier() here. 9764 return appendArrayType(Enc, QT, AT, CGM, TSC, ""); 9765 9766 appendQualifier(Enc, QT); 9767 9768 if (const BuiltinType *BT = QT->getAs<BuiltinType>()) 9769 return appendBuiltinType(Enc, BT); 9770 9771 if (const PointerType *PT = QT->getAs<PointerType>()) 9772 return appendPointerType(Enc, PT, CGM, TSC); 9773 9774 if (const EnumType *ET = QT->getAs<EnumType>()) 9775 return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier()); 9776 9777 if (const RecordType *RT = QT->getAsStructureType()) 9778 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier()); 9779 9780 if (const RecordType *RT = QT->getAsUnionType()) 9781 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier()); 9782 9783 if (const FunctionType *FT = QT->getAs<FunctionType>()) 9784 return appendFunctionType(Enc, FT, CGM, TSC); 9785 9786 return false; 9787 } 9788 9789 static bool getTypeString(SmallStringEnc &Enc, const Decl *D, 9790 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC) { 9791 if (!D) 9792 return false; 9793 9794 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 9795 if (FD->getLanguageLinkage() != CLanguageLinkage) 9796 return false; 9797 return appendType(Enc, FD->getType(), CGM, TSC); 9798 } 9799 9800 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 9801 if (VD->getLanguageLinkage() != CLanguageLinkage) 9802 return false; 9803 QualType QT = VD->getType().getCanonicalType(); 9804 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) { 9805 // Global ArrayTypes are given a size of '*' if the size is unknown. 9806 // The Qualifiers should be attached to the type rather than the array. 9807 // Thus we don't call appendQualifier() here. 9808 return appendArrayType(Enc, QT, AT, CGM, TSC, "*"); 9809 } 9810 return appendType(Enc, QT, CGM, TSC); 9811 } 9812 return false; 9813 } 9814 9815 //===----------------------------------------------------------------------===// 9816 // RISCV ABI Implementation 9817 //===----------------------------------------------------------------------===// 9818 9819 namespace { 9820 class RISCVABIInfo : public DefaultABIInfo { 9821 private: 9822 // Size of the integer ('x') registers in bits. 9823 unsigned XLen; 9824 // Size of the floating point ('f') registers in bits. Note that the target 9825 // ISA might have a wider FLen than the selected ABI (e.g. an RV32IF target 9826 // with soft float ABI has FLen==0). 9827 unsigned FLen; 9828 static const int NumArgGPRs = 8; 9829 static const int NumArgFPRs = 8; 9830 bool detectFPCCEligibleStructHelper(QualType Ty, CharUnits CurOff, 9831 llvm::Type *&Field1Ty, 9832 CharUnits &Field1Off, 9833 llvm::Type *&Field2Ty, 9834 CharUnits &Field2Off) const; 9835 9836 public: 9837 RISCVABIInfo(CodeGen::CodeGenTypes &CGT, unsigned XLen, unsigned FLen) 9838 : DefaultABIInfo(CGT), XLen(XLen), FLen(FLen) {} 9839 9840 // DefaultABIInfo's classifyReturnType and classifyArgumentType are 9841 // non-virtual, but computeInfo is virtual, so we overload it. 9842 void computeInfo(CGFunctionInfo &FI) const override; 9843 9844 ABIArgInfo classifyArgumentType(QualType Ty, bool IsFixed, int &ArgGPRsLeft, 9845 int &ArgFPRsLeft) const; 9846 ABIArgInfo classifyReturnType(QualType RetTy) const; 9847 9848 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 9849 QualType Ty) const override; 9850 9851 ABIArgInfo extendType(QualType Ty) const; 9852 9853 bool detectFPCCEligibleStruct(QualType Ty, llvm::Type *&Field1Ty, 9854 CharUnits &Field1Off, llvm::Type *&Field2Ty, 9855 CharUnits &Field2Off, int &NeededArgGPRs, 9856 int &NeededArgFPRs) const; 9857 ABIArgInfo coerceAndExpandFPCCEligibleStruct(llvm::Type *Field1Ty, 9858 CharUnits Field1Off, 9859 llvm::Type *Field2Ty, 9860 CharUnits Field2Off) const; 9861 }; 9862 } // end anonymous namespace 9863 9864 void RISCVABIInfo::computeInfo(CGFunctionInfo &FI) const { 9865 QualType RetTy = FI.getReturnType(); 9866 if (!getCXXABI().classifyReturnType(FI)) 9867 FI.getReturnInfo() = classifyReturnType(RetTy); 9868 9869 // IsRetIndirect is true if classifyArgumentType indicated the value should 9870 // be passed indirect, or if the type size is a scalar greater than 2*XLen 9871 // and not a complex type with elements <= FLen. e.g. fp128 is passed direct 9872 // in LLVM IR, relying on the backend lowering code to rewrite the argument 9873 // list and pass indirectly on RV32. 9874 bool IsRetIndirect = FI.getReturnInfo().getKind() == ABIArgInfo::Indirect; 9875 if (!IsRetIndirect && RetTy->isScalarType() && 9876 getContext().getTypeSize(RetTy) > (2 * XLen)) { 9877 if (RetTy->isComplexType() && FLen) { 9878 QualType EltTy = RetTy->getAs<ComplexType>()->getElementType(); 9879 IsRetIndirect = getContext().getTypeSize(EltTy) > FLen; 9880 } else { 9881 // This is a normal scalar > 2*XLen, such as fp128 on RV32. 9882 IsRetIndirect = true; 9883 } 9884 } 9885 9886 // We must track the number of GPRs used in order to conform to the RISC-V 9887 // ABI, as integer scalars passed in registers should have signext/zeroext 9888 // when promoted, but are anyext if passed on the stack. As GPR usage is 9889 // different for variadic arguments, we must also track whether we are 9890 // examining a vararg or not. 9891 int ArgGPRsLeft = IsRetIndirect ? NumArgGPRs - 1 : NumArgGPRs; 9892 int ArgFPRsLeft = FLen ? NumArgFPRs : 0; 9893 int NumFixedArgs = FI.getNumRequiredArgs(); 9894 9895 int ArgNum = 0; 9896 for (auto &ArgInfo : FI.arguments()) { 9897 bool IsFixed = ArgNum < NumFixedArgs; 9898 ArgInfo.info = 9899 classifyArgumentType(ArgInfo.type, IsFixed, ArgGPRsLeft, ArgFPRsLeft); 9900 ArgNum++; 9901 } 9902 } 9903 9904 // Returns true if the struct is a potential candidate for the floating point 9905 // calling convention. If this function returns true, the caller is 9906 // responsible for checking that if there is only a single field then that 9907 // field is a float. 9908 bool RISCVABIInfo::detectFPCCEligibleStructHelper(QualType Ty, CharUnits CurOff, 9909 llvm::Type *&Field1Ty, 9910 CharUnits &Field1Off, 9911 llvm::Type *&Field2Ty, 9912 CharUnits &Field2Off) const { 9913 bool IsInt = Ty->isIntegralOrEnumerationType(); 9914 bool IsFloat = Ty->isRealFloatingType(); 9915 9916 if (IsInt || IsFloat) { 9917 uint64_t Size = getContext().getTypeSize(Ty); 9918 if (IsInt && Size > XLen) 9919 return false; 9920 // Can't be eligible if larger than the FP registers. Half precision isn't 9921 // currently supported on RISC-V and the ABI hasn't been confirmed, so 9922 // default to the integer ABI in that case. 9923 if (IsFloat && (Size > FLen || Size < 32)) 9924 return false; 9925 // Can't be eligible if an integer type was already found (int+int pairs 9926 // are not eligible). 9927 if (IsInt && Field1Ty && Field1Ty->isIntegerTy()) 9928 return false; 9929 if (!Field1Ty) { 9930 Field1Ty = CGT.ConvertType(Ty); 9931 Field1Off = CurOff; 9932 return true; 9933 } 9934 if (!Field2Ty) { 9935 Field2Ty = CGT.ConvertType(Ty); 9936 Field2Off = CurOff; 9937 return true; 9938 } 9939 return false; 9940 } 9941 9942 if (auto CTy = Ty->getAs<ComplexType>()) { 9943 if (Field1Ty) 9944 return false; 9945 QualType EltTy = CTy->getElementType(); 9946 if (getContext().getTypeSize(EltTy) > FLen) 9947 return false; 9948 Field1Ty = CGT.ConvertType(EltTy); 9949 Field1Off = CurOff; 9950 assert(CurOff.isZero() && "Unexpected offset for first field"); 9951 Field2Ty = Field1Ty; 9952 Field2Off = Field1Off + getContext().getTypeSizeInChars(EltTy); 9953 return true; 9954 } 9955 9956 if (const ConstantArrayType *ATy = getContext().getAsConstantArrayType(Ty)) { 9957 uint64_t ArraySize = ATy->getSize().getZExtValue(); 9958 QualType EltTy = ATy->getElementType(); 9959 CharUnits EltSize = getContext().getTypeSizeInChars(EltTy); 9960 for (uint64_t i = 0; i < ArraySize; ++i) { 9961 bool Ret = detectFPCCEligibleStructHelper(EltTy, CurOff, Field1Ty, 9962 Field1Off, Field2Ty, Field2Off); 9963 if (!Ret) 9964 return false; 9965 CurOff += EltSize; 9966 } 9967 return true; 9968 } 9969 9970 if (const auto *RTy = Ty->getAs<RecordType>()) { 9971 // Structures with either a non-trivial destructor or a non-trivial 9972 // copy constructor are not eligible for the FP calling convention. 9973 if (getRecordArgABI(Ty, CGT.getCXXABI())) 9974 return false; 9975 if (isEmptyRecord(getContext(), Ty, true)) 9976 return true; 9977 const RecordDecl *RD = RTy->getDecl(); 9978 // Unions aren't eligible unless they're empty (which is caught above). 9979 if (RD->isUnion()) 9980 return false; 9981 int ZeroWidthBitFieldCount = 0; 9982 for (const FieldDecl *FD : RD->fields()) { 9983 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD); 9984 uint64_t FieldOffInBits = Layout.getFieldOffset(FD->getFieldIndex()); 9985 QualType QTy = FD->getType(); 9986 if (FD->isBitField()) { 9987 unsigned BitWidth = FD->getBitWidthValue(getContext()); 9988 // Allow a bitfield with a type greater than XLen as long as the 9989 // bitwidth is XLen or less. 9990 if (getContext().getTypeSize(QTy) > XLen && BitWidth <= XLen) 9991 QTy = getContext().getIntTypeForBitwidth(XLen, false); 9992 if (BitWidth == 0) { 9993 ZeroWidthBitFieldCount++; 9994 continue; 9995 } 9996 } 9997 9998 bool Ret = detectFPCCEligibleStructHelper( 9999 QTy, CurOff + getContext().toCharUnitsFromBits(FieldOffInBits), 10000 Field1Ty, Field1Off, Field2Ty, Field2Off); 10001 if (!Ret) 10002 return false; 10003 10004 // As a quirk of the ABI, zero-width bitfields aren't ignored for fp+fp 10005 // or int+fp structs, but are ignored for a struct with an fp field and 10006 // any number of zero-width bitfields. 10007 if (Field2Ty && ZeroWidthBitFieldCount > 0) 10008 return false; 10009 } 10010 return Field1Ty != nullptr; 10011 } 10012 10013 return false; 10014 } 10015 10016 // Determine if a struct is eligible for passing according to the floating 10017 // point calling convention (i.e., when flattened it contains a single fp 10018 // value, fp+fp, or int+fp of appropriate size). If so, NeededArgFPRs and 10019 // NeededArgGPRs are incremented appropriately. 10020 bool RISCVABIInfo::detectFPCCEligibleStruct(QualType Ty, llvm::Type *&Field1Ty, 10021 CharUnits &Field1Off, 10022 llvm::Type *&Field2Ty, 10023 CharUnits &Field2Off, 10024 int &NeededArgGPRs, 10025 int &NeededArgFPRs) const { 10026 Field1Ty = nullptr; 10027 Field2Ty = nullptr; 10028 NeededArgGPRs = 0; 10029 NeededArgFPRs = 0; 10030 bool IsCandidate = detectFPCCEligibleStructHelper( 10031 Ty, CharUnits::Zero(), Field1Ty, Field1Off, Field2Ty, Field2Off); 10032 // Not really a candidate if we have a single int but no float. 10033 if (Field1Ty && !Field2Ty && !Field1Ty->isFloatingPointTy()) 10034 return false; 10035 if (!IsCandidate) 10036 return false; 10037 if (Field1Ty && Field1Ty->isFloatingPointTy()) 10038 NeededArgFPRs++; 10039 else if (Field1Ty) 10040 NeededArgGPRs++; 10041 if (Field2Ty && Field2Ty->isFloatingPointTy()) 10042 NeededArgFPRs++; 10043 else if (Field2Ty) 10044 NeededArgGPRs++; 10045 return IsCandidate; 10046 } 10047 10048 // Call getCoerceAndExpand for the two-element flattened struct described by 10049 // Field1Ty, Field1Off, Field2Ty, Field2Off. This method will create an 10050 // appropriate coerceToType and unpaddedCoerceToType. 10051 ABIArgInfo RISCVABIInfo::coerceAndExpandFPCCEligibleStruct( 10052 llvm::Type *Field1Ty, CharUnits Field1Off, llvm::Type *Field2Ty, 10053 CharUnits Field2Off) const { 10054 SmallVector<llvm::Type *, 3> CoerceElts; 10055 SmallVector<llvm::Type *, 2> UnpaddedCoerceElts; 10056 if (!Field1Off.isZero()) 10057 CoerceElts.push_back(llvm::ArrayType::get( 10058 llvm::Type::getInt8Ty(getVMContext()), Field1Off.getQuantity())); 10059 10060 CoerceElts.push_back(Field1Ty); 10061 UnpaddedCoerceElts.push_back(Field1Ty); 10062 10063 if (!Field2Ty) { 10064 return ABIArgInfo::getCoerceAndExpand( 10065 llvm::StructType::get(getVMContext(), CoerceElts, !Field1Off.isZero()), 10066 UnpaddedCoerceElts[0]); 10067 } 10068 10069 CharUnits Field2Align = 10070 CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(Field2Ty)); 10071 CharUnits Field1Size = 10072 CharUnits::fromQuantity(getDataLayout().getTypeStoreSize(Field1Ty)); 10073 CharUnits Field2OffNoPadNoPack = Field1Size.alignTo(Field2Align); 10074 10075 CharUnits Padding = CharUnits::Zero(); 10076 if (Field2Off > Field2OffNoPadNoPack) 10077 Padding = Field2Off - Field2OffNoPadNoPack; 10078 else if (Field2Off != Field2Align && Field2Off > Field1Size) 10079 Padding = Field2Off - Field1Size; 10080 10081 bool IsPacked = !Field2Off.isMultipleOf(Field2Align); 10082 10083 if (!Padding.isZero()) 10084 CoerceElts.push_back(llvm::ArrayType::get( 10085 llvm::Type::getInt8Ty(getVMContext()), Padding.getQuantity())); 10086 10087 CoerceElts.push_back(Field2Ty); 10088 UnpaddedCoerceElts.push_back(Field2Ty); 10089 10090 auto CoerceToType = 10091 llvm::StructType::get(getVMContext(), CoerceElts, IsPacked); 10092 auto UnpaddedCoerceToType = 10093 llvm::StructType::get(getVMContext(), UnpaddedCoerceElts, IsPacked); 10094 10095 return ABIArgInfo::getCoerceAndExpand(CoerceToType, UnpaddedCoerceToType); 10096 } 10097 10098 ABIArgInfo RISCVABIInfo::classifyArgumentType(QualType Ty, bool IsFixed, 10099 int &ArgGPRsLeft, 10100 int &ArgFPRsLeft) const { 10101 assert(ArgGPRsLeft <= NumArgGPRs && "Arg GPR tracking underflow"); 10102 Ty = useFirstFieldIfTransparentUnion(Ty); 10103 10104 // Structures with either a non-trivial destructor or a non-trivial 10105 // copy constructor are always passed indirectly. 10106 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) { 10107 if (ArgGPRsLeft) 10108 ArgGPRsLeft -= 1; 10109 return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA == 10110 CGCXXABI::RAA_DirectInMemory); 10111 } 10112 10113 // Ignore empty structs/unions. 10114 if (isEmptyRecord(getContext(), Ty, true)) 10115 return ABIArgInfo::getIgnore(); 10116 10117 uint64_t Size = getContext().getTypeSize(Ty); 10118 10119 // Pass floating point values via FPRs if possible. 10120 if (IsFixed && Ty->isFloatingType() && FLen >= Size && ArgFPRsLeft) { 10121 ArgFPRsLeft--; 10122 return ABIArgInfo::getDirect(); 10123 } 10124 10125 // Complex types for the hard float ABI must be passed direct rather than 10126 // using CoerceAndExpand. 10127 if (IsFixed && Ty->isComplexType() && FLen && ArgFPRsLeft >= 2) { 10128 QualType EltTy = Ty->castAs<ComplexType>()->getElementType(); 10129 if (getContext().getTypeSize(EltTy) <= FLen) { 10130 ArgFPRsLeft -= 2; 10131 return ABIArgInfo::getDirect(); 10132 } 10133 } 10134 10135 if (IsFixed && FLen && Ty->isStructureOrClassType()) { 10136 llvm::Type *Field1Ty = nullptr; 10137 llvm::Type *Field2Ty = nullptr; 10138 CharUnits Field1Off = CharUnits::Zero(); 10139 CharUnits Field2Off = CharUnits::Zero(); 10140 int NeededArgGPRs; 10141 int NeededArgFPRs; 10142 bool IsCandidate = 10143 detectFPCCEligibleStruct(Ty, Field1Ty, Field1Off, Field2Ty, Field2Off, 10144 NeededArgGPRs, NeededArgFPRs); 10145 if (IsCandidate && NeededArgGPRs <= ArgGPRsLeft && 10146 NeededArgFPRs <= ArgFPRsLeft) { 10147 ArgGPRsLeft -= NeededArgGPRs; 10148 ArgFPRsLeft -= NeededArgFPRs; 10149 return coerceAndExpandFPCCEligibleStruct(Field1Ty, Field1Off, Field2Ty, 10150 Field2Off); 10151 } 10152 } 10153 10154 uint64_t NeededAlign = getContext().getTypeAlign(Ty); 10155 bool MustUseStack = false; 10156 // Determine the number of GPRs needed to pass the current argument 10157 // according to the ABI. 2*XLen-aligned varargs are passed in "aligned" 10158 // register pairs, so may consume 3 registers. 10159 int NeededArgGPRs = 1; 10160 if (!IsFixed && NeededAlign == 2 * XLen) 10161 NeededArgGPRs = 2 + (ArgGPRsLeft % 2); 10162 else if (Size > XLen && Size <= 2 * XLen) 10163 NeededArgGPRs = 2; 10164 10165 if (NeededArgGPRs > ArgGPRsLeft) { 10166 MustUseStack = true; 10167 NeededArgGPRs = ArgGPRsLeft; 10168 } 10169 10170 ArgGPRsLeft -= NeededArgGPRs; 10171 10172 if (!isAggregateTypeForABI(Ty) && !Ty->isVectorType()) { 10173 // Treat an enum type as its underlying type. 10174 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 10175 Ty = EnumTy->getDecl()->getIntegerType(); 10176 10177 // All integral types are promoted to XLen width, unless passed on the 10178 // stack. 10179 if (Size < XLen && Ty->isIntegralOrEnumerationType() && !MustUseStack) { 10180 return extendType(Ty); 10181 } 10182 10183 return ABIArgInfo::getDirect(); 10184 } 10185 10186 // Aggregates which are <= 2*XLen will be passed in registers if possible, 10187 // so coerce to integers. 10188 if (Size <= 2 * XLen) { 10189 unsigned Alignment = getContext().getTypeAlign(Ty); 10190 10191 // Use a single XLen int if possible, 2*XLen if 2*XLen alignment is 10192 // required, and a 2-element XLen array if only XLen alignment is required. 10193 if (Size <= XLen) { 10194 return ABIArgInfo::getDirect( 10195 llvm::IntegerType::get(getVMContext(), XLen)); 10196 } else if (Alignment == 2 * XLen) { 10197 return ABIArgInfo::getDirect( 10198 llvm::IntegerType::get(getVMContext(), 2 * XLen)); 10199 } else { 10200 return ABIArgInfo::getDirect(llvm::ArrayType::get( 10201 llvm::IntegerType::get(getVMContext(), XLen), 2)); 10202 } 10203 } 10204 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 10205 } 10206 10207 ABIArgInfo RISCVABIInfo::classifyReturnType(QualType RetTy) const { 10208 if (RetTy->isVoidType()) 10209 return ABIArgInfo::getIgnore(); 10210 10211 int ArgGPRsLeft = 2; 10212 int ArgFPRsLeft = FLen ? 2 : 0; 10213 10214 // The rules for return and argument types are the same, so defer to 10215 // classifyArgumentType. 10216 return classifyArgumentType(RetTy, /*IsFixed=*/true, ArgGPRsLeft, 10217 ArgFPRsLeft); 10218 } 10219 10220 Address RISCVABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 10221 QualType Ty) const { 10222 CharUnits SlotSize = CharUnits::fromQuantity(XLen / 8); 10223 10224 // Empty records are ignored for parameter passing purposes. 10225 if (isEmptyRecord(getContext(), Ty, true)) { 10226 Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize); 10227 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty)); 10228 return Addr; 10229 } 10230 10231 std::pair<CharUnits, CharUnits> SizeAndAlign = 10232 getContext().getTypeInfoInChars(Ty); 10233 10234 // Arguments bigger than 2*Xlen bytes are passed indirectly. 10235 bool IsIndirect = SizeAndAlign.first > 2 * SlotSize; 10236 10237 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, SizeAndAlign, 10238 SlotSize, /*AllowHigherAlign=*/true); 10239 } 10240 10241 ABIArgInfo RISCVABIInfo::extendType(QualType Ty) const { 10242 int TySize = getContext().getTypeSize(Ty); 10243 // RV64 ABI requires unsigned 32 bit integers to be sign extended. 10244 if (XLen == 64 && Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32) 10245 return ABIArgInfo::getSignExtend(Ty); 10246 return ABIArgInfo::getExtend(Ty); 10247 } 10248 10249 namespace { 10250 class RISCVTargetCodeGenInfo : public TargetCodeGenInfo { 10251 public: 10252 RISCVTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, unsigned XLen, 10253 unsigned FLen) 10254 : TargetCodeGenInfo(std::make_unique<RISCVABIInfo>(CGT, XLen, FLen)) {} 10255 10256 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 10257 CodeGen::CodeGenModule &CGM) const override { 10258 const auto *FD = dyn_cast_or_null<FunctionDecl>(D); 10259 if (!FD) return; 10260 10261 const auto *Attr = FD->getAttr<RISCVInterruptAttr>(); 10262 if (!Attr) 10263 return; 10264 10265 const char *Kind; 10266 switch (Attr->getInterrupt()) { 10267 case RISCVInterruptAttr::user: Kind = "user"; break; 10268 case RISCVInterruptAttr::supervisor: Kind = "supervisor"; break; 10269 case RISCVInterruptAttr::machine: Kind = "machine"; break; 10270 } 10271 10272 auto *Fn = cast<llvm::Function>(GV); 10273 10274 Fn->addFnAttr("interrupt", Kind); 10275 } 10276 }; 10277 } // namespace 10278 10279 //===----------------------------------------------------------------------===// 10280 // Driver code 10281 //===----------------------------------------------------------------------===// 10282 10283 bool CodeGenModule::supportsCOMDAT() const { 10284 return getTriple().supportsCOMDAT(); 10285 } 10286 10287 const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() { 10288 if (TheTargetCodeGenInfo) 10289 return *TheTargetCodeGenInfo; 10290 10291 // Helper to set the unique_ptr while still keeping the return value. 10292 auto SetCGInfo = [&](TargetCodeGenInfo *P) -> const TargetCodeGenInfo & { 10293 this->TheTargetCodeGenInfo.reset(P); 10294 return *P; 10295 }; 10296 10297 const llvm::Triple &Triple = getTarget().getTriple(); 10298 switch (Triple.getArch()) { 10299 default: 10300 return SetCGInfo(new DefaultTargetCodeGenInfo(Types)); 10301 10302 case llvm::Triple::le32: 10303 return SetCGInfo(new PNaClTargetCodeGenInfo(Types)); 10304 case llvm::Triple::mips: 10305 case llvm::Triple::mipsel: 10306 if (Triple.getOS() == llvm::Triple::NaCl) 10307 return SetCGInfo(new PNaClTargetCodeGenInfo(Types)); 10308 return SetCGInfo(new MIPSTargetCodeGenInfo(Types, true)); 10309 10310 case llvm::Triple::mips64: 10311 case llvm::Triple::mips64el: 10312 return SetCGInfo(new MIPSTargetCodeGenInfo(Types, false)); 10313 10314 case llvm::Triple::avr: 10315 return SetCGInfo(new AVRTargetCodeGenInfo(Types)); 10316 10317 case llvm::Triple::aarch64: 10318 case llvm::Triple::aarch64_32: 10319 case llvm::Triple::aarch64_be: { 10320 AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS; 10321 if (getTarget().getABI() == "darwinpcs") 10322 Kind = AArch64ABIInfo::DarwinPCS; 10323 else if (Triple.isOSWindows()) 10324 return SetCGInfo( 10325 new WindowsAArch64TargetCodeGenInfo(Types, AArch64ABIInfo::Win64)); 10326 10327 return SetCGInfo(new AArch64TargetCodeGenInfo(Types, Kind)); 10328 } 10329 10330 case llvm::Triple::wasm32: 10331 case llvm::Triple::wasm64: { 10332 WebAssemblyABIInfo::ABIKind Kind = WebAssemblyABIInfo::MVP; 10333 if (getTarget().getABI() == "experimental-mv") 10334 Kind = WebAssemblyABIInfo::ExperimentalMV; 10335 return SetCGInfo(new WebAssemblyTargetCodeGenInfo(Types, Kind)); 10336 } 10337 10338 case llvm::Triple::arm: 10339 case llvm::Triple::armeb: 10340 case llvm::Triple::thumb: 10341 case llvm::Triple::thumbeb: { 10342 if (Triple.getOS() == llvm::Triple::Win32) { 10343 return SetCGInfo( 10344 new WindowsARMTargetCodeGenInfo(Types, ARMABIInfo::AAPCS_VFP)); 10345 } 10346 10347 ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS; 10348 StringRef ABIStr = getTarget().getABI(); 10349 if (ABIStr == "apcs-gnu") 10350 Kind = ARMABIInfo::APCS; 10351 else if (ABIStr == "aapcs16") 10352 Kind = ARMABIInfo::AAPCS16_VFP; 10353 else if (CodeGenOpts.FloatABI == "hard" || 10354 (CodeGenOpts.FloatABI != "soft" && 10355 (Triple.getEnvironment() == llvm::Triple::GNUEABIHF || 10356 Triple.getEnvironment() == llvm::Triple::MuslEABIHF || 10357 Triple.getEnvironment() == llvm::Triple::EABIHF))) 10358 Kind = ARMABIInfo::AAPCS_VFP; 10359 10360 return SetCGInfo(new ARMTargetCodeGenInfo(Types, Kind)); 10361 } 10362 10363 case llvm::Triple::ppc: { 10364 bool IsSoftFloat = 10365 CodeGenOpts.FloatABI == "soft" || getTarget().hasFeature("spe"); 10366 bool RetSmallStructInRegABI = 10367 PPC32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts); 10368 return SetCGInfo( 10369 new PPC32TargetCodeGenInfo(Types, IsSoftFloat, RetSmallStructInRegABI)); 10370 } 10371 case llvm::Triple::ppc64: 10372 if (Triple.isOSBinFormatELF()) { 10373 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1; 10374 if (getTarget().getABI() == "elfv2") 10375 Kind = PPC64_SVR4_ABIInfo::ELFv2; 10376 bool HasQPX = getTarget().getABI() == "elfv1-qpx"; 10377 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft"; 10378 10379 return SetCGInfo(new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX, 10380 IsSoftFloat)); 10381 } else 10382 return SetCGInfo(new PPC64TargetCodeGenInfo(Types)); 10383 case llvm::Triple::ppc64le: { 10384 assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!"); 10385 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2; 10386 if (getTarget().getABI() == "elfv1" || getTarget().getABI() == "elfv1-qpx") 10387 Kind = PPC64_SVR4_ABIInfo::ELFv1; 10388 bool HasQPX = getTarget().getABI() == "elfv1-qpx"; 10389 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft"; 10390 10391 return SetCGInfo(new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX, 10392 IsSoftFloat)); 10393 } 10394 10395 case llvm::Triple::nvptx: 10396 case llvm::Triple::nvptx64: 10397 return SetCGInfo(new NVPTXTargetCodeGenInfo(Types)); 10398 10399 case llvm::Triple::msp430: 10400 return SetCGInfo(new MSP430TargetCodeGenInfo(Types)); 10401 10402 case llvm::Triple::riscv32: 10403 case llvm::Triple::riscv64: { 10404 StringRef ABIStr = getTarget().getABI(); 10405 unsigned XLen = getTarget().getPointerWidth(0); 10406 unsigned ABIFLen = 0; 10407 if (ABIStr.endswith("f")) 10408 ABIFLen = 32; 10409 else if (ABIStr.endswith("d")) 10410 ABIFLen = 64; 10411 return SetCGInfo(new RISCVTargetCodeGenInfo(Types, XLen, ABIFLen)); 10412 } 10413 10414 case llvm::Triple::systemz: { 10415 bool SoftFloat = CodeGenOpts.FloatABI == "soft"; 10416 bool HasVector = !SoftFloat && getTarget().getABI() == "vector"; 10417 return SetCGInfo(new SystemZTargetCodeGenInfo(Types, HasVector, SoftFloat)); 10418 } 10419 10420 case llvm::Triple::tce: 10421 case llvm::Triple::tcele: 10422 return SetCGInfo(new TCETargetCodeGenInfo(Types)); 10423 10424 case llvm::Triple::x86: { 10425 bool IsDarwinVectorABI = Triple.isOSDarwin(); 10426 bool RetSmallStructInRegABI = 10427 X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts); 10428 bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing(); 10429 10430 if (Triple.getOS() == llvm::Triple::Win32) { 10431 return SetCGInfo(new WinX86_32TargetCodeGenInfo( 10432 Types, IsDarwinVectorABI, RetSmallStructInRegABI, 10433 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters)); 10434 } else { 10435 return SetCGInfo(new X86_32TargetCodeGenInfo( 10436 Types, IsDarwinVectorABI, RetSmallStructInRegABI, 10437 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters, 10438 CodeGenOpts.FloatABI == "soft")); 10439 } 10440 } 10441 10442 case llvm::Triple::x86_64: { 10443 StringRef ABI = getTarget().getABI(); 10444 X86AVXABILevel AVXLevel = 10445 (ABI == "avx512" 10446 ? X86AVXABILevel::AVX512 10447 : ABI == "avx" ? X86AVXABILevel::AVX : X86AVXABILevel::None); 10448 10449 switch (Triple.getOS()) { 10450 case llvm::Triple::Win32: 10451 return SetCGInfo(new WinX86_64TargetCodeGenInfo(Types, AVXLevel)); 10452 default: 10453 return SetCGInfo(new X86_64TargetCodeGenInfo(Types, AVXLevel)); 10454 } 10455 } 10456 case llvm::Triple::hexagon: 10457 return SetCGInfo(new HexagonTargetCodeGenInfo(Types)); 10458 case llvm::Triple::lanai: 10459 return SetCGInfo(new LanaiTargetCodeGenInfo(Types)); 10460 case llvm::Triple::r600: 10461 return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types)); 10462 case llvm::Triple::amdgcn: 10463 return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types)); 10464 case llvm::Triple::sparc: 10465 return SetCGInfo(new SparcV8TargetCodeGenInfo(Types)); 10466 case llvm::Triple::sparcv9: 10467 return SetCGInfo(new SparcV9TargetCodeGenInfo(Types)); 10468 case llvm::Triple::xcore: 10469 return SetCGInfo(new XCoreTargetCodeGenInfo(Types)); 10470 case llvm::Triple::arc: 10471 return SetCGInfo(new ARCTargetCodeGenInfo(Types)); 10472 case llvm::Triple::spir: 10473 case llvm::Triple::spir64: 10474 return SetCGInfo(new SPIRTargetCodeGenInfo(Types)); 10475 } 10476 } 10477 10478 /// Create an OpenCL kernel for an enqueued block. 10479 /// 10480 /// The kernel has the same function type as the block invoke function. Its 10481 /// name is the name of the block invoke function postfixed with "_kernel". 10482 /// It simply calls the block invoke function then returns. 10483 llvm::Function * 10484 TargetCodeGenInfo::createEnqueuedBlockKernel(CodeGenFunction &CGF, 10485 llvm::Function *Invoke, 10486 llvm::Value *BlockLiteral) const { 10487 auto *InvokeFT = Invoke->getFunctionType(); 10488 llvm::SmallVector<llvm::Type *, 2> ArgTys; 10489 for (auto &P : InvokeFT->params()) 10490 ArgTys.push_back(P); 10491 auto &C = CGF.getLLVMContext(); 10492 std::string Name = Invoke->getName().str() + "_kernel"; 10493 auto *FT = llvm::FunctionType::get(llvm::Type::getVoidTy(C), ArgTys, false); 10494 auto *F = llvm::Function::Create(FT, llvm::GlobalValue::InternalLinkage, Name, 10495 &CGF.CGM.getModule()); 10496 auto IP = CGF.Builder.saveIP(); 10497 auto *BB = llvm::BasicBlock::Create(C, "entry", F); 10498 auto &Builder = CGF.Builder; 10499 Builder.SetInsertPoint(BB); 10500 llvm::SmallVector<llvm::Value *, 2> Args; 10501 for (auto &A : F->args()) 10502 Args.push_back(&A); 10503 Builder.CreateCall(Invoke, Args); 10504 Builder.CreateRetVoid(); 10505 Builder.restoreIP(IP); 10506 return F; 10507 } 10508 10509 /// Create an OpenCL kernel for an enqueued block. 10510 /// 10511 /// The type of the first argument (the block literal) is the struct type 10512 /// of the block literal instead of a pointer type. The first argument 10513 /// (block literal) is passed directly by value to the kernel. The kernel 10514 /// allocates the same type of struct on stack and stores the block literal 10515 /// to it and passes its pointer to the block invoke function. The kernel 10516 /// has "enqueued-block" function attribute and kernel argument metadata. 10517 llvm::Function *AMDGPUTargetCodeGenInfo::createEnqueuedBlockKernel( 10518 CodeGenFunction &CGF, llvm::Function *Invoke, 10519 llvm::Value *BlockLiteral) const { 10520 auto &Builder = CGF.Builder; 10521 auto &C = CGF.getLLVMContext(); 10522 10523 auto *BlockTy = BlockLiteral->getType()->getPointerElementType(); 10524 auto *InvokeFT = Invoke->getFunctionType(); 10525 llvm::SmallVector<llvm::Type *, 2> ArgTys; 10526 llvm::SmallVector<llvm::Metadata *, 8> AddressQuals; 10527 llvm::SmallVector<llvm::Metadata *, 8> AccessQuals; 10528 llvm::SmallVector<llvm::Metadata *, 8> ArgTypeNames; 10529 llvm::SmallVector<llvm::Metadata *, 8> ArgBaseTypeNames; 10530 llvm::SmallVector<llvm::Metadata *, 8> ArgTypeQuals; 10531 llvm::SmallVector<llvm::Metadata *, 8> ArgNames; 10532 10533 ArgTys.push_back(BlockTy); 10534 ArgTypeNames.push_back(llvm::MDString::get(C, "__block_literal")); 10535 AddressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(0))); 10536 ArgBaseTypeNames.push_back(llvm::MDString::get(C, "__block_literal")); 10537 ArgTypeQuals.push_back(llvm::MDString::get(C, "")); 10538 AccessQuals.push_back(llvm::MDString::get(C, "none")); 10539 ArgNames.push_back(llvm::MDString::get(C, "block_literal")); 10540 for (unsigned I = 1, E = InvokeFT->getNumParams(); I < E; ++I) { 10541 ArgTys.push_back(InvokeFT->getParamType(I)); 10542 ArgTypeNames.push_back(llvm::MDString::get(C, "void*")); 10543 AddressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(3))); 10544 AccessQuals.push_back(llvm::MDString::get(C, "none")); 10545 ArgBaseTypeNames.push_back(llvm::MDString::get(C, "void*")); 10546 ArgTypeQuals.push_back(llvm::MDString::get(C, "")); 10547 ArgNames.push_back( 10548 llvm::MDString::get(C, (Twine("local_arg") + Twine(I)).str())); 10549 } 10550 std::string Name = Invoke->getName().str() + "_kernel"; 10551 auto *FT = llvm::FunctionType::get(llvm::Type::getVoidTy(C), ArgTys, false); 10552 auto *F = llvm::Function::Create(FT, llvm::GlobalValue::InternalLinkage, Name, 10553 &CGF.CGM.getModule()); 10554 F->addFnAttr("enqueued-block"); 10555 auto IP = CGF.Builder.saveIP(); 10556 auto *BB = llvm::BasicBlock::Create(C, "entry", F); 10557 Builder.SetInsertPoint(BB); 10558 const auto BlockAlign = CGF.CGM.getDataLayout().getPrefTypeAlign(BlockTy); 10559 auto *BlockPtr = Builder.CreateAlloca(BlockTy, nullptr); 10560 BlockPtr->setAlignment(BlockAlign); 10561 Builder.CreateAlignedStore(F->arg_begin(), BlockPtr, BlockAlign); 10562 auto *Cast = Builder.CreatePointerCast(BlockPtr, InvokeFT->getParamType(0)); 10563 llvm::SmallVector<llvm::Value *, 2> Args; 10564 Args.push_back(Cast); 10565 for (auto I = F->arg_begin() + 1, E = F->arg_end(); I != E; ++I) 10566 Args.push_back(I); 10567 Builder.CreateCall(Invoke, Args); 10568 Builder.CreateRetVoid(); 10569 Builder.restoreIP(IP); 10570 10571 F->setMetadata("kernel_arg_addr_space", llvm::MDNode::get(C, AddressQuals)); 10572 F->setMetadata("kernel_arg_access_qual", llvm::MDNode::get(C, AccessQuals)); 10573 F->setMetadata("kernel_arg_type", llvm::MDNode::get(C, ArgTypeNames)); 10574 F->setMetadata("kernel_arg_base_type", 10575 llvm::MDNode::get(C, ArgBaseTypeNames)); 10576 F->setMetadata("kernel_arg_type_qual", llvm::MDNode::get(C, ArgTypeQuals)); 10577 if (CGF.CGM.getCodeGenOpts().EmitOpenCLArgMetadata) 10578 F->setMetadata("kernel_arg_name", llvm::MDNode::get(C, ArgNames)); 10579 10580 return F; 10581 } 10582