1 //===---- TargetInfo.cpp - Encapsulate target details -----------*- C++ -*-===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // These classes wrap the information about a call or function 10 // definition used to handle ABI compliancy. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "TargetInfo.h" 15 #include "ABIInfo.h" 16 #include "CGBlocks.h" 17 #include "CGCXXABI.h" 18 #include "CGValue.h" 19 #include "CodeGenFunction.h" 20 #include "clang/AST/Attr.h" 21 #include "clang/AST/RecordLayout.h" 22 #include "clang/Basic/CodeGenOptions.h" 23 #include "clang/Basic/DiagnosticFrontend.h" 24 #include "clang/Basic/Builtins.h" 25 #include "clang/CodeGen/CGFunctionInfo.h" 26 #include "clang/CodeGen/SwiftCallingConv.h" 27 #include "llvm/ADT/SmallBitVector.h" 28 #include "llvm/ADT/StringExtras.h" 29 #include "llvm/ADT/StringSwitch.h" 30 #include "llvm/ADT/Triple.h" 31 #include "llvm/ADT/Twine.h" 32 #include "llvm/IR/DataLayout.h" 33 #include "llvm/IR/IntrinsicsNVPTX.h" 34 #include "llvm/IR/IntrinsicsS390.h" 35 #include "llvm/IR/Type.h" 36 #include "llvm/Support/raw_ostream.h" 37 #include <algorithm> // std::sort 38 39 using namespace clang; 40 using namespace CodeGen; 41 42 // Helper for coercing an aggregate argument or return value into an integer 43 // array of the same size (including padding) and alignment. This alternate 44 // coercion happens only for the RenderScript ABI and can be removed after 45 // runtimes that rely on it are no longer supported. 46 // 47 // RenderScript assumes that the size of the argument / return value in the IR 48 // is the same as the size of the corresponding qualified type. This helper 49 // coerces the aggregate type into an array of the same size (including 50 // padding). This coercion is used in lieu of expansion of struct members or 51 // other canonical coercions that return a coerced-type of larger size. 52 // 53 // Ty - The argument / return value type 54 // Context - The associated ASTContext 55 // LLVMContext - The associated LLVMContext 56 static ABIArgInfo coerceToIntArray(QualType Ty, 57 ASTContext &Context, 58 llvm::LLVMContext &LLVMContext) { 59 // Alignment and Size are measured in bits. 60 const uint64_t Size = Context.getTypeSize(Ty); 61 const uint64_t Alignment = Context.getTypeAlign(Ty); 62 llvm::Type *IntType = llvm::Type::getIntNTy(LLVMContext, Alignment); 63 const uint64_t NumElements = (Size + Alignment - 1) / Alignment; 64 return ABIArgInfo::getDirect(llvm::ArrayType::get(IntType, NumElements)); 65 } 66 67 static void AssignToArrayRange(CodeGen::CGBuilderTy &Builder, 68 llvm::Value *Array, 69 llvm::Value *Value, 70 unsigned FirstIndex, 71 unsigned LastIndex) { 72 // Alternatively, we could emit this as a loop in the source. 73 for (unsigned I = FirstIndex; I <= LastIndex; ++I) { 74 llvm::Value *Cell = 75 Builder.CreateConstInBoundsGEP1_32(Builder.getInt8Ty(), Array, I); 76 Builder.CreateAlignedStore(Value, Cell, CharUnits::One()); 77 } 78 } 79 80 static bool isAggregateTypeForABI(QualType T) { 81 return !CodeGenFunction::hasScalarEvaluationKind(T) || 82 T->isMemberFunctionPointerType(); 83 } 84 85 ABIArgInfo ABIInfo::getNaturalAlignIndirect(QualType Ty, bool ByVal, 86 bool Realign, 87 llvm::Type *Padding) const { 88 return ABIArgInfo::getIndirect(getContext().getTypeAlignInChars(Ty), ByVal, 89 Realign, Padding); 90 } 91 92 ABIArgInfo 93 ABIInfo::getNaturalAlignIndirectInReg(QualType Ty, bool Realign) const { 94 return ABIArgInfo::getIndirectInReg(getContext().getTypeAlignInChars(Ty), 95 /*ByVal*/ false, Realign); 96 } 97 98 Address ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr, 99 QualType Ty) const { 100 return Address::invalid(); 101 } 102 103 bool ABIInfo::isPromotableIntegerTypeForABI(QualType Ty) const { 104 if (Ty->isPromotableIntegerType()) 105 return true; 106 107 if (const auto *EIT = Ty->getAs<ExtIntType>()) 108 if (EIT->getNumBits() < getContext().getTypeSize(getContext().IntTy)) 109 return true; 110 111 return false; 112 } 113 114 ABIInfo::~ABIInfo() {} 115 116 /// Does the given lowering require more than the given number of 117 /// registers when expanded? 118 /// 119 /// This is intended to be the basis of a reasonable basic implementation 120 /// of should{Pass,Return}IndirectlyForSwift. 121 /// 122 /// For most targets, a limit of four total registers is reasonable; this 123 /// limits the amount of code required in order to move around the value 124 /// in case it wasn't produced immediately prior to the call by the caller 125 /// (or wasn't produced in exactly the right registers) or isn't used 126 /// immediately within the callee. But some targets may need to further 127 /// limit the register count due to an inability to support that many 128 /// return registers. 129 static bool occupiesMoreThan(CodeGenTypes &cgt, 130 ArrayRef<llvm::Type*> scalarTypes, 131 unsigned maxAllRegisters) { 132 unsigned intCount = 0, fpCount = 0; 133 for (llvm::Type *type : scalarTypes) { 134 if (type->isPointerTy()) { 135 intCount++; 136 } else if (auto intTy = dyn_cast<llvm::IntegerType>(type)) { 137 auto ptrWidth = cgt.getTarget().getPointerWidth(0); 138 intCount += (intTy->getBitWidth() + ptrWidth - 1) / ptrWidth; 139 } else { 140 assert(type->isVectorTy() || type->isFloatingPointTy()); 141 fpCount++; 142 } 143 } 144 145 return (intCount + fpCount > maxAllRegisters); 146 } 147 148 bool SwiftABIInfo::isLegalVectorTypeForSwift(CharUnits vectorSize, 149 llvm::Type *eltTy, 150 unsigned numElts) const { 151 // The default implementation of this assumes that the target guarantees 152 // 128-bit SIMD support but nothing more. 153 return (vectorSize.getQuantity() > 8 && vectorSize.getQuantity() <= 16); 154 } 155 156 static CGCXXABI::RecordArgABI getRecordArgABI(const RecordType *RT, 157 CGCXXABI &CXXABI) { 158 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 159 if (!RD) { 160 if (!RT->getDecl()->canPassInRegisters()) 161 return CGCXXABI::RAA_Indirect; 162 return CGCXXABI::RAA_Default; 163 } 164 return CXXABI.getRecordArgABI(RD); 165 } 166 167 static CGCXXABI::RecordArgABI getRecordArgABI(QualType T, 168 CGCXXABI &CXXABI) { 169 const RecordType *RT = T->getAs<RecordType>(); 170 if (!RT) 171 return CGCXXABI::RAA_Default; 172 return getRecordArgABI(RT, CXXABI); 173 } 174 175 static bool classifyReturnType(const CGCXXABI &CXXABI, CGFunctionInfo &FI, 176 const ABIInfo &Info) { 177 QualType Ty = FI.getReturnType(); 178 179 if (const auto *RT = Ty->getAs<RecordType>()) 180 if (!isa<CXXRecordDecl>(RT->getDecl()) && 181 !RT->getDecl()->canPassInRegisters()) { 182 FI.getReturnInfo() = Info.getNaturalAlignIndirect(Ty); 183 return true; 184 } 185 186 return CXXABI.classifyReturnType(FI); 187 } 188 189 /// Pass transparent unions as if they were the type of the first element. Sema 190 /// should ensure that all elements of the union have the same "machine type". 191 static QualType useFirstFieldIfTransparentUnion(QualType Ty) { 192 if (const RecordType *UT = Ty->getAsUnionType()) { 193 const RecordDecl *UD = UT->getDecl(); 194 if (UD->hasAttr<TransparentUnionAttr>()) { 195 assert(!UD->field_empty() && "sema created an empty transparent union"); 196 return UD->field_begin()->getType(); 197 } 198 } 199 return Ty; 200 } 201 202 CGCXXABI &ABIInfo::getCXXABI() const { 203 return CGT.getCXXABI(); 204 } 205 206 ASTContext &ABIInfo::getContext() const { 207 return CGT.getContext(); 208 } 209 210 llvm::LLVMContext &ABIInfo::getVMContext() const { 211 return CGT.getLLVMContext(); 212 } 213 214 const llvm::DataLayout &ABIInfo::getDataLayout() const { 215 return CGT.getDataLayout(); 216 } 217 218 const TargetInfo &ABIInfo::getTarget() const { 219 return CGT.getTarget(); 220 } 221 222 const CodeGenOptions &ABIInfo::getCodeGenOpts() const { 223 return CGT.getCodeGenOpts(); 224 } 225 226 bool ABIInfo::isAndroid() const { return getTarget().getTriple().isAndroid(); } 227 228 bool ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const { 229 return false; 230 } 231 232 bool ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base, 233 uint64_t Members) const { 234 return false; 235 } 236 237 LLVM_DUMP_METHOD void ABIArgInfo::dump() const { 238 raw_ostream &OS = llvm::errs(); 239 OS << "(ABIArgInfo Kind="; 240 switch (TheKind) { 241 case Direct: 242 OS << "Direct Type="; 243 if (llvm::Type *Ty = getCoerceToType()) 244 Ty->print(OS); 245 else 246 OS << "null"; 247 break; 248 case Extend: 249 OS << "Extend"; 250 break; 251 case Ignore: 252 OS << "Ignore"; 253 break; 254 case InAlloca: 255 OS << "InAlloca Offset=" << getInAllocaFieldIndex(); 256 break; 257 case Indirect: 258 OS << "Indirect Align=" << getIndirectAlign().getQuantity() 259 << " ByVal=" << getIndirectByVal() 260 << " Realign=" << getIndirectRealign(); 261 break; 262 case IndirectAliased: 263 OS << "Indirect Align=" << getIndirectAlign().getQuantity() 264 << " AadrSpace=" << getIndirectAddrSpace() 265 << " Realign=" << getIndirectRealign(); 266 break; 267 case Expand: 268 OS << "Expand"; 269 break; 270 case CoerceAndExpand: 271 OS << "CoerceAndExpand Type="; 272 getCoerceAndExpandType()->print(OS); 273 break; 274 } 275 OS << ")\n"; 276 } 277 278 // Dynamically round a pointer up to a multiple of the given alignment. 279 static llvm::Value *emitRoundPointerUpToAlignment(CodeGenFunction &CGF, 280 llvm::Value *Ptr, 281 CharUnits Align) { 282 llvm::Value *PtrAsInt = Ptr; 283 // OverflowArgArea = (OverflowArgArea + Align - 1) & -Align; 284 PtrAsInt = CGF.Builder.CreatePtrToInt(PtrAsInt, CGF.IntPtrTy); 285 PtrAsInt = CGF.Builder.CreateAdd(PtrAsInt, 286 llvm::ConstantInt::get(CGF.IntPtrTy, Align.getQuantity() - 1)); 287 PtrAsInt = CGF.Builder.CreateAnd(PtrAsInt, 288 llvm::ConstantInt::get(CGF.IntPtrTy, -Align.getQuantity())); 289 PtrAsInt = CGF.Builder.CreateIntToPtr(PtrAsInt, 290 Ptr->getType(), 291 Ptr->getName() + ".aligned"); 292 return PtrAsInt; 293 } 294 295 /// Emit va_arg for a platform using the common void* representation, 296 /// where arguments are simply emitted in an array of slots on the stack. 297 /// 298 /// This version implements the core direct-value passing rules. 299 /// 300 /// \param SlotSize - The size and alignment of a stack slot. 301 /// Each argument will be allocated to a multiple of this number of 302 /// slots, and all the slots will be aligned to this value. 303 /// \param AllowHigherAlign - The slot alignment is not a cap; 304 /// an argument type with an alignment greater than the slot size 305 /// will be emitted on a higher-alignment address, potentially 306 /// leaving one or more empty slots behind as padding. If this 307 /// is false, the returned address might be less-aligned than 308 /// DirectAlign. 309 static Address emitVoidPtrDirectVAArg(CodeGenFunction &CGF, 310 Address VAListAddr, 311 llvm::Type *DirectTy, 312 CharUnits DirectSize, 313 CharUnits DirectAlign, 314 CharUnits SlotSize, 315 bool AllowHigherAlign) { 316 // Cast the element type to i8* if necessary. Some platforms define 317 // va_list as a struct containing an i8* instead of just an i8*. 318 if (VAListAddr.getElementType() != CGF.Int8PtrTy) 319 VAListAddr = CGF.Builder.CreateElementBitCast(VAListAddr, CGF.Int8PtrTy); 320 321 llvm::Value *Ptr = CGF.Builder.CreateLoad(VAListAddr, "argp.cur"); 322 323 // If the CC aligns values higher than the slot size, do so if needed. 324 Address Addr = Address::invalid(); 325 if (AllowHigherAlign && DirectAlign > SlotSize) { 326 Addr = Address(emitRoundPointerUpToAlignment(CGF, Ptr, DirectAlign), 327 DirectAlign); 328 } else { 329 Addr = Address(Ptr, SlotSize); 330 } 331 332 // Advance the pointer past the argument, then store that back. 333 CharUnits FullDirectSize = DirectSize.alignTo(SlotSize); 334 Address NextPtr = 335 CGF.Builder.CreateConstInBoundsByteGEP(Addr, FullDirectSize, "argp.next"); 336 CGF.Builder.CreateStore(NextPtr.getPointer(), VAListAddr); 337 338 // If the argument is smaller than a slot, and this is a big-endian 339 // target, the argument will be right-adjusted in its slot. 340 if (DirectSize < SlotSize && CGF.CGM.getDataLayout().isBigEndian() && 341 !DirectTy->isStructTy()) { 342 Addr = CGF.Builder.CreateConstInBoundsByteGEP(Addr, SlotSize - DirectSize); 343 } 344 345 Addr = CGF.Builder.CreateElementBitCast(Addr, DirectTy); 346 return Addr; 347 } 348 349 /// Emit va_arg for a platform using the common void* representation, 350 /// where arguments are simply emitted in an array of slots on the stack. 351 /// 352 /// \param IsIndirect - Values of this type are passed indirectly. 353 /// \param ValueInfo - The size and alignment of this type, generally 354 /// computed with getContext().getTypeInfoInChars(ValueTy). 355 /// \param SlotSizeAndAlign - The size and alignment of a stack slot. 356 /// Each argument will be allocated to a multiple of this number of 357 /// slots, and all the slots will be aligned to this value. 358 /// \param AllowHigherAlign - The slot alignment is not a cap; 359 /// an argument type with an alignment greater than the slot size 360 /// will be emitted on a higher-alignment address, potentially 361 /// leaving one or more empty slots behind as padding. 362 static Address emitVoidPtrVAArg(CodeGenFunction &CGF, Address VAListAddr, 363 QualType ValueTy, bool IsIndirect, 364 TypeInfoChars ValueInfo, 365 CharUnits SlotSizeAndAlign, 366 bool AllowHigherAlign) { 367 // The size and alignment of the value that was passed directly. 368 CharUnits DirectSize, DirectAlign; 369 if (IsIndirect) { 370 DirectSize = CGF.getPointerSize(); 371 DirectAlign = CGF.getPointerAlign(); 372 } else { 373 DirectSize = ValueInfo.Width; 374 DirectAlign = ValueInfo.Align; 375 } 376 377 // Cast the address we've calculated to the right type. 378 llvm::Type *DirectTy = CGF.ConvertTypeForMem(ValueTy); 379 if (IsIndirect) 380 DirectTy = DirectTy->getPointerTo(0); 381 382 Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, DirectTy, 383 DirectSize, DirectAlign, 384 SlotSizeAndAlign, 385 AllowHigherAlign); 386 387 if (IsIndirect) { 388 Addr = Address(CGF.Builder.CreateLoad(Addr), ValueInfo.Align); 389 } 390 391 return Addr; 392 393 } 394 395 static Address complexTempStructure(CodeGenFunction &CGF, Address VAListAddr, 396 QualType Ty, CharUnits SlotSize, 397 CharUnits EltSize, const ComplexType *CTy) { 398 Address Addr = 399 emitVoidPtrDirectVAArg(CGF, VAListAddr, CGF.Int8Ty, SlotSize * 2, 400 SlotSize, SlotSize, /*AllowHigher*/ true); 401 402 Address RealAddr = Addr; 403 Address ImagAddr = RealAddr; 404 if (CGF.CGM.getDataLayout().isBigEndian()) { 405 RealAddr = 406 CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, SlotSize - EltSize); 407 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(ImagAddr, 408 2 * SlotSize - EltSize); 409 } else { 410 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, SlotSize); 411 } 412 413 llvm::Type *EltTy = CGF.ConvertTypeForMem(CTy->getElementType()); 414 RealAddr = CGF.Builder.CreateElementBitCast(RealAddr, EltTy); 415 ImagAddr = CGF.Builder.CreateElementBitCast(ImagAddr, EltTy); 416 llvm::Value *Real = CGF.Builder.CreateLoad(RealAddr, ".vareal"); 417 llvm::Value *Imag = CGF.Builder.CreateLoad(ImagAddr, ".vaimag"); 418 419 Address Temp = CGF.CreateMemTemp(Ty, "vacplx"); 420 CGF.EmitStoreOfComplex({Real, Imag}, CGF.MakeAddrLValue(Temp, Ty), 421 /*init*/ true); 422 return Temp; 423 } 424 425 static Address emitMergePHI(CodeGenFunction &CGF, 426 Address Addr1, llvm::BasicBlock *Block1, 427 Address Addr2, llvm::BasicBlock *Block2, 428 const llvm::Twine &Name = "") { 429 assert(Addr1.getType() == Addr2.getType()); 430 llvm::PHINode *PHI = CGF.Builder.CreatePHI(Addr1.getType(), 2, Name); 431 PHI->addIncoming(Addr1.getPointer(), Block1); 432 PHI->addIncoming(Addr2.getPointer(), Block2); 433 CharUnits Align = std::min(Addr1.getAlignment(), Addr2.getAlignment()); 434 return Address(PHI, Align); 435 } 436 437 TargetCodeGenInfo::~TargetCodeGenInfo() = default; 438 439 // If someone can figure out a general rule for this, that would be great. 440 // It's probably just doomed to be platform-dependent, though. 441 unsigned TargetCodeGenInfo::getSizeOfUnwindException() const { 442 // Verified for: 443 // x86-64 FreeBSD, Linux, Darwin 444 // x86-32 FreeBSD, Linux, Darwin 445 // PowerPC Linux, Darwin 446 // ARM Darwin (*not* EABI) 447 // AArch64 Linux 448 return 32; 449 } 450 451 bool TargetCodeGenInfo::isNoProtoCallVariadic(const CallArgList &args, 452 const FunctionNoProtoType *fnType) const { 453 // The following conventions are known to require this to be false: 454 // x86_stdcall 455 // MIPS 456 // For everything else, we just prefer false unless we opt out. 457 return false; 458 } 459 460 void 461 TargetCodeGenInfo::getDependentLibraryOption(llvm::StringRef Lib, 462 llvm::SmallString<24> &Opt) const { 463 // This assumes the user is passing a library name like "rt" instead of a 464 // filename like "librt.a/so", and that they don't care whether it's static or 465 // dynamic. 466 Opt = "-l"; 467 Opt += Lib; 468 } 469 470 unsigned TargetCodeGenInfo::getOpenCLKernelCallingConv() const { 471 // OpenCL kernels are called via an explicit runtime API with arguments 472 // set with clSetKernelArg(), not as normal sub-functions. 473 // Return SPIR_KERNEL by default as the kernel calling convention to 474 // ensure the fingerprint is fixed such way that each OpenCL argument 475 // gets one matching argument in the produced kernel function argument 476 // list to enable feasible implementation of clSetKernelArg() with 477 // aggregates etc. In case we would use the default C calling conv here, 478 // clSetKernelArg() might break depending on the target-specific 479 // conventions; different targets might split structs passed as values 480 // to multiple function arguments etc. 481 return llvm::CallingConv::SPIR_KERNEL; 482 } 483 484 llvm::Constant *TargetCodeGenInfo::getNullPointer(const CodeGen::CodeGenModule &CGM, 485 llvm::PointerType *T, QualType QT) const { 486 return llvm::ConstantPointerNull::get(T); 487 } 488 489 LangAS TargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM, 490 const VarDecl *D) const { 491 assert(!CGM.getLangOpts().OpenCL && 492 !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) && 493 "Address space agnostic languages only"); 494 return D ? D->getType().getAddressSpace() : LangAS::Default; 495 } 496 497 llvm::Value *TargetCodeGenInfo::performAddrSpaceCast( 498 CodeGen::CodeGenFunction &CGF, llvm::Value *Src, LangAS SrcAddr, 499 LangAS DestAddr, llvm::Type *DestTy, bool isNonNull) const { 500 // Since target may map different address spaces in AST to the same address 501 // space, an address space conversion may end up as a bitcast. 502 if (auto *C = dyn_cast<llvm::Constant>(Src)) 503 return performAddrSpaceCast(CGF.CGM, C, SrcAddr, DestAddr, DestTy); 504 // Try to preserve the source's name to make IR more readable. 505 return CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( 506 Src, DestTy, Src->hasName() ? Src->getName() + ".ascast" : ""); 507 } 508 509 llvm::Constant * 510 TargetCodeGenInfo::performAddrSpaceCast(CodeGenModule &CGM, llvm::Constant *Src, 511 LangAS SrcAddr, LangAS DestAddr, 512 llvm::Type *DestTy) const { 513 // Since target may map different address spaces in AST to the same address 514 // space, an address space conversion may end up as a bitcast. 515 return llvm::ConstantExpr::getPointerCast(Src, DestTy); 516 } 517 518 llvm::SyncScope::ID 519 TargetCodeGenInfo::getLLVMSyncScopeID(const LangOptions &LangOpts, 520 SyncScope Scope, 521 llvm::AtomicOrdering Ordering, 522 llvm::LLVMContext &Ctx) const { 523 return Ctx.getOrInsertSyncScopeID(""); /* default sync scope */ 524 } 525 526 static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays); 527 528 /// isEmptyField - Return true iff a the field is "empty", that is it 529 /// is an unnamed bit-field or an (array of) empty record(s). 530 static bool isEmptyField(ASTContext &Context, const FieldDecl *FD, 531 bool AllowArrays) { 532 if (FD->isUnnamedBitfield()) 533 return true; 534 535 QualType FT = FD->getType(); 536 537 // Constant arrays of empty records count as empty, strip them off. 538 // Constant arrays of zero length always count as empty. 539 bool WasArray = false; 540 if (AllowArrays) 541 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) { 542 if (AT->getSize() == 0) 543 return true; 544 FT = AT->getElementType(); 545 // The [[no_unique_address]] special case below does not apply to 546 // arrays of C++ empty records, so we need to remember this fact. 547 WasArray = true; 548 } 549 550 const RecordType *RT = FT->getAs<RecordType>(); 551 if (!RT) 552 return false; 553 554 // C++ record fields are never empty, at least in the Itanium ABI. 555 // 556 // FIXME: We should use a predicate for whether this behavior is true in the 557 // current ABI. 558 // 559 // The exception to the above rule are fields marked with the 560 // [[no_unique_address]] attribute (since C++20). Those do count as empty 561 // according to the Itanium ABI. The exception applies only to records, 562 // not arrays of records, so we must also check whether we stripped off an 563 // array type above. 564 if (isa<CXXRecordDecl>(RT->getDecl()) && 565 (WasArray || !FD->hasAttr<NoUniqueAddressAttr>())) 566 return false; 567 568 return isEmptyRecord(Context, FT, AllowArrays); 569 } 570 571 /// isEmptyRecord - Return true iff a structure contains only empty 572 /// fields. Note that a structure with a flexible array member is not 573 /// considered empty. 574 static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) { 575 const RecordType *RT = T->getAs<RecordType>(); 576 if (!RT) 577 return false; 578 const RecordDecl *RD = RT->getDecl(); 579 if (RD->hasFlexibleArrayMember()) 580 return false; 581 582 // If this is a C++ record, check the bases first. 583 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 584 for (const auto &I : CXXRD->bases()) 585 if (!isEmptyRecord(Context, I.getType(), true)) 586 return false; 587 588 for (const auto *I : RD->fields()) 589 if (!isEmptyField(Context, I, AllowArrays)) 590 return false; 591 return true; 592 } 593 594 /// isSingleElementStruct - Determine if a structure is a "single 595 /// element struct", i.e. it has exactly one non-empty field or 596 /// exactly one field which is itself a single element 597 /// struct. Structures with flexible array members are never 598 /// considered single element structs. 599 /// 600 /// \return The field declaration for the single non-empty field, if 601 /// it exists. 602 static const Type *isSingleElementStruct(QualType T, ASTContext &Context) { 603 const RecordType *RT = T->getAs<RecordType>(); 604 if (!RT) 605 return nullptr; 606 607 const RecordDecl *RD = RT->getDecl(); 608 if (RD->hasFlexibleArrayMember()) 609 return nullptr; 610 611 const Type *Found = nullptr; 612 613 // If this is a C++ record, check the bases first. 614 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 615 for (const auto &I : CXXRD->bases()) { 616 // Ignore empty records. 617 if (isEmptyRecord(Context, I.getType(), true)) 618 continue; 619 620 // If we already found an element then this isn't a single-element struct. 621 if (Found) 622 return nullptr; 623 624 // If this is non-empty and not a single element struct, the composite 625 // cannot be a single element struct. 626 Found = isSingleElementStruct(I.getType(), Context); 627 if (!Found) 628 return nullptr; 629 } 630 } 631 632 // Check for single element. 633 for (const auto *FD : RD->fields()) { 634 QualType FT = FD->getType(); 635 636 // Ignore empty fields. 637 if (isEmptyField(Context, FD, true)) 638 continue; 639 640 // If we already found an element then this isn't a single-element 641 // struct. 642 if (Found) 643 return nullptr; 644 645 // Treat single element arrays as the element. 646 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) { 647 if (AT->getSize().getZExtValue() != 1) 648 break; 649 FT = AT->getElementType(); 650 } 651 652 if (!isAggregateTypeForABI(FT)) { 653 Found = FT.getTypePtr(); 654 } else { 655 Found = isSingleElementStruct(FT, Context); 656 if (!Found) 657 return nullptr; 658 } 659 } 660 661 // We don't consider a struct a single-element struct if it has 662 // padding beyond the element type. 663 if (Found && Context.getTypeSize(Found) != Context.getTypeSize(T)) 664 return nullptr; 665 666 return Found; 667 } 668 669 namespace { 670 Address EmitVAArgInstr(CodeGenFunction &CGF, Address VAListAddr, QualType Ty, 671 const ABIArgInfo &AI) { 672 // This default implementation defers to the llvm backend's va_arg 673 // instruction. It can handle only passing arguments directly 674 // (typically only handled in the backend for primitive types), or 675 // aggregates passed indirectly by pointer (NOTE: if the "byval" 676 // flag has ABI impact in the callee, this implementation cannot 677 // work.) 678 679 // Only a few cases are covered here at the moment -- those needed 680 // by the default abi. 681 llvm::Value *Val; 682 683 if (AI.isIndirect()) { 684 assert(!AI.getPaddingType() && 685 "Unexpected PaddingType seen in arginfo in generic VAArg emitter!"); 686 assert( 687 !AI.getIndirectRealign() && 688 "Unexpected IndirectRealign seen in arginfo in generic VAArg emitter!"); 689 690 auto TyInfo = CGF.getContext().getTypeInfoInChars(Ty); 691 CharUnits TyAlignForABI = TyInfo.Align; 692 693 llvm::Type *BaseTy = 694 llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty)); 695 llvm::Value *Addr = 696 CGF.Builder.CreateVAArg(VAListAddr.getPointer(), BaseTy); 697 return Address(Addr, TyAlignForABI); 698 } else { 699 assert((AI.isDirect() || AI.isExtend()) && 700 "Unexpected ArgInfo Kind in generic VAArg emitter!"); 701 702 assert(!AI.getInReg() && 703 "Unexpected InReg seen in arginfo in generic VAArg emitter!"); 704 assert(!AI.getPaddingType() && 705 "Unexpected PaddingType seen in arginfo in generic VAArg emitter!"); 706 assert(!AI.getDirectOffset() && 707 "Unexpected DirectOffset seen in arginfo in generic VAArg emitter!"); 708 assert(!AI.getCoerceToType() && 709 "Unexpected CoerceToType seen in arginfo in generic VAArg emitter!"); 710 711 Address Temp = CGF.CreateMemTemp(Ty, "varet"); 712 Val = CGF.Builder.CreateVAArg(VAListAddr.getPointer(), CGF.ConvertType(Ty)); 713 CGF.Builder.CreateStore(Val, Temp); 714 return Temp; 715 } 716 } 717 718 /// DefaultABIInfo - The default implementation for ABI specific 719 /// details. This implementation provides information which results in 720 /// self-consistent and sensible LLVM IR generation, but does not 721 /// conform to any particular ABI. 722 class DefaultABIInfo : public ABIInfo { 723 public: 724 DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {} 725 726 ABIArgInfo classifyReturnType(QualType RetTy) const; 727 ABIArgInfo classifyArgumentType(QualType RetTy) const; 728 729 void computeInfo(CGFunctionInfo &FI) const override { 730 if (!getCXXABI().classifyReturnType(FI)) 731 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 732 for (auto &I : FI.arguments()) 733 I.info = classifyArgumentType(I.type); 734 } 735 736 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 737 QualType Ty) const override { 738 return EmitVAArgInstr(CGF, VAListAddr, Ty, classifyArgumentType(Ty)); 739 } 740 }; 741 742 class DefaultTargetCodeGenInfo : public TargetCodeGenInfo { 743 public: 744 DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT) 745 : TargetCodeGenInfo(std::make_unique<DefaultABIInfo>(CGT)) {} 746 }; 747 748 ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const { 749 Ty = useFirstFieldIfTransparentUnion(Ty); 750 751 if (isAggregateTypeForABI(Ty)) { 752 // Records with non-trivial destructors/copy-constructors should not be 753 // passed by value. 754 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 755 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 756 757 return getNaturalAlignIndirect(Ty); 758 } 759 760 // Treat an enum type as its underlying type. 761 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 762 Ty = EnumTy->getDecl()->getIntegerType(); 763 764 ASTContext &Context = getContext(); 765 if (const auto *EIT = Ty->getAs<ExtIntType>()) 766 if (EIT->getNumBits() > 767 Context.getTypeSize(Context.getTargetInfo().hasInt128Type() 768 ? Context.Int128Ty 769 : Context.LongLongTy)) 770 return getNaturalAlignIndirect(Ty); 771 772 return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty) 773 : ABIArgInfo::getDirect()); 774 } 775 776 ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const { 777 if (RetTy->isVoidType()) 778 return ABIArgInfo::getIgnore(); 779 780 if (isAggregateTypeForABI(RetTy)) 781 return getNaturalAlignIndirect(RetTy); 782 783 // Treat an enum type as its underlying type. 784 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 785 RetTy = EnumTy->getDecl()->getIntegerType(); 786 787 if (const auto *EIT = RetTy->getAs<ExtIntType>()) 788 if (EIT->getNumBits() > 789 getContext().getTypeSize(getContext().getTargetInfo().hasInt128Type() 790 ? getContext().Int128Ty 791 : getContext().LongLongTy)) 792 return getNaturalAlignIndirect(RetTy); 793 794 return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy) 795 : ABIArgInfo::getDirect()); 796 } 797 798 //===----------------------------------------------------------------------===// 799 // WebAssembly ABI Implementation 800 // 801 // This is a very simple ABI that relies a lot on DefaultABIInfo. 802 //===----------------------------------------------------------------------===// 803 804 class WebAssemblyABIInfo final : public SwiftABIInfo { 805 public: 806 enum ABIKind { 807 MVP = 0, 808 ExperimentalMV = 1, 809 }; 810 811 private: 812 DefaultABIInfo defaultInfo; 813 ABIKind Kind; 814 815 public: 816 explicit WebAssemblyABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind) 817 : SwiftABIInfo(CGT), defaultInfo(CGT), Kind(Kind) {} 818 819 private: 820 ABIArgInfo classifyReturnType(QualType RetTy) const; 821 ABIArgInfo classifyArgumentType(QualType Ty) const; 822 823 // DefaultABIInfo's classifyReturnType and classifyArgumentType are 824 // non-virtual, but computeInfo and EmitVAArg are virtual, so we 825 // overload them. 826 void computeInfo(CGFunctionInfo &FI) const override { 827 if (!getCXXABI().classifyReturnType(FI)) 828 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 829 for (auto &Arg : FI.arguments()) 830 Arg.info = classifyArgumentType(Arg.type); 831 } 832 833 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 834 QualType Ty) const override; 835 836 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars, 837 bool asReturnValue) const override { 838 return occupiesMoreThan(CGT, scalars, /*total*/ 4); 839 } 840 841 bool isSwiftErrorInRegister() const override { 842 return false; 843 } 844 }; 845 846 class WebAssemblyTargetCodeGenInfo final : public TargetCodeGenInfo { 847 public: 848 explicit WebAssemblyTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, 849 WebAssemblyABIInfo::ABIKind K) 850 : TargetCodeGenInfo(std::make_unique<WebAssemblyABIInfo>(CGT, K)) {} 851 852 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 853 CodeGen::CodeGenModule &CGM) const override { 854 TargetCodeGenInfo::setTargetAttributes(D, GV, CGM); 855 if (const auto *FD = dyn_cast_or_null<FunctionDecl>(D)) { 856 if (const auto *Attr = FD->getAttr<WebAssemblyImportModuleAttr>()) { 857 llvm::Function *Fn = cast<llvm::Function>(GV); 858 llvm::AttrBuilder B; 859 B.addAttribute("wasm-import-module", Attr->getImportModule()); 860 Fn->addFnAttrs(B); 861 } 862 if (const auto *Attr = FD->getAttr<WebAssemblyImportNameAttr>()) { 863 llvm::Function *Fn = cast<llvm::Function>(GV); 864 llvm::AttrBuilder B; 865 B.addAttribute("wasm-import-name", Attr->getImportName()); 866 Fn->addFnAttrs(B); 867 } 868 if (const auto *Attr = FD->getAttr<WebAssemblyExportNameAttr>()) { 869 llvm::Function *Fn = cast<llvm::Function>(GV); 870 llvm::AttrBuilder B; 871 B.addAttribute("wasm-export-name", Attr->getExportName()); 872 Fn->addFnAttrs(B); 873 } 874 } 875 876 if (auto *FD = dyn_cast_or_null<FunctionDecl>(D)) { 877 llvm::Function *Fn = cast<llvm::Function>(GV); 878 if (!FD->doesThisDeclarationHaveABody() && !FD->hasPrototype()) 879 Fn->addFnAttr("no-prototype"); 880 } 881 } 882 }; 883 884 /// Classify argument of given type \p Ty. 885 ABIArgInfo WebAssemblyABIInfo::classifyArgumentType(QualType Ty) const { 886 Ty = useFirstFieldIfTransparentUnion(Ty); 887 888 if (isAggregateTypeForABI(Ty)) { 889 // Records with non-trivial destructors/copy-constructors should not be 890 // passed by value. 891 if (auto RAA = getRecordArgABI(Ty, getCXXABI())) 892 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 893 // Ignore empty structs/unions. 894 if (isEmptyRecord(getContext(), Ty, true)) 895 return ABIArgInfo::getIgnore(); 896 // Lower single-element structs to just pass a regular value. TODO: We 897 // could do reasonable-size multiple-element structs too, using getExpand(), 898 // though watch out for things like bitfields. 899 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext())) 900 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0))); 901 // For the experimental multivalue ABI, fully expand all other aggregates 902 if (Kind == ABIKind::ExperimentalMV) { 903 const RecordType *RT = Ty->getAs<RecordType>(); 904 assert(RT); 905 bool HasBitField = false; 906 for (auto *Field : RT->getDecl()->fields()) { 907 if (Field->isBitField()) { 908 HasBitField = true; 909 break; 910 } 911 } 912 if (!HasBitField) 913 return ABIArgInfo::getExpand(); 914 } 915 } 916 917 // Otherwise just do the default thing. 918 return defaultInfo.classifyArgumentType(Ty); 919 } 920 921 ABIArgInfo WebAssemblyABIInfo::classifyReturnType(QualType RetTy) const { 922 if (isAggregateTypeForABI(RetTy)) { 923 // Records with non-trivial destructors/copy-constructors should not be 924 // returned by value. 925 if (!getRecordArgABI(RetTy, getCXXABI())) { 926 // Ignore empty structs/unions. 927 if (isEmptyRecord(getContext(), RetTy, true)) 928 return ABIArgInfo::getIgnore(); 929 // Lower single-element structs to just return a regular value. TODO: We 930 // could do reasonable-size multiple-element structs too, using 931 // ABIArgInfo::getDirect(). 932 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext())) 933 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0))); 934 // For the experimental multivalue ABI, return all other aggregates 935 if (Kind == ABIKind::ExperimentalMV) 936 return ABIArgInfo::getDirect(); 937 } 938 } 939 940 // Otherwise just do the default thing. 941 return defaultInfo.classifyReturnType(RetTy); 942 } 943 944 Address WebAssemblyABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 945 QualType Ty) const { 946 bool IsIndirect = isAggregateTypeForABI(Ty) && 947 !isEmptyRecord(getContext(), Ty, true) && 948 !isSingleElementStruct(Ty, getContext()); 949 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, 950 getContext().getTypeInfoInChars(Ty), 951 CharUnits::fromQuantity(4), 952 /*AllowHigherAlign=*/true); 953 } 954 955 //===----------------------------------------------------------------------===// 956 // le32/PNaCl bitcode ABI Implementation 957 // 958 // This is a simplified version of the x86_32 ABI. Arguments and return values 959 // are always passed on the stack. 960 //===----------------------------------------------------------------------===// 961 962 class PNaClABIInfo : public ABIInfo { 963 public: 964 PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {} 965 966 ABIArgInfo classifyReturnType(QualType RetTy) const; 967 ABIArgInfo classifyArgumentType(QualType RetTy) const; 968 969 void computeInfo(CGFunctionInfo &FI) const override; 970 Address EmitVAArg(CodeGenFunction &CGF, 971 Address VAListAddr, QualType Ty) const override; 972 }; 973 974 class PNaClTargetCodeGenInfo : public TargetCodeGenInfo { 975 public: 976 PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT) 977 : TargetCodeGenInfo(std::make_unique<PNaClABIInfo>(CGT)) {} 978 }; 979 980 void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const { 981 if (!getCXXABI().classifyReturnType(FI)) 982 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 983 984 for (auto &I : FI.arguments()) 985 I.info = classifyArgumentType(I.type); 986 } 987 988 Address PNaClABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 989 QualType Ty) const { 990 // The PNaCL ABI is a bit odd, in that varargs don't use normal 991 // function classification. Structs get passed directly for varargs 992 // functions, through a rewriting transform in 993 // pnacl-llvm/lib/Transforms/NaCl/ExpandVarArgs.cpp, which allows 994 // this target to actually support a va_arg instructions with an 995 // aggregate type, unlike other targets. 996 return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect()); 997 } 998 999 /// Classify argument of given type \p Ty. 1000 ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const { 1001 if (isAggregateTypeForABI(Ty)) { 1002 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 1003 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 1004 return getNaturalAlignIndirect(Ty); 1005 } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) { 1006 // Treat an enum type as its underlying type. 1007 Ty = EnumTy->getDecl()->getIntegerType(); 1008 } else if (Ty->isFloatingType()) { 1009 // Floating-point types don't go inreg. 1010 return ABIArgInfo::getDirect(); 1011 } else if (const auto *EIT = Ty->getAs<ExtIntType>()) { 1012 // Treat extended integers as integers if <=64, otherwise pass indirectly. 1013 if (EIT->getNumBits() > 64) 1014 return getNaturalAlignIndirect(Ty); 1015 return ABIArgInfo::getDirect(); 1016 } 1017 1018 return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty) 1019 : ABIArgInfo::getDirect()); 1020 } 1021 1022 ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const { 1023 if (RetTy->isVoidType()) 1024 return ABIArgInfo::getIgnore(); 1025 1026 // In the PNaCl ABI we always return records/structures on the stack. 1027 if (isAggregateTypeForABI(RetTy)) 1028 return getNaturalAlignIndirect(RetTy); 1029 1030 // Treat extended integers as integers if <=64, otherwise pass indirectly. 1031 if (const auto *EIT = RetTy->getAs<ExtIntType>()) { 1032 if (EIT->getNumBits() > 64) 1033 return getNaturalAlignIndirect(RetTy); 1034 return ABIArgInfo::getDirect(); 1035 } 1036 1037 // Treat an enum type as its underlying type. 1038 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 1039 RetTy = EnumTy->getDecl()->getIntegerType(); 1040 1041 return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy) 1042 : ABIArgInfo::getDirect()); 1043 } 1044 1045 /// IsX86_MMXType - Return true if this is an MMX type. 1046 bool IsX86_MMXType(llvm::Type *IRType) { 1047 // Return true if the type is an MMX type <2 x i32>, <4 x i16>, or <8 x i8>. 1048 return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 && 1049 cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() && 1050 IRType->getScalarSizeInBits() != 64; 1051 } 1052 1053 static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF, 1054 StringRef Constraint, 1055 llvm::Type* Ty) { 1056 bool IsMMXCons = llvm::StringSwitch<bool>(Constraint) 1057 .Cases("y", "&y", "^Ym", true) 1058 .Default(false); 1059 if (IsMMXCons && Ty->isVectorTy()) { 1060 if (cast<llvm::VectorType>(Ty)->getPrimitiveSizeInBits().getFixedSize() != 1061 64) { 1062 // Invalid MMX constraint 1063 return nullptr; 1064 } 1065 1066 return llvm::Type::getX86_MMXTy(CGF.getLLVMContext()); 1067 } 1068 1069 // No operation needed 1070 return Ty; 1071 } 1072 1073 /// Returns true if this type can be passed in SSE registers with the 1074 /// X86_VectorCall calling convention. Shared between x86_32 and x86_64. 1075 static bool isX86VectorTypeForVectorCall(ASTContext &Context, QualType Ty) { 1076 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) { 1077 if (BT->isFloatingPoint() && BT->getKind() != BuiltinType::Half) { 1078 if (BT->getKind() == BuiltinType::LongDouble) { 1079 if (&Context.getTargetInfo().getLongDoubleFormat() == 1080 &llvm::APFloat::x87DoubleExtended()) 1081 return false; 1082 } 1083 return true; 1084 } 1085 } else if (const VectorType *VT = Ty->getAs<VectorType>()) { 1086 // vectorcall can pass XMM, YMM, and ZMM vectors. We don't pass SSE1 MMX 1087 // registers specially. 1088 unsigned VecSize = Context.getTypeSize(VT); 1089 if (VecSize == 128 || VecSize == 256 || VecSize == 512) 1090 return true; 1091 } 1092 return false; 1093 } 1094 1095 /// Returns true if this aggregate is small enough to be passed in SSE registers 1096 /// in the X86_VectorCall calling convention. Shared between x86_32 and x86_64. 1097 static bool isX86VectorCallAggregateSmallEnough(uint64_t NumMembers) { 1098 return NumMembers <= 4; 1099 } 1100 1101 /// Returns a Homogeneous Vector Aggregate ABIArgInfo, used in X86. 1102 static ABIArgInfo getDirectX86Hva(llvm::Type* T = nullptr) { 1103 auto AI = ABIArgInfo::getDirect(T); 1104 AI.setInReg(true); 1105 AI.setCanBeFlattened(false); 1106 return AI; 1107 } 1108 1109 //===----------------------------------------------------------------------===// 1110 // X86-32 ABI Implementation 1111 //===----------------------------------------------------------------------===// 1112 1113 /// Similar to llvm::CCState, but for Clang. 1114 struct CCState { 1115 CCState(CGFunctionInfo &FI) 1116 : IsPreassigned(FI.arg_size()), CC(FI.getCallingConvention()) {} 1117 1118 llvm::SmallBitVector IsPreassigned; 1119 unsigned CC = CallingConv::CC_C; 1120 unsigned FreeRegs = 0; 1121 unsigned FreeSSERegs = 0; 1122 }; 1123 1124 /// X86_32ABIInfo - The X86-32 ABI information. 1125 class X86_32ABIInfo : public SwiftABIInfo { 1126 enum Class { 1127 Integer, 1128 Float 1129 }; 1130 1131 static const unsigned MinABIStackAlignInBytes = 4; 1132 1133 bool IsDarwinVectorABI; 1134 bool IsRetSmallStructInRegABI; 1135 bool IsWin32StructABI; 1136 bool IsSoftFloatABI; 1137 bool IsMCUABI; 1138 bool IsLinuxABI; 1139 unsigned DefaultNumRegisterParameters; 1140 1141 static bool isRegisterSize(unsigned Size) { 1142 return (Size == 8 || Size == 16 || Size == 32 || Size == 64); 1143 } 1144 1145 bool isHomogeneousAggregateBaseType(QualType Ty) const override { 1146 // FIXME: Assumes vectorcall is in use. 1147 return isX86VectorTypeForVectorCall(getContext(), Ty); 1148 } 1149 1150 bool isHomogeneousAggregateSmallEnough(const Type *Ty, 1151 uint64_t NumMembers) const override { 1152 // FIXME: Assumes vectorcall is in use. 1153 return isX86VectorCallAggregateSmallEnough(NumMembers); 1154 } 1155 1156 bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context) const; 1157 1158 /// getIndirectResult - Give a source type \arg Ty, return a suitable result 1159 /// such that the argument will be passed in memory. 1160 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const; 1161 1162 ABIArgInfo getIndirectReturnResult(QualType Ty, CCState &State) const; 1163 1164 /// Return the alignment to use for the given type on the stack. 1165 unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const; 1166 1167 Class classify(QualType Ty) const; 1168 ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const; 1169 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const; 1170 1171 /// Updates the number of available free registers, returns 1172 /// true if any registers were allocated. 1173 bool updateFreeRegs(QualType Ty, CCState &State) const; 1174 1175 bool shouldAggregateUseDirect(QualType Ty, CCState &State, bool &InReg, 1176 bool &NeedsPadding) const; 1177 bool shouldPrimitiveUseInReg(QualType Ty, CCState &State) const; 1178 1179 bool canExpandIndirectArgument(QualType Ty) const; 1180 1181 /// Rewrite the function info so that all memory arguments use 1182 /// inalloca. 1183 void rewriteWithInAlloca(CGFunctionInfo &FI) const; 1184 1185 void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields, 1186 CharUnits &StackOffset, ABIArgInfo &Info, 1187 QualType Type) const; 1188 void runVectorCallFirstPass(CGFunctionInfo &FI, CCState &State) const; 1189 1190 public: 1191 1192 void computeInfo(CGFunctionInfo &FI) const override; 1193 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 1194 QualType Ty) const override; 1195 1196 X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI, 1197 bool RetSmallStructInRegABI, bool Win32StructABI, 1198 unsigned NumRegisterParameters, bool SoftFloatABI) 1199 : SwiftABIInfo(CGT), IsDarwinVectorABI(DarwinVectorABI), 1200 IsRetSmallStructInRegABI(RetSmallStructInRegABI), 1201 IsWin32StructABI(Win32StructABI), IsSoftFloatABI(SoftFloatABI), 1202 IsMCUABI(CGT.getTarget().getTriple().isOSIAMCU()), 1203 IsLinuxABI(CGT.getTarget().getTriple().isOSLinux() || 1204 CGT.getTarget().getTriple().isOSCygMing()), 1205 DefaultNumRegisterParameters(NumRegisterParameters) {} 1206 1207 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars, 1208 bool asReturnValue) const override { 1209 // LLVM's x86-32 lowering currently only assigns up to three 1210 // integer registers and three fp registers. Oddly, it'll use up to 1211 // four vector registers for vectors, but those can overlap with the 1212 // scalar registers. 1213 return occupiesMoreThan(CGT, scalars, /*total*/ 3); 1214 } 1215 1216 bool isSwiftErrorInRegister() const override { 1217 // x86-32 lowering does not support passing swifterror in a register. 1218 return false; 1219 } 1220 }; 1221 1222 class X86_32TargetCodeGenInfo : public TargetCodeGenInfo { 1223 public: 1224 X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI, 1225 bool RetSmallStructInRegABI, bool Win32StructABI, 1226 unsigned NumRegisterParameters, bool SoftFloatABI) 1227 : TargetCodeGenInfo(std::make_unique<X86_32ABIInfo>( 1228 CGT, DarwinVectorABI, RetSmallStructInRegABI, Win32StructABI, 1229 NumRegisterParameters, SoftFloatABI)) {} 1230 1231 static bool isStructReturnInRegABI( 1232 const llvm::Triple &Triple, const CodeGenOptions &Opts); 1233 1234 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 1235 CodeGen::CodeGenModule &CGM) const override; 1236 1237 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override { 1238 // Darwin uses different dwarf register numbers for EH. 1239 if (CGM.getTarget().getTriple().isOSDarwin()) return 5; 1240 return 4; 1241 } 1242 1243 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 1244 llvm::Value *Address) const override; 1245 1246 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF, 1247 StringRef Constraint, 1248 llvm::Type* Ty) const override { 1249 return X86AdjustInlineAsmType(CGF, Constraint, Ty); 1250 } 1251 1252 void addReturnRegisterOutputs(CodeGenFunction &CGF, LValue ReturnValue, 1253 std::string &Constraints, 1254 std::vector<llvm::Type *> &ResultRegTypes, 1255 std::vector<llvm::Type *> &ResultTruncRegTypes, 1256 std::vector<LValue> &ResultRegDests, 1257 std::string &AsmString, 1258 unsigned NumOutputs) const override; 1259 1260 llvm::Constant * 1261 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override { 1262 unsigned Sig = (0xeb << 0) | // jmp rel8 1263 (0x06 << 8) | // .+0x08 1264 ('v' << 16) | 1265 ('2' << 24); 1266 return llvm::ConstantInt::get(CGM.Int32Ty, Sig); 1267 } 1268 1269 StringRef getARCRetainAutoreleasedReturnValueMarker() const override { 1270 return "movl\t%ebp, %ebp" 1271 "\t\t// marker for objc_retainAutoreleaseReturnValue"; 1272 } 1273 }; 1274 1275 } 1276 1277 /// Rewrite input constraint references after adding some output constraints. 1278 /// In the case where there is one output and one input and we add one output, 1279 /// we need to replace all operand references greater than or equal to 1: 1280 /// mov $0, $1 1281 /// mov eax, $1 1282 /// The result will be: 1283 /// mov $0, $2 1284 /// mov eax, $2 1285 static void rewriteInputConstraintReferences(unsigned FirstIn, 1286 unsigned NumNewOuts, 1287 std::string &AsmString) { 1288 std::string Buf; 1289 llvm::raw_string_ostream OS(Buf); 1290 size_t Pos = 0; 1291 while (Pos < AsmString.size()) { 1292 size_t DollarStart = AsmString.find('$', Pos); 1293 if (DollarStart == std::string::npos) 1294 DollarStart = AsmString.size(); 1295 size_t DollarEnd = AsmString.find_first_not_of('$', DollarStart); 1296 if (DollarEnd == std::string::npos) 1297 DollarEnd = AsmString.size(); 1298 OS << StringRef(&AsmString[Pos], DollarEnd - Pos); 1299 Pos = DollarEnd; 1300 size_t NumDollars = DollarEnd - DollarStart; 1301 if (NumDollars % 2 != 0 && Pos < AsmString.size()) { 1302 // We have an operand reference. 1303 size_t DigitStart = Pos; 1304 if (AsmString[DigitStart] == '{') { 1305 OS << '{'; 1306 ++DigitStart; 1307 } 1308 size_t DigitEnd = AsmString.find_first_not_of("0123456789", DigitStart); 1309 if (DigitEnd == std::string::npos) 1310 DigitEnd = AsmString.size(); 1311 StringRef OperandStr(&AsmString[DigitStart], DigitEnd - DigitStart); 1312 unsigned OperandIndex; 1313 if (!OperandStr.getAsInteger(10, OperandIndex)) { 1314 if (OperandIndex >= FirstIn) 1315 OperandIndex += NumNewOuts; 1316 OS << OperandIndex; 1317 } else { 1318 OS << OperandStr; 1319 } 1320 Pos = DigitEnd; 1321 } 1322 } 1323 AsmString = std::move(OS.str()); 1324 } 1325 1326 /// Add output constraints for EAX:EDX because they are return registers. 1327 void X86_32TargetCodeGenInfo::addReturnRegisterOutputs( 1328 CodeGenFunction &CGF, LValue ReturnSlot, std::string &Constraints, 1329 std::vector<llvm::Type *> &ResultRegTypes, 1330 std::vector<llvm::Type *> &ResultTruncRegTypes, 1331 std::vector<LValue> &ResultRegDests, std::string &AsmString, 1332 unsigned NumOutputs) const { 1333 uint64_t RetWidth = CGF.getContext().getTypeSize(ReturnSlot.getType()); 1334 1335 // Use the EAX constraint if the width is 32 or smaller and EAX:EDX if it is 1336 // larger. 1337 if (!Constraints.empty()) 1338 Constraints += ','; 1339 if (RetWidth <= 32) { 1340 Constraints += "={eax}"; 1341 ResultRegTypes.push_back(CGF.Int32Ty); 1342 } else { 1343 // Use the 'A' constraint for EAX:EDX. 1344 Constraints += "=A"; 1345 ResultRegTypes.push_back(CGF.Int64Ty); 1346 } 1347 1348 // Truncate EAX or EAX:EDX to an integer of the appropriate size. 1349 llvm::Type *CoerceTy = llvm::IntegerType::get(CGF.getLLVMContext(), RetWidth); 1350 ResultTruncRegTypes.push_back(CoerceTy); 1351 1352 // Coerce the integer by bitcasting the return slot pointer. 1353 ReturnSlot.setAddress(CGF.Builder.CreateBitCast(ReturnSlot.getAddress(CGF), 1354 CoerceTy->getPointerTo())); 1355 ResultRegDests.push_back(ReturnSlot); 1356 1357 rewriteInputConstraintReferences(NumOutputs, 1, AsmString); 1358 } 1359 1360 /// shouldReturnTypeInRegister - Determine if the given type should be 1361 /// returned in a register (for the Darwin and MCU ABI). 1362 bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty, 1363 ASTContext &Context) const { 1364 uint64_t Size = Context.getTypeSize(Ty); 1365 1366 // For i386, type must be register sized. 1367 // For the MCU ABI, it only needs to be <= 8-byte 1368 if ((IsMCUABI && Size > 64) || (!IsMCUABI && !isRegisterSize(Size))) 1369 return false; 1370 1371 if (Ty->isVectorType()) { 1372 // 64- and 128- bit vectors inside structures are not returned in 1373 // registers. 1374 if (Size == 64 || Size == 128) 1375 return false; 1376 1377 return true; 1378 } 1379 1380 // If this is a builtin, pointer, enum, complex type, member pointer, or 1381 // member function pointer it is ok. 1382 if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() || 1383 Ty->isAnyComplexType() || Ty->isEnumeralType() || 1384 Ty->isBlockPointerType() || Ty->isMemberPointerType()) 1385 return true; 1386 1387 // Arrays are treated like records. 1388 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) 1389 return shouldReturnTypeInRegister(AT->getElementType(), Context); 1390 1391 // Otherwise, it must be a record type. 1392 const RecordType *RT = Ty->getAs<RecordType>(); 1393 if (!RT) return false; 1394 1395 // FIXME: Traverse bases here too. 1396 1397 // Structure types are passed in register if all fields would be 1398 // passed in a register. 1399 for (const auto *FD : RT->getDecl()->fields()) { 1400 // Empty fields are ignored. 1401 if (isEmptyField(Context, FD, true)) 1402 continue; 1403 1404 // Check fields recursively. 1405 if (!shouldReturnTypeInRegister(FD->getType(), Context)) 1406 return false; 1407 } 1408 return true; 1409 } 1410 1411 static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) { 1412 // Treat complex types as the element type. 1413 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) 1414 Ty = CTy->getElementType(); 1415 1416 // Check for a type which we know has a simple scalar argument-passing 1417 // convention without any padding. (We're specifically looking for 32 1418 // and 64-bit integer and integer-equivalents, float, and double.) 1419 if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() && 1420 !Ty->isEnumeralType() && !Ty->isBlockPointerType()) 1421 return false; 1422 1423 uint64_t Size = Context.getTypeSize(Ty); 1424 return Size == 32 || Size == 64; 1425 } 1426 1427 static bool addFieldSizes(ASTContext &Context, const RecordDecl *RD, 1428 uint64_t &Size) { 1429 for (const auto *FD : RD->fields()) { 1430 // Scalar arguments on the stack get 4 byte alignment on x86. If the 1431 // argument is smaller than 32-bits, expanding the struct will create 1432 // alignment padding. 1433 if (!is32Or64BitBasicType(FD->getType(), Context)) 1434 return false; 1435 1436 // FIXME: Reject bit-fields wholesale; there are two problems, we don't know 1437 // how to expand them yet, and the predicate for telling if a bitfield still 1438 // counts as "basic" is more complicated than what we were doing previously. 1439 if (FD->isBitField()) 1440 return false; 1441 1442 Size += Context.getTypeSize(FD->getType()); 1443 } 1444 return true; 1445 } 1446 1447 static bool addBaseAndFieldSizes(ASTContext &Context, const CXXRecordDecl *RD, 1448 uint64_t &Size) { 1449 // Don't do this if there are any non-empty bases. 1450 for (const CXXBaseSpecifier &Base : RD->bases()) { 1451 if (!addBaseAndFieldSizes(Context, Base.getType()->getAsCXXRecordDecl(), 1452 Size)) 1453 return false; 1454 } 1455 if (!addFieldSizes(Context, RD, Size)) 1456 return false; 1457 return true; 1458 } 1459 1460 /// Test whether an argument type which is to be passed indirectly (on the 1461 /// stack) would have the equivalent layout if it was expanded into separate 1462 /// arguments. If so, we prefer to do the latter to avoid inhibiting 1463 /// optimizations. 1464 bool X86_32ABIInfo::canExpandIndirectArgument(QualType Ty) const { 1465 // We can only expand structure types. 1466 const RecordType *RT = Ty->getAs<RecordType>(); 1467 if (!RT) 1468 return false; 1469 const RecordDecl *RD = RT->getDecl(); 1470 uint64_t Size = 0; 1471 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 1472 if (!IsWin32StructABI) { 1473 // On non-Windows, we have to conservatively match our old bitcode 1474 // prototypes in order to be ABI-compatible at the bitcode level. 1475 if (!CXXRD->isCLike()) 1476 return false; 1477 } else { 1478 // Don't do this for dynamic classes. 1479 if (CXXRD->isDynamicClass()) 1480 return false; 1481 } 1482 if (!addBaseAndFieldSizes(getContext(), CXXRD, Size)) 1483 return false; 1484 } else { 1485 if (!addFieldSizes(getContext(), RD, Size)) 1486 return false; 1487 } 1488 1489 // We can do this if there was no alignment padding. 1490 return Size == getContext().getTypeSize(Ty); 1491 } 1492 1493 ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(QualType RetTy, CCState &State) const { 1494 // If the return value is indirect, then the hidden argument is consuming one 1495 // integer register. 1496 if (State.FreeRegs) { 1497 --State.FreeRegs; 1498 if (!IsMCUABI) 1499 return getNaturalAlignIndirectInReg(RetTy); 1500 } 1501 return getNaturalAlignIndirect(RetTy, /*ByVal=*/false); 1502 } 1503 1504 ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy, 1505 CCState &State) const { 1506 if (RetTy->isVoidType()) 1507 return ABIArgInfo::getIgnore(); 1508 1509 const Type *Base = nullptr; 1510 uint64_t NumElts = 0; 1511 if ((State.CC == llvm::CallingConv::X86_VectorCall || 1512 State.CC == llvm::CallingConv::X86_RegCall) && 1513 isHomogeneousAggregate(RetTy, Base, NumElts)) { 1514 // The LLVM struct type for such an aggregate should lower properly. 1515 return ABIArgInfo::getDirect(); 1516 } 1517 1518 if (const VectorType *VT = RetTy->getAs<VectorType>()) { 1519 // On Darwin, some vectors are returned in registers. 1520 if (IsDarwinVectorABI) { 1521 uint64_t Size = getContext().getTypeSize(RetTy); 1522 1523 // 128-bit vectors are a special case; they are returned in 1524 // registers and we need to make sure to pick a type the LLVM 1525 // backend will like. 1526 if (Size == 128) 1527 return ABIArgInfo::getDirect(llvm::FixedVectorType::get( 1528 llvm::Type::getInt64Ty(getVMContext()), 2)); 1529 1530 // Always return in register if it fits in a general purpose 1531 // register, or if it is 64 bits and has a single element. 1532 if ((Size == 8 || Size == 16 || Size == 32) || 1533 (Size == 64 && VT->getNumElements() == 1)) 1534 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 1535 Size)); 1536 1537 return getIndirectReturnResult(RetTy, State); 1538 } 1539 1540 return ABIArgInfo::getDirect(); 1541 } 1542 1543 if (isAggregateTypeForABI(RetTy)) { 1544 if (const RecordType *RT = RetTy->getAs<RecordType>()) { 1545 // Structures with flexible arrays are always indirect. 1546 if (RT->getDecl()->hasFlexibleArrayMember()) 1547 return getIndirectReturnResult(RetTy, State); 1548 } 1549 1550 // If specified, structs and unions are always indirect. 1551 if (!IsRetSmallStructInRegABI && !RetTy->isAnyComplexType()) 1552 return getIndirectReturnResult(RetTy, State); 1553 1554 // Ignore empty structs/unions. 1555 if (isEmptyRecord(getContext(), RetTy, true)) 1556 return ABIArgInfo::getIgnore(); 1557 1558 // Return complex of _Float16 as <2 x half> so the backend will use xmm0. 1559 if (const ComplexType *CT = RetTy->getAs<ComplexType>()) { 1560 QualType ET = getContext().getCanonicalType(CT->getElementType()); 1561 if (ET->isFloat16Type()) 1562 return ABIArgInfo::getDirect(llvm::FixedVectorType::get( 1563 llvm::Type::getHalfTy(getVMContext()), 2)); 1564 } 1565 1566 // Small structures which are register sized are generally returned 1567 // in a register. 1568 if (shouldReturnTypeInRegister(RetTy, getContext())) { 1569 uint64_t Size = getContext().getTypeSize(RetTy); 1570 1571 // As a special-case, if the struct is a "single-element" struct, and 1572 // the field is of type "float" or "double", return it in a 1573 // floating-point register. (MSVC does not apply this special case.) 1574 // We apply a similar transformation for pointer types to improve the 1575 // quality of the generated IR. 1576 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext())) 1577 if ((!IsWin32StructABI && SeltTy->isRealFloatingType()) 1578 || SeltTy->hasPointerRepresentation()) 1579 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0))); 1580 1581 // FIXME: We should be able to narrow this integer in cases with dead 1582 // padding. 1583 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size)); 1584 } 1585 1586 return getIndirectReturnResult(RetTy, State); 1587 } 1588 1589 // Treat an enum type as its underlying type. 1590 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 1591 RetTy = EnumTy->getDecl()->getIntegerType(); 1592 1593 if (const auto *EIT = RetTy->getAs<ExtIntType>()) 1594 if (EIT->getNumBits() > 64) 1595 return getIndirectReturnResult(RetTy, State); 1596 1597 return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy) 1598 : ABIArgInfo::getDirect()); 1599 } 1600 1601 static bool isSIMDVectorType(ASTContext &Context, QualType Ty) { 1602 return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128; 1603 } 1604 1605 static bool isRecordWithSIMDVectorType(ASTContext &Context, QualType Ty) { 1606 const RecordType *RT = Ty->getAs<RecordType>(); 1607 if (!RT) 1608 return 0; 1609 const RecordDecl *RD = RT->getDecl(); 1610 1611 // If this is a C++ record, check the bases first. 1612 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 1613 for (const auto &I : CXXRD->bases()) 1614 if (!isRecordWithSIMDVectorType(Context, I.getType())) 1615 return false; 1616 1617 for (const auto *i : RD->fields()) { 1618 QualType FT = i->getType(); 1619 1620 if (isSIMDVectorType(Context, FT)) 1621 return true; 1622 1623 if (isRecordWithSIMDVectorType(Context, FT)) 1624 return true; 1625 } 1626 1627 return false; 1628 } 1629 1630 unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty, 1631 unsigned Align) const { 1632 // Otherwise, if the alignment is less than or equal to the minimum ABI 1633 // alignment, just use the default; the backend will handle this. 1634 if (Align <= MinABIStackAlignInBytes) 1635 return 0; // Use default alignment. 1636 1637 if (IsLinuxABI) { 1638 // Exclude other System V OS (e.g Darwin, PS4 and FreeBSD) since we don't 1639 // want to spend any effort dealing with the ramifications of ABI breaks. 1640 // 1641 // If the vector type is __m128/__m256/__m512, return the default alignment. 1642 if (Ty->isVectorType() && (Align == 16 || Align == 32 || Align == 64)) 1643 return Align; 1644 } 1645 // On non-Darwin, the stack type alignment is always 4. 1646 if (!IsDarwinVectorABI) { 1647 // Set explicit alignment, since we may need to realign the top. 1648 return MinABIStackAlignInBytes; 1649 } 1650 1651 // Otherwise, if the type contains an SSE vector type, the alignment is 16. 1652 if (Align >= 16 && (isSIMDVectorType(getContext(), Ty) || 1653 isRecordWithSIMDVectorType(getContext(), Ty))) 1654 return 16; 1655 1656 return MinABIStackAlignInBytes; 1657 } 1658 1659 ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal, 1660 CCState &State) const { 1661 if (!ByVal) { 1662 if (State.FreeRegs) { 1663 --State.FreeRegs; // Non-byval indirects just use one pointer. 1664 if (!IsMCUABI) 1665 return getNaturalAlignIndirectInReg(Ty); 1666 } 1667 return getNaturalAlignIndirect(Ty, false); 1668 } 1669 1670 // Compute the byval alignment. 1671 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8; 1672 unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign); 1673 if (StackAlign == 0) 1674 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true); 1675 1676 // If the stack alignment is less than the type alignment, realign the 1677 // argument. 1678 bool Realign = TypeAlign > StackAlign; 1679 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(StackAlign), 1680 /*ByVal=*/true, Realign); 1681 } 1682 1683 X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const { 1684 const Type *T = isSingleElementStruct(Ty, getContext()); 1685 if (!T) 1686 T = Ty.getTypePtr(); 1687 1688 if (const BuiltinType *BT = T->getAs<BuiltinType>()) { 1689 BuiltinType::Kind K = BT->getKind(); 1690 if (K == BuiltinType::Float || K == BuiltinType::Double) 1691 return Float; 1692 } 1693 return Integer; 1694 } 1695 1696 bool X86_32ABIInfo::updateFreeRegs(QualType Ty, CCState &State) const { 1697 if (!IsSoftFloatABI) { 1698 Class C = classify(Ty); 1699 if (C == Float) 1700 return false; 1701 } 1702 1703 unsigned Size = getContext().getTypeSize(Ty); 1704 unsigned SizeInRegs = (Size + 31) / 32; 1705 1706 if (SizeInRegs == 0) 1707 return false; 1708 1709 if (!IsMCUABI) { 1710 if (SizeInRegs > State.FreeRegs) { 1711 State.FreeRegs = 0; 1712 return false; 1713 } 1714 } else { 1715 // The MCU psABI allows passing parameters in-reg even if there are 1716 // earlier parameters that are passed on the stack. Also, 1717 // it does not allow passing >8-byte structs in-register, 1718 // even if there are 3 free registers available. 1719 if (SizeInRegs > State.FreeRegs || SizeInRegs > 2) 1720 return false; 1721 } 1722 1723 State.FreeRegs -= SizeInRegs; 1724 return true; 1725 } 1726 1727 bool X86_32ABIInfo::shouldAggregateUseDirect(QualType Ty, CCState &State, 1728 bool &InReg, 1729 bool &NeedsPadding) const { 1730 // On Windows, aggregates other than HFAs are never passed in registers, and 1731 // they do not consume register slots. Homogenous floating-point aggregates 1732 // (HFAs) have already been dealt with at this point. 1733 if (IsWin32StructABI && isAggregateTypeForABI(Ty)) 1734 return false; 1735 1736 NeedsPadding = false; 1737 InReg = !IsMCUABI; 1738 1739 if (!updateFreeRegs(Ty, State)) 1740 return false; 1741 1742 if (IsMCUABI) 1743 return true; 1744 1745 if (State.CC == llvm::CallingConv::X86_FastCall || 1746 State.CC == llvm::CallingConv::X86_VectorCall || 1747 State.CC == llvm::CallingConv::X86_RegCall) { 1748 if (getContext().getTypeSize(Ty) <= 32 && State.FreeRegs) 1749 NeedsPadding = true; 1750 1751 return false; 1752 } 1753 1754 return true; 1755 } 1756 1757 bool X86_32ABIInfo::shouldPrimitiveUseInReg(QualType Ty, CCState &State) const { 1758 if (!updateFreeRegs(Ty, State)) 1759 return false; 1760 1761 if (IsMCUABI) 1762 return false; 1763 1764 if (State.CC == llvm::CallingConv::X86_FastCall || 1765 State.CC == llvm::CallingConv::X86_VectorCall || 1766 State.CC == llvm::CallingConv::X86_RegCall) { 1767 if (getContext().getTypeSize(Ty) > 32) 1768 return false; 1769 1770 return (Ty->isIntegralOrEnumerationType() || Ty->isPointerType() || 1771 Ty->isReferenceType()); 1772 } 1773 1774 return true; 1775 } 1776 1777 void X86_32ABIInfo::runVectorCallFirstPass(CGFunctionInfo &FI, CCState &State) const { 1778 // Vectorcall x86 works subtly different than in x64, so the format is 1779 // a bit different than the x64 version. First, all vector types (not HVAs) 1780 // are assigned, with the first 6 ending up in the [XYZ]MM0-5 registers. 1781 // This differs from the x64 implementation, where the first 6 by INDEX get 1782 // registers. 1783 // In the second pass over the arguments, HVAs are passed in the remaining 1784 // vector registers if possible, or indirectly by address. The address will be 1785 // passed in ECX/EDX if available. Any other arguments are passed according to 1786 // the usual fastcall rules. 1787 MutableArrayRef<CGFunctionInfoArgInfo> Args = FI.arguments(); 1788 for (int I = 0, E = Args.size(); I < E; ++I) { 1789 const Type *Base = nullptr; 1790 uint64_t NumElts = 0; 1791 const QualType &Ty = Args[I].type; 1792 if ((Ty->isVectorType() || Ty->isBuiltinType()) && 1793 isHomogeneousAggregate(Ty, Base, NumElts)) { 1794 if (State.FreeSSERegs >= NumElts) { 1795 State.FreeSSERegs -= NumElts; 1796 Args[I].info = ABIArgInfo::getDirectInReg(); 1797 State.IsPreassigned.set(I); 1798 } 1799 } 1800 } 1801 } 1802 1803 ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty, 1804 CCState &State) const { 1805 // FIXME: Set alignment on indirect arguments. 1806 bool IsFastCall = State.CC == llvm::CallingConv::X86_FastCall; 1807 bool IsRegCall = State.CC == llvm::CallingConv::X86_RegCall; 1808 bool IsVectorCall = State.CC == llvm::CallingConv::X86_VectorCall; 1809 1810 Ty = useFirstFieldIfTransparentUnion(Ty); 1811 TypeInfo TI = getContext().getTypeInfo(Ty); 1812 1813 // Check with the C++ ABI first. 1814 const RecordType *RT = Ty->getAs<RecordType>(); 1815 if (RT) { 1816 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()); 1817 if (RAA == CGCXXABI::RAA_Indirect) { 1818 return getIndirectResult(Ty, false, State); 1819 } else if (RAA == CGCXXABI::RAA_DirectInMemory) { 1820 // The field index doesn't matter, we'll fix it up later. 1821 return ABIArgInfo::getInAlloca(/*FieldIndex=*/0); 1822 } 1823 } 1824 1825 // Regcall uses the concept of a homogenous vector aggregate, similar 1826 // to other targets. 1827 const Type *Base = nullptr; 1828 uint64_t NumElts = 0; 1829 if ((IsRegCall || IsVectorCall) && 1830 isHomogeneousAggregate(Ty, Base, NumElts)) { 1831 if (State.FreeSSERegs >= NumElts) { 1832 State.FreeSSERegs -= NumElts; 1833 1834 // Vectorcall passes HVAs directly and does not flatten them, but regcall 1835 // does. 1836 if (IsVectorCall) 1837 return getDirectX86Hva(); 1838 1839 if (Ty->isBuiltinType() || Ty->isVectorType()) 1840 return ABIArgInfo::getDirect(); 1841 return ABIArgInfo::getExpand(); 1842 } 1843 return getIndirectResult(Ty, /*ByVal=*/false, State); 1844 } 1845 1846 if (isAggregateTypeForABI(Ty)) { 1847 // Structures with flexible arrays are always indirect. 1848 // FIXME: This should not be byval! 1849 if (RT && RT->getDecl()->hasFlexibleArrayMember()) 1850 return getIndirectResult(Ty, true, State); 1851 1852 // Ignore empty structs/unions on non-Windows. 1853 if (!IsWin32StructABI && isEmptyRecord(getContext(), Ty, true)) 1854 return ABIArgInfo::getIgnore(); 1855 1856 llvm::LLVMContext &LLVMContext = getVMContext(); 1857 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext); 1858 bool NeedsPadding = false; 1859 bool InReg; 1860 if (shouldAggregateUseDirect(Ty, State, InReg, NeedsPadding)) { 1861 unsigned SizeInRegs = (TI.Width + 31) / 32; 1862 SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32); 1863 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements); 1864 if (InReg) 1865 return ABIArgInfo::getDirectInReg(Result); 1866 else 1867 return ABIArgInfo::getDirect(Result); 1868 } 1869 llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : nullptr; 1870 1871 // Pass over-aligned aggregates on Windows indirectly. This behavior was 1872 // added in MSVC 2015. 1873 if (IsWin32StructABI && TI.isAlignRequired() && TI.Align > 32) 1874 return getIndirectResult(Ty, /*ByVal=*/false, State); 1875 1876 // Expand small (<= 128-bit) record types when we know that the stack layout 1877 // of those arguments will match the struct. This is important because the 1878 // LLVM backend isn't smart enough to remove byval, which inhibits many 1879 // optimizations. 1880 // Don't do this for the MCU if there are still free integer registers 1881 // (see X86_64 ABI for full explanation). 1882 if (TI.Width <= 4 * 32 && (!IsMCUABI || State.FreeRegs == 0) && 1883 canExpandIndirectArgument(Ty)) 1884 return ABIArgInfo::getExpandWithPadding( 1885 IsFastCall || IsVectorCall || IsRegCall, PaddingType); 1886 1887 return getIndirectResult(Ty, true, State); 1888 } 1889 1890 if (const VectorType *VT = Ty->getAs<VectorType>()) { 1891 // On Windows, vectors are passed directly if registers are available, or 1892 // indirectly if not. This avoids the need to align argument memory. Pass 1893 // user-defined vector types larger than 512 bits indirectly for simplicity. 1894 if (IsWin32StructABI) { 1895 if (TI.Width <= 512 && State.FreeSSERegs > 0) { 1896 --State.FreeSSERegs; 1897 return ABIArgInfo::getDirectInReg(); 1898 } 1899 return getIndirectResult(Ty, /*ByVal=*/false, State); 1900 } 1901 1902 // On Darwin, some vectors are passed in memory, we handle this by passing 1903 // it as an i8/i16/i32/i64. 1904 if (IsDarwinVectorABI) { 1905 if ((TI.Width == 8 || TI.Width == 16 || TI.Width == 32) || 1906 (TI.Width == 64 && VT->getNumElements() == 1)) 1907 return ABIArgInfo::getDirect( 1908 llvm::IntegerType::get(getVMContext(), TI.Width)); 1909 } 1910 1911 if (IsX86_MMXType(CGT.ConvertType(Ty))) 1912 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64)); 1913 1914 return ABIArgInfo::getDirect(); 1915 } 1916 1917 1918 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 1919 Ty = EnumTy->getDecl()->getIntegerType(); 1920 1921 bool InReg = shouldPrimitiveUseInReg(Ty, State); 1922 1923 if (isPromotableIntegerTypeForABI(Ty)) { 1924 if (InReg) 1925 return ABIArgInfo::getExtendInReg(Ty); 1926 return ABIArgInfo::getExtend(Ty); 1927 } 1928 1929 if (const auto * EIT = Ty->getAs<ExtIntType>()) { 1930 if (EIT->getNumBits() <= 64) { 1931 if (InReg) 1932 return ABIArgInfo::getDirectInReg(); 1933 return ABIArgInfo::getDirect(); 1934 } 1935 return getIndirectResult(Ty, /*ByVal=*/false, State); 1936 } 1937 1938 if (InReg) 1939 return ABIArgInfo::getDirectInReg(); 1940 return ABIArgInfo::getDirect(); 1941 } 1942 1943 void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const { 1944 CCState State(FI); 1945 if (IsMCUABI) 1946 State.FreeRegs = 3; 1947 else if (State.CC == llvm::CallingConv::X86_FastCall) { 1948 State.FreeRegs = 2; 1949 State.FreeSSERegs = 3; 1950 } else if (State.CC == llvm::CallingConv::X86_VectorCall) { 1951 State.FreeRegs = 2; 1952 State.FreeSSERegs = 6; 1953 } else if (FI.getHasRegParm()) 1954 State.FreeRegs = FI.getRegParm(); 1955 else if (State.CC == llvm::CallingConv::X86_RegCall) { 1956 State.FreeRegs = 5; 1957 State.FreeSSERegs = 8; 1958 } else if (IsWin32StructABI) { 1959 // Since MSVC 2015, the first three SSE vectors have been passed in 1960 // registers. The rest are passed indirectly. 1961 State.FreeRegs = DefaultNumRegisterParameters; 1962 State.FreeSSERegs = 3; 1963 } else 1964 State.FreeRegs = DefaultNumRegisterParameters; 1965 1966 if (!::classifyReturnType(getCXXABI(), FI, *this)) { 1967 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), State); 1968 } else if (FI.getReturnInfo().isIndirect()) { 1969 // The C++ ABI is not aware of register usage, so we have to check if the 1970 // return value was sret and put it in a register ourselves if appropriate. 1971 if (State.FreeRegs) { 1972 --State.FreeRegs; // The sret parameter consumes a register. 1973 if (!IsMCUABI) 1974 FI.getReturnInfo().setInReg(true); 1975 } 1976 } 1977 1978 // The chain argument effectively gives us another free register. 1979 if (FI.isChainCall()) 1980 ++State.FreeRegs; 1981 1982 // For vectorcall, do a first pass over the arguments, assigning FP and vector 1983 // arguments to XMM registers as available. 1984 if (State.CC == llvm::CallingConv::X86_VectorCall) 1985 runVectorCallFirstPass(FI, State); 1986 1987 bool UsedInAlloca = false; 1988 MutableArrayRef<CGFunctionInfoArgInfo> Args = FI.arguments(); 1989 for (int I = 0, E = Args.size(); I < E; ++I) { 1990 // Skip arguments that have already been assigned. 1991 if (State.IsPreassigned.test(I)) 1992 continue; 1993 1994 Args[I].info = classifyArgumentType(Args[I].type, State); 1995 UsedInAlloca |= (Args[I].info.getKind() == ABIArgInfo::InAlloca); 1996 } 1997 1998 // If we needed to use inalloca for any argument, do a second pass and rewrite 1999 // all the memory arguments to use inalloca. 2000 if (UsedInAlloca) 2001 rewriteWithInAlloca(FI); 2002 } 2003 2004 void 2005 X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields, 2006 CharUnits &StackOffset, ABIArgInfo &Info, 2007 QualType Type) const { 2008 // Arguments are always 4-byte-aligned. 2009 CharUnits WordSize = CharUnits::fromQuantity(4); 2010 assert(StackOffset.isMultipleOf(WordSize) && "unaligned inalloca struct"); 2011 2012 // sret pointers and indirect things will require an extra pointer 2013 // indirection, unless they are byval. Most things are byval, and will not 2014 // require this indirection. 2015 bool IsIndirect = false; 2016 if (Info.isIndirect() && !Info.getIndirectByVal()) 2017 IsIndirect = true; 2018 Info = ABIArgInfo::getInAlloca(FrameFields.size(), IsIndirect); 2019 llvm::Type *LLTy = CGT.ConvertTypeForMem(Type); 2020 if (IsIndirect) 2021 LLTy = LLTy->getPointerTo(0); 2022 FrameFields.push_back(LLTy); 2023 StackOffset += IsIndirect ? WordSize : getContext().getTypeSizeInChars(Type); 2024 2025 // Insert padding bytes to respect alignment. 2026 CharUnits FieldEnd = StackOffset; 2027 StackOffset = FieldEnd.alignTo(WordSize); 2028 if (StackOffset != FieldEnd) { 2029 CharUnits NumBytes = StackOffset - FieldEnd; 2030 llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext()); 2031 Ty = llvm::ArrayType::get(Ty, NumBytes.getQuantity()); 2032 FrameFields.push_back(Ty); 2033 } 2034 } 2035 2036 static bool isArgInAlloca(const ABIArgInfo &Info) { 2037 // Leave ignored and inreg arguments alone. 2038 switch (Info.getKind()) { 2039 case ABIArgInfo::InAlloca: 2040 return true; 2041 case ABIArgInfo::Ignore: 2042 case ABIArgInfo::IndirectAliased: 2043 return false; 2044 case ABIArgInfo::Indirect: 2045 case ABIArgInfo::Direct: 2046 case ABIArgInfo::Extend: 2047 return !Info.getInReg(); 2048 case ABIArgInfo::Expand: 2049 case ABIArgInfo::CoerceAndExpand: 2050 // These are aggregate types which are never passed in registers when 2051 // inalloca is involved. 2052 return true; 2053 } 2054 llvm_unreachable("invalid enum"); 2055 } 2056 2057 void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const { 2058 assert(IsWin32StructABI && "inalloca only supported on win32"); 2059 2060 // Build a packed struct type for all of the arguments in memory. 2061 SmallVector<llvm::Type *, 6> FrameFields; 2062 2063 // The stack alignment is always 4. 2064 CharUnits StackAlign = CharUnits::fromQuantity(4); 2065 2066 CharUnits StackOffset; 2067 CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end(); 2068 2069 // Put 'this' into the struct before 'sret', if necessary. 2070 bool IsThisCall = 2071 FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall; 2072 ABIArgInfo &Ret = FI.getReturnInfo(); 2073 if (Ret.isIndirect() && Ret.isSRetAfterThis() && !IsThisCall && 2074 isArgInAlloca(I->info)) { 2075 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type); 2076 ++I; 2077 } 2078 2079 // Put the sret parameter into the inalloca struct if it's in memory. 2080 if (Ret.isIndirect() && !Ret.getInReg()) { 2081 addFieldToArgStruct(FrameFields, StackOffset, Ret, FI.getReturnType()); 2082 // On Windows, the hidden sret parameter is always returned in eax. 2083 Ret.setInAllocaSRet(IsWin32StructABI); 2084 } 2085 2086 // Skip the 'this' parameter in ecx. 2087 if (IsThisCall) 2088 ++I; 2089 2090 // Put arguments passed in memory into the struct. 2091 for (; I != E; ++I) { 2092 if (isArgInAlloca(I->info)) 2093 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type); 2094 } 2095 2096 FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields, 2097 /*isPacked=*/true), 2098 StackAlign); 2099 } 2100 2101 Address X86_32ABIInfo::EmitVAArg(CodeGenFunction &CGF, 2102 Address VAListAddr, QualType Ty) const { 2103 2104 auto TypeInfo = getContext().getTypeInfoInChars(Ty); 2105 2106 // x86-32 changes the alignment of certain arguments on the stack. 2107 // 2108 // Just messing with TypeInfo like this works because we never pass 2109 // anything indirectly. 2110 TypeInfo.Align = CharUnits::fromQuantity( 2111 getTypeStackAlignInBytes(Ty, TypeInfo.Align.getQuantity())); 2112 2113 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false, 2114 TypeInfo, CharUnits::fromQuantity(4), 2115 /*AllowHigherAlign*/ true); 2116 } 2117 2118 bool X86_32TargetCodeGenInfo::isStructReturnInRegABI( 2119 const llvm::Triple &Triple, const CodeGenOptions &Opts) { 2120 assert(Triple.getArch() == llvm::Triple::x86); 2121 2122 switch (Opts.getStructReturnConvention()) { 2123 case CodeGenOptions::SRCK_Default: 2124 break; 2125 case CodeGenOptions::SRCK_OnStack: // -fpcc-struct-return 2126 return false; 2127 case CodeGenOptions::SRCK_InRegs: // -freg-struct-return 2128 return true; 2129 } 2130 2131 if (Triple.isOSDarwin() || Triple.isOSIAMCU()) 2132 return true; 2133 2134 switch (Triple.getOS()) { 2135 case llvm::Triple::DragonFly: 2136 case llvm::Triple::FreeBSD: 2137 case llvm::Triple::OpenBSD: 2138 case llvm::Triple::Win32: 2139 return true; 2140 default: 2141 return false; 2142 } 2143 } 2144 2145 static void addX86InterruptAttrs(const FunctionDecl *FD, llvm::GlobalValue *GV, 2146 CodeGen::CodeGenModule &CGM) { 2147 if (!FD->hasAttr<AnyX86InterruptAttr>()) 2148 return; 2149 2150 llvm::Function *Fn = cast<llvm::Function>(GV); 2151 Fn->setCallingConv(llvm::CallingConv::X86_INTR); 2152 if (FD->getNumParams() == 0) 2153 return; 2154 2155 auto PtrTy = cast<PointerType>(FD->getParamDecl(0)->getType()); 2156 llvm::Type *ByValTy = CGM.getTypes().ConvertType(PtrTy->getPointeeType()); 2157 llvm::Attribute NewAttr = llvm::Attribute::getWithByValType( 2158 Fn->getContext(), ByValTy); 2159 Fn->addParamAttr(0, NewAttr); 2160 } 2161 2162 void X86_32TargetCodeGenInfo::setTargetAttributes( 2163 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const { 2164 if (GV->isDeclaration()) 2165 return; 2166 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) { 2167 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) { 2168 llvm::Function *Fn = cast<llvm::Function>(GV); 2169 Fn->addFnAttr("stackrealign"); 2170 } 2171 2172 addX86InterruptAttrs(FD, GV, CGM); 2173 } 2174 } 2175 2176 bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable( 2177 CodeGen::CodeGenFunction &CGF, 2178 llvm::Value *Address) const { 2179 CodeGen::CGBuilderTy &Builder = CGF.Builder; 2180 2181 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4); 2182 2183 // 0-7 are the eight integer registers; the order is different 2184 // on Darwin (for EH), but the range is the same. 2185 // 8 is %eip. 2186 AssignToArrayRange(Builder, Address, Four8, 0, 8); 2187 2188 if (CGF.CGM.getTarget().getTriple().isOSDarwin()) { 2189 // 12-16 are st(0..4). Not sure why we stop at 4. 2190 // These have size 16, which is sizeof(long double) on 2191 // platforms with 8-byte alignment for that type. 2192 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16); 2193 AssignToArrayRange(Builder, Address, Sixteen8, 12, 16); 2194 2195 } else { 2196 // 9 is %eflags, which doesn't get a size on Darwin for some 2197 // reason. 2198 Builder.CreateAlignedStore( 2199 Four8, Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, Address, 9), 2200 CharUnits::One()); 2201 2202 // 11-16 are st(0..5). Not sure why we stop at 5. 2203 // These have size 12, which is sizeof(long double) on 2204 // platforms with 4-byte alignment for that type. 2205 llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12); 2206 AssignToArrayRange(Builder, Address, Twelve8, 11, 16); 2207 } 2208 2209 return false; 2210 } 2211 2212 //===----------------------------------------------------------------------===// 2213 // X86-64 ABI Implementation 2214 //===----------------------------------------------------------------------===// 2215 2216 2217 namespace { 2218 /// The AVX ABI level for X86 targets. 2219 enum class X86AVXABILevel { 2220 None, 2221 AVX, 2222 AVX512 2223 }; 2224 2225 /// \p returns the size in bits of the largest (native) vector for \p AVXLevel. 2226 static unsigned getNativeVectorSizeForAVXABI(X86AVXABILevel AVXLevel) { 2227 switch (AVXLevel) { 2228 case X86AVXABILevel::AVX512: 2229 return 512; 2230 case X86AVXABILevel::AVX: 2231 return 256; 2232 case X86AVXABILevel::None: 2233 return 128; 2234 } 2235 llvm_unreachable("Unknown AVXLevel"); 2236 } 2237 2238 /// X86_64ABIInfo - The X86_64 ABI information. 2239 class X86_64ABIInfo : public SwiftABIInfo { 2240 enum Class { 2241 Integer = 0, 2242 SSE, 2243 SSEUp, 2244 X87, 2245 X87Up, 2246 ComplexX87, 2247 NoClass, 2248 Memory 2249 }; 2250 2251 /// merge - Implement the X86_64 ABI merging algorithm. 2252 /// 2253 /// Merge an accumulating classification \arg Accum with a field 2254 /// classification \arg Field. 2255 /// 2256 /// \param Accum - The accumulating classification. This should 2257 /// always be either NoClass or the result of a previous merge 2258 /// call. In addition, this should never be Memory (the caller 2259 /// should just return Memory for the aggregate). 2260 static Class merge(Class Accum, Class Field); 2261 2262 /// postMerge - Implement the X86_64 ABI post merging algorithm. 2263 /// 2264 /// Post merger cleanup, reduces a malformed Hi and Lo pair to 2265 /// final MEMORY or SSE classes when necessary. 2266 /// 2267 /// \param AggregateSize - The size of the current aggregate in 2268 /// the classification process. 2269 /// 2270 /// \param Lo - The classification for the parts of the type 2271 /// residing in the low word of the containing object. 2272 /// 2273 /// \param Hi - The classification for the parts of the type 2274 /// residing in the higher words of the containing object. 2275 /// 2276 void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const; 2277 2278 /// classify - Determine the x86_64 register classes in which the 2279 /// given type T should be passed. 2280 /// 2281 /// \param Lo - The classification for the parts of the type 2282 /// residing in the low word of the containing object. 2283 /// 2284 /// \param Hi - The classification for the parts of the type 2285 /// residing in the high word of the containing object. 2286 /// 2287 /// \param OffsetBase - The bit offset of this type in the 2288 /// containing object. Some parameters are classified different 2289 /// depending on whether they straddle an eightbyte boundary. 2290 /// 2291 /// \param isNamedArg - Whether the argument in question is a "named" 2292 /// argument, as used in AMD64-ABI 3.5.7. 2293 /// 2294 /// If a word is unused its result will be NoClass; if a type should 2295 /// be passed in Memory then at least the classification of \arg Lo 2296 /// will be Memory. 2297 /// 2298 /// The \arg Lo class will be NoClass iff the argument is ignored. 2299 /// 2300 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will 2301 /// also be ComplexX87. 2302 void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi, 2303 bool isNamedArg) const; 2304 2305 llvm::Type *GetByteVectorType(QualType Ty) const; 2306 llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType, 2307 unsigned IROffset, QualType SourceTy, 2308 unsigned SourceOffset) const; 2309 llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType, 2310 unsigned IROffset, QualType SourceTy, 2311 unsigned SourceOffset) const; 2312 2313 /// getIndirectResult - Give a source type \arg Ty, return a suitable result 2314 /// such that the argument will be returned in memory. 2315 ABIArgInfo getIndirectReturnResult(QualType Ty) const; 2316 2317 /// getIndirectResult - Give a source type \arg Ty, return a suitable result 2318 /// such that the argument will be passed in memory. 2319 /// 2320 /// \param freeIntRegs - The number of free integer registers remaining 2321 /// available. 2322 ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const; 2323 2324 ABIArgInfo classifyReturnType(QualType RetTy) const; 2325 2326 ABIArgInfo classifyArgumentType(QualType Ty, unsigned freeIntRegs, 2327 unsigned &neededInt, unsigned &neededSSE, 2328 bool isNamedArg) const; 2329 2330 ABIArgInfo classifyRegCallStructType(QualType Ty, unsigned &NeededInt, 2331 unsigned &NeededSSE) const; 2332 2333 ABIArgInfo classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt, 2334 unsigned &NeededSSE) const; 2335 2336 bool IsIllegalVectorType(QualType Ty) const; 2337 2338 /// The 0.98 ABI revision clarified a lot of ambiguities, 2339 /// unfortunately in ways that were not always consistent with 2340 /// certain previous compilers. In particular, platforms which 2341 /// required strict binary compatibility with older versions of GCC 2342 /// may need to exempt themselves. 2343 bool honorsRevision0_98() const { 2344 return !getTarget().getTriple().isOSDarwin(); 2345 } 2346 2347 /// GCC classifies <1 x long long> as SSE but some platform ABIs choose to 2348 /// classify it as INTEGER (for compatibility with older clang compilers). 2349 bool classifyIntegerMMXAsSSE() const { 2350 // Clang <= 3.8 did not do this. 2351 if (getContext().getLangOpts().getClangABICompat() <= 2352 LangOptions::ClangABI::Ver3_8) 2353 return false; 2354 2355 const llvm::Triple &Triple = getTarget().getTriple(); 2356 if (Triple.isOSDarwin() || Triple.getOS() == llvm::Triple::PS4) 2357 return false; 2358 if (Triple.isOSFreeBSD() && Triple.getOSMajorVersion() >= 10) 2359 return false; 2360 return true; 2361 } 2362 2363 // GCC classifies vectors of __int128 as memory. 2364 bool passInt128VectorsInMem() const { 2365 // Clang <= 9.0 did not do this. 2366 if (getContext().getLangOpts().getClangABICompat() <= 2367 LangOptions::ClangABI::Ver9) 2368 return false; 2369 2370 const llvm::Triple &T = getTarget().getTriple(); 2371 return T.isOSLinux() || T.isOSNetBSD(); 2372 } 2373 2374 X86AVXABILevel AVXLevel; 2375 // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on 2376 // 64-bit hardware. 2377 bool Has64BitPointers; 2378 2379 public: 2380 X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) : 2381 SwiftABIInfo(CGT), AVXLevel(AVXLevel), 2382 Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) { 2383 } 2384 2385 bool isPassedUsingAVXType(QualType type) const { 2386 unsigned neededInt, neededSSE; 2387 // The freeIntRegs argument doesn't matter here. 2388 ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE, 2389 /*isNamedArg*/true); 2390 if (info.isDirect()) { 2391 llvm::Type *ty = info.getCoerceToType(); 2392 if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty)) 2393 return vectorTy->getPrimitiveSizeInBits().getFixedSize() > 128; 2394 } 2395 return false; 2396 } 2397 2398 void computeInfo(CGFunctionInfo &FI) const override; 2399 2400 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 2401 QualType Ty) const override; 2402 Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr, 2403 QualType Ty) const override; 2404 2405 bool has64BitPointers() const { 2406 return Has64BitPointers; 2407 } 2408 2409 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars, 2410 bool asReturnValue) const override { 2411 return occupiesMoreThan(CGT, scalars, /*total*/ 4); 2412 } 2413 bool isSwiftErrorInRegister() const override { 2414 return true; 2415 } 2416 }; 2417 2418 /// WinX86_64ABIInfo - The Windows X86_64 ABI information. 2419 class WinX86_64ABIInfo : public SwiftABIInfo { 2420 public: 2421 WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) 2422 : SwiftABIInfo(CGT), AVXLevel(AVXLevel), 2423 IsMingw64(getTarget().getTriple().isWindowsGNUEnvironment()) {} 2424 2425 void computeInfo(CGFunctionInfo &FI) const override; 2426 2427 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 2428 QualType Ty) const override; 2429 2430 bool isHomogeneousAggregateBaseType(QualType Ty) const override { 2431 // FIXME: Assumes vectorcall is in use. 2432 return isX86VectorTypeForVectorCall(getContext(), Ty); 2433 } 2434 2435 bool isHomogeneousAggregateSmallEnough(const Type *Ty, 2436 uint64_t NumMembers) const override { 2437 // FIXME: Assumes vectorcall is in use. 2438 return isX86VectorCallAggregateSmallEnough(NumMembers); 2439 } 2440 2441 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type *> scalars, 2442 bool asReturnValue) const override { 2443 return occupiesMoreThan(CGT, scalars, /*total*/ 4); 2444 } 2445 2446 bool isSwiftErrorInRegister() const override { 2447 return true; 2448 } 2449 2450 private: 2451 ABIArgInfo classify(QualType Ty, unsigned &FreeSSERegs, bool IsReturnType, 2452 bool IsVectorCall, bool IsRegCall) const; 2453 ABIArgInfo reclassifyHvaArgForVectorCall(QualType Ty, unsigned &FreeSSERegs, 2454 const ABIArgInfo ¤t) const; 2455 2456 X86AVXABILevel AVXLevel; 2457 2458 bool IsMingw64; 2459 }; 2460 2461 class X86_64TargetCodeGenInfo : public TargetCodeGenInfo { 2462 public: 2463 X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) 2464 : TargetCodeGenInfo(std::make_unique<X86_64ABIInfo>(CGT, AVXLevel)) {} 2465 2466 const X86_64ABIInfo &getABIInfo() const { 2467 return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo()); 2468 } 2469 2470 /// Disable tail call on x86-64. The epilogue code before the tail jump blocks 2471 /// autoreleaseRV/retainRV and autoreleaseRV/unsafeClaimRV optimizations. 2472 bool markARCOptimizedReturnCallsAsNoTail() const override { return true; } 2473 2474 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override { 2475 return 7; 2476 } 2477 2478 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 2479 llvm::Value *Address) const override { 2480 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8); 2481 2482 // 0-15 are the 16 integer registers. 2483 // 16 is %rip. 2484 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16); 2485 return false; 2486 } 2487 2488 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF, 2489 StringRef Constraint, 2490 llvm::Type* Ty) const override { 2491 return X86AdjustInlineAsmType(CGF, Constraint, Ty); 2492 } 2493 2494 bool isNoProtoCallVariadic(const CallArgList &args, 2495 const FunctionNoProtoType *fnType) const override { 2496 // The default CC on x86-64 sets %al to the number of SSA 2497 // registers used, and GCC sets this when calling an unprototyped 2498 // function, so we override the default behavior. However, don't do 2499 // that when AVX types are involved: the ABI explicitly states it is 2500 // undefined, and it doesn't work in practice because of how the ABI 2501 // defines varargs anyway. 2502 if (fnType->getCallConv() == CC_C) { 2503 bool HasAVXType = false; 2504 for (CallArgList::const_iterator 2505 it = args.begin(), ie = args.end(); it != ie; ++it) { 2506 if (getABIInfo().isPassedUsingAVXType(it->Ty)) { 2507 HasAVXType = true; 2508 break; 2509 } 2510 } 2511 2512 if (!HasAVXType) 2513 return true; 2514 } 2515 2516 return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType); 2517 } 2518 2519 llvm::Constant * 2520 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override { 2521 unsigned Sig = (0xeb << 0) | // jmp rel8 2522 (0x06 << 8) | // .+0x08 2523 ('v' << 16) | 2524 ('2' << 24); 2525 return llvm::ConstantInt::get(CGM.Int32Ty, Sig); 2526 } 2527 2528 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 2529 CodeGen::CodeGenModule &CGM) const override { 2530 if (GV->isDeclaration()) 2531 return; 2532 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) { 2533 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) { 2534 llvm::Function *Fn = cast<llvm::Function>(GV); 2535 Fn->addFnAttr("stackrealign"); 2536 } 2537 2538 addX86InterruptAttrs(FD, GV, CGM); 2539 } 2540 } 2541 2542 void checkFunctionCallABI(CodeGenModule &CGM, SourceLocation CallLoc, 2543 const FunctionDecl *Caller, 2544 const FunctionDecl *Callee, 2545 const CallArgList &Args) const override; 2546 }; 2547 2548 static void initFeatureMaps(const ASTContext &Ctx, 2549 llvm::StringMap<bool> &CallerMap, 2550 const FunctionDecl *Caller, 2551 llvm::StringMap<bool> &CalleeMap, 2552 const FunctionDecl *Callee) { 2553 if (CalleeMap.empty() && CallerMap.empty()) { 2554 // The caller is potentially nullptr in the case where the call isn't in a 2555 // function. In this case, the getFunctionFeatureMap ensures we just get 2556 // the TU level setting (since it cannot be modified by 'target'.. 2557 Ctx.getFunctionFeatureMap(CallerMap, Caller); 2558 Ctx.getFunctionFeatureMap(CalleeMap, Callee); 2559 } 2560 } 2561 2562 static bool checkAVXParamFeature(DiagnosticsEngine &Diag, 2563 SourceLocation CallLoc, 2564 const llvm::StringMap<bool> &CallerMap, 2565 const llvm::StringMap<bool> &CalleeMap, 2566 QualType Ty, StringRef Feature, 2567 bool IsArgument) { 2568 bool CallerHasFeat = CallerMap.lookup(Feature); 2569 bool CalleeHasFeat = CalleeMap.lookup(Feature); 2570 if (!CallerHasFeat && !CalleeHasFeat) 2571 return Diag.Report(CallLoc, diag::warn_avx_calling_convention) 2572 << IsArgument << Ty << Feature; 2573 2574 // Mixing calling conventions here is very clearly an error. 2575 if (!CallerHasFeat || !CalleeHasFeat) 2576 return Diag.Report(CallLoc, diag::err_avx_calling_convention) 2577 << IsArgument << Ty << Feature; 2578 2579 // Else, both caller and callee have the required feature, so there is no need 2580 // to diagnose. 2581 return false; 2582 } 2583 2584 static bool checkAVXParam(DiagnosticsEngine &Diag, ASTContext &Ctx, 2585 SourceLocation CallLoc, 2586 const llvm::StringMap<bool> &CallerMap, 2587 const llvm::StringMap<bool> &CalleeMap, QualType Ty, 2588 bool IsArgument) { 2589 uint64_t Size = Ctx.getTypeSize(Ty); 2590 if (Size > 256) 2591 return checkAVXParamFeature(Diag, CallLoc, CallerMap, CalleeMap, Ty, 2592 "avx512f", IsArgument); 2593 2594 if (Size > 128) 2595 return checkAVXParamFeature(Diag, CallLoc, CallerMap, CalleeMap, Ty, "avx", 2596 IsArgument); 2597 2598 return false; 2599 } 2600 2601 void X86_64TargetCodeGenInfo::checkFunctionCallABI( 2602 CodeGenModule &CGM, SourceLocation CallLoc, const FunctionDecl *Caller, 2603 const FunctionDecl *Callee, const CallArgList &Args) const { 2604 llvm::StringMap<bool> CallerMap; 2605 llvm::StringMap<bool> CalleeMap; 2606 unsigned ArgIndex = 0; 2607 2608 // We need to loop through the actual call arguments rather than the the 2609 // function's parameters, in case this variadic. 2610 for (const CallArg &Arg : Args) { 2611 // The "avx" feature changes how vectors >128 in size are passed. "avx512f" 2612 // additionally changes how vectors >256 in size are passed. Like GCC, we 2613 // warn when a function is called with an argument where this will change. 2614 // Unlike GCC, we also error when it is an obvious ABI mismatch, that is, 2615 // the caller and callee features are mismatched. 2616 // Unfortunately, we cannot do this diagnostic in SEMA, since the callee can 2617 // change its ABI with attribute-target after this call. 2618 if (Arg.getType()->isVectorType() && 2619 CGM.getContext().getTypeSize(Arg.getType()) > 128) { 2620 initFeatureMaps(CGM.getContext(), CallerMap, Caller, CalleeMap, Callee); 2621 QualType Ty = Arg.getType(); 2622 // The CallArg seems to have desugared the type already, so for clearer 2623 // diagnostics, replace it with the type in the FunctionDecl if possible. 2624 if (ArgIndex < Callee->getNumParams()) 2625 Ty = Callee->getParamDecl(ArgIndex)->getType(); 2626 2627 if (checkAVXParam(CGM.getDiags(), CGM.getContext(), CallLoc, CallerMap, 2628 CalleeMap, Ty, /*IsArgument*/ true)) 2629 return; 2630 } 2631 ++ArgIndex; 2632 } 2633 2634 // Check return always, as we don't have a good way of knowing in codegen 2635 // whether this value is used, tail-called, etc. 2636 if (Callee->getReturnType()->isVectorType() && 2637 CGM.getContext().getTypeSize(Callee->getReturnType()) > 128) { 2638 initFeatureMaps(CGM.getContext(), CallerMap, Caller, CalleeMap, Callee); 2639 checkAVXParam(CGM.getDiags(), CGM.getContext(), CallLoc, CallerMap, 2640 CalleeMap, Callee->getReturnType(), 2641 /*IsArgument*/ false); 2642 } 2643 } 2644 2645 static std::string qualifyWindowsLibrary(llvm::StringRef Lib) { 2646 // If the argument does not end in .lib, automatically add the suffix. 2647 // If the argument contains a space, enclose it in quotes. 2648 // This matches the behavior of MSVC. 2649 bool Quote = (Lib.find(' ') != StringRef::npos); 2650 std::string ArgStr = Quote ? "\"" : ""; 2651 ArgStr += Lib; 2652 if (!Lib.endswith_insensitive(".lib") && !Lib.endswith_insensitive(".a")) 2653 ArgStr += ".lib"; 2654 ArgStr += Quote ? "\"" : ""; 2655 return ArgStr; 2656 } 2657 2658 class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo { 2659 public: 2660 WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, 2661 bool DarwinVectorABI, bool RetSmallStructInRegABI, bool Win32StructABI, 2662 unsigned NumRegisterParameters) 2663 : X86_32TargetCodeGenInfo(CGT, DarwinVectorABI, RetSmallStructInRegABI, 2664 Win32StructABI, NumRegisterParameters, false) {} 2665 2666 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 2667 CodeGen::CodeGenModule &CGM) const override; 2668 2669 void getDependentLibraryOption(llvm::StringRef Lib, 2670 llvm::SmallString<24> &Opt) const override { 2671 Opt = "/DEFAULTLIB:"; 2672 Opt += qualifyWindowsLibrary(Lib); 2673 } 2674 2675 void getDetectMismatchOption(llvm::StringRef Name, 2676 llvm::StringRef Value, 2677 llvm::SmallString<32> &Opt) const override { 2678 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\""; 2679 } 2680 }; 2681 2682 static void addStackProbeTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 2683 CodeGen::CodeGenModule &CGM) { 2684 if (llvm::Function *Fn = dyn_cast_or_null<llvm::Function>(GV)) { 2685 2686 if (CGM.getCodeGenOpts().StackProbeSize != 4096) 2687 Fn->addFnAttr("stack-probe-size", 2688 llvm::utostr(CGM.getCodeGenOpts().StackProbeSize)); 2689 if (CGM.getCodeGenOpts().NoStackArgProbe) 2690 Fn->addFnAttr("no-stack-arg-probe"); 2691 } 2692 } 2693 2694 void WinX86_32TargetCodeGenInfo::setTargetAttributes( 2695 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const { 2696 X86_32TargetCodeGenInfo::setTargetAttributes(D, GV, CGM); 2697 if (GV->isDeclaration()) 2698 return; 2699 addStackProbeTargetAttributes(D, GV, CGM); 2700 } 2701 2702 class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo { 2703 public: 2704 WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, 2705 X86AVXABILevel AVXLevel) 2706 : TargetCodeGenInfo(std::make_unique<WinX86_64ABIInfo>(CGT, AVXLevel)) {} 2707 2708 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 2709 CodeGen::CodeGenModule &CGM) const override; 2710 2711 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override { 2712 return 7; 2713 } 2714 2715 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 2716 llvm::Value *Address) const override { 2717 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8); 2718 2719 // 0-15 are the 16 integer registers. 2720 // 16 is %rip. 2721 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16); 2722 return false; 2723 } 2724 2725 void getDependentLibraryOption(llvm::StringRef Lib, 2726 llvm::SmallString<24> &Opt) const override { 2727 Opt = "/DEFAULTLIB:"; 2728 Opt += qualifyWindowsLibrary(Lib); 2729 } 2730 2731 void getDetectMismatchOption(llvm::StringRef Name, 2732 llvm::StringRef Value, 2733 llvm::SmallString<32> &Opt) const override { 2734 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\""; 2735 } 2736 }; 2737 2738 void WinX86_64TargetCodeGenInfo::setTargetAttributes( 2739 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const { 2740 TargetCodeGenInfo::setTargetAttributes(D, GV, CGM); 2741 if (GV->isDeclaration()) 2742 return; 2743 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) { 2744 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) { 2745 llvm::Function *Fn = cast<llvm::Function>(GV); 2746 Fn->addFnAttr("stackrealign"); 2747 } 2748 2749 addX86InterruptAttrs(FD, GV, CGM); 2750 } 2751 2752 addStackProbeTargetAttributes(D, GV, CGM); 2753 } 2754 } 2755 2756 void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo, 2757 Class &Hi) const { 2758 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done: 2759 // 2760 // (a) If one of the classes is Memory, the whole argument is passed in 2761 // memory. 2762 // 2763 // (b) If X87UP is not preceded by X87, the whole argument is passed in 2764 // memory. 2765 // 2766 // (c) If the size of the aggregate exceeds two eightbytes and the first 2767 // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole 2768 // argument is passed in memory. NOTE: This is necessary to keep the 2769 // ABI working for processors that don't support the __m256 type. 2770 // 2771 // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE. 2772 // 2773 // Some of these are enforced by the merging logic. Others can arise 2774 // only with unions; for example: 2775 // union { _Complex double; unsigned; } 2776 // 2777 // Note that clauses (b) and (c) were added in 0.98. 2778 // 2779 if (Hi == Memory) 2780 Lo = Memory; 2781 if (Hi == X87Up && Lo != X87 && honorsRevision0_98()) 2782 Lo = Memory; 2783 if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp)) 2784 Lo = Memory; 2785 if (Hi == SSEUp && Lo != SSE) 2786 Hi = SSE; 2787 } 2788 2789 X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) { 2790 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is 2791 // classified recursively so that always two fields are 2792 // considered. The resulting class is calculated according to 2793 // the classes of the fields in the eightbyte: 2794 // 2795 // (a) If both classes are equal, this is the resulting class. 2796 // 2797 // (b) If one of the classes is NO_CLASS, the resulting class is 2798 // the other class. 2799 // 2800 // (c) If one of the classes is MEMORY, the result is the MEMORY 2801 // class. 2802 // 2803 // (d) If one of the classes is INTEGER, the result is the 2804 // INTEGER. 2805 // 2806 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class, 2807 // MEMORY is used as class. 2808 // 2809 // (f) Otherwise class SSE is used. 2810 2811 // Accum should never be memory (we should have returned) or 2812 // ComplexX87 (because this cannot be passed in a structure). 2813 assert((Accum != Memory && Accum != ComplexX87) && 2814 "Invalid accumulated classification during merge."); 2815 if (Accum == Field || Field == NoClass) 2816 return Accum; 2817 if (Field == Memory) 2818 return Memory; 2819 if (Accum == NoClass) 2820 return Field; 2821 if (Accum == Integer || Field == Integer) 2822 return Integer; 2823 if (Field == X87 || Field == X87Up || Field == ComplexX87 || 2824 Accum == X87 || Accum == X87Up) 2825 return Memory; 2826 return SSE; 2827 } 2828 2829 void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase, 2830 Class &Lo, Class &Hi, bool isNamedArg) const { 2831 // FIXME: This code can be simplified by introducing a simple value class for 2832 // Class pairs with appropriate constructor methods for the various 2833 // situations. 2834 2835 // FIXME: Some of the split computations are wrong; unaligned vectors 2836 // shouldn't be passed in registers for example, so there is no chance they 2837 // can straddle an eightbyte. Verify & simplify. 2838 2839 Lo = Hi = NoClass; 2840 2841 Class &Current = OffsetBase < 64 ? Lo : Hi; 2842 Current = Memory; 2843 2844 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) { 2845 BuiltinType::Kind k = BT->getKind(); 2846 2847 if (k == BuiltinType::Void) { 2848 Current = NoClass; 2849 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) { 2850 Lo = Integer; 2851 Hi = Integer; 2852 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) { 2853 Current = Integer; 2854 } else if (k == BuiltinType::Float || k == BuiltinType::Double || 2855 k == BuiltinType::Float16) { 2856 Current = SSE; 2857 } else if (k == BuiltinType::LongDouble) { 2858 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat(); 2859 if (LDF == &llvm::APFloat::IEEEquad()) { 2860 Lo = SSE; 2861 Hi = SSEUp; 2862 } else if (LDF == &llvm::APFloat::x87DoubleExtended()) { 2863 Lo = X87; 2864 Hi = X87Up; 2865 } else if (LDF == &llvm::APFloat::IEEEdouble()) { 2866 Current = SSE; 2867 } else 2868 llvm_unreachable("unexpected long double representation!"); 2869 } 2870 // FIXME: _Decimal32 and _Decimal64 are SSE. 2871 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp). 2872 return; 2873 } 2874 2875 if (const EnumType *ET = Ty->getAs<EnumType>()) { 2876 // Classify the underlying integer type. 2877 classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg); 2878 return; 2879 } 2880 2881 if (Ty->hasPointerRepresentation()) { 2882 Current = Integer; 2883 return; 2884 } 2885 2886 if (Ty->isMemberPointerType()) { 2887 if (Ty->isMemberFunctionPointerType()) { 2888 if (Has64BitPointers) { 2889 // If Has64BitPointers, this is an {i64, i64}, so classify both 2890 // Lo and Hi now. 2891 Lo = Hi = Integer; 2892 } else { 2893 // Otherwise, with 32-bit pointers, this is an {i32, i32}. If that 2894 // straddles an eightbyte boundary, Hi should be classified as well. 2895 uint64_t EB_FuncPtr = (OffsetBase) / 64; 2896 uint64_t EB_ThisAdj = (OffsetBase + 64 - 1) / 64; 2897 if (EB_FuncPtr != EB_ThisAdj) { 2898 Lo = Hi = Integer; 2899 } else { 2900 Current = Integer; 2901 } 2902 } 2903 } else { 2904 Current = Integer; 2905 } 2906 return; 2907 } 2908 2909 if (const VectorType *VT = Ty->getAs<VectorType>()) { 2910 uint64_t Size = getContext().getTypeSize(VT); 2911 if (Size == 1 || Size == 8 || Size == 16 || Size == 32) { 2912 // gcc passes the following as integer: 2913 // 4 bytes - <4 x char>, <2 x short>, <1 x int>, <1 x float> 2914 // 2 bytes - <2 x char>, <1 x short> 2915 // 1 byte - <1 x char> 2916 Current = Integer; 2917 2918 // If this type crosses an eightbyte boundary, it should be 2919 // split. 2920 uint64_t EB_Lo = (OffsetBase) / 64; 2921 uint64_t EB_Hi = (OffsetBase + Size - 1) / 64; 2922 if (EB_Lo != EB_Hi) 2923 Hi = Lo; 2924 } else if (Size == 64) { 2925 QualType ElementType = VT->getElementType(); 2926 2927 // gcc passes <1 x double> in memory. :( 2928 if (ElementType->isSpecificBuiltinType(BuiltinType::Double)) 2929 return; 2930 2931 // gcc passes <1 x long long> as SSE but clang used to unconditionally 2932 // pass them as integer. For platforms where clang is the de facto 2933 // platform compiler, we must continue to use integer. 2934 if (!classifyIntegerMMXAsSSE() && 2935 (ElementType->isSpecificBuiltinType(BuiltinType::LongLong) || 2936 ElementType->isSpecificBuiltinType(BuiltinType::ULongLong) || 2937 ElementType->isSpecificBuiltinType(BuiltinType::Long) || 2938 ElementType->isSpecificBuiltinType(BuiltinType::ULong))) 2939 Current = Integer; 2940 else 2941 Current = SSE; 2942 2943 // If this type crosses an eightbyte boundary, it should be 2944 // split. 2945 if (OffsetBase && OffsetBase != 64) 2946 Hi = Lo; 2947 } else if (Size == 128 || 2948 (isNamedArg && Size <= getNativeVectorSizeForAVXABI(AVXLevel))) { 2949 QualType ElementType = VT->getElementType(); 2950 2951 // gcc passes 256 and 512 bit <X x __int128> vectors in memory. :( 2952 if (passInt128VectorsInMem() && Size != 128 && 2953 (ElementType->isSpecificBuiltinType(BuiltinType::Int128) || 2954 ElementType->isSpecificBuiltinType(BuiltinType::UInt128))) 2955 return; 2956 2957 // Arguments of 256-bits are split into four eightbyte chunks. The 2958 // least significant one belongs to class SSE and all the others to class 2959 // SSEUP. The original Lo and Hi design considers that types can't be 2960 // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense. 2961 // This design isn't correct for 256-bits, but since there're no cases 2962 // where the upper parts would need to be inspected, avoid adding 2963 // complexity and just consider Hi to match the 64-256 part. 2964 // 2965 // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in 2966 // registers if they are "named", i.e. not part of the "..." of a 2967 // variadic function. 2968 // 2969 // Similarly, per 3.2.3. of the AVX512 draft, 512-bits ("named") args are 2970 // split into eight eightbyte chunks, one SSE and seven SSEUP. 2971 Lo = SSE; 2972 Hi = SSEUp; 2973 } 2974 return; 2975 } 2976 2977 if (const ComplexType *CT = Ty->getAs<ComplexType>()) { 2978 QualType ET = getContext().getCanonicalType(CT->getElementType()); 2979 2980 uint64_t Size = getContext().getTypeSize(Ty); 2981 if (ET->isIntegralOrEnumerationType()) { 2982 if (Size <= 64) 2983 Current = Integer; 2984 else if (Size <= 128) 2985 Lo = Hi = Integer; 2986 } else if (ET->isFloat16Type() || ET == getContext().FloatTy) { 2987 Current = SSE; 2988 } else if (ET == getContext().DoubleTy) { 2989 Lo = Hi = SSE; 2990 } else if (ET == getContext().LongDoubleTy) { 2991 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat(); 2992 if (LDF == &llvm::APFloat::IEEEquad()) 2993 Current = Memory; 2994 else if (LDF == &llvm::APFloat::x87DoubleExtended()) 2995 Current = ComplexX87; 2996 else if (LDF == &llvm::APFloat::IEEEdouble()) 2997 Lo = Hi = SSE; 2998 else 2999 llvm_unreachable("unexpected long double representation!"); 3000 } 3001 3002 // If this complex type crosses an eightbyte boundary then it 3003 // should be split. 3004 uint64_t EB_Real = (OffsetBase) / 64; 3005 uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64; 3006 if (Hi == NoClass && EB_Real != EB_Imag) 3007 Hi = Lo; 3008 3009 return; 3010 } 3011 3012 if (const auto *EITy = Ty->getAs<ExtIntType>()) { 3013 if (EITy->getNumBits() <= 64) 3014 Current = Integer; 3015 else if (EITy->getNumBits() <= 128) 3016 Lo = Hi = Integer; 3017 // Larger values need to get passed in memory. 3018 return; 3019 } 3020 3021 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) { 3022 // Arrays are treated like structures. 3023 3024 uint64_t Size = getContext().getTypeSize(Ty); 3025 3026 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger 3027 // than eight eightbytes, ..., it has class MEMORY. 3028 if (Size > 512) 3029 return; 3030 3031 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned 3032 // fields, it has class MEMORY. 3033 // 3034 // Only need to check alignment of array base. 3035 if (OffsetBase % getContext().getTypeAlign(AT->getElementType())) 3036 return; 3037 3038 // Otherwise implement simplified merge. We could be smarter about 3039 // this, but it isn't worth it and would be harder to verify. 3040 Current = NoClass; 3041 uint64_t EltSize = getContext().getTypeSize(AT->getElementType()); 3042 uint64_t ArraySize = AT->getSize().getZExtValue(); 3043 3044 // The only case a 256-bit wide vector could be used is when the array 3045 // contains a single 256-bit element. Since Lo and Hi logic isn't extended 3046 // to work for sizes wider than 128, early check and fallback to memory. 3047 // 3048 if (Size > 128 && 3049 (Size != EltSize || Size > getNativeVectorSizeForAVXABI(AVXLevel))) 3050 return; 3051 3052 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) { 3053 Class FieldLo, FieldHi; 3054 classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg); 3055 Lo = merge(Lo, FieldLo); 3056 Hi = merge(Hi, FieldHi); 3057 if (Lo == Memory || Hi == Memory) 3058 break; 3059 } 3060 3061 postMerge(Size, Lo, Hi); 3062 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification."); 3063 return; 3064 } 3065 3066 if (const RecordType *RT = Ty->getAs<RecordType>()) { 3067 uint64_t Size = getContext().getTypeSize(Ty); 3068 3069 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger 3070 // than eight eightbytes, ..., it has class MEMORY. 3071 if (Size > 512) 3072 return; 3073 3074 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial 3075 // copy constructor or a non-trivial destructor, it is passed by invisible 3076 // reference. 3077 if (getRecordArgABI(RT, getCXXABI())) 3078 return; 3079 3080 const RecordDecl *RD = RT->getDecl(); 3081 3082 // Assume variable sized types are passed in memory. 3083 if (RD->hasFlexibleArrayMember()) 3084 return; 3085 3086 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD); 3087 3088 // Reset Lo class, this will be recomputed. 3089 Current = NoClass; 3090 3091 // If this is a C++ record, classify the bases first. 3092 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 3093 for (const auto &I : CXXRD->bases()) { 3094 assert(!I.isVirtual() && !I.getType()->isDependentType() && 3095 "Unexpected base class!"); 3096 const auto *Base = 3097 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl()); 3098 3099 // Classify this field. 3100 // 3101 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a 3102 // single eightbyte, each is classified separately. Each eightbyte gets 3103 // initialized to class NO_CLASS. 3104 Class FieldLo, FieldHi; 3105 uint64_t Offset = 3106 OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base)); 3107 classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg); 3108 Lo = merge(Lo, FieldLo); 3109 Hi = merge(Hi, FieldHi); 3110 if (Lo == Memory || Hi == Memory) { 3111 postMerge(Size, Lo, Hi); 3112 return; 3113 } 3114 } 3115 } 3116 3117 // Classify the fields one at a time, merging the results. 3118 unsigned idx = 0; 3119 bool UseClang11Compat = getContext().getLangOpts().getClangABICompat() <= 3120 LangOptions::ClangABI::Ver11 || 3121 getContext().getTargetInfo().getTriple().isPS4(); 3122 bool IsUnion = RT->isUnionType() && !UseClang11Compat; 3123 3124 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 3125 i != e; ++i, ++idx) { 3126 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx); 3127 bool BitField = i->isBitField(); 3128 3129 // Ignore padding bit-fields. 3130 if (BitField && i->isUnnamedBitfield()) 3131 continue; 3132 3133 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than 3134 // eight eightbytes, or it contains unaligned fields, it has class MEMORY. 3135 // 3136 // The only case a 256-bit or a 512-bit wide vector could be used is when 3137 // the struct contains a single 256-bit or 512-bit element. Early check 3138 // and fallback to memory. 3139 // 3140 // FIXME: Extended the Lo and Hi logic properly to work for size wider 3141 // than 128. 3142 if (Size > 128 && 3143 ((!IsUnion && Size != getContext().getTypeSize(i->getType())) || 3144 Size > getNativeVectorSizeForAVXABI(AVXLevel))) { 3145 Lo = Memory; 3146 postMerge(Size, Lo, Hi); 3147 return; 3148 } 3149 // Note, skip this test for bit-fields, see below. 3150 if (!BitField && Offset % getContext().getTypeAlign(i->getType())) { 3151 Lo = Memory; 3152 postMerge(Size, Lo, Hi); 3153 return; 3154 } 3155 3156 // Classify this field. 3157 // 3158 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate 3159 // exceeds a single eightbyte, each is classified 3160 // separately. Each eightbyte gets initialized to class 3161 // NO_CLASS. 3162 Class FieldLo, FieldHi; 3163 3164 // Bit-fields require special handling, they do not force the 3165 // structure to be passed in memory even if unaligned, and 3166 // therefore they can straddle an eightbyte. 3167 if (BitField) { 3168 assert(!i->isUnnamedBitfield()); 3169 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx); 3170 uint64_t Size = i->getBitWidthValue(getContext()); 3171 3172 uint64_t EB_Lo = Offset / 64; 3173 uint64_t EB_Hi = (Offset + Size - 1) / 64; 3174 3175 if (EB_Lo) { 3176 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes."); 3177 FieldLo = NoClass; 3178 FieldHi = Integer; 3179 } else { 3180 FieldLo = Integer; 3181 FieldHi = EB_Hi ? Integer : NoClass; 3182 } 3183 } else 3184 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg); 3185 Lo = merge(Lo, FieldLo); 3186 Hi = merge(Hi, FieldHi); 3187 if (Lo == Memory || Hi == Memory) 3188 break; 3189 } 3190 3191 postMerge(Size, Lo, Hi); 3192 } 3193 } 3194 3195 ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const { 3196 // If this is a scalar LLVM value then assume LLVM will pass it in the right 3197 // place naturally. 3198 if (!isAggregateTypeForABI(Ty)) { 3199 // Treat an enum type as its underlying type. 3200 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 3201 Ty = EnumTy->getDecl()->getIntegerType(); 3202 3203 if (Ty->isExtIntType()) 3204 return getNaturalAlignIndirect(Ty); 3205 3206 return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty) 3207 : ABIArgInfo::getDirect()); 3208 } 3209 3210 return getNaturalAlignIndirect(Ty); 3211 } 3212 3213 bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const { 3214 if (const VectorType *VecTy = Ty->getAs<VectorType>()) { 3215 uint64_t Size = getContext().getTypeSize(VecTy); 3216 unsigned LargestVector = getNativeVectorSizeForAVXABI(AVXLevel); 3217 if (Size <= 64 || Size > LargestVector) 3218 return true; 3219 QualType EltTy = VecTy->getElementType(); 3220 if (passInt128VectorsInMem() && 3221 (EltTy->isSpecificBuiltinType(BuiltinType::Int128) || 3222 EltTy->isSpecificBuiltinType(BuiltinType::UInt128))) 3223 return true; 3224 } 3225 3226 return false; 3227 } 3228 3229 ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty, 3230 unsigned freeIntRegs) const { 3231 // If this is a scalar LLVM value then assume LLVM will pass it in the right 3232 // place naturally. 3233 // 3234 // This assumption is optimistic, as there could be free registers available 3235 // when we need to pass this argument in memory, and LLVM could try to pass 3236 // the argument in the free register. This does not seem to happen currently, 3237 // but this code would be much safer if we could mark the argument with 3238 // 'onstack'. See PR12193. 3239 if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty) && 3240 !Ty->isExtIntType()) { 3241 // Treat an enum type as its underlying type. 3242 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 3243 Ty = EnumTy->getDecl()->getIntegerType(); 3244 3245 return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty) 3246 : ABIArgInfo::getDirect()); 3247 } 3248 3249 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 3250 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 3251 3252 // Compute the byval alignment. We specify the alignment of the byval in all 3253 // cases so that the mid-level optimizer knows the alignment of the byval. 3254 unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U); 3255 3256 // Attempt to avoid passing indirect results using byval when possible. This 3257 // is important for good codegen. 3258 // 3259 // We do this by coercing the value into a scalar type which the backend can 3260 // handle naturally (i.e., without using byval). 3261 // 3262 // For simplicity, we currently only do this when we have exhausted all of the 3263 // free integer registers. Doing this when there are free integer registers 3264 // would require more care, as we would have to ensure that the coerced value 3265 // did not claim the unused register. That would require either reording the 3266 // arguments to the function (so that any subsequent inreg values came first), 3267 // or only doing this optimization when there were no following arguments that 3268 // might be inreg. 3269 // 3270 // We currently expect it to be rare (particularly in well written code) for 3271 // arguments to be passed on the stack when there are still free integer 3272 // registers available (this would typically imply large structs being passed 3273 // by value), so this seems like a fair tradeoff for now. 3274 // 3275 // We can revisit this if the backend grows support for 'onstack' parameter 3276 // attributes. See PR12193. 3277 if (freeIntRegs == 0) { 3278 uint64_t Size = getContext().getTypeSize(Ty); 3279 3280 // If this type fits in an eightbyte, coerce it into the matching integral 3281 // type, which will end up on the stack (with alignment 8). 3282 if (Align == 8 && Size <= 64) 3283 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 3284 Size)); 3285 } 3286 3287 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(Align)); 3288 } 3289 3290 /// The ABI specifies that a value should be passed in a full vector XMM/YMM 3291 /// register. Pick an LLVM IR type that will be passed as a vector register. 3292 llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const { 3293 // Wrapper structs/arrays that only contain vectors are passed just like 3294 // vectors; strip them off if present. 3295 if (const Type *InnerTy = isSingleElementStruct(Ty, getContext())) 3296 Ty = QualType(InnerTy, 0); 3297 3298 llvm::Type *IRType = CGT.ConvertType(Ty); 3299 if (isa<llvm::VectorType>(IRType)) { 3300 // Don't pass vXi128 vectors in their native type, the backend can't 3301 // legalize them. 3302 if (passInt128VectorsInMem() && 3303 cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy(128)) { 3304 // Use a vXi64 vector. 3305 uint64_t Size = getContext().getTypeSize(Ty); 3306 return llvm::FixedVectorType::get(llvm::Type::getInt64Ty(getVMContext()), 3307 Size / 64); 3308 } 3309 3310 return IRType; 3311 } 3312 3313 if (IRType->getTypeID() == llvm::Type::FP128TyID) 3314 return IRType; 3315 3316 // We couldn't find the preferred IR vector type for 'Ty'. 3317 uint64_t Size = getContext().getTypeSize(Ty); 3318 assert((Size == 128 || Size == 256 || Size == 512) && "Invalid type found!"); 3319 3320 3321 // Return a LLVM IR vector type based on the size of 'Ty'. 3322 return llvm::FixedVectorType::get(llvm::Type::getDoubleTy(getVMContext()), 3323 Size / 64); 3324 } 3325 3326 /// BitsContainNoUserData - Return true if the specified [start,end) bit range 3327 /// is known to either be off the end of the specified type or being in 3328 /// alignment padding. The user type specified is known to be at most 128 bits 3329 /// in size, and have passed through X86_64ABIInfo::classify with a successful 3330 /// classification that put one of the two halves in the INTEGER class. 3331 /// 3332 /// It is conservatively correct to return false. 3333 static bool BitsContainNoUserData(QualType Ty, unsigned StartBit, 3334 unsigned EndBit, ASTContext &Context) { 3335 // If the bytes being queried are off the end of the type, there is no user 3336 // data hiding here. This handles analysis of builtins, vectors and other 3337 // types that don't contain interesting padding. 3338 unsigned TySize = (unsigned)Context.getTypeSize(Ty); 3339 if (TySize <= StartBit) 3340 return true; 3341 3342 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) { 3343 unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType()); 3344 unsigned NumElts = (unsigned)AT->getSize().getZExtValue(); 3345 3346 // Check each element to see if the element overlaps with the queried range. 3347 for (unsigned i = 0; i != NumElts; ++i) { 3348 // If the element is after the span we care about, then we're done.. 3349 unsigned EltOffset = i*EltSize; 3350 if (EltOffset >= EndBit) break; 3351 3352 unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0; 3353 if (!BitsContainNoUserData(AT->getElementType(), EltStart, 3354 EndBit-EltOffset, Context)) 3355 return false; 3356 } 3357 // If it overlaps no elements, then it is safe to process as padding. 3358 return true; 3359 } 3360 3361 if (const RecordType *RT = Ty->getAs<RecordType>()) { 3362 const RecordDecl *RD = RT->getDecl(); 3363 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); 3364 3365 // If this is a C++ record, check the bases first. 3366 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 3367 for (const auto &I : CXXRD->bases()) { 3368 assert(!I.isVirtual() && !I.getType()->isDependentType() && 3369 "Unexpected base class!"); 3370 const auto *Base = 3371 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl()); 3372 3373 // If the base is after the span we care about, ignore it. 3374 unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base)); 3375 if (BaseOffset >= EndBit) continue; 3376 3377 unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0; 3378 if (!BitsContainNoUserData(I.getType(), BaseStart, 3379 EndBit-BaseOffset, Context)) 3380 return false; 3381 } 3382 } 3383 3384 // Verify that no field has data that overlaps the region of interest. Yes 3385 // this could be sped up a lot by being smarter about queried fields, 3386 // however we're only looking at structs up to 16 bytes, so we don't care 3387 // much. 3388 unsigned idx = 0; 3389 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 3390 i != e; ++i, ++idx) { 3391 unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx); 3392 3393 // If we found a field after the region we care about, then we're done. 3394 if (FieldOffset >= EndBit) break; 3395 3396 unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0; 3397 if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset, 3398 Context)) 3399 return false; 3400 } 3401 3402 // If nothing in this record overlapped the area of interest, then we're 3403 // clean. 3404 return true; 3405 } 3406 3407 return false; 3408 } 3409 3410 /// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a 3411 /// float member at the specified offset. For example, {int,{float}} has a 3412 /// float at offset 4. It is conservatively correct for this routine to return 3413 /// false. 3414 static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset, 3415 const llvm::DataLayout &TD) { 3416 // Base case if we find a float. 3417 if (IROffset == 0 && IRType->isFloatTy()) 3418 return true; 3419 3420 // If this is a struct, recurse into the field at the specified offset. 3421 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) { 3422 const llvm::StructLayout *SL = TD.getStructLayout(STy); 3423 unsigned Elt = SL->getElementContainingOffset(IROffset); 3424 IROffset -= SL->getElementOffset(Elt); 3425 return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD); 3426 } 3427 3428 // If this is an array, recurse into the field at the specified offset. 3429 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) { 3430 llvm::Type *EltTy = ATy->getElementType(); 3431 unsigned EltSize = TD.getTypeAllocSize(EltTy); 3432 IROffset -= IROffset/EltSize*EltSize; 3433 return ContainsFloatAtOffset(EltTy, IROffset, TD); 3434 } 3435 3436 return false; 3437 } 3438 3439 /// ContainsHalfAtOffset - Return true if the specified LLVM IR type has a 3440 /// half member at the specified offset. For example, {int,{half}} has a 3441 /// half at offset 4. It is conservatively correct for this routine to return 3442 /// false. 3443 /// FIXME: Merge with ContainsFloatAtOffset 3444 static bool ContainsHalfAtOffset(llvm::Type *IRType, unsigned IROffset, 3445 const llvm::DataLayout &TD) { 3446 // Base case if we find a float. 3447 if (IROffset == 0 && IRType->isHalfTy()) 3448 return true; 3449 3450 // If this is a struct, recurse into the field at the specified offset. 3451 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) { 3452 const llvm::StructLayout *SL = TD.getStructLayout(STy); 3453 unsigned Elt = SL->getElementContainingOffset(IROffset); 3454 IROffset -= SL->getElementOffset(Elt); 3455 return ContainsHalfAtOffset(STy->getElementType(Elt), IROffset, TD); 3456 } 3457 3458 // If this is an array, recurse into the field at the specified offset. 3459 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) { 3460 llvm::Type *EltTy = ATy->getElementType(); 3461 unsigned EltSize = TD.getTypeAllocSize(EltTy); 3462 IROffset -= IROffset / EltSize * EltSize; 3463 return ContainsHalfAtOffset(EltTy, IROffset, TD); 3464 } 3465 3466 return false; 3467 } 3468 3469 /// GetSSETypeAtOffset - Return a type that will be passed by the backend in the 3470 /// low 8 bytes of an XMM register, corresponding to the SSE class. 3471 llvm::Type *X86_64ABIInfo:: 3472 GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset, 3473 QualType SourceTy, unsigned SourceOffset) const { 3474 // If the high 32 bits are not used, we have three choices. Single half, 3475 // single float or two halfs. 3476 if (BitsContainNoUserData(SourceTy, SourceOffset * 8 + 32, 3477 SourceOffset * 8 + 64, getContext())) { 3478 if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout())) 3479 return llvm::Type::getFloatTy(getVMContext()); 3480 if (ContainsHalfAtOffset(IRType, IROffset + 2, getDataLayout())) 3481 return llvm::FixedVectorType::get(llvm::Type::getHalfTy(getVMContext()), 3482 2); 3483 3484 return llvm::Type::getHalfTy(getVMContext()); 3485 } 3486 3487 // We want to pass as <2 x float> if the LLVM IR type contains a float at 3488 // offset+0 and offset+4. Walk the LLVM IR type to find out if this is the 3489 // case. 3490 if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) && 3491 ContainsFloatAtOffset(IRType, IROffset + 4, getDataLayout())) 3492 return llvm::FixedVectorType::get(llvm::Type::getFloatTy(getVMContext()), 3493 2); 3494 3495 // We want to pass as <4 x half> if the LLVM IR type contains a half at 3496 // offset+0, +2, +4. Walk the LLVM IR type to find out if this is the case. 3497 if (ContainsHalfAtOffset(IRType, IROffset, getDataLayout()) && 3498 ContainsHalfAtOffset(IRType, IROffset + 2, getDataLayout()) && 3499 ContainsHalfAtOffset(IRType, IROffset + 4, getDataLayout())) 3500 return llvm::FixedVectorType::get(llvm::Type::getHalfTy(getVMContext()), 4); 3501 3502 // We want to pass as <4 x half> if the LLVM IR type contains a mix of float 3503 // and half. 3504 // FIXME: Do we have a better representation for the mixed type? 3505 if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) || 3506 ContainsFloatAtOffset(IRType, IROffset + 4, getDataLayout())) 3507 return llvm::FixedVectorType::get(llvm::Type::getHalfTy(getVMContext()), 4); 3508 3509 return llvm::Type::getDoubleTy(getVMContext()); 3510 } 3511 3512 3513 /// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in 3514 /// an 8-byte GPR. This means that we either have a scalar or we are talking 3515 /// about the high or low part of an up-to-16-byte struct. This routine picks 3516 /// the best LLVM IR type to represent this, which may be i64 or may be anything 3517 /// else that the backend will pass in a GPR that works better (e.g. i8, %foo*, 3518 /// etc). 3519 /// 3520 /// PrefType is an LLVM IR type that corresponds to (part of) the IR type for 3521 /// the source type. IROffset is an offset in bytes into the LLVM IR type that 3522 /// the 8-byte value references. PrefType may be null. 3523 /// 3524 /// SourceTy is the source-level type for the entire argument. SourceOffset is 3525 /// an offset into this that we're processing (which is always either 0 or 8). 3526 /// 3527 llvm::Type *X86_64ABIInfo:: 3528 GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset, 3529 QualType SourceTy, unsigned SourceOffset) const { 3530 // If we're dealing with an un-offset LLVM IR type, then it means that we're 3531 // returning an 8-byte unit starting with it. See if we can safely use it. 3532 if (IROffset == 0) { 3533 // Pointers and int64's always fill the 8-byte unit. 3534 if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) || 3535 IRType->isIntegerTy(64)) 3536 return IRType; 3537 3538 // If we have a 1/2/4-byte integer, we can use it only if the rest of the 3539 // goodness in the source type is just tail padding. This is allowed to 3540 // kick in for struct {double,int} on the int, but not on 3541 // struct{double,int,int} because we wouldn't return the second int. We 3542 // have to do this analysis on the source type because we can't depend on 3543 // unions being lowered a specific way etc. 3544 if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) || 3545 IRType->isIntegerTy(32) || 3546 (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) { 3547 unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 : 3548 cast<llvm::IntegerType>(IRType)->getBitWidth(); 3549 3550 if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth, 3551 SourceOffset*8+64, getContext())) 3552 return IRType; 3553 } 3554 } 3555 3556 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) { 3557 // If this is a struct, recurse into the field at the specified offset. 3558 const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy); 3559 if (IROffset < SL->getSizeInBytes()) { 3560 unsigned FieldIdx = SL->getElementContainingOffset(IROffset); 3561 IROffset -= SL->getElementOffset(FieldIdx); 3562 3563 return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset, 3564 SourceTy, SourceOffset); 3565 } 3566 } 3567 3568 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) { 3569 llvm::Type *EltTy = ATy->getElementType(); 3570 unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy); 3571 unsigned EltOffset = IROffset/EltSize*EltSize; 3572 return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy, 3573 SourceOffset); 3574 } 3575 3576 // Okay, we don't have any better idea of what to pass, so we pass this in an 3577 // integer register that isn't too big to fit the rest of the struct. 3578 unsigned TySizeInBytes = 3579 (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity(); 3580 3581 assert(TySizeInBytes != SourceOffset && "Empty field?"); 3582 3583 // It is always safe to classify this as an integer type up to i64 that 3584 // isn't larger than the structure. 3585 return llvm::IntegerType::get(getVMContext(), 3586 std::min(TySizeInBytes-SourceOffset, 8U)*8); 3587 } 3588 3589 3590 /// GetX86_64ByValArgumentPair - Given a high and low type that can ideally 3591 /// be used as elements of a two register pair to pass or return, return a 3592 /// first class aggregate to represent them. For example, if the low part of 3593 /// a by-value argument should be passed as i32* and the high part as float, 3594 /// return {i32*, float}. 3595 static llvm::Type * 3596 GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi, 3597 const llvm::DataLayout &TD) { 3598 // In order to correctly satisfy the ABI, we need to the high part to start 3599 // at offset 8. If the high and low parts we inferred are both 4-byte types 3600 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have 3601 // the second element at offset 8. Check for this: 3602 unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo); 3603 unsigned HiAlign = TD.getABITypeAlignment(Hi); 3604 unsigned HiStart = llvm::alignTo(LoSize, HiAlign); 3605 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!"); 3606 3607 // To handle this, we have to increase the size of the low part so that the 3608 // second element will start at an 8 byte offset. We can't increase the size 3609 // of the second element because it might make us access off the end of the 3610 // struct. 3611 if (HiStart != 8) { 3612 // There are usually two sorts of types the ABI generation code can produce 3613 // for the low part of a pair that aren't 8 bytes in size: half, float or 3614 // i8/i16/i32. This can also include pointers when they are 32-bit (X32 and 3615 // NaCl). 3616 // Promote these to a larger type. 3617 if (Lo->isHalfTy() || Lo->isFloatTy()) 3618 Lo = llvm::Type::getDoubleTy(Lo->getContext()); 3619 else { 3620 assert((Lo->isIntegerTy() || Lo->isPointerTy()) 3621 && "Invalid/unknown lo type"); 3622 Lo = llvm::Type::getInt64Ty(Lo->getContext()); 3623 } 3624 } 3625 3626 llvm::StructType *Result = llvm::StructType::get(Lo, Hi); 3627 3628 // Verify that the second element is at an 8-byte offset. 3629 assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 && 3630 "Invalid x86-64 argument pair!"); 3631 return Result; 3632 } 3633 3634 ABIArgInfo X86_64ABIInfo:: 3635 classifyReturnType(QualType RetTy) const { 3636 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the 3637 // classification algorithm. 3638 X86_64ABIInfo::Class Lo, Hi; 3639 classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true); 3640 3641 // Check some invariants. 3642 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification."); 3643 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification."); 3644 3645 llvm::Type *ResType = nullptr; 3646 switch (Lo) { 3647 case NoClass: 3648 if (Hi == NoClass) 3649 return ABIArgInfo::getIgnore(); 3650 // If the low part is just padding, it takes no register, leave ResType 3651 // null. 3652 assert((Hi == SSE || Hi == Integer || Hi == X87Up) && 3653 "Unknown missing lo part"); 3654 break; 3655 3656 case SSEUp: 3657 case X87Up: 3658 llvm_unreachable("Invalid classification for lo word."); 3659 3660 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via 3661 // hidden argument. 3662 case Memory: 3663 return getIndirectReturnResult(RetTy); 3664 3665 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next 3666 // available register of the sequence %rax, %rdx is used. 3667 case Integer: 3668 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0); 3669 3670 // If we have a sign or zero extended integer, make sure to return Extend 3671 // so that the parameter gets the right LLVM IR attributes. 3672 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) { 3673 // Treat an enum type as its underlying type. 3674 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 3675 RetTy = EnumTy->getDecl()->getIntegerType(); 3676 3677 if (RetTy->isIntegralOrEnumerationType() && 3678 isPromotableIntegerTypeForABI(RetTy)) 3679 return ABIArgInfo::getExtend(RetTy); 3680 } 3681 break; 3682 3683 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next 3684 // available SSE register of the sequence %xmm0, %xmm1 is used. 3685 case SSE: 3686 ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0); 3687 break; 3688 3689 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is 3690 // returned on the X87 stack in %st0 as 80-bit x87 number. 3691 case X87: 3692 ResType = llvm::Type::getX86_FP80Ty(getVMContext()); 3693 break; 3694 3695 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real 3696 // part of the value is returned in %st0 and the imaginary part in 3697 // %st1. 3698 case ComplexX87: 3699 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification."); 3700 ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()), 3701 llvm::Type::getX86_FP80Ty(getVMContext())); 3702 break; 3703 } 3704 3705 llvm::Type *HighPart = nullptr; 3706 switch (Hi) { 3707 // Memory was handled previously and X87 should 3708 // never occur as a hi class. 3709 case Memory: 3710 case X87: 3711 llvm_unreachable("Invalid classification for hi word."); 3712 3713 case ComplexX87: // Previously handled. 3714 case NoClass: 3715 break; 3716 3717 case Integer: 3718 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8); 3719 if (Lo == NoClass) // Return HighPart at offset 8 in memory. 3720 return ABIArgInfo::getDirect(HighPart, 8); 3721 break; 3722 case SSE: 3723 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8); 3724 if (Lo == NoClass) // Return HighPart at offset 8 in memory. 3725 return ABIArgInfo::getDirect(HighPart, 8); 3726 break; 3727 3728 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte 3729 // is passed in the next available eightbyte chunk if the last used 3730 // vector register. 3731 // 3732 // SSEUP should always be preceded by SSE, just widen. 3733 case SSEUp: 3734 assert(Lo == SSE && "Unexpected SSEUp classification."); 3735 ResType = GetByteVectorType(RetTy); 3736 break; 3737 3738 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is 3739 // returned together with the previous X87 value in %st0. 3740 case X87Up: 3741 // If X87Up is preceded by X87, we don't need to do 3742 // anything. However, in some cases with unions it may not be 3743 // preceded by X87. In such situations we follow gcc and pass the 3744 // extra bits in an SSE reg. 3745 if (Lo != X87) { 3746 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8); 3747 if (Lo == NoClass) // Return HighPart at offset 8 in memory. 3748 return ABIArgInfo::getDirect(HighPart, 8); 3749 } 3750 break; 3751 } 3752 3753 // If a high part was specified, merge it together with the low part. It is 3754 // known to pass in the high eightbyte of the result. We do this by forming a 3755 // first class struct aggregate with the high and low part: {low, high} 3756 if (HighPart) 3757 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout()); 3758 3759 return ABIArgInfo::getDirect(ResType); 3760 } 3761 3762 ABIArgInfo X86_64ABIInfo::classifyArgumentType( 3763 QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE, 3764 bool isNamedArg) 3765 const 3766 { 3767 Ty = useFirstFieldIfTransparentUnion(Ty); 3768 3769 X86_64ABIInfo::Class Lo, Hi; 3770 classify(Ty, 0, Lo, Hi, isNamedArg); 3771 3772 // Check some invariants. 3773 // FIXME: Enforce these by construction. 3774 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification."); 3775 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification."); 3776 3777 neededInt = 0; 3778 neededSSE = 0; 3779 llvm::Type *ResType = nullptr; 3780 switch (Lo) { 3781 case NoClass: 3782 if (Hi == NoClass) 3783 return ABIArgInfo::getIgnore(); 3784 // If the low part is just padding, it takes no register, leave ResType 3785 // null. 3786 assert((Hi == SSE || Hi == Integer || Hi == X87Up) && 3787 "Unknown missing lo part"); 3788 break; 3789 3790 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument 3791 // on the stack. 3792 case Memory: 3793 3794 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or 3795 // COMPLEX_X87, it is passed in memory. 3796 case X87: 3797 case ComplexX87: 3798 if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect) 3799 ++neededInt; 3800 return getIndirectResult(Ty, freeIntRegs); 3801 3802 case SSEUp: 3803 case X87Up: 3804 llvm_unreachable("Invalid classification for lo word."); 3805 3806 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next 3807 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8 3808 // and %r9 is used. 3809 case Integer: 3810 ++neededInt; 3811 3812 // Pick an 8-byte type based on the preferred type. 3813 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0); 3814 3815 // If we have a sign or zero extended integer, make sure to return Extend 3816 // so that the parameter gets the right LLVM IR attributes. 3817 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) { 3818 // Treat an enum type as its underlying type. 3819 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 3820 Ty = EnumTy->getDecl()->getIntegerType(); 3821 3822 if (Ty->isIntegralOrEnumerationType() && 3823 isPromotableIntegerTypeForABI(Ty)) 3824 return ABIArgInfo::getExtend(Ty); 3825 } 3826 3827 break; 3828 3829 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next 3830 // available SSE register is used, the registers are taken in the 3831 // order from %xmm0 to %xmm7. 3832 case SSE: { 3833 llvm::Type *IRType = CGT.ConvertType(Ty); 3834 ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0); 3835 ++neededSSE; 3836 break; 3837 } 3838 } 3839 3840 llvm::Type *HighPart = nullptr; 3841 switch (Hi) { 3842 // Memory was handled previously, ComplexX87 and X87 should 3843 // never occur as hi classes, and X87Up must be preceded by X87, 3844 // which is passed in memory. 3845 case Memory: 3846 case X87: 3847 case ComplexX87: 3848 llvm_unreachable("Invalid classification for hi word."); 3849 3850 case NoClass: break; 3851 3852 case Integer: 3853 ++neededInt; 3854 // Pick an 8-byte type based on the preferred type. 3855 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8); 3856 3857 if (Lo == NoClass) // Pass HighPart at offset 8 in memory. 3858 return ABIArgInfo::getDirect(HighPart, 8); 3859 break; 3860 3861 // X87Up generally doesn't occur here (long double is passed in 3862 // memory), except in situations involving unions. 3863 case X87Up: 3864 case SSE: 3865 HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8); 3866 3867 if (Lo == NoClass) // Pass HighPart at offset 8 in memory. 3868 return ABIArgInfo::getDirect(HighPart, 8); 3869 3870 ++neededSSE; 3871 break; 3872 3873 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the 3874 // eightbyte is passed in the upper half of the last used SSE 3875 // register. This only happens when 128-bit vectors are passed. 3876 case SSEUp: 3877 assert(Lo == SSE && "Unexpected SSEUp classification"); 3878 ResType = GetByteVectorType(Ty); 3879 break; 3880 } 3881 3882 // If a high part was specified, merge it together with the low part. It is 3883 // known to pass in the high eightbyte of the result. We do this by forming a 3884 // first class struct aggregate with the high and low part: {low, high} 3885 if (HighPart) 3886 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout()); 3887 3888 return ABIArgInfo::getDirect(ResType); 3889 } 3890 3891 ABIArgInfo 3892 X86_64ABIInfo::classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt, 3893 unsigned &NeededSSE) const { 3894 auto RT = Ty->getAs<RecordType>(); 3895 assert(RT && "classifyRegCallStructType only valid with struct types"); 3896 3897 if (RT->getDecl()->hasFlexibleArrayMember()) 3898 return getIndirectReturnResult(Ty); 3899 3900 // Sum up bases 3901 if (auto CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl())) { 3902 if (CXXRD->isDynamicClass()) { 3903 NeededInt = NeededSSE = 0; 3904 return getIndirectReturnResult(Ty); 3905 } 3906 3907 for (const auto &I : CXXRD->bases()) 3908 if (classifyRegCallStructTypeImpl(I.getType(), NeededInt, NeededSSE) 3909 .isIndirect()) { 3910 NeededInt = NeededSSE = 0; 3911 return getIndirectReturnResult(Ty); 3912 } 3913 } 3914 3915 // Sum up members 3916 for (const auto *FD : RT->getDecl()->fields()) { 3917 if (FD->getType()->isRecordType() && !FD->getType()->isUnionType()) { 3918 if (classifyRegCallStructTypeImpl(FD->getType(), NeededInt, NeededSSE) 3919 .isIndirect()) { 3920 NeededInt = NeededSSE = 0; 3921 return getIndirectReturnResult(Ty); 3922 } 3923 } else { 3924 unsigned LocalNeededInt, LocalNeededSSE; 3925 if (classifyArgumentType(FD->getType(), UINT_MAX, LocalNeededInt, 3926 LocalNeededSSE, true) 3927 .isIndirect()) { 3928 NeededInt = NeededSSE = 0; 3929 return getIndirectReturnResult(Ty); 3930 } 3931 NeededInt += LocalNeededInt; 3932 NeededSSE += LocalNeededSSE; 3933 } 3934 } 3935 3936 return ABIArgInfo::getDirect(); 3937 } 3938 3939 ABIArgInfo X86_64ABIInfo::classifyRegCallStructType(QualType Ty, 3940 unsigned &NeededInt, 3941 unsigned &NeededSSE) const { 3942 3943 NeededInt = 0; 3944 NeededSSE = 0; 3945 3946 return classifyRegCallStructTypeImpl(Ty, NeededInt, NeededSSE); 3947 } 3948 3949 void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const { 3950 3951 const unsigned CallingConv = FI.getCallingConvention(); 3952 // It is possible to force Win64 calling convention on any x86_64 target by 3953 // using __attribute__((ms_abi)). In such case to correctly emit Win64 3954 // compatible code delegate this call to WinX86_64ABIInfo::computeInfo. 3955 if (CallingConv == llvm::CallingConv::Win64) { 3956 WinX86_64ABIInfo Win64ABIInfo(CGT, AVXLevel); 3957 Win64ABIInfo.computeInfo(FI); 3958 return; 3959 } 3960 3961 bool IsRegCall = CallingConv == llvm::CallingConv::X86_RegCall; 3962 3963 // Keep track of the number of assigned registers. 3964 unsigned FreeIntRegs = IsRegCall ? 11 : 6; 3965 unsigned FreeSSERegs = IsRegCall ? 16 : 8; 3966 unsigned NeededInt, NeededSSE; 3967 3968 if (!::classifyReturnType(getCXXABI(), FI, *this)) { 3969 if (IsRegCall && FI.getReturnType()->getTypePtr()->isRecordType() && 3970 !FI.getReturnType()->getTypePtr()->isUnionType()) { 3971 FI.getReturnInfo() = 3972 classifyRegCallStructType(FI.getReturnType(), NeededInt, NeededSSE); 3973 if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) { 3974 FreeIntRegs -= NeededInt; 3975 FreeSSERegs -= NeededSSE; 3976 } else { 3977 FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType()); 3978 } 3979 } else if (IsRegCall && FI.getReturnType()->getAs<ComplexType>() && 3980 getContext().getCanonicalType(FI.getReturnType() 3981 ->getAs<ComplexType>() 3982 ->getElementType()) == 3983 getContext().LongDoubleTy) 3984 // Complex Long Double Type is passed in Memory when Regcall 3985 // calling convention is used. 3986 FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType()); 3987 else 3988 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 3989 } 3990 3991 // If the return value is indirect, then the hidden argument is consuming one 3992 // integer register. 3993 if (FI.getReturnInfo().isIndirect()) 3994 --FreeIntRegs; 3995 3996 // The chain argument effectively gives us another free register. 3997 if (FI.isChainCall()) 3998 ++FreeIntRegs; 3999 4000 unsigned NumRequiredArgs = FI.getNumRequiredArgs(); 4001 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers 4002 // get assigned (in left-to-right order) for passing as follows... 4003 unsigned ArgNo = 0; 4004 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end(); 4005 it != ie; ++it, ++ArgNo) { 4006 bool IsNamedArg = ArgNo < NumRequiredArgs; 4007 4008 if (IsRegCall && it->type->isStructureOrClassType()) 4009 it->info = classifyRegCallStructType(it->type, NeededInt, NeededSSE); 4010 else 4011 it->info = classifyArgumentType(it->type, FreeIntRegs, NeededInt, 4012 NeededSSE, IsNamedArg); 4013 4014 // AMD64-ABI 3.2.3p3: If there are no registers available for any 4015 // eightbyte of an argument, the whole argument is passed on the 4016 // stack. If registers have already been assigned for some 4017 // eightbytes of such an argument, the assignments get reverted. 4018 if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) { 4019 FreeIntRegs -= NeededInt; 4020 FreeSSERegs -= NeededSSE; 4021 } else { 4022 it->info = getIndirectResult(it->type, FreeIntRegs); 4023 } 4024 } 4025 } 4026 4027 static Address EmitX86_64VAArgFromMemory(CodeGenFunction &CGF, 4028 Address VAListAddr, QualType Ty) { 4029 Address overflow_arg_area_p = 4030 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_p"); 4031 llvm::Value *overflow_arg_area = 4032 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area"); 4033 4034 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16 4035 // byte boundary if alignment needed by type exceeds 8 byte boundary. 4036 // It isn't stated explicitly in the standard, but in practice we use 4037 // alignment greater than 16 where necessary. 4038 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty); 4039 if (Align > CharUnits::fromQuantity(8)) { 4040 overflow_arg_area = emitRoundPointerUpToAlignment(CGF, overflow_arg_area, 4041 Align); 4042 } 4043 4044 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area. 4045 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty); 4046 llvm::Value *Res = 4047 CGF.Builder.CreateBitCast(overflow_arg_area, 4048 llvm::PointerType::getUnqual(LTy)); 4049 4050 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to: 4051 // l->overflow_arg_area + sizeof(type). 4052 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to 4053 // an 8 byte boundary. 4054 4055 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8; 4056 llvm::Value *Offset = 4057 llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7); 4058 overflow_arg_area = CGF.Builder.CreateGEP(CGF.Int8Ty, overflow_arg_area, 4059 Offset, "overflow_arg_area.next"); 4060 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p); 4061 4062 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type. 4063 return Address(Res, Align); 4064 } 4065 4066 Address X86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 4067 QualType Ty) const { 4068 // Assume that va_list type is correct; should be pointer to LLVM type: 4069 // struct { 4070 // i32 gp_offset; 4071 // i32 fp_offset; 4072 // i8* overflow_arg_area; 4073 // i8* reg_save_area; 4074 // }; 4075 unsigned neededInt, neededSSE; 4076 4077 Ty = getContext().getCanonicalType(Ty); 4078 ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE, 4079 /*isNamedArg*/false); 4080 4081 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed 4082 // in the registers. If not go to step 7. 4083 if (!neededInt && !neededSSE) 4084 return EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty); 4085 4086 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of 4087 // general purpose registers needed to pass type and num_fp to hold 4088 // the number of floating point registers needed. 4089 4090 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into 4091 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or 4092 // l->fp_offset > 304 - num_fp * 16 go to step 7. 4093 // 4094 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of 4095 // register save space). 4096 4097 llvm::Value *InRegs = nullptr; 4098 Address gp_offset_p = Address::invalid(), fp_offset_p = Address::invalid(); 4099 llvm::Value *gp_offset = nullptr, *fp_offset = nullptr; 4100 if (neededInt) { 4101 gp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "gp_offset_p"); 4102 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset"); 4103 InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8); 4104 InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp"); 4105 } 4106 4107 if (neededSSE) { 4108 fp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 1, "fp_offset_p"); 4109 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset"); 4110 llvm::Value *FitsInFP = 4111 llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16); 4112 FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp"); 4113 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP; 4114 } 4115 4116 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg"); 4117 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem"); 4118 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end"); 4119 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock); 4120 4121 // Emit code to load the value if it was passed in registers. 4122 4123 CGF.EmitBlock(InRegBlock); 4124 4125 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with 4126 // an offset of l->gp_offset and/or l->fp_offset. This may require 4127 // copying to a temporary location in case the parameter is passed 4128 // in different register classes or requires an alignment greater 4129 // than 8 for general purpose registers and 16 for XMM registers. 4130 // 4131 // FIXME: This really results in shameful code when we end up needing to 4132 // collect arguments from different places; often what should result in a 4133 // simple assembling of a structure from scattered addresses has many more 4134 // loads than necessary. Can we clean this up? 4135 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty); 4136 llvm::Value *RegSaveArea = CGF.Builder.CreateLoad( 4137 CGF.Builder.CreateStructGEP(VAListAddr, 3), "reg_save_area"); 4138 4139 Address RegAddr = Address::invalid(); 4140 if (neededInt && neededSSE) { 4141 // FIXME: Cleanup. 4142 assert(AI.isDirect() && "Unexpected ABI info for mixed regs"); 4143 llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType()); 4144 Address Tmp = CGF.CreateMemTemp(Ty); 4145 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST); 4146 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs"); 4147 llvm::Type *TyLo = ST->getElementType(0); 4148 llvm::Type *TyHi = ST->getElementType(1); 4149 assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) && 4150 "Unexpected ABI info for mixed regs"); 4151 llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo); 4152 llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi); 4153 llvm::Value *GPAddr = 4154 CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, gp_offset); 4155 llvm::Value *FPAddr = 4156 CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, fp_offset); 4157 llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr; 4158 llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr; 4159 4160 // Copy the first element. 4161 // FIXME: Our choice of alignment here and below is probably pessimistic. 4162 llvm::Value *V = CGF.Builder.CreateAlignedLoad( 4163 TyLo, CGF.Builder.CreateBitCast(RegLoAddr, PTyLo), 4164 CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyLo))); 4165 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0)); 4166 4167 // Copy the second element. 4168 V = CGF.Builder.CreateAlignedLoad( 4169 TyHi, CGF.Builder.CreateBitCast(RegHiAddr, PTyHi), 4170 CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyHi))); 4171 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1)); 4172 4173 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy); 4174 } else if (neededInt) { 4175 RegAddr = Address(CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, gp_offset), 4176 CharUnits::fromQuantity(8)); 4177 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy); 4178 4179 // Copy to a temporary if necessary to ensure the appropriate alignment. 4180 auto TInfo = getContext().getTypeInfoInChars(Ty); 4181 uint64_t TySize = TInfo.Width.getQuantity(); 4182 CharUnits TyAlign = TInfo.Align; 4183 4184 // Copy into a temporary if the type is more aligned than the 4185 // register save area. 4186 if (TyAlign.getQuantity() > 8) { 4187 Address Tmp = CGF.CreateMemTemp(Ty); 4188 CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, false); 4189 RegAddr = Tmp; 4190 } 4191 4192 } else if (neededSSE == 1) { 4193 RegAddr = Address(CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, fp_offset), 4194 CharUnits::fromQuantity(16)); 4195 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy); 4196 } else { 4197 assert(neededSSE == 2 && "Invalid number of needed registers!"); 4198 // SSE registers are spaced 16 bytes apart in the register save 4199 // area, we need to collect the two eightbytes together. 4200 // The ABI isn't explicit about this, but it seems reasonable 4201 // to assume that the slots are 16-byte aligned, since the stack is 4202 // naturally 16-byte aligned and the prologue is expected to store 4203 // all the SSE registers to the RSA. 4204 Address RegAddrLo = Address(CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, 4205 fp_offset), 4206 CharUnits::fromQuantity(16)); 4207 Address RegAddrHi = 4208 CGF.Builder.CreateConstInBoundsByteGEP(RegAddrLo, 4209 CharUnits::fromQuantity(16)); 4210 llvm::Type *ST = AI.canHaveCoerceToType() 4211 ? AI.getCoerceToType() 4212 : llvm::StructType::get(CGF.DoubleTy, CGF.DoubleTy); 4213 llvm::Value *V; 4214 Address Tmp = CGF.CreateMemTemp(Ty); 4215 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST); 4216 V = CGF.Builder.CreateLoad(CGF.Builder.CreateElementBitCast( 4217 RegAddrLo, ST->getStructElementType(0))); 4218 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0)); 4219 V = CGF.Builder.CreateLoad(CGF.Builder.CreateElementBitCast( 4220 RegAddrHi, ST->getStructElementType(1))); 4221 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1)); 4222 4223 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy); 4224 } 4225 4226 // AMD64-ABI 3.5.7p5: Step 5. Set: 4227 // l->gp_offset = l->gp_offset + num_gp * 8 4228 // l->fp_offset = l->fp_offset + num_fp * 16. 4229 if (neededInt) { 4230 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8); 4231 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset), 4232 gp_offset_p); 4233 } 4234 if (neededSSE) { 4235 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16); 4236 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset), 4237 fp_offset_p); 4238 } 4239 CGF.EmitBranch(ContBlock); 4240 4241 // Emit code to load the value if it was passed in memory. 4242 4243 CGF.EmitBlock(InMemBlock); 4244 Address MemAddr = EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty); 4245 4246 // Return the appropriate result. 4247 4248 CGF.EmitBlock(ContBlock); 4249 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, MemAddr, InMemBlock, 4250 "vaarg.addr"); 4251 return ResAddr; 4252 } 4253 4254 Address X86_64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr, 4255 QualType Ty) const { 4256 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is 4257 // not 1, 2, 4, or 8 bytes, must be passed by reference." 4258 uint64_t Width = getContext().getTypeSize(Ty); 4259 bool IsIndirect = Width > 64 || !llvm::isPowerOf2_64(Width); 4260 4261 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, 4262 CGF.getContext().getTypeInfoInChars(Ty), 4263 CharUnits::fromQuantity(8), 4264 /*allowHigherAlign*/ false); 4265 } 4266 4267 ABIArgInfo WinX86_64ABIInfo::reclassifyHvaArgForVectorCall( 4268 QualType Ty, unsigned &FreeSSERegs, const ABIArgInfo ¤t) const { 4269 const Type *Base = nullptr; 4270 uint64_t NumElts = 0; 4271 4272 if (!Ty->isBuiltinType() && !Ty->isVectorType() && 4273 isHomogeneousAggregate(Ty, Base, NumElts) && FreeSSERegs >= NumElts) { 4274 FreeSSERegs -= NumElts; 4275 return getDirectX86Hva(); 4276 } 4277 return current; 4278 } 4279 4280 ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, unsigned &FreeSSERegs, 4281 bool IsReturnType, bool IsVectorCall, 4282 bool IsRegCall) const { 4283 4284 if (Ty->isVoidType()) 4285 return ABIArgInfo::getIgnore(); 4286 4287 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 4288 Ty = EnumTy->getDecl()->getIntegerType(); 4289 4290 TypeInfo Info = getContext().getTypeInfo(Ty); 4291 uint64_t Width = Info.Width; 4292 CharUnits Align = getContext().toCharUnitsFromBits(Info.Align); 4293 4294 const RecordType *RT = Ty->getAs<RecordType>(); 4295 if (RT) { 4296 if (!IsReturnType) { 4297 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI())) 4298 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 4299 } 4300 4301 if (RT->getDecl()->hasFlexibleArrayMember()) 4302 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 4303 4304 } 4305 4306 const Type *Base = nullptr; 4307 uint64_t NumElts = 0; 4308 // vectorcall adds the concept of a homogenous vector aggregate, similar to 4309 // other targets. 4310 if ((IsVectorCall || IsRegCall) && 4311 isHomogeneousAggregate(Ty, Base, NumElts)) { 4312 if (IsRegCall) { 4313 if (FreeSSERegs >= NumElts) { 4314 FreeSSERegs -= NumElts; 4315 if (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType()) 4316 return ABIArgInfo::getDirect(); 4317 return ABIArgInfo::getExpand(); 4318 } 4319 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false); 4320 } else if (IsVectorCall) { 4321 if (FreeSSERegs >= NumElts && 4322 (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())) { 4323 FreeSSERegs -= NumElts; 4324 return ABIArgInfo::getDirect(); 4325 } else if (IsReturnType) { 4326 return ABIArgInfo::getExpand(); 4327 } else if (!Ty->isBuiltinType() && !Ty->isVectorType()) { 4328 // HVAs are delayed and reclassified in the 2nd step. 4329 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false); 4330 } 4331 } 4332 } 4333 4334 if (Ty->isMemberPointerType()) { 4335 // If the member pointer is represented by an LLVM int or ptr, pass it 4336 // directly. 4337 llvm::Type *LLTy = CGT.ConvertType(Ty); 4338 if (LLTy->isPointerTy() || LLTy->isIntegerTy()) 4339 return ABIArgInfo::getDirect(); 4340 } 4341 4342 if (RT || Ty->isAnyComplexType() || Ty->isMemberPointerType()) { 4343 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is 4344 // not 1, 2, 4, or 8 bytes, must be passed by reference." 4345 if (Width > 64 || !llvm::isPowerOf2_64(Width)) 4346 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 4347 4348 // Otherwise, coerce it to a small integer. 4349 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Width)); 4350 } 4351 4352 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) { 4353 switch (BT->getKind()) { 4354 case BuiltinType::Bool: 4355 // Bool type is always extended to the ABI, other builtin types are not 4356 // extended. 4357 return ABIArgInfo::getExtend(Ty); 4358 4359 case BuiltinType::LongDouble: 4360 // Mingw64 GCC uses the old 80 bit extended precision floating point 4361 // unit. It passes them indirectly through memory. 4362 if (IsMingw64) { 4363 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat(); 4364 if (LDF == &llvm::APFloat::x87DoubleExtended()) 4365 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false); 4366 } 4367 break; 4368 4369 case BuiltinType::Int128: 4370 case BuiltinType::UInt128: 4371 // If it's a parameter type, the normal ABI rule is that arguments larger 4372 // than 8 bytes are passed indirectly. GCC follows it. We follow it too, 4373 // even though it isn't particularly efficient. 4374 if (!IsReturnType) 4375 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false); 4376 4377 // Mingw64 GCC returns i128 in XMM0. Coerce to v2i64 to handle that. 4378 // Clang matches them for compatibility. 4379 return ABIArgInfo::getDirect(llvm::FixedVectorType::get( 4380 llvm::Type::getInt64Ty(getVMContext()), 2)); 4381 4382 default: 4383 break; 4384 } 4385 } 4386 4387 if (Ty->isExtIntType()) { 4388 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is 4389 // not 1, 2, 4, or 8 bytes, must be passed by reference." 4390 // However, non-power-of-two _ExtInts will be passed as 1,2,4 or 8 bytes 4391 // anyway as long is it fits in them, so we don't have to check the power of 4392 // 2. 4393 if (Width <= 64) 4394 return ABIArgInfo::getDirect(); 4395 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false); 4396 } 4397 4398 return ABIArgInfo::getDirect(); 4399 } 4400 4401 void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const { 4402 const unsigned CC = FI.getCallingConvention(); 4403 bool IsVectorCall = CC == llvm::CallingConv::X86_VectorCall; 4404 bool IsRegCall = CC == llvm::CallingConv::X86_RegCall; 4405 4406 // If __attribute__((sysv_abi)) is in use, use the SysV argument 4407 // classification rules. 4408 if (CC == llvm::CallingConv::X86_64_SysV) { 4409 X86_64ABIInfo SysVABIInfo(CGT, AVXLevel); 4410 SysVABIInfo.computeInfo(FI); 4411 return; 4412 } 4413 4414 unsigned FreeSSERegs = 0; 4415 if (IsVectorCall) { 4416 // We can use up to 4 SSE return registers with vectorcall. 4417 FreeSSERegs = 4; 4418 } else if (IsRegCall) { 4419 // RegCall gives us 16 SSE registers. 4420 FreeSSERegs = 16; 4421 } 4422 4423 if (!getCXXABI().classifyReturnType(FI)) 4424 FI.getReturnInfo() = classify(FI.getReturnType(), FreeSSERegs, true, 4425 IsVectorCall, IsRegCall); 4426 4427 if (IsVectorCall) { 4428 // We can use up to 6 SSE register parameters with vectorcall. 4429 FreeSSERegs = 6; 4430 } else if (IsRegCall) { 4431 // RegCall gives us 16 SSE registers, we can reuse the return registers. 4432 FreeSSERegs = 16; 4433 } 4434 4435 unsigned ArgNum = 0; 4436 unsigned ZeroSSERegs = 0; 4437 for (auto &I : FI.arguments()) { 4438 // Vectorcall in x64 only permits the first 6 arguments to be passed as 4439 // XMM/YMM registers. After the sixth argument, pretend no vector 4440 // registers are left. 4441 unsigned *MaybeFreeSSERegs = 4442 (IsVectorCall && ArgNum >= 6) ? &ZeroSSERegs : &FreeSSERegs; 4443 I.info = 4444 classify(I.type, *MaybeFreeSSERegs, false, IsVectorCall, IsRegCall); 4445 ++ArgNum; 4446 } 4447 4448 if (IsVectorCall) { 4449 // For vectorcall, assign aggregate HVAs to any free vector registers in a 4450 // second pass. 4451 for (auto &I : FI.arguments()) 4452 I.info = reclassifyHvaArgForVectorCall(I.type, FreeSSERegs, I.info); 4453 } 4454 } 4455 4456 Address WinX86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 4457 QualType Ty) const { 4458 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is 4459 // not 1, 2, 4, or 8 bytes, must be passed by reference." 4460 uint64_t Width = getContext().getTypeSize(Ty); 4461 bool IsIndirect = Width > 64 || !llvm::isPowerOf2_64(Width); 4462 4463 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, 4464 CGF.getContext().getTypeInfoInChars(Ty), 4465 CharUnits::fromQuantity(8), 4466 /*allowHigherAlign*/ false); 4467 } 4468 4469 static bool PPC_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 4470 llvm::Value *Address, bool Is64Bit, 4471 bool IsAIX) { 4472 // This is calculated from the LLVM and GCC tables and verified 4473 // against gcc output. AFAIK all PPC ABIs use the same encoding. 4474 4475 CodeGen::CGBuilderTy &Builder = CGF.Builder; 4476 4477 llvm::IntegerType *i8 = CGF.Int8Ty; 4478 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4); 4479 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8); 4480 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16); 4481 4482 // 0-31: r0-31, the 4-byte or 8-byte general-purpose registers 4483 AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 0, 31); 4484 4485 // 32-63: fp0-31, the 8-byte floating-point registers 4486 AssignToArrayRange(Builder, Address, Eight8, 32, 63); 4487 4488 // 64-67 are various 4-byte or 8-byte special-purpose registers: 4489 // 64: mq 4490 // 65: lr 4491 // 66: ctr 4492 // 67: ap 4493 AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 64, 67); 4494 4495 // 68-76 are various 4-byte special-purpose registers: 4496 // 68-75 cr0-7 4497 // 76: xer 4498 AssignToArrayRange(Builder, Address, Four8, 68, 76); 4499 4500 // 77-108: v0-31, the 16-byte vector registers 4501 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108); 4502 4503 // 109: vrsave 4504 // 110: vscr 4505 AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 109, 110); 4506 4507 // AIX does not utilize the rest of the registers. 4508 if (IsAIX) 4509 return false; 4510 4511 // 111: spe_acc 4512 // 112: spefscr 4513 // 113: sfp 4514 AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 111, 113); 4515 4516 if (!Is64Bit) 4517 return false; 4518 4519 // TODO: Need to verify if these registers are used on 64 bit AIX with Power8 4520 // or above CPU. 4521 // 64-bit only registers: 4522 // 114: tfhar 4523 // 115: tfiar 4524 // 116: texasr 4525 AssignToArrayRange(Builder, Address, Eight8, 114, 116); 4526 4527 return false; 4528 } 4529 4530 // AIX 4531 namespace { 4532 /// AIXABIInfo - The AIX XCOFF ABI information. 4533 class AIXABIInfo : public ABIInfo { 4534 const bool Is64Bit; 4535 const unsigned PtrByteSize; 4536 CharUnits getParamTypeAlignment(QualType Ty) const; 4537 4538 public: 4539 AIXABIInfo(CodeGen::CodeGenTypes &CGT, bool Is64Bit) 4540 : ABIInfo(CGT), Is64Bit(Is64Bit), PtrByteSize(Is64Bit ? 8 : 4) {} 4541 4542 bool isPromotableTypeForABI(QualType Ty) const; 4543 4544 ABIArgInfo classifyReturnType(QualType RetTy) const; 4545 ABIArgInfo classifyArgumentType(QualType Ty) const; 4546 4547 void computeInfo(CGFunctionInfo &FI) const override { 4548 if (!getCXXABI().classifyReturnType(FI)) 4549 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 4550 4551 for (auto &I : FI.arguments()) 4552 I.info = classifyArgumentType(I.type); 4553 } 4554 4555 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 4556 QualType Ty) const override; 4557 }; 4558 4559 class AIXTargetCodeGenInfo : public TargetCodeGenInfo { 4560 const bool Is64Bit; 4561 4562 public: 4563 AIXTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool Is64Bit) 4564 : TargetCodeGenInfo(std::make_unique<AIXABIInfo>(CGT, Is64Bit)), 4565 Is64Bit(Is64Bit) {} 4566 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 4567 return 1; // r1 is the dedicated stack pointer 4568 } 4569 4570 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 4571 llvm::Value *Address) const override; 4572 }; 4573 } // namespace 4574 4575 // Return true if the ABI requires Ty to be passed sign- or zero- 4576 // extended to 32/64 bits. 4577 bool AIXABIInfo::isPromotableTypeForABI(QualType Ty) const { 4578 // Treat an enum type as its underlying type. 4579 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 4580 Ty = EnumTy->getDecl()->getIntegerType(); 4581 4582 // Promotable integer types are required to be promoted by the ABI. 4583 if (Ty->isPromotableIntegerType()) 4584 return true; 4585 4586 if (!Is64Bit) 4587 return false; 4588 4589 // For 64 bit mode, in addition to the usual promotable integer types, we also 4590 // need to extend all 32-bit types, since the ABI requires promotion to 64 4591 // bits. 4592 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) 4593 switch (BT->getKind()) { 4594 case BuiltinType::Int: 4595 case BuiltinType::UInt: 4596 return true; 4597 default: 4598 break; 4599 } 4600 4601 return false; 4602 } 4603 4604 ABIArgInfo AIXABIInfo::classifyReturnType(QualType RetTy) const { 4605 if (RetTy->isAnyComplexType()) 4606 return ABIArgInfo::getDirect(); 4607 4608 if (RetTy->isVectorType()) 4609 return ABIArgInfo::getDirect(); 4610 4611 if (RetTy->isVoidType()) 4612 return ABIArgInfo::getIgnore(); 4613 4614 if (isAggregateTypeForABI(RetTy)) 4615 return getNaturalAlignIndirect(RetTy); 4616 4617 return (isPromotableTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy) 4618 : ABIArgInfo::getDirect()); 4619 } 4620 4621 ABIArgInfo AIXABIInfo::classifyArgumentType(QualType Ty) const { 4622 Ty = useFirstFieldIfTransparentUnion(Ty); 4623 4624 if (Ty->isAnyComplexType()) 4625 return ABIArgInfo::getDirect(); 4626 4627 if (Ty->isVectorType()) 4628 return ABIArgInfo::getDirect(); 4629 4630 if (isAggregateTypeForABI(Ty)) { 4631 // Records with non-trivial destructors/copy-constructors should not be 4632 // passed by value. 4633 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 4634 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 4635 4636 CharUnits CCAlign = getParamTypeAlignment(Ty); 4637 CharUnits TyAlign = getContext().getTypeAlignInChars(Ty); 4638 4639 return ABIArgInfo::getIndirect(CCAlign, /*ByVal*/ true, 4640 /*Realign*/ TyAlign > CCAlign); 4641 } 4642 4643 return (isPromotableTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty) 4644 : ABIArgInfo::getDirect()); 4645 } 4646 4647 CharUnits AIXABIInfo::getParamTypeAlignment(QualType Ty) const { 4648 // Complex types are passed just like their elements. 4649 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) 4650 Ty = CTy->getElementType(); 4651 4652 if (Ty->isVectorType()) 4653 return CharUnits::fromQuantity(16); 4654 4655 // If the structure contains a vector type, the alignment is 16. 4656 if (isRecordWithSIMDVectorType(getContext(), Ty)) 4657 return CharUnits::fromQuantity(16); 4658 4659 return CharUnits::fromQuantity(PtrByteSize); 4660 } 4661 4662 Address AIXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 4663 QualType Ty) const { 4664 4665 auto TypeInfo = getContext().getTypeInfoInChars(Ty); 4666 TypeInfo.Align = getParamTypeAlignment(Ty); 4667 4668 CharUnits SlotSize = CharUnits::fromQuantity(PtrByteSize); 4669 4670 // If we have a complex type and the base type is smaller than the register 4671 // size, the ABI calls for the real and imaginary parts to be right-adjusted 4672 // in separate words in 32bit mode or doublewords in 64bit mode. However, 4673 // Clang expects us to produce a pointer to a structure with the two parts 4674 // packed tightly. So generate loads of the real and imaginary parts relative 4675 // to the va_list pointer, and store them to a temporary structure. We do the 4676 // same as the PPC64ABI here. 4677 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) { 4678 CharUnits EltSize = TypeInfo.Width / 2; 4679 if (EltSize < SlotSize) 4680 return complexTempStructure(CGF, VAListAddr, Ty, SlotSize, EltSize, CTy); 4681 } 4682 4683 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false, TypeInfo, 4684 SlotSize, /*AllowHigher*/ true); 4685 } 4686 4687 bool AIXTargetCodeGenInfo::initDwarfEHRegSizeTable( 4688 CodeGen::CodeGenFunction &CGF, llvm::Value *Address) const { 4689 return PPC_initDwarfEHRegSizeTable(CGF, Address, Is64Bit, /*IsAIX*/ true); 4690 } 4691 4692 // PowerPC-32 4693 namespace { 4694 /// PPC32_SVR4_ABIInfo - The 32-bit PowerPC ELF (SVR4) ABI information. 4695 class PPC32_SVR4_ABIInfo : public DefaultABIInfo { 4696 bool IsSoftFloatABI; 4697 bool IsRetSmallStructInRegABI; 4698 4699 CharUnits getParamTypeAlignment(QualType Ty) const; 4700 4701 public: 4702 PPC32_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, bool SoftFloatABI, 4703 bool RetSmallStructInRegABI) 4704 : DefaultABIInfo(CGT), IsSoftFloatABI(SoftFloatABI), 4705 IsRetSmallStructInRegABI(RetSmallStructInRegABI) {} 4706 4707 ABIArgInfo classifyReturnType(QualType RetTy) const; 4708 4709 void computeInfo(CGFunctionInfo &FI) const override { 4710 if (!getCXXABI().classifyReturnType(FI)) 4711 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 4712 for (auto &I : FI.arguments()) 4713 I.info = classifyArgumentType(I.type); 4714 } 4715 4716 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 4717 QualType Ty) const override; 4718 }; 4719 4720 class PPC32TargetCodeGenInfo : public TargetCodeGenInfo { 4721 public: 4722 PPC32TargetCodeGenInfo(CodeGenTypes &CGT, bool SoftFloatABI, 4723 bool RetSmallStructInRegABI) 4724 : TargetCodeGenInfo(std::make_unique<PPC32_SVR4_ABIInfo>( 4725 CGT, SoftFloatABI, RetSmallStructInRegABI)) {} 4726 4727 static bool isStructReturnInRegABI(const llvm::Triple &Triple, 4728 const CodeGenOptions &Opts); 4729 4730 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 4731 // This is recovered from gcc output. 4732 return 1; // r1 is the dedicated stack pointer 4733 } 4734 4735 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 4736 llvm::Value *Address) const override; 4737 }; 4738 } 4739 4740 CharUnits PPC32_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const { 4741 // Complex types are passed just like their elements. 4742 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) 4743 Ty = CTy->getElementType(); 4744 4745 if (Ty->isVectorType()) 4746 return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16 4747 : 4); 4748 4749 // For single-element float/vector structs, we consider the whole type 4750 // to have the same alignment requirements as its single element. 4751 const Type *AlignTy = nullptr; 4752 if (const Type *EltType = isSingleElementStruct(Ty, getContext())) { 4753 const BuiltinType *BT = EltType->getAs<BuiltinType>(); 4754 if ((EltType->isVectorType() && getContext().getTypeSize(EltType) == 128) || 4755 (BT && BT->isFloatingPoint())) 4756 AlignTy = EltType; 4757 } 4758 4759 if (AlignTy) 4760 return CharUnits::fromQuantity(AlignTy->isVectorType() ? 16 : 4); 4761 return CharUnits::fromQuantity(4); 4762 } 4763 4764 ABIArgInfo PPC32_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const { 4765 uint64_t Size; 4766 4767 // -msvr4-struct-return puts small aggregates in GPR3 and GPR4. 4768 if (isAggregateTypeForABI(RetTy) && IsRetSmallStructInRegABI && 4769 (Size = getContext().getTypeSize(RetTy)) <= 64) { 4770 // System V ABI (1995), page 3-22, specified: 4771 // > A structure or union whose size is less than or equal to 8 bytes 4772 // > shall be returned in r3 and r4, as if it were first stored in the 4773 // > 8-byte aligned memory area and then the low addressed word were 4774 // > loaded into r3 and the high-addressed word into r4. Bits beyond 4775 // > the last member of the structure or union are not defined. 4776 // 4777 // GCC for big-endian PPC32 inserts the pad before the first member, 4778 // not "beyond the last member" of the struct. To stay compatible 4779 // with GCC, we coerce the struct to an integer of the same size. 4780 // LLVM will extend it and return i32 in r3, or i64 in r3:r4. 4781 if (Size == 0) 4782 return ABIArgInfo::getIgnore(); 4783 else { 4784 llvm::Type *CoerceTy = llvm::Type::getIntNTy(getVMContext(), Size); 4785 return ABIArgInfo::getDirect(CoerceTy); 4786 } 4787 } 4788 4789 return DefaultABIInfo::classifyReturnType(RetTy); 4790 } 4791 4792 // TODO: this implementation is now likely redundant with 4793 // DefaultABIInfo::EmitVAArg. 4794 Address PPC32_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAList, 4795 QualType Ty) const { 4796 if (getTarget().getTriple().isOSDarwin()) { 4797 auto TI = getContext().getTypeInfoInChars(Ty); 4798 TI.Align = getParamTypeAlignment(Ty); 4799 4800 CharUnits SlotSize = CharUnits::fromQuantity(4); 4801 return emitVoidPtrVAArg(CGF, VAList, Ty, 4802 classifyArgumentType(Ty).isIndirect(), TI, SlotSize, 4803 /*AllowHigherAlign=*/true); 4804 } 4805 4806 const unsigned OverflowLimit = 8; 4807 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) { 4808 // TODO: Implement this. For now ignore. 4809 (void)CTy; 4810 return Address::invalid(); // FIXME? 4811 } 4812 4813 // struct __va_list_tag { 4814 // unsigned char gpr; 4815 // unsigned char fpr; 4816 // unsigned short reserved; 4817 // void *overflow_arg_area; 4818 // void *reg_save_area; 4819 // }; 4820 4821 bool isI64 = Ty->isIntegerType() && getContext().getTypeSize(Ty) == 64; 4822 bool isInt = !Ty->isFloatingType(); 4823 bool isF64 = Ty->isFloatingType() && getContext().getTypeSize(Ty) == 64; 4824 4825 // All aggregates are passed indirectly? That doesn't seem consistent 4826 // with the argument-lowering code. 4827 bool isIndirect = isAggregateTypeForABI(Ty); 4828 4829 CGBuilderTy &Builder = CGF.Builder; 4830 4831 // The calling convention either uses 1-2 GPRs or 1 FPR. 4832 Address NumRegsAddr = Address::invalid(); 4833 if (isInt || IsSoftFloatABI) { 4834 NumRegsAddr = Builder.CreateStructGEP(VAList, 0, "gpr"); 4835 } else { 4836 NumRegsAddr = Builder.CreateStructGEP(VAList, 1, "fpr"); 4837 } 4838 4839 llvm::Value *NumRegs = Builder.CreateLoad(NumRegsAddr, "numUsedRegs"); 4840 4841 // "Align" the register count when TY is i64. 4842 if (isI64 || (isF64 && IsSoftFloatABI)) { 4843 NumRegs = Builder.CreateAdd(NumRegs, Builder.getInt8(1)); 4844 NumRegs = Builder.CreateAnd(NumRegs, Builder.getInt8((uint8_t) ~1U)); 4845 } 4846 4847 llvm::Value *CC = 4848 Builder.CreateICmpULT(NumRegs, Builder.getInt8(OverflowLimit), "cond"); 4849 4850 llvm::BasicBlock *UsingRegs = CGF.createBasicBlock("using_regs"); 4851 llvm::BasicBlock *UsingOverflow = CGF.createBasicBlock("using_overflow"); 4852 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont"); 4853 4854 Builder.CreateCondBr(CC, UsingRegs, UsingOverflow); 4855 4856 llvm::Type *DirectTy = CGF.ConvertType(Ty); 4857 if (isIndirect) DirectTy = DirectTy->getPointerTo(0); 4858 4859 // Case 1: consume registers. 4860 Address RegAddr = Address::invalid(); 4861 { 4862 CGF.EmitBlock(UsingRegs); 4863 4864 Address RegSaveAreaPtr = Builder.CreateStructGEP(VAList, 4); 4865 RegAddr = Address(Builder.CreateLoad(RegSaveAreaPtr), 4866 CharUnits::fromQuantity(8)); 4867 assert(RegAddr.getElementType() == CGF.Int8Ty); 4868 4869 // Floating-point registers start after the general-purpose registers. 4870 if (!(isInt || IsSoftFloatABI)) { 4871 RegAddr = Builder.CreateConstInBoundsByteGEP(RegAddr, 4872 CharUnits::fromQuantity(32)); 4873 } 4874 4875 // Get the address of the saved value by scaling the number of 4876 // registers we've used by the number of 4877 CharUnits RegSize = CharUnits::fromQuantity((isInt || IsSoftFloatABI) ? 4 : 8); 4878 llvm::Value *RegOffset = 4879 Builder.CreateMul(NumRegs, Builder.getInt8(RegSize.getQuantity())); 4880 RegAddr = Address(Builder.CreateInBoundsGEP(CGF.Int8Ty, 4881 RegAddr.getPointer(), RegOffset), 4882 RegAddr.getAlignment().alignmentOfArrayElement(RegSize)); 4883 RegAddr = Builder.CreateElementBitCast(RegAddr, DirectTy); 4884 4885 // Increase the used-register count. 4886 NumRegs = 4887 Builder.CreateAdd(NumRegs, 4888 Builder.getInt8((isI64 || (isF64 && IsSoftFloatABI)) ? 2 : 1)); 4889 Builder.CreateStore(NumRegs, NumRegsAddr); 4890 4891 CGF.EmitBranch(Cont); 4892 } 4893 4894 // Case 2: consume space in the overflow area. 4895 Address MemAddr = Address::invalid(); 4896 { 4897 CGF.EmitBlock(UsingOverflow); 4898 4899 Builder.CreateStore(Builder.getInt8(OverflowLimit), NumRegsAddr); 4900 4901 // Everything in the overflow area is rounded up to a size of at least 4. 4902 CharUnits OverflowAreaAlign = CharUnits::fromQuantity(4); 4903 4904 CharUnits Size; 4905 if (!isIndirect) { 4906 auto TypeInfo = CGF.getContext().getTypeInfoInChars(Ty); 4907 Size = TypeInfo.Width.alignTo(OverflowAreaAlign); 4908 } else { 4909 Size = CGF.getPointerSize(); 4910 } 4911 4912 Address OverflowAreaAddr = Builder.CreateStructGEP(VAList, 3); 4913 Address OverflowArea(Builder.CreateLoad(OverflowAreaAddr, "argp.cur"), 4914 OverflowAreaAlign); 4915 // Round up address of argument to alignment 4916 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty); 4917 if (Align > OverflowAreaAlign) { 4918 llvm::Value *Ptr = OverflowArea.getPointer(); 4919 OverflowArea = Address(emitRoundPointerUpToAlignment(CGF, Ptr, Align), 4920 Align); 4921 } 4922 4923 MemAddr = Builder.CreateElementBitCast(OverflowArea, DirectTy); 4924 4925 // Increase the overflow area. 4926 OverflowArea = Builder.CreateConstInBoundsByteGEP(OverflowArea, Size); 4927 Builder.CreateStore(OverflowArea.getPointer(), OverflowAreaAddr); 4928 CGF.EmitBranch(Cont); 4929 } 4930 4931 CGF.EmitBlock(Cont); 4932 4933 // Merge the cases with a phi. 4934 Address Result = emitMergePHI(CGF, RegAddr, UsingRegs, MemAddr, UsingOverflow, 4935 "vaarg.addr"); 4936 4937 // Load the pointer if the argument was passed indirectly. 4938 if (isIndirect) { 4939 Result = Address(Builder.CreateLoad(Result, "aggr"), 4940 getContext().getTypeAlignInChars(Ty)); 4941 } 4942 4943 return Result; 4944 } 4945 4946 bool PPC32TargetCodeGenInfo::isStructReturnInRegABI( 4947 const llvm::Triple &Triple, const CodeGenOptions &Opts) { 4948 assert(Triple.isPPC32()); 4949 4950 switch (Opts.getStructReturnConvention()) { 4951 case CodeGenOptions::SRCK_Default: 4952 break; 4953 case CodeGenOptions::SRCK_OnStack: // -maix-struct-return 4954 return false; 4955 case CodeGenOptions::SRCK_InRegs: // -msvr4-struct-return 4956 return true; 4957 } 4958 4959 if (Triple.isOSBinFormatELF() && !Triple.isOSLinux()) 4960 return true; 4961 4962 return false; 4963 } 4964 4965 bool 4966 PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 4967 llvm::Value *Address) const { 4968 return PPC_initDwarfEHRegSizeTable(CGF, Address, /*Is64Bit*/ false, 4969 /*IsAIX*/ false); 4970 } 4971 4972 // PowerPC-64 4973 4974 namespace { 4975 /// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information. 4976 class PPC64_SVR4_ABIInfo : public SwiftABIInfo { 4977 public: 4978 enum ABIKind { 4979 ELFv1 = 0, 4980 ELFv2 4981 }; 4982 4983 private: 4984 static const unsigned GPRBits = 64; 4985 ABIKind Kind; 4986 bool IsSoftFloatABI; 4987 4988 public: 4989 PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind, 4990 bool SoftFloatABI) 4991 : SwiftABIInfo(CGT), Kind(Kind), IsSoftFloatABI(SoftFloatABI) {} 4992 4993 bool isPromotableTypeForABI(QualType Ty) const; 4994 CharUnits getParamTypeAlignment(QualType Ty) const; 4995 4996 ABIArgInfo classifyReturnType(QualType RetTy) const; 4997 ABIArgInfo classifyArgumentType(QualType Ty) const; 4998 4999 bool isHomogeneousAggregateBaseType(QualType Ty) const override; 5000 bool isHomogeneousAggregateSmallEnough(const Type *Ty, 5001 uint64_t Members) const override; 5002 5003 // TODO: We can add more logic to computeInfo to improve performance. 5004 // Example: For aggregate arguments that fit in a register, we could 5005 // use getDirectInReg (as is done below for structs containing a single 5006 // floating-point value) to avoid pushing them to memory on function 5007 // entry. This would require changing the logic in PPCISelLowering 5008 // when lowering the parameters in the caller and args in the callee. 5009 void computeInfo(CGFunctionInfo &FI) const override { 5010 if (!getCXXABI().classifyReturnType(FI)) 5011 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 5012 for (auto &I : FI.arguments()) { 5013 // We rely on the default argument classification for the most part. 5014 // One exception: An aggregate containing a single floating-point 5015 // or vector item must be passed in a register if one is available. 5016 const Type *T = isSingleElementStruct(I.type, getContext()); 5017 if (T) { 5018 const BuiltinType *BT = T->getAs<BuiltinType>(); 5019 if ((T->isVectorType() && getContext().getTypeSize(T) == 128) || 5020 (BT && BT->isFloatingPoint())) { 5021 QualType QT(T, 0); 5022 I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT)); 5023 continue; 5024 } 5025 } 5026 I.info = classifyArgumentType(I.type); 5027 } 5028 } 5029 5030 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 5031 QualType Ty) const override; 5032 5033 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars, 5034 bool asReturnValue) const override { 5035 return occupiesMoreThan(CGT, scalars, /*total*/ 4); 5036 } 5037 5038 bool isSwiftErrorInRegister() const override { 5039 return false; 5040 } 5041 }; 5042 5043 class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo { 5044 5045 public: 5046 PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT, 5047 PPC64_SVR4_ABIInfo::ABIKind Kind, 5048 bool SoftFloatABI) 5049 : TargetCodeGenInfo( 5050 std::make_unique<PPC64_SVR4_ABIInfo>(CGT, Kind, SoftFloatABI)) {} 5051 5052 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 5053 // This is recovered from gcc output. 5054 return 1; // r1 is the dedicated stack pointer 5055 } 5056 5057 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 5058 llvm::Value *Address) const override; 5059 }; 5060 5061 class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo { 5062 public: 5063 PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {} 5064 5065 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 5066 // This is recovered from gcc output. 5067 return 1; // r1 is the dedicated stack pointer 5068 } 5069 5070 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 5071 llvm::Value *Address) const override; 5072 }; 5073 5074 } 5075 5076 // Return true if the ABI requires Ty to be passed sign- or zero- 5077 // extended to 64 bits. 5078 bool 5079 PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const { 5080 // Treat an enum type as its underlying type. 5081 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 5082 Ty = EnumTy->getDecl()->getIntegerType(); 5083 5084 // Promotable integer types are required to be promoted by the ABI. 5085 if (isPromotableIntegerTypeForABI(Ty)) 5086 return true; 5087 5088 // In addition to the usual promotable integer types, we also need to 5089 // extend all 32-bit types, since the ABI requires promotion to 64 bits. 5090 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) 5091 switch (BT->getKind()) { 5092 case BuiltinType::Int: 5093 case BuiltinType::UInt: 5094 return true; 5095 default: 5096 break; 5097 } 5098 5099 if (const auto *EIT = Ty->getAs<ExtIntType>()) 5100 if (EIT->getNumBits() < 64) 5101 return true; 5102 5103 return false; 5104 } 5105 5106 /// isAlignedParamType - Determine whether a type requires 16-byte or 5107 /// higher alignment in the parameter area. Always returns at least 8. 5108 CharUnits PPC64_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const { 5109 // Complex types are passed just like their elements. 5110 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) 5111 Ty = CTy->getElementType(); 5112 5113 // Only vector types of size 16 bytes need alignment (larger types are 5114 // passed via reference, smaller types are not aligned). 5115 if (Ty->isVectorType()) { 5116 return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16 : 8); 5117 } else if (Ty->isRealFloatingType() && 5118 &getContext().getFloatTypeSemantics(Ty) == 5119 &llvm::APFloat::IEEEquad()) { 5120 // According to ABI document section 'Optional Save Areas': If extended 5121 // precision floating-point values in IEEE BINARY 128 QUADRUPLE PRECISION 5122 // format are supported, map them to a single quadword, quadword aligned. 5123 return CharUnits::fromQuantity(16); 5124 } 5125 5126 // For single-element float/vector structs, we consider the whole type 5127 // to have the same alignment requirements as its single element. 5128 const Type *AlignAsType = nullptr; 5129 const Type *EltType = isSingleElementStruct(Ty, getContext()); 5130 if (EltType) { 5131 const BuiltinType *BT = EltType->getAs<BuiltinType>(); 5132 if ((EltType->isVectorType() && getContext().getTypeSize(EltType) == 128) || 5133 (BT && BT->isFloatingPoint())) 5134 AlignAsType = EltType; 5135 } 5136 5137 // Likewise for ELFv2 homogeneous aggregates. 5138 const Type *Base = nullptr; 5139 uint64_t Members = 0; 5140 if (!AlignAsType && Kind == ELFv2 && 5141 isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members)) 5142 AlignAsType = Base; 5143 5144 // With special case aggregates, only vector base types need alignment. 5145 if (AlignAsType) { 5146 return CharUnits::fromQuantity(AlignAsType->isVectorType() ? 16 : 8); 5147 } 5148 5149 // Otherwise, we only need alignment for any aggregate type that 5150 // has an alignment requirement of >= 16 bytes. 5151 if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128) { 5152 return CharUnits::fromQuantity(16); 5153 } 5154 5155 return CharUnits::fromQuantity(8); 5156 } 5157 5158 /// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous 5159 /// aggregate. Base is set to the base element type, and Members is set 5160 /// to the number of base elements. 5161 bool ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base, 5162 uint64_t &Members) const { 5163 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) { 5164 uint64_t NElements = AT->getSize().getZExtValue(); 5165 if (NElements == 0) 5166 return false; 5167 if (!isHomogeneousAggregate(AT->getElementType(), Base, Members)) 5168 return false; 5169 Members *= NElements; 5170 } else if (const RecordType *RT = Ty->getAs<RecordType>()) { 5171 const RecordDecl *RD = RT->getDecl(); 5172 if (RD->hasFlexibleArrayMember()) 5173 return false; 5174 5175 Members = 0; 5176 5177 // If this is a C++ record, check the properties of the record such as 5178 // bases and ABI specific restrictions 5179 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 5180 if (!getCXXABI().isPermittedToBeHomogeneousAggregate(CXXRD)) 5181 return false; 5182 5183 for (const auto &I : CXXRD->bases()) { 5184 // Ignore empty records. 5185 if (isEmptyRecord(getContext(), I.getType(), true)) 5186 continue; 5187 5188 uint64_t FldMembers; 5189 if (!isHomogeneousAggregate(I.getType(), Base, FldMembers)) 5190 return false; 5191 5192 Members += FldMembers; 5193 } 5194 } 5195 5196 for (const auto *FD : RD->fields()) { 5197 // Ignore (non-zero arrays of) empty records. 5198 QualType FT = FD->getType(); 5199 while (const ConstantArrayType *AT = 5200 getContext().getAsConstantArrayType(FT)) { 5201 if (AT->getSize().getZExtValue() == 0) 5202 return false; 5203 FT = AT->getElementType(); 5204 } 5205 if (isEmptyRecord(getContext(), FT, true)) 5206 continue; 5207 5208 // For compatibility with GCC, ignore empty bitfields in C++ mode. 5209 if (getContext().getLangOpts().CPlusPlus && 5210 FD->isZeroLengthBitField(getContext())) 5211 continue; 5212 5213 uint64_t FldMembers; 5214 if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers)) 5215 return false; 5216 5217 Members = (RD->isUnion() ? 5218 std::max(Members, FldMembers) : Members + FldMembers); 5219 } 5220 5221 if (!Base) 5222 return false; 5223 5224 // Ensure there is no padding. 5225 if (getContext().getTypeSize(Base) * Members != 5226 getContext().getTypeSize(Ty)) 5227 return false; 5228 } else { 5229 Members = 1; 5230 if (const ComplexType *CT = Ty->getAs<ComplexType>()) { 5231 Members = 2; 5232 Ty = CT->getElementType(); 5233 } 5234 5235 // Most ABIs only support float, double, and some vector type widths. 5236 if (!isHomogeneousAggregateBaseType(Ty)) 5237 return false; 5238 5239 // The base type must be the same for all members. Types that 5240 // agree in both total size and mode (float vs. vector) are 5241 // treated as being equivalent here. 5242 const Type *TyPtr = Ty.getTypePtr(); 5243 if (!Base) { 5244 Base = TyPtr; 5245 // If it's a non-power-of-2 vector, its size is already a power-of-2, 5246 // so make sure to widen it explicitly. 5247 if (const VectorType *VT = Base->getAs<VectorType>()) { 5248 QualType EltTy = VT->getElementType(); 5249 unsigned NumElements = 5250 getContext().getTypeSize(VT) / getContext().getTypeSize(EltTy); 5251 Base = getContext() 5252 .getVectorType(EltTy, NumElements, VT->getVectorKind()) 5253 .getTypePtr(); 5254 } 5255 } 5256 5257 if (Base->isVectorType() != TyPtr->isVectorType() || 5258 getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr)) 5259 return false; 5260 } 5261 return Members > 0 && isHomogeneousAggregateSmallEnough(Base, Members); 5262 } 5263 5264 bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const { 5265 // Homogeneous aggregates for ELFv2 must have base types of float, 5266 // double, long double, or 128-bit vectors. 5267 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) { 5268 if (BT->getKind() == BuiltinType::Float || 5269 BT->getKind() == BuiltinType::Double || 5270 BT->getKind() == BuiltinType::LongDouble || 5271 BT->getKind() == BuiltinType::Ibm128 || 5272 (getContext().getTargetInfo().hasFloat128Type() && 5273 (BT->getKind() == BuiltinType::Float128))) { 5274 if (IsSoftFloatABI) 5275 return false; 5276 return true; 5277 } 5278 } 5279 if (const VectorType *VT = Ty->getAs<VectorType>()) { 5280 if (getContext().getTypeSize(VT) == 128) 5281 return true; 5282 } 5283 return false; 5284 } 5285 5286 bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateSmallEnough( 5287 const Type *Base, uint64_t Members) const { 5288 // Vector and fp128 types require one register, other floating point types 5289 // require one or two registers depending on their size. 5290 uint32_t NumRegs = 5291 ((getContext().getTargetInfo().hasFloat128Type() && 5292 Base->isFloat128Type()) || 5293 Base->isVectorType()) ? 1 5294 : (getContext().getTypeSize(Base) + 63) / 64; 5295 5296 // Homogeneous Aggregates may occupy at most 8 registers. 5297 return Members * NumRegs <= 8; 5298 } 5299 5300 ABIArgInfo 5301 PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const { 5302 Ty = useFirstFieldIfTransparentUnion(Ty); 5303 5304 if (Ty->isAnyComplexType()) 5305 return ABIArgInfo::getDirect(); 5306 5307 // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes) 5308 // or via reference (larger than 16 bytes). 5309 if (Ty->isVectorType()) { 5310 uint64_t Size = getContext().getTypeSize(Ty); 5311 if (Size > 128) 5312 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 5313 else if (Size < 128) { 5314 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size); 5315 return ABIArgInfo::getDirect(CoerceTy); 5316 } 5317 } 5318 5319 if (const auto *EIT = Ty->getAs<ExtIntType>()) 5320 if (EIT->getNumBits() > 128) 5321 return getNaturalAlignIndirect(Ty, /*ByVal=*/true); 5322 5323 if (isAggregateTypeForABI(Ty)) { 5324 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 5325 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 5326 5327 uint64_t ABIAlign = getParamTypeAlignment(Ty).getQuantity(); 5328 uint64_t TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity(); 5329 5330 // ELFv2 homogeneous aggregates are passed as array types. 5331 const Type *Base = nullptr; 5332 uint64_t Members = 0; 5333 if (Kind == ELFv2 && 5334 isHomogeneousAggregate(Ty, Base, Members)) { 5335 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0)); 5336 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members); 5337 return ABIArgInfo::getDirect(CoerceTy); 5338 } 5339 5340 // If an aggregate may end up fully in registers, we do not 5341 // use the ByVal method, but pass the aggregate as array. 5342 // This is usually beneficial since we avoid forcing the 5343 // back-end to store the argument to memory. 5344 uint64_t Bits = getContext().getTypeSize(Ty); 5345 if (Bits > 0 && Bits <= 8 * GPRBits) { 5346 llvm::Type *CoerceTy; 5347 5348 // Types up to 8 bytes are passed as integer type (which will be 5349 // properly aligned in the argument save area doubleword). 5350 if (Bits <= GPRBits) 5351 CoerceTy = 5352 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8)); 5353 // Larger types are passed as arrays, with the base type selected 5354 // according to the required alignment in the save area. 5355 else { 5356 uint64_t RegBits = ABIAlign * 8; 5357 uint64_t NumRegs = llvm::alignTo(Bits, RegBits) / RegBits; 5358 llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits); 5359 CoerceTy = llvm::ArrayType::get(RegTy, NumRegs); 5360 } 5361 5362 return ABIArgInfo::getDirect(CoerceTy); 5363 } 5364 5365 // All other aggregates are passed ByVal. 5366 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign), 5367 /*ByVal=*/true, 5368 /*Realign=*/TyAlign > ABIAlign); 5369 } 5370 5371 return (isPromotableTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty) 5372 : ABIArgInfo::getDirect()); 5373 } 5374 5375 ABIArgInfo 5376 PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const { 5377 if (RetTy->isVoidType()) 5378 return ABIArgInfo::getIgnore(); 5379 5380 if (RetTy->isAnyComplexType()) 5381 return ABIArgInfo::getDirect(); 5382 5383 // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes) 5384 // or via reference (larger than 16 bytes). 5385 if (RetTy->isVectorType()) { 5386 uint64_t Size = getContext().getTypeSize(RetTy); 5387 if (Size > 128) 5388 return getNaturalAlignIndirect(RetTy); 5389 else if (Size < 128) { 5390 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size); 5391 return ABIArgInfo::getDirect(CoerceTy); 5392 } 5393 } 5394 5395 if (const auto *EIT = RetTy->getAs<ExtIntType>()) 5396 if (EIT->getNumBits() > 128) 5397 return getNaturalAlignIndirect(RetTy, /*ByVal=*/false); 5398 5399 if (isAggregateTypeForABI(RetTy)) { 5400 // ELFv2 homogeneous aggregates are returned as array types. 5401 const Type *Base = nullptr; 5402 uint64_t Members = 0; 5403 if (Kind == ELFv2 && 5404 isHomogeneousAggregate(RetTy, Base, Members)) { 5405 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0)); 5406 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members); 5407 return ABIArgInfo::getDirect(CoerceTy); 5408 } 5409 5410 // ELFv2 small aggregates are returned in up to two registers. 5411 uint64_t Bits = getContext().getTypeSize(RetTy); 5412 if (Kind == ELFv2 && Bits <= 2 * GPRBits) { 5413 if (Bits == 0) 5414 return ABIArgInfo::getIgnore(); 5415 5416 llvm::Type *CoerceTy; 5417 if (Bits > GPRBits) { 5418 CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits); 5419 CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy); 5420 } else 5421 CoerceTy = 5422 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8)); 5423 return ABIArgInfo::getDirect(CoerceTy); 5424 } 5425 5426 // All other aggregates are returned indirectly. 5427 return getNaturalAlignIndirect(RetTy); 5428 } 5429 5430 return (isPromotableTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy) 5431 : ABIArgInfo::getDirect()); 5432 } 5433 5434 // Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine. 5435 Address PPC64_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 5436 QualType Ty) const { 5437 auto TypeInfo = getContext().getTypeInfoInChars(Ty); 5438 TypeInfo.Align = getParamTypeAlignment(Ty); 5439 5440 CharUnits SlotSize = CharUnits::fromQuantity(8); 5441 5442 // If we have a complex type and the base type is smaller than 8 bytes, 5443 // the ABI calls for the real and imaginary parts to be right-adjusted 5444 // in separate doublewords. However, Clang expects us to produce a 5445 // pointer to a structure with the two parts packed tightly. So generate 5446 // loads of the real and imaginary parts relative to the va_list pointer, 5447 // and store them to a temporary structure. 5448 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) { 5449 CharUnits EltSize = TypeInfo.Width / 2; 5450 if (EltSize < SlotSize) 5451 return complexTempStructure(CGF, VAListAddr, Ty, SlotSize, EltSize, CTy); 5452 } 5453 5454 // Otherwise, just use the general rule. 5455 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false, 5456 TypeInfo, SlotSize, /*AllowHigher*/ true); 5457 } 5458 5459 bool 5460 PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable( 5461 CodeGen::CodeGenFunction &CGF, 5462 llvm::Value *Address) const { 5463 return PPC_initDwarfEHRegSizeTable(CGF, Address, /*Is64Bit*/ true, 5464 /*IsAIX*/ false); 5465 } 5466 5467 bool 5468 PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 5469 llvm::Value *Address) const { 5470 return PPC_initDwarfEHRegSizeTable(CGF, Address, /*Is64Bit*/ true, 5471 /*IsAIX*/ false); 5472 } 5473 5474 //===----------------------------------------------------------------------===// 5475 // AArch64 ABI Implementation 5476 //===----------------------------------------------------------------------===// 5477 5478 namespace { 5479 5480 class AArch64ABIInfo : public SwiftABIInfo { 5481 public: 5482 enum ABIKind { 5483 AAPCS = 0, 5484 DarwinPCS, 5485 Win64 5486 }; 5487 5488 private: 5489 ABIKind Kind; 5490 5491 public: 5492 AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind) 5493 : SwiftABIInfo(CGT), Kind(Kind) {} 5494 5495 private: 5496 ABIKind getABIKind() const { return Kind; } 5497 bool isDarwinPCS() const { return Kind == DarwinPCS; } 5498 5499 ABIArgInfo classifyReturnType(QualType RetTy, bool IsVariadic) const; 5500 ABIArgInfo classifyArgumentType(QualType RetTy, bool IsVariadic, 5501 unsigned CallingConvention) const; 5502 ABIArgInfo coerceIllegalVector(QualType Ty) const; 5503 bool isHomogeneousAggregateBaseType(QualType Ty) const override; 5504 bool isHomogeneousAggregateSmallEnough(const Type *Ty, 5505 uint64_t Members) const override; 5506 5507 bool isIllegalVectorType(QualType Ty) const; 5508 5509 void computeInfo(CGFunctionInfo &FI) const override { 5510 if (!::classifyReturnType(getCXXABI(), FI, *this)) 5511 FI.getReturnInfo() = 5512 classifyReturnType(FI.getReturnType(), FI.isVariadic()); 5513 5514 for (auto &it : FI.arguments()) 5515 it.info = classifyArgumentType(it.type, FI.isVariadic(), 5516 FI.getCallingConvention()); 5517 } 5518 5519 Address EmitDarwinVAArg(Address VAListAddr, QualType Ty, 5520 CodeGenFunction &CGF) const; 5521 5522 Address EmitAAPCSVAArg(Address VAListAddr, QualType Ty, 5523 CodeGenFunction &CGF) const; 5524 5525 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 5526 QualType Ty) const override { 5527 llvm::Type *BaseTy = CGF.ConvertType(Ty); 5528 if (isa<llvm::ScalableVectorType>(BaseTy)) 5529 llvm::report_fatal_error("Passing SVE types to variadic functions is " 5530 "currently not supported"); 5531 5532 return Kind == Win64 ? EmitMSVAArg(CGF, VAListAddr, Ty) 5533 : isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF) 5534 : EmitAAPCSVAArg(VAListAddr, Ty, CGF); 5535 } 5536 5537 Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr, 5538 QualType Ty) const override; 5539 5540 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars, 5541 bool asReturnValue) const override { 5542 return occupiesMoreThan(CGT, scalars, /*total*/ 4); 5543 } 5544 bool isSwiftErrorInRegister() const override { 5545 return true; 5546 } 5547 5548 bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy, 5549 unsigned elts) const override; 5550 5551 bool allowBFloatArgsAndRet() const override { 5552 return getTarget().hasBFloat16Type(); 5553 } 5554 }; 5555 5556 class AArch64TargetCodeGenInfo : public TargetCodeGenInfo { 5557 public: 5558 AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind) 5559 : TargetCodeGenInfo(std::make_unique<AArch64ABIInfo>(CGT, Kind)) {} 5560 5561 StringRef getARCRetainAutoreleasedReturnValueMarker() const override { 5562 return "mov\tfp, fp\t\t// marker for objc_retainAutoreleaseReturnValue"; 5563 } 5564 5565 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 5566 return 31; 5567 } 5568 5569 bool doesReturnSlotInterfereWithArgs() const override { return false; } 5570 5571 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 5572 CodeGen::CodeGenModule &CGM) const override { 5573 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D); 5574 if (!FD) 5575 return; 5576 5577 const auto *TA = FD->getAttr<TargetAttr>(); 5578 if (TA == nullptr) 5579 return; 5580 5581 ParsedTargetAttr Attr = TA->parse(); 5582 if (Attr.BranchProtection.empty()) 5583 return; 5584 5585 TargetInfo::BranchProtectionInfo BPI; 5586 StringRef Error; 5587 (void)CGM.getTarget().validateBranchProtection(Attr.BranchProtection, 5588 BPI, Error); 5589 assert(Error.empty()); 5590 5591 auto *Fn = cast<llvm::Function>(GV); 5592 static const char *SignReturnAddrStr[] = {"none", "non-leaf", "all"}; 5593 Fn->addFnAttr("sign-return-address", SignReturnAddrStr[static_cast<int>(BPI.SignReturnAddr)]); 5594 5595 if (BPI.SignReturnAddr != LangOptions::SignReturnAddressScopeKind::None) { 5596 Fn->addFnAttr("sign-return-address-key", 5597 BPI.SignKey == LangOptions::SignReturnAddressKeyKind::AKey 5598 ? "a_key" 5599 : "b_key"); 5600 } 5601 5602 Fn->addFnAttr("branch-target-enforcement", 5603 BPI.BranchTargetEnforcement ? "true" : "false"); 5604 } 5605 5606 bool isScalarizableAsmOperand(CodeGen::CodeGenFunction &CGF, 5607 llvm::Type *Ty) const override { 5608 if (CGF.getTarget().hasFeature("ls64")) { 5609 auto *ST = dyn_cast<llvm::StructType>(Ty); 5610 if (ST && ST->getNumElements() == 1) { 5611 auto *AT = dyn_cast<llvm::ArrayType>(ST->getElementType(0)); 5612 if (AT && AT->getNumElements() == 8 && 5613 AT->getElementType()->isIntegerTy(64)) 5614 return true; 5615 } 5616 } 5617 return TargetCodeGenInfo::isScalarizableAsmOperand(CGF, Ty); 5618 } 5619 }; 5620 5621 class WindowsAArch64TargetCodeGenInfo : public AArch64TargetCodeGenInfo { 5622 public: 5623 WindowsAArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind K) 5624 : AArch64TargetCodeGenInfo(CGT, K) {} 5625 5626 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 5627 CodeGen::CodeGenModule &CGM) const override; 5628 5629 void getDependentLibraryOption(llvm::StringRef Lib, 5630 llvm::SmallString<24> &Opt) const override { 5631 Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib); 5632 } 5633 5634 void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value, 5635 llvm::SmallString<32> &Opt) const override { 5636 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\""; 5637 } 5638 }; 5639 5640 void WindowsAArch64TargetCodeGenInfo::setTargetAttributes( 5641 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const { 5642 AArch64TargetCodeGenInfo::setTargetAttributes(D, GV, CGM); 5643 if (GV->isDeclaration()) 5644 return; 5645 addStackProbeTargetAttributes(D, GV, CGM); 5646 } 5647 } 5648 5649 ABIArgInfo AArch64ABIInfo::coerceIllegalVector(QualType Ty) const { 5650 assert(Ty->isVectorType() && "expected vector type!"); 5651 5652 const auto *VT = Ty->castAs<VectorType>(); 5653 if (VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector) { 5654 assert(VT->getElementType()->isBuiltinType() && "expected builtin type!"); 5655 assert(VT->getElementType()->castAs<BuiltinType>()->getKind() == 5656 BuiltinType::UChar && 5657 "unexpected builtin type for SVE predicate!"); 5658 return ABIArgInfo::getDirect(llvm::ScalableVectorType::get( 5659 llvm::Type::getInt1Ty(getVMContext()), 16)); 5660 } 5661 5662 if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector) { 5663 assert(VT->getElementType()->isBuiltinType() && "expected builtin type!"); 5664 5665 const auto *BT = VT->getElementType()->castAs<BuiltinType>(); 5666 llvm::ScalableVectorType *ResType = nullptr; 5667 switch (BT->getKind()) { 5668 default: 5669 llvm_unreachable("unexpected builtin type for SVE vector!"); 5670 case BuiltinType::SChar: 5671 case BuiltinType::UChar: 5672 ResType = llvm::ScalableVectorType::get( 5673 llvm::Type::getInt8Ty(getVMContext()), 16); 5674 break; 5675 case BuiltinType::Short: 5676 case BuiltinType::UShort: 5677 ResType = llvm::ScalableVectorType::get( 5678 llvm::Type::getInt16Ty(getVMContext()), 8); 5679 break; 5680 case BuiltinType::Int: 5681 case BuiltinType::UInt: 5682 ResType = llvm::ScalableVectorType::get( 5683 llvm::Type::getInt32Ty(getVMContext()), 4); 5684 break; 5685 case BuiltinType::Long: 5686 case BuiltinType::ULong: 5687 ResType = llvm::ScalableVectorType::get( 5688 llvm::Type::getInt64Ty(getVMContext()), 2); 5689 break; 5690 case BuiltinType::Half: 5691 ResType = llvm::ScalableVectorType::get( 5692 llvm::Type::getHalfTy(getVMContext()), 8); 5693 break; 5694 case BuiltinType::Float: 5695 ResType = llvm::ScalableVectorType::get( 5696 llvm::Type::getFloatTy(getVMContext()), 4); 5697 break; 5698 case BuiltinType::Double: 5699 ResType = llvm::ScalableVectorType::get( 5700 llvm::Type::getDoubleTy(getVMContext()), 2); 5701 break; 5702 case BuiltinType::BFloat16: 5703 ResType = llvm::ScalableVectorType::get( 5704 llvm::Type::getBFloatTy(getVMContext()), 8); 5705 break; 5706 } 5707 return ABIArgInfo::getDirect(ResType); 5708 } 5709 5710 uint64_t Size = getContext().getTypeSize(Ty); 5711 // Android promotes <2 x i8> to i16, not i32 5712 if (isAndroid() && (Size <= 16)) { 5713 llvm::Type *ResType = llvm::Type::getInt16Ty(getVMContext()); 5714 return ABIArgInfo::getDirect(ResType); 5715 } 5716 if (Size <= 32) { 5717 llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext()); 5718 return ABIArgInfo::getDirect(ResType); 5719 } 5720 if (Size == 64) { 5721 auto *ResType = 5722 llvm::FixedVectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2); 5723 return ABIArgInfo::getDirect(ResType); 5724 } 5725 if (Size == 128) { 5726 auto *ResType = 5727 llvm::FixedVectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4); 5728 return ABIArgInfo::getDirect(ResType); 5729 } 5730 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 5731 } 5732 5733 ABIArgInfo 5734 AArch64ABIInfo::classifyArgumentType(QualType Ty, bool IsVariadic, 5735 unsigned CallingConvention) const { 5736 Ty = useFirstFieldIfTransparentUnion(Ty); 5737 5738 // Handle illegal vector types here. 5739 if (isIllegalVectorType(Ty)) 5740 return coerceIllegalVector(Ty); 5741 5742 if (!isAggregateTypeForABI(Ty)) { 5743 // Treat an enum type as its underlying type. 5744 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 5745 Ty = EnumTy->getDecl()->getIntegerType(); 5746 5747 if (const auto *EIT = Ty->getAs<ExtIntType>()) 5748 if (EIT->getNumBits() > 128) 5749 return getNaturalAlignIndirect(Ty); 5750 5751 return (isPromotableIntegerTypeForABI(Ty) && isDarwinPCS() 5752 ? ABIArgInfo::getExtend(Ty) 5753 : ABIArgInfo::getDirect()); 5754 } 5755 5756 // Structures with either a non-trivial destructor or a non-trivial 5757 // copy constructor are always indirect. 5758 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) { 5759 return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA == 5760 CGCXXABI::RAA_DirectInMemory); 5761 } 5762 5763 // Empty records are always ignored on Darwin, but actually passed in C++ mode 5764 // elsewhere for GNU compatibility. 5765 uint64_t Size = getContext().getTypeSize(Ty); 5766 bool IsEmpty = isEmptyRecord(getContext(), Ty, true); 5767 if (IsEmpty || Size == 0) { 5768 if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS()) 5769 return ABIArgInfo::getIgnore(); 5770 5771 // GNU C mode. The only argument that gets ignored is an empty one with size 5772 // 0. 5773 if (IsEmpty && Size == 0) 5774 return ABIArgInfo::getIgnore(); 5775 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext())); 5776 } 5777 5778 // Homogeneous Floating-point Aggregates (HFAs) need to be expanded. 5779 const Type *Base = nullptr; 5780 uint64_t Members = 0; 5781 bool IsWin64 = Kind == Win64 || CallingConvention == llvm::CallingConv::Win64; 5782 bool IsWinVariadic = IsWin64 && IsVariadic; 5783 // In variadic functions on Windows, all composite types are treated alike, 5784 // no special handling of HFAs/HVAs. 5785 if (!IsWinVariadic && isHomogeneousAggregate(Ty, Base, Members)) { 5786 if (Kind != AArch64ABIInfo::AAPCS) 5787 return ABIArgInfo::getDirect( 5788 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members)); 5789 5790 // For alignment adjusted HFAs, cap the argument alignment to 16, leave it 5791 // default otherwise. 5792 unsigned Align = 5793 getContext().getTypeUnadjustedAlignInChars(Ty).getQuantity(); 5794 unsigned BaseAlign = getContext().getTypeAlignInChars(Base).getQuantity(); 5795 Align = (Align > BaseAlign && Align >= 16) ? 16 : 0; 5796 return ABIArgInfo::getDirect( 5797 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members), 0, 5798 nullptr, true, Align); 5799 } 5800 5801 // Aggregates <= 16 bytes are passed directly in registers or on the stack. 5802 if (Size <= 128) { 5803 // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of 5804 // same size and alignment. 5805 if (getTarget().isRenderScriptTarget()) { 5806 return coerceToIntArray(Ty, getContext(), getVMContext()); 5807 } 5808 unsigned Alignment; 5809 if (Kind == AArch64ABIInfo::AAPCS) { 5810 Alignment = getContext().getTypeUnadjustedAlign(Ty); 5811 Alignment = Alignment < 128 ? 64 : 128; 5812 } else { 5813 Alignment = std::max(getContext().getTypeAlign(Ty), 5814 (unsigned)getTarget().getPointerWidth(0)); 5815 } 5816 Size = llvm::alignTo(Size, Alignment); 5817 5818 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment. 5819 // For aggregates with 16-byte alignment, we use i128. 5820 llvm::Type *BaseTy = llvm::Type::getIntNTy(getVMContext(), Alignment); 5821 return ABIArgInfo::getDirect( 5822 Size == Alignment ? BaseTy 5823 : llvm::ArrayType::get(BaseTy, Size / Alignment)); 5824 } 5825 5826 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 5827 } 5828 5829 ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy, 5830 bool IsVariadic) const { 5831 if (RetTy->isVoidType()) 5832 return ABIArgInfo::getIgnore(); 5833 5834 if (const auto *VT = RetTy->getAs<VectorType>()) { 5835 if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector || 5836 VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector) 5837 return coerceIllegalVector(RetTy); 5838 } 5839 5840 // Large vector types should be returned via memory. 5841 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128) 5842 return getNaturalAlignIndirect(RetTy); 5843 5844 if (!isAggregateTypeForABI(RetTy)) { 5845 // Treat an enum type as its underlying type. 5846 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 5847 RetTy = EnumTy->getDecl()->getIntegerType(); 5848 5849 if (const auto *EIT = RetTy->getAs<ExtIntType>()) 5850 if (EIT->getNumBits() > 128) 5851 return getNaturalAlignIndirect(RetTy); 5852 5853 return (isPromotableIntegerTypeForABI(RetTy) && isDarwinPCS() 5854 ? ABIArgInfo::getExtend(RetTy) 5855 : ABIArgInfo::getDirect()); 5856 } 5857 5858 uint64_t Size = getContext().getTypeSize(RetTy); 5859 if (isEmptyRecord(getContext(), RetTy, true) || Size == 0) 5860 return ABIArgInfo::getIgnore(); 5861 5862 const Type *Base = nullptr; 5863 uint64_t Members = 0; 5864 if (isHomogeneousAggregate(RetTy, Base, Members) && 5865 !(getTarget().getTriple().getArch() == llvm::Triple::aarch64_32 && 5866 IsVariadic)) 5867 // Homogeneous Floating-point Aggregates (HFAs) are returned directly. 5868 return ABIArgInfo::getDirect(); 5869 5870 // Aggregates <= 16 bytes are returned directly in registers or on the stack. 5871 if (Size <= 128) { 5872 // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of 5873 // same size and alignment. 5874 if (getTarget().isRenderScriptTarget()) { 5875 return coerceToIntArray(RetTy, getContext(), getVMContext()); 5876 } 5877 5878 if (Size <= 64 && getDataLayout().isLittleEndian()) { 5879 // Composite types are returned in lower bits of a 64-bit register for LE, 5880 // and in higher bits for BE. However, integer types are always returned 5881 // in lower bits for both LE and BE, and they are not rounded up to 5882 // 64-bits. We can skip rounding up of composite types for LE, but not for 5883 // BE, otherwise composite types will be indistinguishable from integer 5884 // types. 5885 return ABIArgInfo::getDirect( 5886 llvm::IntegerType::get(getVMContext(), Size)); 5887 } 5888 5889 unsigned Alignment = getContext().getTypeAlign(RetTy); 5890 Size = llvm::alignTo(Size, 64); // round up to multiple of 8 bytes 5891 5892 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment. 5893 // For aggregates with 16-byte alignment, we use i128. 5894 if (Alignment < 128 && Size == 128) { 5895 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext()); 5896 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64)); 5897 } 5898 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size)); 5899 } 5900 5901 return getNaturalAlignIndirect(RetTy); 5902 } 5903 5904 /// isIllegalVectorType - check whether the vector type is legal for AArch64. 5905 bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const { 5906 if (const VectorType *VT = Ty->getAs<VectorType>()) { 5907 // Check whether VT is a fixed-length SVE vector. These types are 5908 // represented as scalable vectors in function args/return and must be 5909 // coerced from fixed vectors. 5910 if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector || 5911 VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector) 5912 return true; 5913 5914 // Check whether VT is legal. 5915 unsigned NumElements = VT->getNumElements(); 5916 uint64_t Size = getContext().getTypeSize(VT); 5917 // NumElements should be power of 2. 5918 if (!llvm::isPowerOf2_32(NumElements)) 5919 return true; 5920 5921 // arm64_32 has to be compatible with the ARM logic here, which allows huge 5922 // vectors for some reason. 5923 llvm::Triple Triple = getTarget().getTriple(); 5924 if (Triple.getArch() == llvm::Triple::aarch64_32 && 5925 Triple.isOSBinFormatMachO()) 5926 return Size <= 32; 5927 5928 return Size != 64 && (Size != 128 || NumElements == 1); 5929 } 5930 return false; 5931 } 5932 5933 bool AArch64ABIInfo::isLegalVectorTypeForSwift(CharUnits totalSize, 5934 llvm::Type *eltTy, 5935 unsigned elts) const { 5936 if (!llvm::isPowerOf2_32(elts)) 5937 return false; 5938 if (totalSize.getQuantity() != 8 && 5939 (totalSize.getQuantity() != 16 || elts == 1)) 5940 return false; 5941 return true; 5942 } 5943 5944 bool AArch64ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const { 5945 // Homogeneous aggregates for AAPCS64 must have base types of a floating 5946 // point type or a short-vector type. This is the same as the 32-bit ABI, 5947 // but with the difference that any floating-point type is allowed, 5948 // including __fp16. 5949 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) { 5950 if (BT->isFloatingPoint()) 5951 return true; 5952 } else if (const VectorType *VT = Ty->getAs<VectorType>()) { 5953 unsigned VecSize = getContext().getTypeSize(VT); 5954 if (VecSize == 64 || VecSize == 128) 5955 return true; 5956 } 5957 return false; 5958 } 5959 5960 bool AArch64ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base, 5961 uint64_t Members) const { 5962 return Members <= 4; 5963 } 5964 5965 Address AArch64ABIInfo::EmitAAPCSVAArg(Address VAListAddr, QualType Ty, 5966 CodeGenFunction &CGF) const { 5967 ABIArgInfo AI = classifyArgumentType(Ty, /*IsVariadic=*/true, 5968 CGF.CurFnInfo->getCallingConvention()); 5969 bool IsIndirect = AI.isIndirect(); 5970 5971 llvm::Type *BaseTy = CGF.ConvertType(Ty); 5972 if (IsIndirect) 5973 BaseTy = llvm::PointerType::getUnqual(BaseTy); 5974 else if (AI.getCoerceToType()) 5975 BaseTy = AI.getCoerceToType(); 5976 5977 unsigned NumRegs = 1; 5978 if (llvm::ArrayType *ArrTy = dyn_cast<llvm::ArrayType>(BaseTy)) { 5979 BaseTy = ArrTy->getElementType(); 5980 NumRegs = ArrTy->getNumElements(); 5981 } 5982 bool IsFPR = BaseTy->isFloatingPointTy() || BaseTy->isVectorTy(); 5983 5984 // The AArch64 va_list type and handling is specified in the Procedure Call 5985 // Standard, section B.4: 5986 // 5987 // struct { 5988 // void *__stack; 5989 // void *__gr_top; 5990 // void *__vr_top; 5991 // int __gr_offs; 5992 // int __vr_offs; 5993 // }; 5994 5995 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg"); 5996 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg"); 5997 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack"); 5998 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end"); 5999 6000 CharUnits TySize = getContext().getTypeSizeInChars(Ty); 6001 CharUnits TyAlign = getContext().getTypeUnadjustedAlignInChars(Ty); 6002 6003 Address reg_offs_p = Address::invalid(); 6004 llvm::Value *reg_offs = nullptr; 6005 int reg_top_index; 6006 int RegSize = IsIndirect ? 8 : TySize.getQuantity(); 6007 if (!IsFPR) { 6008 // 3 is the field number of __gr_offs 6009 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 3, "gr_offs_p"); 6010 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs"); 6011 reg_top_index = 1; // field number for __gr_top 6012 RegSize = llvm::alignTo(RegSize, 8); 6013 } else { 6014 // 4 is the field number of __vr_offs. 6015 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 4, "vr_offs_p"); 6016 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs"); 6017 reg_top_index = 2; // field number for __vr_top 6018 RegSize = 16 * NumRegs; 6019 } 6020 6021 //======================================= 6022 // Find out where argument was passed 6023 //======================================= 6024 6025 // If reg_offs >= 0 we're already using the stack for this type of 6026 // argument. We don't want to keep updating reg_offs (in case it overflows, 6027 // though anyone passing 2GB of arguments, each at most 16 bytes, deserves 6028 // whatever they get). 6029 llvm::Value *UsingStack = nullptr; 6030 UsingStack = CGF.Builder.CreateICmpSGE( 6031 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0)); 6032 6033 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock); 6034 6035 // Otherwise, at least some kind of argument could go in these registers, the 6036 // question is whether this particular type is too big. 6037 CGF.EmitBlock(MaybeRegBlock); 6038 6039 // Integer arguments may need to correct register alignment (for example a 6040 // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we 6041 // align __gr_offs to calculate the potential address. 6042 if (!IsFPR && !IsIndirect && TyAlign.getQuantity() > 8) { 6043 int Align = TyAlign.getQuantity(); 6044 6045 reg_offs = CGF.Builder.CreateAdd( 6046 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1), 6047 "align_regoffs"); 6048 reg_offs = CGF.Builder.CreateAnd( 6049 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align), 6050 "aligned_regoffs"); 6051 } 6052 6053 // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list. 6054 // The fact that this is done unconditionally reflects the fact that 6055 // allocating an argument to the stack also uses up all the remaining 6056 // registers of the appropriate kind. 6057 llvm::Value *NewOffset = nullptr; 6058 NewOffset = CGF.Builder.CreateAdd( 6059 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs"); 6060 CGF.Builder.CreateStore(NewOffset, reg_offs_p); 6061 6062 // Now we're in a position to decide whether this argument really was in 6063 // registers or not. 6064 llvm::Value *InRegs = nullptr; 6065 InRegs = CGF.Builder.CreateICmpSLE( 6066 NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg"); 6067 6068 CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock); 6069 6070 //======================================= 6071 // Argument was in registers 6072 //======================================= 6073 6074 // Now we emit the code for if the argument was originally passed in 6075 // registers. First start the appropriate block: 6076 CGF.EmitBlock(InRegBlock); 6077 6078 llvm::Value *reg_top = nullptr; 6079 Address reg_top_p = 6080 CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index, "reg_top_p"); 6081 reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top"); 6082 Address BaseAddr(CGF.Builder.CreateInBoundsGEP(CGF.Int8Ty, reg_top, reg_offs), 6083 CharUnits::fromQuantity(IsFPR ? 16 : 8)); 6084 Address RegAddr = Address::invalid(); 6085 llvm::Type *MemTy = CGF.ConvertTypeForMem(Ty); 6086 6087 if (IsIndirect) { 6088 // If it's been passed indirectly (actually a struct), whatever we find from 6089 // stored registers or on the stack will actually be a struct **. 6090 MemTy = llvm::PointerType::getUnqual(MemTy); 6091 } 6092 6093 const Type *Base = nullptr; 6094 uint64_t NumMembers = 0; 6095 bool IsHFA = isHomogeneousAggregate(Ty, Base, NumMembers); 6096 if (IsHFA && NumMembers > 1) { 6097 // Homogeneous aggregates passed in registers will have their elements split 6098 // and stored 16-bytes apart regardless of size (they're notionally in qN, 6099 // qN+1, ...). We reload and store into a temporary local variable 6100 // contiguously. 6101 assert(!IsIndirect && "Homogeneous aggregates should be passed directly"); 6102 auto BaseTyInfo = getContext().getTypeInfoInChars(QualType(Base, 0)); 6103 llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0)); 6104 llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers); 6105 Address Tmp = CGF.CreateTempAlloca(HFATy, 6106 std::max(TyAlign, BaseTyInfo.Align)); 6107 6108 // On big-endian platforms, the value will be right-aligned in its slot. 6109 int Offset = 0; 6110 if (CGF.CGM.getDataLayout().isBigEndian() && 6111 BaseTyInfo.Width.getQuantity() < 16) 6112 Offset = 16 - BaseTyInfo.Width.getQuantity(); 6113 6114 for (unsigned i = 0; i < NumMembers; ++i) { 6115 CharUnits BaseOffset = CharUnits::fromQuantity(16 * i + Offset); 6116 Address LoadAddr = 6117 CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, BaseOffset); 6118 LoadAddr = CGF.Builder.CreateElementBitCast(LoadAddr, BaseTy); 6119 6120 Address StoreAddr = CGF.Builder.CreateConstArrayGEP(Tmp, i); 6121 6122 llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr); 6123 CGF.Builder.CreateStore(Elem, StoreAddr); 6124 } 6125 6126 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, MemTy); 6127 } else { 6128 // Otherwise the object is contiguous in memory. 6129 6130 // It might be right-aligned in its slot. 6131 CharUnits SlotSize = BaseAddr.getAlignment(); 6132 if (CGF.CGM.getDataLayout().isBigEndian() && !IsIndirect && 6133 (IsHFA || !isAggregateTypeForABI(Ty)) && 6134 TySize < SlotSize) { 6135 CharUnits Offset = SlotSize - TySize; 6136 BaseAddr = CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, Offset); 6137 } 6138 6139 RegAddr = CGF.Builder.CreateElementBitCast(BaseAddr, MemTy); 6140 } 6141 6142 CGF.EmitBranch(ContBlock); 6143 6144 //======================================= 6145 // Argument was on the stack 6146 //======================================= 6147 CGF.EmitBlock(OnStackBlock); 6148 6149 Address stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "stack_p"); 6150 llvm::Value *OnStackPtr = CGF.Builder.CreateLoad(stack_p, "stack"); 6151 6152 // Again, stack arguments may need realignment. In this case both integer and 6153 // floating-point ones might be affected. 6154 if (!IsIndirect && TyAlign.getQuantity() > 8) { 6155 int Align = TyAlign.getQuantity(); 6156 6157 OnStackPtr = CGF.Builder.CreatePtrToInt(OnStackPtr, CGF.Int64Ty); 6158 6159 OnStackPtr = CGF.Builder.CreateAdd( 6160 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1), 6161 "align_stack"); 6162 OnStackPtr = CGF.Builder.CreateAnd( 6163 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, -Align), 6164 "align_stack"); 6165 6166 OnStackPtr = CGF.Builder.CreateIntToPtr(OnStackPtr, CGF.Int8PtrTy); 6167 } 6168 Address OnStackAddr(OnStackPtr, 6169 std::max(CharUnits::fromQuantity(8), TyAlign)); 6170 6171 // All stack slots are multiples of 8 bytes. 6172 CharUnits StackSlotSize = CharUnits::fromQuantity(8); 6173 CharUnits StackSize; 6174 if (IsIndirect) 6175 StackSize = StackSlotSize; 6176 else 6177 StackSize = TySize.alignTo(StackSlotSize); 6178 6179 llvm::Value *StackSizeC = CGF.Builder.getSize(StackSize); 6180 llvm::Value *NewStack = CGF.Builder.CreateInBoundsGEP( 6181 CGF.Int8Ty, OnStackPtr, StackSizeC, "new_stack"); 6182 6183 // Write the new value of __stack for the next call to va_arg 6184 CGF.Builder.CreateStore(NewStack, stack_p); 6185 6186 if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) && 6187 TySize < StackSlotSize) { 6188 CharUnits Offset = StackSlotSize - TySize; 6189 OnStackAddr = CGF.Builder.CreateConstInBoundsByteGEP(OnStackAddr, Offset); 6190 } 6191 6192 OnStackAddr = CGF.Builder.CreateElementBitCast(OnStackAddr, MemTy); 6193 6194 CGF.EmitBranch(ContBlock); 6195 6196 //======================================= 6197 // Tidy up 6198 //======================================= 6199 CGF.EmitBlock(ContBlock); 6200 6201 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, 6202 OnStackAddr, OnStackBlock, "vaargs.addr"); 6203 6204 if (IsIndirect) 6205 return Address(CGF.Builder.CreateLoad(ResAddr, "vaarg.addr"), 6206 TyAlign); 6207 6208 return ResAddr; 6209 } 6210 6211 Address AArch64ABIInfo::EmitDarwinVAArg(Address VAListAddr, QualType Ty, 6212 CodeGenFunction &CGF) const { 6213 // The backend's lowering doesn't support va_arg for aggregates or 6214 // illegal vector types. Lower VAArg here for these cases and use 6215 // the LLVM va_arg instruction for everything else. 6216 if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty)) 6217 return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect()); 6218 6219 uint64_t PointerSize = getTarget().getPointerWidth(0) / 8; 6220 CharUnits SlotSize = CharUnits::fromQuantity(PointerSize); 6221 6222 // Empty records are ignored for parameter passing purposes. 6223 if (isEmptyRecord(getContext(), Ty, true)) { 6224 Address Addr(CGF.Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize); 6225 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty)); 6226 return Addr; 6227 } 6228 6229 // The size of the actual thing passed, which might end up just 6230 // being a pointer for indirect types. 6231 auto TyInfo = getContext().getTypeInfoInChars(Ty); 6232 6233 // Arguments bigger than 16 bytes which aren't homogeneous 6234 // aggregates should be passed indirectly. 6235 bool IsIndirect = false; 6236 if (TyInfo.Width.getQuantity() > 16) { 6237 const Type *Base = nullptr; 6238 uint64_t Members = 0; 6239 IsIndirect = !isHomogeneousAggregate(Ty, Base, Members); 6240 } 6241 6242 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, 6243 TyInfo, SlotSize, /*AllowHigherAlign*/ true); 6244 } 6245 6246 Address AArch64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr, 6247 QualType Ty) const { 6248 bool IsIndirect = false; 6249 6250 // Composites larger than 16 bytes are passed by reference. 6251 if (isAggregateTypeForABI(Ty) && getContext().getTypeSize(Ty) > 128) 6252 IsIndirect = true; 6253 6254 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, 6255 CGF.getContext().getTypeInfoInChars(Ty), 6256 CharUnits::fromQuantity(8), 6257 /*allowHigherAlign*/ false); 6258 } 6259 6260 //===----------------------------------------------------------------------===// 6261 // ARM ABI Implementation 6262 //===----------------------------------------------------------------------===// 6263 6264 namespace { 6265 6266 class ARMABIInfo : public SwiftABIInfo { 6267 public: 6268 enum ABIKind { 6269 APCS = 0, 6270 AAPCS = 1, 6271 AAPCS_VFP = 2, 6272 AAPCS16_VFP = 3, 6273 }; 6274 6275 private: 6276 ABIKind Kind; 6277 bool IsFloatABISoftFP; 6278 6279 public: 6280 ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind) 6281 : SwiftABIInfo(CGT), Kind(_Kind) { 6282 setCCs(); 6283 IsFloatABISoftFP = CGT.getCodeGenOpts().FloatABI == "softfp" || 6284 CGT.getCodeGenOpts().FloatABI == ""; // default 6285 } 6286 6287 bool isEABI() const { 6288 switch (getTarget().getTriple().getEnvironment()) { 6289 case llvm::Triple::Android: 6290 case llvm::Triple::EABI: 6291 case llvm::Triple::EABIHF: 6292 case llvm::Triple::GNUEABI: 6293 case llvm::Triple::GNUEABIHF: 6294 case llvm::Triple::MuslEABI: 6295 case llvm::Triple::MuslEABIHF: 6296 return true; 6297 default: 6298 return false; 6299 } 6300 } 6301 6302 bool isEABIHF() const { 6303 switch (getTarget().getTriple().getEnvironment()) { 6304 case llvm::Triple::EABIHF: 6305 case llvm::Triple::GNUEABIHF: 6306 case llvm::Triple::MuslEABIHF: 6307 return true; 6308 default: 6309 return false; 6310 } 6311 } 6312 6313 ABIKind getABIKind() const { return Kind; } 6314 6315 bool allowBFloatArgsAndRet() const override { 6316 return !IsFloatABISoftFP && getTarget().hasBFloat16Type(); 6317 } 6318 6319 private: 6320 ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic, 6321 unsigned functionCallConv) const; 6322 ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic, 6323 unsigned functionCallConv) const; 6324 ABIArgInfo classifyHomogeneousAggregate(QualType Ty, const Type *Base, 6325 uint64_t Members) const; 6326 ABIArgInfo coerceIllegalVector(QualType Ty) const; 6327 bool isIllegalVectorType(QualType Ty) const; 6328 bool containsAnyFP16Vectors(QualType Ty) const; 6329 6330 bool isHomogeneousAggregateBaseType(QualType Ty) const override; 6331 bool isHomogeneousAggregateSmallEnough(const Type *Ty, 6332 uint64_t Members) const override; 6333 6334 bool isEffectivelyAAPCS_VFP(unsigned callConvention, bool acceptHalf) const; 6335 6336 void computeInfo(CGFunctionInfo &FI) const override; 6337 6338 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 6339 QualType Ty) const override; 6340 6341 llvm::CallingConv::ID getLLVMDefaultCC() const; 6342 llvm::CallingConv::ID getABIDefaultCC() const; 6343 void setCCs(); 6344 6345 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars, 6346 bool asReturnValue) const override { 6347 return occupiesMoreThan(CGT, scalars, /*total*/ 4); 6348 } 6349 bool isSwiftErrorInRegister() const override { 6350 return true; 6351 } 6352 bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy, 6353 unsigned elts) const override; 6354 }; 6355 6356 class ARMTargetCodeGenInfo : public TargetCodeGenInfo { 6357 public: 6358 ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K) 6359 : TargetCodeGenInfo(std::make_unique<ARMABIInfo>(CGT, K)) {} 6360 6361 const ARMABIInfo &getABIInfo() const { 6362 return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo()); 6363 } 6364 6365 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 6366 return 13; 6367 } 6368 6369 StringRef getARCRetainAutoreleasedReturnValueMarker() const override { 6370 return "mov\tr7, r7\t\t// marker for objc_retainAutoreleaseReturnValue"; 6371 } 6372 6373 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 6374 llvm::Value *Address) const override { 6375 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4); 6376 6377 // 0-15 are the 16 integer registers. 6378 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15); 6379 return false; 6380 } 6381 6382 unsigned getSizeOfUnwindException() const override { 6383 if (getABIInfo().isEABI()) return 88; 6384 return TargetCodeGenInfo::getSizeOfUnwindException(); 6385 } 6386 6387 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 6388 CodeGen::CodeGenModule &CGM) const override { 6389 if (GV->isDeclaration()) 6390 return; 6391 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D); 6392 if (!FD) 6393 return; 6394 6395 const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>(); 6396 if (!Attr) 6397 return; 6398 6399 const char *Kind; 6400 switch (Attr->getInterrupt()) { 6401 case ARMInterruptAttr::Generic: Kind = ""; break; 6402 case ARMInterruptAttr::IRQ: Kind = "IRQ"; break; 6403 case ARMInterruptAttr::FIQ: Kind = "FIQ"; break; 6404 case ARMInterruptAttr::SWI: Kind = "SWI"; break; 6405 case ARMInterruptAttr::ABORT: Kind = "ABORT"; break; 6406 case ARMInterruptAttr::UNDEF: Kind = "UNDEF"; break; 6407 } 6408 6409 llvm::Function *Fn = cast<llvm::Function>(GV); 6410 6411 Fn->addFnAttr("interrupt", Kind); 6412 6413 ARMABIInfo::ABIKind ABI = cast<ARMABIInfo>(getABIInfo()).getABIKind(); 6414 if (ABI == ARMABIInfo::APCS) 6415 return; 6416 6417 // AAPCS guarantees that sp will be 8-byte aligned on any public interface, 6418 // however this is not necessarily true on taking any interrupt. Instruct 6419 // the backend to perform a realignment as part of the function prologue. 6420 llvm::AttrBuilder B; 6421 B.addStackAlignmentAttr(8); 6422 Fn->addFnAttrs(B); 6423 } 6424 }; 6425 6426 class WindowsARMTargetCodeGenInfo : public ARMTargetCodeGenInfo { 6427 public: 6428 WindowsARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K) 6429 : ARMTargetCodeGenInfo(CGT, K) {} 6430 6431 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 6432 CodeGen::CodeGenModule &CGM) const override; 6433 6434 void getDependentLibraryOption(llvm::StringRef Lib, 6435 llvm::SmallString<24> &Opt) const override { 6436 Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib); 6437 } 6438 6439 void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value, 6440 llvm::SmallString<32> &Opt) const override { 6441 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\""; 6442 } 6443 }; 6444 6445 void WindowsARMTargetCodeGenInfo::setTargetAttributes( 6446 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const { 6447 ARMTargetCodeGenInfo::setTargetAttributes(D, GV, CGM); 6448 if (GV->isDeclaration()) 6449 return; 6450 addStackProbeTargetAttributes(D, GV, CGM); 6451 } 6452 } 6453 6454 void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const { 6455 if (!::classifyReturnType(getCXXABI(), FI, *this)) 6456 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), FI.isVariadic(), 6457 FI.getCallingConvention()); 6458 6459 for (auto &I : FI.arguments()) 6460 I.info = classifyArgumentType(I.type, FI.isVariadic(), 6461 FI.getCallingConvention()); 6462 6463 6464 // Always honor user-specified calling convention. 6465 if (FI.getCallingConvention() != llvm::CallingConv::C) 6466 return; 6467 6468 llvm::CallingConv::ID cc = getRuntimeCC(); 6469 if (cc != llvm::CallingConv::C) 6470 FI.setEffectiveCallingConvention(cc); 6471 } 6472 6473 /// Return the default calling convention that LLVM will use. 6474 llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const { 6475 // The default calling convention that LLVM will infer. 6476 if (isEABIHF() || getTarget().getTriple().isWatchABI()) 6477 return llvm::CallingConv::ARM_AAPCS_VFP; 6478 else if (isEABI()) 6479 return llvm::CallingConv::ARM_AAPCS; 6480 else 6481 return llvm::CallingConv::ARM_APCS; 6482 } 6483 6484 /// Return the calling convention that our ABI would like us to use 6485 /// as the C calling convention. 6486 llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const { 6487 switch (getABIKind()) { 6488 case APCS: return llvm::CallingConv::ARM_APCS; 6489 case AAPCS: return llvm::CallingConv::ARM_AAPCS; 6490 case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP; 6491 case AAPCS16_VFP: return llvm::CallingConv::ARM_AAPCS_VFP; 6492 } 6493 llvm_unreachable("bad ABI kind"); 6494 } 6495 6496 void ARMABIInfo::setCCs() { 6497 assert(getRuntimeCC() == llvm::CallingConv::C); 6498 6499 // Don't muddy up the IR with a ton of explicit annotations if 6500 // they'd just match what LLVM will infer from the triple. 6501 llvm::CallingConv::ID abiCC = getABIDefaultCC(); 6502 if (abiCC != getLLVMDefaultCC()) 6503 RuntimeCC = abiCC; 6504 } 6505 6506 ABIArgInfo ARMABIInfo::coerceIllegalVector(QualType Ty) const { 6507 uint64_t Size = getContext().getTypeSize(Ty); 6508 if (Size <= 32) { 6509 llvm::Type *ResType = 6510 llvm::Type::getInt32Ty(getVMContext()); 6511 return ABIArgInfo::getDirect(ResType); 6512 } 6513 if (Size == 64 || Size == 128) { 6514 auto *ResType = llvm::FixedVectorType::get( 6515 llvm::Type::getInt32Ty(getVMContext()), Size / 32); 6516 return ABIArgInfo::getDirect(ResType); 6517 } 6518 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 6519 } 6520 6521 ABIArgInfo ARMABIInfo::classifyHomogeneousAggregate(QualType Ty, 6522 const Type *Base, 6523 uint64_t Members) const { 6524 assert(Base && "Base class should be set for homogeneous aggregate"); 6525 // Base can be a floating-point or a vector. 6526 if (const VectorType *VT = Base->getAs<VectorType>()) { 6527 // FP16 vectors should be converted to integer vectors 6528 if (!getTarget().hasLegalHalfType() && containsAnyFP16Vectors(Ty)) { 6529 uint64_t Size = getContext().getTypeSize(VT); 6530 auto *NewVecTy = llvm::FixedVectorType::get( 6531 llvm::Type::getInt32Ty(getVMContext()), Size / 32); 6532 llvm::Type *Ty = llvm::ArrayType::get(NewVecTy, Members); 6533 return ABIArgInfo::getDirect(Ty, 0, nullptr, false); 6534 } 6535 } 6536 unsigned Align = 0; 6537 if (getABIKind() == ARMABIInfo::AAPCS || 6538 getABIKind() == ARMABIInfo::AAPCS_VFP) { 6539 // For alignment adjusted HFAs, cap the argument alignment to 8, leave it 6540 // default otherwise. 6541 Align = getContext().getTypeUnadjustedAlignInChars(Ty).getQuantity(); 6542 unsigned BaseAlign = getContext().getTypeAlignInChars(Base).getQuantity(); 6543 Align = (Align > BaseAlign && Align >= 8) ? 8 : 0; 6544 } 6545 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false, Align); 6546 } 6547 6548 ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty, bool isVariadic, 6549 unsigned functionCallConv) const { 6550 // 6.1.2.1 The following argument types are VFP CPRCs: 6551 // A single-precision floating-point type (including promoted 6552 // half-precision types); A double-precision floating-point type; 6553 // A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate 6554 // with a Base Type of a single- or double-precision floating-point type, 6555 // 64-bit containerized vectors or 128-bit containerized vectors with one 6556 // to four Elements. 6557 // Variadic functions should always marshal to the base standard. 6558 bool IsAAPCS_VFP = 6559 !isVariadic && isEffectivelyAAPCS_VFP(functionCallConv, /* AAPCS16 */ false); 6560 6561 Ty = useFirstFieldIfTransparentUnion(Ty); 6562 6563 // Handle illegal vector types here. 6564 if (isIllegalVectorType(Ty)) 6565 return coerceIllegalVector(Ty); 6566 6567 if (!isAggregateTypeForABI(Ty)) { 6568 // Treat an enum type as its underlying type. 6569 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) { 6570 Ty = EnumTy->getDecl()->getIntegerType(); 6571 } 6572 6573 if (const auto *EIT = Ty->getAs<ExtIntType>()) 6574 if (EIT->getNumBits() > 64) 6575 return getNaturalAlignIndirect(Ty, /*ByVal=*/true); 6576 6577 return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty) 6578 : ABIArgInfo::getDirect()); 6579 } 6580 6581 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) { 6582 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 6583 } 6584 6585 // Ignore empty records. 6586 if (isEmptyRecord(getContext(), Ty, true)) 6587 return ABIArgInfo::getIgnore(); 6588 6589 if (IsAAPCS_VFP) { 6590 // Homogeneous Aggregates need to be expanded when we can fit the aggregate 6591 // into VFP registers. 6592 const Type *Base = nullptr; 6593 uint64_t Members = 0; 6594 if (isHomogeneousAggregate(Ty, Base, Members)) 6595 return classifyHomogeneousAggregate(Ty, Base, Members); 6596 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) { 6597 // WatchOS does have homogeneous aggregates. Note that we intentionally use 6598 // this convention even for a variadic function: the backend will use GPRs 6599 // if needed. 6600 const Type *Base = nullptr; 6601 uint64_t Members = 0; 6602 if (isHomogeneousAggregate(Ty, Base, Members)) { 6603 assert(Base && Members <= 4 && "unexpected homogeneous aggregate"); 6604 llvm::Type *Ty = 6605 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members); 6606 return ABIArgInfo::getDirect(Ty, 0, nullptr, false); 6607 } 6608 } 6609 6610 if (getABIKind() == ARMABIInfo::AAPCS16_VFP && 6611 getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(16)) { 6612 // WatchOS is adopting the 64-bit AAPCS rule on composite types: if they're 6613 // bigger than 128-bits, they get placed in space allocated by the caller, 6614 // and a pointer is passed. 6615 return ABIArgInfo::getIndirect( 6616 CharUnits::fromQuantity(getContext().getTypeAlign(Ty) / 8), false); 6617 } 6618 6619 // Support byval for ARM. 6620 // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at 6621 // most 8-byte. We realign the indirect argument if type alignment is bigger 6622 // than ABI alignment. 6623 uint64_t ABIAlign = 4; 6624 uint64_t TyAlign; 6625 if (getABIKind() == ARMABIInfo::AAPCS_VFP || 6626 getABIKind() == ARMABIInfo::AAPCS) { 6627 TyAlign = getContext().getTypeUnadjustedAlignInChars(Ty).getQuantity(); 6628 ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8); 6629 } else { 6630 TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity(); 6631 } 6632 if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) { 6633 assert(getABIKind() != ARMABIInfo::AAPCS16_VFP && "unexpected byval"); 6634 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign), 6635 /*ByVal=*/true, 6636 /*Realign=*/TyAlign > ABIAlign); 6637 } 6638 6639 // On RenderScript, coerce Aggregates <= 64 bytes to an integer array of 6640 // same size and alignment. 6641 if (getTarget().isRenderScriptTarget()) { 6642 return coerceToIntArray(Ty, getContext(), getVMContext()); 6643 } 6644 6645 // Otherwise, pass by coercing to a structure of the appropriate size. 6646 llvm::Type* ElemTy; 6647 unsigned SizeRegs; 6648 // FIXME: Try to match the types of the arguments more accurately where 6649 // we can. 6650 if (TyAlign <= 4) { 6651 ElemTy = llvm::Type::getInt32Ty(getVMContext()); 6652 SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32; 6653 } else { 6654 ElemTy = llvm::Type::getInt64Ty(getVMContext()); 6655 SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64; 6656 } 6657 6658 return ABIArgInfo::getDirect(llvm::ArrayType::get(ElemTy, SizeRegs)); 6659 } 6660 6661 static bool isIntegerLikeType(QualType Ty, ASTContext &Context, 6662 llvm::LLVMContext &VMContext) { 6663 // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure 6664 // is called integer-like if its size is less than or equal to one word, and 6665 // the offset of each of its addressable sub-fields is zero. 6666 6667 uint64_t Size = Context.getTypeSize(Ty); 6668 6669 // Check that the type fits in a word. 6670 if (Size > 32) 6671 return false; 6672 6673 // FIXME: Handle vector types! 6674 if (Ty->isVectorType()) 6675 return false; 6676 6677 // Float types are never treated as "integer like". 6678 if (Ty->isRealFloatingType()) 6679 return false; 6680 6681 // If this is a builtin or pointer type then it is ok. 6682 if (Ty->getAs<BuiltinType>() || Ty->isPointerType()) 6683 return true; 6684 6685 // Small complex integer types are "integer like". 6686 if (const ComplexType *CT = Ty->getAs<ComplexType>()) 6687 return isIntegerLikeType(CT->getElementType(), Context, VMContext); 6688 6689 // Single element and zero sized arrays should be allowed, by the definition 6690 // above, but they are not. 6691 6692 // Otherwise, it must be a record type. 6693 const RecordType *RT = Ty->getAs<RecordType>(); 6694 if (!RT) return false; 6695 6696 // Ignore records with flexible arrays. 6697 const RecordDecl *RD = RT->getDecl(); 6698 if (RD->hasFlexibleArrayMember()) 6699 return false; 6700 6701 // Check that all sub-fields are at offset 0, and are themselves "integer 6702 // like". 6703 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); 6704 6705 bool HadField = false; 6706 unsigned idx = 0; 6707 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 6708 i != e; ++i, ++idx) { 6709 const FieldDecl *FD = *i; 6710 6711 // Bit-fields are not addressable, we only need to verify they are "integer 6712 // like". We still have to disallow a subsequent non-bitfield, for example: 6713 // struct { int : 0; int x } 6714 // is non-integer like according to gcc. 6715 if (FD->isBitField()) { 6716 if (!RD->isUnion()) 6717 HadField = true; 6718 6719 if (!isIntegerLikeType(FD->getType(), Context, VMContext)) 6720 return false; 6721 6722 continue; 6723 } 6724 6725 // Check if this field is at offset 0. 6726 if (Layout.getFieldOffset(idx) != 0) 6727 return false; 6728 6729 if (!isIntegerLikeType(FD->getType(), Context, VMContext)) 6730 return false; 6731 6732 // Only allow at most one field in a structure. This doesn't match the 6733 // wording above, but follows gcc in situations with a field following an 6734 // empty structure. 6735 if (!RD->isUnion()) { 6736 if (HadField) 6737 return false; 6738 6739 HadField = true; 6740 } 6741 } 6742 6743 return true; 6744 } 6745 6746 ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy, bool isVariadic, 6747 unsigned functionCallConv) const { 6748 6749 // Variadic functions should always marshal to the base standard. 6750 bool IsAAPCS_VFP = 6751 !isVariadic && isEffectivelyAAPCS_VFP(functionCallConv, /* AAPCS16 */ true); 6752 6753 if (RetTy->isVoidType()) 6754 return ABIArgInfo::getIgnore(); 6755 6756 if (const VectorType *VT = RetTy->getAs<VectorType>()) { 6757 // Large vector types should be returned via memory. 6758 if (getContext().getTypeSize(RetTy) > 128) 6759 return getNaturalAlignIndirect(RetTy); 6760 // TODO: FP16/BF16 vectors should be converted to integer vectors 6761 // This check is similar to isIllegalVectorType - refactor? 6762 if ((!getTarget().hasLegalHalfType() && 6763 (VT->getElementType()->isFloat16Type() || 6764 VT->getElementType()->isHalfType())) || 6765 (IsFloatABISoftFP && 6766 VT->getElementType()->isBFloat16Type())) 6767 return coerceIllegalVector(RetTy); 6768 } 6769 6770 if (!isAggregateTypeForABI(RetTy)) { 6771 // Treat an enum type as its underlying type. 6772 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 6773 RetTy = EnumTy->getDecl()->getIntegerType(); 6774 6775 if (const auto *EIT = RetTy->getAs<ExtIntType>()) 6776 if (EIT->getNumBits() > 64) 6777 return getNaturalAlignIndirect(RetTy, /*ByVal=*/false); 6778 6779 return isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy) 6780 : ABIArgInfo::getDirect(); 6781 } 6782 6783 // Are we following APCS? 6784 if (getABIKind() == APCS) { 6785 if (isEmptyRecord(getContext(), RetTy, false)) 6786 return ABIArgInfo::getIgnore(); 6787 6788 // Complex types are all returned as packed integers. 6789 // 6790 // FIXME: Consider using 2 x vector types if the back end handles them 6791 // correctly. 6792 if (RetTy->isAnyComplexType()) 6793 return ABIArgInfo::getDirect(llvm::IntegerType::get( 6794 getVMContext(), getContext().getTypeSize(RetTy))); 6795 6796 // Integer like structures are returned in r0. 6797 if (isIntegerLikeType(RetTy, getContext(), getVMContext())) { 6798 // Return in the smallest viable integer type. 6799 uint64_t Size = getContext().getTypeSize(RetTy); 6800 if (Size <= 8) 6801 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext())); 6802 if (Size <= 16) 6803 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext())); 6804 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext())); 6805 } 6806 6807 // Otherwise return in memory. 6808 return getNaturalAlignIndirect(RetTy); 6809 } 6810 6811 // Otherwise this is an AAPCS variant. 6812 6813 if (isEmptyRecord(getContext(), RetTy, true)) 6814 return ABIArgInfo::getIgnore(); 6815 6816 // Check for homogeneous aggregates with AAPCS-VFP. 6817 if (IsAAPCS_VFP) { 6818 const Type *Base = nullptr; 6819 uint64_t Members = 0; 6820 if (isHomogeneousAggregate(RetTy, Base, Members)) 6821 return classifyHomogeneousAggregate(RetTy, Base, Members); 6822 } 6823 6824 // Aggregates <= 4 bytes are returned in r0; other aggregates 6825 // are returned indirectly. 6826 uint64_t Size = getContext().getTypeSize(RetTy); 6827 if (Size <= 32) { 6828 // On RenderScript, coerce Aggregates <= 4 bytes to an integer array of 6829 // same size and alignment. 6830 if (getTarget().isRenderScriptTarget()) { 6831 return coerceToIntArray(RetTy, getContext(), getVMContext()); 6832 } 6833 if (getDataLayout().isBigEndian()) 6834 // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4) 6835 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext())); 6836 6837 // Return in the smallest viable integer type. 6838 if (Size <= 8) 6839 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext())); 6840 if (Size <= 16) 6841 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext())); 6842 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext())); 6843 } else if (Size <= 128 && getABIKind() == AAPCS16_VFP) { 6844 llvm::Type *Int32Ty = llvm::Type::getInt32Ty(getVMContext()); 6845 llvm::Type *CoerceTy = 6846 llvm::ArrayType::get(Int32Ty, llvm::alignTo(Size, 32) / 32); 6847 return ABIArgInfo::getDirect(CoerceTy); 6848 } 6849 6850 return getNaturalAlignIndirect(RetTy); 6851 } 6852 6853 /// isIllegalVector - check whether Ty is an illegal vector type. 6854 bool ARMABIInfo::isIllegalVectorType(QualType Ty) const { 6855 if (const VectorType *VT = Ty->getAs<VectorType> ()) { 6856 // On targets that don't support half, fp16 or bfloat, they are expanded 6857 // into float, and we don't want the ABI to depend on whether or not they 6858 // are supported in hardware. Thus return false to coerce vectors of these 6859 // types into integer vectors. 6860 // We do not depend on hasLegalHalfType for bfloat as it is a 6861 // separate IR type. 6862 if ((!getTarget().hasLegalHalfType() && 6863 (VT->getElementType()->isFloat16Type() || 6864 VT->getElementType()->isHalfType())) || 6865 (IsFloatABISoftFP && 6866 VT->getElementType()->isBFloat16Type())) 6867 return true; 6868 if (isAndroid()) { 6869 // Android shipped using Clang 3.1, which supported a slightly different 6870 // vector ABI. The primary differences were that 3-element vector types 6871 // were legal, and so were sub 32-bit vectors (i.e. <2 x i8>). This path 6872 // accepts that legacy behavior for Android only. 6873 // Check whether VT is legal. 6874 unsigned NumElements = VT->getNumElements(); 6875 // NumElements should be power of 2 or equal to 3. 6876 if (!llvm::isPowerOf2_32(NumElements) && NumElements != 3) 6877 return true; 6878 } else { 6879 // Check whether VT is legal. 6880 unsigned NumElements = VT->getNumElements(); 6881 uint64_t Size = getContext().getTypeSize(VT); 6882 // NumElements should be power of 2. 6883 if (!llvm::isPowerOf2_32(NumElements)) 6884 return true; 6885 // Size should be greater than 32 bits. 6886 return Size <= 32; 6887 } 6888 } 6889 return false; 6890 } 6891 6892 /// Return true if a type contains any 16-bit floating point vectors 6893 bool ARMABIInfo::containsAnyFP16Vectors(QualType Ty) const { 6894 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) { 6895 uint64_t NElements = AT->getSize().getZExtValue(); 6896 if (NElements == 0) 6897 return false; 6898 return containsAnyFP16Vectors(AT->getElementType()); 6899 } else if (const RecordType *RT = Ty->getAs<RecordType>()) { 6900 const RecordDecl *RD = RT->getDecl(); 6901 6902 // If this is a C++ record, check the bases first. 6903 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 6904 if (llvm::any_of(CXXRD->bases(), [this](const CXXBaseSpecifier &B) { 6905 return containsAnyFP16Vectors(B.getType()); 6906 })) 6907 return true; 6908 6909 if (llvm::any_of(RD->fields(), [this](FieldDecl *FD) { 6910 return FD && containsAnyFP16Vectors(FD->getType()); 6911 })) 6912 return true; 6913 6914 return false; 6915 } else { 6916 if (const VectorType *VT = Ty->getAs<VectorType>()) 6917 return (VT->getElementType()->isFloat16Type() || 6918 VT->getElementType()->isBFloat16Type() || 6919 VT->getElementType()->isHalfType()); 6920 return false; 6921 } 6922 } 6923 6924 bool ARMABIInfo::isLegalVectorTypeForSwift(CharUnits vectorSize, 6925 llvm::Type *eltTy, 6926 unsigned numElts) const { 6927 if (!llvm::isPowerOf2_32(numElts)) 6928 return false; 6929 unsigned size = getDataLayout().getTypeStoreSizeInBits(eltTy); 6930 if (size > 64) 6931 return false; 6932 if (vectorSize.getQuantity() != 8 && 6933 (vectorSize.getQuantity() != 16 || numElts == 1)) 6934 return false; 6935 return true; 6936 } 6937 6938 bool ARMABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const { 6939 // Homogeneous aggregates for AAPCS-VFP must have base types of float, 6940 // double, or 64-bit or 128-bit vectors. 6941 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) { 6942 if (BT->getKind() == BuiltinType::Float || 6943 BT->getKind() == BuiltinType::Double || 6944 BT->getKind() == BuiltinType::LongDouble) 6945 return true; 6946 } else if (const VectorType *VT = Ty->getAs<VectorType>()) { 6947 unsigned VecSize = getContext().getTypeSize(VT); 6948 if (VecSize == 64 || VecSize == 128) 6949 return true; 6950 } 6951 return false; 6952 } 6953 6954 bool ARMABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base, 6955 uint64_t Members) const { 6956 return Members <= 4; 6957 } 6958 6959 bool ARMABIInfo::isEffectivelyAAPCS_VFP(unsigned callConvention, 6960 bool acceptHalf) const { 6961 // Give precedence to user-specified calling conventions. 6962 if (callConvention != llvm::CallingConv::C) 6963 return (callConvention == llvm::CallingConv::ARM_AAPCS_VFP); 6964 else 6965 return (getABIKind() == AAPCS_VFP) || 6966 (acceptHalf && (getABIKind() == AAPCS16_VFP)); 6967 } 6968 6969 Address ARMABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 6970 QualType Ty) const { 6971 CharUnits SlotSize = CharUnits::fromQuantity(4); 6972 6973 // Empty records are ignored for parameter passing purposes. 6974 if (isEmptyRecord(getContext(), Ty, true)) { 6975 Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize); 6976 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty)); 6977 return Addr; 6978 } 6979 6980 CharUnits TySize = getContext().getTypeSizeInChars(Ty); 6981 CharUnits TyAlignForABI = getContext().getTypeUnadjustedAlignInChars(Ty); 6982 6983 // Use indirect if size of the illegal vector is bigger than 16 bytes. 6984 bool IsIndirect = false; 6985 const Type *Base = nullptr; 6986 uint64_t Members = 0; 6987 if (TySize > CharUnits::fromQuantity(16) && isIllegalVectorType(Ty)) { 6988 IsIndirect = true; 6989 6990 // ARMv7k passes structs bigger than 16 bytes indirectly, in space 6991 // allocated by the caller. 6992 } else if (TySize > CharUnits::fromQuantity(16) && 6993 getABIKind() == ARMABIInfo::AAPCS16_VFP && 6994 !isHomogeneousAggregate(Ty, Base, Members)) { 6995 IsIndirect = true; 6996 6997 // Otherwise, bound the type's ABI alignment. 6998 // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for 6999 // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte. 7000 // Our callers should be prepared to handle an under-aligned address. 7001 } else if (getABIKind() == ARMABIInfo::AAPCS_VFP || 7002 getABIKind() == ARMABIInfo::AAPCS) { 7003 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4)); 7004 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(8)); 7005 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) { 7006 // ARMv7k allows type alignment up to 16 bytes. 7007 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4)); 7008 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(16)); 7009 } else { 7010 TyAlignForABI = CharUnits::fromQuantity(4); 7011 } 7012 7013 TypeInfoChars TyInfo(TySize, TyAlignForABI, AlignRequirementKind::None); 7014 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TyInfo, 7015 SlotSize, /*AllowHigherAlign*/ true); 7016 } 7017 7018 //===----------------------------------------------------------------------===// 7019 // NVPTX ABI Implementation 7020 //===----------------------------------------------------------------------===// 7021 7022 namespace { 7023 7024 class NVPTXTargetCodeGenInfo; 7025 7026 class NVPTXABIInfo : public ABIInfo { 7027 NVPTXTargetCodeGenInfo &CGInfo; 7028 7029 public: 7030 NVPTXABIInfo(CodeGenTypes &CGT, NVPTXTargetCodeGenInfo &Info) 7031 : ABIInfo(CGT), CGInfo(Info) {} 7032 7033 ABIArgInfo classifyReturnType(QualType RetTy) const; 7034 ABIArgInfo classifyArgumentType(QualType Ty) const; 7035 7036 void computeInfo(CGFunctionInfo &FI) const override; 7037 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 7038 QualType Ty) const override; 7039 bool isUnsupportedType(QualType T) const; 7040 ABIArgInfo coerceToIntArrayWithLimit(QualType Ty, unsigned MaxSize) const; 7041 }; 7042 7043 class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo { 7044 public: 7045 NVPTXTargetCodeGenInfo(CodeGenTypes &CGT) 7046 : TargetCodeGenInfo(std::make_unique<NVPTXABIInfo>(CGT, *this)) {} 7047 7048 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 7049 CodeGen::CodeGenModule &M) const override; 7050 bool shouldEmitStaticExternCAliases() const override; 7051 7052 llvm::Type *getCUDADeviceBuiltinSurfaceDeviceType() const override { 7053 // On the device side, surface reference is represented as an object handle 7054 // in 64-bit integer. 7055 return llvm::Type::getInt64Ty(getABIInfo().getVMContext()); 7056 } 7057 7058 llvm::Type *getCUDADeviceBuiltinTextureDeviceType() const override { 7059 // On the device side, texture reference is represented as an object handle 7060 // in 64-bit integer. 7061 return llvm::Type::getInt64Ty(getABIInfo().getVMContext()); 7062 } 7063 7064 bool emitCUDADeviceBuiltinSurfaceDeviceCopy(CodeGenFunction &CGF, LValue Dst, 7065 LValue Src) const override { 7066 emitBuiltinSurfTexDeviceCopy(CGF, Dst, Src); 7067 return true; 7068 } 7069 7070 bool emitCUDADeviceBuiltinTextureDeviceCopy(CodeGenFunction &CGF, LValue Dst, 7071 LValue Src) const override { 7072 emitBuiltinSurfTexDeviceCopy(CGF, Dst, Src); 7073 return true; 7074 } 7075 7076 private: 7077 // Adds a NamedMDNode with GV, Name, and Operand as operands, and adds the 7078 // resulting MDNode to the nvvm.annotations MDNode. 7079 static void addNVVMMetadata(llvm::GlobalValue *GV, StringRef Name, 7080 int Operand); 7081 7082 static void emitBuiltinSurfTexDeviceCopy(CodeGenFunction &CGF, LValue Dst, 7083 LValue Src) { 7084 llvm::Value *Handle = nullptr; 7085 llvm::Constant *C = 7086 llvm::dyn_cast<llvm::Constant>(Src.getAddress(CGF).getPointer()); 7087 // Lookup `addrspacecast` through the constant pointer if any. 7088 if (auto *ASC = llvm::dyn_cast_or_null<llvm::AddrSpaceCastOperator>(C)) 7089 C = llvm::cast<llvm::Constant>(ASC->getPointerOperand()); 7090 if (auto *GV = llvm::dyn_cast_or_null<llvm::GlobalVariable>(C)) { 7091 // Load the handle from the specific global variable using 7092 // `nvvm.texsurf.handle.internal` intrinsic. 7093 Handle = CGF.EmitRuntimeCall( 7094 CGF.CGM.getIntrinsic(llvm::Intrinsic::nvvm_texsurf_handle_internal, 7095 {GV->getType()}), 7096 {GV}, "texsurf_handle"); 7097 } else 7098 Handle = CGF.EmitLoadOfScalar(Src, SourceLocation()); 7099 CGF.EmitStoreOfScalar(Handle, Dst); 7100 } 7101 }; 7102 7103 /// Checks if the type is unsupported directly by the current target. 7104 bool NVPTXABIInfo::isUnsupportedType(QualType T) const { 7105 ASTContext &Context = getContext(); 7106 if (!Context.getTargetInfo().hasFloat16Type() && T->isFloat16Type()) 7107 return true; 7108 if (!Context.getTargetInfo().hasFloat128Type() && 7109 (T->isFloat128Type() || 7110 (T->isRealFloatingType() && Context.getTypeSize(T) == 128))) 7111 return true; 7112 if (const auto *EIT = T->getAs<ExtIntType>()) 7113 return EIT->getNumBits() > 7114 (Context.getTargetInfo().hasInt128Type() ? 128U : 64U); 7115 if (!Context.getTargetInfo().hasInt128Type() && T->isIntegerType() && 7116 Context.getTypeSize(T) > 64U) 7117 return true; 7118 if (const auto *AT = T->getAsArrayTypeUnsafe()) 7119 return isUnsupportedType(AT->getElementType()); 7120 const auto *RT = T->getAs<RecordType>(); 7121 if (!RT) 7122 return false; 7123 const RecordDecl *RD = RT->getDecl(); 7124 7125 // If this is a C++ record, check the bases first. 7126 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 7127 for (const CXXBaseSpecifier &I : CXXRD->bases()) 7128 if (isUnsupportedType(I.getType())) 7129 return true; 7130 7131 for (const FieldDecl *I : RD->fields()) 7132 if (isUnsupportedType(I->getType())) 7133 return true; 7134 return false; 7135 } 7136 7137 /// Coerce the given type into an array with maximum allowed size of elements. 7138 ABIArgInfo NVPTXABIInfo::coerceToIntArrayWithLimit(QualType Ty, 7139 unsigned MaxSize) const { 7140 // Alignment and Size are measured in bits. 7141 const uint64_t Size = getContext().getTypeSize(Ty); 7142 const uint64_t Alignment = getContext().getTypeAlign(Ty); 7143 const unsigned Div = std::min<unsigned>(MaxSize, Alignment); 7144 llvm::Type *IntType = llvm::Type::getIntNTy(getVMContext(), Div); 7145 const uint64_t NumElements = (Size + Div - 1) / Div; 7146 return ABIArgInfo::getDirect(llvm::ArrayType::get(IntType, NumElements)); 7147 } 7148 7149 ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const { 7150 if (RetTy->isVoidType()) 7151 return ABIArgInfo::getIgnore(); 7152 7153 if (getContext().getLangOpts().OpenMP && 7154 getContext().getLangOpts().OpenMPIsDevice && isUnsupportedType(RetTy)) 7155 return coerceToIntArrayWithLimit(RetTy, 64); 7156 7157 // note: this is different from default ABI 7158 if (!RetTy->isScalarType()) 7159 return ABIArgInfo::getDirect(); 7160 7161 // Treat an enum type as its underlying type. 7162 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 7163 RetTy = EnumTy->getDecl()->getIntegerType(); 7164 7165 return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy) 7166 : ABIArgInfo::getDirect()); 7167 } 7168 7169 ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const { 7170 // Treat an enum type as its underlying type. 7171 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 7172 Ty = EnumTy->getDecl()->getIntegerType(); 7173 7174 // Return aggregates type as indirect by value 7175 if (isAggregateTypeForABI(Ty)) { 7176 // Under CUDA device compilation, tex/surf builtin types are replaced with 7177 // object types and passed directly. 7178 if (getContext().getLangOpts().CUDAIsDevice) { 7179 if (Ty->isCUDADeviceBuiltinSurfaceType()) 7180 return ABIArgInfo::getDirect( 7181 CGInfo.getCUDADeviceBuiltinSurfaceDeviceType()); 7182 if (Ty->isCUDADeviceBuiltinTextureType()) 7183 return ABIArgInfo::getDirect( 7184 CGInfo.getCUDADeviceBuiltinTextureDeviceType()); 7185 } 7186 return getNaturalAlignIndirect(Ty, /* byval */ true); 7187 } 7188 7189 if (const auto *EIT = Ty->getAs<ExtIntType>()) { 7190 if ((EIT->getNumBits() > 128) || 7191 (!getContext().getTargetInfo().hasInt128Type() && 7192 EIT->getNumBits() > 64)) 7193 return getNaturalAlignIndirect(Ty, /* byval */ true); 7194 } 7195 7196 return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty) 7197 : ABIArgInfo::getDirect()); 7198 } 7199 7200 void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const { 7201 if (!getCXXABI().classifyReturnType(FI)) 7202 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 7203 for (auto &I : FI.arguments()) 7204 I.info = classifyArgumentType(I.type); 7205 7206 // Always honor user-specified calling convention. 7207 if (FI.getCallingConvention() != llvm::CallingConv::C) 7208 return; 7209 7210 FI.setEffectiveCallingConvention(getRuntimeCC()); 7211 } 7212 7213 Address NVPTXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 7214 QualType Ty) const { 7215 llvm_unreachable("NVPTX does not support varargs"); 7216 } 7217 7218 void NVPTXTargetCodeGenInfo::setTargetAttributes( 7219 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const { 7220 if (GV->isDeclaration()) 7221 return; 7222 const VarDecl *VD = dyn_cast_or_null<VarDecl>(D); 7223 if (VD) { 7224 if (M.getLangOpts().CUDA) { 7225 if (VD->getType()->isCUDADeviceBuiltinSurfaceType()) 7226 addNVVMMetadata(GV, "surface", 1); 7227 else if (VD->getType()->isCUDADeviceBuiltinTextureType()) 7228 addNVVMMetadata(GV, "texture", 1); 7229 return; 7230 } 7231 } 7232 7233 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D); 7234 if (!FD) return; 7235 7236 llvm::Function *F = cast<llvm::Function>(GV); 7237 7238 // Perform special handling in OpenCL mode 7239 if (M.getLangOpts().OpenCL) { 7240 // Use OpenCL function attributes to check for kernel functions 7241 // By default, all functions are device functions 7242 if (FD->hasAttr<OpenCLKernelAttr>()) { 7243 // OpenCL __kernel functions get kernel metadata 7244 // Create !{<func-ref>, metadata !"kernel", i32 1} node 7245 addNVVMMetadata(F, "kernel", 1); 7246 // And kernel functions are not subject to inlining 7247 F->addFnAttr(llvm::Attribute::NoInline); 7248 } 7249 } 7250 7251 // Perform special handling in CUDA mode. 7252 if (M.getLangOpts().CUDA) { 7253 // CUDA __global__ functions get a kernel metadata entry. Since 7254 // __global__ functions cannot be called from the device, we do not 7255 // need to set the noinline attribute. 7256 if (FD->hasAttr<CUDAGlobalAttr>()) { 7257 // Create !{<func-ref>, metadata !"kernel", i32 1} node 7258 addNVVMMetadata(F, "kernel", 1); 7259 } 7260 if (CUDALaunchBoundsAttr *Attr = FD->getAttr<CUDALaunchBoundsAttr>()) { 7261 // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node 7262 llvm::APSInt MaxThreads(32); 7263 MaxThreads = Attr->getMaxThreads()->EvaluateKnownConstInt(M.getContext()); 7264 if (MaxThreads > 0) 7265 addNVVMMetadata(F, "maxntidx", MaxThreads.getExtValue()); 7266 7267 // min blocks is an optional argument for CUDALaunchBoundsAttr. If it was 7268 // not specified in __launch_bounds__ or if the user specified a 0 value, 7269 // we don't have to add a PTX directive. 7270 if (Attr->getMinBlocks()) { 7271 llvm::APSInt MinBlocks(32); 7272 MinBlocks = Attr->getMinBlocks()->EvaluateKnownConstInt(M.getContext()); 7273 if (MinBlocks > 0) 7274 // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node 7275 addNVVMMetadata(F, "minctasm", MinBlocks.getExtValue()); 7276 } 7277 } 7278 } 7279 } 7280 7281 void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::GlobalValue *GV, 7282 StringRef Name, int Operand) { 7283 llvm::Module *M = GV->getParent(); 7284 llvm::LLVMContext &Ctx = M->getContext(); 7285 7286 // Get "nvvm.annotations" metadata node 7287 llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations"); 7288 7289 llvm::Metadata *MDVals[] = { 7290 llvm::ConstantAsMetadata::get(GV), llvm::MDString::get(Ctx, Name), 7291 llvm::ConstantAsMetadata::get( 7292 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand))}; 7293 // Append metadata to nvvm.annotations 7294 MD->addOperand(llvm::MDNode::get(Ctx, MDVals)); 7295 } 7296 7297 bool NVPTXTargetCodeGenInfo::shouldEmitStaticExternCAliases() const { 7298 return false; 7299 } 7300 } 7301 7302 //===----------------------------------------------------------------------===// 7303 // SystemZ ABI Implementation 7304 //===----------------------------------------------------------------------===// 7305 7306 namespace { 7307 7308 class SystemZABIInfo : public SwiftABIInfo { 7309 bool HasVector; 7310 bool IsSoftFloatABI; 7311 7312 public: 7313 SystemZABIInfo(CodeGenTypes &CGT, bool HV, bool SF) 7314 : SwiftABIInfo(CGT), HasVector(HV), IsSoftFloatABI(SF) {} 7315 7316 bool isPromotableIntegerTypeForABI(QualType Ty) const; 7317 bool isCompoundType(QualType Ty) const; 7318 bool isVectorArgumentType(QualType Ty) const; 7319 bool isFPArgumentType(QualType Ty) const; 7320 QualType GetSingleElementType(QualType Ty) const; 7321 7322 ABIArgInfo classifyReturnType(QualType RetTy) const; 7323 ABIArgInfo classifyArgumentType(QualType ArgTy) const; 7324 7325 void computeInfo(CGFunctionInfo &FI) const override { 7326 if (!getCXXABI().classifyReturnType(FI)) 7327 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 7328 for (auto &I : FI.arguments()) 7329 I.info = classifyArgumentType(I.type); 7330 } 7331 7332 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 7333 QualType Ty) const override; 7334 7335 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars, 7336 bool asReturnValue) const override { 7337 return occupiesMoreThan(CGT, scalars, /*total*/ 4); 7338 } 7339 bool isSwiftErrorInRegister() const override { 7340 return false; 7341 } 7342 }; 7343 7344 class SystemZTargetCodeGenInfo : public TargetCodeGenInfo { 7345 public: 7346 SystemZTargetCodeGenInfo(CodeGenTypes &CGT, bool HasVector, bool SoftFloatABI) 7347 : TargetCodeGenInfo( 7348 std::make_unique<SystemZABIInfo>(CGT, HasVector, SoftFloatABI)) {} 7349 7350 llvm::Value *testFPKind(llvm::Value *V, unsigned BuiltinID, 7351 CGBuilderTy &Builder, 7352 CodeGenModule &CGM) const override { 7353 assert(V->getType()->isFloatingPointTy() && "V should have an FP type."); 7354 // Only use TDC in constrained FP mode. 7355 if (!Builder.getIsFPConstrained()) 7356 return nullptr; 7357 7358 llvm::Type *Ty = V->getType(); 7359 if (Ty->isFloatTy() || Ty->isDoubleTy() || Ty->isFP128Ty()) { 7360 llvm::Module &M = CGM.getModule(); 7361 auto &Ctx = M.getContext(); 7362 llvm::Function *TDCFunc = 7363 llvm::Intrinsic::getDeclaration(&M, llvm::Intrinsic::s390_tdc, Ty); 7364 unsigned TDCBits = 0; 7365 switch (BuiltinID) { 7366 case Builtin::BI__builtin_isnan: 7367 TDCBits = 0xf; 7368 break; 7369 case Builtin::BIfinite: 7370 case Builtin::BI__finite: 7371 case Builtin::BIfinitef: 7372 case Builtin::BI__finitef: 7373 case Builtin::BIfinitel: 7374 case Builtin::BI__finitel: 7375 case Builtin::BI__builtin_isfinite: 7376 TDCBits = 0xfc0; 7377 break; 7378 case Builtin::BI__builtin_isinf: 7379 TDCBits = 0x30; 7380 break; 7381 default: 7382 break; 7383 } 7384 if (TDCBits) 7385 return Builder.CreateCall( 7386 TDCFunc, 7387 {V, llvm::ConstantInt::get(llvm::Type::getInt64Ty(Ctx), TDCBits)}); 7388 } 7389 return nullptr; 7390 } 7391 }; 7392 } 7393 7394 bool SystemZABIInfo::isPromotableIntegerTypeForABI(QualType Ty) const { 7395 // Treat an enum type as its underlying type. 7396 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 7397 Ty = EnumTy->getDecl()->getIntegerType(); 7398 7399 // Promotable integer types are required to be promoted by the ABI. 7400 if (ABIInfo::isPromotableIntegerTypeForABI(Ty)) 7401 return true; 7402 7403 if (const auto *EIT = Ty->getAs<ExtIntType>()) 7404 if (EIT->getNumBits() < 64) 7405 return true; 7406 7407 // 32-bit values must also be promoted. 7408 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) 7409 switch (BT->getKind()) { 7410 case BuiltinType::Int: 7411 case BuiltinType::UInt: 7412 return true; 7413 default: 7414 return false; 7415 } 7416 return false; 7417 } 7418 7419 bool SystemZABIInfo::isCompoundType(QualType Ty) const { 7420 return (Ty->isAnyComplexType() || 7421 Ty->isVectorType() || 7422 isAggregateTypeForABI(Ty)); 7423 } 7424 7425 bool SystemZABIInfo::isVectorArgumentType(QualType Ty) const { 7426 return (HasVector && 7427 Ty->isVectorType() && 7428 getContext().getTypeSize(Ty) <= 128); 7429 } 7430 7431 bool SystemZABIInfo::isFPArgumentType(QualType Ty) const { 7432 if (IsSoftFloatABI) 7433 return false; 7434 7435 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) 7436 switch (BT->getKind()) { 7437 case BuiltinType::Float: 7438 case BuiltinType::Double: 7439 return true; 7440 default: 7441 return false; 7442 } 7443 7444 return false; 7445 } 7446 7447 QualType SystemZABIInfo::GetSingleElementType(QualType Ty) const { 7448 const RecordType *RT = Ty->getAs<RecordType>(); 7449 7450 if (RT && RT->isStructureOrClassType()) { 7451 const RecordDecl *RD = RT->getDecl(); 7452 QualType Found; 7453 7454 // If this is a C++ record, check the bases first. 7455 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 7456 for (const auto &I : CXXRD->bases()) { 7457 QualType Base = I.getType(); 7458 7459 // Empty bases don't affect things either way. 7460 if (isEmptyRecord(getContext(), Base, true)) 7461 continue; 7462 7463 if (!Found.isNull()) 7464 return Ty; 7465 Found = GetSingleElementType(Base); 7466 } 7467 7468 // Check the fields. 7469 for (const auto *FD : RD->fields()) { 7470 // For compatibility with GCC, ignore empty bitfields in C++ mode. 7471 // Unlike isSingleElementStruct(), empty structure and array fields 7472 // do count. So do anonymous bitfields that aren't zero-sized. 7473 if (getContext().getLangOpts().CPlusPlus && 7474 FD->isZeroLengthBitField(getContext())) 7475 continue; 7476 // Like isSingleElementStruct(), ignore C++20 empty data members. 7477 if (FD->hasAttr<NoUniqueAddressAttr>() && 7478 isEmptyRecord(getContext(), FD->getType(), true)) 7479 continue; 7480 7481 // Unlike isSingleElementStruct(), arrays do not count. 7482 // Nested structures still do though. 7483 if (!Found.isNull()) 7484 return Ty; 7485 Found = GetSingleElementType(FD->getType()); 7486 } 7487 7488 // Unlike isSingleElementStruct(), trailing padding is allowed. 7489 // An 8-byte aligned struct s { float f; } is passed as a double. 7490 if (!Found.isNull()) 7491 return Found; 7492 } 7493 7494 return Ty; 7495 } 7496 7497 Address SystemZABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 7498 QualType Ty) const { 7499 // Assume that va_list type is correct; should be pointer to LLVM type: 7500 // struct { 7501 // i64 __gpr; 7502 // i64 __fpr; 7503 // i8 *__overflow_arg_area; 7504 // i8 *__reg_save_area; 7505 // }; 7506 7507 // Every non-vector argument occupies 8 bytes and is passed by preference 7508 // in either GPRs or FPRs. Vector arguments occupy 8 or 16 bytes and are 7509 // always passed on the stack. 7510 Ty = getContext().getCanonicalType(Ty); 7511 auto TyInfo = getContext().getTypeInfoInChars(Ty); 7512 llvm::Type *ArgTy = CGF.ConvertTypeForMem(Ty); 7513 llvm::Type *DirectTy = ArgTy; 7514 ABIArgInfo AI = classifyArgumentType(Ty); 7515 bool IsIndirect = AI.isIndirect(); 7516 bool InFPRs = false; 7517 bool IsVector = false; 7518 CharUnits UnpaddedSize; 7519 CharUnits DirectAlign; 7520 if (IsIndirect) { 7521 DirectTy = llvm::PointerType::getUnqual(DirectTy); 7522 UnpaddedSize = DirectAlign = CharUnits::fromQuantity(8); 7523 } else { 7524 if (AI.getCoerceToType()) 7525 ArgTy = AI.getCoerceToType(); 7526 InFPRs = (!IsSoftFloatABI && (ArgTy->isFloatTy() || ArgTy->isDoubleTy())); 7527 IsVector = ArgTy->isVectorTy(); 7528 UnpaddedSize = TyInfo.Width; 7529 DirectAlign = TyInfo.Align; 7530 } 7531 CharUnits PaddedSize = CharUnits::fromQuantity(8); 7532 if (IsVector && UnpaddedSize > PaddedSize) 7533 PaddedSize = CharUnits::fromQuantity(16); 7534 assert((UnpaddedSize <= PaddedSize) && "Invalid argument size."); 7535 7536 CharUnits Padding = (PaddedSize - UnpaddedSize); 7537 7538 llvm::Type *IndexTy = CGF.Int64Ty; 7539 llvm::Value *PaddedSizeV = 7540 llvm::ConstantInt::get(IndexTy, PaddedSize.getQuantity()); 7541 7542 if (IsVector) { 7543 // Work out the address of a vector argument on the stack. 7544 // Vector arguments are always passed in the high bits of a 7545 // single (8 byte) or double (16 byte) stack slot. 7546 Address OverflowArgAreaPtr = 7547 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr"); 7548 Address OverflowArgArea = 7549 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"), 7550 TyInfo.Align); 7551 Address MemAddr = 7552 CGF.Builder.CreateElementBitCast(OverflowArgArea, DirectTy, "mem_addr"); 7553 7554 // Update overflow_arg_area_ptr pointer 7555 llvm::Value *NewOverflowArgArea = 7556 CGF.Builder.CreateGEP(OverflowArgArea.getElementType(), 7557 OverflowArgArea.getPointer(), PaddedSizeV, 7558 "overflow_arg_area"); 7559 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr); 7560 7561 return MemAddr; 7562 } 7563 7564 assert(PaddedSize.getQuantity() == 8); 7565 7566 unsigned MaxRegs, RegCountField, RegSaveIndex; 7567 CharUnits RegPadding; 7568 if (InFPRs) { 7569 MaxRegs = 4; // Maximum of 4 FPR arguments 7570 RegCountField = 1; // __fpr 7571 RegSaveIndex = 16; // save offset for f0 7572 RegPadding = CharUnits(); // floats are passed in the high bits of an FPR 7573 } else { 7574 MaxRegs = 5; // Maximum of 5 GPR arguments 7575 RegCountField = 0; // __gpr 7576 RegSaveIndex = 2; // save offset for r2 7577 RegPadding = Padding; // values are passed in the low bits of a GPR 7578 } 7579 7580 Address RegCountPtr = 7581 CGF.Builder.CreateStructGEP(VAListAddr, RegCountField, "reg_count_ptr"); 7582 llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count"); 7583 llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs); 7584 llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV, 7585 "fits_in_regs"); 7586 7587 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg"); 7588 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem"); 7589 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end"); 7590 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock); 7591 7592 // Emit code to load the value if it was passed in registers. 7593 CGF.EmitBlock(InRegBlock); 7594 7595 // Work out the address of an argument register. 7596 llvm::Value *ScaledRegCount = 7597 CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count"); 7598 llvm::Value *RegBase = 7599 llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize.getQuantity() 7600 + RegPadding.getQuantity()); 7601 llvm::Value *RegOffset = 7602 CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset"); 7603 Address RegSaveAreaPtr = 7604 CGF.Builder.CreateStructGEP(VAListAddr, 3, "reg_save_area_ptr"); 7605 llvm::Value *RegSaveArea = 7606 CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area"); 7607 Address RawRegAddr(CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, RegOffset, 7608 "raw_reg_addr"), 7609 PaddedSize); 7610 Address RegAddr = 7611 CGF.Builder.CreateElementBitCast(RawRegAddr, DirectTy, "reg_addr"); 7612 7613 // Update the register count 7614 llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1); 7615 llvm::Value *NewRegCount = 7616 CGF.Builder.CreateAdd(RegCount, One, "reg_count"); 7617 CGF.Builder.CreateStore(NewRegCount, RegCountPtr); 7618 CGF.EmitBranch(ContBlock); 7619 7620 // Emit code to load the value if it was passed in memory. 7621 CGF.EmitBlock(InMemBlock); 7622 7623 // Work out the address of a stack argument. 7624 Address OverflowArgAreaPtr = 7625 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr"); 7626 Address OverflowArgArea = 7627 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"), 7628 PaddedSize); 7629 Address RawMemAddr = 7630 CGF.Builder.CreateConstByteGEP(OverflowArgArea, Padding, "raw_mem_addr"); 7631 Address MemAddr = 7632 CGF.Builder.CreateElementBitCast(RawMemAddr, DirectTy, "mem_addr"); 7633 7634 // Update overflow_arg_area_ptr pointer 7635 llvm::Value *NewOverflowArgArea = 7636 CGF.Builder.CreateGEP(OverflowArgArea.getElementType(), 7637 OverflowArgArea.getPointer(), PaddedSizeV, 7638 "overflow_arg_area"); 7639 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr); 7640 CGF.EmitBranch(ContBlock); 7641 7642 // Return the appropriate result. 7643 CGF.EmitBlock(ContBlock); 7644 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, 7645 MemAddr, InMemBlock, "va_arg.addr"); 7646 7647 if (IsIndirect) 7648 ResAddr = Address(CGF.Builder.CreateLoad(ResAddr, "indirect_arg"), 7649 TyInfo.Align); 7650 7651 return ResAddr; 7652 } 7653 7654 ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const { 7655 if (RetTy->isVoidType()) 7656 return ABIArgInfo::getIgnore(); 7657 if (isVectorArgumentType(RetTy)) 7658 return ABIArgInfo::getDirect(); 7659 if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64) 7660 return getNaturalAlignIndirect(RetTy); 7661 return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy) 7662 : ABIArgInfo::getDirect()); 7663 } 7664 7665 ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const { 7666 // Handle the generic C++ ABI. 7667 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 7668 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 7669 7670 // Integers and enums are extended to full register width. 7671 if (isPromotableIntegerTypeForABI(Ty)) 7672 return ABIArgInfo::getExtend(Ty); 7673 7674 // Handle vector types and vector-like structure types. Note that 7675 // as opposed to float-like structure types, we do not allow any 7676 // padding for vector-like structures, so verify the sizes match. 7677 uint64_t Size = getContext().getTypeSize(Ty); 7678 QualType SingleElementTy = GetSingleElementType(Ty); 7679 if (isVectorArgumentType(SingleElementTy) && 7680 getContext().getTypeSize(SingleElementTy) == Size) 7681 return ABIArgInfo::getDirect(CGT.ConvertType(SingleElementTy)); 7682 7683 // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly. 7684 if (Size != 8 && Size != 16 && Size != 32 && Size != 64) 7685 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 7686 7687 // Handle small structures. 7688 if (const RecordType *RT = Ty->getAs<RecordType>()) { 7689 // Structures with flexible arrays have variable length, so really 7690 // fail the size test above. 7691 const RecordDecl *RD = RT->getDecl(); 7692 if (RD->hasFlexibleArrayMember()) 7693 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 7694 7695 // The structure is passed as an unextended integer, a float, or a double. 7696 llvm::Type *PassTy; 7697 if (isFPArgumentType(SingleElementTy)) { 7698 assert(Size == 32 || Size == 64); 7699 if (Size == 32) 7700 PassTy = llvm::Type::getFloatTy(getVMContext()); 7701 else 7702 PassTy = llvm::Type::getDoubleTy(getVMContext()); 7703 } else 7704 PassTy = llvm::IntegerType::get(getVMContext(), Size); 7705 return ABIArgInfo::getDirect(PassTy); 7706 } 7707 7708 // Non-structure compounds are passed indirectly. 7709 if (isCompoundType(Ty)) 7710 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 7711 7712 return ABIArgInfo::getDirect(nullptr); 7713 } 7714 7715 //===----------------------------------------------------------------------===// 7716 // MSP430 ABI Implementation 7717 //===----------------------------------------------------------------------===// 7718 7719 namespace { 7720 7721 class MSP430ABIInfo : public DefaultABIInfo { 7722 static ABIArgInfo complexArgInfo() { 7723 ABIArgInfo Info = ABIArgInfo::getDirect(); 7724 Info.setCanBeFlattened(false); 7725 return Info; 7726 } 7727 7728 public: 7729 MSP430ABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {} 7730 7731 ABIArgInfo classifyReturnType(QualType RetTy) const { 7732 if (RetTy->isAnyComplexType()) 7733 return complexArgInfo(); 7734 7735 return DefaultABIInfo::classifyReturnType(RetTy); 7736 } 7737 7738 ABIArgInfo classifyArgumentType(QualType RetTy) const { 7739 if (RetTy->isAnyComplexType()) 7740 return complexArgInfo(); 7741 7742 return DefaultABIInfo::classifyArgumentType(RetTy); 7743 } 7744 7745 // Just copy the original implementations because 7746 // DefaultABIInfo::classify{Return,Argument}Type() are not virtual 7747 void computeInfo(CGFunctionInfo &FI) const override { 7748 if (!getCXXABI().classifyReturnType(FI)) 7749 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 7750 for (auto &I : FI.arguments()) 7751 I.info = classifyArgumentType(I.type); 7752 } 7753 7754 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 7755 QualType Ty) const override { 7756 return EmitVAArgInstr(CGF, VAListAddr, Ty, classifyArgumentType(Ty)); 7757 } 7758 }; 7759 7760 class MSP430TargetCodeGenInfo : public TargetCodeGenInfo { 7761 public: 7762 MSP430TargetCodeGenInfo(CodeGenTypes &CGT) 7763 : TargetCodeGenInfo(std::make_unique<MSP430ABIInfo>(CGT)) {} 7764 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 7765 CodeGen::CodeGenModule &M) const override; 7766 }; 7767 7768 } 7769 7770 void MSP430TargetCodeGenInfo::setTargetAttributes( 7771 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const { 7772 if (GV->isDeclaration()) 7773 return; 7774 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) { 7775 const auto *InterruptAttr = FD->getAttr<MSP430InterruptAttr>(); 7776 if (!InterruptAttr) 7777 return; 7778 7779 // Handle 'interrupt' attribute: 7780 llvm::Function *F = cast<llvm::Function>(GV); 7781 7782 // Step 1: Set ISR calling convention. 7783 F->setCallingConv(llvm::CallingConv::MSP430_INTR); 7784 7785 // Step 2: Add attributes goodness. 7786 F->addFnAttr(llvm::Attribute::NoInline); 7787 F->addFnAttr("interrupt", llvm::utostr(InterruptAttr->getNumber())); 7788 } 7789 } 7790 7791 //===----------------------------------------------------------------------===// 7792 // MIPS ABI Implementation. This works for both little-endian and 7793 // big-endian variants. 7794 //===----------------------------------------------------------------------===// 7795 7796 namespace { 7797 class MipsABIInfo : public ABIInfo { 7798 bool IsO32; 7799 unsigned MinABIStackAlignInBytes, StackAlignInBytes; 7800 void CoerceToIntArgs(uint64_t TySize, 7801 SmallVectorImpl<llvm::Type *> &ArgList) const; 7802 llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const; 7803 llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const; 7804 llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const; 7805 public: 7806 MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) : 7807 ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8), 7808 StackAlignInBytes(IsO32 ? 8 : 16) {} 7809 7810 ABIArgInfo classifyReturnType(QualType RetTy) const; 7811 ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const; 7812 void computeInfo(CGFunctionInfo &FI) const override; 7813 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 7814 QualType Ty) const override; 7815 ABIArgInfo extendType(QualType Ty) const; 7816 }; 7817 7818 class MIPSTargetCodeGenInfo : public TargetCodeGenInfo { 7819 unsigned SizeOfUnwindException; 7820 public: 7821 MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32) 7822 : TargetCodeGenInfo(std::make_unique<MipsABIInfo>(CGT, IsO32)), 7823 SizeOfUnwindException(IsO32 ? 24 : 32) {} 7824 7825 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override { 7826 return 29; 7827 } 7828 7829 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 7830 CodeGen::CodeGenModule &CGM) const override { 7831 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D); 7832 if (!FD) return; 7833 llvm::Function *Fn = cast<llvm::Function>(GV); 7834 7835 if (FD->hasAttr<MipsLongCallAttr>()) 7836 Fn->addFnAttr("long-call"); 7837 else if (FD->hasAttr<MipsShortCallAttr>()) 7838 Fn->addFnAttr("short-call"); 7839 7840 // Other attributes do not have a meaning for declarations. 7841 if (GV->isDeclaration()) 7842 return; 7843 7844 if (FD->hasAttr<Mips16Attr>()) { 7845 Fn->addFnAttr("mips16"); 7846 } 7847 else if (FD->hasAttr<NoMips16Attr>()) { 7848 Fn->addFnAttr("nomips16"); 7849 } 7850 7851 if (FD->hasAttr<MicroMipsAttr>()) 7852 Fn->addFnAttr("micromips"); 7853 else if (FD->hasAttr<NoMicroMipsAttr>()) 7854 Fn->addFnAttr("nomicromips"); 7855 7856 const MipsInterruptAttr *Attr = FD->getAttr<MipsInterruptAttr>(); 7857 if (!Attr) 7858 return; 7859 7860 const char *Kind; 7861 switch (Attr->getInterrupt()) { 7862 case MipsInterruptAttr::eic: Kind = "eic"; break; 7863 case MipsInterruptAttr::sw0: Kind = "sw0"; break; 7864 case MipsInterruptAttr::sw1: Kind = "sw1"; break; 7865 case MipsInterruptAttr::hw0: Kind = "hw0"; break; 7866 case MipsInterruptAttr::hw1: Kind = "hw1"; break; 7867 case MipsInterruptAttr::hw2: Kind = "hw2"; break; 7868 case MipsInterruptAttr::hw3: Kind = "hw3"; break; 7869 case MipsInterruptAttr::hw4: Kind = "hw4"; break; 7870 case MipsInterruptAttr::hw5: Kind = "hw5"; break; 7871 } 7872 7873 Fn->addFnAttr("interrupt", Kind); 7874 7875 } 7876 7877 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 7878 llvm::Value *Address) const override; 7879 7880 unsigned getSizeOfUnwindException() const override { 7881 return SizeOfUnwindException; 7882 } 7883 }; 7884 } 7885 7886 void MipsABIInfo::CoerceToIntArgs( 7887 uint64_t TySize, SmallVectorImpl<llvm::Type *> &ArgList) const { 7888 llvm::IntegerType *IntTy = 7889 llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8); 7890 7891 // Add (TySize / MinABIStackAlignInBytes) args of IntTy. 7892 for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N) 7893 ArgList.push_back(IntTy); 7894 7895 // If necessary, add one more integer type to ArgList. 7896 unsigned R = TySize % (MinABIStackAlignInBytes * 8); 7897 7898 if (R) 7899 ArgList.push_back(llvm::IntegerType::get(getVMContext(), R)); 7900 } 7901 7902 // In N32/64, an aligned double precision floating point field is passed in 7903 // a register. 7904 llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const { 7905 SmallVector<llvm::Type*, 8> ArgList, IntArgList; 7906 7907 if (IsO32) { 7908 CoerceToIntArgs(TySize, ArgList); 7909 return llvm::StructType::get(getVMContext(), ArgList); 7910 } 7911 7912 if (Ty->isComplexType()) 7913 return CGT.ConvertType(Ty); 7914 7915 const RecordType *RT = Ty->getAs<RecordType>(); 7916 7917 // Unions/vectors are passed in integer registers. 7918 if (!RT || !RT->isStructureOrClassType()) { 7919 CoerceToIntArgs(TySize, ArgList); 7920 return llvm::StructType::get(getVMContext(), ArgList); 7921 } 7922 7923 const RecordDecl *RD = RT->getDecl(); 7924 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD); 7925 assert(!(TySize % 8) && "Size of structure must be multiple of 8."); 7926 7927 uint64_t LastOffset = 0; 7928 unsigned idx = 0; 7929 llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64); 7930 7931 // Iterate over fields in the struct/class and check if there are any aligned 7932 // double fields. 7933 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 7934 i != e; ++i, ++idx) { 7935 const QualType Ty = i->getType(); 7936 const BuiltinType *BT = Ty->getAs<BuiltinType>(); 7937 7938 if (!BT || BT->getKind() != BuiltinType::Double) 7939 continue; 7940 7941 uint64_t Offset = Layout.getFieldOffset(idx); 7942 if (Offset % 64) // Ignore doubles that are not aligned. 7943 continue; 7944 7945 // Add ((Offset - LastOffset) / 64) args of type i64. 7946 for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j) 7947 ArgList.push_back(I64); 7948 7949 // Add double type. 7950 ArgList.push_back(llvm::Type::getDoubleTy(getVMContext())); 7951 LastOffset = Offset + 64; 7952 } 7953 7954 CoerceToIntArgs(TySize - LastOffset, IntArgList); 7955 ArgList.append(IntArgList.begin(), IntArgList.end()); 7956 7957 return llvm::StructType::get(getVMContext(), ArgList); 7958 } 7959 7960 llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset, 7961 uint64_t Offset) const { 7962 if (OrigOffset + MinABIStackAlignInBytes > Offset) 7963 return nullptr; 7964 7965 return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8); 7966 } 7967 7968 ABIArgInfo 7969 MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const { 7970 Ty = useFirstFieldIfTransparentUnion(Ty); 7971 7972 uint64_t OrigOffset = Offset; 7973 uint64_t TySize = getContext().getTypeSize(Ty); 7974 uint64_t Align = getContext().getTypeAlign(Ty) / 8; 7975 7976 Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes), 7977 (uint64_t)StackAlignInBytes); 7978 unsigned CurrOffset = llvm::alignTo(Offset, Align); 7979 Offset = CurrOffset + llvm::alignTo(TySize, Align * 8) / 8; 7980 7981 if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) { 7982 // Ignore empty aggregates. 7983 if (TySize == 0) 7984 return ABIArgInfo::getIgnore(); 7985 7986 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) { 7987 Offset = OrigOffset + MinABIStackAlignInBytes; 7988 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 7989 } 7990 7991 // If we have reached here, aggregates are passed directly by coercing to 7992 // another structure type. Padding is inserted if the offset of the 7993 // aggregate is unaligned. 7994 ABIArgInfo ArgInfo = 7995 ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0, 7996 getPaddingType(OrigOffset, CurrOffset)); 7997 ArgInfo.setInReg(true); 7998 return ArgInfo; 7999 } 8000 8001 // Treat an enum type as its underlying type. 8002 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 8003 Ty = EnumTy->getDecl()->getIntegerType(); 8004 8005 // Make sure we pass indirectly things that are too large. 8006 if (const auto *EIT = Ty->getAs<ExtIntType>()) 8007 if (EIT->getNumBits() > 128 || 8008 (EIT->getNumBits() > 64 && 8009 !getContext().getTargetInfo().hasInt128Type())) 8010 return getNaturalAlignIndirect(Ty); 8011 8012 // All integral types are promoted to the GPR width. 8013 if (Ty->isIntegralOrEnumerationType()) 8014 return extendType(Ty); 8015 8016 return ABIArgInfo::getDirect( 8017 nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset)); 8018 } 8019 8020 llvm::Type* 8021 MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const { 8022 const RecordType *RT = RetTy->getAs<RecordType>(); 8023 SmallVector<llvm::Type*, 8> RTList; 8024 8025 if (RT && RT->isStructureOrClassType()) { 8026 const RecordDecl *RD = RT->getDecl(); 8027 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD); 8028 unsigned FieldCnt = Layout.getFieldCount(); 8029 8030 // N32/64 returns struct/classes in floating point registers if the 8031 // following conditions are met: 8032 // 1. The size of the struct/class is no larger than 128-bit. 8033 // 2. The struct/class has one or two fields all of which are floating 8034 // point types. 8035 // 3. The offset of the first field is zero (this follows what gcc does). 8036 // 8037 // Any other composite results are returned in integer registers. 8038 // 8039 if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) { 8040 RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end(); 8041 for (; b != e; ++b) { 8042 const BuiltinType *BT = b->getType()->getAs<BuiltinType>(); 8043 8044 if (!BT || !BT->isFloatingPoint()) 8045 break; 8046 8047 RTList.push_back(CGT.ConvertType(b->getType())); 8048 } 8049 8050 if (b == e) 8051 return llvm::StructType::get(getVMContext(), RTList, 8052 RD->hasAttr<PackedAttr>()); 8053 8054 RTList.clear(); 8055 } 8056 } 8057 8058 CoerceToIntArgs(Size, RTList); 8059 return llvm::StructType::get(getVMContext(), RTList); 8060 } 8061 8062 ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const { 8063 uint64_t Size = getContext().getTypeSize(RetTy); 8064 8065 if (RetTy->isVoidType()) 8066 return ABIArgInfo::getIgnore(); 8067 8068 // O32 doesn't treat zero-sized structs differently from other structs. 8069 // However, N32/N64 ignores zero sized return values. 8070 if (!IsO32 && Size == 0) 8071 return ABIArgInfo::getIgnore(); 8072 8073 if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) { 8074 if (Size <= 128) { 8075 if (RetTy->isAnyComplexType()) 8076 return ABIArgInfo::getDirect(); 8077 8078 // O32 returns integer vectors in registers and N32/N64 returns all small 8079 // aggregates in registers. 8080 if (!IsO32 || 8081 (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) { 8082 ABIArgInfo ArgInfo = 8083 ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size)); 8084 ArgInfo.setInReg(true); 8085 return ArgInfo; 8086 } 8087 } 8088 8089 return getNaturalAlignIndirect(RetTy); 8090 } 8091 8092 // Treat an enum type as its underlying type. 8093 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 8094 RetTy = EnumTy->getDecl()->getIntegerType(); 8095 8096 // Make sure we pass indirectly things that are too large. 8097 if (const auto *EIT = RetTy->getAs<ExtIntType>()) 8098 if (EIT->getNumBits() > 128 || 8099 (EIT->getNumBits() > 64 && 8100 !getContext().getTargetInfo().hasInt128Type())) 8101 return getNaturalAlignIndirect(RetTy); 8102 8103 if (isPromotableIntegerTypeForABI(RetTy)) 8104 return ABIArgInfo::getExtend(RetTy); 8105 8106 if ((RetTy->isUnsignedIntegerOrEnumerationType() || 8107 RetTy->isSignedIntegerOrEnumerationType()) && Size == 32 && !IsO32) 8108 return ABIArgInfo::getSignExtend(RetTy); 8109 8110 return ABIArgInfo::getDirect(); 8111 } 8112 8113 void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const { 8114 ABIArgInfo &RetInfo = FI.getReturnInfo(); 8115 if (!getCXXABI().classifyReturnType(FI)) 8116 RetInfo = classifyReturnType(FI.getReturnType()); 8117 8118 // Check if a pointer to an aggregate is passed as a hidden argument. 8119 uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0; 8120 8121 for (auto &I : FI.arguments()) 8122 I.info = classifyArgumentType(I.type, Offset); 8123 } 8124 8125 Address MipsABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 8126 QualType OrigTy) const { 8127 QualType Ty = OrigTy; 8128 8129 // Integer arguments are promoted to 32-bit on O32 and 64-bit on N32/N64. 8130 // Pointers are also promoted in the same way but this only matters for N32. 8131 unsigned SlotSizeInBits = IsO32 ? 32 : 64; 8132 unsigned PtrWidth = getTarget().getPointerWidth(0); 8133 bool DidPromote = false; 8134 if ((Ty->isIntegerType() && 8135 getContext().getIntWidth(Ty) < SlotSizeInBits) || 8136 (Ty->isPointerType() && PtrWidth < SlotSizeInBits)) { 8137 DidPromote = true; 8138 Ty = getContext().getIntTypeForBitwidth(SlotSizeInBits, 8139 Ty->isSignedIntegerType()); 8140 } 8141 8142 auto TyInfo = getContext().getTypeInfoInChars(Ty); 8143 8144 // The alignment of things in the argument area is never larger than 8145 // StackAlignInBytes. 8146 TyInfo.Align = 8147 std::min(TyInfo.Align, CharUnits::fromQuantity(StackAlignInBytes)); 8148 8149 // MinABIStackAlignInBytes is the size of argument slots on the stack. 8150 CharUnits ArgSlotSize = CharUnits::fromQuantity(MinABIStackAlignInBytes); 8151 8152 Address Addr = emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false, 8153 TyInfo, ArgSlotSize, /*AllowHigherAlign*/ true); 8154 8155 8156 // If there was a promotion, "unpromote" into a temporary. 8157 // TODO: can we just use a pointer into a subset of the original slot? 8158 if (DidPromote) { 8159 Address Temp = CGF.CreateMemTemp(OrigTy, "vaarg.promotion-temp"); 8160 llvm::Value *Promoted = CGF.Builder.CreateLoad(Addr); 8161 8162 // Truncate down to the right width. 8163 llvm::Type *IntTy = (OrigTy->isIntegerType() ? Temp.getElementType() 8164 : CGF.IntPtrTy); 8165 llvm::Value *V = CGF.Builder.CreateTrunc(Promoted, IntTy); 8166 if (OrigTy->isPointerType()) 8167 V = CGF.Builder.CreateIntToPtr(V, Temp.getElementType()); 8168 8169 CGF.Builder.CreateStore(V, Temp); 8170 Addr = Temp; 8171 } 8172 8173 return Addr; 8174 } 8175 8176 ABIArgInfo MipsABIInfo::extendType(QualType Ty) const { 8177 int TySize = getContext().getTypeSize(Ty); 8178 8179 // MIPS64 ABI requires unsigned 32 bit integers to be sign extended. 8180 if (Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32) 8181 return ABIArgInfo::getSignExtend(Ty); 8182 8183 return ABIArgInfo::getExtend(Ty); 8184 } 8185 8186 bool 8187 MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 8188 llvm::Value *Address) const { 8189 // This information comes from gcc's implementation, which seems to 8190 // as canonical as it gets. 8191 8192 // Everything on MIPS is 4 bytes. Double-precision FP registers 8193 // are aliased to pairs of single-precision FP registers. 8194 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4); 8195 8196 // 0-31 are the general purpose registers, $0 - $31. 8197 // 32-63 are the floating-point registers, $f0 - $f31. 8198 // 64 and 65 are the multiply/divide registers, $hi and $lo. 8199 // 66 is the (notional, I think) register for signal-handler return. 8200 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65); 8201 8202 // 67-74 are the floating-point status registers, $fcc0 - $fcc7. 8203 // They are one bit wide and ignored here. 8204 8205 // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31. 8206 // (coprocessor 1 is the FP unit) 8207 // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31. 8208 // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31. 8209 // 176-181 are the DSP accumulator registers. 8210 AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181); 8211 return false; 8212 } 8213 8214 //===----------------------------------------------------------------------===// 8215 // M68k ABI Implementation 8216 //===----------------------------------------------------------------------===// 8217 8218 namespace { 8219 8220 class M68kTargetCodeGenInfo : public TargetCodeGenInfo { 8221 public: 8222 M68kTargetCodeGenInfo(CodeGenTypes &CGT) 8223 : TargetCodeGenInfo(std::make_unique<DefaultABIInfo>(CGT)) {} 8224 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 8225 CodeGen::CodeGenModule &M) const override; 8226 }; 8227 8228 } // namespace 8229 8230 void M68kTargetCodeGenInfo::setTargetAttributes( 8231 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const { 8232 if (const auto *FD = dyn_cast_or_null<FunctionDecl>(D)) { 8233 if (const auto *attr = FD->getAttr<M68kInterruptAttr>()) { 8234 // Handle 'interrupt' attribute: 8235 llvm::Function *F = cast<llvm::Function>(GV); 8236 8237 // Step 1: Set ISR calling convention. 8238 F->setCallingConv(llvm::CallingConv::M68k_INTR); 8239 8240 // Step 2: Add attributes goodness. 8241 F->addFnAttr(llvm::Attribute::NoInline); 8242 8243 // Step 3: Emit ISR vector alias. 8244 unsigned Num = attr->getNumber() / 2; 8245 llvm::GlobalAlias::create(llvm::Function::ExternalLinkage, 8246 "__isr_" + Twine(Num), F); 8247 } 8248 } 8249 } 8250 8251 //===----------------------------------------------------------------------===// 8252 // AVR ABI Implementation. Documented at 8253 // https://gcc.gnu.org/wiki/avr-gcc#Calling_Convention 8254 // https://gcc.gnu.org/wiki/avr-gcc#Reduced_Tiny 8255 //===----------------------------------------------------------------------===// 8256 8257 namespace { 8258 class AVRABIInfo : public DefaultABIInfo { 8259 public: 8260 AVRABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {} 8261 8262 ABIArgInfo classifyReturnType(QualType Ty) const { 8263 // A return struct with size less than or equal to 8 bytes is returned 8264 // directly via registers R18-R25. 8265 if (isAggregateTypeForABI(Ty) && getContext().getTypeSize(Ty) <= 64) 8266 return ABIArgInfo::getDirect(); 8267 else 8268 return DefaultABIInfo::classifyReturnType(Ty); 8269 } 8270 8271 // Just copy the original implementation of DefaultABIInfo::computeInfo(), 8272 // since DefaultABIInfo::classify{Return,Argument}Type() are not virtual. 8273 void computeInfo(CGFunctionInfo &FI) const override { 8274 if (!getCXXABI().classifyReturnType(FI)) 8275 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 8276 for (auto &I : FI.arguments()) 8277 I.info = classifyArgumentType(I.type); 8278 } 8279 }; 8280 8281 class AVRTargetCodeGenInfo : public TargetCodeGenInfo { 8282 public: 8283 AVRTargetCodeGenInfo(CodeGenTypes &CGT) 8284 : TargetCodeGenInfo(std::make_unique<AVRABIInfo>(CGT)) {} 8285 8286 LangAS getGlobalVarAddressSpace(CodeGenModule &CGM, 8287 const VarDecl *D) const override { 8288 // Check if a global/static variable is defined within address space 1 8289 // but not constant. 8290 LangAS AS = D->getType().getAddressSpace(); 8291 if (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 1 && 8292 !D->getType().isConstQualified()) 8293 CGM.getDiags().Report(D->getLocation(), 8294 diag::err_verify_nonconst_addrspace) 8295 << "__flash"; 8296 return TargetCodeGenInfo::getGlobalVarAddressSpace(CGM, D); 8297 } 8298 8299 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 8300 CodeGen::CodeGenModule &CGM) const override { 8301 if (GV->isDeclaration()) 8302 return; 8303 const auto *FD = dyn_cast_or_null<FunctionDecl>(D); 8304 if (!FD) return; 8305 auto *Fn = cast<llvm::Function>(GV); 8306 8307 if (FD->getAttr<AVRInterruptAttr>()) 8308 Fn->addFnAttr("interrupt"); 8309 8310 if (FD->getAttr<AVRSignalAttr>()) 8311 Fn->addFnAttr("signal"); 8312 } 8313 }; 8314 } 8315 8316 //===----------------------------------------------------------------------===// 8317 // TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults. 8318 // Currently subclassed only to implement custom OpenCL C function attribute 8319 // handling. 8320 //===----------------------------------------------------------------------===// 8321 8322 namespace { 8323 8324 class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo { 8325 public: 8326 TCETargetCodeGenInfo(CodeGenTypes &CGT) 8327 : DefaultTargetCodeGenInfo(CGT) {} 8328 8329 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 8330 CodeGen::CodeGenModule &M) const override; 8331 }; 8332 8333 void TCETargetCodeGenInfo::setTargetAttributes( 8334 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const { 8335 if (GV->isDeclaration()) 8336 return; 8337 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D); 8338 if (!FD) return; 8339 8340 llvm::Function *F = cast<llvm::Function>(GV); 8341 8342 if (M.getLangOpts().OpenCL) { 8343 if (FD->hasAttr<OpenCLKernelAttr>()) { 8344 // OpenCL C Kernel functions are not subject to inlining 8345 F->addFnAttr(llvm::Attribute::NoInline); 8346 const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>(); 8347 if (Attr) { 8348 // Convert the reqd_work_group_size() attributes to metadata. 8349 llvm::LLVMContext &Context = F->getContext(); 8350 llvm::NamedMDNode *OpenCLMetadata = 8351 M.getModule().getOrInsertNamedMetadata( 8352 "opencl.kernel_wg_size_info"); 8353 8354 SmallVector<llvm::Metadata *, 5> Operands; 8355 Operands.push_back(llvm::ConstantAsMetadata::get(F)); 8356 8357 Operands.push_back( 8358 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue( 8359 M.Int32Ty, llvm::APInt(32, Attr->getXDim())))); 8360 Operands.push_back( 8361 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue( 8362 M.Int32Ty, llvm::APInt(32, Attr->getYDim())))); 8363 Operands.push_back( 8364 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue( 8365 M.Int32Ty, llvm::APInt(32, Attr->getZDim())))); 8366 8367 // Add a boolean constant operand for "required" (true) or "hint" 8368 // (false) for implementing the work_group_size_hint attr later. 8369 // Currently always true as the hint is not yet implemented. 8370 Operands.push_back( 8371 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getTrue(Context))); 8372 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands)); 8373 } 8374 } 8375 } 8376 } 8377 8378 } 8379 8380 //===----------------------------------------------------------------------===// 8381 // Hexagon ABI Implementation 8382 //===----------------------------------------------------------------------===// 8383 8384 namespace { 8385 8386 class HexagonABIInfo : public DefaultABIInfo { 8387 public: 8388 HexagonABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {} 8389 8390 private: 8391 ABIArgInfo classifyReturnType(QualType RetTy) const; 8392 ABIArgInfo classifyArgumentType(QualType RetTy) const; 8393 ABIArgInfo classifyArgumentType(QualType RetTy, unsigned *RegsLeft) const; 8394 8395 void computeInfo(CGFunctionInfo &FI) const override; 8396 8397 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 8398 QualType Ty) const override; 8399 Address EmitVAArgFromMemory(CodeGenFunction &CFG, Address VAListAddr, 8400 QualType Ty) const; 8401 Address EmitVAArgForHexagon(CodeGenFunction &CFG, Address VAListAddr, 8402 QualType Ty) const; 8403 Address EmitVAArgForHexagonLinux(CodeGenFunction &CFG, Address VAListAddr, 8404 QualType Ty) const; 8405 }; 8406 8407 class HexagonTargetCodeGenInfo : public TargetCodeGenInfo { 8408 public: 8409 HexagonTargetCodeGenInfo(CodeGenTypes &CGT) 8410 : TargetCodeGenInfo(std::make_unique<HexagonABIInfo>(CGT)) {} 8411 8412 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 8413 return 29; 8414 } 8415 8416 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 8417 CodeGen::CodeGenModule &GCM) const override { 8418 if (GV->isDeclaration()) 8419 return; 8420 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D); 8421 if (!FD) 8422 return; 8423 } 8424 }; 8425 8426 } // namespace 8427 8428 void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const { 8429 unsigned RegsLeft = 6; 8430 if (!getCXXABI().classifyReturnType(FI)) 8431 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 8432 for (auto &I : FI.arguments()) 8433 I.info = classifyArgumentType(I.type, &RegsLeft); 8434 } 8435 8436 static bool HexagonAdjustRegsLeft(uint64_t Size, unsigned *RegsLeft) { 8437 assert(Size <= 64 && "Not expecting to pass arguments larger than 64 bits" 8438 " through registers"); 8439 8440 if (*RegsLeft == 0) 8441 return false; 8442 8443 if (Size <= 32) { 8444 (*RegsLeft)--; 8445 return true; 8446 } 8447 8448 if (2 <= (*RegsLeft & (~1U))) { 8449 *RegsLeft = (*RegsLeft & (~1U)) - 2; 8450 return true; 8451 } 8452 8453 // Next available register was r5 but candidate was greater than 32-bits so it 8454 // has to go on the stack. However we still consume r5 8455 if (*RegsLeft == 1) 8456 *RegsLeft = 0; 8457 8458 return false; 8459 } 8460 8461 ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty, 8462 unsigned *RegsLeft) const { 8463 if (!isAggregateTypeForABI(Ty)) { 8464 // Treat an enum type as its underlying type. 8465 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 8466 Ty = EnumTy->getDecl()->getIntegerType(); 8467 8468 uint64_t Size = getContext().getTypeSize(Ty); 8469 if (Size <= 64) 8470 HexagonAdjustRegsLeft(Size, RegsLeft); 8471 8472 if (Size > 64 && Ty->isExtIntType()) 8473 return getNaturalAlignIndirect(Ty, /*ByVal=*/true); 8474 8475 return isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty) 8476 : ABIArgInfo::getDirect(); 8477 } 8478 8479 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 8480 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 8481 8482 // Ignore empty records. 8483 if (isEmptyRecord(getContext(), Ty, true)) 8484 return ABIArgInfo::getIgnore(); 8485 8486 uint64_t Size = getContext().getTypeSize(Ty); 8487 unsigned Align = getContext().getTypeAlign(Ty); 8488 8489 if (Size > 64) 8490 return getNaturalAlignIndirect(Ty, /*ByVal=*/true); 8491 8492 if (HexagonAdjustRegsLeft(Size, RegsLeft)) 8493 Align = Size <= 32 ? 32 : 64; 8494 if (Size <= Align) { 8495 // Pass in the smallest viable integer type. 8496 if (!llvm::isPowerOf2_64(Size)) 8497 Size = llvm::NextPowerOf2(Size); 8498 return ABIArgInfo::getDirect(llvm::Type::getIntNTy(getVMContext(), Size)); 8499 } 8500 return DefaultABIInfo::classifyArgumentType(Ty); 8501 } 8502 8503 ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const { 8504 if (RetTy->isVoidType()) 8505 return ABIArgInfo::getIgnore(); 8506 8507 const TargetInfo &T = CGT.getTarget(); 8508 uint64_t Size = getContext().getTypeSize(RetTy); 8509 8510 if (RetTy->getAs<VectorType>()) { 8511 // HVX vectors are returned in vector registers or register pairs. 8512 if (T.hasFeature("hvx")) { 8513 assert(T.hasFeature("hvx-length64b") || T.hasFeature("hvx-length128b")); 8514 uint64_t VecSize = T.hasFeature("hvx-length64b") ? 64*8 : 128*8; 8515 if (Size == VecSize || Size == 2*VecSize) 8516 return ABIArgInfo::getDirectInReg(); 8517 } 8518 // Large vector types should be returned via memory. 8519 if (Size > 64) 8520 return getNaturalAlignIndirect(RetTy); 8521 } 8522 8523 if (!isAggregateTypeForABI(RetTy)) { 8524 // Treat an enum type as its underlying type. 8525 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 8526 RetTy = EnumTy->getDecl()->getIntegerType(); 8527 8528 if (Size > 64 && RetTy->isExtIntType()) 8529 return getNaturalAlignIndirect(RetTy, /*ByVal=*/false); 8530 8531 return isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy) 8532 : ABIArgInfo::getDirect(); 8533 } 8534 8535 if (isEmptyRecord(getContext(), RetTy, true)) 8536 return ABIArgInfo::getIgnore(); 8537 8538 // Aggregates <= 8 bytes are returned in registers, other aggregates 8539 // are returned indirectly. 8540 if (Size <= 64) { 8541 // Return in the smallest viable integer type. 8542 if (!llvm::isPowerOf2_64(Size)) 8543 Size = llvm::NextPowerOf2(Size); 8544 return ABIArgInfo::getDirect(llvm::Type::getIntNTy(getVMContext(), Size)); 8545 } 8546 return getNaturalAlignIndirect(RetTy, /*ByVal=*/true); 8547 } 8548 8549 Address HexagonABIInfo::EmitVAArgFromMemory(CodeGenFunction &CGF, 8550 Address VAListAddr, 8551 QualType Ty) const { 8552 // Load the overflow area pointer. 8553 Address __overflow_area_pointer_p = 8554 CGF.Builder.CreateStructGEP(VAListAddr, 2, "__overflow_area_pointer_p"); 8555 llvm::Value *__overflow_area_pointer = CGF.Builder.CreateLoad( 8556 __overflow_area_pointer_p, "__overflow_area_pointer"); 8557 8558 uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8; 8559 if (Align > 4) { 8560 // Alignment should be a power of 2. 8561 assert((Align & (Align - 1)) == 0 && "Alignment is not power of 2!"); 8562 8563 // overflow_arg_area = (overflow_arg_area + align - 1) & -align; 8564 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int64Ty, Align - 1); 8565 8566 // Add offset to the current pointer to access the argument. 8567 __overflow_area_pointer = 8568 CGF.Builder.CreateGEP(CGF.Int8Ty, __overflow_area_pointer, Offset); 8569 llvm::Value *AsInt = 8570 CGF.Builder.CreatePtrToInt(__overflow_area_pointer, CGF.Int32Ty); 8571 8572 // Create a mask which should be "AND"ed 8573 // with (overflow_arg_area + align - 1) 8574 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int32Ty, -(int)Align); 8575 __overflow_area_pointer = CGF.Builder.CreateIntToPtr( 8576 CGF.Builder.CreateAnd(AsInt, Mask), __overflow_area_pointer->getType(), 8577 "__overflow_area_pointer.align"); 8578 } 8579 8580 // Get the type of the argument from memory and bitcast 8581 // overflow area pointer to the argument type. 8582 llvm::Type *PTy = CGF.ConvertTypeForMem(Ty); 8583 Address AddrTyped = CGF.Builder.CreateBitCast( 8584 Address(__overflow_area_pointer, CharUnits::fromQuantity(Align)), 8585 llvm::PointerType::getUnqual(PTy)); 8586 8587 // Round up to the minimum stack alignment for varargs which is 4 bytes. 8588 uint64_t Offset = llvm::alignTo(CGF.getContext().getTypeSize(Ty) / 8, 4); 8589 8590 __overflow_area_pointer = CGF.Builder.CreateGEP( 8591 CGF.Int8Ty, __overflow_area_pointer, 8592 llvm::ConstantInt::get(CGF.Int32Ty, Offset), 8593 "__overflow_area_pointer.next"); 8594 CGF.Builder.CreateStore(__overflow_area_pointer, __overflow_area_pointer_p); 8595 8596 return AddrTyped; 8597 } 8598 8599 Address HexagonABIInfo::EmitVAArgForHexagon(CodeGenFunction &CGF, 8600 Address VAListAddr, 8601 QualType Ty) const { 8602 // FIXME: Need to handle alignment 8603 llvm::Type *BP = CGF.Int8PtrTy; 8604 llvm::Type *BPP = CGF.Int8PtrPtrTy; 8605 CGBuilderTy &Builder = CGF.Builder; 8606 Address VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap"); 8607 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur"); 8608 // Handle address alignment for type alignment > 32 bits 8609 uint64_t TyAlign = CGF.getContext().getTypeAlign(Ty) / 8; 8610 if (TyAlign > 4) { 8611 assert((TyAlign & (TyAlign - 1)) == 0 && "Alignment is not power of 2!"); 8612 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int32Ty); 8613 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt32(TyAlign - 1)); 8614 AddrAsInt = Builder.CreateAnd(AddrAsInt, Builder.getInt32(~(TyAlign - 1))); 8615 Addr = Builder.CreateIntToPtr(AddrAsInt, BP); 8616 } 8617 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty)); 8618 Address AddrTyped = Builder.CreateBitCast( 8619 Address(Addr, CharUnits::fromQuantity(TyAlign)), PTy); 8620 8621 uint64_t Offset = llvm::alignTo(CGF.getContext().getTypeSize(Ty) / 8, 4); 8622 llvm::Value *NextAddr = Builder.CreateGEP( 8623 CGF.Int8Ty, Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset), "ap.next"); 8624 Builder.CreateStore(NextAddr, VAListAddrAsBPP); 8625 8626 return AddrTyped; 8627 } 8628 8629 Address HexagonABIInfo::EmitVAArgForHexagonLinux(CodeGenFunction &CGF, 8630 Address VAListAddr, 8631 QualType Ty) const { 8632 int ArgSize = CGF.getContext().getTypeSize(Ty) / 8; 8633 8634 if (ArgSize > 8) 8635 return EmitVAArgFromMemory(CGF, VAListAddr, Ty); 8636 8637 // Here we have check if the argument is in register area or 8638 // in overflow area. 8639 // If the saved register area pointer + argsize rounded up to alignment > 8640 // saved register area end pointer, argument is in overflow area. 8641 unsigned RegsLeft = 6; 8642 Ty = CGF.getContext().getCanonicalType(Ty); 8643 (void)classifyArgumentType(Ty, &RegsLeft); 8644 8645 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg"); 8646 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg"); 8647 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack"); 8648 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end"); 8649 8650 // Get rounded size of the argument.GCC does not allow vararg of 8651 // size < 4 bytes. We follow the same logic here. 8652 ArgSize = (CGF.getContext().getTypeSize(Ty) <= 32) ? 4 : 8; 8653 int ArgAlign = (CGF.getContext().getTypeSize(Ty) <= 32) ? 4 : 8; 8654 8655 // Argument may be in saved register area 8656 CGF.EmitBlock(MaybeRegBlock); 8657 8658 // Load the current saved register area pointer. 8659 Address __current_saved_reg_area_pointer_p = CGF.Builder.CreateStructGEP( 8660 VAListAddr, 0, "__current_saved_reg_area_pointer_p"); 8661 llvm::Value *__current_saved_reg_area_pointer = CGF.Builder.CreateLoad( 8662 __current_saved_reg_area_pointer_p, "__current_saved_reg_area_pointer"); 8663 8664 // Load the saved register area end pointer. 8665 Address __saved_reg_area_end_pointer_p = CGF.Builder.CreateStructGEP( 8666 VAListAddr, 1, "__saved_reg_area_end_pointer_p"); 8667 llvm::Value *__saved_reg_area_end_pointer = CGF.Builder.CreateLoad( 8668 __saved_reg_area_end_pointer_p, "__saved_reg_area_end_pointer"); 8669 8670 // If the size of argument is > 4 bytes, check if the stack 8671 // location is aligned to 8 bytes 8672 if (ArgAlign > 4) { 8673 8674 llvm::Value *__current_saved_reg_area_pointer_int = 8675 CGF.Builder.CreatePtrToInt(__current_saved_reg_area_pointer, 8676 CGF.Int32Ty); 8677 8678 __current_saved_reg_area_pointer_int = CGF.Builder.CreateAdd( 8679 __current_saved_reg_area_pointer_int, 8680 llvm::ConstantInt::get(CGF.Int32Ty, (ArgAlign - 1)), 8681 "align_current_saved_reg_area_pointer"); 8682 8683 __current_saved_reg_area_pointer_int = 8684 CGF.Builder.CreateAnd(__current_saved_reg_area_pointer_int, 8685 llvm::ConstantInt::get(CGF.Int32Ty, -ArgAlign), 8686 "align_current_saved_reg_area_pointer"); 8687 8688 __current_saved_reg_area_pointer = 8689 CGF.Builder.CreateIntToPtr(__current_saved_reg_area_pointer_int, 8690 __current_saved_reg_area_pointer->getType(), 8691 "align_current_saved_reg_area_pointer"); 8692 } 8693 8694 llvm::Value *__new_saved_reg_area_pointer = 8695 CGF.Builder.CreateGEP(CGF.Int8Ty, __current_saved_reg_area_pointer, 8696 llvm::ConstantInt::get(CGF.Int32Ty, ArgSize), 8697 "__new_saved_reg_area_pointer"); 8698 8699 llvm::Value *UsingStack = 0; 8700 UsingStack = CGF.Builder.CreateICmpSGT(__new_saved_reg_area_pointer, 8701 __saved_reg_area_end_pointer); 8702 8703 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, InRegBlock); 8704 8705 // Argument in saved register area 8706 // Implement the block where argument is in register saved area 8707 CGF.EmitBlock(InRegBlock); 8708 8709 llvm::Type *PTy = CGF.ConvertType(Ty); 8710 llvm::Value *__saved_reg_area_p = CGF.Builder.CreateBitCast( 8711 __current_saved_reg_area_pointer, llvm::PointerType::getUnqual(PTy)); 8712 8713 CGF.Builder.CreateStore(__new_saved_reg_area_pointer, 8714 __current_saved_reg_area_pointer_p); 8715 8716 CGF.EmitBranch(ContBlock); 8717 8718 // Argument in overflow area 8719 // Implement the block where the argument is in overflow area. 8720 CGF.EmitBlock(OnStackBlock); 8721 8722 // Load the overflow area pointer 8723 Address __overflow_area_pointer_p = 8724 CGF.Builder.CreateStructGEP(VAListAddr, 2, "__overflow_area_pointer_p"); 8725 llvm::Value *__overflow_area_pointer = CGF.Builder.CreateLoad( 8726 __overflow_area_pointer_p, "__overflow_area_pointer"); 8727 8728 // Align the overflow area pointer according to the alignment of the argument 8729 if (ArgAlign > 4) { 8730 llvm::Value *__overflow_area_pointer_int = 8731 CGF.Builder.CreatePtrToInt(__overflow_area_pointer, CGF.Int32Ty); 8732 8733 __overflow_area_pointer_int = 8734 CGF.Builder.CreateAdd(__overflow_area_pointer_int, 8735 llvm::ConstantInt::get(CGF.Int32Ty, ArgAlign - 1), 8736 "align_overflow_area_pointer"); 8737 8738 __overflow_area_pointer_int = 8739 CGF.Builder.CreateAnd(__overflow_area_pointer_int, 8740 llvm::ConstantInt::get(CGF.Int32Ty, -ArgAlign), 8741 "align_overflow_area_pointer"); 8742 8743 __overflow_area_pointer = CGF.Builder.CreateIntToPtr( 8744 __overflow_area_pointer_int, __overflow_area_pointer->getType(), 8745 "align_overflow_area_pointer"); 8746 } 8747 8748 // Get the pointer for next argument in overflow area and store it 8749 // to overflow area pointer. 8750 llvm::Value *__new_overflow_area_pointer = CGF.Builder.CreateGEP( 8751 CGF.Int8Ty, __overflow_area_pointer, 8752 llvm::ConstantInt::get(CGF.Int32Ty, ArgSize), 8753 "__overflow_area_pointer.next"); 8754 8755 CGF.Builder.CreateStore(__new_overflow_area_pointer, 8756 __overflow_area_pointer_p); 8757 8758 CGF.Builder.CreateStore(__new_overflow_area_pointer, 8759 __current_saved_reg_area_pointer_p); 8760 8761 // Bitcast the overflow area pointer to the type of argument. 8762 llvm::Type *OverflowPTy = CGF.ConvertTypeForMem(Ty); 8763 llvm::Value *__overflow_area_p = CGF.Builder.CreateBitCast( 8764 __overflow_area_pointer, llvm::PointerType::getUnqual(OverflowPTy)); 8765 8766 CGF.EmitBranch(ContBlock); 8767 8768 // Get the correct pointer to load the variable argument 8769 // Implement the ContBlock 8770 CGF.EmitBlock(ContBlock); 8771 8772 llvm::Type *MemPTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty)); 8773 llvm::PHINode *ArgAddr = CGF.Builder.CreatePHI(MemPTy, 2, "vaarg.addr"); 8774 ArgAddr->addIncoming(__saved_reg_area_p, InRegBlock); 8775 ArgAddr->addIncoming(__overflow_area_p, OnStackBlock); 8776 8777 return Address(ArgAddr, CharUnits::fromQuantity(ArgAlign)); 8778 } 8779 8780 Address HexagonABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 8781 QualType Ty) const { 8782 8783 if (getTarget().getTriple().isMusl()) 8784 return EmitVAArgForHexagonLinux(CGF, VAListAddr, Ty); 8785 8786 return EmitVAArgForHexagon(CGF, VAListAddr, Ty); 8787 } 8788 8789 //===----------------------------------------------------------------------===// 8790 // Lanai ABI Implementation 8791 //===----------------------------------------------------------------------===// 8792 8793 namespace { 8794 class LanaiABIInfo : public DefaultABIInfo { 8795 public: 8796 LanaiABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {} 8797 8798 bool shouldUseInReg(QualType Ty, CCState &State) const; 8799 8800 void computeInfo(CGFunctionInfo &FI) const override { 8801 CCState State(FI); 8802 // Lanai uses 4 registers to pass arguments unless the function has the 8803 // regparm attribute set. 8804 if (FI.getHasRegParm()) { 8805 State.FreeRegs = FI.getRegParm(); 8806 } else { 8807 State.FreeRegs = 4; 8808 } 8809 8810 if (!getCXXABI().classifyReturnType(FI)) 8811 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 8812 for (auto &I : FI.arguments()) 8813 I.info = classifyArgumentType(I.type, State); 8814 } 8815 8816 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const; 8817 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const; 8818 }; 8819 } // end anonymous namespace 8820 8821 bool LanaiABIInfo::shouldUseInReg(QualType Ty, CCState &State) const { 8822 unsigned Size = getContext().getTypeSize(Ty); 8823 unsigned SizeInRegs = llvm::alignTo(Size, 32U) / 32U; 8824 8825 if (SizeInRegs == 0) 8826 return false; 8827 8828 if (SizeInRegs > State.FreeRegs) { 8829 State.FreeRegs = 0; 8830 return false; 8831 } 8832 8833 State.FreeRegs -= SizeInRegs; 8834 8835 return true; 8836 } 8837 8838 ABIArgInfo LanaiABIInfo::getIndirectResult(QualType Ty, bool ByVal, 8839 CCState &State) const { 8840 if (!ByVal) { 8841 if (State.FreeRegs) { 8842 --State.FreeRegs; // Non-byval indirects just use one pointer. 8843 return getNaturalAlignIndirectInReg(Ty); 8844 } 8845 return getNaturalAlignIndirect(Ty, false); 8846 } 8847 8848 // Compute the byval alignment. 8849 const unsigned MinABIStackAlignInBytes = 4; 8850 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8; 8851 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true, 8852 /*Realign=*/TypeAlign > 8853 MinABIStackAlignInBytes); 8854 } 8855 8856 ABIArgInfo LanaiABIInfo::classifyArgumentType(QualType Ty, 8857 CCState &State) const { 8858 // Check with the C++ ABI first. 8859 const RecordType *RT = Ty->getAs<RecordType>(); 8860 if (RT) { 8861 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()); 8862 if (RAA == CGCXXABI::RAA_Indirect) { 8863 return getIndirectResult(Ty, /*ByVal=*/false, State); 8864 } else if (RAA == CGCXXABI::RAA_DirectInMemory) { 8865 return getNaturalAlignIndirect(Ty, /*ByVal=*/true); 8866 } 8867 } 8868 8869 if (isAggregateTypeForABI(Ty)) { 8870 // Structures with flexible arrays are always indirect. 8871 if (RT && RT->getDecl()->hasFlexibleArrayMember()) 8872 return getIndirectResult(Ty, /*ByVal=*/true, State); 8873 8874 // Ignore empty structs/unions. 8875 if (isEmptyRecord(getContext(), Ty, true)) 8876 return ABIArgInfo::getIgnore(); 8877 8878 llvm::LLVMContext &LLVMContext = getVMContext(); 8879 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32; 8880 if (SizeInRegs <= State.FreeRegs) { 8881 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext); 8882 SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32); 8883 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements); 8884 State.FreeRegs -= SizeInRegs; 8885 return ABIArgInfo::getDirectInReg(Result); 8886 } else { 8887 State.FreeRegs = 0; 8888 } 8889 return getIndirectResult(Ty, true, State); 8890 } 8891 8892 // Treat an enum type as its underlying type. 8893 if (const auto *EnumTy = Ty->getAs<EnumType>()) 8894 Ty = EnumTy->getDecl()->getIntegerType(); 8895 8896 bool InReg = shouldUseInReg(Ty, State); 8897 8898 // Don't pass >64 bit integers in registers. 8899 if (const auto *EIT = Ty->getAs<ExtIntType>()) 8900 if (EIT->getNumBits() > 64) 8901 return getIndirectResult(Ty, /*ByVal=*/true, State); 8902 8903 if (isPromotableIntegerTypeForABI(Ty)) { 8904 if (InReg) 8905 return ABIArgInfo::getDirectInReg(); 8906 return ABIArgInfo::getExtend(Ty); 8907 } 8908 if (InReg) 8909 return ABIArgInfo::getDirectInReg(); 8910 return ABIArgInfo::getDirect(); 8911 } 8912 8913 namespace { 8914 class LanaiTargetCodeGenInfo : public TargetCodeGenInfo { 8915 public: 8916 LanaiTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT) 8917 : TargetCodeGenInfo(std::make_unique<LanaiABIInfo>(CGT)) {} 8918 }; 8919 } 8920 8921 //===----------------------------------------------------------------------===// 8922 // AMDGPU ABI Implementation 8923 //===----------------------------------------------------------------------===// 8924 8925 namespace { 8926 8927 class AMDGPUABIInfo final : public DefaultABIInfo { 8928 private: 8929 static const unsigned MaxNumRegsForArgsRet = 16; 8930 8931 unsigned numRegsForType(QualType Ty) const; 8932 8933 bool isHomogeneousAggregateBaseType(QualType Ty) const override; 8934 bool isHomogeneousAggregateSmallEnough(const Type *Base, 8935 uint64_t Members) const override; 8936 8937 // Coerce HIP scalar pointer arguments from generic pointers to global ones. 8938 llvm::Type *coerceKernelArgumentType(llvm::Type *Ty, unsigned FromAS, 8939 unsigned ToAS) const { 8940 // Single value types. 8941 if (Ty->isPointerTy() && Ty->getPointerAddressSpace() == FromAS) 8942 return llvm::PointerType::get( 8943 cast<llvm::PointerType>(Ty)->getElementType(), ToAS); 8944 return Ty; 8945 } 8946 8947 public: 8948 explicit AMDGPUABIInfo(CodeGen::CodeGenTypes &CGT) : 8949 DefaultABIInfo(CGT) {} 8950 8951 ABIArgInfo classifyReturnType(QualType RetTy) const; 8952 ABIArgInfo classifyKernelArgumentType(QualType Ty) const; 8953 ABIArgInfo classifyArgumentType(QualType Ty, unsigned &NumRegsLeft) const; 8954 8955 void computeInfo(CGFunctionInfo &FI) const override; 8956 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 8957 QualType Ty) const override; 8958 }; 8959 8960 bool AMDGPUABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const { 8961 return true; 8962 } 8963 8964 bool AMDGPUABIInfo::isHomogeneousAggregateSmallEnough( 8965 const Type *Base, uint64_t Members) const { 8966 uint32_t NumRegs = (getContext().getTypeSize(Base) + 31) / 32; 8967 8968 // Homogeneous Aggregates may occupy at most 16 registers. 8969 return Members * NumRegs <= MaxNumRegsForArgsRet; 8970 } 8971 8972 /// Estimate number of registers the type will use when passed in registers. 8973 unsigned AMDGPUABIInfo::numRegsForType(QualType Ty) const { 8974 unsigned NumRegs = 0; 8975 8976 if (const VectorType *VT = Ty->getAs<VectorType>()) { 8977 // Compute from the number of elements. The reported size is based on the 8978 // in-memory size, which includes the padding 4th element for 3-vectors. 8979 QualType EltTy = VT->getElementType(); 8980 unsigned EltSize = getContext().getTypeSize(EltTy); 8981 8982 // 16-bit element vectors should be passed as packed. 8983 if (EltSize == 16) 8984 return (VT->getNumElements() + 1) / 2; 8985 8986 unsigned EltNumRegs = (EltSize + 31) / 32; 8987 return EltNumRegs * VT->getNumElements(); 8988 } 8989 8990 if (const RecordType *RT = Ty->getAs<RecordType>()) { 8991 const RecordDecl *RD = RT->getDecl(); 8992 assert(!RD->hasFlexibleArrayMember()); 8993 8994 for (const FieldDecl *Field : RD->fields()) { 8995 QualType FieldTy = Field->getType(); 8996 NumRegs += numRegsForType(FieldTy); 8997 } 8998 8999 return NumRegs; 9000 } 9001 9002 return (getContext().getTypeSize(Ty) + 31) / 32; 9003 } 9004 9005 void AMDGPUABIInfo::computeInfo(CGFunctionInfo &FI) const { 9006 llvm::CallingConv::ID CC = FI.getCallingConvention(); 9007 9008 if (!getCXXABI().classifyReturnType(FI)) 9009 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 9010 9011 unsigned NumRegsLeft = MaxNumRegsForArgsRet; 9012 for (auto &Arg : FI.arguments()) { 9013 if (CC == llvm::CallingConv::AMDGPU_KERNEL) { 9014 Arg.info = classifyKernelArgumentType(Arg.type); 9015 } else { 9016 Arg.info = classifyArgumentType(Arg.type, NumRegsLeft); 9017 } 9018 } 9019 } 9020 9021 Address AMDGPUABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 9022 QualType Ty) const { 9023 llvm_unreachable("AMDGPU does not support varargs"); 9024 } 9025 9026 ABIArgInfo AMDGPUABIInfo::classifyReturnType(QualType RetTy) const { 9027 if (isAggregateTypeForABI(RetTy)) { 9028 // Records with non-trivial destructors/copy-constructors should not be 9029 // returned by value. 9030 if (!getRecordArgABI(RetTy, getCXXABI())) { 9031 // Ignore empty structs/unions. 9032 if (isEmptyRecord(getContext(), RetTy, true)) 9033 return ABIArgInfo::getIgnore(); 9034 9035 // Lower single-element structs to just return a regular value. 9036 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext())) 9037 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0))); 9038 9039 if (const RecordType *RT = RetTy->getAs<RecordType>()) { 9040 const RecordDecl *RD = RT->getDecl(); 9041 if (RD->hasFlexibleArrayMember()) 9042 return DefaultABIInfo::classifyReturnType(RetTy); 9043 } 9044 9045 // Pack aggregates <= 4 bytes into single VGPR or pair. 9046 uint64_t Size = getContext().getTypeSize(RetTy); 9047 if (Size <= 16) 9048 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext())); 9049 9050 if (Size <= 32) 9051 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext())); 9052 9053 if (Size <= 64) { 9054 llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext()); 9055 return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2)); 9056 } 9057 9058 if (numRegsForType(RetTy) <= MaxNumRegsForArgsRet) 9059 return ABIArgInfo::getDirect(); 9060 } 9061 } 9062 9063 // Otherwise just do the default thing. 9064 return DefaultABIInfo::classifyReturnType(RetTy); 9065 } 9066 9067 /// For kernels all parameters are really passed in a special buffer. It doesn't 9068 /// make sense to pass anything byval, so everything must be direct. 9069 ABIArgInfo AMDGPUABIInfo::classifyKernelArgumentType(QualType Ty) const { 9070 Ty = useFirstFieldIfTransparentUnion(Ty); 9071 9072 // TODO: Can we omit empty structs? 9073 9074 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext())) 9075 Ty = QualType(SeltTy, 0); 9076 9077 llvm::Type *OrigLTy = CGT.ConvertType(Ty); 9078 llvm::Type *LTy = OrigLTy; 9079 if (getContext().getLangOpts().HIP) { 9080 LTy = coerceKernelArgumentType( 9081 OrigLTy, /*FromAS=*/getContext().getTargetAddressSpace(LangAS::Default), 9082 /*ToAS=*/getContext().getTargetAddressSpace(LangAS::cuda_device)); 9083 } 9084 9085 // FIXME: Should also use this for OpenCL, but it requires addressing the 9086 // problem of kernels being called. 9087 // 9088 // FIXME: This doesn't apply the optimization of coercing pointers in structs 9089 // to global address space when using byref. This would require implementing a 9090 // new kind of coercion of the in-memory type when for indirect arguments. 9091 if (!getContext().getLangOpts().OpenCL && LTy == OrigLTy && 9092 isAggregateTypeForABI(Ty)) { 9093 return ABIArgInfo::getIndirectAliased( 9094 getContext().getTypeAlignInChars(Ty), 9095 getContext().getTargetAddressSpace(LangAS::opencl_constant), 9096 false /*Realign*/, nullptr /*Padding*/); 9097 } 9098 9099 // If we set CanBeFlattened to true, CodeGen will expand the struct to its 9100 // individual elements, which confuses the Clover OpenCL backend; therefore we 9101 // have to set it to false here. Other args of getDirect() are just defaults. 9102 return ABIArgInfo::getDirect(LTy, 0, nullptr, false); 9103 } 9104 9105 ABIArgInfo AMDGPUABIInfo::classifyArgumentType(QualType Ty, 9106 unsigned &NumRegsLeft) const { 9107 assert(NumRegsLeft <= MaxNumRegsForArgsRet && "register estimate underflow"); 9108 9109 Ty = useFirstFieldIfTransparentUnion(Ty); 9110 9111 if (isAggregateTypeForABI(Ty)) { 9112 // Records with non-trivial destructors/copy-constructors should not be 9113 // passed by value. 9114 if (auto RAA = getRecordArgABI(Ty, getCXXABI())) 9115 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 9116 9117 // Ignore empty structs/unions. 9118 if (isEmptyRecord(getContext(), Ty, true)) 9119 return ABIArgInfo::getIgnore(); 9120 9121 // Lower single-element structs to just pass a regular value. TODO: We 9122 // could do reasonable-size multiple-element structs too, using getExpand(), 9123 // though watch out for things like bitfields. 9124 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext())) 9125 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0))); 9126 9127 if (const RecordType *RT = Ty->getAs<RecordType>()) { 9128 const RecordDecl *RD = RT->getDecl(); 9129 if (RD->hasFlexibleArrayMember()) 9130 return DefaultABIInfo::classifyArgumentType(Ty); 9131 } 9132 9133 // Pack aggregates <= 8 bytes into single VGPR or pair. 9134 uint64_t Size = getContext().getTypeSize(Ty); 9135 if (Size <= 64) { 9136 unsigned NumRegs = (Size + 31) / 32; 9137 NumRegsLeft -= std::min(NumRegsLeft, NumRegs); 9138 9139 if (Size <= 16) 9140 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext())); 9141 9142 if (Size <= 32) 9143 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext())); 9144 9145 // XXX: Should this be i64 instead, and should the limit increase? 9146 llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext()); 9147 return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2)); 9148 } 9149 9150 if (NumRegsLeft > 0) { 9151 unsigned NumRegs = numRegsForType(Ty); 9152 if (NumRegsLeft >= NumRegs) { 9153 NumRegsLeft -= NumRegs; 9154 return ABIArgInfo::getDirect(); 9155 } 9156 } 9157 } 9158 9159 // Otherwise just do the default thing. 9160 ABIArgInfo ArgInfo = DefaultABIInfo::classifyArgumentType(Ty); 9161 if (!ArgInfo.isIndirect()) { 9162 unsigned NumRegs = numRegsForType(Ty); 9163 NumRegsLeft -= std::min(NumRegs, NumRegsLeft); 9164 } 9165 9166 return ArgInfo; 9167 } 9168 9169 class AMDGPUTargetCodeGenInfo : public TargetCodeGenInfo { 9170 public: 9171 AMDGPUTargetCodeGenInfo(CodeGenTypes &CGT) 9172 : TargetCodeGenInfo(std::make_unique<AMDGPUABIInfo>(CGT)) {} 9173 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 9174 CodeGen::CodeGenModule &M) const override; 9175 unsigned getOpenCLKernelCallingConv() const override; 9176 9177 llvm::Constant *getNullPointer(const CodeGen::CodeGenModule &CGM, 9178 llvm::PointerType *T, QualType QT) const override; 9179 9180 LangAS getASTAllocaAddressSpace() const override { 9181 return getLangASFromTargetAS( 9182 getABIInfo().getDataLayout().getAllocaAddrSpace()); 9183 } 9184 LangAS getGlobalVarAddressSpace(CodeGenModule &CGM, 9185 const VarDecl *D) const override; 9186 llvm::SyncScope::ID getLLVMSyncScopeID(const LangOptions &LangOpts, 9187 SyncScope Scope, 9188 llvm::AtomicOrdering Ordering, 9189 llvm::LLVMContext &Ctx) const override; 9190 llvm::Function * 9191 createEnqueuedBlockKernel(CodeGenFunction &CGF, 9192 llvm::Function *BlockInvokeFunc, 9193 llvm::Value *BlockLiteral) const override; 9194 bool shouldEmitStaticExternCAliases() const override; 9195 void setCUDAKernelCallingConvention(const FunctionType *&FT) const override; 9196 }; 9197 } 9198 9199 static bool requiresAMDGPUProtectedVisibility(const Decl *D, 9200 llvm::GlobalValue *GV) { 9201 if (GV->getVisibility() != llvm::GlobalValue::HiddenVisibility) 9202 return false; 9203 9204 return D->hasAttr<OpenCLKernelAttr>() || 9205 (isa<FunctionDecl>(D) && D->hasAttr<CUDAGlobalAttr>()) || 9206 (isa<VarDecl>(D) && 9207 (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>() || 9208 cast<VarDecl>(D)->getType()->isCUDADeviceBuiltinSurfaceType() || 9209 cast<VarDecl>(D)->getType()->isCUDADeviceBuiltinTextureType())); 9210 } 9211 9212 void AMDGPUTargetCodeGenInfo::setTargetAttributes( 9213 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const { 9214 if (requiresAMDGPUProtectedVisibility(D, GV)) { 9215 GV->setVisibility(llvm::GlobalValue::ProtectedVisibility); 9216 GV->setDSOLocal(true); 9217 } 9218 9219 if (GV->isDeclaration()) 9220 return; 9221 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D); 9222 if (!FD) 9223 return; 9224 9225 llvm::Function *F = cast<llvm::Function>(GV); 9226 9227 const auto *ReqdWGS = M.getLangOpts().OpenCL ? 9228 FD->getAttr<ReqdWorkGroupSizeAttr>() : nullptr; 9229 9230 9231 const bool IsOpenCLKernel = M.getLangOpts().OpenCL && 9232 FD->hasAttr<OpenCLKernelAttr>(); 9233 const bool IsHIPKernel = M.getLangOpts().HIP && 9234 FD->hasAttr<CUDAGlobalAttr>(); 9235 if ((IsOpenCLKernel || IsHIPKernel) && 9236 (M.getTriple().getOS() == llvm::Triple::AMDHSA)) 9237 F->addFnAttr("amdgpu-implicitarg-num-bytes", "56"); 9238 9239 if (IsHIPKernel) 9240 F->addFnAttr("uniform-work-group-size", "true"); 9241 9242 9243 const auto *FlatWGS = FD->getAttr<AMDGPUFlatWorkGroupSizeAttr>(); 9244 if (ReqdWGS || FlatWGS) { 9245 unsigned Min = 0; 9246 unsigned Max = 0; 9247 if (FlatWGS) { 9248 Min = FlatWGS->getMin() 9249 ->EvaluateKnownConstInt(M.getContext()) 9250 .getExtValue(); 9251 Max = FlatWGS->getMax() 9252 ->EvaluateKnownConstInt(M.getContext()) 9253 .getExtValue(); 9254 } 9255 if (ReqdWGS && Min == 0 && Max == 0) 9256 Min = Max = ReqdWGS->getXDim() * ReqdWGS->getYDim() * ReqdWGS->getZDim(); 9257 9258 if (Min != 0) { 9259 assert(Min <= Max && "Min must be less than or equal Max"); 9260 9261 std::string AttrVal = llvm::utostr(Min) + "," + llvm::utostr(Max); 9262 F->addFnAttr("amdgpu-flat-work-group-size", AttrVal); 9263 } else 9264 assert(Max == 0 && "Max must be zero"); 9265 } else if (IsOpenCLKernel || IsHIPKernel) { 9266 // By default, restrict the maximum size to a value specified by 9267 // --gpu-max-threads-per-block=n or its default value for HIP. 9268 const unsigned OpenCLDefaultMaxWorkGroupSize = 256; 9269 const unsigned DefaultMaxWorkGroupSize = 9270 IsOpenCLKernel ? OpenCLDefaultMaxWorkGroupSize 9271 : M.getLangOpts().GPUMaxThreadsPerBlock; 9272 std::string AttrVal = 9273 std::string("1,") + llvm::utostr(DefaultMaxWorkGroupSize); 9274 F->addFnAttr("amdgpu-flat-work-group-size", AttrVal); 9275 } 9276 9277 if (const auto *Attr = FD->getAttr<AMDGPUWavesPerEUAttr>()) { 9278 unsigned Min = 9279 Attr->getMin()->EvaluateKnownConstInt(M.getContext()).getExtValue(); 9280 unsigned Max = Attr->getMax() ? Attr->getMax() 9281 ->EvaluateKnownConstInt(M.getContext()) 9282 .getExtValue() 9283 : 0; 9284 9285 if (Min != 0) { 9286 assert((Max == 0 || Min <= Max) && "Min must be less than or equal Max"); 9287 9288 std::string AttrVal = llvm::utostr(Min); 9289 if (Max != 0) 9290 AttrVal = AttrVal + "," + llvm::utostr(Max); 9291 F->addFnAttr("amdgpu-waves-per-eu", AttrVal); 9292 } else 9293 assert(Max == 0 && "Max must be zero"); 9294 } 9295 9296 if (const auto *Attr = FD->getAttr<AMDGPUNumSGPRAttr>()) { 9297 unsigned NumSGPR = Attr->getNumSGPR(); 9298 9299 if (NumSGPR != 0) 9300 F->addFnAttr("amdgpu-num-sgpr", llvm::utostr(NumSGPR)); 9301 } 9302 9303 if (const auto *Attr = FD->getAttr<AMDGPUNumVGPRAttr>()) { 9304 uint32_t NumVGPR = Attr->getNumVGPR(); 9305 9306 if (NumVGPR != 0) 9307 F->addFnAttr("amdgpu-num-vgpr", llvm::utostr(NumVGPR)); 9308 } 9309 9310 if (M.getContext().getTargetInfo().allowAMDGPUUnsafeFPAtomics()) 9311 F->addFnAttr("amdgpu-unsafe-fp-atomics", "true"); 9312 9313 if (!getABIInfo().getCodeGenOpts().EmitIEEENaNCompliantInsts) 9314 F->addFnAttr("amdgpu-ieee", "false"); 9315 } 9316 9317 unsigned AMDGPUTargetCodeGenInfo::getOpenCLKernelCallingConv() const { 9318 return llvm::CallingConv::AMDGPU_KERNEL; 9319 } 9320 9321 // Currently LLVM assumes null pointers always have value 0, 9322 // which results in incorrectly transformed IR. Therefore, instead of 9323 // emitting null pointers in private and local address spaces, a null 9324 // pointer in generic address space is emitted which is casted to a 9325 // pointer in local or private address space. 9326 llvm::Constant *AMDGPUTargetCodeGenInfo::getNullPointer( 9327 const CodeGen::CodeGenModule &CGM, llvm::PointerType *PT, 9328 QualType QT) const { 9329 if (CGM.getContext().getTargetNullPointerValue(QT) == 0) 9330 return llvm::ConstantPointerNull::get(PT); 9331 9332 auto &Ctx = CGM.getContext(); 9333 auto NPT = llvm::PointerType::get(PT->getElementType(), 9334 Ctx.getTargetAddressSpace(LangAS::opencl_generic)); 9335 return llvm::ConstantExpr::getAddrSpaceCast( 9336 llvm::ConstantPointerNull::get(NPT), PT); 9337 } 9338 9339 LangAS 9340 AMDGPUTargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM, 9341 const VarDecl *D) const { 9342 assert(!CGM.getLangOpts().OpenCL && 9343 !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) && 9344 "Address space agnostic languages only"); 9345 LangAS DefaultGlobalAS = getLangASFromTargetAS( 9346 CGM.getContext().getTargetAddressSpace(LangAS::opencl_global)); 9347 if (!D) 9348 return DefaultGlobalAS; 9349 9350 LangAS AddrSpace = D->getType().getAddressSpace(); 9351 assert(AddrSpace == LangAS::Default || isTargetAddressSpace(AddrSpace)); 9352 if (AddrSpace != LangAS::Default) 9353 return AddrSpace; 9354 9355 if (CGM.isTypeConstant(D->getType(), false)) { 9356 if (auto ConstAS = CGM.getTarget().getConstantAddressSpace()) 9357 return ConstAS.getValue(); 9358 } 9359 return DefaultGlobalAS; 9360 } 9361 9362 llvm::SyncScope::ID 9363 AMDGPUTargetCodeGenInfo::getLLVMSyncScopeID(const LangOptions &LangOpts, 9364 SyncScope Scope, 9365 llvm::AtomicOrdering Ordering, 9366 llvm::LLVMContext &Ctx) const { 9367 std::string Name; 9368 switch (Scope) { 9369 case SyncScope::OpenCLWorkGroup: 9370 Name = "workgroup"; 9371 break; 9372 case SyncScope::OpenCLDevice: 9373 Name = "agent"; 9374 break; 9375 case SyncScope::OpenCLAllSVMDevices: 9376 Name = ""; 9377 break; 9378 case SyncScope::OpenCLSubGroup: 9379 Name = "wavefront"; 9380 } 9381 9382 if (Ordering != llvm::AtomicOrdering::SequentiallyConsistent) { 9383 if (!Name.empty()) 9384 Name = Twine(Twine(Name) + Twine("-")).str(); 9385 9386 Name = Twine(Twine(Name) + Twine("one-as")).str(); 9387 } 9388 9389 return Ctx.getOrInsertSyncScopeID(Name); 9390 } 9391 9392 bool AMDGPUTargetCodeGenInfo::shouldEmitStaticExternCAliases() const { 9393 return false; 9394 } 9395 9396 void AMDGPUTargetCodeGenInfo::setCUDAKernelCallingConvention( 9397 const FunctionType *&FT) const { 9398 FT = getABIInfo().getContext().adjustFunctionType( 9399 FT, FT->getExtInfo().withCallingConv(CC_OpenCLKernel)); 9400 } 9401 9402 //===----------------------------------------------------------------------===// 9403 // SPARC v8 ABI Implementation. 9404 // Based on the SPARC Compliance Definition version 2.4.1. 9405 // 9406 // Ensures that complex values are passed in registers. 9407 // 9408 namespace { 9409 class SparcV8ABIInfo : public DefaultABIInfo { 9410 public: 9411 SparcV8ABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {} 9412 9413 private: 9414 ABIArgInfo classifyReturnType(QualType RetTy) const; 9415 void computeInfo(CGFunctionInfo &FI) const override; 9416 }; 9417 } // end anonymous namespace 9418 9419 9420 ABIArgInfo 9421 SparcV8ABIInfo::classifyReturnType(QualType Ty) const { 9422 if (Ty->isAnyComplexType()) { 9423 return ABIArgInfo::getDirect(); 9424 } 9425 else { 9426 return DefaultABIInfo::classifyReturnType(Ty); 9427 } 9428 } 9429 9430 void SparcV8ABIInfo::computeInfo(CGFunctionInfo &FI) const { 9431 9432 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 9433 for (auto &Arg : FI.arguments()) 9434 Arg.info = classifyArgumentType(Arg.type); 9435 } 9436 9437 namespace { 9438 class SparcV8TargetCodeGenInfo : public TargetCodeGenInfo { 9439 public: 9440 SparcV8TargetCodeGenInfo(CodeGenTypes &CGT) 9441 : TargetCodeGenInfo(std::make_unique<SparcV8ABIInfo>(CGT)) {} 9442 }; 9443 } // end anonymous namespace 9444 9445 //===----------------------------------------------------------------------===// 9446 // SPARC v9 ABI Implementation. 9447 // Based on the SPARC Compliance Definition version 2.4.1. 9448 // 9449 // Function arguments a mapped to a nominal "parameter array" and promoted to 9450 // registers depending on their type. Each argument occupies 8 or 16 bytes in 9451 // the array, structs larger than 16 bytes are passed indirectly. 9452 // 9453 // One case requires special care: 9454 // 9455 // struct mixed { 9456 // int i; 9457 // float f; 9458 // }; 9459 // 9460 // When a struct mixed is passed by value, it only occupies 8 bytes in the 9461 // parameter array, but the int is passed in an integer register, and the float 9462 // is passed in a floating point register. This is represented as two arguments 9463 // with the LLVM IR inreg attribute: 9464 // 9465 // declare void f(i32 inreg %i, float inreg %f) 9466 // 9467 // The code generator will only allocate 4 bytes from the parameter array for 9468 // the inreg arguments. All other arguments are allocated a multiple of 8 9469 // bytes. 9470 // 9471 namespace { 9472 class SparcV9ABIInfo : public ABIInfo { 9473 public: 9474 SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {} 9475 9476 private: 9477 ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const; 9478 void computeInfo(CGFunctionInfo &FI) const override; 9479 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 9480 QualType Ty) const override; 9481 9482 // Coercion type builder for structs passed in registers. The coercion type 9483 // serves two purposes: 9484 // 9485 // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned' 9486 // in registers. 9487 // 2. Expose aligned floating point elements as first-level elements, so the 9488 // code generator knows to pass them in floating point registers. 9489 // 9490 // We also compute the InReg flag which indicates that the struct contains 9491 // aligned 32-bit floats. 9492 // 9493 struct CoerceBuilder { 9494 llvm::LLVMContext &Context; 9495 const llvm::DataLayout &DL; 9496 SmallVector<llvm::Type*, 8> Elems; 9497 uint64_t Size; 9498 bool InReg; 9499 9500 CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl) 9501 : Context(c), DL(dl), Size(0), InReg(false) {} 9502 9503 // Pad Elems with integers until Size is ToSize. 9504 void pad(uint64_t ToSize) { 9505 assert(ToSize >= Size && "Cannot remove elements"); 9506 if (ToSize == Size) 9507 return; 9508 9509 // Finish the current 64-bit word. 9510 uint64_t Aligned = llvm::alignTo(Size, 64); 9511 if (Aligned > Size && Aligned <= ToSize) { 9512 Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size)); 9513 Size = Aligned; 9514 } 9515 9516 // Add whole 64-bit words. 9517 while (Size + 64 <= ToSize) { 9518 Elems.push_back(llvm::Type::getInt64Ty(Context)); 9519 Size += 64; 9520 } 9521 9522 // Final in-word padding. 9523 if (Size < ToSize) { 9524 Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size)); 9525 Size = ToSize; 9526 } 9527 } 9528 9529 // Add a floating point element at Offset. 9530 void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) { 9531 // Unaligned floats are treated as integers. 9532 if (Offset % Bits) 9533 return; 9534 // The InReg flag is only required if there are any floats < 64 bits. 9535 if (Bits < 64) 9536 InReg = true; 9537 pad(Offset); 9538 Elems.push_back(Ty); 9539 Size = Offset + Bits; 9540 } 9541 9542 // Add a struct type to the coercion type, starting at Offset (in bits). 9543 void addStruct(uint64_t Offset, llvm::StructType *StrTy) { 9544 const llvm::StructLayout *Layout = DL.getStructLayout(StrTy); 9545 for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) { 9546 llvm::Type *ElemTy = StrTy->getElementType(i); 9547 uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i); 9548 switch (ElemTy->getTypeID()) { 9549 case llvm::Type::StructTyID: 9550 addStruct(ElemOffset, cast<llvm::StructType>(ElemTy)); 9551 break; 9552 case llvm::Type::FloatTyID: 9553 addFloat(ElemOffset, ElemTy, 32); 9554 break; 9555 case llvm::Type::DoubleTyID: 9556 addFloat(ElemOffset, ElemTy, 64); 9557 break; 9558 case llvm::Type::FP128TyID: 9559 addFloat(ElemOffset, ElemTy, 128); 9560 break; 9561 case llvm::Type::PointerTyID: 9562 if (ElemOffset % 64 == 0) { 9563 pad(ElemOffset); 9564 Elems.push_back(ElemTy); 9565 Size += 64; 9566 } 9567 break; 9568 default: 9569 break; 9570 } 9571 } 9572 } 9573 9574 // Check if Ty is a usable substitute for the coercion type. 9575 bool isUsableType(llvm::StructType *Ty) const { 9576 return llvm::makeArrayRef(Elems) == Ty->elements(); 9577 } 9578 9579 // Get the coercion type as a literal struct type. 9580 llvm::Type *getType() const { 9581 if (Elems.size() == 1) 9582 return Elems.front(); 9583 else 9584 return llvm::StructType::get(Context, Elems); 9585 } 9586 }; 9587 }; 9588 } // end anonymous namespace 9589 9590 ABIArgInfo 9591 SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const { 9592 if (Ty->isVoidType()) 9593 return ABIArgInfo::getIgnore(); 9594 9595 uint64_t Size = getContext().getTypeSize(Ty); 9596 9597 // Anything too big to fit in registers is passed with an explicit indirect 9598 // pointer / sret pointer. 9599 if (Size > SizeLimit) 9600 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 9601 9602 // Treat an enum type as its underlying type. 9603 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 9604 Ty = EnumTy->getDecl()->getIntegerType(); 9605 9606 // Integer types smaller than a register are extended. 9607 if (Size < 64 && Ty->isIntegerType()) 9608 return ABIArgInfo::getExtend(Ty); 9609 9610 if (const auto *EIT = Ty->getAs<ExtIntType>()) 9611 if (EIT->getNumBits() < 64) 9612 return ABIArgInfo::getExtend(Ty); 9613 9614 // Other non-aggregates go in registers. 9615 if (!isAggregateTypeForABI(Ty)) 9616 return ABIArgInfo::getDirect(); 9617 9618 // If a C++ object has either a non-trivial copy constructor or a non-trivial 9619 // destructor, it is passed with an explicit indirect pointer / sret pointer. 9620 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 9621 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 9622 9623 // This is a small aggregate type that should be passed in registers. 9624 // Build a coercion type from the LLVM struct type. 9625 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty)); 9626 if (!StrTy) 9627 return ABIArgInfo::getDirect(); 9628 9629 CoerceBuilder CB(getVMContext(), getDataLayout()); 9630 CB.addStruct(0, StrTy); 9631 CB.pad(llvm::alignTo(CB.DL.getTypeSizeInBits(StrTy), 64)); 9632 9633 // Try to use the original type for coercion. 9634 llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType(); 9635 9636 if (CB.InReg) 9637 return ABIArgInfo::getDirectInReg(CoerceTy); 9638 else 9639 return ABIArgInfo::getDirect(CoerceTy); 9640 } 9641 9642 Address SparcV9ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 9643 QualType Ty) const { 9644 ABIArgInfo AI = classifyType(Ty, 16 * 8); 9645 llvm::Type *ArgTy = CGT.ConvertType(Ty); 9646 if (AI.canHaveCoerceToType() && !AI.getCoerceToType()) 9647 AI.setCoerceToType(ArgTy); 9648 9649 CharUnits SlotSize = CharUnits::fromQuantity(8); 9650 9651 CGBuilderTy &Builder = CGF.Builder; 9652 Address Addr(Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize); 9653 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy); 9654 9655 auto TypeInfo = getContext().getTypeInfoInChars(Ty); 9656 9657 Address ArgAddr = Address::invalid(); 9658 CharUnits Stride; 9659 switch (AI.getKind()) { 9660 case ABIArgInfo::Expand: 9661 case ABIArgInfo::CoerceAndExpand: 9662 case ABIArgInfo::InAlloca: 9663 llvm_unreachable("Unsupported ABI kind for va_arg"); 9664 9665 case ABIArgInfo::Extend: { 9666 Stride = SlotSize; 9667 CharUnits Offset = SlotSize - TypeInfo.Width; 9668 ArgAddr = Builder.CreateConstInBoundsByteGEP(Addr, Offset, "extend"); 9669 break; 9670 } 9671 9672 case ABIArgInfo::Direct: { 9673 auto AllocSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType()); 9674 Stride = CharUnits::fromQuantity(AllocSize).alignTo(SlotSize); 9675 ArgAddr = Addr; 9676 break; 9677 } 9678 9679 case ABIArgInfo::Indirect: 9680 case ABIArgInfo::IndirectAliased: 9681 Stride = SlotSize; 9682 ArgAddr = Builder.CreateElementBitCast(Addr, ArgPtrTy, "indirect"); 9683 ArgAddr = Address(Builder.CreateLoad(ArgAddr, "indirect.arg"), 9684 TypeInfo.Align); 9685 break; 9686 9687 case ABIArgInfo::Ignore: 9688 return Address(llvm::UndefValue::get(ArgPtrTy), TypeInfo.Align); 9689 } 9690 9691 // Update VAList. 9692 Address NextPtr = Builder.CreateConstInBoundsByteGEP(Addr, Stride, "ap.next"); 9693 Builder.CreateStore(NextPtr.getPointer(), VAListAddr); 9694 9695 return Builder.CreateBitCast(ArgAddr, ArgPtrTy, "arg.addr"); 9696 } 9697 9698 void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const { 9699 FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8); 9700 for (auto &I : FI.arguments()) 9701 I.info = classifyType(I.type, 16 * 8); 9702 } 9703 9704 namespace { 9705 class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo { 9706 public: 9707 SparcV9TargetCodeGenInfo(CodeGenTypes &CGT) 9708 : TargetCodeGenInfo(std::make_unique<SparcV9ABIInfo>(CGT)) {} 9709 9710 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 9711 return 14; 9712 } 9713 9714 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 9715 llvm::Value *Address) const override; 9716 }; 9717 } // end anonymous namespace 9718 9719 bool 9720 SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 9721 llvm::Value *Address) const { 9722 // This is calculated from the LLVM and GCC tables and verified 9723 // against gcc output. AFAIK all ABIs use the same encoding. 9724 9725 CodeGen::CGBuilderTy &Builder = CGF.Builder; 9726 9727 llvm::IntegerType *i8 = CGF.Int8Ty; 9728 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4); 9729 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8); 9730 9731 // 0-31: the 8-byte general-purpose registers 9732 AssignToArrayRange(Builder, Address, Eight8, 0, 31); 9733 9734 // 32-63: f0-31, the 4-byte floating-point registers 9735 AssignToArrayRange(Builder, Address, Four8, 32, 63); 9736 9737 // Y = 64 9738 // PSR = 65 9739 // WIM = 66 9740 // TBR = 67 9741 // PC = 68 9742 // NPC = 69 9743 // FSR = 70 9744 // CSR = 71 9745 AssignToArrayRange(Builder, Address, Eight8, 64, 71); 9746 9747 // 72-87: d0-15, the 8-byte floating-point registers 9748 AssignToArrayRange(Builder, Address, Eight8, 72, 87); 9749 9750 return false; 9751 } 9752 9753 // ARC ABI implementation. 9754 namespace { 9755 9756 class ARCABIInfo : public DefaultABIInfo { 9757 public: 9758 using DefaultABIInfo::DefaultABIInfo; 9759 9760 private: 9761 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 9762 QualType Ty) const override; 9763 9764 void updateState(const ABIArgInfo &Info, QualType Ty, CCState &State) const { 9765 if (!State.FreeRegs) 9766 return; 9767 if (Info.isIndirect() && Info.getInReg()) 9768 State.FreeRegs--; 9769 else if (Info.isDirect() && Info.getInReg()) { 9770 unsigned sz = (getContext().getTypeSize(Ty) + 31) / 32; 9771 if (sz < State.FreeRegs) 9772 State.FreeRegs -= sz; 9773 else 9774 State.FreeRegs = 0; 9775 } 9776 } 9777 9778 void computeInfo(CGFunctionInfo &FI) const override { 9779 CCState State(FI); 9780 // ARC uses 8 registers to pass arguments. 9781 State.FreeRegs = 8; 9782 9783 if (!getCXXABI().classifyReturnType(FI)) 9784 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 9785 updateState(FI.getReturnInfo(), FI.getReturnType(), State); 9786 for (auto &I : FI.arguments()) { 9787 I.info = classifyArgumentType(I.type, State.FreeRegs); 9788 updateState(I.info, I.type, State); 9789 } 9790 } 9791 9792 ABIArgInfo getIndirectByRef(QualType Ty, bool HasFreeRegs) const; 9793 ABIArgInfo getIndirectByValue(QualType Ty) const; 9794 ABIArgInfo classifyArgumentType(QualType Ty, uint8_t FreeRegs) const; 9795 ABIArgInfo classifyReturnType(QualType RetTy) const; 9796 }; 9797 9798 class ARCTargetCodeGenInfo : public TargetCodeGenInfo { 9799 public: 9800 ARCTargetCodeGenInfo(CodeGenTypes &CGT) 9801 : TargetCodeGenInfo(std::make_unique<ARCABIInfo>(CGT)) {} 9802 }; 9803 9804 9805 ABIArgInfo ARCABIInfo::getIndirectByRef(QualType Ty, bool HasFreeRegs) const { 9806 return HasFreeRegs ? getNaturalAlignIndirectInReg(Ty) : 9807 getNaturalAlignIndirect(Ty, false); 9808 } 9809 9810 ABIArgInfo ARCABIInfo::getIndirectByValue(QualType Ty) const { 9811 // Compute the byval alignment. 9812 const unsigned MinABIStackAlignInBytes = 4; 9813 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8; 9814 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true, 9815 TypeAlign > MinABIStackAlignInBytes); 9816 } 9817 9818 Address ARCABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 9819 QualType Ty) const { 9820 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false, 9821 getContext().getTypeInfoInChars(Ty), 9822 CharUnits::fromQuantity(4), true); 9823 } 9824 9825 ABIArgInfo ARCABIInfo::classifyArgumentType(QualType Ty, 9826 uint8_t FreeRegs) const { 9827 // Handle the generic C++ ABI. 9828 const RecordType *RT = Ty->getAs<RecordType>(); 9829 if (RT) { 9830 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()); 9831 if (RAA == CGCXXABI::RAA_Indirect) 9832 return getIndirectByRef(Ty, FreeRegs > 0); 9833 9834 if (RAA == CGCXXABI::RAA_DirectInMemory) 9835 return getIndirectByValue(Ty); 9836 } 9837 9838 // Treat an enum type as its underlying type. 9839 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 9840 Ty = EnumTy->getDecl()->getIntegerType(); 9841 9842 auto SizeInRegs = llvm::alignTo(getContext().getTypeSize(Ty), 32) / 32; 9843 9844 if (isAggregateTypeForABI(Ty)) { 9845 // Structures with flexible arrays are always indirect. 9846 if (RT && RT->getDecl()->hasFlexibleArrayMember()) 9847 return getIndirectByValue(Ty); 9848 9849 // Ignore empty structs/unions. 9850 if (isEmptyRecord(getContext(), Ty, true)) 9851 return ABIArgInfo::getIgnore(); 9852 9853 llvm::LLVMContext &LLVMContext = getVMContext(); 9854 9855 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext); 9856 SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32); 9857 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements); 9858 9859 return FreeRegs >= SizeInRegs ? 9860 ABIArgInfo::getDirectInReg(Result) : 9861 ABIArgInfo::getDirect(Result, 0, nullptr, false); 9862 } 9863 9864 if (const auto *EIT = Ty->getAs<ExtIntType>()) 9865 if (EIT->getNumBits() > 64) 9866 return getIndirectByValue(Ty); 9867 9868 return isPromotableIntegerTypeForABI(Ty) 9869 ? (FreeRegs >= SizeInRegs ? ABIArgInfo::getExtendInReg(Ty) 9870 : ABIArgInfo::getExtend(Ty)) 9871 : (FreeRegs >= SizeInRegs ? ABIArgInfo::getDirectInReg() 9872 : ABIArgInfo::getDirect()); 9873 } 9874 9875 ABIArgInfo ARCABIInfo::classifyReturnType(QualType RetTy) const { 9876 if (RetTy->isAnyComplexType()) 9877 return ABIArgInfo::getDirectInReg(); 9878 9879 // Arguments of size > 4 registers are indirect. 9880 auto RetSize = llvm::alignTo(getContext().getTypeSize(RetTy), 32) / 32; 9881 if (RetSize > 4) 9882 return getIndirectByRef(RetTy, /*HasFreeRegs*/ true); 9883 9884 return DefaultABIInfo::classifyReturnType(RetTy); 9885 } 9886 9887 } // End anonymous namespace. 9888 9889 //===----------------------------------------------------------------------===// 9890 // XCore ABI Implementation 9891 //===----------------------------------------------------------------------===// 9892 9893 namespace { 9894 9895 /// A SmallStringEnc instance is used to build up the TypeString by passing 9896 /// it by reference between functions that append to it. 9897 typedef llvm::SmallString<128> SmallStringEnc; 9898 9899 /// TypeStringCache caches the meta encodings of Types. 9900 /// 9901 /// The reason for caching TypeStrings is two fold: 9902 /// 1. To cache a type's encoding for later uses; 9903 /// 2. As a means to break recursive member type inclusion. 9904 /// 9905 /// A cache Entry can have a Status of: 9906 /// NonRecursive: The type encoding is not recursive; 9907 /// Recursive: The type encoding is recursive; 9908 /// Incomplete: An incomplete TypeString; 9909 /// IncompleteUsed: An incomplete TypeString that has been used in a 9910 /// Recursive type encoding. 9911 /// 9912 /// A NonRecursive entry will have all of its sub-members expanded as fully 9913 /// as possible. Whilst it may contain types which are recursive, the type 9914 /// itself is not recursive and thus its encoding may be safely used whenever 9915 /// the type is encountered. 9916 /// 9917 /// A Recursive entry will have all of its sub-members expanded as fully as 9918 /// possible. The type itself is recursive and it may contain other types which 9919 /// are recursive. The Recursive encoding must not be used during the expansion 9920 /// of a recursive type's recursive branch. For simplicity the code uses 9921 /// IncompleteCount to reject all usage of Recursive encodings for member types. 9922 /// 9923 /// An Incomplete entry is always a RecordType and only encodes its 9924 /// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and 9925 /// are placed into the cache during type expansion as a means to identify and 9926 /// handle recursive inclusion of types as sub-members. If there is recursion 9927 /// the entry becomes IncompleteUsed. 9928 /// 9929 /// During the expansion of a RecordType's members: 9930 /// 9931 /// If the cache contains a NonRecursive encoding for the member type, the 9932 /// cached encoding is used; 9933 /// 9934 /// If the cache contains a Recursive encoding for the member type, the 9935 /// cached encoding is 'Swapped' out, as it may be incorrect, and... 9936 /// 9937 /// If the member is a RecordType, an Incomplete encoding is placed into the 9938 /// cache to break potential recursive inclusion of itself as a sub-member; 9939 /// 9940 /// Once a member RecordType has been expanded, its temporary incomplete 9941 /// entry is removed from the cache. If a Recursive encoding was swapped out 9942 /// it is swapped back in; 9943 /// 9944 /// If an incomplete entry is used to expand a sub-member, the incomplete 9945 /// entry is marked as IncompleteUsed. The cache keeps count of how many 9946 /// IncompleteUsed entries it currently contains in IncompleteUsedCount; 9947 /// 9948 /// If a member's encoding is found to be a NonRecursive or Recursive viz: 9949 /// IncompleteUsedCount==0, the member's encoding is added to the cache. 9950 /// Else the member is part of a recursive type and thus the recursion has 9951 /// been exited too soon for the encoding to be correct for the member. 9952 /// 9953 class TypeStringCache { 9954 enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed}; 9955 struct Entry { 9956 std::string Str; // The encoded TypeString for the type. 9957 enum Status State; // Information about the encoding in 'Str'. 9958 std::string Swapped; // A temporary place holder for a Recursive encoding 9959 // during the expansion of RecordType's members. 9960 }; 9961 std::map<const IdentifierInfo *, struct Entry> Map; 9962 unsigned IncompleteCount; // Number of Incomplete entries in the Map. 9963 unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map. 9964 public: 9965 TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {} 9966 void addIncomplete(const IdentifierInfo *ID, std::string StubEnc); 9967 bool removeIncomplete(const IdentifierInfo *ID); 9968 void addIfComplete(const IdentifierInfo *ID, StringRef Str, 9969 bool IsRecursive); 9970 StringRef lookupStr(const IdentifierInfo *ID); 9971 }; 9972 9973 /// TypeString encodings for enum & union fields must be order. 9974 /// FieldEncoding is a helper for this ordering process. 9975 class FieldEncoding { 9976 bool HasName; 9977 std::string Enc; 9978 public: 9979 FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {} 9980 StringRef str() { return Enc; } 9981 bool operator<(const FieldEncoding &rhs) const { 9982 if (HasName != rhs.HasName) return HasName; 9983 return Enc < rhs.Enc; 9984 } 9985 }; 9986 9987 class XCoreABIInfo : public DefaultABIInfo { 9988 public: 9989 XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {} 9990 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 9991 QualType Ty) const override; 9992 }; 9993 9994 class XCoreTargetCodeGenInfo : public TargetCodeGenInfo { 9995 mutable TypeStringCache TSC; 9996 void emitTargetMD(const Decl *D, llvm::GlobalValue *GV, 9997 const CodeGen::CodeGenModule &M) const; 9998 9999 public: 10000 XCoreTargetCodeGenInfo(CodeGenTypes &CGT) 10001 : TargetCodeGenInfo(std::make_unique<XCoreABIInfo>(CGT)) {} 10002 void emitTargetMetadata(CodeGen::CodeGenModule &CGM, 10003 const llvm::MapVector<GlobalDecl, StringRef> 10004 &MangledDeclNames) const override; 10005 }; 10006 10007 } // End anonymous namespace. 10008 10009 // TODO: this implementation is likely now redundant with the default 10010 // EmitVAArg. 10011 Address XCoreABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 10012 QualType Ty) const { 10013 CGBuilderTy &Builder = CGF.Builder; 10014 10015 // Get the VAList. 10016 CharUnits SlotSize = CharUnits::fromQuantity(4); 10017 Address AP(Builder.CreateLoad(VAListAddr), SlotSize); 10018 10019 // Handle the argument. 10020 ABIArgInfo AI = classifyArgumentType(Ty); 10021 CharUnits TypeAlign = getContext().getTypeAlignInChars(Ty); 10022 llvm::Type *ArgTy = CGT.ConvertType(Ty); 10023 if (AI.canHaveCoerceToType() && !AI.getCoerceToType()) 10024 AI.setCoerceToType(ArgTy); 10025 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy); 10026 10027 Address Val = Address::invalid(); 10028 CharUnits ArgSize = CharUnits::Zero(); 10029 switch (AI.getKind()) { 10030 case ABIArgInfo::Expand: 10031 case ABIArgInfo::CoerceAndExpand: 10032 case ABIArgInfo::InAlloca: 10033 llvm_unreachable("Unsupported ABI kind for va_arg"); 10034 case ABIArgInfo::Ignore: 10035 Val = Address(llvm::UndefValue::get(ArgPtrTy), TypeAlign); 10036 ArgSize = CharUnits::Zero(); 10037 break; 10038 case ABIArgInfo::Extend: 10039 case ABIArgInfo::Direct: 10040 Val = Builder.CreateBitCast(AP, ArgPtrTy); 10041 ArgSize = CharUnits::fromQuantity( 10042 getDataLayout().getTypeAllocSize(AI.getCoerceToType())); 10043 ArgSize = ArgSize.alignTo(SlotSize); 10044 break; 10045 case ABIArgInfo::Indirect: 10046 case ABIArgInfo::IndirectAliased: 10047 Val = Builder.CreateElementBitCast(AP, ArgPtrTy); 10048 Val = Address(Builder.CreateLoad(Val), TypeAlign); 10049 ArgSize = SlotSize; 10050 break; 10051 } 10052 10053 // Increment the VAList. 10054 if (!ArgSize.isZero()) { 10055 Address APN = Builder.CreateConstInBoundsByteGEP(AP, ArgSize); 10056 Builder.CreateStore(APN.getPointer(), VAListAddr); 10057 } 10058 10059 return Val; 10060 } 10061 10062 /// During the expansion of a RecordType, an incomplete TypeString is placed 10063 /// into the cache as a means to identify and break recursion. 10064 /// If there is a Recursive encoding in the cache, it is swapped out and will 10065 /// be reinserted by removeIncomplete(). 10066 /// All other types of encoding should have been used rather than arriving here. 10067 void TypeStringCache::addIncomplete(const IdentifierInfo *ID, 10068 std::string StubEnc) { 10069 if (!ID) 10070 return; 10071 Entry &E = Map[ID]; 10072 assert( (E.Str.empty() || E.State == Recursive) && 10073 "Incorrectly use of addIncomplete"); 10074 assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()"); 10075 E.Swapped.swap(E.Str); // swap out the Recursive 10076 E.Str.swap(StubEnc); 10077 E.State = Incomplete; 10078 ++IncompleteCount; 10079 } 10080 10081 /// Once the RecordType has been expanded, the temporary incomplete TypeString 10082 /// must be removed from the cache. 10083 /// If a Recursive was swapped out by addIncomplete(), it will be replaced. 10084 /// Returns true if the RecordType was defined recursively. 10085 bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) { 10086 if (!ID) 10087 return false; 10088 auto I = Map.find(ID); 10089 assert(I != Map.end() && "Entry not present"); 10090 Entry &E = I->second; 10091 assert( (E.State == Incomplete || 10092 E.State == IncompleteUsed) && 10093 "Entry must be an incomplete type"); 10094 bool IsRecursive = false; 10095 if (E.State == IncompleteUsed) { 10096 // We made use of our Incomplete encoding, thus we are recursive. 10097 IsRecursive = true; 10098 --IncompleteUsedCount; 10099 } 10100 if (E.Swapped.empty()) 10101 Map.erase(I); 10102 else { 10103 // Swap the Recursive back. 10104 E.Swapped.swap(E.Str); 10105 E.Swapped.clear(); 10106 E.State = Recursive; 10107 } 10108 --IncompleteCount; 10109 return IsRecursive; 10110 } 10111 10112 /// Add the encoded TypeString to the cache only if it is NonRecursive or 10113 /// Recursive (viz: all sub-members were expanded as fully as possible). 10114 void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str, 10115 bool IsRecursive) { 10116 if (!ID || IncompleteUsedCount) 10117 return; // No key or it is is an incomplete sub-type so don't add. 10118 Entry &E = Map[ID]; 10119 if (IsRecursive && !E.Str.empty()) { 10120 assert(E.State==Recursive && E.Str.size() == Str.size() && 10121 "This is not the same Recursive entry"); 10122 // The parent container was not recursive after all, so we could have used 10123 // this Recursive sub-member entry after all, but we assumed the worse when 10124 // we started viz: IncompleteCount!=0. 10125 return; 10126 } 10127 assert(E.Str.empty() && "Entry already present"); 10128 E.Str = Str.str(); 10129 E.State = IsRecursive? Recursive : NonRecursive; 10130 } 10131 10132 /// Return a cached TypeString encoding for the ID. If there isn't one, or we 10133 /// are recursively expanding a type (IncompleteCount != 0) and the cached 10134 /// encoding is Recursive, return an empty StringRef. 10135 StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) { 10136 if (!ID) 10137 return StringRef(); // We have no key. 10138 auto I = Map.find(ID); 10139 if (I == Map.end()) 10140 return StringRef(); // We have no encoding. 10141 Entry &E = I->second; 10142 if (E.State == Recursive && IncompleteCount) 10143 return StringRef(); // We don't use Recursive encodings for member types. 10144 10145 if (E.State == Incomplete) { 10146 // The incomplete type is being used to break out of recursion. 10147 E.State = IncompleteUsed; 10148 ++IncompleteUsedCount; 10149 } 10150 return E.Str; 10151 } 10152 10153 /// The XCore ABI includes a type information section that communicates symbol 10154 /// type information to the linker. The linker uses this information to verify 10155 /// safety/correctness of things such as array bound and pointers et al. 10156 /// The ABI only requires C (and XC) language modules to emit TypeStrings. 10157 /// This type information (TypeString) is emitted into meta data for all global 10158 /// symbols: definitions, declarations, functions & variables. 10159 /// 10160 /// The TypeString carries type, qualifier, name, size & value details. 10161 /// Please see 'Tools Development Guide' section 2.16.2 for format details: 10162 /// https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf 10163 /// The output is tested by test/CodeGen/xcore-stringtype.c. 10164 /// 10165 static bool getTypeString(SmallStringEnc &Enc, const Decl *D, 10166 const CodeGen::CodeGenModule &CGM, 10167 TypeStringCache &TSC); 10168 10169 /// XCore uses emitTargetMD to emit TypeString metadata for global symbols. 10170 void XCoreTargetCodeGenInfo::emitTargetMD( 10171 const Decl *D, llvm::GlobalValue *GV, 10172 const CodeGen::CodeGenModule &CGM) const { 10173 SmallStringEnc Enc; 10174 if (getTypeString(Enc, D, CGM, TSC)) { 10175 llvm::LLVMContext &Ctx = CGM.getModule().getContext(); 10176 llvm::Metadata *MDVals[] = {llvm::ConstantAsMetadata::get(GV), 10177 llvm::MDString::get(Ctx, Enc.str())}; 10178 llvm::NamedMDNode *MD = 10179 CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings"); 10180 MD->addOperand(llvm::MDNode::get(Ctx, MDVals)); 10181 } 10182 } 10183 10184 void XCoreTargetCodeGenInfo::emitTargetMetadata( 10185 CodeGen::CodeGenModule &CGM, 10186 const llvm::MapVector<GlobalDecl, StringRef> &MangledDeclNames) const { 10187 // Warning, new MangledDeclNames may be appended within this loop. 10188 // We rely on MapVector insertions adding new elements to the end 10189 // of the container. 10190 for (unsigned I = 0; I != MangledDeclNames.size(); ++I) { 10191 auto Val = *(MangledDeclNames.begin() + I); 10192 llvm::GlobalValue *GV = CGM.GetGlobalValue(Val.second); 10193 if (GV) { 10194 const Decl *D = Val.first.getDecl()->getMostRecentDecl(); 10195 emitTargetMD(D, GV, CGM); 10196 } 10197 } 10198 } 10199 //===----------------------------------------------------------------------===// 10200 // SPIR ABI Implementation 10201 //===----------------------------------------------------------------------===// 10202 10203 namespace { 10204 class SPIRABIInfo : public DefaultABIInfo { 10205 public: 10206 SPIRABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) { setCCs(); } 10207 10208 private: 10209 void setCCs(); 10210 }; 10211 } // end anonymous namespace 10212 namespace { 10213 class SPIRTargetCodeGenInfo : public TargetCodeGenInfo { 10214 public: 10215 SPIRTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT) 10216 : TargetCodeGenInfo(std::make_unique<SPIRABIInfo>(CGT)) {} 10217 10218 LangAS getASTAllocaAddressSpace() const override { 10219 return getLangASFromTargetAS( 10220 getABIInfo().getDataLayout().getAllocaAddrSpace()); 10221 } 10222 10223 unsigned getOpenCLKernelCallingConv() const override; 10224 }; 10225 10226 } // End anonymous namespace. 10227 void SPIRABIInfo::setCCs() { 10228 assert(getRuntimeCC() == llvm::CallingConv::C); 10229 RuntimeCC = llvm::CallingConv::SPIR_FUNC; 10230 } 10231 10232 namespace clang { 10233 namespace CodeGen { 10234 void computeSPIRKernelABIInfo(CodeGenModule &CGM, CGFunctionInfo &FI) { 10235 DefaultABIInfo SPIRABI(CGM.getTypes()); 10236 SPIRABI.computeInfo(FI); 10237 } 10238 } 10239 } 10240 10241 unsigned SPIRTargetCodeGenInfo::getOpenCLKernelCallingConv() const { 10242 return llvm::CallingConv::SPIR_KERNEL; 10243 } 10244 10245 static bool appendType(SmallStringEnc &Enc, QualType QType, 10246 const CodeGen::CodeGenModule &CGM, 10247 TypeStringCache &TSC); 10248 10249 /// Helper function for appendRecordType(). 10250 /// Builds a SmallVector containing the encoded field types in declaration 10251 /// order. 10252 static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE, 10253 const RecordDecl *RD, 10254 const CodeGen::CodeGenModule &CGM, 10255 TypeStringCache &TSC) { 10256 for (const auto *Field : RD->fields()) { 10257 SmallStringEnc Enc; 10258 Enc += "m("; 10259 Enc += Field->getName(); 10260 Enc += "){"; 10261 if (Field->isBitField()) { 10262 Enc += "b("; 10263 llvm::raw_svector_ostream OS(Enc); 10264 OS << Field->getBitWidthValue(CGM.getContext()); 10265 Enc += ':'; 10266 } 10267 if (!appendType(Enc, Field->getType(), CGM, TSC)) 10268 return false; 10269 if (Field->isBitField()) 10270 Enc += ')'; 10271 Enc += '}'; 10272 FE.emplace_back(!Field->getName().empty(), Enc); 10273 } 10274 return true; 10275 } 10276 10277 /// Appends structure and union types to Enc and adds encoding to cache. 10278 /// Recursively calls appendType (via extractFieldType) for each field. 10279 /// Union types have their fields ordered according to the ABI. 10280 static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT, 10281 const CodeGen::CodeGenModule &CGM, 10282 TypeStringCache &TSC, const IdentifierInfo *ID) { 10283 // Append the cached TypeString if we have one. 10284 StringRef TypeString = TSC.lookupStr(ID); 10285 if (!TypeString.empty()) { 10286 Enc += TypeString; 10287 return true; 10288 } 10289 10290 // Start to emit an incomplete TypeString. 10291 size_t Start = Enc.size(); 10292 Enc += (RT->isUnionType()? 'u' : 's'); 10293 Enc += '('; 10294 if (ID) 10295 Enc += ID->getName(); 10296 Enc += "){"; 10297 10298 // We collect all encoded fields and order as necessary. 10299 bool IsRecursive = false; 10300 const RecordDecl *RD = RT->getDecl()->getDefinition(); 10301 if (RD && !RD->field_empty()) { 10302 // An incomplete TypeString stub is placed in the cache for this RecordType 10303 // so that recursive calls to this RecordType will use it whilst building a 10304 // complete TypeString for this RecordType. 10305 SmallVector<FieldEncoding, 16> FE; 10306 std::string StubEnc(Enc.substr(Start).str()); 10307 StubEnc += '}'; // StubEnc now holds a valid incomplete TypeString. 10308 TSC.addIncomplete(ID, std::move(StubEnc)); 10309 if (!extractFieldType(FE, RD, CGM, TSC)) { 10310 (void) TSC.removeIncomplete(ID); 10311 return false; 10312 } 10313 IsRecursive = TSC.removeIncomplete(ID); 10314 // The ABI requires unions to be sorted but not structures. 10315 // See FieldEncoding::operator< for sort algorithm. 10316 if (RT->isUnionType()) 10317 llvm::sort(FE); 10318 // We can now complete the TypeString. 10319 unsigned E = FE.size(); 10320 for (unsigned I = 0; I != E; ++I) { 10321 if (I) 10322 Enc += ','; 10323 Enc += FE[I].str(); 10324 } 10325 } 10326 Enc += '}'; 10327 TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive); 10328 return true; 10329 } 10330 10331 /// Appends enum types to Enc and adds the encoding to the cache. 10332 static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET, 10333 TypeStringCache &TSC, 10334 const IdentifierInfo *ID) { 10335 // Append the cached TypeString if we have one. 10336 StringRef TypeString = TSC.lookupStr(ID); 10337 if (!TypeString.empty()) { 10338 Enc += TypeString; 10339 return true; 10340 } 10341 10342 size_t Start = Enc.size(); 10343 Enc += "e("; 10344 if (ID) 10345 Enc += ID->getName(); 10346 Enc += "){"; 10347 10348 // We collect all encoded enumerations and order them alphanumerically. 10349 if (const EnumDecl *ED = ET->getDecl()->getDefinition()) { 10350 SmallVector<FieldEncoding, 16> FE; 10351 for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E; 10352 ++I) { 10353 SmallStringEnc EnumEnc; 10354 EnumEnc += "m("; 10355 EnumEnc += I->getName(); 10356 EnumEnc += "){"; 10357 I->getInitVal().toString(EnumEnc); 10358 EnumEnc += '}'; 10359 FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc)); 10360 } 10361 llvm::sort(FE); 10362 unsigned E = FE.size(); 10363 for (unsigned I = 0; I != E; ++I) { 10364 if (I) 10365 Enc += ','; 10366 Enc += FE[I].str(); 10367 } 10368 } 10369 Enc += '}'; 10370 TSC.addIfComplete(ID, Enc.substr(Start), false); 10371 return true; 10372 } 10373 10374 /// Appends type's qualifier to Enc. 10375 /// This is done prior to appending the type's encoding. 10376 static void appendQualifier(SmallStringEnc &Enc, QualType QT) { 10377 // Qualifiers are emitted in alphabetical order. 10378 static const char *const Table[]={"","c:","r:","cr:","v:","cv:","rv:","crv:"}; 10379 int Lookup = 0; 10380 if (QT.isConstQualified()) 10381 Lookup += 1<<0; 10382 if (QT.isRestrictQualified()) 10383 Lookup += 1<<1; 10384 if (QT.isVolatileQualified()) 10385 Lookup += 1<<2; 10386 Enc += Table[Lookup]; 10387 } 10388 10389 /// Appends built-in types to Enc. 10390 static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) { 10391 const char *EncType; 10392 switch (BT->getKind()) { 10393 case BuiltinType::Void: 10394 EncType = "0"; 10395 break; 10396 case BuiltinType::Bool: 10397 EncType = "b"; 10398 break; 10399 case BuiltinType::Char_U: 10400 EncType = "uc"; 10401 break; 10402 case BuiltinType::UChar: 10403 EncType = "uc"; 10404 break; 10405 case BuiltinType::SChar: 10406 EncType = "sc"; 10407 break; 10408 case BuiltinType::UShort: 10409 EncType = "us"; 10410 break; 10411 case BuiltinType::Short: 10412 EncType = "ss"; 10413 break; 10414 case BuiltinType::UInt: 10415 EncType = "ui"; 10416 break; 10417 case BuiltinType::Int: 10418 EncType = "si"; 10419 break; 10420 case BuiltinType::ULong: 10421 EncType = "ul"; 10422 break; 10423 case BuiltinType::Long: 10424 EncType = "sl"; 10425 break; 10426 case BuiltinType::ULongLong: 10427 EncType = "ull"; 10428 break; 10429 case BuiltinType::LongLong: 10430 EncType = "sll"; 10431 break; 10432 case BuiltinType::Float: 10433 EncType = "ft"; 10434 break; 10435 case BuiltinType::Double: 10436 EncType = "d"; 10437 break; 10438 case BuiltinType::LongDouble: 10439 EncType = "ld"; 10440 break; 10441 default: 10442 return false; 10443 } 10444 Enc += EncType; 10445 return true; 10446 } 10447 10448 /// Appends a pointer encoding to Enc before calling appendType for the pointee. 10449 static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT, 10450 const CodeGen::CodeGenModule &CGM, 10451 TypeStringCache &TSC) { 10452 Enc += "p("; 10453 if (!appendType(Enc, PT->getPointeeType(), CGM, TSC)) 10454 return false; 10455 Enc += ')'; 10456 return true; 10457 } 10458 10459 /// Appends array encoding to Enc before calling appendType for the element. 10460 static bool appendArrayType(SmallStringEnc &Enc, QualType QT, 10461 const ArrayType *AT, 10462 const CodeGen::CodeGenModule &CGM, 10463 TypeStringCache &TSC, StringRef NoSizeEnc) { 10464 if (AT->getSizeModifier() != ArrayType::Normal) 10465 return false; 10466 Enc += "a("; 10467 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) 10468 CAT->getSize().toStringUnsigned(Enc); 10469 else 10470 Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "". 10471 Enc += ':'; 10472 // The Qualifiers should be attached to the type rather than the array. 10473 appendQualifier(Enc, QT); 10474 if (!appendType(Enc, AT->getElementType(), CGM, TSC)) 10475 return false; 10476 Enc += ')'; 10477 return true; 10478 } 10479 10480 /// Appends a function encoding to Enc, calling appendType for the return type 10481 /// and the arguments. 10482 static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT, 10483 const CodeGen::CodeGenModule &CGM, 10484 TypeStringCache &TSC) { 10485 Enc += "f{"; 10486 if (!appendType(Enc, FT->getReturnType(), CGM, TSC)) 10487 return false; 10488 Enc += "}("; 10489 if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) { 10490 // N.B. we are only interested in the adjusted param types. 10491 auto I = FPT->param_type_begin(); 10492 auto E = FPT->param_type_end(); 10493 if (I != E) { 10494 do { 10495 if (!appendType(Enc, *I, CGM, TSC)) 10496 return false; 10497 ++I; 10498 if (I != E) 10499 Enc += ','; 10500 } while (I != E); 10501 if (FPT->isVariadic()) 10502 Enc += ",va"; 10503 } else { 10504 if (FPT->isVariadic()) 10505 Enc += "va"; 10506 else 10507 Enc += '0'; 10508 } 10509 } 10510 Enc += ')'; 10511 return true; 10512 } 10513 10514 /// Handles the type's qualifier before dispatching a call to handle specific 10515 /// type encodings. 10516 static bool appendType(SmallStringEnc &Enc, QualType QType, 10517 const CodeGen::CodeGenModule &CGM, 10518 TypeStringCache &TSC) { 10519 10520 QualType QT = QType.getCanonicalType(); 10521 10522 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) 10523 // The Qualifiers should be attached to the type rather than the array. 10524 // Thus we don't call appendQualifier() here. 10525 return appendArrayType(Enc, QT, AT, CGM, TSC, ""); 10526 10527 appendQualifier(Enc, QT); 10528 10529 if (const BuiltinType *BT = QT->getAs<BuiltinType>()) 10530 return appendBuiltinType(Enc, BT); 10531 10532 if (const PointerType *PT = QT->getAs<PointerType>()) 10533 return appendPointerType(Enc, PT, CGM, TSC); 10534 10535 if (const EnumType *ET = QT->getAs<EnumType>()) 10536 return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier()); 10537 10538 if (const RecordType *RT = QT->getAsStructureType()) 10539 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier()); 10540 10541 if (const RecordType *RT = QT->getAsUnionType()) 10542 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier()); 10543 10544 if (const FunctionType *FT = QT->getAs<FunctionType>()) 10545 return appendFunctionType(Enc, FT, CGM, TSC); 10546 10547 return false; 10548 } 10549 10550 static bool getTypeString(SmallStringEnc &Enc, const Decl *D, 10551 const CodeGen::CodeGenModule &CGM, 10552 TypeStringCache &TSC) { 10553 if (!D) 10554 return false; 10555 10556 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 10557 if (FD->getLanguageLinkage() != CLanguageLinkage) 10558 return false; 10559 return appendType(Enc, FD->getType(), CGM, TSC); 10560 } 10561 10562 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 10563 if (VD->getLanguageLinkage() != CLanguageLinkage) 10564 return false; 10565 QualType QT = VD->getType().getCanonicalType(); 10566 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) { 10567 // Global ArrayTypes are given a size of '*' if the size is unknown. 10568 // The Qualifiers should be attached to the type rather than the array. 10569 // Thus we don't call appendQualifier() here. 10570 return appendArrayType(Enc, QT, AT, CGM, TSC, "*"); 10571 } 10572 return appendType(Enc, QT, CGM, TSC); 10573 } 10574 return false; 10575 } 10576 10577 //===----------------------------------------------------------------------===// 10578 // RISCV ABI Implementation 10579 //===----------------------------------------------------------------------===// 10580 10581 namespace { 10582 class RISCVABIInfo : public DefaultABIInfo { 10583 private: 10584 // Size of the integer ('x') registers in bits. 10585 unsigned XLen; 10586 // Size of the floating point ('f') registers in bits. Note that the target 10587 // ISA might have a wider FLen than the selected ABI (e.g. an RV32IF target 10588 // with soft float ABI has FLen==0). 10589 unsigned FLen; 10590 static const int NumArgGPRs = 8; 10591 static const int NumArgFPRs = 8; 10592 bool detectFPCCEligibleStructHelper(QualType Ty, CharUnits CurOff, 10593 llvm::Type *&Field1Ty, 10594 CharUnits &Field1Off, 10595 llvm::Type *&Field2Ty, 10596 CharUnits &Field2Off) const; 10597 10598 public: 10599 RISCVABIInfo(CodeGen::CodeGenTypes &CGT, unsigned XLen, unsigned FLen) 10600 : DefaultABIInfo(CGT), XLen(XLen), FLen(FLen) {} 10601 10602 // DefaultABIInfo's classifyReturnType and classifyArgumentType are 10603 // non-virtual, but computeInfo is virtual, so we overload it. 10604 void computeInfo(CGFunctionInfo &FI) const override; 10605 10606 ABIArgInfo classifyArgumentType(QualType Ty, bool IsFixed, int &ArgGPRsLeft, 10607 int &ArgFPRsLeft) const; 10608 ABIArgInfo classifyReturnType(QualType RetTy) const; 10609 10610 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 10611 QualType Ty) const override; 10612 10613 ABIArgInfo extendType(QualType Ty) const; 10614 10615 bool detectFPCCEligibleStruct(QualType Ty, llvm::Type *&Field1Ty, 10616 CharUnits &Field1Off, llvm::Type *&Field2Ty, 10617 CharUnits &Field2Off, int &NeededArgGPRs, 10618 int &NeededArgFPRs) const; 10619 ABIArgInfo coerceAndExpandFPCCEligibleStruct(llvm::Type *Field1Ty, 10620 CharUnits Field1Off, 10621 llvm::Type *Field2Ty, 10622 CharUnits Field2Off) const; 10623 }; 10624 } // end anonymous namespace 10625 10626 void RISCVABIInfo::computeInfo(CGFunctionInfo &FI) const { 10627 QualType RetTy = FI.getReturnType(); 10628 if (!getCXXABI().classifyReturnType(FI)) 10629 FI.getReturnInfo() = classifyReturnType(RetTy); 10630 10631 // IsRetIndirect is true if classifyArgumentType indicated the value should 10632 // be passed indirect, or if the type size is a scalar greater than 2*XLen 10633 // and not a complex type with elements <= FLen. e.g. fp128 is passed direct 10634 // in LLVM IR, relying on the backend lowering code to rewrite the argument 10635 // list and pass indirectly on RV32. 10636 bool IsRetIndirect = FI.getReturnInfo().getKind() == ABIArgInfo::Indirect; 10637 if (!IsRetIndirect && RetTy->isScalarType() && 10638 getContext().getTypeSize(RetTy) > (2 * XLen)) { 10639 if (RetTy->isComplexType() && FLen) { 10640 QualType EltTy = RetTy->castAs<ComplexType>()->getElementType(); 10641 IsRetIndirect = getContext().getTypeSize(EltTy) > FLen; 10642 } else { 10643 // This is a normal scalar > 2*XLen, such as fp128 on RV32. 10644 IsRetIndirect = true; 10645 } 10646 } 10647 10648 // We must track the number of GPRs used in order to conform to the RISC-V 10649 // ABI, as integer scalars passed in registers should have signext/zeroext 10650 // when promoted, but are anyext if passed on the stack. As GPR usage is 10651 // different for variadic arguments, we must also track whether we are 10652 // examining a vararg or not. 10653 int ArgGPRsLeft = IsRetIndirect ? NumArgGPRs - 1 : NumArgGPRs; 10654 int ArgFPRsLeft = FLen ? NumArgFPRs : 0; 10655 int NumFixedArgs = FI.getNumRequiredArgs(); 10656 10657 int ArgNum = 0; 10658 for (auto &ArgInfo : FI.arguments()) { 10659 bool IsFixed = ArgNum < NumFixedArgs; 10660 ArgInfo.info = 10661 classifyArgumentType(ArgInfo.type, IsFixed, ArgGPRsLeft, ArgFPRsLeft); 10662 ArgNum++; 10663 } 10664 } 10665 10666 // Returns true if the struct is a potential candidate for the floating point 10667 // calling convention. If this function returns true, the caller is 10668 // responsible for checking that if there is only a single field then that 10669 // field is a float. 10670 bool RISCVABIInfo::detectFPCCEligibleStructHelper(QualType Ty, CharUnits CurOff, 10671 llvm::Type *&Field1Ty, 10672 CharUnits &Field1Off, 10673 llvm::Type *&Field2Ty, 10674 CharUnits &Field2Off) const { 10675 bool IsInt = Ty->isIntegralOrEnumerationType(); 10676 bool IsFloat = Ty->isRealFloatingType(); 10677 10678 if (IsInt || IsFloat) { 10679 uint64_t Size = getContext().getTypeSize(Ty); 10680 if (IsInt && Size > XLen) 10681 return false; 10682 // Can't be eligible if larger than the FP registers. Half precision isn't 10683 // currently supported on RISC-V and the ABI hasn't been confirmed, so 10684 // default to the integer ABI in that case. 10685 if (IsFloat && (Size > FLen || Size < 32)) 10686 return false; 10687 // Can't be eligible if an integer type was already found (int+int pairs 10688 // are not eligible). 10689 if (IsInt && Field1Ty && Field1Ty->isIntegerTy()) 10690 return false; 10691 if (!Field1Ty) { 10692 Field1Ty = CGT.ConvertType(Ty); 10693 Field1Off = CurOff; 10694 return true; 10695 } 10696 if (!Field2Ty) { 10697 Field2Ty = CGT.ConvertType(Ty); 10698 Field2Off = CurOff; 10699 return true; 10700 } 10701 return false; 10702 } 10703 10704 if (auto CTy = Ty->getAs<ComplexType>()) { 10705 if (Field1Ty) 10706 return false; 10707 QualType EltTy = CTy->getElementType(); 10708 if (getContext().getTypeSize(EltTy) > FLen) 10709 return false; 10710 Field1Ty = CGT.ConvertType(EltTy); 10711 Field1Off = CurOff; 10712 Field2Ty = Field1Ty; 10713 Field2Off = Field1Off + getContext().getTypeSizeInChars(EltTy); 10714 return true; 10715 } 10716 10717 if (const ConstantArrayType *ATy = getContext().getAsConstantArrayType(Ty)) { 10718 uint64_t ArraySize = ATy->getSize().getZExtValue(); 10719 QualType EltTy = ATy->getElementType(); 10720 CharUnits EltSize = getContext().getTypeSizeInChars(EltTy); 10721 for (uint64_t i = 0; i < ArraySize; ++i) { 10722 bool Ret = detectFPCCEligibleStructHelper(EltTy, CurOff, Field1Ty, 10723 Field1Off, Field2Ty, Field2Off); 10724 if (!Ret) 10725 return false; 10726 CurOff += EltSize; 10727 } 10728 return true; 10729 } 10730 10731 if (const auto *RTy = Ty->getAs<RecordType>()) { 10732 // Structures with either a non-trivial destructor or a non-trivial 10733 // copy constructor are not eligible for the FP calling convention. 10734 if (getRecordArgABI(Ty, CGT.getCXXABI())) 10735 return false; 10736 if (isEmptyRecord(getContext(), Ty, true)) 10737 return true; 10738 const RecordDecl *RD = RTy->getDecl(); 10739 // Unions aren't eligible unless they're empty (which is caught above). 10740 if (RD->isUnion()) 10741 return false; 10742 int ZeroWidthBitFieldCount = 0; 10743 for (const FieldDecl *FD : RD->fields()) { 10744 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD); 10745 uint64_t FieldOffInBits = Layout.getFieldOffset(FD->getFieldIndex()); 10746 QualType QTy = FD->getType(); 10747 if (FD->isBitField()) { 10748 unsigned BitWidth = FD->getBitWidthValue(getContext()); 10749 // Allow a bitfield with a type greater than XLen as long as the 10750 // bitwidth is XLen or less. 10751 if (getContext().getTypeSize(QTy) > XLen && BitWidth <= XLen) 10752 QTy = getContext().getIntTypeForBitwidth(XLen, false); 10753 if (BitWidth == 0) { 10754 ZeroWidthBitFieldCount++; 10755 continue; 10756 } 10757 } 10758 10759 bool Ret = detectFPCCEligibleStructHelper( 10760 QTy, CurOff + getContext().toCharUnitsFromBits(FieldOffInBits), 10761 Field1Ty, Field1Off, Field2Ty, Field2Off); 10762 if (!Ret) 10763 return false; 10764 10765 // As a quirk of the ABI, zero-width bitfields aren't ignored for fp+fp 10766 // or int+fp structs, but are ignored for a struct with an fp field and 10767 // any number of zero-width bitfields. 10768 if (Field2Ty && ZeroWidthBitFieldCount > 0) 10769 return false; 10770 } 10771 return Field1Ty != nullptr; 10772 } 10773 10774 return false; 10775 } 10776 10777 // Determine if a struct is eligible for passing according to the floating 10778 // point calling convention (i.e., when flattened it contains a single fp 10779 // value, fp+fp, or int+fp of appropriate size). If so, NeededArgFPRs and 10780 // NeededArgGPRs are incremented appropriately. 10781 bool RISCVABIInfo::detectFPCCEligibleStruct(QualType Ty, llvm::Type *&Field1Ty, 10782 CharUnits &Field1Off, 10783 llvm::Type *&Field2Ty, 10784 CharUnits &Field2Off, 10785 int &NeededArgGPRs, 10786 int &NeededArgFPRs) const { 10787 Field1Ty = nullptr; 10788 Field2Ty = nullptr; 10789 NeededArgGPRs = 0; 10790 NeededArgFPRs = 0; 10791 bool IsCandidate = detectFPCCEligibleStructHelper( 10792 Ty, CharUnits::Zero(), Field1Ty, Field1Off, Field2Ty, Field2Off); 10793 // Not really a candidate if we have a single int but no float. 10794 if (Field1Ty && !Field2Ty && !Field1Ty->isFloatingPointTy()) 10795 return false; 10796 if (!IsCandidate) 10797 return false; 10798 if (Field1Ty && Field1Ty->isFloatingPointTy()) 10799 NeededArgFPRs++; 10800 else if (Field1Ty) 10801 NeededArgGPRs++; 10802 if (Field2Ty && Field2Ty->isFloatingPointTy()) 10803 NeededArgFPRs++; 10804 else if (Field2Ty) 10805 NeededArgGPRs++; 10806 return true; 10807 } 10808 10809 // Call getCoerceAndExpand for the two-element flattened struct described by 10810 // Field1Ty, Field1Off, Field2Ty, Field2Off. This method will create an 10811 // appropriate coerceToType and unpaddedCoerceToType. 10812 ABIArgInfo RISCVABIInfo::coerceAndExpandFPCCEligibleStruct( 10813 llvm::Type *Field1Ty, CharUnits Field1Off, llvm::Type *Field2Ty, 10814 CharUnits Field2Off) const { 10815 SmallVector<llvm::Type *, 3> CoerceElts; 10816 SmallVector<llvm::Type *, 2> UnpaddedCoerceElts; 10817 if (!Field1Off.isZero()) 10818 CoerceElts.push_back(llvm::ArrayType::get( 10819 llvm::Type::getInt8Ty(getVMContext()), Field1Off.getQuantity())); 10820 10821 CoerceElts.push_back(Field1Ty); 10822 UnpaddedCoerceElts.push_back(Field1Ty); 10823 10824 if (!Field2Ty) { 10825 return ABIArgInfo::getCoerceAndExpand( 10826 llvm::StructType::get(getVMContext(), CoerceElts, !Field1Off.isZero()), 10827 UnpaddedCoerceElts[0]); 10828 } 10829 10830 CharUnits Field2Align = 10831 CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(Field2Ty)); 10832 CharUnits Field1End = Field1Off + 10833 CharUnits::fromQuantity(getDataLayout().getTypeStoreSize(Field1Ty)); 10834 CharUnits Field2OffNoPadNoPack = Field1End.alignTo(Field2Align); 10835 10836 CharUnits Padding = CharUnits::Zero(); 10837 if (Field2Off > Field2OffNoPadNoPack) 10838 Padding = Field2Off - Field2OffNoPadNoPack; 10839 else if (Field2Off != Field2Align && Field2Off > Field1End) 10840 Padding = Field2Off - Field1End; 10841 10842 bool IsPacked = !Field2Off.isMultipleOf(Field2Align); 10843 10844 if (!Padding.isZero()) 10845 CoerceElts.push_back(llvm::ArrayType::get( 10846 llvm::Type::getInt8Ty(getVMContext()), Padding.getQuantity())); 10847 10848 CoerceElts.push_back(Field2Ty); 10849 UnpaddedCoerceElts.push_back(Field2Ty); 10850 10851 auto CoerceToType = 10852 llvm::StructType::get(getVMContext(), CoerceElts, IsPacked); 10853 auto UnpaddedCoerceToType = 10854 llvm::StructType::get(getVMContext(), UnpaddedCoerceElts, IsPacked); 10855 10856 return ABIArgInfo::getCoerceAndExpand(CoerceToType, UnpaddedCoerceToType); 10857 } 10858 10859 ABIArgInfo RISCVABIInfo::classifyArgumentType(QualType Ty, bool IsFixed, 10860 int &ArgGPRsLeft, 10861 int &ArgFPRsLeft) const { 10862 assert(ArgGPRsLeft <= NumArgGPRs && "Arg GPR tracking underflow"); 10863 Ty = useFirstFieldIfTransparentUnion(Ty); 10864 10865 // Structures with either a non-trivial destructor or a non-trivial 10866 // copy constructor are always passed indirectly. 10867 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) { 10868 if (ArgGPRsLeft) 10869 ArgGPRsLeft -= 1; 10870 return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA == 10871 CGCXXABI::RAA_DirectInMemory); 10872 } 10873 10874 // Ignore empty structs/unions. 10875 if (isEmptyRecord(getContext(), Ty, true)) 10876 return ABIArgInfo::getIgnore(); 10877 10878 uint64_t Size = getContext().getTypeSize(Ty); 10879 10880 // Pass floating point values via FPRs if possible. 10881 if (IsFixed && Ty->isFloatingType() && !Ty->isComplexType() && 10882 FLen >= Size && ArgFPRsLeft) { 10883 ArgFPRsLeft--; 10884 return ABIArgInfo::getDirect(); 10885 } 10886 10887 // Complex types for the hard float ABI must be passed direct rather than 10888 // using CoerceAndExpand. 10889 if (IsFixed && Ty->isComplexType() && FLen && ArgFPRsLeft >= 2) { 10890 QualType EltTy = Ty->castAs<ComplexType>()->getElementType(); 10891 if (getContext().getTypeSize(EltTy) <= FLen) { 10892 ArgFPRsLeft -= 2; 10893 return ABIArgInfo::getDirect(); 10894 } 10895 } 10896 10897 if (IsFixed && FLen && Ty->isStructureOrClassType()) { 10898 llvm::Type *Field1Ty = nullptr; 10899 llvm::Type *Field2Ty = nullptr; 10900 CharUnits Field1Off = CharUnits::Zero(); 10901 CharUnits Field2Off = CharUnits::Zero(); 10902 int NeededArgGPRs = 0; 10903 int NeededArgFPRs = 0; 10904 bool IsCandidate = 10905 detectFPCCEligibleStruct(Ty, Field1Ty, Field1Off, Field2Ty, Field2Off, 10906 NeededArgGPRs, NeededArgFPRs); 10907 if (IsCandidate && NeededArgGPRs <= ArgGPRsLeft && 10908 NeededArgFPRs <= ArgFPRsLeft) { 10909 ArgGPRsLeft -= NeededArgGPRs; 10910 ArgFPRsLeft -= NeededArgFPRs; 10911 return coerceAndExpandFPCCEligibleStruct(Field1Ty, Field1Off, Field2Ty, 10912 Field2Off); 10913 } 10914 } 10915 10916 uint64_t NeededAlign = getContext().getTypeAlign(Ty); 10917 bool MustUseStack = false; 10918 // Determine the number of GPRs needed to pass the current argument 10919 // according to the ABI. 2*XLen-aligned varargs are passed in "aligned" 10920 // register pairs, so may consume 3 registers. 10921 int NeededArgGPRs = 1; 10922 if (!IsFixed && NeededAlign == 2 * XLen) 10923 NeededArgGPRs = 2 + (ArgGPRsLeft % 2); 10924 else if (Size > XLen && Size <= 2 * XLen) 10925 NeededArgGPRs = 2; 10926 10927 if (NeededArgGPRs > ArgGPRsLeft) { 10928 MustUseStack = true; 10929 NeededArgGPRs = ArgGPRsLeft; 10930 } 10931 10932 ArgGPRsLeft -= NeededArgGPRs; 10933 10934 if (!isAggregateTypeForABI(Ty) && !Ty->isVectorType()) { 10935 // Treat an enum type as its underlying type. 10936 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 10937 Ty = EnumTy->getDecl()->getIntegerType(); 10938 10939 // All integral types are promoted to XLen width, unless passed on the 10940 // stack. 10941 if (Size < XLen && Ty->isIntegralOrEnumerationType() && !MustUseStack) { 10942 return extendType(Ty); 10943 } 10944 10945 if (const auto *EIT = Ty->getAs<ExtIntType>()) { 10946 if (EIT->getNumBits() < XLen && !MustUseStack) 10947 return extendType(Ty); 10948 if (EIT->getNumBits() > 128 || 10949 (!getContext().getTargetInfo().hasInt128Type() && 10950 EIT->getNumBits() > 64)) 10951 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 10952 } 10953 10954 return ABIArgInfo::getDirect(); 10955 } 10956 10957 // Aggregates which are <= 2*XLen will be passed in registers if possible, 10958 // so coerce to integers. 10959 if (Size <= 2 * XLen) { 10960 unsigned Alignment = getContext().getTypeAlign(Ty); 10961 10962 // Use a single XLen int if possible, 2*XLen if 2*XLen alignment is 10963 // required, and a 2-element XLen array if only XLen alignment is required. 10964 if (Size <= XLen) { 10965 return ABIArgInfo::getDirect( 10966 llvm::IntegerType::get(getVMContext(), XLen)); 10967 } else if (Alignment == 2 * XLen) { 10968 return ABIArgInfo::getDirect( 10969 llvm::IntegerType::get(getVMContext(), 2 * XLen)); 10970 } else { 10971 return ABIArgInfo::getDirect(llvm::ArrayType::get( 10972 llvm::IntegerType::get(getVMContext(), XLen), 2)); 10973 } 10974 } 10975 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 10976 } 10977 10978 ABIArgInfo RISCVABIInfo::classifyReturnType(QualType RetTy) const { 10979 if (RetTy->isVoidType()) 10980 return ABIArgInfo::getIgnore(); 10981 10982 int ArgGPRsLeft = 2; 10983 int ArgFPRsLeft = FLen ? 2 : 0; 10984 10985 // The rules for return and argument types are the same, so defer to 10986 // classifyArgumentType. 10987 return classifyArgumentType(RetTy, /*IsFixed=*/true, ArgGPRsLeft, 10988 ArgFPRsLeft); 10989 } 10990 10991 Address RISCVABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 10992 QualType Ty) const { 10993 CharUnits SlotSize = CharUnits::fromQuantity(XLen / 8); 10994 10995 // Empty records are ignored for parameter passing purposes. 10996 if (isEmptyRecord(getContext(), Ty, true)) { 10997 Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize); 10998 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty)); 10999 return Addr; 11000 } 11001 11002 auto TInfo = getContext().getTypeInfoInChars(Ty); 11003 11004 // Arguments bigger than 2*Xlen bytes are passed indirectly. 11005 bool IsIndirect = TInfo.Width > 2 * SlotSize; 11006 11007 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TInfo, 11008 SlotSize, /*AllowHigherAlign=*/true); 11009 } 11010 11011 ABIArgInfo RISCVABIInfo::extendType(QualType Ty) const { 11012 int TySize = getContext().getTypeSize(Ty); 11013 // RV64 ABI requires unsigned 32 bit integers to be sign extended. 11014 if (XLen == 64 && Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32) 11015 return ABIArgInfo::getSignExtend(Ty); 11016 return ABIArgInfo::getExtend(Ty); 11017 } 11018 11019 namespace { 11020 class RISCVTargetCodeGenInfo : public TargetCodeGenInfo { 11021 public: 11022 RISCVTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, unsigned XLen, 11023 unsigned FLen) 11024 : TargetCodeGenInfo(std::make_unique<RISCVABIInfo>(CGT, XLen, FLen)) {} 11025 11026 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 11027 CodeGen::CodeGenModule &CGM) const override { 11028 const auto *FD = dyn_cast_or_null<FunctionDecl>(D); 11029 if (!FD) return; 11030 11031 const auto *Attr = FD->getAttr<RISCVInterruptAttr>(); 11032 if (!Attr) 11033 return; 11034 11035 const char *Kind; 11036 switch (Attr->getInterrupt()) { 11037 case RISCVInterruptAttr::user: Kind = "user"; break; 11038 case RISCVInterruptAttr::supervisor: Kind = "supervisor"; break; 11039 case RISCVInterruptAttr::machine: Kind = "machine"; break; 11040 } 11041 11042 auto *Fn = cast<llvm::Function>(GV); 11043 11044 Fn->addFnAttr("interrupt", Kind); 11045 } 11046 }; 11047 } // namespace 11048 11049 //===----------------------------------------------------------------------===// 11050 // VE ABI Implementation. 11051 // 11052 namespace { 11053 class VEABIInfo : public DefaultABIInfo { 11054 public: 11055 VEABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {} 11056 11057 private: 11058 ABIArgInfo classifyReturnType(QualType RetTy) const; 11059 ABIArgInfo classifyArgumentType(QualType RetTy) const; 11060 void computeInfo(CGFunctionInfo &FI) const override; 11061 }; 11062 } // end anonymous namespace 11063 11064 ABIArgInfo VEABIInfo::classifyReturnType(QualType Ty) const { 11065 if (Ty->isAnyComplexType()) 11066 return ABIArgInfo::getDirect(); 11067 uint64_t Size = getContext().getTypeSize(Ty); 11068 if (Size < 64 && Ty->isIntegerType()) 11069 return ABIArgInfo::getExtend(Ty); 11070 return DefaultABIInfo::classifyReturnType(Ty); 11071 } 11072 11073 ABIArgInfo VEABIInfo::classifyArgumentType(QualType Ty) const { 11074 if (Ty->isAnyComplexType()) 11075 return ABIArgInfo::getDirect(); 11076 uint64_t Size = getContext().getTypeSize(Ty); 11077 if (Size < 64 && Ty->isIntegerType()) 11078 return ABIArgInfo::getExtend(Ty); 11079 return DefaultABIInfo::classifyArgumentType(Ty); 11080 } 11081 11082 void VEABIInfo::computeInfo(CGFunctionInfo &FI) const { 11083 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 11084 for (auto &Arg : FI.arguments()) 11085 Arg.info = classifyArgumentType(Arg.type); 11086 } 11087 11088 namespace { 11089 class VETargetCodeGenInfo : public TargetCodeGenInfo { 11090 public: 11091 VETargetCodeGenInfo(CodeGenTypes &CGT) 11092 : TargetCodeGenInfo(std::make_unique<VEABIInfo>(CGT)) {} 11093 // VE ABI requires the arguments of variadic and prototype-less functions 11094 // are passed in both registers and memory. 11095 bool isNoProtoCallVariadic(const CallArgList &args, 11096 const FunctionNoProtoType *fnType) const override { 11097 return true; 11098 } 11099 }; 11100 } // end anonymous namespace 11101 11102 //===----------------------------------------------------------------------===// 11103 // Driver code 11104 //===----------------------------------------------------------------------===// 11105 11106 bool CodeGenModule::supportsCOMDAT() const { 11107 return getTriple().supportsCOMDAT(); 11108 } 11109 11110 const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() { 11111 if (TheTargetCodeGenInfo) 11112 return *TheTargetCodeGenInfo; 11113 11114 // Helper to set the unique_ptr while still keeping the return value. 11115 auto SetCGInfo = [&](TargetCodeGenInfo *P) -> const TargetCodeGenInfo & { 11116 this->TheTargetCodeGenInfo.reset(P); 11117 return *P; 11118 }; 11119 11120 const llvm::Triple &Triple = getTarget().getTriple(); 11121 switch (Triple.getArch()) { 11122 default: 11123 return SetCGInfo(new DefaultTargetCodeGenInfo(Types)); 11124 11125 case llvm::Triple::le32: 11126 return SetCGInfo(new PNaClTargetCodeGenInfo(Types)); 11127 case llvm::Triple::m68k: 11128 return SetCGInfo(new M68kTargetCodeGenInfo(Types)); 11129 case llvm::Triple::mips: 11130 case llvm::Triple::mipsel: 11131 if (Triple.getOS() == llvm::Triple::NaCl) 11132 return SetCGInfo(new PNaClTargetCodeGenInfo(Types)); 11133 return SetCGInfo(new MIPSTargetCodeGenInfo(Types, true)); 11134 11135 case llvm::Triple::mips64: 11136 case llvm::Triple::mips64el: 11137 return SetCGInfo(new MIPSTargetCodeGenInfo(Types, false)); 11138 11139 case llvm::Triple::avr: 11140 return SetCGInfo(new AVRTargetCodeGenInfo(Types)); 11141 11142 case llvm::Triple::aarch64: 11143 case llvm::Triple::aarch64_32: 11144 case llvm::Triple::aarch64_be: { 11145 AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS; 11146 if (getTarget().getABI() == "darwinpcs") 11147 Kind = AArch64ABIInfo::DarwinPCS; 11148 else if (Triple.isOSWindows()) 11149 return SetCGInfo( 11150 new WindowsAArch64TargetCodeGenInfo(Types, AArch64ABIInfo::Win64)); 11151 11152 return SetCGInfo(new AArch64TargetCodeGenInfo(Types, Kind)); 11153 } 11154 11155 case llvm::Triple::wasm32: 11156 case llvm::Triple::wasm64: { 11157 WebAssemblyABIInfo::ABIKind Kind = WebAssemblyABIInfo::MVP; 11158 if (getTarget().getABI() == "experimental-mv") 11159 Kind = WebAssemblyABIInfo::ExperimentalMV; 11160 return SetCGInfo(new WebAssemblyTargetCodeGenInfo(Types, Kind)); 11161 } 11162 11163 case llvm::Triple::arm: 11164 case llvm::Triple::armeb: 11165 case llvm::Triple::thumb: 11166 case llvm::Triple::thumbeb: { 11167 if (Triple.getOS() == llvm::Triple::Win32) { 11168 return SetCGInfo( 11169 new WindowsARMTargetCodeGenInfo(Types, ARMABIInfo::AAPCS_VFP)); 11170 } 11171 11172 ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS; 11173 StringRef ABIStr = getTarget().getABI(); 11174 if (ABIStr == "apcs-gnu") 11175 Kind = ARMABIInfo::APCS; 11176 else if (ABIStr == "aapcs16") 11177 Kind = ARMABIInfo::AAPCS16_VFP; 11178 else if (CodeGenOpts.FloatABI == "hard" || 11179 (CodeGenOpts.FloatABI != "soft" && 11180 (Triple.getEnvironment() == llvm::Triple::GNUEABIHF || 11181 Triple.getEnvironment() == llvm::Triple::MuslEABIHF || 11182 Triple.getEnvironment() == llvm::Triple::EABIHF))) 11183 Kind = ARMABIInfo::AAPCS_VFP; 11184 11185 return SetCGInfo(new ARMTargetCodeGenInfo(Types, Kind)); 11186 } 11187 11188 case llvm::Triple::ppc: { 11189 if (Triple.isOSAIX()) 11190 return SetCGInfo(new AIXTargetCodeGenInfo(Types, /*Is64Bit*/ false)); 11191 11192 bool IsSoftFloat = 11193 CodeGenOpts.FloatABI == "soft" || getTarget().hasFeature("spe"); 11194 bool RetSmallStructInRegABI = 11195 PPC32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts); 11196 return SetCGInfo( 11197 new PPC32TargetCodeGenInfo(Types, IsSoftFloat, RetSmallStructInRegABI)); 11198 } 11199 case llvm::Triple::ppcle: { 11200 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft"; 11201 bool RetSmallStructInRegABI = 11202 PPC32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts); 11203 return SetCGInfo( 11204 new PPC32TargetCodeGenInfo(Types, IsSoftFloat, RetSmallStructInRegABI)); 11205 } 11206 case llvm::Triple::ppc64: 11207 if (Triple.isOSAIX()) 11208 return SetCGInfo(new AIXTargetCodeGenInfo(Types, /*Is64Bit*/ true)); 11209 11210 if (Triple.isOSBinFormatELF()) { 11211 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1; 11212 if (getTarget().getABI() == "elfv2") 11213 Kind = PPC64_SVR4_ABIInfo::ELFv2; 11214 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft"; 11215 11216 return SetCGInfo( 11217 new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, IsSoftFloat)); 11218 } 11219 return SetCGInfo(new PPC64TargetCodeGenInfo(Types)); 11220 case llvm::Triple::ppc64le: { 11221 assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!"); 11222 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2; 11223 if (getTarget().getABI() == "elfv1") 11224 Kind = PPC64_SVR4_ABIInfo::ELFv1; 11225 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft"; 11226 11227 return SetCGInfo( 11228 new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, IsSoftFloat)); 11229 } 11230 11231 case llvm::Triple::nvptx: 11232 case llvm::Triple::nvptx64: 11233 return SetCGInfo(new NVPTXTargetCodeGenInfo(Types)); 11234 11235 case llvm::Triple::msp430: 11236 return SetCGInfo(new MSP430TargetCodeGenInfo(Types)); 11237 11238 case llvm::Triple::riscv32: 11239 case llvm::Triple::riscv64: { 11240 StringRef ABIStr = getTarget().getABI(); 11241 unsigned XLen = getTarget().getPointerWidth(0); 11242 unsigned ABIFLen = 0; 11243 if (ABIStr.endswith("f")) 11244 ABIFLen = 32; 11245 else if (ABIStr.endswith("d")) 11246 ABIFLen = 64; 11247 return SetCGInfo(new RISCVTargetCodeGenInfo(Types, XLen, ABIFLen)); 11248 } 11249 11250 case llvm::Triple::systemz: { 11251 bool SoftFloat = CodeGenOpts.FloatABI == "soft"; 11252 bool HasVector = !SoftFloat && getTarget().getABI() == "vector"; 11253 return SetCGInfo(new SystemZTargetCodeGenInfo(Types, HasVector, SoftFloat)); 11254 } 11255 11256 case llvm::Triple::tce: 11257 case llvm::Triple::tcele: 11258 return SetCGInfo(new TCETargetCodeGenInfo(Types)); 11259 11260 case llvm::Triple::x86: { 11261 bool IsDarwinVectorABI = Triple.isOSDarwin(); 11262 bool RetSmallStructInRegABI = 11263 X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts); 11264 bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing(); 11265 11266 if (Triple.getOS() == llvm::Triple::Win32) { 11267 return SetCGInfo(new WinX86_32TargetCodeGenInfo( 11268 Types, IsDarwinVectorABI, RetSmallStructInRegABI, 11269 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters)); 11270 } else { 11271 return SetCGInfo(new X86_32TargetCodeGenInfo( 11272 Types, IsDarwinVectorABI, RetSmallStructInRegABI, 11273 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters, 11274 CodeGenOpts.FloatABI == "soft")); 11275 } 11276 } 11277 11278 case llvm::Triple::x86_64: { 11279 StringRef ABI = getTarget().getABI(); 11280 X86AVXABILevel AVXLevel = 11281 (ABI == "avx512" 11282 ? X86AVXABILevel::AVX512 11283 : ABI == "avx" ? X86AVXABILevel::AVX : X86AVXABILevel::None); 11284 11285 switch (Triple.getOS()) { 11286 case llvm::Triple::Win32: 11287 return SetCGInfo(new WinX86_64TargetCodeGenInfo(Types, AVXLevel)); 11288 default: 11289 return SetCGInfo(new X86_64TargetCodeGenInfo(Types, AVXLevel)); 11290 } 11291 } 11292 case llvm::Triple::hexagon: 11293 return SetCGInfo(new HexagonTargetCodeGenInfo(Types)); 11294 case llvm::Triple::lanai: 11295 return SetCGInfo(new LanaiTargetCodeGenInfo(Types)); 11296 case llvm::Triple::r600: 11297 return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types)); 11298 case llvm::Triple::amdgcn: 11299 return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types)); 11300 case llvm::Triple::sparc: 11301 return SetCGInfo(new SparcV8TargetCodeGenInfo(Types)); 11302 case llvm::Triple::sparcv9: 11303 return SetCGInfo(new SparcV9TargetCodeGenInfo(Types)); 11304 case llvm::Triple::xcore: 11305 return SetCGInfo(new XCoreTargetCodeGenInfo(Types)); 11306 case llvm::Triple::arc: 11307 return SetCGInfo(new ARCTargetCodeGenInfo(Types)); 11308 case llvm::Triple::spir: 11309 case llvm::Triple::spir64: 11310 return SetCGInfo(new SPIRTargetCodeGenInfo(Types)); 11311 case llvm::Triple::ve: 11312 return SetCGInfo(new VETargetCodeGenInfo(Types)); 11313 } 11314 } 11315 11316 /// Create an OpenCL kernel for an enqueued block. 11317 /// 11318 /// The kernel has the same function type as the block invoke function. Its 11319 /// name is the name of the block invoke function postfixed with "_kernel". 11320 /// It simply calls the block invoke function then returns. 11321 llvm::Function * 11322 TargetCodeGenInfo::createEnqueuedBlockKernel(CodeGenFunction &CGF, 11323 llvm::Function *Invoke, 11324 llvm::Value *BlockLiteral) const { 11325 auto *InvokeFT = Invoke->getFunctionType(); 11326 llvm::SmallVector<llvm::Type *, 2> ArgTys; 11327 for (auto &P : InvokeFT->params()) 11328 ArgTys.push_back(P); 11329 auto &C = CGF.getLLVMContext(); 11330 std::string Name = Invoke->getName().str() + "_kernel"; 11331 auto *FT = llvm::FunctionType::get(llvm::Type::getVoidTy(C), ArgTys, false); 11332 auto *F = llvm::Function::Create(FT, llvm::GlobalValue::InternalLinkage, Name, 11333 &CGF.CGM.getModule()); 11334 auto IP = CGF.Builder.saveIP(); 11335 auto *BB = llvm::BasicBlock::Create(C, "entry", F); 11336 auto &Builder = CGF.Builder; 11337 Builder.SetInsertPoint(BB); 11338 llvm::SmallVector<llvm::Value *, 2> Args; 11339 for (auto &A : F->args()) 11340 Args.push_back(&A); 11341 llvm::CallInst *call = Builder.CreateCall(Invoke, Args); 11342 call->setCallingConv(Invoke->getCallingConv()); 11343 Builder.CreateRetVoid(); 11344 Builder.restoreIP(IP); 11345 return F; 11346 } 11347 11348 /// Create an OpenCL kernel for an enqueued block. 11349 /// 11350 /// The type of the first argument (the block literal) is the struct type 11351 /// of the block literal instead of a pointer type. The first argument 11352 /// (block literal) is passed directly by value to the kernel. The kernel 11353 /// allocates the same type of struct on stack and stores the block literal 11354 /// to it and passes its pointer to the block invoke function. The kernel 11355 /// has "enqueued-block" function attribute and kernel argument metadata. 11356 llvm::Function *AMDGPUTargetCodeGenInfo::createEnqueuedBlockKernel( 11357 CodeGenFunction &CGF, llvm::Function *Invoke, 11358 llvm::Value *BlockLiteral) const { 11359 auto &Builder = CGF.Builder; 11360 auto &C = CGF.getLLVMContext(); 11361 11362 auto *BlockTy = BlockLiteral->getType()->getPointerElementType(); 11363 auto *InvokeFT = Invoke->getFunctionType(); 11364 llvm::SmallVector<llvm::Type *, 2> ArgTys; 11365 llvm::SmallVector<llvm::Metadata *, 8> AddressQuals; 11366 llvm::SmallVector<llvm::Metadata *, 8> AccessQuals; 11367 llvm::SmallVector<llvm::Metadata *, 8> ArgTypeNames; 11368 llvm::SmallVector<llvm::Metadata *, 8> ArgBaseTypeNames; 11369 llvm::SmallVector<llvm::Metadata *, 8> ArgTypeQuals; 11370 llvm::SmallVector<llvm::Metadata *, 8> ArgNames; 11371 11372 ArgTys.push_back(BlockTy); 11373 ArgTypeNames.push_back(llvm::MDString::get(C, "__block_literal")); 11374 AddressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(0))); 11375 ArgBaseTypeNames.push_back(llvm::MDString::get(C, "__block_literal")); 11376 ArgTypeQuals.push_back(llvm::MDString::get(C, "")); 11377 AccessQuals.push_back(llvm::MDString::get(C, "none")); 11378 ArgNames.push_back(llvm::MDString::get(C, "block_literal")); 11379 for (unsigned I = 1, E = InvokeFT->getNumParams(); I < E; ++I) { 11380 ArgTys.push_back(InvokeFT->getParamType(I)); 11381 ArgTypeNames.push_back(llvm::MDString::get(C, "void*")); 11382 AddressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(3))); 11383 AccessQuals.push_back(llvm::MDString::get(C, "none")); 11384 ArgBaseTypeNames.push_back(llvm::MDString::get(C, "void*")); 11385 ArgTypeQuals.push_back(llvm::MDString::get(C, "")); 11386 ArgNames.push_back( 11387 llvm::MDString::get(C, (Twine("local_arg") + Twine(I)).str())); 11388 } 11389 std::string Name = Invoke->getName().str() + "_kernel"; 11390 auto *FT = llvm::FunctionType::get(llvm::Type::getVoidTy(C), ArgTys, false); 11391 auto *F = llvm::Function::Create(FT, llvm::GlobalValue::InternalLinkage, Name, 11392 &CGF.CGM.getModule()); 11393 F->addFnAttr("enqueued-block"); 11394 auto IP = CGF.Builder.saveIP(); 11395 auto *BB = llvm::BasicBlock::Create(C, "entry", F); 11396 Builder.SetInsertPoint(BB); 11397 const auto BlockAlign = CGF.CGM.getDataLayout().getPrefTypeAlign(BlockTy); 11398 auto *BlockPtr = Builder.CreateAlloca(BlockTy, nullptr); 11399 BlockPtr->setAlignment(BlockAlign); 11400 Builder.CreateAlignedStore(F->arg_begin(), BlockPtr, BlockAlign); 11401 auto *Cast = Builder.CreatePointerCast(BlockPtr, InvokeFT->getParamType(0)); 11402 llvm::SmallVector<llvm::Value *, 2> Args; 11403 Args.push_back(Cast); 11404 for (auto I = F->arg_begin() + 1, E = F->arg_end(); I != E; ++I) 11405 Args.push_back(I); 11406 llvm::CallInst *call = Builder.CreateCall(Invoke, Args); 11407 call->setCallingConv(Invoke->getCallingConv()); 11408 Builder.CreateRetVoid(); 11409 Builder.restoreIP(IP); 11410 11411 F->setMetadata("kernel_arg_addr_space", llvm::MDNode::get(C, AddressQuals)); 11412 F->setMetadata("kernel_arg_access_qual", llvm::MDNode::get(C, AccessQuals)); 11413 F->setMetadata("kernel_arg_type", llvm::MDNode::get(C, ArgTypeNames)); 11414 F->setMetadata("kernel_arg_base_type", 11415 llvm::MDNode::get(C, ArgBaseTypeNames)); 11416 F->setMetadata("kernel_arg_type_qual", llvm::MDNode::get(C, ArgTypeQuals)); 11417 if (CGF.CGM.getCodeGenOpts().EmitOpenCLArgMetadata) 11418 F->setMetadata("kernel_arg_name", llvm::MDNode::get(C, ArgNames)); 11419 11420 return F; 11421 } 11422