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() { delete Info; } 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(new 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(new 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(new 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)->getBitWidth() != 64) { 974 // Invalid MMX constraint 975 return nullptr; 976 } 977 978 return llvm::Type::getX86_MMXTy(CGF.getLLVMContext()); 979 } 980 981 // No operation needed 982 return Ty; 983 } 984 985 /// Returns true if this type can be passed in SSE registers with the 986 /// X86_VectorCall calling convention. Shared between x86_32 and x86_64. 987 static bool isX86VectorTypeForVectorCall(ASTContext &Context, QualType Ty) { 988 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) { 989 if (BT->isFloatingPoint() && BT->getKind() != BuiltinType::Half) { 990 if (BT->getKind() == BuiltinType::LongDouble) { 991 if (&Context.getTargetInfo().getLongDoubleFormat() == 992 &llvm::APFloat::x87DoubleExtended()) 993 return false; 994 } 995 return true; 996 } 997 } else if (const VectorType *VT = Ty->getAs<VectorType>()) { 998 // vectorcall can pass XMM, YMM, and ZMM vectors. We don't pass SSE1 MMX 999 // registers specially. 1000 unsigned VecSize = Context.getTypeSize(VT); 1001 if (VecSize == 128 || VecSize == 256 || VecSize == 512) 1002 return true; 1003 } 1004 return false; 1005 } 1006 1007 /// Returns true if this aggregate is small enough to be passed in SSE registers 1008 /// in the X86_VectorCall calling convention. Shared between x86_32 and x86_64. 1009 static bool isX86VectorCallAggregateSmallEnough(uint64_t NumMembers) { 1010 return NumMembers <= 4; 1011 } 1012 1013 /// Returns a Homogeneous Vector Aggregate ABIArgInfo, used in X86. 1014 static ABIArgInfo getDirectX86Hva(llvm::Type* T = nullptr) { 1015 auto AI = ABIArgInfo::getDirect(T); 1016 AI.setInReg(true); 1017 AI.setCanBeFlattened(false); 1018 return AI; 1019 } 1020 1021 //===----------------------------------------------------------------------===// 1022 // X86-32 ABI Implementation 1023 //===----------------------------------------------------------------------===// 1024 1025 /// Similar to llvm::CCState, but for Clang. 1026 struct CCState { 1027 CCState(CGFunctionInfo &FI) 1028 : IsPreassigned(FI.arg_size()), CC(FI.getCallingConvention()) {} 1029 1030 llvm::SmallBitVector IsPreassigned; 1031 unsigned CC = CallingConv::CC_C; 1032 unsigned FreeRegs = 0; 1033 unsigned FreeSSERegs = 0; 1034 }; 1035 1036 enum { 1037 // Vectorcall only allows the first 6 parameters to be passed in registers. 1038 VectorcallMaxParamNumAsReg = 6 1039 }; 1040 1041 /// X86_32ABIInfo - The X86-32 ABI information. 1042 class X86_32ABIInfo : public SwiftABIInfo { 1043 enum Class { 1044 Integer, 1045 Float 1046 }; 1047 1048 static const unsigned MinABIStackAlignInBytes = 4; 1049 1050 bool IsDarwinVectorABI; 1051 bool IsRetSmallStructInRegABI; 1052 bool IsWin32StructABI; 1053 bool IsSoftFloatABI; 1054 bool IsMCUABI; 1055 unsigned DefaultNumRegisterParameters; 1056 1057 static bool isRegisterSize(unsigned Size) { 1058 return (Size == 8 || Size == 16 || Size == 32 || Size == 64); 1059 } 1060 1061 bool isHomogeneousAggregateBaseType(QualType Ty) const override { 1062 // FIXME: Assumes vectorcall is in use. 1063 return isX86VectorTypeForVectorCall(getContext(), Ty); 1064 } 1065 1066 bool isHomogeneousAggregateSmallEnough(const Type *Ty, 1067 uint64_t NumMembers) const override { 1068 // FIXME: Assumes vectorcall is in use. 1069 return isX86VectorCallAggregateSmallEnough(NumMembers); 1070 } 1071 1072 bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context) const; 1073 1074 /// getIndirectResult - Give a source type \arg Ty, return a suitable result 1075 /// such that the argument will be passed in memory. 1076 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const; 1077 1078 ABIArgInfo getIndirectReturnResult(QualType Ty, CCState &State) const; 1079 1080 /// Return the alignment to use for the given type on the stack. 1081 unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const; 1082 1083 Class classify(QualType Ty) const; 1084 ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const; 1085 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const; 1086 1087 /// Updates the number of available free registers, returns 1088 /// true if any registers were allocated. 1089 bool updateFreeRegs(QualType Ty, CCState &State) const; 1090 1091 bool shouldAggregateUseDirect(QualType Ty, CCState &State, bool &InReg, 1092 bool &NeedsPadding) const; 1093 bool shouldPrimitiveUseInReg(QualType Ty, CCState &State) const; 1094 1095 bool canExpandIndirectArgument(QualType Ty) const; 1096 1097 /// Rewrite the function info so that all memory arguments use 1098 /// inalloca. 1099 void rewriteWithInAlloca(CGFunctionInfo &FI) const; 1100 1101 void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields, 1102 CharUnits &StackOffset, ABIArgInfo &Info, 1103 QualType Type) const; 1104 void runVectorCallFirstPass(CGFunctionInfo &FI, CCState &State) const; 1105 1106 public: 1107 1108 void computeInfo(CGFunctionInfo &FI) const override; 1109 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 1110 QualType Ty) const override; 1111 1112 X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI, 1113 bool RetSmallStructInRegABI, bool Win32StructABI, 1114 unsigned NumRegisterParameters, bool SoftFloatABI) 1115 : SwiftABIInfo(CGT), IsDarwinVectorABI(DarwinVectorABI), 1116 IsRetSmallStructInRegABI(RetSmallStructInRegABI), 1117 IsWin32StructABI(Win32StructABI), 1118 IsSoftFloatABI(SoftFloatABI), 1119 IsMCUABI(CGT.getTarget().getTriple().isOSIAMCU()), 1120 DefaultNumRegisterParameters(NumRegisterParameters) {} 1121 1122 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars, 1123 bool asReturnValue) const override { 1124 // LLVM's x86-32 lowering currently only assigns up to three 1125 // integer registers and three fp registers. Oddly, it'll use up to 1126 // four vector registers for vectors, but those can overlap with the 1127 // scalar registers. 1128 return occupiesMoreThan(CGT, scalars, /*total*/ 3); 1129 } 1130 1131 bool isSwiftErrorInRegister() const override { 1132 // x86-32 lowering does not support passing swifterror in a register. 1133 return false; 1134 } 1135 }; 1136 1137 class X86_32TargetCodeGenInfo : public TargetCodeGenInfo { 1138 public: 1139 X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI, 1140 bool RetSmallStructInRegABI, bool Win32StructABI, 1141 unsigned NumRegisterParameters, bool SoftFloatABI) 1142 : TargetCodeGenInfo(new X86_32ABIInfo( 1143 CGT, DarwinVectorABI, RetSmallStructInRegABI, Win32StructABI, 1144 NumRegisterParameters, SoftFloatABI)) {} 1145 1146 static bool isStructReturnInRegABI( 1147 const llvm::Triple &Triple, const CodeGenOptions &Opts); 1148 1149 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 1150 CodeGen::CodeGenModule &CGM) const override; 1151 1152 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override { 1153 // Darwin uses different dwarf register numbers for EH. 1154 if (CGM.getTarget().getTriple().isOSDarwin()) return 5; 1155 return 4; 1156 } 1157 1158 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 1159 llvm::Value *Address) const override; 1160 1161 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF, 1162 StringRef Constraint, 1163 llvm::Type* Ty) const override { 1164 return X86AdjustInlineAsmType(CGF, Constraint, Ty); 1165 } 1166 1167 void addReturnRegisterOutputs(CodeGenFunction &CGF, LValue ReturnValue, 1168 std::string &Constraints, 1169 std::vector<llvm::Type *> &ResultRegTypes, 1170 std::vector<llvm::Type *> &ResultTruncRegTypes, 1171 std::vector<LValue> &ResultRegDests, 1172 std::string &AsmString, 1173 unsigned NumOutputs) const override; 1174 1175 llvm::Constant * 1176 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override { 1177 unsigned Sig = (0xeb << 0) | // jmp rel8 1178 (0x06 << 8) | // .+0x08 1179 ('v' << 16) | 1180 ('2' << 24); 1181 return llvm::ConstantInt::get(CGM.Int32Ty, Sig); 1182 } 1183 1184 StringRef getARCRetainAutoreleasedReturnValueMarker() const override { 1185 return "movl\t%ebp, %ebp" 1186 "\t\t// marker for objc_retainAutoreleaseReturnValue"; 1187 } 1188 }; 1189 1190 } 1191 1192 /// Rewrite input constraint references after adding some output constraints. 1193 /// In the case where there is one output and one input and we add one output, 1194 /// we need to replace all operand references greater than or equal to 1: 1195 /// mov $0, $1 1196 /// mov eax, $1 1197 /// The result will be: 1198 /// mov $0, $2 1199 /// mov eax, $2 1200 static void rewriteInputConstraintReferences(unsigned FirstIn, 1201 unsigned NumNewOuts, 1202 std::string &AsmString) { 1203 std::string Buf; 1204 llvm::raw_string_ostream OS(Buf); 1205 size_t Pos = 0; 1206 while (Pos < AsmString.size()) { 1207 size_t DollarStart = AsmString.find('$', Pos); 1208 if (DollarStart == std::string::npos) 1209 DollarStart = AsmString.size(); 1210 size_t DollarEnd = AsmString.find_first_not_of('$', DollarStart); 1211 if (DollarEnd == std::string::npos) 1212 DollarEnd = AsmString.size(); 1213 OS << StringRef(&AsmString[Pos], DollarEnd - Pos); 1214 Pos = DollarEnd; 1215 size_t NumDollars = DollarEnd - DollarStart; 1216 if (NumDollars % 2 != 0 && Pos < AsmString.size()) { 1217 // We have an operand reference. 1218 size_t DigitStart = Pos; 1219 if (AsmString[DigitStart] == '{') { 1220 OS << '{'; 1221 ++DigitStart; 1222 } 1223 size_t DigitEnd = AsmString.find_first_not_of("0123456789", DigitStart); 1224 if (DigitEnd == std::string::npos) 1225 DigitEnd = AsmString.size(); 1226 StringRef OperandStr(&AsmString[DigitStart], DigitEnd - DigitStart); 1227 unsigned OperandIndex; 1228 if (!OperandStr.getAsInteger(10, OperandIndex)) { 1229 if (OperandIndex >= FirstIn) 1230 OperandIndex += NumNewOuts; 1231 OS << OperandIndex; 1232 } else { 1233 OS << OperandStr; 1234 } 1235 Pos = DigitEnd; 1236 } 1237 } 1238 AsmString = std::move(OS.str()); 1239 } 1240 1241 /// Add output constraints for EAX:EDX because they are return registers. 1242 void X86_32TargetCodeGenInfo::addReturnRegisterOutputs( 1243 CodeGenFunction &CGF, LValue ReturnSlot, std::string &Constraints, 1244 std::vector<llvm::Type *> &ResultRegTypes, 1245 std::vector<llvm::Type *> &ResultTruncRegTypes, 1246 std::vector<LValue> &ResultRegDests, std::string &AsmString, 1247 unsigned NumOutputs) const { 1248 uint64_t RetWidth = CGF.getContext().getTypeSize(ReturnSlot.getType()); 1249 1250 // Use the EAX constraint if the width is 32 or smaller and EAX:EDX if it is 1251 // larger. 1252 if (!Constraints.empty()) 1253 Constraints += ','; 1254 if (RetWidth <= 32) { 1255 Constraints += "={eax}"; 1256 ResultRegTypes.push_back(CGF.Int32Ty); 1257 } else { 1258 // Use the 'A' constraint for EAX:EDX. 1259 Constraints += "=A"; 1260 ResultRegTypes.push_back(CGF.Int64Ty); 1261 } 1262 1263 // Truncate EAX or EAX:EDX to an integer of the appropriate size. 1264 llvm::Type *CoerceTy = llvm::IntegerType::get(CGF.getLLVMContext(), RetWidth); 1265 ResultTruncRegTypes.push_back(CoerceTy); 1266 1267 // Coerce the integer by bitcasting the return slot pointer. 1268 ReturnSlot.setAddress(CGF.Builder.CreateBitCast(ReturnSlot.getAddress(CGF), 1269 CoerceTy->getPointerTo())); 1270 ResultRegDests.push_back(ReturnSlot); 1271 1272 rewriteInputConstraintReferences(NumOutputs, 1, AsmString); 1273 } 1274 1275 /// shouldReturnTypeInRegister - Determine if the given type should be 1276 /// returned in a register (for the Darwin and MCU ABI). 1277 bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty, 1278 ASTContext &Context) const { 1279 uint64_t Size = Context.getTypeSize(Ty); 1280 1281 // For i386, type must be register sized. 1282 // For the MCU ABI, it only needs to be <= 8-byte 1283 if ((IsMCUABI && Size > 64) || (!IsMCUABI && !isRegisterSize(Size))) 1284 return false; 1285 1286 if (Ty->isVectorType()) { 1287 // 64- and 128- bit vectors inside structures are not returned in 1288 // registers. 1289 if (Size == 64 || Size == 128) 1290 return false; 1291 1292 return true; 1293 } 1294 1295 // If this is a builtin, pointer, enum, complex type, member pointer, or 1296 // member function pointer it is ok. 1297 if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() || 1298 Ty->isAnyComplexType() || Ty->isEnumeralType() || 1299 Ty->isBlockPointerType() || Ty->isMemberPointerType()) 1300 return true; 1301 1302 // Arrays are treated like records. 1303 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) 1304 return shouldReturnTypeInRegister(AT->getElementType(), Context); 1305 1306 // Otherwise, it must be a record type. 1307 const RecordType *RT = Ty->getAs<RecordType>(); 1308 if (!RT) return false; 1309 1310 // FIXME: Traverse bases here too. 1311 1312 // Structure types are passed in register if all fields would be 1313 // passed in a register. 1314 for (const auto *FD : RT->getDecl()->fields()) { 1315 // Empty fields are ignored. 1316 if (isEmptyField(Context, FD, true)) 1317 continue; 1318 1319 // Check fields recursively. 1320 if (!shouldReturnTypeInRegister(FD->getType(), Context)) 1321 return false; 1322 } 1323 return true; 1324 } 1325 1326 static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) { 1327 // Treat complex types as the element type. 1328 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) 1329 Ty = CTy->getElementType(); 1330 1331 // Check for a type which we know has a simple scalar argument-passing 1332 // convention without any padding. (We're specifically looking for 32 1333 // and 64-bit integer and integer-equivalents, float, and double.) 1334 if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() && 1335 !Ty->isEnumeralType() && !Ty->isBlockPointerType()) 1336 return false; 1337 1338 uint64_t Size = Context.getTypeSize(Ty); 1339 return Size == 32 || Size == 64; 1340 } 1341 1342 static bool addFieldSizes(ASTContext &Context, const RecordDecl *RD, 1343 uint64_t &Size) { 1344 for (const auto *FD : RD->fields()) { 1345 // Scalar arguments on the stack get 4 byte alignment on x86. If the 1346 // argument is smaller than 32-bits, expanding the struct will create 1347 // alignment padding. 1348 if (!is32Or64BitBasicType(FD->getType(), Context)) 1349 return false; 1350 1351 // FIXME: Reject bit-fields wholesale; there are two problems, we don't know 1352 // how to expand them yet, and the predicate for telling if a bitfield still 1353 // counts as "basic" is more complicated than what we were doing previously. 1354 if (FD->isBitField()) 1355 return false; 1356 1357 Size += Context.getTypeSize(FD->getType()); 1358 } 1359 return true; 1360 } 1361 1362 static bool addBaseAndFieldSizes(ASTContext &Context, const CXXRecordDecl *RD, 1363 uint64_t &Size) { 1364 // Don't do this if there are any non-empty bases. 1365 for (const CXXBaseSpecifier &Base : RD->bases()) { 1366 if (!addBaseAndFieldSizes(Context, Base.getType()->getAsCXXRecordDecl(), 1367 Size)) 1368 return false; 1369 } 1370 if (!addFieldSizes(Context, RD, Size)) 1371 return false; 1372 return true; 1373 } 1374 1375 /// Test whether an argument type which is to be passed indirectly (on the 1376 /// stack) would have the equivalent layout if it was expanded into separate 1377 /// arguments. If so, we prefer to do the latter to avoid inhibiting 1378 /// optimizations. 1379 bool X86_32ABIInfo::canExpandIndirectArgument(QualType Ty) const { 1380 // We can only expand structure types. 1381 const RecordType *RT = Ty->getAs<RecordType>(); 1382 if (!RT) 1383 return false; 1384 const RecordDecl *RD = RT->getDecl(); 1385 uint64_t Size = 0; 1386 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 1387 if (!IsWin32StructABI) { 1388 // On non-Windows, we have to conservatively match our old bitcode 1389 // prototypes in order to be ABI-compatible at the bitcode level. 1390 if (!CXXRD->isCLike()) 1391 return false; 1392 } else { 1393 // Don't do this for dynamic classes. 1394 if (CXXRD->isDynamicClass()) 1395 return false; 1396 } 1397 if (!addBaseAndFieldSizes(getContext(), CXXRD, Size)) 1398 return false; 1399 } else { 1400 if (!addFieldSizes(getContext(), RD, Size)) 1401 return false; 1402 } 1403 1404 // We can do this if there was no alignment padding. 1405 return Size == getContext().getTypeSize(Ty); 1406 } 1407 1408 ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(QualType RetTy, CCState &State) const { 1409 // If the return value is indirect, then the hidden argument is consuming one 1410 // integer register. 1411 if (State.FreeRegs) { 1412 --State.FreeRegs; 1413 if (!IsMCUABI) 1414 return getNaturalAlignIndirectInReg(RetTy); 1415 } 1416 return getNaturalAlignIndirect(RetTy, /*ByVal=*/false); 1417 } 1418 1419 ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy, 1420 CCState &State) const { 1421 if (RetTy->isVoidType()) 1422 return ABIArgInfo::getIgnore(); 1423 1424 const Type *Base = nullptr; 1425 uint64_t NumElts = 0; 1426 if ((State.CC == llvm::CallingConv::X86_VectorCall || 1427 State.CC == llvm::CallingConv::X86_RegCall) && 1428 isHomogeneousAggregate(RetTy, Base, NumElts)) { 1429 // The LLVM struct type for such an aggregate should lower properly. 1430 return ABIArgInfo::getDirect(); 1431 } 1432 1433 if (const VectorType *VT = RetTy->getAs<VectorType>()) { 1434 // On Darwin, some vectors are returned in registers. 1435 if (IsDarwinVectorABI) { 1436 uint64_t Size = getContext().getTypeSize(RetTy); 1437 1438 // 128-bit vectors are a special case; they are returned in 1439 // registers and we need to make sure to pick a type the LLVM 1440 // backend will like. 1441 if (Size == 128) 1442 return ABIArgInfo::getDirect(llvm::VectorType::get( 1443 llvm::Type::getInt64Ty(getVMContext()), 2)); 1444 1445 // Always return in register if it fits in a general purpose 1446 // register, or if it is 64 bits and has a single element. 1447 if ((Size == 8 || Size == 16 || Size == 32) || 1448 (Size == 64 && VT->getNumElements() == 1)) 1449 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 1450 Size)); 1451 1452 return getIndirectReturnResult(RetTy, State); 1453 } 1454 1455 return ABIArgInfo::getDirect(); 1456 } 1457 1458 if (isAggregateTypeForABI(RetTy)) { 1459 if (const RecordType *RT = RetTy->getAs<RecordType>()) { 1460 // Structures with flexible arrays are always indirect. 1461 if (RT->getDecl()->hasFlexibleArrayMember()) 1462 return getIndirectReturnResult(RetTy, State); 1463 } 1464 1465 // If specified, structs and unions are always indirect. 1466 if (!IsRetSmallStructInRegABI && !RetTy->isAnyComplexType()) 1467 return getIndirectReturnResult(RetTy, State); 1468 1469 // Ignore empty structs/unions. 1470 if (isEmptyRecord(getContext(), RetTy, true)) 1471 return ABIArgInfo::getIgnore(); 1472 1473 // Small structures which are register sized are generally returned 1474 // in a register. 1475 if (shouldReturnTypeInRegister(RetTy, getContext())) { 1476 uint64_t Size = getContext().getTypeSize(RetTy); 1477 1478 // As a special-case, if the struct is a "single-element" struct, and 1479 // the field is of type "float" or "double", return it in a 1480 // floating-point register. (MSVC does not apply this special case.) 1481 // We apply a similar transformation for pointer types to improve the 1482 // quality of the generated IR. 1483 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext())) 1484 if ((!IsWin32StructABI && SeltTy->isRealFloatingType()) 1485 || SeltTy->hasPointerRepresentation()) 1486 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0))); 1487 1488 // FIXME: We should be able to narrow this integer in cases with dead 1489 // padding. 1490 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size)); 1491 } 1492 1493 return getIndirectReturnResult(RetTy, State); 1494 } 1495 1496 // Treat an enum type as its underlying type. 1497 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 1498 RetTy = EnumTy->getDecl()->getIntegerType(); 1499 1500 return (RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy) 1501 : ABIArgInfo::getDirect()); 1502 } 1503 1504 static bool isSSEVectorType(ASTContext &Context, QualType Ty) { 1505 return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128; 1506 } 1507 1508 static bool isRecordWithSSEVectorType(ASTContext &Context, QualType Ty) { 1509 const RecordType *RT = Ty->getAs<RecordType>(); 1510 if (!RT) 1511 return 0; 1512 const RecordDecl *RD = RT->getDecl(); 1513 1514 // If this is a C++ record, check the bases first. 1515 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 1516 for (const auto &I : CXXRD->bases()) 1517 if (!isRecordWithSSEVectorType(Context, I.getType())) 1518 return false; 1519 1520 for (const auto *i : RD->fields()) { 1521 QualType FT = i->getType(); 1522 1523 if (isSSEVectorType(Context, FT)) 1524 return true; 1525 1526 if (isRecordWithSSEVectorType(Context, FT)) 1527 return true; 1528 } 1529 1530 return false; 1531 } 1532 1533 unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty, 1534 unsigned Align) const { 1535 // Otherwise, if the alignment is less than or equal to the minimum ABI 1536 // alignment, just use the default; the backend will handle this. 1537 if (Align <= MinABIStackAlignInBytes) 1538 return 0; // Use default alignment. 1539 1540 // On non-Darwin, the stack type alignment is always 4. 1541 if (!IsDarwinVectorABI) { 1542 // Set explicit alignment, since we may need to realign the top. 1543 return MinABIStackAlignInBytes; 1544 } 1545 1546 // Otherwise, if the type contains an SSE vector type, the alignment is 16. 1547 if (Align >= 16 && (isSSEVectorType(getContext(), Ty) || 1548 isRecordWithSSEVectorType(getContext(), Ty))) 1549 return 16; 1550 1551 return MinABIStackAlignInBytes; 1552 } 1553 1554 ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal, 1555 CCState &State) const { 1556 if (!ByVal) { 1557 if (State.FreeRegs) { 1558 --State.FreeRegs; // Non-byval indirects just use one pointer. 1559 if (!IsMCUABI) 1560 return getNaturalAlignIndirectInReg(Ty); 1561 } 1562 return getNaturalAlignIndirect(Ty, false); 1563 } 1564 1565 // Compute the byval alignment. 1566 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8; 1567 unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign); 1568 if (StackAlign == 0) 1569 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true); 1570 1571 // If the stack alignment is less than the type alignment, realign the 1572 // argument. 1573 bool Realign = TypeAlign > StackAlign; 1574 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(StackAlign), 1575 /*ByVal=*/true, Realign); 1576 } 1577 1578 X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const { 1579 const Type *T = isSingleElementStruct(Ty, getContext()); 1580 if (!T) 1581 T = Ty.getTypePtr(); 1582 1583 if (const BuiltinType *BT = T->getAs<BuiltinType>()) { 1584 BuiltinType::Kind K = BT->getKind(); 1585 if (K == BuiltinType::Float || K == BuiltinType::Double) 1586 return Float; 1587 } 1588 return Integer; 1589 } 1590 1591 bool X86_32ABIInfo::updateFreeRegs(QualType Ty, CCState &State) const { 1592 if (!IsSoftFloatABI) { 1593 Class C = classify(Ty); 1594 if (C == Float) 1595 return false; 1596 } 1597 1598 unsigned Size = getContext().getTypeSize(Ty); 1599 unsigned SizeInRegs = (Size + 31) / 32; 1600 1601 if (SizeInRegs == 0) 1602 return false; 1603 1604 if (!IsMCUABI) { 1605 if (SizeInRegs > State.FreeRegs) { 1606 State.FreeRegs = 0; 1607 return false; 1608 } 1609 } else { 1610 // The MCU psABI allows passing parameters in-reg even if there are 1611 // earlier parameters that are passed on the stack. Also, 1612 // it does not allow passing >8-byte structs in-register, 1613 // even if there are 3 free registers available. 1614 if (SizeInRegs > State.FreeRegs || SizeInRegs > 2) 1615 return false; 1616 } 1617 1618 State.FreeRegs -= SizeInRegs; 1619 return true; 1620 } 1621 1622 bool X86_32ABIInfo::shouldAggregateUseDirect(QualType Ty, CCState &State, 1623 bool &InReg, 1624 bool &NeedsPadding) const { 1625 // On Windows, aggregates other than HFAs are never passed in registers, and 1626 // they do not consume register slots. Homogenous floating-point aggregates 1627 // (HFAs) have already been dealt with at this point. 1628 if (IsWin32StructABI && isAggregateTypeForABI(Ty)) 1629 return false; 1630 1631 NeedsPadding = false; 1632 InReg = !IsMCUABI; 1633 1634 if (!updateFreeRegs(Ty, State)) 1635 return false; 1636 1637 if (IsMCUABI) 1638 return true; 1639 1640 if (State.CC == llvm::CallingConv::X86_FastCall || 1641 State.CC == llvm::CallingConv::X86_VectorCall || 1642 State.CC == llvm::CallingConv::X86_RegCall) { 1643 if (getContext().getTypeSize(Ty) <= 32 && State.FreeRegs) 1644 NeedsPadding = true; 1645 1646 return false; 1647 } 1648 1649 return true; 1650 } 1651 1652 bool X86_32ABIInfo::shouldPrimitiveUseInReg(QualType Ty, CCState &State) const { 1653 if (!updateFreeRegs(Ty, State)) 1654 return false; 1655 1656 if (IsMCUABI) 1657 return false; 1658 1659 if (State.CC == llvm::CallingConv::X86_FastCall || 1660 State.CC == llvm::CallingConv::X86_VectorCall || 1661 State.CC == llvm::CallingConv::X86_RegCall) { 1662 if (getContext().getTypeSize(Ty) > 32) 1663 return false; 1664 1665 return (Ty->isIntegralOrEnumerationType() || Ty->isPointerType() || 1666 Ty->isReferenceType()); 1667 } 1668 1669 return true; 1670 } 1671 1672 void X86_32ABIInfo::runVectorCallFirstPass(CGFunctionInfo &FI, CCState &State) const { 1673 // Vectorcall x86 works subtly different than in x64, so the format is 1674 // a bit different than the x64 version. First, all vector types (not HVAs) 1675 // are assigned, with the first 6 ending up in the [XYZ]MM0-5 registers. 1676 // This differs from the x64 implementation, where the first 6 by INDEX get 1677 // registers. 1678 // In the second pass over the arguments, HVAs are passed in the remaining 1679 // vector registers if possible, or indirectly by address. The address will be 1680 // passed in ECX/EDX if available. Any other arguments are passed according to 1681 // the usual fastcall rules. 1682 MutableArrayRef<CGFunctionInfoArgInfo> Args = FI.arguments(); 1683 for (int I = 0, E = Args.size(); I < E; ++I) { 1684 const Type *Base = nullptr; 1685 uint64_t NumElts = 0; 1686 const QualType &Ty = Args[I].type; 1687 if ((Ty->isVectorType() || Ty->isBuiltinType()) && 1688 isHomogeneousAggregate(Ty, Base, NumElts)) { 1689 if (State.FreeSSERegs >= NumElts) { 1690 State.FreeSSERegs -= NumElts; 1691 Args[I].info = ABIArgInfo::getDirectInReg(); 1692 State.IsPreassigned.set(I); 1693 } 1694 } 1695 } 1696 } 1697 1698 ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty, 1699 CCState &State) const { 1700 // FIXME: Set alignment on indirect arguments. 1701 bool IsFastCall = State.CC == llvm::CallingConv::X86_FastCall; 1702 bool IsRegCall = State.CC == llvm::CallingConv::X86_RegCall; 1703 bool IsVectorCall = State.CC == llvm::CallingConv::X86_VectorCall; 1704 1705 Ty = useFirstFieldIfTransparentUnion(Ty); 1706 TypeInfo TI = getContext().getTypeInfo(Ty); 1707 1708 // Check with the C++ ABI first. 1709 const RecordType *RT = Ty->getAs<RecordType>(); 1710 if (RT) { 1711 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()); 1712 if (RAA == CGCXXABI::RAA_Indirect) { 1713 return getIndirectResult(Ty, false, State); 1714 } else if (RAA == CGCXXABI::RAA_DirectInMemory) { 1715 // The field index doesn't matter, we'll fix it up later. 1716 return ABIArgInfo::getInAlloca(/*FieldIndex=*/0); 1717 } 1718 } 1719 1720 // Regcall uses the concept of a homogenous vector aggregate, similar 1721 // to other targets. 1722 const Type *Base = nullptr; 1723 uint64_t NumElts = 0; 1724 if ((IsRegCall || IsVectorCall) && 1725 isHomogeneousAggregate(Ty, Base, NumElts)) { 1726 if (State.FreeSSERegs >= NumElts) { 1727 State.FreeSSERegs -= NumElts; 1728 1729 // Vectorcall passes HVAs directly and does not flatten them, but regcall 1730 // does. 1731 if (IsVectorCall) 1732 return getDirectX86Hva(); 1733 1734 if (Ty->isBuiltinType() || Ty->isVectorType()) 1735 return ABIArgInfo::getDirect(); 1736 return ABIArgInfo::getExpand(); 1737 } 1738 return getIndirectResult(Ty, /*ByVal=*/false, State); 1739 } 1740 1741 if (isAggregateTypeForABI(Ty)) { 1742 // Structures with flexible arrays are always indirect. 1743 // FIXME: This should not be byval! 1744 if (RT && RT->getDecl()->hasFlexibleArrayMember()) 1745 return getIndirectResult(Ty, true, State); 1746 1747 // Ignore empty structs/unions on non-Windows. 1748 if (!IsWin32StructABI && isEmptyRecord(getContext(), Ty, true)) 1749 return ABIArgInfo::getIgnore(); 1750 1751 llvm::LLVMContext &LLVMContext = getVMContext(); 1752 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext); 1753 bool NeedsPadding = false; 1754 bool InReg; 1755 if (shouldAggregateUseDirect(Ty, State, InReg, NeedsPadding)) { 1756 unsigned SizeInRegs = (TI.Width + 31) / 32; 1757 SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32); 1758 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements); 1759 if (InReg) 1760 return ABIArgInfo::getDirectInReg(Result); 1761 else 1762 return ABIArgInfo::getDirect(Result); 1763 } 1764 llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : nullptr; 1765 1766 // Pass over-aligned aggregates on Windows indirectly. This behavior was 1767 // added in MSVC 2015. 1768 if (IsWin32StructABI && TI.AlignIsRequired && TI.Align > 32) 1769 return getIndirectResult(Ty, /*ByVal=*/false, State); 1770 1771 // Expand small (<= 128-bit) record types when we know that the stack layout 1772 // of those arguments will match the struct. This is important because the 1773 // LLVM backend isn't smart enough to remove byval, which inhibits many 1774 // optimizations. 1775 // Don't do this for the MCU if there are still free integer registers 1776 // (see X86_64 ABI for full explanation). 1777 if (TI.Width <= 4 * 32 && (!IsMCUABI || State.FreeRegs == 0) && 1778 canExpandIndirectArgument(Ty)) 1779 return ABIArgInfo::getExpandWithPadding( 1780 IsFastCall || IsVectorCall || IsRegCall, PaddingType); 1781 1782 return getIndirectResult(Ty, true, State); 1783 } 1784 1785 if (const VectorType *VT = Ty->getAs<VectorType>()) { 1786 // On Windows, vectors are passed directly if registers are available, or 1787 // indirectly if not. This avoids the need to align argument memory. Pass 1788 // user-defined vector types larger than 512 bits indirectly for simplicity. 1789 if (IsWin32StructABI) { 1790 if (TI.Width <= 512 && State.FreeSSERegs > 0) { 1791 --State.FreeSSERegs; 1792 return ABIArgInfo::getDirectInReg(); 1793 } 1794 return getIndirectResult(Ty, /*ByVal=*/false, State); 1795 } 1796 1797 // On Darwin, some vectors are passed in memory, we handle this by passing 1798 // it as an i8/i16/i32/i64. 1799 if (IsDarwinVectorABI) { 1800 if ((TI.Width == 8 || TI.Width == 16 || TI.Width == 32) || 1801 (TI.Width == 64 && VT->getNumElements() == 1)) 1802 return ABIArgInfo::getDirect( 1803 llvm::IntegerType::get(getVMContext(), TI.Width)); 1804 } 1805 1806 if (IsX86_MMXType(CGT.ConvertType(Ty))) 1807 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64)); 1808 1809 return ABIArgInfo::getDirect(); 1810 } 1811 1812 1813 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 1814 Ty = EnumTy->getDecl()->getIntegerType(); 1815 1816 bool InReg = shouldPrimitiveUseInReg(Ty, State); 1817 1818 if (Ty->isPromotableIntegerType()) { 1819 if (InReg) 1820 return ABIArgInfo::getExtendInReg(Ty); 1821 return ABIArgInfo::getExtend(Ty); 1822 } 1823 1824 if (InReg) 1825 return ABIArgInfo::getDirectInReg(); 1826 return ABIArgInfo::getDirect(); 1827 } 1828 1829 void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const { 1830 CCState State(FI); 1831 if (IsMCUABI) 1832 State.FreeRegs = 3; 1833 else if (State.CC == llvm::CallingConv::X86_FastCall) { 1834 State.FreeRegs = 2; 1835 State.FreeSSERegs = 3; 1836 } else if (State.CC == llvm::CallingConv::X86_VectorCall) { 1837 State.FreeRegs = 2; 1838 State.FreeSSERegs = 6; 1839 } else if (FI.getHasRegParm()) 1840 State.FreeRegs = FI.getRegParm(); 1841 else if (State.CC == llvm::CallingConv::X86_RegCall) { 1842 State.FreeRegs = 5; 1843 State.FreeSSERegs = 8; 1844 } else if (IsWin32StructABI) { 1845 // Since MSVC 2015, the first three SSE vectors have been passed in 1846 // registers. The rest are passed indirectly. 1847 State.FreeRegs = DefaultNumRegisterParameters; 1848 State.FreeSSERegs = 3; 1849 } else 1850 State.FreeRegs = DefaultNumRegisterParameters; 1851 1852 if (!::classifyReturnType(getCXXABI(), FI, *this)) { 1853 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), State); 1854 } else if (FI.getReturnInfo().isIndirect()) { 1855 // The C++ ABI is not aware of register usage, so we have to check if the 1856 // return value was sret and put it in a register ourselves if appropriate. 1857 if (State.FreeRegs) { 1858 --State.FreeRegs; // The sret parameter consumes a register. 1859 if (!IsMCUABI) 1860 FI.getReturnInfo().setInReg(true); 1861 } 1862 } 1863 1864 // The chain argument effectively gives us another free register. 1865 if (FI.isChainCall()) 1866 ++State.FreeRegs; 1867 1868 // For vectorcall, do a first pass over the arguments, assigning FP and vector 1869 // arguments to XMM registers as available. 1870 if (State.CC == llvm::CallingConv::X86_VectorCall) 1871 runVectorCallFirstPass(FI, State); 1872 1873 bool UsedInAlloca = false; 1874 MutableArrayRef<CGFunctionInfoArgInfo> Args = FI.arguments(); 1875 for (int I = 0, E = Args.size(); I < E; ++I) { 1876 // Skip arguments that have already been assigned. 1877 if (State.IsPreassigned.test(I)) 1878 continue; 1879 1880 Args[I].info = classifyArgumentType(Args[I].type, State); 1881 UsedInAlloca |= (Args[I].info.getKind() == ABIArgInfo::InAlloca); 1882 } 1883 1884 // If we needed to use inalloca for any argument, do a second pass and rewrite 1885 // all the memory arguments to use inalloca. 1886 if (UsedInAlloca) 1887 rewriteWithInAlloca(FI); 1888 } 1889 1890 void 1891 X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields, 1892 CharUnits &StackOffset, ABIArgInfo &Info, 1893 QualType Type) const { 1894 // Arguments are always 4-byte-aligned. 1895 CharUnits WordSize = CharUnits::fromQuantity(4); 1896 assert(StackOffset.isMultipleOf(WordSize) && "unaligned inalloca struct"); 1897 1898 // sret pointers and indirect things will require an extra pointer 1899 // indirection, unless they are byval. Most things are byval, and will not 1900 // require this indirection. 1901 bool IsIndirect = false; 1902 if (Info.isIndirect() && !Info.getIndirectByVal()) 1903 IsIndirect = true; 1904 Info = ABIArgInfo::getInAlloca(FrameFields.size(), IsIndirect); 1905 llvm::Type *LLTy = CGT.ConvertTypeForMem(Type); 1906 if (IsIndirect) 1907 LLTy = LLTy->getPointerTo(0); 1908 FrameFields.push_back(LLTy); 1909 StackOffset += IsIndirect ? WordSize : getContext().getTypeSizeInChars(Type); 1910 1911 // Insert padding bytes to respect alignment. 1912 CharUnits FieldEnd = StackOffset; 1913 StackOffset = FieldEnd.alignTo(WordSize); 1914 if (StackOffset != FieldEnd) { 1915 CharUnits NumBytes = StackOffset - FieldEnd; 1916 llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext()); 1917 Ty = llvm::ArrayType::get(Ty, NumBytes.getQuantity()); 1918 FrameFields.push_back(Ty); 1919 } 1920 } 1921 1922 static bool isArgInAlloca(const ABIArgInfo &Info) { 1923 // Leave ignored and inreg arguments alone. 1924 switch (Info.getKind()) { 1925 case ABIArgInfo::InAlloca: 1926 return true; 1927 case ABIArgInfo::Ignore: 1928 return false; 1929 case ABIArgInfo::Indirect: 1930 case ABIArgInfo::Direct: 1931 case ABIArgInfo::Extend: 1932 return !Info.getInReg(); 1933 case ABIArgInfo::Expand: 1934 case ABIArgInfo::CoerceAndExpand: 1935 // These are aggregate types which are never passed in registers when 1936 // inalloca is involved. 1937 return true; 1938 } 1939 llvm_unreachable("invalid enum"); 1940 } 1941 1942 void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const { 1943 assert(IsWin32StructABI && "inalloca only supported on win32"); 1944 1945 // Build a packed struct type for all of the arguments in memory. 1946 SmallVector<llvm::Type *, 6> FrameFields; 1947 1948 // The stack alignment is always 4. 1949 CharUnits StackAlign = CharUnits::fromQuantity(4); 1950 1951 CharUnits StackOffset; 1952 CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end(); 1953 1954 // Put 'this' into the struct before 'sret', if necessary. 1955 bool IsThisCall = 1956 FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall; 1957 ABIArgInfo &Ret = FI.getReturnInfo(); 1958 if (Ret.isIndirect() && Ret.isSRetAfterThis() && !IsThisCall && 1959 isArgInAlloca(I->info)) { 1960 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type); 1961 ++I; 1962 } 1963 1964 // Put the sret parameter into the inalloca struct if it's in memory. 1965 if (Ret.isIndirect() && !Ret.getInReg()) { 1966 addFieldToArgStruct(FrameFields, StackOffset, Ret, FI.getReturnType()); 1967 // On Windows, the hidden sret parameter is always returned in eax. 1968 Ret.setInAllocaSRet(IsWin32StructABI); 1969 } 1970 1971 // Skip the 'this' parameter in ecx. 1972 if (IsThisCall) 1973 ++I; 1974 1975 // Put arguments passed in memory into the struct. 1976 for (; I != E; ++I) { 1977 if (isArgInAlloca(I->info)) 1978 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type); 1979 } 1980 1981 FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields, 1982 /*isPacked=*/true), 1983 StackAlign); 1984 } 1985 1986 Address X86_32ABIInfo::EmitVAArg(CodeGenFunction &CGF, 1987 Address VAListAddr, QualType Ty) const { 1988 1989 auto TypeInfo = getContext().getTypeInfoInChars(Ty); 1990 1991 // x86-32 changes the alignment of certain arguments on the stack. 1992 // 1993 // Just messing with TypeInfo like this works because we never pass 1994 // anything indirectly. 1995 TypeInfo.second = CharUnits::fromQuantity( 1996 getTypeStackAlignInBytes(Ty, TypeInfo.second.getQuantity())); 1997 1998 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false, 1999 TypeInfo, CharUnits::fromQuantity(4), 2000 /*AllowHigherAlign*/ true); 2001 } 2002 2003 bool X86_32TargetCodeGenInfo::isStructReturnInRegABI( 2004 const llvm::Triple &Triple, const CodeGenOptions &Opts) { 2005 assert(Triple.getArch() == llvm::Triple::x86); 2006 2007 switch (Opts.getStructReturnConvention()) { 2008 case CodeGenOptions::SRCK_Default: 2009 break; 2010 case CodeGenOptions::SRCK_OnStack: // -fpcc-struct-return 2011 return false; 2012 case CodeGenOptions::SRCK_InRegs: // -freg-struct-return 2013 return true; 2014 } 2015 2016 if (Triple.isOSDarwin() || Triple.isOSIAMCU()) 2017 return true; 2018 2019 switch (Triple.getOS()) { 2020 case llvm::Triple::DragonFly: 2021 case llvm::Triple::FreeBSD: 2022 case llvm::Triple::OpenBSD: 2023 case llvm::Triple::Win32: 2024 return true; 2025 default: 2026 return false; 2027 } 2028 } 2029 2030 void X86_32TargetCodeGenInfo::setTargetAttributes( 2031 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const { 2032 if (GV->isDeclaration()) 2033 return; 2034 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) { 2035 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) { 2036 llvm::Function *Fn = cast<llvm::Function>(GV); 2037 Fn->addFnAttr("stackrealign"); 2038 } 2039 if (FD->hasAttr<AnyX86InterruptAttr>()) { 2040 llvm::Function *Fn = cast<llvm::Function>(GV); 2041 Fn->setCallingConv(llvm::CallingConv::X86_INTR); 2042 } 2043 } 2044 } 2045 2046 bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable( 2047 CodeGen::CodeGenFunction &CGF, 2048 llvm::Value *Address) const { 2049 CodeGen::CGBuilderTy &Builder = CGF.Builder; 2050 2051 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4); 2052 2053 // 0-7 are the eight integer registers; the order is different 2054 // on Darwin (for EH), but the range is the same. 2055 // 8 is %eip. 2056 AssignToArrayRange(Builder, Address, Four8, 0, 8); 2057 2058 if (CGF.CGM.getTarget().getTriple().isOSDarwin()) { 2059 // 12-16 are st(0..4). Not sure why we stop at 4. 2060 // These have size 16, which is sizeof(long double) on 2061 // platforms with 8-byte alignment for that type. 2062 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16); 2063 AssignToArrayRange(Builder, Address, Sixteen8, 12, 16); 2064 2065 } else { 2066 // 9 is %eflags, which doesn't get a size on Darwin for some 2067 // reason. 2068 Builder.CreateAlignedStore( 2069 Four8, Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, Address, 9), 2070 CharUnits::One()); 2071 2072 // 11-16 are st(0..5). Not sure why we stop at 5. 2073 // These have size 12, which is sizeof(long double) on 2074 // platforms with 4-byte alignment for that type. 2075 llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12); 2076 AssignToArrayRange(Builder, Address, Twelve8, 11, 16); 2077 } 2078 2079 return false; 2080 } 2081 2082 //===----------------------------------------------------------------------===// 2083 // X86-64 ABI Implementation 2084 //===----------------------------------------------------------------------===// 2085 2086 2087 namespace { 2088 /// The AVX ABI level for X86 targets. 2089 enum class X86AVXABILevel { 2090 None, 2091 AVX, 2092 AVX512 2093 }; 2094 2095 /// \p returns the size in bits of the largest (native) vector for \p AVXLevel. 2096 static unsigned getNativeVectorSizeForAVXABI(X86AVXABILevel AVXLevel) { 2097 switch (AVXLevel) { 2098 case X86AVXABILevel::AVX512: 2099 return 512; 2100 case X86AVXABILevel::AVX: 2101 return 256; 2102 case X86AVXABILevel::None: 2103 return 128; 2104 } 2105 llvm_unreachable("Unknown AVXLevel"); 2106 } 2107 2108 /// X86_64ABIInfo - The X86_64 ABI information. 2109 class X86_64ABIInfo : public SwiftABIInfo { 2110 enum Class { 2111 Integer = 0, 2112 SSE, 2113 SSEUp, 2114 X87, 2115 X87Up, 2116 ComplexX87, 2117 NoClass, 2118 Memory 2119 }; 2120 2121 /// merge - Implement the X86_64 ABI merging algorithm. 2122 /// 2123 /// Merge an accumulating classification \arg Accum with a field 2124 /// classification \arg Field. 2125 /// 2126 /// \param Accum - The accumulating classification. This should 2127 /// always be either NoClass or the result of a previous merge 2128 /// call. In addition, this should never be Memory (the caller 2129 /// should just return Memory for the aggregate). 2130 static Class merge(Class Accum, Class Field); 2131 2132 /// postMerge - Implement the X86_64 ABI post merging algorithm. 2133 /// 2134 /// Post merger cleanup, reduces a malformed Hi and Lo pair to 2135 /// final MEMORY or SSE classes when necessary. 2136 /// 2137 /// \param AggregateSize - The size of the current aggregate in 2138 /// the classification process. 2139 /// 2140 /// \param Lo - The classification for the parts of the type 2141 /// residing in the low word of the containing object. 2142 /// 2143 /// \param Hi - The classification for the parts of the type 2144 /// residing in the higher words of the containing object. 2145 /// 2146 void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const; 2147 2148 /// classify - Determine the x86_64 register classes in which the 2149 /// given type T should be passed. 2150 /// 2151 /// \param Lo - The classification for the parts of the type 2152 /// residing in the low word of the containing object. 2153 /// 2154 /// \param Hi - The classification for the parts of the type 2155 /// residing in the high word of the containing object. 2156 /// 2157 /// \param OffsetBase - The bit offset of this type in the 2158 /// containing object. Some parameters are classified different 2159 /// depending on whether they straddle an eightbyte boundary. 2160 /// 2161 /// \param isNamedArg - Whether the argument in question is a "named" 2162 /// argument, as used in AMD64-ABI 3.5.7. 2163 /// 2164 /// If a word is unused its result will be NoClass; if a type should 2165 /// be passed in Memory then at least the classification of \arg Lo 2166 /// will be Memory. 2167 /// 2168 /// The \arg Lo class will be NoClass iff the argument is ignored. 2169 /// 2170 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will 2171 /// also be ComplexX87. 2172 void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi, 2173 bool isNamedArg) const; 2174 2175 llvm::Type *GetByteVectorType(QualType Ty) const; 2176 llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType, 2177 unsigned IROffset, QualType SourceTy, 2178 unsigned SourceOffset) const; 2179 llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType, 2180 unsigned IROffset, QualType SourceTy, 2181 unsigned SourceOffset) const; 2182 2183 /// getIndirectResult - Give a source type \arg Ty, return a suitable result 2184 /// such that the argument will be returned in memory. 2185 ABIArgInfo getIndirectReturnResult(QualType Ty) const; 2186 2187 /// getIndirectResult - Give a source type \arg Ty, return a suitable result 2188 /// such that the argument will be passed in memory. 2189 /// 2190 /// \param freeIntRegs - The number of free integer registers remaining 2191 /// available. 2192 ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const; 2193 2194 ABIArgInfo classifyReturnType(QualType RetTy) const; 2195 2196 ABIArgInfo classifyArgumentType(QualType Ty, unsigned freeIntRegs, 2197 unsigned &neededInt, unsigned &neededSSE, 2198 bool isNamedArg) const; 2199 2200 ABIArgInfo classifyRegCallStructType(QualType Ty, unsigned &NeededInt, 2201 unsigned &NeededSSE) const; 2202 2203 ABIArgInfo classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt, 2204 unsigned &NeededSSE) const; 2205 2206 bool IsIllegalVectorType(QualType Ty) const; 2207 2208 /// The 0.98 ABI revision clarified a lot of ambiguities, 2209 /// unfortunately in ways that were not always consistent with 2210 /// certain previous compilers. In particular, platforms which 2211 /// required strict binary compatibility with older versions of GCC 2212 /// may need to exempt themselves. 2213 bool honorsRevision0_98() const { 2214 return !getTarget().getTriple().isOSDarwin(); 2215 } 2216 2217 /// GCC classifies <1 x long long> as SSE but some platform ABIs choose to 2218 /// classify it as INTEGER (for compatibility with older clang compilers). 2219 bool classifyIntegerMMXAsSSE() const { 2220 // Clang <= 3.8 did not do this. 2221 if (getContext().getLangOpts().getClangABICompat() <= 2222 LangOptions::ClangABI::Ver3_8) 2223 return false; 2224 2225 const llvm::Triple &Triple = getTarget().getTriple(); 2226 if (Triple.isOSDarwin() || Triple.getOS() == llvm::Triple::PS4) 2227 return false; 2228 if (Triple.isOSFreeBSD() && Triple.getOSMajorVersion() >= 10) 2229 return false; 2230 return true; 2231 } 2232 2233 // GCC classifies vectors of __int128 as memory. 2234 bool passInt128VectorsInMem() const { 2235 // Clang <= 9.0 did not do this. 2236 if (getContext().getLangOpts().getClangABICompat() <= 2237 LangOptions::ClangABI::Ver9) 2238 return false; 2239 2240 const llvm::Triple &T = getTarget().getTriple(); 2241 return T.isOSLinux() || T.isOSNetBSD(); 2242 } 2243 2244 X86AVXABILevel AVXLevel; 2245 // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on 2246 // 64-bit hardware. 2247 bool Has64BitPointers; 2248 2249 public: 2250 X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) : 2251 SwiftABIInfo(CGT), AVXLevel(AVXLevel), 2252 Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) { 2253 } 2254 2255 bool isPassedUsingAVXType(QualType type) const { 2256 unsigned neededInt, neededSSE; 2257 // The freeIntRegs argument doesn't matter here. 2258 ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE, 2259 /*isNamedArg*/true); 2260 if (info.isDirect()) { 2261 llvm::Type *ty = info.getCoerceToType(); 2262 if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty)) 2263 return (vectorTy->getBitWidth() > 128); 2264 } 2265 return false; 2266 } 2267 2268 void computeInfo(CGFunctionInfo &FI) const override; 2269 2270 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 2271 QualType Ty) const override; 2272 Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr, 2273 QualType Ty) const override; 2274 2275 bool has64BitPointers() const { 2276 return Has64BitPointers; 2277 } 2278 2279 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars, 2280 bool asReturnValue) const override { 2281 return occupiesMoreThan(CGT, scalars, /*total*/ 4); 2282 } 2283 bool isSwiftErrorInRegister() const override { 2284 return true; 2285 } 2286 }; 2287 2288 /// WinX86_64ABIInfo - The Windows X86_64 ABI information. 2289 class WinX86_64ABIInfo : public SwiftABIInfo { 2290 public: 2291 WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) 2292 : SwiftABIInfo(CGT), AVXLevel(AVXLevel), 2293 IsMingw64(getTarget().getTriple().isWindowsGNUEnvironment()) {} 2294 2295 void computeInfo(CGFunctionInfo &FI) const override; 2296 2297 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 2298 QualType Ty) const override; 2299 2300 bool isHomogeneousAggregateBaseType(QualType Ty) const override { 2301 // FIXME: Assumes vectorcall is in use. 2302 return isX86VectorTypeForVectorCall(getContext(), Ty); 2303 } 2304 2305 bool isHomogeneousAggregateSmallEnough(const Type *Ty, 2306 uint64_t NumMembers) const override { 2307 // FIXME: Assumes vectorcall is in use. 2308 return isX86VectorCallAggregateSmallEnough(NumMembers); 2309 } 2310 2311 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type *> scalars, 2312 bool asReturnValue) const override { 2313 return occupiesMoreThan(CGT, scalars, /*total*/ 4); 2314 } 2315 2316 bool isSwiftErrorInRegister() const override { 2317 return true; 2318 } 2319 2320 private: 2321 ABIArgInfo classify(QualType Ty, unsigned &FreeSSERegs, bool IsReturnType, 2322 bool IsVectorCall, bool IsRegCall) const; 2323 ABIArgInfo reclassifyHvaArgType(QualType Ty, unsigned &FreeSSERegs, 2324 const ABIArgInfo ¤t) const; 2325 void computeVectorCallArgs(CGFunctionInfo &FI, unsigned FreeSSERegs, 2326 bool IsVectorCall, bool IsRegCall) const; 2327 2328 X86AVXABILevel AVXLevel; 2329 2330 bool IsMingw64; 2331 }; 2332 2333 class X86_64TargetCodeGenInfo : public TargetCodeGenInfo { 2334 public: 2335 X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) 2336 : TargetCodeGenInfo(new X86_64ABIInfo(CGT, AVXLevel)) {} 2337 2338 const X86_64ABIInfo &getABIInfo() const { 2339 return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo()); 2340 } 2341 2342 /// Disable tail call on x86-64. The epilogue code before the tail jump blocks 2343 /// the autoreleaseRV/retainRV optimization. 2344 bool shouldSuppressTailCallsOfRetainAutoreleasedReturnValue() const override { 2345 return true; 2346 } 2347 2348 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override { 2349 return 7; 2350 } 2351 2352 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 2353 llvm::Value *Address) const override { 2354 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8); 2355 2356 // 0-15 are the 16 integer registers. 2357 // 16 is %rip. 2358 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16); 2359 return false; 2360 } 2361 2362 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF, 2363 StringRef Constraint, 2364 llvm::Type* Ty) const override { 2365 return X86AdjustInlineAsmType(CGF, Constraint, Ty); 2366 } 2367 2368 bool isNoProtoCallVariadic(const CallArgList &args, 2369 const FunctionNoProtoType *fnType) const override { 2370 // The default CC on x86-64 sets %al to the number of SSA 2371 // registers used, and GCC sets this when calling an unprototyped 2372 // function, so we override the default behavior. However, don't do 2373 // that when AVX types are involved: the ABI explicitly states it is 2374 // undefined, and it doesn't work in practice because of how the ABI 2375 // defines varargs anyway. 2376 if (fnType->getCallConv() == CC_C) { 2377 bool HasAVXType = false; 2378 for (CallArgList::const_iterator 2379 it = args.begin(), ie = args.end(); it != ie; ++it) { 2380 if (getABIInfo().isPassedUsingAVXType(it->Ty)) { 2381 HasAVXType = true; 2382 break; 2383 } 2384 } 2385 2386 if (!HasAVXType) 2387 return true; 2388 } 2389 2390 return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType); 2391 } 2392 2393 llvm::Constant * 2394 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override { 2395 unsigned Sig = (0xeb << 0) | // jmp rel8 2396 (0x06 << 8) | // .+0x08 2397 ('v' << 16) | 2398 ('2' << 24); 2399 return llvm::ConstantInt::get(CGM.Int32Ty, Sig); 2400 } 2401 2402 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 2403 CodeGen::CodeGenModule &CGM) const override { 2404 if (GV->isDeclaration()) 2405 return; 2406 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) { 2407 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) { 2408 llvm::Function *Fn = cast<llvm::Function>(GV); 2409 Fn->addFnAttr("stackrealign"); 2410 } 2411 if (FD->hasAttr<AnyX86InterruptAttr>()) { 2412 llvm::Function *Fn = cast<llvm::Function>(GV); 2413 Fn->setCallingConv(llvm::CallingConv::X86_INTR); 2414 } 2415 } 2416 } 2417 }; 2418 2419 static std::string qualifyWindowsLibrary(llvm::StringRef Lib) { 2420 // If the argument does not end in .lib, automatically add the suffix. 2421 // If the argument contains a space, enclose it in quotes. 2422 // This matches the behavior of MSVC. 2423 bool Quote = (Lib.find(" ") != StringRef::npos); 2424 std::string ArgStr = Quote ? "\"" : ""; 2425 ArgStr += Lib; 2426 if (!Lib.endswith_lower(".lib") && !Lib.endswith_lower(".a")) 2427 ArgStr += ".lib"; 2428 ArgStr += Quote ? "\"" : ""; 2429 return ArgStr; 2430 } 2431 2432 class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo { 2433 public: 2434 WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, 2435 bool DarwinVectorABI, bool RetSmallStructInRegABI, bool Win32StructABI, 2436 unsigned NumRegisterParameters) 2437 : X86_32TargetCodeGenInfo(CGT, DarwinVectorABI, RetSmallStructInRegABI, 2438 Win32StructABI, NumRegisterParameters, false) {} 2439 2440 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 2441 CodeGen::CodeGenModule &CGM) const override; 2442 2443 void getDependentLibraryOption(llvm::StringRef Lib, 2444 llvm::SmallString<24> &Opt) const override { 2445 Opt = "/DEFAULTLIB:"; 2446 Opt += qualifyWindowsLibrary(Lib); 2447 } 2448 2449 void getDetectMismatchOption(llvm::StringRef Name, 2450 llvm::StringRef Value, 2451 llvm::SmallString<32> &Opt) const override { 2452 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\""; 2453 } 2454 }; 2455 2456 static void addStackProbeTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 2457 CodeGen::CodeGenModule &CGM) { 2458 if (llvm::Function *Fn = dyn_cast_or_null<llvm::Function>(GV)) { 2459 2460 if (CGM.getCodeGenOpts().StackProbeSize != 4096) 2461 Fn->addFnAttr("stack-probe-size", 2462 llvm::utostr(CGM.getCodeGenOpts().StackProbeSize)); 2463 if (CGM.getCodeGenOpts().NoStackArgProbe) 2464 Fn->addFnAttr("no-stack-arg-probe"); 2465 } 2466 } 2467 2468 void WinX86_32TargetCodeGenInfo::setTargetAttributes( 2469 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const { 2470 X86_32TargetCodeGenInfo::setTargetAttributes(D, GV, CGM); 2471 if (GV->isDeclaration()) 2472 return; 2473 addStackProbeTargetAttributes(D, GV, CGM); 2474 } 2475 2476 class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo { 2477 public: 2478 WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, 2479 X86AVXABILevel AVXLevel) 2480 : TargetCodeGenInfo(new WinX86_64ABIInfo(CGT, AVXLevel)) {} 2481 2482 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 2483 CodeGen::CodeGenModule &CGM) const override; 2484 2485 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override { 2486 return 7; 2487 } 2488 2489 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 2490 llvm::Value *Address) const override { 2491 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8); 2492 2493 // 0-15 are the 16 integer registers. 2494 // 16 is %rip. 2495 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16); 2496 return false; 2497 } 2498 2499 void getDependentLibraryOption(llvm::StringRef Lib, 2500 llvm::SmallString<24> &Opt) const override { 2501 Opt = "/DEFAULTLIB:"; 2502 Opt += qualifyWindowsLibrary(Lib); 2503 } 2504 2505 void getDetectMismatchOption(llvm::StringRef Name, 2506 llvm::StringRef Value, 2507 llvm::SmallString<32> &Opt) const override { 2508 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\""; 2509 } 2510 }; 2511 2512 void WinX86_64TargetCodeGenInfo::setTargetAttributes( 2513 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const { 2514 TargetCodeGenInfo::setTargetAttributes(D, GV, CGM); 2515 if (GV->isDeclaration()) 2516 return; 2517 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) { 2518 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) { 2519 llvm::Function *Fn = cast<llvm::Function>(GV); 2520 Fn->addFnAttr("stackrealign"); 2521 } 2522 if (FD->hasAttr<AnyX86InterruptAttr>()) { 2523 llvm::Function *Fn = cast<llvm::Function>(GV); 2524 Fn->setCallingConv(llvm::CallingConv::X86_INTR); 2525 } 2526 } 2527 2528 addStackProbeTargetAttributes(D, GV, CGM); 2529 } 2530 } 2531 2532 void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo, 2533 Class &Hi) const { 2534 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done: 2535 // 2536 // (a) If one of the classes is Memory, the whole argument is passed in 2537 // memory. 2538 // 2539 // (b) If X87UP is not preceded by X87, the whole argument is passed in 2540 // memory. 2541 // 2542 // (c) If the size of the aggregate exceeds two eightbytes and the first 2543 // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole 2544 // argument is passed in memory. NOTE: This is necessary to keep the 2545 // ABI working for processors that don't support the __m256 type. 2546 // 2547 // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE. 2548 // 2549 // Some of these are enforced by the merging logic. Others can arise 2550 // only with unions; for example: 2551 // union { _Complex double; unsigned; } 2552 // 2553 // Note that clauses (b) and (c) were added in 0.98. 2554 // 2555 if (Hi == Memory) 2556 Lo = Memory; 2557 if (Hi == X87Up && Lo != X87 && honorsRevision0_98()) 2558 Lo = Memory; 2559 if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp)) 2560 Lo = Memory; 2561 if (Hi == SSEUp && Lo != SSE) 2562 Hi = SSE; 2563 } 2564 2565 X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) { 2566 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is 2567 // classified recursively so that always two fields are 2568 // considered. The resulting class is calculated according to 2569 // the classes of the fields in the eightbyte: 2570 // 2571 // (a) If both classes are equal, this is the resulting class. 2572 // 2573 // (b) If one of the classes is NO_CLASS, the resulting class is 2574 // the other class. 2575 // 2576 // (c) If one of the classes is MEMORY, the result is the MEMORY 2577 // class. 2578 // 2579 // (d) If one of the classes is INTEGER, the result is the 2580 // INTEGER. 2581 // 2582 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class, 2583 // MEMORY is used as class. 2584 // 2585 // (f) Otherwise class SSE is used. 2586 2587 // Accum should never be memory (we should have returned) or 2588 // ComplexX87 (because this cannot be passed in a structure). 2589 assert((Accum != Memory && Accum != ComplexX87) && 2590 "Invalid accumulated classification during merge."); 2591 if (Accum == Field || Field == NoClass) 2592 return Accum; 2593 if (Field == Memory) 2594 return Memory; 2595 if (Accum == NoClass) 2596 return Field; 2597 if (Accum == Integer || Field == Integer) 2598 return Integer; 2599 if (Field == X87 || Field == X87Up || Field == ComplexX87 || 2600 Accum == X87 || Accum == X87Up) 2601 return Memory; 2602 return SSE; 2603 } 2604 2605 void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase, 2606 Class &Lo, Class &Hi, bool isNamedArg) const { 2607 // FIXME: This code can be simplified by introducing a simple value class for 2608 // Class pairs with appropriate constructor methods for the various 2609 // situations. 2610 2611 // FIXME: Some of the split computations are wrong; unaligned vectors 2612 // shouldn't be passed in registers for example, so there is no chance they 2613 // can straddle an eightbyte. Verify & simplify. 2614 2615 Lo = Hi = NoClass; 2616 2617 Class &Current = OffsetBase < 64 ? Lo : Hi; 2618 Current = Memory; 2619 2620 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) { 2621 BuiltinType::Kind k = BT->getKind(); 2622 2623 if (k == BuiltinType::Void) { 2624 Current = NoClass; 2625 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) { 2626 Lo = Integer; 2627 Hi = Integer; 2628 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) { 2629 Current = Integer; 2630 } else if (k == BuiltinType::Float || k == BuiltinType::Double) { 2631 Current = SSE; 2632 } else if (k == BuiltinType::LongDouble) { 2633 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat(); 2634 if (LDF == &llvm::APFloat::IEEEquad()) { 2635 Lo = SSE; 2636 Hi = SSEUp; 2637 } else if (LDF == &llvm::APFloat::x87DoubleExtended()) { 2638 Lo = X87; 2639 Hi = X87Up; 2640 } else if (LDF == &llvm::APFloat::IEEEdouble()) { 2641 Current = SSE; 2642 } else 2643 llvm_unreachable("unexpected long double representation!"); 2644 } 2645 // FIXME: _Decimal32 and _Decimal64 are SSE. 2646 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp). 2647 return; 2648 } 2649 2650 if (const EnumType *ET = Ty->getAs<EnumType>()) { 2651 // Classify the underlying integer type. 2652 classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg); 2653 return; 2654 } 2655 2656 if (Ty->hasPointerRepresentation()) { 2657 Current = Integer; 2658 return; 2659 } 2660 2661 if (Ty->isMemberPointerType()) { 2662 if (Ty->isMemberFunctionPointerType()) { 2663 if (Has64BitPointers) { 2664 // If Has64BitPointers, this is an {i64, i64}, so classify both 2665 // Lo and Hi now. 2666 Lo = Hi = Integer; 2667 } else { 2668 // Otherwise, with 32-bit pointers, this is an {i32, i32}. If that 2669 // straddles an eightbyte boundary, Hi should be classified as well. 2670 uint64_t EB_FuncPtr = (OffsetBase) / 64; 2671 uint64_t EB_ThisAdj = (OffsetBase + 64 - 1) / 64; 2672 if (EB_FuncPtr != EB_ThisAdj) { 2673 Lo = Hi = Integer; 2674 } else { 2675 Current = Integer; 2676 } 2677 } 2678 } else { 2679 Current = Integer; 2680 } 2681 return; 2682 } 2683 2684 if (const VectorType *VT = Ty->getAs<VectorType>()) { 2685 uint64_t Size = getContext().getTypeSize(VT); 2686 if (Size == 1 || Size == 8 || Size == 16 || Size == 32) { 2687 // gcc passes the following as integer: 2688 // 4 bytes - <4 x char>, <2 x short>, <1 x int>, <1 x float> 2689 // 2 bytes - <2 x char>, <1 x short> 2690 // 1 byte - <1 x char> 2691 Current = Integer; 2692 2693 // If this type crosses an eightbyte boundary, it should be 2694 // split. 2695 uint64_t EB_Lo = (OffsetBase) / 64; 2696 uint64_t EB_Hi = (OffsetBase + Size - 1) / 64; 2697 if (EB_Lo != EB_Hi) 2698 Hi = Lo; 2699 } else if (Size == 64) { 2700 QualType ElementType = VT->getElementType(); 2701 2702 // gcc passes <1 x double> in memory. :( 2703 if (ElementType->isSpecificBuiltinType(BuiltinType::Double)) 2704 return; 2705 2706 // gcc passes <1 x long long> as SSE but clang used to unconditionally 2707 // pass them as integer. For platforms where clang is the de facto 2708 // platform compiler, we must continue to use integer. 2709 if (!classifyIntegerMMXAsSSE() && 2710 (ElementType->isSpecificBuiltinType(BuiltinType::LongLong) || 2711 ElementType->isSpecificBuiltinType(BuiltinType::ULongLong) || 2712 ElementType->isSpecificBuiltinType(BuiltinType::Long) || 2713 ElementType->isSpecificBuiltinType(BuiltinType::ULong))) 2714 Current = Integer; 2715 else 2716 Current = SSE; 2717 2718 // If this type crosses an eightbyte boundary, it should be 2719 // split. 2720 if (OffsetBase && OffsetBase != 64) 2721 Hi = Lo; 2722 } else if (Size == 128 || 2723 (isNamedArg && Size <= getNativeVectorSizeForAVXABI(AVXLevel))) { 2724 QualType ElementType = VT->getElementType(); 2725 2726 // gcc passes 256 and 512 bit <X x __int128> vectors in memory. :( 2727 if (passInt128VectorsInMem() && Size != 128 && 2728 (ElementType->isSpecificBuiltinType(BuiltinType::Int128) || 2729 ElementType->isSpecificBuiltinType(BuiltinType::UInt128))) 2730 return; 2731 2732 // Arguments of 256-bits are split into four eightbyte chunks. The 2733 // least significant one belongs to class SSE and all the others to class 2734 // SSEUP. The original Lo and Hi design considers that types can't be 2735 // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense. 2736 // This design isn't correct for 256-bits, but since there're no cases 2737 // where the upper parts would need to be inspected, avoid adding 2738 // complexity and just consider Hi to match the 64-256 part. 2739 // 2740 // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in 2741 // registers if they are "named", i.e. not part of the "..." of a 2742 // variadic function. 2743 // 2744 // Similarly, per 3.2.3. of the AVX512 draft, 512-bits ("named") args are 2745 // split into eight eightbyte chunks, one SSE and seven SSEUP. 2746 Lo = SSE; 2747 Hi = SSEUp; 2748 } 2749 return; 2750 } 2751 2752 if (const ComplexType *CT = Ty->getAs<ComplexType>()) { 2753 QualType ET = getContext().getCanonicalType(CT->getElementType()); 2754 2755 uint64_t Size = getContext().getTypeSize(Ty); 2756 if (ET->isIntegralOrEnumerationType()) { 2757 if (Size <= 64) 2758 Current = Integer; 2759 else if (Size <= 128) 2760 Lo = Hi = Integer; 2761 } else if (ET == getContext().FloatTy) { 2762 Current = SSE; 2763 } else if (ET == getContext().DoubleTy) { 2764 Lo = Hi = SSE; 2765 } else if (ET == getContext().LongDoubleTy) { 2766 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat(); 2767 if (LDF == &llvm::APFloat::IEEEquad()) 2768 Current = Memory; 2769 else if (LDF == &llvm::APFloat::x87DoubleExtended()) 2770 Current = ComplexX87; 2771 else if (LDF == &llvm::APFloat::IEEEdouble()) 2772 Lo = Hi = SSE; 2773 else 2774 llvm_unreachable("unexpected long double representation!"); 2775 } 2776 2777 // If this complex type crosses an eightbyte boundary then it 2778 // should be split. 2779 uint64_t EB_Real = (OffsetBase) / 64; 2780 uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64; 2781 if (Hi == NoClass && EB_Real != EB_Imag) 2782 Hi = Lo; 2783 2784 return; 2785 } 2786 2787 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) { 2788 // Arrays are treated like structures. 2789 2790 uint64_t Size = getContext().getTypeSize(Ty); 2791 2792 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger 2793 // than eight eightbytes, ..., it has class MEMORY. 2794 if (Size > 512) 2795 return; 2796 2797 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned 2798 // fields, it has class MEMORY. 2799 // 2800 // Only need to check alignment of array base. 2801 if (OffsetBase % getContext().getTypeAlign(AT->getElementType())) 2802 return; 2803 2804 // Otherwise implement simplified merge. We could be smarter about 2805 // this, but it isn't worth it and would be harder to verify. 2806 Current = NoClass; 2807 uint64_t EltSize = getContext().getTypeSize(AT->getElementType()); 2808 uint64_t ArraySize = AT->getSize().getZExtValue(); 2809 2810 // The only case a 256-bit wide vector could be used is when the array 2811 // contains a single 256-bit element. Since Lo and Hi logic isn't extended 2812 // to work for sizes wider than 128, early check and fallback to memory. 2813 // 2814 if (Size > 128 && 2815 (Size != EltSize || Size > getNativeVectorSizeForAVXABI(AVXLevel))) 2816 return; 2817 2818 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) { 2819 Class FieldLo, FieldHi; 2820 classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg); 2821 Lo = merge(Lo, FieldLo); 2822 Hi = merge(Hi, FieldHi); 2823 if (Lo == Memory || Hi == Memory) 2824 break; 2825 } 2826 2827 postMerge(Size, Lo, Hi); 2828 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification."); 2829 return; 2830 } 2831 2832 if (const RecordType *RT = Ty->getAs<RecordType>()) { 2833 uint64_t Size = getContext().getTypeSize(Ty); 2834 2835 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger 2836 // than eight eightbytes, ..., it has class MEMORY. 2837 if (Size > 512) 2838 return; 2839 2840 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial 2841 // copy constructor or a non-trivial destructor, it is passed by invisible 2842 // reference. 2843 if (getRecordArgABI(RT, getCXXABI())) 2844 return; 2845 2846 const RecordDecl *RD = RT->getDecl(); 2847 2848 // Assume variable sized types are passed in memory. 2849 if (RD->hasFlexibleArrayMember()) 2850 return; 2851 2852 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD); 2853 2854 // Reset Lo class, this will be recomputed. 2855 Current = NoClass; 2856 2857 // If this is a C++ record, classify the bases first. 2858 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 2859 for (const auto &I : CXXRD->bases()) { 2860 assert(!I.isVirtual() && !I.getType()->isDependentType() && 2861 "Unexpected base class!"); 2862 const auto *Base = 2863 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl()); 2864 2865 // Classify this field. 2866 // 2867 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a 2868 // single eightbyte, each is classified separately. Each eightbyte gets 2869 // initialized to class NO_CLASS. 2870 Class FieldLo, FieldHi; 2871 uint64_t Offset = 2872 OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base)); 2873 classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg); 2874 Lo = merge(Lo, FieldLo); 2875 Hi = merge(Hi, FieldHi); 2876 if (Lo == Memory || Hi == Memory) { 2877 postMerge(Size, Lo, Hi); 2878 return; 2879 } 2880 } 2881 } 2882 2883 // Classify the fields one at a time, merging the results. 2884 unsigned idx = 0; 2885 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 2886 i != e; ++i, ++idx) { 2887 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx); 2888 bool BitField = i->isBitField(); 2889 2890 // Ignore padding bit-fields. 2891 if (BitField && i->isUnnamedBitfield()) 2892 continue; 2893 2894 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than 2895 // four eightbytes, or it contains unaligned fields, it has class MEMORY. 2896 // 2897 // The only case a 256-bit wide vector could be used is when the struct 2898 // contains a single 256-bit element. Since Lo and Hi logic isn't extended 2899 // to work for sizes wider than 128, early check and fallback to memory. 2900 // 2901 if (Size > 128 && (Size != getContext().getTypeSize(i->getType()) || 2902 Size > getNativeVectorSizeForAVXABI(AVXLevel))) { 2903 Lo = Memory; 2904 postMerge(Size, Lo, Hi); 2905 return; 2906 } 2907 // Note, skip this test for bit-fields, see below. 2908 if (!BitField && Offset % getContext().getTypeAlign(i->getType())) { 2909 Lo = Memory; 2910 postMerge(Size, Lo, Hi); 2911 return; 2912 } 2913 2914 // Classify this field. 2915 // 2916 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate 2917 // exceeds a single eightbyte, each is classified 2918 // separately. Each eightbyte gets initialized to class 2919 // NO_CLASS. 2920 Class FieldLo, FieldHi; 2921 2922 // Bit-fields require special handling, they do not force the 2923 // structure to be passed in memory even if unaligned, and 2924 // therefore they can straddle an eightbyte. 2925 if (BitField) { 2926 assert(!i->isUnnamedBitfield()); 2927 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx); 2928 uint64_t Size = i->getBitWidthValue(getContext()); 2929 2930 uint64_t EB_Lo = Offset / 64; 2931 uint64_t EB_Hi = (Offset + Size - 1) / 64; 2932 2933 if (EB_Lo) { 2934 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes."); 2935 FieldLo = NoClass; 2936 FieldHi = Integer; 2937 } else { 2938 FieldLo = Integer; 2939 FieldHi = EB_Hi ? Integer : NoClass; 2940 } 2941 } else 2942 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg); 2943 Lo = merge(Lo, FieldLo); 2944 Hi = merge(Hi, FieldHi); 2945 if (Lo == Memory || Hi == Memory) 2946 break; 2947 } 2948 2949 postMerge(Size, Lo, Hi); 2950 } 2951 } 2952 2953 ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const { 2954 // If this is a scalar LLVM value then assume LLVM will pass it in the right 2955 // place naturally. 2956 if (!isAggregateTypeForABI(Ty)) { 2957 // Treat an enum type as its underlying type. 2958 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 2959 Ty = EnumTy->getDecl()->getIntegerType(); 2960 2961 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty) 2962 : ABIArgInfo::getDirect()); 2963 } 2964 2965 return getNaturalAlignIndirect(Ty); 2966 } 2967 2968 bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const { 2969 if (const VectorType *VecTy = Ty->getAs<VectorType>()) { 2970 uint64_t Size = getContext().getTypeSize(VecTy); 2971 unsigned LargestVector = getNativeVectorSizeForAVXABI(AVXLevel); 2972 if (Size <= 64 || Size > LargestVector) 2973 return true; 2974 QualType EltTy = VecTy->getElementType(); 2975 if (passInt128VectorsInMem() && 2976 (EltTy->isSpecificBuiltinType(BuiltinType::Int128) || 2977 EltTy->isSpecificBuiltinType(BuiltinType::UInt128))) 2978 return true; 2979 } 2980 2981 return false; 2982 } 2983 2984 ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty, 2985 unsigned freeIntRegs) const { 2986 // If this is a scalar LLVM value then assume LLVM will pass it in the right 2987 // place naturally. 2988 // 2989 // This assumption is optimistic, as there could be free registers available 2990 // when we need to pass this argument in memory, and LLVM could try to pass 2991 // the argument in the free register. This does not seem to happen currently, 2992 // but this code would be much safer if we could mark the argument with 2993 // 'onstack'. See PR12193. 2994 if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty)) { 2995 // Treat an enum type as its underlying type. 2996 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 2997 Ty = EnumTy->getDecl()->getIntegerType(); 2998 2999 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty) 3000 : ABIArgInfo::getDirect()); 3001 } 3002 3003 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 3004 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 3005 3006 // Compute the byval alignment. We specify the alignment of the byval in all 3007 // cases so that the mid-level optimizer knows the alignment of the byval. 3008 unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U); 3009 3010 // Attempt to avoid passing indirect results using byval when possible. This 3011 // is important for good codegen. 3012 // 3013 // We do this by coercing the value into a scalar type which the backend can 3014 // handle naturally (i.e., without using byval). 3015 // 3016 // For simplicity, we currently only do this when we have exhausted all of the 3017 // free integer registers. Doing this when there are free integer registers 3018 // would require more care, as we would have to ensure that the coerced value 3019 // did not claim the unused register. That would require either reording the 3020 // arguments to the function (so that any subsequent inreg values came first), 3021 // or only doing this optimization when there were no following arguments that 3022 // might be inreg. 3023 // 3024 // We currently expect it to be rare (particularly in well written code) for 3025 // arguments to be passed on the stack when there are still free integer 3026 // registers available (this would typically imply large structs being passed 3027 // by value), so this seems like a fair tradeoff for now. 3028 // 3029 // We can revisit this if the backend grows support for 'onstack' parameter 3030 // attributes. See PR12193. 3031 if (freeIntRegs == 0) { 3032 uint64_t Size = getContext().getTypeSize(Ty); 3033 3034 // If this type fits in an eightbyte, coerce it into the matching integral 3035 // type, which will end up on the stack (with alignment 8). 3036 if (Align == 8 && Size <= 64) 3037 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 3038 Size)); 3039 } 3040 3041 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(Align)); 3042 } 3043 3044 /// The ABI specifies that a value should be passed in a full vector XMM/YMM 3045 /// register. Pick an LLVM IR type that will be passed as a vector register. 3046 llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const { 3047 // Wrapper structs/arrays that only contain vectors are passed just like 3048 // vectors; strip them off if present. 3049 if (const Type *InnerTy = isSingleElementStruct(Ty, getContext())) 3050 Ty = QualType(InnerTy, 0); 3051 3052 llvm::Type *IRType = CGT.ConvertType(Ty); 3053 if (isa<llvm::VectorType>(IRType)) { 3054 // Don't pass vXi128 vectors in their native type, the backend can't 3055 // legalize them. 3056 if (passInt128VectorsInMem() && 3057 IRType->getVectorElementType()->isIntegerTy(128)) { 3058 // Use a vXi64 vector. 3059 uint64_t Size = getContext().getTypeSize(Ty); 3060 return llvm::VectorType::get(llvm::Type::getInt64Ty(getVMContext()), 3061 Size / 64); 3062 } 3063 3064 return IRType; 3065 } 3066 3067 if (IRType->getTypeID() == llvm::Type::FP128TyID) 3068 return IRType; 3069 3070 // We couldn't find the preferred IR vector type for 'Ty'. 3071 uint64_t Size = getContext().getTypeSize(Ty); 3072 assert((Size == 128 || Size == 256 || Size == 512) && "Invalid type found!"); 3073 3074 3075 // Return a LLVM IR vector type based on the size of 'Ty'. 3076 return llvm::VectorType::get(llvm::Type::getDoubleTy(getVMContext()), 3077 Size / 64); 3078 } 3079 3080 /// BitsContainNoUserData - Return true if the specified [start,end) bit range 3081 /// is known to either be off the end of the specified type or being in 3082 /// alignment padding. The user type specified is known to be at most 128 bits 3083 /// in size, and have passed through X86_64ABIInfo::classify with a successful 3084 /// classification that put one of the two halves in the INTEGER class. 3085 /// 3086 /// It is conservatively correct to return false. 3087 static bool BitsContainNoUserData(QualType Ty, unsigned StartBit, 3088 unsigned EndBit, ASTContext &Context) { 3089 // If the bytes being queried are off the end of the type, there is no user 3090 // data hiding here. This handles analysis of builtins, vectors and other 3091 // types that don't contain interesting padding. 3092 unsigned TySize = (unsigned)Context.getTypeSize(Ty); 3093 if (TySize <= StartBit) 3094 return true; 3095 3096 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) { 3097 unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType()); 3098 unsigned NumElts = (unsigned)AT->getSize().getZExtValue(); 3099 3100 // Check each element to see if the element overlaps with the queried range. 3101 for (unsigned i = 0; i != NumElts; ++i) { 3102 // If the element is after the span we care about, then we're done.. 3103 unsigned EltOffset = i*EltSize; 3104 if (EltOffset >= EndBit) break; 3105 3106 unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0; 3107 if (!BitsContainNoUserData(AT->getElementType(), EltStart, 3108 EndBit-EltOffset, Context)) 3109 return false; 3110 } 3111 // If it overlaps no elements, then it is safe to process as padding. 3112 return true; 3113 } 3114 3115 if (const RecordType *RT = Ty->getAs<RecordType>()) { 3116 const RecordDecl *RD = RT->getDecl(); 3117 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); 3118 3119 // If this is a C++ record, check the bases first. 3120 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 3121 for (const auto &I : CXXRD->bases()) { 3122 assert(!I.isVirtual() && !I.getType()->isDependentType() && 3123 "Unexpected base class!"); 3124 const auto *Base = 3125 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl()); 3126 3127 // If the base is after the span we care about, ignore it. 3128 unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base)); 3129 if (BaseOffset >= EndBit) continue; 3130 3131 unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0; 3132 if (!BitsContainNoUserData(I.getType(), BaseStart, 3133 EndBit-BaseOffset, Context)) 3134 return false; 3135 } 3136 } 3137 3138 // Verify that no field has data that overlaps the region of interest. Yes 3139 // this could be sped up a lot by being smarter about queried fields, 3140 // however we're only looking at structs up to 16 bytes, so we don't care 3141 // much. 3142 unsigned idx = 0; 3143 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 3144 i != e; ++i, ++idx) { 3145 unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx); 3146 3147 // If we found a field after the region we care about, then we're done. 3148 if (FieldOffset >= EndBit) break; 3149 3150 unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0; 3151 if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset, 3152 Context)) 3153 return false; 3154 } 3155 3156 // If nothing in this record overlapped the area of interest, then we're 3157 // clean. 3158 return true; 3159 } 3160 3161 return false; 3162 } 3163 3164 /// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a 3165 /// float member at the specified offset. For example, {int,{float}} has a 3166 /// float at offset 4. It is conservatively correct for this routine to return 3167 /// false. 3168 static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset, 3169 const llvm::DataLayout &TD) { 3170 // Base case if we find a float. 3171 if (IROffset == 0 && IRType->isFloatTy()) 3172 return true; 3173 3174 // If this is a struct, recurse into the field at the specified offset. 3175 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) { 3176 const llvm::StructLayout *SL = TD.getStructLayout(STy); 3177 unsigned Elt = SL->getElementContainingOffset(IROffset); 3178 IROffset -= SL->getElementOffset(Elt); 3179 return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD); 3180 } 3181 3182 // If this is an array, recurse into the field at the specified offset. 3183 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) { 3184 llvm::Type *EltTy = ATy->getElementType(); 3185 unsigned EltSize = TD.getTypeAllocSize(EltTy); 3186 IROffset -= IROffset/EltSize*EltSize; 3187 return ContainsFloatAtOffset(EltTy, IROffset, TD); 3188 } 3189 3190 return false; 3191 } 3192 3193 3194 /// GetSSETypeAtOffset - Return a type that will be passed by the backend in the 3195 /// low 8 bytes of an XMM register, corresponding to the SSE class. 3196 llvm::Type *X86_64ABIInfo:: 3197 GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset, 3198 QualType SourceTy, unsigned SourceOffset) const { 3199 // The only three choices we have are either double, <2 x float>, or float. We 3200 // pass as float if the last 4 bytes is just padding. This happens for 3201 // structs that contain 3 floats. 3202 if (BitsContainNoUserData(SourceTy, SourceOffset*8+32, 3203 SourceOffset*8+64, getContext())) 3204 return llvm::Type::getFloatTy(getVMContext()); 3205 3206 // We want to pass as <2 x float> if the LLVM IR type contains a float at 3207 // offset+0 and offset+4. Walk the LLVM IR type to find out if this is the 3208 // case. 3209 if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) && 3210 ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout())) 3211 return llvm::VectorType::get(llvm::Type::getFloatTy(getVMContext()), 2); 3212 3213 return llvm::Type::getDoubleTy(getVMContext()); 3214 } 3215 3216 3217 /// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in 3218 /// an 8-byte GPR. This means that we either have a scalar or we are talking 3219 /// about the high or low part of an up-to-16-byte struct. This routine picks 3220 /// the best LLVM IR type to represent this, which may be i64 or may be anything 3221 /// else that the backend will pass in a GPR that works better (e.g. i8, %foo*, 3222 /// etc). 3223 /// 3224 /// PrefType is an LLVM IR type that corresponds to (part of) the IR type for 3225 /// the source type. IROffset is an offset in bytes into the LLVM IR type that 3226 /// the 8-byte value references. PrefType may be null. 3227 /// 3228 /// SourceTy is the source-level type for the entire argument. SourceOffset is 3229 /// an offset into this that we're processing (which is always either 0 or 8). 3230 /// 3231 llvm::Type *X86_64ABIInfo:: 3232 GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset, 3233 QualType SourceTy, unsigned SourceOffset) const { 3234 // If we're dealing with an un-offset LLVM IR type, then it means that we're 3235 // returning an 8-byte unit starting with it. See if we can safely use it. 3236 if (IROffset == 0) { 3237 // Pointers and int64's always fill the 8-byte unit. 3238 if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) || 3239 IRType->isIntegerTy(64)) 3240 return IRType; 3241 3242 // If we have a 1/2/4-byte integer, we can use it only if the rest of the 3243 // goodness in the source type is just tail padding. This is allowed to 3244 // kick in for struct {double,int} on the int, but not on 3245 // struct{double,int,int} because we wouldn't return the second int. We 3246 // have to do this analysis on the source type because we can't depend on 3247 // unions being lowered a specific way etc. 3248 if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) || 3249 IRType->isIntegerTy(32) || 3250 (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) { 3251 unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 : 3252 cast<llvm::IntegerType>(IRType)->getBitWidth(); 3253 3254 if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth, 3255 SourceOffset*8+64, getContext())) 3256 return IRType; 3257 } 3258 } 3259 3260 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) { 3261 // If this is a struct, recurse into the field at the specified offset. 3262 const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy); 3263 if (IROffset < SL->getSizeInBytes()) { 3264 unsigned FieldIdx = SL->getElementContainingOffset(IROffset); 3265 IROffset -= SL->getElementOffset(FieldIdx); 3266 3267 return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset, 3268 SourceTy, SourceOffset); 3269 } 3270 } 3271 3272 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) { 3273 llvm::Type *EltTy = ATy->getElementType(); 3274 unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy); 3275 unsigned EltOffset = IROffset/EltSize*EltSize; 3276 return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy, 3277 SourceOffset); 3278 } 3279 3280 // Okay, we don't have any better idea of what to pass, so we pass this in an 3281 // integer register that isn't too big to fit the rest of the struct. 3282 unsigned TySizeInBytes = 3283 (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity(); 3284 3285 assert(TySizeInBytes != SourceOffset && "Empty field?"); 3286 3287 // It is always safe to classify this as an integer type up to i64 that 3288 // isn't larger than the structure. 3289 return llvm::IntegerType::get(getVMContext(), 3290 std::min(TySizeInBytes-SourceOffset, 8U)*8); 3291 } 3292 3293 3294 /// GetX86_64ByValArgumentPair - Given a high and low type that can ideally 3295 /// be used as elements of a two register pair to pass or return, return a 3296 /// first class aggregate to represent them. For example, if the low part of 3297 /// a by-value argument should be passed as i32* and the high part as float, 3298 /// return {i32*, float}. 3299 static llvm::Type * 3300 GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi, 3301 const llvm::DataLayout &TD) { 3302 // In order to correctly satisfy the ABI, we need to the high part to start 3303 // at offset 8. If the high and low parts we inferred are both 4-byte types 3304 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have 3305 // the second element at offset 8. Check for this: 3306 unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo); 3307 unsigned HiAlign = TD.getABITypeAlignment(Hi); 3308 unsigned HiStart = llvm::alignTo(LoSize, HiAlign); 3309 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!"); 3310 3311 // To handle this, we have to increase the size of the low part so that the 3312 // second element will start at an 8 byte offset. We can't increase the size 3313 // of the second element because it might make us access off the end of the 3314 // struct. 3315 if (HiStart != 8) { 3316 // There are usually two sorts of types the ABI generation code can produce 3317 // for the low part of a pair that aren't 8 bytes in size: float or 3318 // i8/i16/i32. This can also include pointers when they are 32-bit (X32 and 3319 // NaCl). 3320 // Promote these to a larger type. 3321 if (Lo->isFloatTy()) 3322 Lo = llvm::Type::getDoubleTy(Lo->getContext()); 3323 else { 3324 assert((Lo->isIntegerTy() || Lo->isPointerTy()) 3325 && "Invalid/unknown lo type"); 3326 Lo = llvm::Type::getInt64Ty(Lo->getContext()); 3327 } 3328 } 3329 3330 llvm::StructType *Result = llvm::StructType::get(Lo, Hi); 3331 3332 // Verify that the second element is at an 8-byte offset. 3333 assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 && 3334 "Invalid x86-64 argument pair!"); 3335 return Result; 3336 } 3337 3338 ABIArgInfo X86_64ABIInfo:: 3339 classifyReturnType(QualType RetTy) const { 3340 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the 3341 // classification algorithm. 3342 X86_64ABIInfo::Class Lo, Hi; 3343 classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true); 3344 3345 // Check some invariants. 3346 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification."); 3347 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification."); 3348 3349 llvm::Type *ResType = nullptr; 3350 switch (Lo) { 3351 case NoClass: 3352 if (Hi == NoClass) 3353 return ABIArgInfo::getIgnore(); 3354 // If the low part is just padding, it takes no register, leave ResType 3355 // null. 3356 assert((Hi == SSE || Hi == Integer || Hi == X87Up) && 3357 "Unknown missing lo part"); 3358 break; 3359 3360 case SSEUp: 3361 case X87Up: 3362 llvm_unreachable("Invalid classification for lo word."); 3363 3364 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via 3365 // hidden argument. 3366 case Memory: 3367 return getIndirectReturnResult(RetTy); 3368 3369 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next 3370 // available register of the sequence %rax, %rdx is used. 3371 case Integer: 3372 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0); 3373 3374 // If we have a sign or zero extended integer, make sure to return Extend 3375 // so that the parameter gets the right LLVM IR attributes. 3376 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) { 3377 // Treat an enum type as its underlying type. 3378 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 3379 RetTy = EnumTy->getDecl()->getIntegerType(); 3380 3381 if (RetTy->isIntegralOrEnumerationType() && 3382 RetTy->isPromotableIntegerType()) 3383 return ABIArgInfo::getExtend(RetTy); 3384 } 3385 break; 3386 3387 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next 3388 // available SSE register of the sequence %xmm0, %xmm1 is used. 3389 case SSE: 3390 ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0); 3391 break; 3392 3393 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is 3394 // returned on the X87 stack in %st0 as 80-bit x87 number. 3395 case X87: 3396 ResType = llvm::Type::getX86_FP80Ty(getVMContext()); 3397 break; 3398 3399 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real 3400 // part of the value is returned in %st0 and the imaginary part in 3401 // %st1. 3402 case ComplexX87: 3403 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification."); 3404 ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()), 3405 llvm::Type::getX86_FP80Ty(getVMContext())); 3406 break; 3407 } 3408 3409 llvm::Type *HighPart = nullptr; 3410 switch (Hi) { 3411 // Memory was handled previously and X87 should 3412 // never occur as a hi class. 3413 case Memory: 3414 case X87: 3415 llvm_unreachable("Invalid classification for hi word."); 3416 3417 case ComplexX87: // Previously handled. 3418 case NoClass: 3419 break; 3420 3421 case Integer: 3422 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8); 3423 if (Lo == NoClass) // Return HighPart at offset 8 in memory. 3424 return ABIArgInfo::getDirect(HighPart, 8); 3425 break; 3426 case SSE: 3427 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8); 3428 if (Lo == NoClass) // Return HighPart at offset 8 in memory. 3429 return ABIArgInfo::getDirect(HighPart, 8); 3430 break; 3431 3432 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte 3433 // is passed in the next available eightbyte chunk if the last used 3434 // vector register. 3435 // 3436 // SSEUP should always be preceded by SSE, just widen. 3437 case SSEUp: 3438 assert(Lo == SSE && "Unexpected SSEUp classification."); 3439 ResType = GetByteVectorType(RetTy); 3440 break; 3441 3442 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is 3443 // returned together with the previous X87 value in %st0. 3444 case X87Up: 3445 // If X87Up is preceded by X87, we don't need to do 3446 // anything. However, in some cases with unions it may not be 3447 // preceded by X87. In such situations we follow gcc and pass the 3448 // extra bits in an SSE reg. 3449 if (Lo != X87) { 3450 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8); 3451 if (Lo == NoClass) // Return HighPart at offset 8 in memory. 3452 return ABIArgInfo::getDirect(HighPart, 8); 3453 } 3454 break; 3455 } 3456 3457 // If a high part was specified, merge it together with the low part. It is 3458 // known to pass in the high eightbyte of the result. We do this by forming a 3459 // first class struct aggregate with the high and low part: {low, high} 3460 if (HighPart) 3461 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout()); 3462 3463 return ABIArgInfo::getDirect(ResType); 3464 } 3465 3466 ABIArgInfo X86_64ABIInfo::classifyArgumentType( 3467 QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE, 3468 bool isNamedArg) 3469 const 3470 { 3471 Ty = useFirstFieldIfTransparentUnion(Ty); 3472 3473 X86_64ABIInfo::Class Lo, Hi; 3474 classify(Ty, 0, Lo, Hi, isNamedArg); 3475 3476 // Check some invariants. 3477 // FIXME: Enforce these by construction. 3478 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification."); 3479 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification."); 3480 3481 neededInt = 0; 3482 neededSSE = 0; 3483 llvm::Type *ResType = nullptr; 3484 switch (Lo) { 3485 case NoClass: 3486 if (Hi == NoClass) 3487 return ABIArgInfo::getIgnore(); 3488 // If the low part is just padding, it takes no register, leave ResType 3489 // null. 3490 assert((Hi == SSE || Hi == Integer || Hi == X87Up) && 3491 "Unknown missing lo part"); 3492 break; 3493 3494 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument 3495 // on the stack. 3496 case Memory: 3497 3498 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or 3499 // COMPLEX_X87, it is passed in memory. 3500 case X87: 3501 case ComplexX87: 3502 if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect) 3503 ++neededInt; 3504 return getIndirectResult(Ty, freeIntRegs); 3505 3506 case SSEUp: 3507 case X87Up: 3508 llvm_unreachable("Invalid classification for lo word."); 3509 3510 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next 3511 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8 3512 // and %r9 is used. 3513 case Integer: 3514 ++neededInt; 3515 3516 // Pick an 8-byte type based on the preferred type. 3517 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0); 3518 3519 // If we have a sign or zero extended integer, make sure to return Extend 3520 // so that the parameter gets the right LLVM IR attributes. 3521 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) { 3522 // Treat an enum type as its underlying type. 3523 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 3524 Ty = EnumTy->getDecl()->getIntegerType(); 3525 3526 if (Ty->isIntegralOrEnumerationType() && 3527 Ty->isPromotableIntegerType()) 3528 return ABIArgInfo::getExtend(Ty); 3529 } 3530 3531 break; 3532 3533 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next 3534 // available SSE register is used, the registers are taken in the 3535 // order from %xmm0 to %xmm7. 3536 case SSE: { 3537 llvm::Type *IRType = CGT.ConvertType(Ty); 3538 ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0); 3539 ++neededSSE; 3540 break; 3541 } 3542 } 3543 3544 llvm::Type *HighPart = nullptr; 3545 switch (Hi) { 3546 // Memory was handled previously, ComplexX87 and X87 should 3547 // never occur as hi classes, and X87Up must be preceded by X87, 3548 // which is passed in memory. 3549 case Memory: 3550 case X87: 3551 case ComplexX87: 3552 llvm_unreachable("Invalid classification for hi word."); 3553 3554 case NoClass: break; 3555 3556 case Integer: 3557 ++neededInt; 3558 // Pick an 8-byte type based on the preferred type. 3559 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8); 3560 3561 if (Lo == NoClass) // Pass HighPart at offset 8 in memory. 3562 return ABIArgInfo::getDirect(HighPart, 8); 3563 break; 3564 3565 // X87Up generally doesn't occur here (long double is passed in 3566 // memory), except in situations involving unions. 3567 case X87Up: 3568 case SSE: 3569 HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8); 3570 3571 if (Lo == NoClass) // Pass HighPart at offset 8 in memory. 3572 return ABIArgInfo::getDirect(HighPart, 8); 3573 3574 ++neededSSE; 3575 break; 3576 3577 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the 3578 // eightbyte is passed in the upper half of the last used SSE 3579 // register. This only happens when 128-bit vectors are passed. 3580 case SSEUp: 3581 assert(Lo == SSE && "Unexpected SSEUp classification"); 3582 ResType = GetByteVectorType(Ty); 3583 break; 3584 } 3585 3586 // If a high part was specified, merge it together with the low part. It is 3587 // known to pass in the high eightbyte of the result. We do this by forming a 3588 // first class struct aggregate with the high and low part: {low, high} 3589 if (HighPart) 3590 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout()); 3591 3592 return ABIArgInfo::getDirect(ResType); 3593 } 3594 3595 ABIArgInfo 3596 X86_64ABIInfo::classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt, 3597 unsigned &NeededSSE) const { 3598 auto RT = Ty->getAs<RecordType>(); 3599 assert(RT && "classifyRegCallStructType only valid with struct types"); 3600 3601 if (RT->getDecl()->hasFlexibleArrayMember()) 3602 return getIndirectReturnResult(Ty); 3603 3604 // Sum up bases 3605 if (auto CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl())) { 3606 if (CXXRD->isDynamicClass()) { 3607 NeededInt = NeededSSE = 0; 3608 return getIndirectReturnResult(Ty); 3609 } 3610 3611 for (const auto &I : CXXRD->bases()) 3612 if (classifyRegCallStructTypeImpl(I.getType(), NeededInt, NeededSSE) 3613 .isIndirect()) { 3614 NeededInt = NeededSSE = 0; 3615 return getIndirectReturnResult(Ty); 3616 } 3617 } 3618 3619 // Sum up members 3620 for (const auto *FD : RT->getDecl()->fields()) { 3621 if (FD->getType()->isRecordType() && !FD->getType()->isUnionType()) { 3622 if (classifyRegCallStructTypeImpl(FD->getType(), NeededInt, NeededSSE) 3623 .isIndirect()) { 3624 NeededInt = NeededSSE = 0; 3625 return getIndirectReturnResult(Ty); 3626 } 3627 } else { 3628 unsigned LocalNeededInt, LocalNeededSSE; 3629 if (classifyArgumentType(FD->getType(), UINT_MAX, LocalNeededInt, 3630 LocalNeededSSE, true) 3631 .isIndirect()) { 3632 NeededInt = NeededSSE = 0; 3633 return getIndirectReturnResult(Ty); 3634 } 3635 NeededInt += LocalNeededInt; 3636 NeededSSE += LocalNeededSSE; 3637 } 3638 } 3639 3640 return ABIArgInfo::getDirect(); 3641 } 3642 3643 ABIArgInfo X86_64ABIInfo::classifyRegCallStructType(QualType Ty, 3644 unsigned &NeededInt, 3645 unsigned &NeededSSE) const { 3646 3647 NeededInt = 0; 3648 NeededSSE = 0; 3649 3650 return classifyRegCallStructTypeImpl(Ty, NeededInt, NeededSSE); 3651 } 3652 3653 void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const { 3654 3655 const unsigned CallingConv = FI.getCallingConvention(); 3656 // It is possible to force Win64 calling convention on any x86_64 target by 3657 // using __attribute__((ms_abi)). In such case to correctly emit Win64 3658 // compatible code delegate this call to WinX86_64ABIInfo::computeInfo. 3659 if (CallingConv == llvm::CallingConv::Win64) { 3660 WinX86_64ABIInfo Win64ABIInfo(CGT, AVXLevel); 3661 Win64ABIInfo.computeInfo(FI); 3662 return; 3663 } 3664 3665 bool IsRegCall = CallingConv == llvm::CallingConv::X86_RegCall; 3666 3667 // Keep track of the number of assigned registers. 3668 unsigned FreeIntRegs = IsRegCall ? 11 : 6; 3669 unsigned FreeSSERegs = IsRegCall ? 16 : 8; 3670 unsigned NeededInt, NeededSSE; 3671 3672 if (!::classifyReturnType(getCXXABI(), FI, *this)) { 3673 if (IsRegCall && FI.getReturnType()->getTypePtr()->isRecordType() && 3674 !FI.getReturnType()->getTypePtr()->isUnionType()) { 3675 FI.getReturnInfo() = 3676 classifyRegCallStructType(FI.getReturnType(), NeededInt, NeededSSE); 3677 if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) { 3678 FreeIntRegs -= NeededInt; 3679 FreeSSERegs -= NeededSSE; 3680 } else { 3681 FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType()); 3682 } 3683 } else if (IsRegCall && FI.getReturnType()->getAs<ComplexType>()) { 3684 // Complex Long Double Type is passed in Memory when Regcall 3685 // calling convention is used. 3686 const ComplexType *CT = FI.getReturnType()->getAs<ComplexType>(); 3687 if (getContext().getCanonicalType(CT->getElementType()) == 3688 getContext().LongDoubleTy) 3689 FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType()); 3690 } else 3691 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 3692 } 3693 3694 // If the return value is indirect, then the hidden argument is consuming one 3695 // integer register. 3696 if (FI.getReturnInfo().isIndirect()) 3697 --FreeIntRegs; 3698 3699 // The chain argument effectively gives us another free register. 3700 if (FI.isChainCall()) 3701 ++FreeIntRegs; 3702 3703 unsigned NumRequiredArgs = FI.getNumRequiredArgs(); 3704 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers 3705 // get assigned (in left-to-right order) for passing as follows... 3706 unsigned ArgNo = 0; 3707 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end(); 3708 it != ie; ++it, ++ArgNo) { 3709 bool IsNamedArg = ArgNo < NumRequiredArgs; 3710 3711 if (IsRegCall && it->type->isStructureOrClassType()) 3712 it->info = classifyRegCallStructType(it->type, NeededInt, NeededSSE); 3713 else 3714 it->info = classifyArgumentType(it->type, FreeIntRegs, NeededInt, 3715 NeededSSE, IsNamedArg); 3716 3717 // AMD64-ABI 3.2.3p3: If there are no registers available for any 3718 // eightbyte of an argument, the whole argument is passed on the 3719 // stack. If registers have already been assigned for some 3720 // eightbytes of such an argument, the assignments get reverted. 3721 if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) { 3722 FreeIntRegs -= NeededInt; 3723 FreeSSERegs -= NeededSSE; 3724 } else { 3725 it->info = getIndirectResult(it->type, FreeIntRegs); 3726 } 3727 } 3728 } 3729 3730 static Address EmitX86_64VAArgFromMemory(CodeGenFunction &CGF, 3731 Address VAListAddr, QualType Ty) { 3732 Address overflow_arg_area_p = 3733 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_p"); 3734 llvm::Value *overflow_arg_area = 3735 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area"); 3736 3737 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16 3738 // byte boundary if alignment needed by type exceeds 8 byte boundary. 3739 // It isn't stated explicitly in the standard, but in practice we use 3740 // alignment greater than 16 where necessary. 3741 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty); 3742 if (Align > CharUnits::fromQuantity(8)) { 3743 overflow_arg_area = emitRoundPointerUpToAlignment(CGF, overflow_arg_area, 3744 Align); 3745 } 3746 3747 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area. 3748 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty); 3749 llvm::Value *Res = 3750 CGF.Builder.CreateBitCast(overflow_arg_area, 3751 llvm::PointerType::getUnqual(LTy)); 3752 3753 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to: 3754 // l->overflow_arg_area + sizeof(type). 3755 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to 3756 // an 8 byte boundary. 3757 3758 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8; 3759 llvm::Value *Offset = 3760 llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7); 3761 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset, 3762 "overflow_arg_area.next"); 3763 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p); 3764 3765 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type. 3766 return Address(Res, Align); 3767 } 3768 3769 Address X86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 3770 QualType Ty) const { 3771 // Assume that va_list type is correct; should be pointer to LLVM type: 3772 // struct { 3773 // i32 gp_offset; 3774 // i32 fp_offset; 3775 // i8* overflow_arg_area; 3776 // i8* reg_save_area; 3777 // }; 3778 unsigned neededInt, neededSSE; 3779 3780 Ty = getContext().getCanonicalType(Ty); 3781 ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE, 3782 /*isNamedArg*/false); 3783 3784 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed 3785 // in the registers. If not go to step 7. 3786 if (!neededInt && !neededSSE) 3787 return EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty); 3788 3789 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of 3790 // general purpose registers needed to pass type and num_fp to hold 3791 // the number of floating point registers needed. 3792 3793 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into 3794 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or 3795 // l->fp_offset > 304 - num_fp * 16 go to step 7. 3796 // 3797 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of 3798 // register save space). 3799 3800 llvm::Value *InRegs = nullptr; 3801 Address gp_offset_p = Address::invalid(), fp_offset_p = Address::invalid(); 3802 llvm::Value *gp_offset = nullptr, *fp_offset = nullptr; 3803 if (neededInt) { 3804 gp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "gp_offset_p"); 3805 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset"); 3806 InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8); 3807 InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp"); 3808 } 3809 3810 if (neededSSE) { 3811 fp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 1, "fp_offset_p"); 3812 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset"); 3813 llvm::Value *FitsInFP = 3814 llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16); 3815 FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp"); 3816 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP; 3817 } 3818 3819 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg"); 3820 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem"); 3821 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end"); 3822 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock); 3823 3824 // Emit code to load the value if it was passed in registers. 3825 3826 CGF.EmitBlock(InRegBlock); 3827 3828 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with 3829 // an offset of l->gp_offset and/or l->fp_offset. This may require 3830 // copying to a temporary location in case the parameter is passed 3831 // in different register classes or requires an alignment greater 3832 // than 8 for general purpose registers and 16 for XMM registers. 3833 // 3834 // FIXME: This really results in shameful code when we end up needing to 3835 // collect arguments from different places; often what should result in a 3836 // simple assembling of a structure from scattered addresses has many more 3837 // loads than necessary. Can we clean this up? 3838 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty); 3839 llvm::Value *RegSaveArea = CGF.Builder.CreateLoad( 3840 CGF.Builder.CreateStructGEP(VAListAddr, 3), "reg_save_area"); 3841 3842 Address RegAddr = Address::invalid(); 3843 if (neededInt && neededSSE) { 3844 // FIXME: Cleanup. 3845 assert(AI.isDirect() && "Unexpected ABI info for mixed regs"); 3846 llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType()); 3847 Address Tmp = CGF.CreateMemTemp(Ty); 3848 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST); 3849 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs"); 3850 llvm::Type *TyLo = ST->getElementType(0); 3851 llvm::Type *TyHi = ST->getElementType(1); 3852 assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) && 3853 "Unexpected ABI info for mixed regs"); 3854 llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo); 3855 llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi); 3856 llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegSaveArea, gp_offset); 3857 llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegSaveArea, fp_offset); 3858 llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr; 3859 llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr; 3860 3861 // Copy the first element. 3862 // FIXME: Our choice of alignment here and below is probably pessimistic. 3863 llvm::Value *V = CGF.Builder.CreateAlignedLoad( 3864 TyLo, CGF.Builder.CreateBitCast(RegLoAddr, PTyLo), 3865 CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyLo))); 3866 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0)); 3867 3868 // Copy the second element. 3869 V = CGF.Builder.CreateAlignedLoad( 3870 TyHi, CGF.Builder.CreateBitCast(RegHiAddr, PTyHi), 3871 CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyHi))); 3872 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1)); 3873 3874 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy); 3875 } else if (neededInt) { 3876 RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, gp_offset), 3877 CharUnits::fromQuantity(8)); 3878 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy); 3879 3880 // Copy to a temporary if necessary to ensure the appropriate alignment. 3881 std::pair<CharUnits, CharUnits> SizeAlign = 3882 getContext().getTypeInfoInChars(Ty); 3883 uint64_t TySize = SizeAlign.first.getQuantity(); 3884 CharUnits TyAlign = SizeAlign.second; 3885 3886 // Copy into a temporary if the type is more aligned than the 3887 // register save area. 3888 if (TyAlign.getQuantity() > 8) { 3889 Address Tmp = CGF.CreateMemTemp(Ty); 3890 CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, false); 3891 RegAddr = Tmp; 3892 } 3893 3894 } else if (neededSSE == 1) { 3895 RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset), 3896 CharUnits::fromQuantity(16)); 3897 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy); 3898 } else { 3899 assert(neededSSE == 2 && "Invalid number of needed registers!"); 3900 // SSE registers are spaced 16 bytes apart in the register save 3901 // area, we need to collect the two eightbytes together. 3902 // The ABI isn't explicit about this, but it seems reasonable 3903 // to assume that the slots are 16-byte aligned, since the stack is 3904 // naturally 16-byte aligned and the prologue is expected to store 3905 // all the SSE registers to the RSA. 3906 Address RegAddrLo = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset), 3907 CharUnits::fromQuantity(16)); 3908 Address RegAddrHi = 3909 CGF.Builder.CreateConstInBoundsByteGEP(RegAddrLo, 3910 CharUnits::fromQuantity(16)); 3911 llvm::Type *ST = AI.canHaveCoerceToType() 3912 ? AI.getCoerceToType() 3913 : llvm::StructType::get(CGF.DoubleTy, CGF.DoubleTy); 3914 llvm::Value *V; 3915 Address Tmp = CGF.CreateMemTemp(Ty); 3916 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST); 3917 V = CGF.Builder.CreateLoad(CGF.Builder.CreateElementBitCast( 3918 RegAddrLo, ST->getStructElementType(0))); 3919 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0)); 3920 V = CGF.Builder.CreateLoad(CGF.Builder.CreateElementBitCast( 3921 RegAddrHi, ST->getStructElementType(1))); 3922 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1)); 3923 3924 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy); 3925 } 3926 3927 // AMD64-ABI 3.5.7p5: Step 5. Set: 3928 // l->gp_offset = l->gp_offset + num_gp * 8 3929 // l->fp_offset = l->fp_offset + num_fp * 16. 3930 if (neededInt) { 3931 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8); 3932 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset), 3933 gp_offset_p); 3934 } 3935 if (neededSSE) { 3936 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16); 3937 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset), 3938 fp_offset_p); 3939 } 3940 CGF.EmitBranch(ContBlock); 3941 3942 // Emit code to load the value if it was passed in memory. 3943 3944 CGF.EmitBlock(InMemBlock); 3945 Address MemAddr = EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty); 3946 3947 // Return the appropriate result. 3948 3949 CGF.EmitBlock(ContBlock); 3950 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, MemAddr, InMemBlock, 3951 "vaarg.addr"); 3952 return ResAddr; 3953 } 3954 3955 Address X86_64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr, 3956 QualType Ty) const { 3957 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false, 3958 CGF.getContext().getTypeInfoInChars(Ty), 3959 CharUnits::fromQuantity(8), 3960 /*allowHigherAlign*/ false); 3961 } 3962 3963 ABIArgInfo 3964 WinX86_64ABIInfo::reclassifyHvaArgType(QualType Ty, unsigned &FreeSSERegs, 3965 const ABIArgInfo ¤t) const { 3966 // Assumes vectorCall calling convention. 3967 const Type *Base = nullptr; 3968 uint64_t NumElts = 0; 3969 3970 if (!Ty->isBuiltinType() && !Ty->isVectorType() && 3971 isHomogeneousAggregate(Ty, Base, NumElts) && FreeSSERegs >= NumElts) { 3972 FreeSSERegs -= NumElts; 3973 return getDirectX86Hva(); 3974 } 3975 return current; 3976 } 3977 3978 ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, unsigned &FreeSSERegs, 3979 bool IsReturnType, bool IsVectorCall, 3980 bool IsRegCall) const { 3981 3982 if (Ty->isVoidType()) 3983 return ABIArgInfo::getIgnore(); 3984 3985 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 3986 Ty = EnumTy->getDecl()->getIntegerType(); 3987 3988 TypeInfo Info = getContext().getTypeInfo(Ty); 3989 uint64_t Width = Info.Width; 3990 CharUnits Align = getContext().toCharUnitsFromBits(Info.Align); 3991 3992 const RecordType *RT = Ty->getAs<RecordType>(); 3993 if (RT) { 3994 if (!IsReturnType) { 3995 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI())) 3996 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 3997 } 3998 3999 if (RT->getDecl()->hasFlexibleArrayMember()) 4000 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 4001 4002 } 4003 4004 const Type *Base = nullptr; 4005 uint64_t NumElts = 0; 4006 // vectorcall adds the concept of a homogenous vector aggregate, similar to 4007 // other targets. 4008 if ((IsVectorCall || IsRegCall) && 4009 isHomogeneousAggregate(Ty, Base, NumElts)) { 4010 if (IsRegCall) { 4011 if (FreeSSERegs >= NumElts) { 4012 FreeSSERegs -= NumElts; 4013 if (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType()) 4014 return ABIArgInfo::getDirect(); 4015 return ABIArgInfo::getExpand(); 4016 } 4017 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false); 4018 } else if (IsVectorCall) { 4019 if (FreeSSERegs >= NumElts && 4020 (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())) { 4021 FreeSSERegs -= NumElts; 4022 return ABIArgInfo::getDirect(); 4023 } else if (IsReturnType) { 4024 return ABIArgInfo::getExpand(); 4025 } else if (!Ty->isBuiltinType() && !Ty->isVectorType()) { 4026 // HVAs are delayed and reclassified in the 2nd step. 4027 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false); 4028 } 4029 } 4030 } 4031 4032 if (Ty->isMemberPointerType()) { 4033 // If the member pointer is represented by an LLVM int or ptr, pass it 4034 // directly. 4035 llvm::Type *LLTy = CGT.ConvertType(Ty); 4036 if (LLTy->isPointerTy() || LLTy->isIntegerTy()) 4037 return ABIArgInfo::getDirect(); 4038 } 4039 4040 if (RT || Ty->isAnyComplexType() || Ty->isMemberPointerType()) { 4041 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is 4042 // not 1, 2, 4, or 8 bytes, must be passed by reference." 4043 if (Width > 64 || !llvm::isPowerOf2_64(Width)) 4044 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 4045 4046 // Otherwise, coerce it to a small integer. 4047 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Width)); 4048 } 4049 4050 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) { 4051 switch (BT->getKind()) { 4052 case BuiltinType::Bool: 4053 // Bool type is always extended to the ABI, other builtin types are not 4054 // extended. 4055 return ABIArgInfo::getExtend(Ty); 4056 4057 case BuiltinType::LongDouble: 4058 // Mingw64 GCC uses the old 80 bit extended precision floating point 4059 // unit. It passes them indirectly through memory. 4060 if (IsMingw64) { 4061 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat(); 4062 if (LDF == &llvm::APFloat::x87DoubleExtended()) 4063 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false); 4064 } 4065 break; 4066 4067 case BuiltinType::Int128: 4068 case BuiltinType::UInt128: 4069 // If it's a parameter type, the normal ABI rule is that arguments larger 4070 // than 8 bytes are passed indirectly. GCC follows it. We follow it too, 4071 // even though it isn't particularly efficient. 4072 if (!IsReturnType) 4073 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false); 4074 4075 // Mingw64 GCC returns i128 in XMM0. Coerce to v2i64 to handle that. 4076 // Clang matches them for compatibility. 4077 return ABIArgInfo::getDirect( 4078 llvm::VectorType::get(llvm::Type::getInt64Ty(getVMContext()), 2)); 4079 4080 default: 4081 break; 4082 } 4083 } 4084 4085 return ABIArgInfo::getDirect(); 4086 } 4087 4088 void WinX86_64ABIInfo::computeVectorCallArgs(CGFunctionInfo &FI, 4089 unsigned FreeSSERegs, 4090 bool IsVectorCall, 4091 bool IsRegCall) const { 4092 unsigned Count = 0; 4093 for (auto &I : FI.arguments()) { 4094 // Vectorcall in x64 only permits the first 6 arguments to be passed 4095 // as XMM/YMM registers. 4096 if (Count < VectorcallMaxParamNumAsReg) 4097 I.info = classify(I.type, FreeSSERegs, false, IsVectorCall, IsRegCall); 4098 else { 4099 // Since these cannot be passed in registers, pretend no registers 4100 // are left. 4101 unsigned ZeroSSERegsAvail = 0; 4102 I.info = classify(I.type, /*FreeSSERegs=*/ZeroSSERegsAvail, false, 4103 IsVectorCall, IsRegCall); 4104 } 4105 ++Count; 4106 } 4107 4108 for (auto &I : FI.arguments()) { 4109 I.info = reclassifyHvaArgType(I.type, FreeSSERegs, I.info); 4110 } 4111 } 4112 4113 void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const { 4114 const unsigned CC = FI.getCallingConvention(); 4115 bool IsVectorCall = CC == llvm::CallingConv::X86_VectorCall; 4116 bool IsRegCall = CC == llvm::CallingConv::X86_RegCall; 4117 4118 // If __attribute__((sysv_abi)) is in use, use the SysV argument 4119 // classification rules. 4120 if (CC == llvm::CallingConv::X86_64_SysV) { 4121 X86_64ABIInfo SysVABIInfo(CGT, AVXLevel); 4122 SysVABIInfo.computeInfo(FI); 4123 return; 4124 } 4125 4126 unsigned FreeSSERegs = 0; 4127 if (IsVectorCall) { 4128 // We can use up to 4 SSE return registers with vectorcall. 4129 FreeSSERegs = 4; 4130 } else if (IsRegCall) { 4131 // RegCall gives us 16 SSE registers. 4132 FreeSSERegs = 16; 4133 } 4134 4135 if (!getCXXABI().classifyReturnType(FI)) 4136 FI.getReturnInfo() = classify(FI.getReturnType(), FreeSSERegs, true, 4137 IsVectorCall, IsRegCall); 4138 4139 if (IsVectorCall) { 4140 // We can use up to 6 SSE register parameters with vectorcall. 4141 FreeSSERegs = 6; 4142 } else if (IsRegCall) { 4143 // RegCall gives us 16 SSE registers, we can reuse the return registers. 4144 FreeSSERegs = 16; 4145 } 4146 4147 if (IsVectorCall) { 4148 computeVectorCallArgs(FI, FreeSSERegs, IsVectorCall, IsRegCall); 4149 } else { 4150 for (auto &I : FI.arguments()) 4151 I.info = classify(I.type, FreeSSERegs, false, IsVectorCall, IsRegCall); 4152 } 4153 4154 } 4155 4156 Address WinX86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 4157 QualType Ty) const { 4158 4159 bool IsIndirect = false; 4160 4161 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is 4162 // not 1, 2, 4, or 8 bytes, must be passed by reference." 4163 if (isAggregateTypeForABI(Ty) || Ty->isMemberPointerType()) { 4164 uint64_t Width = getContext().getTypeSize(Ty); 4165 IsIndirect = Width > 64 || !llvm::isPowerOf2_64(Width); 4166 } 4167 4168 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, 4169 CGF.getContext().getTypeInfoInChars(Ty), 4170 CharUnits::fromQuantity(8), 4171 /*allowHigherAlign*/ false); 4172 } 4173 4174 // PowerPC-32 4175 namespace { 4176 /// PPC32_SVR4_ABIInfo - The 32-bit PowerPC ELF (SVR4) ABI information. 4177 class PPC32_SVR4_ABIInfo : public DefaultABIInfo { 4178 bool IsSoftFloatABI; 4179 4180 CharUnits getParamTypeAlignment(QualType Ty) const; 4181 4182 public: 4183 PPC32_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, bool SoftFloatABI) 4184 : DefaultABIInfo(CGT), IsSoftFloatABI(SoftFloatABI) {} 4185 4186 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 4187 QualType Ty) const override; 4188 }; 4189 4190 class PPC32TargetCodeGenInfo : public TargetCodeGenInfo { 4191 public: 4192 PPC32TargetCodeGenInfo(CodeGenTypes &CGT, bool SoftFloatABI) 4193 : TargetCodeGenInfo(new PPC32_SVR4_ABIInfo(CGT, SoftFloatABI)) {} 4194 4195 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 4196 // This is recovered from gcc output. 4197 return 1; // r1 is the dedicated stack pointer 4198 } 4199 4200 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 4201 llvm::Value *Address) const override; 4202 }; 4203 } 4204 4205 CharUnits PPC32_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const { 4206 // Complex types are passed just like their elements 4207 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) 4208 Ty = CTy->getElementType(); 4209 4210 if (Ty->isVectorType()) 4211 return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16 4212 : 4); 4213 4214 // For single-element float/vector structs, we consider the whole type 4215 // to have the same alignment requirements as its single element. 4216 const Type *AlignTy = nullptr; 4217 if (const Type *EltType = isSingleElementStruct(Ty, getContext())) { 4218 const BuiltinType *BT = EltType->getAs<BuiltinType>(); 4219 if ((EltType->isVectorType() && getContext().getTypeSize(EltType) == 128) || 4220 (BT && BT->isFloatingPoint())) 4221 AlignTy = EltType; 4222 } 4223 4224 if (AlignTy) 4225 return CharUnits::fromQuantity(AlignTy->isVectorType() ? 16 : 4); 4226 return CharUnits::fromQuantity(4); 4227 } 4228 4229 // TODO: this implementation is now likely redundant with 4230 // DefaultABIInfo::EmitVAArg. 4231 Address PPC32_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAList, 4232 QualType Ty) const { 4233 if (getTarget().getTriple().isOSDarwin()) { 4234 auto TI = getContext().getTypeInfoInChars(Ty); 4235 TI.second = getParamTypeAlignment(Ty); 4236 4237 CharUnits SlotSize = CharUnits::fromQuantity(4); 4238 return emitVoidPtrVAArg(CGF, VAList, Ty, 4239 classifyArgumentType(Ty).isIndirect(), TI, SlotSize, 4240 /*AllowHigherAlign=*/true); 4241 } 4242 4243 const unsigned OverflowLimit = 8; 4244 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) { 4245 // TODO: Implement this. For now ignore. 4246 (void)CTy; 4247 return Address::invalid(); // FIXME? 4248 } 4249 4250 // struct __va_list_tag { 4251 // unsigned char gpr; 4252 // unsigned char fpr; 4253 // unsigned short reserved; 4254 // void *overflow_arg_area; 4255 // void *reg_save_area; 4256 // }; 4257 4258 bool isI64 = Ty->isIntegerType() && getContext().getTypeSize(Ty) == 64; 4259 bool isInt = 4260 Ty->isIntegerType() || Ty->isPointerType() || Ty->isAggregateType(); 4261 bool isF64 = Ty->isFloatingType() && getContext().getTypeSize(Ty) == 64; 4262 4263 // All aggregates are passed indirectly? That doesn't seem consistent 4264 // with the argument-lowering code. 4265 bool isIndirect = Ty->isAggregateType(); 4266 4267 CGBuilderTy &Builder = CGF.Builder; 4268 4269 // The calling convention either uses 1-2 GPRs or 1 FPR. 4270 Address NumRegsAddr = Address::invalid(); 4271 if (isInt || IsSoftFloatABI) { 4272 NumRegsAddr = Builder.CreateStructGEP(VAList, 0, "gpr"); 4273 } else { 4274 NumRegsAddr = Builder.CreateStructGEP(VAList, 1, "fpr"); 4275 } 4276 4277 llvm::Value *NumRegs = Builder.CreateLoad(NumRegsAddr, "numUsedRegs"); 4278 4279 // "Align" the register count when TY is i64. 4280 if (isI64 || (isF64 && IsSoftFloatABI)) { 4281 NumRegs = Builder.CreateAdd(NumRegs, Builder.getInt8(1)); 4282 NumRegs = Builder.CreateAnd(NumRegs, Builder.getInt8((uint8_t) ~1U)); 4283 } 4284 4285 llvm::Value *CC = 4286 Builder.CreateICmpULT(NumRegs, Builder.getInt8(OverflowLimit), "cond"); 4287 4288 llvm::BasicBlock *UsingRegs = CGF.createBasicBlock("using_regs"); 4289 llvm::BasicBlock *UsingOverflow = CGF.createBasicBlock("using_overflow"); 4290 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont"); 4291 4292 Builder.CreateCondBr(CC, UsingRegs, UsingOverflow); 4293 4294 llvm::Type *DirectTy = CGF.ConvertType(Ty); 4295 if (isIndirect) DirectTy = DirectTy->getPointerTo(0); 4296 4297 // Case 1: consume registers. 4298 Address RegAddr = Address::invalid(); 4299 { 4300 CGF.EmitBlock(UsingRegs); 4301 4302 Address RegSaveAreaPtr = Builder.CreateStructGEP(VAList, 4); 4303 RegAddr = Address(Builder.CreateLoad(RegSaveAreaPtr), 4304 CharUnits::fromQuantity(8)); 4305 assert(RegAddr.getElementType() == CGF.Int8Ty); 4306 4307 // Floating-point registers start after the general-purpose registers. 4308 if (!(isInt || IsSoftFloatABI)) { 4309 RegAddr = Builder.CreateConstInBoundsByteGEP(RegAddr, 4310 CharUnits::fromQuantity(32)); 4311 } 4312 4313 // Get the address of the saved value by scaling the number of 4314 // registers we've used by the number of 4315 CharUnits RegSize = CharUnits::fromQuantity((isInt || IsSoftFloatABI) ? 4 : 8); 4316 llvm::Value *RegOffset = 4317 Builder.CreateMul(NumRegs, Builder.getInt8(RegSize.getQuantity())); 4318 RegAddr = Address(Builder.CreateInBoundsGEP(CGF.Int8Ty, 4319 RegAddr.getPointer(), RegOffset), 4320 RegAddr.getAlignment().alignmentOfArrayElement(RegSize)); 4321 RegAddr = Builder.CreateElementBitCast(RegAddr, DirectTy); 4322 4323 // Increase the used-register count. 4324 NumRegs = 4325 Builder.CreateAdd(NumRegs, 4326 Builder.getInt8((isI64 || (isF64 && IsSoftFloatABI)) ? 2 : 1)); 4327 Builder.CreateStore(NumRegs, NumRegsAddr); 4328 4329 CGF.EmitBranch(Cont); 4330 } 4331 4332 // Case 2: consume space in the overflow area. 4333 Address MemAddr = Address::invalid(); 4334 { 4335 CGF.EmitBlock(UsingOverflow); 4336 4337 Builder.CreateStore(Builder.getInt8(OverflowLimit), NumRegsAddr); 4338 4339 // Everything in the overflow area is rounded up to a size of at least 4. 4340 CharUnits OverflowAreaAlign = CharUnits::fromQuantity(4); 4341 4342 CharUnits Size; 4343 if (!isIndirect) { 4344 auto TypeInfo = CGF.getContext().getTypeInfoInChars(Ty); 4345 Size = TypeInfo.first.alignTo(OverflowAreaAlign); 4346 } else { 4347 Size = CGF.getPointerSize(); 4348 } 4349 4350 Address OverflowAreaAddr = Builder.CreateStructGEP(VAList, 3); 4351 Address OverflowArea(Builder.CreateLoad(OverflowAreaAddr, "argp.cur"), 4352 OverflowAreaAlign); 4353 // Round up address of argument to alignment 4354 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty); 4355 if (Align > OverflowAreaAlign) { 4356 llvm::Value *Ptr = OverflowArea.getPointer(); 4357 OverflowArea = Address(emitRoundPointerUpToAlignment(CGF, Ptr, Align), 4358 Align); 4359 } 4360 4361 MemAddr = Builder.CreateElementBitCast(OverflowArea, DirectTy); 4362 4363 // Increase the overflow area. 4364 OverflowArea = Builder.CreateConstInBoundsByteGEP(OverflowArea, Size); 4365 Builder.CreateStore(OverflowArea.getPointer(), OverflowAreaAddr); 4366 CGF.EmitBranch(Cont); 4367 } 4368 4369 CGF.EmitBlock(Cont); 4370 4371 // Merge the cases with a phi. 4372 Address Result = emitMergePHI(CGF, RegAddr, UsingRegs, MemAddr, UsingOverflow, 4373 "vaarg.addr"); 4374 4375 // Load the pointer if the argument was passed indirectly. 4376 if (isIndirect) { 4377 Result = Address(Builder.CreateLoad(Result, "aggr"), 4378 getContext().getTypeAlignInChars(Ty)); 4379 } 4380 4381 return Result; 4382 } 4383 4384 bool 4385 PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 4386 llvm::Value *Address) const { 4387 // This is calculated from the LLVM and GCC tables and verified 4388 // against gcc output. AFAIK all ABIs use the same encoding. 4389 4390 CodeGen::CGBuilderTy &Builder = CGF.Builder; 4391 4392 llvm::IntegerType *i8 = CGF.Int8Ty; 4393 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4); 4394 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8); 4395 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16); 4396 4397 // 0-31: r0-31, the 4-byte general-purpose registers 4398 AssignToArrayRange(Builder, Address, Four8, 0, 31); 4399 4400 // 32-63: fp0-31, the 8-byte floating-point registers 4401 AssignToArrayRange(Builder, Address, Eight8, 32, 63); 4402 4403 // 64-76 are various 4-byte special-purpose registers: 4404 // 64: mq 4405 // 65: lr 4406 // 66: ctr 4407 // 67: ap 4408 // 68-75 cr0-7 4409 // 76: xer 4410 AssignToArrayRange(Builder, Address, Four8, 64, 76); 4411 4412 // 77-108: v0-31, the 16-byte vector registers 4413 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108); 4414 4415 // 109: vrsave 4416 // 110: vscr 4417 // 111: spe_acc 4418 // 112: spefscr 4419 // 113: sfp 4420 AssignToArrayRange(Builder, Address, Four8, 109, 113); 4421 4422 return false; 4423 } 4424 4425 // PowerPC-64 4426 4427 namespace { 4428 /// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information. 4429 class PPC64_SVR4_ABIInfo : public SwiftABIInfo { 4430 public: 4431 enum ABIKind { 4432 ELFv1 = 0, 4433 ELFv2 4434 }; 4435 4436 private: 4437 static const unsigned GPRBits = 64; 4438 ABIKind Kind; 4439 bool HasQPX; 4440 bool IsSoftFloatABI; 4441 4442 // A vector of float or double will be promoted to <4 x f32> or <4 x f64> and 4443 // will be passed in a QPX register. 4444 bool IsQPXVectorTy(const Type *Ty) const { 4445 if (!HasQPX) 4446 return false; 4447 4448 if (const VectorType *VT = Ty->getAs<VectorType>()) { 4449 unsigned NumElements = VT->getNumElements(); 4450 if (NumElements == 1) 4451 return false; 4452 4453 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double)) { 4454 if (getContext().getTypeSize(Ty) <= 256) 4455 return true; 4456 } else if (VT->getElementType()-> 4457 isSpecificBuiltinType(BuiltinType::Float)) { 4458 if (getContext().getTypeSize(Ty) <= 128) 4459 return true; 4460 } 4461 } 4462 4463 return false; 4464 } 4465 4466 bool IsQPXVectorTy(QualType Ty) const { 4467 return IsQPXVectorTy(Ty.getTypePtr()); 4468 } 4469 4470 public: 4471 PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind, bool HasQPX, 4472 bool SoftFloatABI) 4473 : SwiftABIInfo(CGT), Kind(Kind), HasQPX(HasQPX), 4474 IsSoftFloatABI(SoftFloatABI) {} 4475 4476 bool isPromotableTypeForABI(QualType Ty) const; 4477 CharUnits getParamTypeAlignment(QualType Ty) const; 4478 4479 ABIArgInfo classifyReturnType(QualType RetTy) const; 4480 ABIArgInfo classifyArgumentType(QualType Ty) const; 4481 4482 bool isHomogeneousAggregateBaseType(QualType Ty) const override; 4483 bool isHomogeneousAggregateSmallEnough(const Type *Ty, 4484 uint64_t Members) const override; 4485 4486 // TODO: We can add more logic to computeInfo to improve performance. 4487 // Example: For aggregate arguments that fit in a register, we could 4488 // use getDirectInReg (as is done below for structs containing a single 4489 // floating-point value) to avoid pushing them to memory on function 4490 // entry. This would require changing the logic in PPCISelLowering 4491 // when lowering the parameters in the caller and args in the callee. 4492 void computeInfo(CGFunctionInfo &FI) const override { 4493 if (!getCXXABI().classifyReturnType(FI)) 4494 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 4495 for (auto &I : FI.arguments()) { 4496 // We rely on the default argument classification for the most part. 4497 // One exception: An aggregate containing a single floating-point 4498 // or vector item must be passed in a register if one is available. 4499 const Type *T = isSingleElementStruct(I.type, getContext()); 4500 if (T) { 4501 const BuiltinType *BT = T->getAs<BuiltinType>(); 4502 if (IsQPXVectorTy(T) || 4503 (T->isVectorType() && getContext().getTypeSize(T) == 128) || 4504 (BT && BT->isFloatingPoint())) { 4505 QualType QT(T, 0); 4506 I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT)); 4507 continue; 4508 } 4509 } 4510 I.info = classifyArgumentType(I.type); 4511 } 4512 } 4513 4514 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 4515 QualType Ty) const override; 4516 4517 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars, 4518 bool asReturnValue) const override { 4519 return occupiesMoreThan(CGT, scalars, /*total*/ 4); 4520 } 4521 4522 bool isSwiftErrorInRegister() const override { 4523 return false; 4524 } 4525 }; 4526 4527 class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo { 4528 4529 public: 4530 PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT, 4531 PPC64_SVR4_ABIInfo::ABIKind Kind, bool HasQPX, 4532 bool SoftFloatABI) 4533 : TargetCodeGenInfo(new PPC64_SVR4_ABIInfo(CGT, Kind, HasQPX, 4534 SoftFloatABI)) {} 4535 4536 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 4537 // This is recovered from gcc output. 4538 return 1; // r1 is the dedicated stack pointer 4539 } 4540 4541 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 4542 llvm::Value *Address) const override; 4543 }; 4544 4545 class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo { 4546 public: 4547 PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {} 4548 4549 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 4550 // This is recovered from gcc output. 4551 return 1; // r1 is the dedicated stack pointer 4552 } 4553 4554 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 4555 llvm::Value *Address) const override; 4556 }; 4557 4558 } 4559 4560 // Return true if the ABI requires Ty to be passed sign- or zero- 4561 // extended to 64 bits. 4562 bool 4563 PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const { 4564 // Treat an enum type as its underlying type. 4565 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 4566 Ty = EnumTy->getDecl()->getIntegerType(); 4567 4568 // Promotable integer types are required to be promoted by the ABI. 4569 if (Ty->isPromotableIntegerType()) 4570 return true; 4571 4572 // In addition to the usual promotable integer types, we also need to 4573 // extend all 32-bit types, since the ABI requires promotion to 64 bits. 4574 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) 4575 switch (BT->getKind()) { 4576 case BuiltinType::Int: 4577 case BuiltinType::UInt: 4578 return true; 4579 default: 4580 break; 4581 } 4582 4583 return false; 4584 } 4585 4586 /// isAlignedParamType - Determine whether a type requires 16-byte or 4587 /// higher alignment in the parameter area. Always returns at least 8. 4588 CharUnits PPC64_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const { 4589 // Complex types are passed just like their elements. 4590 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) 4591 Ty = CTy->getElementType(); 4592 4593 // Only vector types of size 16 bytes need alignment (larger types are 4594 // passed via reference, smaller types are not aligned). 4595 if (IsQPXVectorTy(Ty)) { 4596 if (getContext().getTypeSize(Ty) > 128) 4597 return CharUnits::fromQuantity(32); 4598 4599 return CharUnits::fromQuantity(16); 4600 } else if (Ty->isVectorType()) { 4601 return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16 : 8); 4602 } 4603 4604 // For single-element float/vector structs, we consider the whole type 4605 // to have the same alignment requirements as its single element. 4606 const Type *AlignAsType = nullptr; 4607 const Type *EltType = isSingleElementStruct(Ty, getContext()); 4608 if (EltType) { 4609 const BuiltinType *BT = EltType->getAs<BuiltinType>(); 4610 if (IsQPXVectorTy(EltType) || (EltType->isVectorType() && 4611 getContext().getTypeSize(EltType) == 128) || 4612 (BT && BT->isFloatingPoint())) 4613 AlignAsType = EltType; 4614 } 4615 4616 // Likewise for ELFv2 homogeneous aggregates. 4617 const Type *Base = nullptr; 4618 uint64_t Members = 0; 4619 if (!AlignAsType && Kind == ELFv2 && 4620 isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members)) 4621 AlignAsType = Base; 4622 4623 // With special case aggregates, only vector base types need alignment. 4624 if (AlignAsType && IsQPXVectorTy(AlignAsType)) { 4625 if (getContext().getTypeSize(AlignAsType) > 128) 4626 return CharUnits::fromQuantity(32); 4627 4628 return CharUnits::fromQuantity(16); 4629 } else if (AlignAsType) { 4630 return CharUnits::fromQuantity(AlignAsType->isVectorType() ? 16 : 8); 4631 } 4632 4633 // Otherwise, we only need alignment for any aggregate type that 4634 // has an alignment requirement of >= 16 bytes. 4635 if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128) { 4636 if (HasQPX && getContext().getTypeAlign(Ty) >= 256) 4637 return CharUnits::fromQuantity(32); 4638 return CharUnits::fromQuantity(16); 4639 } 4640 4641 return CharUnits::fromQuantity(8); 4642 } 4643 4644 /// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous 4645 /// aggregate. Base is set to the base element type, and Members is set 4646 /// to the number of base elements. 4647 bool ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base, 4648 uint64_t &Members) const { 4649 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) { 4650 uint64_t NElements = AT->getSize().getZExtValue(); 4651 if (NElements == 0) 4652 return false; 4653 if (!isHomogeneousAggregate(AT->getElementType(), Base, Members)) 4654 return false; 4655 Members *= NElements; 4656 } else if (const RecordType *RT = Ty->getAs<RecordType>()) { 4657 const RecordDecl *RD = RT->getDecl(); 4658 if (RD->hasFlexibleArrayMember()) 4659 return false; 4660 4661 Members = 0; 4662 4663 // If this is a C++ record, check the bases first. 4664 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 4665 for (const auto &I : CXXRD->bases()) { 4666 // Ignore empty records. 4667 if (isEmptyRecord(getContext(), I.getType(), true)) 4668 continue; 4669 4670 uint64_t FldMembers; 4671 if (!isHomogeneousAggregate(I.getType(), Base, FldMembers)) 4672 return false; 4673 4674 Members += FldMembers; 4675 } 4676 } 4677 4678 for (const auto *FD : RD->fields()) { 4679 // Ignore (non-zero arrays of) empty records. 4680 QualType FT = FD->getType(); 4681 while (const ConstantArrayType *AT = 4682 getContext().getAsConstantArrayType(FT)) { 4683 if (AT->getSize().getZExtValue() == 0) 4684 return false; 4685 FT = AT->getElementType(); 4686 } 4687 if (isEmptyRecord(getContext(), FT, true)) 4688 continue; 4689 4690 // For compatibility with GCC, ignore empty bitfields in C++ mode. 4691 if (getContext().getLangOpts().CPlusPlus && 4692 FD->isZeroLengthBitField(getContext())) 4693 continue; 4694 4695 uint64_t FldMembers; 4696 if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers)) 4697 return false; 4698 4699 Members = (RD->isUnion() ? 4700 std::max(Members, FldMembers) : Members + FldMembers); 4701 } 4702 4703 if (!Base) 4704 return false; 4705 4706 // Ensure there is no padding. 4707 if (getContext().getTypeSize(Base) * Members != 4708 getContext().getTypeSize(Ty)) 4709 return false; 4710 } else { 4711 Members = 1; 4712 if (const ComplexType *CT = Ty->getAs<ComplexType>()) { 4713 Members = 2; 4714 Ty = CT->getElementType(); 4715 } 4716 4717 // Most ABIs only support float, double, and some vector type widths. 4718 if (!isHomogeneousAggregateBaseType(Ty)) 4719 return false; 4720 4721 // The base type must be the same for all members. Types that 4722 // agree in both total size and mode (float vs. vector) are 4723 // treated as being equivalent here. 4724 const Type *TyPtr = Ty.getTypePtr(); 4725 if (!Base) { 4726 Base = TyPtr; 4727 // If it's a non-power-of-2 vector, its size is already a power-of-2, 4728 // so make sure to widen it explicitly. 4729 if (const VectorType *VT = Base->getAs<VectorType>()) { 4730 QualType EltTy = VT->getElementType(); 4731 unsigned NumElements = 4732 getContext().getTypeSize(VT) / getContext().getTypeSize(EltTy); 4733 Base = getContext() 4734 .getVectorType(EltTy, NumElements, VT->getVectorKind()) 4735 .getTypePtr(); 4736 } 4737 } 4738 4739 if (Base->isVectorType() != TyPtr->isVectorType() || 4740 getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr)) 4741 return false; 4742 } 4743 return Members > 0 && isHomogeneousAggregateSmallEnough(Base, Members); 4744 } 4745 4746 bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const { 4747 // Homogeneous aggregates for ELFv2 must have base types of float, 4748 // double, long double, or 128-bit vectors. 4749 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) { 4750 if (BT->getKind() == BuiltinType::Float || 4751 BT->getKind() == BuiltinType::Double || 4752 BT->getKind() == BuiltinType::LongDouble || 4753 (getContext().getTargetInfo().hasFloat128Type() && 4754 (BT->getKind() == BuiltinType::Float128))) { 4755 if (IsSoftFloatABI) 4756 return false; 4757 return true; 4758 } 4759 } 4760 if (const VectorType *VT = Ty->getAs<VectorType>()) { 4761 if (getContext().getTypeSize(VT) == 128 || IsQPXVectorTy(Ty)) 4762 return true; 4763 } 4764 return false; 4765 } 4766 4767 bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateSmallEnough( 4768 const Type *Base, uint64_t Members) const { 4769 // Vector and fp128 types require one register, other floating point types 4770 // require one or two registers depending on their size. 4771 uint32_t NumRegs = 4772 ((getContext().getTargetInfo().hasFloat128Type() && 4773 Base->isFloat128Type()) || 4774 Base->isVectorType()) ? 1 4775 : (getContext().getTypeSize(Base) + 63) / 64; 4776 4777 // Homogeneous Aggregates may occupy at most 8 registers. 4778 return Members * NumRegs <= 8; 4779 } 4780 4781 ABIArgInfo 4782 PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const { 4783 Ty = useFirstFieldIfTransparentUnion(Ty); 4784 4785 if (Ty->isAnyComplexType()) 4786 return ABIArgInfo::getDirect(); 4787 4788 // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes) 4789 // or via reference (larger than 16 bytes). 4790 if (Ty->isVectorType() && !IsQPXVectorTy(Ty)) { 4791 uint64_t Size = getContext().getTypeSize(Ty); 4792 if (Size > 128) 4793 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 4794 else if (Size < 128) { 4795 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size); 4796 return ABIArgInfo::getDirect(CoerceTy); 4797 } 4798 } 4799 4800 if (isAggregateTypeForABI(Ty)) { 4801 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 4802 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 4803 4804 uint64_t ABIAlign = getParamTypeAlignment(Ty).getQuantity(); 4805 uint64_t TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity(); 4806 4807 // ELFv2 homogeneous aggregates are passed as array types. 4808 const Type *Base = nullptr; 4809 uint64_t Members = 0; 4810 if (Kind == ELFv2 && 4811 isHomogeneousAggregate(Ty, Base, Members)) { 4812 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0)); 4813 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members); 4814 return ABIArgInfo::getDirect(CoerceTy); 4815 } 4816 4817 // If an aggregate may end up fully in registers, we do not 4818 // use the ByVal method, but pass the aggregate as array. 4819 // This is usually beneficial since we avoid forcing the 4820 // back-end to store the argument to memory. 4821 uint64_t Bits = getContext().getTypeSize(Ty); 4822 if (Bits > 0 && Bits <= 8 * GPRBits) { 4823 llvm::Type *CoerceTy; 4824 4825 // Types up to 8 bytes are passed as integer type (which will be 4826 // properly aligned in the argument save area doubleword). 4827 if (Bits <= GPRBits) 4828 CoerceTy = 4829 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8)); 4830 // Larger types are passed as arrays, with the base type selected 4831 // according to the required alignment in the save area. 4832 else { 4833 uint64_t RegBits = ABIAlign * 8; 4834 uint64_t NumRegs = llvm::alignTo(Bits, RegBits) / RegBits; 4835 llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits); 4836 CoerceTy = llvm::ArrayType::get(RegTy, NumRegs); 4837 } 4838 4839 return ABIArgInfo::getDirect(CoerceTy); 4840 } 4841 4842 // All other aggregates are passed ByVal. 4843 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign), 4844 /*ByVal=*/true, 4845 /*Realign=*/TyAlign > ABIAlign); 4846 } 4847 4848 return (isPromotableTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty) 4849 : ABIArgInfo::getDirect()); 4850 } 4851 4852 ABIArgInfo 4853 PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const { 4854 if (RetTy->isVoidType()) 4855 return ABIArgInfo::getIgnore(); 4856 4857 if (RetTy->isAnyComplexType()) 4858 return ABIArgInfo::getDirect(); 4859 4860 // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes) 4861 // or via reference (larger than 16 bytes). 4862 if (RetTy->isVectorType() && !IsQPXVectorTy(RetTy)) { 4863 uint64_t Size = getContext().getTypeSize(RetTy); 4864 if (Size > 128) 4865 return getNaturalAlignIndirect(RetTy); 4866 else if (Size < 128) { 4867 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size); 4868 return ABIArgInfo::getDirect(CoerceTy); 4869 } 4870 } 4871 4872 if (isAggregateTypeForABI(RetTy)) { 4873 // ELFv2 homogeneous aggregates are returned as array types. 4874 const Type *Base = nullptr; 4875 uint64_t Members = 0; 4876 if (Kind == ELFv2 && 4877 isHomogeneousAggregate(RetTy, Base, Members)) { 4878 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0)); 4879 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members); 4880 return ABIArgInfo::getDirect(CoerceTy); 4881 } 4882 4883 // ELFv2 small aggregates are returned in up to two registers. 4884 uint64_t Bits = getContext().getTypeSize(RetTy); 4885 if (Kind == ELFv2 && Bits <= 2 * GPRBits) { 4886 if (Bits == 0) 4887 return ABIArgInfo::getIgnore(); 4888 4889 llvm::Type *CoerceTy; 4890 if (Bits > GPRBits) { 4891 CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits); 4892 CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy); 4893 } else 4894 CoerceTy = 4895 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8)); 4896 return ABIArgInfo::getDirect(CoerceTy); 4897 } 4898 4899 // All other aggregates are returned indirectly. 4900 return getNaturalAlignIndirect(RetTy); 4901 } 4902 4903 return (isPromotableTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy) 4904 : ABIArgInfo::getDirect()); 4905 } 4906 4907 // Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine. 4908 Address PPC64_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 4909 QualType Ty) const { 4910 auto TypeInfo = getContext().getTypeInfoInChars(Ty); 4911 TypeInfo.second = getParamTypeAlignment(Ty); 4912 4913 CharUnits SlotSize = CharUnits::fromQuantity(8); 4914 4915 // If we have a complex type and the base type is smaller than 8 bytes, 4916 // the ABI calls for the real and imaginary parts to be right-adjusted 4917 // in separate doublewords. However, Clang expects us to produce a 4918 // pointer to a structure with the two parts packed tightly. So generate 4919 // loads of the real and imaginary parts relative to the va_list pointer, 4920 // and store them to a temporary structure. 4921 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) { 4922 CharUnits EltSize = TypeInfo.first / 2; 4923 if (EltSize < SlotSize) { 4924 Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, CGF.Int8Ty, 4925 SlotSize * 2, SlotSize, 4926 SlotSize, /*AllowHigher*/ true); 4927 4928 Address RealAddr = Addr; 4929 Address ImagAddr = RealAddr; 4930 if (CGF.CGM.getDataLayout().isBigEndian()) { 4931 RealAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, 4932 SlotSize - EltSize); 4933 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(ImagAddr, 4934 2 * SlotSize - EltSize); 4935 } else { 4936 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, SlotSize); 4937 } 4938 4939 llvm::Type *EltTy = CGF.ConvertTypeForMem(CTy->getElementType()); 4940 RealAddr = CGF.Builder.CreateElementBitCast(RealAddr, EltTy); 4941 ImagAddr = CGF.Builder.CreateElementBitCast(ImagAddr, EltTy); 4942 llvm::Value *Real = CGF.Builder.CreateLoad(RealAddr, ".vareal"); 4943 llvm::Value *Imag = CGF.Builder.CreateLoad(ImagAddr, ".vaimag"); 4944 4945 Address Temp = CGF.CreateMemTemp(Ty, "vacplx"); 4946 CGF.EmitStoreOfComplex({Real, Imag}, CGF.MakeAddrLValue(Temp, Ty), 4947 /*init*/ true); 4948 return Temp; 4949 } 4950 } 4951 4952 // Otherwise, just use the general rule. 4953 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false, 4954 TypeInfo, SlotSize, /*AllowHigher*/ true); 4955 } 4956 4957 static bool 4958 PPC64_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 4959 llvm::Value *Address) { 4960 // This is calculated from the LLVM and GCC tables and verified 4961 // against gcc output. AFAIK all ABIs use the same encoding. 4962 4963 CodeGen::CGBuilderTy &Builder = CGF.Builder; 4964 4965 llvm::IntegerType *i8 = CGF.Int8Ty; 4966 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4); 4967 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8); 4968 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16); 4969 4970 // 0-31: r0-31, the 8-byte general-purpose registers 4971 AssignToArrayRange(Builder, Address, Eight8, 0, 31); 4972 4973 // 32-63: fp0-31, the 8-byte floating-point registers 4974 AssignToArrayRange(Builder, Address, Eight8, 32, 63); 4975 4976 // 64-67 are various 8-byte special-purpose registers: 4977 // 64: mq 4978 // 65: lr 4979 // 66: ctr 4980 // 67: ap 4981 AssignToArrayRange(Builder, Address, Eight8, 64, 67); 4982 4983 // 68-76 are various 4-byte special-purpose registers: 4984 // 68-75 cr0-7 4985 // 76: xer 4986 AssignToArrayRange(Builder, Address, Four8, 68, 76); 4987 4988 // 77-108: v0-31, the 16-byte vector registers 4989 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108); 4990 4991 // 109: vrsave 4992 // 110: vscr 4993 // 111: spe_acc 4994 // 112: spefscr 4995 // 113: sfp 4996 // 114: tfhar 4997 // 115: tfiar 4998 // 116: texasr 4999 AssignToArrayRange(Builder, Address, Eight8, 109, 116); 5000 5001 return false; 5002 } 5003 5004 bool 5005 PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable( 5006 CodeGen::CodeGenFunction &CGF, 5007 llvm::Value *Address) const { 5008 5009 return PPC64_initDwarfEHRegSizeTable(CGF, Address); 5010 } 5011 5012 bool 5013 PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 5014 llvm::Value *Address) const { 5015 5016 return PPC64_initDwarfEHRegSizeTable(CGF, Address); 5017 } 5018 5019 //===----------------------------------------------------------------------===// 5020 // AArch64 ABI Implementation 5021 //===----------------------------------------------------------------------===// 5022 5023 namespace { 5024 5025 class AArch64ABIInfo : public SwiftABIInfo { 5026 public: 5027 enum ABIKind { 5028 AAPCS = 0, 5029 DarwinPCS, 5030 Win64 5031 }; 5032 5033 private: 5034 ABIKind Kind; 5035 5036 public: 5037 AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind) 5038 : SwiftABIInfo(CGT), Kind(Kind) {} 5039 5040 private: 5041 ABIKind getABIKind() const { return Kind; } 5042 bool isDarwinPCS() const { return Kind == DarwinPCS; } 5043 5044 ABIArgInfo classifyReturnType(QualType RetTy, bool IsVariadic) const; 5045 ABIArgInfo classifyArgumentType(QualType RetTy) const; 5046 bool isHomogeneousAggregateBaseType(QualType Ty) const override; 5047 bool isHomogeneousAggregateSmallEnough(const Type *Ty, 5048 uint64_t Members) const override; 5049 5050 bool isIllegalVectorType(QualType Ty) const; 5051 5052 void computeInfo(CGFunctionInfo &FI) const override { 5053 if (!::classifyReturnType(getCXXABI(), FI, *this)) 5054 FI.getReturnInfo() = 5055 classifyReturnType(FI.getReturnType(), FI.isVariadic()); 5056 5057 for (auto &it : FI.arguments()) 5058 it.info = classifyArgumentType(it.type); 5059 } 5060 5061 Address EmitDarwinVAArg(Address VAListAddr, QualType Ty, 5062 CodeGenFunction &CGF) const; 5063 5064 Address EmitAAPCSVAArg(Address VAListAddr, QualType Ty, 5065 CodeGenFunction &CGF) const; 5066 5067 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 5068 QualType Ty) const override { 5069 return Kind == Win64 ? EmitMSVAArg(CGF, VAListAddr, Ty) 5070 : isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF) 5071 : EmitAAPCSVAArg(VAListAddr, Ty, CGF); 5072 } 5073 5074 Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr, 5075 QualType Ty) const override; 5076 5077 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars, 5078 bool asReturnValue) const override { 5079 return occupiesMoreThan(CGT, scalars, /*total*/ 4); 5080 } 5081 bool isSwiftErrorInRegister() const override { 5082 return true; 5083 } 5084 5085 bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy, 5086 unsigned elts) const override; 5087 }; 5088 5089 class AArch64TargetCodeGenInfo : public TargetCodeGenInfo { 5090 public: 5091 AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind) 5092 : TargetCodeGenInfo(new AArch64ABIInfo(CGT, Kind)) {} 5093 5094 StringRef getARCRetainAutoreleasedReturnValueMarker() const override { 5095 return "mov\tfp, fp\t\t// marker for objc_retainAutoreleaseReturnValue"; 5096 } 5097 5098 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 5099 return 31; 5100 } 5101 5102 bool doesReturnSlotInterfereWithArgs() const override { return false; } 5103 5104 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 5105 CodeGen::CodeGenModule &CGM) const override { 5106 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D); 5107 if (!FD) 5108 return; 5109 5110 LangOptions::SignReturnAddressScopeKind Scope = 5111 CGM.getLangOpts().getSignReturnAddressScope(); 5112 LangOptions::SignReturnAddressKeyKind Key = 5113 CGM.getLangOpts().getSignReturnAddressKey(); 5114 bool BranchTargetEnforcement = CGM.getLangOpts().BranchTargetEnforcement; 5115 if (const auto *TA = FD->getAttr<TargetAttr>()) { 5116 ParsedTargetAttr Attr = TA->parse(); 5117 if (!Attr.BranchProtection.empty()) { 5118 TargetInfo::BranchProtectionInfo BPI; 5119 StringRef Error; 5120 (void)CGM.getTarget().validateBranchProtection(Attr.BranchProtection, 5121 BPI, Error); 5122 assert(Error.empty()); 5123 Scope = BPI.SignReturnAddr; 5124 Key = BPI.SignKey; 5125 BranchTargetEnforcement = BPI.BranchTargetEnforcement; 5126 } 5127 } 5128 5129 auto *Fn = cast<llvm::Function>(GV); 5130 if (Scope != LangOptions::SignReturnAddressScopeKind::None) { 5131 Fn->addFnAttr("sign-return-address", 5132 Scope == LangOptions::SignReturnAddressScopeKind::All 5133 ? "all" 5134 : "non-leaf"); 5135 5136 Fn->addFnAttr("sign-return-address-key", 5137 Key == LangOptions::SignReturnAddressKeyKind::AKey 5138 ? "a_key" 5139 : "b_key"); 5140 } 5141 5142 if (BranchTargetEnforcement) 5143 Fn->addFnAttr("branch-target-enforcement"); 5144 } 5145 }; 5146 5147 class WindowsAArch64TargetCodeGenInfo : public AArch64TargetCodeGenInfo { 5148 public: 5149 WindowsAArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind K) 5150 : AArch64TargetCodeGenInfo(CGT, K) {} 5151 5152 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 5153 CodeGen::CodeGenModule &CGM) const override; 5154 5155 void getDependentLibraryOption(llvm::StringRef Lib, 5156 llvm::SmallString<24> &Opt) const override { 5157 Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib); 5158 } 5159 5160 void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value, 5161 llvm::SmallString<32> &Opt) const override { 5162 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\""; 5163 } 5164 }; 5165 5166 void WindowsAArch64TargetCodeGenInfo::setTargetAttributes( 5167 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const { 5168 AArch64TargetCodeGenInfo::setTargetAttributes(D, GV, CGM); 5169 if (GV->isDeclaration()) 5170 return; 5171 addStackProbeTargetAttributes(D, GV, CGM); 5172 } 5173 } 5174 5175 ABIArgInfo AArch64ABIInfo::classifyArgumentType(QualType Ty) const { 5176 Ty = useFirstFieldIfTransparentUnion(Ty); 5177 5178 // Handle illegal vector types here. 5179 if (isIllegalVectorType(Ty)) { 5180 uint64_t Size = getContext().getTypeSize(Ty); 5181 // Android promotes <2 x i8> to i16, not i32 5182 if (isAndroid() && (Size <= 16)) { 5183 llvm::Type *ResType = llvm::Type::getInt16Ty(getVMContext()); 5184 return ABIArgInfo::getDirect(ResType); 5185 } 5186 if (Size <= 32) { 5187 llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext()); 5188 return ABIArgInfo::getDirect(ResType); 5189 } 5190 if (Size == 64) { 5191 llvm::Type *ResType = 5192 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2); 5193 return ABIArgInfo::getDirect(ResType); 5194 } 5195 if (Size == 128) { 5196 llvm::Type *ResType = 5197 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4); 5198 return ABIArgInfo::getDirect(ResType); 5199 } 5200 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 5201 } 5202 5203 if (!isAggregateTypeForABI(Ty)) { 5204 // Treat an enum type as its underlying type. 5205 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 5206 Ty = EnumTy->getDecl()->getIntegerType(); 5207 5208 return (Ty->isPromotableIntegerType() && isDarwinPCS() 5209 ? ABIArgInfo::getExtend(Ty) 5210 : ABIArgInfo::getDirect()); 5211 } 5212 5213 // Structures with either a non-trivial destructor or a non-trivial 5214 // copy constructor are always indirect. 5215 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) { 5216 return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA == 5217 CGCXXABI::RAA_DirectInMemory); 5218 } 5219 5220 // Empty records are always ignored on Darwin, but actually passed in C++ mode 5221 // elsewhere for GNU compatibility. 5222 uint64_t Size = getContext().getTypeSize(Ty); 5223 bool IsEmpty = isEmptyRecord(getContext(), Ty, true); 5224 if (IsEmpty || Size == 0) { 5225 if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS()) 5226 return ABIArgInfo::getIgnore(); 5227 5228 // GNU C mode. The only argument that gets ignored is an empty one with size 5229 // 0. 5230 if (IsEmpty && Size == 0) 5231 return ABIArgInfo::getIgnore(); 5232 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext())); 5233 } 5234 5235 // Homogeneous Floating-point Aggregates (HFAs) need to be expanded. 5236 const Type *Base = nullptr; 5237 uint64_t Members = 0; 5238 if (isHomogeneousAggregate(Ty, Base, Members)) { 5239 return ABIArgInfo::getDirect( 5240 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members)); 5241 } 5242 5243 // Aggregates <= 16 bytes are passed directly in registers or on the stack. 5244 if (Size <= 128) { 5245 // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of 5246 // same size and alignment. 5247 if (getTarget().isRenderScriptTarget()) { 5248 return coerceToIntArray(Ty, getContext(), getVMContext()); 5249 } 5250 unsigned Alignment; 5251 if (Kind == AArch64ABIInfo::AAPCS) { 5252 Alignment = getContext().getTypeUnadjustedAlign(Ty); 5253 Alignment = Alignment < 128 ? 64 : 128; 5254 } else { 5255 Alignment = std::max(getContext().getTypeAlign(Ty), 5256 (unsigned)getTarget().getPointerWidth(0)); 5257 } 5258 Size = llvm::alignTo(Size, Alignment); 5259 5260 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment. 5261 // For aggregates with 16-byte alignment, we use i128. 5262 llvm::Type *BaseTy = llvm::Type::getIntNTy(getVMContext(), Alignment); 5263 return ABIArgInfo::getDirect( 5264 Size == Alignment ? BaseTy 5265 : llvm::ArrayType::get(BaseTy, Size / Alignment)); 5266 } 5267 5268 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 5269 } 5270 5271 ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy, 5272 bool IsVariadic) const { 5273 if (RetTy->isVoidType()) 5274 return ABIArgInfo::getIgnore(); 5275 5276 // Large vector types should be returned via memory. 5277 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128) 5278 return getNaturalAlignIndirect(RetTy); 5279 5280 if (!isAggregateTypeForABI(RetTy)) { 5281 // Treat an enum type as its underlying type. 5282 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 5283 RetTy = EnumTy->getDecl()->getIntegerType(); 5284 5285 return (RetTy->isPromotableIntegerType() && isDarwinPCS() 5286 ? ABIArgInfo::getExtend(RetTy) 5287 : ABIArgInfo::getDirect()); 5288 } 5289 5290 uint64_t Size = getContext().getTypeSize(RetTy); 5291 if (isEmptyRecord(getContext(), RetTy, true) || Size == 0) 5292 return ABIArgInfo::getIgnore(); 5293 5294 const Type *Base = nullptr; 5295 uint64_t Members = 0; 5296 if (isHomogeneousAggregate(RetTy, Base, Members) && 5297 !(getTarget().getTriple().getArch() == llvm::Triple::aarch64_32 && 5298 IsVariadic)) 5299 // Homogeneous Floating-point Aggregates (HFAs) are returned directly. 5300 return ABIArgInfo::getDirect(); 5301 5302 // Aggregates <= 16 bytes are returned directly in registers or on the stack. 5303 if (Size <= 128) { 5304 // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of 5305 // same size and alignment. 5306 if (getTarget().isRenderScriptTarget()) { 5307 return coerceToIntArray(RetTy, getContext(), getVMContext()); 5308 } 5309 unsigned Alignment = getContext().getTypeAlign(RetTy); 5310 Size = llvm::alignTo(Size, 64); // round up to multiple of 8 bytes 5311 5312 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment. 5313 // For aggregates with 16-byte alignment, we use i128. 5314 if (Alignment < 128 && Size == 128) { 5315 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext()); 5316 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64)); 5317 } 5318 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size)); 5319 } 5320 5321 return getNaturalAlignIndirect(RetTy); 5322 } 5323 5324 /// isIllegalVectorType - check whether the vector type is legal for AArch64. 5325 bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const { 5326 if (const VectorType *VT = Ty->getAs<VectorType>()) { 5327 // Check whether VT is legal. 5328 unsigned NumElements = VT->getNumElements(); 5329 uint64_t Size = getContext().getTypeSize(VT); 5330 // NumElements should be power of 2. 5331 if (!llvm::isPowerOf2_32(NumElements)) 5332 return true; 5333 5334 // arm64_32 has to be compatible with the ARM logic here, which allows huge 5335 // vectors for some reason. 5336 llvm::Triple Triple = getTarget().getTriple(); 5337 if (Triple.getArch() == llvm::Triple::aarch64_32 && 5338 Triple.isOSBinFormatMachO()) 5339 return Size <= 32; 5340 5341 return Size != 64 && (Size != 128 || NumElements == 1); 5342 } 5343 return false; 5344 } 5345 5346 bool AArch64ABIInfo::isLegalVectorTypeForSwift(CharUnits totalSize, 5347 llvm::Type *eltTy, 5348 unsigned elts) const { 5349 if (!llvm::isPowerOf2_32(elts)) 5350 return false; 5351 if (totalSize.getQuantity() != 8 && 5352 (totalSize.getQuantity() != 16 || elts == 1)) 5353 return false; 5354 return true; 5355 } 5356 5357 bool AArch64ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const { 5358 // Homogeneous aggregates for AAPCS64 must have base types of a floating 5359 // point type or a short-vector type. This is the same as the 32-bit ABI, 5360 // but with the difference that any floating-point type is allowed, 5361 // including __fp16. 5362 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) { 5363 if (BT->isFloatingPoint()) 5364 return true; 5365 } else if (const VectorType *VT = Ty->getAs<VectorType>()) { 5366 unsigned VecSize = getContext().getTypeSize(VT); 5367 if (VecSize == 64 || VecSize == 128) 5368 return true; 5369 } 5370 return false; 5371 } 5372 5373 bool AArch64ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base, 5374 uint64_t Members) const { 5375 return Members <= 4; 5376 } 5377 5378 Address AArch64ABIInfo::EmitAAPCSVAArg(Address VAListAddr, 5379 QualType Ty, 5380 CodeGenFunction &CGF) const { 5381 ABIArgInfo AI = classifyArgumentType(Ty); 5382 bool IsIndirect = AI.isIndirect(); 5383 5384 llvm::Type *BaseTy = CGF.ConvertType(Ty); 5385 if (IsIndirect) 5386 BaseTy = llvm::PointerType::getUnqual(BaseTy); 5387 else if (AI.getCoerceToType()) 5388 BaseTy = AI.getCoerceToType(); 5389 5390 unsigned NumRegs = 1; 5391 if (llvm::ArrayType *ArrTy = dyn_cast<llvm::ArrayType>(BaseTy)) { 5392 BaseTy = ArrTy->getElementType(); 5393 NumRegs = ArrTy->getNumElements(); 5394 } 5395 bool IsFPR = BaseTy->isFloatingPointTy() || BaseTy->isVectorTy(); 5396 5397 // The AArch64 va_list type and handling is specified in the Procedure Call 5398 // Standard, section B.4: 5399 // 5400 // struct { 5401 // void *__stack; 5402 // void *__gr_top; 5403 // void *__vr_top; 5404 // int __gr_offs; 5405 // int __vr_offs; 5406 // }; 5407 5408 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg"); 5409 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg"); 5410 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack"); 5411 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end"); 5412 5413 CharUnits TySize = getContext().getTypeSizeInChars(Ty); 5414 CharUnits TyAlign = getContext().getTypeUnadjustedAlignInChars(Ty); 5415 5416 Address reg_offs_p = Address::invalid(); 5417 llvm::Value *reg_offs = nullptr; 5418 int reg_top_index; 5419 int RegSize = IsIndirect ? 8 : TySize.getQuantity(); 5420 if (!IsFPR) { 5421 // 3 is the field number of __gr_offs 5422 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 3, "gr_offs_p"); 5423 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs"); 5424 reg_top_index = 1; // field number for __gr_top 5425 RegSize = llvm::alignTo(RegSize, 8); 5426 } else { 5427 // 4 is the field number of __vr_offs. 5428 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 4, "vr_offs_p"); 5429 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs"); 5430 reg_top_index = 2; // field number for __vr_top 5431 RegSize = 16 * NumRegs; 5432 } 5433 5434 //======================================= 5435 // Find out where argument was passed 5436 //======================================= 5437 5438 // If reg_offs >= 0 we're already using the stack for this type of 5439 // argument. We don't want to keep updating reg_offs (in case it overflows, 5440 // though anyone passing 2GB of arguments, each at most 16 bytes, deserves 5441 // whatever they get). 5442 llvm::Value *UsingStack = nullptr; 5443 UsingStack = CGF.Builder.CreateICmpSGE( 5444 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0)); 5445 5446 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock); 5447 5448 // Otherwise, at least some kind of argument could go in these registers, the 5449 // question is whether this particular type is too big. 5450 CGF.EmitBlock(MaybeRegBlock); 5451 5452 // Integer arguments may need to correct register alignment (for example a 5453 // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we 5454 // align __gr_offs to calculate the potential address. 5455 if (!IsFPR && !IsIndirect && TyAlign.getQuantity() > 8) { 5456 int Align = TyAlign.getQuantity(); 5457 5458 reg_offs = CGF.Builder.CreateAdd( 5459 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1), 5460 "align_regoffs"); 5461 reg_offs = CGF.Builder.CreateAnd( 5462 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align), 5463 "aligned_regoffs"); 5464 } 5465 5466 // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list. 5467 // The fact that this is done unconditionally reflects the fact that 5468 // allocating an argument to the stack also uses up all the remaining 5469 // registers of the appropriate kind. 5470 llvm::Value *NewOffset = nullptr; 5471 NewOffset = CGF.Builder.CreateAdd( 5472 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs"); 5473 CGF.Builder.CreateStore(NewOffset, reg_offs_p); 5474 5475 // Now we're in a position to decide whether this argument really was in 5476 // registers or not. 5477 llvm::Value *InRegs = nullptr; 5478 InRegs = CGF.Builder.CreateICmpSLE( 5479 NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg"); 5480 5481 CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock); 5482 5483 //======================================= 5484 // Argument was in registers 5485 //======================================= 5486 5487 // Now we emit the code for if the argument was originally passed in 5488 // registers. First start the appropriate block: 5489 CGF.EmitBlock(InRegBlock); 5490 5491 llvm::Value *reg_top = nullptr; 5492 Address reg_top_p = 5493 CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index, "reg_top_p"); 5494 reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top"); 5495 Address BaseAddr(CGF.Builder.CreateInBoundsGEP(reg_top, reg_offs), 5496 CharUnits::fromQuantity(IsFPR ? 16 : 8)); 5497 Address RegAddr = Address::invalid(); 5498 llvm::Type *MemTy = CGF.ConvertTypeForMem(Ty); 5499 5500 if (IsIndirect) { 5501 // If it's been passed indirectly (actually a struct), whatever we find from 5502 // stored registers or on the stack will actually be a struct **. 5503 MemTy = llvm::PointerType::getUnqual(MemTy); 5504 } 5505 5506 const Type *Base = nullptr; 5507 uint64_t NumMembers = 0; 5508 bool IsHFA = isHomogeneousAggregate(Ty, Base, NumMembers); 5509 if (IsHFA && NumMembers > 1) { 5510 // Homogeneous aggregates passed in registers will have their elements split 5511 // and stored 16-bytes apart regardless of size (they're notionally in qN, 5512 // qN+1, ...). We reload and store into a temporary local variable 5513 // contiguously. 5514 assert(!IsIndirect && "Homogeneous aggregates should be passed directly"); 5515 auto BaseTyInfo = getContext().getTypeInfoInChars(QualType(Base, 0)); 5516 llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0)); 5517 llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers); 5518 Address Tmp = CGF.CreateTempAlloca(HFATy, 5519 std::max(TyAlign, BaseTyInfo.second)); 5520 5521 // On big-endian platforms, the value will be right-aligned in its slot. 5522 int Offset = 0; 5523 if (CGF.CGM.getDataLayout().isBigEndian() && 5524 BaseTyInfo.first.getQuantity() < 16) 5525 Offset = 16 - BaseTyInfo.first.getQuantity(); 5526 5527 for (unsigned i = 0; i < NumMembers; ++i) { 5528 CharUnits BaseOffset = CharUnits::fromQuantity(16 * i + Offset); 5529 Address LoadAddr = 5530 CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, BaseOffset); 5531 LoadAddr = CGF.Builder.CreateElementBitCast(LoadAddr, BaseTy); 5532 5533 Address StoreAddr = CGF.Builder.CreateConstArrayGEP(Tmp, i); 5534 5535 llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr); 5536 CGF.Builder.CreateStore(Elem, StoreAddr); 5537 } 5538 5539 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, MemTy); 5540 } else { 5541 // Otherwise the object is contiguous in memory. 5542 5543 // It might be right-aligned in its slot. 5544 CharUnits SlotSize = BaseAddr.getAlignment(); 5545 if (CGF.CGM.getDataLayout().isBigEndian() && !IsIndirect && 5546 (IsHFA || !isAggregateTypeForABI(Ty)) && 5547 TySize < SlotSize) { 5548 CharUnits Offset = SlotSize - TySize; 5549 BaseAddr = CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, Offset); 5550 } 5551 5552 RegAddr = CGF.Builder.CreateElementBitCast(BaseAddr, MemTy); 5553 } 5554 5555 CGF.EmitBranch(ContBlock); 5556 5557 //======================================= 5558 // Argument was on the stack 5559 //======================================= 5560 CGF.EmitBlock(OnStackBlock); 5561 5562 Address stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "stack_p"); 5563 llvm::Value *OnStackPtr = CGF.Builder.CreateLoad(stack_p, "stack"); 5564 5565 // Again, stack arguments may need realignment. In this case both integer and 5566 // floating-point ones might be affected. 5567 if (!IsIndirect && TyAlign.getQuantity() > 8) { 5568 int Align = TyAlign.getQuantity(); 5569 5570 OnStackPtr = CGF.Builder.CreatePtrToInt(OnStackPtr, CGF.Int64Ty); 5571 5572 OnStackPtr = CGF.Builder.CreateAdd( 5573 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1), 5574 "align_stack"); 5575 OnStackPtr = CGF.Builder.CreateAnd( 5576 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, -Align), 5577 "align_stack"); 5578 5579 OnStackPtr = CGF.Builder.CreateIntToPtr(OnStackPtr, CGF.Int8PtrTy); 5580 } 5581 Address OnStackAddr(OnStackPtr, 5582 std::max(CharUnits::fromQuantity(8), TyAlign)); 5583 5584 // All stack slots are multiples of 8 bytes. 5585 CharUnits StackSlotSize = CharUnits::fromQuantity(8); 5586 CharUnits StackSize; 5587 if (IsIndirect) 5588 StackSize = StackSlotSize; 5589 else 5590 StackSize = TySize.alignTo(StackSlotSize); 5591 5592 llvm::Value *StackSizeC = CGF.Builder.getSize(StackSize); 5593 llvm::Value *NewStack = 5594 CGF.Builder.CreateInBoundsGEP(OnStackPtr, StackSizeC, "new_stack"); 5595 5596 // Write the new value of __stack for the next call to va_arg 5597 CGF.Builder.CreateStore(NewStack, stack_p); 5598 5599 if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) && 5600 TySize < StackSlotSize) { 5601 CharUnits Offset = StackSlotSize - TySize; 5602 OnStackAddr = CGF.Builder.CreateConstInBoundsByteGEP(OnStackAddr, Offset); 5603 } 5604 5605 OnStackAddr = CGF.Builder.CreateElementBitCast(OnStackAddr, MemTy); 5606 5607 CGF.EmitBranch(ContBlock); 5608 5609 //======================================= 5610 // Tidy up 5611 //======================================= 5612 CGF.EmitBlock(ContBlock); 5613 5614 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, 5615 OnStackAddr, OnStackBlock, "vaargs.addr"); 5616 5617 if (IsIndirect) 5618 return Address(CGF.Builder.CreateLoad(ResAddr, "vaarg.addr"), 5619 TyAlign); 5620 5621 return ResAddr; 5622 } 5623 5624 Address AArch64ABIInfo::EmitDarwinVAArg(Address VAListAddr, QualType Ty, 5625 CodeGenFunction &CGF) const { 5626 // The backend's lowering doesn't support va_arg for aggregates or 5627 // illegal vector types. Lower VAArg here for these cases and use 5628 // the LLVM va_arg instruction for everything else. 5629 if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty)) 5630 return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect()); 5631 5632 uint64_t PointerSize = getTarget().getPointerWidth(0) / 8; 5633 CharUnits SlotSize = CharUnits::fromQuantity(PointerSize); 5634 5635 // Empty records are ignored for parameter passing purposes. 5636 if (isEmptyRecord(getContext(), Ty, true)) { 5637 Address Addr(CGF.Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize); 5638 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty)); 5639 return Addr; 5640 } 5641 5642 // The size of the actual thing passed, which might end up just 5643 // being a pointer for indirect types. 5644 auto TyInfo = getContext().getTypeInfoInChars(Ty); 5645 5646 // Arguments bigger than 16 bytes which aren't homogeneous 5647 // aggregates should be passed indirectly. 5648 bool IsIndirect = false; 5649 if (TyInfo.first.getQuantity() > 16) { 5650 const Type *Base = nullptr; 5651 uint64_t Members = 0; 5652 IsIndirect = !isHomogeneousAggregate(Ty, Base, Members); 5653 } 5654 5655 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, 5656 TyInfo, SlotSize, /*AllowHigherAlign*/ true); 5657 } 5658 5659 Address AArch64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr, 5660 QualType Ty) const { 5661 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false, 5662 CGF.getContext().getTypeInfoInChars(Ty), 5663 CharUnits::fromQuantity(8), 5664 /*allowHigherAlign*/ false); 5665 } 5666 5667 //===----------------------------------------------------------------------===// 5668 // ARM ABI Implementation 5669 //===----------------------------------------------------------------------===// 5670 5671 namespace { 5672 5673 class ARMABIInfo : public SwiftABIInfo { 5674 public: 5675 enum ABIKind { 5676 APCS = 0, 5677 AAPCS = 1, 5678 AAPCS_VFP = 2, 5679 AAPCS16_VFP = 3, 5680 }; 5681 5682 private: 5683 ABIKind Kind; 5684 5685 public: 5686 ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind) 5687 : SwiftABIInfo(CGT), Kind(_Kind) { 5688 setCCs(); 5689 } 5690 5691 bool isEABI() const { 5692 switch (getTarget().getTriple().getEnvironment()) { 5693 case llvm::Triple::Android: 5694 case llvm::Triple::EABI: 5695 case llvm::Triple::EABIHF: 5696 case llvm::Triple::GNUEABI: 5697 case llvm::Triple::GNUEABIHF: 5698 case llvm::Triple::MuslEABI: 5699 case llvm::Triple::MuslEABIHF: 5700 return true; 5701 default: 5702 return false; 5703 } 5704 } 5705 5706 bool isEABIHF() const { 5707 switch (getTarget().getTriple().getEnvironment()) { 5708 case llvm::Triple::EABIHF: 5709 case llvm::Triple::GNUEABIHF: 5710 case llvm::Triple::MuslEABIHF: 5711 return true; 5712 default: 5713 return false; 5714 } 5715 } 5716 5717 ABIKind getABIKind() const { return Kind; } 5718 5719 private: 5720 ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic, 5721 unsigned functionCallConv) const; 5722 ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic, 5723 unsigned functionCallConv) const; 5724 ABIArgInfo classifyHomogeneousAggregate(QualType Ty, const Type *Base, 5725 uint64_t Members) const; 5726 ABIArgInfo coerceIllegalVector(QualType Ty) const; 5727 bool isIllegalVectorType(QualType Ty) const; 5728 bool containsAnyFP16Vectors(QualType Ty) const; 5729 5730 bool isHomogeneousAggregateBaseType(QualType Ty) const override; 5731 bool isHomogeneousAggregateSmallEnough(const Type *Ty, 5732 uint64_t Members) const override; 5733 5734 bool isEffectivelyAAPCS_VFP(unsigned callConvention, bool acceptHalf) const; 5735 5736 void computeInfo(CGFunctionInfo &FI) const override; 5737 5738 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 5739 QualType Ty) const override; 5740 5741 llvm::CallingConv::ID getLLVMDefaultCC() const; 5742 llvm::CallingConv::ID getABIDefaultCC() const; 5743 void setCCs(); 5744 5745 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars, 5746 bool asReturnValue) const override { 5747 return occupiesMoreThan(CGT, scalars, /*total*/ 4); 5748 } 5749 bool isSwiftErrorInRegister() const override { 5750 return true; 5751 } 5752 bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy, 5753 unsigned elts) const override; 5754 }; 5755 5756 class ARMTargetCodeGenInfo : public TargetCodeGenInfo { 5757 public: 5758 ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K) 5759 :TargetCodeGenInfo(new ARMABIInfo(CGT, K)) {} 5760 5761 const ARMABIInfo &getABIInfo() const { 5762 return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo()); 5763 } 5764 5765 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 5766 return 13; 5767 } 5768 5769 StringRef getARCRetainAutoreleasedReturnValueMarker() const override { 5770 return "mov\tr7, r7\t\t// marker for objc_retainAutoreleaseReturnValue"; 5771 } 5772 5773 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 5774 llvm::Value *Address) const override { 5775 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4); 5776 5777 // 0-15 are the 16 integer registers. 5778 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15); 5779 return false; 5780 } 5781 5782 unsigned getSizeOfUnwindException() const override { 5783 if (getABIInfo().isEABI()) return 88; 5784 return TargetCodeGenInfo::getSizeOfUnwindException(); 5785 } 5786 5787 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 5788 CodeGen::CodeGenModule &CGM) const override { 5789 if (GV->isDeclaration()) 5790 return; 5791 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D); 5792 if (!FD) 5793 return; 5794 5795 const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>(); 5796 if (!Attr) 5797 return; 5798 5799 const char *Kind; 5800 switch (Attr->getInterrupt()) { 5801 case ARMInterruptAttr::Generic: Kind = ""; break; 5802 case ARMInterruptAttr::IRQ: Kind = "IRQ"; break; 5803 case ARMInterruptAttr::FIQ: Kind = "FIQ"; break; 5804 case ARMInterruptAttr::SWI: Kind = "SWI"; break; 5805 case ARMInterruptAttr::ABORT: Kind = "ABORT"; break; 5806 case ARMInterruptAttr::UNDEF: Kind = "UNDEF"; break; 5807 } 5808 5809 llvm::Function *Fn = cast<llvm::Function>(GV); 5810 5811 Fn->addFnAttr("interrupt", Kind); 5812 5813 ARMABIInfo::ABIKind ABI = cast<ARMABIInfo>(getABIInfo()).getABIKind(); 5814 if (ABI == ARMABIInfo::APCS) 5815 return; 5816 5817 // AAPCS guarantees that sp will be 8-byte aligned on any public interface, 5818 // however this is not necessarily true on taking any interrupt. Instruct 5819 // the backend to perform a realignment as part of the function prologue. 5820 llvm::AttrBuilder B; 5821 B.addStackAlignmentAttr(8); 5822 Fn->addAttributes(llvm::AttributeList::FunctionIndex, B); 5823 } 5824 }; 5825 5826 class WindowsARMTargetCodeGenInfo : public ARMTargetCodeGenInfo { 5827 public: 5828 WindowsARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K) 5829 : ARMTargetCodeGenInfo(CGT, K) {} 5830 5831 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 5832 CodeGen::CodeGenModule &CGM) const override; 5833 5834 void getDependentLibraryOption(llvm::StringRef Lib, 5835 llvm::SmallString<24> &Opt) const override { 5836 Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib); 5837 } 5838 5839 void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value, 5840 llvm::SmallString<32> &Opt) const override { 5841 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\""; 5842 } 5843 }; 5844 5845 void WindowsARMTargetCodeGenInfo::setTargetAttributes( 5846 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const { 5847 ARMTargetCodeGenInfo::setTargetAttributes(D, GV, CGM); 5848 if (GV->isDeclaration()) 5849 return; 5850 addStackProbeTargetAttributes(D, GV, CGM); 5851 } 5852 } 5853 5854 void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const { 5855 if (!::classifyReturnType(getCXXABI(), FI, *this)) 5856 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), FI.isVariadic(), 5857 FI.getCallingConvention()); 5858 5859 for (auto &I : FI.arguments()) 5860 I.info = classifyArgumentType(I.type, FI.isVariadic(), 5861 FI.getCallingConvention()); 5862 5863 5864 // Always honor user-specified calling convention. 5865 if (FI.getCallingConvention() != llvm::CallingConv::C) 5866 return; 5867 5868 llvm::CallingConv::ID cc = getRuntimeCC(); 5869 if (cc != llvm::CallingConv::C) 5870 FI.setEffectiveCallingConvention(cc); 5871 } 5872 5873 /// Return the default calling convention that LLVM will use. 5874 llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const { 5875 // The default calling convention that LLVM will infer. 5876 if (isEABIHF() || getTarget().getTriple().isWatchABI()) 5877 return llvm::CallingConv::ARM_AAPCS_VFP; 5878 else if (isEABI()) 5879 return llvm::CallingConv::ARM_AAPCS; 5880 else 5881 return llvm::CallingConv::ARM_APCS; 5882 } 5883 5884 /// Return the calling convention that our ABI would like us to use 5885 /// as the C calling convention. 5886 llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const { 5887 switch (getABIKind()) { 5888 case APCS: return llvm::CallingConv::ARM_APCS; 5889 case AAPCS: return llvm::CallingConv::ARM_AAPCS; 5890 case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP; 5891 case AAPCS16_VFP: return llvm::CallingConv::ARM_AAPCS_VFP; 5892 } 5893 llvm_unreachable("bad ABI kind"); 5894 } 5895 5896 void ARMABIInfo::setCCs() { 5897 assert(getRuntimeCC() == llvm::CallingConv::C); 5898 5899 // Don't muddy up the IR with a ton of explicit annotations if 5900 // they'd just match what LLVM will infer from the triple. 5901 llvm::CallingConv::ID abiCC = getABIDefaultCC(); 5902 if (abiCC != getLLVMDefaultCC()) 5903 RuntimeCC = abiCC; 5904 } 5905 5906 ABIArgInfo ARMABIInfo::coerceIllegalVector(QualType Ty) const { 5907 uint64_t Size = getContext().getTypeSize(Ty); 5908 if (Size <= 32) { 5909 llvm::Type *ResType = 5910 llvm::Type::getInt32Ty(getVMContext()); 5911 return ABIArgInfo::getDirect(ResType); 5912 } 5913 if (Size == 64 || Size == 128) { 5914 llvm::Type *ResType = llvm::VectorType::get( 5915 llvm::Type::getInt32Ty(getVMContext()), Size / 32); 5916 return ABIArgInfo::getDirect(ResType); 5917 } 5918 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 5919 } 5920 5921 ABIArgInfo ARMABIInfo::classifyHomogeneousAggregate(QualType Ty, 5922 const Type *Base, 5923 uint64_t Members) const { 5924 assert(Base && "Base class should be set for homogeneous aggregate"); 5925 // Base can be a floating-point or a vector. 5926 if (const VectorType *VT = Base->getAs<VectorType>()) { 5927 // FP16 vectors should be converted to integer vectors 5928 if (!getTarget().hasLegalHalfType() && containsAnyFP16Vectors(Ty)) { 5929 uint64_t Size = getContext().getTypeSize(VT); 5930 llvm::Type *NewVecTy = llvm::VectorType::get( 5931 llvm::Type::getInt32Ty(getVMContext()), Size / 32); 5932 llvm::Type *Ty = llvm::ArrayType::get(NewVecTy, Members); 5933 return ABIArgInfo::getDirect(Ty, 0, nullptr, false); 5934 } 5935 } 5936 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false); 5937 } 5938 5939 ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty, bool isVariadic, 5940 unsigned functionCallConv) const { 5941 // 6.1.2.1 The following argument types are VFP CPRCs: 5942 // A single-precision floating-point type (including promoted 5943 // half-precision types); A double-precision floating-point type; 5944 // A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate 5945 // with a Base Type of a single- or double-precision floating-point type, 5946 // 64-bit containerized vectors or 128-bit containerized vectors with one 5947 // to four Elements. 5948 // Variadic functions should always marshal to the base standard. 5949 bool IsAAPCS_VFP = 5950 !isVariadic && isEffectivelyAAPCS_VFP(functionCallConv, /* AAPCS16 */ false); 5951 5952 Ty = useFirstFieldIfTransparentUnion(Ty); 5953 5954 // Handle illegal vector types here. 5955 if (isIllegalVectorType(Ty)) 5956 return coerceIllegalVector(Ty); 5957 5958 // _Float16 and __fp16 get passed as if it were an int or float, but with 5959 // the top 16 bits unspecified. This is not done for OpenCL as it handles the 5960 // half type natively, and does not need to interwork with AAPCS code. 5961 if ((Ty->isFloat16Type() || Ty->isHalfType()) && 5962 !getContext().getLangOpts().NativeHalfArgsAndReturns) { 5963 llvm::Type *ResType = IsAAPCS_VFP ? 5964 llvm::Type::getFloatTy(getVMContext()) : 5965 llvm::Type::getInt32Ty(getVMContext()); 5966 return ABIArgInfo::getDirect(ResType); 5967 } 5968 5969 if (!isAggregateTypeForABI(Ty)) { 5970 // Treat an enum type as its underlying type. 5971 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) { 5972 Ty = EnumTy->getDecl()->getIntegerType(); 5973 } 5974 5975 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty) 5976 : ABIArgInfo::getDirect()); 5977 } 5978 5979 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) { 5980 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 5981 } 5982 5983 // Ignore empty records. 5984 if (isEmptyRecord(getContext(), Ty, true)) 5985 return ABIArgInfo::getIgnore(); 5986 5987 if (IsAAPCS_VFP) { 5988 // Homogeneous Aggregates need to be expanded when we can fit the aggregate 5989 // into VFP registers. 5990 const Type *Base = nullptr; 5991 uint64_t Members = 0; 5992 if (isHomogeneousAggregate(Ty, Base, Members)) 5993 return classifyHomogeneousAggregate(Ty, Base, Members); 5994 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) { 5995 // WatchOS does have homogeneous aggregates. Note that we intentionally use 5996 // this convention even for a variadic function: the backend will use GPRs 5997 // if needed. 5998 const Type *Base = nullptr; 5999 uint64_t Members = 0; 6000 if (isHomogeneousAggregate(Ty, Base, Members)) { 6001 assert(Base && Members <= 4 && "unexpected homogeneous aggregate"); 6002 llvm::Type *Ty = 6003 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members); 6004 return ABIArgInfo::getDirect(Ty, 0, nullptr, false); 6005 } 6006 } 6007 6008 if (getABIKind() == ARMABIInfo::AAPCS16_VFP && 6009 getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(16)) { 6010 // WatchOS is adopting the 64-bit AAPCS rule on composite types: if they're 6011 // bigger than 128-bits, they get placed in space allocated by the caller, 6012 // and a pointer is passed. 6013 return ABIArgInfo::getIndirect( 6014 CharUnits::fromQuantity(getContext().getTypeAlign(Ty) / 8), false); 6015 } 6016 6017 // Support byval for ARM. 6018 // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at 6019 // most 8-byte. We realign the indirect argument if type alignment is bigger 6020 // than ABI alignment. 6021 uint64_t ABIAlign = 4; 6022 uint64_t TyAlign; 6023 if (getABIKind() == ARMABIInfo::AAPCS_VFP || 6024 getABIKind() == ARMABIInfo::AAPCS) { 6025 TyAlign = getContext().getTypeUnadjustedAlignInChars(Ty).getQuantity(); 6026 ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8); 6027 } else { 6028 TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity(); 6029 } 6030 if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) { 6031 assert(getABIKind() != ARMABIInfo::AAPCS16_VFP && "unexpected byval"); 6032 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign), 6033 /*ByVal=*/true, 6034 /*Realign=*/TyAlign > ABIAlign); 6035 } 6036 6037 // On RenderScript, coerce Aggregates <= 64 bytes to an integer array of 6038 // same size and alignment. 6039 if (getTarget().isRenderScriptTarget()) { 6040 return coerceToIntArray(Ty, getContext(), getVMContext()); 6041 } 6042 6043 // Otherwise, pass by coercing to a structure of the appropriate size. 6044 llvm::Type* ElemTy; 6045 unsigned SizeRegs; 6046 // FIXME: Try to match the types of the arguments more accurately where 6047 // we can. 6048 if (TyAlign <= 4) { 6049 ElemTy = llvm::Type::getInt32Ty(getVMContext()); 6050 SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32; 6051 } else { 6052 ElemTy = llvm::Type::getInt64Ty(getVMContext()); 6053 SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64; 6054 } 6055 6056 return ABIArgInfo::getDirect(llvm::ArrayType::get(ElemTy, SizeRegs)); 6057 } 6058 6059 static bool isIntegerLikeType(QualType Ty, ASTContext &Context, 6060 llvm::LLVMContext &VMContext) { 6061 // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure 6062 // is called integer-like if its size is less than or equal to one word, and 6063 // the offset of each of its addressable sub-fields is zero. 6064 6065 uint64_t Size = Context.getTypeSize(Ty); 6066 6067 // Check that the type fits in a word. 6068 if (Size > 32) 6069 return false; 6070 6071 // FIXME: Handle vector types! 6072 if (Ty->isVectorType()) 6073 return false; 6074 6075 // Float types are never treated as "integer like". 6076 if (Ty->isRealFloatingType()) 6077 return false; 6078 6079 // If this is a builtin or pointer type then it is ok. 6080 if (Ty->getAs<BuiltinType>() || Ty->isPointerType()) 6081 return true; 6082 6083 // Small complex integer types are "integer like". 6084 if (const ComplexType *CT = Ty->getAs<ComplexType>()) 6085 return isIntegerLikeType(CT->getElementType(), Context, VMContext); 6086 6087 // Single element and zero sized arrays should be allowed, by the definition 6088 // above, but they are not. 6089 6090 // Otherwise, it must be a record type. 6091 const RecordType *RT = Ty->getAs<RecordType>(); 6092 if (!RT) return false; 6093 6094 // Ignore records with flexible arrays. 6095 const RecordDecl *RD = RT->getDecl(); 6096 if (RD->hasFlexibleArrayMember()) 6097 return false; 6098 6099 // Check that all sub-fields are at offset 0, and are themselves "integer 6100 // like". 6101 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); 6102 6103 bool HadField = false; 6104 unsigned idx = 0; 6105 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 6106 i != e; ++i, ++idx) { 6107 const FieldDecl *FD = *i; 6108 6109 // Bit-fields are not addressable, we only need to verify they are "integer 6110 // like". We still have to disallow a subsequent non-bitfield, for example: 6111 // struct { int : 0; int x } 6112 // is non-integer like according to gcc. 6113 if (FD->isBitField()) { 6114 if (!RD->isUnion()) 6115 HadField = true; 6116 6117 if (!isIntegerLikeType(FD->getType(), Context, VMContext)) 6118 return false; 6119 6120 continue; 6121 } 6122 6123 // Check if this field is at offset 0. 6124 if (Layout.getFieldOffset(idx) != 0) 6125 return false; 6126 6127 if (!isIntegerLikeType(FD->getType(), Context, VMContext)) 6128 return false; 6129 6130 // Only allow at most one field in a structure. This doesn't match the 6131 // wording above, but follows gcc in situations with a field following an 6132 // empty structure. 6133 if (!RD->isUnion()) { 6134 if (HadField) 6135 return false; 6136 6137 HadField = true; 6138 } 6139 } 6140 6141 return true; 6142 } 6143 6144 ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy, bool isVariadic, 6145 unsigned functionCallConv) const { 6146 6147 // Variadic functions should always marshal to the base standard. 6148 bool IsAAPCS_VFP = 6149 !isVariadic && isEffectivelyAAPCS_VFP(functionCallConv, /* AAPCS16 */ true); 6150 6151 if (RetTy->isVoidType()) 6152 return ABIArgInfo::getIgnore(); 6153 6154 if (const VectorType *VT = RetTy->getAs<VectorType>()) { 6155 // Large vector types should be returned via memory. 6156 if (getContext().getTypeSize(RetTy) > 128) 6157 return getNaturalAlignIndirect(RetTy); 6158 // FP16 vectors should be converted to integer vectors 6159 if (!getTarget().hasLegalHalfType() && 6160 (VT->getElementType()->isFloat16Type() || 6161 VT->getElementType()->isHalfType())) 6162 return coerceIllegalVector(RetTy); 6163 } 6164 6165 // _Float16 and __fp16 get returned as if it were an int or float, but with 6166 // the top 16 bits unspecified. This is not done for OpenCL as it handles the 6167 // half type natively, and does not need to interwork with AAPCS code. 6168 if ((RetTy->isFloat16Type() || RetTy->isHalfType()) && 6169 !getContext().getLangOpts().NativeHalfArgsAndReturns) { 6170 llvm::Type *ResType = IsAAPCS_VFP ? 6171 llvm::Type::getFloatTy(getVMContext()) : 6172 llvm::Type::getInt32Ty(getVMContext()); 6173 return ABIArgInfo::getDirect(ResType); 6174 } 6175 6176 if (!isAggregateTypeForABI(RetTy)) { 6177 // Treat an enum type as its underlying type. 6178 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 6179 RetTy = EnumTy->getDecl()->getIntegerType(); 6180 6181 return RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy) 6182 : ABIArgInfo::getDirect(); 6183 } 6184 6185 // Are we following APCS? 6186 if (getABIKind() == APCS) { 6187 if (isEmptyRecord(getContext(), RetTy, false)) 6188 return ABIArgInfo::getIgnore(); 6189 6190 // Complex types are all returned as packed integers. 6191 // 6192 // FIXME: Consider using 2 x vector types if the back end handles them 6193 // correctly. 6194 if (RetTy->isAnyComplexType()) 6195 return ABIArgInfo::getDirect(llvm::IntegerType::get( 6196 getVMContext(), getContext().getTypeSize(RetTy))); 6197 6198 // Integer like structures are returned in r0. 6199 if (isIntegerLikeType(RetTy, getContext(), getVMContext())) { 6200 // Return in the smallest viable integer type. 6201 uint64_t Size = getContext().getTypeSize(RetTy); 6202 if (Size <= 8) 6203 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext())); 6204 if (Size <= 16) 6205 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext())); 6206 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext())); 6207 } 6208 6209 // Otherwise return in memory. 6210 return getNaturalAlignIndirect(RetTy); 6211 } 6212 6213 // Otherwise this is an AAPCS variant. 6214 6215 if (isEmptyRecord(getContext(), RetTy, true)) 6216 return ABIArgInfo::getIgnore(); 6217 6218 // Check for homogeneous aggregates with AAPCS-VFP. 6219 if (IsAAPCS_VFP) { 6220 const Type *Base = nullptr; 6221 uint64_t Members = 0; 6222 if (isHomogeneousAggregate(RetTy, Base, Members)) 6223 return classifyHomogeneousAggregate(RetTy, Base, Members); 6224 } 6225 6226 // Aggregates <= 4 bytes are returned in r0; other aggregates 6227 // are returned indirectly. 6228 uint64_t Size = getContext().getTypeSize(RetTy); 6229 if (Size <= 32) { 6230 // On RenderScript, coerce Aggregates <= 4 bytes to an integer array of 6231 // same size and alignment. 6232 if (getTarget().isRenderScriptTarget()) { 6233 return coerceToIntArray(RetTy, getContext(), getVMContext()); 6234 } 6235 if (getDataLayout().isBigEndian()) 6236 // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4) 6237 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext())); 6238 6239 // Return in the smallest viable integer type. 6240 if (Size <= 8) 6241 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext())); 6242 if (Size <= 16) 6243 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext())); 6244 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext())); 6245 } else if (Size <= 128 && getABIKind() == AAPCS16_VFP) { 6246 llvm::Type *Int32Ty = llvm::Type::getInt32Ty(getVMContext()); 6247 llvm::Type *CoerceTy = 6248 llvm::ArrayType::get(Int32Ty, llvm::alignTo(Size, 32) / 32); 6249 return ABIArgInfo::getDirect(CoerceTy); 6250 } 6251 6252 return getNaturalAlignIndirect(RetTy); 6253 } 6254 6255 /// isIllegalVector - check whether Ty is an illegal vector type. 6256 bool ARMABIInfo::isIllegalVectorType(QualType Ty) const { 6257 if (const VectorType *VT = Ty->getAs<VectorType> ()) { 6258 // On targets that don't support FP16, FP16 is expanded into float, and we 6259 // don't want the ABI to depend on whether or not FP16 is supported in 6260 // hardware. Thus return false to coerce FP16 vectors into integer vectors. 6261 if (!getTarget().hasLegalHalfType() && 6262 (VT->getElementType()->isFloat16Type() || 6263 VT->getElementType()->isHalfType())) 6264 return true; 6265 if (isAndroid()) { 6266 // Android shipped using Clang 3.1, which supported a slightly different 6267 // vector ABI. The primary differences were that 3-element vector types 6268 // were legal, and so were sub 32-bit vectors (i.e. <2 x i8>). This path 6269 // accepts that legacy behavior for Android only. 6270 // Check whether VT is legal. 6271 unsigned NumElements = VT->getNumElements(); 6272 // NumElements should be power of 2 or equal to 3. 6273 if (!llvm::isPowerOf2_32(NumElements) && NumElements != 3) 6274 return true; 6275 } else { 6276 // Check whether VT is legal. 6277 unsigned NumElements = VT->getNumElements(); 6278 uint64_t Size = getContext().getTypeSize(VT); 6279 // NumElements should be power of 2. 6280 if (!llvm::isPowerOf2_32(NumElements)) 6281 return true; 6282 // Size should be greater than 32 bits. 6283 return Size <= 32; 6284 } 6285 } 6286 return false; 6287 } 6288 6289 /// Return true if a type contains any 16-bit floating point vectors 6290 bool ARMABIInfo::containsAnyFP16Vectors(QualType Ty) const { 6291 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) { 6292 uint64_t NElements = AT->getSize().getZExtValue(); 6293 if (NElements == 0) 6294 return false; 6295 return containsAnyFP16Vectors(AT->getElementType()); 6296 } else if (const RecordType *RT = Ty->getAs<RecordType>()) { 6297 const RecordDecl *RD = RT->getDecl(); 6298 6299 // If this is a C++ record, check the bases first. 6300 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 6301 if (llvm::any_of(CXXRD->bases(), [this](const CXXBaseSpecifier &B) { 6302 return containsAnyFP16Vectors(B.getType()); 6303 })) 6304 return true; 6305 6306 if (llvm::any_of(RD->fields(), [this](FieldDecl *FD) { 6307 return FD && containsAnyFP16Vectors(FD->getType()); 6308 })) 6309 return true; 6310 6311 return false; 6312 } else { 6313 if (const VectorType *VT = Ty->getAs<VectorType>()) 6314 return (VT->getElementType()->isFloat16Type() || 6315 VT->getElementType()->isHalfType()); 6316 return false; 6317 } 6318 } 6319 6320 bool ARMABIInfo::isLegalVectorTypeForSwift(CharUnits vectorSize, 6321 llvm::Type *eltTy, 6322 unsigned numElts) const { 6323 if (!llvm::isPowerOf2_32(numElts)) 6324 return false; 6325 unsigned size = getDataLayout().getTypeStoreSizeInBits(eltTy); 6326 if (size > 64) 6327 return false; 6328 if (vectorSize.getQuantity() != 8 && 6329 (vectorSize.getQuantity() != 16 || numElts == 1)) 6330 return false; 6331 return true; 6332 } 6333 6334 bool ARMABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const { 6335 // Homogeneous aggregates for AAPCS-VFP must have base types of float, 6336 // double, or 64-bit or 128-bit vectors. 6337 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) { 6338 if (BT->getKind() == BuiltinType::Float || 6339 BT->getKind() == BuiltinType::Double || 6340 BT->getKind() == BuiltinType::LongDouble) 6341 return true; 6342 } else if (const VectorType *VT = Ty->getAs<VectorType>()) { 6343 unsigned VecSize = getContext().getTypeSize(VT); 6344 if (VecSize == 64 || VecSize == 128) 6345 return true; 6346 } 6347 return false; 6348 } 6349 6350 bool ARMABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base, 6351 uint64_t Members) const { 6352 return Members <= 4; 6353 } 6354 6355 bool ARMABIInfo::isEffectivelyAAPCS_VFP(unsigned callConvention, 6356 bool acceptHalf) const { 6357 // Give precedence to user-specified calling conventions. 6358 if (callConvention != llvm::CallingConv::C) 6359 return (callConvention == llvm::CallingConv::ARM_AAPCS_VFP); 6360 else 6361 return (getABIKind() == AAPCS_VFP) || 6362 (acceptHalf && (getABIKind() == AAPCS16_VFP)); 6363 } 6364 6365 Address ARMABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 6366 QualType Ty) const { 6367 CharUnits SlotSize = CharUnits::fromQuantity(4); 6368 6369 // Empty records are ignored for parameter passing purposes. 6370 if (isEmptyRecord(getContext(), Ty, true)) { 6371 Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize); 6372 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty)); 6373 return Addr; 6374 } 6375 6376 CharUnits TySize = getContext().getTypeSizeInChars(Ty); 6377 CharUnits TyAlignForABI = getContext().getTypeUnadjustedAlignInChars(Ty); 6378 6379 // Use indirect if size of the illegal vector is bigger than 16 bytes. 6380 bool IsIndirect = false; 6381 const Type *Base = nullptr; 6382 uint64_t Members = 0; 6383 if (TySize > CharUnits::fromQuantity(16) && isIllegalVectorType(Ty)) { 6384 IsIndirect = true; 6385 6386 // ARMv7k passes structs bigger than 16 bytes indirectly, in space 6387 // allocated by the caller. 6388 } else if (TySize > CharUnits::fromQuantity(16) && 6389 getABIKind() == ARMABIInfo::AAPCS16_VFP && 6390 !isHomogeneousAggregate(Ty, Base, Members)) { 6391 IsIndirect = true; 6392 6393 // Otherwise, bound the type's ABI alignment. 6394 // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for 6395 // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte. 6396 // Our callers should be prepared to handle an under-aligned address. 6397 } else if (getABIKind() == ARMABIInfo::AAPCS_VFP || 6398 getABIKind() == ARMABIInfo::AAPCS) { 6399 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4)); 6400 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(8)); 6401 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) { 6402 // ARMv7k allows type alignment up to 16 bytes. 6403 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4)); 6404 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(16)); 6405 } else { 6406 TyAlignForABI = CharUnits::fromQuantity(4); 6407 } 6408 6409 std::pair<CharUnits, CharUnits> TyInfo = { TySize, TyAlignForABI }; 6410 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TyInfo, 6411 SlotSize, /*AllowHigherAlign*/ true); 6412 } 6413 6414 //===----------------------------------------------------------------------===// 6415 // NVPTX ABI Implementation 6416 //===----------------------------------------------------------------------===// 6417 6418 namespace { 6419 6420 class NVPTXTargetCodeGenInfo; 6421 6422 class NVPTXABIInfo : public ABIInfo { 6423 NVPTXTargetCodeGenInfo &CGInfo; 6424 6425 public: 6426 NVPTXABIInfo(CodeGenTypes &CGT, NVPTXTargetCodeGenInfo &Info) 6427 : ABIInfo(CGT), CGInfo(Info) {} 6428 6429 ABIArgInfo classifyReturnType(QualType RetTy) const; 6430 ABIArgInfo classifyArgumentType(QualType Ty) const; 6431 6432 void computeInfo(CGFunctionInfo &FI) const override; 6433 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 6434 QualType Ty) const override; 6435 }; 6436 6437 class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo { 6438 public: 6439 NVPTXTargetCodeGenInfo(CodeGenTypes &CGT) 6440 : TargetCodeGenInfo(new NVPTXABIInfo(CGT, *this)) {} 6441 6442 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 6443 CodeGen::CodeGenModule &M) const override; 6444 bool shouldEmitStaticExternCAliases() const override; 6445 6446 llvm::Type *getCUDADeviceBuiltinSurfaceDeviceType() const override { 6447 // On the device side, surface reference is represented as an object handle 6448 // in 64-bit integer. 6449 return llvm::Type::getInt64Ty(getABIInfo().getVMContext()); 6450 } 6451 6452 llvm::Type *getCUDADeviceBuiltinTextureDeviceType() const override { 6453 // On the device side, texture reference is represented as an object handle 6454 // in 64-bit integer. 6455 return llvm::Type::getInt64Ty(getABIInfo().getVMContext()); 6456 } 6457 6458 bool emitCUDADeviceBuiltinSurfaceDeviceCopy(CodeGenFunction &CGF, LValue Dst, 6459 LValue Src) const override { 6460 emitBuiltinSurfTexDeviceCopy(CGF, Dst, Src); 6461 return true; 6462 } 6463 6464 bool emitCUDADeviceBuiltinTextureDeviceCopy(CodeGenFunction &CGF, LValue Dst, 6465 LValue Src) const override { 6466 emitBuiltinSurfTexDeviceCopy(CGF, Dst, Src); 6467 return true; 6468 } 6469 6470 private: 6471 // Adds a NamedMDNode with GV, Name, and Operand as operands, and adds the 6472 // resulting MDNode to the nvvm.annotations MDNode. 6473 static void addNVVMMetadata(llvm::GlobalValue *GV, StringRef Name, 6474 int Operand); 6475 6476 static void emitBuiltinSurfTexDeviceCopy(CodeGenFunction &CGF, LValue Dst, 6477 LValue Src) { 6478 llvm::Value *Handle = nullptr; 6479 llvm::Constant *C = 6480 llvm::dyn_cast<llvm::Constant>(Src.getAddress(CGF).getPointer()); 6481 // Lookup `addrspacecast` through the constant pointer if any. 6482 if (auto *ASC = llvm::dyn_cast_or_null<llvm::AddrSpaceCastOperator>(C)) 6483 C = llvm::cast<llvm::Constant>(ASC->getPointerOperand()); 6484 if (auto *GV = llvm::dyn_cast_or_null<llvm::GlobalVariable>(C)) { 6485 // Load the handle from the specific global variable using 6486 // `nvvm.texsurf.handle.internal` intrinsic. 6487 Handle = CGF.EmitRuntimeCall( 6488 CGF.CGM.getIntrinsic(llvm::Intrinsic::nvvm_texsurf_handle_internal, 6489 {GV->getType()}), 6490 {GV}, "texsurf_handle"); 6491 } else 6492 Handle = CGF.EmitLoadOfScalar(Src, SourceLocation()); 6493 CGF.EmitStoreOfScalar(Handle, Dst); 6494 } 6495 }; 6496 6497 /// Checks if the type is unsupported directly by the current target. 6498 static bool isUnsupportedType(ASTContext &Context, QualType T) { 6499 if (!Context.getTargetInfo().hasFloat16Type() && T->isFloat16Type()) 6500 return true; 6501 if (!Context.getTargetInfo().hasFloat128Type() && 6502 (T->isFloat128Type() || 6503 (T->isRealFloatingType() && Context.getTypeSize(T) == 128))) 6504 return true; 6505 if (!Context.getTargetInfo().hasInt128Type() && T->isIntegerType() && 6506 Context.getTypeSize(T) > 64) 6507 return true; 6508 if (const auto *AT = T->getAsArrayTypeUnsafe()) 6509 return isUnsupportedType(Context, AT->getElementType()); 6510 const auto *RT = T->getAs<RecordType>(); 6511 if (!RT) 6512 return false; 6513 const RecordDecl *RD = RT->getDecl(); 6514 6515 // If this is a C++ record, check the bases first. 6516 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 6517 for (const CXXBaseSpecifier &I : CXXRD->bases()) 6518 if (isUnsupportedType(Context, I.getType())) 6519 return true; 6520 6521 for (const FieldDecl *I : RD->fields()) 6522 if (isUnsupportedType(Context, I->getType())) 6523 return true; 6524 return false; 6525 } 6526 6527 /// Coerce the given type into an array with maximum allowed size of elements. 6528 static ABIArgInfo coerceToIntArrayWithLimit(QualType Ty, ASTContext &Context, 6529 llvm::LLVMContext &LLVMContext, 6530 unsigned MaxSize) { 6531 // Alignment and Size are measured in bits. 6532 const uint64_t Size = Context.getTypeSize(Ty); 6533 const uint64_t Alignment = Context.getTypeAlign(Ty); 6534 const unsigned Div = std::min<unsigned>(MaxSize, Alignment); 6535 llvm::Type *IntType = llvm::Type::getIntNTy(LLVMContext, Div); 6536 const uint64_t NumElements = (Size + Div - 1) / Div; 6537 return ABIArgInfo::getDirect(llvm::ArrayType::get(IntType, NumElements)); 6538 } 6539 6540 ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const { 6541 if (RetTy->isVoidType()) 6542 return ABIArgInfo::getIgnore(); 6543 6544 if (getContext().getLangOpts().OpenMP && 6545 getContext().getLangOpts().OpenMPIsDevice && 6546 isUnsupportedType(getContext(), RetTy)) 6547 return coerceToIntArrayWithLimit(RetTy, getContext(), getVMContext(), 64); 6548 6549 // note: this is different from default ABI 6550 if (!RetTy->isScalarType()) 6551 return ABIArgInfo::getDirect(); 6552 6553 // Treat an enum type as its underlying type. 6554 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 6555 RetTy = EnumTy->getDecl()->getIntegerType(); 6556 6557 return (RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy) 6558 : ABIArgInfo::getDirect()); 6559 } 6560 6561 ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const { 6562 // Treat an enum type as its underlying type. 6563 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 6564 Ty = EnumTy->getDecl()->getIntegerType(); 6565 6566 // Return aggregates type as indirect by value 6567 if (isAggregateTypeForABI(Ty)) { 6568 // Under CUDA device compilation, tex/surf builtin types are replaced with 6569 // object types and passed directly. 6570 if (getContext().getLangOpts().CUDAIsDevice) { 6571 if (Ty->isCUDADeviceBuiltinSurfaceType()) 6572 return ABIArgInfo::getDirect( 6573 CGInfo.getCUDADeviceBuiltinSurfaceDeviceType()); 6574 if (Ty->isCUDADeviceBuiltinTextureType()) 6575 return ABIArgInfo::getDirect( 6576 CGInfo.getCUDADeviceBuiltinTextureDeviceType()); 6577 } 6578 return getNaturalAlignIndirect(Ty, /* byval */ true); 6579 } 6580 6581 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty) 6582 : ABIArgInfo::getDirect()); 6583 } 6584 6585 void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const { 6586 if (!getCXXABI().classifyReturnType(FI)) 6587 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 6588 for (auto &I : FI.arguments()) 6589 I.info = classifyArgumentType(I.type); 6590 6591 // Always honor user-specified calling convention. 6592 if (FI.getCallingConvention() != llvm::CallingConv::C) 6593 return; 6594 6595 FI.setEffectiveCallingConvention(getRuntimeCC()); 6596 } 6597 6598 Address NVPTXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 6599 QualType Ty) const { 6600 llvm_unreachable("NVPTX does not support varargs"); 6601 } 6602 6603 void NVPTXTargetCodeGenInfo::setTargetAttributes( 6604 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const { 6605 if (GV->isDeclaration()) 6606 return; 6607 const VarDecl *VD = dyn_cast_or_null<VarDecl>(D); 6608 if (VD) { 6609 if (M.getLangOpts().CUDA) { 6610 if (VD->getType()->isCUDADeviceBuiltinSurfaceType()) 6611 addNVVMMetadata(GV, "surface", 1); 6612 else if (VD->getType()->isCUDADeviceBuiltinTextureType()) 6613 addNVVMMetadata(GV, "texture", 1); 6614 return; 6615 } 6616 } 6617 6618 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D); 6619 if (!FD) return; 6620 6621 llvm::Function *F = cast<llvm::Function>(GV); 6622 6623 // Perform special handling in OpenCL mode 6624 if (M.getLangOpts().OpenCL) { 6625 // Use OpenCL function attributes to check for kernel functions 6626 // By default, all functions are device functions 6627 if (FD->hasAttr<OpenCLKernelAttr>()) { 6628 // OpenCL __kernel functions get kernel metadata 6629 // Create !{<func-ref>, metadata !"kernel", i32 1} node 6630 addNVVMMetadata(F, "kernel", 1); 6631 // And kernel functions are not subject to inlining 6632 F->addFnAttr(llvm::Attribute::NoInline); 6633 } 6634 } 6635 6636 // Perform special handling in CUDA mode. 6637 if (M.getLangOpts().CUDA) { 6638 // CUDA __global__ functions get a kernel metadata entry. Since 6639 // __global__ functions cannot be called from the device, we do not 6640 // need to set the noinline attribute. 6641 if (FD->hasAttr<CUDAGlobalAttr>()) { 6642 // Create !{<func-ref>, metadata !"kernel", i32 1} node 6643 addNVVMMetadata(F, "kernel", 1); 6644 } 6645 if (CUDALaunchBoundsAttr *Attr = FD->getAttr<CUDALaunchBoundsAttr>()) { 6646 // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node 6647 llvm::APSInt MaxThreads(32); 6648 MaxThreads = Attr->getMaxThreads()->EvaluateKnownConstInt(M.getContext()); 6649 if (MaxThreads > 0) 6650 addNVVMMetadata(F, "maxntidx", MaxThreads.getExtValue()); 6651 6652 // min blocks is an optional argument for CUDALaunchBoundsAttr. If it was 6653 // not specified in __launch_bounds__ or if the user specified a 0 value, 6654 // we don't have to add a PTX directive. 6655 if (Attr->getMinBlocks()) { 6656 llvm::APSInt MinBlocks(32); 6657 MinBlocks = Attr->getMinBlocks()->EvaluateKnownConstInt(M.getContext()); 6658 if (MinBlocks > 0) 6659 // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node 6660 addNVVMMetadata(F, "minctasm", MinBlocks.getExtValue()); 6661 } 6662 } 6663 } 6664 } 6665 6666 void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::GlobalValue *GV, 6667 StringRef Name, int Operand) { 6668 llvm::Module *M = GV->getParent(); 6669 llvm::LLVMContext &Ctx = M->getContext(); 6670 6671 // Get "nvvm.annotations" metadata node 6672 llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations"); 6673 6674 llvm::Metadata *MDVals[] = { 6675 llvm::ConstantAsMetadata::get(GV), llvm::MDString::get(Ctx, Name), 6676 llvm::ConstantAsMetadata::get( 6677 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand))}; 6678 // Append metadata to nvvm.annotations 6679 MD->addOperand(llvm::MDNode::get(Ctx, MDVals)); 6680 } 6681 6682 bool NVPTXTargetCodeGenInfo::shouldEmitStaticExternCAliases() const { 6683 return false; 6684 } 6685 } 6686 6687 //===----------------------------------------------------------------------===// 6688 // SystemZ ABI Implementation 6689 //===----------------------------------------------------------------------===// 6690 6691 namespace { 6692 6693 class SystemZABIInfo : public SwiftABIInfo { 6694 bool HasVector; 6695 bool IsSoftFloatABI; 6696 6697 public: 6698 SystemZABIInfo(CodeGenTypes &CGT, bool HV, bool SF) 6699 : SwiftABIInfo(CGT), HasVector(HV), IsSoftFloatABI(SF) {} 6700 6701 bool isPromotableIntegerType(QualType Ty) const; 6702 bool isCompoundType(QualType Ty) const; 6703 bool isVectorArgumentType(QualType Ty) const; 6704 bool isFPArgumentType(QualType Ty) const; 6705 QualType GetSingleElementType(QualType Ty) const; 6706 6707 ABIArgInfo classifyReturnType(QualType RetTy) const; 6708 ABIArgInfo classifyArgumentType(QualType ArgTy) const; 6709 6710 void computeInfo(CGFunctionInfo &FI) const override { 6711 if (!getCXXABI().classifyReturnType(FI)) 6712 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 6713 for (auto &I : FI.arguments()) 6714 I.info = classifyArgumentType(I.type); 6715 } 6716 6717 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 6718 QualType Ty) const override; 6719 6720 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars, 6721 bool asReturnValue) const override { 6722 return occupiesMoreThan(CGT, scalars, /*total*/ 4); 6723 } 6724 bool isSwiftErrorInRegister() const override { 6725 return false; 6726 } 6727 }; 6728 6729 class SystemZTargetCodeGenInfo : public TargetCodeGenInfo { 6730 public: 6731 SystemZTargetCodeGenInfo(CodeGenTypes &CGT, bool HasVector, bool SoftFloatABI) 6732 : TargetCodeGenInfo(new SystemZABIInfo(CGT, HasVector, SoftFloatABI)) {} 6733 }; 6734 6735 } 6736 6737 bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const { 6738 // Treat an enum type as its underlying type. 6739 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 6740 Ty = EnumTy->getDecl()->getIntegerType(); 6741 6742 // Promotable integer types are required to be promoted by the ABI. 6743 if (Ty->isPromotableIntegerType()) 6744 return true; 6745 6746 // 32-bit values must also be promoted. 6747 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) 6748 switch (BT->getKind()) { 6749 case BuiltinType::Int: 6750 case BuiltinType::UInt: 6751 return true; 6752 default: 6753 return false; 6754 } 6755 return false; 6756 } 6757 6758 bool SystemZABIInfo::isCompoundType(QualType Ty) const { 6759 return (Ty->isAnyComplexType() || 6760 Ty->isVectorType() || 6761 isAggregateTypeForABI(Ty)); 6762 } 6763 6764 bool SystemZABIInfo::isVectorArgumentType(QualType Ty) const { 6765 return (HasVector && 6766 Ty->isVectorType() && 6767 getContext().getTypeSize(Ty) <= 128); 6768 } 6769 6770 bool SystemZABIInfo::isFPArgumentType(QualType Ty) const { 6771 if (IsSoftFloatABI) 6772 return false; 6773 6774 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) 6775 switch (BT->getKind()) { 6776 case BuiltinType::Float: 6777 case BuiltinType::Double: 6778 return true; 6779 default: 6780 return false; 6781 } 6782 6783 return false; 6784 } 6785 6786 QualType SystemZABIInfo::GetSingleElementType(QualType Ty) const { 6787 if (const RecordType *RT = Ty->getAsStructureType()) { 6788 const RecordDecl *RD = RT->getDecl(); 6789 QualType Found; 6790 6791 // If this is a C++ record, check the bases first. 6792 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 6793 for (const auto &I : CXXRD->bases()) { 6794 QualType Base = I.getType(); 6795 6796 // Empty bases don't affect things either way. 6797 if (isEmptyRecord(getContext(), Base, true)) 6798 continue; 6799 6800 if (!Found.isNull()) 6801 return Ty; 6802 Found = GetSingleElementType(Base); 6803 } 6804 6805 // Check the fields. 6806 for (const auto *FD : RD->fields()) { 6807 // For compatibility with GCC, ignore empty bitfields in C++ mode. 6808 // Unlike isSingleElementStruct(), empty structure and array fields 6809 // do count. So do anonymous bitfields that aren't zero-sized. 6810 if (getContext().getLangOpts().CPlusPlus && 6811 FD->isZeroLengthBitField(getContext())) 6812 continue; 6813 6814 // Unlike isSingleElementStruct(), arrays do not count. 6815 // Nested structures still do though. 6816 if (!Found.isNull()) 6817 return Ty; 6818 Found = GetSingleElementType(FD->getType()); 6819 } 6820 6821 // Unlike isSingleElementStruct(), trailing padding is allowed. 6822 // An 8-byte aligned struct s { float f; } is passed as a double. 6823 if (!Found.isNull()) 6824 return Found; 6825 } 6826 6827 return Ty; 6828 } 6829 6830 Address SystemZABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 6831 QualType Ty) const { 6832 // Assume that va_list type is correct; should be pointer to LLVM type: 6833 // struct { 6834 // i64 __gpr; 6835 // i64 __fpr; 6836 // i8 *__overflow_arg_area; 6837 // i8 *__reg_save_area; 6838 // }; 6839 6840 // Every non-vector argument occupies 8 bytes and is passed by preference 6841 // in either GPRs or FPRs. Vector arguments occupy 8 or 16 bytes and are 6842 // always passed on the stack. 6843 Ty = getContext().getCanonicalType(Ty); 6844 auto TyInfo = getContext().getTypeInfoInChars(Ty); 6845 llvm::Type *ArgTy = CGF.ConvertTypeForMem(Ty); 6846 llvm::Type *DirectTy = ArgTy; 6847 ABIArgInfo AI = classifyArgumentType(Ty); 6848 bool IsIndirect = AI.isIndirect(); 6849 bool InFPRs = false; 6850 bool IsVector = false; 6851 CharUnits UnpaddedSize; 6852 CharUnits DirectAlign; 6853 if (IsIndirect) { 6854 DirectTy = llvm::PointerType::getUnqual(DirectTy); 6855 UnpaddedSize = DirectAlign = CharUnits::fromQuantity(8); 6856 } else { 6857 if (AI.getCoerceToType()) 6858 ArgTy = AI.getCoerceToType(); 6859 InFPRs = (!IsSoftFloatABI && (ArgTy->isFloatTy() || ArgTy->isDoubleTy())); 6860 IsVector = ArgTy->isVectorTy(); 6861 UnpaddedSize = TyInfo.first; 6862 DirectAlign = TyInfo.second; 6863 } 6864 CharUnits PaddedSize = CharUnits::fromQuantity(8); 6865 if (IsVector && UnpaddedSize > PaddedSize) 6866 PaddedSize = CharUnits::fromQuantity(16); 6867 assert((UnpaddedSize <= PaddedSize) && "Invalid argument size."); 6868 6869 CharUnits Padding = (PaddedSize - UnpaddedSize); 6870 6871 llvm::Type *IndexTy = CGF.Int64Ty; 6872 llvm::Value *PaddedSizeV = 6873 llvm::ConstantInt::get(IndexTy, PaddedSize.getQuantity()); 6874 6875 if (IsVector) { 6876 // Work out the address of a vector argument on the stack. 6877 // Vector arguments are always passed in the high bits of a 6878 // single (8 byte) or double (16 byte) stack slot. 6879 Address OverflowArgAreaPtr = 6880 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr"); 6881 Address OverflowArgArea = 6882 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"), 6883 TyInfo.second); 6884 Address MemAddr = 6885 CGF.Builder.CreateElementBitCast(OverflowArgArea, DirectTy, "mem_addr"); 6886 6887 // Update overflow_arg_area_ptr pointer 6888 llvm::Value *NewOverflowArgArea = 6889 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV, 6890 "overflow_arg_area"); 6891 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr); 6892 6893 return MemAddr; 6894 } 6895 6896 assert(PaddedSize.getQuantity() == 8); 6897 6898 unsigned MaxRegs, RegCountField, RegSaveIndex; 6899 CharUnits RegPadding; 6900 if (InFPRs) { 6901 MaxRegs = 4; // Maximum of 4 FPR arguments 6902 RegCountField = 1; // __fpr 6903 RegSaveIndex = 16; // save offset for f0 6904 RegPadding = CharUnits(); // floats are passed in the high bits of an FPR 6905 } else { 6906 MaxRegs = 5; // Maximum of 5 GPR arguments 6907 RegCountField = 0; // __gpr 6908 RegSaveIndex = 2; // save offset for r2 6909 RegPadding = Padding; // values are passed in the low bits of a GPR 6910 } 6911 6912 Address RegCountPtr = 6913 CGF.Builder.CreateStructGEP(VAListAddr, RegCountField, "reg_count_ptr"); 6914 llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count"); 6915 llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs); 6916 llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV, 6917 "fits_in_regs"); 6918 6919 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg"); 6920 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem"); 6921 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end"); 6922 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock); 6923 6924 // Emit code to load the value if it was passed in registers. 6925 CGF.EmitBlock(InRegBlock); 6926 6927 // Work out the address of an argument register. 6928 llvm::Value *ScaledRegCount = 6929 CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count"); 6930 llvm::Value *RegBase = 6931 llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize.getQuantity() 6932 + RegPadding.getQuantity()); 6933 llvm::Value *RegOffset = 6934 CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset"); 6935 Address RegSaveAreaPtr = 6936 CGF.Builder.CreateStructGEP(VAListAddr, 3, "reg_save_area_ptr"); 6937 llvm::Value *RegSaveArea = 6938 CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area"); 6939 Address RawRegAddr(CGF.Builder.CreateGEP(RegSaveArea, RegOffset, 6940 "raw_reg_addr"), 6941 PaddedSize); 6942 Address RegAddr = 6943 CGF.Builder.CreateElementBitCast(RawRegAddr, DirectTy, "reg_addr"); 6944 6945 // Update the register count 6946 llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1); 6947 llvm::Value *NewRegCount = 6948 CGF.Builder.CreateAdd(RegCount, One, "reg_count"); 6949 CGF.Builder.CreateStore(NewRegCount, RegCountPtr); 6950 CGF.EmitBranch(ContBlock); 6951 6952 // Emit code to load the value if it was passed in memory. 6953 CGF.EmitBlock(InMemBlock); 6954 6955 // Work out the address of a stack argument. 6956 Address OverflowArgAreaPtr = 6957 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr"); 6958 Address OverflowArgArea = 6959 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"), 6960 PaddedSize); 6961 Address RawMemAddr = 6962 CGF.Builder.CreateConstByteGEP(OverflowArgArea, Padding, "raw_mem_addr"); 6963 Address MemAddr = 6964 CGF.Builder.CreateElementBitCast(RawMemAddr, DirectTy, "mem_addr"); 6965 6966 // Update overflow_arg_area_ptr pointer 6967 llvm::Value *NewOverflowArgArea = 6968 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV, 6969 "overflow_arg_area"); 6970 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr); 6971 CGF.EmitBranch(ContBlock); 6972 6973 // Return the appropriate result. 6974 CGF.EmitBlock(ContBlock); 6975 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, 6976 MemAddr, InMemBlock, "va_arg.addr"); 6977 6978 if (IsIndirect) 6979 ResAddr = Address(CGF.Builder.CreateLoad(ResAddr, "indirect_arg"), 6980 TyInfo.second); 6981 6982 return ResAddr; 6983 } 6984 6985 ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const { 6986 if (RetTy->isVoidType()) 6987 return ABIArgInfo::getIgnore(); 6988 if (isVectorArgumentType(RetTy)) 6989 return ABIArgInfo::getDirect(); 6990 if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64) 6991 return getNaturalAlignIndirect(RetTy); 6992 return (isPromotableIntegerType(RetTy) ? ABIArgInfo::getExtend(RetTy) 6993 : ABIArgInfo::getDirect()); 6994 } 6995 6996 ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const { 6997 // Handle the generic C++ ABI. 6998 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 6999 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 7000 7001 // Integers and enums are extended to full register width. 7002 if (isPromotableIntegerType(Ty)) 7003 return ABIArgInfo::getExtend(Ty); 7004 7005 // Handle vector types and vector-like structure types. Note that 7006 // as opposed to float-like structure types, we do not allow any 7007 // padding for vector-like structures, so verify the sizes match. 7008 uint64_t Size = getContext().getTypeSize(Ty); 7009 QualType SingleElementTy = GetSingleElementType(Ty); 7010 if (isVectorArgumentType(SingleElementTy) && 7011 getContext().getTypeSize(SingleElementTy) == Size) 7012 return ABIArgInfo::getDirect(CGT.ConvertType(SingleElementTy)); 7013 7014 // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly. 7015 if (Size != 8 && Size != 16 && Size != 32 && Size != 64) 7016 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 7017 7018 // Handle small structures. 7019 if (const RecordType *RT = Ty->getAs<RecordType>()) { 7020 // Structures with flexible arrays have variable length, so really 7021 // fail the size test above. 7022 const RecordDecl *RD = RT->getDecl(); 7023 if (RD->hasFlexibleArrayMember()) 7024 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 7025 7026 // The structure is passed as an unextended integer, a float, or a double. 7027 llvm::Type *PassTy; 7028 if (isFPArgumentType(SingleElementTy)) { 7029 assert(Size == 32 || Size == 64); 7030 if (Size == 32) 7031 PassTy = llvm::Type::getFloatTy(getVMContext()); 7032 else 7033 PassTy = llvm::Type::getDoubleTy(getVMContext()); 7034 } else 7035 PassTy = llvm::IntegerType::get(getVMContext(), Size); 7036 return ABIArgInfo::getDirect(PassTy); 7037 } 7038 7039 // Non-structure compounds are passed indirectly. 7040 if (isCompoundType(Ty)) 7041 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 7042 7043 return ABIArgInfo::getDirect(nullptr); 7044 } 7045 7046 //===----------------------------------------------------------------------===// 7047 // MSP430 ABI Implementation 7048 //===----------------------------------------------------------------------===// 7049 7050 namespace { 7051 7052 class MSP430TargetCodeGenInfo : public TargetCodeGenInfo { 7053 public: 7054 MSP430TargetCodeGenInfo(CodeGenTypes &CGT) 7055 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {} 7056 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 7057 CodeGen::CodeGenModule &M) const override; 7058 }; 7059 7060 } 7061 7062 void MSP430TargetCodeGenInfo::setTargetAttributes( 7063 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const { 7064 if (GV->isDeclaration()) 7065 return; 7066 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) { 7067 const auto *InterruptAttr = FD->getAttr<MSP430InterruptAttr>(); 7068 if (!InterruptAttr) 7069 return; 7070 7071 // Handle 'interrupt' attribute: 7072 llvm::Function *F = cast<llvm::Function>(GV); 7073 7074 // Step 1: Set ISR calling convention. 7075 F->setCallingConv(llvm::CallingConv::MSP430_INTR); 7076 7077 // Step 2: Add attributes goodness. 7078 F->addFnAttr(llvm::Attribute::NoInline); 7079 F->addFnAttr("interrupt", llvm::utostr(InterruptAttr->getNumber())); 7080 } 7081 } 7082 7083 //===----------------------------------------------------------------------===// 7084 // MIPS ABI Implementation. This works for both little-endian and 7085 // big-endian variants. 7086 //===----------------------------------------------------------------------===// 7087 7088 namespace { 7089 class MipsABIInfo : public ABIInfo { 7090 bool IsO32; 7091 unsigned MinABIStackAlignInBytes, StackAlignInBytes; 7092 void CoerceToIntArgs(uint64_t TySize, 7093 SmallVectorImpl<llvm::Type *> &ArgList) const; 7094 llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const; 7095 llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const; 7096 llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const; 7097 public: 7098 MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) : 7099 ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8), 7100 StackAlignInBytes(IsO32 ? 8 : 16) {} 7101 7102 ABIArgInfo classifyReturnType(QualType RetTy) const; 7103 ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const; 7104 void computeInfo(CGFunctionInfo &FI) const override; 7105 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 7106 QualType Ty) const override; 7107 ABIArgInfo extendType(QualType Ty) const; 7108 }; 7109 7110 class MIPSTargetCodeGenInfo : public TargetCodeGenInfo { 7111 unsigned SizeOfUnwindException; 7112 public: 7113 MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32) 7114 : TargetCodeGenInfo(new MipsABIInfo(CGT, IsO32)), 7115 SizeOfUnwindException(IsO32 ? 24 : 32) {} 7116 7117 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override { 7118 return 29; 7119 } 7120 7121 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 7122 CodeGen::CodeGenModule &CGM) const override { 7123 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D); 7124 if (!FD) return; 7125 llvm::Function *Fn = cast<llvm::Function>(GV); 7126 7127 if (FD->hasAttr<MipsLongCallAttr>()) 7128 Fn->addFnAttr("long-call"); 7129 else if (FD->hasAttr<MipsShortCallAttr>()) 7130 Fn->addFnAttr("short-call"); 7131 7132 // Other attributes do not have a meaning for declarations. 7133 if (GV->isDeclaration()) 7134 return; 7135 7136 if (FD->hasAttr<Mips16Attr>()) { 7137 Fn->addFnAttr("mips16"); 7138 } 7139 else if (FD->hasAttr<NoMips16Attr>()) { 7140 Fn->addFnAttr("nomips16"); 7141 } 7142 7143 if (FD->hasAttr<MicroMipsAttr>()) 7144 Fn->addFnAttr("micromips"); 7145 else if (FD->hasAttr<NoMicroMipsAttr>()) 7146 Fn->addFnAttr("nomicromips"); 7147 7148 const MipsInterruptAttr *Attr = FD->getAttr<MipsInterruptAttr>(); 7149 if (!Attr) 7150 return; 7151 7152 const char *Kind; 7153 switch (Attr->getInterrupt()) { 7154 case MipsInterruptAttr::eic: Kind = "eic"; break; 7155 case MipsInterruptAttr::sw0: Kind = "sw0"; break; 7156 case MipsInterruptAttr::sw1: Kind = "sw1"; break; 7157 case MipsInterruptAttr::hw0: Kind = "hw0"; break; 7158 case MipsInterruptAttr::hw1: Kind = "hw1"; break; 7159 case MipsInterruptAttr::hw2: Kind = "hw2"; break; 7160 case MipsInterruptAttr::hw3: Kind = "hw3"; break; 7161 case MipsInterruptAttr::hw4: Kind = "hw4"; break; 7162 case MipsInterruptAttr::hw5: Kind = "hw5"; break; 7163 } 7164 7165 Fn->addFnAttr("interrupt", Kind); 7166 7167 } 7168 7169 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 7170 llvm::Value *Address) const override; 7171 7172 unsigned getSizeOfUnwindException() const override { 7173 return SizeOfUnwindException; 7174 } 7175 }; 7176 } 7177 7178 void MipsABIInfo::CoerceToIntArgs( 7179 uint64_t TySize, SmallVectorImpl<llvm::Type *> &ArgList) const { 7180 llvm::IntegerType *IntTy = 7181 llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8); 7182 7183 // Add (TySize / MinABIStackAlignInBytes) args of IntTy. 7184 for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N) 7185 ArgList.push_back(IntTy); 7186 7187 // If necessary, add one more integer type to ArgList. 7188 unsigned R = TySize % (MinABIStackAlignInBytes * 8); 7189 7190 if (R) 7191 ArgList.push_back(llvm::IntegerType::get(getVMContext(), R)); 7192 } 7193 7194 // In N32/64, an aligned double precision floating point field is passed in 7195 // a register. 7196 llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const { 7197 SmallVector<llvm::Type*, 8> ArgList, IntArgList; 7198 7199 if (IsO32) { 7200 CoerceToIntArgs(TySize, ArgList); 7201 return llvm::StructType::get(getVMContext(), ArgList); 7202 } 7203 7204 if (Ty->isComplexType()) 7205 return CGT.ConvertType(Ty); 7206 7207 const RecordType *RT = Ty->getAs<RecordType>(); 7208 7209 // Unions/vectors are passed in integer registers. 7210 if (!RT || !RT->isStructureOrClassType()) { 7211 CoerceToIntArgs(TySize, ArgList); 7212 return llvm::StructType::get(getVMContext(), ArgList); 7213 } 7214 7215 const RecordDecl *RD = RT->getDecl(); 7216 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD); 7217 assert(!(TySize % 8) && "Size of structure must be multiple of 8."); 7218 7219 uint64_t LastOffset = 0; 7220 unsigned idx = 0; 7221 llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64); 7222 7223 // Iterate over fields in the struct/class and check if there are any aligned 7224 // double fields. 7225 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 7226 i != e; ++i, ++idx) { 7227 const QualType Ty = i->getType(); 7228 const BuiltinType *BT = Ty->getAs<BuiltinType>(); 7229 7230 if (!BT || BT->getKind() != BuiltinType::Double) 7231 continue; 7232 7233 uint64_t Offset = Layout.getFieldOffset(idx); 7234 if (Offset % 64) // Ignore doubles that are not aligned. 7235 continue; 7236 7237 // Add ((Offset - LastOffset) / 64) args of type i64. 7238 for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j) 7239 ArgList.push_back(I64); 7240 7241 // Add double type. 7242 ArgList.push_back(llvm::Type::getDoubleTy(getVMContext())); 7243 LastOffset = Offset + 64; 7244 } 7245 7246 CoerceToIntArgs(TySize - LastOffset, IntArgList); 7247 ArgList.append(IntArgList.begin(), IntArgList.end()); 7248 7249 return llvm::StructType::get(getVMContext(), ArgList); 7250 } 7251 7252 llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset, 7253 uint64_t Offset) const { 7254 if (OrigOffset + MinABIStackAlignInBytes > Offset) 7255 return nullptr; 7256 7257 return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8); 7258 } 7259 7260 ABIArgInfo 7261 MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const { 7262 Ty = useFirstFieldIfTransparentUnion(Ty); 7263 7264 uint64_t OrigOffset = Offset; 7265 uint64_t TySize = getContext().getTypeSize(Ty); 7266 uint64_t Align = getContext().getTypeAlign(Ty) / 8; 7267 7268 Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes), 7269 (uint64_t)StackAlignInBytes); 7270 unsigned CurrOffset = llvm::alignTo(Offset, Align); 7271 Offset = CurrOffset + llvm::alignTo(TySize, Align * 8) / 8; 7272 7273 if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) { 7274 // Ignore empty aggregates. 7275 if (TySize == 0) 7276 return ABIArgInfo::getIgnore(); 7277 7278 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) { 7279 Offset = OrigOffset + MinABIStackAlignInBytes; 7280 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 7281 } 7282 7283 // If we have reached here, aggregates are passed directly by coercing to 7284 // another structure type. Padding is inserted if the offset of the 7285 // aggregate is unaligned. 7286 ABIArgInfo ArgInfo = 7287 ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0, 7288 getPaddingType(OrigOffset, CurrOffset)); 7289 ArgInfo.setInReg(true); 7290 return ArgInfo; 7291 } 7292 7293 // Treat an enum type as its underlying type. 7294 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 7295 Ty = EnumTy->getDecl()->getIntegerType(); 7296 7297 // All integral types are promoted to the GPR width. 7298 if (Ty->isIntegralOrEnumerationType()) 7299 return extendType(Ty); 7300 7301 return ABIArgInfo::getDirect( 7302 nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset)); 7303 } 7304 7305 llvm::Type* 7306 MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const { 7307 const RecordType *RT = RetTy->getAs<RecordType>(); 7308 SmallVector<llvm::Type*, 8> RTList; 7309 7310 if (RT && RT->isStructureOrClassType()) { 7311 const RecordDecl *RD = RT->getDecl(); 7312 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD); 7313 unsigned FieldCnt = Layout.getFieldCount(); 7314 7315 // N32/64 returns struct/classes in floating point registers if the 7316 // following conditions are met: 7317 // 1. The size of the struct/class is no larger than 128-bit. 7318 // 2. The struct/class has one or two fields all of which are floating 7319 // point types. 7320 // 3. The offset of the first field is zero (this follows what gcc does). 7321 // 7322 // Any other composite results are returned in integer registers. 7323 // 7324 if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) { 7325 RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end(); 7326 for (; b != e; ++b) { 7327 const BuiltinType *BT = b->getType()->getAs<BuiltinType>(); 7328 7329 if (!BT || !BT->isFloatingPoint()) 7330 break; 7331 7332 RTList.push_back(CGT.ConvertType(b->getType())); 7333 } 7334 7335 if (b == e) 7336 return llvm::StructType::get(getVMContext(), RTList, 7337 RD->hasAttr<PackedAttr>()); 7338 7339 RTList.clear(); 7340 } 7341 } 7342 7343 CoerceToIntArgs(Size, RTList); 7344 return llvm::StructType::get(getVMContext(), RTList); 7345 } 7346 7347 ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const { 7348 uint64_t Size = getContext().getTypeSize(RetTy); 7349 7350 if (RetTy->isVoidType()) 7351 return ABIArgInfo::getIgnore(); 7352 7353 // O32 doesn't treat zero-sized structs differently from other structs. 7354 // However, N32/N64 ignores zero sized return values. 7355 if (!IsO32 && Size == 0) 7356 return ABIArgInfo::getIgnore(); 7357 7358 if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) { 7359 if (Size <= 128) { 7360 if (RetTy->isAnyComplexType()) 7361 return ABIArgInfo::getDirect(); 7362 7363 // O32 returns integer vectors in registers and N32/N64 returns all small 7364 // aggregates in registers. 7365 if (!IsO32 || 7366 (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) { 7367 ABIArgInfo ArgInfo = 7368 ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size)); 7369 ArgInfo.setInReg(true); 7370 return ArgInfo; 7371 } 7372 } 7373 7374 return getNaturalAlignIndirect(RetTy); 7375 } 7376 7377 // Treat an enum type as its underlying type. 7378 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 7379 RetTy = EnumTy->getDecl()->getIntegerType(); 7380 7381 if (RetTy->isPromotableIntegerType()) 7382 return ABIArgInfo::getExtend(RetTy); 7383 7384 if ((RetTy->isUnsignedIntegerOrEnumerationType() || 7385 RetTy->isSignedIntegerOrEnumerationType()) && Size == 32 && !IsO32) 7386 return ABIArgInfo::getSignExtend(RetTy); 7387 7388 return ABIArgInfo::getDirect(); 7389 } 7390 7391 void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const { 7392 ABIArgInfo &RetInfo = FI.getReturnInfo(); 7393 if (!getCXXABI().classifyReturnType(FI)) 7394 RetInfo = classifyReturnType(FI.getReturnType()); 7395 7396 // Check if a pointer to an aggregate is passed as a hidden argument. 7397 uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0; 7398 7399 for (auto &I : FI.arguments()) 7400 I.info = classifyArgumentType(I.type, Offset); 7401 } 7402 7403 Address MipsABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 7404 QualType OrigTy) const { 7405 QualType Ty = OrigTy; 7406 7407 // Integer arguments are promoted to 32-bit on O32 and 64-bit on N32/N64. 7408 // Pointers are also promoted in the same way but this only matters for N32. 7409 unsigned SlotSizeInBits = IsO32 ? 32 : 64; 7410 unsigned PtrWidth = getTarget().getPointerWidth(0); 7411 bool DidPromote = false; 7412 if ((Ty->isIntegerType() && 7413 getContext().getIntWidth(Ty) < SlotSizeInBits) || 7414 (Ty->isPointerType() && PtrWidth < SlotSizeInBits)) { 7415 DidPromote = true; 7416 Ty = getContext().getIntTypeForBitwidth(SlotSizeInBits, 7417 Ty->isSignedIntegerType()); 7418 } 7419 7420 auto TyInfo = getContext().getTypeInfoInChars(Ty); 7421 7422 // The alignment of things in the argument area is never larger than 7423 // StackAlignInBytes. 7424 TyInfo.second = 7425 std::min(TyInfo.second, CharUnits::fromQuantity(StackAlignInBytes)); 7426 7427 // MinABIStackAlignInBytes is the size of argument slots on the stack. 7428 CharUnits ArgSlotSize = CharUnits::fromQuantity(MinABIStackAlignInBytes); 7429 7430 Address Addr = emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false, 7431 TyInfo, ArgSlotSize, /*AllowHigherAlign*/ true); 7432 7433 7434 // If there was a promotion, "unpromote" into a temporary. 7435 // TODO: can we just use a pointer into a subset of the original slot? 7436 if (DidPromote) { 7437 Address Temp = CGF.CreateMemTemp(OrigTy, "vaarg.promotion-temp"); 7438 llvm::Value *Promoted = CGF.Builder.CreateLoad(Addr); 7439 7440 // Truncate down to the right width. 7441 llvm::Type *IntTy = (OrigTy->isIntegerType() ? Temp.getElementType() 7442 : CGF.IntPtrTy); 7443 llvm::Value *V = CGF.Builder.CreateTrunc(Promoted, IntTy); 7444 if (OrigTy->isPointerType()) 7445 V = CGF.Builder.CreateIntToPtr(V, Temp.getElementType()); 7446 7447 CGF.Builder.CreateStore(V, Temp); 7448 Addr = Temp; 7449 } 7450 7451 return Addr; 7452 } 7453 7454 ABIArgInfo MipsABIInfo::extendType(QualType Ty) const { 7455 int TySize = getContext().getTypeSize(Ty); 7456 7457 // MIPS64 ABI requires unsigned 32 bit integers to be sign extended. 7458 if (Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32) 7459 return ABIArgInfo::getSignExtend(Ty); 7460 7461 return ABIArgInfo::getExtend(Ty); 7462 } 7463 7464 bool 7465 MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 7466 llvm::Value *Address) const { 7467 // This information comes from gcc's implementation, which seems to 7468 // as canonical as it gets. 7469 7470 // Everything on MIPS is 4 bytes. Double-precision FP registers 7471 // are aliased to pairs of single-precision FP registers. 7472 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4); 7473 7474 // 0-31 are the general purpose registers, $0 - $31. 7475 // 32-63 are the floating-point registers, $f0 - $f31. 7476 // 64 and 65 are the multiply/divide registers, $hi and $lo. 7477 // 66 is the (notional, I think) register for signal-handler return. 7478 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65); 7479 7480 // 67-74 are the floating-point status registers, $fcc0 - $fcc7. 7481 // They are one bit wide and ignored here. 7482 7483 // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31. 7484 // (coprocessor 1 is the FP unit) 7485 // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31. 7486 // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31. 7487 // 176-181 are the DSP accumulator registers. 7488 AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181); 7489 return false; 7490 } 7491 7492 //===----------------------------------------------------------------------===// 7493 // AVR ABI Implementation. 7494 //===----------------------------------------------------------------------===// 7495 7496 namespace { 7497 class AVRTargetCodeGenInfo : public TargetCodeGenInfo { 7498 public: 7499 AVRTargetCodeGenInfo(CodeGenTypes &CGT) 7500 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) { } 7501 7502 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 7503 CodeGen::CodeGenModule &CGM) const override { 7504 if (GV->isDeclaration()) 7505 return; 7506 const auto *FD = dyn_cast_or_null<FunctionDecl>(D); 7507 if (!FD) return; 7508 auto *Fn = cast<llvm::Function>(GV); 7509 7510 if (FD->getAttr<AVRInterruptAttr>()) 7511 Fn->addFnAttr("interrupt"); 7512 7513 if (FD->getAttr<AVRSignalAttr>()) 7514 Fn->addFnAttr("signal"); 7515 } 7516 }; 7517 } 7518 7519 //===----------------------------------------------------------------------===// 7520 // TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults. 7521 // Currently subclassed only to implement custom OpenCL C function attribute 7522 // handling. 7523 //===----------------------------------------------------------------------===// 7524 7525 namespace { 7526 7527 class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo { 7528 public: 7529 TCETargetCodeGenInfo(CodeGenTypes &CGT) 7530 : DefaultTargetCodeGenInfo(CGT) {} 7531 7532 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 7533 CodeGen::CodeGenModule &M) const override; 7534 }; 7535 7536 void TCETargetCodeGenInfo::setTargetAttributes( 7537 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const { 7538 if (GV->isDeclaration()) 7539 return; 7540 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D); 7541 if (!FD) return; 7542 7543 llvm::Function *F = cast<llvm::Function>(GV); 7544 7545 if (M.getLangOpts().OpenCL) { 7546 if (FD->hasAttr<OpenCLKernelAttr>()) { 7547 // OpenCL C Kernel functions are not subject to inlining 7548 F->addFnAttr(llvm::Attribute::NoInline); 7549 const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>(); 7550 if (Attr) { 7551 // Convert the reqd_work_group_size() attributes to metadata. 7552 llvm::LLVMContext &Context = F->getContext(); 7553 llvm::NamedMDNode *OpenCLMetadata = 7554 M.getModule().getOrInsertNamedMetadata( 7555 "opencl.kernel_wg_size_info"); 7556 7557 SmallVector<llvm::Metadata *, 5> Operands; 7558 Operands.push_back(llvm::ConstantAsMetadata::get(F)); 7559 7560 Operands.push_back( 7561 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue( 7562 M.Int32Ty, llvm::APInt(32, Attr->getXDim())))); 7563 Operands.push_back( 7564 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue( 7565 M.Int32Ty, llvm::APInt(32, Attr->getYDim())))); 7566 Operands.push_back( 7567 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue( 7568 M.Int32Ty, llvm::APInt(32, Attr->getZDim())))); 7569 7570 // Add a boolean constant operand for "required" (true) or "hint" 7571 // (false) for implementing the work_group_size_hint attr later. 7572 // Currently always true as the hint is not yet implemented. 7573 Operands.push_back( 7574 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getTrue(Context))); 7575 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands)); 7576 } 7577 } 7578 } 7579 } 7580 7581 } 7582 7583 //===----------------------------------------------------------------------===// 7584 // Hexagon ABI Implementation 7585 //===----------------------------------------------------------------------===// 7586 7587 namespace { 7588 7589 class HexagonABIInfo : public DefaultABIInfo { 7590 public: 7591 HexagonABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {} 7592 7593 private: 7594 ABIArgInfo classifyReturnType(QualType RetTy) const; 7595 ABIArgInfo classifyArgumentType(QualType RetTy) const; 7596 ABIArgInfo classifyArgumentType(QualType RetTy, unsigned *RegsLeft) const; 7597 7598 void computeInfo(CGFunctionInfo &FI) const override; 7599 7600 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 7601 QualType Ty) const override; 7602 Address EmitVAArgFromMemory(CodeGenFunction &CFG, Address VAListAddr, 7603 QualType Ty) const; 7604 Address EmitVAArgForHexagon(CodeGenFunction &CFG, Address VAListAddr, 7605 QualType Ty) const; 7606 Address EmitVAArgForHexagonLinux(CodeGenFunction &CFG, Address VAListAddr, 7607 QualType Ty) const; 7608 }; 7609 7610 class HexagonTargetCodeGenInfo : public TargetCodeGenInfo { 7611 public: 7612 HexagonTargetCodeGenInfo(CodeGenTypes &CGT) 7613 : TargetCodeGenInfo(new HexagonABIInfo(CGT)) {} 7614 7615 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 7616 return 29; 7617 } 7618 7619 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 7620 CodeGen::CodeGenModule &GCM) const override { 7621 if (GV->isDeclaration()) 7622 return; 7623 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D); 7624 if (!FD) 7625 return; 7626 } 7627 }; 7628 7629 } // namespace 7630 7631 void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const { 7632 unsigned RegsLeft = 6; 7633 if (!getCXXABI().classifyReturnType(FI)) 7634 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 7635 for (auto &I : FI.arguments()) 7636 I.info = classifyArgumentType(I.type, &RegsLeft); 7637 } 7638 7639 static bool HexagonAdjustRegsLeft(uint64_t Size, unsigned *RegsLeft) { 7640 assert(Size <= 64 && "Not expecting to pass arguments larger than 64 bits" 7641 " through registers"); 7642 7643 if (*RegsLeft == 0) 7644 return false; 7645 7646 if (Size <= 32) { 7647 (*RegsLeft)--; 7648 return true; 7649 } 7650 7651 if (2 <= (*RegsLeft & (~1U))) { 7652 *RegsLeft = (*RegsLeft & (~1U)) - 2; 7653 return true; 7654 } 7655 7656 // Next available register was r5 but candidate was greater than 32-bits so it 7657 // has to go on the stack. However we still consume r5 7658 if (*RegsLeft == 1) 7659 *RegsLeft = 0; 7660 7661 return false; 7662 } 7663 7664 ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty, 7665 unsigned *RegsLeft) const { 7666 if (!isAggregateTypeForABI(Ty)) { 7667 // Treat an enum type as its underlying type. 7668 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 7669 Ty = EnumTy->getDecl()->getIntegerType(); 7670 7671 uint64_t Size = getContext().getTypeSize(Ty); 7672 if (Size <= 64) 7673 HexagonAdjustRegsLeft(Size, RegsLeft); 7674 7675 return Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty) 7676 : ABIArgInfo::getDirect(); 7677 } 7678 7679 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 7680 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 7681 7682 // Ignore empty records. 7683 if (isEmptyRecord(getContext(), Ty, true)) 7684 return ABIArgInfo::getIgnore(); 7685 7686 uint64_t Size = getContext().getTypeSize(Ty); 7687 unsigned Align = getContext().getTypeAlign(Ty); 7688 7689 if (Size > 64) 7690 return getNaturalAlignIndirect(Ty, /*ByVal=*/true); 7691 7692 if (HexagonAdjustRegsLeft(Size, RegsLeft)) 7693 Align = Size <= 32 ? 32 : 64; 7694 if (Size <= Align) { 7695 // Pass in the smallest viable integer type. 7696 if (!llvm::isPowerOf2_64(Size)) 7697 Size = llvm::NextPowerOf2(Size); 7698 return ABIArgInfo::getDirect(llvm::Type::getIntNTy(getVMContext(), Size)); 7699 } 7700 return DefaultABIInfo::classifyArgumentType(Ty); 7701 } 7702 7703 ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const { 7704 if (RetTy->isVoidType()) 7705 return ABIArgInfo::getIgnore(); 7706 7707 const TargetInfo &T = CGT.getTarget(); 7708 uint64_t Size = getContext().getTypeSize(RetTy); 7709 7710 if (RetTy->getAs<VectorType>()) { 7711 // HVX vectors are returned in vector registers or register pairs. 7712 if (T.hasFeature("hvx")) { 7713 assert(T.hasFeature("hvx-length64b") || T.hasFeature("hvx-length128b")); 7714 uint64_t VecSize = T.hasFeature("hvx-length64b") ? 64*8 : 128*8; 7715 if (Size == VecSize || Size == 2*VecSize) 7716 return ABIArgInfo::getDirectInReg(); 7717 } 7718 // Large vector types should be returned via memory. 7719 if (Size > 64) 7720 return getNaturalAlignIndirect(RetTy); 7721 } 7722 7723 if (!isAggregateTypeForABI(RetTy)) { 7724 // Treat an enum type as its underlying type. 7725 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 7726 RetTy = EnumTy->getDecl()->getIntegerType(); 7727 7728 return RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy) 7729 : ABIArgInfo::getDirect(); 7730 } 7731 7732 if (isEmptyRecord(getContext(), RetTy, true)) 7733 return ABIArgInfo::getIgnore(); 7734 7735 // Aggregates <= 8 bytes are returned in registers, other aggregates 7736 // are returned indirectly. 7737 if (Size <= 64) { 7738 // Return in the smallest viable integer type. 7739 if (!llvm::isPowerOf2_64(Size)) 7740 Size = llvm::NextPowerOf2(Size); 7741 return ABIArgInfo::getDirect(llvm::Type::getIntNTy(getVMContext(), Size)); 7742 } 7743 return getNaturalAlignIndirect(RetTy, /*ByVal=*/true); 7744 } 7745 7746 Address HexagonABIInfo::EmitVAArgFromMemory(CodeGenFunction &CGF, 7747 Address VAListAddr, 7748 QualType Ty) const { 7749 // Load the overflow area pointer. 7750 Address __overflow_area_pointer_p = 7751 CGF.Builder.CreateStructGEP(VAListAddr, 2, "__overflow_area_pointer_p"); 7752 llvm::Value *__overflow_area_pointer = CGF.Builder.CreateLoad( 7753 __overflow_area_pointer_p, "__overflow_area_pointer"); 7754 7755 uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8; 7756 if (Align > 4) { 7757 // Alignment should be a power of 2. 7758 assert((Align & (Align - 1)) == 0 && "Alignment is not power of 2!"); 7759 7760 // overflow_arg_area = (overflow_arg_area + align - 1) & -align; 7761 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int64Ty, Align - 1); 7762 7763 // Add offset to the current pointer to access the argument. 7764 __overflow_area_pointer = 7765 CGF.Builder.CreateGEP(__overflow_area_pointer, Offset); 7766 llvm::Value *AsInt = 7767 CGF.Builder.CreatePtrToInt(__overflow_area_pointer, CGF.Int32Ty); 7768 7769 // Create a mask which should be "AND"ed 7770 // with (overflow_arg_area + align - 1) 7771 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int32Ty, -(int)Align); 7772 __overflow_area_pointer = CGF.Builder.CreateIntToPtr( 7773 CGF.Builder.CreateAnd(AsInt, Mask), __overflow_area_pointer->getType(), 7774 "__overflow_area_pointer.align"); 7775 } 7776 7777 // Get the type of the argument from memory and bitcast 7778 // overflow area pointer to the argument type. 7779 llvm::Type *PTy = CGF.ConvertTypeForMem(Ty); 7780 Address AddrTyped = CGF.Builder.CreateBitCast( 7781 Address(__overflow_area_pointer, CharUnits::fromQuantity(Align)), 7782 llvm::PointerType::getUnqual(PTy)); 7783 7784 // Round up to the minimum stack alignment for varargs which is 4 bytes. 7785 uint64_t Offset = llvm::alignTo(CGF.getContext().getTypeSize(Ty) / 8, 4); 7786 7787 __overflow_area_pointer = CGF.Builder.CreateGEP( 7788 __overflow_area_pointer, llvm::ConstantInt::get(CGF.Int32Ty, Offset), 7789 "__overflow_area_pointer.next"); 7790 CGF.Builder.CreateStore(__overflow_area_pointer, __overflow_area_pointer_p); 7791 7792 return AddrTyped; 7793 } 7794 7795 Address HexagonABIInfo::EmitVAArgForHexagon(CodeGenFunction &CGF, 7796 Address VAListAddr, 7797 QualType Ty) const { 7798 // FIXME: Need to handle alignment 7799 llvm::Type *BP = CGF.Int8PtrTy; 7800 llvm::Type *BPP = CGF.Int8PtrPtrTy; 7801 CGBuilderTy &Builder = CGF.Builder; 7802 Address VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap"); 7803 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur"); 7804 // Handle address alignment for type alignment > 32 bits 7805 uint64_t TyAlign = CGF.getContext().getTypeAlign(Ty) / 8; 7806 if (TyAlign > 4) { 7807 assert((TyAlign & (TyAlign - 1)) == 0 && "Alignment is not power of 2!"); 7808 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int32Ty); 7809 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt32(TyAlign - 1)); 7810 AddrAsInt = Builder.CreateAnd(AddrAsInt, Builder.getInt32(~(TyAlign - 1))); 7811 Addr = Builder.CreateIntToPtr(AddrAsInt, BP); 7812 } 7813 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty)); 7814 Address AddrTyped = Builder.CreateBitCast( 7815 Address(Addr, CharUnits::fromQuantity(TyAlign)), PTy); 7816 7817 uint64_t Offset = llvm::alignTo(CGF.getContext().getTypeSize(Ty) / 8, 4); 7818 llvm::Value *NextAddr = Builder.CreateGEP( 7819 Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset), "ap.next"); 7820 Builder.CreateStore(NextAddr, VAListAddrAsBPP); 7821 7822 return AddrTyped; 7823 } 7824 7825 Address HexagonABIInfo::EmitVAArgForHexagonLinux(CodeGenFunction &CGF, 7826 Address VAListAddr, 7827 QualType Ty) const { 7828 int ArgSize = CGF.getContext().getTypeSize(Ty) / 8; 7829 7830 if (ArgSize > 8) 7831 return EmitVAArgFromMemory(CGF, VAListAddr, Ty); 7832 7833 // Here we have check if the argument is in register area or 7834 // in overflow area. 7835 // If the saved register area pointer + argsize rounded up to alignment > 7836 // saved register area end pointer, argument is in overflow area. 7837 unsigned RegsLeft = 6; 7838 Ty = CGF.getContext().getCanonicalType(Ty); 7839 (void)classifyArgumentType(Ty, &RegsLeft); 7840 7841 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg"); 7842 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg"); 7843 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack"); 7844 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end"); 7845 7846 // Get rounded size of the argument.GCC does not allow vararg of 7847 // size < 4 bytes. We follow the same logic here. 7848 ArgSize = (CGF.getContext().getTypeSize(Ty) <= 32) ? 4 : 8; 7849 int ArgAlign = (CGF.getContext().getTypeSize(Ty) <= 32) ? 4 : 8; 7850 7851 // Argument may be in saved register area 7852 CGF.EmitBlock(MaybeRegBlock); 7853 7854 // Load the current saved register area pointer. 7855 Address __current_saved_reg_area_pointer_p = CGF.Builder.CreateStructGEP( 7856 VAListAddr, 0, "__current_saved_reg_area_pointer_p"); 7857 llvm::Value *__current_saved_reg_area_pointer = CGF.Builder.CreateLoad( 7858 __current_saved_reg_area_pointer_p, "__current_saved_reg_area_pointer"); 7859 7860 // Load the saved register area end pointer. 7861 Address __saved_reg_area_end_pointer_p = CGF.Builder.CreateStructGEP( 7862 VAListAddr, 1, "__saved_reg_area_end_pointer_p"); 7863 llvm::Value *__saved_reg_area_end_pointer = CGF.Builder.CreateLoad( 7864 __saved_reg_area_end_pointer_p, "__saved_reg_area_end_pointer"); 7865 7866 // If the size of argument is > 4 bytes, check if the stack 7867 // location is aligned to 8 bytes 7868 if (ArgAlign > 4) { 7869 7870 llvm::Value *__current_saved_reg_area_pointer_int = 7871 CGF.Builder.CreatePtrToInt(__current_saved_reg_area_pointer, 7872 CGF.Int32Ty); 7873 7874 __current_saved_reg_area_pointer_int = CGF.Builder.CreateAdd( 7875 __current_saved_reg_area_pointer_int, 7876 llvm::ConstantInt::get(CGF.Int32Ty, (ArgAlign - 1)), 7877 "align_current_saved_reg_area_pointer"); 7878 7879 __current_saved_reg_area_pointer_int = 7880 CGF.Builder.CreateAnd(__current_saved_reg_area_pointer_int, 7881 llvm::ConstantInt::get(CGF.Int32Ty, -ArgAlign), 7882 "align_current_saved_reg_area_pointer"); 7883 7884 __current_saved_reg_area_pointer = 7885 CGF.Builder.CreateIntToPtr(__current_saved_reg_area_pointer_int, 7886 __current_saved_reg_area_pointer->getType(), 7887 "align_current_saved_reg_area_pointer"); 7888 } 7889 7890 llvm::Value *__new_saved_reg_area_pointer = 7891 CGF.Builder.CreateGEP(__current_saved_reg_area_pointer, 7892 llvm::ConstantInt::get(CGF.Int32Ty, ArgSize), 7893 "__new_saved_reg_area_pointer"); 7894 7895 llvm::Value *UsingStack = 0; 7896 UsingStack = CGF.Builder.CreateICmpSGT(__new_saved_reg_area_pointer, 7897 __saved_reg_area_end_pointer); 7898 7899 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, InRegBlock); 7900 7901 // Argument in saved register area 7902 // Implement the block where argument is in register saved area 7903 CGF.EmitBlock(InRegBlock); 7904 7905 llvm::Type *PTy = CGF.ConvertType(Ty); 7906 llvm::Value *__saved_reg_area_p = CGF.Builder.CreateBitCast( 7907 __current_saved_reg_area_pointer, llvm::PointerType::getUnqual(PTy)); 7908 7909 CGF.Builder.CreateStore(__new_saved_reg_area_pointer, 7910 __current_saved_reg_area_pointer_p); 7911 7912 CGF.EmitBranch(ContBlock); 7913 7914 // Argument in overflow area 7915 // Implement the block where the argument is in overflow area. 7916 CGF.EmitBlock(OnStackBlock); 7917 7918 // Load the overflow area pointer 7919 Address __overflow_area_pointer_p = 7920 CGF.Builder.CreateStructGEP(VAListAddr, 2, "__overflow_area_pointer_p"); 7921 llvm::Value *__overflow_area_pointer = CGF.Builder.CreateLoad( 7922 __overflow_area_pointer_p, "__overflow_area_pointer"); 7923 7924 // Align the overflow area pointer according to the alignment of the argument 7925 if (ArgAlign > 4) { 7926 llvm::Value *__overflow_area_pointer_int = 7927 CGF.Builder.CreatePtrToInt(__overflow_area_pointer, CGF.Int32Ty); 7928 7929 __overflow_area_pointer_int = 7930 CGF.Builder.CreateAdd(__overflow_area_pointer_int, 7931 llvm::ConstantInt::get(CGF.Int32Ty, ArgAlign - 1), 7932 "align_overflow_area_pointer"); 7933 7934 __overflow_area_pointer_int = 7935 CGF.Builder.CreateAnd(__overflow_area_pointer_int, 7936 llvm::ConstantInt::get(CGF.Int32Ty, -ArgAlign), 7937 "align_overflow_area_pointer"); 7938 7939 __overflow_area_pointer = CGF.Builder.CreateIntToPtr( 7940 __overflow_area_pointer_int, __overflow_area_pointer->getType(), 7941 "align_overflow_area_pointer"); 7942 } 7943 7944 // Get the pointer for next argument in overflow area and store it 7945 // to overflow area pointer. 7946 llvm::Value *__new_overflow_area_pointer = CGF.Builder.CreateGEP( 7947 __overflow_area_pointer, llvm::ConstantInt::get(CGF.Int32Ty, ArgSize), 7948 "__overflow_area_pointer.next"); 7949 7950 CGF.Builder.CreateStore(__new_overflow_area_pointer, 7951 __overflow_area_pointer_p); 7952 7953 CGF.Builder.CreateStore(__new_overflow_area_pointer, 7954 __current_saved_reg_area_pointer_p); 7955 7956 // Bitcast the overflow area pointer to the type of argument. 7957 llvm::Type *OverflowPTy = CGF.ConvertTypeForMem(Ty); 7958 llvm::Value *__overflow_area_p = CGF.Builder.CreateBitCast( 7959 __overflow_area_pointer, llvm::PointerType::getUnqual(OverflowPTy)); 7960 7961 CGF.EmitBranch(ContBlock); 7962 7963 // Get the correct pointer to load the variable argument 7964 // Implement the ContBlock 7965 CGF.EmitBlock(ContBlock); 7966 7967 llvm::Type *MemPTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty)); 7968 llvm::PHINode *ArgAddr = CGF.Builder.CreatePHI(MemPTy, 2, "vaarg.addr"); 7969 ArgAddr->addIncoming(__saved_reg_area_p, InRegBlock); 7970 ArgAddr->addIncoming(__overflow_area_p, OnStackBlock); 7971 7972 return Address(ArgAddr, CharUnits::fromQuantity(ArgAlign)); 7973 } 7974 7975 Address HexagonABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 7976 QualType Ty) const { 7977 7978 if (getTarget().getTriple().isMusl()) 7979 return EmitVAArgForHexagonLinux(CGF, VAListAddr, Ty); 7980 7981 return EmitVAArgForHexagon(CGF, VAListAddr, Ty); 7982 } 7983 7984 //===----------------------------------------------------------------------===// 7985 // Lanai ABI Implementation 7986 //===----------------------------------------------------------------------===// 7987 7988 namespace { 7989 class LanaiABIInfo : public DefaultABIInfo { 7990 public: 7991 LanaiABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {} 7992 7993 bool shouldUseInReg(QualType Ty, CCState &State) const; 7994 7995 void computeInfo(CGFunctionInfo &FI) const override { 7996 CCState State(FI); 7997 // Lanai uses 4 registers to pass arguments unless the function has the 7998 // regparm attribute set. 7999 if (FI.getHasRegParm()) { 8000 State.FreeRegs = FI.getRegParm(); 8001 } else { 8002 State.FreeRegs = 4; 8003 } 8004 8005 if (!getCXXABI().classifyReturnType(FI)) 8006 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 8007 for (auto &I : FI.arguments()) 8008 I.info = classifyArgumentType(I.type, State); 8009 } 8010 8011 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const; 8012 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const; 8013 }; 8014 } // end anonymous namespace 8015 8016 bool LanaiABIInfo::shouldUseInReg(QualType Ty, CCState &State) const { 8017 unsigned Size = getContext().getTypeSize(Ty); 8018 unsigned SizeInRegs = llvm::alignTo(Size, 32U) / 32U; 8019 8020 if (SizeInRegs == 0) 8021 return false; 8022 8023 if (SizeInRegs > State.FreeRegs) { 8024 State.FreeRegs = 0; 8025 return false; 8026 } 8027 8028 State.FreeRegs -= SizeInRegs; 8029 8030 return true; 8031 } 8032 8033 ABIArgInfo LanaiABIInfo::getIndirectResult(QualType Ty, bool ByVal, 8034 CCState &State) const { 8035 if (!ByVal) { 8036 if (State.FreeRegs) { 8037 --State.FreeRegs; // Non-byval indirects just use one pointer. 8038 return getNaturalAlignIndirectInReg(Ty); 8039 } 8040 return getNaturalAlignIndirect(Ty, false); 8041 } 8042 8043 // Compute the byval alignment. 8044 const unsigned MinABIStackAlignInBytes = 4; 8045 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8; 8046 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true, 8047 /*Realign=*/TypeAlign > 8048 MinABIStackAlignInBytes); 8049 } 8050 8051 ABIArgInfo LanaiABIInfo::classifyArgumentType(QualType Ty, 8052 CCState &State) const { 8053 // Check with the C++ ABI first. 8054 const RecordType *RT = Ty->getAs<RecordType>(); 8055 if (RT) { 8056 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()); 8057 if (RAA == CGCXXABI::RAA_Indirect) { 8058 return getIndirectResult(Ty, /*ByVal=*/false, State); 8059 } else if (RAA == CGCXXABI::RAA_DirectInMemory) { 8060 return getNaturalAlignIndirect(Ty, /*ByRef=*/true); 8061 } 8062 } 8063 8064 if (isAggregateTypeForABI(Ty)) { 8065 // Structures with flexible arrays are always indirect. 8066 if (RT && RT->getDecl()->hasFlexibleArrayMember()) 8067 return getIndirectResult(Ty, /*ByVal=*/true, State); 8068 8069 // Ignore empty structs/unions. 8070 if (isEmptyRecord(getContext(), Ty, true)) 8071 return ABIArgInfo::getIgnore(); 8072 8073 llvm::LLVMContext &LLVMContext = getVMContext(); 8074 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32; 8075 if (SizeInRegs <= State.FreeRegs) { 8076 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext); 8077 SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32); 8078 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements); 8079 State.FreeRegs -= SizeInRegs; 8080 return ABIArgInfo::getDirectInReg(Result); 8081 } else { 8082 State.FreeRegs = 0; 8083 } 8084 return getIndirectResult(Ty, true, State); 8085 } 8086 8087 // Treat an enum type as its underlying type. 8088 if (const auto *EnumTy = Ty->getAs<EnumType>()) 8089 Ty = EnumTy->getDecl()->getIntegerType(); 8090 8091 bool InReg = shouldUseInReg(Ty, State); 8092 if (Ty->isPromotableIntegerType()) { 8093 if (InReg) 8094 return ABIArgInfo::getDirectInReg(); 8095 return ABIArgInfo::getExtend(Ty); 8096 } 8097 if (InReg) 8098 return ABIArgInfo::getDirectInReg(); 8099 return ABIArgInfo::getDirect(); 8100 } 8101 8102 namespace { 8103 class LanaiTargetCodeGenInfo : public TargetCodeGenInfo { 8104 public: 8105 LanaiTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT) 8106 : TargetCodeGenInfo(new LanaiABIInfo(CGT)) {} 8107 }; 8108 } 8109 8110 //===----------------------------------------------------------------------===// 8111 // AMDGPU ABI Implementation 8112 //===----------------------------------------------------------------------===// 8113 8114 namespace { 8115 8116 class AMDGPUABIInfo final : public DefaultABIInfo { 8117 private: 8118 static const unsigned MaxNumRegsForArgsRet = 16; 8119 8120 unsigned numRegsForType(QualType Ty) const; 8121 8122 bool isHomogeneousAggregateBaseType(QualType Ty) const override; 8123 bool isHomogeneousAggregateSmallEnough(const Type *Base, 8124 uint64_t Members) const override; 8125 8126 // Coerce HIP pointer arguments from generic pointers to global ones. 8127 llvm::Type *coerceKernelArgumentType(llvm::Type *Ty, unsigned FromAS, 8128 unsigned ToAS) const { 8129 // Structure types. 8130 if (auto STy = dyn_cast<llvm::StructType>(Ty)) { 8131 SmallVector<llvm::Type *, 8> EltTys; 8132 bool Changed = false; 8133 for (auto T : STy->elements()) { 8134 auto NT = coerceKernelArgumentType(T, FromAS, ToAS); 8135 EltTys.push_back(NT); 8136 Changed |= (NT != T); 8137 } 8138 // Skip if there is no change in element types. 8139 if (!Changed) 8140 return STy; 8141 if (STy->hasName()) 8142 return llvm::StructType::create( 8143 EltTys, (STy->getName() + ".coerce").str(), STy->isPacked()); 8144 return llvm::StructType::get(getVMContext(), EltTys, STy->isPacked()); 8145 } 8146 // Arrary types. 8147 if (auto ATy = dyn_cast<llvm::ArrayType>(Ty)) { 8148 auto T = ATy->getElementType(); 8149 auto NT = coerceKernelArgumentType(T, FromAS, ToAS); 8150 // Skip if there is no change in that element type. 8151 if (NT == T) 8152 return ATy; 8153 return llvm::ArrayType::get(NT, ATy->getNumElements()); 8154 } 8155 // Single value types. 8156 if (Ty->isPointerTy() && Ty->getPointerAddressSpace() == FromAS) 8157 return llvm::PointerType::get( 8158 cast<llvm::PointerType>(Ty)->getElementType(), ToAS); 8159 return Ty; 8160 } 8161 8162 public: 8163 explicit AMDGPUABIInfo(CodeGen::CodeGenTypes &CGT) : 8164 DefaultABIInfo(CGT) {} 8165 8166 ABIArgInfo classifyReturnType(QualType RetTy) const; 8167 ABIArgInfo classifyKernelArgumentType(QualType Ty) const; 8168 ABIArgInfo classifyArgumentType(QualType Ty, unsigned &NumRegsLeft) const; 8169 8170 void computeInfo(CGFunctionInfo &FI) const override; 8171 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 8172 QualType Ty) const override; 8173 }; 8174 8175 bool AMDGPUABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const { 8176 return true; 8177 } 8178 8179 bool AMDGPUABIInfo::isHomogeneousAggregateSmallEnough( 8180 const Type *Base, uint64_t Members) const { 8181 uint32_t NumRegs = (getContext().getTypeSize(Base) + 31) / 32; 8182 8183 // Homogeneous Aggregates may occupy at most 16 registers. 8184 return Members * NumRegs <= MaxNumRegsForArgsRet; 8185 } 8186 8187 /// Estimate number of registers the type will use when passed in registers. 8188 unsigned AMDGPUABIInfo::numRegsForType(QualType Ty) const { 8189 unsigned NumRegs = 0; 8190 8191 if (const VectorType *VT = Ty->getAs<VectorType>()) { 8192 // Compute from the number of elements. The reported size is based on the 8193 // in-memory size, which includes the padding 4th element for 3-vectors. 8194 QualType EltTy = VT->getElementType(); 8195 unsigned EltSize = getContext().getTypeSize(EltTy); 8196 8197 // 16-bit element vectors should be passed as packed. 8198 if (EltSize == 16) 8199 return (VT->getNumElements() + 1) / 2; 8200 8201 unsigned EltNumRegs = (EltSize + 31) / 32; 8202 return EltNumRegs * VT->getNumElements(); 8203 } 8204 8205 if (const RecordType *RT = Ty->getAs<RecordType>()) { 8206 const RecordDecl *RD = RT->getDecl(); 8207 assert(!RD->hasFlexibleArrayMember()); 8208 8209 for (const FieldDecl *Field : RD->fields()) { 8210 QualType FieldTy = Field->getType(); 8211 NumRegs += numRegsForType(FieldTy); 8212 } 8213 8214 return NumRegs; 8215 } 8216 8217 return (getContext().getTypeSize(Ty) + 31) / 32; 8218 } 8219 8220 void AMDGPUABIInfo::computeInfo(CGFunctionInfo &FI) const { 8221 llvm::CallingConv::ID CC = FI.getCallingConvention(); 8222 8223 if (!getCXXABI().classifyReturnType(FI)) 8224 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 8225 8226 unsigned NumRegsLeft = MaxNumRegsForArgsRet; 8227 for (auto &Arg : FI.arguments()) { 8228 if (CC == llvm::CallingConv::AMDGPU_KERNEL) { 8229 Arg.info = classifyKernelArgumentType(Arg.type); 8230 } else { 8231 Arg.info = classifyArgumentType(Arg.type, NumRegsLeft); 8232 } 8233 } 8234 } 8235 8236 Address AMDGPUABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 8237 QualType Ty) const { 8238 llvm_unreachable("AMDGPU does not support varargs"); 8239 } 8240 8241 ABIArgInfo AMDGPUABIInfo::classifyReturnType(QualType RetTy) const { 8242 if (isAggregateTypeForABI(RetTy)) { 8243 // Records with non-trivial destructors/copy-constructors should not be 8244 // returned by value. 8245 if (!getRecordArgABI(RetTy, getCXXABI())) { 8246 // Ignore empty structs/unions. 8247 if (isEmptyRecord(getContext(), RetTy, true)) 8248 return ABIArgInfo::getIgnore(); 8249 8250 // Lower single-element structs to just return a regular value. 8251 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext())) 8252 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0))); 8253 8254 if (const RecordType *RT = RetTy->getAs<RecordType>()) { 8255 const RecordDecl *RD = RT->getDecl(); 8256 if (RD->hasFlexibleArrayMember()) 8257 return DefaultABIInfo::classifyReturnType(RetTy); 8258 } 8259 8260 // Pack aggregates <= 4 bytes into single VGPR or pair. 8261 uint64_t Size = getContext().getTypeSize(RetTy); 8262 if (Size <= 16) 8263 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext())); 8264 8265 if (Size <= 32) 8266 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext())); 8267 8268 if (Size <= 64) { 8269 llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext()); 8270 return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2)); 8271 } 8272 8273 if (numRegsForType(RetTy) <= MaxNumRegsForArgsRet) 8274 return ABIArgInfo::getDirect(); 8275 } 8276 } 8277 8278 // Otherwise just do the default thing. 8279 return DefaultABIInfo::classifyReturnType(RetTy); 8280 } 8281 8282 /// For kernels all parameters are really passed in a special buffer. It doesn't 8283 /// make sense to pass anything byval, so everything must be direct. 8284 ABIArgInfo AMDGPUABIInfo::classifyKernelArgumentType(QualType Ty) const { 8285 Ty = useFirstFieldIfTransparentUnion(Ty); 8286 8287 // TODO: Can we omit empty structs? 8288 8289 llvm::Type *LTy = nullptr; 8290 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext())) 8291 LTy = CGT.ConvertType(QualType(SeltTy, 0)); 8292 8293 if (getContext().getLangOpts().HIP) { 8294 if (!LTy) 8295 LTy = CGT.ConvertType(Ty); 8296 LTy = coerceKernelArgumentType( 8297 LTy, /*FromAS=*/getContext().getTargetAddressSpace(LangAS::Default), 8298 /*ToAS=*/getContext().getTargetAddressSpace(LangAS::cuda_device)); 8299 } 8300 8301 // If we set CanBeFlattened to true, CodeGen will expand the struct to its 8302 // individual elements, which confuses the Clover OpenCL backend; therefore we 8303 // have to set it to false here. Other args of getDirect() are just defaults. 8304 return ABIArgInfo::getDirect(LTy, 0, nullptr, false); 8305 } 8306 8307 ABIArgInfo AMDGPUABIInfo::classifyArgumentType(QualType Ty, 8308 unsigned &NumRegsLeft) const { 8309 assert(NumRegsLeft <= MaxNumRegsForArgsRet && "register estimate underflow"); 8310 8311 Ty = useFirstFieldIfTransparentUnion(Ty); 8312 8313 if (isAggregateTypeForABI(Ty)) { 8314 // Records with non-trivial destructors/copy-constructors should not be 8315 // passed by value. 8316 if (auto RAA = getRecordArgABI(Ty, getCXXABI())) 8317 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 8318 8319 // Ignore empty structs/unions. 8320 if (isEmptyRecord(getContext(), Ty, true)) 8321 return ABIArgInfo::getIgnore(); 8322 8323 // Lower single-element structs to just pass a regular value. TODO: We 8324 // could do reasonable-size multiple-element structs too, using getExpand(), 8325 // though watch out for things like bitfields. 8326 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext())) 8327 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0))); 8328 8329 if (const RecordType *RT = Ty->getAs<RecordType>()) { 8330 const RecordDecl *RD = RT->getDecl(); 8331 if (RD->hasFlexibleArrayMember()) 8332 return DefaultABIInfo::classifyArgumentType(Ty); 8333 } 8334 8335 // Pack aggregates <= 8 bytes into single VGPR or pair. 8336 uint64_t Size = getContext().getTypeSize(Ty); 8337 if (Size <= 64) { 8338 unsigned NumRegs = (Size + 31) / 32; 8339 NumRegsLeft -= std::min(NumRegsLeft, NumRegs); 8340 8341 if (Size <= 16) 8342 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext())); 8343 8344 if (Size <= 32) 8345 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext())); 8346 8347 // XXX: Should this be i64 instead, and should the limit increase? 8348 llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext()); 8349 return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2)); 8350 } 8351 8352 if (NumRegsLeft > 0) { 8353 unsigned NumRegs = numRegsForType(Ty); 8354 if (NumRegsLeft >= NumRegs) { 8355 NumRegsLeft -= NumRegs; 8356 return ABIArgInfo::getDirect(); 8357 } 8358 } 8359 } 8360 8361 // Otherwise just do the default thing. 8362 ABIArgInfo ArgInfo = DefaultABIInfo::classifyArgumentType(Ty); 8363 if (!ArgInfo.isIndirect()) { 8364 unsigned NumRegs = numRegsForType(Ty); 8365 NumRegsLeft -= std::min(NumRegs, NumRegsLeft); 8366 } 8367 8368 return ArgInfo; 8369 } 8370 8371 class AMDGPUTargetCodeGenInfo : public TargetCodeGenInfo { 8372 public: 8373 AMDGPUTargetCodeGenInfo(CodeGenTypes &CGT) 8374 : TargetCodeGenInfo(new AMDGPUABIInfo(CGT)) {} 8375 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 8376 CodeGen::CodeGenModule &M) const override; 8377 unsigned getOpenCLKernelCallingConv() const override; 8378 8379 llvm::Constant *getNullPointer(const CodeGen::CodeGenModule &CGM, 8380 llvm::PointerType *T, QualType QT) const override; 8381 8382 LangAS getASTAllocaAddressSpace() const override { 8383 return getLangASFromTargetAS( 8384 getABIInfo().getDataLayout().getAllocaAddrSpace()); 8385 } 8386 LangAS getGlobalVarAddressSpace(CodeGenModule &CGM, 8387 const VarDecl *D) const override; 8388 llvm::SyncScope::ID getLLVMSyncScopeID(const LangOptions &LangOpts, 8389 SyncScope Scope, 8390 llvm::AtomicOrdering Ordering, 8391 llvm::LLVMContext &Ctx) const override; 8392 llvm::Function * 8393 createEnqueuedBlockKernel(CodeGenFunction &CGF, 8394 llvm::Function *BlockInvokeFunc, 8395 llvm::Value *BlockLiteral) const override; 8396 bool shouldEmitStaticExternCAliases() const override; 8397 void setCUDAKernelCallingConvention(const FunctionType *&FT) const override; 8398 }; 8399 } 8400 8401 static bool requiresAMDGPUProtectedVisibility(const Decl *D, 8402 llvm::GlobalValue *GV) { 8403 if (GV->getVisibility() != llvm::GlobalValue::HiddenVisibility) 8404 return false; 8405 8406 return D->hasAttr<OpenCLKernelAttr>() || 8407 (isa<FunctionDecl>(D) && D->hasAttr<CUDAGlobalAttr>()) || 8408 (isa<VarDecl>(D) && 8409 (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>() || 8410 D->hasAttr<HIPPinnedShadowAttr>())); 8411 } 8412 8413 static bool requiresAMDGPUDefaultVisibility(const Decl *D, 8414 llvm::GlobalValue *GV) { 8415 if (GV->getVisibility() != llvm::GlobalValue::HiddenVisibility) 8416 return false; 8417 8418 return isa<VarDecl>(D) && D->hasAttr<HIPPinnedShadowAttr>(); 8419 } 8420 8421 void AMDGPUTargetCodeGenInfo::setTargetAttributes( 8422 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const { 8423 if (requiresAMDGPUDefaultVisibility(D, GV)) { 8424 GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 8425 GV->setDSOLocal(false); 8426 } else if (requiresAMDGPUProtectedVisibility(D, GV)) { 8427 GV->setVisibility(llvm::GlobalValue::ProtectedVisibility); 8428 GV->setDSOLocal(true); 8429 } 8430 8431 if (GV->isDeclaration()) 8432 return; 8433 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D); 8434 if (!FD) 8435 return; 8436 8437 llvm::Function *F = cast<llvm::Function>(GV); 8438 8439 const auto *ReqdWGS = M.getLangOpts().OpenCL ? 8440 FD->getAttr<ReqdWorkGroupSizeAttr>() : nullptr; 8441 8442 8443 const bool IsOpenCLKernel = M.getLangOpts().OpenCL && 8444 FD->hasAttr<OpenCLKernelAttr>(); 8445 const bool IsHIPKernel = M.getLangOpts().HIP && 8446 FD->hasAttr<CUDAGlobalAttr>(); 8447 if ((IsOpenCLKernel || IsHIPKernel) && 8448 (M.getTriple().getOS() == llvm::Triple::AMDHSA)) 8449 F->addFnAttr("amdgpu-implicitarg-num-bytes", "56"); 8450 8451 if (IsHIPKernel) 8452 F->addFnAttr("uniform-work-group-size", "true"); 8453 8454 8455 const auto *FlatWGS = FD->getAttr<AMDGPUFlatWorkGroupSizeAttr>(); 8456 if (ReqdWGS || FlatWGS) { 8457 unsigned Min = 0; 8458 unsigned Max = 0; 8459 if (FlatWGS) { 8460 Min = FlatWGS->getMin() 8461 ->EvaluateKnownConstInt(M.getContext()) 8462 .getExtValue(); 8463 Max = FlatWGS->getMax() 8464 ->EvaluateKnownConstInt(M.getContext()) 8465 .getExtValue(); 8466 } 8467 if (ReqdWGS && Min == 0 && Max == 0) 8468 Min = Max = ReqdWGS->getXDim() * ReqdWGS->getYDim() * ReqdWGS->getZDim(); 8469 8470 if (Min != 0) { 8471 assert(Min <= Max && "Min must be less than or equal Max"); 8472 8473 std::string AttrVal = llvm::utostr(Min) + "," + llvm::utostr(Max); 8474 F->addFnAttr("amdgpu-flat-work-group-size", AttrVal); 8475 } else 8476 assert(Max == 0 && "Max must be zero"); 8477 } else if (IsOpenCLKernel || IsHIPKernel) { 8478 // By default, restrict the maximum size to a value specified by 8479 // --gpu-max-threads-per-block=n or its default value. 8480 std::string AttrVal = 8481 std::string("1,") + llvm::utostr(M.getLangOpts().GPUMaxThreadsPerBlock); 8482 F->addFnAttr("amdgpu-flat-work-group-size", AttrVal); 8483 } 8484 8485 if (const auto *Attr = FD->getAttr<AMDGPUWavesPerEUAttr>()) { 8486 unsigned Min = 8487 Attr->getMin()->EvaluateKnownConstInt(M.getContext()).getExtValue(); 8488 unsigned Max = Attr->getMax() ? Attr->getMax() 8489 ->EvaluateKnownConstInt(M.getContext()) 8490 .getExtValue() 8491 : 0; 8492 8493 if (Min != 0) { 8494 assert((Max == 0 || Min <= Max) && "Min must be less than or equal Max"); 8495 8496 std::string AttrVal = llvm::utostr(Min); 8497 if (Max != 0) 8498 AttrVal = AttrVal + "," + llvm::utostr(Max); 8499 F->addFnAttr("amdgpu-waves-per-eu", AttrVal); 8500 } else 8501 assert(Max == 0 && "Max must be zero"); 8502 } 8503 8504 if (const auto *Attr = FD->getAttr<AMDGPUNumSGPRAttr>()) { 8505 unsigned NumSGPR = Attr->getNumSGPR(); 8506 8507 if (NumSGPR != 0) 8508 F->addFnAttr("amdgpu-num-sgpr", llvm::utostr(NumSGPR)); 8509 } 8510 8511 if (const auto *Attr = FD->getAttr<AMDGPUNumVGPRAttr>()) { 8512 uint32_t NumVGPR = Attr->getNumVGPR(); 8513 8514 if (NumVGPR != 0) 8515 F->addFnAttr("amdgpu-num-vgpr", llvm::utostr(NumVGPR)); 8516 } 8517 } 8518 8519 unsigned AMDGPUTargetCodeGenInfo::getOpenCLKernelCallingConv() const { 8520 return llvm::CallingConv::AMDGPU_KERNEL; 8521 } 8522 8523 // Currently LLVM assumes null pointers always have value 0, 8524 // which results in incorrectly transformed IR. Therefore, instead of 8525 // emitting null pointers in private and local address spaces, a null 8526 // pointer in generic address space is emitted which is casted to a 8527 // pointer in local or private address space. 8528 llvm::Constant *AMDGPUTargetCodeGenInfo::getNullPointer( 8529 const CodeGen::CodeGenModule &CGM, llvm::PointerType *PT, 8530 QualType QT) const { 8531 if (CGM.getContext().getTargetNullPointerValue(QT) == 0) 8532 return llvm::ConstantPointerNull::get(PT); 8533 8534 auto &Ctx = CGM.getContext(); 8535 auto NPT = llvm::PointerType::get(PT->getElementType(), 8536 Ctx.getTargetAddressSpace(LangAS::opencl_generic)); 8537 return llvm::ConstantExpr::getAddrSpaceCast( 8538 llvm::ConstantPointerNull::get(NPT), PT); 8539 } 8540 8541 LangAS 8542 AMDGPUTargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM, 8543 const VarDecl *D) const { 8544 assert(!CGM.getLangOpts().OpenCL && 8545 !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) && 8546 "Address space agnostic languages only"); 8547 LangAS DefaultGlobalAS = getLangASFromTargetAS( 8548 CGM.getContext().getTargetAddressSpace(LangAS::opencl_global)); 8549 if (!D) 8550 return DefaultGlobalAS; 8551 8552 LangAS AddrSpace = D->getType().getAddressSpace(); 8553 assert(AddrSpace == LangAS::Default || isTargetAddressSpace(AddrSpace)); 8554 if (AddrSpace != LangAS::Default) 8555 return AddrSpace; 8556 8557 if (CGM.isTypeConstant(D->getType(), false)) { 8558 if (auto ConstAS = CGM.getTarget().getConstantAddressSpace()) 8559 return ConstAS.getValue(); 8560 } 8561 return DefaultGlobalAS; 8562 } 8563 8564 llvm::SyncScope::ID 8565 AMDGPUTargetCodeGenInfo::getLLVMSyncScopeID(const LangOptions &LangOpts, 8566 SyncScope Scope, 8567 llvm::AtomicOrdering Ordering, 8568 llvm::LLVMContext &Ctx) const { 8569 std::string Name; 8570 switch (Scope) { 8571 case SyncScope::OpenCLWorkGroup: 8572 Name = "workgroup"; 8573 break; 8574 case SyncScope::OpenCLDevice: 8575 Name = "agent"; 8576 break; 8577 case SyncScope::OpenCLAllSVMDevices: 8578 Name = ""; 8579 break; 8580 case SyncScope::OpenCLSubGroup: 8581 Name = "wavefront"; 8582 } 8583 8584 if (Ordering != llvm::AtomicOrdering::SequentiallyConsistent) { 8585 if (!Name.empty()) 8586 Name = Twine(Twine(Name) + Twine("-")).str(); 8587 8588 Name = Twine(Twine(Name) + Twine("one-as")).str(); 8589 } 8590 8591 return Ctx.getOrInsertSyncScopeID(Name); 8592 } 8593 8594 bool AMDGPUTargetCodeGenInfo::shouldEmitStaticExternCAliases() const { 8595 return false; 8596 } 8597 8598 void AMDGPUTargetCodeGenInfo::setCUDAKernelCallingConvention( 8599 const FunctionType *&FT) const { 8600 FT = getABIInfo().getContext().adjustFunctionType( 8601 FT, FT->getExtInfo().withCallingConv(CC_OpenCLKernel)); 8602 } 8603 8604 //===----------------------------------------------------------------------===// 8605 // SPARC v8 ABI Implementation. 8606 // Based on the SPARC Compliance Definition version 2.4.1. 8607 // 8608 // Ensures that complex values are passed in registers. 8609 // 8610 namespace { 8611 class SparcV8ABIInfo : public DefaultABIInfo { 8612 public: 8613 SparcV8ABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {} 8614 8615 private: 8616 ABIArgInfo classifyReturnType(QualType RetTy) const; 8617 void computeInfo(CGFunctionInfo &FI) const override; 8618 }; 8619 } // end anonymous namespace 8620 8621 8622 ABIArgInfo 8623 SparcV8ABIInfo::classifyReturnType(QualType Ty) const { 8624 if (Ty->isAnyComplexType()) { 8625 return ABIArgInfo::getDirect(); 8626 } 8627 else { 8628 return DefaultABIInfo::classifyReturnType(Ty); 8629 } 8630 } 8631 8632 void SparcV8ABIInfo::computeInfo(CGFunctionInfo &FI) const { 8633 8634 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 8635 for (auto &Arg : FI.arguments()) 8636 Arg.info = classifyArgumentType(Arg.type); 8637 } 8638 8639 namespace { 8640 class SparcV8TargetCodeGenInfo : public TargetCodeGenInfo { 8641 public: 8642 SparcV8TargetCodeGenInfo(CodeGenTypes &CGT) 8643 : TargetCodeGenInfo(new SparcV8ABIInfo(CGT)) {} 8644 }; 8645 } // end anonymous namespace 8646 8647 //===----------------------------------------------------------------------===// 8648 // SPARC v9 ABI Implementation. 8649 // Based on the SPARC Compliance Definition version 2.4.1. 8650 // 8651 // Function arguments a mapped to a nominal "parameter array" and promoted to 8652 // registers depending on their type. Each argument occupies 8 or 16 bytes in 8653 // the array, structs larger than 16 bytes are passed indirectly. 8654 // 8655 // One case requires special care: 8656 // 8657 // struct mixed { 8658 // int i; 8659 // float f; 8660 // }; 8661 // 8662 // When a struct mixed is passed by value, it only occupies 8 bytes in the 8663 // parameter array, but the int is passed in an integer register, and the float 8664 // is passed in a floating point register. This is represented as two arguments 8665 // with the LLVM IR inreg attribute: 8666 // 8667 // declare void f(i32 inreg %i, float inreg %f) 8668 // 8669 // The code generator will only allocate 4 bytes from the parameter array for 8670 // the inreg arguments. All other arguments are allocated a multiple of 8 8671 // bytes. 8672 // 8673 namespace { 8674 class SparcV9ABIInfo : public ABIInfo { 8675 public: 8676 SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {} 8677 8678 private: 8679 ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const; 8680 void computeInfo(CGFunctionInfo &FI) const override; 8681 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 8682 QualType Ty) const override; 8683 8684 // Coercion type builder for structs passed in registers. The coercion type 8685 // serves two purposes: 8686 // 8687 // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned' 8688 // in registers. 8689 // 2. Expose aligned floating point elements as first-level elements, so the 8690 // code generator knows to pass them in floating point registers. 8691 // 8692 // We also compute the InReg flag which indicates that the struct contains 8693 // aligned 32-bit floats. 8694 // 8695 struct CoerceBuilder { 8696 llvm::LLVMContext &Context; 8697 const llvm::DataLayout &DL; 8698 SmallVector<llvm::Type*, 8> Elems; 8699 uint64_t Size; 8700 bool InReg; 8701 8702 CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl) 8703 : Context(c), DL(dl), Size(0), InReg(false) {} 8704 8705 // Pad Elems with integers until Size is ToSize. 8706 void pad(uint64_t ToSize) { 8707 assert(ToSize >= Size && "Cannot remove elements"); 8708 if (ToSize == Size) 8709 return; 8710 8711 // Finish the current 64-bit word. 8712 uint64_t Aligned = llvm::alignTo(Size, 64); 8713 if (Aligned > Size && Aligned <= ToSize) { 8714 Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size)); 8715 Size = Aligned; 8716 } 8717 8718 // Add whole 64-bit words. 8719 while (Size + 64 <= ToSize) { 8720 Elems.push_back(llvm::Type::getInt64Ty(Context)); 8721 Size += 64; 8722 } 8723 8724 // Final in-word padding. 8725 if (Size < ToSize) { 8726 Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size)); 8727 Size = ToSize; 8728 } 8729 } 8730 8731 // Add a floating point element at Offset. 8732 void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) { 8733 // Unaligned floats are treated as integers. 8734 if (Offset % Bits) 8735 return; 8736 // The InReg flag is only required if there are any floats < 64 bits. 8737 if (Bits < 64) 8738 InReg = true; 8739 pad(Offset); 8740 Elems.push_back(Ty); 8741 Size = Offset + Bits; 8742 } 8743 8744 // Add a struct type to the coercion type, starting at Offset (in bits). 8745 void addStruct(uint64_t Offset, llvm::StructType *StrTy) { 8746 const llvm::StructLayout *Layout = DL.getStructLayout(StrTy); 8747 for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) { 8748 llvm::Type *ElemTy = StrTy->getElementType(i); 8749 uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i); 8750 switch (ElemTy->getTypeID()) { 8751 case llvm::Type::StructTyID: 8752 addStruct(ElemOffset, cast<llvm::StructType>(ElemTy)); 8753 break; 8754 case llvm::Type::FloatTyID: 8755 addFloat(ElemOffset, ElemTy, 32); 8756 break; 8757 case llvm::Type::DoubleTyID: 8758 addFloat(ElemOffset, ElemTy, 64); 8759 break; 8760 case llvm::Type::FP128TyID: 8761 addFloat(ElemOffset, ElemTy, 128); 8762 break; 8763 case llvm::Type::PointerTyID: 8764 if (ElemOffset % 64 == 0) { 8765 pad(ElemOffset); 8766 Elems.push_back(ElemTy); 8767 Size += 64; 8768 } 8769 break; 8770 default: 8771 break; 8772 } 8773 } 8774 } 8775 8776 // Check if Ty is a usable substitute for the coercion type. 8777 bool isUsableType(llvm::StructType *Ty) const { 8778 return llvm::makeArrayRef(Elems) == Ty->elements(); 8779 } 8780 8781 // Get the coercion type as a literal struct type. 8782 llvm::Type *getType() const { 8783 if (Elems.size() == 1) 8784 return Elems.front(); 8785 else 8786 return llvm::StructType::get(Context, Elems); 8787 } 8788 }; 8789 }; 8790 } // end anonymous namespace 8791 8792 ABIArgInfo 8793 SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const { 8794 if (Ty->isVoidType()) 8795 return ABIArgInfo::getIgnore(); 8796 8797 uint64_t Size = getContext().getTypeSize(Ty); 8798 8799 // Anything too big to fit in registers is passed with an explicit indirect 8800 // pointer / sret pointer. 8801 if (Size > SizeLimit) 8802 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 8803 8804 // Treat an enum type as its underlying type. 8805 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 8806 Ty = EnumTy->getDecl()->getIntegerType(); 8807 8808 // Integer types smaller than a register are extended. 8809 if (Size < 64 && Ty->isIntegerType()) 8810 return ABIArgInfo::getExtend(Ty); 8811 8812 // Other non-aggregates go in registers. 8813 if (!isAggregateTypeForABI(Ty)) 8814 return ABIArgInfo::getDirect(); 8815 8816 // If a C++ object has either a non-trivial copy constructor or a non-trivial 8817 // destructor, it is passed with an explicit indirect pointer / sret pointer. 8818 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 8819 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 8820 8821 // This is a small aggregate type that should be passed in registers. 8822 // Build a coercion type from the LLVM struct type. 8823 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty)); 8824 if (!StrTy) 8825 return ABIArgInfo::getDirect(); 8826 8827 CoerceBuilder CB(getVMContext(), getDataLayout()); 8828 CB.addStruct(0, StrTy); 8829 CB.pad(llvm::alignTo(CB.DL.getTypeSizeInBits(StrTy), 64)); 8830 8831 // Try to use the original type for coercion. 8832 llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType(); 8833 8834 if (CB.InReg) 8835 return ABIArgInfo::getDirectInReg(CoerceTy); 8836 else 8837 return ABIArgInfo::getDirect(CoerceTy); 8838 } 8839 8840 Address SparcV9ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 8841 QualType Ty) const { 8842 ABIArgInfo AI = classifyType(Ty, 16 * 8); 8843 llvm::Type *ArgTy = CGT.ConvertType(Ty); 8844 if (AI.canHaveCoerceToType() && !AI.getCoerceToType()) 8845 AI.setCoerceToType(ArgTy); 8846 8847 CharUnits SlotSize = CharUnits::fromQuantity(8); 8848 8849 CGBuilderTy &Builder = CGF.Builder; 8850 Address Addr(Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize); 8851 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy); 8852 8853 auto TypeInfo = getContext().getTypeInfoInChars(Ty); 8854 8855 Address ArgAddr = Address::invalid(); 8856 CharUnits Stride; 8857 switch (AI.getKind()) { 8858 case ABIArgInfo::Expand: 8859 case ABIArgInfo::CoerceAndExpand: 8860 case ABIArgInfo::InAlloca: 8861 llvm_unreachable("Unsupported ABI kind for va_arg"); 8862 8863 case ABIArgInfo::Extend: { 8864 Stride = SlotSize; 8865 CharUnits Offset = SlotSize - TypeInfo.first; 8866 ArgAddr = Builder.CreateConstInBoundsByteGEP(Addr, Offset, "extend"); 8867 break; 8868 } 8869 8870 case ABIArgInfo::Direct: { 8871 auto AllocSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType()); 8872 Stride = CharUnits::fromQuantity(AllocSize).alignTo(SlotSize); 8873 ArgAddr = Addr; 8874 break; 8875 } 8876 8877 case ABIArgInfo::Indirect: 8878 Stride = SlotSize; 8879 ArgAddr = Builder.CreateElementBitCast(Addr, ArgPtrTy, "indirect"); 8880 ArgAddr = Address(Builder.CreateLoad(ArgAddr, "indirect.arg"), 8881 TypeInfo.second); 8882 break; 8883 8884 case ABIArgInfo::Ignore: 8885 return Address(llvm::UndefValue::get(ArgPtrTy), TypeInfo.second); 8886 } 8887 8888 // Update VAList. 8889 Address NextPtr = Builder.CreateConstInBoundsByteGEP(Addr, Stride, "ap.next"); 8890 Builder.CreateStore(NextPtr.getPointer(), VAListAddr); 8891 8892 return Builder.CreateBitCast(ArgAddr, ArgPtrTy, "arg.addr"); 8893 } 8894 8895 void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const { 8896 FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8); 8897 for (auto &I : FI.arguments()) 8898 I.info = classifyType(I.type, 16 * 8); 8899 } 8900 8901 namespace { 8902 class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo { 8903 public: 8904 SparcV9TargetCodeGenInfo(CodeGenTypes &CGT) 8905 : TargetCodeGenInfo(new SparcV9ABIInfo(CGT)) {} 8906 8907 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 8908 return 14; 8909 } 8910 8911 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 8912 llvm::Value *Address) const override; 8913 }; 8914 } // end anonymous namespace 8915 8916 bool 8917 SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 8918 llvm::Value *Address) const { 8919 // This is calculated from the LLVM and GCC tables and verified 8920 // against gcc output. AFAIK all ABIs use the same encoding. 8921 8922 CodeGen::CGBuilderTy &Builder = CGF.Builder; 8923 8924 llvm::IntegerType *i8 = CGF.Int8Ty; 8925 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4); 8926 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8); 8927 8928 // 0-31: the 8-byte general-purpose registers 8929 AssignToArrayRange(Builder, Address, Eight8, 0, 31); 8930 8931 // 32-63: f0-31, the 4-byte floating-point registers 8932 AssignToArrayRange(Builder, Address, Four8, 32, 63); 8933 8934 // Y = 64 8935 // PSR = 65 8936 // WIM = 66 8937 // TBR = 67 8938 // PC = 68 8939 // NPC = 69 8940 // FSR = 70 8941 // CSR = 71 8942 AssignToArrayRange(Builder, Address, Eight8, 64, 71); 8943 8944 // 72-87: d0-15, the 8-byte floating-point registers 8945 AssignToArrayRange(Builder, Address, Eight8, 72, 87); 8946 8947 return false; 8948 } 8949 8950 // ARC ABI implementation. 8951 namespace { 8952 8953 class ARCABIInfo : public DefaultABIInfo { 8954 public: 8955 using DefaultABIInfo::DefaultABIInfo; 8956 8957 private: 8958 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 8959 QualType Ty) const override; 8960 8961 void updateState(const ABIArgInfo &Info, QualType Ty, CCState &State) const { 8962 if (!State.FreeRegs) 8963 return; 8964 if (Info.isIndirect() && Info.getInReg()) 8965 State.FreeRegs--; 8966 else if (Info.isDirect() && Info.getInReg()) { 8967 unsigned sz = (getContext().getTypeSize(Ty) + 31) / 32; 8968 if (sz < State.FreeRegs) 8969 State.FreeRegs -= sz; 8970 else 8971 State.FreeRegs = 0; 8972 } 8973 } 8974 8975 void computeInfo(CGFunctionInfo &FI) const override { 8976 CCState State(FI); 8977 // ARC uses 8 registers to pass arguments. 8978 State.FreeRegs = 8; 8979 8980 if (!getCXXABI().classifyReturnType(FI)) 8981 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 8982 updateState(FI.getReturnInfo(), FI.getReturnType(), State); 8983 for (auto &I : FI.arguments()) { 8984 I.info = classifyArgumentType(I.type, State.FreeRegs); 8985 updateState(I.info, I.type, State); 8986 } 8987 } 8988 8989 ABIArgInfo getIndirectByRef(QualType Ty, bool HasFreeRegs) const; 8990 ABIArgInfo getIndirectByValue(QualType Ty) const; 8991 ABIArgInfo classifyArgumentType(QualType Ty, uint8_t FreeRegs) const; 8992 ABIArgInfo classifyReturnType(QualType RetTy) const; 8993 }; 8994 8995 class ARCTargetCodeGenInfo : public TargetCodeGenInfo { 8996 public: 8997 ARCTargetCodeGenInfo(CodeGenTypes &CGT) 8998 : TargetCodeGenInfo(new ARCABIInfo(CGT)) {} 8999 }; 9000 9001 9002 ABIArgInfo ARCABIInfo::getIndirectByRef(QualType Ty, bool HasFreeRegs) const { 9003 return HasFreeRegs ? getNaturalAlignIndirectInReg(Ty) : 9004 getNaturalAlignIndirect(Ty, false); 9005 } 9006 9007 ABIArgInfo ARCABIInfo::getIndirectByValue(QualType Ty) const { 9008 // Compute the byval alignment. 9009 const unsigned MinABIStackAlignInBytes = 4; 9010 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8; 9011 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true, 9012 TypeAlign > MinABIStackAlignInBytes); 9013 } 9014 9015 Address ARCABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 9016 QualType Ty) const { 9017 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false, 9018 getContext().getTypeInfoInChars(Ty), 9019 CharUnits::fromQuantity(4), true); 9020 } 9021 9022 ABIArgInfo ARCABIInfo::classifyArgumentType(QualType Ty, 9023 uint8_t FreeRegs) const { 9024 // Handle the generic C++ ABI. 9025 const RecordType *RT = Ty->getAs<RecordType>(); 9026 if (RT) { 9027 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()); 9028 if (RAA == CGCXXABI::RAA_Indirect) 9029 return getIndirectByRef(Ty, FreeRegs > 0); 9030 9031 if (RAA == CGCXXABI::RAA_DirectInMemory) 9032 return getIndirectByValue(Ty); 9033 } 9034 9035 // Treat an enum type as its underlying type. 9036 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 9037 Ty = EnumTy->getDecl()->getIntegerType(); 9038 9039 auto SizeInRegs = llvm::alignTo(getContext().getTypeSize(Ty), 32) / 32; 9040 9041 if (isAggregateTypeForABI(Ty)) { 9042 // Structures with flexible arrays are always indirect. 9043 if (RT && RT->getDecl()->hasFlexibleArrayMember()) 9044 return getIndirectByValue(Ty); 9045 9046 // Ignore empty structs/unions. 9047 if (isEmptyRecord(getContext(), Ty, true)) 9048 return ABIArgInfo::getIgnore(); 9049 9050 llvm::LLVMContext &LLVMContext = getVMContext(); 9051 9052 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext); 9053 SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32); 9054 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements); 9055 9056 return FreeRegs >= SizeInRegs ? 9057 ABIArgInfo::getDirectInReg(Result) : 9058 ABIArgInfo::getDirect(Result, 0, nullptr, false); 9059 } 9060 9061 return Ty->isPromotableIntegerType() ? 9062 (FreeRegs >= SizeInRegs ? ABIArgInfo::getExtendInReg(Ty) : 9063 ABIArgInfo::getExtend(Ty)) : 9064 (FreeRegs >= SizeInRegs ? ABIArgInfo::getDirectInReg() : 9065 ABIArgInfo::getDirect()); 9066 } 9067 9068 ABIArgInfo ARCABIInfo::classifyReturnType(QualType RetTy) const { 9069 if (RetTy->isAnyComplexType()) 9070 return ABIArgInfo::getDirectInReg(); 9071 9072 // Arguments of size > 4 registers are indirect. 9073 auto RetSize = llvm::alignTo(getContext().getTypeSize(RetTy), 32) / 32; 9074 if (RetSize > 4) 9075 return getIndirectByRef(RetTy, /*HasFreeRegs*/ true); 9076 9077 return DefaultABIInfo::classifyReturnType(RetTy); 9078 } 9079 9080 } // End anonymous namespace. 9081 9082 //===----------------------------------------------------------------------===// 9083 // XCore ABI Implementation 9084 //===----------------------------------------------------------------------===// 9085 9086 namespace { 9087 9088 /// A SmallStringEnc instance is used to build up the TypeString by passing 9089 /// it by reference between functions that append to it. 9090 typedef llvm::SmallString<128> SmallStringEnc; 9091 9092 /// TypeStringCache caches the meta encodings of Types. 9093 /// 9094 /// The reason for caching TypeStrings is two fold: 9095 /// 1. To cache a type's encoding for later uses; 9096 /// 2. As a means to break recursive member type inclusion. 9097 /// 9098 /// A cache Entry can have a Status of: 9099 /// NonRecursive: The type encoding is not recursive; 9100 /// Recursive: The type encoding is recursive; 9101 /// Incomplete: An incomplete TypeString; 9102 /// IncompleteUsed: An incomplete TypeString that has been used in a 9103 /// Recursive type encoding. 9104 /// 9105 /// A NonRecursive entry will have all of its sub-members expanded as fully 9106 /// as possible. Whilst it may contain types which are recursive, the type 9107 /// itself is not recursive and thus its encoding may be safely used whenever 9108 /// the type is encountered. 9109 /// 9110 /// A Recursive entry will have all of its sub-members expanded as fully as 9111 /// possible. The type itself is recursive and it may contain other types which 9112 /// are recursive. The Recursive encoding must not be used during the expansion 9113 /// of a recursive type's recursive branch. For simplicity the code uses 9114 /// IncompleteCount to reject all usage of Recursive encodings for member types. 9115 /// 9116 /// An Incomplete entry is always a RecordType and only encodes its 9117 /// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and 9118 /// are placed into the cache during type expansion as a means to identify and 9119 /// handle recursive inclusion of types as sub-members. If there is recursion 9120 /// the entry becomes IncompleteUsed. 9121 /// 9122 /// During the expansion of a RecordType's members: 9123 /// 9124 /// If the cache contains a NonRecursive encoding for the member type, the 9125 /// cached encoding is used; 9126 /// 9127 /// If the cache contains a Recursive encoding for the member type, the 9128 /// cached encoding is 'Swapped' out, as it may be incorrect, and... 9129 /// 9130 /// If the member is a RecordType, an Incomplete encoding is placed into the 9131 /// cache to break potential recursive inclusion of itself as a sub-member; 9132 /// 9133 /// Once a member RecordType has been expanded, its temporary incomplete 9134 /// entry is removed from the cache. If a Recursive encoding was swapped out 9135 /// it is swapped back in; 9136 /// 9137 /// If an incomplete entry is used to expand a sub-member, the incomplete 9138 /// entry is marked as IncompleteUsed. The cache keeps count of how many 9139 /// IncompleteUsed entries it currently contains in IncompleteUsedCount; 9140 /// 9141 /// If a member's encoding is found to be a NonRecursive or Recursive viz: 9142 /// IncompleteUsedCount==0, the member's encoding is added to the cache. 9143 /// Else the member is part of a recursive type and thus the recursion has 9144 /// been exited too soon for the encoding to be correct for the member. 9145 /// 9146 class TypeStringCache { 9147 enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed}; 9148 struct Entry { 9149 std::string Str; // The encoded TypeString for the type. 9150 enum Status State; // Information about the encoding in 'Str'. 9151 std::string Swapped; // A temporary place holder for a Recursive encoding 9152 // during the expansion of RecordType's members. 9153 }; 9154 std::map<const IdentifierInfo *, struct Entry> Map; 9155 unsigned IncompleteCount; // Number of Incomplete entries in the Map. 9156 unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map. 9157 public: 9158 TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {} 9159 void addIncomplete(const IdentifierInfo *ID, std::string StubEnc); 9160 bool removeIncomplete(const IdentifierInfo *ID); 9161 void addIfComplete(const IdentifierInfo *ID, StringRef Str, 9162 bool IsRecursive); 9163 StringRef lookupStr(const IdentifierInfo *ID); 9164 }; 9165 9166 /// TypeString encodings for enum & union fields must be order. 9167 /// FieldEncoding is a helper for this ordering process. 9168 class FieldEncoding { 9169 bool HasName; 9170 std::string Enc; 9171 public: 9172 FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {} 9173 StringRef str() { return Enc; } 9174 bool operator<(const FieldEncoding &rhs) const { 9175 if (HasName != rhs.HasName) return HasName; 9176 return Enc < rhs.Enc; 9177 } 9178 }; 9179 9180 class XCoreABIInfo : public DefaultABIInfo { 9181 public: 9182 XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {} 9183 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 9184 QualType Ty) const override; 9185 }; 9186 9187 class XCoreTargetCodeGenInfo : public TargetCodeGenInfo { 9188 mutable TypeStringCache TSC; 9189 public: 9190 XCoreTargetCodeGenInfo(CodeGenTypes &CGT) 9191 :TargetCodeGenInfo(new XCoreABIInfo(CGT)) {} 9192 void emitTargetMD(const Decl *D, llvm::GlobalValue *GV, 9193 CodeGen::CodeGenModule &M) const override; 9194 }; 9195 9196 } // End anonymous namespace. 9197 9198 // TODO: this implementation is likely now redundant with the default 9199 // EmitVAArg. 9200 Address XCoreABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 9201 QualType Ty) const { 9202 CGBuilderTy &Builder = CGF.Builder; 9203 9204 // Get the VAList. 9205 CharUnits SlotSize = CharUnits::fromQuantity(4); 9206 Address AP(Builder.CreateLoad(VAListAddr), SlotSize); 9207 9208 // Handle the argument. 9209 ABIArgInfo AI = classifyArgumentType(Ty); 9210 CharUnits TypeAlign = getContext().getTypeAlignInChars(Ty); 9211 llvm::Type *ArgTy = CGT.ConvertType(Ty); 9212 if (AI.canHaveCoerceToType() && !AI.getCoerceToType()) 9213 AI.setCoerceToType(ArgTy); 9214 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy); 9215 9216 Address Val = Address::invalid(); 9217 CharUnits ArgSize = CharUnits::Zero(); 9218 switch (AI.getKind()) { 9219 case ABIArgInfo::Expand: 9220 case ABIArgInfo::CoerceAndExpand: 9221 case ABIArgInfo::InAlloca: 9222 llvm_unreachable("Unsupported ABI kind for va_arg"); 9223 case ABIArgInfo::Ignore: 9224 Val = Address(llvm::UndefValue::get(ArgPtrTy), TypeAlign); 9225 ArgSize = CharUnits::Zero(); 9226 break; 9227 case ABIArgInfo::Extend: 9228 case ABIArgInfo::Direct: 9229 Val = Builder.CreateBitCast(AP, ArgPtrTy); 9230 ArgSize = CharUnits::fromQuantity( 9231 getDataLayout().getTypeAllocSize(AI.getCoerceToType())); 9232 ArgSize = ArgSize.alignTo(SlotSize); 9233 break; 9234 case ABIArgInfo::Indirect: 9235 Val = Builder.CreateElementBitCast(AP, ArgPtrTy); 9236 Val = Address(Builder.CreateLoad(Val), TypeAlign); 9237 ArgSize = SlotSize; 9238 break; 9239 } 9240 9241 // Increment the VAList. 9242 if (!ArgSize.isZero()) { 9243 Address APN = Builder.CreateConstInBoundsByteGEP(AP, ArgSize); 9244 Builder.CreateStore(APN.getPointer(), VAListAddr); 9245 } 9246 9247 return Val; 9248 } 9249 9250 /// During the expansion of a RecordType, an incomplete TypeString is placed 9251 /// into the cache as a means to identify and break recursion. 9252 /// If there is a Recursive encoding in the cache, it is swapped out and will 9253 /// be reinserted by removeIncomplete(). 9254 /// All other types of encoding should have been used rather than arriving here. 9255 void TypeStringCache::addIncomplete(const IdentifierInfo *ID, 9256 std::string StubEnc) { 9257 if (!ID) 9258 return; 9259 Entry &E = Map[ID]; 9260 assert( (E.Str.empty() || E.State == Recursive) && 9261 "Incorrectly use of addIncomplete"); 9262 assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()"); 9263 E.Swapped.swap(E.Str); // swap out the Recursive 9264 E.Str.swap(StubEnc); 9265 E.State = Incomplete; 9266 ++IncompleteCount; 9267 } 9268 9269 /// Once the RecordType has been expanded, the temporary incomplete TypeString 9270 /// must be removed from the cache. 9271 /// If a Recursive was swapped out by addIncomplete(), it will be replaced. 9272 /// Returns true if the RecordType was defined recursively. 9273 bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) { 9274 if (!ID) 9275 return false; 9276 auto I = Map.find(ID); 9277 assert(I != Map.end() && "Entry not present"); 9278 Entry &E = I->second; 9279 assert( (E.State == Incomplete || 9280 E.State == IncompleteUsed) && 9281 "Entry must be an incomplete type"); 9282 bool IsRecursive = false; 9283 if (E.State == IncompleteUsed) { 9284 // We made use of our Incomplete encoding, thus we are recursive. 9285 IsRecursive = true; 9286 --IncompleteUsedCount; 9287 } 9288 if (E.Swapped.empty()) 9289 Map.erase(I); 9290 else { 9291 // Swap the Recursive back. 9292 E.Swapped.swap(E.Str); 9293 E.Swapped.clear(); 9294 E.State = Recursive; 9295 } 9296 --IncompleteCount; 9297 return IsRecursive; 9298 } 9299 9300 /// Add the encoded TypeString to the cache only if it is NonRecursive or 9301 /// Recursive (viz: all sub-members were expanded as fully as possible). 9302 void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str, 9303 bool IsRecursive) { 9304 if (!ID || IncompleteUsedCount) 9305 return; // No key or it is is an incomplete sub-type so don't add. 9306 Entry &E = Map[ID]; 9307 if (IsRecursive && !E.Str.empty()) { 9308 assert(E.State==Recursive && E.Str.size() == Str.size() && 9309 "This is not the same Recursive entry"); 9310 // The parent container was not recursive after all, so we could have used 9311 // this Recursive sub-member entry after all, but we assumed the worse when 9312 // we started viz: IncompleteCount!=0. 9313 return; 9314 } 9315 assert(E.Str.empty() && "Entry already present"); 9316 E.Str = Str.str(); 9317 E.State = IsRecursive? Recursive : NonRecursive; 9318 } 9319 9320 /// Return a cached TypeString encoding for the ID. If there isn't one, or we 9321 /// are recursively expanding a type (IncompleteCount != 0) and the cached 9322 /// encoding is Recursive, return an empty StringRef. 9323 StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) { 9324 if (!ID) 9325 return StringRef(); // We have no key. 9326 auto I = Map.find(ID); 9327 if (I == Map.end()) 9328 return StringRef(); // We have no encoding. 9329 Entry &E = I->second; 9330 if (E.State == Recursive && IncompleteCount) 9331 return StringRef(); // We don't use Recursive encodings for member types. 9332 9333 if (E.State == Incomplete) { 9334 // The incomplete type is being used to break out of recursion. 9335 E.State = IncompleteUsed; 9336 ++IncompleteUsedCount; 9337 } 9338 return E.Str; 9339 } 9340 9341 /// The XCore ABI includes a type information section that communicates symbol 9342 /// type information to the linker. The linker uses this information to verify 9343 /// safety/correctness of things such as array bound and pointers et al. 9344 /// The ABI only requires C (and XC) language modules to emit TypeStrings. 9345 /// This type information (TypeString) is emitted into meta data for all global 9346 /// symbols: definitions, declarations, functions & variables. 9347 /// 9348 /// The TypeString carries type, qualifier, name, size & value details. 9349 /// Please see 'Tools Development Guide' section 2.16.2 for format details: 9350 /// https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf 9351 /// The output is tested by test/CodeGen/xcore-stringtype.c. 9352 /// 9353 static bool getTypeString(SmallStringEnc &Enc, const Decl *D, 9354 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC); 9355 9356 /// XCore uses emitTargetMD to emit TypeString metadata for global symbols. 9357 void XCoreTargetCodeGenInfo::emitTargetMD(const Decl *D, llvm::GlobalValue *GV, 9358 CodeGen::CodeGenModule &CGM) const { 9359 SmallStringEnc Enc; 9360 if (getTypeString(Enc, D, CGM, TSC)) { 9361 llvm::LLVMContext &Ctx = CGM.getModule().getContext(); 9362 llvm::Metadata *MDVals[] = {llvm::ConstantAsMetadata::get(GV), 9363 llvm::MDString::get(Ctx, Enc.str())}; 9364 llvm::NamedMDNode *MD = 9365 CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings"); 9366 MD->addOperand(llvm::MDNode::get(Ctx, MDVals)); 9367 } 9368 } 9369 9370 //===----------------------------------------------------------------------===// 9371 // SPIR ABI Implementation 9372 //===----------------------------------------------------------------------===// 9373 9374 namespace { 9375 class SPIRTargetCodeGenInfo : public TargetCodeGenInfo { 9376 public: 9377 SPIRTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT) 9378 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {} 9379 unsigned getOpenCLKernelCallingConv() const override; 9380 }; 9381 9382 } // End anonymous namespace. 9383 9384 namespace clang { 9385 namespace CodeGen { 9386 void computeSPIRKernelABIInfo(CodeGenModule &CGM, CGFunctionInfo &FI) { 9387 DefaultABIInfo SPIRABI(CGM.getTypes()); 9388 SPIRABI.computeInfo(FI); 9389 } 9390 } 9391 } 9392 9393 unsigned SPIRTargetCodeGenInfo::getOpenCLKernelCallingConv() const { 9394 return llvm::CallingConv::SPIR_KERNEL; 9395 } 9396 9397 static bool appendType(SmallStringEnc &Enc, QualType QType, 9398 const CodeGen::CodeGenModule &CGM, 9399 TypeStringCache &TSC); 9400 9401 /// Helper function for appendRecordType(). 9402 /// Builds a SmallVector containing the encoded field types in declaration 9403 /// order. 9404 static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE, 9405 const RecordDecl *RD, 9406 const CodeGen::CodeGenModule &CGM, 9407 TypeStringCache &TSC) { 9408 for (const auto *Field : RD->fields()) { 9409 SmallStringEnc Enc; 9410 Enc += "m("; 9411 Enc += Field->getName(); 9412 Enc += "){"; 9413 if (Field->isBitField()) { 9414 Enc += "b("; 9415 llvm::raw_svector_ostream OS(Enc); 9416 OS << Field->getBitWidthValue(CGM.getContext()); 9417 Enc += ':'; 9418 } 9419 if (!appendType(Enc, Field->getType(), CGM, TSC)) 9420 return false; 9421 if (Field->isBitField()) 9422 Enc += ')'; 9423 Enc += '}'; 9424 FE.emplace_back(!Field->getName().empty(), Enc); 9425 } 9426 return true; 9427 } 9428 9429 /// Appends structure and union types to Enc and adds encoding to cache. 9430 /// Recursively calls appendType (via extractFieldType) for each field. 9431 /// Union types have their fields ordered according to the ABI. 9432 static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT, 9433 const CodeGen::CodeGenModule &CGM, 9434 TypeStringCache &TSC, const IdentifierInfo *ID) { 9435 // Append the cached TypeString if we have one. 9436 StringRef TypeString = TSC.lookupStr(ID); 9437 if (!TypeString.empty()) { 9438 Enc += TypeString; 9439 return true; 9440 } 9441 9442 // Start to emit an incomplete TypeString. 9443 size_t Start = Enc.size(); 9444 Enc += (RT->isUnionType()? 'u' : 's'); 9445 Enc += '('; 9446 if (ID) 9447 Enc += ID->getName(); 9448 Enc += "){"; 9449 9450 // We collect all encoded fields and order as necessary. 9451 bool IsRecursive = false; 9452 const RecordDecl *RD = RT->getDecl()->getDefinition(); 9453 if (RD && !RD->field_empty()) { 9454 // An incomplete TypeString stub is placed in the cache for this RecordType 9455 // so that recursive calls to this RecordType will use it whilst building a 9456 // complete TypeString for this RecordType. 9457 SmallVector<FieldEncoding, 16> FE; 9458 std::string StubEnc(Enc.substr(Start).str()); 9459 StubEnc += '}'; // StubEnc now holds a valid incomplete TypeString. 9460 TSC.addIncomplete(ID, std::move(StubEnc)); 9461 if (!extractFieldType(FE, RD, CGM, TSC)) { 9462 (void) TSC.removeIncomplete(ID); 9463 return false; 9464 } 9465 IsRecursive = TSC.removeIncomplete(ID); 9466 // The ABI requires unions to be sorted but not structures. 9467 // See FieldEncoding::operator< for sort algorithm. 9468 if (RT->isUnionType()) 9469 llvm::sort(FE); 9470 // We can now complete the TypeString. 9471 unsigned E = FE.size(); 9472 for (unsigned I = 0; I != E; ++I) { 9473 if (I) 9474 Enc += ','; 9475 Enc += FE[I].str(); 9476 } 9477 } 9478 Enc += '}'; 9479 TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive); 9480 return true; 9481 } 9482 9483 /// Appends enum types to Enc and adds the encoding to the cache. 9484 static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET, 9485 TypeStringCache &TSC, 9486 const IdentifierInfo *ID) { 9487 // Append the cached TypeString if we have one. 9488 StringRef TypeString = TSC.lookupStr(ID); 9489 if (!TypeString.empty()) { 9490 Enc += TypeString; 9491 return true; 9492 } 9493 9494 size_t Start = Enc.size(); 9495 Enc += "e("; 9496 if (ID) 9497 Enc += ID->getName(); 9498 Enc += "){"; 9499 9500 // We collect all encoded enumerations and order them alphanumerically. 9501 if (const EnumDecl *ED = ET->getDecl()->getDefinition()) { 9502 SmallVector<FieldEncoding, 16> FE; 9503 for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E; 9504 ++I) { 9505 SmallStringEnc EnumEnc; 9506 EnumEnc += "m("; 9507 EnumEnc += I->getName(); 9508 EnumEnc += "){"; 9509 I->getInitVal().toString(EnumEnc); 9510 EnumEnc += '}'; 9511 FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc)); 9512 } 9513 llvm::sort(FE); 9514 unsigned E = FE.size(); 9515 for (unsigned I = 0; I != E; ++I) { 9516 if (I) 9517 Enc += ','; 9518 Enc += FE[I].str(); 9519 } 9520 } 9521 Enc += '}'; 9522 TSC.addIfComplete(ID, Enc.substr(Start), false); 9523 return true; 9524 } 9525 9526 /// Appends type's qualifier to Enc. 9527 /// This is done prior to appending the type's encoding. 9528 static void appendQualifier(SmallStringEnc &Enc, QualType QT) { 9529 // Qualifiers are emitted in alphabetical order. 9530 static const char *const Table[]={"","c:","r:","cr:","v:","cv:","rv:","crv:"}; 9531 int Lookup = 0; 9532 if (QT.isConstQualified()) 9533 Lookup += 1<<0; 9534 if (QT.isRestrictQualified()) 9535 Lookup += 1<<1; 9536 if (QT.isVolatileQualified()) 9537 Lookup += 1<<2; 9538 Enc += Table[Lookup]; 9539 } 9540 9541 /// Appends built-in types to Enc. 9542 static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) { 9543 const char *EncType; 9544 switch (BT->getKind()) { 9545 case BuiltinType::Void: 9546 EncType = "0"; 9547 break; 9548 case BuiltinType::Bool: 9549 EncType = "b"; 9550 break; 9551 case BuiltinType::Char_U: 9552 EncType = "uc"; 9553 break; 9554 case BuiltinType::UChar: 9555 EncType = "uc"; 9556 break; 9557 case BuiltinType::SChar: 9558 EncType = "sc"; 9559 break; 9560 case BuiltinType::UShort: 9561 EncType = "us"; 9562 break; 9563 case BuiltinType::Short: 9564 EncType = "ss"; 9565 break; 9566 case BuiltinType::UInt: 9567 EncType = "ui"; 9568 break; 9569 case BuiltinType::Int: 9570 EncType = "si"; 9571 break; 9572 case BuiltinType::ULong: 9573 EncType = "ul"; 9574 break; 9575 case BuiltinType::Long: 9576 EncType = "sl"; 9577 break; 9578 case BuiltinType::ULongLong: 9579 EncType = "ull"; 9580 break; 9581 case BuiltinType::LongLong: 9582 EncType = "sll"; 9583 break; 9584 case BuiltinType::Float: 9585 EncType = "ft"; 9586 break; 9587 case BuiltinType::Double: 9588 EncType = "d"; 9589 break; 9590 case BuiltinType::LongDouble: 9591 EncType = "ld"; 9592 break; 9593 default: 9594 return false; 9595 } 9596 Enc += EncType; 9597 return true; 9598 } 9599 9600 /// Appends a pointer encoding to Enc before calling appendType for the pointee. 9601 static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT, 9602 const CodeGen::CodeGenModule &CGM, 9603 TypeStringCache &TSC) { 9604 Enc += "p("; 9605 if (!appendType(Enc, PT->getPointeeType(), CGM, TSC)) 9606 return false; 9607 Enc += ')'; 9608 return true; 9609 } 9610 9611 /// Appends array encoding to Enc before calling appendType for the element. 9612 static bool appendArrayType(SmallStringEnc &Enc, QualType QT, 9613 const ArrayType *AT, 9614 const CodeGen::CodeGenModule &CGM, 9615 TypeStringCache &TSC, StringRef NoSizeEnc) { 9616 if (AT->getSizeModifier() != ArrayType::Normal) 9617 return false; 9618 Enc += "a("; 9619 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) 9620 CAT->getSize().toStringUnsigned(Enc); 9621 else 9622 Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "". 9623 Enc += ':'; 9624 // The Qualifiers should be attached to the type rather than the array. 9625 appendQualifier(Enc, QT); 9626 if (!appendType(Enc, AT->getElementType(), CGM, TSC)) 9627 return false; 9628 Enc += ')'; 9629 return true; 9630 } 9631 9632 /// Appends a function encoding to Enc, calling appendType for the return type 9633 /// and the arguments. 9634 static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT, 9635 const CodeGen::CodeGenModule &CGM, 9636 TypeStringCache &TSC) { 9637 Enc += "f{"; 9638 if (!appendType(Enc, FT->getReturnType(), CGM, TSC)) 9639 return false; 9640 Enc += "}("; 9641 if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) { 9642 // N.B. we are only interested in the adjusted param types. 9643 auto I = FPT->param_type_begin(); 9644 auto E = FPT->param_type_end(); 9645 if (I != E) { 9646 do { 9647 if (!appendType(Enc, *I, CGM, TSC)) 9648 return false; 9649 ++I; 9650 if (I != E) 9651 Enc += ','; 9652 } while (I != E); 9653 if (FPT->isVariadic()) 9654 Enc += ",va"; 9655 } else { 9656 if (FPT->isVariadic()) 9657 Enc += "va"; 9658 else 9659 Enc += '0'; 9660 } 9661 } 9662 Enc += ')'; 9663 return true; 9664 } 9665 9666 /// Handles the type's qualifier before dispatching a call to handle specific 9667 /// type encodings. 9668 static bool appendType(SmallStringEnc &Enc, QualType QType, 9669 const CodeGen::CodeGenModule &CGM, 9670 TypeStringCache &TSC) { 9671 9672 QualType QT = QType.getCanonicalType(); 9673 9674 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) 9675 // The Qualifiers should be attached to the type rather than the array. 9676 // Thus we don't call appendQualifier() here. 9677 return appendArrayType(Enc, QT, AT, CGM, TSC, ""); 9678 9679 appendQualifier(Enc, QT); 9680 9681 if (const BuiltinType *BT = QT->getAs<BuiltinType>()) 9682 return appendBuiltinType(Enc, BT); 9683 9684 if (const PointerType *PT = QT->getAs<PointerType>()) 9685 return appendPointerType(Enc, PT, CGM, TSC); 9686 9687 if (const EnumType *ET = QT->getAs<EnumType>()) 9688 return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier()); 9689 9690 if (const RecordType *RT = QT->getAsStructureType()) 9691 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier()); 9692 9693 if (const RecordType *RT = QT->getAsUnionType()) 9694 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier()); 9695 9696 if (const FunctionType *FT = QT->getAs<FunctionType>()) 9697 return appendFunctionType(Enc, FT, CGM, TSC); 9698 9699 return false; 9700 } 9701 9702 static bool getTypeString(SmallStringEnc &Enc, const Decl *D, 9703 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC) { 9704 if (!D) 9705 return false; 9706 9707 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 9708 if (FD->getLanguageLinkage() != CLanguageLinkage) 9709 return false; 9710 return appendType(Enc, FD->getType(), CGM, TSC); 9711 } 9712 9713 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 9714 if (VD->getLanguageLinkage() != CLanguageLinkage) 9715 return false; 9716 QualType QT = VD->getType().getCanonicalType(); 9717 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) { 9718 // Global ArrayTypes are given a size of '*' if the size is unknown. 9719 // The Qualifiers should be attached to the type rather than the array. 9720 // Thus we don't call appendQualifier() here. 9721 return appendArrayType(Enc, QT, AT, CGM, TSC, "*"); 9722 } 9723 return appendType(Enc, QT, CGM, TSC); 9724 } 9725 return false; 9726 } 9727 9728 //===----------------------------------------------------------------------===// 9729 // RISCV ABI Implementation 9730 //===----------------------------------------------------------------------===// 9731 9732 namespace { 9733 class RISCVABIInfo : public DefaultABIInfo { 9734 private: 9735 // Size of the integer ('x') registers in bits. 9736 unsigned XLen; 9737 // Size of the floating point ('f') registers in bits. Note that the target 9738 // ISA might have a wider FLen than the selected ABI (e.g. an RV32IF target 9739 // with soft float ABI has FLen==0). 9740 unsigned FLen; 9741 static const int NumArgGPRs = 8; 9742 static const int NumArgFPRs = 8; 9743 bool detectFPCCEligibleStructHelper(QualType Ty, CharUnits CurOff, 9744 llvm::Type *&Field1Ty, 9745 CharUnits &Field1Off, 9746 llvm::Type *&Field2Ty, 9747 CharUnits &Field2Off) const; 9748 9749 public: 9750 RISCVABIInfo(CodeGen::CodeGenTypes &CGT, unsigned XLen, unsigned FLen) 9751 : DefaultABIInfo(CGT), XLen(XLen), FLen(FLen) {} 9752 9753 // DefaultABIInfo's classifyReturnType and classifyArgumentType are 9754 // non-virtual, but computeInfo is virtual, so we overload it. 9755 void computeInfo(CGFunctionInfo &FI) const override; 9756 9757 ABIArgInfo classifyArgumentType(QualType Ty, bool IsFixed, int &ArgGPRsLeft, 9758 int &ArgFPRsLeft) const; 9759 ABIArgInfo classifyReturnType(QualType RetTy) const; 9760 9761 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 9762 QualType Ty) const override; 9763 9764 ABIArgInfo extendType(QualType Ty) const; 9765 9766 bool detectFPCCEligibleStruct(QualType Ty, llvm::Type *&Field1Ty, 9767 CharUnits &Field1Off, llvm::Type *&Field2Ty, 9768 CharUnits &Field2Off, int &NeededArgGPRs, 9769 int &NeededArgFPRs) const; 9770 ABIArgInfo coerceAndExpandFPCCEligibleStruct(llvm::Type *Field1Ty, 9771 CharUnits Field1Off, 9772 llvm::Type *Field2Ty, 9773 CharUnits Field2Off) const; 9774 }; 9775 } // end anonymous namespace 9776 9777 void RISCVABIInfo::computeInfo(CGFunctionInfo &FI) const { 9778 QualType RetTy = FI.getReturnType(); 9779 if (!getCXXABI().classifyReturnType(FI)) 9780 FI.getReturnInfo() = classifyReturnType(RetTy); 9781 9782 // IsRetIndirect is true if classifyArgumentType indicated the value should 9783 // be passed indirect, or if the type size is a scalar greater than 2*XLen 9784 // and not a complex type with elements <= FLen. e.g. fp128 is passed direct 9785 // in LLVM IR, relying on the backend lowering code to rewrite the argument 9786 // list and pass indirectly on RV32. 9787 bool IsRetIndirect = FI.getReturnInfo().getKind() == ABIArgInfo::Indirect; 9788 if (!IsRetIndirect && RetTy->isScalarType() && 9789 getContext().getTypeSize(RetTy) > (2 * XLen)) { 9790 if (RetTy->isComplexType() && FLen) { 9791 QualType EltTy = RetTy->getAs<ComplexType>()->getElementType(); 9792 IsRetIndirect = getContext().getTypeSize(EltTy) > FLen; 9793 } else { 9794 // This is a normal scalar > 2*XLen, such as fp128 on RV32. 9795 IsRetIndirect = true; 9796 } 9797 } 9798 9799 // We must track the number of GPRs used in order to conform to the RISC-V 9800 // ABI, as integer scalars passed in registers should have signext/zeroext 9801 // when promoted, but are anyext if passed on the stack. As GPR usage is 9802 // different for variadic arguments, we must also track whether we are 9803 // examining a vararg or not. 9804 int ArgGPRsLeft = IsRetIndirect ? NumArgGPRs - 1 : NumArgGPRs; 9805 int ArgFPRsLeft = FLen ? NumArgFPRs : 0; 9806 int NumFixedArgs = FI.getNumRequiredArgs(); 9807 9808 int ArgNum = 0; 9809 for (auto &ArgInfo : FI.arguments()) { 9810 bool IsFixed = ArgNum < NumFixedArgs; 9811 ArgInfo.info = 9812 classifyArgumentType(ArgInfo.type, IsFixed, ArgGPRsLeft, ArgFPRsLeft); 9813 ArgNum++; 9814 } 9815 } 9816 9817 // Returns true if the struct is a potential candidate for the floating point 9818 // calling convention. If this function returns true, the caller is 9819 // responsible for checking that if there is only a single field then that 9820 // field is a float. 9821 bool RISCVABIInfo::detectFPCCEligibleStructHelper(QualType Ty, CharUnits CurOff, 9822 llvm::Type *&Field1Ty, 9823 CharUnits &Field1Off, 9824 llvm::Type *&Field2Ty, 9825 CharUnits &Field2Off) const { 9826 bool IsInt = Ty->isIntegralOrEnumerationType(); 9827 bool IsFloat = Ty->isRealFloatingType(); 9828 9829 if (IsInt || IsFloat) { 9830 uint64_t Size = getContext().getTypeSize(Ty); 9831 if (IsInt && Size > XLen) 9832 return false; 9833 // Can't be eligible if larger than the FP registers. Half precision isn't 9834 // currently supported on RISC-V and the ABI hasn't been confirmed, so 9835 // default to the integer ABI in that case. 9836 if (IsFloat && (Size > FLen || Size < 32)) 9837 return false; 9838 // Can't be eligible if an integer type was already found (int+int pairs 9839 // are not eligible). 9840 if (IsInt && Field1Ty && Field1Ty->isIntegerTy()) 9841 return false; 9842 if (!Field1Ty) { 9843 Field1Ty = CGT.ConvertType(Ty); 9844 Field1Off = CurOff; 9845 return true; 9846 } 9847 if (!Field2Ty) { 9848 Field2Ty = CGT.ConvertType(Ty); 9849 Field2Off = CurOff; 9850 return true; 9851 } 9852 return false; 9853 } 9854 9855 if (auto CTy = Ty->getAs<ComplexType>()) { 9856 if (Field1Ty) 9857 return false; 9858 QualType EltTy = CTy->getElementType(); 9859 if (getContext().getTypeSize(EltTy) > FLen) 9860 return false; 9861 Field1Ty = CGT.ConvertType(EltTy); 9862 Field1Off = CurOff; 9863 assert(CurOff.isZero() && "Unexpected offset for first field"); 9864 Field2Ty = Field1Ty; 9865 Field2Off = Field1Off + getContext().getTypeSizeInChars(EltTy); 9866 return true; 9867 } 9868 9869 if (const ConstantArrayType *ATy = getContext().getAsConstantArrayType(Ty)) { 9870 uint64_t ArraySize = ATy->getSize().getZExtValue(); 9871 QualType EltTy = ATy->getElementType(); 9872 CharUnits EltSize = getContext().getTypeSizeInChars(EltTy); 9873 for (uint64_t i = 0; i < ArraySize; ++i) { 9874 bool Ret = detectFPCCEligibleStructHelper(EltTy, CurOff, Field1Ty, 9875 Field1Off, Field2Ty, Field2Off); 9876 if (!Ret) 9877 return false; 9878 CurOff += EltSize; 9879 } 9880 return true; 9881 } 9882 9883 if (const auto *RTy = Ty->getAs<RecordType>()) { 9884 // Structures with either a non-trivial destructor or a non-trivial 9885 // copy constructor are not eligible for the FP calling convention. 9886 if (getRecordArgABI(Ty, CGT.getCXXABI())) 9887 return false; 9888 if (isEmptyRecord(getContext(), Ty, true)) 9889 return true; 9890 const RecordDecl *RD = RTy->getDecl(); 9891 // Unions aren't eligible unless they're empty (which is caught above). 9892 if (RD->isUnion()) 9893 return false; 9894 int ZeroWidthBitFieldCount = 0; 9895 for (const FieldDecl *FD : RD->fields()) { 9896 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD); 9897 uint64_t FieldOffInBits = Layout.getFieldOffset(FD->getFieldIndex()); 9898 QualType QTy = FD->getType(); 9899 if (FD->isBitField()) { 9900 unsigned BitWidth = FD->getBitWidthValue(getContext()); 9901 // Allow a bitfield with a type greater than XLen as long as the 9902 // bitwidth is XLen or less. 9903 if (getContext().getTypeSize(QTy) > XLen && BitWidth <= XLen) 9904 QTy = getContext().getIntTypeForBitwidth(XLen, false); 9905 if (BitWidth == 0) { 9906 ZeroWidthBitFieldCount++; 9907 continue; 9908 } 9909 } 9910 9911 bool Ret = detectFPCCEligibleStructHelper( 9912 QTy, CurOff + getContext().toCharUnitsFromBits(FieldOffInBits), 9913 Field1Ty, Field1Off, Field2Ty, Field2Off); 9914 if (!Ret) 9915 return false; 9916 9917 // As a quirk of the ABI, zero-width bitfields aren't ignored for fp+fp 9918 // or int+fp structs, but are ignored for a struct with an fp field and 9919 // any number of zero-width bitfields. 9920 if (Field2Ty && ZeroWidthBitFieldCount > 0) 9921 return false; 9922 } 9923 return Field1Ty != nullptr; 9924 } 9925 9926 return false; 9927 } 9928 9929 // Determine if a struct is eligible for passing according to the floating 9930 // point calling convention (i.e., when flattened it contains a single fp 9931 // value, fp+fp, or int+fp of appropriate size). If so, NeededArgFPRs and 9932 // NeededArgGPRs are incremented appropriately. 9933 bool RISCVABIInfo::detectFPCCEligibleStruct(QualType Ty, llvm::Type *&Field1Ty, 9934 CharUnits &Field1Off, 9935 llvm::Type *&Field2Ty, 9936 CharUnits &Field2Off, 9937 int &NeededArgGPRs, 9938 int &NeededArgFPRs) const { 9939 Field1Ty = nullptr; 9940 Field2Ty = nullptr; 9941 NeededArgGPRs = 0; 9942 NeededArgFPRs = 0; 9943 bool IsCandidate = detectFPCCEligibleStructHelper( 9944 Ty, CharUnits::Zero(), Field1Ty, Field1Off, Field2Ty, Field2Off); 9945 // Not really a candidate if we have a single int but no float. 9946 if (Field1Ty && !Field2Ty && !Field1Ty->isFloatingPointTy()) 9947 return false; 9948 if (!IsCandidate) 9949 return false; 9950 if (Field1Ty && Field1Ty->isFloatingPointTy()) 9951 NeededArgFPRs++; 9952 else if (Field1Ty) 9953 NeededArgGPRs++; 9954 if (Field2Ty && Field2Ty->isFloatingPointTy()) 9955 NeededArgFPRs++; 9956 else if (Field2Ty) 9957 NeededArgGPRs++; 9958 return IsCandidate; 9959 } 9960 9961 // Call getCoerceAndExpand for the two-element flattened struct described by 9962 // Field1Ty, Field1Off, Field2Ty, Field2Off. This method will create an 9963 // appropriate coerceToType and unpaddedCoerceToType. 9964 ABIArgInfo RISCVABIInfo::coerceAndExpandFPCCEligibleStruct( 9965 llvm::Type *Field1Ty, CharUnits Field1Off, llvm::Type *Field2Ty, 9966 CharUnits Field2Off) const { 9967 SmallVector<llvm::Type *, 3> CoerceElts; 9968 SmallVector<llvm::Type *, 2> UnpaddedCoerceElts; 9969 if (!Field1Off.isZero()) 9970 CoerceElts.push_back(llvm::ArrayType::get( 9971 llvm::Type::getInt8Ty(getVMContext()), Field1Off.getQuantity())); 9972 9973 CoerceElts.push_back(Field1Ty); 9974 UnpaddedCoerceElts.push_back(Field1Ty); 9975 9976 if (!Field2Ty) { 9977 return ABIArgInfo::getCoerceAndExpand( 9978 llvm::StructType::get(getVMContext(), CoerceElts, !Field1Off.isZero()), 9979 UnpaddedCoerceElts[0]); 9980 } 9981 9982 CharUnits Field2Align = 9983 CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(Field2Ty)); 9984 CharUnits Field1Size = 9985 CharUnits::fromQuantity(getDataLayout().getTypeStoreSize(Field1Ty)); 9986 CharUnits Field2OffNoPadNoPack = Field1Size.alignTo(Field2Align); 9987 9988 CharUnits Padding = CharUnits::Zero(); 9989 if (Field2Off > Field2OffNoPadNoPack) 9990 Padding = Field2Off - Field2OffNoPadNoPack; 9991 else if (Field2Off != Field2Align && Field2Off > Field1Size) 9992 Padding = Field2Off - Field1Size; 9993 9994 bool IsPacked = !Field2Off.isMultipleOf(Field2Align); 9995 9996 if (!Padding.isZero()) 9997 CoerceElts.push_back(llvm::ArrayType::get( 9998 llvm::Type::getInt8Ty(getVMContext()), Padding.getQuantity())); 9999 10000 CoerceElts.push_back(Field2Ty); 10001 UnpaddedCoerceElts.push_back(Field2Ty); 10002 10003 auto CoerceToType = 10004 llvm::StructType::get(getVMContext(), CoerceElts, IsPacked); 10005 auto UnpaddedCoerceToType = 10006 llvm::StructType::get(getVMContext(), UnpaddedCoerceElts, IsPacked); 10007 10008 return ABIArgInfo::getCoerceAndExpand(CoerceToType, UnpaddedCoerceToType); 10009 } 10010 10011 ABIArgInfo RISCVABIInfo::classifyArgumentType(QualType Ty, bool IsFixed, 10012 int &ArgGPRsLeft, 10013 int &ArgFPRsLeft) const { 10014 assert(ArgGPRsLeft <= NumArgGPRs && "Arg GPR tracking underflow"); 10015 Ty = useFirstFieldIfTransparentUnion(Ty); 10016 10017 // Structures with either a non-trivial destructor or a non-trivial 10018 // copy constructor are always passed indirectly. 10019 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) { 10020 if (ArgGPRsLeft) 10021 ArgGPRsLeft -= 1; 10022 return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA == 10023 CGCXXABI::RAA_DirectInMemory); 10024 } 10025 10026 // Ignore empty structs/unions. 10027 if (isEmptyRecord(getContext(), Ty, true)) 10028 return ABIArgInfo::getIgnore(); 10029 10030 uint64_t Size = getContext().getTypeSize(Ty); 10031 10032 // Pass floating point values via FPRs if possible. 10033 if (IsFixed && Ty->isFloatingType() && FLen >= Size && ArgFPRsLeft) { 10034 ArgFPRsLeft--; 10035 return ABIArgInfo::getDirect(); 10036 } 10037 10038 // Complex types for the hard float ABI must be passed direct rather than 10039 // using CoerceAndExpand. 10040 if (IsFixed && Ty->isComplexType() && FLen && ArgFPRsLeft >= 2) { 10041 QualType EltTy = Ty->castAs<ComplexType>()->getElementType(); 10042 if (getContext().getTypeSize(EltTy) <= FLen) { 10043 ArgFPRsLeft -= 2; 10044 return ABIArgInfo::getDirect(); 10045 } 10046 } 10047 10048 if (IsFixed && FLen && Ty->isStructureOrClassType()) { 10049 llvm::Type *Field1Ty = nullptr; 10050 llvm::Type *Field2Ty = nullptr; 10051 CharUnits Field1Off = CharUnits::Zero(); 10052 CharUnits Field2Off = CharUnits::Zero(); 10053 int NeededArgGPRs; 10054 int NeededArgFPRs; 10055 bool IsCandidate = 10056 detectFPCCEligibleStruct(Ty, Field1Ty, Field1Off, Field2Ty, Field2Off, 10057 NeededArgGPRs, NeededArgFPRs); 10058 if (IsCandidate && NeededArgGPRs <= ArgGPRsLeft && 10059 NeededArgFPRs <= ArgFPRsLeft) { 10060 ArgGPRsLeft -= NeededArgGPRs; 10061 ArgFPRsLeft -= NeededArgFPRs; 10062 return coerceAndExpandFPCCEligibleStruct(Field1Ty, Field1Off, Field2Ty, 10063 Field2Off); 10064 } 10065 } 10066 10067 uint64_t NeededAlign = getContext().getTypeAlign(Ty); 10068 bool MustUseStack = false; 10069 // Determine the number of GPRs needed to pass the current argument 10070 // according to the ABI. 2*XLen-aligned varargs are passed in "aligned" 10071 // register pairs, so may consume 3 registers. 10072 int NeededArgGPRs = 1; 10073 if (!IsFixed && NeededAlign == 2 * XLen) 10074 NeededArgGPRs = 2 + (ArgGPRsLeft % 2); 10075 else if (Size > XLen && Size <= 2 * XLen) 10076 NeededArgGPRs = 2; 10077 10078 if (NeededArgGPRs > ArgGPRsLeft) { 10079 MustUseStack = true; 10080 NeededArgGPRs = ArgGPRsLeft; 10081 } 10082 10083 ArgGPRsLeft -= NeededArgGPRs; 10084 10085 if (!isAggregateTypeForABI(Ty) && !Ty->isVectorType()) { 10086 // Treat an enum type as its underlying type. 10087 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 10088 Ty = EnumTy->getDecl()->getIntegerType(); 10089 10090 // All integral types are promoted to XLen width, unless passed on the 10091 // stack. 10092 if (Size < XLen && Ty->isIntegralOrEnumerationType() && !MustUseStack) { 10093 return extendType(Ty); 10094 } 10095 10096 return ABIArgInfo::getDirect(); 10097 } 10098 10099 // Aggregates which are <= 2*XLen will be passed in registers if possible, 10100 // so coerce to integers. 10101 if (Size <= 2 * XLen) { 10102 unsigned Alignment = getContext().getTypeAlign(Ty); 10103 10104 // Use a single XLen int if possible, 2*XLen if 2*XLen alignment is 10105 // required, and a 2-element XLen array if only XLen alignment is required. 10106 if (Size <= XLen) { 10107 return ABIArgInfo::getDirect( 10108 llvm::IntegerType::get(getVMContext(), XLen)); 10109 } else if (Alignment == 2 * XLen) { 10110 return ABIArgInfo::getDirect( 10111 llvm::IntegerType::get(getVMContext(), 2 * XLen)); 10112 } else { 10113 return ABIArgInfo::getDirect(llvm::ArrayType::get( 10114 llvm::IntegerType::get(getVMContext(), XLen), 2)); 10115 } 10116 } 10117 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 10118 } 10119 10120 ABIArgInfo RISCVABIInfo::classifyReturnType(QualType RetTy) const { 10121 if (RetTy->isVoidType()) 10122 return ABIArgInfo::getIgnore(); 10123 10124 int ArgGPRsLeft = 2; 10125 int ArgFPRsLeft = FLen ? 2 : 0; 10126 10127 // The rules for return and argument types are the same, so defer to 10128 // classifyArgumentType. 10129 return classifyArgumentType(RetTy, /*IsFixed=*/true, ArgGPRsLeft, 10130 ArgFPRsLeft); 10131 } 10132 10133 Address RISCVABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 10134 QualType Ty) const { 10135 CharUnits SlotSize = CharUnits::fromQuantity(XLen / 8); 10136 10137 // Empty records are ignored for parameter passing purposes. 10138 if (isEmptyRecord(getContext(), Ty, true)) { 10139 Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize); 10140 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty)); 10141 return Addr; 10142 } 10143 10144 std::pair<CharUnits, CharUnits> SizeAndAlign = 10145 getContext().getTypeInfoInChars(Ty); 10146 10147 // Arguments bigger than 2*Xlen bytes are passed indirectly. 10148 bool IsIndirect = SizeAndAlign.first > 2 * SlotSize; 10149 10150 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, SizeAndAlign, 10151 SlotSize, /*AllowHigherAlign=*/true); 10152 } 10153 10154 ABIArgInfo RISCVABIInfo::extendType(QualType Ty) const { 10155 int TySize = getContext().getTypeSize(Ty); 10156 // RV64 ABI requires unsigned 32 bit integers to be sign extended. 10157 if (XLen == 64 && Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32) 10158 return ABIArgInfo::getSignExtend(Ty); 10159 return ABIArgInfo::getExtend(Ty); 10160 } 10161 10162 namespace { 10163 class RISCVTargetCodeGenInfo : public TargetCodeGenInfo { 10164 public: 10165 RISCVTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, unsigned XLen, 10166 unsigned FLen) 10167 : TargetCodeGenInfo(new RISCVABIInfo(CGT, XLen, FLen)) {} 10168 10169 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 10170 CodeGen::CodeGenModule &CGM) const override { 10171 const auto *FD = dyn_cast_or_null<FunctionDecl>(D); 10172 if (!FD) return; 10173 10174 const auto *Attr = FD->getAttr<RISCVInterruptAttr>(); 10175 if (!Attr) 10176 return; 10177 10178 const char *Kind; 10179 switch (Attr->getInterrupt()) { 10180 case RISCVInterruptAttr::user: Kind = "user"; break; 10181 case RISCVInterruptAttr::supervisor: Kind = "supervisor"; break; 10182 case RISCVInterruptAttr::machine: Kind = "machine"; break; 10183 } 10184 10185 auto *Fn = cast<llvm::Function>(GV); 10186 10187 Fn->addFnAttr("interrupt", Kind); 10188 } 10189 }; 10190 } // namespace 10191 10192 //===----------------------------------------------------------------------===// 10193 // Driver code 10194 //===----------------------------------------------------------------------===// 10195 10196 bool CodeGenModule::supportsCOMDAT() const { 10197 return getTriple().supportsCOMDAT(); 10198 } 10199 10200 const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() { 10201 if (TheTargetCodeGenInfo) 10202 return *TheTargetCodeGenInfo; 10203 10204 // Helper to set the unique_ptr while still keeping the return value. 10205 auto SetCGInfo = [&](TargetCodeGenInfo *P) -> const TargetCodeGenInfo & { 10206 this->TheTargetCodeGenInfo.reset(P); 10207 return *P; 10208 }; 10209 10210 const llvm::Triple &Triple = getTarget().getTriple(); 10211 switch (Triple.getArch()) { 10212 default: 10213 return SetCGInfo(new DefaultTargetCodeGenInfo(Types)); 10214 10215 case llvm::Triple::le32: 10216 return SetCGInfo(new PNaClTargetCodeGenInfo(Types)); 10217 case llvm::Triple::mips: 10218 case llvm::Triple::mipsel: 10219 if (Triple.getOS() == llvm::Triple::NaCl) 10220 return SetCGInfo(new PNaClTargetCodeGenInfo(Types)); 10221 return SetCGInfo(new MIPSTargetCodeGenInfo(Types, true)); 10222 10223 case llvm::Triple::mips64: 10224 case llvm::Triple::mips64el: 10225 return SetCGInfo(new MIPSTargetCodeGenInfo(Types, false)); 10226 10227 case llvm::Triple::avr: 10228 return SetCGInfo(new AVRTargetCodeGenInfo(Types)); 10229 10230 case llvm::Triple::aarch64: 10231 case llvm::Triple::aarch64_32: 10232 case llvm::Triple::aarch64_be: { 10233 AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS; 10234 if (getTarget().getABI() == "darwinpcs") 10235 Kind = AArch64ABIInfo::DarwinPCS; 10236 else if (Triple.isOSWindows()) 10237 return SetCGInfo( 10238 new WindowsAArch64TargetCodeGenInfo(Types, AArch64ABIInfo::Win64)); 10239 10240 return SetCGInfo(new AArch64TargetCodeGenInfo(Types, Kind)); 10241 } 10242 10243 case llvm::Triple::wasm32: 10244 case llvm::Triple::wasm64: { 10245 WebAssemblyABIInfo::ABIKind Kind = WebAssemblyABIInfo::MVP; 10246 if (getTarget().getABI() == "experimental-mv") 10247 Kind = WebAssemblyABIInfo::ExperimentalMV; 10248 return SetCGInfo(new WebAssemblyTargetCodeGenInfo(Types, Kind)); 10249 } 10250 10251 case llvm::Triple::arm: 10252 case llvm::Triple::armeb: 10253 case llvm::Triple::thumb: 10254 case llvm::Triple::thumbeb: { 10255 if (Triple.getOS() == llvm::Triple::Win32) { 10256 return SetCGInfo( 10257 new WindowsARMTargetCodeGenInfo(Types, ARMABIInfo::AAPCS_VFP)); 10258 } 10259 10260 ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS; 10261 StringRef ABIStr = getTarget().getABI(); 10262 if (ABIStr == "apcs-gnu") 10263 Kind = ARMABIInfo::APCS; 10264 else if (ABIStr == "aapcs16") 10265 Kind = ARMABIInfo::AAPCS16_VFP; 10266 else if (CodeGenOpts.FloatABI == "hard" || 10267 (CodeGenOpts.FloatABI != "soft" && 10268 (Triple.getEnvironment() == llvm::Triple::GNUEABIHF || 10269 Triple.getEnvironment() == llvm::Triple::MuslEABIHF || 10270 Triple.getEnvironment() == llvm::Triple::EABIHF))) 10271 Kind = ARMABIInfo::AAPCS_VFP; 10272 10273 return SetCGInfo(new ARMTargetCodeGenInfo(Types, Kind)); 10274 } 10275 10276 case llvm::Triple::ppc: 10277 return SetCGInfo( 10278 new PPC32TargetCodeGenInfo(Types, CodeGenOpts.FloatABI == "soft" || 10279 getTarget().hasFeature("spe"))); 10280 case llvm::Triple::ppc64: 10281 if (Triple.isOSBinFormatELF()) { 10282 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1; 10283 if (getTarget().getABI() == "elfv2") 10284 Kind = PPC64_SVR4_ABIInfo::ELFv2; 10285 bool HasQPX = getTarget().getABI() == "elfv1-qpx"; 10286 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft"; 10287 10288 return SetCGInfo(new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX, 10289 IsSoftFloat)); 10290 } else 10291 return SetCGInfo(new PPC64TargetCodeGenInfo(Types)); 10292 case llvm::Triple::ppc64le: { 10293 assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!"); 10294 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2; 10295 if (getTarget().getABI() == "elfv1" || getTarget().getABI() == "elfv1-qpx") 10296 Kind = PPC64_SVR4_ABIInfo::ELFv1; 10297 bool HasQPX = getTarget().getABI() == "elfv1-qpx"; 10298 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft"; 10299 10300 return SetCGInfo(new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX, 10301 IsSoftFloat)); 10302 } 10303 10304 case llvm::Triple::nvptx: 10305 case llvm::Triple::nvptx64: 10306 return SetCGInfo(new NVPTXTargetCodeGenInfo(Types)); 10307 10308 case llvm::Triple::msp430: 10309 return SetCGInfo(new MSP430TargetCodeGenInfo(Types)); 10310 10311 case llvm::Triple::riscv32: 10312 case llvm::Triple::riscv64: { 10313 StringRef ABIStr = getTarget().getABI(); 10314 unsigned XLen = getTarget().getPointerWidth(0); 10315 unsigned ABIFLen = 0; 10316 if (ABIStr.endswith("f")) 10317 ABIFLen = 32; 10318 else if (ABIStr.endswith("d")) 10319 ABIFLen = 64; 10320 return SetCGInfo(new RISCVTargetCodeGenInfo(Types, XLen, ABIFLen)); 10321 } 10322 10323 case llvm::Triple::systemz: { 10324 bool SoftFloat = CodeGenOpts.FloatABI == "soft"; 10325 bool HasVector = !SoftFloat && getTarget().getABI() == "vector"; 10326 return SetCGInfo(new SystemZTargetCodeGenInfo(Types, HasVector, SoftFloat)); 10327 } 10328 10329 case llvm::Triple::tce: 10330 case llvm::Triple::tcele: 10331 return SetCGInfo(new TCETargetCodeGenInfo(Types)); 10332 10333 case llvm::Triple::x86: { 10334 bool IsDarwinVectorABI = Triple.isOSDarwin(); 10335 bool RetSmallStructInRegABI = 10336 X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts); 10337 bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing(); 10338 10339 if (Triple.getOS() == llvm::Triple::Win32) { 10340 return SetCGInfo(new WinX86_32TargetCodeGenInfo( 10341 Types, IsDarwinVectorABI, RetSmallStructInRegABI, 10342 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters)); 10343 } else { 10344 return SetCGInfo(new X86_32TargetCodeGenInfo( 10345 Types, IsDarwinVectorABI, RetSmallStructInRegABI, 10346 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters, 10347 CodeGenOpts.FloatABI == "soft")); 10348 } 10349 } 10350 10351 case llvm::Triple::x86_64: { 10352 StringRef ABI = getTarget().getABI(); 10353 X86AVXABILevel AVXLevel = 10354 (ABI == "avx512" 10355 ? X86AVXABILevel::AVX512 10356 : ABI == "avx" ? X86AVXABILevel::AVX : X86AVXABILevel::None); 10357 10358 switch (Triple.getOS()) { 10359 case llvm::Triple::Win32: 10360 return SetCGInfo(new WinX86_64TargetCodeGenInfo(Types, AVXLevel)); 10361 default: 10362 return SetCGInfo(new X86_64TargetCodeGenInfo(Types, AVXLevel)); 10363 } 10364 } 10365 case llvm::Triple::hexagon: 10366 return SetCGInfo(new HexagonTargetCodeGenInfo(Types)); 10367 case llvm::Triple::lanai: 10368 return SetCGInfo(new LanaiTargetCodeGenInfo(Types)); 10369 case llvm::Triple::r600: 10370 return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types)); 10371 case llvm::Triple::amdgcn: 10372 return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types)); 10373 case llvm::Triple::sparc: 10374 return SetCGInfo(new SparcV8TargetCodeGenInfo(Types)); 10375 case llvm::Triple::sparcv9: 10376 return SetCGInfo(new SparcV9TargetCodeGenInfo(Types)); 10377 case llvm::Triple::xcore: 10378 return SetCGInfo(new XCoreTargetCodeGenInfo(Types)); 10379 case llvm::Triple::arc: 10380 return SetCGInfo(new ARCTargetCodeGenInfo(Types)); 10381 case llvm::Triple::spir: 10382 case llvm::Triple::spir64: 10383 return SetCGInfo(new SPIRTargetCodeGenInfo(Types)); 10384 } 10385 } 10386 10387 /// Create an OpenCL kernel for an enqueued block. 10388 /// 10389 /// The kernel has the same function type as the block invoke function. Its 10390 /// name is the name of the block invoke function postfixed with "_kernel". 10391 /// It simply calls the block invoke function then returns. 10392 llvm::Function * 10393 TargetCodeGenInfo::createEnqueuedBlockKernel(CodeGenFunction &CGF, 10394 llvm::Function *Invoke, 10395 llvm::Value *BlockLiteral) const { 10396 auto *InvokeFT = Invoke->getFunctionType(); 10397 llvm::SmallVector<llvm::Type *, 2> ArgTys; 10398 for (auto &P : InvokeFT->params()) 10399 ArgTys.push_back(P); 10400 auto &C = CGF.getLLVMContext(); 10401 std::string Name = Invoke->getName().str() + "_kernel"; 10402 auto *FT = llvm::FunctionType::get(llvm::Type::getVoidTy(C), ArgTys, false); 10403 auto *F = llvm::Function::Create(FT, llvm::GlobalValue::InternalLinkage, Name, 10404 &CGF.CGM.getModule()); 10405 auto IP = CGF.Builder.saveIP(); 10406 auto *BB = llvm::BasicBlock::Create(C, "entry", F); 10407 auto &Builder = CGF.Builder; 10408 Builder.SetInsertPoint(BB); 10409 llvm::SmallVector<llvm::Value *, 2> Args; 10410 for (auto &A : F->args()) 10411 Args.push_back(&A); 10412 Builder.CreateCall(Invoke, Args); 10413 Builder.CreateRetVoid(); 10414 Builder.restoreIP(IP); 10415 return F; 10416 } 10417 10418 /// Create an OpenCL kernel for an enqueued block. 10419 /// 10420 /// The type of the first argument (the block literal) is the struct type 10421 /// of the block literal instead of a pointer type. The first argument 10422 /// (block literal) is passed directly by value to the kernel. The kernel 10423 /// allocates the same type of struct on stack and stores the block literal 10424 /// to it and passes its pointer to the block invoke function. The kernel 10425 /// has "enqueued-block" function attribute and kernel argument metadata. 10426 llvm::Function *AMDGPUTargetCodeGenInfo::createEnqueuedBlockKernel( 10427 CodeGenFunction &CGF, llvm::Function *Invoke, 10428 llvm::Value *BlockLiteral) const { 10429 auto &Builder = CGF.Builder; 10430 auto &C = CGF.getLLVMContext(); 10431 10432 auto *BlockTy = BlockLiteral->getType()->getPointerElementType(); 10433 auto *InvokeFT = Invoke->getFunctionType(); 10434 llvm::SmallVector<llvm::Type *, 2> ArgTys; 10435 llvm::SmallVector<llvm::Metadata *, 8> AddressQuals; 10436 llvm::SmallVector<llvm::Metadata *, 8> AccessQuals; 10437 llvm::SmallVector<llvm::Metadata *, 8> ArgTypeNames; 10438 llvm::SmallVector<llvm::Metadata *, 8> ArgBaseTypeNames; 10439 llvm::SmallVector<llvm::Metadata *, 8> ArgTypeQuals; 10440 llvm::SmallVector<llvm::Metadata *, 8> ArgNames; 10441 10442 ArgTys.push_back(BlockTy); 10443 ArgTypeNames.push_back(llvm::MDString::get(C, "__block_literal")); 10444 AddressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(0))); 10445 ArgBaseTypeNames.push_back(llvm::MDString::get(C, "__block_literal")); 10446 ArgTypeQuals.push_back(llvm::MDString::get(C, "")); 10447 AccessQuals.push_back(llvm::MDString::get(C, "none")); 10448 ArgNames.push_back(llvm::MDString::get(C, "block_literal")); 10449 for (unsigned I = 1, E = InvokeFT->getNumParams(); I < E; ++I) { 10450 ArgTys.push_back(InvokeFT->getParamType(I)); 10451 ArgTypeNames.push_back(llvm::MDString::get(C, "void*")); 10452 AddressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(3))); 10453 AccessQuals.push_back(llvm::MDString::get(C, "none")); 10454 ArgBaseTypeNames.push_back(llvm::MDString::get(C, "void*")); 10455 ArgTypeQuals.push_back(llvm::MDString::get(C, "")); 10456 ArgNames.push_back( 10457 llvm::MDString::get(C, (Twine("local_arg") + Twine(I)).str())); 10458 } 10459 std::string Name = Invoke->getName().str() + "_kernel"; 10460 auto *FT = llvm::FunctionType::get(llvm::Type::getVoidTy(C), ArgTys, false); 10461 auto *F = llvm::Function::Create(FT, llvm::GlobalValue::InternalLinkage, Name, 10462 &CGF.CGM.getModule()); 10463 F->addFnAttr("enqueued-block"); 10464 auto IP = CGF.Builder.saveIP(); 10465 auto *BB = llvm::BasicBlock::Create(C, "entry", F); 10466 Builder.SetInsertPoint(BB); 10467 const auto BlockAlign = CGF.CGM.getDataLayout().getPrefTypeAlign(BlockTy); 10468 auto *BlockPtr = Builder.CreateAlloca(BlockTy, nullptr); 10469 BlockPtr->setAlignment(BlockAlign); 10470 Builder.CreateAlignedStore(F->arg_begin(), BlockPtr, BlockAlign); 10471 auto *Cast = Builder.CreatePointerCast(BlockPtr, InvokeFT->getParamType(0)); 10472 llvm::SmallVector<llvm::Value *, 2> Args; 10473 Args.push_back(Cast); 10474 for (auto I = F->arg_begin() + 1, E = F->arg_end(); I != E; ++I) 10475 Args.push_back(I); 10476 Builder.CreateCall(Invoke, Args); 10477 Builder.CreateRetVoid(); 10478 Builder.restoreIP(IP); 10479 10480 F->setMetadata("kernel_arg_addr_space", llvm::MDNode::get(C, AddressQuals)); 10481 F->setMetadata("kernel_arg_access_qual", llvm::MDNode::get(C, AccessQuals)); 10482 F->setMetadata("kernel_arg_type", llvm::MDNode::get(C, ArgTypeNames)); 10483 F->setMetadata("kernel_arg_base_type", 10484 llvm::MDNode::get(C, ArgBaseTypeNames)); 10485 F->setMetadata("kernel_arg_type_qual", llvm::MDNode::get(C, ArgTypeQuals)); 10486 if (CGF.CGM.getCodeGenOpts().EmitOpenCLArgMetadata) 10487 F->setMetadata("kernel_arg_name", llvm::MDNode::get(C, ArgNames)); 10488 10489 return F; 10490 } 10491