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