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/Builtins.h" 23 #include "clang/Basic/CodeGenOptions.h" 24 #include "clang/Basic/DiagnosticFrontend.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/MathExtras.h" 37 #include "llvm/Support/raw_ostream.h" 38 #include <algorithm> // std::sort 39 40 using namespace clang; 41 using namespace CodeGen; 42 43 // Helper for coercing an aggregate argument or return value into an integer 44 // array of the same size (including padding) and alignment. This alternate 45 // coercion happens only for the RenderScript ABI and can be removed after 46 // runtimes that rely on it are no longer supported. 47 // 48 // RenderScript assumes that the size of the argument / return value in the IR 49 // is the same as the size of the corresponding qualified type. This helper 50 // coerces the aggregate type into an array of the same size (including 51 // padding). This coercion is used in lieu of expansion of struct members or 52 // other canonical coercions that return a coerced-type of larger size. 53 // 54 // Ty - The argument / return value type 55 // Context - The associated ASTContext 56 // LLVMContext - The associated LLVMContext 57 static ABIArgInfo coerceToIntArray(QualType Ty, 58 ASTContext &Context, 59 llvm::LLVMContext &LLVMContext) { 60 // Alignment and Size are measured in bits. 61 const uint64_t Size = Context.getTypeSize(Ty); 62 const uint64_t Alignment = Context.getTypeAlign(Ty); 63 llvm::Type *IntType = llvm::Type::getIntNTy(LLVMContext, Alignment); 64 const uint64_t NumElements = (Size + Alignment - 1) / Alignment; 65 return ABIArgInfo::getDirect(llvm::ArrayType::get(IntType, NumElements)); 66 } 67 68 static void AssignToArrayRange(CodeGen::CGBuilderTy &Builder, 69 llvm::Value *Array, 70 llvm::Value *Value, 71 unsigned FirstIndex, 72 unsigned LastIndex) { 73 // Alternatively, we could emit this as a loop in the source. 74 for (unsigned I = FirstIndex; I <= LastIndex; ++I) { 75 llvm::Value *Cell = 76 Builder.CreateConstInBoundsGEP1_32(Builder.getInt8Ty(), Array, I); 77 Builder.CreateAlignedStore(Value, Cell, CharUnits::One()); 78 } 79 } 80 81 static bool isAggregateTypeForABI(QualType T) { 82 return !CodeGenFunction::hasScalarEvaluationKind(T) || 83 T->isMemberFunctionPointerType(); 84 } 85 86 ABIArgInfo ABIInfo::getNaturalAlignIndirect(QualType Ty, bool ByVal, 87 bool Realign, 88 llvm::Type *Padding) const { 89 return ABIArgInfo::getIndirect(getContext().getTypeAlignInChars(Ty), ByVal, 90 Realign, Padding); 91 } 92 93 ABIArgInfo 94 ABIInfo::getNaturalAlignIndirectInReg(QualType Ty, bool Realign) const { 95 return ABIArgInfo::getIndirectInReg(getContext().getTypeAlignInChars(Ty), 96 /*ByVal*/ false, Realign); 97 } 98 99 Address ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr, 100 QualType Ty) const { 101 return Address::invalid(); 102 } 103 104 bool ABIInfo::isPromotableIntegerTypeForABI(QualType Ty) const { 105 if (Ty->isPromotableIntegerType()) 106 return true; 107 108 if (const auto *EIT = Ty->getAs<BitIntType>()) 109 if (EIT->getNumBits() < getContext().getTypeSize(getContext().IntTy)) 110 return true; 111 112 return false; 113 } 114 115 ABIInfo::~ABIInfo() {} 116 117 /// Does the given lowering require more than the given number of 118 /// registers when expanded? 119 /// 120 /// This is intended to be the basis of a reasonable basic implementation 121 /// of should{Pass,Return}IndirectlyForSwift. 122 /// 123 /// For most targets, a limit of four total registers is reasonable; this 124 /// limits the amount of code required in order to move around the value 125 /// in case it wasn't produced immediately prior to the call by the caller 126 /// (or wasn't produced in exactly the right registers) or isn't used 127 /// immediately within the callee. But some targets may need to further 128 /// limit the register count due to an inability to support that many 129 /// return registers. 130 static bool occupiesMoreThan(CodeGenTypes &cgt, 131 ArrayRef<llvm::Type*> scalarTypes, 132 unsigned maxAllRegisters) { 133 unsigned intCount = 0, fpCount = 0; 134 for (llvm::Type *type : scalarTypes) { 135 if (type->isPointerTy()) { 136 intCount++; 137 } else if (auto intTy = dyn_cast<llvm::IntegerType>(type)) { 138 auto ptrWidth = cgt.getTarget().getPointerWidth(0); 139 intCount += (intTy->getBitWidth() + ptrWidth - 1) / ptrWidth; 140 } else { 141 assert(type->isVectorTy() || type->isFloatingPointTy()); 142 fpCount++; 143 } 144 } 145 146 return (intCount + fpCount > maxAllRegisters); 147 } 148 149 bool SwiftABIInfo::isLegalVectorTypeForSwift(CharUnits vectorSize, 150 llvm::Type *eltTy, 151 unsigned numElts) const { 152 // The default implementation of this assumes that the target guarantees 153 // 128-bit SIMD support but nothing more. 154 return (vectorSize.getQuantity() > 8 && vectorSize.getQuantity() <= 16); 155 } 156 157 static CGCXXABI::RecordArgABI getRecordArgABI(const RecordType *RT, 158 CGCXXABI &CXXABI) { 159 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 160 if (!RD) { 161 if (!RT->getDecl()->canPassInRegisters()) 162 return CGCXXABI::RAA_Indirect; 163 return CGCXXABI::RAA_Default; 164 } 165 return CXXABI.getRecordArgABI(RD); 166 } 167 168 static CGCXXABI::RecordArgABI getRecordArgABI(QualType T, 169 CGCXXABI &CXXABI) { 170 const RecordType *RT = T->getAs<RecordType>(); 171 if (!RT) 172 return CGCXXABI::RAA_Default; 173 return getRecordArgABI(RT, CXXABI); 174 } 175 176 static bool classifyReturnType(const CGCXXABI &CXXABI, CGFunctionInfo &FI, 177 const ABIInfo &Info) { 178 QualType Ty = FI.getReturnType(); 179 180 if (const auto *RT = Ty->getAs<RecordType>()) 181 if (!isa<CXXRecordDecl>(RT->getDecl()) && 182 !RT->getDecl()->canPassInRegisters()) { 183 FI.getReturnInfo() = Info.getNaturalAlignIndirect(Ty); 184 return true; 185 } 186 187 return CXXABI.classifyReturnType(FI); 188 } 189 190 /// Pass transparent unions as if they were the type of the first element. Sema 191 /// should ensure that all elements of the union have the same "machine type". 192 static QualType useFirstFieldIfTransparentUnion(QualType Ty) { 193 if (const RecordType *UT = Ty->getAsUnionType()) { 194 const RecordDecl *UD = UT->getDecl(); 195 if (UD->hasAttr<TransparentUnionAttr>()) { 196 assert(!UD->field_empty() && "sema created an empty transparent union"); 197 return UD->field_begin()->getType(); 198 } 199 } 200 return Ty; 201 } 202 203 CGCXXABI &ABIInfo::getCXXABI() const { 204 return CGT.getCXXABI(); 205 } 206 207 ASTContext &ABIInfo::getContext() const { 208 return CGT.getContext(); 209 } 210 211 llvm::LLVMContext &ABIInfo::getVMContext() const { 212 return CGT.getLLVMContext(); 213 } 214 215 const llvm::DataLayout &ABIInfo::getDataLayout() const { 216 return CGT.getDataLayout(); 217 } 218 219 const TargetInfo &ABIInfo::getTarget() const { 220 return CGT.getTarget(); 221 } 222 223 const CodeGenOptions &ABIInfo::getCodeGenOpts() const { 224 return CGT.getCodeGenOpts(); 225 } 226 227 bool ABIInfo::isAndroid() const { return getTarget().getTriple().isAndroid(); } 228 229 bool ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const { 230 return false; 231 } 232 233 bool ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base, 234 uint64_t Members) const { 235 return false; 236 } 237 238 LLVM_DUMP_METHOD void ABIArgInfo::dump() const { 239 raw_ostream &OS = llvm::errs(); 240 OS << "(ABIArgInfo Kind="; 241 switch (TheKind) { 242 case Direct: 243 OS << "Direct Type="; 244 if (llvm::Type *Ty = getCoerceToType()) 245 Ty->print(OS); 246 else 247 OS << "null"; 248 break; 249 case Extend: 250 OS << "Extend"; 251 break; 252 case Ignore: 253 OS << "Ignore"; 254 break; 255 case InAlloca: 256 OS << "InAlloca Offset=" << getInAllocaFieldIndex(); 257 break; 258 case Indirect: 259 OS << "Indirect Align=" << getIndirectAlign().getQuantity() 260 << " ByVal=" << getIndirectByVal() 261 << " Realign=" << getIndirectRealign(); 262 break; 263 case IndirectAliased: 264 OS << "Indirect Align=" << getIndirectAlign().getQuantity() 265 << " AadrSpace=" << getIndirectAddrSpace() 266 << " Realign=" << getIndirectRealign(); 267 break; 268 case Expand: 269 OS << "Expand"; 270 break; 271 case CoerceAndExpand: 272 OS << "CoerceAndExpand Type="; 273 getCoerceAndExpandType()->print(OS); 274 break; 275 } 276 OS << ")\n"; 277 } 278 279 // Dynamically round a pointer up to a multiple of the given alignment. 280 static llvm::Value *emitRoundPointerUpToAlignment(CodeGenFunction &CGF, 281 llvm::Value *Ptr, 282 CharUnits Align) { 283 llvm::Value *PtrAsInt = Ptr; 284 // OverflowArgArea = (OverflowArgArea + Align - 1) & -Align; 285 PtrAsInt = CGF.Builder.CreatePtrToInt(PtrAsInt, CGF.IntPtrTy); 286 PtrAsInt = CGF.Builder.CreateAdd(PtrAsInt, 287 llvm::ConstantInt::get(CGF.IntPtrTy, Align.getQuantity() - 1)); 288 PtrAsInt = CGF.Builder.CreateAnd(PtrAsInt, 289 llvm::ConstantInt::get(CGF.IntPtrTy, -Align.getQuantity())); 290 PtrAsInt = CGF.Builder.CreateIntToPtr(PtrAsInt, 291 Ptr->getType(), 292 Ptr->getName() + ".aligned"); 293 return PtrAsInt; 294 } 295 296 /// Emit va_arg for a platform using the common void* representation, 297 /// where arguments are simply emitted in an array of slots on the stack. 298 /// 299 /// This version implements the core direct-value passing rules. 300 /// 301 /// \param SlotSize - The size and alignment of a stack slot. 302 /// Each argument will be allocated to a multiple of this number of 303 /// slots, and all the slots will be aligned to this value. 304 /// \param AllowHigherAlign - The slot alignment is not a cap; 305 /// an argument type with an alignment greater than the slot size 306 /// will be emitted on a higher-alignment address, potentially 307 /// leaving one or more empty slots behind as padding. If this 308 /// is false, the returned address might be less-aligned than 309 /// DirectAlign. 310 static Address emitVoidPtrDirectVAArg(CodeGenFunction &CGF, 311 Address VAListAddr, 312 llvm::Type *DirectTy, 313 CharUnits DirectSize, 314 CharUnits DirectAlign, 315 CharUnits SlotSize, 316 bool AllowHigherAlign) { 317 // Cast the element type to i8* if necessary. Some platforms define 318 // va_list as a struct containing an i8* instead of just an i8*. 319 if (VAListAddr.getElementType() != CGF.Int8PtrTy) 320 VAListAddr = CGF.Builder.CreateElementBitCast(VAListAddr, CGF.Int8PtrTy); 321 322 llvm::Value *Ptr = CGF.Builder.CreateLoad(VAListAddr, "argp.cur"); 323 324 // If the CC aligns values higher than the slot size, do so if needed. 325 Address Addr = Address::invalid(); 326 if (AllowHigherAlign && DirectAlign > SlotSize) { 327 Addr = Address(emitRoundPointerUpToAlignment(CGF, Ptr, DirectAlign), 328 DirectAlign); 329 } else { 330 Addr = Address(Ptr, SlotSize); 331 } 332 333 // Advance the pointer past the argument, then store that back. 334 CharUnits FullDirectSize = DirectSize.alignTo(SlotSize); 335 Address NextPtr = 336 CGF.Builder.CreateConstInBoundsByteGEP(Addr, FullDirectSize, "argp.next"); 337 CGF.Builder.CreateStore(NextPtr.getPointer(), VAListAddr); 338 339 // If the argument is smaller than a slot, and this is a big-endian 340 // target, the argument will be right-adjusted in its slot. 341 if (DirectSize < SlotSize && CGF.CGM.getDataLayout().isBigEndian() && 342 !DirectTy->isStructTy()) { 343 Addr = CGF.Builder.CreateConstInBoundsByteGEP(Addr, SlotSize - DirectSize); 344 } 345 346 Addr = CGF.Builder.CreateElementBitCast(Addr, DirectTy); 347 return Addr; 348 } 349 350 /// Emit va_arg for a platform using the common void* representation, 351 /// where arguments are simply emitted in an array of slots on the stack. 352 /// 353 /// \param IsIndirect - Values of this type are passed indirectly. 354 /// \param ValueInfo - The size and alignment of this type, generally 355 /// computed with getContext().getTypeInfoInChars(ValueTy). 356 /// \param SlotSizeAndAlign - The size and alignment of a stack slot. 357 /// Each argument will be allocated to a multiple of this number of 358 /// slots, and all the slots will be aligned to this value. 359 /// \param AllowHigherAlign - The slot alignment is not a cap; 360 /// an argument type with an alignment greater than the slot size 361 /// will be emitted on a higher-alignment address, potentially 362 /// leaving one or more empty slots behind as padding. 363 static Address emitVoidPtrVAArg(CodeGenFunction &CGF, Address VAListAddr, 364 QualType ValueTy, bool IsIndirect, 365 TypeInfoChars ValueInfo, 366 CharUnits SlotSizeAndAlign, 367 bool AllowHigherAlign) { 368 // The size and alignment of the value that was passed directly. 369 CharUnits DirectSize, DirectAlign; 370 if (IsIndirect) { 371 DirectSize = CGF.getPointerSize(); 372 DirectAlign = CGF.getPointerAlign(); 373 } else { 374 DirectSize = ValueInfo.Width; 375 DirectAlign = ValueInfo.Align; 376 } 377 378 // Cast the address we've calculated to the right type. 379 llvm::Type *DirectTy = CGF.ConvertTypeForMem(ValueTy); 380 if (IsIndirect) 381 DirectTy = DirectTy->getPointerTo(0); 382 383 Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, DirectTy, 384 DirectSize, DirectAlign, 385 SlotSizeAndAlign, 386 AllowHigherAlign); 387 388 if (IsIndirect) { 389 Addr = Address(CGF.Builder.CreateLoad(Addr), ValueInfo.Align); 390 } 391 392 return Addr; 393 394 } 395 396 static Address complexTempStructure(CodeGenFunction &CGF, Address VAListAddr, 397 QualType Ty, CharUnits SlotSize, 398 CharUnits EltSize, const ComplexType *CTy) { 399 Address Addr = 400 emitVoidPtrDirectVAArg(CGF, VAListAddr, CGF.Int8Ty, SlotSize * 2, 401 SlotSize, SlotSize, /*AllowHigher*/ true); 402 403 Address RealAddr = Addr; 404 Address ImagAddr = RealAddr; 405 if (CGF.CGM.getDataLayout().isBigEndian()) { 406 RealAddr = 407 CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, SlotSize - EltSize); 408 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(ImagAddr, 409 2 * SlotSize - EltSize); 410 } else { 411 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, SlotSize); 412 } 413 414 llvm::Type *EltTy = CGF.ConvertTypeForMem(CTy->getElementType()); 415 RealAddr = CGF.Builder.CreateElementBitCast(RealAddr, EltTy); 416 ImagAddr = CGF.Builder.CreateElementBitCast(ImagAddr, EltTy); 417 llvm::Value *Real = CGF.Builder.CreateLoad(RealAddr, ".vareal"); 418 llvm::Value *Imag = CGF.Builder.CreateLoad(ImagAddr, ".vaimag"); 419 420 Address Temp = CGF.CreateMemTemp(Ty, "vacplx"); 421 CGF.EmitStoreOfComplex({Real, Imag}, CGF.MakeAddrLValue(Temp, Ty), 422 /*init*/ true); 423 return Temp; 424 } 425 426 static Address emitMergePHI(CodeGenFunction &CGF, 427 Address Addr1, llvm::BasicBlock *Block1, 428 Address Addr2, llvm::BasicBlock *Block2, 429 const llvm::Twine &Name = "") { 430 assert(Addr1.getType() == Addr2.getType()); 431 llvm::PHINode *PHI = CGF.Builder.CreatePHI(Addr1.getType(), 2, Name); 432 PHI->addIncoming(Addr1.getPointer(), Block1); 433 PHI->addIncoming(Addr2.getPointer(), Block2); 434 CharUnits Align = std::min(Addr1.getAlignment(), Addr2.getAlignment()); 435 return Address(PHI, Addr1.getElementType(), Align); 436 } 437 438 TargetCodeGenInfo::~TargetCodeGenInfo() = default; 439 440 // If someone can figure out a general rule for this, that would be great. 441 // It's probably just doomed to be platform-dependent, though. 442 unsigned TargetCodeGenInfo::getSizeOfUnwindException() const { 443 // Verified for: 444 // x86-64 FreeBSD, Linux, Darwin 445 // x86-32 FreeBSD, Linux, Darwin 446 // PowerPC Linux, Darwin 447 // ARM Darwin (*not* EABI) 448 // AArch64 Linux 449 return 32; 450 } 451 452 bool TargetCodeGenInfo::isNoProtoCallVariadic(const CallArgList &args, 453 const FunctionNoProtoType *fnType) const { 454 // The following conventions are known to require this to be false: 455 // x86_stdcall 456 // MIPS 457 // For everything else, we just prefer false unless we opt out. 458 return false; 459 } 460 461 void 462 TargetCodeGenInfo::getDependentLibraryOption(llvm::StringRef Lib, 463 llvm::SmallString<24> &Opt) const { 464 // This assumes the user is passing a library name like "rt" instead of a 465 // filename like "librt.a/so", and that they don't care whether it's static or 466 // dynamic. 467 Opt = "-l"; 468 Opt += Lib; 469 } 470 471 unsigned TargetCodeGenInfo::getOpenCLKernelCallingConv() const { 472 // OpenCL kernels are called via an explicit runtime API with arguments 473 // set with clSetKernelArg(), not as normal sub-functions. 474 // Return SPIR_KERNEL by default as the kernel calling convention to 475 // ensure the fingerprint is fixed such way that each OpenCL argument 476 // gets one matching argument in the produced kernel function argument 477 // list to enable feasible implementation of clSetKernelArg() with 478 // aggregates etc. In case we would use the default C calling conv here, 479 // clSetKernelArg() might break depending on the target-specific 480 // conventions; different targets might split structs passed as values 481 // to multiple function arguments etc. 482 return llvm::CallingConv::SPIR_KERNEL; 483 } 484 485 llvm::Constant *TargetCodeGenInfo::getNullPointer(const CodeGen::CodeGenModule &CGM, 486 llvm::PointerType *T, QualType QT) const { 487 return llvm::ConstantPointerNull::get(T); 488 } 489 490 LangAS TargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM, 491 const VarDecl *D) const { 492 assert(!CGM.getLangOpts().OpenCL && 493 !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) && 494 "Address space agnostic languages only"); 495 return D ? D->getType().getAddressSpace() : LangAS::Default; 496 } 497 498 llvm::Value *TargetCodeGenInfo::performAddrSpaceCast( 499 CodeGen::CodeGenFunction &CGF, llvm::Value *Src, LangAS SrcAddr, 500 LangAS DestAddr, llvm::Type *DestTy, bool isNonNull) const { 501 // Since target may map different address spaces in AST to the same address 502 // space, an address space conversion may end up as a bitcast. 503 if (auto *C = dyn_cast<llvm::Constant>(Src)) 504 return performAddrSpaceCast(CGF.CGM, C, SrcAddr, DestAddr, DestTy); 505 // Try to preserve the source's name to make IR more readable. 506 return CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( 507 Src, DestTy, Src->hasName() ? Src->getName() + ".ascast" : ""); 508 } 509 510 llvm::Constant * 511 TargetCodeGenInfo::performAddrSpaceCast(CodeGenModule &CGM, llvm::Constant *Src, 512 LangAS SrcAddr, LangAS DestAddr, 513 llvm::Type *DestTy) const { 514 // Since target may map different address spaces in AST to the same address 515 // space, an address space conversion may end up as a bitcast. 516 return llvm::ConstantExpr::getPointerCast(Src, DestTy); 517 } 518 519 llvm::SyncScope::ID 520 TargetCodeGenInfo::getLLVMSyncScopeID(const LangOptions &LangOpts, 521 SyncScope Scope, 522 llvm::AtomicOrdering Ordering, 523 llvm::LLVMContext &Ctx) const { 524 return Ctx.getOrInsertSyncScopeID(""); /* default sync scope */ 525 } 526 527 static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays); 528 529 /// isEmptyField - Return true iff a the field is "empty", that is it 530 /// is an unnamed bit-field or an (array of) empty record(s). 531 static bool isEmptyField(ASTContext &Context, const FieldDecl *FD, 532 bool AllowArrays) { 533 if (FD->isUnnamedBitfield()) 534 return true; 535 536 QualType FT = FD->getType(); 537 538 // Constant arrays of empty records count as empty, strip them off. 539 // Constant arrays of zero length always count as empty. 540 bool WasArray = false; 541 if (AllowArrays) 542 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) { 543 if (AT->getSize() == 0) 544 return true; 545 FT = AT->getElementType(); 546 // The [[no_unique_address]] special case below does not apply to 547 // arrays of C++ empty records, so we need to remember this fact. 548 WasArray = true; 549 } 550 551 const RecordType *RT = FT->getAs<RecordType>(); 552 if (!RT) 553 return false; 554 555 // C++ record fields are never empty, at least in the Itanium ABI. 556 // 557 // FIXME: We should use a predicate for whether this behavior is true in the 558 // current ABI. 559 // 560 // The exception to the above rule are fields marked with the 561 // [[no_unique_address]] attribute (since C++20). Those do count as empty 562 // according to the Itanium ABI. The exception applies only to records, 563 // not arrays of records, so we must also check whether we stripped off an 564 // array type above. 565 if (isa<CXXRecordDecl>(RT->getDecl()) && 566 (WasArray || !FD->hasAttr<NoUniqueAddressAttr>())) 567 return false; 568 569 return isEmptyRecord(Context, FT, AllowArrays); 570 } 571 572 /// isEmptyRecord - Return true iff a structure contains only empty 573 /// fields. Note that a structure with a flexible array member is not 574 /// considered empty. 575 static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) { 576 const RecordType *RT = T->getAs<RecordType>(); 577 if (!RT) 578 return false; 579 const RecordDecl *RD = RT->getDecl(); 580 if (RD->hasFlexibleArrayMember()) 581 return false; 582 583 // If this is a C++ record, check the bases first. 584 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 585 for (const auto &I : CXXRD->bases()) 586 if (!isEmptyRecord(Context, I.getType(), true)) 587 return false; 588 589 for (const auto *I : RD->fields()) 590 if (!isEmptyField(Context, I, AllowArrays)) 591 return false; 592 return true; 593 } 594 595 /// isSingleElementStruct - Determine if a structure is a "single 596 /// element struct", i.e. it has exactly one non-empty field or 597 /// exactly one field which is itself a single element 598 /// struct. Structures with flexible array members are never 599 /// considered single element structs. 600 /// 601 /// \return The field declaration for the single non-empty field, if 602 /// it exists. 603 static const Type *isSingleElementStruct(QualType T, ASTContext &Context) { 604 const RecordType *RT = T->getAs<RecordType>(); 605 if (!RT) 606 return nullptr; 607 608 const RecordDecl *RD = RT->getDecl(); 609 if (RD->hasFlexibleArrayMember()) 610 return nullptr; 611 612 const Type *Found = nullptr; 613 614 // If this is a C++ record, check the bases first. 615 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 616 for (const auto &I : CXXRD->bases()) { 617 // Ignore empty records. 618 if (isEmptyRecord(Context, I.getType(), true)) 619 continue; 620 621 // If we already found an element then this isn't a single-element struct. 622 if (Found) 623 return nullptr; 624 625 // If this is non-empty and not a single element struct, the composite 626 // cannot be a single element struct. 627 Found = isSingleElementStruct(I.getType(), Context); 628 if (!Found) 629 return nullptr; 630 } 631 } 632 633 // Check for single element. 634 for (const auto *FD : RD->fields()) { 635 QualType FT = FD->getType(); 636 637 // Ignore empty fields. 638 if (isEmptyField(Context, FD, true)) 639 continue; 640 641 // If we already found an element then this isn't a single-element 642 // struct. 643 if (Found) 644 return nullptr; 645 646 // Treat single element arrays as the element. 647 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) { 648 if (AT->getSize().getZExtValue() != 1) 649 break; 650 FT = AT->getElementType(); 651 } 652 653 if (!isAggregateTypeForABI(FT)) { 654 Found = FT.getTypePtr(); 655 } else { 656 Found = isSingleElementStruct(FT, Context); 657 if (!Found) 658 return nullptr; 659 } 660 } 661 662 // We don't consider a struct a single-element struct if it has 663 // padding beyond the element type. 664 if (Found && Context.getTypeSize(Found) != Context.getTypeSize(T)) 665 return nullptr; 666 667 return Found; 668 } 669 670 namespace { 671 Address EmitVAArgInstr(CodeGenFunction &CGF, Address VAListAddr, QualType Ty, 672 const ABIArgInfo &AI) { 673 // This default implementation defers to the llvm backend's va_arg 674 // instruction. It can handle only passing arguments directly 675 // (typically only handled in the backend for primitive types), or 676 // aggregates passed indirectly by pointer (NOTE: if the "byval" 677 // flag has ABI impact in the callee, this implementation cannot 678 // work.) 679 680 // Only a few cases are covered here at the moment -- those needed 681 // by the default abi. 682 llvm::Value *Val; 683 684 if (AI.isIndirect()) { 685 assert(!AI.getPaddingType() && 686 "Unexpected PaddingType seen in arginfo in generic VAArg emitter!"); 687 assert( 688 !AI.getIndirectRealign() && 689 "Unexpected IndirectRealign seen in arginfo in generic VAArg emitter!"); 690 691 auto TyInfo = CGF.getContext().getTypeInfoInChars(Ty); 692 CharUnits TyAlignForABI = TyInfo.Align; 693 694 llvm::Type *BaseTy = 695 llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty)); 696 llvm::Value *Addr = 697 CGF.Builder.CreateVAArg(VAListAddr.getPointer(), BaseTy); 698 return Address(Addr, TyAlignForABI); 699 } else { 700 assert((AI.isDirect() || AI.isExtend()) && 701 "Unexpected ArgInfo Kind in generic VAArg emitter!"); 702 703 assert(!AI.getInReg() && 704 "Unexpected InReg seen in arginfo in generic VAArg emitter!"); 705 assert(!AI.getPaddingType() && 706 "Unexpected PaddingType seen in arginfo in generic VAArg emitter!"); 707 assert(!AI.getDirectOffset() && 708 "Unexpected DirectOffset seen in arginfo in generic VAArg emitter!"); 709 assert(!AI.getCoerceToType() && 710 "Unexpected CoerceToType seen in arginfo in generic VAArg emitter!"); 711 712 Address Temp = CGF.CreateMemTemp(Ty, "varet"); 713 Val = CGF.Builder.CreateVAArg(VAListAddr.getPointer(), CGF.ConvertType(Ty)); 714 CGF.Builder.CreateStore(Val, Temp); 715 return Temp; 716 } 717 } 718 719 /// DefaultABIInfo - The default implementation for ABI specific 720 /// details. This implementation provides information which results in 721 /// self-consistent and sensible LLVM IR generation, but does not 722 /// conform to any particular ABI. 723 class DefaultABIInfo : public ABIInfo { 724 public: 725 DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {} 726 727 ABIArgInfo classifyReturnType(QualType RetTy) const; 728 ABIArgInfo classifyArgumentType(QualType RetTy) const; 729 730 void computeInfo(CGFunctionInfo &FI) const override { 731 if (!getCXXABI().classifyReturnType(FI)) 732 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 733 for (auto &I : FI.arguments()) 734 I.info = classifyArgumentType(I.type); 735 } 736 737 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 738 QualType Ty) const override { 739 return EmitVAArgInstr(CGF, VAListAddr, Ty, classifyArgumentType(Ty)); 740 } 741 }; 742 743 class DefaultTargetCodeGenInfo : public TargetCodeGenInfo { 744 public: 745 DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT) 746 : TargetCodeGenInfo(std::make_unique<DefaultABIInfo>(CGT)) {} 747 }; 748 749 ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const { 750 Ty = useFirstFieldIfTransparentUnion(Ty); 751 752 if (isAggregateTypeForABI(Ty)) { 753 // Records with non-trivial destructors/copy-constructors should not be 754 // passed by value. 755 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 756 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 757 758 return getNaturalAlignIndirect(Ty); 759 } 760 761 // Treat an enum type as its underlying type. 762 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 763 Ty = EnumTy->getDecl()->getIntegerType(); 764 765 ASTContext &Context = getContext(); 766 if (const auto *EIT = Ty->getAs<BitIntType>()) 767 if (EIT->getNumBits() > 768 Context.getTypeSize(Context.getTargetInfo().hasInt128Type() 769 ? Context.Int128Ty 770 : Context.LongLongTy)) 771 return getNaturalAlignIndirect(Ty); 772 773 return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty) 774 : ABIArgInfo::getDirect()); 775 } 776 777 ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const { 778 if (RetTy->isVoidType()) 779 return ABIArgInfo::getIgnore(); 780 781 if (isAggregateTypeForABI(RetTy)) 782 return getNaturalAlignIndirect(RetTy); 783 784 // Treat an enum type as its underlying type. 785 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 786 RetTy = EnumTy->getDecl()->getIntegerType(); 787 788 if (const auto *EIT = RetTy->getAs<BitIntType>()) 789 if (EIT->getNumBits() > 790 getContext().getTypeSize(getContext().getTargetInfo().hasInt128Type() 791 ? getContext().Int128Ty 792 : getContext().LongLongTy)) 793 return getNaturalAlignIndirect(RetTy); 794 795 return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy) 796 : ABIArgInfo::getDirect()); 797 } 798 799 //===----------------------------------------------------------------------===// 800 // WebAssembly ABI Implementation 801 // 802 // This is a very simple ABI that relies a lot on DefaultABIInfo. 803 //===----------------------------------------------------------------------===// 804 805 class WebAssemblyABIInfo final : public SwiftABIInfo { 806 public: 807 enum ABIKind { 808 MVP = 0, 809 ExperimentalMV = 1, 810 }; 811 812 private: 813 DefaultABIInfo defaultInfo; 814 ABIKind Kind; 815 816 public: 817 explicit WebAssemblyABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind) 818 : SwiftABIInfo(CGT), defaultInfo(CGT), Kind(Kind) {} 819 820 private: 821 ABIArgInfo classifyReturnType(QualType RetTy) const; 822 ABIArgInfo classifyArgumentType(QualType Ty) const; 823 824 // DefaultABIInfo's classifyReturnType and classifyArgumentType are 825 // non-virtual, but computeInfo and EmitVAArg are virtual, so we 826 // overload them. 827 void computeInfo(CGFunctionInfo &FI) const override { 828 if (!getCXXABI().classifyReturnType(FI)) 829 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 830 for (auto &Arg : FI.arguments()) 831 Arg.info = classifyArgumentType(Arg.type); 832 } 833 834 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 835 QualType Ty) const override; 836 837 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars, 838 bool asReturnValue) const override { 839 return occupiesMoreThan(CGT, scalars, /*total*/ 4); 840 } 841 842 bool isSwiftErrorInRegister() const override { 843 return false; 844 } 845 }; 846 847 class WebAssemblyTargetCodeGenInfo final : public TargetCodeGenInfo { 848 public: 849 explicit WebAssemblyTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, 850 WebAssemblyABIInfo::ABIKind K) 851 : TargetCodeGenInfo(std::make_unique<WebAssemblyABIInfo>(CGT, K)) {} 852 853 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 854 CodeGen::CodeGenModule &CGM) const override { 855 TargetCodeGenInfo::setTargetAttributes(D, GV, CGM); 856 if (const auto *FD = dyn_cast_or_null<FunctionDecl>(D)) { 857 if (const auto *Attr = FD->getAttr<WebAssemblyImportModuleAttr>()) { 858 llvm::Function *Fn = cast<llvm::Function>(GV); 859 llvm::AttrBuilder B(GV->getContext()); 860 B.addAttribute("wasm-import-module", Attr->getImportModule()); 861 Fn->addFnAttrs(B); 862 } 863 if (const auto *Attr = FD->getAttr<WebAssemblyImportNameAttr>()) { 864 llvm::Function *Fn = cast<llvm::Function>(GV); 865 llvm::AttrBuilder B(GV->getContext()); 866 B.addAttribute("wasm-import-name", Attr->getImportName()); 867 Fn->addFnAttrs(B); 868 } 869 if (const auto *Attr = FD->getAttr<WebAssemblyExportNameAttr>()) { 870 llvm::Function *Fn = cast<llvm::Function>(GV); 871 llvm::AttrBuilder B(GV->getContext()); 872 B.addAttribute("wasm-export-name", Attr->getExportName()); 873 Fn->addFnAttrs(B); 874 } 875 } 876 877 if (auto *FD = dyn_cast_or_null<FunctionDecl>(D)) { 878 llvm::Function *Fn = cast<llvm::Function>(GV); 879 if (!FD->doesThisDeclarationHaveABody() && !FD->hasPrototype()) 880 Fn->addFnAttr("no-prototype"); 881 } 882 } 883 }; 884 885 /// Classify argument of given type \p Ty. 886 ABIArgInfo WebAssemblyABIInfo::classifyArgumentType(QualType Ty) const { 887 Ty = useFirstFieldIfTransparentUnion(Ty); 888 889 if (isAggregateTypeForABI(Ty)) { 890 // Records with non-trivial destructors/copy-constructors should not be 891 // passed by value. 892 if (auto RAA = getRecordArgABI(Ty, getCXXABI())) 893 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 894 // Ignore empty structs/unions. 895 if (isEmptyRecord(getContext(), Ty, true)) 896 return ABIArgInfo::getIgnore(); 897 // Lower single-element structs to just pass a regular value. TODO: We 898 // could do reasonable-size multiple-element structs too, using getExpand(), 899 // though watch out for things like bitfields. 900 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext())) 901 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0))); 902 // For the experimental multivalue ABI, fully expand all other aggregates 903 if (Kind == ABIKind::ExperimentalMV) { 904 const RecordType *RT = Ty->getAs<RecordType>(); 905 assert(RT); 906 bool HasBitField = false; 907 for (auto *Field : RT->getDecl()->fields()) { 908 if (Field->isBitField()) { 909 HasBitField = true; 910 break; 911 } 912 } 913 if (!HasBitField) 914 return ABIArgInfo::getExpand(); 915 } 916 } 917 918 // Otherwise just do the default thing. 919 return defaultInfo.classifyArgumentType(Ty); 920 } 921 922 ABIArgInfo WebAssemblyABIInfo::classifyReturnType(QualType RetTy) const { 923 if (isAggregateTypeForABI(RetTy)) { 924 // Records with non-trivial destructors/copy-constructors should not be 925 // returned by value. 926 if (!getRecordArgABI(RetTy, getCXXABI())) { 927 // Ignore empty structs/unions. 928 if (isEmptyRecord(getContext(), RetTy, true)) 929 return ABIArgInfo::getIgnore(); 930 // Lower single-element structs to just return a regular value. TODO: We 931 // could do reasonable-size multiple-element structs too, using 932 // ABIArgInfo::getDirect(). 933 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext())) 934 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0))); 935 // For the experimental multivalue ABI, return all other aggregates 936 if (Kind == ABIKind::ExperimentalMV) 937 return ABIArgInfo::getDirect(); 938 } 939 } 940 941 // Otherwise just do the default thing. 942 return defaultInfo.classifyReturnType(RetTy); 943 } 944 945 Address WebAssemblyABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 946 QualType Ty) const { 947 bool IsIndirect = isAggregateTypeForABI(Ty) && 948 !isEmptyRecord(getContext(), Ty, true) && 949 !isSingleElementStruct(Ty, getContext()); 950 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, 951 getContext().getTypeInfoInChars(Ty), 952 CharUnits::fromQuantity(4), 953 /*AllowHigherAlign=*/true); 954 } 955 956 //===----------------------------------------------------------------------===// 957 // le32/PNaCl bitcode ABI Implementation 958 // 959 // This is a simplified version of the x86_32 ABI. Arguments and return values 960 // are always passed on the stack. 961 //===----------------------------------------------------------------------===// 962 963 class PNaClABIInfo : public ABIInfo { 964 public: 965 PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {} 966 967 ABIArgInfo classifyReturnType(QualType RetTy) const; 968 ABIArgInfo classifyArgumentType(QualType RetTy) const; 969 970 void computeInfo(CGFunctionInfo &FI) const override; 971 Address EmitVAArg(CodeGenFunction &CGF, 972 Address VAListAddr, QualType Ty) const override; 973 }; 974 975 class PNaClTargetCodeGenInfo : public TargetCodeGenInfo { 976 public: 977 PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT) 978 : TargetCodeGenInfo(std::make_unique<PNaClABIInfo>(CGT)) {} 979 }; 980 981 void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const { 982 if (!getCXXABI().classifyReturnType(FI)) 983 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 984 985 for (auto &I : FI.arguments()) 986 I.info = classifyArgumentType(I.type); 987 } 988 989 Address PNaClABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 990 QualType Ty) const { 991 // The PNaCL ABI is a bit odd, in that varargs don't use normal 992 // function classification. Structs get passed directly for varargs 993 // functions, through a rewriting transform in 994 // pnacl-llvm/lib/Transforms/NaCl/ExpandVarArgs.cpp, which allows 995 // this target to actually support a va_arg instructions with an 996 // aggregate type, unlike other targets. 997 return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect()); 998 } 999 1000 /// Classify argument of given type \p Ty. 1001 ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const { 1002 if (isAggregateTypeForABI(Ty)) { 1003 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 1004 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 1005 return getNaturalAlignIndirect(Ty); 1006 } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) { 1007 // Treat an enum type as its underlying type. 1008 Ty = EnumTy->getDecl()->getIntegerType(); 1009 } else if (Ty->isFloatingType()) { 1010 // Floating-point types don't go inreg. 1011 return ABIArgInfo::getDirect(); 1012 } else if (const auto *EIT = Ty->getAs<BitIntType>()) { 1013 // Treat bit-precise integers as integers if <= 64, otherwise pass 1014 // indirectly. 1015 if (EIT->getNumBits() > 64) 1016 return getNaturalAlignIndirect(Ty); 1017 return ABIArgInfo::getDirect(); 1018 } 1019 1020 return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty) 1021 : ABIArgInfo::getDirect()); 1022 } 1023 1024 ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const { 1025 if (RetTy->isVoidType()) 1026 return ABIArgInfo::getIgnore(); 1027 1028 // In the PNaCl ABI we always return records/structures on the stack. 1029 if (isAggregateTypeForABI(RetTy)) 1030 return getNaturalAlignIndirect(RetTy); 1031 1032 // Treat bit-precise integers as integers if <= 64, otherwise pass indirectly. 1033 if (const auto *EIT = RetTy->getAs<BitIntType>()) { 1034 if (EIT->getNumBits() > 64) 1035 return getNaturalAlignIndirect(RetTy); 1036 return ABIArgInfo::getDirect(); 1037 } 1038 1039 // Treat an enum type as its underlying type. 1040 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 1041 RetTy = EnumTy->getDecl()->getIntegerType(); 1042 1043 return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy) 1044 : ABIArgInfo::getDirect()); 1045 } 1046 1047 /// IsX86_MMXType - Return true if this is an MMX type. 1048 bool IsX86_MMXType(llvm::Type *IRType) { 1049 // Return true if the type is an MMX type <2 x i32>, <4 x i16>, or <8 x i8>. 1050 return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 && 1051 cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() && 1052 IRType->getScalarSizeInBits() != 64; 1053 } 1054 1055 static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF, 1056 StringRef Constraint, 1057 llvm::Type* Ty) { 1058 bool IsMMXCons = llvm::StringSwitch<bool>(Constraint) 1059 .Cases("y", "&y", "^Ym", true) 1060 .Default(false); 1061 if (IsMMXCons && Ty->isVectorTy()) { 1062 if (cast<llvm::VectorType>(Ty)->getPrimitiveSizeInBits().getFixedSize() != 1063 64) { 1064 // Invalid MMX constraint 1065 return nullptr; 1066 } 1067 1068 return llvm::Type::getX86_MMXTy(CGF.getLLVMContext()); 1069 } 1070 1071 // No operation needed 1072 return Ty; 1073 } 1074 1075 /// Returns true if this type can be passed in SSE registers with the 1076 /// X86_VectorCall calling convention. Shared between x86_32 and x86_64. 1077 static bool isX86VectorTypeForVectorCall(ASTContext &Context, QualType Ty) { 1078 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) { 1079 if (BT->isFloatingPoint() && BT->getKind() != BuiltinType::Half) { 1080 if (BT->getKind() == BuiltinType::LongDouble) { 1081 if (&Context.getTargetInfo().getLongDoubleFormat() == 1082 &llvm::APFloat::x87DoubleExtended()) 1083 return false; 1084 } 1085 return true; 1086 } 1087 } else if (const VectorType *VT = Ty->getAs<VectorType>()) { 1088 // vectorcall can pass XMM, YMM, and ZMM vectors. We don't pass SSE1 MMX 1089 // registers specially. 1090 unsigned VecSize = Context.getTypeSize(VT); 1091 if (VecSize == 128 || VecSize == 256 || VecSize == 512) 1092 return true; 1093 } 1094 return false; 1095 } 1096 1097 /// Returns true if this aggregate is small enough to be passed in SSE registers 1098 /// in the X86_VectorCall calling convention. Shared between x86_32 and x86_64. 1099 static bool isX86VectorCallAggregateSmallEnough(uint64_t NumMembers) { 1100 return NumMembers <= 4; 1101 } 1102 1103 /// Returns a Homogeneous Vector Aggregate ABIArgInfo, used in X86. 1104 static ABIArgInfo getDirectX86Hva(llvm::Type* T = nullptr) { 1105 auto AI = ABIArgInfo::getDirect(T); 1106 AI.setInReg(true); 1107 AI.setCanBeFlattened(false); 1108 return AI; 1109 } 1110 1111 //===----------------------------------------------------------------------===// 1112 // X86-32 ABI Implementation 1113 //===----------------------------------------------------------------------===// 1114 1115 /// Similar to llvm::CCState, but for Clang. 1116 struct CCState { 1117 CCState(CGFunctionInfo &FI) 1118 : IsPreassigned(FI.arg_size()), CC(FI.getCallingConvention()) {} 1119 1120 llvm::SmallBitVector IsPreassigned; 1121 unsigned CC = CallingConv::CC_C; 1122 unsigned FreeRegs = 0; 1123 unsigned FreeSSERegs = 0; 1124 }; 1125 1126 /// X86_32ABIInfo - The X86-32 ABI information. 1127 class X86_32ABIInfo : public SwiftABIInfo { 1128 enum Class { 1129 Integer, 1130 Float 1131 }; 1132 1133 static const unsigned MinABIStackAlignInBytes = 4; 1134 1135 bool IsDarwinVectorABI; 1136 bool IsRetSmallStructInRegABI; 1137 bool IsWin32StructABI; 1138 bool IsSoftFloatABI; 1139 bool IsMCUABI; 1140 bool IsLinuxABI; 1141 unsigned DefaultNumRegisterParameters; 1142 1143 static bool isRegisterSize(unsigned Size) { 1144 return (Size == 8 || Size == 16 || Size == 32 || Size == 64); 1145 } 1146 1147 bool isHomogeneousAggregateBaseType(QualType Ty) const override { 1148 // FIXME: Assumes vectorcall is in use. 1149 return isX86VectorTypeForVectorCall(getContext(), Ty); 1150 } 1151 1152 bool isHomogeneousAggregateSmallEnough(const Type *Ty, 1153 uint64_t NumMembers) const override { 1154 // FIXME: Assumes vectorcall is in use. 1155 return isX86VectorCallAggregateSmallEnough(NumMembers); 1156 } 1157 1158 bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context) const; 1159 1160 /// getIndirectResult - Give a source type \arg Ty, return a suitable result 1161 /// such that the argument will be passed in memory. 1162 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const; 1163 1164 ABIArgInfo getIndirectReturnResult(QualType Ty, CCState &State) const; 1165 1166 /// Return the alignment to use for the given type on the stack. 1167 unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const; 1168 1169 Class classify(QualType Ty) const; 1170 ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const; 1171 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const; 1172 1173 /// Updates the number of available free registers, returns 1174 /// true if any registers were allocated. 1175 bool updateFreeRegs(QualType Ty, CCState &State) const; 1176 1177 bool shouldAggregateUseDirect(QualType Ty, CCState &State, bool &InReg, 1178 bool &NeedsPadding) const; 1179 bool shouldPrimitiveUseInReg(QualType Ty, CCState &State) const; 1180 1181 bool canExpandIndirectArgument(QualType Ty) const; 1182 1183 /// Rewrite the function info so that all memory arguments use 1184 /// inalloca. 1185 void rewriteWithInAlloca(CGFunctionInfo &FI) const; 1186 1187 void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields, 1188 CharUnits &StackOffset, ABIArgInfo &Info, 1189 QualType Type) const; 1190 void runVectorCallFirstPass(CGFunctionInfo &FI, CCState &State) const; 1191 1192 public: 1193 1194 void computeInfo(CGFunctionInfo &FI) const override; 1195 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 1196 QualType Ty) const override; 1197 1198 X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI, 1199 bool RetSmallStructInRegABI, bool Win32StructABI, 1200 unsigned NumRegisterParameters, bool SoftFloatABI) 1201 : SwiftABIInfo(CGT), IsDarwinVectorABI(DarwinVectorABI), 1202 IsRetSmallStructInRegABI(RetSmallStructInRegABI), 1203 IsWin32StructABI(Win32StructABI), IsSoftFloatABI(SoftFloatABI), 1204 IsMCUABI(CGT.getTarget().getTriple().isOSIAMCU()), 1205 IsLinuxABI(CGT.getTarget().getTriple().isOSLinux() || 1206 CGT.getTarget().getTriple().isOSCygMing()), 1207 DefaultNumRegisterParameters(NumRegisterParameters) {} 1208 1209 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars, 1210 bool asReturnValue) const override { 1211 // LLVM's x86-32 lowering currently only assigns up to three 1212 // integer registers and three fp registers. Oddly, it'll use up to 1213 // four vector registers for vectors, but those can overlap with the 1214 // scalar registers. 1215 return occupiesMoreThan(CGT, scalars, /*total*/ 3); 1216 } 1217 1218 bool isSwiftErrorInRegister() const override { 1219 // x86-32 lowering does not support passing swifterror in a register. 1220 return false; 1221 } 1222 }; 1223 1224 class X86_32TargetCodeGenInfo : public TargetCodeGenInfo { 1225 public: 1226 X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI, 1227 bool RetSmallStructInRegABI, bool Win32StructABI, 1228 unsigned NumRegisterParameters, bool SoftFloatABI) 1229 : TargetCodeGenInfo(std::make_unique<X86_32ABIInfo>( 1230 CGT, DarwinVectorABI, RetSmallStructInRegABI, Win32StructABI, 1231 NumRegisterParameters, SoftFloatABI)) {} 1232 1233 static bool isStructReturnInRegABI( 1234 const llvm::Triple &Triple, const CodeGenOptions &Opts); 1235 1236 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 1237 CodeGen::CodeGenModule &CGM) const override; 1238 1239 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override { 1240 // Darwin uses different dwarf register numbers for EH. 1241 if (CGM.getTarget().getTriple().isOSDarwin()) return 5; 1242 return 4; 1243 } 1244 1245 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 1246 llvm::Value *Address) const override; 1247 1248 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF, 1249 StringRef Constraint, 1250 llvm::Type* Ty) const override { 1251 return X86AdjustInlineAsmType(CGF, Constraint, Ty); 1252 } 1253 1254 void addReturnRegisterOutputs(CodeGenFunction &CGF, LValue ReturnValue, 1255 std::string &Constraints, 1256 std::vector<llvm::Type *> &ResultRegTypes, 1257 std::vector<llvm::Type *> &ResultTruncRegTypes, 1258 std::vector<LValue> &ResultRegDests, 1259 std::string &AsmString, 1260 unsigned NumOutputs) const override; 1261 1262 llvm::Constant * 1263 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override { 1264 unsigned Sig = (0xeb << 0) | // jmp rel8 1265 (0x06 << 8) | // .+0x08 1266 ('v' << 16) | 1267 ('2' << 24); 1268 return llvm::ConstantInt::get(CGM.Int32Ty, Sig); 1269 } 1270 1271 StringRef getARCRetainAutoreleasedReturnValueMarker() const override { 1272 return "movl\t%ebp, %ebp" 1273 "\t\t// marker for objc_retainAutoreleaseReturnValue"; 1274 } 1275 }; 1276 1277 } 1278 1279 /// Rewrite input constraint references after adding some output constraints. 1280 /// In the case where there is one output and one input and we add one output, 1281 /// we need to replace all operand references greater than or equal to 1: 1282 /// mov $0, $1 1283 /// mov eax, $1 1284 /// The result will be: 1285 /// mov $0, $2 1286 /// mov eax, $2 1287 static void rewriteInputConstraintReferences(unsigned FirstIn, 1288 unsigned NumNewOuts, 1289 std::string &AsmString) { 1290 std::string Buf; 1291 llvm::raw_string_ostream OS(Buf); 1292 size_t Pos = 0; 1293 while (Pos < AsmString.size()) { 1294 size_t DollarStart = AsmString.find('$', Pos); 1295 if (DollarStart == std::string::npos) 1296 DollarStart = AsmString.size(); 1297 size_t DollarEnd = AsmString.find_first_not_of('$', DollarStart); 1298 if (DollarEnd == std::string::npos) 1299 DollarEnd = AsmString.size(); 1300 OS << StringRef(&AsmString[Pos], DollarEnd - Pos); 1301 Pos = DollarEnd; 1302 size_t NumDollars = DollarEnd - DollarStart; 1303 if (NumDollars % 2 != 0 && Pos < AsmString.size()) { 1304 // We have an operand reference. 1305 size_t DigitStart = Pos; 1306 if (AsmString[DigitStart] == '{') { 1307 OS << '{'; 1308 ++DigitStart; 1309 } 1310 size_t DigitEnd = AsmString.find_first_not_of("0123456789", DigitStart); 1311 if (DigitEnd == std::string::npos) 1312 DigitEnd = AsmString.size(); 1313 StringRef OperandStr(&AsmString[DigitStart], DigitEnd - DigitStart); 1314 unsigned OperandIndex; 1315 if (!OperandStr.getAsInteger(10, OperandIndex)) { 1316 if (OperandIndex >= FirstIn) 1317 OperandIndex += NumNewOuts; 1318 OS << OperandIndex; 1319 } else { 1320 OS << OperandStr; 1321 } 1322 Pos = DigitEnd; 1323 } 1324 } 1325 AsmString = std::move(OS.str()); 1326 } 1327 1328 /// Add output constraints for EAX:EDX because they are return registers. 1329 void X86_32TargetCodeGenInfo::addReturnRegisterOutputs( 1330 CodeGenFunction &CGF, LValue ReturnSlot, std::string &Constraints, 1331 std::vector<llvm::Type *> &ResultRegTypes, 1332 std::vector<llvm::Type *> &ResultTruncRegTypes, 1333 std::vector<LValue> &ResultRegDests, std::string &AsmString, 1334 unsigned NumOutputs) const { 1335 uint64_t RetWidth = CGF.getContext().getTypeSize(ReturnSlot.getType()); 1336 1337 // Use the EAX constraint if the width is 32 or smaller and EAX:EDX if it is 1338 // larger. 1339 if (!Constraints.empty()) 1340 Constraints += ','; 1341 if (RetWidth <= 32) { 1342 Constraints += "={eax}"; 1343 ResultRegTypes.push_back(CGF.Int32Ty); 1344 } else { 1345 // Use the 'A' constraint for EAX:EDX. 1346 Constraints += "=A"; 1347 ResultRegTypes.push_back(CGF.Int64Ty); 1348 } 1349 1350 // Truncate EAX or EAX:EDX to an integer of the appropriate size. 1351 llvm::Type *CoerceTy = llvm::IntegerType::get(CGF.getLLVMContext(), RetWidth); 1352 ResultTruncRegTypes.push_back(CoerceTy); 1353 1354 // Coerce the integer by bitcasting the return slot pointer. 1355 ReturnSlot.setAddress(CGF.Builder.CreateBitCast(ReturnSlot.getAddress(CGF), 1356 CoerceTy->getPointerTo())); 1357 ResultRegDests.push_back(ReturnSlot); 1358 1359 rewriteInputConstraintReferences(NumOutputs, 1, AsmString); 1360 } 1361 1362 /// shouldReturnTypeInRegister - Determine if the given type should be 1363 /// returned in a register (for the Darwin and MCU ABI). 1364 bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty, 1365 ASTContext &Context) const { 1366 uint64_t Size = Context.getTypeSize(Ty); 1367 1368 // For i386, type must be register sized. 1369 // For the MCU ABI, it only needs to be <= 8-byte 1370 if ((IsMCUABI && Size > 64) || (!IsMCUABI && !isRegisterSize(Size))) 1371 return false; 1372 1373 if (Ty->isVectorType()) { 1374 // 64- and 128- bit vectors inside structures are not returned in 1375 // registers. 1376 if (Size == 64 || Size == 128) 1377 return false; 1378 1379 return true; 1380 } 1381 1382 // If this is a builtin, pointer, enum, complex type, member pointer, or 1383 // member function pointer it is ok. 1384 if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() || 1385 Ty->isAnyComplexType() || Ty->isEnumeralType() || 1386 Ty->isBlockPointerType() || Ty->isMemberPointerType()) 1387 return true; 1388 1389 // Arrays are treated like records. 1390 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) 1391 return shouldReturnTypeInRegister(AT->getElementType(), Context); 1392 1393 // Otherwise, it must be a record type. 1394 const RecordType *RT = Ty->getAs<RecordType>(); 1395 if (!RT) return false; 1396 1397 // FIXME: Traverse bases here too. 1398 1399 // Structure types are passed in register if all fields would be 1400 // passed in a register. 1401 for (const auto *FD : RT->getDecl()->fields()) { 1402 // Empty fields are ignored. 1403 if (isEmptyField(Context, FD, true)) 1404 continue; 1405 1406 // Check fields recursively. 1407 if (!shouldReturnTypeInRegister(FD->getType(), Context)) 1408 return false; 1409 } 1410 return true; 1411 } 1412 1413 static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) { 1414 // Treat complex types as the element type. 1415 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) 1416 Ty = CTy->getElementType(); 1417 1418 // Check for a type which we know has a simple scalar argument-passing 1419 // convention without any padding. (We're specifically looking for 32 1420 // and 64-bit integer and integer-equivalents, float, and double.) 1421 if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() && 1422 !Ty->isEnumeralType() && !Ty->isBlockPointerType()) 1423 return false; 1424 1425 uint64_t Size = Context.getTypeSize(Ty); 1426 return Size == 32 || Size == 64; 1427 } 1428 1429 static bool addFieldSizes(ASTContext &Context, const RecordDecl *RD, 1430 uint64_t &Size) { 1431 for (const auto *FD : RD->fields()) { 1432 // Scalar arguments on the stack get 4 byte alignment on x86. If the 1433 // argument is smaller than 32-bits, expanding the struct will create 1434 // alignment padding. 1435 if (!is32Or64BitBasicType(FD->getType(), Context)) 1436 return false; 1437 1438 // FIXME: Reject bit-fields wholesale; there are two problems, we don't know 1439 // how to expand them yet, and the predicate for telling if a bitfield still 1440 // counts as "basic" is more complicated than what we were doing previously. 1441 if (FD->isBitField()) 1442 return false; 1443 1444 Size += Context.getTypeSize(FD->getType()); 1445 } 1446 return true; 1447 } 1448 1449 static bool addBaseAndFieldSizes(ASTContext &Context, const CXXRecordDecl *RD, 1450 uint64_t &Size) { 1451 // Don't do this if there are any non-empty bases. 1452 for (const CXXBaseSpecifier &Base : RD->bases()) { 1453 if (!addBaseAndFieldSizes(Context, Base.getType()->getAsCXXRecordDecl(), 1454 Size)) 1455 return false; 1456 } 1457 if (!addFieldSizes(Context, RD, Size)) 1458 return false; 1459 return true; 1460 } 1461 1462 /// Test whether an argument type which is to be passed indirectly (on the 1463 /// stack) would have the equivalent layout if it was expanded into separate 1464 /// arguments. If so, we prefer to do the latter to avoid inhibiting 1465 /// optimizations. 1466 bool X86_32ABIInfo::canExpandIndirectArgument(QualType Ty) const { 1467 // We can only expand structure types. 1468 const RecordType *RT = Ty->getAs<RecordType>(); 1469 if (!RT) 1470 return false; 1471 const RecordDecl *RD = RT->getDecl(); 1472 uint64_t Size = 0; 1473 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 1474 if (!IsWin32StructABI) { 1475 // On non-Windows, we have to conservatively match our old bitcode 1476 // prototypes in order to be ABI-compatible at the bitcode level. 1477 if (!CXXRD->isCLike()) 1478 return false; 1479 } else { 1480 // Don't do this for dynamic classes. 1481 if (CXXRD->isDynamicClass()) 1482 return false; 1483 } 1484 if (!addBaseAndFieldSizes(getContext(), CXXRD, Size)) 1485 return false; 1486 } else { 1487 if (!addFieldSizes(getContext(), RD, Size)) 1488 return false; 1489 } 1490 1491 // We can do this if there was no alignment padding. 1492 return Size == getContext().getTypeSize(Ty); 1493 } 1494 1495 ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(QualType RetTy, CCState &State) const { 1496 // If the return value is indirect, then the hidden argument is consuming one 1497 // integer register. 1498 if (State.FreeRegs) { 1499 --State.FreeRegs; 1500 if (!IsMCUABI) 1501 return getNaturalAlignIndirectInReg(RetTy); 1502 } 1503 return getNaturalAlignIndirect(RetTy, /*ByVal=*/false); 1504 } 1505 1506 ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy, 1507 CCState &State) const { 1508 if (RetTy->isVoidType()) 1509 return ABIArgInfo::getIgnore(); 1510 1511 const Type *Base = nullptr; 1512 uint64_t NumElts = 0; 1513 if ((State.CC == llvm::CallingConv::X86_VectorCall || 1514 State.CC == llvm::CallingConv::X86_RegCall) && 1515 isHomogeneousAggregate(RetTy, Base, NumElts)) { 1516 // The LLVM struct type for such an aggregate should lower properly. 1517 return ABIArgInfo::getDirect(); 1518 } 1519 1520 if (const VectorType *VT = RetTy->getAs<VectorType>()) { 1521 // On Darwin, some vectors are returned in registers. 1522 if (IsDarwinVectorABI) { 1523 uint64_t Size = getContext().getTypeSize(RetTy); 1524 1525 // 128-bit vectors are a special case; they are returned in 1526 // registers and we need to make sure to pick a type the LLVM 1527 // backend will like. 1528 if (Size == 128) 1529 return ABIArgInfo::getDirect(llvm::FixedVectorType::get( 1530 llvm::Type::getInt64Ty(getVMContext()), 2)); 1531 1532 // Always return in register if it fits in a general purpose 1533 // register, or if it is 64 bits and has a single element. 1534 if ((Size == 8 || Size == 16 || Size == 32) || 1535 (Size == 64 && VT->getNumElements() == 1)) 1536 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 1537 Size)); 1538 1539 return getIndirectReturnResult(RetTy, State); 1540 } 1541 1542 return ABIArgInfo::getDirect(); 1543 } 1544 1545 if (isAggregateTypeForABI(RetTy)) { 1546 if (const RecordType *RT = RetTy->getAs<RecordType>()) { 1547 // Structures with flexible arrays are always indirect. 1548 if (RT->getDecl()->hasFlexibleArrayMember()) 1549 return getIndirectReturnResult(RetTy, State); 1550 } 1551 1552 // If specified, structs and unions are always indirect. 1553 if (!IsRetSmallStructInRegABI && !RetTy->isAnyComplexType()) 1554 return getIndirectReturnResult(RetTy, State); 1555 1556 // Ignore empty structs/unions. 1557 if (isEmptyRecord(getContext(), RetTy, true)) 1558 return ABIArgInfo::getIgnore(); 1559 1560 // Return complex of _Float16 as <2 x half> so the backend will use xmm0. 1561 if (const ComplexType *CT = RetTy->getAs<ComplexType>()) { 1562 QualType ET = getContext().getCanonicalType(CT->getElementType()); 1563 if (ET->isFloat16Type()) 1564 return ABIArgInfo::getDirect(llvm::FixedVectorType::get( 1565 llvm::Type::getHalfTy(getVMContext()), 2)); 1566 } 1567 1568 // Small structures which are register sized are generally returned 1569 // in a register. 1570 if (shouldReturnTypeInRegister(RetTy, getContext())) { 1571 uint64_t Size = getContext().getTypeSize(RetTy); 1572 1573 // As a special-case, if the struct is a "single-element" struct, and 1574 // the field is of type "float" or "double", return it in a 1575 // floating-point register. (MSVC does not apply this special case.) 1576 // We apply a similar transformation for pointer types to improve the 1577 // quality of the generated IR. 1578 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext())) 1579 if ((!IsWin32StructABI && SeltTy->isRealFloatingType()) 1580 || SeltTy->hasPointerRepresentation()) 1581 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0))); 1582 1583 // FIXME: We should be able to narrow this integer in cases with dead 1584 // padding. 1585 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size)); 1586 } 1587 1588 return getIndirectReturnResult(RetTy, State); 1589 } 1590 1591 // Treat an enum type as its underlying type. 1592 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 1593 RetTy = EnumTy->getDecl()->getIntegerType(); 1594 1595 if (const auto *EIT = RetTy->getAs<BitIntType>()) 1596 if (EIT->getNumBits() > 64) 1597 return getIndirectReturnResult(RetTy, State); 1598 1599 return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy) 1600 : ABIArgInfo::getDirect()); 1601 } 1602 1603 static bool isSIMDVectorType(ASTContext &Context, QualType Ty) { 1604 return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128; 1605 } 1606 1607 static bool isRecordWithSIMDVectorType(ASTContext &Context, QualType Ty) { 1608 const RecordType *RT = Ty->getAs<RecordType>(); 1609 if (!RT) 1610 return false; 1611 const RecordDecl *RD = RT->getDecl(); 1612 1613 // If this is a C++ record, check the bases first. 1614 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 1615 for (const auto &I : CXXRD->bases()) 1616 if (!isRecordWithSIMDVectorType(Context, I.getType())) 1617 return false; 1618 1619 for (const auto *i : RD->fields()) { 1620 QualType FT = i->getType(); 1621 1622 if (isSIMDVectorType(Context, FT)) 1623 return true; 1624 1625 if (isRecordWithSIMDVectorType(Context, FT)) 1626 return true; 1627 } 1628 1629 return false; 1630 } 1631 1632 unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty, 1633 unsigned Align) const { 1634 // Otherwise, if the alignment is less than or equal to the minimum ABI 1635 // alignment, just use the default; the backend will handle this. 1636 if (Align <= MinABIStackAlignInBytes) 1637 return 0; // Use default alignment. 1638 1639 if (IsLinuxABI) { 1640 // Exclude other System V OS (e.g Darwin, PS4 and FreeBSD) since we don't 1641 // want to spend any effort dealing with the ramifications of ABI breaks. 1642 // 1643 // If the vector type is __m128/__m256/__m512, return the default alignment. 1644 if (Ty->isVectorType() && (Align == 16 || Align == 32 || Align == 64)) 1645 return Align; 1646 } 1647 // On non-Darwin, the stack type alignment is always 4. 1648 if (!IsDarwinVectorABI) { 1649 // Set explicit alignment, since we may need to realign the top. 1650 return MinABIStackAlignInBytes; 1651 } 1652 1653 // Otherwise, if the type contains an SSE vector type, the alignment is 16. 1654 if (Align >= 16 && (isSIMDVectorType(getContext(), Ty) || 1655 isRecordWithSIMDVectorType(getContext(), Ty))) 1656 return 16; 1657 1658 return MinABIStackAlignInBytes; 1659 } 1660 1661 ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal, 1662 CCState &State) const { 1663 if (!ByVal) { 1664 if (State.FreeRegs) { 1665 --State.FreeRegs; // Non-byval indirects just use one pointer. 1666 if (!IsMCUABI) 1667 return getNaturalAlignIndirectInReg(Ty); 1668 } 1669 return getNaturalAlignIndirect(Ty, false); 1670 } 1671 1672 // Compute the byval alignment. 1673 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8; 1674 unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign); 1675 if (StackAlign == 0) 1676 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true); 1677 1678 // If the stack alignment is less than the type alignment, realign the 1679 // argument. 1680 bool Realign = TypeAlign > StackAlign; 1681 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(StackAlign), 1682 /*ByVal=*/true, Realign); 1683 } 1684 1685 X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const { 1686 const Type *T = isSingleElementStruct(Ty, getContext()); 1687 if (!T) 1688 T = Ty.getTypePtr(); 1689 1690 if (const BuiltinType *BT = T->getAs<BuiltinType>()) { 1691 BuiltinType::Kind K = BT->getKind(); 1692 if (K == BuiltinType::Float || K == BuiltinType::Double) 1693 return Float; 1694 } 1695 return Integer; 1696 } 1697 1698 bool X86_32ABIInfo::updateFreeRegs(QualType Ty, CCState &State) const { 1699 if (!IsSoftFloatABI) { 1700 Class C = classify(Ty); 1701 if (C == Float) 1702 return false; 1703 } 1704 1705 unsigned Size = getContext().getTypeSize(Ty); 1706 unsigned SizeInRegs = (Size + 31) / 32; 1707 1708 if (SizeInRegs == 0) 1709 return false; 1710 1711 if (!IsMCUABI) { 1712 if (SizeInRegs > State.FreeRegs) { 1713 State.FreeRegs = 0; 1714 return false; 1715 } 1716 } else { 1717 // The MCU psABI allows passing parameters in-reg even if there are 1718 // earlier parameters that are passed on the stack. Also, 1719 // it does not allow passing >8-byte structs in-register, 1720 // even if there are 3 free registers available. 1721 if (SizeInRegs > State.FreeRegs || SizeInRegs > 2) 1722 return false; 1723 } 1724 1725 State.FreeRegs -= SizeInRegs; 1726 return true; 1727 } 1728 1729 bool X86_32ABIInfo::shouldAggregateUseDirect(QualType Ty, CCState &State, 1730 bool &InReg, 1731 bool &NeedsPadding) const { 1732 // On Windows, aggregates other than HFAs are never passed in registers, and 1733 // they do not consume register slots. Homogenous floating-point aggregates 1734 // (HFAs) have already been dealt with at this point. 1735 if (IsWin32StructABI && isAggregateTypeForABI(Ty)) 1736 return false; 1737 1738 NeedsPadding = false; 1739 InReg = !IsMCUABI; 1740 1741 if (!updateFreeRegs(Ty, State)) 1742 return false; 1743 1744 if (IsMCUABI) 1745 return true; 1746 1747 if (State.CC == llvm::CallingConv::X86_FastCall || 1748 State.CC == llvm::CallingConv::X86_VectorCall || 1749 State.CC == llvm::CallingConv::X86_RegCall) { 1750 if (getContext().getTypeSize(Ty) <= 32 && State.FreeRegs) 1751 NeedsPadding = true; 1752 1753 return false; 1754 } 1755 1756 return true; 1757 } 1758 1759 bool X86_32ABIInfo::shouldPrimitiveUseInReg(QualType Ty, CCState &State) const { 1760 if (!updateFreeRegs(Ty, State)) 1761 return false; 1762 1763 if (IsMCUABI) 1764 return false; 1765 1766 if (State.CC == llvm::CallingConv::X86_FastCall || 1767 State.CC == llvm::CallingConv::X86_VectorCall || 1768 State.CC == llvm::CallingConv::X86_RegCall) { 1769 if (getContext().getTypeSize(Ty) > 32) 1770 return false; 1771 1772 return (Ty->isIntegralOrEnumerationType() || Ty->isPointerType() || 1773 Ty->isReferenceType()); 1774 } 1775 1776 return true; 1777 } 1778 1779 void X86_32ABIInfo::runVectorCallFirstPass(CGFunctionInfo &FI, CCState &State) const { 1780 // Vectorcall x86 works subtly different than in x64, so the format is 1781 // a bit different than the x64 version. First, all vector types (not HVAs) 1782 // are assigned, with the first 6 ending up in the [XYZ]MM0-5 registers. 1783 // This differs from the x64 implementation, where the first 6 by INDEX get 1784 // registers. 1785 // In the second pass over the arguments, HVAs are passed in the remaining 1786 // vector registers if possible, or indirectly by address. The address will be 1787 // passed in ECX/EDX if available. Any other arguments are passed according to 1788 // the usual fastcall rules. 1789 MutableArrayRef<CGFunctionInfoArgInfo> Args = FI.arguments(); 1790 for (int I = 0, E = Args.size(); I < E; ++I) { 1791 const Type *Base = nullptr; 1792 uint64_t NumElts = 0; 1793 const QualType &Ty = Args[I].type; 1794 if ((Ty->isVectorType() || Ty->isBuiltinType()) && 1795 isHomogeneousAggregate(Ty, Base, NumElts)) { 1796 if (State.FreeSSERegs >= NumElts) { 1797 State.FreeSSERegs -= NumElts; 1798 Args[I].info = ABIArgInfo::getDirectInReg(); 1799 State.IsPreassigned.set(I); 1800 } 1801 } 1802 } 1803 } 1804 1805 ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty, 1806 CCState &State) const { 1807 // FIXME: Set alignment on indirect arguments. 1808 bool IsFastCall = State.CC == llvm::CallingConv::X86_FastCall; 1809 bool IsRegCall = State.CC == llvm::CallingConv::X86_RegCall; 1810 bool IsVectorCall = State.CC == llvm::CallingConv::X86_VectorCall; 1811 1812 Ty = useFirstFieldIfTransparentUnion(Ty); 1813 TypeInfo TI = getContext().getTypeInfo(Ty); 1814 1815 // Check with the C++ ABI first. 1816 const RecordType *RT = Ty->getAs<RecordType>(); 1817 if (RT) { 1818 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()); 1819 if (RAA == CGCXXABI::RAA_Indirect) { 1820 return getIndirectResult(Ty, false, State); 1821 } else if (RAA == CGCXXABI::RAA_DirectInMemory) { 1822 // The field index doesn't matter, we'll fix it up later. 1823 return ABIArgInfo::getInAlloca(/*FieldIndex=*/0); 1824 } 1825 } 1826 1827 // Regcall uses the concept of a homogenous vector aggregate, similar 1828 // to other targets. 1829 const Type *Base = nullptr; 1830 uint64_t NumElts = 0; 1831 if ((IsRegCall || IsVectorCall) && 1832 isHomogeneousAggregate(Ty, Base, NumElts)) { 1833 if (State.FreeSSERegs >= NumElts) { 1834 State.FreeSSERegs -= NumElts; 1835 1836 // Vectorcall passes HVAs directly and does not flatten them, but regcall 1837 // does. 1838 if (IsVectorCall) 1839 return getDirectX86Hva(); 1840 1841 if (Ty->isBuiltinType() || Ty->isVectorType()) 1842 return ABIArgInfo::getDirect(); 1843 return ABIArgInfo::getExpand(); 1844 } 1845 return getIndirectResult(Ty, /*ByVal=*/false, State); 1846 } 1847 1848 if (isAggregateTypeForABI(Ty)) { 1849 // Structures with flexible arrays are always indirect. 1850 // FIXME: This should not be byval! 1851 if (RT && RT->getDecl()->hasFlexibleArrayMember()) 1852 return getIndirectResult(Ty, true, State); 1853 1854 // Ignore empty structs/unions on non-Windows. 1855 if (!IsWin32StructABI && isEmptyRecord(getContext(), Ty, true)) 1856 return ABIArgInfo::getIgnore(); 1857 1858 llvm::LLVMContext &LLVMContext = getVMContext(); 1859 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext); 1860 bool NeedsPadding = false; 1861 bool InReg; 1862 if (shouldAggregateUseDirect(Ty, State, InReg, NeedsPadding)) { 1863 unsigned SizeInRegs = (TI.Width + 31) / 32; 1864 SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32); 1865 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements); 1866 if (InReg) 1867 return ABIArgInfo::getDirectInReg(Result); 1868 else 1869 return ABIArgInfo::getDirect(Result); 1870 } 1871 llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : nullptr; 1872 1873 // Pass over-aligned aggregates on Windows indirectly. This behavior was 1874 // added in MSVC 2015. 1875 if (IsWin32StructABI && TI.isAlignRequired() && TI.Align > 32) 1876 return getIndirectResult(Ty, /*ByVal=*/false, State); 1877 1878 // Expand small (<= 128-bit) record types when we know that the stack layout 1879 // of those arguments will match the struct. This is important because the 1880 // LLVM backend isn't smart enough to remove byval, which inhibits many 1881 // optimizations. 1882 // Don't do this for the MCU if there are still free integer registers 1883 // (see X86_64 ABI for full explanation). 1884 if (TI.Width <= 4 * 32 && (!IsMCUABI || State.FreeRegs == 0) && 1885 canExpandIndirectArgument(Ty)) 1886 return ABIArgInfo::getExpandWithPadding( 1887 IsFastCall || IsVectorCall || IsRegCall, PaddingType); 1888 1889 return getIndirectResult(Ty, true, State); 1890 } 1891 1892 if (const VectorType *VT = Ty->getAs<VectorType>()) { 1893 // On Windows, vectors are passed directly if registers are available, or 1894 // indirectly if not. This avoids the need to align argument memory. Pass 1895 // user-defined vector types larger than 512 bits indirectly for simplicity. 1896 if (IsWin32StructABI) { 1897 if (TI.Width <= 512 && State.FreeSSERegs > 0) { 1898 --State.FreeSSERegs; 1899 return ABIArgInfo::getDirectInReg(); 1900 } 1901 return getIndirectResult(Ty, /*ByVal=*/false, State); 1902 } 1903 1904 // On Darwin, some vectors are passed in memory, we handle this by passing 1905 // it as an i8/i16/i32/i64. 1906 if (IsDarwinVectorABI) { 1907 if ((TI.Width == 8 || TI.Width == 16 || TI.Width == 32) || 1908 (TI.Width == 64 && VT->getNumElements() == 1)) 1909 return ABIArgInfo::getDirect( 1910 llvm::IntegerType::get(getVMContext(), TI.Width)); 1911 } 1912 1913 if (IsX86_MMXType(CGT.ConvertType(Ty))) 1914 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64)); 1915 1916 return ABIArgInfo::getDirect(); 1917 } 1918 1919 1920 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 1921 Ty = EnumTy->getDecl()->getIntegerType(); 1922 1923 bool InReg = shouldPrimitiveUseInReg(Ty, State); 1924 1925 if (isPromotableIntegerTypeForABI(Ty)) { 1926 if (InReg) 1927 return ABIArgInfo::getExtendInReg(Ty); 1928 return ABIArgInfo::getExtend(Ty); 1929 } 1930 1931 if (const auto *EIT = Ty->getAs<BitIntType>()) { 1932 if (EIT->getNumBits() <= 64) { 1933 if (InReg) 1934 return ABIArgInfo::getDirectInReg(); 1935 return ABIArgInfo::getDirect(); 1936 } 1937 return getIndirectResult(Ty, /*ByVal=*/false, State); 1938 } 1939 1940 if (InReg) 1941 return ABIArgInfo::getDirectInReg(); 1942 return ABIArgInfo::getDirect(); 1943 } 1944 1945 void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const { 1946 CCState State(FI); 1947 if (IsMCUABI) 1948 State.FreeRegs = 3; 1949 else if (State.CC == llvm::CallingConv::X86_FastCall) { 1950 State.FreeRegs = 2; 1951 State.FreeSSERegs = 3; 1952 } else if (State.CC == llvm::CallingConv::X86_VectorCall) { 1953 State.FreeRegs = 2; 1954 State.FreeSSERegs = 6; 1955 } else if (FI.getHasRegParm()) 1956 State.FreeRegs = FI.getRegParm(); 1957 else if (State.CC == llvm::CallingConv::X86_RegCall) { 1958 State.FreeRegs = 5; 1959 State.FreeSSERegs = 8; 1960 } else if (IsWin32StructABI) { 1961 // Since MSVC 2015, the first three SSE vectors have been passed in 1962 // registers. The rest are passed indirectly. 1963 State.FreeRegs = DefaultNumRegisterParameters; 1964 State.FreeSSERegs = 3; 1965 } else 1966 State.FreeRegs = DefaultNumRegisterParameters; 1967 1968 if (!::classifyReturnType(getCXXABI(), FI, *this)) { 1969 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), State); 1970 } else if (FI.getReturnInfo().isIndirect()) { 1971 // The C++ ABI is not aware of register usage, so we have to check if the 1972 // return value was sret and put it in a register ourselves if appropriate. 1973 if (State.FreeRegs) { 1974 --State.FreeRegs; // The sret parameter consumes a register. 1975 if (!IsMCUABI) 1976 FI.getReturnInfo().setInReg(true); 1977 } 1978 } 1979 1980 // The chain argument effectively gives us another free register. 1981 if (FI.isChainCall()) 1982 ++State.FreeRegs; 1983 1984 // For vectorcall, do a first pass over the arguments, assigning FP and vector 1985 // arguments to XMM registers as available. 1986 if (State.CC == llvm::CallingConv::X86_VectorCall) 1987 runVectorCallFirstPass(FI, State); 1988 1989 bool UsedInAlloca = false; 1990 MutableArrayRef<CGFunctionInfoArgInfo> Args = FI.arguments(); 1991 for (int I = 0, E = Args.size(); I < E; ++I) { 1992 // Skip arguments that have already been assigned. 1993 if (State.IsPreassigned.test(I)) 1994 continue; 1995 1996 Args[I].info = classifyArgumentType(Args[I].type, State); 1997 UsedInAlloca |= (Args[I].info.getKind() == ABIArgInfo::InAlloca); 1998 } 1999 2000 // If we needed to use inalloca for any argument, do a second pass and rewrite 2001 // all the memory arguments to use inalloca. 2002 if (UsedInAlloca) 2003 rewriteWithInAlloca(FI); 2004 } 2005 2006 void 2007 X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields, 2008 CharUnits &StackOffset, ABIArgInfo &Info, 2009 QualType Type) const { 2010 // Arguments are always 4-byte-aligned. 2011 CharUnits WordSize = CharUnits::fromQuantity(4); 2012 assert(StackOffset.isMultipleOf(WordSize) && "unaligned inalloca struct"); 2013 2014 // sret pointers and indirect things will require an extra pointer 2015 // indirection, unless they are byval. Most things are byval, and will not 2016 // require this indirection. 2017 bool IsIndirect = false; 2018 if (Info.isIndirect() && !Info.getIndirectByVal()) 2019 IsIndirect = true; 2020 Info = ABIArgInfo::getInAlloca(FrameFields.size(), IsIndirect); 2021 llvm::Type *LLTy = CGT.ConvertTypeForMem(Type); 2022 if (IsIndirect) 2023 LLTy = LLTy->getPointerTo(0); 2024 FrameFields.push_back(LLTy); 2025 StackOffset += IsIndirect ? WordSize : getContext().getTypeSizeInChars(Type); 2026 2027 // Insert padding bytes to respect alignment. 2028 CharUnits FieldEnd = StackOffset; 2029 StackOffset = FieldEnd.alignTo(WordSize); 2030 if (StackOffset != FieldEnd) { 2031 CharUnits NumBytes = StackOffset - FieldEnd; 2032 llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext()); 2033 Ty = llvm::ArrayType::get(Ty, NumBytes.getQuantity()); 2034 FrameFields.push_back(Ty); 2035 } 2036 } 2037 2038 static bool isArgInAlloca(const ABIArgInfo &Info) { 2039 // Leave ignored and inreg arguments alone. 2040 switch (Info.getKind()) { 2041 case ABIArgInfo::InAlloca: 2042 return true; 2043 case ABIArgInfo::Ignore: 2044 case ABIArgInfo::IndirectAliased: 2045 return false; 2046 case ABIArgInfo::Indirect: 2047 case ABIArgInfo::Direct: 2048 case ABIArgInfo::Extend: 2049 return !Info.getInReg(); 2050 case ABIArgInfo::Expand: 2051 case ABIArgInfo::CoerceAndExpand: 2052 // These are aggregate types which are never passed in registers when 2053 // inalloca is involved. 2054 return true; 2055 } 2056 llvm_unreachable("invalid enum"); 2057 } 2058 2059 void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const { 2060 assert(IsWin32StructABI && "inalloca only supported on win32"); 2061 2062 // Build a packed struct type for all of the arguments in memory. 2063 SmallVector<llvm::Type *, 6> FrameFields; 2064 2065 // The stack alignment is always 4. 2066 CharUnits StackAlign = CharUnits::fromQuantity(4); 2067 2068 CharUnits StackOffset; 2069 CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end(); 2070 2071 // Put 'this' into the struct before 'sret', if necessary. 2072 bool IsThisCall = 2073 FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall; 2074 ABIArgInfo &Ret = FI.getReturnInfo(); 2075 if (Ret.isIndirect() && Ret.isSRetAfterThis() && !IsThisCall && 2076 isArgInAlloca(I->info)) { 2077 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type); 2078 ++I; 2079 } 2080 2081 // Put the sret parameter into the inalloca struct if it's in memory. 2082 if (Ret.isIndirect() && !Ret.getInReg()) { 2083 addFieldToArgStruct(FrameFields, StackOffset, Ret, FI.getReturnType()); 2084 // On Windows, the hidden sret parameter is always returned in eax. 2085 Ret.setInAllocaSRet(IsWin32StructABI); 2086 } 2087 2088 // Skip the 'this' parameter in ecx. 2089 if (IsThisCall) 2090 ++I; 2091 2092 // Put arguments passed in memory into the struct. 2093 for (; I != E; ++I) { 2094 if (isArgInAlloca(I->info)) 2095 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type); 2096 } 2097 2098 FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields, 2099 /*isPacked=*/true), 2100 StackAlign); 2101 } 2102 2103 Address X86_32ABIInfo::EmitVAArg(CodeGenFunction &CGF, 2104 Address VAListAddr, QualType Ty) const { 2105 2106 auto TypeInfo = getContext().getTypeInfoInChars(Ty); 2107 2108 // x86-32 changes the alignment of certain arguments on the stack. 2109 // 2110 // Just messing with TypeInfo like this works because we never pass 2111 // anything indirectly. 2112 TypeInfo.Align = CharUnits::fromQuantity( 2113 getTypeStackAlignInBytes(Ty, TypeInfo.Align.getQuantity())); 2114 2115 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false, 2116 TypeInfo, CharUnits::fromQuantity(4), 2117 /*AllowHigherAlign*/ true); 2118 } 2119 2120 bool X86_32TargetCodeGenInfo::isStructReturnInRegABI( 2121 const llvm::Triple &Triple, const CodeGenOptions &Opts) { 2122 assert(Triple.getArch() == llvm::Triple::x86); 2123 2124 switch (Opts.getStructReturnConvention()) { 2125 case CodeGenOptions::SRCK_Default: 2126 break; 2127 case CodeGenOptions::SRCK_OnStack: // -fpcc-struct-return 2128 return false; 2129 case CodeGenOptions::SRCK_InRegs: // -freg-struct-return 2130 return true; 2131 } 2132 2133 if (Triple.isOSDarwin() || Triple.isOSIAMCU()) 2134 return true; 2135 2136 switch (Triple.getOS()) { 2137 case llvm::Triple::DragonFly: 2138 case llvm::Triple::FreeBSD: 2139 case llvm::Triple::OpenBSD: 2140 case llvm::Triple::Win32: 2141 return true; 2142 default: 2143 return false; 2144 } 2145 } 2146 2147 static void addX86InterruptAttrs(const FunctionDecl *FD, llvm::GlobalValue *GV, 2148 CodeGen::CodeGenModule &CGM) { 2149 if (!FD->hasAttr<AnyX86InterruptAttr>()) 2150 return; 2151 2152 llvm::Function *Fn = cast<llvm::Function>(GV); 2153 Fn->setCallingConv(llvm::CallingConv::X86_INTR); 2154 if (FD->getNumParams() == 0) 2155 return; 2156 2157 auto PtrTy = cast<PointerType>(FD->getParamDecl(0)->getType()); 2158 llvm::Type *ByValTy = CGM.getTypes().ConvertType(PtrTy->getPointeeType()); 2159 llvm::Attribute NewAttr = llvm::Attribute::getWithByValType( 2160 Fn->getContext(), ByValTy); 2161 Fn->addParamAttr(0, NewAttr); 2162 } 2163 2164 void X86_32TargetCodeGenInfo::setTargetAttributes( 2165 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const { 2166 if (GV->isDeclaration()) 2167 return; 2168 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) { 2169 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) { 2170 llvm::Function *Fn = cast<llvm::Function>(GV); 2171 Fn->addFnAttr("stackrealign"); 2172 } 2173 2174 addX86InterruptAttrs(FD, GV, CGM); 2175 } 2176 } 2177 2178 bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable( 2179 CodeGen::CodeGenFunction &CGF, 2180 llvm::Value *Address) const { 2181 CodeGen::CGBuilderTy &Builder = CGF.Builder; 2182 2183 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4); 2184 2185 // 0-7 are the eight integer registers; the order is different 2186 // on Darwin (for EH), but the range is the same. 2187 // 8 is %eip. 2188 AssignToArrayRange(Builder, Address, Four8, 0, 8); 2189 2190 if (CGF.CGM.getTarget().getTriple().isOSDarwin()) { 2191 // 12-16 are st(0..4). Not sure why we stop at 4. 2192 // These have size 16, which is sizeof(long double) on 2193 // platforms with 8-byte alignment for that type. 2194 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16); 2195 AssignToArrayRange(Builder, Address, Sixteen8, 12, 16); 2196 2197 } else { 2198 // 9 is %eflags, which doesn't get a size on Darwin for some 2199 // reason. 2200 Builder.CreateAlignedStore( 2201 Four8, Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, Address, 9), 2202 CharUnits::One()); 2203 2204 // 11-16 are st(0..5). Not sure why we stop at 5. 2205 // These have size 12, which is sizeof(long double) on 2206 // platforms with 4-byte alignment for that type. 2207 llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12); 2208 AssignToArrayRange(Builder, Address, Twelve8, 11, 16); 2209 } 2210 2211 return false; 2212 } 2213 2214 //===----------------------------------------------------------------------===// 2215 // X86-64 ABI Implementation 2216 //===----------------------------------------------------------------------===// 2217 2218 2219 namespace { 2220 /// The AVX ABI level for X86 targets. 2221 enum class X86AVXABILevel { 2222 None, 2223 AVX, 2224 AVX512 2225 }; 2226 2227 /// \p returns the size in bits of the largest (native) vector for \p AVXLevel. 2228 static unsigned getNativeVectorSizeForAVXABI(X86AVXABILevel AVXLevel) { 2229 switch (AVXLevel) { 2230 case X86AVXABILevel::AVX512: 2231 return 512; 2232 case X86AVXABILevel::AVX: 2233 return 256; 2234 case X86AVXABILevel::None: 2235 return 128; 2236 } 2237 llvm_unreachable("Unknown AVXLevel"); 2238 } 2239 2240 /// X86_64ABIInfo - The X86_64 ABI information. 2241 class X86_64ABIInfo : public SwiftABIInfo { 2242 enum Class { 2243 Integer = 0, 2244 SSE, 2245 SSEUp, 2246 X87, 2247 X87Up, 2248 ComplexX87, 2249 NoClass, 2250 Memory 2251 }; 2252 2253 /// merge - Implement the X86_64 ABI merging algorithm. 2254 /// 2255 /// Merge an accumulating classification \arg Accum with a field 2256 /// classification \arg Field. 2257 /// 2258 /// \param Accum - The accumulating classification. This should 2259 /// always be either NoClass or the result of a previous merge 2260 /// call. In addition, this should never be Memory (the caller 2261 /// should just return Memory for the aggregate). 2262 static Class merge(Class Accum, Class Field); 2263 2264 /// postMerge - Implement the X86_64 ABI post merging algorithm. 2265 /// 2266 /// Post merger cleanup, reduces a malformed Hi and Lo pair to 2267 /// final MEMORY or SSE classes when necessary. 2268 /// 2269 /// \param AggregateSize - The size of the current aggregate in 2270 /// the classification process. 2271 /// 2272 /// \param Lo - The classification for the parts of the type 2273 /// residing in the low word of the containing object. 2274 /// 2275 /// \param Hi - The classification for the parts of the type 2276 /// residing in the higher words of the containing object. 2277 /// 2278 void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const; 2279 2280 /// classify - Determine the x86_64 register classes in which the 2281 /// given type T should be passed. 2282 /// 2283 /// \param Lo - The classification for the parts of the type 2284 /// residing in the low word of the containing object. 2285 /// 2286 /// \param Hi - The classification for the parts of the type 2287 /// residing in the high word of the containing object. 2288 /// 2289 /// \param OffsetBase - The bit offset of this type in the 2290 /// containing object. Some parameters are classified different 2291 /// depending on whether they straddle an eightbyte boundary. 2292 /// 2293 /// \param isNamedArg - Whether the argument in question is a "named" 2294 /// argument, as used in AMD64-ABI 3.5.7. 2295 /// 2296 /// If a word is unused its result will be NoClass; if a type should 2297 /// be passed in Memory then at least the classification of \arg Lo 2298 /// will be Memory. 2299 /// 2300 /// The \arg Lo class will be NoClass iff the argument is ignored. 2301 /// 2302 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will 2303 /// also be ComplexX87. 2304 void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi, 2305 bool isNamedArg) const; 2306 2307 llvm::Type *GetByteVectorType(QualType Ty) const; 2308 llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType, 2309 unsigned IROffset, QualType SourceTy, 2310 unsigned SourceOffset) const; 2311 llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType, 2312 unsigned IROffset, QualType SourceTy, 2313 unsigned SourceOffset) const; 2314 2315 /// getIndirectResult - Give a source type \arg Ty, return a suitable result 2316 /// such that the argument will be returned in memory. 2317 ABIArgInfo getIndirectReturnResult(QualType Ty) const; 2318 2319 /// getIndirectResult - Give a source type \arg Ty, return a suitable result 2320 /// such that the argument will be passed in memory. 2321 /// 2322 /// \param freeIntRegs - The number of free integer registers remaining 2323 /// available. 2324 ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const; 2325 2326 ABIArgInfo classifyReturnType(QualType RetTy) const; 2327 2328 ABIArgInfo classifyArgumentType(QualType Ty, unsigned freeIntRegs, 2329 unsigned &neededInt, unsigned &neededSSE, 2330 bool isNamedArg) const; 2331 2332 ABIArgInfo classifyRegCallStructType(QualType Ty, unsigned &NeededInt, 2333 unsigned &NeededSSE) const; 2334 2335 ABIArgInfo classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt, 2336 unsigned &NeededSSE) const; 2337 2338 bool IsIllegalVectorType(QualType Ty) const; 2339 2340 /// The 0.98 ABI revision clarified a lot of ambiguities, 2341 /// unfortunately in ways that were not always consistent with 2342 /// certain previous compilers. In particular, platforms which 2343 /// required strict binary compatibility with older versions of GCC 2344 /// may need to exempt themselves. 2345 bool honorsRevision0_98() const { 2346 return !getTarget().getTriple().isOSDarwin(); 2347 } 2348 2349 /// GCC classifies <1 x long long> as SSE but some platform ABIs choose to 2350 /// classify it as INTEGER (for compatibility with older clang compilers). 2351 bool classifyIntegerMMXAsSSE() const { 2352 // Clang <= 3.8 did not do this. 2353 if (getContext().getLangOpts().getClangABICompat() <= 2354 LangOptions::ClangABI::Ver3_8) 2355 return false; 2356 2357 const llvm::Triple &Triple = getTarget().getTriple(); 2358 if (Triple.isOSDarwin() || Triple.getOS() == llvm::Triple::PS4) 2359 return false; 2360 if (Triple.isOSFreeBSD() && Triple.getOSMajorVersion() >= 10) 2361 return false; 2362 return true; 2363 } 2364 2365 // GCC classifies vectors of __int128 as memory. 2366 bool passInt128VectorsInMem() const { 2367 // Clang <= 9.0 did not do this. 2368 if (getContext().getLangOpts().getClangABICompat() <= 2369 LangOptions::ClangABI::Ver9) 2370 return false; 2371 2372 const llvm::Triple &T = getTarget().getTriple(); 2373 return T.isOSLinux() || T.isOSNetBSD(); 2374 } 2375 2376 X86AVXABILevel AVXLevel; 2377 // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on 2378 // 64-bit hardware. 2379 bool Has64BitPointers; 2380 2381 public: 2382 X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) : 2383 SwiftABIInfo(CGT), AVXLevel(AVXLevel), 2384 Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) { 2385 } 2386 2387 bool isPassedUsingAVXType(QualType type) const { 2388 unsigned neededInt, neededSSE; 2389 // The freeIntRegs argument doesn't matter here. 2390 ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE, 2391 /*isNamedArg*/true); 2392 if (info.isDirect()) { 2393 llvm::Type *ty = info.getCoerceToType(); 2394 if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty)) 2395 return vectorTy->getPrimitiveSizeInBits().getFixedSize() > 128; 2396 } 2397 return false; 2398 } 2399 2400 void computeInfo(CGFunctionInfo &FI) const override; 2401 2402 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 2403 QualType Ty) const override; 2404 Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr, 2405 QualType Ty) const override; 2406 2407 bool has64BitPointers() const { 2408 return Has64BitPointers; 2409 } 2410 2411 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars, 2412 bool asReturnValue) const override { 2413 return occupiesMoreThan(CGT, scalars, /*total*/ 4); 2414 } 2415 bool isSwiftErrorInRegister() const override { 2416 return true; 2417 } 2418 }; 2419 2420 /// WinX86_64ABIInfo - The Windows X86_64 ABI information. 2421 class WinX86_64ABIInfo : public SwiftABIInfo { 2422 public: 2423 WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) 2424 : SwiftABIInfo(CGT), AVXLevel(AVXLevel), 2425 IsMingw64(getTarget().getTriple().isWindowsGNUEnvironment()) {} 2426 2427 void computeInfo(CGFunctionInfo &FI) const override; 2428 2429 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 2430 QualType Ty) const override; 2431 2432 bool isHomogeneousAggregateBaseType(QualType Ty) const override { 2433 // FIXME: Assumes vectorcall is in use. 2434 return isX86VectorTypeForVectorCall(getContext(), Ty); 2435 } 2436 2437 bool isHomogeneousAggregateSmallEnough(const Type *Ty, 2438 uint64_t NumMembers) const override { 2439 // FIXME: Assumes vectorcall is in use. 2440 return isX86VectorCallAggregateSmallEnough(NumMembers); 2441 } 2442 2443 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type *> scalars, 2444 bool asReturnValue) const override { 2445 return occupiesMoreThan(CGT, scalars, /*total*/ 4); 2446 } 2447 2448 bool isSwiftErrorInRegister() const override { 2449 return true; 2450 } 2451 2452 private: 2453 ABIArgInfo classify(QualType Ty, unsigned &FreeSSERegs, bool IsReturnType, 2454 bool IsVectorCall, bool IsRegCall) const; 2455 ABIArgInfo reclassifyHvaArgForVectorCall(QualType Ty, unsigned &FreeSSERegs, 2456 const ABIArgInfo ¤t) const; 2457 2458 X86AVXABILevel AVXLevel; 2459 2460 bool IsMingw64; 2461 }; 2462 2463 class X86_64TargetCodeGenInfo : public TargetCodeGenInfo { 2464 public: 2465 X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) 2466 : TargetCodeGenInfo(std::make_unique<X86_64ABIInfo>(CGT, AVXLevel)) {} 2467 2468 const X86_64ABIInfo &getABIInfo() const { 2469 return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo()); 2470 } 2471 2472 /// Disable tail call on x86-64. The epilogue code before the tail jump blocks 2473 /// autoreleaseRV/retainRV and autoreleaseRV/unsafeClaimRV optimizations. 2474 bool markARCOptimizedReturnCallsAsNoTail() const override { return true; } 2475 2476 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override { 2477 return 7; 2478 } 2479 2480 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 2481 llvm::Value *Address) const override { 2482 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8); 2483 2484 // 0-15 are the 16 integer registers. 2485 // 16 is %rip. 2486 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16); 2487 return false; 2488 } 2489 2490 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF, 2491 StringRef Constraint, 2492 llvm::Type* Ty) const override { 2493 return X86AdjustInlineAsmType(CGF, Constraint, Ty); 2494 } 2495 2496 bool isNoProtoCallVariadic(const CallArgList &args, 2497 const FunctionNoProtoType *fnType) const override { 2498 // The default CC on x86-64 sets %al to the number of SSA 2499 // registers used, and GCC sets this when calling an unprototyped 2500 // function, so we override the default behavior. However, don't do 2501 // that when AVX types are involved: the ABI explicitly states it is 2502 // undefined, and it doesn't work in practice because of how the ABI 2503 // defines varargs anyway. 2504 if (fnType->getCallConv() == CC_C) { 2505 bool HasAVXType = false; 2506 for (CallArgList::const_iterator 2507 it = args.begin(), ie = args.end(); it != ie; ++it) { 2508 if (getABIInfo().isPassedUsingAVXType(it->Ty)) { 2509 HasAVXType = true; 2510 break; 2511 } 2512 } 2513 2514 if (!HasAVXType) 2515 return true; 2516 } 2517 2518 return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType); 2519 } 2520 2521 llvm::Constant * 2522 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override { 2523 unsigned Sig = (0xeb << 0) | // jmp rel8 2524 (0x06 << 8) | // .+0x08 2525 ('v' << 16) | 2526 ('2' << 24); 2527 return llvm::ConstantInt::get(CGM.Int32Ty, Sig); 2528 } 2529 2530 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 2531 CodeGen::CodeGenModule &CGM) const override { 2532 if (GV->isDeclaration()) 2533 return; 2534 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) { 2535 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) { 2536 llvm::Function *Fn = cast<llvm::Function>(GV); 2537 Fn->addFnAttr("stackrealign"); 2538 } 2539 2540 addX86InterruptAttrs(FD, GV, CGM); 2541 } 2542 } 2543 2544 void checkFunctionCallABI(CodeGenModule &CGM, SourceLocation CallLoc, 2545 const FunctionDecl *Caller, 2546 const FunctionDecl *Callee, 2547 const CallArgList &Args) const override; 2548 }; 2549 2550 static void initFeatureMaps(const ASTContext &Ctx, 2551 llvm::StringMap<bool> &CallerMap, 2552 const FunctionDecl *Caller, 2553 llvm::StringMap<bool> &CalleeMap, 2554 const FunctionDecl *Callee) { 2555 if (CalleeMap.empty() && CallerMap.empty()) { 2556 // The caller is potentially nullptr in the case where the call isn't in a 2557 // function. In this case, the getFunctionFeatureMap ensures we just get 2558 // the TU level setting (since it cannot be modified by 'target'.. 2559 Ctx.getFunctionFeatureMap(CallerMap, Caller); 2560 Ctx.getFunctionFeatureMap(CalleeMap, Callee); 2561 } 2562 } 2563 2564 static bool checkAVXParamFeature(DiagnosticsEngine &Diag, 2565 SourceLocation CallLoc, 2566 const llvm::StringMap<bool> &CallerMap, 2567 const llvm::StringMap<bool> &CalleeMap, 2568 QualType Ty, StringRef Feature, 2569 bool IsArgument) { 2570 bool CallerHasFeat = CallerMap.lookup(Feature); 2571 bool CalleeHasFeat = CalleeMap.lookup(Feature); 2572 if (!CallerHasFeat && !CalleeHasFeat) 2573 return Diag.Report(CallLoc, diag::warn_avx_calling_convention) 2574 << IsArgument << Ty << Feature; 2575 2576 // Mixing calling conventions here is very clearly an error. 2577 if (!CallerHasFeat || !CalleeHasFeat) 2578 return Diag.Report(CallLoc, diag::err_avx_calling_convention) 2579 << IsArgument << Ty << Feature; 2580 2581 // Else, both caller and callee have the required feature, so there is no need 2582 // to diagnose. 2583 return false; 2584 } 2585 2586 static bool checkAVXParam(DiagnosticsEngine &Diag, ASTContext &Ctx, 2587 SourceLocation CallLoc, 2588 const llvm::StringMap<bool> &CallerMap, 2589 const llvm::StringMap<bool> &CalleeMap, QualType Ty, 2590 bool IsArgument) { 2591 uint64_t Size = Ctx.getTypeSize(Ty); 2592 if (Size > 256) 2593 return checkAVXParamFeature(Diag, CallLoc, CallerMap, CalleeMap, Ty, 2594 "avx512f", IsArgument); 2595 2596 if (Size > 128) 2597 return checkAVXParamFeature(Diag, CallLoc, CallerMap, CalleeMap, Ty, "avx", 2598 IsArgument); 2599 2600 return false; 2601 } 2602 2603 void X86_64TargetCodeGenInfo::checkFunctionCallABI( 2604 CodeGenModule &CGM, SourceLocation CallLoc, const FunctionDecl *Caller, 2605 const FunctionDecl *Callee, const CallArgList &Args) const { 2606 llvm::StringMap<bool> CallerMap; 2607 llvm::StringMap<bool> CalleeMap; 2608 unsigned ArgIndex = 0; 2609 2610 // We need to loop through the actual call arguments rather than the the 2611 // function's parameters, in case this variadic. 2612 for (const CallArg &Arg : Args) { 2613 // The "avx" feature changes how vectors >128 in size are passed. "avx512f" 2614 // additionally changes how vectors >256 in size are passed. Like GCC, we 2615 // warn when a function is called with an argument where this will change. 2616 // Unlike GCC, we also error when it is an obvious ABI mismatch, that is, 2617 // the caller and callee features are mismatched. 2618 // Unfortunately, we cannot do this diagnostic in SEMA, since the callee can 2619 // change its ABI with attribute-target after this call. 2620 if (Arg.getType()->isVectorType() && 2621 CGM.getContext().getTypeSize(Arg.getType()) > 128) { 2622 initFeatureMaps(CGM.getContext(), CallerMap, Caller, CalleeMap, Callee); 2623 QualType Ty = Arg.getType(); 2624 // The CallArg seems to have desugared the type already, so for clearer 2625 // diagnostics, replace it with the type in the FunctionDecl if possible. 2626 if (ArgIndex < Callee->getNumParams()) 2627 Ty = Callee->getParamDecl(ArgIndex)->getType(); 2628 2629 if (checkAVXParam(CGM.getDiags(), CGM.getContext(), CallLoc, CallerMap, 2630 CalleeMap, Ty, /*IsArgument*/ true)) 2631 return; 2632 } 2633 ++ArgIndex; 2634 } 2635 2636 // Check return always, as we don't have a good way of knowing in codegen 2637 // whether this value is used, tail-called, etc. 2638 if (Callee->getReturnType()->isVectorType() && 2639 CGM.getContext().getTypeSize(Callee->getReturnType()) > 128) { 2640 initFeatureMaps(CGM.getContext(), CallerMap, Caller, CalleeMap, Callee); 2641 checkAVXParam(CGM.getDiags(), CGM.getContext(), CallLoc, CallerMap, 2642 CalleeMap, Callee->getReturnType(), 2643 /*IsArgument*/ false); 2644 } 2645 } 2646 2647 static std::string qualifyWindowsLibrary(llvm::StringRef Lib) { 2648 // If the argument does not end in .lib, automatically add the suffix. 2649 // If the argument contains a space, enclose it in quotes. 2650 // This matches the behavior of MSVC. 2651 bool Quote = Lib.contains(' '); 2652 std::string ArgStr = Quote ? "\"" : ""; 2653 ArgStr += Lib; 2654 if (!Lib.endswith_insensitive(".lib") && !Lib.endswith_insensitive(".a")) 2655 ArgStr += ".lib"; 2656 ArgStr += Quote ? "\"" : ""; 2657 return ArgStr; 2658 } 2659 2660 class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo { 2661 public: 2662 WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, 2663 bool DarwinVectorABI, bool RetSmallStructInRegABI, bool Win32StructABI, 2664 unsigned NumRegisterParameters) 2665 : X86_32TargetCodeGenInfo(CGT, DarwinVectorABI, RetSmallStructInRegABI, 2666 Win32StructABI, NumRegisterParameters, false) {} 2667 2668 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 2669 CodeGen::CodeGenModule &CGM) const override; 2670 2671 void getDependentLibraryOption(llvm::StringRef Lib, 2672 llvm::SmallString<24> &Opt) const override { 2673 Opt = "/DEFAULTLIB:"; 2674 Opt += qualifyWindowsLibrary(Lib); 2675 } 2676 2677 void getDetectMismatchOption(llvm::StringRef Name, 2678 llvm::StringRef Value, 2679 llvm::SmallString<32> &Opt) const override { 2680 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\""; 2681 } 2682 }; 2683 2684 static void addStackProbeTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 2685 CodeGen::CodeGenModule &CGM) { 2686 if (llvm::Function *Fn = dyn_cast_or_null<llvm::Function>(GV)) { 2687 2688 if (CGM.getCodeGenOpts().StackProbeSize != 4096) 2689 Fn->addFnAttr("stack-probe-size", 2690 llvm::utostr(CGM.getCodeGenOpts().StackProbeSize)); 2691 if (CGM.getCodeGenOpts().NoStackArgProbe) 2692 Fn->addFnAttr("no-stack-arg-probe"); 2693 } 2694 } 2695 2696 void WinX86_32TargetCodeGenInfo::setTargetAttributes( 2697 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const { 2698 X86_32TargetCodeGenInfo::setTargetAttributes(D, GV, CGM); 2699 if (GV->isDeclaration()) 2700 return; 2701 addStackProbeTargetAttributes(D, GV, CGM); 2702 } 2703 2704 class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo { 2705 public: 2706 WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, 2707 X86AVXABILevel AVXLevel) 2708 : TargetCodeGenInfo(std::make_unique<WinX86_64ABIInfo>(CGT, AVXLevel)) {} 2709 2710 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 2711 CodeGen::CodeGenModule &CGM) const override; 2712 2713 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override { 2714 return 7; 2715 } 2716 2717 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 2718 llvm::Value *Address) const override { 2719 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8); 2720 2721 // 0-15 are the 16 integer registers. 2722 // 16 is %rip. 2723 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16); 2724 return false; 2725 } 2726 2727 void getDependentLibraryOption(llvm::StringRef Lib, 2728 llvm::SmallString<24> &Opt) const override { 2729 Opt = "/DEFAULTLIB:"; 2730 Opt += qualifyWindowsLibrary(Lib); 2731 } 2732 2733 void getDetectMismatchOption(llvm::StringRef Name, 2734 llvm::StringRef Value, 2735 llvm::SmallString<32> &Opt) const override { 2736 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\""; 2737 } 2738 }; 2739 2740 void WinX86_64TargetCodeGenInfo::setTargetAttributes( 2741 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const { 2742 TargetCodeGenInfo::setTargetAttributes(D, GV, CGM); 2743 if (GV->isDeclaration()) 2744 return; 2745 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) { 2746 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) { 2747 llvm::Function *Fn = cast<llvm::Function>(GV); 2748 Fn->addFnAttr("stackrealign"); 2749 } 2750 2751 addX86InterruptAttrs(FD, GV, CGM); 2752 } 2753 2754 addStackProbeTargetAttributes(D, GV, CGM); 2755 } 2756 } 2757 2758 void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo, 2759 Class &Hi) const { 2760 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done: 2761 // 2762 // (a) If one of the classes is Memory, the whole argument is passed in 2763 // memory. 2764 // 2765 // (b) If X87UP is not preceded by X87, the whole argument is passed in 2766 // memory. 2767 // 2768 // (c) If the size of the aggregate exceeds two eightbytes and the first 2769 // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole 2770 // argument is passed in memory. NOTE: This is necessary to keep the 2771 // ABI working for processors that don't support the __m256 type. 2772 // 2773 // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE. 2774 // 2775 // Some of these are enforced by the merging logic. Others can arise 2776 // only with unions; for example: 2777 // union { _Complex double; unsigned; } 2778 // 2779 // Note that clauses (b) and (c) were added in 0.98. 2780 // 2781 if (Hi == Memory) 2782 Lo = Memory; 2783 if (Hi == X87Up && Lo != X87 && honorsRevision0_98()) 2784 Lo = Memory; 2785 if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp)) 2786 Lo = Memory; 2787 if (Hi == SSEUp && Lo != SSE) 2788 Hi = SSE; 2789 } 2790 2791 X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) { 2792 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is 2793 // classified recursively so that always two fields are 2794 // considered. The resulting class is calculated according to 2795 // the classes of the fields in the eightbyte: 2796 // 2797 // (a) If both classes are equal, this is the resulting class. 2798 // 2799 // (b) If one of the classes is NO_CLASS, the resulting class is 2800 // the other class. 2801 // 2802 // (c) If one of the classes is MEMORY, the result is the MEMORY 2803 // class. 2804 // 2805 // (d) If one of the classes is INTEGER, the result is the 2806 // INTEGER. 2807 // 2808 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class, 2809 // MEMORY is used as class. 2810 // 2811 // (f) Otherwise class SSE is used. 2812 2813 // Accum should never be memory (we should have returned) or 2814 // ComplexX87 (because this cannot be passed in a structure). 2815 assert((Accum != Memory && Accum != ComplexX87) && 2816 "Invalid accumulated classification during merge."); 2817 if (Accum == Field || Field == NoClass) 2818 return Accum; 2819 if (Field == Memory) 2820 return Memory; 2821 if (Accum == NoClass) 2822 return Field; 2823 if (Accum == Integer || Field == Integer) 2824 return Integer; 2825 if (Field == X87 || Field == X87Up || Field == ComplexX87 || 2826 Accum == X87 || Accum == X87Up) 2827 return Memory; 2828 return SSE; 2829 } 2830 2831 void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase, 2832 Class &Lo, Class &Hi, bool isNamedArg) const { 2833 // FIXME: This code can be simplified by introducing a simple value class for 2834 // Class pairs with appropriate constructor methods for the various 2835 // situations. 2836 2837 // FIXME: Some of the split computations are wrong; unaligned vectors 2838 // shouldn't be passed in registers for example, so there is no chance they 2839 // can straddle an eightbyte. Verify & simplify. 2840 2841 Lo = Hi = NoClass; 2842 2843 Class &Current = OffsetBase < 64 ? Lo : Hi; 2844 Current = Memory; 2845 2846 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) { 2847 BuiltinType::Kind k = BT->getKind(); 2848 2849 if (k == BuiltinType::Void) { 2850 Current = NoClass; 2851 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) { 2852 Lo = Integer; 2853 Hi = Integer; 2854 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) { 2855 Current = Integer; 2856 } else if (k == BuiltinType::Float || k == BuiltinType::Double || 2857 k == BuiltinType::Float16) { 2858 Current = SSE; 2859 } else if (k == BuiltinType::LongDouble) { 2860 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat(); 2861 if (LDF == &llvm::APFloat::IEEEquad()) { 2862 Lo = SSE; 2863 Hi = SSEUp; 2864 } else if (LDF == &llvm::APFloat::x87DoubleExtended()) { 2865 Lo = X87; 2866 Hi = X87Up; 2867 } else if (LDF == &llvm::APFloat::IEEEdouble()) { 2868 Current = SSE; 2869 } else 2870 llvm_unreachable("unexpected long double representation!"); 2871 } 2872 // FIXME: _Decimal32 and _Decimal64 are SSE. 2873 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp). 2874 return; 2875 } 2876 2877 if (const EnumType *ET = Ty->getAs<EnumType>()) { 2878 // Classify the underlying integer type. 2879 classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg); 2880 return; 2881 } 2882 2883 if (Ty->hasPointerRepresentation()) { 2884 Current = Integer; 2885 return; 2886 } 2887 2888 if (Ty->isMemberPointerType()) { 2889 if (Ty->isMemberFunctionPointerType()) { 2890 if (Has64BitPointers) { 2891 // If Has64BitPointers, this is an {i64, i64}, so classify both 2892 // Lo and Hi now. 2893 Lo = Hi = Integer; 2894 } else { 2895 // Otherwise, with 32-bit pointers, this is an {i32, i32}. If that 2896 // straddles an eightbyte boundary, Hi should be classified as well. 2897 uint64_t EB_FuncPtr = (OffsetBase) / 64; 2898 uint64_t EB_ThisAdj = (OffsetBase + 64 - 1) / 64; 2899 if (EB_FuncPtr != EB_ThisAdj) { 2900 Lo = Hi = Integer; 2901 } else { 2902 Current = Integer; 2903 } 2904 } 2905 } else { 2906 Current = Integer; 2907 } 2908 return; 2909 } 2910 2911 if (const VectorType *VT = Ty->getAs<VectorType>()) { 2912 uint64_t Size = getContext().getTypeSize(VT); 2913 if (Size == 1 || Size == 8 || Size == 16 || Size == 32) { 2914 // gcc passes the following as integer: 2915 // 4 bytes - <4 x char>, <2 x short>, <1 x int>, <1 x float> 2916 // 2 bytes - <2 x char>, <1 x short> 2917 // 1 byte - <1 x char> 2918 Current = Integer; 2919 2920 // If this type crosses an eightbyte boundary, it should be 2921 // split. 2922 uint64_t EB_Lo = (OffsetBase) / 64; 2923 uint64_t EB_Hi = (OffsetBase + Size - 1) / 64; 2924 if (EB_Lo != EB_Hi) 2925 Hi = Lo; 2926 } else if (Size == 64) { 2927 QualType ElementType = VT->getElementType(); 2928 2929 // gcc passes <1 x double> in memory. :( 2930 if (ElementType->isSpecificBuiltinType(BuiltinType::Double)) 2931 return; 2932 2933 // gcc passes <1 x long long> as SSE but clang used to unconditionally 2934 // pass them as integer. For platforms where clang is the de facto 2935 // platform compiler, we must continue to use integer. 2936 if (!classifyIntegerMMXAsSSE() && 2937 (ElementType->isSpecificBuiltinType(BuiltinType::LongLong) || 2938 ElementType->isSpecificBuiltinType(BuiltinType::ULongLong) || 2939 ElementType->isSpecificBuiltinType(BuiltinType::Long) || 2940 ElementType->isSpecificBuiltinType(BuiltinType::ULong))) 2941 Current = Integer; 2942 else 2943 Current = SSE; 2944 2945 // If this type crosses an eightbyte boundary, it should be 2946 // split. 2947 if (OffsetBase && OffsetBase != 64) 2948 Hi = Lo; 2949 } else if (Size == 128 || 2950 (isNamedArg && Size <= getNativeVectorSizeForAVXABI(AVXLevel))) { 2951 QualType ElementType = VT->getElementType(); 2952 2953 // gcc passes 256 and 512 bit <X x __int128> vectors in memory. :( 2954 if (passInt128VectorsInMem() && Size != 128 && 2955 (ElementType->isSpecificBuiltinType(BuiltinType::Int128) || 2956 ElementType->isSpecificBuiltinType(BuiltinType::UInt128))) 2957 return; 2958 2959 // Arguments of 256-bits are split into four eightbyte chunks. The 2960 // least significant one belongs to class SSE and all the others to class 2961 // SSEUP. The original Lo and Hi design considers that types can't be 2962 // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense. 2963 // This design isn't correct for 256-bits, but since there're no cases 2964 // where the upper parts would need to be inspected, avoid adding 2965 // complexity and just consider Hi to match the 64-256 part. 2966 // 2967 // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in 2968 // registers if they are "named", i.e. not part of the "..." of a 2969 // variadic function. 2970 // 2971 // Similarly, per 3.2.3. of the AVX512 draft, 512-bits ("named") args are 2972 // split into eight eightbyte chunks, one SSE and seven SSEUP. 2973 Lo = SSE; 2974 Hi = SSEUp; 2975 } 2976 return; 2977 } 2978 2979 if (const ComplexType *CT = Ty->getAs<ComplexType>()) { 2980 QualType ET = getContext().getCanonicalType(CT->getElementType()); 2981 2982 uint64_t Size = getContext().getTypeSize(Ty); 2983 if (ET->isIntegralOrEnumerationType()) { 2984 if (Size <= 64) 2985 Current = Integer; 2986 else if (Size <= 128) 2987 Lo = Hi = Integer; 2988 } else if (ET->isFloat16Type() || ET == getContext().FloatTy) { 2989 Current = SSE; 2990 } else if (ET == getContext().DoubleTy) { 2991 Lo = Hi = SSE; 2992 } else if (ET == getContext().LongDoubleTy) { 2993 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat(); 2994 if (LDF == &llvm::APFloat::IEEEquad()) 2995 Current = Memory; 2996 else if (LDF == &llvm::APFloat::x87DoubleExtended()) 2997 Current = ComplexX87; 2998 else if (LDF == &llvm::APFloat::IEEEdouble()) 2999 Lo = Hi = SSE; 3000 else 3001 llvm_unreachable("unexpected long double representation!"); 3002 } 3003 3004 // If this complex type crosses an eightbyte boundary then it 3005 // should be split. 3006 uint64_t EB_Real = (OffsetBase) / 64; 3007 uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64; 3008 if (Hi == NoClass && EB_Real != EB_Imag) 3009 Hi = Lo; 3010 3011 return; 3012 } 3013 3014 if (const auto *EITy = Ty->getAs<BitIntType>()) { 3015 if (EITy->getNumBits() <= 64) 3016 Current = Integer; 3017 else if (EITy->getNumBits() <= 128) 3018 Lo = Hi = Integer; 3019 // Larger values need to get passed in memory. 3020 return; 3021 } 3022 3023 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) { 3024 // Arrays are treated like structures. 3025 3026 uint64_t Size = getContext().getTypeSize(Ty); 3027 3028 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger 3029 // than eight eightbytes, ..., it has class MEMORY. 3030 if (Size > 512) 3031 return; 3032 3033 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned 3034 // fields, it has class MEMORY. 3035 // 3036 // Only need to check alignment of array base. 3037 if (OffsetBase % getContext().getTypeAlign(AT->getElementType())) 3038 return; 3039 3040 // Otherwise implement simplified merge. We could be smarter about 3041 // this, but it isn't worth it and would be harder to verify. 3042 Current = NoClass; 3043 uint64_t EltSize = getContext().getTypeSize(AT->getElementType()); 3044 uint64_t ArraySize = AT->getSize().getZExtValue(); 3045 3046 // The only case a 256-bit wide vector could be used is when the array 3047 // contains a single 256-bit element. Since Lo and Hi logic isn't extended 3048 // to work for sizes wider than 128, early check and fallback to memory. 3049 // 3050 if (Size > 128 && 3051 (Size != EltSize || Size > getNativeVectorSizeForAVXABI(AVXLevel))) 3052 return; 3053 3054 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) { 3055 Class FieldLo, FieldHi; 3056 classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg); 3057 Lo = merge(Lo, FieldLo); 3058 Hi = merge(Hi, FieldHi); 3059 if (Lo == Memory || Hi == Memory) 3060 break; 3061 } 3062 3063 postMerge(Size, Lo, Hi); 3064 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification."); 3065 return; 3066 } 3067 3068 if (const RecordType *RT = Ty->getAs<RecordType>()) { 3069 uint64_t Size = getContext().getTypeSize(Ty); 3070 3071 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger 3072 // than eight eightbytes, ..., it has class MEMORY. 3073 if (Size > 512) 3074 return; 3075 3076 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial 3077 // copy constructor or a non-trivial destructor, it is passed by invisible 3078 // reference. 3079 if (getRecordArgABI(RT, getCXXABI())) 3080 return; 3081 3082 const RecordDecl *RD = RT->getDecl(); 3083 3084 // Assume variable sized types are passed in memory. 3085 if (RD->hasFlexibleArrayMember()) 3086 return; 3087 3088 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD); 3089 3090 // Reset Lo class, this will be recomputed. 3091 Current = NoClass; 3092 3093 // If this is a C++ record, classify the bases first. 3094 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 3095 for (const auto &I : CXXRD->bases()) { 3096 assert(!I.isVirtual() && !I.getType()->isDependentType() && 3097 "Unexpected base class!"); 3098 const auto *Base = 3099 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl()); 3100 3101 // Classify this field. 3102 // 3103 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a 3104 // single eightbyte, each is classified separately. Each eightbyte gets 3105 // initialized to class NO_CLASS. 3106 Class FieldLo, FieldHi; 3107 uint64_t Offset = 3108 OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base)); 3109 classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg); 3110 Lo = merge(Lo, FieldLo); 3111 Hi = merge(Hi, FieldHi); 3112 if (Lo == Memory || Hi == Memory) { 3113 postMerge(Size, Lo, Hi); 3114 return; 3115 } 3116 } 3117 } 3118 3119 // Classify the fields one at a time, merging the results. 3120 unsigned idx = 0; 3121 bool UseClang11Compat = getContext().getLangOpts().getClangABICompat() <= 3122 LangOptions::ClangABI::Ver11 || 3123 getContext().getTargetInfo().getTriple().isPS4(); 3124 bool IsUnion = RT->isUnionType() && !UseClang11Compat; 3125 3126 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 3127 i != e; ++i, ++idx) { 3128 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx); 3129 bool BitField = i->isBitField(); 3130 3131 // Ignore padding bit-fields. 3132 if (BitField && i->isUnnamedBitfield()) 3133 continue; 3134 3135 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than 3136 // eight eightbytes, or it contains unaligned fields, it has class MEMORY. 3137 // 3138 // The only case a 256-bit or a 512-bit wide vector could be used is when 3139 // the struct contains a single 256-bit or 512-bit element. Early check 3140 // and fallback to memory. 3141 // 3142 // FIXME: Extended the Lo and Hi logic properly to work for size wider 3143 // than 128. 3144 if (Size > 128 && 3145 ((!IsUnion && Size != getContext().getTypeSize(i->getType())) || 3146 Size > getNativeVectorSizeForAVXABI(AVXLevel))) { 3147 Lo = Memory; 3148 postMerge(Size, Lo, Hi); 3149 return; 3150 } 3151 // Note, skip this test for bit-fields, see below. 3152 if (!BitField && Offset % getContext().getTypeAlign(i->getType())) { 3153 Lo = Memory; 3154 postMerge(Size, Lo, Hi); 3155 return; 3156 } 3157 3158 // Classify this field. 3159 // 3160 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate 3161 // exceeds a single eightbyte, each is classified 3162 // separately. Each eightbyte gets initialized to class 3163 // NO_CLASS. 3164 Class FieldLo, FieldHi; 3165 3166 // Bit-fields require special handling, they do not force the 3167 // structure to be passed in memory even if unaligned, and 3168 // therefore they can straddle an eightbyte. 3169 if (BitField) { 3170 assert(!i->isUnnamedBitfield()); 3171 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx); 3172 uint64_t Size = i->getBitWidthValue(getContext()); 3173 3174 uint64_t EB_Lo = Offset / 64; 3175 uint64_t EB_Hi = (Offset + Size - 1) / 64; 3176 3177 if (EB_Lo) { 3178 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes."); 3179 FieldLo = NoClass; 3180 FieldHi = Integer; 3181 } else { 3182 FieldLo = Integer; 3183 FieldHi = EB_Hi ? Integer : NoClass; 3184 } 3185 } else 3186 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg); 3187 Lo = merge(Lo, FieldLo); 3188 Hi = merge(Hi, FieldHi); 3189 if (Lo == Memory || Hi == Memory) 3190 break; 3191 } 3192 3193 postMerge(Size, Lo, Hi); 3194 } 3195 } 3196 3197 ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const { 3198 // If this is a scalar LLVM value then assume LLVM will pass it in the right 3199 // place naturally. 3200 if (!isAggregateTypeForABI(Ty)) { 3201 // Treat an enum type as its underlying type. 3202 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 3203 Ty = EnumTy->getDecl()->getIntegerType(); 3204 3205 if (Ty->isBitIntType()) 3206 return getNaturalAlignIndirect(Ty); 3207 3208 return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty) 3209 : ABIArgInfo::getDirect()); 3210 } 3211 3212 return getNaturalAlignIndirect(Ty); 3213 } 3214 3215 bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const { 3216 if (const VectorType *VecTy = Ty->getAs<VectorType>()) { 3217 uint64_t Size = getContext().getTypeSize(VecTy); 3218 unsigned LargestVector = getNativeVectorSizeForAVXABI(AVXLevel); 3219 if (Size <= 64 || Size > LargestVector) 3220 return true; 3221 QualType EltTy = VecTy->getElementType(); 3222 if (passInt128VectorsInMem() && 3223 (EltTy->isSpecificBuiltinType(BuiltinType::Int128) || 3224 EltTy->isSpecificBuiltinType(BuiltinType::UInt128))) 3225 return true; 3226 } 3227 3228 return false; 3229 } 3230 3231 ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty, 3232 unsigned freeIntRegs) const { 3233 // If this is a scalar LLVM value then assume LLVM will pass it in the right 3234 // place naturally. 3235 // 3236 // This assumption is optimistic, as there could be free registers available 3237 // when we need to pass this argument in memory, and LLVM could try to pass 3238 // the argument in the free register. This does not seem to happen currently, 3239 // but this code would be much safer if we could mark the argument with 3240 // 'onstack'. See PR12193. 3241 if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty) && 3242 !Ty->isBitIntType()) { 3243 // Treat an enum type as its underlying type. 3244 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 3245 Ty = EnumTy->getDecl()->getIntegerType(); 3246 3247 return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty) 3248 : ABIArgInfo::getDirect()); 3249 } 3250 3251 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 3252 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 3253 3254 // Compute the byval alignment. We specify the alignment of the byval in all 3255 // cases so that the mid-level optimizer knows the alignment of the byval. 3256 unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U); 3257 3258 // Attempt to avoid passing indirect results using byval when possible. This 3259 // is important for good codegen. 3260 // 3261 // We do this by coercing the value into a scalar type which the backend can 3262 // handle naturally (i.e., without using byval). 3263 // 3264 // For simplicity, we currently only do this when we have exhausted all of the 3265 // free integer registers. Doing this when there are free integer registers 3266 // would require more care, as we would have to ensure that the coerced value 3267 // did not claim the unused register. That would require either reording the 3268 // arguments to the function (so that any subsequent inreg values came first), 3269 // or only doing this optimization when there were no following arguments that 3270 // might be inreg. 3271 // 3272 // We currently expect it to be rare (particularly in well written code) for 3273 // arguments to be passed on the stack when there are still free integer 3274 // registers available (this would typically imply large structs being passed 3275 // by value), so this seems like a fair tradeoff for now. 3276 // 3277 // We can revisit this if the backend grows support for 'onstack' parameter 3278 // attributes. See PR12193. 3279 if (freeIntRegs == 0) { 3280 uint64_t Size = getContext().getTypeSize(Ty); 3281 3282 // If this type fits in an eightbyte, coerce it into the matching integral 3283 // type, which will end up on the stack (with alignment 8). 3284 if (Align == 8 && Size <= 64) 3285 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 3286 Size)); 3287 } 3288 3289 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(Align)); 3290 } 3291 3292 /// The ABI specifies that a value should be passed in a full vector XMM/YMM 3293 /// register. Pick an LLVM IR type that will be passed as a vector register. 3294 llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const { 3295 // Wrapper structs/arrays that only contain vectors are passed just like 3296 // vectors; strip them off if present. 3297 if (const Type *InnerTy = isSingleElementStruct(Ty, getContext())) 3298 Ty = QualType(InnerTy, 0); 3299 3300 llvm::Type *IRType = CGT.ConvertType(Ty); 3301 if (isa<llvm::VectorType>(IRType)) { 3302 // Don't pass vXi128 vectors in their native type, the backend can't 3303 // legalize them. 3304 if (passInt128VectorsInMem() && 3305 cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy(128)) { 3306 // Use a vXi64 vector. 3307 uint64_t Size = getContext().getTypeSize(Ty); 3308 return llvm::FixedVectorType::get(llvm::Type::getInt64Ty(getVMContext()), 3309 Size / 64); 3310 } 3311 3312 return IRType; 3313 } 3314 3315 if (IRType->getTypeID() == llvm::Type::FP128TyID) 3316 return IRType; 3317 3318 // We couldn't find the preferred IR vector type for 'Ty'. 3319 uint64_t Size = getContext().getTypeSize(Ty); 3320 assert((Size == 128 || Size == 256 || Size == 512) && "Invalid type found!"); 3321 3322 3323 // Return a LLVM IR vector type based on the size of 'Ty'. 3324 return llvm::FixedVectorType::get(llvm::Type::getDoubleTy(getVMContext()), 3325 Size / 64); 3326 } 3327 3328 /// BitsContainNoUserData - Return true if the specified [start,end) bit range 3329 /// is known to either be off the end of the specified type or being in 3330 /// alignment padding. The user type specified is known to be at most 128 bits 3331 /// in size, and have passed through X86_64ABIInfo::classify with a successful 3332 /// classification that put one of the two halves in the INTEGER class. 3333 /// 3334 /// It is conservatively correct to return false. 3335 static bool BitsContainNoUserData(QualType Ty, unsigned StartBit, 3336 unsigned EndBit, ASTContext &Context) { 3337 // If the bytes being queried are off the end of the type, there is no user 3338 // data hiding here. This handles analysis of builtins, vectors and other 3339 // types that don't contain interesting padding. 3340 unsigned TySize = (unsigned)Context.getTypeSize(Ty); 3341 if (TySize <= StartBit) 3342 return true; 3343 3344 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) { 3345 unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType()); 3346 unsigned NumElts = (unsigned)AT->getSize().getZExtValue(); 3347 3348 // Check each element to see if the element overlaps with the queried range. 3349 for (unsigned i = 0; i != NumElts; ++i) { 3350 // If the element is after the span we care about, then we're done.. 3351 unsigned EltOffset = i*EltSize; 3352 if (EltOffset >= EndBit) break; 3353 3354 unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0; 3355 if (!BitsContainNoUserData(AT->getElementType(), EltStart, 3356 EndBit-EltOffset, Context)) 3357 return false; 3358 } 3359 // If it overlaps no elements, then it is safe to process as padding. 3360 return true; 3361 } 3362 3363 if (const RecordType *RT = Ty->getAs<RecordType>()) { 3364 const RecordDecl *RD = RT->getDecl(); 3365 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); 3366 3367 // If this is a C++ record, check the bases first. 3368 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 3369 for (const auto &I : CXXRD->bases()) { 3370 assert(!I.isVirtual() && !I.getType()->isDependentType() && 3371 "Unexpected base class!"); 3372 const auto *Base = 3373 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl()); 3374 3375 // If the base is after the span we care about, ignore it. 3376 unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base)); 3377 if (BaseOffset >= EndBit) continue; 3378 3379 unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0; 3380 if (!BitsContainNoUserData(I.getType(), BaseStart, 3381 EndBit-BaseOffset, Context)) 3382 return false; 3383 } 3384 } 3385 3386 // Verify that no field has data that overlaps the region of interest. Yes 3387 // this could be sped up a lot by being smarter about queried fields, 3388 // however we're only looking at structs up to 16 bytes, so we don't care 3389 // much. 3390 unsigned idx = 0; 3391 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 3392 i != e; ++i, ++idx) { 3393 unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx); 3394 3395 // If we found a field after the region we care about, then we're done. 3396 if (FieldOffset >= EndBit) break; 3397 3398 unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0; 3399 if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset, 3400 Context)) 3401 return false; 3402 } 3403 3404 // If nothing in this record overlapped the area of interest, then we're 3405 // clean. 3406 return true; 3407 } 3408 3409 return false; 3410 } 3411 3412 /// getFPTypeAtOffset - Return a floating point type at the specified offset. 3413 static llvm::Type *getFPTypeAtOffset(llvm::Type *IRType, unsigned IROffset, 3414 const llvm::DataLayout &TD) { 3415 if (IROffset == 0 && IRType->isFloatingPointTy()) 3416 return IRType; 3417 3418 // If this is a struct, recurse into the field at the specified offset. 3419 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) { 3420 if (!STy->getNumContainedTypes()) 3421 return nullptr; 3422 3423 const llvm::StructLayout *SL = TD.getStructLayout(STy); 3424 unsigned Elt = SL->getElementContainingOffset(IROffset); 3425 IROffset -= SL->getElementOffset(Elt); 3426 return getFPTypeAtOffset(STy->getElementType(Elt), IROffset, TD); 3427 } 3428 3429 // If this is an array, recurse into the field at the specified offset. 3430 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) { 3431 llvm::Type *EltTy = ATy->getElementType(); 3432 unsigned EltSize = TD.getTypeAllocSize(EltTy); 3433 IROffset -= IROffset / EltSize * EltSize; 3434 return getFPTypeAtOffset(EltTy, IROffset, TD); 3435 } 3436 3437 return nullptr; 3438 } 3439 3440 /// GetSSETypeAtOffset - Return a type that will be passed by the backend in the 3441 /// low 8 bytes of an XMM register, corresponding to the SSE class. 3442 llvm::Type *X86_64ABIInfo:: 3443 GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset, 3444 QualType SourceTy, unsigned SourceOffset) const { 3445 const llvm::DataLayout &TD = getDataLayout(); 3446 unsigned SourceSize = 3447 (unsigned)getContext().getTypeSize(SourceTy) / 8 - SourceOffset; 3448 llvm::Type *T0 = getFPTypeAtOffset(IRType, IROffset, TD); 3449 if (!T0 || T0->isDoubleTy()) 3450 return llvm::Type::getDoubleTy(getVMContext()); 3451 3452 // Get the adjacent FP type. 3453 llvm::Type *T1 = nullptr; 3454 unsigned T0Size = TD.getTypeAllocSize(T0); 3455 if (SourceSize > T0Size) 3456 T1 = getFPTypeAtOffset(IRType, IROffset + T0Size, TD); 3457 if (T1 == nullptr) { 3458 // Check if IRType is a half + float. float type will be in IROffset+4 due 3459 // to its alignment. 3460 if (T0->isHalfTy() && SourceSize > 4) 3461 T1 = getFPTypeAtOffset(IRType, IROffset + 4, TD); 3462 // If we can't get a second FP type, return a simple half or float. 3463 // avx512fp16-abi.c:pr51813_2 shows it works to return float for 3464 // {float, i8} too. 3465 if (T1 == nullptr) 3466 return T0; 3467 } 3468 3469 if (T0->isFloatTy() && T1->isFloatTy()) 3470 return llvm::FixedVectorType::get(T0, 2); 3471 3472 if (T0->isHalfTy() && T1->isHalfTy()) { 3473 llvm::Type *T2 = nullptr; 3474 if (SourceSize > 4) 3475 T2 = getFPTypeAtOffset(IRType, IROffset + 4, TD); 3476 if (T2 == nullptr) 3477 return llvm::FixedVectorType::get(T0, 2); 3478 return llvm::FixedVectorType::get(T0, 4); 3479 } 3480 3481 if (T0->isHalfTy() || T1->isHalfTy()) 3482 return llvm::FixedVectorType::get(llvm::Type::getHalfTy(getVMContext()), 4); 3483 3484 return llvm::Type::getDoubleTy(getVMContext()); 3485 } 3486 3487 3488 /// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in 3489 /// an 8-byte GPR. This means that we either have a scalar or we are talking 3490 /// about the high or low part of an up-to-16-byte struct. This routine picks 3491 /// the best LLVM IR type to represent this, which may be i64 or may be anything 3492 /// else that the backend will pass in a GPR that works better (e.g. i8, %foo*, 3493 /// etc). 3494 /// 3495 /// PrefType is an LLVM IR type that corresponds to (part of) the IR type for 3496 /// the source type. IROffset is an offset in bytes into the LLVM IR type that 3497 /// the 8-byte value references. PrefType may be null. 3498 /// 3499 /// SourceTy is the source-level type for the entire argument. SourceOffset is 3500 /// an offset into this that we're processing (which is always either 0 or 8). 3501 /// 3502 llvm::Type *X86_64ABIInfo:: 3503 GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset, 3504 QualType SourceTy, unsigned SourceOffset) const { 3505 // If we're dealing with an un-offset LLVM IR type, then it means that we're 3506 // returning an 8-byte unit starting with it. See if we can safely use it. 3507 if (IROffset == 0) { 3508 // Pointers and int64's always fill the 8-byte unit. 3509 if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) || 3510 IRType->isIntegerTy(64)) 3511 return IRType; 3512 3513 // If we have a 1/2/4-byte integer, we can use it only if the rest of the 3514 // goodness in the source type is just tail padding. This is allowed to 3515 // kick in for struct {double,int} on the int, but not on 3516 // struct{double,int,int} because we wouldn't return the second int. We 3517 // have to do this analysis on the source type because we can't depend on 3518 // unions being lowered a specific way etc. 3519 if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) || 3520 IRType->isIntegerTy(32) || 3521 (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) { 3522 unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 : 3523 cast<llvm::IntegerType>(IRType)->getBitWidth(); 3524 3525 if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth, 3526 SourceOffset*8+64, getContext())) 3527 return IRType; 3528 } 3529 } 3530 3531 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) { 3532 // If this is a struct, recurse into the field at the specified offset. 3533 const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy); 3534 if (IROffset < SL->getSizeInBytes()) { 3535 unsigned FieldIdx = SL->getElementContainingOffset(IROffset); 3536 IROffset -= SL->getElementOffset(FieldIdx); 3537 3538 return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset, 3539 SourceTy, SourceOffset); 3540 } 3541 } 3542 3543 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) { 3544 llvm::Type *EltTy = ATy->getElementType(); 3545 unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy); 3546 unsigned EltOffset = IROffset/EltSize*EltSize; 3547 return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy, 3548 SourceOffset); 3549 } 3550 3551 // Okay, we don't have any better idea of what to pass, so we pass this in an 3552 // integer register that isn't too big to fit the rest of the struct. 3553 unsigned TySizeInBytes = 3554 (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity(); 3555 3556 assert(TySizeInBytes != SourceOffset && "Empty field?"); 3557 3558 // It is always safe to classify this as an integer type up to i64 that 3559 // isn't larger than the structure. 3560 return llvm::IntegerType::get(getVMContext(), 3561 std::min(TySizeInBytes-SourceOffset, 8U)*8); 3562 } 3563 3564 3565 /// GetX86_64ByValArgumentPair - Given a high and low type that can ideally 3566 /// be used as elements of a two register pair to pass or return, return a 3567 /// first class aggregate to represent them. For example, if the low part of 3568 /// a by-value argument should be passed as i32* and the high part as float, 3569 /// return {i32*, float}. 3570 static llvm::Type * 3571 GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi, 3572 const llvm::DataLayout &TD) { 3573 // In order to correctly satisfy the ABI, we need to the high part to start 3574 // at offset 8. If the high and low parts we inferred are both 4-byte types 3575 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have 3576 // the second element at offset 8. Check for this: 3577 unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo); 3578 unsigned HiAlign = TD.getABITypeAlignment(Hi); 3579 unsigned HiStart = llvm::alignTo(LoSize, HiAlign); 3580 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!"); 3581 3582 // To handle this, we have to increase the size of the low part so that the 3583 // second element will start at an 8 byte offset. We can't increase the size 3584 // of the second element because it might make us access off the end of the 3585 // struct. 3586 if (HiStart != 8) { 3587 // There are usually two sorts of types the ABI generation code can produce 3588 // for the low part of a pair that aren't 8 bytes in size: half, float or 3589 // i8/i16/i32. This can also include pointers when they are 32-bit (X32 and 3590 // NaCl). 3591 // Promote these to a larger type. 3592 if (Lo->isHalfTy() || Lo->isFloatTy()) 3593 Lo = llvm::Type::getDoubleTy(Lo->getContext()); 3594 else { 3595 assert((Lo->isIntegerTy() || Lo->isPointerTy()) 3596 && "Invalid/unknown lo type"); 3597 Lo = llvm::Type::getInt64Ty(Lo->getContext()); 3598 } 3599 } 3600 3601 llvm::StructType *Result = llvm::StructType::get(Lo, Hi); 3602 3603 // Verify that the second element is at an 8-byte offset. 3604 assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 && 3605 "Invalid x86-64 argument pair!"); 3606 return Result; 3607 } 3608 3609 ABIArgInfo X86_64ABIInfo:: 3610 classifyReturnType(QualType RetTy) const { 3611 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the 3612 // classification algorithm. 3613 X86_64ABIInfo::Class Lo, Hi; 3614 classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true); 3615 3616 // Check some invariants. 3617 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification."); 3618 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification."); 3619 3620 llvm::Type *ResType = nullptr; 3621 switch (Lo) { 3622 case NoClass: 3623 if (Hi == NoClass) 3624 return ABIArgInfo::getIgnore(); 3625 // If the low part is just padding, it takes no register, leave ResType 3626 // null. 3627 assert((Hi == SSE || Hi == Integer || Hi == X87Up) && 3628 "Unknown missing lo part"); 3629 break; 3630 3631 case SSEUp: 3632 case X87Up: 3633 llvm_unreachable("Invalid classification for lo word."); 3634 3635 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via 3636 // hidden argument. 3637 case Memory: 3638 return getIndirectReturnResult(RetTy); 3639 3640 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next 3641 // available register of the sequence %rax, %rdx is used. 3642 case Integer: 3643 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0); 3644 3645 // If we have a sign or zero extended integer, make sure to return Extend 3646 // so that the parameter gets the right LLVM IR attributes. 3647 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) { 3648 // Treat an enum type as its underlying type. 3649 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 3650 RetTy = EnumTy->getDecl()->getIntegerType(); 3651 3652 if (RetTy->isIntegralOrEnumerationType() && 3653 isPromotableIntegerTypeForABI(RetTy)) 3654 return ABIArgInfo::getExtend(RetTy); 3655 } 3656 break; 3657 3658 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next 3659 // available SSE register of the sequence %xmm0, %xmm1 is used. 3660 case SSE: 3661 ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0); 3662 break; 3663 3664 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is 3665 // returned on the X87 stack in %st0 as 80-bit x87 number. 3666 case X87: 3667 ResType = llvm::Type::getX86_FP80Ty(getVMContext()); 3668 break; 3669 3670 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real 3671 // part of the value is returned in %st0 and the imaginary part in 3672 // %st1. 3673 case ComplexX87: 3674 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification."); 3675 ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()), 3676 llvm::Type::getX86_FP80Ty(getVMContext())); 3677 break; 3678 } 3679 3680 llvm::Type *HighPart = nullptr; 3681 switch (Hi) { 3682 // Memory was handled previously and X87 should 3683 // never occur as a hi class. 3684 case Memory: 3685 case X87: 3686 llvm_unreachable("Invalid classification for hi word."); 3687 3688 case ComplexX87: // Previously handled. 3689 case NoClass: 3690 break; 3691 3692 case Integer: 3693 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8); 3694 if (Lo == NoClass) // Return HighPart at offset 8 in memory. 3695 return ABIArgInfo::getDirect(HighPart, 8); 3696 break; 3697 case SSE: 3698 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8); 3699 if (Lo == NoClass) // Return HighPart at offset 8 in memory. 3700 return ABIArgInfo::getDirect(HighPart, 8); 3701 break; 3702 3703 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte 3704 // is passed in the next available eightbyte chunk if the last used 3705 // vector register. 3706 // 3707 // SSEUP should always be preceded by SSE, just widen. 3708 case SSEUp: 3709 assert(Lo == SSE && "Unexpected SSEUp classification."); 3710 ResType = GetByteVectorType(RetTy); 3711 break; 3712 3713 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is 3714 // returned together with the previous X87 value in %st0. 3715 case X87Up: 3716 // If X87Up is preceded by X87, we don't need to do 3717 // anything. However, in some cases with unions it may not be 3718 // preceded by X87. In such situations we follow gcc and pass the 3719 // extra bits in an SSE reg. 3720 if (Lo != X87) { 3721 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8); 3722 if (Lo == NoClass) // Return HighPart at offset 8 in memory. 3723 return ABIArgInfo::getDirect(HighPart, 8); 3724 } 3725 break; 3726 } 3727 3728 // If a high part was specified, merge it together with the low part. It is 3729 // known to pass in the high eightbyte of the result. We do this by forming a 3730 // first class struct aggregate with the high and low part: {low, high} 3731 if (HighPart) 3732 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout()); 3733 3734 return ABIArgInfo::getDirect(ResType); 3735 } 3736 3737 ABIArgInfo X86_64ABIInfo::classifyArgumentType( 3738 QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE, 3739 bool isNamedArg) 3740 const 3741 { 3742 Ty = useFirstFieldIfTransparentUnion(Ty); 3743 3744 X86_64ABIInfo::Class Lo, Hi; 3745 classify(Ty, 0, Lo, Hi, isNamedArg); 3746 3747 // Check some invariants. 3748 // FIXME: Enforce these by construction. 3749 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification."); 3750 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification."); 3751 3752 neededInt = 0; 3753 neededSSE = 0; 3754 llvm::Type *ResType = nullptr; 3755 switch (Lo) { 3756 case NoClass: 3757 if (Hi == NoClass) 3758 return ABIArgInfo::getIgnore(); 3759 // If the low part is just padding, it takes no register, leave ResType 3760 // null. 3761 assert((Hi == SSE || Hi == Integer || Hi == X87Up) && 3762 "Unknown missing lo part"); 3763 break; 3764 3765 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument 3766 // on the stack. 3767 case Memory: 3768 3769 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or 3770 // COMPLEX_X87, it is passed in memory. 3771 case X87: 3772 case ComplexX87: 3773 if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect) 3774 ++neededInt; 3775 return getIndirectResult(Ty, freeIntRegs); 3776 3777 case SSEUp: 3778 case X87Up: 3779 llvm_unreachable("Invalid classification for lo word."); 3780 3781 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next 3782 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8 3783 // and %r9 is used. 3784 case Integer: 3785 ++neededInt; 3786 3787 // Pick an 8-byte type based on the preferred type. 3788 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0); 3789 3790 // If we have a sign or zero extended integer, make sure to return Extend 3791 // so that the parameter gets the right LLVM IR attributes. 3792 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) { 3793 // Treat an enum type as its underlying type. 3794 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 3795 Ty = EnumTy->getDecl()->getIntegerType(); 3796 3797 if (Ty->isIntegralOrEnumerationType() && 3798 isPromotableIntegerTypeForABI(Ty)) 3799 return ABIArgInfo::getExtend(Ty); 3800 } 3801 3802 break; 3803 3804 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next 3805 // available SSE register is used, the registers are taken in the 3806 // order from %xmm0 to %xmm7. 3807 case SSE: { 3808 llvm::Type *IRType = CGT.ConvertType(Ty); 3809 ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0); 3810 ++neededSSE; 3811 break; 3812 } 3813 } 3814 3815 llvm::Type *HighPart = nullptr; 3816 switch (Hi) { 3817 // Memory was handled previously, ComplexX87 and X87 should 3818 // never occur as hi classes, and X87Up must be preceded by X87, 3819 // which is passed in memory. 3820 case Memory: 3821 case X87: 3822 case ComplexX87: 3823 llvm_unreachable("Invalid classification for hi word."); 3824 3825 case NoClass: break; 3826 3827 case Integer: 3828 ++neededInt; 3829 // Pick an 8-byte type based on the preferred type. 3830 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8); 3831 3832 if (Lo == NoClass) // Pass HighPart at offset 8 in memory. 3833 return ABIArgInfo::getDirect(HighPart, 8); 3834 break; 3835 3836 // X87Up generally doesn't occur here (long double is passed in 3837 // memory), except in situations involving unions. 3838 case X87Up: 3839 case SSE: 3840 HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8); 3841 3842 if (Lo == NoClass) // Pass HighPart at offset 8 in memory. 3843 return ABIArgInfo::getDirect(HighPart, 8); 3844 3845 ++neededSSE; 3846 break; 3847 3848 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the 3849 // eightbyte is passed in the upper half of the last used SSE 3850 // register. This only happens when 128-bit vectors are passed. 3851 case SSEUp: 3852 assert(Lo == SSE && "Unexpected SSEUp classification"); 3853 ResType = GetByteVectorType(Ty); 3854 break; 3855 } 3856 3857 // If a high part was specified, merge it together with the low part. It is 3858 // known to pass in the high eightbyte of the result. We do this by forming a 3859 // first class struct aggregate with the high and low part: {low, high} 3860 if (HighPart) 3861 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout()); 3862 3863 return ABIArgInfo::getDirect(ResType); 3864 } 3865 3866 ABIArgInfo 3867 X86_64ABIInfo::classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt, 3868 unsigned &NeededSSE) const { 3869 auto RT = Ty->getAs<RecordType>(); 3870 assert(RT && "classifyRegCallStructType only valid with struct types"); 3871 3872 if (RT->getDecl()->hasFlexibleArrayMember()) 3873 return getIndirectReturnResult(Ty); 3874 3875 // Sum up bases 3876 if (auto CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl())) { 3877 if (CXXRD->isDynamicClass()) { 3878 NeededInt = NeededSSE = 0; 3879 return getIndirectReturnResult(Ty); 3880 } 3881 3882 for (const auto &I : CXXRD->bases()) 3883 if (classifyRegCallStructTypeImpl(I.getType(), NeededInt, NeededSSE) 3884 .isIndirect()) { 3885 NeededInt = NeededSSE = 0; 3886 return getIndirectReturnResult(Ty); 3887 } 3888 } 3889 3890 // Sum up members 3891 for (const auto *FD : RT->getDecl()->fields()) { 3892 if (FD->getType()->isRecordType() && !FD->getType()->isUnionType()) { 3893 if (classifyRegCallStructTypeImpl(FD->getType(), NeededInt, NeededSSE) 3894 .isIndirect()) { 3895 NeededInt = NeededSSE = 0; 3896 return getIndirectReturnResult(Ty); 3897 } 3898 } else { 3899 unsigned LocalNeededInt, LocalNeededSSE; 3900 if (classifyArgumentType(FD->getType(), UINT_MAX, LocalNeededInt, 3901 LocalNeededSSE, true) 3902 .isIndirect()) { 3903 NeededInt = NeededSSE = 0; 3904 return getIndirectReturnResult(Ty); 3905 } 3906 NeededInt += LocalNeededInt; 3907 NeededSSE += LocalNeededSSE; 3908 } 3909 } 3910 3911 return ABIArgInfo::getDirect(); 3912 } 3913 3914 ABIArgInfo X86_64ABIInfo::classifyRegCallStructType(QualType Ty, 3915 unsigned &NeededInt, 3916 unsigned &NeededSSE) const { 3917 3918 NeededInt = 0; 3919 NeededSSE = 0; 3920 3921 return classifyRegCallStructTypeImpl(Ty, NeededInt, NeededSSE); 3922 } 3923 3924 void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const { 3925 3926 const unsigned CallingConv = FI.getCallingConvention(); 3927 // It is possible to force Win64 calling convention on any x86_64 target by 3928 // using __attribute__((ms_abi)). In such case to correctly emit Win64 3929 // compatible code delegate this call to WinX86_64ABIInfo::computeInfo. 3930 if (CallingConv == llvm::CallingConv::Win64) { 3931 WinX86_64ABIInfo Win64ABIInfo(CGT, AVXLevel); 3932 Win64ABIInfo.computeInfo(FI); 3933 return; 3934 } 3935 3936 bool IsRegCall = CallingConv == llvm::CallingConv::X86_RegCall; 3937 3938 // Keep track of the number of assigned registers. 3939 unsigned FreeIntRegs = IsRegCall ? 11 : 6; 3940 unsigned FreeSSERegs = IsRegCall ? 16 : 8; 3941 unsigned NeededInt, NeededSSE; 3942 3943 if (!::classifyReturnType(getCXXABI(), FI, *this)) { 3944 if (IsRegCall && FI.getReturnType()->getTypePtr()->isRecordType() && 3945 !FI.getReturnType()->getTypePtr()->isUnionType()) { 3946 FI.getReturnInfo() = 3947 classifyRegCallStructType(FI.getReturnType(), NeededInt, NeededSSE); 3948 if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) { 3949 FreeIntRegs -= NeededInt; 3950 FreeSSERegs -= NeededSSE; 3951 } else { 3952 FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType()); 3953 } 3954 } else if (IsRegCall && FI.getReturnType()->getAs<ComplexType>() && 3955 getContext().getCanonicalType(FI.getReturnType() 3956 ->getAs<ComplexType>() 3957 ->getElementType()) == 3958 getContext().LongDoubleTy) 3959 // Complex Long Double Type is passed in Memory when Regcall 3960 // calling convention is used. 3961 FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType()); 3962 else 3963 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 3964 } 3965 3966 // If the return value is indirect, then the hidden argument is consuming one 3967 // integer register. 3968 if (FI.getReturnInfo().isIndirect()) 3969 --FreeIntRegs; 3970 3971 // The chain argument effectively gives us another free register. 3972 if (FI.isChainCall()) 3973 ++FreeIntRegs; 3974 3975 unsigned NumRequiredArgs = FI.getNumRequiredArgs(); 3976 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers 3977 // get assigned (in left-to-right order) for passing as follows... 3978 unsigned ArgNo = 0; 3979 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end(); 3980 it != ie; ++it, ++ArgNo) { 3981 bool IsNamedArg = ArgNo < NumRequiredArgs; 3982 3983 if (IsRegCall && it->type->isStructureOrClassType()) 3984 it->info = classifyRegCallStructType(it->type, NeededInt, NeededSSE); 3985 else 3986 it->info = classifyArgumentType(it->type, FreeIntRegs, NeededInt, 3987 NeededSSE, IsNamedArg); 3988 3989 // AMD64-ABI 3.2.3p3: If there are no registers available for any 3990 // eightbyte of an argument, the whole argument is passed on the 3991 // stack. If registers have already been assigned for some 3992 // eightbytes of such an argument, the assignments get reverted. 3993 if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) { 3994 FreeIntRegs -= NeededInt; 3995 FreeSSERegs -= NeededSSE; 3996 } else { 3997 it->info = getIndirectResult(it->type, FreeIntRegs); 3998 } 3999 } 4000 } 4001 4002 static Address EmitX86_64VAArgFromMemory(CodeGenFunction &CGF, 4003 Address VAListAddr, QualType Ty) { 4004 Address overflow_arg_area_p = 4005 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_p"); 4006 llvm::Value *overflow_arg_area = 4007 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area"); 4008 4009 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16 4010 // byte boundary if alignment needed by type exceeds 8 byte boundary. 4011 // It isn't stated explicitly in the standard, but in practice we use 4012 // alignment greater than 16 where necessary. 4013 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty); 4014 if (Align > CharUnits::fromQuantity(8)) { 4015 overflow_arg_area = emitRoundPointerUpToAlignment(CGF, overflow_arg_area, 4016 Align); 4017 } 4018 4019 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area. 4020 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty); 4021 llvm::Value *Res = 4022 CGF.Builder.CreateBitCast(overflow_arg_area, 4023 llvm::PointerType::getUnqual(LTy)); 4024 4025 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to: 4026 // l->overflow_arg_area + sizeof(type). 4027 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to 4028 // an 8 byte boundary. 4029 4030 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8; 4031 llvm::Value *Offset = 4032 llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7); 4033 overflow_arg_area = CGF.Builder.CreateGEP(CGF.Int8Ty, overflow_arg_area, 4034 Offset, "overflow_arg_area.next"); 4035 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p); 4036 4037 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type. 4038 return Address(Res, LTy, Align); 4039 } 4040 4041 Address X86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 4042 QualType Ty) const { 4043 // Assume that va_list type is correct; should be pointer to LLVM type: 4044 // struct { 4045 // i32 gp_offset; 4046 // i32 fp_offset; 4047 // i8* overflow_arg_area; 4048 // i8* reg_save_area; 4049 // }; 4050 unsigned neededInt, neededSSE; 4051 4052 Ty = getContext().getCanonicalType(Ty); 4053 ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE, 4054 /*isNamedArg*/false); 4055 4056 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed 4057 // in the registers. If not go to step 7. 4058 if (!neededInt && !neededSSE) 4059 return EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty); 4060 4061 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of 4062 // general purpose registers needed to pass type and num_fp to hold 4063 // the number of floating point registers needed. 4064 4065 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into 4066 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or 4067 // l->fp_offset > 304 - num_fp * 16 go to step 7. 4068 // 4069 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of 4070 // register save space). 4071 4072 llvm::Value *InRegs = nullptr; 4073 Address gp_offset_p = Address::invalid(), fp_offset_p = Address::invalid(); 4074 llvm::Value *gp_offset = nullptr, *fp_offset = nullptr; 4075 if (neededInt) { 4076 gp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "gp_offset_p"); 4077 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset"); 4078 InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8); 4079 InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp"); 4080 } 4081 4082 if (neededSSE) { 4083 fp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 1, "fp_offset_p"); 4084 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset"); 4085 llvm::Value *FitsInFP = 4086 llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16); 4087 FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp"); 4088 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP; 4089 } 4090 4091 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg"); 4092 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem"); 4093 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end"); 4094 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock); 4095 4096 // Emit code to load the value if it was passed in registers. 4097 4098 CGF.EmitBlock(InRegBlock); 4099 4100 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with 4101 // an offset of l->gp_offset and/or l->fp_offset. This may require 4102 // copying to a temporary location in case the parameter is passed 4103 // in different register classes or requires an alignment greater 4104 // than 8 for general purpose registers and 16 for XMM registers. 4105 // 4106 // FIXME: This really results in shameful code when we end up needing to 4107 // collect arguments from different places; often what should result in a 4108 // simple assembling of a structure from scattered addresses has many more 4109 // loads than necessary. Can we clean this up? 4110 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty); 4111 llvm::Value *RegSaveArea = CGF.Builder.CreateLoad( 4112 CGF.Builder.CreateStructGEP(VAListAddr, 3), "reg_save_area"); 4113 4114 Address RegAddr = Address::invalid(); 4115 if (neededInt && neededSSE) { 4116 // FIXME: Cleanup. 4117 assert(AI.isDirect() && "Unexpected ABI info for mixed regs"); 4118 llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType()); 4119 Address Tmp = CGF.CreateMemTemp(Ty); 4120 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST); 4121 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs"); 4122 llvm::Type *TyLo = ST->getElementType(0); 4123 llvm::Type *TyHi = ST->getElementType(1); 4124 assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) && 4125 "Unexpected ABI info for mixed regs"); 4126 llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo); 4127 llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi); 4128 llvm::Value *GPAddr = 4129 CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, gp_offset); 4130 llvm::Value *FPAddr = 4131 CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, fp_offset); 4132 llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr; 4133 llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr; 4134 4135 // Copy the first element. 4136 // FIXME: Our choice of alignment here and below is probably pessimistic. 4137 llvm::Value *V = CGF.Builder.CreateAlignedLoad( 4138 TyLo, CGF.Builder.CreateBitCast(RegLoAddr, PTyLo), 4139 CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyLo))); 4140 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0)); 4141 4142 // Copy the second element. 4143 V = CGF.Builder.CreateAlignedLoad( 4144 TyHi, CGF.Builder.CreateBitCast(RegHiAddr, PTyHi), 4145 CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyHi))); 4146 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1)); 4147 4148 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy); 4149 } else if (neededInt) { 4150 RegAddr = Address(CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, gp_offset), 4151 CGF.Int8Ty, CharUnits::fromQuantity(8)); 4152 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy); 4153 4154 // Copy to a temporary if necessary to ensure the appropriate alignment. 4155 auto TInfo = getContext().getTypeInfoInChars(Ty); 4156 uint64_t TySize = TInfo.Width.getQuantity(); 4157 CharUnits TyAlign = TInfo.Align; 4158 4159 // Copy into a temporary if the type is more aligned than the 4160 // register save area. 4161 if (TyAlign.getQuantity() > 8) { 4162 Address Tmp = CGF.CreateMemTemp(Ty); 4163 CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, false); 4164 RegAddr = Tmp; 4165 } 4166 4167 } else if (neededSSE == 1) { 4168 RegAddr = Address(CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, fp_offset), 4169 CGF.Int8Ty, CharUnits::fromQuantity(16)); 4170 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy); 4171 } else { 4172 assert(neededSSE == 2 && "Invalid number of needed registers!"); 4173 // SSE registers are spaced 16 bytes apart in the register save 4174 // area, we need to collect the two eightbytes together. 4175 // The ABI isn't explicit about this, but it seems reasonable 4176 // to assume that the slots are 16-byte aligned, since the stack is 4177 // naturally 16-byte aligned and the prologue is expected to store 4178 // all the SSE registers to the RSA. 4179 Address RegAddrLo = Address(CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, 4180 fp_offset), 4181 CGF.Int8Ty, CharUnits::fromQuantity(16)); 4182 Address RegAddrHi = 4183 CGF.Builder.CreateConstInBoundsByteGEP(RegAddrLo, 4184 CharUnits::fromQuantity(16)); 4185 llvm::Type *ST = AI.canHaveCoerceToType() 4186 ? AI.getCoerceToType() 4187 : llvm::StructType::get(CGF.DoubleTy, CGF.DoubleTy); 4188 llvm::Value *V; 4189 Address Tmp = CGF.CreateMemTemp(Ty); 4190 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST); 4191 V = CGF.Builder.CreateLoad(CGF.Builder.CreateElementBitCast( 4192 RegAddrLo, ST->getStructElementType(0))); 4193 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0)); 4194 V = CGF.Builder.CreateLoad(CGF.Builder.CreateElementBitCast( 4195 RegAddrHi, ST->getStructElementType(1))); 4196 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1)); 4197 4198 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy); 4199 } 4200 4201 // AMD64-ABI 3.5.7p5: Step 5. Set: 4202 // l->gp_offset = l->gp_offset + num_gp * 8 4203 // l->fp_offset = l->fp_offset + num_fp * 16. 4204 if (neededInt) { 4205 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8); 4206 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset), 4207 gp_offset_p); 4208 } 4209 if (neededSSE) { 4210 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16); 4211 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset), 4212 fp_offset_p); 4213 } 4214 CGF.EmitBranch(ContBlock); 4215 4216 // Emit code to load the value if it was passed in memory. 4217 4218 CGF.EmitBlock(InMemBlock); 4219 Address MemAddr = EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty); 4220 4221 // Return the appropriate result. 4222 4223 CGF.EmitBlock(ContBlock); 4224 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, MemAddr, InMemBlock, 4225 "vaarg.addr"); 4226 return ResAddr; 4227 } 4228 4229 Address X86_64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr, 4230 QualType Ty) const { 4231 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is 4232 // not 1, 2, 4, or 8 bytes, must be passed by reference." 4233 uint64_t Width = getContext().getTypeSize(Ty); 4234 bool IsIndirect = Width > 64 || !llvm::isPowerOf2_64(Width); 4235 4236 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, 4237 CGF.getContext().getTypeInfoInChars(Ty), 4238 CharUnits::fromQuantity(8), 4239 /*allowHigherAlign*/ false); 4240 } 4241 4242 ABIArgInfo WinX86_64ABIInfo::reclassifyHvaArgForVectorCall( 4243 QualType Ty, unsigned &FreeSSERegs, const ABIArgInfo ¤t) const { 4244 const Type *Base = nullptr; 4245 uint64_t NumElts = 0; 4246 4247 if (!Ty->isBuiltinType() && !Ty->isVectorType() && 4248 isHomogeneousAggregate(Ty, Base, NumElts) && FreeSSERegs >= NumElts) { 4249 FreeSSERegs -= NumElts; 4250 return getDirectX86Hva(); 4251 } 4252 return current; 4253 } 4254 4255 ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, unsigned &FreeSSERegs, 4256 bool IsReturnType, bool IsVectorCall, 4257 bool IsRegCall) const { 4258 4259 if (Ty->isVoidType()) 4260 return ABIArgInfo::getIgnore(); 4261 4262 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 4263 Ty = EnumTy->getDecl()->getIntegerType(); 4264 4265 TypeInfo Info = getContext().getTypeInfo(Ty); 4266 uint64_t Width = Info.Width; 4267 CharUnits Align = getContext().toCharUnitsFromBits(Info.Align); 4268 4269 const RecordType *RT = Ty->getAs<RecordType>(); 4270 if (RT) { 4271 if (!IsReturnType) { 4272 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI())) 4273 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 4274 } 4275 4276 if (RT->getDecl()->hasFlexibleArrayMember()) 4277 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 4278 4279 } 4280 4281 const Type *Base = nullptr; 4282 uint64_t NumElts = 0; 4283 // vectorcall adds the concept of a homogenous vector aggregate, similar to 4284 // other targets. 4285 if ((IsVectorCall || IsRegCall) && 4286 isHomogeneousAggregate(Ty, Base, NumElts)) { 4287 if (IsRegCall) { 4288 if (FreeSSERegs >= NumElts) { 4289 FreeSSERegs -= NumElts; 4290 if (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType()) 4291 return ABIArgInfo::getDirect(); 4292 return ABIArgInfo::getExpand(); 4293 } 4294 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false); 4295 } else if (IsVectorCall) { 4296 if (FreeSSERegs >= NumElts && 4297 (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())) { 4298 FreeSSERegs -= NumElts; 4299 return ABIArgInfo::getDirect(); 4300 } else if (IsReturnType) { 4301 return ABIArgInfo::getExpand(); 4302 } else if (!Ty->isBuiltinType() && !Ty->isVectorType()) { 4303 // HVAs are delayed and reclassified in the 2nd step. 4304 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false); 4305 } 4306 } 4307 } 4308 4309 if (Ty->isMemberPointerType()) { 4310 // If the member pointer is represented by an LLVM int or ptr, pass it 4311 // directly. 4312 llvm::Type *LLTy = CGT.ConvertType(Ty); 4313 if (LLTy->isPointerTy() || LLTy->isIntegerTy()) 4314 return ABIArgInfo::getDirect(); 4315 } 4316 4317 if (RT || Ty->isAnyComplexType() || Ty->isMemberPointerType()) { 4318 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is 4319 // not 1, 2, 4, or 8 bytes, must be passed by reference." 4320 if (Width > 64 || !llvm::isPowerOf2_64(Width)) 4321 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 4322 4323 // Otherwise, coerce it to a small integer. 4324 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Width)); 4325 } 4326 4327 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) { 4328 switch (BT->getKind()) { 4329 case BuiltinType::Bool: 4330 // Bool type is always extended to the ABI, other builtin types are not 4331 // extended. 4332 return ABIArgInfo::getExtend(Ty); 4333 4334 case BuiltinType::LongDouble: 4335 // Mingw64 GCC uses the old 80 bit extended precision floating point 4336 // unit. It passes them indirectly through memory. 4337 if (IsMingw64) { 4338 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat(); 4339 if (LDF == &llvm::APFloat::x87DoubleExtended()) 4340 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false); 4341 } 4342 break; 4343 4344 case BuiltinType::Int128: 4345 case BuiltinType::UInt128: 4346 // If it's a parameter type, the normal ABI rule is that arguments larger 4347 // than 8 bytes are passed indirectly. GCC follows it. We follow it too, 4348 // even though it isn't particularly efficient. 4349 if (!IsReturnType) 4350 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false); 4351 4352 // Mingw64 GCC returns i128 in XMM0. Coerce to v2i64 to handle that. 4353 // Clang matches them for compatibility. 4354 return ABIArgInfo::getDirect(llvm::FixedVectorType::get( 4355 llvm::Type::getInt64Ty(getVMContext()), 2)); 4356 4357 default: 4358 break; 4359 } 4360 } 4361 4362 if (Ty->isBitIntType()) { 4363 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is 4364 // not 1, 2, 4, or 8 bytes, must be passed by reference." 4365 // However, non-power-of-two bit-precise integers will be passed as 1, 2, 4, 4366 // or 8 bytes anyway as long is it fits in them, so we don't have to check 4367 // the power of 2. 4368 if (Width <= 64) 4369 return ABIArgInfo::getDirect(); 4370 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false); 4371 } 4372 4373 return ABIArgInfo::getDirect(); 4374 } 4375 4376 void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const { 4377 const unsigned CC = FI.getCallingConvention(); 4378 bool IsVectorCall = CC == llvm::CallingConv::X86_VectorCall; 4379 bool IsRegCall = CC == llvm::CallingConv::X86_RegCall; 4380 4381 // If __attribute__((sysv_abi)) is in use, use the SysV argument 4382 // classification rules. 4383 if (CC == llvm::CallingConv::X86_64_SysV) { 4384 X86_64ABIInfo SysVABIInfo(CGT, AVXLevel); 4385 SysVABIInfo.computeInfo(FI); 4386 return; 4387 } 4388 4389 unsigned FreeSSERegs = 0; 4390 if (IsVectorCall) { 4391 // We can use up to 4 SSE return registers with vectorcall. 4392 FreeSSERegs = 4; 4393 } else if (IsRegCall) { 4394 // RegCall gives us 16 SSE registers. 4395 FreeSSERegs = 16; 4396 } 4397 4398 if (!getCXXABI().classifyReturnType(FI)) 4399 FI.getReturnInfo() = classify(FI.getReturnType(), FreeSSERegs, true, 4400 IsVectorCall, IsRegCall); 4401 4402 if (IsVectorCall) { 4403 // We can use up to 6 SSE register parameters with vectorcall. 4404 FreeSSERegs = 6; 4405 } else if (IsRegCall) { 4406 // RegCall gives us 16 SSE registers, we can reuse the return registers. 4407 FreeSSERegs = 16; 4408 } 4409 4410 unsigned ArgNum = 0; 4411 unsigned ZeroSSERegs = 0; 4412 for (auto &I : FI.arguments()) { 4413 // Vectorcall in x64 only permits the first 6 arguments to be passed as 4414 // XMM/YMM registers. After the sixth argument, pretend no vector 4415 // registers are left. 4416 unsigned *MaybeFreeSSERegs = 4417 (IsVectorCall && ArgNum >= 6) ? &ZeroSSERegs : &FreeSSERegs; 4418 I.info = 4419 classify(I.type, *MaybeFreeSSERegs, false, IsVectorCall, IsRegCall); 4420 ++ArgNum; 4421 } 4422 4423 if (IsVectorCall) { 4424 // For vectorcall, assign aggregate HVAs to any free vector registers in a 4425 // second pass. 4426 for (auto &I : FI.arguments()) 4427 I.info = reclassifyHvaArgForVectorCall(I.type, FreeSSERegs, I.info); 4428 } 4429 } 4430 4431 Address WinX86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 4432 QualType Ty) const { 4433 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is 4434 // not 1, 2, 4, or 8 bytes, must be passed by reference." 4435 uint64_t Width = getContext().getTypeSize(Ty); 4436 bool IsIndirect = Width > 64 || !llvm::isPowerOf2_64(Width); 4437 4438 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, 4439 CGF.getContext().getTypeInfoInChars(Ty), 4440 CharUnits::fromQuantity(8), 4441 /*allowHigherAlign*/ false); 4442 } 4443 4444 static bool PPC_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 4445 llvm::Value *Address, bool Is64Bit, 4446 bool IsAIX) { 4447 // This is calculated from the LLVM and GCC tables and verified 4448 // against gcc output. AFAIK all PPC ABIs use the same encoding. 4449 4450 CodeGen::CGBuilderTy &Builder = CGF.Builder; 4451 4452 llvm::IntegerType *i8 = CGF.Int8Ty; 4453 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4); 4454 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8); 4455 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16); 4456 4457 // 0-31: r0-31, the 4-byte or 8-byte general-purpose registers 4458 AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 0, 31); 4459 4460 // 32-63: fp0-31, the 8-byte floating-point registers 4461 AssignToArrayRange(Builder, Address, Eight8, 32, 63); 4462 4463 // 64-67 are various 4-byte or 8-byte special-purpose registers: 4464 // 64: mq 4465 // 65: lr 4466 // 66: ctr 4467 // 67: ap 4468 AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 64, 67); 4469 4470 // 68-76 are various 4-byte special-purpose registers: 4471 // 68-75 cr0-7 4472 // 76: xer 4473 AssignToArrayRange(Builder, Address, Four8, 68, 76); 4474 4475 // 77-108: v0-31, the 16-byte vector registers 4476 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108); 4477 4478 // 109: vrsave 4479 // 110: vscr 4480 AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 109, 110); 4481 4482 // AIX does not utilize the rest of the registers. 4483 if (IsAIX) 4484 return false; 4485 4486 // 111: spe_acc 4487 // 112: spefscr 4488 // 113: sfp 4489 AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 111, 113); 4490 4491 if (!Is64Bit) 4492 return false; 4493 4494 // TODO: Need to verify if these registers are used on 64 bit AIX with Power8 4495 // or above CPU. 4496 // 64-bit only registers: 4497 // 114: tfhar 4498 // 115: tfiar 4499 // 116: texasr 4500 AssignToArrayRange(Builder, Address, Eight8, 114, 116); 4501 4502 return false; 4503 } 4504 4505 // AIX 4506 namespace { 4507 /// AIXABIInfo - The AIX XCOFF ABI information. 4508 class AIXABIInfo : public ABIInfo { 4509 const bool Is64Bit; 4510 const unsigned PtrByteSize; 4511 CharUnits getParamTypeAlignment(QualType Ty) const; 4512 4513 public: 4514 AIXABIInfo(CodeGen::CodeGenTypes &CGT, bool Is64Bit) 4515 : ABIInfo(CGT), Is64Bit(Is64Bit), PtrByteSize(Is64Bit ? 8 : 4) {} 4516 4517 bool isPromotableTypeForABI(QualType Ty) const; 4518 4519 ABIArgInfo classifyReturnType(QualType RetTy) const; 4520 ABIArgInfo classifyArgumentType(QualType Ty) const; 4521 4522 void computeInfo(CGFunctionInfo &FI) const override { 4523 if (!getCXXABI().classifyReturnType(FI)) 4524 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 4525 4526 for (auto &I : FI.arguments()) 4527 I.info = classifyArgumentType(I.type); 4528 } 4529 4530 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 4531 QualType Ty) const override; 4532 }; 4533 4534 class AIXTargetCodeGenInfo : public TargetCodeGenInfo { 4535 const bool Is64Bit; 4536 4537 public: 4538 AIXTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool Is64Bit) 4539 : TargetCodeGenInfo(std::make_unique<AIXABIInfo>(CGT, Is64Bit)), 4540 Is64Bit(Is64Bit) {} 4541 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 4542 return 1; // r1 is the dedicated stack pointer 4543 } 4544 4545 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 4546 llvm::Value *Address) const override; 4547 }; 4548 } // namespace 4549 4550 // Return true if the ABI requires Ty to be passed sign- or zero- 4551 // extended to 32/64 bits. 4552 bool AIXABIInfo::isPromotableTypeForABI(QualType Ty) const { 4553 // Treat an enum type as its underlying type. 4554 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 4555 Ty = EnumTy->getDecl()->getIntegerType(); 4556 4557 // Promotable integer types are required to be promoted by the ABI. 4558 if (Ty->isPromotableIntegerType()) 4559 return true; 4560 4561 if (!Is64Bit) 4562 return false; 4563 4564 // For 64 bit mode, in addition to the usual promotable integer types, we also 4565 // need to extend all 32-bit types, since the ABI requires promotion to 64 4566 // bits. 4567 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) 4568 switch (BT->getKind()) { 4569 case BuiltinType::Int: 4570 case BuiltinType::UInt: 4571 return true; 4572 default: 4573 break; 4574 } 4575 4576 return false; 4577 } 4578 4579 ABIArgInfo AIXABIInfo::classifyReturnType(QualType RetTy) const { 4580 if (RetTy->isAnyComplexType()) 4581 return ABIArgInfo::getDirect(); 4582 4583 if (RetTy->isVectorType()) 4584 return ABIArgInfo::getDirect(); 4585 4586 if (RetTy->isVoidType()) 4587 return ABIArgInfo::getIgnore(); 4588 4589 if (isAggregateTypeForABI(RetTy)) 4590 return getNaturalAlignIndirect(RetTy); 4591 4592 return (isPromotableTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy) 4593 : ABIArgInfo::getDirect()); 4594 } 4595 4596 ABIArgInfo AIXABIInfo::classifyArgumentType(QualType Ty) const { 4597 Ty = useFirstFieldIfTransparentUnion(Ty); 4598 4599 if (Ty->isAnyComplexType()) 4600 return ABIArgInfo::getDirect(); 4601 4602 if (Ty->isVectorType()) 4603 return ABIArgInfo::getDirect(); 4604 4605 if (isAggregateTypeForABI(Ty)) { 4606 // Records with non-trivial destructors/copy-constructors should not be 4607 // passed by value. 4608 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 4609 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 4610 4611 CharUnits CCAlign = getParamTypeAlignment(Ty); 4612 CharUnits TyAlign = getContext().getTypeAlignInChars(Ty); 4613 4614 return ABIArgInfo::getIndirect(CCAlign, /*ByVal*/ true, 4615 /*Realign*/ TyAlign > CCAlign); 4616 } 4617 4618 return (isPromotableTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty) 4619 : ABIArgInfo::getDirect()); 4620 } 4621 4622 CharUnits AIXABIInfo::getParamTypeAlignment(QualType Ty) const { 4623 // Complex types are passed just like their elements. 4624 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) 4625 Ty = CTy->getElementType(); 4626 4627 if (Ty->isVectorType()) 4628 return CharUnits::fromQuantity(16); 4629 4630 // If the structure contains a vector type, the alignment is 16. 4631 if (isRecordWithSIMDVectorType(getContext(), Ty)) 4632 return CharUnits::fromQuantity(16); 4633 4634 return CharUnits::fromQuantity(PtrByteSize); 4635 } 4636 4637 Address AIXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 4638 QualType Ty) const { 4639 4640 auto TypeInfo = getContext().getTypeInfoInChars(Ty); 4641 TypeInfo.Align = getParamTypeAlignment(Ty); 4642 4643 CharUnits SlotSize = CharUnits::fromQuantity(PtrByteSize); 4644 4645 // If we have a complex type and the base type is smaller than the register 4646 // size, the ABI calls for the real and imaginary parts to be right-adjusted 4647 // in separate words in 32bit mode or doublewords in 64bit mode. However, 4648 // Clang expects us to produce a pointer to a structure with the two parts 4649 // packed tightly. So generate loads of the real and imaginary parts relative 4650 // to the va_list pointer, and store them to a temporary structure. We do the 4651 // same as the PPC64ABI here. 4652 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) { 4653 CharUnits EltSize = TypeInfo.Width / 2; 4654 if (EltSize < SlotSize) 4655 return complexTempStructure(CGF, VAListAddr, Ty, SlotSize, EltSize, CTy); 4656 } 4657 4658 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false, TypeInfo, 4659 SlotSize, /*AllowHigher*/ true); 4660 } 4661 4662 bool AIXTargetCodeGenInfo::initDwarfEHRegSizeTable( 4663 CodeGen::CodeGenFunction &CGF, llvm::Value *Address) const { 4664 return PPC_initDwarfEHRegSizeTable(CGF, Address, Is64Bit, /*IsAIX*/ true); 4665 } 4666 4667 // PowerPC-32 4668 namespace { 4669 /// PPC32_SVR4_ABIInfo - The 32-bit PowerPC ELF (SVR4) ABI information. 4670 class PPC32_SVR4_ABIInfo : public DefaultABIInfo { 4671 bool IsSoftFloatABI; 4672 bool IsRetSmallStructInRegABI; 4673 4674 CharUnits getParamTypeAlignment(QualType Ty) const; 4675 4676 public: 4677 PPC32_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, bool SoftFloatABI, 4678 bool RetSmallStructInRegABI) 4679 : DefaultABIInfo(CGT), IsSoftFloatABI(SoftFloatABI), 4680 IsRetSmallStructInRegABI(RetSmallStructInRegABI) {} 4681 4682 ABIArgInfo classifyReturnType(QualType RetTy) const; 4683 4684 void computeInfo(CGFunctionInfo &FI) const override { 4685 if (!getCXXABI().classifyReturnType(FI)) 4686 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 4687 for (auto &I : FI.arguments()) 4688 I.info = classifyArgumentType(I.type); 4689 } 4690 4691 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 4692 QualType Ty) const override; 4693 }; 4694 4695 class PPC32TargetCodeGenInfo : public TargetCodeGenInfo { 4696 public: 4697 PPC32TargetCodeGenInfo(CodeGenTypes &CGT, bool SoftFloatABI, 4698 bool RetSmallStructInRegABI) 4699 : TargetCodeGenInfo(std::make_unique<PPC32_SVR4_ABIInfo>( 4700 CGT, SoftFloatABI, RetSmallStructInRegABI)) {} 4701 4702 static bool isStructReturnInRegABI(const llvm::Triple &Triple, 4703 const CodeGenOptions &Opts); 4704 4705 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 4706 // This is recovered from gcc output. 4707 return 1; // r1 is the dedicated stack pointer 4708 } 4709 4710 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 4711 llvm::Value *Address) const override; 4712 }; 4713 } 4714 4715 CharUnits PPC32_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const { 4716 // Complex types are passed just like their elements. 4717 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) 4718 Ty = CTy->getElementType(); 4719 4720 if (Ty->isVectorType()) 4721 return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16 4722 : 4); 4723 4724 // For single-element float/vector structs, we consider the whole type 4725 // to have the same alignment requirements as its single element. 4726 const Type *AlignTy = nullptr; 4727 if (const Type *EltType = isSingleElementStruct(Ty, getContext())) { 4728 const BuiltinType *BT = EltType->getAs<BuiltinType>(); 4729 if ((EltType->isVectorType() && getContext().getTypeSize(EltType) == 128) || 4730 (BT && BT->isFloatingPoint())) 4731 AlignTy = EltType; 4732 } 4733 4734 if (AlignTy) 4735 return CharUnits::fromQuantity(AlignTy->isVectorType() ? 16 : 4); 4736 return CharUnits::fromQuantity(4); 4737 } 4738 4739 ABIArgInfo PPC32_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const { 4740 uint64_t Size; 4741 4742 // -msvr4-struct-return puts small aggregates in GPR3 and GPR4. 4743 if (isAggregateTypeForABI(RetTy) && IsRetSmallStructInRegABI && 4744 (Size = getContext().getTypeSize(RetTy)) <= 64) { 4745 // System V ABI (1995), page 3-22, specified: 4746 // > A structure or union whose size is less than or equal to 8 bytes 4747 // > shall be returned in r3 and r4, as if it were first stored in the 4748 // > 8-byte aligned memory area and then the low addressed word were 4749 // > loaded into r3 and the high-addressed word into r4. Bits beyond 4750 // > the last member of the structure or union are not defined. 4751 // 4752 // GCC for big-endian PPC32 inserts the pad before the first member, 4753 // not "beyond the last member" of the struct. To stay compatible 4754 // with GCC, we coerce the struct to an integer of the same size. 4755 // LLVM will extend it and return i32 in r3, or i64 in r3:r4. 4756 if (Size == 0) 4757 return ABIArgInfo::getIgnore(); 4758 else { 4759 llvm::Type *CoerceTy = llvm::Type::getIntNTy(getVMContext(), Size); 4760 return ABIArgInfo::getDirect(CoerceTy); 4761 } 4762 } 4763 4764 return DefaultABIInfo::classifyReturnType(RetTy); 4765 } 4766 4767 // TODO: this implementation is now likely redundant with 4768 // DefaultABIInfo::EmitVAArg. 4769 Address PPC32_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAList, 4770 QualType Ty) const { 4771 if (getTarget().getTriple().isOSDarwin()) { 4772 auto TI = getContext().getTypeInfoInChars(Ty); 4773 TI.Align = getParamTypeAlignment(Ty); 4774 4775 CharUnits SlotSize = CharUnits::fromQuantity(4); 4776 return emitVoidPtrVAArg(CGF, VAList, Ty, 4777 classifyArgumentType(Ty).isIndirect(), TI, SlotSize, 4778 /*AllowHigherAlign=*/true); 4779 } 4780 4781 const unsigned OverflowLimit = 8; 4782 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) { 4783 // TODO: Implement this. For now ignore. 4784 (void)CTy; 4785 return Address::invalid(); // FIXME? 4786 } 4787 4788 // struct __va_list_tag { 4789 // unsigned char gpr; 4790 // unsigned char fpr; 4791 // unsigned short reserved; 4792 // void *overflow_arg_area; 4793 // void *reg_save_area; 4794 // }; 4795 4796 bool isI64 = Ty->isIntegerType() && getContext().getTypeSize(Ty) == 64; 4797 bool isInt = !Ty->isFloatingType(); 4798 bool isF64 = Ty->isFloatingType() && getContext().getTypeSize(Ty) == 64; 4799 4800 // All aggregates are passed indirectly? That doesn't seem consistent 4801 // with the argument-lowering code. 4802 bool isIndirect = isAggregateTypeForABI(Ty); 4803 4804 CGBuilderTy &Builder = CGF.Builder; 4805 4806 // The calling convention either uses 1-2 GPRs or 1 FPR. 4807 Address NumRegsAddr = Address::invalid(); 4808 if (isInt || IsSoftFloatABI) { 4809 NumRegsAddr = Builder.CreateStructGEP(VAList, 0, "gpr"); 4810 } else { 4811 NumRegsAddr = Builder.CreateStructGEP(VAList, 1, "fpr"); 4812 } 4813 4814 llvm::Value *NumRegs = Builder.CreateLoad(NumRegsAddr, "numUsedRegs"); 4815 4816 // "Align" the register count when TY is i64. 4817 if (isI64 || (isF64 && IsSoftFloatABI)) { 4818 NumRegs = Builder.CreateAdd(NumRegs, Builder.getInt8(1)); 4819 NumRegs = Builder.CreateAnd(NumRegs, Builder.getInt8((uint8_t) ~1U)); 4820 } 4821 4822 llvm::Value *CC = 4823 Builder.CreateICmpULT(NumRegs, Builder.getInt8(OverflowLimit), "cond"); 4824 4825 llvm::BasicBlock *UsingRegs = CGF.createBasicBlock("using_regs"); 4826 llvm::BasicBlock *UsingOverflow = CGF.createBasicBlock("using_overflow"); 4827 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont"); 4828 4829 Builder.CreateCondBr(CC, UsingRegs, UsingOverflow); 4830 4831 llvm::Type *DirectTy = CGF.ConvertType(Ty); 4832 if (isIndirect) DirectTy = DirectTy->getPointerTo(0); 4833 4834 // Case 1: consume registers. 4835 Address RegAddr = Address::invalid(); 4836 { 4837 CGF.EmitBlock(UsingRegs); 4838 4839 Address RegSaveAreaPtr = Builder.CreateStructGEP(VAList, 4); 4840 RegAddr = Address(Builder.CreateLoad(RegSaveAreaPtr), 4841 CharUnits::fromQuantity(8)); 4842 assert(RegAddr.getElementType() == CGF.Int8Ty); 4843 4844 // Floating-point registers start after the general-purpose registers. 4845 if (!(isInt || IsSoftFloatABI)) { 4846 RegAddr = Builder.CreateConstInBoundsByteGEP(RegAddr, 4847 CharUnits::fromQuantity(32)); 4848 } 4849 4850 // Get the address of the saved value by scaling the number of 4851 // registers we've used by the number of 4852 CharUnits RegSize = CharUnits::fromQuantity((isInt || IsSoftFloatABI) ? 4 : 8); 4853 llvm::Value *RegOffset = 4854 Builder.CreateMul(NumRegs, Builder.getInt8(RegSize.getQuantity())); 4855 RegAddr = Address(Builder.CreateInBoundsGEP(CGF.Int8Ty, 4856 RegAddr.getPointer(), RegOffset), 4857 RegAddr.getAlignment().alignmentOfArrayElement(RegSize)); 4858 RegAddr = Builder.CreateElementBitCast(RegAddr, DirectTy); 4859 4860 // Increase the used-register count. 4861 NumRegs = 4862 Builder.CreateAdd(NumRegs, 4863 Builder.getInt8((isI64 || (isF64 && IsSoftFloatABI)) ? 2 : 1)); 4864 Builder.CreateStore(NumRegs, NumRegsAddr); 4865 4866 CGF.EmitBranch(Cont); 4867 } 4868 4869 // Case 2: consume space in the overflow area. 4870 Address MemAddr = Address::invalid(); 4871 { 4872 CGF.EmitBlock(UsingOverflow); 4873 4874 Builder.CreateStore(Builder.getInt8(OverflowLimit), NumRegsAddr); 4875 4876 // Everything in the overflow area is rounded up to a size of at least 4. 4877 CharUnits OverflowAreaAlign = CharUnits::fromQuantity(4); 4878 4879 CharUnits Size; 4880 if (!isIndirect) { 4881 auto TypeInfo = CGF.getContext().getTypeInfoInChars(Ty); 4882 Size = TypeInfo.Width.alignTo(OverflowAreaAlign); 4883 } else { 4884 Size = CGF.getPointerSize(); 4885 } 4886 4887 Address OverflowAreaAddr = Builder.CreateStructGEP(VAList, 3); 4888 Address OverflowArea(Builder.CreateLoad(OverflowAreaAddr, "argp.cur"), 4889 OverflowAreaAlign); 4890 // Round up address of argument to alignment 4891 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty); 4892 if (Align > OverflowAreaAlign) { 4893 llvm::Value *Ptr = OverflowArea.getPointer(); 4894 OverflowArea = Address(emitRoundPointerUpToAlignment(CGF, Ptr, Align), 4895 Align); 4896 } 4897 4898 MemAddr = Builder.CreateElementBitCast(OverflowArea, DirectTy); 4899 4900 // Increase the overflow area. 4901 OverflowArea = Builder.CreateConstInBoundsByteGEP(OverflowArea, Size); 4902 Builder.CreateStore(OverflowArea.getPointer(), OverflowAreaAddr); 4903 CGF.EmitBranch(Cont); 4904 } 4905 4906 CGF.EmitBlock(Cont); 4907 4908 // Merge the cases with a phi. 4909 Address Result = emitMergePHI(CGF, RegAddr, UsingRegs, MemAddr, UsingOverflow, 4910 "vaarg.addr"); 4911 4912 // Load the pointer if the argument was passed indirectly. 4913 if (isIndirect) { 4914 Result = Address(Builder.CreateLoad(Result, "aggr"), 4915 getContext().getTypeAlignInChars(Ty)); 4916 } 4917 4918 return Result; 4919 } 4920 4921 bool PPC32TargetCodeGenInfo::isStructReturnInRegABI( 4922 const llvm::Triple &Triple, const CodeGenOptions &Opts) { 4923 assert(Triple.isPPC32()); 4924 4925 switch (Opts.getStructReturnConvention()) { 4926 case CodeGenOptions::SRCK_Default: 4927 break; 4928 case CodeGenOptions::SRCK_OnStack: // -maix-struct-return 4929 return false; 4930 case CodeGenOptions::SRCK_InRegs: // -msvr4-struct-return 4931 return true; 4932 } 4933 4934 if (Triple.isOSBinFormatELF() && !Triple.isOSLinux()) 4935 return true; 4936 4937 return false; 4938 } 4939 4940 bool 4941 PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 4942 llvm::Value *Address) const { 4943 return PPC_initDwarfEHRegSizeTable(CGF, Address, /*Is64Bit*/ false, 4944 /*IsAIX*/ false); 4945 } 4946 4947 // PowerPC-64 4948 4949 namespace { 4950 /// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information. 4951 class PPC64_SVR4_ABIInfo : public SwiftABIInfo { 4952 public: 4953 enum ABIKind { 4954 ELFv1 = 0, 4955 ELFv2 4956 }; 4957 4958 private: 4959 static const unsigned GPRBits = 64; 4960 ABIKind Kind; 4961 bool IsSoftFloatABI; 4962 4963 public: 4964 PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind, 4965 bool SoftFloatABI) 4966 : SwiftABIInfo(CGT), Kind(Kind), IsSoftFloatABI(SoftFloatABI) {} 4967 4968 bool isPromotableTypeForABI(QualType Ty) const; 4969 CharUnits getParamTypeAlignment(QualType Ty) const; 4970 4971 ABIArgInfo classifyReturnType(QualType RetTy) const; 4972 ABIArgInfo classifyArgumentType(QualType Ty) const; 4973 4974 bool isHomogeneousAggregateBaseType(QualType Ty) const override; 4975 bool isHomogeneousAggregateSmallEnough(const Type *Ty, 4976 uint64_t Members) const override; 4977 4978 // TODO: We can add more logic to computeInfo to improve performance. 4979 // Example: For aggregate arguments that fit in a register, we could 4980 // use getDirectInReg (as is done below for structs containing a single 4981 // floating-point value) to avoid pushing them to memory on function 4982 // entry. This would require changing the logic in PPCISelLowering 4983 // when lowering the parameters in the caller and args in the callee. 4984 void computeInfo(CGFunctionInfo &FI) const override { 4985 if (!getCXXABI().classifyReturnType(FI)) 4986 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 4987 for (auto &I : FI.arguments()) { 4988 // We rely on the default argument classification for the most part. 4989 // One exception: An aggregate containing a single floating-point 4990 // or vector item must be passed in a register if one is available. 4991 const Type *T = isSingleElementStruct(I.type, getContext()); 4992 if (T) { 4993 const BuiltinType *BT = T->getAs<BuiltinType>(); 4994 if ((T->isVectorType() && getContext().getTypeSize(T) == 128) || 4995 (BT && BT->isFloatingPoint())) { 4996 QualType QT(T, 0); 4997 I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT)); 4998 continue; 4999 } 5000 } 5001 I.info = classifyArgumentType(I.type); 5002 } 5003 } 5004 5005 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 5006 QualType Ty) const override; 5007 5008 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars, 5009 bool asReturnValue) const override { 5010 return occupiesMoreThan(CGT, scalars, /*total*/ 4); 5011 } 5012 5013 bool isSwiftErrorInRegister() const override { 5014 return false; 5015 } 5016 }; 5017 5018 class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo { 5019 5020 public: 5021 PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT, 5022 PPC64_SVR4_ABIInfo::ABIKind Kind, 5023 bool SoftFloatABI) 5024 : TargetCodeGenInfo( 5025 std::make_unique<PPC64_SVR4_ABIInfo>(CGT, Kind, SoftFloatABI)) {} 5026 5027 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 5028 // This is recovered from gcc output. 5029 return 1; // r1 is the dedicated stack pointer 5030 } 5031 5032 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 5033 llvm::Value *Address) const override; 5034 }; 5035 5036 class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo { 5037 public: 5038 PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {} 5039 5040 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 5041 // This is recovered from gcc output. 5042 return 1; // r1 is the dedicated stack pointer 5043 } 5044 5045 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 5046 llvm::Value *Address) const override; 5047 }; 5048 5049 } 5050 5051 // Return true if the ABI requires Ty to be passed sign- or zero- 5052 // extended to 64 bits. 5053 bool 5054 PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const { 5055 // Treat an enum type as its underlying type. 5056 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 5057 Ty = EnumTy->getDecl()->getIntegerType(); 5058 5059 // Promotable integer types are required to be promoted by the ABI. 5060 if (isPromotableIntegerTypeForABI(Ty)) 5061 return true; 5062 5063 // In addition to the usual promotable integer types, we also need to 5064 // extend all 32-bit types, since the ABI requires promotion to 64 bits. 5065 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) 5066 switch (BT->getKind()) { 5067 case BuiltinType::Int: 5068 case BuiltinType::UInt: 5069 return true; 5070 default: 5071 break; 5072 } 5073 5074 if (const auto *EIT = Ty->getAs<BitIntType>()) 5075 if (EIT->getNumBits() < 64) 5076 return true; 5077 5078 return false; 5079 } 5080 5081 /// isAlignedParamType - Determine whether a type requires 16-byte or 5082 /// higher alignment in the parameter area. Always returns at least 8. 5083 CharUnits PPC64_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const { 5084 // Complex types are passed just like their elements. 5085 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) 5086 Ty = CTy->getElementType(); 5087 5088 auto FloatUsesVector = [this](QualType Ty){ 5089 return Ty->isRealFloatingType() && &getContext().getFloatTypeSemantics( 5090 Ty) == &llvm::APFloat::IEEEquad(); 5091 }; 5092 5093 // Only vector types of size 16 bytes need alignment (larger types are 5094 // passed via reference, smaller types are not aligned). 5095 if (Ty->isVectorType()) { 5096 return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16 : 8); 5097 } else if (FloatUsesVector(Ty)) { 5098 // According to ABI document section 'Optional Save Areas': If extended 5099 // precision floating-point values in IEEE BINARY 128 QUADRUPLE PRECISION 5100 // format are supported, map them to a single quadword, quadword aligned. 5101 return CharUnits::fromQuantity(16); 5102 } 5103 5104 // For single-element float/vector structs, we consider the whole type 5105 // to have the same alignment requirements as its single element. 5106 const Type *AlignAsType = nullptr; 5107 const Type *EltType = isSingleElementStruct(Ty, getContext()); 5108 if (EltType) { 5109 const BuiltinType *BT = EltType->getAs<BuiltinType>(); 5110 if ((EltType->isVectorType() && getContext().getTypeSize(EltType) == 128) || 5111 (BT && BT->isFloatingPoint())) 5112 AlignAsType = EltType; 5113 } 5114 5115 // Likewise for ELFv2 homogeneous aggregates. 5116 const Type *Base = nullptr; 5117 uint64_t Members = 0; 5118 if (!AlignAsType && Kind == ELFv2 && 5119 isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members)) 5120 AlignAsType = Base; 5121 5122 // With special case aggregates, only vector base types need alignment. 5123 if (AlignAsType) { 5124 bool UsesVector = AlignAsType->isVectorType() || 5125 FloatUsesVector(QualType(AlignAsType, 0)); 5126 return CharUnits::fromQuantity(UsesVector ? 16 : 8); 5127 } 5128 5129 // Otherwise, we only need alignment for any aggregate type that 5130 // has an alignment requirement of >= 16 bytes. 5131 if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128) { 5132 return CharUnits::fromQuantity(16); 5133 } 5134 5135 return CharUnits::fromQuantity(8); 5136 } 5137 5138 /// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous 5139 /// aggregate. Base is set to the base element type, and Members is set 5140 /// to the number of base elements. 5141 bool ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base, 5142 uint64_t &Members) const { 5143 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) { 5144 uint64_t NElements = AT->getSize().getZExtValue(); 5145 if (NElements == 0) 5146 return false; 5147 if (!isHomogeneousAggregate(AT->getElementType(), Base, Members)) 5148 return false; 5149 Members *= NElements; 5150 } else if (const RecordType *RT = Ty->getAs<RecordType>()) { 5151 const RecordDecl *RD = RT->getDecl(); 5152 if (RD->hasFlexibleArrayMember()) 5153 return false; 5154 5155 Members = 0; 5156 5157 // If this is a C++ record, check the properties of the record such as 5158 // bases and ABI specific restrictions 5159 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 5160 if (!getCXXABI().isPermittedToBeHomogeneousAggregate(CXXRD)) 5161 return false; 5162 5163 for (const auto &I : CXXRD->bases()) { 5164 // Ignore empty records. 5165 if (isEmptyRecord(getContext(), I.getType(), true)) 5166 continue; 5167 5168 uint64_t FldMembers; 5169 if (!isHomogeneousAggregate(I.getType(), Base, FldMembers)) 5170 return false; 5171 5172 Members += FldMembers; 5173 } 5174 } 5175 5176 for (const auto *FD : RD->fields()) { 5177 // Ignore (non-zero arrays of) empty records. 5178 QualType FT = FD->getType(); 5179 while (const ConstantArrayType *AT = 5180 getContext().getAsConstantArrayType(FT)) { 5181 if (AT->getSize().getZExtValue() == 0) 5182 return false; 5183 FT = AT->getElementType(); 5184 } 5185 if (isEmptyRecord(getContext(), FT, true)) 5186 continue; 5187 5188 // For compatibility with GCC, ignore empty bitfields in C++ mode. 5189 if (getContext().getLangOpts().CPlusPlus && 5190 FD->isZeroLengthBitField(getContext())) 5191 continue; 5192 5193 uint64_t FldMembers; 5194 if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers)) 5195 return false; 5196 5197 Members = (RD->isUnion() ? 5198 std::max(Members, FldMembers) : Members + FldMembers); 5199 } 5200 5201 if (!Base) 5202 return false; 5203 5204 // Ensure there is no padding. 5205 if (getContext().getTypeSize(Base) * Members != 5206 getContext().getTypeSize(Ty)) 5207 return false; 5208 } else { 5209 Members = 1; 5210 if (const ComplexType *CT = Ty->getAs<ComplexType>()) { 5211 Members = 2; 5212 Ty = CT->getElementType(); 5213 } 5214 5215 // Most ABIs only support float, double, and some vector type widths. 5216 if (!isHomogeneousAggregateBaseType(Ty)) 5217 return false; 5218 5219 // The base type must be the same for all members. Types that 5220 // agree in both total size and mode (float vs. vector) are 5221 // treated as being equivalent here. 5222 const Type *TyPtr = Ty.getTypePtr(); 5223 if (!Base) { 5224 Base = TyPtr; 5225 // If it's a non-power-of-2 vector, its size is already a power-of-2, 5226 // so make sure to widen it explicitly. 5227 if (const VectorType *VT = Base->getAs<VectorType>()) { 5228 QualType EltTy = VT->getElementType(); 5229 unsigned NumElements = 5230 getContext().getTypeSize(VT) / getContext().getTypeSize(EltTy); 5231 Base = getContext() 5232 .getVectorType(EltTy, NumElements, VT->getVectorKind()) 5233 .getTypePtr(); 5234 } 5235 } 5236 5237 if (Base->isVectorType() != TyPtr->isVectorType() || 5238 getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr)) 5239 return false; 5240 } 5241 return Members > 0 && isHomogeneousAggregateSmallEnough(Base, Members); 5242 } 5243 5244 bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const { 5245 // Homogeneous aggregates for ELFv2 must have base types of float, 5246 // double, long double, or 128-bit vectors. 5247 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) { 5248 if (BT->getKind() == BuiltinType::Float || 5249 BT->getKind() == BuiltinType::Double || 5250 BT->getKind() == BuiltinType::LongDouble || 5251 BT->getKind() == BuiltinType::Ibm128 || 5252 (getContext().getTargetInfo().hasFloat128Type() && 5253 (BT->getKind() == BuiltinType::Float128))) { 5254 if (IsSoftFloatABI) 5255 return false; 5256 return true; 5257 } 5258 } 5259 if (const VectorType *VT = Ty->getAs<VectorType>()) { 5260 if (getContext().getTypeSize(VT) == 128) 5261 return true; 5262 } 5263 return false; 5264 } 5265 5266 bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateSmallEnough( 5267 const Type *Base, uint64_t Members) const { 5268 // Vector and fp128 types require one register, other floating point types 5269 // require one or two registers depending on their size. 5270 uint32_t NumRegs = 5271 ((getContext().getTargetInfo().hasFloat128Type() && 5272 Base->isFloat128Type()) || 5273 Base->isVectorType()) ? 1 5274 : (getContext().getTypeSize(Base) + 63) / 64; 5275 5276 // Homogeneous Aggregates may occupy at most 8 registers. 5277 return Members * NumRegs <= 8; 5278 } 5279 5280 ABIArgInfo 5281 PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const { 5282 Ty = useFirstFieldIfTransparentUnion(Ty); 5283 5284 if (Ty->isAnyComplexType()) 5285 return ABIArgInfo::getDirect(); 5286 5287 // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes) 5288 // or via reference (larger than 16 bytes). 5289 if (Ty->isVectorType()) { 5290 uint64_t Size = getContext().getTypeSize(Ty); 5291 if (Size > 128) 5292 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 5293 else if (Size < 128) { 5294 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size); 5295 return ABIArgInfo::getDirect(CoerceTy); 5296 } 5297 } 5298 5299 if (const auto *EIT = Ty->getAs<BitIntType>()) 5300 if (EIT->getNumBits() > 128) 5301 return getNaturalAlignIndirect(Ty, /*ByVal=*/true); 5302 5303 if (isAggregateTypeForABI(Ty)) { 5304 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 5305 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 5306 5307 uint64_t ABIAlign = getParamTypeAlignment(Ty).getQuantity(); 5308 uint64_t TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity(); 5309 5310 // ELFv2 homogeneous aggregates are passed as array types. 5311 const Type *Base = nullptr; 5312 uint64_t Members = 0; 5313 if (Kind == ELFv2 && 5314 isHomogeneousAggregate(Ty, Base, Members)) { 5315 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0)); 5316 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members); 5317 return ABIArgInfo::getDirect(CoerceTy); 5318 } 5319 5320 // If an aggregate may end up fully in registers, we do not 5321 // use the ByVal method, but pass the aggregate as array. 5322 // This is usually beneficial since we avoid forcing the 5323 // back-end to store the argument to memory. 5324 uint64_t Bits = getContext().getTypeSize(Ty); 5325 if (Bits > 0 && Bits <= 8 * GPRBits) { 5326 llvm::Type *CoerceTy; 5327 5328 // Types up to 8 bytes are passed as integer type (which will be 5329 // properly aligned in the argument save area doubleword). 5330 if (Bits <= GPRBits) 5331 CoerceTy = 5332 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8)); 5333 // Larger types are passed as arrays, with the base type selected 5334 // according to the required alignment in the save area. 5335 else { 5336 uint64_t RegBits = ABIAlign * 8; 5337 uint64_t NumRegs = llvm::alignTo(Bits, RegBits) / RegBits; 5338 llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits); 5339 CoerceTy = llvm::ArrayType::get(RegTy, NumRegs); 5340 } 5341 5342 return ABIArgInfo::getDirect(CoerceTy); 5343 } 5344 5345 // All other aggregates are passed ByVal. 5346 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign), 5347 /*ByVal=*/true, 5348 /*Realign=*/TyAlign > ABIAlign); 5349 } 5350 5351 return (isPromotableTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty) 5352 : ABIArgInfo::getDirect()); 5353 } 5354 5355 ABIArgInfo 5356 PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const { 5357 if (RetTy->isVoidType()) 5358 return ABIArgInfo::getIgnore(); 5359 5360 if (RetTy->isAnyComplexType()) 5361 return ABIArgInfo::getDirect(); 5362 5363 // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes) 5364 // or via reference (larger than 16 bytes). 5365 if (RetTy->isVectorType()) { 5366 uint64_t Size = getContext().getTypeSize(RetTy); 5367 if (Size > 128) 5368 return getNaturalAlignIndirect(RetTy); 5369 else if (Size < 128) { 5370 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size); 5371 return ABIArgInfo::getDirect(CoerceTy); 5372 } 5373 } 5374 5375 if (const auto *EIT = RetTy->getAs<BitIntType>()) 5376 if (EIT->getNumBits() > 128) 5377 return getNaturalAlignIndirect(RetTy, /*ByVal=*/false); 5378 5379 if (isAggregateTypeForABI(RetTy)) { 5380 // ELFv2 homogeneous aggregates are returned as array types. 5381 const Type *Base = nullptr; 5382 uint64_t Members = 0; 5383 if (Kind == ELFv2 && 5384 isHomogeneousAggregate(RetTy, Base, Members)) { 5385 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0)); 5386 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members); 5387 return ABIArgInfo::getDirect(CoerceTy); 5388 } 5389 5390 // ELFv2 small aggregates are returned in up to two registers. 5391 uint64_t Bits = getContext().getTypeSize(RetTy); 5392 if (Kind == ELFv2 && Bits <= 2 * GPRBits) { 5393 if (Bits == 0) 5394 return ABIArgInfo::getIgnore(); 5395 5396 llvm::Type *CoerceTy; 5397 if (Bits > GPRBits) { 5398 CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits); 5399 CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy); 5400 } else 5401 CoerceTy = 5402 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8)); 5403 return ABIArgInfo::getDirect(CoerceTy); 5404 } 5405 5406 // All other aggregates are returned indirectly. 5407 return getNaturalAlignIndirect(RetTy); 5408 } 5409 5410 return (isPromotableTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy) 5411 : ABIArgInfo::getDirect()); 5412 } 5413 5414 // Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine. 5415 Address PPC64_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 5416 QualType Ty) const { 5417 auto TypeInfo = getContext().getTypeInfoInChars(Ty); 5418 TypeInfo.Align = getParamTypeAlignment(Ty); 5419 5420 CharUnits SlotSize = CharUnits::fromQuantity(8); 5421 5422 // If we have a complex type and the base type is smaller than 8 bytes, 5423 // the ABI calls for the real and imaginary parts to be right-adjusted 5424 // in separate doublewords. However, Clang expects us to produce a 5425 // pointer to a structure with the two parts packed tightly. So generate 5426 // loads of the real and imaginary parts relative to the va_list pointer, 5427 // and store them to a temporary structure. 5428 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) { 5429 CharUnits EltSize = TypeInfo.Width / 2; 5430 if (EltSize < SlotSize) 5431 return complexTempStructure(CGF, VAListAddr, Ty, SlotSize, EltSize, CTy); 5432 } 5433 5434 // Otherwise, just use the general rule. 5435 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false, 5436 TypeInfo, SlotSize, /*AllowHigher*/ true); 5437 } 5438 5439 bool 5440 PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable( 5441 CodeGen::CodeGenFunction &CGF, 5442 llvm::Value *Address) const { 5443 return PPC_initDwarfEHRegSizeTable(CGF, Address, /*Is64Bit*/ true, 5444 /*IsAIX*/ false); 5445 } 5446 5447 bool 5448 PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 5449 llvm::Value *Address) const { 5450 return PPC_initDwarfEHRegSizeTable(CGF, Address, /*Is64Bit*/ true, 5451 /*IsAIX*/ false); 5452 } 5453 5454 //===----------------------------------------------------------------------===// 5455 // AArch64 ABI Implementation 5456 //===----------------------------------------------------------------------===// 5457 5458 namespace { 5459 5460 class AArch64ABIInfo : public SwiftABIInfo { 5461 public: 5462 enum ABIKind { 5463 AAPCS = 0, 5464 DarwinPCS, 5465 Win64 5466 }; 5467 5468 private: 5469 ABIKind Kind; 5470 5471 public: 5472 AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind) 5473 : SwiftABIInfo(CGT), Kind(Kind) {} 5474 5475 private: 5476 ABIKind getABIKind() const { return Kind; } 5477 bool isDarwinPCS() const { return Kind == DarwinPCS; } 5478 5479 ABIArgInfo classifyReturnType(QualType RetTy, bool IsVariadic) const; 5480 ABIArgInfo classifyArgumentType(QualType RetTy, bool IsVariadic, 5481 unsigned CallingConvention) const; 5482 ABIArgInfo coerceIllegalVector(QualType Ty) const; 5483 bool isHomogeneousAggregateBaseType(QualType Ty) const override; 5484 bool isHomogeneousAggregateSmallEnough(const Type *Ty, 5485 uint64_t Members) const override; 5486 5487 bool isIllegalVectorType(QualType Ty) const; 5488 5489 void computeInfo(CGFunctionInfo &FI) const override { 5490 if (!::classifyReturnType(getCXXABI(), FI, *this)) 5491 FI.getReturnInfo() = 5492 classifyReturnType(FI.getReturnType(), FI.isVariadic()); 5493 5494 for (auto &it : FI.arguments()) 5495 it.info = classifyArgumentType(it.type, FI.isVariadic(), 5496 FI.getCallingConvention()); 5497 } 5498 5499 Address EmitDarwinVAArg(Address VAListAddr, QualType Ty, 5500 CodeGenFunction &CGF) const; 5501 5502 Address EmitAAPCSVAArg(Address VAListAddr, QualType Ty, 5503 CodeGenFunction &CGF) const; 5504 5505 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 5506 QualType Ty) const override { 5507 llvm::Type *BaseTy = CGF.ConvertType(Ty); 5508 if (isa<llvm::ScalableVectorType>(BaseTy)) 5509 llvm::report_fatal_error("Passing SVE types to variadic functions is " 5510 "currently not supported"); 5511 5512 return Kind == Win64 ? EmitMSVAArg(CGF, VAListAddr, Ty) 5513 : isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF) 5514 : EmitAAPCSVAArg(VAListAddr, Ty, CGF); 5515 } 5516 5517 Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr, 5518 QualType Ty) const override; 5519 5520 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars, 5521 bool asReturnValue) const override { 5522 return occupiesMoreThan(CGT, scalars, /*total*/ 4); 5523 } 5524 bool isSwiftErrorInRegister() const override { 5525 return true; 5526 } 5527 5528 bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy, 5529 unsigned elts) const override; 5530 5531 bool allowBFloatArgsAndRet() const override { 5532 return getTarget().hasBFloat16Type(); 5533 } 5534 }; 5535 5536 class AArch64TargetCodeGenInfo : public TargetCodeGenInfo { 5537 public: 5538 AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind) 5539 : TargetCodeGenInfo(std::make_unique<AArch64ABIInfo>(CGT, Kind)) {} 5540 5541 StringRef getARCRetainAutoreleasedReturnValueMarker() const override { 5542 return "mov\tfp, fp\t\t// marker for objc_retainAutoreleaseReturnValue"; 5543 } 5544 5545 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 5546 return 31; 5547 } 5548 5549 bool doesReturnSlotInterfereWithArgs() const override { return false; } 5550 5551 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 5552 CodeGen::CodeGenModule &CGM) const override { 5553 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D); 5554 if (!FD) 5555 return; 5556 5557 const auto *TA = FD->getAttr<TargetAttr>(); 5558 if (TA == nullptr) 5559 return; 5560 5561 ParsedTargetAttr Attr = TA->parse(); 5562 if (Attr.BranchProtection.empty()) 5563 return; 5564 5565 TargetInfo::BranchProtectionInfo BPI; 5566 StringRef Error; 5567 (void)CGM.getTarget().validateBranchProtection( 5568 Attr.BranchProtection, Attr.Architecture, BPI, Error); 5569 assert(Error.empty()); 5570 5571 auto *Fn = cast<llvm::Function>(GV); 5572 static const char *SignReturnAddrStr[] = {"none", "non-leaf", "all"}; 5573 Fn->addFnAttr("sign-return-address", SignReturnAddrStr[static_cast<int>(BPI.SignReturnAddr)]); 5574 5575 if (BPI.SignReturnAddr != LangOptions::SignReturnAddressScopeKind::None) { 5576 Fn->addFnAttr("sign-return-address-key", 5577 BPI.SignKey == LangOptions::SignReturnAddressKeyKind::AKey 5578 ? "a_key" 5579 : "b_key"); 5580 } 5581 5582 Fn->addFnAttr("branch-target-enforcement", 5583 BPI.BranchTargetEnforcement ? "true" : "false"); 5584 } 5585 5586 bool isScalarizableAsmOperand(CodeGen::CodeGenFunction &CGF, 5587 llvm::Type *Ty) const override { 5588 if (CGF.getTarget().hasFeature("ls64")) { 5589 auto *ST = dyn_cast<llvm::StructType>(Ty); 5590 if (ST && ST->getNumElements() == 1) { 5591 auto *AT = dyn_cast<llvm::ArrayType>(ST->getElementType(0)); 5592 if (AT && AT->getNumElements() == 8 && 5593 AT->getElementType()->isIntegerTy(64)) 5594 return true; 5595 } 5596 } 5597 return TargetCodeGenInfo::isScalarizableAsmOperand(CGF, Ty); 5598 } 5599 }; 5600 5601 class WindowsAArch64TargetCodeGenInfo : public AArch64TargetCodeGenInfo { 5602 public: 5603 WindowsAArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind K) 5604 : AArch64TargetCodeGenInfo(CGT, K) {} 5605 5606 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 5607 CodeGen::CodeGenModule &CGM) const override; 5608 5609 void getDependentLibraryOption(llvm::StringRef Lib, 5610 llvm::SmallString<24> &Opt) const override { 5611 Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib); 5612 } 5613 5614 void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value, 5615 llvm::SmallString<32> &Opt) const override { 5616 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\""; 5617 } 5618 }; 5619 5620 void WindowsAArch64TargetCodeGenInfo::setTargetAttributes( 5621 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const { 5622 AArch64TargetCodeGenInfo::setTargetAttributes(D, GV, CGM); 5623 if (GV->isDeclaration()) 5624 return; 5625 addStackProbeTargetAttributes(D, GV, CGM); 5626 } 5627 } 5628 5629 ABIArgInfo AArch64ABIInfo::coerceIllegalVector(QualType Ty) const { 5630 assert(Ty->isVectorType() && "expected vector type!"); 5631 5632 const auto *VT = Ty->castAs<VectorType>(); 5633 if (VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector) { 5634 assert(VT->getElementType()->isBuiltinType() && "expected builtin type!"); 5635 assert(VT->getElementType()->castAs<BuiltinType>()->getKind() == 5636 BuiltinType::UChar && 5637 "unexpected builtin type for SVE predicate!"); 5638 return ABIArgInfo::getDirect(llvm::ScalableVectorType::get( 5639 llvm::Type::getInt1Ty(getVMContext()), 16)); 5640 } 5641 5642 if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector) { 5643 assert(VT->getElementType()->isBuiltinType() && "expected builtin type!"); 5644 5645 const auto *BT = VT->getElementType()->castAs<BuiltinType>(); 5646 llvm::ScalableVectorType *ResType = nullptr; 5647 switch (BT->getKind()) { 5648 default: 5649 llvm_unreachable("unexpected builtin type for SVE vector!"); 5650 case BuiltinType::SChar: 5651 case BuiltinType::UChar: 5652 ResType = llvm::ScalableVectorType::get( 5653 llvm::Type::getInt8Ty(getVMContext()), 16); 5654 break; 5655 case BuiltinType::Short: 5656 case BuiltinType::UShort: 5657 ResType = llvm::ScalableVectorType::get( 5658 llvm::Type::getInt16Ty(getVMContext()), 8); 5659 break; 5660 case BuiltinType::Int: 5661 case BuiltinType::UInt: 5662 ResType = llvm::ScalableVectorType::get( 5663 llvm::Type::getInt32Ty(getVMContext()), 4); 5664 break; 5665 case BuiltinType::Long: 5666 case BuiltinType::ULong: 5667 ResType = llvm::ScalableVectorType::get( 5668 llvm::Type::getInt64Ty(getVMContext()), 2); 5669 break; 5670 case BuiltinType::Half: 5671 ResType = llvm::ScalableVectorType::get( 5672 llvm::Type::getHalfTy(getVMContext()), 8); 5673 break; 5674 case BuiltinType::Float: 5675 ResType = llvm::ScalableVectorType::get( 5676 llvm::Type::getFloatTy(getVMContext()), 4); 5677 break; 5678 case BuiltinType::Double: 5679 ResType = llvm::ScalableVectorType::get( 5680 llvm::Type::getDoubleTy(getVMContext()), 2); 5681 break; 5682 case BuiltinType::BFloat16: 5683 ResType = llvm::ScalableVectorType::get( 5684 llvm::Type::getBFloatTy(getVMContext()), 8); 5685 break; 5686 } 5687 return ABIArgInfo::getDirect(ResType); 5688 } 5689 5690 uint64_t Size = getContext().getTypeSize(Ty); 5691 // Android promotes <2 x i8> to i16, not i32 5692 if (isAndroid() && (Size <= 16)) { 5693 llvm::Type *ResType = llvm::Type::getInt16Ty(getVMContext()); 5694 return ABIArgInfo::getDirect(ResType); 5695 } 5696 if (Size <= 32) { 5697 llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext()); 5698 return ABIArgInfo::getDirect(ResType); 5699 } 5700 if (Size == 64) { 5701 auto *ResType = 5702 llvm::FixedVectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2); 5703 return ABIArgInfo::getDirect(ResType); 5704 } 5705 if (Size == 128) { 5706 auto *ResType = 5707 llvm::FixedVectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4); 5708 return ABIArgInfo::getDirect(ResType); 5709 } 5710 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 5711 } 5712 5713 ABIArgInfo 5714 AArch64ABIInfo::classifyArgumentType(QualType Ty, bool IsVariadic, 5715 unsigned CallingConvention) const { 5716 Ty = useFirstFieldIfTransparentUnion(Ty); 5717 5718 // Handle illegal vector types here. 5719 if (isIllegalVectorType(Ty)) 5720 return coerceIllegalVector(Ty); 5721 5722 if (!isAggregateTypeForABI(Ty)) { 5723 // Treat an enum type as its underlying type. 5724 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 5725 Ty = EnumTy->getDecl()->getIntegerType(); 5726 5727 if (const auto *EIT = Ty->getAs<BitIntType>()) 5728 if (EIT->getNumBits() > 128) 5729 return getNaturalAlignIndirect(Ty); 5730 5731 return (isPromotableIntegerTypeForABI(Ty) && isDarwinPCS() 5732 ? ABIArgInfo::getExtend(Ty) 5733 : ABIArgInfo::getDirect()); 5734 } 5735 5736 // Structures with either a non-trivial destructor or a non-trivial 5737 // copy constructor are always indirect. 5738 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) { 5739 return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA == 5740 CGCXXABI::RAA_DirectInMemory); 5741 } 5742 5743 // Empty records are always ignored on Darwin, but actually passed in C++ mode 5744 // elsewhere for GNU compatibility. 5745 uint64_t Size = getContext().getTypeSize(Ty); 5746 bool IsEmpty = isEmptyRecord(getContext(), Ty, true); 5747 if (IsEmpty || Size == 0) { 5748 if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS()) 5749 return ABIArgInfo::getIgnore(); 5750 5751 // GNU C mode. The only argument that gets ignored is an empty one with size 5752 // 0. 5753 if (IsEmpty && Size == 0) 5754 return ABIArgInfo::getIgnore(); 5755 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext())); 5756 } 5757 5758 // Homogeneous Floating-point Aggregates (HFAs) need to be expanded. 5759 const Type *Base = nullptr; 5760 uint64_t Members = 0; 5761 bool IsWin64 = Kind == Win64 || CallingConvention == llvm::CallingConv::Win64; 5762 bool IsWinVariadic = IsWin64 && IsVariadic; 5763 // In variadic functions on Windows, all composite types are treated alike, 5764 // no special handling of HFAs/HVAs. 5765 if (!IsWinVariadic && isHomogeneousAggregate(Ty, Base, Members)) { 5766 if (Kind != AArch64ABIInfo::AAPCS) 5767 return ABIArgInfo::getDirect( 5768 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members)); 5769 5770 // For alignment adjusted HFAs, cap the argument alignment to 16, leave it 5771 // default otherwise. 5772 unsigned Align = 5773 getContext().getTypeUnadjustedAlignInChars(Ty).getQuantity(); 5774 unsigned BaseAlign = getContext().getTypeAlignInChars(Base).getQuantity(); 5775 Align = (Align > BaseAlign && Align >= 16) ? 16 : 0; 5776 return ABIArgInfo::getDirect( 5777 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members), 0, 5778 nullptr, true, Align); 5779 } 5780 5781 // Aggregates <= 16 bytes are passed directly in registers or on the stack. 5782 if (Size <= 128) { 5783 // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of 5784 // same size and alignment. 5785 if (getTarget().isRenderScriptTarget()) { 5786 return coerceToIntArray(Ty, getContext(), getVMContext()); 5787 } 5788 unsigned Alignment; 5789 if (Kind == AArch64ABIInfo::AAPCS) { 5790 Alignment = getContext().getTypeUnadjustedAlign(Ty); 5791 Alignment = Alignment < 128 ? 64 : 128; 5792 } else { 5793 Alignment = std::max(getContext().getTypeAlign(Ty), 5794 (unsigned)getTarget().getPointerWidth(0)); 5795 } 5796 Size = llvm::alignTo(Size, Alignment); 5797 5798 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment. 5799 // For aggregates with 16-byte alignment, we use i128. 5800 llvm::Type *BaseTy = llvm::Type::getIntNTy(getVMContext(), Alignment); 5801 return ABIArgInfo::getDirect( 5802 Size == Alignment ? BaseTy 5803 : llvm::ArrayType::get(BaseTy, Size / Alignment)); 5804 } 5805 5806 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 5807 } 5808 5809 ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy, 5810 bool IsVariadic) const { 5811 if (RetTy->isVoidType()) 5812 return ABIArgInfo::getIgnore(); 5813 5814 if (const auto *VT = RetTy->getAs<VectorType>()) { 5815 if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector || 5816 VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector) 5817 return coerceIllegalVector(RetTy); 5818 } 5819 5820 // Large vector types should be returned via memory. 5821 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128) 5822 return getNaturalAlignIndirect(RetTy); 5823 5824 if (!isAggregateTypeForABI(RetTy)) { 5825 // Treat an enum type as its underlying type. 5826 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 5827 RetTy = EnumTy->getDecl()->getIntegerType(); 5828 5829 if (const auto *EIT = RetTy->getAs<BitIntType>()) 5830 if (EIT->getNumBits() > 128) 5831 return getNaturalAlignIndirect(RetTy); 5832 5833 return (isPromotableIntegerTypeForABI(RetTy) && isDarwinPCS() 5834 ? ABIArgInfo::getExtend(RetTy) 5835 : ABIArgInfo::getDirect()); 5836 } 5837 5838 uint64_t Size = getContext().getTypeSize(RetTy); 5839 if (isEmptyRecord(getContext(), RetTy, true) || Size == 0) 5840 return ABIArgInfo::getIgnore(); 5841 5842 const Type *Base = nullptr; 5843 uint64_t Members = 0; 5844 if (isHomogeneousAggregate(RetTy, Base, Members) && 5845 !(getTarget().getTriple().getArch() == llvm::Triple::aarch64_32 && 5846 IsVariadic)) 5847 // Homogeneous Floating-point Aggregates (HFAs) are returned directly. 5848 return ABIArgInfo::getDirect(); 5849 5850 // Aggregates <= 16 bytes are returned directly in registers or on the stack. 5851 if (Size <= 128) { 5852 // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of 5853 // same size and alignment. 5854 if (getTarget().isRenderScriptTarget()) { 5855 return coerceToIntArray(RetTy, getContext(), getVMContext()); 5856 } 5857 5858 if (Size <= 64 && getDataLayout().isLittleEndian()) { 5859 // Composite types are returned in lower bits of a 64-bit register for LE, 5860 // and in higher bits for BE. However, integer types are always returned 5861 // in lower bits for both LE and BE, and they are not rounded up to 5862 // 64-bits. We can skip rounding up of composite types for LE, but not for 5863 // BE, otherwise composite types will be indistinguishable from integer 5864 // types. 5865 return ABIArgInfo::getDirect( 5866 llvm::IntegerType::get(getVMContext(), Size)); 5867 } 5868 5869 unsigned Alignment = getContext().getTypeAlign(RetTy); 5870 Size = llvm::alignTo(Size, 64); // round up to multiple of 8 bytes 5871 5872 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment. 5873 // For aggregates with 16-byte alignment, we use i128. 5874 if (Alignment < 128 && Size == 128) { 5875 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext()); 5876 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64)); 5877 } 5878 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size)); 5879 } 5880 5881 return getNaturalAlignIndirect(RetTy); 5882 } 5883 5884 /// isIllegalVectorType - check whether the vector type is legal for AArch64. 5885 bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const { 5886 if (const VectorType *VT = Ty->getAs<VectorType>()) { 5887 // Check whether VT is a fixed-length SVE vector. These types are 5888 // represented as scalable vectors in function args/return and must be 5889 // coerced from fixed vectors. 5890 if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector || 5891 VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector) 5892 return true; 5893 5894 // Check whether VT is legal. 5895 unsigned NumElements = VT->getNumElements(); 5896 uint64_t Size = getContext().getTypeSize(VT); 5897 // NumElements should be power of 2. 5898 if (!llvm::isPowerOf2_32(NumElements)) 5899 return true; 5900 5901 // arm64_32 has to be compatible with the ARM logic here, which allows huge 5902 // vectors for some reason. 5903 llvm::Triple Triple = getTarget().getTriple(); 5904 if (Triple.getArch() == llvm::Triple::aarch64_32 && 5905 Triple.isOSBinFormatMachO()) 5906 return Size <= 32; 5907 5908 return Size != 64 && (Size != 128 || NumElements == 1); 5909 } 5910 return false; 5911 } 5912 5913 bool AArch64ABIInfo::isLegalVectorTypeForSwift(CharUnits totalSize, 5914 llvm::Type *eltTy, 5915 unsigned elts) const { 5916 if (!llvm::isPowerOf2_32(elts)) 5917 return false; 5918 if (totalSize.getQuantity() != 8 && 5919 (totalSize.getQuantity() != 16 || elts == 1)) 5920 return false; 5921 return true; 5922 } 5923 5924 bool AArch64ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const { 5925 // Homogeneous aggregates for AAPCS64 must have base types of a floating 5926 // point type or a short-vector type. This is the same as the 32-bit ABI, 5927 // but with the difference that any floating-point type is allowed, 5928 // including __fp16. 5929 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) { 5930 if (BT->isFloatingPoint()) 5931 return true; 5932 } else if (const VectorType *VT = Ty->getAs<VectorType>()) { 5933 unsigned VecSize = getContext().getTypeSize(VT); 5934 if (VecSize == 64 || VecSize == 128) 5935 return true; 5936 } 5937 return false; 5938 } 5939 5940 bool AArch64ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base, 5941 uint64_t Members) const { 5942 return Members <= 4; 5943 } 5944 5945 Address AArch64ABIInfo::EmitAAPCSVAArg(Address VAListAddr, QualType Ty, 5946 CodeGenFunction &CGF) const { 5947 ABIArgInfo AI = classifyArgumentType(Ty, /*IsVariadic=*/true, 5948 CGF.CurFnInfo->getCallingConvention()); 5949 bool IsIndirect = AI.isIndirect(); 5950 5951 llvm::Type *BaseTy = CGF.ConvertType(Ty); 5952 if (IsIndirect) 5953 BaseTy = llvm::PointerType::getUnqual(BaseTy); 5954 else if (AI.getCoerceToType()) 5955 BaseTy = AI.getCoerceToType(); 5956 5957 unsigned NumRegs = 1; 5958 if (llvm::ArrayType *ArrTy = dyn_cast<llvm::ArrayType>(BaseTy)) { 5959 BaseTy = ArrTy->getElementType(); 5960 NumRegs = ArrTy->getNumElements(); 5961 } 5962 bool IsFPR = BaseTy->isFloatingPointTy() || BaseTy->isVectorTy(); 5963 5964 // The AArch64 va_list type and handling is specified in the Procedure Call 5965 // Standard, section B.4: 5966 // 5967 // struct { 5968 // void *__stack; 5969 // void *__gr_top; 5970 // void *__vr_top; 5971 // int __gr_offs; 5972 // int __vr_offs; 5973 // }; 5974 5975 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg"); 5976 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg"); 5977 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack"); 5978 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end"); 5979 5980 CharUnits TySize = getContext().getTypeSizeInChars(Ty); 5981 CharUnits TyAlign = getContext().getTypeUnadjustedAlignInChars(Ty); 5982 5983 Address reg_offs_p = Address::invalid(); 5984 llvm::Value *reg_offs = nullptr; 5985 int reg_top_index; 5986 int RegSize = IsIndirect ? 8 : TySize.getQuantity(); 5987 if (!IsFPR) { 5988 // 3 is the field number of __gr_offs 5989 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 3, "gr_offs_p"); 5990 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs"); 5991 reg_top_index = 1; // field number for __gr_top 5992 RegSize = llvm::alignTo(RegSize, 8); 5993 } else { 5994 // 4 is the field number of __vr_offs. 5995 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 4, "vr_offs_p"); 5996 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs"); 5997 reg_top_index = 2; // field number for __vr_top 5998 RegSize = 16 * NumRegs; 5999 } 6000 6001 //======================================= 6002 // Find out where argument was passed 6003 //======================================= 6004 6005 // If reg_offs >= 0 we're already using the stack for this type of 6006 // argument. We don't want to keep updating reg_offs (in case it overflows, 6007 // though anyone passing 2GB of arguments, each at most 16 bytes, deserves 6008 // whatever they get). 6009 llvm::Value *UsingStack = nullptr; 6010 UsingStack = CGF.Builder.CreateICmpSGE( 6011 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0)); 6012 6013 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock); 6014 6015 // Otherwise, at least some kind of argument could go in these registers, the 6016 // question is whether this particular type is too big. 6017 CGF.EmitBlock(MaybeRegBlock); 6018 6019 // Integer arguments may need to correct register alignment (for example a 6020 // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we 6021 // align __gr_offs to calculate the potential address. 6022 if (!IsFPR && !IsIndirect && TyAlign.getQuantity() > 8) { 6023 int Align = TyAlign.getQuantity(); 6024 6025 reg_offs = CGF.Builder.CreateAdd( 6026 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1), 6027 "align_regoffs"); 6028 reg_offs = CGF.Builder.CreateAnd( 6029 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align), 6030 "aligned_regoffs"); 6031 } 6032 6033 // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list. 6034 // The fact that this is done unconditionally reflects the fact that 6035 // allocating an argument to the stack also uses up all the remaining 6036 // registers of the appropriate kind. 6037 llvm::Value *NewOffset = nullptr; 6038 NewOffset = CGF.Builder.CreateAdd( 6039 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs"); 6040 CGF.Builder.CreateStore(NewOffset, reg_offs_p); 6041 6042 // Now we're in a position to decide whether this argument really was in 6043 // registers or not. 6044 llvm::Value *InRegs = nullptr; 6045 InRegs = CGF.Builder.CreateICmpSLE( 6046 NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg"); 6047 6048 CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock); 6049 6050 //======================================= 6051 // Argument was in registers 6052 //======================================= 6053 6054 // Now we emit the code for if the argument was originally passed in 6055 // registers. First start the appropriate block: 6056 CGF.EmitBlock(InRegBlock); 6057 6058 llvm::Value *reg_top = nullptr; 6059 Address reg_top_p = 6060 CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index, "reg_top_p"); 6061 reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top"); 6062 Address BaseAddr(CGF.Builder.CreateInBoundsGEP(CGF.Int8Ty, reg_top, reg_offs), 6063 CharUnits::fromQuantity(IsFPR ? 16 : 8)); 6064 Address RegAddr = Address::invalid(); 6065 llvm::Type *MemTy = CGF.ConvertTypeForMem(Ty); 6066 6067 if (IsIndirect) { 6068 // If it's been passed indirectly (actually a struct), whatever we find from 6069 // stored registers or on the stack will actually be a struct **. 6070 MemTy = llvm::PointerType::getUnqual(MemTy); 6071 } 6072 6073 const Type *Base = nullptr; 6074 uint64_t NumMembers = 0; 6075 bool IsHFA = isHomogeneousAggregate(Ty, Base, NumMembers); 6076 if (IsHFA && NumMembers > 1) { 6077 // Homogeneous aggregates passed in registers will have their elements split 6078 // and stored 16-bytes apart regardless of size (they're notionally in qN, 6079 // qN+1, ...). We reload and store into a temporary local variable 6080 // contiguously. 6081 assert(!IsIndirect && "Homogeneous aggregates should be passed directly"); 6082 auto BaseTyInfo = getContext().getTypeInfoInChars(QualType(Base, 0)); 6083 llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0)); 6084 llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers); 6085 Address Tmp = CGF.CreateTempAlloca(HFATy, 6086 std::max(TyAlign, BaseTyInfo.Align)); 6087 6088 // On big-endian platforms, the value will be right-aligned in its slot. 6089 int Offset = 0; 6090 if (CGF.CGM.getDataLayout().isBigEndian() && 6091 BaseTyInfo.Width.getQuantity() < 16) 6092 Offset = 16 - BaseTyInfo.Width.getQuantity(); 6093 6094 for (unsigned i = 0; i < NumMembers; ++i) { 6095 CharUnits BaseOffset = CharUnits::fromQuantity(16 * i + Offset); 6096 Address LoadAddr = 6097 CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, BaseOffset); 6098 LoadAddr = CGF.Builder.CreateElementBitCast(LoadAddr, BaseTy); 6099 6100 Address StoreAddr = CGF.Builder.CreateConstArrayGEP(Tmp, i); 6101 6102 llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr); 6103 CGF.Builder.CreateStore(Elem, StoreAddr); 6104 } 6105 6106 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, MemTy); 6107 } else { 6108 // Otherwise the object is contiguous in memory. 6109 6110 // It might be right-aligned in its slot. 6111 CharUnits SlotSize = BaseAddr.getAlignment(); 6112 if (CGF.CGM.getDataLayout().isBigEndian() && !IsIndirect && 6113 (IsHFA || !isAggregateTypeForABI(Ty)) && 6114 TySize < SlotSize) { 6115 CharUnits Offset = SlotSize - TySize; 6116 BaseAddr = CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, Offset); 6117 } 6118 6119 RegAddr = CGF.Builder.CreateElementBitCast(BaseAddr, MemTy); 6120 } 6121 6122 CGF.EmitBranch(ContBlock); 6123 6124 //======================================= 6125 // Argument was on the stack 6126 //======================================= 6127 CGF.EmitBlock(OnStackBlock); 6128 6129 Address stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "stack_p"); 6130 llvm::Value *OnStackPtr = CGF.Builder.CreateLoad(stack_p, "stack"); 6131 6132 // Again, stack arguments may need realignment. In this case both integer and 6133 // floating-point ones might be affected. 6134 if (!IsIndirect && TyAlign.getQuantity() > 8) { 6135 int Align = TyAlign.getQuantity(); 6136 6137 OnStackPtr = CGF.Builder.CreatePtrToInt(OnStackPtr, CGF.Int64Ty); 6138 6139 OnStackPtr = CGF.Builder.CreateAdd( 6140 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1), 6141 "align_stack"); 6142 OnStackPtr = CGF.Builder.CreateAnd( 6143 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, -Align), 6144 "align_stack"); 6145 6146 OnStackPtr = CGF.Builder.CreateIntToPtr(OnStackPtr, CGF.Int8PtrTy); 6147 } 6148 Address OnStackAddr(OnStackPtr, 6149 std::max(CharUnits::fromQuantity(8), TyAlign)); 6150 6151 // All stack slots are multiples of 8 bytes. 6152 CharUnits StackSlotSize = CharUnits::fromQuantity(8); 6153 CharUnits StackSize; 6154 if (IsIndirect) 6155 StackSize = StackSlotSize; 6156 else 6157 StackSize = TySize.alignTo(StackSlotSize); 6158 6159 llvm::Value *StackSizeC = CGF.Builder.getSize(StackSize); 6160 llvm::Value *NewStack = CGF.Builder.CreateInBoundsGEP( 6161 CGF.Int8Ty, OnStackPtr, StackSizeC, "new_stack"); 6162 6163 // Write the new value of __stack for the next call to va_arg 6164 CGF.Builder.CreateStore(NewStack, stack_p); 6165 6166 if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) && 6167 TySize < StackSlotSize) { 6168 CharUnits Offset = StackSlotSize - TySize; 6169 OnStackAddr = CGF.Builder.CreateConstInBoundsByteGEP(OnStackAddr, Offset); 6170 } 6171 6172 OnStackAddr = CGF.Builder.CreateElementBitCast(OnStackAddr, MemTy); 6173 6174 CGF.EmitBranch(ContBlock); 6175 6176 //======================================= 6177 // Tidy up 6178 //======================================= 6179 CGF.EmitBlock(ContBlock); 6180 6181 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, 6182 OnStackAddr, OnStackBlock, "vaargs.addr"); 6183 6184 if (IsIndirect) 6185 return Address(CGF.Builder.CreateLoad(ResAddr, "vaarg.addr"), 6186 TyAlign); 6187 6188 return ResAddr; 6189 } 6190 6191 Address AArch64ABIInfo::EmitDarwinVAArg(Address VAListAddr, QualType Ty, 6192 CodeGenFunction &CGF) const { 6193 // The backend's lowering doesn't support va_arg for aggregates or 6194 // illegal vector types. Lower VAArg here for these cases and use 6195 // the LLVM va_arg instruction for everything else. 6196 if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty)) 6197 return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect()); 6198 6199 uint64_t PointerSize = getTarget().getPointerWidth(0) / 8; 6200 CharUnits SlotSize = CharUnits::fromQuantity(PointerSize); 6201 6202 // Empty records are ignored for parameter passing purposes. 6203 if (isEmptyRecord(getContext(), Ty, true)) { 6204 Address Addr(CGF.Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize); 6205 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty)); 6206 return Addr; 6207 } 6208 6209 // The size of the actual thing passed, which might end up just 6210 // being a pointer for indirect types. 6211 auto TyInfo = getContext().getTypeInfoInChars(Ty); 6212 6213 // Arguments bigger than 16 bytes which aren't homogeneous 6214 // aggregates should be passed indirectly. 6215 bool IsIndirect = false; 6216 if (TyInfo.Width.getQuantity() > 16) { 6217 const Type *Base = nullptr; 6218 uint64_t Members = 0; 6219 IsIndirect = !isHomogeneousAggregate(Ty, Base, Members); 6220 } 6221 6222 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, 6223 TyInfo, SlotSize, /*AllowHigherAlign*/ true); 6224 } 6225 6226 Address AArch64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr, 6227 QualType Ty) const { 6228 bool IsIndirect = false; 6229 6230 // Composites larger than 16 bytes are passed by reference. 6231 if (isAggregateTypeForABI(Ty) && getContext().getTypeSize(Ty) > 128) 6232 IsIndirect = true; 6233 6234 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, 6235 CGF.getContext().getTypeInfoInChars(Ty), 6236 CharUnits::fromQuantity(8), 6237 /*allowHigherAlign*/ false); 6238 } 6239 6240 //===----------------------------------------------------------------------===// 6241 // ARM ABI Implementation 6242 //===----------------------------------------------------------------------===// 6243 6244 namespace { 6245 6246 class ARMABIInfo : public SwiftABIInfo { 6247 public: 6248 enum ABIKind { 6249 APCS = 0, 6250 AAPCS = 1, 6251 AAPCS_VFP = 2, 6252 AAPCS16_VFP = 3, 6253 }; 6254 6255 private: 6256 ABIKind Kind; 6257 bool IsFloatABISoftFP; 6258 6259 public: 6260 ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind) 6261 : SwiftABIInfo(CGT), Kind(_Kind) { 6262 setCCs(); 6263 IsFloatABISoftFP = CGT.getCodeGenOpts().FloatABI == "softfp" || 6264 CGT.getCodeGenOpts().FloatABI == ""; // default 6265 } 6266 6267 bool isEABI() const { 6268 switch (getTarget().getTriple().getEnvironment()) { 6269 case llvm::Triple::Android: 6270 case llvm::Triple::EABI: 6271 case llvm::Triple::EABIHF: 6272 case llvm::Triple::GNUEABI: 6273 case llvm::Triple::GNUEABIHF: 6274 case llvm::Triple::MuslEABI: 6275 case llvm::Triple::MuslEABIHF: 6276 return true; 6277 default: 6278 return false; 6279 } 6280 } 6281 6282 bool isEABIHF() const { 6283 switch (getTarget().getTriple().getEnvironment()) { 6284 case llvm::Triple::EABIHF: 6285 case llvm::Triple::GNUEABIHF: 6286 case llvm::Triple::MuslEABIHF: 6287 return true; 6288 default: 6289 return false; 6290 } 6291 } 6292 6293 ABIKind getABIKind() const { return Kind; } 6294 6295 bool allowBFloatArgsAndRet() const override { 6296 return !IsFloatABISoftFP && getTarget().hasBFloat16Type(); 6297 } 6298 6299 private: 6300 ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic, 6301 unsigned functionCallConv) const; 6302 ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic, 6303 unsigned functionCallConv) const; 6304 ABIArgInfo classifyHomogeneousAggregate(QualType Ty, const Type *Base, 6305 uint64_t Members) const; 6306 ABIArgInfo coerceIllegalVector(QualType Ty) const; 6307 bool isIllegalVectorType(QualType Ty) const; 6308 bool containsAnyFP16Vectors(QualType Ty) const; 6309 6310 bool isHomogeneousAggregateBaseType(QualType Ty) const override; 6311 bool isHomogeneousAggregateSmallEnough(const Type *Ty, 6312 uint64_t Members) const override; 6313 6314 bool isEffectivelyAAPCS_VFP(unsigned callConvention, bool acceptHalf) const; 6315 6316 void computeInfo(CGFunctionInfo &FI) const override; 6317 6318 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 6319 QualType Ty) const override; 6320 6321 llvm::CallingConv::ID getLLVMDefaultCC() const; 6322 llvm::CallingConv::ID getABIDefaultCC() const; 6323 void setCCs(); 6324 6325 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars, 6326 bool asReturnValue) const override { 6327 return occupiesMoreThan(CGT, scalars, /*total*/ 4); 6328 } 6329 bool isSwiftErrorInRegister() const override { 6330 return true; 6331 } 6332 bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy, 6333 unsigned elts) const override; 6334 }; 6335 6336 class ARMTargetCodeGenInfo : public TargetCodeGenInfo { 6337 public: 6338 ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K) 6339 : TargetCodeGenInfo(std::make_unique<ARMABIInfo>(CGT, K)) {} 6340 6341 const ARMABIInfo &getABIInfo() const { 6342 return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo()); 6343 } 6344 6345 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 6346 return 13; 6347 } 6348 6349 StringRef getARCRetainAutoreleasedReturnValueMarker() const override { 6350 return "mov\tr7, r7\t\t// marker for objc_retainAutoreleaseReturnValue"; 6351 } 6352 6353 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 6354 llvm::Value *Address) const override { 6355 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4); 6356 6357 // 0-15 are the 16 integer registers. 6358 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15); 6359 return false; 6360 } 6361 6362 unsigned getSizeOfUnwindException() const override { 6363 if (getABIInfo().isEABI()) return 88; 6364 return TargetCodeGenInfo::getSizeOfUnwindException(); 6365 } 6366 6367 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 6368 CodeGen::CodeGenModule &CGM) const override { 6369 if (GV->isDeclaration()) 6370 return; 6371 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D); 6372 if (!FD) 6373 return; 6374 auto *Fn = cast<llvm::Function>(GV); 6375 6376 if (const auto *TA = FD->getAttr<TargetAttr>()) { 6377 ParsedTargetAttr Attr = TA->parse(); 6378 if (!Attr.BranchProtection.empty()) { 6379 TargetInfo::BranchProtectionInfo BPI; 6380 StringRef DiagMsg; 6381 StringRef Arch = Attr.Architecture.empty() 6382 ? CGM.getTarget().getTargetOpts().CPU 6383 : Attr.Architecture; 6384 if (!CGM.getTarget().validateBranchProtection(Attr.BranchProtection, 6385 Arch, BPI, DiagMsg)) { 6386 CGM.getDiags().Report( 6387 D->getLocation(), 6388 diag::warn_target_unsupported_branch_protection_attribute) 6389 << Arch; 6390 } else { 6391 static const char *SignReturnAddrStr[] = {"none", "non-leaf", "all"}; 6392 assert(static_cast<unsigned>(BPI.SignReturnAddr) <= 2 && 6393 "Unexpected SignReturnAddressScopeKind"); 6394 Fn->addFnAttr( 6395 "sign-return-address", 6396 SignReturnAddrStr[static_cast<int>(BPI.SignReturnAddr)]); 6397 6398 Fn->addFnAttr("branch-target-enforcement", 6399 BPI.BranchTargetEnforcement ? "true" : "false"); 6400 } 6401 } else if (CGM.getLangOpts().BranchTargetEnforcement || 6402 CGM.getLangOpts().hasSignReturnAddress()) { 6403 // If the Branch Protection attribute is missing, validate the target 6404 // Architecture attribute against Branch Protection command line 6405 // settings. 6406 if (!CGM.getTarget().isBranchProtectionSupportedArch(Attr.Architecture)) 6407 CGM.getDiags().Report( 6408 D->getLocation(), 6409 diag::warn_target_unsupported_branch_protection_attribute) 6410 << Attr.Architecture; 6411 } 6412 } 6413 6414 const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>(); 6415 if (!Attr) 6416 return; 6417 6418 const char *Kind; 6419 switch (Attr->getInterrupt()) { 6420 case ARMInterruptAttr::Generic: Kind = ""; break; 6421 case ARMInterruptAttr::IRQ: Kind = "IRQ"; break; 6422 case ARMInterruptAttr::FIQ: Kind = "FIQ"; break; 6423 case ARMInterruptAttr::SWI: Kind = "SWI"; break; 6424 case ARMInterruptAttr::ABORT: Kind = "ABORT"; break; 6425 case ARMInterruptAttr::UNDEF: Kind = "UNDEF"; break; 6426 } 6427 6428 Fn->addFnAttr("interrupt", Kind); 6429 6430 ARMABIInfo::ABIKind ABI = cast<ARMABIInfo>(getABIInfo()).getABIKind(); 6431 if (ABI == ARMABIInfo::APCS) 6432 return; 6433 6434 // AAPCS guarantees that sp will be 8-byte aligned on any public interface, 6435 // however this is not necessarily true on taking any interrupt. Instruct 6436 // the backend to perform a realignment as part of the function prologue. 6437 llvm::AttrBuilder B(Fn->getContext()); 6438 B.addStackAlignmentAttr(8); 6439 Fn->addFnAttrs(B); 6440 } 6441 }; 6442 6443 class WindowsARMTargetCodeGenInfo : public ARMTargetCodeGenInfo { 6444 public: 6445 WindowsARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K) 6446 : ARMTargetCodeGenInfo(CGT, K) {} 6447 6448 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 6449 CodeGen::CodeGenModule &CGM) const override; 6450 6451 void getDependentLibraryOption(llvm::StringRef Lib, 6452 llvm::SmallString<24> &Opt) const override { 6453 Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib); 6454 } 6455 6456 void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value, 6457 llvm::SmallString<32> &Opt) const override { 6458 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\""; 6459 } 6460 }; 6461 6462 void WindowsARMTargetCodeGenInfo::setTargetAttributes( 6463 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const { 6464 ARMTargetCodeGenInfo::setTargetAttributes(D, GV, CGM); 6465 if (GV->isDeclaration()) 6466 return; 6467 addStackProbeTargetAttributes(D, GV, CGM); 6468 } 6469 } 6470 6471 void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const { 6472 if (!::classifyReturnType(getCXXABI(), FI, *this)) 6473 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), FI.isVariadic(), 6474 FI.getCallingConvention()); 6475 6476 for (auto &I : FI.arguments()) 6477 I.info = classifyArgumentType(I.type, FI.isVariadic(), 6478 FI.getCallingConvention()); 6479 6480 6481 // Always honor user-specified calling convention. 6482 if (FI.getCallingConvention() != llvm::CallingConv::C) 6483 return; 6484 6485 llvm::CallingConv::ID cc = getRuntimeCC(); 6486 if (cc != llvm::CallingConv::C) 6487 FI.setEffectiveCallingConvention(cc); 6488 } 6489 6490 /// Return the default calling convention that LLVM will use. 6491 llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const { 6492 // The default calling convention that LLVM will infer. 6493 if (isEABIHF() || getTarget().getTriple().isWatchABI()) 6494 return llvm::CallingConv::ARM_AAPCS_VFP; 6495 else if (isEABI()) 6496 return llvm::CallingConv::ARM_AAPCS; 6497 else 6498 return llvm::CallingConv::ARM_APCS; 6499 } 6500 6501 /// Return the calling convention that our ABI would like us to use 6502 /// as the C calling convention. 6503 llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const { 6504 switch (getABIKind()) { 6505 case APCS: return llvm::CallingConv::ARM_APCS; 6506 case AAPCS: return llvm::CallingConv::ARM_AAPCS; 6507 case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP; 6508 case AAPCS16_VFP: return llvm::CallingConv::ARM_AAPCS_VFP; 6509 } 6510 llvm_unreachable("bad ABI kind"); 6511 } 6512 6513 void ARMABIInfo::setCCs() { 6514 assert(getRuntimeCC() == llvm::CallingConv::C); 6515 6516 // Don't muddy up the IR with a ton of explicit annotations if 6517 // they'd just match what LLVM will infer from the triple. 6518 llvm::CallingConv::ID abiCC = getABIDefaultCC(); 6519 if (abiCC != getLLVMDefaultCC()) 6520 RuntimeCC = abiCC; 6521 } 6522 6523 ABIArgInfo ARMABIInfo::coerceIllegalVector(QualType Ty) const { 6524 uint64_t Size = getContext().getTypeSize(Ty); 6525 if (Size <= 32) { 6526 llvm::Type *ResType = 6527 llvm::Type::getInt32Ty(getVMContext()); 6528 return ABIArgInfo::getDirect(ResType); 6529 } 6530 if (Size == 64 || Size == 128) { 6531 auto *ResType = llvm::FixedVectorType::get( 6532 llvm::Type::getInt32Ty(getVMContext()), Size / 32); 6533 return ABIArgInfo::getDirect(ResType); 6534 } 6535 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 6536 } 6537 6538 ABIArgInfo ARMABIInfo::classifyHomogeneousAggregate(QualType Ty, 6539 const Type *Base, 6540 uint64_t Members) const { 6541 assert(Base && "Base class should be set for homogeneous aggregate"); 6542 // Base can be a floating-point or a vector. 6543 if (const VectorType *VT = Base->getAs<VectorType>()) { 6544 // FP16 vectors should be converted to integer vectors 6545 if (!getTarget().hasLegalHalfType() && containsAnyFP16Vectors(Ty)) { 6546 uint64_t Size = getContext().getTypeSize(VT); 6547 auto *NewVecTy = llvm::FixedVectorType::get( 6548 llvm::Type::getInt32Ty(getVMContext()), Size / 32); 6549 llvm::Type *Ty = llvm::ArrayType::get(NewVecTy, Members); 6550 return ABIArgInfo::getDirect(Ty, 0, nullptr, false); 6551 } 6552 } 6553 unsigned Align = 0; 6554 if (getABIKind() == ARMABIInfo::AAPCS || 6555 getABIKind() == ARMABIInfo::AAPCS_VFP) { 6556 // For alignment adjusted HFAs, cap the argument alignment to 8, leave it 6557 // default otherwise. 6558 Align = getContext().getTypeUnadjustedAlignInChars(Ty).getQuantity(); 6559 unsigned BaseAlign = getContext().getTypeAlignInChars(Base).getQuantity(); 6560 Align = (Align > BaseAlign && Align >= 8) ? 8 : 0; 6561 } 6562 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false, Align); 6563 } 6564 6565 ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty, bool isVariadic, 6566 unsigned functionCallConv) const { 6567 // 6.1.2.1 The following argument types are VFP CPRCs: 6568 // A single-precision floating-point type (including promoted 6569 // half-precision types); A double-precision floating-point type; 6570 // A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate 6571 // with a Base Type of a single- or double-precision floating-point type, 6572 // 64-bit containerized vectors or 128-bit containerized vectors with one 6573 // to four Elements. 6574 // Variadic functions should always marshal to the base standard. 6575 bool IsAAPCS_VFP = 6576 !isVariadic && isEffectivelyAAPCS_VFP(functionCallConv, /* AAPCS16 */ false); 6577 6578 Ty = useFirstFieldIfTransparentUnion(Ty); 6579 6580 // Handle illegal vector types here. 6581 if (isIllegalVectorType(Ty)) 6582 return coerceIllegalVector(Ty); 6583 6584 if (!isAggregateTypeForABI(Ty)) { 6585 // Treat an enum type as its underlying type. 6586 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) { 6587 Ty = EnumTy->getDecl()->getIntegerType(); 6588 } 6589 6590 if (const auto *EIT = Ty->getAs<BitIntType>()) 6591 if (EIT->getNumBits() > 64) 6592 return getNaturalAlignIndirect(Ty, /*ByVal=*/true); 6593 6594 return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty) 6595 : ABIArgInfo::getDirect()); 6596 } 6597 6598 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) { 6599 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 6600 } 6601 6602 // Ignore empty records. 6603 if (isEmptyRecord(getContext(), Ty, true)) 6604 return ABIArgInfo::getIgnore(); 6605 6606 if (IsAAPCS_VFP) { 6607 // Homogeneous Aggregates need to be expanded when we can fit the aggregate 6608 // into VFP registers. 6609 const Type *Base = nullptr; 6610 uint64_t Members = 0; 6611 if (isHomogeneousAggregate(Ty, Base, Members)) 6612 return classifyHomogeneousAggregate(Ty, Base, Members); 6613 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) { 6614 // WatchOS does have homogeneous aggregates. Note that we intentionally use 6615 // this convention even for a variadic function: the backend will use GPRs 6616 // if needed. 6617 const Type *Base = nullptr; 6618 uint64_t Members = 0; 6619 if (isHomogeneousAggregate(Ty, Base, Members)) { 6620 assert(Base && Members <= 4 && "unexpected homogeneous aggregate"); 6621 llvm::Type *Ty = 6622 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members); 6623 return ABIArgInfo::getDirect(Ty, 0, nullptr, false); 6624 } 6625 } 6626 6627 if (getABIKind() == ARMABIInfo::AAPCS16_VFP && 6628 getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(16)) { 6629 // WatchOS is adopting the 64-bit AAPCS rule on composite types: if they're 6630 // bigger than 128-bits, they get placed in space allocated by the caller, 6631 // and a pointer is passed. 6632 return ABIArgInfo::getIndirect( 6633 CharUnits::fromQuantity(getContext().getTypeAlign(Ty) / 8), false); 6634 } 6635 6636 // Support byval for ARM. 6637 // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at 6638 // most 8-byte. We realign the indirect argument if type alignment is bigger 6639 // than ABI alignment. 6640 uint64_t ABIAlign = 4; 6641 uint64_t TyAlign; 6642 if (getABIKind() == ARMABIInfo::AAPCS_VFP || 6643 getABIKind() == ARMABIInfo::AAPCS) { 6644 TyAlign = getContext().getTypeUnadjustedAlignInChars(Ty).getQuantity(); 6645 ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8); 6646 } else { 6647 TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity(); 6648 } 6649 if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) { 6650 assert(getABIKind() != ARMABIInfo::AAPCS16_VFP && "unexpected byval"); 6651 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign), 6652 /*ByVal=*/true, 6653 /*Realign=*/TyAlign > ABIAlign); 6654 } 6655 6656 // On RenderScript, coerce Aggregates <= 64 bytes to an integer array of 6657 // same size and alignment. 6658 if (getTarget().isRenderScriptTarget()) { 6659 return coerceToIntArray(Ty, getContext(), getVMContext()); 6660 } 6661 6662 // Otherwise, pass by coercing to a structure of the appropriate size. 6663 llvm::Type* ElemTy; 6664 unsigned SizeRegs; 6665 // FIXME: Try to match the types of the arguments more accurately where 6666 // we can. 6667 if (TyAlign <= 4) { 6668 ElemTy = llvm::Type::getInt32Ty(getVMContext()); 6669 SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32; 6670 } else { 6671 ElemTy = llvm::Type::getInt64Ty(getVMContext()); 6672 SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64; 6673 } 6674 6675 return ABIArgInfo::getDirect(llvm::ArrayType::get(ElemTy, SizeRegs)); 6676 } 6677 6678 static bool isIntegerLikeType(QualType Ty, ASTContext &Context, 6679 llvm::LLVMContext &VMContext) { 6680 // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure 6681 // is called integer-like if its size is less than or equal to one word, and 6682 // the offset of each of its addressable sub-fields is zero. 6683 6684 uint64_t Size = Context.getTypeSize(Ty); 6685 6686 // Check that the type fits in a word. 6687 if (Size > 32) 6688 return false; 6689 6690 // FIXME: Handle vector types! 6691 if (Ty->isVectorType()) 6692 return false; 6693 6694 // Float types are never treated as "integer like". 6695 if (Ty->isRealFloatingType()) 6696 return false; 6697 6698 // If this is a builtin or pointer type then it is ok. 6699 if (Ty->getAs<BuiltinType>() || Ty->isPointerType()) 6700 return true; 6701 6702 // Small complex integer types are "integer like". 6703 if (const ComplexType *CT = Ty->getAs<ComplexType>()) 6704 return isIntegerLikeType(CT->getElementType(), Context, VMContext); 6705 6706 // Single element and zero sized arrays should be allowed, by the definition 6707 // above, but they are not. 6708 6709 // Otherwise, it must be a record type. 6710 const RecordType *RT = Ty->getAs<RecordType>(); 6711 if (!RT) return false; 6712 6713 // Ignore records with flexible arrays. 6714 const RecordDecl *RD = RT->getDecl(); 6715 if (RD->hasFlexibleArrayMember()) 6716 return false; 6717 6718 // Check that all sub-fields are at offset 0, and are themselves "integer 6719 // like". 6720 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); 6721 6722 bool HadField = false; 6723 unsigned idx = 0; 6724 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 6725 i != e; ++i, ++idx) { 6726 const FieldDecl *FD = *i; 6727 6728 // Bit-fields are not addressable, we only need to verify they are "integer 6729 // like". We still have to disallow a subsequent non-bitfield, for example: 6730 // struct { int : 0; int x } 6731 // is non-integer like according to gcc. 6732 if (FD->isBitField()) { 6733 if (!RD->isUnion()) 6734 HadField = true; 6735 6736 if (!isIntegerLikeType(FD->getType(), Context, VMContext)) 6737 return false; 6738 6739 continue; 6740 } 6741 6742 // Check if this field is at offset 0. 6743 if (Layout.getFieldOffset(idx) != 0) 6744 return false; 6745 6746 if (!isIntegerLikeType(FD->getType(), Context, VMContext)) 6747 return false; 6748 6749 // Only allow at most one field in a structure. This doesn't match the 6750 // wording above, but follows gcc in situations with a field following an 6751 // empty structure. 6752 if (!RD->isUnion()) { 6753 if (HadField) 6754 return false; 6755 6756 HadField = true; 6757 } 6758 } 6759 6760 return true; 6761 } 6762 6763 ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy, bool isVariadic, 6764 unsigned functionCallConv) const { 6765 6766 // Variadic functions should always marshal to the base standard. 6767 bool IsAAPCS_VFP = 6768 !isVariadic && isEffectivelyAAPCS_VFP(functionCallConv, /* AAPCS16 */ true); 6769 6770 if (RetTy->isVoidType()) 6771 return ABIArgInfo::getIgnore(); 6772 6773 if (const VectorType *VT = RetTy->getAs<VectorType>()) { 6774 // Large vector types should be returned via memory. 6775 if (getContext().getTypeSize(RetTy) > 128) 6776 return getNaturalAlignIndirect(RetTy); 6777 // TODO: FP16/BF16 vectors should be converted to integer vectors 6778 // This check is similar to isIllegalVectorType - refactor? 6779 if ((!getTarget().hasLegalHalfType() && 6780 (VT->getElementType()->isFloat16Type() || 6781 VT->getElementType()->isHalfType())) || 6782 (IsFloatABISoftFP && 6783 VT->getElementType()->isBFloat16Type())) 6784 return coerceIllegalVector(RetTy); 6785 } 6786 6787 if (!isAggregateTypeForABI(RetTy)) { 6788 // Treat an enum type as its underlying type. 6789 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 6790 RetTy = EnumTy->getDecl()->getIntegerType(); 6791 6792 if (const auto *EIT = RetTy->getAs<BitIntType>()) 6793 if (EIT->getNumBits() > 64) 6794 return getNaturalAlignIndirect(RetTy, /*ByVal=*/false); 6795 6796 return isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy) 6797 : ABIArgInfo::getDirect(); 6798 } 6799 6800 // Are we following APCS? 6801 if (getABIKind() == APCS) { 6802 if (isEmptyRecord(getContext(), RetTy, false)) 6803 return ABIArgInfo::getIgnore(); 6804 6805 // Complex types are all returned as packed integers. 6806 // 6807 // FIXME: Consider using 2 x vector types if the back end handles them 6808 // correctly. 6809 if (RetTy->isAnyComplexType()) 6810 return ABIArgInfo::getDirect(llvm::IntegerType::get( 6811 getVMContext(), getContext().getTypeSize(RetTy))); 6812 6813 // Integer like structures are returned in r0. 6814 if (isIntegerLikeType(RetTy, getContext(), getVMContext())) { 6815 // Return in the smallest viable integer type. 6816 uint64_t Size = getContext().getTypeSize(RetTy); 6817 if (Size <= 8) 6818 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext())); 6819 if (Size <= 16) 6820 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext())); 6821 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext())); 6822 } 6823 6824 // Otherwise return in memory. 6825 return getNaturalAlignIndirect(RetTy); 6826 } 6827 6828 // Otherwise this is an AAPCS variant. 6829 6830 if (isEmptyRecord(getContext(), RetTy, true)) 6831 return ABIArgInfo::getIgnore(); 6832 6833 // Check for homogeneous aggregates with AAPCS-VFP. 6834 if (IsAAPCS_VFP) { 6835 const Type *Base = nullptr; 6836 uint64_t Members = 0; 6837 if (isHomogeneousAggregate(RetTy, Base, Members)) 6838 return classifyHomogeneousAggregate(RetTy, Base, Members); 6839 } 6840 6841 // Aggregates <= 4 bytes are returned in r0; other aggregates 6842 // are returned indirectly. 6843 uint64_t Size = getContext().getTypeSize(RetTy); 6844 if (Size <= 32) { 6845 // On RenderScript, coerce Aggregates <= 4 bytes to an integer array of 6846 // same size and alignment. 6847 if (getTarget().isRenderScriptTarget()) { 6848 return coerceToIntArray(RetTy, getContext(), getVMContext()); 6849 } 6850 if (getDataLayout().isBigEndian()) 6851 // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4) 6852 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext())); 6853 6854 // Return in the smallest viable integer type. 6855 if (Size <= 8) 6856 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext())); 6857 if (Size <= 16) 6858 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext())); 6859 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext())); 6860 } else if (Size <= 128 && getABIKind() == AAPCS16_VFP) { 6861 llvm::Type *Int32Ty = llvm::Type::getInt32Ty(getVMContext()); 6862 llvm::Type *CoerceTy = 6863 llvm::ArrayType::get(Int32Ty, llvm::alignTo(Size, 32) / 32); 6864 return ABIArgInfo::getDirect(CoerceTy); 6865 } 6866 6867 return getNaturalAlignIndirect(RetTy); 6868 } 6869 6870 /// isIllegalVector - check whether Ty is an illegal vector type. 6871 bool ARMABIInfo::isIllegalVectorType(QualType Ty) const { 6872 if (const VectorType *VT = Ty->getAs<VectorType> ()) { 6873 // On targets that don't support half, fp16 or bfloat, they are expanded 6874 // into float, and we don't want the ABI to depend on whether or not they 6875 // are supported in hardware. Thus return false to coerce vectors of these 6876 // types into integer vectors. 6877 // We do not depend on hasLegalHalfType for bfloat as it is a 6878 // separate IR type. 6879 if ((!getTarget().hasLegalHalfType() && 6880 (VT->getElementType()->isFloat16Type() || 6881 VT->getElementType()->isHalfType())) || 6882 (IsFloatABISoftFP && 6883 VT->getElementType()->isBFloat16Type())) 6884 return true; 6885 if (isAndroid()) { 6886 // Android shipped using Clang 3.1, which supported a slightly different 6887 // vector ABI. The primary differences were that 3-element vector types 6888 // were legal, and so were sub 32-bit vectors (i.e. <2 x i8>). This path 6889 // accepts that legacy behavior for Android only. 6890 // Check whether VT is legal. 6891 unsigned NumElements = VT->getNumElements(); 6892 // NumElements should be power of 2 or equal to 3. 6893 if (!llvm::isPowerOf2_32(NumElements) && NumElements != 3) 6894 return true; 6895 } else { 6896 // Check whether VT is legal. 6897 unsigned NumElements = VT->getNumElements(); 6898 uint64_t Size = getContext().getTypeSize(VT); 6899 // NumElements should be power of 2. 6900 if (!llvm::isPowerOf2_32(NumElements)) 6901 return true; 6902 // Size should be greater than 32 bits. 6903 return Size <= 32; 6904 } 6905 } 6906 return false; 6907 } 6908 6909 /// Return true if a type contains any 16-bit floating point vectors 6910 bool ARMABIInfo::containsAnyFP16Vectors(QualType Ty) const { 6911 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) { 6912 uint64_t NElements = AT->getSize().getZExtValue(); 6913 if (NElements == 0) 6914 return false; 6915 return containsAnyFP16Vectors(AT->getElementType()); 6916 } else if (const RecordType *RT = Ty->getAs<RecordType>()) { 6917 const RecordDecl *RD = RT->getDecl(); 6918 6919 // If this is a C++ record, check the bases first. 6920 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 6921 if (llvm::any_of(CXXRD->bases(), [this](const CXXBaseSpecifier &B) { 6922 return containsAnyFP16Vectors(B.getType()); 6923 })) 6924 return true; 6925 6926 if (llvm::any_of(RD->fields(), [this](FieldDecl *FD) { 6927 return FD && containsAnyFP16Vectors(FD->getType()); 6928 })) 6929 return true; 6930 6931 return false; 6932 } else { 6933 if (const VectorType *VT = Ty->getAs<VectorType>()) 6934 return (VT->getElementType()->isFloat16Type() || 6935 VT->getElementType()->isBFloat16Type() || 6936 VT->getElementType()->isHalfType()); 6937 return false; 6938 } 6939 } 6940 6941 bool ARMABIInfo::isLegalVectorTypeForSwift(CharUnits vectorSize, 6942 llvm::Type *eltTy, 6943 unsigned numElts) const { 6944 if (!llvm::isPowerOf2_32(numElts)) 6945 return false; 6946 unsigned size = getDataLayout().getTypeStoreSizeInBits(eltTy); 6947 if (size > 64) 6948 return false; 6949 if (vectorSize.getQuantity() != 8 && 6950 (vectorSize.getQuantity() != 16 || numElts == 1)) 6951 return false; 6952 return true; 6953 } 6954 6955 bool ARMABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const { 6956 // Homogeneous aggregates for AAPCS-VFP must have base types of float, 6957 // double, or 64-bit or 128-bit vectors. 6958 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) { 6959 if (BT->getKind() == BuiltinType::Float || 6960 BT->getKind() == BuiltinType::Double || 6961 BT->getKind() == BuiltinType::LongDouble) 6962 return true; 6963 } else if (const VectorType *VT = Ty->getAs<VectorType>()) { 6964 unsigned VecSize = getContext().getTypeSize(VT); 6965 if (VecSize == 64 || VecSize == 128) 6966 return true; 6967 } 6968 return false; 6969 } 6970 6971 bool ARMABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base, 6972 uint64_t Members) const { 6973 return Members <= 4; 6974 } 6975 6976 bool ARMABIInfo::isEffectivelyAAPCS_VFP(unsigned callConvention, 6977 bool acceptHalf) const { 6978 // Give precedence to user-specified calling conventions. 6979 if (callConvention != llvm::CallingConv::C) 6980 return (callConvention == llvm::CallingConv::ARM_AAPCS_VFP); 6981 else 6982 return (getABIKind() == AAPCS_VFP) || 6983 (acceptHalf && (getABIKind() == AAPCS16_VFP)); 6984 } 6985 6986 Address ARMABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 6987 QualType Ty) const { 6988 CharUnits SlotSize = CharUnits::fromQuantity(4); 6989 6990 // Empty records are ignored for parameter passing purposes. 6991 if (isEmptyRecord(getContext(), Ty, true)) { 6992 Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize); 6993 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty)); 6994 return Addr; 6995 } 6996 6997 CharUnits TySize = getContext().getTypeSizeInChars(Ty); 6998 CharUnits TyAlignForABI = getContext().getTypeUnadjustedAlignInChars(Ty); 6999 7000 // Use indirect if size of the illegal vector is bigger than 16 bytes. 7001 bool IsIndirect = false; 7002 const Type *Base = nullptr; 7003 uint64_t Members = 0; 7004 if (TySize > CharUnits::fromQuantity(16) && isIllegalVectorType(Ty)) { 7005 IsIndirect = true; 7006 7007 // ARMv7k passes structs bigger than 16 bytes indirectly, in space 7008 // allocated by the caller. 7009 } else if (TySize > CharUnits::fromQuantity(16) && 7010 getABIKind() == ARMABIInfo::AAPCS16_VFP && 7011 !isHomogeneousAggregate(Ty, Base, Members)) { 7012 IsIndirect = true; 7013 7014 // Otherwise, bound the type's ABI alignment. 7015 // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for 7016 // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte. 7017 // Our callers should be prepared to handle an under-aligned address. 7018 } else if (getABIKind() == ARMABIInfo::AAPCS_VFP || 7019 getABIKind() == ARMABIInfo::AAPCS) { 7020 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4)); 7021 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(8)); 7022 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) { 7023 // ARMv7k allows type alignment up to 16 bytes. 7024 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4)); 7025 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(16)); 7026 } else { 7027 TyAlignForABI = CharUnits::fromQuantity(4); 7028 } 7029 7030 TypeInfoChars TyInfo(TySize, TyAlignForABI, AlignRequirementKind::None); 7031 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TyInfo, 7032 SlotSize, /*AllowHigherAlign*/ true); 7033 } 7034 7035 //===----------------------------------------------------------------------===// 7036 // NVPTX ABI Implementation 7037 //===----------------------------------------------------------------------===// 7038 7039 namespace { 7040 7041 class NVPTXTargetCodeGenInfo; 7042 7043 class NVPTXABIInfo : public ABIInfo { 7044 NVPTXTargetCodeGenInfo &CGInfo; 7045 7046 public: 7047 NVPTXABIInfo(CodeGenTypes &CGT, NVPTXTargetCodeGenInfo &Info) 7048 : ABIInfo(CGT), CGInfo(Info) {} 7049 7050 ABIArgInfo classifyReturnType(QualType RetTy) const; 7051 ABIArgInfo classifyArgumentType(QualType Ty) const; 7052 7053 void computeInfo(CGFunctionInfo &FI) const override; 7054 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 7055 QualType Ty) const override; 7056 bool isUnsupportedType(QualType T) const; 7057 ABIArgInfo coerceToIntArrayWithLimit(QualType Ty, unsigned MaxSize) const; 7058 }; 7059 7060 class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo { 7061 public: 7062 NVPTXTargetCodeGenInfo(CodeGenTypes &CGT) 7063 : TargetCodeGenInfo(std::make_unique<NVPTXABIInfo>(CGT, *this)) {} 7064 7065 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 7066 CodeGen::CodeGenModule &M) const override; 7067 bool shouldEmitStaticExternCAliases() const override; 7068 7069 llvm::Type *getCUDADeviceBuiltinSurfaceDeviceType() const override { 7070 // On the device side, surface reference is represented as an object handle 7071 // in 64-bit integer. 7072 return llvm::Type::getInt64Ty(getABIInfo().getVMContext()); 7073 } 7074 7075 llvm::Type *getCUDADeviceBuiltinTextureDeviceType() const override { 7076 // On the device side, texture reference is represented as an object handle 7077 // in 64-bit integer. 7078 return llvm::Type::getInt64Ty(getABIInfo().getVMContext()); 7079 } 7080 7081 bool emitCUDADeviceBuiltinSurfaceDeviceCopy(CodeGenFunction &CGF, LValue Dst, 7082 LValue Src) const override { 7083 emitBuiltinSurfTexDeviceCopy(CGF, Dst, Src); 7084 return true; 7085 } 7086 7087 bool emitCUDADeviceBuiltinTextureDeviceCopy(CodeGenFunction &CGF, LValue Dst, 7088 LValue Src) const override { 7089 emitBuiltinSurfTexDeviceCopy(CGF, Dst, Src); 7090 return true; 7091 } 7092 7093 private: 7094 // Adds a NamedMDNode with GV, Name, and Operand as operands, and adds the 7095 // resulting MDNode to the nvvm.annotations MDNode. 7096 static void addNVVMMetadata(llvm::GlobalValue *GV, StringRef Name, 7097 int Operand); 7098 7099 static void emitBuiltinSurfTexDeviceCopy(CodeGenFunction &CGF, LValue Dst, 7100 LValue Src) { 7101 llvm::Value *Handle = nullptr; 7102 llvm::Constant *C = 7103 llvm::dyn_cast<llvm::Constant>(Src.getAddress(CGF).getPointer()); 7104 // Lookup `addrspacecast` through the constant pointer if any. 7105 if (auto *ASC = llvm::dyn_cast_or_null<llvm::AddrSpaceCastOperator>(C)) 7106 C = llvm::cast<llvm::Constant>(ASC->getPointerOperand()); 7107 if (auto *GV = llvm::dyn_cast_or_null<llvm::GlobalVariable>(C)) { 7108 // Load the handle from the specific global variable using 7109 // `nvvm.texsurf.handle.internal` intrinsic. 7110 Handle = CGF.EmitRuntimeCall( 7111 CGF.CGM.getIntrinsic(llvm::Intrinsic::nvvm_texsurf_handle_internal, 7112 {GV->getType()}), 7113 {GV}, "texsurf_handle"); 7114 } else 7115 Handle = CGF.EmitLoadOfScalar(Src, SourceLocation()); 7116 CGF.EmitStoreOfScalar(Handle, Dst); 7117 } 7118 }; 7119 7120 /// Checks if the type is unsupported directly by the current target. 7121 bool NVPTXABIInfo::isUnsupportedType(QualType T) const { 7122 ASTContext &Context = getContext(); 7123 if (!Context.getTargetInfo().hasFloat16Type() && T->isFloat16Type()) 7124 return true; 7125 if (!Context.getTargetInfo().hasFloat128Type() && 7126 (T->isFloat128Type() || 7127 (T->isRealFloatingType() && Context.getTypeSize(T) == 128))) 7128 return true; 7129 if (const auto *EIT = T->getAs<BitIntType>()) 7130 return EIT->getNumBits() > 7131 (Context.getTargetInfo().hasInt128Type() ? 128U : 64U); 7132 if (!Context.getTargetInfo().hasInt128Type() && T->isIntegerType() && 7133 Context.getTypeSize(T) > 64U) 7134 return true; 7135 if (const auto *AT = T->getAsArrayTypeUnsafe()) 7136 return isUnsupportedType(AT->getElementType()); 7137 const auto *RT = T->getAs<RecordType>(); 7138 if (!RT) 7139 return false; 7140 const RecordDecl *RD = RT->getDecl(); 7141 7142 // If this is a C++ record, check the bases first. 7143 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 7144 for (const CXXBaseSpecifier &I : CXXRD->bases()) 7145 if (isUnsupportedType(I.getType())) 7146 return true; 7147 7148 for (const FieldDecl *I : RD->fields()) 7149 if (isUnsupportedType(I->getType())) 7150 return true; 7151 return false; 7152 } 7153 7154 /// Coerce the given type into an array with maximum allowed size of elements. 7155 ABIArgInfo NVPTXABIInfo::coerceToIntArrayWithLimit(QualType Ty, 7156 unsigned MaxSize) const { 7157 // Alignment and Size are measured in bits. 7158 const uint64_t Size = getContext().getTypeSize(Ty); 7159 const uint64_t Alignment = getContext().getTypeAlign(Ty); 7160 const unsigned Div = std::min<unsigned>(MaxSize, Alignment); 7161 llvm::Type *IntType = llvm::Type::getIntNTy(getVMContext(), Div); 7162 const uint64_t NumElements = (Size + Div - 1) / Div; 7163 return ABIArgInfo::getDirect(llvm::ArrayType::get(IntType, NumElements)); 7164 } 7165 7166 ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const { 7167 if (RetTy->isVoidType()) 7168 return ABIArgInfo::getIgnore(); 7169 7170 if (getContext().getLangOpts().OpenMP && 7171 getContext().getLangOpts().OpenMPIsDevice && isUnsupportedType(RetTy)) 7172 return coerceToIntArrayWithLimit(RetTy, 64); 7173 7174 // note: this is different from default ABI 7175 if (!RetTy->isScalarType()) 7176 return ABIArgInfo::getDirect(); 7177 7178 // Treat an enum type as its underlying type. 7179 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 7180 RetTy = EnumTy->getDecl()->getIntegerType(); 7181 7182 return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy) 7183 : ABIArgInfo::getDirect()); 7184 } 7185 7186 ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const { 7187 // Treat an enum type as its underlying type. 7188 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 7189 Ty = EnumTy->getDecl()->getIntegerType(); 7190 7191 // Return aggregates type as indirect by value 7192 if (isAggregateTypeForABI(Ty)) { 7193 // Under CUDA device compilation, tex/surf builtin types are replaced with 7194 // object types and passed directly. 7195 if (getContext().getLangOpts().CUDAIsDevice) { 7196 if (Ty->isCUDADeviceBuiltinSurfaceType()) 7197 return ABIArgInfo::getDirect( 7198 CGInfo.getCUDADeviceBuiltinSurfaceDeviceType()); 7199 if (Ty->isCUDADeviceBuiltinTextureType()) 7200 return ABIArgInfo::getDirect( 7201 CGInfo.getCUDADeviceBuiltinTextureDeviceType()); 7202 } 7203 return getNaturalAlignIndirect(Ty, /* byval */ true); 7204 } 7205 7206 if (const auto *EIT = Ty->getAs<BitIntType>()) { 7207 if ((EIT->getNumBits() > 128) || 7208 (!getContext().getTargetInfo().hasInt128Type() && 7209 EIT->getNumBits() > 64)) 7210 return getNaturalAlignIndirect(Ty, /* byval */ true); 7211 } 7212 7213 return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty) 7214 : ABIArgInfo::getDirect()); 7215 } 7216 7217 void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const { 7218 if (!getCXXABI().classifyReturnType(FI)) 7219 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 7220 for (auto &I : FI.arguments()) 7221 I.info = classifyArgumentType(I.type); 7222 7223 // Always honor user-specified calling convention. 7224 if (FI.getCallingConvention() != llvm::CallingConv::C) 7225 return; 7226 7227 FI.setEffectiveCallingConvention(getRuntimeCC()); 7228 } 7229 7230 Address NVPTXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 7231 QualType Ty) const { 7232 llvm_unreachable("NVPTX does not support varargs"); 7233 } 7234 7235 void NVPTXTargetCodeGenInfo::setTargetAttributes( 7236 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const { 7237 if (GV->isDeclaration()) 7238 return; 7239 const VarDecl *VD = dyn_cast_or_null<VarDecl>(D); 7240 if (VD) { 7241 if (M.getLangOpts().CUDA) { 7242 if (VD->getType()->isCUDADeviceBuiltinSurfaceType()) 7243 addNVVMMetadata(GV, "surface", 1); 7244 else if (VD->getType()->isCUDADeviceBuiltinTextureType()) 7245 addNVVMMetadata(GV, "texture", 1); 7246 return; 7247 } 7248 } 7249 7250 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D); 7251 if (!FD) return; 7252 7253 llvm::Function *F = cast<llvm::Function>(GV); 7254 7255 // Perform special handling in OpenCL mode 7256 if (M.getLangOpts().OpenCL) { 7257 // Use OpenCL function attributes to check for kernel functions 7258 // By default, all functions are device functions 7259 if (FD->hasAttr<OpenCLKernelAttr>()) { 7260 // OpenCL __kernel functions get kernel metadata 7261 // Create !{<func-ref>, metadata !"kernel", i32 1} node 7262 addNVVMMetadata(F, "kernel", 1); 7263 // And kernel functions are not subject to inlining 7264 F->addFnAttr(llvm::Attribute::NoInline); 7265 } 7266 } 7267 7268 // Perform special handling in CUDA mode. 7269 if (M.getLangOpts().CUDA) { 7270 // CUDA __global__ functions get a kernel metadata entry. Since 7271 // __global__ functions cannot be called from the device, we do not 7272 // need to set the noinline attribute. 7273 if (FD->hasAttr<CUDAGlobalAttr>()) { 7274 // Create !{<func-ref>, metadata !"kernel", i32 1} node 7275 addNVVMMetadata(F, "kernel", 1); 7276 } 7277 if (CUDALaunchBoundsAttr *Attr = FD->getAttr<CUDALaunchBoundsAttr>()) { 7278 // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node 7279 llvm::APSInt MaxThreads(32); 7280 MaxThreads = Attr->getMaxThreads()->EvaluateKnownConstInt(M.getContext()); 7281 if (MaxThreads > 0) 7282 addNVVMMetadata(F, "maxntidx", MaxThreads.getExtValue()); 7283 7284 // min blocks is an optional argument for CUDALaunchBoundsAttr. If it was 7285 // not specified in __launch_bounds__ or if the user specified a 0 value, 7286 // we don't have to add a PTX directive. 7287 if (Attr->getMinBlocks()) { 7288 llvm::APSInt MinBlocks(32); 7289 MinBlocks = Attr->getMinBlocks()->EvaluateKnownConstInt(M.getContext()); 7290 if (MinBlocks > 0) 7291 // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node 7292 addNVVMMetadata(F, "minctasm", MinBlocks.getExtValue()); 7293 } 7294 } 7295 } 7296 } 7297 7298 void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::GlobalValue *GV, 7299 StringRef Name, int Operand) { 7300 llvm::Module *M = GV->getParent(); 7301 llvm::LLVMContext &Ctx = M->getContext(); 7302 7303 // Get "nvvm.annotations" metadata node 7304 llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations"); 7305 7306 llvm::Metadata *MDVals[] = { 7307 llvm::ConstantAsMetadata::get(GV), llvm::MDString::get(Ctx, Name), 7308 llvm::ConstantAsMetadata::get( 7309 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand))}; 7310 // Append metadata to nvvm.annotations 7311 MD->addOperand(llvm::MDNode::get(Ctx, MDVals)); 7312 } 7313 7314 bool NVPTXTargetCodeGenInfo::shouldEmitStaticExternCAliases() const { 7315 return false; 7316 } 7317 } 7318 7319 //===----------------------------------------------------------------------===// 7320 // SystemZ ABI Implementation 7321 //===----------------------------------------------------------------------===// 7322 7323 namespace { 7324 7325 class SystemZABIInfo : public SwiftABIInfo { 7326 bool HasVector; 7327 bool IsSoftFloatABI; 7328 7329 public: 7330 SystemZABIInfo(CodeGenTypes &CGT, bool HV, bool SF) 7331 : SwiftABIInfo(CGT), HasVector(HV), IsSoftFloatABI(SF) {} 7332 7333 bool isPromotableIntegerTypeForABI(QualType Ty) const; 7334 bool isCompoundType(QualType Ty) const; 7335 bool isVectorArgumentType(QualType Ty) const; 7336 bool isFPArgumentType(QualType Ty) const; 7337 QualType GetSingleElementType(QualType Ty) const; 7338 7339 ABIArgInfo classifyReturnType(QualType RetTy) const; 7340 ABIArgInfo classifyArgumentType(QualType ArgTy) const; 7341 7342 void computeInfo(CGFunctionInfo &FI) const override { 7343 if (!getCXXABI().classifyReturnType(FI)) 7344 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 7345 for (auto &I : FI.arguments()) 7346 I.info = classifyArgumentType(I.type); 7347 } 7348 7349 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 7350 QualType Ty) const override; 7351 7352 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars, 7353 bool asReturnValue) const override { 7354 return occupiesMoreThan(CGT, scalars, /*total*/ 4); 7355 } 7356 bool isSwiftErrorInRegister() const override { 7357 return false; 7358 } 7359 }; 7360 7361 class SystemZTargetCodeGenInfo : public TargetCodeGenInfo { 7362 public: 7363 SystemZTargetCodeGenInfo(CodeGenTypes &CGT, bool HasVector, bool SoftFloatABI) 7364 : TargetCodeGenInfo( 7365 std::make_unique<SystemZABIInfo>(CGT, HasVector, SoftFloatABI)) {} 7366 7367 llvm::Value *testFPKind(llvm::Value *V, unsigned BuiltinID, 7368 CGBuilderTy &Builder, 7369 CodeGenModule &CGM) const override { 7370 assert(V->getType()->isFloatingPointTy() && "V should have an FP type."); 7371 // Only use TDC in constrained FP mode. 7372 if (!Builder.getIsFPConstrained()) 7373 return nullptr; 7374 7375 llvm::Type *Ty = V->getType(); 7376 if (Ty->isFloatTy() || Ty->isDoubleTy() || Ty->isFP128Ty()) { 7377 llvm::Module &M = CGM.getModule(); 7378 auto &Ctx = M.getContext(); 7379 llvm::Function *TDCFunc = 7380 llvm::Intrinsic::getDeclaration(&M, llvm::Intrinsic::s390_tdc, Ty); 7381 unsigned TDCBits = 0; 7382 switch (BuiltinID) { 7383 case Builtin::BI__builtin_isnan: 7384 TDCBits = 0xf; 7385 break; 7386 case Builtin::BIfinite: 7387 case Builtin::BI__finite: 7388 case Builtin::BIfinitef: 7389 case Builtin::BI__finitef: 7390 case Builtin::BIfinitel: 7391 case Builtin::BI__finitel: 7392 case Builtin::BI__builtin_isfinite: 7393 TDCBits = 0xfc0; 7394 break; 7395 case Builtin::BI__builtin_isinf: 7396 TDCBits = 0x30; 7397 break; 7398 default: 7399 break; 7400 } 7401 if (TDCBits) 7402 return Builder.CreateCall( 7403 TDCFunc, 7404 {V, llvm::ConstantInt::get(llvm::Type::getInt64Ty(Ctx), TDCBits)}); 7405 } 7406 return nullptr; 7407 } 7408 }; 7409 } 7410 7411 bool SystemZABIInfo::isPromotableIntegerTypeForABI(QualType Ty) const { 7412 // Treat an enum type as its underlying type. 7413 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 7414 Ty = EnumTy->getDecl()->getIntegerType(); 7415 7416 // Promotable integer types are required to be promoted by the ABI. 7417 if (ABIInfo::isPromotableIntegerTypeForABI(Ty)) 7418 return true; 7419 7420 if (const auto *EIT = Ty->getAs<BitIntType>()) 7421 if (EIT->getNumBits() < 64) 7422 return true; 7423 7424 // 32-bit values must also be promoted. 7425 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) 7426 switch (BT->getKind()) { 7427 case BuiltinType::Int: 7428 case BuiltinType::UInt: 7429 return true; 7430 default: 7431 return false; 7432 } 7433 return false; 7434 } 7435 7436 bool SystemZABIInfo::isCompoundType(QualType Ty) const { 7437 return (Ty->isAnyComplexType() || 7438 Ty->isVectorType() || 7439 isAggregateTypeForABI(Ty)); 7440 } 7441 7442 bool SystemZABIInfo::isVectorArgumentType(QualType Ty) const { 7443 return (HasVector && 7444 Ty->isVectorType() && 7445 getContext().getTypeSize(Ty) <= 128); 7446 } 7447 7448 bool SystemZABIInfo::isFPArgumentType(QualType Ty) const { 7449 if (IsSoftFloatABI) 7450 return false; 7451 7452 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) 7453 switch (BT->getKind()) { 7454 case BuiltinType::Float: 7455 case BuiltinType::Double: 7456 return true; 7457 default: 7458 return false; 7459 } 7460 7461 return false; 7462 } 7463 7464 QualType SystemZABIInfo::GetSingleElementType(QualType Ty) const { 7465 const RecordType *RT = Ty->getAs<RecordType>(); 7466 7467 if (RT && RT->isStructureOrClassType()) { 7468 const RecordDecl *RD = RT->getDecl(); 7469 QualType Found; 7470 7471 // If this is a C++ record, check the bases first. 7472 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 7473 for (const auto &I : CXXRD->bases()) { 7474 QualType Base = I.getType(); 7475 7476 // Empty bases don't affect things either way. 7477 if (isEmptyRecord(getContext(), Base, true)) 7478 continue; 7479 7480 if (!Found.isNull()) 7481 return Ty; 7482 Found = GetSingleElementType(Base); 7483 } 7484 7485 // Check the fields. 7486 for (const auto *FD : RD->fields()) { 7487 // For compatibility with GCC, ignore empty bitfields in C++ mode. 7488 // Unlike isSingleElementStruct(), empty structure and array fields 7489 // do count. So do anonymous bitfields that aren't zero-sized. 7490 if (getContext().getLangOpts().CPlusPlus && 7491 FD->isZeroLengthBitField(getContext())) 7492 continue; 7493 // Like isSingleElementStruct(), ignore C++20 empty data members. 7494 if (FD->hasAttr<NoUniqueAddressAttr>() && 7495 isEmptyRecord(getContext(), FD->getType(), true)) 7496 continue; 7497 7498 // Unlike isSingleElementStruct(), arrays do not count. 7499 // Nested structures still do though. 7500 if (!Found.isNull()) 7501 return Ty; 7502 Found = GetSingleElementType(FD->getType()); 7503 } 7504 7505 // Unlike isSingleElementStruct(), trailing padding is allowed. 7506 // An 8-byte aligned struct s { float f; } is passed as a double. 7507 if (!Found.isNull()) 7508 return Found; 7509 } 7510 7511 return Ty; 7512 } 7513 7514 Address SystemZABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 7515 QualType Ty) const { 7516 // Assume that va_list type is correct; should be pointer to LLVM type: 7517 // struct { 7518 // i64 __gpr; 7519 // i64 __fpr; 7520 // i8 *__overflow_arg_area; 7521 // i8 *__reg_save_area; 7522 // }; 7523 7524 // Every non-vector argument occupies 8 bytes and is passed by preference 7525 // in either GPRs or FPRs. Vector arguments occupy 8 or 16 bytes and are 7526 // always passed on the stack. 7527 Ty = getContext().getCanonicalType(Ty); 7528 auto TyInfo = getContext().getTypeInfoInChars(Ty); 7529 llvm::Type *ArgTy = CGF.ConvertTypeForMem(Ty); 7530 llvm::Type *DirectTy = ArgTy; 7531 ABIArgInfo AI = classifyArgumentType(Ty); 7532 bool IsIndirect = AI.isIndirect(); 7533 bool InFPRs = false; 7534 bool IsVector = false; 7535 CharUnits UnpaddedSize; 7536 CharUnits DirectAlign; 7537 if (IsIndirect) { 7538 DirectTy = llvm::PointerType::getUnqual(DirectTy); 7539 UnpaddedSize = DirectAlign = CharUnits::fromQuantity(8); 7540 } else { 7541 if (AI.getCoerceToType()) 7542 ArgTy = AI.getCoerceToType(); 7543 InFPRs = (!IsSoftFloatABI && (ArgTy->isFloatTy() || ArgTy->isDoubleTy())); 7544 IsVector = ArgTy->isVectorTy(); 7545 UnpaddedSize = TyInfo.Width; 7546 DirectAlign = TyInfo.Align; 7547 } 7548 CharUnits PaddedSize = CharUnits::fromQuantity(8); 7549 if (IsVector && UnpaddedSize > PaddedSize) 7550 PaddedSize = CharUnits::fromQuantity(16); 7551 assert((UnpaddedSize <= PaddedSize) && "Invalid argument size."); 7552 7553 CharUnits Padding = (PaddedSize - UnpaddedSize); 7554 7555 llvm::Type *IndexTy = CGF.Int64Ty; 7556 llvm::Value *PaddedSizeV = 7557 llvm::ConstantInt::get(IndexTy, PaddedSize.getQuantity()); 7558 7559 if (IsVector) { 7560 // Work out the address of a vector argument on the stack. 7561 // Vector arguments are always passed in the high bits of a 7562 // single (8 byte) or double (16 byte) stack slot. 7563 Address OverflowArgAreaPtr = 7564 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr"); 7565 Address OverflowArgArea = 7566 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"), 7567 TyInfo.Align); 7568 Address MemAddr = 7569 CGF.Builder.CreateElementBitCast(OverflowArgArea, DirectTy, "mem_addr"); 7570 7571 // Update overflow_arg_area_ptr pointer 7572 llvm::Value *NewOverflowArgArea = 7573 CGF.Builder.CreateGEP(OverflowArgArea.getElementType(), 7574 OverflowArgArea.getPointer(), PaddedSizeV, 7575 "overflow_arg_area"); 7576 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr); 7577 7578 return MemAddr; 7579 } 7580 7581 assert(PaddedSize.getQuantity() == 8); 7582 7583 unsigned MaxRegs, RegCountField, RegSaveIndex; 7584 CharUnits RegPadding; 7585 if (InFPRs) { 7586 MaxRegs = 4; // Maximum of 4 FPR arguments 7587 RegCountField = 1; // __fpr 7588 RegSaveIndex = 16; // save offset for f0 7589 RegPadding = CharUnits(); // floats are passed in the high bits of an FPR 7590 } else { 7591 MaxRegs = 5; // Maximum of 5 GPR arguments 7592 RegCountField = 0; // __gpr 7593 RegSaveIndex = 2; // save offset for r2 7594 RegPadding = Padding; // values are passed in the low bits of a GPR 7595 } 7596 7597 Address RegCountPtr = 7598 CGF.Builder.CreateStructGEP(VAListAddr, RegCountField, "reg_count_ptr"); 7599 llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count"); 7600 llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs); 7601 llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV, 7602 "fits_in_regs"); 7603 7604 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg"); 7605 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem"); 7606 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end"); 7607 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock); 7608 7609 // Emit code to load the value if it was passed in registers. 7610 CGF.EmitBlock(InRegBlock); 7611 7612 // Work out the address of an argument register. 7613 llvm::Value *ScaledRegCount = 7614 CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count"); 7615 llvm::Value *RegBase = 7616 llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize.getQuantity() 7617 + RegPadding.getQuantity()); 7618 llvm::Value *RegOffset = 7619 CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset"); 7620 Address RegSaveAreaPtr = 7621 CGF.Builder.CreateStructGEP(VAListAddr, 3, "reg_save_area_ptr"); 7622 llvm::Value *RegSaveArea = 7623 CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area"); 7624 Address RawRegAddr(CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, RegOffset, 7625 "raw_reg_addr"), 7626 PaddedSize); 7627 Address RegAddr = 7628 CGF.Builder.CreateElementBitCast(RawRegAddr, DirectTy, "reg_addr"); 7629 7630 // Update the register count 7631 llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1); 7632 llvm::Value *NewRegCount = 7633 CGF.Builder.CreateAdd(RegCount, One, "reg_count"); 7634 CGF.Builder.CreateStore(NewRegCount, RegCountPtr); 7635 CGF.EmitBranch(ContBlock); 7636 7637 // Emit code to load the value if it was passed in memory. 7638 CGF.EmitBlock(InMemBlock); 7639 7640 // Work out the address of a stack argument. 7641 Address OverflowArgAreaPtr = 7642 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr"); 7643 Address OverflowArgArea = 7644 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"), 7645 PaddedSize); 7646 Address RawMemAddr = 7647 CGF.Builder.CreateConstByteGEP(OverflowArgArea, Padding, "raw_mem_addr"); 7648 Address MemAddr = 7649 CGF.Builder.CreateElementBitCast(RawMemAddr, DirectTy, "mem_addr"); 7650 7651 // Update overflow_arg_area_ptr pointer 7652 llvm::Value *NewOverflowArgArea = 7653 CGF.Builder.CreateGEP(OverflowArgArea.getElementType(), 7654 OverflowArgArea.getPointer(), PaddedSizeV, 7655 "overflow_arg_area"); 7656 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr); 7657 CGF.EmitBranch(ContBlock); 7658 7659 // Return the appropriate result. 7660 CGF.EmitBlock(ContBlock); 7661 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, 7662 MemAddr, InMemBlock, "va_arg.addr"); 7663 7664 if (IsIndirect) 7665 ResAddr = Address(CGF.Builder.CreateLoad(ResAddr, "indirect_arg"), 7666 TyInfo.Align); 7667 7668 return ResAddr; 7669 } 7670 7671 ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const { 7672 if (RetTy->isVoidType()) 7673 return ABIArgInfo::getIgnore(); 7674 if (isVectorArgumentType(RetTy)) 7675 return ABIArgInfo::getDirect(); 7676 if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64) 7677 return getNaturalAlignIndirect(RetTy); 7678 return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy) 7679 : ABIArgInfo::getDirect()); 7680 } 7681 7682 ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const { 7683 // Handle the generic C++ ABI. 7684 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 7685 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 7686 7687 // Integers and enums are extended to full register width. 7688 if (isPromotableIntegerTypeForABI(Ty)) 7689 return ABIArgInfo::getExtend(Ty); 7690 7691 // Handle vector types and vector-like structure types. Note that 7692 // as opposed to float-like structure types, we do not allow any 7693 // padding for vector-like structures, so verify the sizes match. 7694 uint64_t Size = getContext().getTypeSize(Ty); 7695 QualType SingleElementTy = GetSingleElementType(Ty); 7696 if (isVectorArgumentType(SingleElementTy) && 7697 getContext().getTypeSize(SingleElementTy) == Size) 7698 return ABIArgInfo::getDirect(CGT.ConvertType(SingleElementTy)); 7699 7700 // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly. 7701 if (Size != 8 && Size != 16 && Size != 32 && Size != 64) 7702 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 7703 7704 // Handle small structures. 7705 if (const RecordType *RT = Ty->getAs<RecordType>()) { 7706 // Structures with flexible arrays have variable length, so really 7707 // fail the size test above. 7708 const RecordDecl *RD = RT->getDecl(); 7709 if (RD->hasFlexibleArrayMember()) 7710 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 7711 7712 // The structure is passed as an unextended integer, a float, or a double. 7713 llvm::Type *PassTy; 7714 if (isFPArgumentType(SingleElementTy)) { 7715 assert(Size == 32 || Size == 64); 7716 if (Size == 32) 7717 PassTy = llvm::Type::getFloatTy(getVMContext()); 7718 else 7719 PassTy = llvm::Type::getDoubleTy(getVMContext()); 7720 } else 7721 PassTy = llvm::IntegerType::get(getVMContext(), Size); 7722 return ABIArgInfo::getDirect(PassTy); 7723 } 7724 7725 // Non-structure compounds are passed indirectly. 7726 if (isCompoundType(Ty)) 7727 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 7728 7729 return ABIArgInfo::getDirect(nullptr); 7730 } 7731 7732 //===----------------------------------------------------------------------===// 7733 // MSP430 ABI Implementation 7734 //===----------------------------------------------------------------------===// 7735 7736 namespace { 7737 7738 class MSP430ABIInfo : public DefaultABIInfo { 7739 static ABIArgInfo complexArgInfo() { 7740 ABIArgInfo Info = ABIArgInfo::getDirect(); 7741 Info.setCanBeFlattened(false); 7742 return Info; 7743 } 7744 7745 public: 7746 MSP430ABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {} 7747 7748 ABIArgInfo classifyReturnType(QualType RetTy) const { 7749 if (RetTy->isAnyComplexType()) 7750 return complexArgInfo(); 7751 7752 return DefaultABIInfo::classifyReturnType(RetTy); 7753 } 7754 7755 ABIArgInfo classifyArgumentType(QualType RetTy) const { 7756 if (RetTy->isAnyComplexType()) 7757 return complexArgInfo(); 7758 7759 return DefaultABIInfo::classifyArgumentType(RetTy); 7760 } 7761 7762 // Just copy the original implementations because 7763 // DefaultABIInfo::classify{Return,Argument}Type() are not virtual 7764 void computeInfo(CGFunctionInfo &FI) const override { 7765 if (!getCXXABI().classifyReturnType(FI)) 7766 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 7767 for (auto &I : FI.arguments()) 7768 I.info = classifyArgumentType(I.type); 7769 } 7770 7771 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 7772 QualType Ty) const override { 7773 return EmitVAArgInstr(CGF, VAListAddr, Ty, classifyArgumentType(Ty)); 7774 } 7775 }; 7776 7777 class MSP430TargetCodeGenInfo : public TargetCodeGenInfo { 7778 public: 7779 MSP430TargetCodeGenInfo(CodeGenTypes &CGT) 7780 : TargetCodeGenInfo(std::make_unique<MSP430ABIInfo>(CGT)) {} 7781 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 7782 CodeGen::CodeGenModule &M) const override; 7783 }; 7784 7785 } 7786 7787 void MSP430TargetCodeGenInfo::setTargetAttributes( 7788 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const { 7789 if (GV->isDeclaration()) 7790 return; 7791 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) { 7792 const auto *InterruptAttr = FD->getAttr<MSP430InterruptAttr>(); 7793 if (!InterruptAttr) 7794 return; 7795 7796 // Handle 'interrupt' attribute: 7797 llvm::Function *F = cast<llvm::Function>(GV); 7798 7799 // Step 1: Set ISR calling convention. 7800 F->setCallingConv(llvm::CallingConv::MSP430_INTR); 7801 7802 // Step 2: Add attributes goodness. 7803 F->addFnAttr(llvm::Attribute::NoInline); 7804 F->addFnAttr("interrupt", llvm::utostr(InterruptAttr->getNumber())); 7805 } 7806 } 7807 7808 //===----------------------------------------------------------------------===// 7809 // MIPS ABI Implementation. This works for both little-endian and 7810 // big-endian variants. 7811 //===----------------------------------------------------------------------===// 7812 7813 namespace { 7814 class MipsABIInfo : public ABIInfo { 7815 bool IsO32; 7816 unsigned MinABIStackAlignInBytes, StackAlignInBytes; 7817 void CoerceToIntArgs(uint64_t TySize, 7818 SmallVectorImpl<llvm::Type *> &ArgList) const; 7819 llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const; 7820 llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const; 7821 llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const; 7822 public: 7823 MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) : 7824 ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8), 7825 StackAlignInBytes(IsO32 ? 8 : 16) {} 7826 7827 ABIArgInfo classifyReturnType(QualType RetTy) const; 7828 ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const; 7829 void computeInfo(CGFunctionInfo &FI) const override; 7830 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 7831 QualType Ty) const override; 7832 ABIArgInfo extendType(QualType Ty) const; 7833 }; 7834 7835 class MIPSTargetCodeGenInfo : public TargetCodeGenInfo { 7836 unsigned SizeOfUnwindException; 7837 public: 7838 MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32) 7839 : TargetCodeGenInfo(std::make_unique<MipsABIInfo>(CGT, IsO32)), 7840 SizeOfUnwindException(IsO32 ? 24 : 32) {} 7841 7842 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override { 7843 return 29; 7844 } 7845 7846 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 7847 CodeGen::CodeGenModule &CGM) const override { 7848 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D); 7849 if (!FD) return; 7850 llvm::Function *Fn = cast<llvm::Function>(GV); 7851 7852 if (FD->hasAttr<MipsLongCallAttr>()) 7853 Fn->addFnAttr("long-call"); 7854 else if (FD->hasAttr<MipsShortCallAttr>()) 7855 Fn->addFnAttr("short-call"); 7856 7857 // Other attributes do not have a meaning for declarations. 7858 if (GV->isDeclaration()) 7859 return; 7860 7861 if (FD->hasAttr<Mips16Attr>()) { 7862 Fn->addFnAttr("mips16"); 7863 } 7864 else if (FD->hasAttr<NoMips16Attr>()) { 7865 Fn->addFnAttr("nomips16"); 7866 } 7867 7868 if (FD->hasAttr<MicroMipsAttr>()) 7869 Fn->addFnAttr("micromips"); 7870 else if (FD->hasAttr<NoMicroMipsAttr>()) 7871 Fn->addFnAttr("nomicromips"); 7872 7873 const MipsInterruptAttr *Attr = FD->getAttr<MipsInterruptAttr>(); 7874 if (!Attr) 7875 return; 7876 7877 const char *Kind; 7878 switch (Attr->getInterrupt()) { 7879 case MipsInterruptAttr::eic: Kind = "eic"; break; 7880 case MipsInterruptAttr::sw0: Kind = "sw0"; break; 7881 case MipsInterruptAttr::sw1: Kind = "sw1"; break; 7882 case MipsInterruptAttr::hw0: Kind = "hw0"; break; 7883 case MipsInterruptAttr::hw1: Kind = "hw1"; break; 7884 case MipsInterruptAttr::hw2: Kind = "hw2"; break; 7885 case MipsInterruptAttr::hw3: Kind = "hw3"; break; 7886 case MipsInterruptAttr::hw4: Kind = "hw4"; break; 7887 case MipsInterruptAttr::hw5: Kind = "hw5"; break; 7888 } 7889 7890 Fn->addFnAttr("interrupt", Kind); 7891 7892 } 7893 7894 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 7895 llvm::Value *Address) const override; 7896 7897 unsigned getSizeOfUnwindException() const override { 7898 return SizeOfUnwindException; 7899 } 7900 }; 7901 } 7902 7903 void MipsABIInfo::CoerceToIntArgs( 7904 uint64_t TySize, SmallVectorImpl<llvm::Type *> &ArgList) const { 7905 llvm::IntegerType *IntTy = 7906 llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8); 7907 7908 // Add (TySize / MinABIStackAlignInBytes) args of IntTy. 7909 for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N) 7910 ArgList.push_back(IntTy); 7911 7912 // If necessary, add one more integer type to ArgList. 7913 unsigned R = TySize % (MinABIStackAlignInBytes * 8); 7914 7915 if (R) 7916 ArgList.push_back(llvm::IntegerType::get(getVMContext(), R)); 7917 } 7918 7919 // In N32/64, an aligned double precision floating point field is passed in 7920 // a register. 7921 llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const { 7922 SmallVector<llvm::Type*, 8> ArgList, IntArgList; 7923 7924 if (IsO32) { 7925 CoerceToIntArgs(TySize, ArgList); 7926 return llvm::StructType::get(getVMContext(), ArgList); 7927 } 7928 7929 if (Ty->isComplexType()) 7930 return CGT.ConvertType(Ty); 7931 7932 const RecordType *RT = Ty->getAs<RecordType>(); 7933 7934 // Unions/vectors are passed in integer registers. 7935 if (!RT || !RT->isStructureOrClassType()) { 7936 CoerceToIntArgs(TySize, ArgList); 7937 return llvm::StructType::get(getVMContext(), ArgList); 7938 } 7939 7940 const RecordDecl *RD = RT->getDecl(); 7941 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD); 7942 assert(!(TySize % 8) && "Size of structure must be multiple of 8."); 7943 7944 uint64_t LastOffset = 0; 7945 unsigned idx = 0; 7946 llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64); 7947 7948 // Iterate over fields in the struct/class and check if there are any aligned 7949 // double fields. 7950 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 7951 i != e; ++i, ++idx) { 7952 const QualType Ty = i->getType(); 7953 const BuiltinType *BT = Ty->getAs<BuiltinType>(); 7954 7955 if (!BT || BT->getKind() != BuiltinType::Double) 7956 continue; 7957 7958 uint64_t Offset = Layout.getFieldOffset(idx); 7959 if (Offset % 64) // Ignore doubles that are not aligned. 7960 continue; 7961 7962 // Add ((Offset - LastOffset) / 64) args of type i64. 7963 for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j) 7964 ArgList.push_back(I64); 7965 7966 // Add double type. 7967 ArgList.push_back(llvm::Type::getDoubleTy(getVMContext())); 7968 LastOffset = Offset + 64; 7969 } 7970 7971 CoerceToIntArgs(TySize - LastOffset, IntArgList); 7972 ArgList.append(IntArgList.begin(), IntArgList.end()); 7973 7974 return llvm::StructType::get(getVMContext(), ArgList); 7975 } 7976 7977 llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset, 7978 uint64_t Offset) const { 7979 if (OrigOffset + MinABIStackAlignInBytes > Offset) 7980 return nullptr; 7981 7982 return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8); 7983 } 7984 7985 ABIArgInfo 7986 MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const { 7987 Ty = useFirstFieldIfTransparentUnion(Ty); 7988 7989 uint64_t OrigOffset = Offset; 7990 uint64_t TySize = getContext().getTypeSize(Ty); 7991 uint64_t Align = getContext().getTypeAlign(Ty) / 8; 7992 7993 Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes), 7994 (uint64_t)StackAlignInBytes); 7995 unsigned CurrOffset = llvm::alignTo(Offset, Align); 7996 Offset = CurrOffset + llvm::alignTo(TySize, Align * 8) / 8; 7997 7998 if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) { 7999 // Ignore empty aggregates. 8000 if (TySize == 0) 8001 return ABIArgInfo::getIgnore(); 8002 8003 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) { 8004 Offset = OrigOffset + MinABIStackAlignInBytes; 8005 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 8006 } 8007 8008 // If we have reached here, aggregates are passed directly by coercing to 8009 // another structure type. Padding is inserted if the offset of the 8010 // aggregate is unaligned. 8011 ABIArgInfo ArgInfo = 8012 ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0, 8013 getPaddingType(OrigOffset, CurrOffset)); 8014 ArgInfo.setInReg(true); 8015 return ArgInfo; 8016 } 8017 8018 // Treat an enum type as its underlying type. 8019 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 8020 Ty = EnumTy->getDecl()->getIntegerType(); 8021 8022 // Make sure we pass indirectly things that are too large. 8023 if (const auto *EIT = Ty->getAs<BitIntType>()) 8024 if (EIT->getNumBits() > 128 || 8025 (EIT->getNumBits() > 64 && 8026 !getContext().getTargetInfo().hasInt128Type())) 8027 return getNaturalAlignIndirect(Ty); 8028 8029 // All integral types are promoted to the GPR width. 8030 if (Ty->isIntegralOrEnumerationType()) 8031 return extendType(Ty); 8032 8033 return ABIArgInfo::getDirect( 8034 nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset)); 8035 } 8036 8037 llvm::Type* 8038 MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const { 8039 const RecordType *RT = RetTy->getAs<RecordType>(); 8040 SmallVector<llvm::Type*, 8> RTList; 8041 8042 if (RT && RT->isStructureOrClassType()) { 8043 const RecordDecl *RD = RT->getDecl(); 8044 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD); 8045 unsigned FieldCnt = Layout.getFieldCount(); 8046 8047 // N32/64 returns struct/classes in floating point registers if the 8048 // following conditions are met: 8049 // 1. The size of the struct/class is no larger than 128-bit. 8050 // 2. The struct/class has one or two fields all of which are floating 8051 // point types. 8052 // 3. The offset of the first field is zero (this follows what gcc does). 8053 // 8054 // Any other composite results are returned in integer registers. 8055 // 8056 if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) { 8057 RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end(); 8058 for (; b != e; ++b) { 8059 const BuiltinType *BT = b->getType()->getAs<BuiltinType>(); 8060 8061 if (!BT || !BT->isFloatingPoint()) 8062 break; 8063 8064 RTList.push_back(CGT.ConvertType(b->getType())); 8065 } 8066 8067 if (b == e) 8068 return llvm::StructType::get(getVMContext(), RTList, 8069 RD->hasAttr<PackedAttr>()); 8070 8071 RTList.clear(); 8072 } 8073 } 8074 8075 CoerceToIntArgs(Size, RTList); 8076 return llvm::StructType::get(getVMContext(), RTList); 8077 } 8078 8079 ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const { 8080 uint64_t Size = getContext().getTypeSize(RetTy); 8081 8082 if (RetTy->isVoidType()) 8083 return ABIArgInfo::getIgnore(); 8084 8085 // O32 doesn't treat zero-sized structs differently from other structs. 8086 // However, N32/N64 ignores zero sized return values. 8087 if (!IsO32 && Size == 0) 8088 return ABIArgInfo::getIgnore(); 8089 8090 if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) { 8091 if (Size <= 128) { 8092 if (RetTy->isAnyComplexType()) 8093 return ABIArgInfo::getDirect(); 8094 8095 // O32 returns integer vectors in registers and N32/N64 returns all small 8096 // aggregates in registers. 8097 if (!IsO32 || 8098 (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) { 8099 ABIArgInfo ArgInfo = 8100 ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size)); 8101 ArgInfo.setInReg(true); 8102 return ArgInfo; 8103 } 8104 } 8105 8106 return getNaturalAlignIndirect(RetTy); 8107 } 8108 8109 // Treat an enum type as its underlying type. 8110 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 8111 RetTy = EnumTy->getDecl()->getIntegerType(); 8112 8113 // Make sure we pass indirectly things that are too large. 8114 if (const auto *EIT = RetTy->getAs<BitIntType>()) 8115 if (EIT->getNumBits() > 128 || 8116 (EIT->getNumBits() > 64 && 8117 !getContext().getTargetInfo().hasInt128Type())) 8118 return getNaturalAlignIndirect(RetTy); 8119 8120 if (isPromotableIntegerTypeForABI(RetTy)) 8121 return ABIArgInfo::getExtend(RetTy); 8122 8123 if ((RetTy->isUnsignedIntegerOrEnumerationType() || 8124 RetTy->isSignedIntegerOrEnumerationType()) && Size == 32 && !IsO32) 8125 return ABIArgInfo::getSignExtend(RetTy); 8126 8127 return ABIArgInfo::getDirect(); 8128 } 8129 8130 void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const { 8131 ABIArgInfo &RetInfo = FI.getReturnInfo(); 8132 if (!getCXXABI().classifyReturnType(FI)) 8133 RetInfo = classifyReturnType(FI.getReturnType()); 8134 8135 // Check if a pointer to an aggregate is passed as a hidden argument. 8136 uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0; 8137 8138 for (auto &I : FI.arguments()) 8139 I.info = classifyArgumentType(I.type, Offset); 8140 } 8141 8142 Address MipsABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 8143 QualType OrigTy) const { 8144 QualType Ty = OrigTy; 8145 8146 // Integer arguments are promoted to 32-bit on O32 and 64-bit on N32/N64. 8147 // Pointers are also promoted in the same way but this only matters for N32. 8148 unsigned SlotSizeInBits = IsO32 ? 32 : 64; 8149 unsigned PtrWidth = getTarget().getPointerWidth(0); 8150 bool DidPromote = false; 8151 if ((Ty->isIntegerType() && 8152 getContext().getIntWidth(Ty) < SlotSizeInBits) || 8153 (Ty->isPointerType() && PtrWidth < SlotSizeInBits)) { 8154 DidPromote = true; 8155 Ty = getContext().getIntTypeForBitwidth(SlotSizeInBits, 8156 Ty->isSignedIntegerType()); 8157 } 8158 8159 auto TyInfo = getContext().getTypeInfoInChars(Ty); 8160 8161 // The alignment of things in the argument area is never larger than 8162 // StackAlignInBytes. 8163 TyInfo.Align = 8164 std::min(TyInfo.Align, CharUnits::fromQuantity(StackAlignInBytes)); 8165 8166 // MinABIStackAlignInBytes is the size of argument slots on the stack. 8167 CharUnits ArgSlotSize = CharUnits::fromQuantity(MinABIStackAlignInBytes); 8168 8169 Address Addr = emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false, 8170 TyInfo, ArgSlotSize, /*AllowHigherAlign*/ true); 8171 8172 8173 // If there was a promotion, "unpromote" into a temporary. 8174 // TODO: can we just use a pointer into a subset of the original slot? 8175 if (DidPromote) { 8176 Address Temp = CGF.CreateMemTemp(OrigTy, "vaarg.promotion-temp"); 8177 llvm::Value *Promoted = CGF.Builder.CreateLoad(Addr); 8178 8179 // Truncate down to the right width. 8180 llvm::Type *IntTy = (OrigTy->isIntegerType() ? Temp.getElementType() 8181 : CGF.IntPtrTy); 8182 llvm::Value *V = CGF.Builder.CreateTrunc(Promoted, IntTy); 8183 if (OrigTy->isPointerType()) 8184 V = CGF.Builder.CreateIntToPtr(V, Temp.getElementType()); 8185 8186 CGF.Builder.CreateStore(V, Temp); 8187 Addr = Temp; 8188 } 8189 8190 return Addr; 8191 } 8192 8193 ABIArgInfo MipsABIInfo::extendType(QualType Ty) const { 8194 int TySize = getContext().getTypeSize(Ty); 8195 8196 // MIPS64 ABI requires unsigned 32 bit integers to be sign extended. 8197 if (Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32) 8198 return ABIArgInfo::getSignExtend(Ty); 8199 8200 return ABIArgInfo::getExtend(Ty); 8201 } 8202 8203 bool 8204 MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 8205 llvm::Value *Address) const { 8206 // This information comes from gcc's implementation, which seems to 8207 // as canonical as it gets. 8208 8209 // Everything on MIPS is 4 bytes. Double-precision FP registers 8210 // are aliased to pairs of single-precision FP registers. 8211 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4); 8212 8213 // 0-31 are the general purpose registers, $0 - $31. 8214 // 32-63 are the floating-point registers, $f0 - $f31. 8215 // 64 and 65 are the multiply/divide registers, $hi and $lo. 8216 // 66 is the (notional, I think) register for signal-handler return. 8217 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65); 8218 8219 // 67-74 are the floating-point status registers, $fcc0 - $fcc7. 8220 // They are one bit wide and ignored here. 8221 8222 // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31. 8223 // (coprocessor 1 is the FP unit) 8224 // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31. 8225 // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31. 8226 // 176-181 are the DSP accumulator registers. 8227 AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181); 8228 return false; 8229 } 8230 8231 //===----------------------------------------------------------------------===// 8232 // M68k ABI Implementation 8233 //===----------------------------------------------------------------------===// 8234 8235 namespace { 8236 8237 class M68kTargetCodeGenInfo : public TargetCodeGenInfo { 8238 public: 8239 M68kTargetCodeGenInfo(CodeGenTypes &CGT) 8240 : TargetCodeGenInfo(std::make_unique<DefaultABIInfo>(CGT)) {} 8241 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 8242 CodeGen::CodeGenModule &M) const override; 8243 }; 8244 8245 } // namespace 8246 8247 void M68kTargetCodeGenInfo::setTargetAttributes( 8248 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const { 8249 if (const auto *FD = dyn_cast_or_null<FunctionDecl>(D)) { 8250 if (const auto *attr = FD->getAttr<M68kInterruptAttr>()) { 8251 // Handle 'interrupt' attribute: 8252 llvm::Function *F = cast<llvm::Function>(GV); 8253 8254 // Step 1: Set ISR calling convention. 8255 F->setCallingConv(llvm::CallingConv::M68k_INTR); 8256 8257 // Step 2: Add attributes goodness. 8258 F->addFnAttr(llvm::Attribute::NoInline); 8259 8260 // Step 3: Emit ISR vector alias. 8261 unsigned Num = attr->getNumber() / 2; 8262 llvm::GlobalAlias::create(llvm::Function::ExternalLinkage, 8263 "__isr_" + Twine(Num), F); 8264 } 8265 } 8266 } 8267 8268 //===----------------------------------------------------------------------===// 8269 // AVR ABI Implementation. Documented at 8270 // https://gcc.gnu.org/wiki/avr-gcc#Calling_Convention 8271 // https://gcc.gnu.org/wiki/avr-gcc#Reduced_Tiny 8272 //===----------------------------------------------------------------------===// 8273 8274 namespace { 8275 class AVRABIInfo : public DefaultABIInfo { 8276 private: 8277 // The total amount of registers can be used to pass parameters. It is 18 on 8278 // AVR, or 6 on AVRTiny. 8279 const unsigned ParamRegs; 8280 // The total amount of registers can be used to pass return value. It is 8 on 8281 // AVR, or 4 on AVRTiny. 8282 const unsigned RetRegs; 8283 8284 public: 8285 AVRABIInfo(CodeGenTypes &CGT, unsigned NPR, unsigned NRR) 8286 : DefaultABIInfo(CGT), ParamRegs(NPR), RetRegs(NRR) {} 8287 8288 ABIArgInfo classifyReturnType(QualType Ty, bool &LargeRet) const { 8289 if (isAggregateTypeForABI(Ty)) { 8290 // On AVR, a return struct with size less than or equals to 8 bytes is 8291 // returned directly via registers R18-R25. On AVRTiny, a return struct 8292 // with size less than or equals to 4 bytes is returned directly via 8293 // registers R22-R25. 8294 if (getContext().getTypeSize(Ty) <= RetRegs * 8) 8295 return ABIArgInfo::getDirect(); 8296 // A return struct with larger size is returned via a stack 8297 // slot, along with a pointer to it as the function's implicit argument. 8298 LargeRet = true; 8299 return getNaturalAlignIndirect(Ty); 8300 } 8301 // Otherwise we follow the default way which is compatible. 8302 return DefaultABIInfo::classifyReturnType(Ty); 8303 } 8304 8305 ABIArgInfo classifyArgumentType(QualType Ty, unsigned &NumRegs) const { 8306 unsigned TySize = getContext().getTypeSize(Ty); 8307 8308 // An int8 type argument always costs two registers like an int16. 8309 if (TySize == 8 && NumRegs >= 2) { 8310 NumRegs -= 2; 8311 return ABIArgInfo::getExtend(Ty); 8312 } 8313 8314 // If the argument size is an odd number of bytes, round up the size 8315 // to the next even number. 8316 TySize = llvm::alignTo(TySize, 16); 8317 8318 // Any type including an array/struct type can be passed in rgisters, 8319 // if there are enough registers left. 8320 if (TySize <= NumRegs * 8) { 8321 NumRegs -= TySize / 8; 8322 return ABIArgInfo::getDirect(); 8323 } 8324 8325 // An argument is passed either completely in registers or completely in 8326 // memory. Since there are not enough registers left, current argument 8327 // and all other unprocessed arguments should be passed in memory. 8328 // However we still need to return `ABIArgInfo::getDirect()` other than 8329 // `ABIInfo::getNaturalAlignIndirect(Ty)`, otherwise an extra stack slot 8330 // will be allocated, so the stack frame layout will be incompatible with 8331 // avr-gcc. 8332 NumRegs = 0; 8333 return ABIArgInfo::getDirect(); 8334 } 8335 8336 void computeInfo(CGFunctionInfo &FI) const override { 8337 // Decide the return type. 8338 bool LargeRet = false; 8339 if (!getCXXABI().classifyReturnType(FI)) 8340 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), LargeRet); 8341 8342 // Decide each argument type. The total number of registers can be used for 8343 // arguments depends on several factors: 8344 // 1. Arguments of varargs functions are passed on the stack. This applies 8345 // even to the named arguments. So no register can be used. 8346 // 2. Total 18 registers can be used on avr and 6 ones on avrtiny. 8347 // 3. If the return type is a struct with too large size, two registers 8348 // (out of 18/6) will be cost as an implicit pointer argument. 8349 unsigned NumRegs = ParamRegs; 8350 if (FI.isVariadic()) 8351 NumRegs = 0; 8352 else if (LargeRet) 8353 NumRegs -= 2; 8354 for (auto &I : FI.arguments()) 8355 I.info = classifyArgumentType(I.type, NumRegs); 8356 } 8357 }; 8358 8359 class AVRTargetCodeGenInfo : public TargetCodeGenInfo { 8360 public: 8361 AVRTargetCodeGenInfo(CodeGenTypes &CGT, unsigned NPR, unsigned NRR) 8362 : TargetCodeGenInfo(std::make_unique<AVRABIInfo>(CGT, NPR, NRR)) {} 8363 8364 LangAS getGlobalVarAddressSpace(CodeGenModule &CGM, 8365 const VarDecl *D) const override { 8366 // Check if global/static variable is defined in address space 8367 // 1~6 (__flash, __flash1, __flash2, __flash3, __flash4, __flash5) 8368 // but not constant. 8369 if (D) { 8370 LangAS AS = D->getType().getAddressSpace(); 8371 if (isTargetAddressSpace(AS) && 1 <= toTargetAddressSpace(AS) && 8372 toTargetAddressSpace(AS) <= 6 && !D->getType().isConstQualified()) 8373 CGM.getDiags().Report(D->getLocation(), 8374 diag::err_verify_nonconst_addrspace) 8375 << "__flash*"; 8376 } 8377 return TargetCodeGenInfo::getGlobalVarAddressSpace(CGM, D); 8378 } 8379 8380 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 8381 CodeGen::CodeGenModule &CGM) const override { 8382 if (GV->isDeclaration()) 8383 return; 8384 const auto *FD = dyn_cast_or_null<FunctionDecl>(D); 8385 if (!FD) return; 8386 auto *Fn = cast<llvm::Function>(GV); 8387 8388 if (FD->getAttr<AVRInterruptAttr>()) 8389 Fn->addFnAttr("interrupt"); 8390 8391 if (FD->getAttr<AVRSignalAttr>()) 8392 Fn->addFnAttr("signal"); 8393 } 8394 }; 8395 } 8396 8397 //===----------------------------------------------------------------------===// 8398 // TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults. 8399 // Currently subclassed only to implement custom OpenCL C function attribute 8400 // handling. 8401 //===----------------------------------------------------------------------===// 8402 8403 namespace { 8404 8405 class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo { 8406 public: 8407 TCETargetCodeGenInfo(CodeGenTypes &CGT) 8408 : DefaultTargetCodeGenInfo(CGT) {} 8409 8410 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 8411 CodeGen::CodeGenModule &M) const override; 8412 }; 8413 8414 void TCETargetCodeGenInfo::setTargetAttributes( 8415 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const { 8416 if (GV->isDeclaration()) 8417 return; 8418 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D); 8419 if (!FD) return; 8420 8421 llvm::Function *F = cast<llvm::Function>(GV); 8422 8423 if (M.getLangOpts().OpenCL) { 8424 if (FD->hasAttr<OpenCLKernelAttr>()) { 8425 // OpenCL C Kernel functions are not subject to inlining 8426 F->addFnAttr(llvm::Attribute::NoInline); 8427 const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>(); 8428 if (Attr) { 8429 // Convert the reqd_work_group_size() attributes to metadata. 8430 llvm::LLVMContext &Context = F->getContext(); 8431 llvm::NamedMDNode *OpenCLMetadata = 8432 M.getModule().getOrInsertNamedMetadata( 8433 "opencl.kernel_wg_size_info"); 8434 8435 SmallVector<llvm::Metadata *, 5> Operands; 8436 Operands.push_back(llvm::ConstantAsMetadata::get(F)); 8437 8438 Operands.push_back( 8439 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue( 8440 M.Int32Ty, llvm::APInt(32, Attr->getXDim())))); 8441 Operands.push_back( 8442 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue( 8443 M.Int32Ty, llvm::APInt(32, Attr->getYDim())))); 8444 Operands.push_back( 8445 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue( 8446 M.Int32Ty, llvm::APInt(32, Attr->getZDim())))); 8447 8448 // Add a boolean constant operand for "required" (true) or "hint" 8449 // (false) for implementing the work_group_size_hint attr later. 8450 // Currently always true as the hint is not yet implemented. 8451 Operands.push_back( 8452 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getTrue(Context))); 8453 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands)); 8454 } 8455 } 8456 } 8457 } 8458 8459 } 8460 8461 //===----------------------------------------------------------------------===// 8462 // Hexagon ABI Implementation 8463 //===----------------------------------------------------------------------===// 8464 8465 namespace { 8466 8467 class HexagonABIInfo : public DefaultABIInfo { 8468 public: 8469 HexagonABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {} 8470 8471 private: 8472 ABIArgInfo classifyReturnType(QualType RetTy) const; 8473 ABIArgInfo classifyArgumentType(QualType RetTy) const; 8474 ABIArgInfo classifyArgumentType(QualType RetTy, unsigned *RegsLeft) const; 8475 8476 void computeInfo(CGFunctionInfo &FI) const override; 8477 8478 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 8479 QualType Ty) const override; 8480 Address EmitVAArgFromMemory(CodeGenFunction &CFG, Address VAListAddr, 8481 QualType Ty) const; 8482 Address EmitVAArgForHexagon(CodeGenFunction &CFG, Address VAListAddr, 8483 QualType Ty) const; 8484 Address EmitVAArgForHexagonLinux(CodeGenFunction &CFG, Address VAListAddr, 8485 QualType Ty) const; 8486 }; 8487 8488 class HexagonTargetCodeGenInfo : public TargetCodeGenInfo { 8489 public: 8490 HexagonTargetCodeGenInfo(CodeGenTypes &CGT) 8491 : TargetCodeGenInfo(std::make_unique<HexagonABIInfo>(CGT)) {} 8492 8493 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 8494 return 29; 8495 } 8496 8497 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 8498 CodeGen::CodeGenModule &GCM) const override { 8499 if (GV->isDeclaration()) 8500 return; 8501 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D); 8502 if (!FD) 8503 return; 8504 } 8505 }; 8506 8507 } // namespace 8508 8509 void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const { 8510 unsigned RegsLeft = 6; 8511 if (!getCXXABI().classifyReturnType(FI)) 8512 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 8513 for (auto &I : FI.arguments()) 8514 I.info = classifyArgumentType(I.type, &RegsLeft); 8515 } 8516 8517 static bool HexagonAdjustRegsLeft(uint64_t Size, unsigned *RegsLeft) { 8518 assert(Size <= 64 && "Not expecting to pass arguments larger than 64 bits" 8519 " through registers"); 8520 8521 if (*RegsLeft == 0) 8522 return false; 8523 8524 if (Size <= 32) { 8525 (*RegsLeft)--; 8526 return true; 8527 } 8528 8529 if (2 <= (*RegsLeft & (~1U))) { 8530 *RegsLeft = (*RegsLeft & (~1U)) - 2; 8531 return true; 8532 } 8533 8534 // Next available register was r5 but candidate was greater than 32-bits so it 8535 // has to go on the stack. However we still consume r5 8536 if (*RegsLeft == 1) 8537 *RegsLeft = 0; 8538 8539 return false; 8540 } 8541 8542 ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty, 8543 unsigned *RegsLeft) const { 8544 if (!isAggregateTypeForABI(Ty)) { 8545 // Treat an enum type as its underlying type. 8546 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 8547 Ty = EnumTy->getDecl()->getIntegerType(); 8548 8549 uint64_t Size = getContext().getTypeSize(Ty); 8550 if (Size <= 64) 8551 HexagonAdjustRegsLeft(Size, RegsLeft); 8552 8553 if (Size > 64 && Ty->isBitIntType()) 8554 return getNaturalAlignIndirect(Ty, /*ByVal=*/true); 8555 8556 return isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty) 8557 : ABIArgInfo::getDirect(); 8558 } 8559 8560 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 8561 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 8562 8563 // Ignore empty records. 8564 if (isEmptyRecord(getContext(), Ty, true)) 8565 return ABIArgInfo::getIgnore(); 8566 8567 uint64_t Size = getContext().getTypeSize(Ty); 8568 unsigned Align = getContext().getTypeAlign(Ty); 8569 8570 if (Size > 64) 8571 return getNaturalAlignIndirect(Ty, /*ByVal=*/true); 8572 8573 if (HexagonAdjustRegsLeft(Size, RegsLeft)) 8574 Align = Size <= 32 ? 32 : 64; 8575 if (Size <= Align) { 8576 // Pass in the smallest viable integer type. 8577 if (!llvm::isPowerOf2_64(Size)) 8578 Size = llvm::NextPowerOf2(Size); 8579 return ABIArgInfo::getDirect(llvm::Type::getIntNTy(getVMContext(), Size)); 8580 } 8581 return DefaultABIInfo::classifyArgumentType(Ty); 8582 } 8583 8584 ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const { 8585 if (RetTy->isVoidType()) 8586 return ABIArgInfo::getIgnore(); 8587 8588 const TargetInfo &T = CGT.getTarget(); 8589 uint64_t Size = getContext().getTypeSize(RetTy); 8590 8591 if (RetTy->getAs<VectorType>()) { 8592 // HVX vectors are returned in vector registers or register pairs. 8593 if (T.hasFeature("hvx")) { 8594 assert(T.hasFeature("hvx-length64b") || T.hasFeature("hvx-length128b")); 8595 uint64_t VecSize = T.hasFeature("hvx-length64b") ? 64*8 : 128*8; 8596 if (Size == VecSize || Size == 2*VecSize) 8597 return ABIArgInfo::getDirectInReg(); 8598 } 8599 // Large vector types should be returned via memory. 8600 if (Size > 64) 8601 return getNaturalAlignIndirect(RetTy); 8602 } 8603 8604 if (!isAggregateTypeForABI(RetTy)) { 8605 // Treat an enum type as its underlying type. 8606 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 8607 RetTy = EnumTy->getDecl()->getIntegerType(); 8608 8609 if (Size > 64 && RetTy->isBitIntType()) 8610 return getNaturalAlignIndirect(RetTy, /*ByVal=*/false); 8611 8612 return isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy) 8613 : ABIArgInfo::getDirect(); 8614 } 8615 8616 if (isEmptyRecord(getContext(), RetTy, true)) 8617 return ABIArgInfo::getIgnore(); 8618 8619 // Aggregates <= 8 bytes are returned in registers, other aggregates 8620 // are returned indirectly. 8621 if (Size <= 64) { 8622 // Return in the smallest viable integer type. 8623 if (!llvm::isPowerOf2_64(Size)) 8624 Size = llvm::NextPowerOf2(Size); 8625 return ABIArgInfo::getDirect(llvm::Type::getIntNTy(getVMContext(), Size)); 8626 } 8627 return getNaturalAlignIndirect(RetTy, /*ByVal=*/true); 8628 } 8629 8630 Address HexagonABIInfo::EmitVAArgFromMemory(CodeGenFunction &CGF, 8631 Address VAListAddr, 8632 QualType Ty) const { 8633 // Load the overflow area pointer. 8634 Address __overflow_area_pointer_p = 8635 CGF.Builder.CreateStructGEP(VAListAddr, 2, "__overflow_area_pointer_p"); 8636 llvm::Value *__overflow_area_pointer = CGF.Builder.CreateLoad( 8637 __overflow_area_pointer_p, "__overflow_area_pointer"); 8638 8639 uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8; 8640 if (Align > 4) { 8641 // Alignment should be a power of 2. 8642 assert((Align & (Align - 1)) == 0 && "Alignment is not power of 2!"); 8643 8644 // overflow_arg_area = (overflow_arg_area + align - 1) & -align; 8645 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int64Ty, Align - 1); 8646 8647 // Add offset to the current pointer to access the argument. 8648 __overflow_area_pointer = 8649 CGF.Builder.CreateGEP(CGF.Int8Ty, __overflow_area_pointer, Offset); 8650 llvm::Value *AsInt = 8651 CGF.Builder.CreatePtrToInt(__overflow_area_pointer, CGF.Int32Ty); 8652 8653 // Create a mask which should be "AND"ed 8654 // with (overflow_arg_area + align - 1) 8655 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int32Ty, -(int)Align); 8656 __overflow_area_pointer = CGF.Builder.CreateIntToPtr( 8657 CGF.Builder.CreateAnd(AsInt, Mask), __overflow_area_pointer->getType(), 8658 "__overflow_area_pointer.align"); 8659 } 8660 8661 // Get the type of the argument from memory and bitcast 8662 // overflow area pointer to the argument type. 8663 llvm::Type *PTy = CGF.ConvertTypeForMem(Ty); 8664 Address AddrTyped = CGF.Builder.CreateBitCast( 8665 Address(__overflow_area_pointer, CharUnits::fromQuantity(Align)), 8666 llvm::PointerType::getUnqual(PTy)); 8667 8668 // Round up to the minimum stack alignment for varargs which is 4 bytes. 8669 uint64_t Offset = llvm::alignTo(CGF.getContext().getTypeSize(Ty) / 8, 4); 8670 8671 __overflow_area_pointer = CGF.Builder.CreateGEP( 8672 CGF.Int8Ty, __overflow_area_pointer, 8673 llvm::ConstantInt::get(CGF.Int32Ty, Offset), 8674 "__overflow_area_pointer.next"); 8675 CGF.Builder.CreateStore(__overflow_area_pointer, __overflow_area_pointer_p); 8676 8677 return AddrTyped; 8678 } 8679 8680 Address HexagonABIInfo::EmitVAArgForHexagon(CodeGenFunction &CGF, 8681 Address VAListAddr, 8682 QualType Ty) const { 8683 // FIXME: Need to handle alignment 8684 llvm::Type *BP = CGF.Int8PtrTy; 8685 llvm::Type *BPP = CGF.Int8PtrPtrTy; 8686 CGBuilderTy &Builder = CGF.Builder; 8687 Address VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap"); 8688 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur"); 8689 // Handle address alignment for type alignment > 32 bits 8690 uint64_t TyAlign = CGF.getContext().getTypeAlign(Ty) / 8; 8691 if (TyAlign > 4) { 8692 assert((TyAlign & (TyAlign - 1)) == 0 && "Alignment is not power of 2!"); 8693 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int32Ty); 8694 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt32(TyAlign - 1)); 8695 AddrAsInt = Builder.CreateAnd(AddrAsInt, Builder.getInt32(~(TyAlign - 1))); 8696 Addr = Builder.CreateIntToPtr(AddrAsInt, BP); 8697 } 8698 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty)); 8699 Address AddrTyped = Builder.CreateBitCast( 8700 Address(Addr, CharUnits::fromQuantity(TyAlign)), PTy); 8701 8702 uint64_t Offset = llvm::alignTo(CGF.getContext().getTypeSize(Ty) / 8, 4); 8703 llvm::Value *NextAddr = Builder.CreateGEP( 8704 CGF.Int8Ty, Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset), "ap.next"); 8705 Builder.CreateStore(NextAddr, VAListAddrAsBPP); 8706 8707 return AddrTyped; 8708 } 8709 8710 Address HexagonABIInfo::EmitVAArgForHexagonLinux(CodeGenFunction &CGF, 8711 Address VAListAddr, 8712 QualType Ty) const { 8713 int ArgSize = CGF.getContext().getTypeSize(Ty) / 8; 8714 8715 if (ArgSize > 8) 8716 return EmitVAArgFromMemory(CGF, VAListAddr, Ty); 8717 8718 // Here we have check if the argument is in register area or 8719 // in overflow area. 8720 // If the saved register area pointer + argsize rounded up to alignment > 8721 // saved register area end pointer, argument is in overflow area. 8722 unsigned RegsLeft = 6; 8723 Ty = CGF.getContext().getCanonicalType(Ty); 8724 (void)classifyArgumentType(Ty, &RegsLeft); 8725 8726 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg"); 8727 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg"); 8728 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack"); 8729 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end"); 8730 8731 // Get rounded size of the argument.GCC does not allow vararg of 8732 // size < 4 bytes. We follow the same logic here. 8733 ArgSize = (CGF.getContext().getTypeSize(Ty) <= 32) ? 4 : 8; 8734 int ArgAlign = (CGF.getContext().getTypeSize(Ty) <= 32) ? 4 : 8; 8735 8736 // Argument may be in saved register area 8737 CGF.EmitBlock(MaybeRegBlock); 8738 8739 // Load the current saved register area pointer. 8740 Address __current_saved_reg_area_pointer_p = CGF.Builder.CreateStructGEP( 8741 VAListAddr, 0, "__current_saved_reg_area_pointer_p"); 8742 llvm::Value *__current_saved_reg_area_pointer = CGF.Builder.CreateLoad( 8743 __current_saved_reg_area_pointer_p, "__current_saved_reg_area_pointer"); 8744 8745 // Load the saved register area end pointer. 8746 Address __saved_reg_area_end_pointer_p = CGF.Builder.CreateStructGEP( 8747 VAListAddr, 1, "__saved_reg_area_end_pointer_p"); 8748 llvm::Value *__saved_reg_area_end_pointer = CGF.Builder.CreateLoad( 8749 __saved_reg_area_end_pointer_p, "__saved_reg_area_end_pointer"); 8750 8751 // If the size of argument is > 4 bytes, check if the stack 8752 // location is aligned to 8 bytes 8753 if (ArgAlign > 4) { 8754 8755 llvm::Value *__current_saved_reg_area_pointer_int = 8756 CGF.Builder.CreatePtrToInt(__current_saved_reg_area_pointer, 8757 CGF.Int32Ty); 8758 8759 __current_saved_reg_area_pointer_int = CGF.Builder.CreateAdd( 8760 __current_saved_reg_area_pointer_int, 8761 llvm::ConstantInt::get(CGF.Int32Ty, (ArgAlign - 1)), 8762 "align_current_saved_reg_area_pointer"); 8763 8764 __current_saved_reg_area_pointer_int = 8765 CGF.Builder.CreateAnd(__current_saved_reg_area_pointer_int, 8766 llvm::ConstantInt::get(CGF.Int32Ty, -ArgAlign), 8767 "align_current_saved_reg_area_pointer"); 8768 8769 __current_saved_reg_area_pointer = 8770 CGF.Builder.CreateIntToPtr(__current_saved_reg_area_pointer_int, 8771 __current_saved_reg_area_pointer->getType(), 8772 "align_current_saved_reg_area_pointer"); 8773 } 8774 8775 llvm::Value *__new_saved_reg_area_pointer = 8776 CGF.Builder.CreateGEP(CGF.Int8Ty, __current_saved_reg_area_pointer, 8777 llvm::ConstantInt::get(CGF.Int32Ty, ArgSize), 8778 "__new_saved_reg_area_pointer"); 8779 8780 llvm::Value *UsingStack = nullptr; 8781 UsingStack = CGF.Builder.CreateICmpSGT(__new_saved_reg_area_pointer, 8782 __saved_reg_area_end_pointer); 8783 8784 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, InRegBlock); 8785 8786 // Argument in saved register area 8787 // Implement the block where argument is in register saved area 8788 CGF.EmitBlock(InRegBlock); 8789 8790 llvm::Type *PTy = CGF.ConvertType(Ty); 8791 llvm::Value *__saved_reg_area_p = CGF.Builder.CreateBitCast( 8792 __current_saved_reg_area_pointer, llvm::PointerType::getUnqual(PTy)); 8793 8794 CGF.Builder.CreateStore(__new_saved_reg_area_pointer, 8795 __current_saved_reg_area_pointer_p); 8796 8797 CGF.EmitBranch(ContBlock); 8798 8799 // Argument in overflow area 8800 // Implement the block where the argument is in overflow area. 8801 CGF.EmitBlock(OnStackBlock); 8802 8803 // Load the overflow area pointer 8804 Address __overflow_area_pointer_p = 8805 CGF.Builder.CreateStructGEP(VAListAddr, 2, "__overflow_area_pointer_p"); 8806 llvm::Value *__overflow_area_pointer = CGF.Builder.CreateLoad( 8807 __overflow_area_pointer_p, "__overflow_area_pointer"); 8808 8809 // Align the overflow area pointer according to the alignment of the argument 8810 if (ArgAlign > 4) { 8811 llvm::Value *__overflow_area_pointer_int = 8812 CGF.Builder.CreatePtrToInt(__overflow_area_pointer, CGF.Int32Ty); 8813 8814 __overflow_area_pointer_int = 8815 CGF.Builder.CreateAdd(__overflow_area_pointer_int, 8816 llvm::ConstantInt::get(CGF.Int32Ty, ArgAlign - 1), 8817 "align_overflow_area_pointer"); 8818 8819 __overflow_area_pointer_int = 8820 CGF.Builder.CreateAnd(__overflow_area_pointer_int, 8821 llvm::ConstantInt::get(CGF.Int32Ty, -ArgAlign), 8822 "align_overflow_area_pointer"); 8823 8824 __overflow_area_pointer = CGF.Builder.CreateIntToPtr( 8825 __overflow_area_pointer_int, __overflow_area_pointer->getType(), 8826 "align_overflow_area_pointer"); 8827 } 8828 8829 // Get the pointer for next argument in overflow area and store it 8830 // to overflow area pointer. 8831 llvm::Value *__new_overflow_area_pointer = CGF.Builder.CreateGEP( 8832 CGF.Int8Ty, __overflow_area_pointer, 8833 llvm::ConstantInt::get(CGF.Int32Ty, ArgSize), 8834 "__overflow_area_pointer.next"); 8835 8836 CGF.Builder.CreateStore(__new_overflow_area_pointer, 8837 __overflow_area_pointer_p); 8838 8839 CGF.Builder.CreateStore(__new_overflow_area_pointer, 8840 __current_saved_reg_area_pointer_p); 8841 8842 // Bitcast the overflow area pointer to the type of argument. 8843 llvm::Type *OverflowPTy = CGF.ConvertTypeForMem(Ty); 8844 llvm::Value *__overflow_area_p = CGF.Builder.CreateBitCast( 8845 __overflow_area_pointer, llvm::PointerType::getUnqual(OverflowPTy)); 8846 8847 CGF.EmitBranch(ContBlock); 8848 8849 // Get the correct pointer to load the variable argument 8850 // Implement the ContBlock 8851 CGF.EmitBlock(ContBlock); 8852 8853 llvm::Type *MemPTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty)); 8854 llvm::PHINode *ArgAddr = CGF.Builder.CreatePHI(MemPTy, 2, "vaarg.addr"); 8855 ArgAddr->addIncoming(__saved_reg_area_p, InRegBlock); 8856 ArgAddr->addIncoming(__overflow_area_p, OnStackBlock); 8857 8858 return Address(ArgAddr, CharUnits::fromQuantity(ArgAlign)); 8859 } 8860 8861 Address HexagonABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 8862 QualType Ty) const { 8863 8864 if (getTarget().getTriple().isMusl()) 8865 return EmitVAArgForHexagonLinux(CGF, VAListAddr, Ty); 8866 8867 return EmitVAArgForHexagon(CGF, VAListAddr, Ty); 8868 } 8869 8870 //===----------------------------------------------------------------------===// 8871 // Lanai ABI Implementation 8872 //===----------------------------------------------------------------------===// 8873 8874 namespace { 8875 class LanaiABIInfo : public DefaultABIInfo { 8876 public: 8877 LanaiABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {} 8878 8879 bool shouldUseInReg(QualType Ty, CCState &State) const; 8880 8881 void computeInfo(CGFunctionInfo &FI) const override { 8882 CCState State(FI); 8883 // Lanai uses 4 registers to pass arguments unless the function has the 8884 // regparm attribute set. 8885 if (FI.getHasRegParm()) { 8886 State.FreeRegs = FI.getRegParm(); 8887 } else { 8888 State.FreeRegs = 4; 8889 } 8890 8891 if (!getCXXABI().classifyReturnType(FI)) 8892 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 8893 for (auto &I : FI.arguments()) 8894 I.info = classifyArgumentType(I.type, State); 8895 } 8896 8897 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const; 8898 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const; 8899 }; 8900 } // end anonymous namespace 8901 8902 bool LanaiABIInfo::shouldUseInReg(QualType Ty, CCState &State) const { 8903 unsigned Size = getContext().getTypeSize(Ty); 8904 unsigned SizeInRegs = llvm::alignTo(Size, 32U) / 32U; 8905 8906 if (SizeInRegs == 0) 8907 return false; 8908 8909 if (SizeInRegs > State.FreeRegs) { 8910 State.FreeRegs = 0; 8911 return false; 8912 } 8913 8914 State.FreeRegs -= SizeInRegs; 8915 8916 return true; 8917 } 8918 8919 ABIArgInfo LanaiABIInfo::getIndirectResult(QualType Ty, bool ByVal, 8920 CCState &State) const { 8921 if (!ByVal) { 8922 if (State.FreeRegs) { 8923 --State.FreeRegs; // Non-byval indirects just use one pointer. 8924 return getNaturalAlignIndirectInReg(Ty); 8925 } 8926 return getNaturalAlignIndirect(Ty, false); 8927 } 8928 8929 // Compute the byval alignment. 8930 const unsigned MinABIStackAlignInBytes = 4; 8931 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8; 8932 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true, 8933 /*Realign=*/TypeAlign > 8934 MinABIStackAlignInBytes); 8935 } 8936 8937 ABIArgInfo LanaiABIInfo::classifyArgumentType(QualType Ty, 8938 CCState &State) const { 8939 // Check with the C++ ABI first. 8940 const RecordType *RT = Ty->getAs<RecordType>(); 8941 if (RT) { 8942 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()); 8943 if (RAA == CGCXXABI::RAA_Indirect) { 8944 return getIndirectResult(Ty, /*ByVal=*/false, State); 8945 } else if (RAA == CGCXXABI::RAA_DirectInMemory) { 8946 return getNaturalAlignIndirect(Ty, /*ByVal=*/true); 8947 } 8948 } 8949 8950 if (isAggregateTypeForABI(Ty)) { 8951 // Structures with flexible arrays are always indirect. 8952 if (RT && RT->getDecl()->hasFlexibleArrayMember()) 8953 return getIndirectResult(Ty, /*ByVal=*/true, State); 8954 8955 // Ignore empty structs/unions. 8956 if (isEmptyRecord(getContext(), Ty, true)) 8957 return ABIArgInfo::getIgnore(); 8958 8959 llvm::LLVMContext &LLVMContext = getVMContext(); 8960 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32; 8961 if (SizeInRegs <= State.FreeRegs) { 8962 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext); 8963 SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32); 8964 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements); 8965 State.FreeRegs -= SizeInRegs; 8966 return ABIArgInfo::getDirectInReg(Result); 8967 } else { 8968 State.FreeRegs = 0; 8969 } 8970 return getIndirectResult(Ty, true, State); 8971 } 8972 8973 // Treat an enum type as its underlying type. 8974 if (const auto *EnumTy = Ty->getAs<EnumType>()) 8975 Ty = EnumTy->getDecl()->getIntegerType(); 8976 8977 bool InReg = shouldUseInReg(Ty, State); 8978 8979 // Don't pass >64 bit integers in registers. 8980 if (const auto *EIT = Ty->getAs<BitIntType>()) 8981 if (EIT->getNumBits() > 64) 8982 return getIndirectResult(Ty, /*ByVal=*/true, State); 8983 8984 if (isPromotableIntegerTypeForABI(Ty)) { 8985 if (InReg) 8986 return ABIArgInfo::getDirectInReg(); 8987 return ABIArgInfo::getExtend(Ty); 8988 } 8989 if (InReg) 8990 return ABIArgInfo::getDirectInReg(); 8991 return ABIArgInfo::getDirect(); 8992 } 8993 8994 namespace { 8995 class LanaiTargetCodeGenInfo : public TargetCodeGenInfo { 8996 public: 8997 LanaiTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT) 8998 : TargetCodeGenInfo(std::make_unique<LanaiABIInfo>(CGT)) {} 8999 }; 9000 } 9001 9002 //===----------------------------------------------------------------------===// 9003 // AMDGPU ABI Implementation 9004 //===----------------------------------------------------------------------===// 9005 9006 namespace { 9007 9008 class AMDGPUABIInfo final : public DefaultABIInfo { 9009 private: 9010 static const unsigned MaxNumRegsForArgsRet = 16; 9011 9012 unsigned numRegsForType(QualType Ty) const; 9013 9014 bool isHomogeneousAggregateBaseType(QualType Ty) const override; 9015 bool isHomogeneousAggregateSmallEnough(const Type *Base, 9016 uint64_t Members) const override; 9017 9018 // Coerce HIP scalar pointer arguments from generic pointers to global ones. 9019 llvm::Type *coerceKernelArgumentType(llvm::Type *Ty, unsigned FromAS, 9020 unsigned ToAS) const { 9021 // Single value types. 9022 auto *PtrTy = llvm::dyn_cast<llvm::PointerType>(Ty); 9023 if (PtrTy && PtrTy->getAddressSpace() == FromAS) 9024 return llvm::PointerType::getWithSamePointeeType(PtrTy, ToAS); 9025 return Ty; 9026 } 9027 9028 public: 9029 explicit AMDGPUABIInfo(CodeGen::CodeGenTypes &CGT) : 9030 DefaultABIInfo(CGT) {} 9031 9032 ABIArgInfo classifyReturnType(QualType RetTy) const; 9033 ABIArgInfo classifyKernelArgumentType(QualType Ty) const; 9034 ABIArgInfo classifyArgumentType(QualType Ty, unsigned &NumRegsLeft) const; 9035 9036 void computeInfo(CGFunctionInfo &FI) const override; 9037 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 9038 QualType Ty) const override; 9039 }; 9040 9041 bool AMDGPUABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const { 9042 return true; 9043 } 9044 9045 bool AMDGPUABIInfo::isHomogeneousAggregateSmallEnough( 9046 const Type *Base, uint64_t Members) const { 9047 uint32_t NumRegs = (getContext().getTypeSize(Base) + 31) / 32; 9048 9049 // Homogeneous Aggregates may occupy at most 16 registers. 9050 return Members * NumRegs <= MaxNumRegsForArgsRet; 9051 } 9052 9053 /// Estimate number of registers the type will use when passed in registers. 9054 unsigned AMDGPUABIInfo::numRegsForType(QualType Ty) const { 9055 unsigned NumRegs = 0; 9056 9057 if (const VectorType *VT = Ty->getAs<VectorType>()) { 9058 // Compute from the number of elements. The reported size is based on the 9059 // in-memory size, which includes the padding 4th element for 3-vectors. 9060 QualType EltTy = VT->getElementType(); 9061 unsigned EltSize = getContext().getTypeSize(EltTy); 9062 9063 // 16-bit element vectors should be passed as packed. 9064 if (EltSize == 16) 9065 return (VT->getNumElements() + 1) / 2; 9066 9067 unsigned EltNumRegs = (EltSize + 31) / 32; 9068 return EltNumRegs * VT->getNumElements(); 9069 } 9070 9071 if (const RecordType *RT = Ty->getAs<RecordType>()) { 9072 const RecordDecl *RD = RT->getDecl(); 9073 assert(!RD->hasFlexibleArrayMember()); 9074 9075 for (const FieldDecl *Field : RD->fields()) { 9076 QualType FieldTy = Field->getType(); 9077 NumRegs += numRegsForType(FieldTy); 9078 } 9079 9080 return NumRegs; 9081 } 9082 9083 return (getContext().getTypeSize(Ty) + 31) / 32; 9084 } 9085 9086 void AMDGPUABIInfo::computeInfo(CGFunctionInfo &FI) const { 9087 llvm::CallingConv::ID CC = FI.getCallingConvention(); 9088 9089 if (!getCXXABI().classifyReturnType(FI)) 9090 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 9091 9092 unsigned NumRegsLeft = MaxNumRegsForArgsRet; 9093 for (auto &Arg : FI.arguments()) { 9094 if (CC == llvm::CallingConv::AMDGPU_KERNEL) { 9095 Arg.info = classifyKernelArgumentType(Arg.type); 9096 } else { 9097 Arg.info = classifyArgumentType(Arg.type, NumRegsLeft); 9098 } 9099 } 9100 } 9101 9102 Address AMDGPUABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 9103 QualType Ty) const { 9104 llvm_unreachable("AMDGPU does not support varargs"); 9105 } 9106 9107 ABIArgInfo AMDGPUABIInfo::classifyReturnType(QualType RetTy) const { 9108 if (isAggregateTypeForABI(RetTy)) { 9109 // Records with non-trivial destructors/copy-constructors should not be 9110 // returned by value. 9111 if (!getRecordArgABI(RetTy, getCXXABI())) { 9112 // Ignore empty structs/unions. 9113 if (isEmptyRecord(getContext(), RetTy, true)) 9114 return ABIArgInfo::getIgnore(); 9115 9116 // Lower single-element structs to just return a regular value. 9117 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext())) 9118 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0))); 9119 9120 if (const RecordType *RT = RetTy->getAs<RecordType>()) { 9121 const RecordDecl *RD = RT->getDecl(); 9122 if (RD->hasFlexibleArrayMember()) 9123 return DefaultABIInfo::classifyReturnType(RetTy); 9124 } 9125 9126 // Pack aggregates <= 4 bytes into single VGPR or pair. 9127 uint64_t Size = getContext().getTypeSize(RetTy); 9128 if (Size <= 16) 9129 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext())); 9130 9131 if (Size <= 32) 9132 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext())); 9133 9134 if (Size <= 64) { 9135 llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext()); 9136 return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2)); 9137 } 9138 9139 if (numRegsForType(RetTy) <= MaxNumRegsForArgsRet) 9140 return ABIArgInfo::getDirect(); 9141 } 9142 } 9143 9144 // Otherwise just do the default thing. 9145 return DefaultABIInfo::classifyReturnType(RetTy); 9146 } 9147 9148 /// For kernels all parameters are really passed in a special buffer. It doesn't 9149 /// make sense to pass anything byval, so everything must be direct. 9150 ABIArgInfo AMDGPUABIInfo::classifyKernelArgumentType(QualType Ty) const { 9151 Ty = useFirstFieldIfTransparentUnion(Ty); 9152 9153 // TODO: Can we omit empty structs? 9154 9155 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext())) 9156 Ty = QualType(SeltTy, 0); 9157 9158 llvm::Type *OrigLTy = CGT.ConvertType(Ty); 9159 llvm::Type *LTy = OrigLTy; 9160 if (getContext().getLangOpts().HIP) { 9161 LTy = coerceKernelArgumentType( 9162 OrigLTy, /*FromAS=*/getContext().getTargetAddressSpace(LangAS::Default), 9163 /*ToAS=*/getContext().getTargetAddressSpace(LangAS::cuda_device)); 9164 } 9165 9166 // FIXME: Should also use this for OpenCL, but it requires addressing the 9167 // problem of kernels being called. 9168 // 9169 // FIXME: This doesn't apply the optimization of coercing pointers in structs 9170 // to global address space when using byref. This would require implementing a 9171 // new kind of coercion of the in-memory type when for indirect arguments. 9172 if (!getContext().getLangOpts().OpenCL && LTy == OrigLTy && 9173 isAggregateTypeForABI(Ty)) { 9174 return ABIArgInfo::getIndirectAliased( 9175 getContext().getTypeAlignInChars(Ty), 9176 getContext().getTargetAddressSpace(LangAS::opencl_constant), 9177 false /*Realign*/, nullptr /*Padding*/); 9178 } 9179 9180 // If we set CanBeFlattened to true, CodeGen will expand the struct to its 9181 // individual elements, which confuses the Clover OpenCL backend; therefore we 9182 // have to set it to false here. Other args of getDirect() are just defaults. 9183 return ABIArgInfo::getDirect(LTy, 0, nullptr, false); 9184 } 9185 9186 ABIArgInfo AMDGPUABIInfo::classifyArgumentType(QualType Ty, 9187 unsigned &NumRegsLeft) const { 9188 assert(NumRegsLeft <= MaxNumRegsForArgsRet && "register estimate underflow"); 9189 9190 Ty = useFirstFieldIfTransparentUnion(Ty); 9191 9192 if (isAggregateTypeForABI(Ty)) { 9193 // Records with non-trivial destructors/copy-constructors should not be 9194 // passed by value. 9195 if (auto RAA = getRecordArgABI(Ty, getCXXABI())) 9196 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 9197 9198 // Ignore empty structs/unions. 9199 if (isEmptyRecord(getContext(), Ty, true)) 9200 return ABIArgInfo::getIgnore(); 9201 9202 // Lower single-element structs to just pass a regular value. TODO: We 9203 // could do reasonable-size multiple-element structs too, using getExpand(), 9204 // though watch out for things like bitfields. 9205 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext())) 9206 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0))); 9207 9208 if (const RecordType *RT = Ty->getAs<RecordType>()) { 9209 const RecordDecl *RD = RT->getDecl(); 9210 if (RD->hasFlexibleArrayMember()) 9211 return DefaultABIInfo::classifyArgumentType(Ty); 9212 } 9213 9214 // Pack aggregates <= 8 bytes into single VGPR or pair. 9215 uint64_t Size = getContext().getTypeSize(Ty); 9216 if (Size <= 64) { 9217 unsigned NumRegs = (Size + 31) / 32; 9218 NumRegsLeft -= std::min(NumRegsLeft, NumRegs); 9219 9220 if (Size <= 16) 9221 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext())); 9222 9223 if (Size <= 32) 9224 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext())); 9225 9226 // XXX: Should this be i64 instead, and should the limit increase? 9227 llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext()); 9228 return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2)); 9229 } 9230 9231 if (NumRegsLeft > 0) { 9232 unsigned NumRegs = numRegsForType(Ty); 9233 if (NumRegsLeft >= NumRegs) { 9234 NumRegsLeft -= NumRegs; 9235 return ABIArgInfo::getDirect(); 9236 } 9237 } 9238 } 9239 9240 // Otherwise just do the default thing. 9241 ABIArgInfo ArgInfo = DefaultABIInfo::classifyArgumentType(Ty); 9242 if (!ArgInfo.isIndirect()) { 9243 unsigned NumRegs = numRegsForType(Ty); 9244 NumRegsLeft -= std::min(NumRegs, NumRegsLeft); 9245 } 9246 9247 return ArgInfo; 9248 } 9249 9250 class AMDGPUTargetCodeGenInfo : public TargetCodeGenInfo { 9251 public: 9252 AMDGPUTargetCodeGenInfo(CodeGenTypes &CGT) 9253 : TargetCodeGenInfo(std::make_unique<AMDGPUABIInfo>(CGT)) {} 9254 9255 void setFunctionDeclAttributes(const FunctionDecl *FD, llvm::Function *F, 9256 CodeGenModule &CGM) const; 9257 9258 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 9259 CodeGen::CodeGenModule &M) const override; 9260 unsigned getOpenCLKernelCallingConv() const override; 9261 9262 llvm::Constant *getNullPointer(const CodeGen::CodeGenModule &CGM, 9263 llvm::PointerType *T, QualType QT) const override; 9264 9265 LangAS getASTAllocaAddressSpace() const override { 9266 return getLangASFromTargetAS( 9267 getABIInfo().getDataLayout().getAllocaAddrSpace()); 9268 } 9269 LangAS getGlobalVarAddressSpace(CodeGenModule &CGM, 9270 const VarDecl *D) const override; 9271 llvm::SyncScope::ID getLLVMSyncScopeID(const LangOptions &LangOpts, 9272 SyncScope Scope, 9273 llvm::AtomicOrdering Ordering, 9274 llvm::LLVMContext &Ctx) const override; 9275 llvm::Function * 9276 createEnqueuedBlockKernel(CodeGenFunction &CGF, 9277 llvm::Function *BlockInvokeFunc, 9278 llvm::Value *BlockLiteral) const override; 9279 bool shouldEmitStaticExternCAliases() const override; 9280 void setCUDAKernelCallingConvention(const FunctionType *&FT) const override; 9281 }; 9282 } 9283 9284 static bool requiresAMDGPUProtectedVisibility(const Decl *D, 9285 llvm::GlobalValue *GV) { 9286 if (GV->getVisibility() != llvm::GlobalValue::HiddenVisibility) 9287 return false; 9288 9289 return D->hasAttr<OpenCLKernelAttr>() || 9290 (isa<FunctionDecl>(D) && D->hasAttr<CUDAGlobalAttr>()) || 9291 (isa<VarDecl>(D) && 9292 (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>() || 9293 cast<VarDecl>(D)->getType()->isCUDADeviceBuiltinSurfaceType() || 9294 cast<VarDecl>(D)->getType()->isCUDADeviceBuiltinTextureType())); 9295 } 9296 9297 void AMDGPUTargetCodeGenInfo::setFunctionDeclAttributes( 9298 const FunctionDecl *FD, llvm::Function *F, CodeGenModule &M) const { 9299 const auto *ReqdWGS = 9300 M.getLangOpts().OpenCL ? FD->getAttr<ReqdWorkGroupSizeAttr>() : nullptr; 9301 const bool IsOpenCLKernel = 9302 M.getLangOpts().OpenCL && FD->hasAttr<OpenCLKernelAttr>(); 9303 const bool IsHIPKernel = M.getLangOpts().HIP && FD->hasAttr<CUDAGlobalAttr>(); 9304 9305 const auto *FlatWGS = FD->getAttr<AMDGPUFlatWorkGroupSizeAttr>(); 9306 if (ReqdWGS || FlatWGS) { 9307 unsigned Min = 0; 9308 unsigned Max = 0; 9309 if (FlatWGS) { 9310 Min = FlatWGS->getMin() 9311 ->EvaluateKnownConstInt(M.getContext()) 9312 .getExtValue(); 9313 Max = FlatWGS->getMax() 9314 ->EvaluateKnownConstInt(M.getContext()) 9315 .getExtValue(); 9316 } 9317 if (ReqdWGS && Min == 0 && Max == 0) 9318 Min = Max = ReqdWGS->getXDim() * ReqdWGS->getYDim() * ReqdWGS->getZDim(); 9319 9320 if (Min != 0) { 9321 assert(Min <= Max && "Min must be less than or equal Max"); 9322 9323 std::string AttrVal = llvm::utostr(Min) + "," + llvm::utostr(Max); 9324 F->addFnAttr("amdgpu-flat-work-group-size", AttrVal); 9325 } else 9326 assert(Max == 0 && "Max must be zero"); 9327 } else if (IsOpenCLKernel || IsHIPKernel) { 9328 // By default, restrict the maximum size to a value specified by 9329 // --gpu-max-threads-per-block=n or its default value for HIP. 9330 const unsigned OpenCLDefaultMaxWorkGroupSize = 256; 9331 const unsigned DefaultMaxWorkGroupSize = 9332 IsOpenCLKernel ? OpenCLDefaultMaxWorkGroupSize 9333 : M.getLangOpts().GPUMaxThreadsPerBlock; 9334 std::string AttrVal = 9335 std::string("1,") + llvm::utostr(DefaultMaxWorkGroupSize); 9336 F->addFnAttr("amdgpu-flat-work-group-size", AttrVal); 9337 } 9338 9339 if (const auto *Attr = FD->getAttr<AMDGPUWavesPerEUAttr>()) { 9340 unsigned Min = 9341 Attr->getMin()->EvaluateKnownConstInt(M.getContext()).getExtValue(); 9342 unsigned Max = Attr->getMax() ? Attr->getMax() 9343 ->EvaluateKnownConstInt(M.getContext()) 9344 .getExtValue() 9345 : 0; 9346 9347 if (Min != 0) { 9348 assert((Max == 0 || Min <= Max) && "Min must be less than or equal Max"); 9349 9350 std::string AttrVal = llvm::utostr(Min); 9351 if (Max != 0) 9352 AttrVal = AttrVal + "," + llvm::utostr(Max); 9353 F->addFnAttr("amdgpu-waves-per-eu", AttrVal); 9354 } else 9355 assert(Max == 0 && "Max must be zero"); 9356 } 9357 9358 if (const auto *Attr = FD->getAttr<AMDGPUNumSGPRAttr>()) { 9359 unsigned NumSGPR = Attr->getNumSGPR(); 9360 9361 if (NumSGPR != 0) 9362 F->addFnAttr("amdgpu-num-sgpr", llvm::utostr(NumSGPR)); 9363 } 9364 9365 if (const auto *Attr = FD->getAttr<AMDGPUNumVGPRAttr>()) { 9366 uint32_t NumVGPR = Attr->getNumVGPR(); 9367 9368 if (NumVGPR != 0) 9369 F->addFnAttr("amdgpu-num-vgpr", llvm::utostr(NumVGPR)); 9370 } 9371 } 9372 9373 void AMDGPUTargetCodeGenInfo::setTargetAttributes( 9374 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const { 9375 if (requiresAMDGPUProtectedVisibility(D, GV)) { 9376 GV->setVisibility(llvm::GlobalValue::ProtectedVisibility); 9377 GV->setDSOLocal(true); 9378 } 9379 9380 if (GV->isDeclaration()) 9381 return; 9382 9383 llvm::Function *F = dyn_cast<llvm::Function>(GV); 9384 if (!F) 9385 return; 9386 9387 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D); 9388 if (FD) 9389 setFunctionDeclAttributes(FD, F, M); 9390 9391 const bool IsHIPKernel = 9392 M.getLangOpts().HIP && FD && FD->hasAttr<CUDAGlobalAttr>(); 9393 9394 if (IsHIPKernel) 9395 F->addFnAttr("uniform-work-group-size", "true"); 9396 9397 if (M.getContext().getTargetInfo().allowAMDGPUUnsafeFPAtomics()) 9398 F->addFnAttr("amdgpu-unsafe-fp-atomics", "true"); 9399 9400 if (!getABIInfo().getCodeGenOpts().EmitIEEENaNCompliantInsts) 9401 F->addFnAttr("amdgpu-ieee", "false"); 9402 } 9403 9404 unsigned AMDGPUTargetCodeGenInfo::getOpenCLKernelCallingConv() const { 9405 return llvm::CallingConv::AMDGPU_KERNEL; 9406 } 9407 9408 // Currently LLVM assumes null pointers always have value 0, 9409 // which results in incorrectly transformed IR. Therefore, instead of 9410 // emitting null pointers in private and local address spaces, a null 9411 // pointer in generic address space is emitted which is casted to a 9412 // pointer in local or private address space. 9413 llvm::Constant *AMDGPUTargetCodeGenInfo::getNullPointer( 9414 const CodeGen::CodeGenModule &CGM, llvm::PointerType *PT, 9415 QualType QT) const { 9416 if (CGM.getContext().getTargetNullPointerValue(QT) == 0) 9417 return llvm::ConstantPointerNull::get(PT); 9418 9419 auto &Ctx = CGM.getContext(); 9420 auto NPT = llvm::PointerType::getWithSamePointeeType( 9421 PT, Ctx.getTargetAddressSpace(LangAS::opencl_generic)); 9422 return llvm::ConstantExpr::getAddrSpaceCast( 9423 llvm::ConstantPointerNull::get(NPT), PT); 9424 } 9425 9426 LangAS 9427 AMDGPUTargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM, 9428 const VarDecl *D) const { 9429 assert(!CGM.getLangOpts().OpenCL && 9430 !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) && 9431 "Address space agnostic languages only"); 9432 LangAS DefaultGlobalAS = getLangASFromTargetAS( 9433 CGM.getContext().getTargetAddressSpace(LangAS::opencl_global)); 9434 if (!D) 9435 return DefaultGlobalAS; 9436 9437 LangAS AddrSpace = D->getType().getAddressSpace(); 9438 assert(AddrSpace == LangAS::Default || isTargetAddressSpace(AddrSpace)); 9439 if (AddrSpace != LangAS::Default) 9440 return AddrSpace; 9441 9442 // Only promote to address space 4 if VarDecl has constant initialization. 9443 if (CGM.isTypeConstant(D->getType(), false) && 9444 D->hasConstantInitialization()) { 9445 if (auto ConstAS = CGM.getTarget().getConstantAddressSpace()) 9446 return ConstAS.getValue(); 9447 } 9448 return DefaultGlobalAS; 9449 } 9450 9451 llvm::SyncScope::ID 9452 AMDGPUTargetCodeGenInfo::getLLVMSyncScopeID(const LangOptions &LangOpts, 9453 SyncScope Scope, 9454 llvm::AtomicOrdering Ordering, 9455 llvm::LLVMContext &Ctx) const { 9456 std::string Name; 9457 switch (Scope) { 9458 case SyncScope::HIPSingleThread: 9459 Name = "singlethread"; 9460 break; 9461 case SyncScope::HIPWavefront: 9462 case SyncScope::OpenCLSubGroup: 9463 Name = "wavefront"; 9464 break; 9465 case SyncScope::HIPWorkgroup: 9466 case SyncScope::OpenCLWorkGroup: 9467 Name = "workgroup"; 9468 break; 9469 case SyncScope::HIPAgent: 9470 case SyncScope::OpenCLDevice: 9471 Name = "agent"; 9472 break; 9473 case SyncScope::HIPSystem: 9474 case SyncScope::OpenCLAllSVMDevices: 9475 Name = ""; 9476 break; 9477 } 9478 9479 if (Ordering != llvm::AtomicOrdering::SequentiallyConsistent) { 9480 if (!Name.empty()) 9481 Name = Twine(Twine(Name) + Twine("-")).str(); 9482 9483 Name = Twine(Twine(Name) + Twine("one-as")).str(); 9484 } 9485 9486 return Ctx.getOrInsertSyncScopeID(Name); 9487 } 9488 9489 bool AMDGPUTargetCodeGenInfo::shouldEmitStaticExternCAliases() const { 9490 return false; 9491 } 9492 9493 void AMDGPUTargetCodeGenInfo::setCUDAKernelCallingConvention( 9494 const FunctionType *&FT) const { 9495 FT = getABIInfo().getContext().adjustFunctionType( 9496 FT, FT->getExtInfo().withCallingConv(CC_OpenCLKernel)); 9497 } 9498 9499 //===----------------------------------------------------------------------===// 9500 // SPARC v8 ABI Implementation. 9501 // Based on the SPARC Compliance Definition version 2.4.1. 9502 // 9503 // Ensures that complex values are passed in registers. 9504 // 9505 namespace { 9506 class SparcV8ABIInfo : public DefaultABIInfo { 9507 public: 9508 SparcV8ABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {} 9509 9510 private: 9511 ABIArgInfo classifyReturnType(QualType RetTy) const; 9512 void computeInfo(CGFunctionInfo &FI) const override; 9513 }; 9514 } // end anonymous namespace 9515 9516 9517 ABIArgInfo 9518 SparcV8ABIInfo::classifyReturnType(QualType Ty) const { 9519 if (Ty->isAnyComplexType()) { 9520 return ABIArgInfo::getDirect(); 9521 } 9522 else { 9523 return DefaultABIInfo::classifyReturnType(Ty); 9524 } 9525 } 9526 9527 void SparcV8ABIInfo::computeInfo(CGFunctionInfo &FI) const { 9528 9529 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 9530 for (auto &Arg : FI.arguments()) 9531 Arg.info = classifyArgumentType(Arg.type); 9532 } 9533 9534 namespace { 9535 class SparcV8TargetCodeGenInfo : public TargetCodeGenInfo { 9536 public: 9537 SparcV8TargetCodeGenInfo(CodeGenTypes &CGT) 9538 : TargetCodeGenInfo(std::make_unique<SparcV8ABIInfo>(CGT)) {} 9539 9540 llvm::Value *decodeReturnAddress(CodeGen::CodeGenFunction &CGF, 9541 llvm::Value *Address) const override { 9542 int Offset; 9543 if (isAggregateTypeForABI(CGF.CurFnInfo->getReturnType())) 9544 Offset = 12; 9545 else 9546 Offset = 8; 9547 return CGF.Builder.CreateGEP(CGF.Int8Ty, Address, 9548 llvm::ConstantInt::get(CGF.Int32Ty, Offset)); 9549 } 9550 9551 llvm::Value *encodeReturnAddress(CodeGen::CodeGenFunction &CGF, 9552 llvm::Value *Address) const override { 9553 int Offset; 9554 if (isAggregateTypeForABI(CGF.CurFnInfo->getReturnType())) 9555 Offset = -12; 9556 else 9557 Offset = -8; 9558 return CGF.Builder.CreateGEP(CGF.Int8Ty, Address, 9559 llvm::ConstantInt::get(CGF.Int32Ty, Offset)); 9560 } 9561 }; 9562 } // end anonymous namespace 9563 9564 //===----------------------------------------------------------------------===// 9565 // SPARC v9 ABI Implementation. 9566 // Based on the SPARC Compliance Definition version 2.4.1. 9567 // 9568 // Function arguments a mapped to a nominal "parameter array" and promoted to 9569 // registers depending on their type. Each argument occupies 8 or 16 bytes in 9570 // the array, structs larger than 16 bytes are passed indirectly. 9571 // 9572 // One case requires special care: 9573 // 9574 // struct mixed { 9575 // int i; 9576 // float f; 9577 // }; 9578 // 9579 // When a struct mixed is passed by value, it only occupies 8 bytes in the 9580 // parameter array, but the int is passed in an integer register, and the float 9581 // is passed in a floating point register. This is represented as two arguments 9582 // with the LLVM IR inreg attribute: 9583 // 9584 // declare void f(i32 inreg %i, float inreg %f) 9585 // 9586 // The code generator will only allocate 4 bytes from the parameter array for 9587 // the inreg arguments. All other arguments are allocated a multiple of 8 9588 // bytes. 9589 // 9590 namespace { 9591 class SparcV9ABIInfo : public ABIInfo { 9592 public: 9593 SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {} 9594 9595 private: 9596 ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const; 9597 void computeInfo(CGFunctionInfo &FI) const override; 9598 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 9599 QualType Ty) const override; 9600 9601 // Coercion type builder for structs passed in registers. The coercion type 9602 // serves two purposes: 9603 // 9604 // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned' 9605 // in registers. 9606 // 2. Expose aligned floating point elements as first-level elements, so the 9607 // code generator knows to pass them in floating point registers. 9608 // 9609 // We also compute the InReg flag which indicates that the struct contains 9610 // aligned 32-bit floats. 9611 // 9612 struct CoerceBuilder { 9613 llvm::LLVMContext &Context; 9614 const llvm::DataLayout &DL; 9615 SmallVector<llvm::Type*, 8> Elems; 9616 uint64_t Size; 9617 bool InReg; 9618 9619 CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl) 9620 : Context(c), DL(dl), Size(0), InReg(false) {} 9621 9622 // Pad Elems with integers until Size is ToSize. 9623 void pad(uint64_t ToSize) { 9624 assert(ToSize >= Size && "Cannot remove elements"); 9625 if (ToSize == Size) 9626 return; 9627 9628 // Finish the current 64-bit word. 9629 uint64_t Aligned = llvm::alignTo(Size, 64); 9630 if (Aligned > Size && Aligned <= ToSize) { 9631 Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size)); 9632 Size = Aligned; 9633 } 9634 9635 // Add whole 64-bit words. 9636 while (Size + 64 <= ToSize) { 9637 Elems.push_back(llvm::Type::getInt64Ty(Context)); 9638 Size += 64; 9639 } 9640 9641 // Final in-word padding. 9642 if (Size < ToSize) { 9643 Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size)); 9644 Size = ToSize; 9645 } 9646 } 9647 9648 // Add a floating point element at Offset. 9649 void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) { 9650 // Unaligned floats are treated as integers. 9651 if (Offset % Bits) 9652 return; 9653 // The InReg flag is only required if there are any floats < 64 bits. 9654 if (Bits < 64) 9655 InReg = true; 9656 pad(Offset); 9657 Elems.push_back(Ty); 9658 Size = Offset + Bits; 9659 } 9660 9661 // Add a struct type to the coercion type, starting at Offset (in bits). 9662 void addStruct(uint64_t Offset, llvm::StructType *StrTy) { 9663 const llvm::StructLayout *Layout = DL.getStructLayout(StrTy); 9664 for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) { 9665 llvm::Type *ElemTy = StrTy->getElementType(i); 9666 uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i); 9667 switch (ElemTy->getTypeID()) { 9668 case llvm::Type::StructTyID: 9669 addStruct(ElemOffset, cast<llvm::StructType>(ElemTy)); 9670 break; 9671 case llvm::Type::FloatTyID: 9672 addFloat(ElemOffset, ElemTy, 32); 9673 break; 9674 case llvm::Type::DoubleTyID: 9675 addFloat(ElemOffset, ElemTy, 64); 9676 break; 9677 case llvm::Type::FP128TyID: 9678 addFloat(ElemOffset, ElemTy, 128); 9679 break; 9680 case llvm::Type::PointerTyID: 9681 if (ElemOffset % 64 == 0) { 9682 pad(ElemOffset); 9683 Elems.push_back(ElemTy); 9684 Size += 64; 9685 } 9686 break; 9687 default: 9688 break; 9689 } 9690 } 9691 } 9692 9693 // Check if Ty is a usable substitute for the coercion type. 9694 bool isUsableType(llvm::StructType *Ty) const { 9695 return llvm::makeArrayRef(Elems) == Ty->elements(); 9696 } 9697 9698 // Get the coercion type as a literal struct type. 9699 llvm::Type *getType() const { 9700 if (Elems.size() == 1) 9701 return Elems.front(); 9702 else 9703 return llvm::StructType::get(Context, Elems); 9704 } 9705 }; 9706 }; 9707 } // end anonymous namespace 9708 9709 ABIArgInfo 9710 SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const { 9711 if (Ty->isVoidType()) 9712 return ABIArgInfo::getIgnore(); 9713 9714 uint64_t Size = getContext().getTypeSize(Ty); 9715 9716 // Anything too big to fit in registers is passed with an explicit indirect 9717 // pointer / sret pointer. 9718 if (Size > SizeLimit) 9719 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 9720 9721 // Treat an enum type as its underlying type. 9722 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 9723 Ty = EnumTy->getDecl()->getIntegerType(); 9724 9725 // Integer types smaller than a register are extended. 9726 if (Size < 64 && Ty->isIntegerType()) 9727 return ABIArgInfo::getExtend(Ty); 9728 9729 if (const auto *EIT = Ty->getAs<BitIntType>()) 9730 if (EIT->getNumBits() < 64) 9731 return ABIArgInfo::getExtend(Ty); 9732 9733 // Other non-aggregates go in registers. 9734 if (!isAggregateTypeForABI(Ty)) 9735 return ABIArgInfo::getDirect(); 9736 9737 // If a C++ object has either a non-trivial copy constructor or a non-trivial 9738 // destructor, it is passed with an explicit indirect pointer / sret pointer. 9739 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 9740 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 9741 9742 // This is a small aggregate type that should be passed in registers. 9743 // Build a coercion type from the LLVM struct type. 9744 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty)); 9745 if (!StrTy) 9746 return ABIArgInfo::getDirect(); 9747 9748 CoerceBuilder CB(getVMContext(), getDataLayout()); 9749 CB.addStruct(0, StrTy); 9750 CB.pad(llvm::alignTo(CB.DL.getTypeSizeInBits(StrTy), 64)); 9751 9752 // Try to use the original type for coercion. 9753 llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType(); 9754 9755 if (CB.InReg) 9756 return ABIArgInfo::getDirectInReg(CoerceTy); 9757 else 9758 return ABIArgInfo::getDirect(CoerceTy); 9759 } 9760 9761 Address SparcV9ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 9762 QualType Ty) const { 9763 ABIArgInfo AI = classifyType(Ty, 16 * 8); 9764 llvm::Type *ArgTy = CGT.ConvertType(Ty); 9765 if (AI.canHaveCoerceToType() && !AI.getCoerceToType()) 9766 AI.setCoerceToType(ArgTy); 9767 9768 CharUnits SlotSize = CharUnits::fromQuantity(8); 9769 9770 CGBuilderTy &Builder = CGF.Builder; 9771 Address Addr(Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize); 9772 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy); 9773 9774 auto TypeInfo = getContext().getTypeInfoInChars(Ty); 9775 9776 Address ArgAddr = Address::invalid(); 9777 CharUnits Stride; 9778 switch (AI.getKind()) { 9779 case ABIArgInfo::Expand: 9780 case ABIArgInfo::CoerceAndExpand: 9781 case ABIArgInfo::InAlloca: 9782 llvm_unreachable("Unsupported ABI kind for va_arg"); 9783 9784 case ABIArgInfo::Extend: { 9785 Stride = SlotSize; 9786 CharUnits Offset = SlotSize - TypeInfo.Width; 9787 ArgAddr = Builder.CreateConstInBoundsByteGEP(Addr, Offset, "extend"); 9788 break; 9789 } 9790 9791 case ABIArgInfo::Direct: { 9792 auto AllocSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType()); 9793 Stride = CharUnits::fromQuantity(AllocSize).alignTo(SlotSize); 9794 ArgAddr = Addr; 9795 break; 9796 } 9797 9798 case ABIArgInfo::Indirect: 9799 case ABIArgInfo::IndirectAliased: 9800 Stride = SlotSize; 9801 ArgAddr = Builder.CreateElementBitCast(Addr, ArgPtrTy, "indirect"); 9802 ArgAddr = Address(Builder.CreateLoad(ArgAddr, "indirect.arg"), 9803 TypeInfo.Align); 9804 break; 9805 9806 case ABIArgInfo::Ignore: 9807 return Address(llvm::UndefValue::get(ArgPtrTy), TypeInfo.Align); 9808 } 9809 9810 // Update VAList. 9811 Address NextPtr = Builder.CreateConstInBoundsByteGEP(Addr, Stride, "ap.next"); 9812 Builder.CreateStore(NextPtr.getPointer(), VAListAddr); 9813 9814 return Builder.CreateBitCast(ArgAddr, ArgPtrTy, "arg.addr"); 9815 } 9816 9817 void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const { 9818 FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8); 9819 for (auto &I : FI.arguments()) 9820 I.info = classifyType(I.type, 16 * 8); 9821 } 9822 9823 namespace { 9824 class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo { 9825 public: 9826 SparcV9TargetCodeGenInfo(CodeGenTypes &CGT) 9827 : TargetCodeGenInfo(std::make_unique<SparcV9ABIInfo>(CGT)) {} 9828 9829 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 9830 return 14; 9831 } 9832 9833 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 9834 llvm::Value *Address) const override; 9835 9836 llvm::Value *decodeReturnAddress(CodeGen::CodeGenFunction &CGF, 9837 llvm::Value *Address) const override { 9838 return CGF.Builder.CreateGEP(CGF.Int8Ty, Address, 9839 llvm::ConstantInt::get(CGF.Int32Ty, 8)); 9840 } 9841 9842 llvm::Value *encodeReturnAddress(CodeGen::CodeGenFunction &CGF, 9843 llvm::Value *Address) const override { 9844 return CGF.Builder.CreateGEP(CGF.Int8Ty, Address, 9845 llvm::ConstantInt::get(CGF.Int32Ty, -8)); 9846 } 9847 }; 9848 } // end anonymous namespace 9849 9850 bool 9851 SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 9852 llvm::Value *Address) const { 9853 // This is calculated from the LLVM and GCC tables and verified 9854 // against gcc output. AFAIK all ABIs use the same encoding. 9855 9856 CodeGen::CGBuilderTy &Builder = CGF.Builder; 9857 9858 llvm::IntegerType *i8 = CGF.Int8Ty; 9859 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4); 9860 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8); 9861 9862 // 0-31: the 8-byte general-purpose registers 9863 AssignToArrayRange(Builder, Address, Eight8, 0, 31); 9864 9865 // 32-63: f0-31, the 4-byte floating-point registers 9866 AssignToArrayRange(Builder, Address, Four8, 32, 63); 9867 9868 // Y = 64 9869 // PSR = 65 9870 // WIM = 66 9871 // TBR = 67 9872 // PC = 68 9873 // NPC = 69 9874 // FSR = 70 9875 // CSR = 71 9876 AssignToArrayRange(Builder, Address, Eight8, 64, 71); 9877 9878 // 72-87: d0-15, the 8-byte floating-point registers 9879 AssignToArrayRange(Builder, Address, Eight8, 72, 87); 9880 9881 return false; 9882 } 9883 9884 // ARC ABI implementation. 9885 namespace { 9886 9887 class ARCABIInfo : public DefaultABIInfo { 9888 public: 9889 using DefaultABIInfo::DefaultABIInfo; 9890 9891 private: 9892 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 9893 QualType Ty) const override; 9894 9895 void updateState(const ABIArgInfo &Info, QualType Ty, CCState &State) const { 9896 if (!State.FreeRegs) 9897 return; 9898 if (Info.isIndirect() && Info.getInReg()) 9899 State.FreeRegs--; 9900 else if (Info.isDirect() && Info.getInReg()) { 9901 unsigned sz = (getContext().getTypeSize(Ty) + 31) / 32; 9902 if (sz < State.FreeRegs) 9903 State.FreeRegs -= sz; 9904 else 9905 State.FreeRegs = 0; 9906 } 9907 } 9908 9909 void computeInfo(CGFunctionInfo &FI) const override { 9910 CCState State(FI); 9911 // ARC uses 8 registers to pass arguments. 9912 State.FreeRegs = 8; 9913 9914 if (!getCXXABI().classifyReturnType(FI)) 9915 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 9916 updateState(FI.getReturnInfo(), FI.getReturnType(), State); 9917 for (auto &I : FI.arguments()) { 9918 I.info = classifyArgumentType(I.type, State.FreeRegs); 9919 updateState(I.info, I.type, State); 9920 } 9921 } 9922 9923 ABIArgInfo getIndirectByRef(QualType Ty, bool HasFreeRegs) const; 9924 ABIArgInfo getIndirectByValue(QualType Ty) const; 9925 ABIArgInfo classifyArgumentType(QualType Ty, uint8_t FreeRegs) const; 9926 ABIArgInfo classifyReturnType(QualType RetTy) const; 9927 }; 9928 9929 class ARCTargetCodeGenInfo : public TargetCodeGenInfo { 9930 public: 9931 ARCTargetCodeGenInfo(CodeGenTypes &CGT) 9932 : TargetCodeGenInfo(std::make_unique<ARCABIInfo>(CGT)) {} 9933 }; 9934 9935 9936 ABIArgInfo ARCABIInfo::getIndirectByRef(QualType Ty, bool HasFreeRegs) const { 9937 return HasFreeRegs ? getNaturalAlignIndirectInReg(Ty) : 9938 getNaturalAlignIndirect(Ty, false); 9939 } 9940 9941 ABIArgInfo ARCABIInfo::getIndirectByValue(QualType Ty) const { 9942 // Compute the byval alignment. 9943 const unsigned MinABIStackAlignInBytes = 4; 9944 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8; 9945 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true, 9946 TypeAlign > MinABIStackAlignInBytes); 9947 } 9948 9949 Address ARCABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 9950 QualType Ty) const { 9951 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false, 9952 getContext().getTypeInfoInChars(Ty), 9953 CharUnits::fromQuantity(4), true); 9954 } 9955 9956 ABIArgInfo ARCABIInfo::classifyArgumentType(QualType Ty, 9957 uint8_t FreeRegs) const { 9958 // Handle the generic C++ ABI. 9959 const RecordType *RT = Ty->getAs<RecordType>(); 9960 if (RT) { 9961 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()); 9962 if (RAA == CGCXXABI::RAA_Indirect) 9963 return getIndirectByRef(Ty, FreeRegs > 0); 9964 9965 if (RAA == CGCXXABI::RAA_DirectInMemory) 9966 return getIndirectByValue(Ty); 9967 } 9968 9969 // Treat an enum type as its underlying type. 9970 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 9971 Ty = EnumTy->getDecl()->getIntegerType(); 9972 9973 auto SizeInRegs = llvm::alignTo(getContext().getTypeSize(Ty), 32) / 32; 9974 9975 if (isAggregateTypeForABI(Ty)) { 9976 // Structures with flexible arrays are always indirect. 9977 if (RT && RT->getDecl()->hasFlexibleArrayMember()) 9978 return getIndirectByValue(Ty); 9979 9980 // Ignore empty structs/unions. 9981 if (isEmptyRecord(getContext(), Ty, true)) 9982 return ABIArgInfo::getIgnore(); 9983 9984 llvm::LLVMContext &LLVMContext = getVMContext(); 9985 9986 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext); 9987 SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32); 9988 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements); 9989 9990 return FreeRegs >= SizeInRegs ? 9991 ABIArgInfo::getDirectInReg(Result) : 9992 ABIArgInfo::getDirect(Result, 0, nullptr, false); 9993 } 9994 9995 if (const auto *EIT = Ty->getAs<BitIntType>()) 9996 if (EIT->getNumBits() > 64) 9997 return getIndirectByValue(Ty); 9998 9999 return isPromotableIntegerTypeForABI(Ty) 10000 ? (FreeRegs >= SizeInRegs ? ABIArgInfo::getExtendInReg(Ty) 10001 : ABIArgInfo::getExtend(Ty)) 10002 : (FreeRegs >= SizeInRegs ? ABIArgInfo::getDirectInReg() 10003 : ABIArgInfo::getDirect()); 10004 } 10005 10006 ABIArgInfo ARCABIInfo::classifyReturnType(QualType RetTy) const { 10007 if (RetTy->isAnyComplexType()) 10008 return ABIArgInfo::getDirectInReg(); 10009 10010 // Arguments of size > 4 registers are indirect. 10011 auto RetSize = llvm::alignTo(getContext().getTypeSize(RetTy), 32) / 32; 10012 if (RetSize > 4) 10013 return getIndirectByRef(RetTy, /*HasFreeRegs*/ true); 10014 10015 return DefaultABIInfo::classifyReturnType(RetTy); 10016 } 10017 10018 } // End anonymous namespace. 10019 10020 //===----------------------------------------------------------------------===// 10021 // XCore ABI Implementation 10022 //===----------------------------------------------------------------------===// 10023 10024 namespace { 10025 10026 /// A SmallStringEnc instance is used to build up the TypeString by passing 10027 /// it by reference between functions that append to it. 10028 typedef llvm::SmallString<128> SmallStringEnc; 10029 10030 /// TypeStringCache caches the meta encodings of Types. 10031 /// 10032 /// The reason for caching TypeStrings is two fold: 10033 /// 1. To cache a type's encoding for later uses; 10034 /// 2. As a means to break recursive member type inclusion. 10035 /// 10036 /// A cache Entry can have a Status of: 10037 /// NonRecursive: The type encoding is not recursive; 10038 /// Recursive: The type encoding is recursive; 10039 /// Incomplete: An incomplete TypeString; 10040 /// IncompleteUsed: An incomplete TypeString that has been used in a 10041 /// Recursive type encoding. 10042 /// 10043 /// A NonRecursive entry will have all of its sub-members expanded as fully 10044 /// as possible. Whilst it may contain types which are recursive, the type 10045 /// itself is not recursive and thus its encoding may be safely used whenever 10046 /// the type is encountered. 10047 /// 10048 /// A Recursive entry will have all of its sub-members expanded as fully as 10049 /// possible. The type itself is recursive and it may contain other types which 10050 /// are recursive. The Recursive encoding must not be used during the expansion 10051 /// of a recursive type's recursive branch. For simplicity the code uses 10052 /// IncompleteCount to reject all usage of Recursive encodings for member types. 10053 /// 10054 /// An Incomplete entry is always a RecordType and only encodes its 10055 /// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and 10056 /// are placed into the cache during type expansion as a means to identify and 10057 /// handle recursive inclusion of types as sub-members. If there is recursion 10058 /// the entry becomes IncompleteUsed. 10059 /// 10060 /// During the expansion of a RecordType's members: 10061 /// 10062 /// If the cache contains a NonRecursive encoding for the member type, the 10063 /// cached encoding is used; 10064 /// 10065 /// If the cache contains a Recursive encoding for the member type, the 10066 /// cached encoding is 'Swapped' out, as it may be incorrect, and... 10067 /// 10068 /// If the member is a RecordType, an Incomplete encoding is placed into the 10069 /// cache to break potential recursive inclusion of itself as a sub-member; 10070 /// 10071 /// Once a member RecordType has been expanded, its temporary incomplete 10072 /// entry is removed from the cache. If a Recursive encoding was swapped out 10073 /// it is swapped back in; 10074 /// 10075 /// If an incomplete entry is used to expand a sub-member, the incomplete 10076 /// entry is marked as IncompleteUsed. The cache keeps count of how many 10077 /// IncompleteUsed entries it currently contains in IncompleteUsedCount; 10078 /// 10079 /// If a member's encoding is found to be a NonRecursive or Recursive viz: 10080 /// IncompleteUsedCount==0, the member's encoding is added to the cache. 10081 /// Else the member is part of a recursive type and thus the recursion has 10082 /// been exited too soon for the encoding to be correct for the member. 10083 /// 10084 class TypeStringCache { 10085 enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed}; 10086 struct Entry { 10087 std::string Str; // The encoded TypeString for the type. 10088 enum Status State; // Information about the encoding in 'Str'. 10089 std::string Swapped; // A temporary place holder for a Recursive encoding 10090 // during the expansion of RecordType's members. 10091 }; 10092 std::map<const IdentifierInfo *, struct Entry> Map; 10093 unsigned IncompleteCount; // Number of Incomplete entries in the Map. 10094 unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map. 10095 public: 10096 TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {} 10097 void addIncomplete(const IdentifierInfo *ID, std::string StubEnc); 10098 bool removeIncomplete(const IdentifierInfo *ID); 10099 void addIfComplete(const IdentifierInfo *ID, StringRef Str, 10100 bool IsRecursive); 10101 StringRef lookupStr(const IdentifierInfo *ID); 10102 }; 10103 10104 /// TypeString encodings for enum & union fields must be order. 10105 /// FieldEncoding is a helper for this ordering process. 10106 class FieldEncoding { 10107 bool HasName; 10108 std::string Enc; 10109 public: 10110 FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {} 10111 StringRef str() { return Enc; } 10112 bool operator<(const FieldEncoding &rhs) const { 10113 if (HasName != rhs.HasName) return HasName; 10114 return Enc < rhs.Enc; 10115 } 10116 }; 10117 10118 class XCoreABIInfo : public DefaultABIInfo { 10119 public: 10120 XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {} 10121 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 10122 QualType Ty) const override; 10123 }; 10124 10125 class XCoreTargetCodeGenInfo : public TargetCodeGenInfo { 10126 mutable TypeStringCache TSC; 10127 void emitTargetMD(const Decl *D, llvm::GlobalValue *GV, 10128 const CodeGen::CodeGenModule &M) const; 10129 10130 public: 10131 XCoreTargetCodeGenInfo(CodeGenTypes &CGT) 10132 : TargetCodeGenInfo(std::make_unique<XCoreABIInfo>(CGT)) {} 10133 void emitTargetMetadata(CodeGen::CodeGenModule &CGM, 10134 const llvm::MapVector<GlobalDecl, StringRef> 10135 &MangledDeclNames) const override; 10136 }; 10137 10138 } // End anonymous namespace. 10139 10140 // TODO: this implementation is likely now redundant with the default 10141 // EmitVAArg. 10142 Address XCoreABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 10143 QualType Ty) const { 10144 CGBuilderTy &Builder = CGF.Builder; 10145 10146 // Get the VAList. 10147 CharUnits SlotSize = CharUnits::fromQuantity(4); 10148 Address AP(Builder.CreateLoad(VAListAddr), SlotSize); 10149 10150 // Handle the argument. 10151 ABIArgInfo AI = classifyArgumentType(Ty); 10152 CharUnits TypeAlign = getContext().getTypeAlignInChars(Ty); 10153 llvm::Type *ArgTy = CGT.ConvertType(Ty); 10154 if (AI.canHaveCoerceToType() && !AI.getCoerceToType()) 10155 AI.setCoerceToType(ArgTy); 10156 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy); 10157 10158 Address Val = Address::invalid(); 10159 CharUnits ArgSize = CharUnits::Zero(); 10160 switch (AI.getKind()) { 10161 case ABIArgInfo::Expand: 10162 case ABIArgInfo::CoerceAndExpand: 10163 case ABIArgInfo::InAlloca: 10164 llvm_unreachable("Unsupported ABI kind for va_arg"); 10165 case ABIArgInfo::Ignore: 10166 Val = Address(llvm::UndefValue::get(ArgPtrTy), TypeAlign); 10167 ArgSize = CharUnits::Zero(); 10168 break; 10169 case ABIArgInfo::Extend: 10170 case ABIArgInfo::Direct: 10171 Val = Builder.CreateBitCast(AP, ArgPtrTy); 10172 ArgSize = CharUnits::fromQuantity( 10173 getDataLayout().getTypeAllocSize(AI.getCoerceToType())); 10174 ArgSize = ArgSize.alignTo(SlotSize); 10175 break; 10176 case ABIArgInfo::Indirect: 10177 case ABIArgInfo::IndirectAliased: 10178 Val = Builder.CreateElementBitCast(AP, ArgPtrTy); 10179 Val = Address(Builder.CreateLoad(Val), TypeAlign); 10180 ArgSize = SlotSize; 10181 break; 10182 } 10183 10184 // Increment the VAList. 10185 if (!ArgSize.isZero()) { 10186 Address APN = Builder.CreateConstInBoundsByteGEP(AP, ArgSize); 10187 Builder.CreateStore(APN.getPointer(), VAListAddr); 10188 } 10189 10190 return Val; 10191 } 10192 10193 /// During the expansion of a RecordType, an incomplete TypeString is placed 10194 /// into the cache as a means to identify and break recursion. 10195 /// If there is a Recursive encoding in the cache, it is swapped out and will 10196 /// be reinserted by removeIncomplete(). 10197 /// All other types of encoding should have been used rather than arriving here. 10198 void TypeStringCache::addIncomplete(const IdentifierInfo *ID, 10199 std::string StubEnc) { 10200 if (!ID) 10201 return; 10202 Entry &E = Map[ID]; 10203 assert( (E.Str.empty() || E.State == Recursive) && 10204 "Incorrectly use of addIncomplete"); 10205 assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()"); 10206 E.Swapped.swap(E.Str); // swap out the Recursive 10207 E.Str.swap(StubEnc); 10208 E.State = Incomplete; 10209 ++IncompleteCount; 10210 } 10211 10212 /// Once the RecordType has been expanded, the temporary incomplete TypeString 10213 /// must be removed from the cache. 10214 /// If a Recursive was swapped out by addIncomplete(), it will be replaced. 10215 /// Returns true if the RecordType was defined recursively. 10216 bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) { 10217 if (!ID) 10218 return false; 10219 auto I = Map.find(ID); 10220 assert(I != Map.end() && "Entry not present"); 10221 Entry &E = I->second; 10222 assert( (E.State == Incomplete || 10223 E.State == IncompleteUsed) && 10224 "Entry must be an incomplete type"); 10225 bool IsRecursive = false; 10226 if (E.State == IncompleteUsed) { 10227 // We made use of our Incomplete encoding, thus we are recursive. 10228 IsRecursive = true; 10229 --IncompleteUsedCount; 10230 } 10231 if (E.Swapped.empty()) 10232 Map.erase(I); 10233 else { 10234 // Swap the Recursive back. 10235 E.Swapped.swap(E.Str); 10236 E.Swapped.clear(); 10237 E.State = Recursive; 10238 } 10239 --IncompleteCount; 10240 return IsRecursive; 10241 } 10242 10243 /// Add the encoded TypeString to the cache only if it is NonRecursive or 10244 /// Recursive (viz: all sub-members were expanded as fully as possible). 10245 void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str, 10246 bool IsRecursive) { 10247 if (!ID || IncompleteUsedCount) 10248 return; // No key or it is is an incomplete sub-type so don't add. 10249 Entry &E = Map[ID]; 10250 if (IsRecursive && !E.Str.empty()) { 10251 assert(E.State==Recursive && E.Str.size() == Str.size() && 10252 "This is not the same Recursive entry"); 10253 // The parent container was not recursive after all, so we could have used 10254 // this Recursive sub-member entry after all, but we assumed the worse when 10255 // we started viz: IncompleteCount!=0. 10256 return; 10257 } 10258 assert(E.Str.empty() && "Entry already present"); 10259 E.Str = Str.str(); 10260 E.State = IsRecursive? Recursive : NonRecursive; 10261 } 10262 10263 /// Return a cached TypeString encoding for the ID. If there isn't one, or we 10264 /// are recursively expanding a type (IncompleteCount != 0) and the cached 10265 /// encoding is Recursive, return an empty StringRef. 10266 StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) { 10267 if (!ID) 10268 return StringRef(); // We have no key. 10269 auto I = Map.find(ID); 10270 if (I == Map.end()) 10271 return StringRef(); // We have no encoding. 10272 Entry &E = I->second; 10273 if (E.State == Recursive && IncompleteCount) 10274 return StringRef(); // We don't use Recursive encodings for member types. 10275 10276 if (E.State == Incomplete) { 10277 // The incomplete type is being used to break out of recursion. 10278 E.State = IncompleteUsed; 10279 ++IncompleteUsedCount; 10280 } 10281 return E.Str; 10282 } 10283 10284 /// The XCore ABI includes a type information section that communicates symbol 10285 /// type information to the linker. The linker uses this information to verify 10286 /// safety/correctness of things such as array bound and pointers et al. 10287 /// The ABI only requires C (and XC) language modules to emit TypeStrings. 10288 /// This type information (TypeString) is emitted into meta data for all global 10289 /// symbols: definitions, declarations, functions & variables. 10290 /// 10291 /// The TypeString carries type, qualifier, name, size & value details. 10292 /// Please see 'Tools Development Guide' section 2.16.2 for format details: 10293 /// https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf 10294 /// The output is tested by test/CodeGen/xcore-stringtype.c. 10295 /// 10296 static bool getTypeString(SmallStringEnc &Enc, const Decl *D, 10297 const CodeGen::CodeGenModule &CGM, 10298 TypeStringCache &TSC); 10299 10300 /// XCore uses emitTargetMD to emit TypeString metadata for global symbols. 10301 void XCoreTargetCodeGenInfo::emitTargetMD( 10302 const Decl *D, llvm::GlobalValue *GV, 10303 const CodeGen::CodeGenModule &CGM) const { 10304 SmallStringEnc Enc; 10305 if (getTypeString(Enc, D, CGM, TSC)) { 10306 llvm::LLVMContext &Ctx = CGM.getModule().getContext(); 10307 llvm::Metadata *MDVals[] = {llvm::ConstantAsMetadata::get(GV), 10308 llvm::MDString::get(Ctx, Enc.str())}; 10309 llvm::NamedMDNode *MD = 10310 CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings"); 10311 MD->addOperand(llvm::MDNode::get(Ctx, MDVals)); 10312 } 10313 } 10314 10315 void XCoreTargetCodeGenInfo::emitTargetMetadata( 10316 CodeGen::CodeGenModule &CGM, 10317 const llvm::MapVector<GlobalDecl, StringRef> &MangledDeclNames) const { 10318 // Warning, new MangledDeclNames may be appended within this loop. 10319 // We rely on MapVector insertions adding new elements to the end 10320 // of the container. 10321 for (unsigned I = 0; I != MangledDeclNames.size(); ++I) { 10322 auto Val = *(MangledDeclNames.begin() + I); 10323 llvm::GlobalValue *GV = CGM.GetGlobalValue(Val.second); 10324 if (GV) { 10325 const Decl *D = Val.first.getDecl()->getMostRecentDecl(); 10326 emitTargetMD(D, GV, CGM); 10327 } 10328 } 10329 } 10330 10331 //===----------------------------------------------------------------------===// 10332 // Base ABI and target codegen info implementation common between SPIR and 10333 // SPIR-V. 10334 //===----------------------------------------------------------------------===// 10335 10336 namespace { 10337 class CommonSPIRABIInfo : public DefaultABIInfo { 10338 public: 10339 CommonSPIRABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) { setCCs(); } 10340 10341 private: 10342 void setCCs(); 10343 }; 10344 10345 class SPIRVABIInfo : public CommonSPIRABIInfo { 10346 public: 10347 SPIRVABIInfo(CodeGenTypes &CGT) : CommonSPIRABIInfo(CGT) {} 10348 void computeInfo(CGFunctionInfo &FI) const override; 10349 10350 private: 10351 ABIArgInfo classifyKernelArgumentType(QualType Ty) const; 10352 }; 10353 } // end anonymous namespace 10354 namespace { 10355 class CommonSPIRTargetCodeGenInfo : public TargetCodeGenInfo { 10356 public: 10357 CommonSPIRTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT) 10358 : TargetCodeGenInfo(std::make_unique<CommonSPIRABIInfo>(CGT)) {} 10359 CommonSPIRTargetCodeGenInfo(std::unique_ptr<ABIInfo> ABIInfo) 10360 : TargetCodeGenInfo(std::move(ABIInfo)) {} 10361 10362 LangAS getASTAllocaAddressSpace() const override { 10363 return getLangASFromTargetAS( 10364 getABIInfo().getDataLayout().getAllocaAddrSpace()); 10365 } 10366 10367 unsigned getOpenCLKernelCallingConv() const override; 10368 }; 10369 class SPIRVTargetCodeGenInfo : public CommonSPIRTargetCodeGenInfo { 10370 public: 10371 SPIRVTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT) 10372 : CommonSPIRTargetCodeGenInfo(std::make_unique<SPIRVABIInfo>(CGT)) {} 10373 void setCUDAKernelCallingConvention(const FunctionType *&FT) const override; 10374 }; 10375 } // End anonymous namespace. 10376 10377 void CommonSPIRABIInfo::setCCs() { 10378 assert(getRuntimeCC() == llvm::CallingConv::C); 10379 RuntimeCC = llvm::CallingConv::SPIR_FUNC; 10380 } 10381 10382 ABIArgInfo SPIRVABIInfo::classifyKernelArgumentType(QualType Ty) const { 10383 if (getContext().getLangOpts().HIP) { 10384 // Coerce pointer arguments with default address space to CrossWorkGroup 10385 // pointers for HIPSPV. When the language mode is HIP, the SPIRTargetInfo 10386 // maps cuda_device to SPIR-V's CrossWorkGroup address space. 10387 llvm::Type *LTy = CGT.ConvertType(Ty); 10388 auto DefaultAS = getContext().getTargetAddressSpace(LangAS::Default); 10389 auto GlobalAS = getContext().getTargetAddressSpace(LangAS::cuda_device); 10390 auto *PtrTy = llvm::dyn_cast<llvm::PointerType>(LTy); 10391 if (PtrTy && PtrTy->getAddressSpace() == DefaultAS) { 10392 LTy = llvm::PointerType::getWithSamePointeeType(PtrTy, GlobalAS); 10393 return ABIArgInfo::getDirect(LTy, 0, nullptr, false); 10394 } 10395 } 10396 return classifyArgumentType(Ty); 10397 } 10398 10399 void SPIRVABIInfo::computeInfo(CGFunctionInfo &FI) const { 10400 // The logic is same as in DefaultABIInfo with an exception on the kernel 10401 // arguments handling. 10402 llvm::CallingConv::ID CC = FI.getCallingConvention(); 10403 10404 if (!getCXXABI().classifyReturnType(FI)) 10405 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 10406 10407 for (auto &I : FI.arguments()) { 10408 if (CC == llvm::CallingConv::SPIR_KERNEL) { 10409 I.info = classifyKernelArgumentType(I.type); 10410 } else { 10411 I.info = classifyArgumentType(I.type); 10412 } 10413 } 10414 } 10415 10416 namespace clang { 10417 namespace CodeGen { 10418 void computeSPIRKernelABIInfo(CodeGenModule &CGM, CGFunctionInfo &FI) { 10419 if (CGM.getTarget().getTriple().isSPIRV()) 10420 SPIRVABIInfo(CGM.getTypes()).computeInfo(FI); 10421 else 10422 CommonSPIRABIInfo(CGM.getTypes()).computeInfo(FI); 10423 } 10424 } 10425 } 10426 10427 unsigned CommonSPIRTargetCodeGenInfo::getOpenCLKernelCallingConv() const { 10428 return llvm::CallingConv::SPIR_KERNEL; 10429 } 10430 10431 void SPIRVTargetCodeGenInfo::setCUDAKernelCallingConvention( 10432 const FunctionType *&FT) const { 10433 // Convert HIP kernels to SPIR-V kernels. 10434 if (getABIInfo().getContext().getLangOpts().HIP) { 10435 FT = getABIInfo().getContext().adjustFunctionType( 10436 FT, FT->getExtInfo().withCallingConv(CC_OpenCLKernel)); 10437 return; 10438 } 10439 } 10440 10441 static bool appendType(SmallStringEnc &Enc, QualType QType, 10442 const CodeGen::CodeGenModule &CGM, 10443 TypeStringCache &TSC); 10444 10445 /// Helper function for appendRecordType(). 10446 /// Builds a SmallVector containing the encoded field types in declaration 10447 /// order. 10448 static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE, 10449 const RecordDecl *RD, 10450 const CodeGen::CodeGenModule &CGM, 10451 TypeStringCache &TSC) { 10452 for (const auto *Field : RD->fields()) { 10453 SmallStringEnc Enc; 10454 Enc += "m("; 10455 Enc += Field->getName(); 10456 Enc += "){"; 10457 if (Field->isBitField()) { 10458 Enc += "b("; 10459 llvm::raw_svector_ostream OS(Enc); 10460 OS << Field->getBitWidthValue(CGM.getContext()); 10461 Enc += ':'; 10462 } 10463 if (!appendType(Enc, Field->getType(), CGM, TSC)) 10464 return false; 10465 if (Field->isBitField()) 10466 Enc += ')'; 10467 Enc += '}'; 10468 FE.emplace_back(!Field->getName().empty(), Enc); 10469 } 10470 return true; 10471 } 10472 10473 /// Appends structure and union types to Enc and adds encoding to cache. 10474 /// Recursively calls appendType (via extractFieldType) for each field. 10475 /// Union types have their fields ordered according to the ABI. 10476 static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT, 10477 const CodeGen::CodeGenModule &CGM, 10478 TypeStringCache &TSC, const IdentifierInfo *ID) { 10479 // Append the cached TypeString if we have one. 10480 StringRef TypeString = TSC.lookupStr(ID); 10481 if (!TypeString.empty()) { 10482 Enc += TypeString; 10483 return true; 10484 } 10485 10486 // Start to emit an incomplete TypeString. 10487 size_t Start = Enc.size(); 10488 Enc += (RT->isUnionType()? 'u' : 's'); 10489 Enc += '('; 10490 if (ID) 10491 Enc += ID->getName(); 10492 Enc += "){"; 10493 10494 // We collect all encoded fields and order as necessary. 10495 bool IsRecursive = false; 10496 const RecordDecl *RD = RT->getDecl()->getDefinition(); 10497 if (RD && !RD->field_empty()) { 10498 // An incomplete TypeString stub is placed in the cache for this RecordType 10499 // so that recursive calls to this RecordType will use it whilst building a 10500 // complete TypeString for this RecordType. 10501 SmallVector<FieldEncoding, 16> FE; 10502 std::string StubEnc(Enc.substr(Start).str()); 10503 StubEnc += '}'; // StubEnc now holds a valid incomplete TypeString. 10504 TSC.addIncomplete(ID, std::move(StubEnc)); 10505 if (!extractFieldType(FE, RD, CGM, TSC)) { 10506 (void) TSC.removeIncomplete(ID); 10507 return false; 10508 } 10509 IsRecursive = TSC.removeIncomplete(ID); 10510 // The ABI requires unions to be sorted but not structures. 10511 // See FieldEncoding::operator< for sort algorithm. 10512 if (RT->isUnionType()) 10513 llvm::sort(FE); 10514 // We can now complete the TypeString. 10515 unsigned E = FE.size(); 10516 for (unsigned I = 0; I != E; ++I) { 10517 if (I) 10518 Enc += ','; 10519 Enc += FE[I].str(); 10520 } 10521 } 10522 Enc += '}'; 10523 TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive); 10524 return true; 10525 } 10526 10527 /// Appends enum types to Enc and adds the encoding to the cache. 10528 static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET, 10529 TypeStringCache &TSC, 10530 const IdentifierInfo *ID) { 10531 // Append the cached TypeString if we have one. 10532 StringRef TypeString = TSC.lookupStr(ID); 10533 if (!TypeString.empty()) { 10534 Enc += TypeString; 10535 return true; 10536 } 10537 10538 size_t Start = Enc.size(); 10539 Enc += "e("; 10540 if (ID) 10541 Enc += ID->getName(); 10542 Enc += "){"; 10543 10544 // We collect all encoded enumerations and order them alphanumerically. 10545 if (const EnumDecl *ED = ET->getDecl()->getDefinition()) { 10546 SmallVector<FieldEncoding, 16> FE; 10547 for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E; 10548 ++I) { 10549 SmallStringEnc EnumEnc; 10550 EnumEnc += "m("; 10551 EnumEnc += I->getName(); 10552 EnumEnc += "){"; 10553 I->getInitVal().toString(EnumEnc); 10554 EnumEnc += '}'; 10555 FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc)); 10556 } 10557 llvm::sort(FE); 10558 unsigned E = FE.size(); 10559 for (unsigned I = 0; I != E; ++I) { 10560 if (I) 10561 Enc += ','; 10562 Enc += FE[I].str(); 10563 } 10564 } 10565 Enc += '}'; 10566 TSC.addIfComplete(ID, Enc.substr(Start), false); 10567 return true; 10568 } 10569 10570 /// Appends type's qualifier to Enc. 10571 /// This is done prior to appending the type's encoding. 10572 static void appendQualifier(SmallStringEnc &Enc, QualType QT) { 10573 // Qualifiers are emitted in alphabetical order. 10574 static const char *const Table[]={"","c:","r:","cr:","v:","cv:","rv:","crv:"}; 10575 int Lookup = 0; 10576 if (QT.isConstQualified()) 10577 Lookup += 1<<0; 10578 if (QT.isRestrictQualified()) 10579 Lookup += 1<<1; 10580 if (QT.isVolatileQualified()) 10581 Lookup += 1<<2; 10582 Enc += Table[Lookup]; 10583 } 10584 10585 /// Appends built-in types to Enc. 10586 static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) { 10587 const char *EncType; 10588 switch (BT->getKind()) { 10589 case BuiltinType::Void: 10590 EncType = "0"; 10591 break; 10592 case BuiltinType::Bool: 10593 EncType = "b"; 10594 break; 10595 case BuiltinType::Char_U: 10596 EncType = "uc"; 10597 break; 10598 case BuiltinType::UChar: 10599 EncType = "uc"; 10600 break; 10601 case BuiltinType::SChar: 10602 EncType = "sc"; 10603 break; 10604 case BuiltinType::UShort: 10605 EncType = "us"; 10606 break; 10607 case BuiltinType::Short: 10608 EncType = "ss"; 10609 break; 10610 case BuiltinType::UInt: 10611 EncType = "ui"; 10612 break; 10613 case BuiltinType::Int: 10614 EncType = "si"; 10615 break; 10616 case BuiltinType::ULong: 10617 EncType = "ul"; 10618 break; 10619 case BuiltinType::Long: 10620 EncType = "sl"; 10621 break; 10622 case BuiltinType::ULongLong: 10623 EncType = "ull"; 10624 break; 10625 case BuiltinType::LongLong: 10626 EncType = "sll"; 10627 break; 10628 case BuiltinType::Float: 10629 EncType = "ft"; 10630 break; 10631 case BuiltinType::Double: 10632 EncType = "d"; 10633 break; 10634 case BuiltinType::LongDouble: 10635 EncType = "ld"; 10636 break; 10637 default: 10638 return false; 10639 } 10640 Enc += EncType; 10641 return true; 10642 } 10643 10644 /// Appends a pointer encoding to Enc before calling appendType for the pointee. 10645 static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT, 10646 const CodeGen::CodeGenModule &CGM, 10647 TypeStringCache &TSC) { 10648 Enc += "p("; 10649 if (!appendType(Enc, PT->getPointeeType(), CGM, TSC)) 10650 return false; 10651 Enc += ')'; 10652 return true; 10653 } 10654 10655 /// Appends array encoding to Enc before calling appendType for the element. 10656 static bool appendArrayType(SmallStringEnc &Enc, QualType QT, 10657 const ArrayType *AT, 10658 const CodeGen::CodeGenModule &CGM, 10659 TypeStringCache &TSC, StringRef NoSizeEnc) { 10660 if (AT->getSizeModifier() != ArrayType::Normal) 10661 return false; 10662 Enc += "a("; 10663 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) 10664 CAT->getSize().toStringUnsigned(Enc); 10665 else 10666 Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "". 10667 Enc += ':'; 10668 // The Qualifiers should be attached to the type rather than the array. 10669 appendQualifier(Enc, QT); 10670 if (!appendType(Enc, AT->getElementType(), CGM, TSC)) 10671 return false; 10672 Enc += ')'; 10673 return true; 10674 } 10675 10676 /// Appends a function encoding to Enc, calling appendType for the return type 10677 /// and the arguments. 10678 static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT, 10679 const CodeGen::CodeGenModule &CGM, 10680 TypeStringCache &TSC) { 10681 Enc += "f{"; 10682 if (!appendType(Enc, FT->getReturnType(), CGM, TSC)) 10683 return false; 10684 Enc += "}("; 10685 if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) { 10686 // N.B. we are only interested in the adjusted param types. 10687 auto I = FPT->param_type_begin(); 10688 auto E = FPT->param_type_end(); 10689 if (I != E) { 10690 do { 10691 if (!appendType(Enc, *I, CGM, TSC)) 10692 return false; 10693 ++I; 10694 if (I != E) 10695 Enc += ','; 10696 } while (I != E); 10697 if (FPT->isVariadic()) 10698 Enc += ",va"; 10699 } else { 10700 if (FPT->isVariadic()) 10701 Enc += "va"; 10702 else 10703 Enc += '0'; 10704 } 10705 } 10706 Enc += ')'; 10707 return true; 10708 } 10709 10710 /// Handles the type's qualifier before dispatching a call to handle specific 10711 /// type encodings. 10712 static bool appendType(SmallStringEnc &Enc, QualType QType, 10713 const CodeGen::CodeGenModule &CGM, 10714 TypeStringCache &TSC) { 10715 10716 QualType QT = QType.getCanonicalType(); 10717 10718 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) 10719 // The Qualifiers should be attached to the type rather than the array. 10720 // Thus we don't call appendQualifier() here. 10721 return appendArrayType(Enc, QT, AT, CGM, TSC, ""); 10722 10723 appendQualifier(Enc, QT); 10724 10725 if (const BuiltinType *BT = QT->getAs<BuiltinType>()) 10726 return appendBuiltinType(Enc, BT); 10727 10728 if (const PointerType *PT = QT->getAs<PointerType>()) 10729 return appendPointerType(Enc, PT, CGM, TSC); 10730 10731 if (const EnumType *ET = QT->getAs<EnumType>()) 10732 return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier()); 10733 10734 if (const RecordType *RT = QT->getAsStructureType()) 10735 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier()); 10736 10737 if (const RecordType *RT = QT->getAsUnionType()) 10738 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier()); 10739 10740 if (const FunctionType *FT = QT->getAs<FunctionType>()) 10741 return appendFunctionType(Enc, FT, CGM, TSC); 10742 10743 return false; 10744 } 10745 10746 static bool getTypeString(SmallStringEnc &Enc, const Decl *D, 10747 const CodeGen::CodeGenModule &CGM, 10748 TypeStringCache &TSC) { 10749 if (!D) 10750 return false; 10751 10752 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 10753 if (FD->getLanguageLinkage() != CLanguageLinkage) 10754 return false; 10755 return appendType(Enc, FD->getType(), CGM, TSC); 10756 } 10757 10758 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 10759 if (VD->getLanguageLinkage() != CLanguageLinkage) 10760 return false; 10761 QualType QT = VD->getType().getCanonicalType(); 10762 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) { 10763 // Global ArrayTypes are given a size of '*' if the size is unknown. 10764 // The Qualifiers should be attached to the type rather than the array. 10765 // Thus we don't call appendQualifier() here. 10766 return appendArrayType(Enc, QT, AT, CGM, TSC, "*"); 10767 } 10768 return appendType(Enc, QT, CGM, TSC); 10769 } 10770 return false; 10771 } 10772 10773 //===----------------------------------------------------------------------===// 10774 // RISCV ABI Implementation 10775 //===----------------------------------------------------------------------===// 10776 10777 namespace { 10778 class RISCVABIInfo : public DefaultABIInfo { 10779 private: 10780 // Size of the integer ('x') registers in bits. 10781 unsigned XLen; 10782 // Size of the floating point ('f') registers in bits. Note that the target 10783 // ISA might have a wider FLen than the selected ABI (e.g. an RV32IF target 10784 // with soft float ABI has FLen==0). 10785 unsigned FLen; 10786 static const int NumArgGPRs = 8; 10787 static const int NumArgFPRs = 8; 10788 bool detectFPCCEligibleStructHelper(QualType Ty, CharUnits CurOff, 10789 llvm::Type *&Field1Ty, 10790 CharUnits &Field1Off, 10791 llvm::Type *&Field2Ty, 10792 CharUnits &Field2Off) const; 10793 10794 public: 10795 RISCVABIInfo(CodeGen::CodeGenTypes &CGT, unsigned XLen, unsigned FLen) 10796 : DefaultABIInfo(CGT), XLen(XLen), FLen(FLen) {} 10797 10798 // DefaultABIInfo's classifyReturnType and classifyArgumentType are 10799 // non-virtual, but computeInfo is virtual, so we overload it. 10800 void computeInfo(CGFunctionInfo &FI) const override; 10801 10802 ABIArgInfo classifyArgumentType(QualType Ty, bool IsFixed, int &ArgGPRsLeft, 10803 int &ArgFPRsLeft) const; 10804 ABIArgInfo classifyReturnType(QualType RetTy) const; 10805 10806 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 10807 QualType Ty) const override; 10808 10809 ABIArgInfo extendType(QualType Ty) const; 10810 10811 bool detectFPCCEligibleStruct(QualType Ty, llvm::Type *&Field1Ty, 10812 CharUnits &Field1Off, llvm::Type *&Field2Ty, 10813 CharUnits &Field2Off, int &NeededArgGPRs, 10814 int &NeededArgFPRs) const; 10815 ABIArgInfo coerceAndExpandFPCCEligibleStruct(llvm::Type *Field1Ty, 10816 CharUnits Field1Off, 10817 llvm::Type *Field2Ty, 10818 CharUnits Field2Off) const; 10819 }; 10820 } // end anonymous namespace 10821 10822 void RISCVABIInfo::computeInfo(CGFunctionInfo &FI) const { 10823 QualType RetTy = FI.getReturnType(); 10824 if (!getCXXABI().classifyReturnType(FI)) 10825 FI.getReturnInfo() = classifyReturnType(RetTy); 10826 10827 // IsRetIndirect is true if classifyArgumentType indicated the value should 10828 // be passed indirect, or if the type size is a scalar greater than 2*XLen 10829 // and not a complex type with elements <= FLen. e.g. fp128 is passed direct 10830 // in LLVM IR, relying on the backend lowering code to rewrite the argument 10831 // list and pass indirectly on RV32. 10832 bool IsRetIndirect = FI.getReturnInfo().getKind() == ABIArgInfo::Indirect; 10833 if (!IsRetIndirect && RetTy->isScalarType() && 10834 getContext().getTypeSize(RetTy) > (2 * XLen)) { 10835 if (RetTy->isComplexType() && FLen) { 10836 QualType EltTy = RetTy->castAs<ComplexType>()->getElementType(); 10837 IsRetIndirect = getContext().getTypeSize(EltTy) > FLen; 10838 } else { 10839 // This is a normal scalar > 2*XLen, such as fp128 on RV32. 10840 IsRetIndirect = true; 10841 } 10842 } 10843 10844 // We must track the number of GPRs used in order to conform to the RISC-V 10845 // ABI, as integer scalars passed in registers should have signext/zeroext 10846 // when promoted, but are anyext if passed on the stack. As GPR usage is 10847 // different for variadic arguments, we must also track whether we are 10848 // examining a vararg or not. 10849 int ArgGPRsLeft = IsRetIndirect ? NumArgGPRs - 1 : NumArgGPRs; 10850 int ArgFPRsLeft = FLen ? NumArgFPRs : 0; 10851 int NumFixedArgs = FI.getNumRequiredArgs(); 10852 10853 int ArgNum = 0; 10854 for (auto &ArgInfo : FI.arguments()) { 10855 bool IsFixed = ArgNum < NumFixedArgs; 10856 ArgInfo.info = 10857 classifyArgumentType(ArgInfo.type, IsFixed, ArgGPRsLeft, ArgFPRsLeft); 10858 ArgNum++; 10859 } 10860 } 10861 10862 // Returns true if the struct is a potential candidate for the floating point 10863 // calling convention. If this function returns true, the caller is 10864 // responsible for checking that if there is only a single field then that 10865 // field is a float. 10866 bool RISCVABIInfo::detectFPCCEligibleStructHelper(QualType Ty, CharUnits CurOff, 10867 llvm::Type *&Field1Ty, 10868 CharUnits &Field1Off, 10869 llvm::Type *&Field2Ty, 10870 CharUnits &Field2Off) const { 10871 bool IsInt = Ty->isIntegralOrEnumerationType(); 10872 bool IsFloat = Ty->isRealFloatingType(); 10873 10874 if (IsInt || IsFloat) { 10875 uint64_t Size = getContext().getTypeSize(Ty); 10876 if (IsInt && Size > XLen) 10877 return false; 10878 // Can't be eligible if larger than the FP registers. Half precision isn't 10879 // currently supported on RISC-V and the ABI hasn't been confirmed, so 10880 // default to the integer ABI in that case. 10881 if (IsFloat && (Size > FLen || Size < 32)) 10882 return false; 10883 // Can't be eligible if an integer type was already found (int+int pairs 10884 // are not eligible). 10885 if (IsInt && Field1Ty && Field1Ty->isIntegerTy()) 10886 return false; 10887 if (!Field1Ty) { 10888 Field1Ty = CGT.ConvertType(Ty); 10889 Field1Off = CurOff; 10890 return true; 10891 } 10892 if (!Field2Ty) { 10893 Field2Ty = CGT.ConvertType(Ty); 10894 Field2Off = CurOff; 10895 return true; 10896 } 10897 return false; 10898 } 10899 10900 if (auto CTy = Ty->getAs<ComplexType>()) { 10901 if (Field1Ty) 10902 return false; 10903 QualType EltTy = CTy->getElementType(); 10904 if (getContext().getTypeSize(EltTy) > FLen) 10905 return false; 10906 Field1Ty = CGT.ConvertType(EltTy); 10907 Field1Off = CurOff; 10908 Field2Ty = Field1Ty; 10909 Field2Off = Field1Off + getContext().getTypeSizeInChars(EltTy); 10910 return true; 10911 } 10912 10913 if (const ConstantArrayType *ATy = getContext().getAsConstantArrayType(Ty)) { 10914 uint64_t ArraySize = ATy->getSize().getZExtValue(); 10915 QualType EltTy = ATy->getElementType(); 10916 CharUnits EltSize = getContext().getTypeSizeInChars(EltTy); 10917 for (uint64_t i = 0; i < ArraySize; ++i) { 10918 bool Ret = detectFPCCEligibleStructHelper(EltTy, CurOff, Field1Ty, 10919 Field1Off, Field2Ty, Field2Off); 10920 if (!Ret) 10921 return false; 10922 CurOff += EltSize; 10923 } 10924 return true; 10925 } 10926 10927 if (const auto *RTy = Ty->getAs<RecordType>()) { 10928 // Structures with either a non-trivial destructor or a non-trivial 10929 // copy constructor are not eligible for the FP calling convention. 10930 if (getRecordArgABI(Ty, CGT.getCXXABI())) 10931 return false; 10932 if (isEmptyRecord(getContext(), Ty, true)) 10933 return true; 10934 const RecordDecl *RD = RTy->getDecl(); 10935 // Unions aren't eligible unless they're empty (which is caught above). 10936 if (RD->isUnion()) 10937 return false; 10938 int ZeroWidthBitFieldCount = 0; 10939 for (const FieldDecl *FD : RD->fields()) { 10940 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD); 10941 uint64_t FieldOffInBits = Layout.getFieldOffset(FD->getFieldIndex()); 10942 QualType QTy = FD->getType(); 10943 if (FD->isBitField()) { 10944 unsigned BitWidth = FD->getBitWidthValue(getContext()); 10945 // Allow a bitfield with a type greater than XLen as long as the 10946 // bitwidth is XLen or less. 10947 if (getContext().getTypeSize(QTy) > XLen && BitWidth <= XLen) 10948 QTy = getContext().getIntTypeForBitwidth(XLen, false); 10949 if (BitWidth == 0) { 10950 ZeroWidthBitFieldCount++; 10951 continue; 10952 } 10953 } 10954 10955 bool Ret = detectFPCCEligibleStructHelper( 10956 QTy, CurOff + getContext().toCharUnitsFromBits(FieldOffInBits), 10957 Field1Ty, Field1Off, Field2Ty, Field2Off); 10958 if (!Ret) 10959 return false; 10960 10961 // As a quirk of the ABI, zero-width bitfields aren't ignored for fp+fp 10962 // or int+fp structs, but are ignored for a struct with an fp field and 10963 // any number of zero-width bitfields. 10964 if (Field2Ty && ZeroWidthBitFieldCount > 0) 10965 return false; 10966 } 10967 return Field1Ty != nullptr; 10968 } 10969 10970 return false; 10971 } 10972 10973 // Determine if a struct is eligible for passing according to the floating 10974 // point calling convention (i.e., when flattened it contains a single fp 10975 // value, fp+fp, or int+fp of appropriate size). If so, NeededArgFPRs and 10976 // NeededArgGPRs are incremented appropriately. 10977 bool RISCVABIInfo::detectFPCCEligibleStruct(QualType Ty, llvm::Type *&Field1Ty, 10978 CharUnits &Field1Off, 10979 llvm::Type *&Field2Ty, 10980 CharUnits &Field2Off, 10981 int &NeededArgGPRs, 10982 int &NeededArgFPRs) const { 10983 Field1Ty = nullptr; 10984 Field2Ty = nullptr; 10985 NeededArgGPRs = 0; 10986 NeededArgFPRs = 0; 10987 bool IsCandidate = detectFPCCEligibleStructHelper( 10988 Ty, CharUnits::Zero(), Field1Ty, Field1Off, Field2Ty, Field2Off); 10989 // Not really a candidate if we have a single int but no float. 10990 if (Field1Ty && !Field2Ty && !Field1Ty->isFloatingPointTy()) 10991 return false; 10992 if (!IsCandidate) 10993 return false; 10994 if (Field1Ty && Field1Ty->isFloatingPointTy()) 10995 NeededArgFPRs++; 10996 else if (Field1Ty) 10997 NeededArgGPRs++; 10998 if (Field2Ty && Field2Ty->isFloatingPointTy()) 10999 NeededArgFPRs++; 11000 else if (Field2Ty) 11001 NeededArgGPRs++; 11002 return true; 11003 } 11004 11005 // Call getCoerceAndExpand for the two-element flattened struct described by 11006 // Field1Ty, Field1Off, Field2Ty, Field2Off. This method will create an 11007 // appropriate coerceToType and unpaddedCoerceToType. 11008 ABIArgInfo RISCVABIInfo::coerceAndExpandFPCCEligibleStruct( 11009 llvm::Type *Field1Ty, CharUnits Field1Off, llvm::Type *Field2Ty, 11010 CharUnits Field2Off) const { 11011 SmallVector<llvm::Type *, 3> CoerceElts; 11012 SmallVector<llvm::Type *, 2> UnpaddedCoerceElts; 11013 if (!Field1Off.isZero()) 11014 CoerceElts.push_back(llvm::ArrayType::get( 11015 llvm::Type::getInt8Ty(getVMContext()), Field1Off.getQuantity())); 11016 11017 CoerceElts.push_back(Field1Ty); 11018 UnpaddedCoerceElts.push_back(Field1Ty); 11019 11020 if (!Field2Ty) { 11021 return ABIArgInfo::getCoerceAndExpand( 11022 llvm::StructType::get(getVMContext(), CoerceElts, !Field1Off.isZero()), 11023 UnpaddedCoerceElts[0]); 11024 } 11025 11026 CharUnits Field2Align = 11027 CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(Field2Ty)); 11028 CharUnits Field1End = Field1Off + 11029 CharUnits::fromQuantity(getDataLayout().getTypeStoreSize(Field1Ty)); 11030 CharUnits Field2OffNoPadNoPack = Field1End.alignTo(Field2Align); 11031 11032 CharUnits Padding = CharUnits::Zero(); 11033 if (Field2Off > Field2OffNoPadNoPack) 11034 Padding = Field2Off - Field2OffNoPadNoPack; 11035 else if (Field2Off != Field2Align && Field2Off > Field1End) 11036 Padding = Field2Off - Field1End; 11037 11038 bool IsPacked = !Field2Off.isMultipleOf(Field2Align); 11039 11040 if (!Padding.isZero()) 11041 CoerceElts.push_back(llvm::ArrayType::get( 11042 llvm::Type::getInt8Ty(getVMContext()), Padding.getQuantity())); 11043 11044 CoerceElts.push_back(Field2Ty); 11045 UnpaddedCoerceElts.push_back(Field2Ty); 11046 11047 auto CoerceToType = 11048 llvm::StructType::get(getVMContext(), CoerceElts, IsPacked); 11049 auto UnpaddedCoerceToType = 11050 llvm::StructType::get(getVMContext(), UnpaddedCoerceElts, IsPacked); 11051 11052 return ABIArgInfo::getCoerceAndExpand(CoerceToType, UnpaddedCoerceToType); 11053 } 11054 11055 ABIArgInfo RISCVABIInfo::classifyArgumentType(QualType Ty, bool IsFixed, 11056 int &ArgGPRsLeft, 11057 int &ArgFPRsLeft) const { 11058 assert(ArgGPRsLeft <= NumArgGPRs && "Arg GPR tracking underflow"); 11059 Ty = useFirstFieldIfTransparentUnion(Ty); 11060 11061 // Structures with either a non-trivial destructor or a non-trivial 11062 // copy constructor are always passed indirectly. 11063 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) { 11064 if (ArgGPRsLeft) 11065 ArgGPRsLeft -= 1; 11066 return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA == 11067 CGCXXABI::RAA_DirectInMemory); 11068 } 11069 11070 // Ignore empty structs/unions. 11071 if (isEmptyRecord(getContext(), Ty, true)) 11072 return ABIArgInfo::getIgnore(); 11073 11074 uint64_t Size = getContext().getTypeSize(Ty); 11075 11076 // Pass floating point values via FPRs if possible. 11077 if (IsFixed && Ty->isFloatingType() && !Ty->isComplexType() && 11078 FLen >= Size && ArgFPRsLeft) { 11079 ArgFPRsLeft--; 11080 return ABIArgInfo::getDirect(); 11081 } 11082 11083 // Complex types for the hard float ABI must be passed direct rather than 11084 // using CoerceAndExpand. 11085 if (IsFixed && Ty->isComplexType() && FLen && ArgFPRsLeft >= 2) { 11086 QualType EltTy = Ty->castAs<ComplexType>()->getElementType(); 11087 if (getContext().getTypeSize(EltTy) <= FLen) { 11088 ArgFPRsLeft -= 2; 11089 return ABIArgInfo::getDirect(); 11090 } 11091 } 11092 11093 if (IsFixed && FLen && Ty->isStructureOrClassType()) { 11094 llvm::Type *Field1Ty = nullptr; 11095 llvm::Type *Field2Ty = nullptr; 11096 CharUnits Field1Off = CharUnits::Zero(); 11097 CharUnits Field2Off = CharUnits::Zero(); 11098 int NeededArgGPRs = 0; 11099 int NeededArgFPRs = 0; 11100 bool IsCandidate = 11101 detectFPCCEligibleStruct(Ty, Field1Ty, Field1Off, Field2Ty, Field2Off, 11102 NeededArgGPRs, NeededArgFPRs); 11103 if (IsCandidate && NeededArgGPRs <= ArgGPRsLeft && 11104 NeededArgFPRs <= ArgFPRsLeft) { 11105 ArgGPRsLeft -= NeededArgGPRs; 11106 ArgFPRsLeft -= NeededArgFPRs; 11107 return coerceAndExpandFPCCEligibleStruct(Field1Ty, Field1Off, Field2Ty, 11108 Field2Off); 11109 } 11110 } 11111 11112 uint64_t NeededAlign = getContext().getTypeAlign(Ty); 11113 bool MustUseStack = false; 11114 // Determine the number of GPRs needed to pass the current argument 11115 // according to the ABI. 2*XLen-aligned varargs are passed in "aligned" 11116 // register pairs, so may consume 3 registers. 11117 int NeededArgGPRs = 1; 11118 if (!IsFixed && NeededAlign == 2 * XLen) 11119 NeededArgGPRs = 2 + (ArgGPRsLeft % 2); 11120 else if (Size > XLen && Size <= 2 * XLen) 11121 NeededArgGPRs = 2; 11122 11123 if (NeededArgGPRs > ArgGPRsLeft) { 11124 MustUseStack = true; 11125 NeededArgGPRs = ArgGPRsLeft; 11126 } 11127 11128 ArgGPRsLeft -= NeededArgGPRs; 11129 11130 if (!isAggregateTypeForABI(Ty) && !Ty->isVectorType()) { 11131 // Treat an enum type as its underlying type. 11132 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 11133 Ty = EnumTy->getDecl()->getIntegerType(); 11134 11135 // All integral types are promoted to XLen width, unless passed on the 11136 // stack. 11137 if (Size < XLen && Ty->isIntegralOrEnumerationType() && !MustUseStack) { 11138 return extendType(Ty); 11139 } 11140 11141 if (const auto *EIT = Ty->getAs<BitIntType>()) { 11142 if (EIT->getNumBits() < XLen && !MustUseStack) 11143 return extendType(Ty); 11144 if (EIT->getNumBits() > 128 || 11145 (!getContext().getTargetInfo().hasInt128Type() && 11146 EIT->getNumBits() > 64)) 11147 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 11148 } 11149 11150 return ABIArgInfo::getDirect(); 11151 } 11152 11153 // Aggregates which are <= 2*XLen will be passed in registers if possible, 11154 // so coerce to integers. 11155 if (Size <= 2 * XLen) { 11156 unsigned Alignment = getContext().getTypeAlign(Ty); 11157 11158 // Use a single XLen int if possible, 2*XLen if 2*XLen alignment is 11159 // required, and a 2-element XLen array if only XLen alignment is required. 11160 if (Size <= XLen) { 11161 return ABIArgInfo::getDirect( 11162 llvm::IntegerType::get(getVMContext(), XLen)); 11163 } else if (Alignment == 2 * XLen) { 11164 return ABIArgInfo::getDirect( 11165 llvm::IntegerType::get(getVMContext(), 2 * XLen)); 11166 } else { 11167 return ABIArgInfo::getDirect(llvm::ArrayType::get( 11168 llvm::IntegerType::get(getVMContext(), XLen), 2)); 11169 } 11170 } 11171 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 11172 } 11173 11174 ABIArgInfo RISCVABIInfo::classifyReturnType(QualType RetTy) const { 11175 if (RetTy->isVoidType()) 11176 return ABIArgInfo::getIgnore(); 11177 11178 int ArgGPRsLeft = 2; 11179 int ArgFPRsLeft = FLen ? 2 : 0; 11180 11181 // The rules for return and argument types are the same, so defer to 11182 // classifyArgumentType. 11183 return classifyArgumentType(RetTy, /*IsFixed=*/true, ArgGPRsLeft, 11184 ArgFPRsLeft); 11185 } 11186 11187 Address RISCVABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 11188 QualType Ty) const { 11189 CharUnits SlotSize = CharUnits::fromQuantity(XLen / 8); 11190 11191 // Empty records are ignored for parameter passing purposes. 11192 if (isEmptyRecord(getContext(), Ty, true)) { 11193 Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize); 11194 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty)); 11195 return Addr; 11196 } 11197 11198 auto TInfo = getContext().getTypeInfoInChars(Ty); 11199 11200 // Arguments bigger than 2*Xlen bytes are passed indirectly. 11201 bool IsIndirect = TInfo.Width > 2 * SlotSize; 11202 11203 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TInfo, 11204 SlotSize, /*AllowHigherAlign=*/true); 11205 } 11206 11207 ABIArgInfo RISCVABIInfo::extendType(QualType Ty) const { 11208 int TySize = getContext().getTypeSize(Ty); 11209 // RV64 ABI requires unsigned 32 bit integers to be sign extended. 11210 if (XLen == 64 && Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32) 11211 return ABIArgInfo::getSignExtend(Ty); 11212 return ABIArgInfo::getExtend(Ty); 11213 } 11214 11215 namespace { 11216 class RISCVTargetCodeGenInfo : public TargetCodeGenInfo { 11217 public: 11218 RISCVTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, unsigned XLen, 11219 unsigned FLen) 11220 : TargetCodeGenInfo(std::make_unique<RISCVABIInfo>(CGT, XLen, FLen)) {} 11221 11222 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 11223 CodeGen::CodeGenModule &CGM) const override { 11224 const auto *FD = dyn_cast_or_null<FunctionDecl>(D); 11225 if (!FD) return; 11226 11227 const auto *Attr = FD->getAttr<RISCVInterruptAttr>(); 11228 if (!Attr) 11229 return; 11230 11231 const char *Kind; 11232 switch (Attr->getInterrupt()) { 11233 case RISCVInterruptAttr::user: Kind = "user"; break; 11234 case RISCVInterruptAttr::supervisor: Kind = "supervisor"; break; 11235 case RISCVInterruptAttr::machine: Kind = "machine"; break; 11236 } 11237 11238 auto *Fn = cast<llvm::Function>(GV); 11239 11240 Fn->addFnAttr("interrupt", Kind); 11241 } 11242 }; 11243 } // namespace 11244 11245 //===----------------------------------------------------------------------===// 11246 // VE ABI Implementation. 11247 // 11248 namespace { 11249 class VEABIInfo : public DefaultABIInfo { 11250 public: 11251 VEABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {} 11252 11253 private: 11254 ABIArgInfo classifyReturnType(QualType RetTy) const; 11255 ABIArgInfo classifyArgumentType(QualType RetTy) const; 11256 void computeInfo(CGFunctionInfo &FI) const override; 11257 }; 11258 } // end anonymous namespace 11259 11260 ABIArgInfo VEABIInfo::classifyReturnType(QualType Ty) const { 11261 if (Ty->isAnyComplexType()) 11262 return ABIArgInfo::getDirect(); 11263 uint64_t Size = getContext().getTypeSize(Ty); 11264 if (Size < 64 && Ty->isIntegerType()) 11265 return ABIArgInfo::getExtend(Ty); 11266 return DefaultABIInfo::classifyReturnType(Ty); 11267 } 11268 11269 ABIArgInfo VEABIInfo::classifyArgumentType(QualType Ty) const { 11270 if (Ty->isAnyComplexType()) 11271 return ABIArgInfo::getDirect(); 11272 uint64_t Size = getContext().getTypeSize(Ty); 11273 if (Size < 64 && Ty->isIntegerType()) 11274 return ABIArgInfo::getExtend(Ty); 11275 return DefaultABIInfo::classifyArgumentType(Ty); 11276 } 11277 11278 void VEABIInfo::computeInfo(CGFunctionInfo &FI) const { 11279 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 11280 for (auto &Arg : FI.arguments()) 11281 Arg.info = classifyArgumentType(Arg.type); 11282 } 11283 11284 namespace { 11285 class VETargetCodeGenInfo : public TargetCodeGenInfo { 11286 public: 11287 VETargetCodeGenInfo(CodeGenTypes &CGT) 11288 : TargetCodeGenInfo(std::make_unique<VEABIInfo>(CGT)) {} 11289 // VE ABI requires the arguments of variadic and prototype-less functions 11290 // are passed in both registers and memory. 11291 bool isNoProtoCallVariadic(const CallArgList &args, 11292 const FunctionNoProtoType *fnType) const override { 11293 return true; 11294 } 11295 }; 11296 } // end anonymous namespace 11297 11298 //===----------------------------------------------------------------------===// 11299 // Driver code 11300 //===----------------------------------------------------------------------===// 11301 11302 bool CodeGenModule::supportsCOMDAT() const { 11303 return getTriple().supportsCOMDAT(); 11304 } 11305 11306 const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() { 11307 if (TheTargetCodeGenInfo) 11308 return *TheTargetCodeGenInfo; 11309 11310 // Helper to set the unique_ptr while still keeping the return value. 11311 auto SetCGInfo = [&](TargetCodeGenInfo *P) -> const TargetCodeGenInfo & { 11312 this->TheTargetCodeGenInfo.reset(P); 11313 return *P; 11314 }; 11315 11316 const llvm::Triple &Triple = getTarget().getTriple(); 11317 switch (Triple.getArch()) { 11318 default: 11319 return SetCGInfo(new DefaultTargetCodeGenInfo(Types)); 11320 11321 case llvm::Triple::le32: 11322 return SetCGInfo(new PNaClTargetCodeGenInfo(Types)); 11323 case llvm::Triple::m68k: 11324 return SetCGInfo(new M68kTargetCodeGenInfo(Types)); 11325 case llvm::Triple::mips: 11326 case llvm::Triple::mipsel: 11327 if (Triple.getOS() == llvm::Triple::NaCl) 11328 return SetCGInfo(new PNaClTargetCodeGenInfo(Types)); 11329 return SetCGInfo(new MIPSTargetCodeGenInfo(Types, true)); 11330 11331 case llvm::Triple::mips64: 11332 case llvm::Triple::mips64el: 11333 return SetCGInfo(new MIPSTargetCodeGenInfo(Types, false)); 11334 11335 case llvm::Triple::avr: { 11336 // For passing parameters, R8~R25 are used on avr, and R18~R25 are used 11337 // on avrtiny. For passing return value, R18~R25 are used on avr, and 11338 // R22~R25 are used on avrtiny. 11339 unsigned NPR = getTarget().getABI() == "avrtiny" ? 6 : 18; 11340 unsigned NRR = getTarget().getABI() == "avrtiny" ? 4 : 8; 11341 return SetCGInfo(new AVRTargetCodeGenInfo(Types, NPR, NRR)); 11342 } 11343 11344 case llvm::Triple::aarch64: 11345 case llvm::Triple::aarch64_32: 11346 case llvm::Triple::aarch64_be: { 11347 AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS; 11348 if (getTarget().getABI() == "darwinpcs") 11349 Kind = AArch64ABIInfo::DarwinPCS; 11350 else if (Triple.isOSWindows()) 11351 return SetCGInfo( 11352 new WindowsAArch64TargetCodeGenInfo(Types, AArch64ABIInfo::Win64)); 11353 11354 return SetCGInfo(new AArch64TargetCodeGenInfo(Types, Kind)); 11355 } 11356 11357 case llvm::Triple::wasm32: 11358 case llvm::Triple::wasm64: { 11359 WebAssemblyABIInfo::ABIKind Kind = WebAssemblyABIInfo::MVP; 11360 if (getTarget().getABI() == "experimental-mv") 11361 Kind = WebAssemblyABIInfo::ExperimentalMV; 11362 return SetCGInfo(new WebAssemblyTargetCodeGenInfo(Types, Kind)); 11363 } 11364 11365 case llvm::Triple::arm: 11366 case llvm::Triple::armeb: 11367 case llvm::Triple::thumb: 11368 case llvm::Triple::thumbeb: { 11369 if (Triple.getOS() == llvm::Triple::Win32) { 11370 return SetCGInfo( 11371 new WindowsARMTargetCodeGenInfo(Types, ARMABIInfo::AAPCS_VFP)); 11372 } 11373 11374 ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS; 11375 StringRef ABIStr = getTarget().getABI(); 11376 if (ABIStr == "apcs-gnu") 11377 Kind = ARMABIInfo::APCS; 11378 else if (ABIStr == "aapcs16") 11379 Kind = ARMABIInfo::AAPCS16_VFP; 11380 else if (CodeGenOpts.FloatABI == "hard" || 11381 (CodeGenOpts.FloatABI != "soft" && 11382 (Triple.getEnvironment() == llvm::Triple::GNUEABIHF || 11383 Triple.getEnvironment() == llvm::Triple::MuslEABIHF || 11384 Triple.getEnvironment() == llvm::Triple::EABIHF))) 11385 Kind = ARMABIInfo::AAPCS_VFP; 11386 11387 return SetCGInfo(new ARMTargetCodeGenInfo(Types, Kind)); 11388 } 11389 11390 case llvm::Triple::ppc: { 11391 if (Triple.isOSAIX()) 11392 return SetCGInfo(new AIXTargetCodeGenInfo(Types, /*Is64Bit*/ false)); 11393 11394 bool IsSoftFloat = 11395 CodeGenOpts.FloatABI == "soft" || getTarget().hasFeature("spe"); 11396 bool RetSmallStructInRegABI = 11397 PPC32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts); 11398 return SetCGInfo( 11399 new PPC32TargetCodeGenInfo(Types, IsSoftFloat, RetSmallStructInRegABI)); 11400 } 11401 case llvm::Triple::ppcle: { 11402 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft"; 11403 bool RetSmallStructInRegABI = 11404 PPC32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts); 11405 return SetCGInfo( 11406 new PPC32TargetCodeGenInfo(Types, IsSoftFloat, RetSmallStructInRegABI)); 11407 } 11408 case llvm::Triple::ppc64: 11409 if (Triple.isOSAIX()) 11410 return SetCGInfo(new AIXTargetCodeGenInfo(Types, /*Is64Bit*/ true)); 11411 11412 if (Triple.isOSBinFormatELF()) { 11413 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1; 11414 if (getTarget().getABI() == "elfv2") 11415 Kind = PPC64_SVR4_ABIInfo::ELFv2; 11416 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft"; 11417 11418 return SetCGInfo( 11419 new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, IsSoftFloat)); 11420 } 11421 return SetCGInfo(new PPC64TargetCodeGenInfo(Types)); 11422 case llvm::Triple::ppc64le: { 11423 assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!"); 11424 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2; 11425 if (getTarget().getABI() == "elfv1") 11426 Kind = PPC64_SVR4_ABIInfo::ELFv1; 11427 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft"; 11428 11429 return SetCGInfo( 11430 new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, IsSoftFloat)); 11431 } 11432 11433 case llvm::Triple::nvptx: 11434 case llvm::Triple::nvptx64: 11435 return SetCGInfo(new NVPTXTargetCodeGenInfo(Types)); 11436 11437 case llvm::Triple::msp430: 11438 return SetCGInfo(new MSP430TargetCodeGenInfo(Types)); 11439 11440 case llvm::Triple::riscv32: 11441 case llvm::Triple::riscv64: { 11442 StringRef ABIStr = getTarget().getABI(); 11443 unsigned XLen = getTarget().getPointerWidth(0); 11444 unsigned ABIFLen = 0; 11445 if (ABIStr.endswith("f")) 11446 ABIFLen = 32; 11447 else if (ABIStr.endswith("d")) 11448 ABIFLen = 64; 11449 return SetCGInfo(new RISCVTargetCodeGenInfo(Types, XLen, ABIFLen)); 11450 } 11451 11452 case llvm::Triple::systemz: { 11453 bool SoftFloat = CodeGenOpts.FloatABI == "soft"; 11454 bool HasVector = !SoftFloat && getTarget().getABI() == "vector"; 11455 return SetCGInfo(new SystemZTargetCodeGenInfo(Types, HasVector, SoftFloat)); 11456 } 11457 11458 case llvm::Triple::tce: 11459 case llvm::Triple::tcele: 11460 return SetCGInfo(new TCETargetCodeGenInfo(Types)); 11461 11462 case llvm::Triple::x86: { 11463 bool IsDarwinVectorABI = Triple.isOSDarwin(); 11464 bool RetSmallStructInRegABI = 11465 X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts); 11466 bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing(); 11467 11468 if (Triple.getOS() == llvm::Triple::Win32) { 11469 return SetCGInfo(new WinX86_32TargetCodeGenInfo( 11470 Types, IsDarwinVectorABI, RetSmallStructInRegABI, 11471 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters)); 11472 } else { 11473 return SetCGInfo(new X86_32TargetCodeGenInfo( 11474 Types, IsDarwinVectorABI, RetSmallStructInRegABI, 11475 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters, 11476 CodeGenOpts.FloatABI == "soft")); 11477 } 11478 } 11479 11480 case llvm::Triple::x86_64: { 11481 StringRef ABI = getTarget().getABI(); 11482 X86AVXABILevel AVXLevel = 11483 (ABI == "avx512" 11484 ? X86AVXABILevel::AVX512 11485 : ABI == "avx" ? X86AVXABILevel::AVX : X86AVXABILevel::None); 11486 11487 switch (Triple.getOS()) { 11488 case llvm::Triple::Win32: 11489 return SetCGInfo(new WinX86_64TargetCodeGenInfo(Types, AVXLevel)); 11490 default: 11491 return SetCGInfo(new X86_64TargetCodeGenInfo(Types, AVXLevel)); 11492 } 11493 } 11494 case llvm::Triple::hexagon: 11495 return SetCGInfo(new HexagonTargetCodeGenInfo(Types)); 11496 case llvm::Triple::lanai: 11497 return SetCGInfo(new LanaiTargetCodeGenInfo(Types)); 11498 case llvm::Triple::r600: 11499 return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types)); 11500 case llvm::Triple::amdgcn: 11501 return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types)); 11502 case llvm::Triple::sparc: 11503 return SetCGInfo(new SparcV8TargetCodeGenInfo(Types)); 11504 case llvm::Triple::sparcv9: 11505 return SetCGInfo(new SparcV9TargetCodeGenInfo(Types)); 11506 case llvm::Triple::xcore: 11507 return SetCGInfo(new XCoreTargetCodeGenInfo(Types)); 11508 case llvm::Triple::arc: 11509 return SetCGInfo(new ARCTargetCodeGenInfo(Types)); 11510 case llvm::Triple::spir: 11511 case llvm::Triple::spir64: 11512 return SetCGInfo(new CommonSPIRTargetCodeGenInfo(Types)); 11513 case llvm::Triple::spirv32: 11514 case llvm::Triple::spirv64: 11515 return SetCGInfo(new SPIRVTargetCodeGenInfo(Types)); 11516 case llvm::Triple::ve: 11517 return SetCGInfo(new VETargetCodeGenInfo(Types)); 11518 } 11519 } 11520 11521 /// Create an OpenCL kernel for an enqueued block. 11522 /// 11523 /// The kernel has the same function type as the block invoke function. Its 11524 /// name is the name of the block invoke function postfixed with "_kernel". 11525 /// It simply calls the block invoke function then returns. 11526 llvm::Function * 11527 TargetCodeGenInfo::createEnqueuedBlockKernel(CodeGenFunction &CGF, 11528 llvm::Function *Invoke, 11529 llvm::Value *BlockLiteral) const { 11530 auto *InvokeFT = Invoke->getFunctionType(); 11531 llvm::SmallVector<llvm::Type *, 2> ArgTys; 11532 for (auto &P : InvokeFT->params()) 11533 ArgTys.push_back(P); 11534 auto &C = CGF.getLLVMContext(); 11535 std::string Name = Invoke->getName().str() + "_kernel"; 11536 auto *FT = llvm::FunctionType::get(llvm::Type::getVoidTy(C), ArgTys, false); 11537 auto *F = llvm::Function::Create(FT, llvm::GlobalValue::ExternalLinkage, Name, 11538 &CGF.CGM.getModule()); 11539 auto IP = CGF.Builder.saveIP(); 11540 auto *BB = llvm::BasicBlock::Create(C, "entry", F); 11541 auto &Builder = CGF.Builder; 11542 Builder.SetInsertPoint(BB); 11543 llvm::SmallVector<llvm::Value *, 2> Args; 11544 for (auto &A : F->args()) 11545 Args.push_back(&A); 11546 llvm::CallInst *call = Builder.CreateCall(Invoke, Args); 11547 call->setCallingConv(Invoke->getCallingConv()); 11548 Builder.CreateRetVoid(); 11549 Builder.restoreIP(IP); 11550 return F; 11551 } 11552 11553 /// Create an OpenCL kernel for an enqueued block. 11554 /// 11555 /// The type of the first argument (the block literal) is the struct type 11556 /// of the block literal instead of a pointer type. The first argument 11557 /// (block literal) is passed directly by value to the kernel. The kernel 11558 /// allocates the same type of struct on stack and stores the block literal 11559 /// to it and passes its pointer to the block invoke function. The kernel 11560 /// has "enqueued-block" function attribute and kernel argument metadata. 11561 llvm::Function *AMDGPUTargetCodeGenInfo::createEnqueuedBlockKernel( 11562 CodeGenFunction &CGF, llvm::Function *Invoke, 11563 llvm::Value *BlockLiteral) const { 11564 auto &Builder = CGF.Builder; 11565 auto &C = CGF.getLLVMContext(); 11566 11567 auto *BlockTy = BlockLiteral->getType()->getPointerElementType(); 11568 auto *InvokeFT = Invoke->getFunctionType(); 11569 llvm::SmallVector<llvm::Type *, 2> ArgTys; 11570 llvm::SmallVector<llvm::Metadata *, 8> AddressQuals; 11571 llvm::SmallVector<llvm::Metadata *, 8> AccessQuals; 11572 llvm::SmallVector<llvm::Metadata *, 8> ArgTypeNames; 11573 llvm::SmallVector<llvm::Metadata *, 8> ArgBaseTypeNames; 11574 llvm::SmallVector<llvm::Metadata *, 8> ArgTypeQuals; 11575 llvm::SmallVector<llvm::Metadata *, 8> ArgNames; 11576 11577 ArgTys.push_back(BlockTy); 11578 ArgTypeNames.push_back(llvm::MDString::get(C, "__block_literal")); 11579 AddressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(0))); 11580 ArgBaseTypeNames.push_back(llvm::MDString::get(C, "__block_literal")); 11581 ArgTypeQuals.push_back(llvm::MDString::get(C, "")); 11582 AccessQuals.push_back(llvm::MDString::get(C, "none")); 11583 ArgNames.push_back(llvm::MDString::get(C, "block_literal")); 11584 for (unsigned I = 1, E = InvokeFT->getNumParams(); I < E; ++I) { 11585 ArgTys.push_back(InvokeFT->getParamType(I)); 11586 ArgTypeNames.push_back(llvm::MDString::get(C, "void*")); 11587 AddressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(3))); 11588 AccessQuals.push_back(llvm::MDString::get(C, "none")); 11589 ArgBaseTypeNames.push_back(llvm::MDString::get(C, "void*")); 11590 ArgTypeQuals.push_back(llvm::MDString::get(C, "")); 11591 ArgNames.push_back( 11592 llvm::MDString::get(C, (Twine("local_arg") + Twine(I)).str())); 11593 } 11594 std::string Name = Invoke->getName().str() + "_kernel"; 11595 auto *FT = llvm::FunctionType::get(llvm::Type::getVoidTy(C), ArgTys, false); 11596 auto *F = llvm::Function::Create(FT, llvm::GlobalValue::InternalLinkage, Name, 11597 &CGF.CGM.getModule()); 11598 F->addFnAttr("enqueued-block"); 11599 auto IP = CGF.Builder.saveIP(); 11600 auto *BB = llvm::BasicBlock::Create(C, "entry", F); 11601 Builder.SetInsertPoint(BB); 11602 const auto BlockAlign = CGF.CGM.getDataLayout().getPrefTypeAlign(BlockTy); 11603 auto *BlockPtr = Builder.CreateAlloca(BlockTy, nullptr); 11604 BlockPtr->setAlignment(BlockAlign); 11605 Builder.CreateAlignedStore(F->arg_begin(), BlockPtr, BlockAlign); 11606 auto *Cast = Builder.CreatePointerCast(BlockPtr, InvokeFT->getParamType(0)); 11607 llvm::SmallVector<llvm::Value *, 2> Args; 11608 Args.push_back(Cast); 11609 for (auto I = F->arg_begin() + 1, E = F->arg_end(); I != E; ++I) 11610 Args.push_back(I); 11611 llvm::CallInst *call = Builder.CreateCall(Invoke, Args); 11612 call->setCallingConv(Invoke->getCallingConv()); 11613 Builder.CreateRetVoid(); 11614 Builder.restoreIP(IP); 11615 11616 F->setMetadata("kernel_arg_addr_space", llvm::MDNode::get(C, AddressQuals)); 11617 F->setMetadata("kernel_arg_access_qual", llvm::MDNode::get(C, AccessQuals)); 11618 F->setMetadata("kernel_arg_type", llvm::MDNode::get(C, ArgTypeNames)); 11619 F->setMetadata("kernel_arg_base_type", 11620 llvm::MDNode::get(C, ArgBaseTypeNames)); 11621 F->setMetadata("kernel_arg_type_qual", llvm::MDNode::get(C, ArgTypeQuals)); 11622 if (CGF.CGM.getCodeGenOpts().EmitOpenCLArgMetadata) 11623 F->setMetadata("kernel_arg_name", llvm::MDNode::get(C, ArgNames)); 11624 11625 return F; 11626 } 11627