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 static llvm::Type *getVAListElementType(CodeGenFunction &CGF) { 105 return CGF.ConvertTypeForMem( 106 CGF.getContext().getBuiltinVaListType()->getPointeeType()); 107 } 108 109 bool ABIInfo::isPromotableIntegerTypeForABI(QualType Ty) const { 110 if (Ty->isPromotableIntegerType()) 111 return true; 112 113 if (const auto *EIT = Ty->getAs<BitIntType>()) 114 if (EIT->getNumBits() < getContext().getTypeSize(getContext().IntTy)) 115 return true; 116 117 return false; 118 } 119 120 ABIInfo::~ABIInfo() {} 121 122 /// Does the given lowering require more than the given number of 123 /// registers when expanded? 124 /// 125 /// This is intended to be the basis of a reasonable basic implementation 126 /// of should{Pass,Return}IndirectlyForSwift. 127 /// 128 /// For most targets, a limit of four total registers is reasonable; this 129 /// limits the amount of code required in order to move around the value 130 /// in case it wasn't produced immediately prior to the call by the caller 131 /// (or wasn't produced in exactly the right registers) or isn't used 132 /// immediately within the callee. But some targets may need to further 133 /// limit the register count due to an inability to support that many 134 /// return registers. 135 static bool occupiesMoreThan(CodeGenTypes &cgt, 136 ArrayRef<llvm::Type*> scalarTypes, 137 unsigned maxAllRegisters) { 138 unsigned intCount = 0, fpCount = 0; 139 for (llvm::Type *type : scalarTypes) { 140 if (type->isPointerTy()) { 141 intCount++; 142 } else if (auto intTy = dyn_cast<llvm::IntegerType>(type)) { 143 auto ptrWidth = cgt.getTarget().getPointerWidth(0); 144 intCount += (intTy->getBitWidth() + ptrWidth - 1) / ptrWidth; 145 } else { 146 assert(type->isVectorTy() || type->isFloatingPointTy()); 147 fpCount++; 148 } 149 } 150 151 return (intCount + fpCount > maxAllRegisters); 152 } 153 154 bool SwiftABIInfo::isLegalVectorTypeForSwift(CharUnits vectorSize, 155 llvm::Type *eltTy, 156 unsigned numElts) const { 157 // The default implementation of this assumes that the target guarantees 158 // 128-bit SIMD support but nothing more. 159 return (vectorSize.getQuantity() > 8 && vectorSize.getQuantity() <= 16); 160 } 161 162 static CGCXXABI::RecordArgABI getRecordArgABI(const RecordType *RT, 163 CGCXXABI &CXXABI) { 164 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 165 if (!RD) { 166 if (!RT->getDecl()->canPassInRegisters()) 167 return CGCXXABI::RAA_Indirect; 168 return CGCXXABI::RAA_Default; 169 } 170 return CXXABI.getRecordArgABI(RD); 171 } 172 173 static CGCXXABI::RecordArgABI getRecordArgABI(QualType T, 174 CGCXXABI &CXXABI) { 175 const RecordType *RT = T->getAs<RecordType>(); 176 if (!RT) 177 return CGCXXABI::RAA_Default; 178 return getRecordArgABI(RT, CXXABI); 179 } 180 181 static bool classifyReturnType(const CGCXXABI &CXXABI, CGFunctionInfo &FI, 182 const ABIInfo &Info) { 183 QualType Ty = FI.getReturnType(); 184 185 if (const auto *RT = Ty->getAs<RecordType>()) 186 if (!isa<CXXRecordDecl>(RT->getDecl()) && 187 !RT->getDecl()->canPassInRegisters()) { 188 FI.getReturnInfo() = Info.getNaturalAlignIndirect(Ty); 189 return true; 190 } 191 192 return CXXABI.classifyReturnType(FI); 193 } 194 195 /// Pass transparent unions as if they were the type of the first element. Sema 196 /// should ensure that all elements of the union have the same "machine type". 197 static QualType useFirstFieldIfTransparentUnion(QualType Ty) { 198 if (const RecordType *UT = Ty->getAsUnionType()) { 199 const RecordDecl *UD = UT->getDecl(); 200 if (UD->hasAttr<TransparentUnionAttr>()) { 201 assert(!UD->field_empty() && "sema created an empty transparent union"); 202 return UD->field_begin()->getType(); 203 } 204 } 205 return Ty; 206 } 207 208 CGCXXABI &ABIInfo::getCXXABI() const { 209 return CGT.getCXXABI(); 210 } 211 212 ASTContext &ABIInfo::getContext() const { 213 return CGT.getContext(); 214 } 215 216 llvm::LLVMContext &ABIInfo::getVMContext() const { 217 return CGT.getLLVMContext(); 218 } 219 220 const llvm::DataLayout &ABIInfo::getDataLayout() const { 221 return CGT.getDataLayout(); 222 } 223 224 const TargetInfo &ABIInfo::getTarget() const { 225 return CGT.getTarget(); 226 } 227 228 const CodeGenOptions &ABIInfo::getCodeGenOpts() const { 229 return CGT.getCodeGenOpts(); 230 } 231 232 bool ABIInfo::isAndroid() const { return getTarget().getTriple().isAndroid(); } 233 234 bool ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const { 235 return false; 236 } 237 238 bool ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base, 239 uint64_t Members) const { 240 return false; 241 } 242 243 LLVM_DUMP_METHOD void ABIArgInfo::dump() const { 244 raw_ostream &OS = llvm::errs(); 245 OS << "(ABIArgInfo Kind="; 246 switch (TheKind) { 247 case Direct: 248 OS << "Direct Type="; 249 if (llvm::Type *Ty = getCoerceToType()) 250 Ty->print(OS); 251 else 252 OS << "null"; 253 break; 254 case Extend: 255 OS << "Extend"; 256 break; 257 case Ignore: 258 OS << "Ignore"; 259 break; 260 case InAlloca: 261 OS << "InAlloca Offset=" << getInAllocaFieldIndex(); 262 break; 263 case Indirect: 264 OS << "Indirect Align=" << getIndirectAlign().getQuantity() 265 << " ByVal=" << getIndirectByVal() 266 << " Realign=" << getIndirectRealign(); 267 break; 268 case IndirectAliased: 269 OS << "Indirect Align=" << getIndirectAlign().getQuantity() 270 << " AadrSpace=" << getIndirectAddrSpace() 271 << " Realign=" << getIndirectRealign(); 272 break; 273 case Expand: 274 OS << "Expand"; 275 break; 276 case CoerceAndExpand: 277 OS << "CoerceAndExpand Type="; 278 getCoerceAndExpandType()->print(OS); 279 break; 280 } 281 OS << ")\n"; 282 } 283 284 // Dynamically round a pointer up to a multiple of the given alignment. 285 static llvm::Value *emitRoundPointerUpToAlignment(CodeGenFunction &CGF, 286 llvm::Value *Ptr, 287 CharUnits Align) { 288 llvm::Value *PtrAsInt = Ptr; 289 // OverflowArgArea = (OverflowArgArea + Align - 1) & -Align; 290 PtrAsInt = CGF.Builder.CreatePtrToInt(PtrAsInt, CGF.IntPtrTy); 291 PtrAsInt = CGF.Builder.CreateAdd(PtrAsInt, 292 llvm::ConstantInt::get(CGF.IntPtrTy, Align.getQuantity() - 1)); 293 PtrAsInt = CGF.Builder.CreateAnd(PtrAsInt, 294 llvm::ConstantInt::get(CGF.IntPtrTy, -Align.getQuantity())); 295 PtrAsInt = CGF.Builder.CreateIntToPtr(PtrAsInt, 296 Ptr->getType(), 297 Ptr->getName() + ".aligned"); 298 return PtrAsInt; 299 } 300 301 /// Emit va_arg for a platform using the common void* representation, 302 /// where arguments are simply emitted in an array of slots on the stack. 303 /// 304 /// This version implements the core direct-value passing rules. 305 /// 306 /// \param SlotSize - The size and alignment of a stack slot. 307 /// Each argument will be allocated to a multiple of this number of 308 /// slots, and all the slots will be aligned to this value. 309 /// \param AllowHigherAlign - The slot alignment is not a cap; 310 /// an argument type with an alignment greater than the slot size 311 /// will be emitted on a higher-alignment address, potentially 312 /// leaving one or more empty slots behind as padding. If this 313 /// is false, the returned address might be less-aligned than 314 /// DirectAlign. 315 static Address emitVoidPtrDirectVAArg(CodeGenFunction &CGF, 316 Address VAListAddr, 317 llvm::Type *DirectTy, 318 CharUnits DirectSize, 319 CharUnits DirectAlign, 320 CharUnits SlotSize, 321 bool AllowHigherAlign) { 322 // Cast the element type to i8* if necessary. Some platforms define 323 // va_list as a struct containing an i8* instead of just an i8*. 324 if (VAListAddr.getElementType() != CGF.Int8PtrTy) 325 VAListAddr = CGF.Builder.CreateElementBitCast(VAListAddr, CGF.Int8PtrTy); 326 327 llvm::Value *Ptr = CGF.Builder.CreateLoad(VAListAddr, "argp.cur"); 328 329 // If the CC aligns values higher than the slot size, do so if needed. 330 Address Addr = Address::invalid(); 331 if (AllowHigherAlign && DirectAlign > SlotSize) { 332 Addr = Address(emitRoundPointerUpToAlignment(CGF, Ptr, DirectAlign), 333 CGF.Int8Ty, DirectAlign); 334 } else { 335 Addr = Address(Ptr, CGF.Int8Ty, SlotSize); 336 } 337 338 // Advance the pointer past the argument, then store that back. 339 CharUnits FullDirectSize = DirectSize.alignTo(SlotSize); 340 Address NextPtr = 341 CGF.Builder.CreateConstInBoundsByteGEP(Addr, FullDirectSize, "argp.next"); 342 CGF.Builder.CreateStore(NextPtr.getPointer(), VAListAddr); 343 344 // If the argument is smaller than a slot, and this is a big-endian 345 // target, the argument will be right-adjusted in its slot. 346 if (DirectSize < SlotSize && CGF.CGM.getDataLayout().isBigEndian() && 347 !DirectTy->isStructTy()) { 348 Addr = CGF.Builder.CreateConstInBoundsByteGEP(Addr, SlotSize - DirectSize); 349 } 350 351 Addr = CGF.Builder.CreateElementBitCast(Addr, DirectTy); 352 return Addr; 353 } 354 355 /// Emit va_arg for a platform using the common void* representation, 356 /// where arguments are simply emitted in an array of slots on the stack. 357 /// 358 /// \param IsIndirect - Values of this type are passed indirectly. 359 /// \param ValueInfo - The size and alignment of this type, generally 360 /// computed with getContext().getTypeInfoInChars(ValueTy). 361 /// \param SlotSizeAndAlign - The size and alignment of a stack slot. 362 /// Each argument will be allocated to a multiple of this number of 363 /// slots, and all the slots will be aligned to this value. 364 /// \param AllowHigherAlign - The slot alignment is not a cap; 365 /// an argument type with an alignment greater than the slot size 366 /// will be emitted on a higher-alignment address, potentially 367 /// leaving one or more empty slots behind as padding. 368 static Address emitVoidPtrVAArg(CodeGenFunction &CGF, Address VAListAddr, 369 QualType ValueTy, bool IsIndirect, 370 TypeInfoChars ValueInfo, 371 CharUnits SlotSizeAndAlign, 372 bool AllowHigherAlign) { 373 // The size and alignment of the value that was passed directly. 374 CharUnits DirectSize, DirectAlign; 375 if (IsIndirect) { 376 DirectSize = CGF.getPointerSize(); 377 DirectAlign = CGF.getPointerAlign(); 378 } else { 379 DirectSize = ValueInfo.Width; 380 DirectAlign = ValueInfo.Align; 381 } 382 383 // Cast the address we've calculated to the right type. 384 llvm::Type *DirectTy = CGF.ConvertTypeForMem(ValueTy), *ElementTy = DirectTy; 385 if (IsIndirect) 386 DirectTy = DirectTy->getPointerTo(0); 387 388 Address Addr = 389 emitVoidPtrDirectVAArg(CGF, VAListAddr, DirectTy, DirectSize, DirectAlign, 390 SlotSizeAndAlign, AllowHigherAlign); 391 392 if (IsIndirect) { 393 Addr = Address(CGF.Builder.CreateLoad(Addr), ElementTy, ValueInfo.Align); 394 } 395 396 return Addr; 397 } 398 399 static Address complexTempStructure(CodeGenFunction &CGF, Address VAListAddr, 400 QualType Ty, CharUnits SlotSize, 401 CharUnits EltSize, const ComplexType *CTy) { 402 Address Addr = 403 emitVoidPtrDirectVAArg(CGF, VAListAddr, CGF.Int8Ty, SlotSize * 2, 404 SlotSize, SlotSize, /*AllowHigher*/ true); 405 406 Address RealAddr = Addr; 407 Address ImagAddr = RealAddr; 408 if (CGF.CGM.getDataLayout().isBigEndian()) { 409 RealAddr = 410 CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, SlotSize - EltSize); 411 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(ImagAddr, 412 2 * SlotSize - EltSize); 413 } else { 414 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, SlotSize); 415 } 416 417 llvm::Type *EltTy = CGF.ConvertTypeForMem(CTy->getElementType()); 418 RealAddr = CGF.Builder.CreateElementBitCast(RealAddr, EltTy); 419 ImagAddr = CGF.Builder.CreateElementBitCast(ImagAddr, EltTy); 420 llvm::Value *Real = CGF.Builder.CreateLoad(RealAddr, ".vareal"); 421 llvm::Value *Imag = CGF.Builder.CreateLoad(ImagAddr, ".vaimag"); 422 423 Address Temp = CGF.CreateMemTemp(Ty, "vacplx"); 424 CGF.EmitStoreOfComplex({Real, Imag}, CGF.MakeAddrLValue(Temp, Ty), 425 /*init*/ true); 426 return Temp; 427 } 428 429 static Address emitMergePHI(CodeGenFunction &CGF, 430 Address Addr1, llvm::BasicBlock *Block1, 431 Address Addr2, llvm::BasicBlock *Block2, 432 const llvm::Twine &Name = "") { 433 assert(Addr1.getType() == Addr2.getType()); 434 llvm::PHINode *PHI = CGF.Builder.CreatePHI(Addr1.getType(), 2, Name); 435 PHI->addIncoming(Addr1.getPointer(), Block1); 436 PHI->addIncoming(Addr2.getPointer(), Block2); 437 CharUnits Align = std::min(Addr1.getAlignment(), Addr2.getAlignment()); 438 return Address(PHI, Addr1.getElementType(), Align); 439 } 440 441 TargetCodeGenInfo::~TargetCodeGenInfo() = default; 442 443 // If someone can figure out a general rule for this, that would be great. 444 // It's probably just doomed to be platform-dependent, though. 445 unsigned TargetCodeGenInfo::getSizeOfUnwindException() const { 446 // Verified for: 447 // x86-64 FreeBSD, Linux, Darwin 448 // x86-32 FreeBSD, Linux, Darwin 449 // PowerPC Linux, Darwin 450 // ARM Darwin (*not* EABI) 451 // AArch64 Linux 452 return 32; 453 } 454 455 bool TargetCodeGenInfo::isNoProtoCallVariadic(const CallArgList &args, 456 const FunctionNoProtoType *fnType) const { 457 // The following conventions are known to require this to be false: 458 // x86_stdcall 459 // MIPS 460 // For everything else, we just prefer false unless we opt out. 461 return false; 462 } 463 464 void 465 TargetCodeGenInfo::getDependentLibraryOption(llvm::StringRef Lib, 466 llvm::SmallString<24> &Opt) const { 467 // This assumes the user is passing a library name like "rt" instead of a 468 // filename like "librt.a/so", and that they don't care whether it's static or 469 // dynamic. 470 Opt = "-l"; 471 Opt += Lib; 472 } 473 474 unsigned TargetCodeGenInfo::getOpenCLKernelCallingConv() const { 475 // OpenCL kernels are called via an explicit runtime API with arguments 476 // set with clSetKernelArg(), not as normal sub-functions. 477 // Return SPIR_KERNEL by default as the kernel calling convention to 478 // ensure the fingerprint is fixed such way that each OpenCL argument 479 // gets one matching argument in the produced kernel function argument 480 // list to enable feasible implementation of clSetKernelArg() with 481 // aggregates etc. In case we would use the default C calling conv here, 482 // clSetKernelArg() might break depending on the target-specific 483 // conventions; different targets might split structs passed as values 484 // to multiple function arguments etc. 485 return llvm::CallingConv::SPIR_KERNEL; 486 } 487 488 llvm::Constant *TargetCodeGenInfo::getNullPointer(const CodeGen::CodeGenModule &CGM, 489 llvm::PointerType *T, QualType QT) const { 490 return llvm::ConstantPointerNull::get(T); 491 } 492 493 LangAS TargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM, 494 const VarDecl *D) const { 495 assert(!CGM.getLangOpts().OpenCL && 496 !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) && 497 "Address space agnostic languages only"); 498 return D ? D->getType().getAddressSpace() : LangAS::Default; 499 } 500 501 llvm::Value *TargetCodeGenInfo::performAddrSpaceCast( 502 CodeGen::CodeGenFunction &CGF, llvm::Value *Src, LangAS SrcAddr, 503 LangAS DestAddr, llvm::Type *DestTy, bool isNonNull) const { 504 // Since target may map different address spaces in AST to the same address 505 // space, an address space conversion may end up as a bitcast. 506 if (auto *C = dyn_cast<llvm::Constant>(Src)) 507 return performAddrSpaceCast(CGF.CGM, C, SrcAddr, DestAddr, DestTy); 508 // Try to preserve the source's name to make IR more readable. 509 return CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( 510 Src, DestTy, Src->hasName() ? Src->getName() + ".ascast" : ""); 511 } 512 513 llvm::Constant * 514 TargetCodeGenInfo::performAddrSpaceCast(CodeGenModule &CGM, llvm::Constant *Src, 515 LangAS SrcAddr, LangAS DestAddr, 516 llvm::Type *DestTy) const { 517 // Since target may map different address spaces in AST to the same address 518 // space, an address space conversion may end up as a bitcast. 519 return llvm::ConstantExpr::getPointerCast(Src, DestTy); 520 } 521 522 llvm::SyncScope::ID 523 TargetCodeGenInfo::getLLVMSyncScopeID(const LangOptions &LangOpts, 524 SyncScope Scope, 525 llvm::AtomicOrdering Ordering, 526 llvm::LLVMContext &Ctx) const { 527 return Ctx.getOrInsertSyncScopeID(""); /* default sync scope */ 528 } 529 530 static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays); 531 532 /// isEmptyField - Return true iff a the field is "empty", that is it 533 /// is an unnamed bit-field or an (array of) empty record(s). 534 static bool isEmptyField(ASTContext &Context, const FieldDecl *FD, 535 bool AllowArrays) { 536 if (FD->isUnnamedBitfield()) 537 return true; 538 539 QualType FT = FD->getType(); 540 541 // Constant arrays of empty records count as empty, strip them off. 542 // Constant arrays of zero length always count as empty. 543 bool WasArray = false; 544 if (AllowArrays) 545 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) { 546 if (AT->getSize() == 0) 547 return true; 548 FT = AT->getElementType(); 549 // The [[no_unique_address]] special case below does not apply to 550 // arrays of C++ empty records, so we need to remember this fact. 551 WasArray = true; 552 } 553 554 const RecordType *RT = FT->getAs<RecordType>(); 555 if (!RT) 556 return false; 557 558 // C++ record fields are never empty, at least in the Itanium ABI. 559 // 560 // FIXME: We should use a predicate for whether this behavior is true in the 561 // current ABI. 562 // 563 // The exception to the above rule are fields marked with the 564 // [[no_unique_address]] attribute (since C++20). Those do count as empty 565 // according to the Itanium ABI. The exception applies only to records, 566 // not arrays of records, so we must also check whether we stripped off an 567 // array type above. 568 if (isa<CXXRecordDecl>(RT->getDecl()) && 569 (WasArray || !FD->hasAttr<NoUniqueAddressAttr>())) 570 return false; 571 572 return isEmptyRecord(Context, FT, AllowArrays); 573 } 574 575 /// isEmptyRecord - Return true iff a structure contains only empty 576 /// fields. Note that a structure with a flexible array member is not 577 /// considered empty. 578 static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) { 579 const RecordType *RT = T->getAs<RecordType>(); 580 if (!RT) 581 return false; 582 const RecordDecl *RD = RT->getDecl(); 583 if (RD->hasFlexibleArrayMember()) 584 return false; 585 586 // If this is a C++ record, check the bases first. 587 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 588 for (const auto &I : CXXRD->bases()) 589 if (!isEmptyRecord(Context, I.getType(), true)) 590 return false; 591 592 for (const auto *I : RD->fields()) 593 if (!isEmptyField(Context, I, AllowArrays)) 594 return false; 595 return true; 596 } 597 598 /// isSingleElementStruct - Determine if a structure is a "single 599 /// element struct", i.e. it has exactly one non-empty field or 600 /// exactly one field which is itself a single element 601 /// struct. Structures with flexible array members are never 602 /// considered single element structs. 603 /// 604 /// \return The field declaration for the single non-empty field, if 605 /// it exists. 606 static const Type *isSingleElementStruct(QualType T, ASTContext &Context) { 607 const RecordType *RT = T->getAs<RecordType>(); 608 if (!RT) 609 return nullptr; 610 611 const RecordDecl *RD = RT->getDecl(); 612 if (RD->hasFlexibleArrayMember()) 613 return nullptr; 614 615 const Type *Found = nullptr; 616 617 // If this is a C++ record, check the bases first. 618 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 619 for (const auto &I : CXXRD->bases()) { 620 // Ignore empty records. 621 if (isEmptyRecord(Context, I.getType(), true)) 622 continue; 623 624 // If we already found an element then this isn't a single-element struct. 625 if (Found) 626 return nullptr; 627 628 // If this is non-empty and not a single element struct, the composite 629 // cannot be a single element struct. 630 Found = isSingleElementStruct(I.getType(), Context); 631 if (!Found) 632 return nullptr; 633 } 634 } 635 636 // Check for single element. 637 for (const auto *FD : RD->fields()) { 638 QualType FT = FD->getType(); 639 640 // Ignore empty fields. 641 if (isEmptyField(Context, FD, true)) 642 continue; 643 644 // If we already found an element then this isn't a single-element 645 // struct. 646 if (Found) 647 return nullptr; 648 649 // Treat single element arrays as the element. 650 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) { 651 if (AT->getSize().getZExtValue() != 1) 652 break; 653 FT = AT->getElementType(); 654 } 655 656 if (!isAggregateTypeForABI(FT)) { 657 Found = FT.getTypePtr(); 658 } else { 659 Found = isSingleElementStruct(FT, Context); 660 if (!Found) 661 return nullptr; 662 } 663 } 664 665 // We don't consider a struct a single-element struct if it has 666 // padding beyond the element type. 667 if (Found && Context.getTypeSize(Found) != Context.getTypeSize(T)) 668 return nullptr; 669 670 return Found; 671 } 672 673 namespace { 674 Address EmitVAArgInstr(CodeGenFunction &CGF, Address VAListAddr, QualType Ty, 675 const ABIArgInfo &AI) { 676 // This default implementation defers to the llvm backend's va_arg 677 // instruction. It can handle only passing arguments directly 678 // (typically only handled in the backend for primitive types), or 679 // aggregates passed indirectly by pointer (NOTE: if the "byval" 680 // flag has ABI impact in the callee, this implementation cannot 681 // work.) 682 683 // Only a few cases are covered here at the moment -- those needed 684 // by the default abi. 685 llvm::Value *Val; 686 687 if (AI.isIndirect()) { 688 assert(!AI.getPaddingType() && 689 "Unexpected PaddingType seen in arginfo in generic VAArg emitter!"); 690 assert( 691 !AI.getIndirectRealign() && 692 "Unexpected IndirectRealign seen in arginfo in generic VAArg emitter!"); 693 694 auto TyInfo = CGF.getContext().getTypeInfoInChars(Ty); 695 CharUnits TyAlignForABI = TyInfo.Align; 696 697 llvm::Type *ElementTy = CGF.ConvertTypeForMem(Ty); 698 llvm::Type *BaseTy = llvm::PointerType::getUnqual(ElementTy); 699 llvm::Value *Addr = 700 CGF.Builder.CreateVAArg(VAListAddr.getPointer(), BaseTy); 701 return Address(Addr, ElementTy, TyAlignForABI); 702 } else { 703 assert((AI.isDirect() || AI.isExtend()) && 704 "Unexpected ArgInfo Kind in generic VAArg emitter!"); 705 706 assert(!AI.getInReg() && 707 "Unexpected InReg seen in arginfo in generic VAArg emitter!"); 708 assert(!AI.getPaddingType() && 709 "Unexpected PaddingType seen in arginfo in generic VAArg emitter!"); 710 assert(!AI.getDirectOffset() && 711 "Unexpected DirectOffset seen in arginfo in generic VAArg emitter!"); 712 assert(!AI.getCoerceToType() && 713 "Unexpected CoerceToType seen in arginfo in generic VAArg emitter!"); 714 715 Address Temp = CGF.CreateMemTemp(Ty, "varet"); 716 Val = CGF.Builder.CreateVAArg(VAListAddr.getPointer(), 717 CGF.ConvertTypeForMem(Ty)); 718 CGF.Builder.CreateStore(Val, Temp); 719 return Temp; 720 } 721 } 722 723 /// DefaultABIInfo - The default implementation for ABI specific 724 /// details. This implementation provides information which results in 725 /// self-consistent and sensible LLVM IR generation, but does not 726 /// conform to any particular ABI. 727 class DefaultABIInfo : public ABIInfo { 728 public: 729 DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {} 730 731 ABIArgInfo classifyReturnType(QualType RetTy) const; 732 ABIArgInfo classifyArgumentType(QualType RetTy) const; 733 734 void computeInfo(CGFunctionInfo &FI) const override { 735 if (!getCXXABI().classifyReturnType(FI)) 736 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 737 for (auto &I : FI.arguments()) 738 I.info = classifyArgumentType(I.type); 739 } 740 741 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 742 QualType Ty) const override { 743 return EmitVAArgInstr(CGF, VAListAddr, Ty, classifyArgumentType(Ty)); 744 } 745 }; 746 747 class DefaultTargetCodeGenInfo : public TargetCodeGenInfo { 748 public: 749 DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT) 750 : TargetCodeGenInfo(std::make_unique<DefaultABIInfo>(CGT)) {} 751 }; 752 753 ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const { 754 Ty = useFirstFieldIfTransparentUnion(Ty); 755 756 if (isAggregateTypeForABI(Ty)) { 757 // Records with non-trivial destructors/copy-constructors should not be 758 // passed by value. 759 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 760 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 761 762 return getNaturalAlignIndirect(Ty); 763 } 764 765 // Treat an enum type as its underlying type. 766 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 767 Ty = EnumTy->getDecl()->getIntegerType(); 768 769 ASTContext &Context = getContext(); 770 if (const auto *EIT = Ty->getAs<BitIntType>()) 771 if (EIT->getNumBits() > 772 Context.getTypeSize(Context.getTargetInfo().hasInt128Type() 773 ? Context.Int128Ty 774 : Context.LongLongTy)) 775 return getNaturalAlignIndirect(Ty); 776 777 return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty) 778 : ABIArgInfo::getDirect()); 779 } 780 781 ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const { 782 if (RetTy->isVoidType()) 783 return ABIArgInfo::getIgnore(); 784 785 if (isAggregateTypeForABI(RetTy)) 786 return getNaturalAlignIndirect(RetTy); 787 788 // Treat an enum type as its underlying type. 789 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 790 RetTy = EnumTy->getDecl()->getIntegerType(); 791 792 if (const auto *EIT = RetTy->getAs<BitIntType>()) 793 if (EIT->getNumBits() > 794 getContext().getTypeSize(getContext().getTargetInfo().hasInt128Type() 795 ? getContext().Int128Ty 796 : getContext().LongLongTy)) 797 return getNaturalAlignIndirect(RetTy); 798 799 return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy) 800 : ABIArgInfo::getDirect()); 801 } 802 803 //===----------------------------------------------------------------------===// 804 // WebAssembly ABI Implementation 805 // 806 // This is a very simple ABI that relies a lot on DefaultABIInfo. 807 //===----------------------------------------------------------------------===// 808 809 class WebAssemblyABIInfo final : public SwiftABIInfo { 810 public: 811 enum ABIKind { 812 MVP = 0, 813 ExperimentalMV = 1, 814 }; 815 816 private: 817 DefaultABIInfo defaultInfo; 818 ABIKind Kind; 819 820 public: 821 explicit WebAssemblyABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind) 822 : SwiftABIInfo(CGT), defaultInfo(CGT), Kind(Kind) {} 823 824 private: 825 ABIArgInfo classifyReturnType(QualType RetTy) const; 826 ABIArgInfo classifyArgumentType(QualType Ty) const; 827 828 // DefaultABIInfo's classifyReturnType and classifyArgumentType are 829 // non-virtual, but computeInfo and EmitVAArg are virtual, so we 830 // overload them. 831 void computeInfo(CGFunctionInfo &FI) const override { 832 if (!getCXXABI().classifyReturnType(FI)) 833 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 834 for (auto &Arg : FI.arguments()) 835 Arg.info = classifyArgumentType(Arg.type); 836 } 837 838 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 839 QualType Ty) const override; 840 841 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars, 842 bool asReturnValue) const override { 843 return occupiesMoreThan(CGT, scalars, /*total*/ 4); 844 } 845 846 bool isSwiftErrorInRegister() const override { 847 return false; 848 } 849 }; 850 851 class WebAssemblyTargetCodeGenInfo final : public TargetCodeGenInfo { 852 public: 853 explicit WebAssemblyTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, 854 WebAssemblyABIInfo::ABIKind K) 855 : TargetCodeGenInfo(std::make_unique<WebAssemblyABIInfo>(CGT, K)) {} 856 857 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 858 CodeGen::CodeGenModule &CGM) const override { 859 TargetCodeGenInfo::setTargetAttributes(D, GV, CGM); 860 if (const auto *FD = dyn_cast_or_null<FunctionDecl>(D)) { 861 if (const auto *Attr = FD->getAttr<WebAssemblyImportModuleAttr>()) { 862 llvm::Function *Fn = cast<llvm::Function>(GV); 863 llvm::AttrBuilder B(GV->getContext()); 864 B.addAttribute("wasm-import-module", Attr->getImportModule()); 865 Fn->addFnAttrs(B); 866 } 867 if (const auto *Attr = FD->getAttr<WebAssemblyImportNameAttr>()) { 868 llvm::Function *Fn = cast<llvm::Function>(GV); 869 llvm::AttrBuilder B(GV->getContext()); 870 B.addAttribute("wasm-import-name", Attr->getImportName()); 871 Fn->addFnAttrs(B); 872 } 873 if (const auto *Attr = FD->getAttr<WebAssemblyExportNameAttr>()) { 874 llvm::Function *Fn = cast<llvm::Function>(GV); 875 llvm::AttrBuilder B(GV->getContext()); 876 B.addAttribute("wasm-export-name", Attr->getExportName()); 877 Fn->addFnAttrs(B); 878 } 879 } 880 881 if (auto *FD = dyn_cast_or_null<FunctionDecl>(D)) { 882 llvm::Function *Fn = cast<llvm::Function>(GV); 883 if (!FD->doesThisDeclarationHaveABody() && !FD->hasPrototype()) 884 Fn->addFnAttr("no-prototype"); 885 } 886 } 887 }; 888 889 /// Classify argument of given type \p Ty. 890 ABIArgInfo WebAssemblyABIInfo::classifyArgumentType(QualType Ty) const { 891 Ty = useFirstFieldIfTransparentUnion(Ty); 892 893 if (isAggregateTypeForABI(Ty)) { 894 // Records with non-trivial destructors/copy-constructors should not be 895 // passed by value. 896 if (auto RAA = getRecordArgABI(Ty, getCXXABI())) 897 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 898 // Ignore empty structs/unions. 899 if (isEmptyRecord(getContext(), Ty, true)) 900 return ABIArgInfo::getIgnore(); 901 // Lower single-element structs to just pass a regular value. TODO: We 902 // could do reasonable-size multiple-element structs too, using getExpand(), 903 // though watch out for things like bitfields. 904 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext())) 905 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0))); 906 // For the experimental multivalue ABI, fully expand all other aggregates 907 if (Kind == ABIKind::ExperimentalMV) { 908 const RecordType *RT = Ty->getAs<RecordType>(); 909 assert(RT); 910 bool HasBitField = false; 911 for (auto *Field : RT->getDecl()->fields()) { 912 if (Field->isBitField()) { 913 HasBitField = true; 914 break; 915 } 916 } 917 if (!HasBitField) 918 return ABIArgInfo::getExpand(); 919 } 920 } 921 922 // Otherwise just do the default thing. 923 return defaultInfo.classifyArgumentType(Ty); 924 } 925 926 ABIArgInfo WebAssemblyABIInfo::classifyReturnType(QualType RetTy) const { 927 if (isAggregateTypeForABI(RetTy)) { 928 // Records with non-trivial destructors/copy-constructors should not be 929 // returned by value. 930 if (!getRecordArgABI(RetTy, getCXXABI())) { 931 // Ignore empty structs/unions. 932 if (isEmptyRecord(getContext(), RetTy, true)) 933 return ABIArgInfo::getIgnore(); 934 // Lower single-element structs to just return a regular value. TODO: We 935 // could do reasonable-size multiple-element structs too, using 936 // ABIArgInfo::getDirect(). 937 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext())) 938 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0))); 939 // For the experimental multivalue ABI, return all other aggregates 940 if (Kind == ABIKind::ExperimentalMV) 941 return ABIArgInfo::getDirect(); 942 } 943 } 944 945 // Otherwise just do the default thing. 946 return defaultInfo.classifyReturnType(RetTy); 947 } 948 949 Address WebAssemblyABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 950 QualType Ty) const { 951 bool IsIndirect = isAggregateTypeForABI(Ty) && 952 !isEmptyRecord(getContext(), Ty, true) && 953 !isSingleElementStruct(Ty, getContext()); 954 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, 955 getContext().getTypeInfoInChars(Ty), 956 CharUnits::fromQuantity(4), 957 /*AllowHigherAlign=*/true); 958 } 959 960 //===----------------------------------------------------------------------===// 961 // le32/PNaCl bitcode ABI Implementation 962 // 963 // This is a simplified version of the x86_32 ABI. Arguments and return values 964 // are always passed on the stack. 965 //===----------------------------------------------------------------------===// 966 967 class PNaClABIInfo : public ABIInfo { 968 public: 969 PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {} 970 971 ABIArgInfo classifyReturnType(QualType RetTy) const; 972 ABIArgInfo classifyArgumentType(QualType RetTy) const; 973 974 void computeInfo(CGFunctionInfo &FI) const override; 975 Address EmitVAArg(CodeGenFunction &CGF, 976 Address VAListAddr, QualType Ty) const override; 977 }; 978 979 class PNaClTargetCodeGenInfo : public TargetCodeGenInfo { 980 public: 981 PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT) 982 : TargetCodeGenInfo(std::make_unique<PNaClABIInfo>(CGT)) {} 983 }; 984 985 void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const { 986 if (!getCXXABI().classifyReturnType(FI)) 987 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 988 989 for (auto &I : FI.arguments()) 990 I.info = classifyArgumentType(I.type); 991 } 992 993 Address PNaClABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 994 QualType Ty) const { 995 // The PNaCL ABI is a bit odd, in that varargs don't use normal 996 // function classification. Structs get passed directly for varargs 997 // functions, through a rewriting transform in 998 // pnacl-llvm/lib/Transforms/NaCl/ExpandVarArgs.cpp, which allows 999 // this target to actually support a va_arg instructions with an 1000 // aggregate type, unlike other targets. 1001 return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect()); 1002 } 1003 1004 /// Classify argument of given type \p Ty. 1005 ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const { 1006 if (isAggregateTypeForABI(Ty)) { 1007 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 1008 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 1009 return getNaturalAlignIndirect(Ty); 1010 } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) { 1011 // Treat an enum type as its underlying type. 1012 Ty = EnumTy->getDecl()->getIntegerType(); 1013 } else if (Ty->isFloatingType()) { 1014 // Floating-point types don't go inreg. 1015 return ABIArgInfo::getDirect(); 1016 } else if (const auto *EIT = Ty->getAs<BitIntType>()) { 1017 // Treat bit-precise integers as integers if <= 64, otherwise pass 1018 // indirectly. 1019 if (EIT->getNumBits() > 64) 1020 return getNaturalAlignIndirect(Ty); 1021 return ABIArgInfo::getDirect(); 1022 } 1023 1024 return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty) 1025 : ABIArgInfo::getDirect()); 1026 } 1027 1028 ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const { 1029 if (RetTy->isVoidType()) 1030 return ABIArgInfo::getIgnore(); 1031 1032 // In the PNaCl ABI we always return records/structures on the stack. 1033 if (isAggregateTypeForABI(RetTy)) 1034 return getNaturalAlignIndirect(RetTy); 1035 1036 // Treat bit-precise integers as integers if <= 64, otherwise pass indirectly. 1037 if (const auto *EIT = RetTy->getAs<BitIntType>()) { 1038 if (EIT->getNumBits() > 64) 1039 return getNaturalAlignIndirect(RetTy); 1040 return ABIArgInfo::getDirect(); 1041 } 1042 1043 // Treat an enum type as its underlying type. 1044 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 1045 RetTy = EnumTy->getDecl()->getIntegerType(); 1046 1047 return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy) 1048 : ABIArgInfo::getDirect()); 1049 } 1050 1051 /// IsX86_MMXType - Return true if this is an MMX type. 1052 bool IsX86_MMXType(llvm::Type *IRType) { 1053 // Return true if the type is an MMX type <2 x i32>, <4 x i16>, or <8 x i8>. 1054 return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 && 1055 cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() && 1056 IRType->getScalarSizeInBits() != 64; 1057 } 1058 1059 static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF, 1060 StringRef Constraint, 1061 llvm::Type* Ty) { 1062 bool IsMMXCons = llvm::StringSwitch<bool>(Constraint) 1063 .Cases("y", "&y", "^Ym", true) 1064 .Default(false); 1065 if (IsMMXCons && Ty->isVectorTy()) { 1066 if (cast<llvm::VectorType>(Ty)->getPrimitiveSizeInBits().getFixedSize() != 1067 64) { 1068 // Invalid MMX constraint 1069 return nullptr; 1070 } 1071 1072 return llvm::Type::getX86_MMXTy(CGF.getLLVMContext()); 1073 } 1074 1075 // No operation needed 1076 return Ty; 1077 } 1078 1079 /// Returns true if this type can be passed in SSE registers with the 1080 /// X86_VectorCall calling convention. Shared between x86_32 and x86_64. 1081 static bool isX86VectorTypeForVectorCall(ASTContext &Context, QualType Ty) { 1082 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) { 1083 if (BT->isFloatingPoint() && BT->getKind() != BuiltinType::Half) { 1084 if (BT->getKind() == BuiltinType::LongDouble) { 1085 if (&Context.getTargetInfo().getLongDoubleFormat() == 1086 &llvm::APFloat::x87DoubleExtended()) 1087 return false; 1088 } 1089 return true; 1090 } 1091 } else if (const VectorType *VT = Ty->getAs<VectorType>()) { 1092 // vectorcall can pass XMM, YMM, and ZMM vectors. We don't pass SSE1 MMX 1093 // registers specially. 1094 unsigned VecSize = Context.getTypeSize(VT); 1095 if (VecSize == 128 || VecSize == 256 || VecSize == 512) 1096 return true; 1097 } 1098 return false; 1099 } 1100 1101 /// Returns true if this aggregate is small enough to be passed in SSE registers 1102 /// in the X86_VectorCall calling convention. Shared between x86_32 and x86_64. 1103 static bool isX86VectorCallAggregateSmallEnough(uint64_t NumMembers) { 1104 return NumMembers <= 4; 1105 } 1106 1107 /// Returns a Homogeneous Vector Aggregate ABIArgInfo, used in X86. 1108 static ABIArgInfo getDirectX86Hva(llvm::Type* T = nullptr) { 1109 auto AI = ABIArgInfo::getDirect(T); 1110 AI.setInReg(true); 1111 AI.setCanBeFlattened(false); 1112 return AI; 1113 } 1114 1115 //===----------------------------------------------------------------------===// 1116 // X86-32 ABI Implementation 1117 //===----------------------------------------------------------------------===// 1118 1119 /// Similar to llvm::CCState, but for Clang. 1120 struct CCState { 1121 CCState(CGFunctionInfo &FI) 1122 : IsPreassigned(FI.arg_size()), CC(FI.getCallingConvention()) {} 1123 1124 llvm::SmallBitVector IsPreassigned; 1125 unsigned CC = CallingConv::CC_C; 1126 unsigned FreeRegs = 0; 1127 unsigned FreeSSERegs = 0; 1128 }; 1129 1130 /// X86_32ABIInfo - The X86-32 ABI information. 1131 class X86_32ABIInfo : public SwiftABIInfo { 1132 enum Class { 1133 Integer, 1134 Float 1135 }; 1136 1137 static const unsigned MinABIStackAlignInBytes = 4; 1138 1139 bool IsDarwinVectorABI; 1140 bool IsRetSmallStructInRegABI; 1141 bool IsWin32StructABI; 1142 bool IsSoftFloatABI; 1143 bool IsMCUABI; 1144 bool IsLinuxABI; 1145 unsigned DefaultNumRegisterParameters; 1146 1147 static bool isRegisterSize(unsigned Size) { 1148 return (Size == 8 || Size == 16 || Size == 32 || Size == 64); 1149 } 1150 1151 bool isHomogeneousAggregateBaseType(QualType Ty) const override { 1152 // FIXME: Assumes vectorcall is in use. 1153 return isX86VectorTypeForVectorCall(getContext(), Ty); 1154 } 1155 1156 bool isHomogeneousAggregateSmallEnough(const Type *Ty, 1157 uint64_t NumMembers) const override { 1158 // FIXME: Assumes vectorcall is in use. 1159 return isX86VectorCallAggregateSmallEnough(NumMembers); 1160 } 1161 1162 bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context) const; 1163 1164 /// getIndirectResult - Give a source type \arg Ty, return a suitable result 1165 /// such that the argument will be passed in memory. 1166 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const; 1167 1168 ABIArgInfo getIndirectReturnResult(QualType Ty, CCState &State) const; 1169 1170 /// Return the alignment to use for the given type on the stack. 1171 unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const; 1172 1173 Class classify(QualType Ty) const; 1174 ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const; 1175 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const; 1176 1177 /// Updates the number of available free registers, returns 1178 /// true if any registers were allocated. 1179 bool updateFreeRegs(QualType Ty, CCState &State) const; 1180 1181 bool shouldAggregateUseDirect(QualType Ty, CCState &State, bool &InReg, 1182 bool &NeedsPadding) const; 1183 bool shouldPrimitiveUseInReg(QualType Ty, CCState &State) const; 1184 1185 bool canExpandIndirectArgument(QualType Ty) const; 1186 1187 /// Rewrite the function info so that all memory arguments use 1188 /// inalloca. 1189 void rewriteWithInAlloca(CGFunctionInfo &FI) const; 1190 1191 void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields, 1192 CharUnits &StackOffset, ABIArgInfo &Info, 1193 QualType Type) const; 1194 void runVectorCallFirstPass(CGFunctionInfo &FI, CCState &State) const; 1195 1196 public: 1197 1198 void computeInfo(CGFunctionInfo &FI) const override; 1199 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 1200 QualType Ty) const override; 1201 1202 X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI, 1203 bool RetSmallStructInRegABI, bool Win32StructABI, 1204 unsigned NumRegisterParameters, bool SoftFloatABI) 1205 : SwiftABIInfo(CGT), IsDarwinVectorABI(DarwinVectorABI), 1206 IsRetSmallStructInRegABI(RetSmallStructInRegABI), 1207 IsWin32StructABI(Win32StructABI), IsSoftFloatABI(SoftFloatABI), 1208 IsMCUABI(CGT.getTarget().getTriple().isOSIAMCU()), 1209 IsLinuxABI(CGT.getTarget().getTriple().isOSLinux() || 1210 CGT.getTarget().getTriple().isOSCygMing()), 1211 DefaultNumRegisterParameters(NumRegisterParameters) {} 1212 1213 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars, 1214 bool asReturnValue) const override { 1215 // LLVM's x86-32 lowering currently only assigns up to three 1216 // integer registers and three fp registers. Oddly, it'll use up to 1217 // four vector registers for vectors, but those can overlap with the 1218 // scalar registers. 1219 return occupiesMoreThan(CGT, scalars, /*total*/ 3); 1220 } 1221 1222 bool isSwiftErrorInRegister() const override { 1223 // x86-32 lowering does not support passing swifterror in a register. 1224 return false; 1225 } 1226 }; 1227 1228 class X86_32TargetCodeGenInfo : public TargetCodeGenInfo { 1229 public: 1230 X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI, 1231 bool RetSmallStructInRegABI, bool Win32StructABI, 1232 unsigned NumRegisterParameters, bool SoftFloatABI) 1233 : TargetCodeGenInfo(std::make_unique<X86_32ABIInfo>( 1234 CGT, DarwinVectorABI, RetSmallStructInRegABI, Win32StructABI, 1235 NumRegisterParameters, SoftFloatABI)) {} 1236 1237 static bool isStructReturnInRegABI( 1238 const llvm::Triple &Triple, const CodeGenOptions &Opts); 1239 1240 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 1241 CodeGen::CodeGenModule &CGM) const override; 1242 1243 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override { 1244 // Darwin uses different dwarf register numbers for EH. 1245 if (CGM.getTarget().getTriple().isOSDarwin()) return 5; 1246 return 4; 1247 } 1248 1249 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 1250 llvm::Value *Address) const override; 1251 1252 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF, 1253 StringRef Constraint, 1254 llvm::Type* Ty) const override { 1255 return X86AdjustInlineAsmType(CGF, Constraint, Ty); 1256 } 1257 1258 void addReturnRegisterOutputs(CodeGenFunction &CGF, LValue ReturnValue, 1259 std::string &Constraints, 1260 std::vector<llvm::Type *> &ResultRegTypes, 1261 std::vector<llvm::Type *> &ResultTruncRegTypes, 1262 std::vector<LValue> &ResultRegDests, 1263 std::string &AsmString, 1264 unsigned NumOutputs) const override; 1265 1266 llvm::Constant * 1267 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override { 1268 unsigned Sig = (0xeb << 0) | // jmp rel8 1269 (0x06 << 8) | // .+0x08 1270 ('v' << 16) | 1271 ('2' << 24); 1272 return llvm::ConstantInt::get(CGM.Int32Ty, Sig); 1273 } 1274 1275 StringRef getARCRetainAutoreleasedReturnValueMarker() const override { 1276 return "movl\t%ebp, %ebp" 1277 "\t\t// marker for objc_retainAutoreleaseReturnValue"; 1278 } 1279 }; 1280 1281 } 1282 1283 /// Rewrite input constraint references after adding some output constraints. 1284 /// In the case where there is one output and one input and we add one output, 1285 /// we need to replace all operand references greater than or equal to 1: 1286 /// mov $0, $1 1287 /// mov eax, $1 1288 /// The result will be: 1289 /// mov $0, $2 1290 /// mov eax, $2 1291 static void rewriteInputConstraintReferences(unsigned FirstIn, 1292 unsigned NumNewOuts, 1293 std::string &AsmString) { 1294 std::string Buf; 1295 llvm::raw_string_ostream OS(Buf); 1296 size_t Pos = 0; 1297 while (Pos < AsmString.size()) { 1298 size_t DollarStart = AsmString.find('$', Pos); 1299 if (DollarStart == std::string::npos) 1300 DollarStart = AsmString.size(); 1301 size_t DollarEnd = AsmString.find_first_not_of('$', DollarStart); 1302 if (DollarEnd == std::string::npos) 1303 DollarEnd = AsmString.size(); 1304 OS << StringRef(&AsmString[Pos], DollarEnd - Pos); 1305 Pos = DollarEnd; 1306 size_t NumDollars = DollarEnd - DollarStart; 1307 if (NumDollars % 2 != 0 && Pos < AsmString.size()) { 1308 // We have an operand reference. 1309 size_t DigitStart = Pos; 1310 if (AsmString[DigitStart] == '{') { 1311 OS << '{'; 1312 ++DigitStart; 1313 } 1314 size_t DigitEnd = AsmString.find_first_not_of("0123456789", DigitStart); 1315 if (DigitEnd == std::string::npos) 1316 DigitEnd = AsmString.size(); 1317 StringRef OperandStr(&AsmString[DigitStart], DigitEnd - DigitStart); 1318 unsigned OperandIndex; 1319 if (!OperandStr.getAsInteger(10, OperandIndex)) { 1320 if (OperandIndex >= FirstIn) 1321 OperandIndex += NumNewOuts; 1322 OS << OperandIndex; 1323 } else { 1324 OS << OperandStr; 1325 } 1326 Pos = DigitEnd; 1327 } 1328 } 1329 AsmString = std::move(OS.str()); 1330 } 1331 1332 /// Add output constraints for EAX:EDX because they are return registers. 1333 void X86_32TargetCodeGenInfo::addReturnRegisterOutputs( 1334 CodeGenFunction &CGF, LValue ReturnSlot, std::string &Constraints, 1335 std::vector<llvm::Type *> &ResultRegTypes, 1336 std::vector<llvm::Type *> &ResultTruncRegTypes, 1337 std::vector<LValue> &ResultRegDests, std::string &AsmString, 1338 unsigned NumOutputs) const { 1339 uint64_t RetWidth = CGF.getContext().getTypeSize(ReturnSlot.getType()); 1340 1341 // Use the EAX constraint if the width is 32 or smaller and EAX:EDX if it is 1342 // larger. 1343 if (!Constraints.empty()) 1344 Constraints += ','; 1345 if (RetWidth <= 32) { 1346 Constraints += "={eax}"; 1347 ResultRegTypes.push_back(CGF.Int32Ty); 1348 } else { 1349 // Use the 'A' constraint for EAX:EDX. 1350 Constraints += "=A"; 1351 ResultRegTypes.push_back(CGF.Int64Ty); 1352 } 1353 1354 // Truncate EAX or EAX:EDX to an integer of the appropriate size. 1355 llvm::Type *CoerceTy = llvm::IntegerType::get(CGF.getLLVMContext(), RetWidth); 1356 ResultTruncRegTypes.push_back(CoerceTy); 1357 1358 // Coerce the integer by bitcasting the return slot pointer. 1359 ReturnSlot.setAddress( 1360 CGF.Builder.CreateElementBitCast(ReturnSlot.getAddress(CGF), CoerceTy)); 1361 ResultRegDests.push_back(ReturnSlot); 1362 1363 rewriteInputConstraintReferences(NumOutputs, 1, AsmString); 1364 } 1365 1366 /// shouldReturnTypeInRegister - Determine if the given type should be 1367 /// returned in a register (for the Darwin and MCU ABI). 1368 bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty, 1369 ASTContext &Context) const { 1370 uint64_t Size = Context.getTypeSize(Ty); 1371 1372 // For i386, type must be register sized. 1373 // For the MCU ABI, it only needs to be <= 8-byte 1374 if ((IsMCUABI && Size > 64) || (!IsMCUABI && !isRegisterSize(Size))) 1375 return false; 1376 1377 if (Ty->isVectorType()) { 1378 // 64- and 128- bit vectors inside structures are not returned in 1379 // registers. 1380 if (Size == 64 || Size == 128) 1381 return false; 1382 1383 return true; 1384 } 1385 1386 // If this is a builtin, pointer, enum, complex type, member pointer, or 1387 // member function pointer it is ok. 1388 if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() || 1389 Ty->isAnyComplexType() || Ty->isEnumeralType() || 1390 Ty->isBlockPointerType() || Ty->isMemberPointerType()) 1391 return true; 1392 1393 // Arrays are treated like records. 1394 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) 1395 return shouldReturnTypeInRegister(AT->getElementType(), Context); 1396 1397 // Otherwise, it must be a record type. 1398 const RecordType *RT = Ty->getAs<RecordType>(); 1399 if (!RT) return false; 1400 1401 // FIXME: Traverse bases here too. 1402 1403 // Structure types are passed in register if all fields would be 1404 // passed in a register. 1405 for (const auto *FD : RT->getDecl()->fields()) { 1406 // Empty fields are ignored. 1407 if (isEmptyField(Context, FD, true)) 1408 continue; 1409 1410 // Check fields recursively. 1411 if (!shouldReturnTypeInRegister(FD->getType(), Context)) 1412 return false; 1413 } 1414 return true; 1415 } 1416 1417 static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) { 1418 // Treat complex types as the element type. 1419 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) 1420 Ty = CTy->getElementType(); 1421 1422 // Check for a type which we know has a simple scalar argument-passing 1423 // convention without any padding. (We're specifically looking for 32 1424 // and 64-bit integer and integer-equivalents, float, and double.) 1425 if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() && 1426 !Ty->isEnumeralType() && !Ty->isBlockPointerType()) 1427 return false; 1428 1429 uint64_t Size = Context.getTypeSize(Ty); 1430 return Size == 32 || Size == 64; 1431 } 1432 1433 static bool addFieldSizes(ASTContext &Context, const RecordDecl *RD, 1434 uint64_t &Size) { 1435 for (const auto *FD : RD->fields()) { 1436 // Scalar arguments on the stack get 4 byte alignment on x86. If the 1437 // argument is smaller than 32-bits, expanding the struct will create 1438 // alignment padding. 1439 if (!is32Or64BitBasicType(FD->getType(), Context)) 1440 return false; 1441 1442 // FIXME: Reject bit-fields wholesale; there are two problems, we don't know 1443 // how to expand them yet, and the predicate for telling if a bitfield still 1444 // counts as "basic" is more complicated than what we were doing previously. 1445 if (FD->isBitField()) 1446 return false; 1447 1448 Size += Context.getTypeSize(FD->getType()); 1449 } 1450 return true; 1451 } 1452 1453 static bool addBaseAndFieldSizes(ASTContext &Context, const CXXRecordDecl *RD, 1454 uint64_t &Size) { 1455 // Don't do this if there are any non-empty bases. 1456 for (const CXXBaseSpecifier &Base : RD->bases()) { 1457 if (!addBaseAndFieldSizes(Context, Base.getType()->getAsCXXRecordDecl(), 1458 Size)) 1459 return false; 1460 } 1461 if (!addFieldSizes(Context, RD, Size)) 1462 return false; 1463 return true; 1464 } 1465 1466 /// Test whether an argument type which is to be passed indirectly (on the 1467 /// stack) would have the equivalent layout if it was expanded into separate 1468 /// arguments. If so, we prefer to do the latter to avoid inhibiting 1469 /// optimizations. 1470 bool X86_32ABIInfo::canExpandIndirectArgument(QualType Ty) const { 1471 // We can only expand structure types. 1472 const RecordType *RT = Ty->getAs<RecordType>(); 1473 if (!RT) 1474 return false; 1475 const RecordDecl *RD = RT->getDecl(); 1476 uint64_t Size = 0; 1477 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 1478 if (!IsWin32StructABI) { 1479 // On non-Windows, we have to conservatively match our old bitcode 1480 // prototypes in order to be ABI-compatible at the bitcode level. 1481 if (!CXXRD->isCLike()) 1482 return false; 1483 } else { 1484 // Don't do this for dynamic classes. 1485 if (CXXRD->isDynamicClass()) 1486 return false; 1487 } 1488 if (!addBaseAndFieldSizes(getContext(), CXXRD, Size)) 1489 return false; 1490 } else { 1491 if (!addFieldSizes(getContext(), RD, Size)) 1492 return false; 1493 } 1494 1495 // We can do this if there was no alignment padding. 1496 return Size == getContext().getTypeSize(Ty); 1497 } 1498 1499 ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(QualType RetTy, CCState &State) const { 1500 // If the return value is indirect, then the hidden argument is consuming one 1501 // integer register. 1502 if (State.FreeRegs) { 1503 --State.FreeRegs; 1504 if (!IsMCUABI) 1505 return getNaturalAlignIndirectInReg(RetTy); 1506 } 1507 return getNaturalAlignIndirect(RetTy, /*ByVal=*/false); 1508 } 1509 1510 ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy, 1511 CCState &State) const { 1512 if (RetTy->isVoidType()) 1513 return ABIArgInfo::getIgnore(); 1514 1515 const Type *Base = nullptr; 1516 uint64_t NumElts = 0; 1517 if ((State.CC == llvm::CallingConv::X86_VectorCall || 1518 State.CC == llvm::CallingConv::X86_RegCall) && 1519 isHomogeneousAggregate(RetTy, Base, NumElts)) { 1520 // The LLVM struct type for such an aggregate should lower properly. 1521 return ABIArgInfo::getDirect(); 1522 } 1523 1524 if (const VectorType *VT = RetTy->getAs<VectorType>()) { 1525 // On Darwin, some vectors are returned in registers. 1526 if (IsDarwinVectorABI) { 1527 uint64_t Size = getContext().getTypeSize(RetTy); 1528 1529 // 128-bit vectors are a special case; they are returned in 1530 // registers and we need to make sure to pick a type the LLVM 1531 // backend will like. 1532 if (Size == 128) 1533 return ABIArgInfo::getDirect(llvm::FixedVectorType::get( 1534 llvm::Type::getInt64Ty(getVMContext()), 2)); 1535 1536 // Always return in register if it fits in a general purpose 1537 // register, or if it is 64 bits and has a single element. 1538 if ((Size == 8 || Size == 16 || Size == 32) || 1539 (Size == 64 && VT->getNumElements() == 1)) 1540 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 1541 Size)); 1542 1543 return getIndirectReturnResult(RetTy, State); 1544 } 1545 1546 return ABIArgInfo::getDirect(); 1547 } 1548 1549 if (isAggregateTypeForABI(RetTy)) { 1550 if (const RecordType *RT = RetTy->getAs<RecordType>()) { 1551 // Structures with flexible arrays are always indirect. 1552 if (RT->getDecl()->hasFlexibleArrayMember()) 1553 return getIndirectReturnResult(RetTy, State); 1554 } 1555 1556 // If specified, structs and unions are always indirect. 1557 if (!IsRetSmallStructInRegABI && !RetTy->isAnyComplexType()) 1558 return getIndirectReturnResult(RetTy, State); 1559 1560 // Ignore empty structs/unions. 1561 if (isEmptyRecord(getContext(), RetTy, true)) 1562 return ABIArgInfo::getIgnore(); 1563 1564 // Return complex of _Float16 as <2 x half> so the backend will use xmm0. 1565 if (const ComplexType *CT = RetTy->getAs<ComplexType>()) { 1566 QualType ET = getContext().getCanonicalType(CT->getElementType()); 1567 if (ET->isFloat16Type()) 1568 return ABIArgInfo::getDirect(llvm::FixedVectorType::get( 1569 llvm::Type::getHalfTy(getVMContext()), 2)); 1570 } 1571 1572 // Small structures which are register sized are generally returned 1573 // in a register. 1574 if (shouldReturnTypeInRegister(RetTy, getContext())) { 1575 uint64_t Size = getContext().getTypeSize(RetTy); 1576 1577 // As a special-case, if the struct is a "single-element" struct, and 1578 // the field is of type "float" or "double", return it in a 1579 // floating-point register. (MSVC does not apply this special case.) 1580 // We apply a similar transformation for pointer types to improve the 1581 // quality of the generated IR. 1582 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext())) 1583 if ((!IsWin32StructABI && SeltTy->isRealFloatingType()) 1584 || SeltTy->hasPointerRepresentation()) 1585 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0))); 1586 1587 // FIXME: We should be able to narrow this integer in cases with dead 1588 // padding. 1589 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size)); 1590 } 1591 1592 return getIndirectReturnResult(RetTy, State); 1593 } 1594 1595 // Treat an enum type as its underlying type. 1596 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 1597 RetTy = EnumTy->getDecl()->getIntegerType(); 1598 1599 if (const auto *EIT = RetTy->getAs<BitIntType>()) 1600 if (EIT->getNumBits() > 64) 1601 return getIndirectReturnResult(RetTy, State); 1602 1603 return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy) 1604 : ABIArgInfo::getDirect()); 1605 } 1606 1607 static bool isSIMDVectorType(ASTContext &Context, QualType Ty) { 1608 return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128; 1609 } 1610 1611 static bool isRecordWithSIMDVectorType(ASTContext &Context, QualType Ty) { 1612 const RecordType *RT = Ty->getAs<RecordType>(); 1613 if (!RT) 1614 return false; 1615 const RecordDecl *RD = RT->getDecl(); 1616 1617 // If this is a C++ record, check the bases first. 1618 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 1619 for (const auto &I : CXXRD->bases()) 1620 if (!isRecordWithSIMDVectorType(Context, I.getType())) 1621 return false; 1622 1623 for (const auto *i : RD->fields()) { 1624 QualType FT = i->getType(); 1625 1626 if (isSIMDVectorType(Context, FT)) 1627 return true; 1628 1629 if (isRecordWithSIMDVectorType(Context, FT)) 1630 return true; 1631 } 1632 1633 return false; 1634 } 1635 1636 unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty, 1637 unsigned Align) const { 1638 // Otherwise, if the alignment is less than or equal to the minimum ABI 1639 // alignment, just use the default; the backend will handle this. 1640 if (Align <= MinABIStackAlignInBytes) 1641 return 0; // Use default alignment. 1642 1643 if (IsLinuxABI) { 1644 // Exclude other System V OS (e.g Darwin, PS4 and FreeBSD) since we don't 1645 // want to spend any effort dealing with the ramifications of ABI breaks. 1646 // 1647 // If the vector type is __m128/__m256/__m512, return the default alignment. 1648 if (Ty->isVectorType() && (Align == 16 || Align == 32 || Align == 64)) 1649 return Align; 1650 } 1651 // On non-Darwin, the stack type alignment is always 4. 1652 if (!IsDarwinVectorABI) { 1653 // Set explicit alignment, since we may need to realign the top. 1654 return MinABIStackAlignInBytes; 1655 } 1656 1657 // Otherwise, if the type contains an SSE vector type, the alignment is 16. 1658 if (Align >= 16 && (isSIMDVectorType(getContext(), Ty) || 1659 isRecordWithSIMDVectorType(getContext(), Ty))) 1660 return 16; 1661 1662 return MinABIStackAlignInBytes; 1663 } 1664 1665 ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal, 1666 CCState &State) const { 1667 if (!ByVal) { 1668 if (State.FreeRegs) { 1669 --State.FreeRegs; // Non-byval indirects just use one pointer. 1670 if (!IsMCUABI) 1671 return getNaturalAlignIndirectInReg(Ty); 1672 } 1673 return getNaturalAlignIndirect(Ty, false); 1674 } 1675 1676 // Compute the byval alignment. 1677 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8; 1678 unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign); 1679 if (StackAlign == 0) 1680 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true); 1681 1682 // If the stack alignment is less than the type alignment, realign the 1683 // argument. 1684 bool Realign = TypeAlign > StackAlign; 1685 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(StackAlign), 1686 /*ByVal=*/true, Realign); 1687 } 1688 1689 X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const { 1690 const Type *T = isSingleElementStruct(Ty, getContext()); 1691 if (!T) 1692 T = Ty.getTypePtr(); 1693 1694 if (const BuiltinType *BT = T->getAs<BuiltinType>()) { 1695 BuiltinType::Kind K = BT->getKind(); 1696 if (K == BuiltinType::Float || K == BuiltinType::Double) 1697 return Float; 1698 } 1699 return Integer; 1700 } 1701 1702 bool X86_32ABIInfo::updateFreeRegs(QualType Ty, CCState &State) const { 1703 if (!IsSoftFloatABI) { 1704 Class C = classify(Ty); 1705 if (C == Float) 1706 return false; 1707 } 1708 1709 unsigned Size = getContext().getTypeSize(Ty); 1710 unsigned SizeInRegs = (Size + 31) / 32; 1711 1712 if (SizeInRegs == 0) 1713 return false; 1714 1715 if (!IsMCUABI) { 1716 if (SizeInRegs > State.FreeRegs) { 1717 State.FreeRegs = 0; 1718 return false; 1719 } 1720 } else { 1721 // The MCU psABI allows passing parameters in-reg even if there are 1722 // earlier parameters that are passed on the stack. Also, 1723 // it does not allow passing >8-byte structs in-register, 1724 // even if there are 3 free registers available. 1725 if (SizeInRegs > State.FreeRegs || SizeInRegs > 2) 1726 return false; 1727 } 1728 1729 State.FreeRegs -= SizeInRegs; 1730 return true; 1731 } 1732 1733 bool X86_32ABIInfo::shouldAggregateUseDirect(QualType Ty, CCState &State, 1734 bool &InReg, 1735 bool &NeedsPadding) const { 1736 // On Windows, aggregates other than HFAs are never passed in registers, and 1737 // they do not consume register slots. Homogenous floating-point aggregates 1738 // (HFAs) have already been dealt with at this point. 1739 if (IsWin32StructABI && isAggregateTypeForABI(Ty)) 1740 return false; 1741 1742 NeedsPadding = false; 1743 InReg = !IsMCUABI; 1744 1745 if (!updateFreeRegs(Ty, State)) 1746 return false; 1747 1748 if (IsMCUABI) 1749 return true; 1750 1751 if (State.CC == llvm::CallingConv::X86_FastCall || 1752 State.CC == llvm::CallingConv::X86_VectorCall || 1753 State.CC == llvm::CallingConv::X86_RegCall) { 1754 if (getContext().getTypeSize(Ty) <= 32 && State.FreeRegs) 1755 NeedsPadding = true; 1756 1757 return false; 1758 } 1759 1760 return true; 1761 } 1762 1763 bool X86_32ABIInfo::shouldPrimitiveUseInReg(QualType Ty, CCState &State) const { 1764 if (!updateFreeRegs(Ty, State)) 1765 return false; 1766 1767 if (IsMCUABI) 1768 return false; 1769 1770 if (State.CC == llvm::CallingConv::X86_FastCall || 1771 State.CC == llvm::CallingConv::X86_VectorCall || 1772 State.CC == llvm::CallingConv::X86_RegCall) { 1773 if (getContext().getTypeSize(Ty) > 32) 1774 return false; 1775 1776 return (Ty->isIntegralOrEnumerationType() || Ty->isPointerType() || 1777 Ty->isReferenceType()); 1778 } 1779 1780 return true; 1781 } 1782 1783 void X86_32ABIInfo::runVectorCallFirstPass(CGFunctionInfo &FI, CCState &State) const { 1784 // Vectorcall x86 works subtly different than in x64, so the format is 1785 // a bit different than the x64 version. First, all vector types (not HVAs) 1786 // are assigned, with the first 6 ending up in the [XYZ]MM0-5 registers. 1787 // This differs from the x64 implementation, where the first 6 by INDEX get 1788 // registers. 1789 // In the second pass over the arguments, HVAs are passed in the remaining 1790 // vector registers if possible, or indirectly by address. The address will be 1791 // passed in ECX/EDX if available. Any other arguments are passed according to 1792 // the usual fastcall rules. 1793 MutableArrayRef<CGFunctionInfoArgInfo> Args = FI.arguments(); 1794 for (int I = 0, E = Args.size(); I < E; ++I) { 1795 const Type *Base = nullptr; 1796 uint64_t NumElts = 0; 1797 const QualType &Ty = Args[I].type; 1798 if ((Ty->isVectorType() || Ty->isBuiltinType()) && 1799 isHomogeneousAggregate(Ty, Base, NumElts)) { 1800 if (State.FreeSSERegs >= NumElts) { 1801 State.FreeSSERegs -= NumElts; 1802 Args[I].info = ABIArgInfo::getDirectInReg(); 1803 State.IsPreassigned.set(I); 1804 } 1805 } 1806 } 1807 } 1808 1809 ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty, 1810 CCState &State) const { 1811 // FIXME: Set alignment on indirect arguments. 1812 bool IsFastCall = State.CC == llvm::CallingConv::X86_FastCall; 1813 bool IsRegCall = State.CC == llvm::CallingConv::X86_RegCall; 1814 bool IsVectorCall = State.CC == llvm::CallingConv::X86_VectorCall; 1815 1816 Ty = useFirstFieldIfTransparentUnion(Ty); 1817 TypeInfo TI = getContext().getTypeInfo(Ty); 1818 1819 // Check with the C++ ABI first. 1820 const RecordType *RT = Ty->getAs<RecordType>(); 1821 if (RT) { 1822 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()); 1823 if (RAA == CGCXXABI::RAA_Indirect) { 1824 return getIndirectResult(Ty, false, State); 1825 } else if (RAA == CGCXXABI::RAA_DirectInMemory) { 1826 // The field index doesn't matter, we'll fix it up later. 1827 return ABIArgInfo::getInAlloca(/*FieldIndex=*/0); 1828 } 1829 } 1830 1831 // Regcall uses the concept of a homogenous vector aggregate, similar 1832 // to other targets. 1833 const Type *Base = nullptr; 1834 uint64_t NumElts = 0; 1835 if ((IsRegCall || IsVectorCall) && 1836 isHomogeneousAggregate(Ty, Base, NumElts)) { 1837 if (State.FreeSSERegs >= NumElts) { 1838 State.FreeSSERegs -= NumElts; 1839 1840 // Vectorcall passes HVAs directly and does not flatten them, but regcall 1841 // does. 1842 if (IsVectorCall) 1843 return getDirectX86Hva(); 1844 1845 if (Ty->isBuiltinType() || Ty->isVectorType()) 1846 return ABIArgInfo::getDirect(); 1847 return ABIArgInfo::getExpand(); 1848 } 1849 return getIndirectResult(Ty, /*ByVal=*/false, State); 1850 } 1851 1852 if (isAggregateTypeForABI(Ty)) { 1853 // Structures with flexible arrays are always indirect. 1854 // FIXME: This should not be byval! 1855 if (RT && RT->getDecl()->hasFlexibleArrayMember()) 1856 return getIndirectResult(Ty, true, State); 1857 1858 // Ignore empty structs/unions on non-Windows. 1859 if (!IsWin32StructABI && isEmptyRecord(getContext(), Ty, true)) 1860 return ABIArgInfo::getIgnore(); 1861 1862 llvm::LLVMContext &LLVMContext = getVMContext(); 1863 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext); 1864 bool NeedsPadding = false; 1865 bool InReg; 1866 if (shouldAggregateUseDirect(Ty, State, InReg, NeedsPadding)) { 1867 unsigned SizeInRegs = (TI.Width + 31) / 32; 1868 SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32); 1869 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements); 1870 if (InReg) 1871 return ABIArgInfo::getDirectInReg(Result); 1872 else 1873 return ABIArgInfo::getDirect(Result); 1874 } 1875 llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : nullptr; 1876 1877 // Pass over-aligned aggregates on Windows indirectly. This behavior was 1878 // added in MSVC 2015. 1879 if (IsWin32StructABI && TI.isAlignRequired() && TI.Align > 32) 1880 return getIndirectResult(Ty, /*ByVal=*/false, State); 1881 1882 // Expand small (<= 128-bit) record types when we know that the stack layout 1883 // of those arguments will match the struct. This is important because the 1884 // LLVM backend isn't smart enough to remove byval, which inhibits many 1885 // optimizations. 1886 // Don't do this for the MCU if there are still free integer registers 1887 // (see X86_64 ABI for full explanation). 1888 if (TI.Width <= 4 * 32 && (!IsMCUABI || State.FreeRegs == 0) && 1889 canExpandIndirectArgument(Ty)) 1890 return ABIArgInfo::getExpandWithPadding( 1891 IsFastCall || IsVectorCall || IsRegCall, PaddingType); 1892 1893 return getIndirectResult(Ty, true, State); 1894 } 1895 1896 if (const VectorType *VT = Ty->getAs<VectorType>()) { 1897 // On Windows, vectors are passed directly if registers are available, or 1898 // indirectly if not. This avoids the need to align argument memory. Pass 1899 // user-defined vector types larger than 512 bits indirectly for simplicity. 1900 if (IsWin32StructABI) { 1901 if (TI.Width <= 512 && State.FreeSSERegs > 0) { 1902 --State.FreeSSERegs; 1903 return ABIArgInfo::getDirectInReg(); 1904 } 1905 return getIndirectResult(Ty, /*ByVal=*/false, State); 1906 } 1907 1908 // On Darwin, some vectors are passed in memory, we handle this by passing 1909 // it as an i8/i16/i32/i64. 1910 if (IsDarwinVectorABI) { 1911 if ((TI.Width == 8 || TI.Width == 16 || TI.Width == 32) || 1912 (TI.Width == 64 && VT->getNumElements() == 1)) 1913 return ABIArgInfo::getDirect( 1914 llvm::IntegerType::get(getVMContext(), TI.Width)); 1915 } 1916 1917 if (IsX86_MMXType(CGT.ConvertType(Ty))) 1918 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64)); 1919 1920 return ABIArgInfo::getDirect(); 1921 } 1922 1923 1924 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 1925 Ty = EnumTy->getDecl()->getIntegerType(); 1926 1927 bool InReg = shouldPrimitiveUseInReg(Ty, State); 1928 1929 if (isPromotableIntegerTypeForABI(Ty)) { 1930 if (InReg) 1931 return ABIArgInfo::getExtendInReg(Ty); 1932 return ABIArgInfo::getExtend(Ty); 1933 } 1934 1935 if (const auto *EIT = Ty->getAs<BitIntType>()) { 1936 if (EIT->getNumBits() <= 64) { 1937 if (InReg) 1938 return ABIArgInfo::getDirectInReg(); 1939 return ABIArgInfo::getDirect(); 1940 } 1941 return getIndirectResult(Ty, /*ByVal=*/false, State); 1942 } 1943 1944 if (InReg) 1945 return ABIArgInfo::getDirectInReg(); 1946 return ABIArgInfo::getDirect(); 1947 } 1948 1949 void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const { 1950 CCState State(FI); 1951 if (IsMCUABI) 1952 State.FreeRegs = 3; 1953 else if (State.CC == llvm::CallingConv::X86_FastCall) { 1954 State.FreeRegs = 2; 1955 State.FreeSSERegs = 3; 1956 } else if (State.CC == llvm::CallingConv::X86_VectorCall) { 1957 State.FreeRegs = 2; 1958 State.FreeSSERegs = 6; 1959 } else if (FI.getHasRegParm()) 1960 State.FreeRegs = FI.getRegParm(); 1961 else if (State.CC == llvm::CallingConv::X86_RegCall) { 1962 State.FreeRegs = 5; 1963 State.FreeSSERegs = 8; 1964 } else if (IsWin32StructABI) { 1965 // Since MSVC 2015, the first three SSE vectors have been passed in 1966 // registers. The rest are passed indirectly. 1967 State.FreeRegs = DefaultNumRegisterParameters; 1968 State.FreeSSERegs = 3; 1969 } else 1970 State.FreeRegs = DefaultNumRegisterParameters; 1971 1972 if (!::classifyReturnType(getCXXABI(), FI, *this)) { 1973 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), State); 1974 } else if (FI.getReturnInfo().isIndirect()) { 1975 // The C++ ABI is not aware of register usage, so we have to check if the 1976 // return value was sret and put it in a register ourselves if appropriate. 1977 if (State.FreeRegs) { 1978 --State.FreeRegs; // The sret parameter consumes a register. 1979 if (!IsMCUABI) 1980 FI.getReturnInfo().setInReg(true); 1981 } 1982 } 1983 1984 // The chain argument effectively gives us another free register. 1985 if (FI.isChainCall()) 1986 ++State.FreeRegs; 1987 1988 // For vectorcall, do a first pass over the arguments, assigning FP and vector 1989 // arguments to XMM registers as available. 1990 if (State.CC == llvm::CallingConv::X86_VectorCall) 1991 runVectorCallFirstPass(FI, State); 1992 1993 bool UsedInAlloca = false; 1994 MutableArrayRef<CGFunctionInfoArgInfo> Args = FI.arguments(); 1995 for (int I = 0, E = Args.size(); I < E; ++I) { 1996 // Skip arguments that have already been assigned. 1997 if (State.IsPreassigned.test(I)) 1998 continue; 1999 2000 Args[I].info = classifyArgumentType(Args[I].type, State); 2001 UsedInAlloca |= (Args[I].info.getKind() == ABIArgInfo::InAlloca); 2002 } 2003 2004 // If we needed to use inalloca for any argument, do a second pass and rewrite 2005 // all the memory arguments to use inalloca. 2006 if (UsedInAlloca) 2007 rewriteWithInAlloca(FI); 2008 } 2009 2010 void 2011 X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields, 2012 CharUnits &StackOffset, ABIArgInfo &Info, 2013 QualType Type) const { 2014 // Arguments are always 4-byte-aligned. 2015 CharUnits WordSize = CharUnits::fromQuantity(4); 2016 assert(StackOffset.isMultipleOf(WordSize) && "unaligned inalloca struct"); 2017 2018 // sret pointers and indirect things will require an extra pointer 2019 // indirection, unless they are byval. Most things are byval, and will not 2020 // require this indirection. 2021 bool IsIndirect = false; 2022 if (Info.isIndirect() && !Info.getIndirectByVal()) 2023 IsIndirect = true; 2024 Info = ABIArgInfo::getInAlloca(FrameFields.size(), IsIndirect); 2025 llvm::Type *LLTy = CGT.ConvertTypeForMem(Type); 2026 if (IsIndirect) 2027 LLTy = LLTy->getPointerTo(0); 2028 FrameFields.push_back(LLTy); 2029 StackOffset += IsIndirect ? WordSize : getContext().getTypeSizeInChars(Type); 2030 2031 // Insert padding bytes to respect alignment. 2032 CharUnits FieldEnd = StackOffset; 2033 StackOffset = FieldEnd.alignTo(WordSize); 2034 if (StackOffset != FieldEnd) { 2035 CharUnits NumBytes = StackOffset - FieldEnd; 2036 llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext()); 2037 Ty = llvm::ArrayType::get(Ty, NumBytes.getQuantity()); 2038 FrameFields.push_back(Ty); 2039 } 2040 } 2041 2042 static bool isArgInAlloca(const ABIArgInfo &Info) { 2043 // Leave ignored and inreg arguments alone. 2044 switch (Info.getKind()) { 2045 case ABIArgInfo::InAlloca: 2046 return true; 2047 case ABIArgInfo::Ignore: 2048 case ABIArgInfo::IndirectAliased: 2049 return false; 2050 case ABIArgInfo::Indirect: 2051 case ABIArgInfo::Direct: 2052 case ABIArgInfo::Extend: 2053 return !Info.getInReg(); 2054 case ABIArgInfo::Expand: 2055 case ABIArgInfo::CoerceAndExpand: 2056 // These are aggregate types which are never passed in registers when 2057 // inalloca is involved. 2058 return true; 2059 } 2060 llvm_unreachable("invalid enum"); 2061 } 2062 2063 void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const { 2064 assert(IsWin32StructABI && "inalloca only supported on win32"); 2065 2066 // Build a packed struct type for all of the arguments in memory. 2067 SmallVector<llvm::Type *, 6> FrameFields; 2068 2069 // The stack alignment is always 4. 2070 CharUnits StackAlign = CharUnits::fromQuantity(4); 2071 2072 CharUnits StackOffset; 2073 CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end(); 2074 2075 // Put 'this' into the struct before 'sret', if necessary. 2076 bool IsThisCall = 2077 FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall; 2078 ABIArgInfo &Ret = FI.getReturnInfo(); 2079 if (Ret.isIndirect() && Ret.isSRetAfterThis() && !IsThisCall && 2080 isArgInAlloca(I->info)) { 2081 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type); 2082 ++I; 2083 } 2084 2085 // Put the sret parameter into the inalloca struct if it's in memory. 2086 if (Ret.isIndirect() && !Ret.getInReg()) { 2087 addFieldToArgStruct(FrameFields, StackOffset, Ret, FI.getReturnType()); 2088 // On Windows, the hidden sret parameter is always returned in eax. 2089 Ret.setInAllocaSRet(IsWin32StructABI); 2090 } 2091 2092 // Skip the 'this' parameter in ecx. 2093 if (IsThisCall) 2094 ++I; 2095 2096 // Put arguments passed in memory into the struct. 2097 for (; I != E; ++I) { 2098 if (isArgInAlloca(I->info)) 2099 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type); 2100 } 2101 2102 FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields, 2103 /*isPacked=*/true), 2104 StackAlign); 2105 } 2106 2107 Address X86_32ABIInfo::EmitVAArg(CodeGenFunction &CGF, 2108 Address VAListAddr, QualType Ty) const { 2109 2110 auto TypeInfo = getContext().getTypeInfoInChars(Ty); 2111 2112 // x86-32 changes the alignment of certain arguments on the stack. 2113 // 2114 // Just messing with TypeInfo like this works because we never pass 2115 // anything indirectly. 2116 TypeInfo.Align = CharUnits::fromQuantity( 2117 getTypeStackAlignInBytes(Ty, TypeInfo.Align.getQuantity())); 2118 2119 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false, 2120 TypeInfo, CharUnits::fromQuantity(4), 2121 /*AllowHigherAlign*/ true); 2122 } 2123 2124 bool X86_32TargetCodeGenInfo::isStructReturnInRegABI( 2125 const llvm::Triple &Triple, const CodeGenOptions &Opts) { 2126 assert(Triple.getArch() == llvm::Triple::x86); 2127 2128 switch (Opts.getStructReturnConvention()) { 2129 case CodeGenOptions::SRCK_Default: 2130 break; 2131 case CodeGenOptions::SRCK_OnStack: // -fpcc-struct-return 2132 return false; 2133 case CodeGenOptions::SRCK_InRegs: // -freg-struct-return 2134 return true; 2135 } 2136 2137 if (Triple.isOSDarwin() || Triple.isOSIAMCU()) 2138 return true; 2139 2140 switch (Triple.getOS()) { 2141 case llvm::Triple::DragonFly: 2142 case llvm::Triple::FreeBSD: 2143 case llvm::Triple::OpenBSD: 2144 case llvm::Triple::Win32: 2145 return true; 2146 default: 2147 return false; 2148 } 2149 } 2150 2151 static void addX86InterruptAttrs(const FunctionDecl *FD, llvm::GlobalValue *GV, 2152 CodeGen::CodeGenModule &CGM) { 2153 if (!FD->hasAttr<AnyX86InterruptAttr>()) 2154 return; 2155 2156 llvm::Function *Fn = cast<llvm::Function>(GV); 2157 Fn->setCallingConv(llvm::CallingConv::X86_INTR); 2158 if (FD->getNumParams() == 0) 2159 return; 2160 2161 auto PtrTy = cast<PointerType>(FD->getParamDecl(0)->getType()); 2162 llvm::Type *ByValTy = CGM.getTypes().ConvertType(PtrTy->getPointeeType()); 2163 llvm::Attribute NewAttr = llvm::Attribute::getWithByValType( 2164 Fn->getContext(), ByValTy); 2165 Fn->addParamAttr(0, NewAttr); 2166 } 2167 2168 void X86_32TargetCodeGenInfo::setTargetAttributes( 2169 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const { 2170 if (GV->isDeclaration()) 2171 return; 2172 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) { 2173 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) { 2174 llvm::Function *Fn = cast<llvm::Function>(GV); 2175 Fn->addFnAttr("stackrealign"); 2176 } 2177 2178 addX86InterruptAttrs(FD, GV, CGM); 2179 } 2180 } 2181 2182 bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable( 2183 CodeGen::CodeGenFunction &CGF, 2184 llvm::Value *Address) const { 2185 CodeGen::CGBuilderTy &Builder = CGF.Builder; 2186 2187 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4); 2188 2189 // 0-7 are the eight integer registers; the order is different 2190 // on Darwin (for EH), but the range is the same. 2191 // 8 is %eip. 2192 AssignToArrayRange(Builder, Address, Four8, 0, 8); 2193 2194 if (CGF.CGM.getTarget().getTriple().isOSDarwin()) { 2195 // 12-16 are st(0..4). Not sure why we stop at 4. 2196 // These have size 16, which is sizeof(long double) on 2197 // platforms with 8-byte alignment for that type. 2198 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16); 2199 AssignToArrayRange(Builder, Address, Sixteen8, 12, 16); 2200 2201 } else { 2202 // 9 is %eflags, which doesn't get a size on Darwin for some 2203 // reason. 2204 Builder.CreateAlignedStore( 2205 Four8, Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, Address, 9), 2206 CharUnits::One()); 2207 2208 // 11-16 are st(0..5). Not sure why we stop at 5. 2209 // These have size 12, which is sizeof(long double) on 2210 // platforms with 4-byte alignment for that type. 2211 llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12); 2212 AssignToArrayRange(Builder, Address, Twelve8, 11, 16); 2213 } 2214 2215 return false; 2216 } 2217 2218 //===----------------------------------------------------------------------===// 2219 // X86-64 ABI Implementation 2220 //===----------------------------------------------------------------------===// 2221 2222 2223 namespace { 2224 /// The AVX ABI level for X86 targets. 2225 enum class X86AVXABILevel { 2226 None, 2227 AVX, 2228 AVX512 2229 }; 2230 2231 /// \p returns the size in bits of the largest (native) vector for \p AVXLevel. 2232 static unsigned getNativeVectorSizeForAVXABI(X86AVXABILevel AVXLevel) { 2233 switch (AVXLevel) { 2234 case X86AVXABILevel::AVX512: 2235 return 512; 2236 case X86AVXABILevel::AVX: 2237 return 256; 2238 case X86AVXABILevel::None: 2239 return 128; 2240 } 2241 llvm_unreachable("Unknown AVXLevel"); 2242 } 2243 2244 /// X86_64ABIInfo - The X86_64 ABI information. 2245 class X86_64ABIInfo : public SwiftABIInfo { 2246 enum Class { 2247 Integer = 0, 2248 SSE, 2249 SSEUp, 2250 X87, 2251 X87Up, 2252 ComplexX87, 2253 NoClass, 2254 Memory 2255 }; 2256 2257 /// merge - Implement the X86_64 ABI merging algorithm. 2258 /// 2259 /// Merge an accumulating classification \arg Accum with a field 2260 /// classification \arg Field. 2261 /// 2262 /// \param Accum - The accumulating classification. This should 2263 /// always be either NoClass or the result of a previous merge 2264 /// call. In addition, this should never be Memory (the caller 2265 /// should just return Memory for the aggregate). 2266 static Class merge(Class Accum, Class Field); 2267 2268 /// postMerge - Implement the X86_64 ABI post merging algorithm. 2269 /// 2270 /// Post merger cleanup, reduces a malformed Hi and Lo pair to 2271 /// final MEMORY or SSE classes when necessary. 2272 /// 2273 /// \param AggregateSize - The size of the current aggregate in 2274 /// the classification process. 2275 /// 2276 /// \param Lo - The classification for the parts of the type 2277 /// residing in the low word of the containing object. 2278 /// 2279 /// \param Hi - The classification for the parts of the type 2280 /// residing in the higher words of the containing object. 2281 /// 2282 void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const; 2283 2284 /// classify - Determine the x86_64 register classes in which the 2285 /// given type T should be passed. 2286 /// 2287 /// \param Lo - The classification for the parts of the type 2288 /// residing in the low word of the containing object. 2289 /// 2290 /// \param Hi - The classification for the parts of the type 2291 /// residing in the high word of the containing object. 2292 /// 2293 /// \param OffsetBase - The bit offset of this type in the 2294 /// containing object. Some parameters are classified different 2295 /// depending on whether they straddle an eightbyte boundary. 2296 /// 2297 /// \param isNamedArg - Whether the argument in question is a "named" 2298 /// argument, as used in AMD64-ABI 3.5.7. 2299 /// 2300 /// \param IsRegCall - Whether the calling conversion is regcall. 2301 /// 2302 /// If a word is unused its result will be NoClass; if a type should 2303 /// be passed in Memory then at least the classification of \arg Lo 2304 /// will be Memory. 2305 /// 2306 /// The \arg Lo class will be NoClass iff the argument is ignored. 2307 /// 2308 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will 2309 /// also be ComplexX87. 2310 void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi, 2311 bool isNamedArg, bool IsRegCall = false) const; 2312 2313 llvm::Type *GetByteVectorType(QualType Ty) const; 2314 llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType, 2315 unsigned IROffset, QualType SourceTy, 2316 unsigned SourceOffset) const; 2317 llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType, 2318 unsigned IROffset, QualType SourceTy, 2319 unsigned SourceOffset) const; 2320 2321 /// getIndirectResult - Give a source type \arg Ty, return a suitable result 2322 /// such that the argument will be returned in memory. 2323 ABIArgInfo getIndirectReturnResult(QualType Ty) const; 2324 2325 /// getIndirectResult - Give a source type \arg Ty, return a suitable result 2326 /// such that the argument will be passed in memory. 2327 /// 2328 /// \param freeIntRegs - The number of free integer registers remaining 2329 /// available. 2330 ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const; 2331 2332 ABIArgInfo classifyReturnType(QualType RetTy) const; 2333 2334 ABIArgInfo classifyArgumentType(QualType Ty, unsigned freeIntRegs, 2335 unsigned &neededInt, unsigned &neededSSE, 2336 bool isNamedArg, 2337 bool IsRegCall = false) const; 2338 2339 ABIArgInfo classifyRegCallStructType(QualType Ty, unsigned &NeededInt, 2340 unsigned &NeededSSE, 2341 unsigned &MaxVectorWidth) const; 2342 2343 ABIArgInfo classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt, 2344 unsigned &NeededSSE, 2345 unsigned &MaxVectorWidth) const; 2346 2347 bool IsIllegalVectorType(QualType Ty) const; 2348 2349 /// The 0.98 ABI revision clarified a lot of ambiguities, 2350 /// unfortunately in ways that were not always consistent with 2351 /// certain previous compilers. In particular, platforms which 2352 /// required strict binary compatibility with older versions of GCC 2353 /// may need to exempt themselves. 2354 bool honorsRevision0_98() const { 2355 return !getTarget().getTriple().isOSDarwin(); 2356 } 2357 2358 /// GCC classifies <1 x long long> as SSE but some platform ABIs choose to 2359 /// classify it as INTEGER (for compatibility with older clang compilers). 2360 bool classifyIntegerMMXAsSSE() const { 2361 // Clang <= 3.8 did not do this. 2362 if (getContext().getLangOpts().getClangABICompat() <= 2363 LangOptions::ClangABI::Ver3_8) 2364 return false; 2365 2366 const llvm::Triple &Triple = getTarget().getTriple(); 2367 if (Triple.isOSDarwin() || Triple.getOS() == llvm::Triple::PS4) 2368 return false; 2369 if (Triple.isOSFreeBSD() && Triple.getOSMajorVersion() >= 10) 2370 return false; 2371 return true; 2372 } 2373 2374 // GCC classifies vectors of __int128 as memory. 2375 bool passInt128VectorsInMem() const { 2376 // Clang <= 9.0 did not do this. 2377 if (getContext().getLangOpts().getClangABICompat() <= 2378 LangOptions::ClangABI::Ver9) 2379 return false; 2380 2381 const llvm::Triple &T = getTarget().getTriple(); 2382 return T.isOSLinux() || T.isOSNetBSD(); 2383 } 2384 2385 X86AVXABILevel AVXLevel; 2386 // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on 2387 // 64-bit hardware. 2388 bool Has64BitPointers; 2389 2390 public: 2391 X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) : 2392 SwiftABIInfo(CGT), AVXLevel(AVXLevel), 2393 Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) { 2394 } 2395 2396 bool isPassedUsingAVXType(QualType type) const { 2397 unsigned neededInt, neededSSE; 2398 // The freeIntRegs argument doesn't matter here. 2399 ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE, 2400 /*isNamedArg*/true); 2401 if (info.isDirect()) { 2402 llvm::Type *ty = info.getCoerceToType(); 2403 if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty)) 2404 return vectorTy->getPrimitiveSizeInBits().getFixedSize() > 128; 2405 } 2406 return false; 2407 } 2408 2409 void computeInfo(CGFunctionInfo &FI) const override; 2410 2411 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 2412 QualType Ty) const override; 2413 Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr, 2414 QualType Ty) const override; 2415 2416 bool has64BitPointers() const { 2417 return Has64BitPointers; 2418 } 2419 2420 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars, 2421 bool asReturnValue) const override { 2422 return occupiesMoreThan(CGT, scalars, /*total*/ 4); 2423 } 2424 bool isSwiftErrorInRegister() const override { 2425 return true; 2426 } 2427 }; 2428 2429 /// WinX86_64ABIInfo - The Windows X86_64 ABI information. 2430 class WinX86_64ABIInfo : public SwiftABIInfo { 2431 public: 2432 WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) 2433 : SwiftABIInfo(CGT), AVXLevel(AVXLevel), 2434 IsMingw64(getTarget().getTriple().isWindowsGNUEnvironment()) {} 2435 2436 void computeInfo(CGFunctionInfo &FI) const override; 2437 2438 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 2439 QualType Ty) const override; 2440 2441 bool isHomogeneousAggregateBaseType(QualType Ty) const override { 2442 // FIXME: Assumes vectorcall is in use. 2443 return isX86VectorTypeForVectorCall(getContext(), Ty); 2444 } 2445 2446 bool isHomogeneousAggregateSmallEnough(const Type *Ty, 2447 uint64_t NumMembers) const override { 2448 // FIXME: Assumes vectorcall is in use. 2449 return isX86VectorCallAggregateSmallEnough(NumMembers); 2450 } 2451 2452 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type *> scalars, 2453 bool asReturnValue) const override { 2454 return occupiesMoreThan(CGT, scalars, /*total*/ 4); 2455 } 2456 2457 bool isSwiftErrorInRegister() const override { 2458 return true; 2459 } 2460 2461 private: 2462 ABIArgInfo classify(QualType Ty, unsigned &FreeSSERegs, bool IsReturnType, 2463 bool IsVectorCall, bool IsRegCall) const; 2464 ABIArgInfo reclassifyHvaArgForVectorCall(QualType Ty, unsigned &FreeSSERegs, 2465 const ABIArgInfo ¤t) const; 2466 2467 X86AVXABILevel AVXLevel; 2468 2469 bool IsMingw64; 2470 }; 2471 2472 class X86_64TargetCodeGenInfo : public TargetCodeGenInfo { 2473 public: 2474 X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) 2475 : TargetCodeGenInfo(std::make_unique<X86_64ABIInfo>(CGT, AVXLevel)) {} 2476 2477 const X86_64ABIInfo &getABIInfo() const { 2478 return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo()); 2479 } 2480 2481 /// Disable tail call on x86-64. The epilogue code before the tail jump blocks 2482 /// autoreleaseRV/retainRV and autoreleaseRV/unsafeClaimRV optimizations. 2483 bool markARCOptimizedReturnCallsAsNoTail() const override { return true; } 2484 2485 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override { 2486 return 7; 2487 } 2488 2489 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 2490 llvm::Value *Address) const override { 2491 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8); 2492 2493 // 0-15 are the 16 integer registers. 2494 // 16 is %rip. 2495 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16); 2496 return false; 2497 } 2498 2499 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF, 2500 StringRef Constraint, 2501 llvm::Type* Ty) const override { 2502 return X86AdjustInlineAsmType(CGF, Constraint, Ty); 2503 } 2504 2505 bool isNoProtoCallVariadic(const CallArgList &args, 2506 const FunctionNoProtoType *fnType) const override { 2507 // The default CC on x86-64 sets %al to the number of SSA 2508 // registers used, and GCC sets this when calling an unprototyped 2509 // function, so we override the default behavior. However, don't do 2510 // that when AVX types are involved: the ABI explicitly states it is 2511 // undefined, and it doesn't work in practice because of how the ABI 2512 // defines varargs anyway. 2513 if (fnType->getCallConv() == CC_C) { 2514 bool HasAVXType = false; 2515 for (CallArgList::const_iterator 2516 it = args.begin(), ie = args.end(); it != ie; ++it) { 2517 if (getABIInfo().isPassedUsingAVXType(it->Ty)) { 2518 HasAVXType = true; 2519 break; 2520 } 2521 } 2522 2523 if (!HasAVXType) 2524 return true; 2525 } 2526 2527 return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType); 2528 } 2529 2530 llvm::Constant * 2531 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override { 2532 unsigned Sig = (0xeb << 0) | // jmp rel8 2533 (0x06 << 8) | // .+0x08 2534 ('v' << 16) | 2535 ('2' << 24); 2536 return llvm::ConstantInt::get(CGM.Int32Ty, Sig); 2537 } 2538 2539 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 2540 CodeGen::CodeGenModule &CGM) const override { 2541 if (GV->isDeclaration()) 2542 return; 2543 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) { 2544 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) { 2545 llvm::Function *Fn = cast<llvm::Function>(GV); 2546 Fn->addFnAttr("stackrealign"); 2547 } 2548 2549 addX86InterruptAttrs(FD, GV, CGM); 2550 } 2551 } 2552 2553 void checkFunctionCallABI(CodeGenModule &CGM, SourceLocation CallLoc, 2554 const FunctionDecl *Caller, 2555 const FunctionDecl *Callee, 2556 const CallArgList &Args) const override; 2557 }; 2558 2559 static void initFeatureMaps(const ASTContext &Ctx, 2560 llvm::StringMap<bool> &CallerMap, 2561 const FunctionDecl *Caller, 2562 llvm::StringMap<bool> &CalleeMap, 2563 const FunctionDecl *Callee) { 2564 if (CalleeMap.empty() && CallerMap.empty()) { 2565 // The caller is potentially nullptr in the case where the call isn't in a 2566 // function. In this case, the getFunctionFeatureMap ensures we just get 2567 // the TU level setting (since it cannot be modified by 'target'.. 2568 Ctx.getFunctionFeatureMap(CallerMap, Caller); 2569 Ctx.getFunctionFeatureMap(CalleeMap, Callee); 2570 } 2571 } 2572 2573 static bool checkAVXParamFeature(DiagnosticsEngine &Diag, 2574 SourceLocation CallLoc, 2575 const llvm::StringMap<bool> &CallerMap, 2576 const llvm::StringMap<bool> &CalleeMap, 2577 QualType Ty, StringRef Feature, 2578 bool IsArgument) { 2579 bool CallerHasFeat = CallerMap.lookup(Feature); 2580 bool CalleeHasFeat = CalleeMap.lookup(Feature); 2581 if (!CallerHasFeat && !CalleeHasFeat) 2582 return Diag.Report(CallLoc, diag::warn_avx_calling_convention) 2583 << IsArgument << Ty << Feature; 2584 2585 // Mixing calling conventions here is very clearly an error. 2586 if (!CallerHasFeat || !CalleeHasFeat) 2587 return Diag.Report(CallLoc, diag::err_avx_calling_convention) 2588 << IsArgument << Ty << Feature; 2589 2590 // Else, both caller and callee have the required feature, so there is no need 2591 // to diagnose. 2592 return false; 2593 } 2594 2595 static bool checkAVXParam(DiagnosticsEngine &Diag, ASTContext &Ctx, 2596 SourceLocation CallLoc, 2597 const llvm::StringMap<bool> &CallerMap, 2598 const llvm::StringMap<bool> &CalleeMap, QualType Ty, 2599 bool IsArgument) { 2600 uint64_t Size = Ctx.getTypeSize(Ty); 2601 if (Size > 256) 2602 return checkAVXParamFeature(Diag, CallLoc, CallerMap, CalleeMap, Ty, 2603 "avx512f", IsArgument); 2604 2605 if (Size > 128) 2606 return checkAVXParamFeature(Diag, CallLoc, CallerMap, CalleeMap, Ty, "avx", 2607 IsArgument); 2608 2609 return false; 2610 } 2611 2612 void X86_64TargetCodeGenInfo::checkFunctionCallABI( 2613 CodeGenModule &CGM, SourceLocation CallLoc, const FunctionDecl *Caller, 2614 const FunctionDecl *Callee, const CallArgList &Args) const { 2615 llvm::StringMap<bool> CallerMap; 2616 llvm::StringMap<bool> CalleeMap; 2617 unsigned ArgIndex = 0; 2618 2619 // We need to loop through the actual call arguments rather than the the 2620 // function's parameters, in case this variadic. 2621 for (const CallArg &Arg : Args) { 2622 // The "avx" feature changes how vectors >128 in size are passed. "avx512f" 2623 // additionally changes how vectors >256 in size are passed. Like GCC, we 2624 // warn when a function is called with an argument where this will change. 2625 // Unlike GCC, we also error when it is an obvious ABI mismatch, that is, 2626 // the caller and callee features are mismatched. 2627 // Unfortunately, we cannot do this diagnostic in SEMA, since the callee can 2628 // change its ABI with attribute-target after this call. 2629 if (Arg.getType()->isVectorType() && 2630 CGM.getContext().getTypeSize(Arg.getType()) > 128) { 2631 initFeatureMaps(CGM.getContext(), CallerMap, Caller, CalleeMap, Callee); 2632 QualType Ty = Arg.getType(); 2633 // The CallArg seems to have desugared the type already, so for clearer 2634 // diagnostics, replace it with the type in the FunctionDecl if possible. 2635 if (ArgIndex < Callee->getNumParams()) 2636 Ty = Callee->getParamDecl(ArgIndex)->getType(); 2637 2638 if (checkAVXParam(CGM.getDiags(), CGM.getContext(), CallLoc, CallerMap, 2639 CalleeMap, Ty, /*IsArgument*/ true)) 2640 return; 2641 } 2642 ++ArgIndex; 2643 } 2644 2645 // Check return always, as we don't have a good way of knowing in codegen 2646 // whether this value is used, tail-called, etc. 2647 if (Callee->getReturnType()->isVectorType() && 2648 CGM.getContext().getTypeSize(Callee->getReturnType()) > 128) { 2649 initFeatureMaps(CGM.getContext(), CallerMap, Caller, CalleeMap, Callee); 2650 checkAVXParam(CGM.getDiags(), CGM.getContext(), CallLoc, CallerMap, 2651 CalleeMap, Callee->getReturnType(), 2652 /*IsArgument*/ false); 2653 } 2654 } 2655 2656 static std::string qualifyWindowsLibrary(llvm::StringRef Lib) { 2657 // If the argument does not end in .lib, automatically add the suffix. 2658 // If the argument contains a space, enclose it in quotes. 2659 // This matches the behavior of MSVC. 2660 bool Quote = Lib.contains(' '); 2661 std::string ArgStr = Quote ? "\"" : ""; 2662 ArgStr += Lib; 2663 if (!Lib.endswith_insensitive(".lib") && !Lib.endswith_insensitive(".a")) 2664 ArgStr += ".lib"; 2665 ArgStr += Quote ? "\"" : ""; 2666 return ArgStr; 2667 } 2668 2669 class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo { 2670 public: 2671 WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, 2672 bool DarwinVectorABI, bool RetSmallStructInRegABI, bool Win32StructABI, 2673 unsigned NumRegisterParameters) 2674 : X86_32TargetCodeGenInfo(CGT, DarwinVectorABI, RetSmallStructInRegABI, 2675 Win32StructABI, NumRegisterParameters, false) {} 2676 2677 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 2678 CodeGen::CodeGenModule &CGM) const override; 2679 2680 void getDependentLibraryOption(llvm::StringRef Lib, 2681 llvm::SmallString<24> &Opt) const override { 2682 Opt = "/DEFAULTLIB:"; 2683 Opt += qualifyWindowsLibrary(Lib); 2684 } 2685 2686 void getDetectMismatchOption(llvm::StringRef Name, 2687 llvm::StringRef Value, 2688 llvm::SmallString<32> &Opt) const override { 2689 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\""; 2690 } 2691 }; 2692 2693 static void addStackProbeTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 2694 CodeGen::CodeGenModule &CGM) { 2695 if (llvm::Function *Fn = dyn_cast_or_null<llvm::Function>(GV)) { 2696 2697 if (CGM.getCodeGenOpts().StackProbeSize != 4096) 2698 Fn->addFnAttr("stack-probe-size", 2699 llvm::utostr(CGM.getCodeGenOpts().StackProbeSize)); 2700 if (CGM.getCodeGenOpts().NoStackArgProbe) 2701 Fn->addFnAttr("no-stack-arg-probe"); 2702 } 2703 } 2704 2705 void WinX86_32TargetCodeGenInfo::setTargetAttributes( 2706 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const { 2707 X86_32TargetCodeGenInfo::setTargetAttributes(D, GV, CGM); 2708 if (GV->isDeclaration()) 2709 return; 2710 addStackProbeTargetAttributes(D, GV, CGM); 2711 } 2712 2713 class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo { 2714 public: 2715 WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, 2716 X86AVXABILevel AVXLevel) 2717 : TargetCodeGenInfo(std::make_unique<WinX86_64ABIInfo>(CGT, AVXLevel)) {} 2718 2719 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 2720 CodeGen::CodeGenModule &CGM) const override; 2721 2722 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override { 2723 return 7; 2724 } 2725 2726 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 2727 llvm::Value *Address) const override { 2728 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8); 2729 2730 // 0-15 are the 16 integer registers. 2731 // 16 is %rip. 2732 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16); 2733 return false; 2734 } 2735 2736 void getDependentLibraryOption(llvm::StringRef Lib, 2737 llvm::SmallString<24> &Opt) const override { 2738 Opt = "/DEFAULTLIB:"; 2739 Opt += qualifyWindowsLibrary(Lib); 2740 } 2741 2742 void getDetectMismatchOption(llvm::StringRef Name, 2743 llvm::StringRef Value, 2744 llvm::SmallString<32> &Opt) const override { 2745 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\""; 2746 } 2747 }; 2748 2749 void WinX86_64TargetCodeGenInfo::setTargetAttributes( 2750 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const { 2751 TargetCodeGenInfo::setTargetAttributes(D, GV, CGM); 2752 if (GV->isDeclaration()) 2753 return; 2754 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) { 2755 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) { 2756 llvm::Function *Fn = cast<llvm::Function>(GV); 2757 Fn->addFnAttr("stackrealign"); 2758 } 2759 2760 addX86InterruptAttrs(FD, GV, CGM); 2761 } 2762 2763 addStackProbeTargetAttributes(D, GV, CGM); 2764 } 2765 } 2766 2767 void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo, 2768 Class &Hi) const { 2769 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done: 2770 // 2771 // (a) If one of the classes is Memory, the whole argument is passed in 2772 // memory. 2773 // 2774 // (b) If X87UP is not preceded by X87, the whole argument is passed in 2775 // memory. 2776 // 2777 // (c) If the size of the aggregate exceeds two eightbytes and the first 2778 // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole 2779 // argument is passed in memory. NOTE: This is necessary to keep the 2780 // ABI working for processors that don't support the __m256 type. 2781 // 2782 // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE. 2783 // 2784 // Some of these are enforced by the merging logic. Others can arise 2785 // only with unions; for example: 2786 // union { _Complex double; unsigned; } 2787 // 2788 // Note that clauses (b) and (c) were added in 0.98. 2789 // 2790 if (Hi == Memory) 2791 Lo = Memory; 2792 if (Hi == X87Up && Lo != X87 && honorsRevision0_98()) 2793 Lo = Memory; 2794 if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp)) 2795 Lo = Memory; 2796 if (Hi == SSEUp && Lo != SSE) 2797 Hi = SSE; 2798 } 2799 2800 X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) { 2801 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is 2802 // classified recursively so that always two fields are 2803 // considered. The resulting class is calculated according to 2804 // the classes of the fields in the eightbyte: 2805 // 2806 // (a) If both classes are equal, this is the resulting class. 2807 // 2808 // (b) If one of the classes is NO_CLASS, the resulting class is 2809 // the other class. 2810 // 2811 // (c) If one of the classes is MEMORY, the result is the MEMORY 2812 // class. 2813 // 2814 // (d) If one of the classes is INTEGER, the result is the 2815 // INTEGER. 2816 // 2817 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class, 2818 // MEMORY is used as class. 2819 // 2820 // (f) Otherwise class SSE is used. 2821 2822 // Accum should never be memory (we should have returned) or 2823 // ComplexX87 (because this cannot be passed in a structure). 2824 assert((Accum != Memory && Accum != ComplexX87) && 2825 "Invalid accumulated classification during merge."); 2826 if (Accum == Field || Field == NoClass) 2827 return Accum; 2828 if (Field == Memory) 2829 return Memory; 2830 if (Accum == NoClass) 2831 return Field; 2832 if (Accum == Integer || Field == Integer) 2833 return Integer; 2834 if (Field == X87 || Field == X87Up || Field == ComplexX87 || 2835 Accum == X87 || Accum == X87Up) 2836 return Memory; 2837 return SSE; 2838 } 2839 2840 void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase, Class &Lo, 2841 Class &Hi, bool isNamedArg, bool IsRegCall) const { 2842 // FIXME: This code can be simplified by introducing a simple value class for 2843 // Class pairs with appropriate constructor methods for the various 2844 // situations. 2845 2846 // FIXME: Some of the split computations are wrong; unaligned vectors 2847 // shouldn't be passed in registers for example, so there is no chance they 2848 // can straddle an eightbyte. Verify & simplify. 2849 2850 Lo = Hi = NoClass; 2851 2852 Class &Current = OffsetBase < 64 ? Lo : Hi; 2853 Current = Memory; 2854 2855 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) { 2856 BuiltinType::Kind k = BT->getKind(); 2857 2858 if (k == BuiltinType::Void) { 2859 Current = NoClass; 2860 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) { 2861 Lo = Integer; 2862 Hi = Integer; 2863 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) { 2864 Current = Integer; 2865 } else if (k == BuiltinType::Float || k == BuiltinType::Double || 2866 k == BuiltinType::Float16) { 2867 Current = SSE; 2868 } else if (k == BuiltinType::LongDouble) { 2869 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat(); 2870 if (LDF == &llvm::APFloat::IEEEquad()) { 2871 Lo = SSE; 2872 Hi = SSEUp; 2873 } else if (LDF == &llvm::APFloat::x87DoubleExtended()) { 2874 Lo = X87; 2875 Hi = X87Up; 2876 } else if (LDF == &llvm::APFloat::IEEEdouble()) { 2877 Current = SSE; 2878 } else 2879 llvm_unreachable("unexpected long double representation!"); 2880 } 2881 // FIXME: _Decimal32 and _Decimal64 are SSE. 2882 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp). 2883 return; 2884 } 2885 2886 if (const EnumType *ET = Ty->getAs<EnumType>()) { 2887 // Classify the underlying integer type. 2888 classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg); 2889 return; 2890 } 2891 2892 if (Ty->hasPointerRepresentation()) { 2893 Current = Integer; 2894 return; 2895 } 2896 2897 if (Ty->isMemberPointerType()) { 2898 if (Ty->isMemberFunctionPointerType()) { 2899 if (Has64BitPointers) { 2900 // If Has64BitPointers, this is an {i64, i64}, so classify both 2901 // Lo and Hi now. 2902 Lo = Hi = Integer; 2903 } else { 2904 // Otherwise, with 32-bit pointers, this is an {i32, i32}. If that 2905 // straddles an eightbyte boundary, Hi should be classified as well. 2906 uint64_t EB_FuncPtr = (OffsetBase) / 64; 2907 uint64_t EB_ThisAdj = (OffsetBase + 64 - 1) / 64; 2908 if (EB_FuncPtr != EB_ThisAdj) { 2909 Lo = Hi = Integer; 2910 } else { 2911 Current = Integer; 2912 } 2913 } 2914 } else { 2915 Current = Integer; 2916 } 2917 return; 2918 } 2919 2920 if (const VectorType *VT = Ty->getAs<VectorType>()) { 2921 uint64_t Size = getContext().getTypeSize(VT); 2922 if (Size == 1 || Size == 8 || Size == 16 || Size == 32) { 2923 // gcc passes the following as integer: 2924 // 4 bytes - <4 x char>, <2 x short>, <1 x int>, <1 x float> 2925 // 2 bytes - <2 x char>, <1 x short> 2926 // 1 byte - <1 x char> 2927 Current = Integer; 2928 2929 // If this type crosses an eightbyte boundary, it should be 2930 // split. 2931 uint64_t EB_Lo = (OffsetBase) / 64; 2932 uint64_t EB_Hi = (OffsetBase + Size - 1) / 64; 2933 if (EB_Lo != EB_Hi) 2934 Hi = Lo; 2935 } else if (Size == 64) { 2936 QualType ElementType = VT->getElementType(); 2937 2938 // gcc passes <1 x double> in memory. :( 2939 if (ElementType->isSpecificBuiltinType(BuiltinType::Double)) 2940 return; 2941 2942 // gcc passes <1 x long long> as SSE but clang used to unconditionally 2943 // pass them as integer. For platforms where clang is the de facto 2944 // platform compiler, we must continue to use integer. 2945 if (!classifyIntegerMMXAsSSE() && 2946 (ElementType->isSpecificBuiltinType(BuiltinType::LongLong) || 2947 ElementType->isSpecificBuiltinType(BuiltinType::ULongLong) || 2948 ElementType->isSpecificBuiltinType(BuiltinType::Long) || 2949 ElementType->isSpecificBuiltinType(BuiltinType::ULong))) 2950 Current = Integer; 2951 else 2952 Current = SSE; 2953 2954 // If this type crosses an eightbyte boundary, it should be 2955 // split. 2956 if (OffsetBase && OffsetBase != 64) 2957 Hi = Lo; 2958 } else if (Size == 128 || 2959 (isNamedArg && Size <= getNativeVectorSizeForAVXABI(AVXLevel))) { 2960 QualType ElementType = VT->getElementType(); 2961 2962 // gcc passes 256 and 512 bit <X x __int128> vectors in memory. :( 2963 if (passInt128VectorsInMem() && Size != 128 && 2964 (ElementType->isSpecificBuiltinType(BuiltinType::Int128) || 2965 ElementType->isSpecificBuiltinType(BuiltinType::UInt128))) 2966 return; 2967 2968 // Arguments of 256-bits are split into four eightbyte chunks. The 2969 // least significant one belongs to class SSE and all the others to class 2970 // SSEUP. The original Lo and Hi design considers that types can't be 2971 // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense. 2972 // This design isn't correct for 256-bits, but since there're no cases 2973 // where the upper parts would need to be inspected, avoid adding 2974 // complexity and just consider Hi to match the 64-256 part. 2975 // 2976 // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in 2977 // registers if they are "named", i.e. not part of the "..." of a 2978 // variadic function. 2979 // 2980 // Similarly, per 3.2.3. of the AVX512 draft, 512-bits ("named") args are 2981 // split into eight eightbyte chunks, one SSE and seven SSEUP. 2982 Lo = SSE; 2983 Hi = SSEUp; 2984 } 2985 return; 2986 } 2987 2988 if (const ComplexType *CT = Ty->getAs<ComplexType>()) { 2989 QualType ET = getContext().getCanonicalType(CT->getElementType()); 2990 2991 uint64_t Size = getContext().getTypeSize(Ty); 2992 if (ET->isIntegralOrEnumerationType()) { 2993 if (Size <= 64) 2994 Current = Integer; 2995 else if (Size <= 128) 2996 Lo = Hi = Integer; 2997 } else if (ET->isFloat16Type() || ET == getContext().FloatTy) { 2998 Current = SSE; 2999 } else if (ET == getContext().DoubleTy) { 3000 Lo = Hi = SSE; 3001 } else if (ET == getContext().LongDoubleTy) { 3002 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat(); 3003 if (LDF == &llvm::APFloat::IEEEquad()) 3004 Current = Memory; 3005 else if (LDF == &llvm::APFloat::x87DoubleExtended()) 3006 Current = ComplexX87; 3007 else if (LDF == &llvm::APFloat::IEEEdouble()) 3008 Lo = Hi = SSE; 3009 else 3010 llvm_unreachable("unexpected long double representation!"); 3011 } 3012 3013 // If this complex type crosses an eightbyte boundary then it 3014 // should be split. 3015 uint64_t EB_Real = (OffsetBase) / 64; 3016 uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64; 3017 if (Hi == NoClass && EB_Real != EB_Imag) 3018 Hi = Lo; 3019 3020 return; 3021 } 3022 3023 if (const auto *EITy = Ty->getAs<BitIntType>()) { 3024 if (EITy->getNumBits() <= 64) 3025 Current = Integer; 3026 else if (EITy->getNumBits() <= 128) 3027 Lo = Hi = Integer; 3028 // Larger values need to get passed in memory. 3029 return; 3030 } 3031 3032 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) { 3033 // Arrays are treated like structures. 3034 3035 uint64_t Size = getContext().getTypeSize(Ty); 3036 3037 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger 3038 // than eight eightbytes, ..., it has class MEMORY. 3039 // regcall ABI doesn't have limitation to an object. The only limitation 3040 // is the free registers, which will be checked in computeInfo. 3041 if (!IsRegCall && Size > 512) 3042 return; 3043 3044 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned 3045 // fields, it has class MEMORY. 3046 // 3047 // Only need to check alignment of array base. 3048 if (OffsetBase % getContext().getTypeAlign(AT->getElementType())) 3049 return; 3050 3051 // Otherwise implement simplified merge. We could be smarter about 3052 // this, but it isn't worth it and would be harder to verify. 3053 Current = NoClass; 3054 uint64_t EltSize = getContext().getTypeSize(AT->getElementType()); 3055 uint64_t ArraySize = AT->getSize().getZExtValue(); 3056 3057 // The only case a 256-bit wide vector could be used is when the array 3058 // contains a single 256-bit element. Since Lo and Hi logic isn't extended 3059 // to work for sizes wider than 128, early check and fallback to memory. 3060 // 3061 if (Size > 128 && 3062 (Size != EltSize || Size > getNativeVectorSizeForAVXABI(AVXLevel))) 3063 return; 3064 3065 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) { 3066 Class FieldLo, FieldHi; 3067 classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg); 3068 Lo = merge(Lo, FieldLo); 3069 Hi = merge(Hi, FieldHi); 3070 if (Lo == Memory || Hi == Memory) 3071 break; 3072 } 3073 3074 postMerge(Size, Lo, Hi); 3075 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification."); 3076 return; 3077 } 3078 3079 if (const RecordType *RT = Ty->getAs<RecordType>()) { 3080 uint64_t Size = getContext().getTypeSize(Ty); 3081 3082 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger 3083 // than eight eightbytes, ..., it has class MEMORY. 3084 if (Size > 512) 3085 return; 3086 3087 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial 3088 // copy constructor or a non-trivial destructor, it is passed by invisible 3089 // reference. 3090 if (getRecordArgABI(RT, getCXXABI())) 3091 return; 3092 3093 const RecordDecl *RD = RT->getDecl(); 3094 3095 // Assume variable sized types are passed in memory. 3096 if (RD->hasFlexibleArrayMember()) 3097 return; 3098 3099 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD); 3100 3101 // Reset Lo class, this will be recomputed. 3102 Current = NoClass; 3103 3104 // If this is a C++ record, classify the bases first. 3105 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 3106 for (const auto &I : CXXRD->bases()) { 3107 assert(!I.isVirtual() && !I.getType()->isDependentType() && 3108 "Unexpected base class!"); 3109 const auto *Base = 3110 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl()); 3111 3112 // Classify this field. 3113 // 3114 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a 3115 // single eightbyte, each is classified separately. Each eightbyte gets 3116 // initialized to class NO_CLASS. 3117 Class FieldLo, FieldHi; 3118 uint64_t Offset = 3119 OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base)); 3120 classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg); 3121 Lo = merge(Lo, FieldLo); 3122 Hi = merge(Hi, FieldHi); 3123 if (Lo == Memory || Hi == Memory) { 3124 postMerge(Size, Lo, Hi); 3125 return; 3126 } 3127 } 3128 } 3129 3130 // Classify the fields one at a time, merging the results. 3131 unsigned idx = 0; 3132 bool UseClang11Compat = getContext().getLangOpts().getClangABICompat() <= 3133 LangOptions::ClangABI::Ver11 || 3134 getContext().getTargetInfo().getTriple().isPS4(); 3135 bool IsUnion = RT->isUnionType() && !UseClang11Compat; 3136 3137 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 3138 i != e; ++i, ++idx) { 3139 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx); 3140 bool BitField = i->isBitField(); 3141 3142 // Ignore padding bit-fields. 3143 if (BitField && i->isUnnamedBitfield()) 3144 continue; 3145 3146 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than 3147 // eight eightbytes, or it contains unaligned fields, it has class MEMORY. 3148 // 3149 // The only case a 256-bit or a 512-bit wide vector could be used is when 3150 // the struct contains a single 256-bit or 512-bit element. Early check 3151 // and fallback to memory. 3152 // 3153 // FIXME: Extended the Lo and Hi logic properly to work for size wider 3154 // than 128. 3155 if (Size > 128 && 3156 ((!IsUnion && Size != getContext().getTypeSize(i->getType())) || 3157 Size > getNativeVectorSizeForAVXABI(AVXLevel))) { 3158 Lo = Memory; 3159 postMerge(Size, Lo, Hi); 3160 return; 3161 } 3162 // Note, skip this test for bit-fields, see below. 3163 if (!BitField && Offset % getContext().getTypeAlign(i->getType())) { 3164 Lo = Memory; 3165 postMerge(Size, Lo, Hi); 3166 return; 3167 } 3168 3169 // Classify this field. 3170 // 3171 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate 3172 // exceeds a single eightbyte, each is classified 3173 // separately. Each eightbyte gets initialized to class 3174 // NO_CLASS. 3175 Class FieldLo, FieldHi; 3176 3177 // Bit-fields require special handling, they do not force the 3178 // structure to be passed in memory even if unaligned, and 3179 // therefore they can straddle an eightbyte. 3180 if (BitField) { 3181 assert(!i->isUnnamedBitfield()); 3182 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx); 3183 uint64_t Size = i->getBitWidthValue(getContext()); 3184 3185 uint64_t EB_Lo = Offset / 64; 3186 uint64_t EB_Hi = (Offset + Size - 1) / 64; 3187 3188 if (EB_Lo) { 3189 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes."); 3190 FieldLo = NoClass; 3191 FieldHi = Integer; 3192 } else { 3193 FieldLo = Integer; 3194 FieldHi = EB_Hi ? Integer : NoClass; 3195 } 3196 } else 3197 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg); 3198 Lo = merge(Lo, FieldLo); 3199 Hi = merge(Hi, FieldHi); 3200 if (Lo == Memory || Hi == Memory) 3201 break; 3202 } 3203 3204 postMerge(Size, Lo, Hi); 3205 } 3206 } 3207 3208 ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const { 3209 // If this is a scalar LLVM value then assume LLVM will pass it in the right 3210 // place naturally. 3211 if (!isAggregateTypeForABI(Ty)) { 3212 // Treat an enum type as its underlying type. 3213 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 3214 Ty = EnumTy->getDecl()->getIntegerType(); 3215 3216 if (Ty->isBitIntType()) 3217 return getNaturalAlignIndirect(Ty); 3218 3219 return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty) 3220 : ABIArgInfo::getDirect()); 3221 } 3222 3223 return getNaturalAlignIndirect(Ty); 3224 } 3225 3226 bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const { 3227 if (const VectorType *VecTy = Ty->getAs<VectorType>()) { 3228 uint64_t Size = getContext().getTypeSize(VecTy); 3229 unsigned LargestVector = getNativeVectorSizeForAVXABI(AVXLevel); 3230 if (Size <= 64 || Size > LargestVector) 3231 return true; 3232 QualType EltTy = VecTy->getElementType(); 3233 if (passInt128VectorsInMem() && 3234 (EltTy->isSpecificBuiltinType(BuiltinType::Int128) || 3235 EltTy->isSpecificBuiltinType(BuiltinType::UInt128))) 3236 return true; 3237 } 3238 3239 return false; 3240 } 3241 3242 ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty, 3243 unsigned freeIntRegs) const { 3244 // If this is a scalar LLVM value then assume LLVM will pass it in the right 3245 // place naturally. 3246 // 3247 // This assumption is optimistic, as there could be free registers available 3248 // when we need to pass this argument in memory, and LLVM could try to pass 3249 // the argument in the free register. This does not seem to happen currently, 3250 // but this code would be much safer if we could mark the argument with 3251 // 'onstack'. See PR12193. 3252 if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty) && 3253 !Ty->isBitIntType()) { 3254 // Treat an enum type as its underlying type. 3255 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 3256 Ty = EnumTy->getDecl()->getIntegerType(); 3257 3258 return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty) 3259 : ABIArgInfo::getDirect()); 3260 } 3261 3262 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 3263 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 3264 3265 // Compute the byval alignment. We specify the alignment of the byval in all 3266 // cases so that the mid-level optimizer knows the alignment of the byval. 3267 unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U); 3268 3269 // Attempt to avoid passing indirect results using byval when possible. This 3270 // is important for good codegen. 3271 // 3272 // We do this by coercing the value into a scalar type which the backend can 3273 // handle naturally (i.e., without using byval). 3274 // 3275 // For simplicity, we currently only do this when we have exhausted all of the 3276 // free integer registers. Doing this when there are free integer registers 3277 // would require more care, as we would have to ensure that the coerced value 3278 // did not claim the unused register. That would require either reording the 3279 // arguments to the function (so that any subsequent inreg values came first), 3280 // or only doing this optimization when there were no following arguments that 3281 // might be inreg. 3282 // 3283 // We currently expect it to be rare (particularly in well written code) for 3284 // arguments to be passed on the stack when there are still free integer 3285 // registers available (this would typically imply large structs being passed 3286 // by value), so this seems like a fair tradeoff for now. 3287 // 3288 // We can revisit this if the backend grows support for 'onstack' parameter 3289 // attributes. See PR12193. 3290 if (freeIntRegs == 0) { 3291 uint64_t Size = getContext().getTypeSize(Ty); 3292 3293 // If this type fits in an eightbyte, coerce it into the matching integral 3294 // type, which will end up on the stack (with alignment 8). 3295 if (Align == 8 && Size <= 64) 3296 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 3297 Size)); 3298 } 3299 3300 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(Align)); 3301 } 3302 3303 /// The ABI specifies that a value should be passed in a full vector XMM/YMM 3304 /// register. Pick an LLVM IR type that will be passed as a vector register. 3305 llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const { 3306 // Wrapper structs/arrays that only contain vectors are passed just like 3307 // vectors; strip them off if present. 3308 if (const Type *InnerTy = isSingleElementStruct(Ty, getContext())) 3309 Ty = QualType(InnerTy, 0); 3310 3311 llvm::Type *IRType = CGT.ConvertType(Ty); 3312 if (isa<llvm::VectorType>(IRType)) { 3313 // Don't pass vXi128 vectors in their native type, the backend can't 3314 // legalize them. 3315 if (passInt128VectorsInMem() && 3316 cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy(128)) { 3317 // Use a vXi64 vector. 3318 uint64_t Size = getContext().getTypeSize(Ty); 3319 return llvm::FixedVectorType::get(llvm::Type::getInt64Ty(getVMContext()), 3320 Size / 64); 3321 } 3322 3323 return IRType; 3324 } 3325 3326 if (IRType->getTypeID() == llvm::Type::FP128TyID) 3327 return IRType; 3328 3329 // We couldn't find the preferred IR vector type for 'Ty'. 3330 uint64_t Size = getContext().getTypeSize(Ty); 3331 assert((Size == 128 || Size == 256 || Size == 512) && "Invalid type found!"); 3332 3333 3334 // Return a LLVM IR vector type based on the size of 'Ty'. 3335 return llvm::FixedVectorType::get(llvm::Type::getDoubleTy(getVMContext()), 3336 Size / 64); 3337 } 3338 3339 /// BitsContainNoUserData - Return true if the specified [start,end) bit range 3340 /// is known to either be off the end of the specified type or being in 3341 /// alignment padding. The user type specified is known to be at most 128 bits 3342 /// in size, and have passed through X86_64ABIInfo::classify with a successful 3343 /// classification that put one of the two halves in the INTEGER class. 3344 /// 3345 /// It is conservatively correct to return false. 3346 static bool BitsContainNoUserData(QualType Ty, unsigned StartBit, 3347 unsigned EndBit, ASTContext &Context) { 3348 // If the bytes being queried are off the end of the type, there is no user 3349 // data hiding here. This handles analysis of builtins, vectors and other 3350 // types that don't contain interesting padding. 3351 unsigned TySize = (unsigned)Context.getTypeSize(Ty); 3352 if (TySize <= StartBit) 3353 return true; 3354 3355 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) { 3356 unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType()); 3357 unsigned NumElts = (unsigned)AT->getSize().getZExtValue(); 3358 3359 // Check each element to see if the element overlaps with the queried range. 3360 for (unsigned i = 0; i != NumElts; ++i) { 3361 // If the element is after the span we care about, then we're done.. 3362 unsigned EltOffset = i*EltSize; 3363 if (EltOffset >= EndBit) break; 3364 3365 unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0; 3366 if (!BitsContainNoUserData(AT->getElementType(), EltStart, 3367 EndBit-EltOffset, Context)) 3368 return false; 3369 } 3370 // If it overlaps no elements, then it is safe to process as padding. 3371 return true; 3372 } 3373 3374 if (const RecordType *RT = Ty->getAs<RecordType>()) { 3375 const RecordDecl *RD = RT->getDecl(); 3376 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); 3377 3378 // If this is a C++ record, check the bases first. 3379 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 3380 for (const auto &I : CXXRD->bases()) { 3381 assert(!I.isVirtual() && !I.getType()->isDependentType() && 3382 "Unexpected base class!"); 3383 const auto *Base = 3384 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl()); 3385 3386 // If the base is after the span we care about, ignore it. 3387 unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base)); 3388 if (BaseOffset >= EndBit) continue; 3389 3390 unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0; 3391 if (!BitsContainNoUserData(I.getType(), BaseStart, 3392 EndBit-BaseOffset, Context)) 3393 return false; 3394 } 3395 } 3396 3397 // Verify that no field has data that overlaps the region of interest. Yes 3398 // this could be sped up a lot by being smarter about queried fields, 3399 // however we're only looking at structs up to 16 bytes, so we don't care 3400 // much. 3401 unsigned idx = 0; 3402 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 3403 i != e; ++i, ++idx) { 3404 unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx); 3405 3406 // If we found a field after the region we care about, then we're done. 3407 if (FieldOffset >= EndBit) break; 3408 3409 unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0; 3410 if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset, 3411 Context)) 3412 return false; 3413 } 3414 3415 // If nothing in this record overlapped the area of interest, then we're 3416 // clean. 3417 return true; 3418 } 3419 3420 return false; 3421 } 3422 3423 /// getFPTypeAtOffset - Return a floating point type at the specified offset. 3424 static llvm::Type *getFPTypeAtOffset(llvm::Type *IRType, unsigned IROffset, 3425 const llvm::DataLayout &TD) { 3426 if (IROffset == 0 && IRType->isFloatingPointTy()) 3427 return IRType; 3428 3429 // If this is a struct, recurse into the field at the specified offset. 3430 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) { 3431 if (!STy->getNumContainedTypes()) 3432 return nullptr; 3433 3434 const llvm::StructLayout *SL = TD.getStructLayout(STy); 3435 unsigned Elt = SL->getElementContainingOffset(IROffset); 3436 IROffset -= SL->getElementOffset(Elt); 3437 return getFPTypeAtOffset(STy->getElementType(Elt), IROffset, TD); 3438 } 3439 3440 // If this is an array, recurse into the field at the specified offset. 3441 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) { 3442 llvm::Type *EltTy = ATy->getElementType(); 3443 unsigned EltSize = TD.getTypeAllocSize(EltTy); 3444 IROffset -= IROffset / EltSize * EltSize; 3445 return getFPTypeAtOffset(EltTy, IROffset, TD); 3446 } 3447 3448 return nullptr; 3449 } 3450 3451 /// GetSSETypeAtOffset - Return a type that will be passed by the backend in the 3452 /// low 8 bytes of an XMM register, corresponding to the SSE class. 3453 llvm::Type *X86_64ABIInfo:: 3454 GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset, 3455 QualType SourceTy, unsigned SourceOffset) const { 3456 const llvm::DataLayout &TD = getDataLayout(); 3457 unsigned SourceSize = 3458 (unsigned)getContext().getTypeSize(SourceTy) / 8 - SourceOffset; 3459 llvm::Type *T0 = getFPTypeAtOffset(IRType, IROffset, TD); 3460 if (!T0 || T0->isDoubleTy()) 3461 return llvm::Type::getDoubleTy(getVMContext()); 3462 3463 // Get the adjacent FP type. 3464 llvm::Type *T1 = nullptr; 3465 unsigned T0Size = TD.getTypeAllocSize(T0); 3466 if (SourceSize > T0Size) 3467 T1 = getFPTypeAtOffset(IRType, IROffset + T0Size, TD); 3468 if (T1 == nullptr) { 3469 // Check if IRType is a half + float. float type will be in IROffset+4 due 3470 // to its alignment. 3471 if (T0->isHalfTy() && SourceSize > 4) 3472 T1 = getFPTypeAtOffset(IRType, IROffset + 4, TD); 3473 // If we can't get a second FP type, return a simple half or float. 3474 // avx512fp16-abi.c:pr51813_2 shows it works to return float for 3475 // {float, i8} too. 3476 if (T1 == nullptr) 3477 return T0; 3478 } 3479 3480 if (T0->isFloatTy() && T1->isFloatTy()) 3481 return llvm::FixedVectorType::get(T0, 2); 3482 3483 if (T0->isHalfTy() && T1->isHalfTy()) { 3484 llvm::Type *T2 = nullptr; 3485 if (SourceSize > 4) 3486 T2 = getFPTypeAtOffset(IRType, IROffset + 4, TD); 3487 if (T2 == nullptr) 3488 return llvm::FixedVectorType::get(T0, 2); 3489 return llvm::FixedVectorType::get(T0, 4); 3490 } 3491 3492 if (T0->isHalfTy() || T1->isHalfTy()) 3493 return llvm::FixedVectorType::get(llvm::Type::getHalfTy(getVMContext()), 4); 3494 3495 return llvm::Type::getDoubleTy(getVMContext()); 3496 } 3497 3498 3499 /// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in 3500 /// an 8-byte GPR. This means that we either have a scalar or we are talking 3501 /// about the high or low part of an up-to-16-byte struct. This routine picks 3502 /// the best LLVM IR type to represent this, which may be i64 or may be anything 3503 /// else that the backend will pass in a GPR that works better (e.g. i8, %foo*, 3504 /// etc). 3505 /// 3506 /// PrefType is an LLVM IR type that corresponds to (part of) the IR type for 3507 /// the source type. IROffset is an offset in bytes into the LLVM IR type that 3508 /// the 8-byte value references. PrefType may be null. 3509 /// 3510 /// SourceTy is the source-level type for the entire argument. SourceOffset is 3511 /// an offset into this that we're processing (which is always either 0 or 8). 3512 /// 3513 llvm::Type *X86_64ABIInfo:: 3514 GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset, 3515 QualType SourceTy, unsigned SourceOffset) const { 3516 // If we're dealing with an un-offset LLVM IR type, then it means that we're 3517 // returning an 8-byte unit starting with it. See if we can safely use it. 3518 if (IROffset == 0) { 3519 // Pointers and int64's always fill the 8-byte unit. 3520 if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) || 3521 IRType->isIntegerTy(64)) 3522 return IRType; 3523 3524 // If we have a 1/2/4-byte integer, we can use it only if the rest of the 3525 // goodness in the source type is just tail padding. This is allowed to 3526 // kick in for struct {double,int} on the int, but not on 3527 // struct{double,int,int} because we wouldn't return the second int. We 3528 // have to do this analysis on the source type because we can't depend on 3529 // unions being lowered a specific way etc. 3530 if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) || 3531 IRType->isIntegerTy(32) || 3532 (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) { 3533 unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 : 3534 cast<llvm::IntegerType>(IRType)->getBitWidth(); 3535 3536 if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth, 3537 SourceOffset*8+64, getContext())) 3538 return IRType; 3539 } 3540 } 3541 3542 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) { 3543 // If this is a struct, recurse into the field at the specified offset. 3544 const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy); 3545 if (IROffset < SL->getSizeInBytes()) { 3546 unsigned FieldIdx = SL->getElementContainingOffset(IROffset); 3547 IROffset -= SL->getElementOffset(FieldIdx); 3548 3549 return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset, 3550 SourceTy, SourceOffset); 3551 } 3552 } 3553 3554 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) { 3555 llvm::Type *EltTy = ATy->getElementType(); 3556 unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy); 3557 unsigned EltOffset = IROffset/EltSize*EltSize; 3558 return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy, 3559 SourceOffset); 3560 } 3561 3562 // Okay, we don't have any better idea of what to pass, so we pass this in an 3563 // integer register that isn't too big to fit the rest of the struct. 3564 unsigned TySizeInBytes = 3565 (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity(); 3566 3567 assert(TySizeInBytes != SourceOffset && "Empty field?"); 3568 3569 // It is always safe to classify this as an integer type up to i64 that 3570 // isn't larger than the structure. 3571 return llvm::IntegerType::get(getVMContext(), 3572 std::min(TySizeInBytes-SourceOffset, 8U)*8); 3573 } 3574 3575 3576 /// GetX86_64ByValArgumentPair - Given a high and low type that can ideally 3577 /// be used as elements of a two register pair to pass or return, return a 3578 /// first class aggregate to represent them. For example, if the low part of 3579 /// a by-value argument should be passed as i32* and the high part as float, 3580 /// return {i32*, float}. 3581 static llvm::Type * 3582 GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi, 3583 const llvm::DataLayout &TD) { 3584 // In order to correctly satisfy the ABI, we need to the high part to start 3585 // at offset 8. If the high and low parts we inferred are both 4-byte types 3586 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have 3587 // the second element at offset 8. Check for this: 3588 unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo); 3589 unsigned HiAlign = TD.getABITypeAlignment(Hi); 3590 unsigned HiStart = llvm::alignTo(LoSize, HiAlign); 3591 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!"); 3592 3593 // To handle this, we have to increase the size of the low part so that the 3594 // second element will start at an 8 byte offset. We can't increase the size 3595 // of the second element because it might make us access off the end of the 3596 // struct. 3597 if (HiStart != 8) { 3598 // There are usually two sorts of types the ABI generation code can produce 3599 // for the low part of a pair that aren't 8 bytes in size: half, float or 3600 // i8/i16/i32. This can also include pointers when they are 32-bit (X32 and 3601 // NaCl). 3602 // Promote these to a larger type. 3603 if (Lo->isHalfTy() || Lo->isFloatTy()) 3604 Lo = llvm::Type::getDoubleTy(Lo->getContext()); 3605 else { 3606 assert((Lo->isIntegerTy() || Lo->isPointerTy()) 3607 && "Invalid/unknown lo type"); 3608 Lo = llvm::Type::getInt64Ty(Lo->getContext()); 3609 } 3610 } 3611 3612 llvm::StructType *Result = llvm::StructType::get(Lo, Hi); 3613 3614 // Verify that the second element is at an 8-byte offset. 3615 assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 && 3616 "Invalid x86-64 argument pair!"); 3617 return Result; 3618 } 3619 3620 ABIArgInfo X86_64ABIInfo:: 3621 classifyReturnType(QualType RetTy) const { 3622 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the 3623 // classification algorithm. 3624 X86_64ABIInfo::Class Lo, Hi; 3625 classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true); 3626 3627 // Check some invariants. 3628 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification."); 3629 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification."); 3630 3631 llvm::Type *ResType = nullptr; 3632 switch (Lo) { 3633 case NoClass: 3634 if (Hi == NoClass) 3635 return ABIArgInfo::getIgnore(); 3636 // If the low part is just padding, it takes no register, leave ResType 3637 // null. 3638 assert((Hi == SSE || Hi == Integer || Hi == X87Up) && 3639 "Unknown missing lo part"); 3640 break; 3641 3642 case SSEUp: 3643 case X87Up: 3644 llvm_unreachable("Invalid classification for lo word."); 3645 3646 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via 3647 // hidden argument. 3648 case Memory: 3649 return getIndirectReturnResult(RetTy); 3650 3651 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next 3652 // available register of the sequence %rax, %rdx is used. 3653 case Integer: 3654 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0); 3655 3656 // If we have a sign or zero extended integer, make sure to return Extend 3657 // so that the parameter gets the right LLVM IR attributes. 3658 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) { 3659 // Treat an enum type as its underlying type. 3660 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 3661 RetTy = EnumTy->getDecl()->getIntegerType(); 3662 3663 if (RetTy->isIntegralOrEnumerationType() && 3664 isPromotableIntegerTypeForABI(RetTy)) 3665 return ABIArgInfo::getExtend(RetTy); 3666 } 3667 break; 3668 3669 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next 3670 // available SSE register of the sequence %xmm0, %xmm1 is used. 3671 case SSE: 3672 ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0); 3673 break; 3674 3675 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is 3676 // returned on the X87 stack in %st0 as 80-bit x87 number. 3677 case X87: 3678 ResType = llvm::Type::getX86_FP80Ty(getVMContext()); 3679 break; 3680 3681 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real 3682 // part of the value is returned in %st0 and the imaginary part in 3683 // %st1. 3684 case ComplexX87: 3685 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification."); 3686 ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()), 3687 llvm::Type::getX86_FP80Ty(getVMContext())); 3688 break; 3689 } 3690 3691 llvm::Type *HighPart = nullptr; 3692 switch (Hi) { 3693 // Memory was handled previously and X87 should 3694 // never occur as a hi class. 3695 case Memory: 3696 case X87: 3697 llvm_unreachable("Invalid classification for hi word."); 3698 3699 case ComplexX87: // Previously handled. 3700 case NoClass: 3701 break; 3702 3703 case Integer: 3704 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8); 3705 if (Lo == NoClass) // Return HighPart at offset 8 in memory. 3706 return ABIArgInfo::getDirect(HighPart, 8); 3707 break; 3708 case SSE: 3709 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8); 3710 if (Lo == NoClass) // Return HighPart at offset 8 in memory. 3711 return ABIArgInfo::getDirect(HighPart, 8); 3712 break; 3713 3714 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte 3715 // is passed in the next available eightbyte chunk if the last used 3716 // vector register. 3717 // 3718 // SSEUP should always be preceded by SSE, just widen. 3719 case SSEUp: 3720 assert(Lo == SSE && "Unexpected SSEUp classification."); 3721 ResType = GetByteVectorType(RetTy); 3722 break; 3723 3724 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is 3725 // returned together with the previous X87 value in %st0. 3726 case X87Up: 3727 // If X87Up is preceded by X87, we don't need to do 3728 // anything. However, in some cases with unions it may not be 3729 // preceded by X87. In such situations we follow gcc and pass the 3730 // extra bits in an SSE reg. 3731 if (Lo != X87) { 3732 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8); 3733 if (Lo == NoClass) // Return HighPart at offset 8 in memory. 3734 return ABIArgInfo::getDirect(HighPart, 8); 3735 } 3736 break; 3737 } 3738 3739 // If a high part was specified, merge it together with the low part. It is 3740 // known to pass in the high eightbyte of the result. We do this by forming a 3741 // first class struct aggregate with the high and low part: {low, high} 3742 if (HighPart) 3743 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout()); 3744 3745 return ABIArgInfo::getDirect(ResType); 3746 } 3747 3748 ABIArgInfo 3749 X86_64ABIInfo::classifyArgumentType(QualType Ty, unsigned freeIntRegs, 3750 unsigned &neededInt, unsigned &neededSSE, 3751 bool isNamedArg, bool IsRegCall) const { 3752 Ty = useFirstFieldIfTransparentUnion(Ty); 3753 3754 X86_64ABIInfo::Class Lo, Hi; 3755 classify(Ty, 0, Lo, Hi, isNamedArg, IsRegCall); 3756 3757 // Check some invariants. 3758 // FIXME: Enforce these by construction. 3759 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification."); 3760 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification."); 3761 3762 neededInt = 0; 3763 neededSSE = 0; 3764 llvm::Type *ResType = nullptr; 3765 switch (Lo) { 3766 case NoClass: 3767 if (Hi == NoClass) 3768 return ABIArgInfo::getIgnore(); 3769 // If the low part is just padding, it takes no register, leave ResType 3770 // null. 3771 assert((Hi == SSE || Hi == Integer || Hi == X87Up) && 3772 "Unknown missing lo part"); 3773 break; 3774 3775 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument 3776 // on the stack. 3777 case Memory: 3778 3779 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or 3780 // COMPLEX_X87, it is passed in memory. 3781 case X87: 3782 case ComplexX87: 3783 if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect) 3784 ++neededInt; 3785 return getIndirectResult(Ty, freeIntRegs); 3786 3787 case SSEUp: 3788 case X87Up: 3789 llvm_unreachable("Invalid classification for lo word."); 3790 3791 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next 3792 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8 3793 // and %r9 is used. 3794 case Integer: 3795 ++neededInt; 3796 3797 // Pick an 8-byte type based on the preferred type. 3798 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0); 3799 3800 // If we have a sign or zero extended integer, make sure to return Extend 3801 // so that the parameter gets the right LLVM IR attributes. 3802 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) { 3803 // Treat an enum type as its underlying type. 3804 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 3805 Ty = EnumTy->getDecl()->getIntegerType(); 3806 3807 if (Ty->isIntegralOrEnumerationType() && 3808 isPromotableIntegerTypeForABI(Ty)) 3809 return ABIArgInfo::getExtend(Ty); 3810 } 3811 3812 break; 3813 3814 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next 3815 // available SSE register is used, the registers are taken in the 3816 // order from %xmm0 to %xmm7. 3817 case SSE: { 3818 llvm::Type *IRType = CGT.ConvertType(Ty); 3819 ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0); 3820 ++neededSSE; 3821 break; 3822 } 3823 } 3824 3825 llvm::Type *HighPart = nullptr; 3826 switch (Hi) { 3827 // Memory was handled previously, ComplexX87 and X87 should 3828 // never occur as hi classes, and X87Up must be preceded by X87, 3829 // which is passed in memory. 3830 case Memory: 3831 case X87: 3832 case ComplexX87: 3833 llvm_unreachable("Invalid classification for hi word."); 3834 3835 case NoClass: break; 3836 3837 case Integer: 3838 ++neededInt; 3839 // Pick an 8-byte type based on the preferred type. 3840 HighPart = GetINTEGERTypeAtOffset(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 break; 3845 3846 // X87Up generally doesn't occur here (long double is passed in 3847 // memory), except in situations involving unions. 3848 case X87Up: 3849 case SSE: 3850 HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8); 3851 3852 if (Lo == NoClass) // Pass HighPart at offset 8 in memory. 3853 return ABIArgInfo::getDirect(HighPart, 8); 3854 3855 ++neededSSE; 3856 break; 3857 3858 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the 3859 // eightbyte is passed in the upper half of the last used SSE 3860 // register. This only happens when 128-bit vectors are passed. 3861 case SSEUp: 3862 assert(Lo == SSE && "Unexpected SSEUp classification"); 3863 ResType = GetByteVectorType(Ty); 3864 break; 3865 } 3866 3867 // If a high part was specified, merge it together with the low part. It is 3868 // known to pass in the high eightbyte of the result. We do this by forming a 3869 // first class struct aggregate with the high and low part: {low, high} 3870 if (HighPart) 3871 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout()); 3872 3873 return ABIArgInfo::getDirect(ResType); 3874 } 3875 3876 ABIArgInfo 3877 X86_64ABIInfo::classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt, 3878 unsigned &NeededSSE, 3879 unsigned &MaxVectorWidth) const { 3880 auto RT = Ty->getAs<RecordType>(); 3881 assert(RT && "classifyRegCallStructType only valid with struct types"); 3882 3883 if (RT->getDecl()->hasFlexibleArrayMember()) 3884 return getIndirectReturnResult(Ty); 3885 3886 // Sum up bases 3887 if (auto CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl())) { 3888 if (CXXRD->isDynamicClass()) { 3889 NeededInt = NeededSSE = 0; 3890 return getIndirectReturnResult(Ty); 3891 } 3892 3893 for (const auto &I : CXXRD->bases()) 3894 if (classifyRegCallStructTypeImpl(I.getType(), NeededInt, NeededSSE, 3895 MaxVectorWidth) 3896 .isIndirect()) { 3897 NeededInt = NeededSSE = 0; 3898 return getIndirectReturnResult(Ty); 3899 } 3900 } 3901 3902 // Sum up members 3903 for (const auto *FD : RT->getDecl()->fields()) { 3904 QualType MTy = FD->getType(); 3905 if (MTy->isRecordType() && !MTy->isUnionType()) { 3906 if (classifyRegCallStructTypeImpl(MTy, NeededInt, NeededSSE, 3907 MaxVectorWidth) 3908 .isIndirect()) { 3909 NeededInt = NeededSSE = 0; 3910 return getIndirectReturnResult(Ty); 3911 } 3912 } else { 3913 unsigned LocalNeededInt, LocalNeededSSE; 3914 if (classifyArgumentType(MTy, UINT_MAX, LocalNeededInt, LocalNeededSSE, 3915 true, true) 3916 .isIndirect()) { 3917 NeededInt = NeededSSE = 0; 3918 return getIndirectReturnResult(Ty); 3919 } 3920 if (const auto *AT = getContext().getAsConstantArrayType(MTy)) 3921 MTy = AT->getElementType(); 3922 if (const auto *VT = MTy->getAs<VectorType>()) 3923 if (getContext().getTypeSize(VT) > MaxVectorWidth) 3924 MaxVectorWidth = getContext().getTypeSize(VT); 3925 NeededInt += LocalNeededInt; 3926 NeededSSE += LocalNeededSSE; 3927 } 3928 } 3929 3930 return ABIArgInfo::getDirect(); 3931 } 3932 3933 ABIArgInfo 3934 X86_64ABIInfo::classifyRegCallStructType(QualType Ty, unsigned &NeededInt, 3935 unsigned &NeededSSE, 3936 unsigned &MaxVectorWidth) const { 3937 3938 NeededInt = 0; 3939 NeededSSE = 0; 3940 MaxVectorWidth = 0; 3941 3942 return classifyRegCallStructTypeImpl(Ty, NeededInt, NeededSSE, 3943 MaxVectorWidth); 3944 } 3945 3946 void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const { 3947 3948 const unsigned CallingConv = FI.getCallingConvention(); 3949 // It is possible to force Win64 calling convention on any x86_64 target by 3950 // using __attribute__((ms_abi)). In such case to correctly emit Win64 3951 // compatible code delegate this call to WinX86_64ABIInfo::computeInfo. 3952 if (CallingConv == llvm::CallingConv::Win64) { 3953 WinX86_64ABIInfo Win64ABIInfo(CGT, AVXLevel); 3954 Win64ABIInfo.computeInfo(FI); 3955 return; 3956 } 3957 3958 bool IsRegCall = CallingConv == llvm::CallingConv::X86_RegCall; 3959 3960 // Keep track of the number of assigned registers. 3961 unsigned FreeIntRegs = IsRegCall ? 11 : 6; 3962 unsigned FreeSSERegs = IsRegCall ? 16 : 8; 3963 unsigned NeededInt = 0, NeededSSE = 0, MaxVectorWidth = 0; 3964 3965 if (!::classifyReturnType(getCXXABI(), FI, *this)) { 3966 if (IsRegCall && FI.getReturnType()->getTypePtr()->isRecordType() && 3967 !FI.getReturnType()->getTypePtr()->isUnionType()) { 3968 FI.getReturnInfo() = classifyRegCallStructType( 3969 FI.getReturnType(), NeededInt, NeededSSE, MaxVectorWidth); 3970 if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) { 3971 FreeIntRegs -= NeededInt; 3972 FreeSSERegs -= NeededSSE; 3973 } else { 3974 FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType()); 3975 } 3976 } else if (IsRegCall && FI.getReturnType()->getAs<ComplexType>() && 3977 getContext().getCanonicalType(FI.getReturnType() 3978 ->getAs<ComplexType>() 3979 ->getElementType()) == 3980 getContext().LongDoubleTy) 3981 // Complex Long Double Type is passed in Memory when Regcall 3982 // calling convention is used. 3983 FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType()); 3984 else 3985 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 3986 } 3987 3988 // If the return value is indirect, then the hidden argument is consuming one 3989 // integer register. 3990 if (FI.getReturnInfo().isIndirect()) 3991 --FreeIntRegs; 3992 else if (NeededSSE && MaxVectorWidth > 0) 3993 FI.setMaxVectorWidth(MaxVectorWidth); 3994 3995 // The chain argument effectively gives us another free register. 3996 if (FI.isChainCall()) 3997 ++FreeIntRegs; 3998 3999 unsigned NumRequiredArgs = FI.getNumRequiredArgs(); 4000 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers 4001 // get assigned (in left-to-right order) for passing as follows... 4002 unsigned ArgNo = 0; 4003 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end(); 4004 it != ie; ++it, ++ArgNo) { 4005 bool IsNamedArg = ArgNo < NumRequiredArgs; 4006 4007 if (IsRegCall && it->type->isStructureOrClassType()) 4008 it->info = classifyRegCallStructType(it->type, NeededInt, NeededSSE, 4009 MaxVectorWidth); 4010 else 4011 it->info = classifyArgumentType(it->type, FreeIntRegs, NeededInt, 4012 NeededSSE, IsNamedArg); 4013 4014 // AMD64-ABI 3.2.3p3: If there are no registers available for any 4015 // eightbyte of an argument, the whole argument is passed on the 4016 // stack. If registers have already been assigned for some 4017 // eightbytes of such an argument, the assignments get reverted. 4018 if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) { 4019 FreeIntRegs -= NeededInt; 4020 FreeSSERegs -= NeededSSE; 4021 if (MaxVectorWidth > FI.getMaxVectorWidth()) 4022 FI.setMaxVectorWidth(MaxVectorWidth); 4023 } else { 4024 it->info = getIndirectResult(it->type, FreeIntRegs); 4025 } 4026 } 4027 } 4028 4029 static Address EmitX86_64VAArgFromMemory(CodeGenFunction &CGF, 4030 Address VAListAddr, QualType Ty) { 4031 Address overflow_arg_area_p = 4032 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_p"); 4033 llvm::Value *overflow_arg_area = 4034 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area"); 4035 4036 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16 4037 // byte boundary if alignment needed by type exceeds 8 byte boundary. 4038 // It isn't stated explicitly in the standard, but in practice we use 4039 // alignment greater than 16 where necessary. 4040 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty); 4041 if (Align > CharUnits::fromQuantity(8)) { 4042 overflow_arg_area = emitRoundPointerUpToAlignment(CGF, overflow_arg_area, 4043 Align); 4044 } 4045 4046 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area. 4047 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty); 4048 llvm::Value *Res = 4049 CGF.Builder.CreateBitCast(overflow_arg_area, 4050 llvm::PointerType::getUnqual(LTy)); 4051 4052 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to: 4053 // l->overflow_arg_area + sizeof(type). 4054 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to 4055 // an 8 byte boundary. 4056 4057 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8; 4058 llvm::Value *Offset = 4059 llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7); 4060 overflow_arg_area = CGF.Builder.CreateGEP(CGF.Int8Ty, overflow_arg_area, 4061 Offset, "overflow_arg_area.next"); 4062 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p); 4063 4064 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type. 4065 return Address(Res, LTy, Align); 4066 } 4067 4068 Address X86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 4069 QualType Ty) const { 4070 // Assume that va_list type is correct; should be pointer to LLVM type: 4071 // struct { 4072 // i32 gp_offset; 4073 // i32 fp_offset; 4074 // i8* overflow_arg_area; 4075 // i8* reg_save_area; 4076 // }; 4077 unsigned neededInt, neededSSE; 4078 4079 Ty = getContext().getCanonicalType(Ty); 4080 ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE, 4081 /*isNamedArg*/false); 4082 4083 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed 4084 // in the registers. If not go to step 7. 4085 if (!neededInt && !neededSSE) 4086 return EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty); 4087 4088 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of 4089 // general purpose registers needed to pass type and num_fp to hold 4090 // the number of floating point registers needed. 4091 4092 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into 4093 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or 4094 // l->fp_offset > 304 - num_fp * 16 go to step 7. 4095 // 4096 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of 4097 // register save space). 4098 4099 llvm::Value *InRegs = nullptr; 4100 Address gp_offset_p = Address::invalid(), fp_offset_p = Address::invalid(); 4101 llvm::Value *gp_offset = nullptr, *fp_offset = nullptr; 4102 if (neededInt) { 4103 gp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "gp_offset_p"); 4104 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset"); 4105 InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8); 4106 InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp"); 4107 } 4108 4109 if (neededSSE) { 4110 fp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 1, "fp_offset_p"); 4111 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset"); 4112 llvm::Value *FitsInFP = 4113 llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16); 4114 FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp"); 4115 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP; 4116 } 4117 4118 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg"); 4119 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem"); 4120 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end"); 4121 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock); 4122 4123 // Emit code to load the value if it was passed in registers. 4124 4125 CGF.EmitBlock(InRegBlock); 4126 4127 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with 4128 // an offset of l->gp_offset and/or l->fp_offset. This may require 4129 // copying to a temporary location in case the parameter is passed 4130 // in different register classes or requires an alignment greater 4131 // than 8 for general purpose registers and 16 for XMM registers. 4132 // 4133 // FIXME: This really results in shameful code when we end up needing to 4134 // collect arguments from different places; often what should result in a 4135 // simple assembling of a structure from scattered addresses has many more 4136 // loads than necessary. Can we clean this up? 4137 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty); 4138 llvm::Value *RegSaveArea = CGF.Builder.CreateLoad( 4139 CGF.Builder.CreateStructGEP(VAListAddr, 3), "reg_save_area"); 4140 4141 Address RegAddr = Address::invalid(); 4142 if (neededInt && neededSSE) { 4143 // FIXME: Cleanup. 4144 assert(AI.isDirect() && "Unexpected ABI info for mixed regs"); 4145 llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType()); 4146 Address Tmp = CGF.CreateMemTemp(Ty); 4147 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST); 4148 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs"); 4149 llvm::Type *TyLo = ST->getElementType(0); 4150 llvm::Type *TyHi = ST->getElementType(1); 4151 assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) && 4152 "Unexpected ABI info for mixed regs"); 4153 llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo); 4154 llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi); 4155 llvm::Value *GPAddr = 4156 CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, gp_offset); 4157 llvm::Value *FPAddr = 4158 CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, fp_offset); 4159 llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr; 4160 llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr; 4161 4162 // Copy the first element. 4163 // FIXME: Our choice of alignment here and below is probably pessimistic. 4164 llvm::Value *V = CGF.Builder.CreateAlignedLoad( 4165 TyLo, CGF.Builder.CreateBitCast(RegLoAddr, PTyLo), 4166 CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyLo))); 4167 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0)); 4168 4169 // Copy the second element. 4170 V = CGF.Builder.CreateAlignedLoad( 4171 TyHi, CGF.Builder.CreateBitCast(RegHiAddr, PTyHi), 4172 CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyHi))); 4173 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1)); 4174 4175 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy); 4176 } else if (neededInt) { 4177 RegAddr = Address(CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, gp_offset), 4178 CGF.Int8Ty, CharUnits::fromQuantity(8)); 4179 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy); 4180 4181 // Copy to a temporary if necessary to ensure the appropriate alignment. 4182 auto TInfo = getContext().getTypeInfoInChars(Ty); 4183 uint64_t TySize = TInfo.Width.getQuantity(); 4184 CharUnits TyAlign = TInfo.Align; 4185 4186 // Copy into a temporary if the type is more aligned than the 4187 // register save area. 4188 if (TyAlign.getQuantity() > 8) { 4189 Address Tmp = CGF.CreateMemTemp(Ty); 4190 CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, false); 4191 RegAddr = Tmp; 4192 } 4193 4194 } else if (neededSSE == 1) { 4195 RegAddr = Address(CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, fp_offset), 4196 CGF.Int8Ty, CharUnits::fromQuantity(16)); 4197 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy); 4198 } else { 4199 assert(neededSSE == 2 && "Invalid number of needed registers!"); 4200 // SSE registers are spaced 16 bytes apart in the register save 4201 // area, we need to collect the two eightbytes together. 4202 // The ABI isn't explicit about this, but it seems reasonable 4203 // to assume that the slots are 16-byte aligned, since the stack is 4204 // naturally 16-byte aligned and the prologue is expected to store 4205 // all the SSE registers to the RSA. 4206 Address RegAddrLo = Address(CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, 4207 fp_offset), 4208 CGF.Int8Ty, CharUnits::fromQuantity(16)); 4209 Address RegAddrHi = 4210 CGF.Builder.CreateConstInBoundsByteGEP(RegAddrLo, 4211 CharUnits::fromQuantity(16)); 4212 llvm::Type *ST = AI.canHaveCoerceToType() 4213 ? AI.getCoerceToType() 4214 : llvm::StructType::get(CGF.DoubleTy, CGF.DoubleTy); 4215 llvm::Value *V; 4216 Address Tmp = CGF.CreateMemTemp(Ty); 4217 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST); 4218 V = CGF.Builder.CreateLoad(CGF.Builder.CreateElementBitCast( 4219 RegAddrLo, ST->getStructElementType(0))); 4220 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0)); 4221 V = CGF.Builder.CreateLoad(CGF.Builder.CreateElementBitCast( 4222 RegAddrHi, ST->getStructElementType(1))); 4223 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1)); 4224 4225 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy); 4226 } 4227 4228 // AMD64-ABI 3.5.7p5: Step 5. Set: 4229 // l->gp_offset = l->gp_offset + num_gp * 8 4230 // l->fp_offset = l->fp_offset + num_fp * 16. 4231 if (neededInt) { 4232 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8); 4233 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset), 4234 gp_offset_p); 4235 } 4236 if (neededSSE) { 4237 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16); 4238 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset), 4239 fp_offset_p); 4240 } 4241 CGF.EmitBranch(ContBlock); 4242 4243 // Emit code to load the value if it was passed in memory. 4244 4245 CGF.EmitBlock(InMemBlock); 4246 Address MemAddr = EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty); 4247 4248 // Return the appropriate result. 4249 4250 CGF.EmitBlock(ContBlock); 4251 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, MemAddr, InMemBlock, 4252 "vaarg.addr"); 4253 return ResAddr; 4254 } 4255 4256 Address X86_64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr, 4257 QualType Ty) const { 4258 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is 4259 // not 1, 2, 4, or 8 bytes, must be passed by reference." 4260 uint64_t Width = getContext().getTypeSize(Ty); 4261 bool IsIndirect = Width > 64 || !llvm::isPowerOf2_64(Width); 4262 4263 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, 4264 CGF.getContext().getTypeInfoInChars(Ty), 4265 CharUnits::fromQuantity(8), 4266 /*allowHigherAlign*/ false); 4267 } 4268 4269 ABIArgInfo WinX86_64ABIInfo::reclassifyHvaArgForVectorCall( 4270 QualType Ty, unsigned &FreeSSERegs, const ABIArgInfo ¤t) const { 4271 const Type *Base = nullptr; 4272 uint64_t NumElts = 0; 4273 4274 if (!Ty->isBuiltinType() && !Ty->isVectorType() && 4275 isHomogeneousAggregate(Ty, Base, NumElts) && FreeSSERegs >= NumElts) { 4276 FreeSSERegs -= NumElts; 4277 return getDirectX86Hva(); 4278 } 4279 return current; 4280 } 4281 4282 ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, unsigned &FreeSSERegs, 4283 bool IsReturnType, bool IsVectorCall, 4284 bool IsRegCall) const { 4285 4286 if (Ty->isVoidType()) 4287 return ABIArgInfo::getIgnore(); 4288 4289 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 4290 Ty = EnumTy->getDecl()->getIntegerType(); 4291 4292 TypeInfo Info = getContext().getTypeInfo(Ty); 4293 uint64_t Width = Info.Width; 4294 CharUnits Align = getContext().toCharUnitsFromBits(Info.Align); 4295 4296 const RecordType *RT = Ty->getAs<RecordType>(); 4297 if (RT) { 4298 if (!IsReturnType) { 4299 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI())) 4300 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 4301 } 4302 4303 if (RT->getDecl()->hasFlexibleArrayMember()) 4304 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 4305 4306 } 4307 4308 const Type *Base = nullptr; 4309 uint64_t NumElts = 0; 4310 // vectorcall adds the concept of a homogenous vector aggregate, similar to 4311 // other targets. 4312 if ((IsVectorCall || IsRegCall) && 4313 isHomogeneousAggregate(Ty, Base, NumElts)) { 4314 if (IsRegCall) { 4315 if (FreeSSERegs >= NumElts) { 4316 FreeSSERegs -= NumElts; 4317 if (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType()) 4318 return ABIArgInfo::getDirect(); 4319 return ABIArgInfo::getExpand(); 4320 } 4321 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false); 4322 } else if (IsVectorCall) { 4323 if (FreeSSERegs >= NumElts && 4324 (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())) { 4325 FreeSSERegs -= NumElts; 4326 return ABIArgInfo::getDirect(); 4327 } else if (IsReturnType) { 4328 return ABIArgInfo::getExpand(); 4329 } else if (!Ty->isBuiltinType() && !Ty->isVectorType()) { 4330 // HVAs are delayed and reclassified in the 2nd step. 4331 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false); 4332 } 4333 } 4334 } 4335 4336 if (Ty->isMemberPointerType()) { 4337 // If the member pointer is represented by an LLVM int or ptr, pass it 4338 // directly. 4339 llvm::Type *LLTy = CGT.ConvertType(Ty); 4340 if (LLTy->isPointerTy() || LLTy->isIntegerTy()) 4341 return ABIArgInfo::getDirect(); 4342 } 4343 4344 if (RT || Ty->isAnyComplexType() || Ty->isMemberPointerType()) { 4345 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is 4346 // not 1, 2, 4, or 8 bytes, must be passed by reference." 4347 if (Width > 64 || !llvm::isPowerOf2_64(Width)) 4348 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 4349 4350 // Otherwise, coerce it to a small integer. 4351 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Width)); 4352 } 4353 4354 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) { 4355 switch (BT->getKind()) { 4356 case BuiltinType::Bool: 4357 // Bool type is always extended to the ABI, other builtin types are not 4358 // extended. 4359 return ABIArgInfo::getExtend(Ty); 4360 4361 case BuiltinType::LongDouble: 4362 // Mingw64 GCC uses the old 80 bit extended precision floating point 4363 // unit. It passes them indirectly through memory. 4364 if (IsMingw64) { 4365 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat(); 4366 if (LDF == &llvm::APFloat::x87DoubleExtended()) 4367 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false); 4368 } 4369 break; 4370 4371 case BuiltinType::Int128: 4372 case BuiltinType::UInt128: 4373 // If it's a parameter type, the normal ABI rule is that arguments larger 4374 // than 8 bytes are passed indirectly. GCC follows it. We follow it too, 4375 // even though it isn't particularly efficient. 4376 if (!IsReturnType) 4377 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false); 4378 4379 // Mingw64 GCC returns i128 in XMM0. Coerce to v2i64 to handle that. 4380 // Clang matches them for compatibility. 4381 return ABIArgInfo::getDirect(llvm::FixedVectorType::get( 4382 llvm::Type::getInt64Ty(getVMContext()), 2)); 4383 4384 default: 4385 break; 4386 } 4387 } 4388 4389 if (Ty->isBitIntType()) { 4390 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is 4391 // not 1, 2, 4, or 8 bytes, must be passed by reference." 4392 // However, non-power-of-two bit-precise integers will be passed as 1, 2, 4, 4393 // or 8 bytes anyway as long is it fits in them, so we don't have to check 4394 // the power of 2. 4395 if (Width <= 64) 4396 return ABIArgInfo::getDirect(); 4397 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false); 4398 } 4399 4400 return ABIArgInfo::getDirect(); 4401 } 4402 4403 void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const { 4404 const unsigned CC = FI.getCallingConvention(); 4405 bool IsVectorCall = CC == llvm::CallingConv::X86_VectorCall; 4406 bool IsRegCall = CC == llvm::CallingConv::X86_RegCall; 4407 4408 // If __attribute__((sysv_abi)) is in use, use the SysV argument 4409 // classification rules. 4410 if (CC == llvm::CallingConv::X86_64_SysV) { 4411 X86_64ABIInfo SysVABIInfo(CGT, AVXLevel); 4412 SysVABIInfo.computeInfo(FI); 4413 return; 4414 } 4415 4416 unsigned FreeSSERegs = 0; 4417 if (IsVectorCall) { 4418 // We can use up to 4 SSE return registers with vectorcall. 4419 FreeSSERegs = 4; 4420 } else if (IsRegCall) { 4421 // RegCall gives us 16 SSE registers. 4422 FreeSSERegs = 16; 4423 } 4424 4425 if (!getCXXABI().classifyReturnType(FI)) 4426 FI.getReturnInfo() = classify(FI.getReturnType(), FreeSSERegs, true, 4427 IsVectorCall, IsRegCall); 4428 4429 if (IsVectorCall) { 4430 // We can use up to 6 SSE register parameters with vectorcall. 4431 FreeSSERegs = 6; 4432 } else if (IsRegCall) { 4433 // RegCall gives us 16 SSE registers, we can reuse the return registers. 4434 FreeSSERegs = 16; 4435 } 4436 4437 unsigned ArgNum = 0; 4438 unsigned ZeroSSERegs = 0; 4439 for (auto &I : FI.arguments()) { 4440 // Vectorcall in x64 only permits the first 6 arguments to be passed as 4441 // XMM/YMM registers. After the sixth argument, pretend no vector 4442 // registers are left. 4443 unsigned *MaybeFreeSSERegs = 4444 (IsVectorCall && ArgNum >= 6) ? &ZeroSSERegs : &FreeSSERegs; 4445 I.info = 4446 classify(I.type, *MaybeFreeSSERegs, false, IsVectorCall, IsRegCall); 4447 ++ArgNum; 4448 } 4449 4450 if (IsVectorCall) { 4451 // For vectorcall, assign aggregate HVAs to any free vector registers in a 4452 // second pass. 4453 for (auto &I : FI.arguments()) 4454 I.info = reclassifyHvaArgForVectorCall(I.type, FreeSSERegs, I.info); 4455 } 4456 } 4457 4458 Address WinX86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 4459 QualType Ty) const { 4460 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is 4461 // not 1, 2, 4, or 8 bytes, must be passed by reference." 4462 uint64_t Width = getContext().getTypeSize(Ty); 4463 bool IsIndirect = Width > 64 || !llvm::isPowerOf2_64(Width); 4464 4465 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, 4466 CGF.getContext().getTypeInfoInChars(Ty), 4467 CharUnits::fromQuantity(8), 4468 /*allowHigherAlign*/ false); 4469 } 4470 4471 static bool PPC_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 4472 llvm::Value *Address, bool Is64Bit, 4473 bool IsAIX) { 4474 // This is calculated from the LLVM and GCC tables and verified 4475 // against gcc output. AFAIK all PPC ABIs use the same encoding. 4476 4477 CodeGen::CGBuilderTy &Builder = CGF.Builder; 4478 4479 llvm::IntegerType *i8 = CGF.Int8Ty; 4480 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4); 4481 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8); 4482 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16); 4483 4484 // 0-31: r0-31, the 4-byte or 8-byte general-purpose registers 4485 AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 0, 31); 4486 4487 // 32-63: fp0-31, the 8-byte floating-point registers 4488 AssignToArrayRange(Builder, Address, Eight8, 32, 63); 4489 4490 // 64-67 are various 4-byte or 8-byte special-purpose registers: 4491 // 64: mq 4492 // 65: lr 4493 // 66: ctr 4494 // 67: ap 4495 AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 64, 67); 4496 4497 // 68-76 are various 4-byte special-purpose registers: 4498 // 68-75 cr0-7 4499 // 76: xer 4500 AssignToArrayRange(Builder, Address, Four8, 68, 76); 4501 4502 // 77-108: v0-31, the 16-byte vector registers 4503 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108); 4504 4505 // 109: vrsave 4506 // 110: vscr 4507 AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 109, 110); 4508 4509 // AIX does not utilize the rest of the registers. 4510 if (IsAIX) 4511 return false; 4512 4513 // 111: spe_acc 4514 // 112: spefscr 4515 // 113: sfp 4516 AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 111, 113); 4517 4518 if (!Is64Bit) 4519 return false; 4520 4521 // TODO: Need to verify if these registers are used on 64 bit AIX with Power8 4522 // or above CPU. 4523 // 64-bit only registers: 4524 // 114: tfhar 4525 // 115: tfiar 4526 // 116: texasr 4527 AssignToArrayRange(Builder, Address, Eight8, 114, 116); 4528 4529 return false; 4530 } 4531 4532 // AIX 4533 namespace { 4534 /// AIXABIInfo - The AIX XCOFF ABI information. 4535 class AIXABIInfo : public ABIInfo { 4536 const bool Is64Bit; 4537 const unsigned PtrByteSize; 4538 CharUnits getParamTypeAlignment(QualType Ty) const; 4539 4540 public: 4541 AIXABIInfo(CodeGen::CodeGenTypes &CGT, bool Is64Bit) 4542 : ABIInfo(CGT), Is64Bit(Is64Bit), PtrByteSize(Is64Bit ? 8 : 4) {} 4543 4544 bool isPromotableTypeForABI(QualType Ty) const; 4545 4546 ABIArgInfo classifyReturnType(QualType RetTy) const; 4547 ABIArgInfo classifyArgumentType(QualType Ty) const; 4548 4549 void computeInfo(CGFunctionInfo &FI) const override { 4550 if (!getCXXABI().classifyReturnType(FI)) 4551 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 4552 4553 for (auto &I : FI.arguments()) 4554 I.info = classifyArgumentType(I.type); 4555 } 4556 4557 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 4558 QualType Ty) const override; 4559 }; 4560 4561 class AIXTargetCodeGenInfo : public TargetCodeGenInfo { 4562 const bool Is64Bit; 4563 4564 public: 4565 AIXTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool Is64Bit) 4566 : TargetCodeGenInfo(std::make_unique<AIXABIInfo>(CGT, Is64Bit)), 4567 Is64Bit(Is64Bit) {} 4568 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 4569 return 1; // r1 is the dedicated stack pointer 4570 } 4571 4572 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 4573 llvm::Value *Address) const override; 4574 }; 4575 } // namespace 4576 4577 // Return true if the ABI requires Ty to be passed sign- or zero- 4578 // extended to 32/64 bits. 4579 bool AIXABIInfo::isPromotableTypeForABI(QualType Ty) const { 4580 // Treat an enum type as its underlying type. 4581 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 4582 Ty = EnumTy->getDecl()->getIntegerType(); 4583 4584 // Promotable integer types are required to be promoted by the ABI. 4585 if (Ty->isPromotableIntegerType()) 4586 return true; 4587 4588 if (!Is64Bit) 4589 return false; 4590 4591 // For 64 bit mode, in addition to the usual promotable integer types, we also 4592 // need to extend all 32-bit types, since the ABI requires promotion to 64 4593 // bits. 4594 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) 4595 switch (BT->getKind()) { 4596 case BuiltinType::Int: 4597 case BuiltinType::UInt: 4598 return true; 4599 default: 4600 break; 4601 } 4602 4603 return false; 4604 } 4605 4606 ABIArgInfo AIXABIInfo::classifyReturnType(QualType RetTy) const { 4607 if (RetTy->isAnyComplexType()) 4608 return ABIArgInfo::getDirect(); 4609 4610 if (RetTy->isVectorType()) 4611 return ABIArgInfo::getDirect(); 4612 4613 if (RetTy->isVoidType()) 4614 return ABIArgInfo::getIgnore(); 4615 4616 if (isAggregateTypeForABI(RetTy)) 4617 return getNaturalAlignIndirect(RetTy); 4618 4619 return (isPromotableTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy) 4620 : ABIArgInfo::getDirect()); 4621 } 4622 4623 ABIArgInfo AIXABIInfo::classifyArgumentType(QualType Ty) const { 4624 Ty = useFirstFieldIfTransparentUnion(Ty); 4625 4626 if (Ty->isAnyComplexType()) 4627 return ABIArgInfo::getDirect(); 4628 4629 if (Ty->isVectorType()) 4630 return ABIArgInfo::getDirect(); 4631 4632 if (isAggregateTypeForABI(Ty)) { 4633 // Records with non-trivial destructors/copy-constructors should not be 4634 // passed by value. 4635 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 4636 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 4637 4638 CharUnits CCAlign = getParamTypeAlignment(Ty); 4639 CharUnits TyAlign = getContext().getTypeAlignInChars(Ty); 4640 4641 return ABIArgInfo::getIndirect(CCAlign, /*ByVal*/ true, 4642 /*Realign*/ TyAlign > CCAlign); 4643 } 4644 4645 return (isPromotableTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty) 4646 : ABIArgInfo::getDirect()); 4647 } 4648 4649 CharUnits AIXABIInfo::getParamTypeAlignment(QualType Ty) const { 4650 // Complex types are passed just like their elements. 4651 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) 4652 Ty = CTy->getElementType(); 4653 4654 if (Ty->isVectorType()) 4655 return CharUnits::fromQuantity(16); 4656 4657 // If the structure contains a vector type, the alignment is 16. 4658 if (isRecordWithSIMDVectorType(getContext(), Ty)) 4659 return CharUnits::fromQuantity(16); 4660 4661 return CharUnits::fromQuantity(PtrByteSize); 4662 } 4663 4664 Address AIXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 4665 QualType Ty) const { 4666 4667 auto TypeInfo = getContext().getTypeInfoInChars(Ty); 4668 TypeInfo.Align = getParamTypeAlignment(Ty); 4669 4670 CharUnits SlotSize = CharUnits::fromQuantity(PtrByteSize); 4671 4672 // If we have a complex type and the base type is smaller than the register 4673 // size, the ABI calls for the real and imaginary parts to be right-adjusted 4674 // in separate words in 32bit mode or doublewords in 64bit mode. However, 4675 // Clang expects us to produce a pointer to a structure with the two parts 4676 // packed tightly. So generate loads of the real and imaginary parts relative 4677 // to the va_list pointer, and store them to a temporary structure. We do the 4678 // same as the PPC64ABI here. 4679 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) { 4680 CharUnits EltSize = TypeInfo.Width / 2; 4681 if (EltSize < SlotSize) 4682 return complexTempStructure(CGF, VAListAddr, Ty, SlotSize, EltSize, CTy); 4683 } 4684 4685 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false, TypeInfo, 4686 SlotSize, /*AllowHigher*/ true); 4687 } 4688 4689 bool AIXTargetCodeGenInfo::initDwarfEHRegSizeTable( 4690 CodeGen::CodeGenFunction &CGF, llvm::Value *Address) const { 4691 return PPC_initDwarfEHRegSizeTable(CGF, Address, Is64Bit, /*IsAIX*/ true); 4692 } 4693 4694 // PowerPC-32 4695 namespace { 4696 /// PPC32_SVR4_ABIInfo - The 32-bit PowerPC ELF (SVR4) ABI information. 4697 class PPC32_SVR4_ABIInfo : public DefaultABIInfo { 4698 bool IsSoftFloatABI; 4699 bool IsRetSmallStructInRegABI; 4700 4701 CharUnits getParamTypeAlignment(QualType Ty) const; 4702 4703 public: 4704 PPC32_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, bool SoftFloatABI, 4705 bool RetSmallStructInRegABI) 4706 : DefaultABIInfo(CGT), IsSoftFloatABI(SoftFloatABI), 4707 IsRetSmallStructInRegABI(RetSmallStructInRegABI) {} 4708 4709 ABIArgInfo classifyReturnType(QualType RetTy) const; 4710 4711 void computeInfo(CGFunctionInfo &FI) const override { 4712 if (!getCXXABI().classifyReturnType(FI)) 4713 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 4714 for (auto &I : FI.arguments()) 4715 I.info = classifyArgumentType(I.type); 4716 } 4717 4718 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 4719 QualType Ty) const override; 4720 }; 4721 4722 class PPC32TargetCodeGenInfo : public TargetCodeGenInfo { 4723 public: 4724 PPC32TargetCodeGenInfo(CodeGenTypes &CGT, bool SoftFloatABI, 4725 bool RetSmallStructInRegABI) 4726 : TargetCodeGenInfo(std::make_unique<PPC32_SVR4_ABIInfo>( 4727 CGT, SoftFloatABI, RetSmallStructInRegABI)) {} 4728 4729 static bool isStructReturnInRegABI(const llvm::Triple &Triple, 4730 const CodeGenOptions &Opts); 4731 4732 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 4733 // This is recovered from gcc output. 4734 return 1; // r1 is the dedicated stack pointer 4735 } 4736 4737 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 4738 llvm::Value *Address) const override; 4739 }; 4740 } 4741 4742 CharUnits PPC32_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const { 4743 // Complex types are passed just like their elements. 4744 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) 4745 Ty = CTy->getElementType(); 4746 4747 if (Ty->isVectorType()) 4748 return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16 4749 : 4); 4750 4751 // For single-element float/vector structs, we consider the whole type 4752 // to have the same alignment requirements as its single element. 4753 const Type *AlignTy = nullptr; 4754 if (const Type *EltType = isSingleElementStruct(Ty, getContext())) { 4755 const BuiltinType *BT = EltType->getAs<BuiltinType>(); 4756 if ((EltType->isVectorType() && getContext().getTypeSize(EltType) == 128) || 4757 (BT && BT->isFloatingPoint())) 4758 AlignTy = EltType; 4759 } 4760 4761 if (AlignTy) 4762 return CharUnits::fromQuantity(AlignTy->isVectorType() ? 16 : 4); 4763 return CharUnits::fromQuantity(4); 4764 } 4765 4766 ABIArgInfo PPC32_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const { 4767 uint64_t Size; 4768 4769 // -msvr4-struct-return puts small aggregates in GPR3 and GPR4. 4770 if (isAggregateTypeForABI(RetTy) && IsRetSmallStructInRegABI && 4771 (Size = getContext().getTypeSize(RetTy)) <= 64) { 4772 // System V ABI (1995), page 3-22, specified: 4773 // > A structure or union whose size is less than or equal to 8 bytes 4774 // > shall be returned in r3 and r4, as if it were first stored in the 4775 // > 8-byte aligned memory area and then the low addressed word were 4776 // > loaded into r3 and the high-addressed word into r4. Bits beyond 4777 // > the last member of the structure or union are not defined. 4778 // 4779 // GCC for big-endian PPC32 inserts the pad before the first member, 4780 // not "beyond the last member" of the struct. To stay compatible 4781 // with GCC, we coerce the struct to an integer of the same size. 4782 // LLVM will extend it and return i32 in r3, or i64 in r3:r4. 4783 if (Size == 0) 4784 return ABIArgInfo::getIgnore(); 4785 else { 4786 llvm::Type *CoerceTy = llvm::Type::getIntNTy(getVMContext(), Size); 4787 return ABIArgInfo::getDirect(CoerceTy); 4788 } 4789 } 4790 4791 return DefaultABIInfo::classifyReturnType(RetTy); 4792 } 4793 4794 // TODO: this implementation is now likely redundant with 4795 // DefaultABIInfo::EmitVAArg. 4796 Address PPC32_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAList, 4797 QualType Ty) const { 4798 if (getTarget().getTriple().isOSDarwin()) { 4799 auto TI = getContext().getTypeInfoInChars(Ty); 4800 TI.Align = getParamTypeAlignment(Ty); 4801 4802 CharUnits SlotSize = CharUnits::fromQuantity(4); 4803 return emitVoidPtrVAArg(CGF, VAList, Ty, 4804 classifyArgumentType(Ty).isIndirect(), TI, SlotSize, 4805 /*AllowHigherAlign=*/true); 4806 } 4807 4808 const unsigned OverflowLimit = 8; 4809 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) { 4810 // TODO: Implement this. For now ignore. 4811 (void)CTy; 4812 return Address::invalid(); // FIXME? 4813 } 4814 4815 // struct __va_list_tag { 4816 // unsigned char gpr; 4817 // unsigned char fpr; 4818 // unsigned short reserved; 4819 // void *overflow_arg_area; 4820 // void *reg_save_area; 4821 // }; 4822 4823 bool isI64 = Ty->isIntegerType() && getContext().getTypeSize(Ty) == 64; 4824 bool isInt = !Ty->isFloatingType(); 4825 bool isF64 = Ty->isFloatingType() && getContext().getTypeSize(Ty) == 64; 4826 4827 // All aggregates are passed indirectly? That doesn't seem consistent 4828 // with the argument-lowering code. 4829 bool isIndirect = isAggregateTypeForABI(Ty); 4830 4831 CGBuilderTy &Builder = CGF.Builder; 4832 4833 // The calling convention either uses 1-2 GPRs or 1 FPR. 4834 Address NumRegsAddr = Address::invalid(); 4835 if (isInt || IsSoftFloatABI) { 4836 NumRegsAddr = Builder.CreateStructGEP(VAList, 0, "gpr"); 4837 } else { 4838 NumRegsAddr = Builder.CreateStructGEP(VAList, 1, "fpr"); 4839 } 4840 4841 llvm::Value *NumRegs = Builder.CreateLoad(NumRegsAddr, "numUsedRegs"); 4842 4843 // "Align" the register count when TY is i64. 4844 if (isI64 || (isF64 && IsSoftFloatABI)) { 4845 NumRegs = Builder.CreateAdd(NumRegs, Builder.getInt8(1)); 4846 NumRegs = Builder.CreateAnd(NumRegs, Builder.getInt8((uint8_t) ~1U)); 4847 } 4848 4849 llvm::Value *CC = 4850 Builder.CreateICmpULT(NumRegs, Builder.getInt8(OverflowLimit), "cond"); 4851 4852 llvm::BasicBlock *UsingRegs = CGF.createBasicBlock("using_regs"); 4853 llvm::BasicBlock *UsingOverflow = CGF.createBasicBlock("using_overflow"); 4854 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont"); 4855 4856 Builder.CreateCondBr(CC, UsingRegs, UsingOverflow); 4857 4858 llvm::Type *DirectTy = CGF.ConvertType(Ty), *ElementTy = DirectTy; 4859 if (isIndirect) DirectTy = DirectTy->getPointerTo(0); 4860 4861 // Case 1: consume registers. 4862 Address RegAddr = Address::invalid(); 4863 { 4864 CGF.EmitBlock(UsingRegs); 4865 4866 Address RegSaveAreaPtr = Builder.CreateStructGEP(VAList, 4); 4867 RegAddr = Address(Builder.CreateLoad(RegSaveAreaPtr), CGF.Int8Ty, 4868 CharUnits::fromQuantity(8)); 4869 assert(RegAddr.getElementType() == CGF.Int8Ty); 4870 4871 // Floating-point registers start after the general-purpose registers. 4872 if (!(isInt || IsSoftFloatABI)) { 4873 RegAddr = Builder.CreateConstInBoundsByteGEP(RegAddr, 4874 CharUnits::fromQuantity(32)); 4875 } 4876 4877 // Get the address of the saved value by scaling the number of 4878 // registers we've used by the number of 4879 CharUnits RegSize = CharUnits::fromQuantity((isInt || IsSoftFloatABI) ? 4 : 8); 4880 llvm::Value *RegOffset = 4881 Builder.CreateMul(NumRegs, Builder.getInt8(RegSize.getQuantity())); 4882 RegAddr = Address( 4883 Builder.CreateInBoundsGEP(CGF.Int8Ty, RegAddr.getPointer(), RegOffset), 4884 CGF.Int8Ty, RegAddr.getAlignment().alignmentOfArrayElement(RegSize)); 4885 RegAddr = Builder.CreateElementBitCast(RegAddr, DirectTy); 4886 4887 // Increase the used-register count. 4888 NumRegs = 4889 Builder.CreateAdd(NumRegs, 4890 Builder.getInt8((isI64 || (isF64 && IsSoftFloatABI)) ? 2 : 1)); 4891 Builder.CreateStore(NumRegs, NumRegsAddr); 4892 4893 CGF.EmitBranch(Cont); 4894 } 4895 4896 // Case 2: consume space in the overflow area. 4897 Address MemAddr = Address::invalid(); 4898 { 4899 CGF.EmitBlock(UsingOverflow); 4900 4901 Builder.CreateStore(Builder.getInt8(OverflowLimit), NumRegsAddr); 4902 4903 // Everything in the overflow area is rounded up to a size of at least 4. 4904 CharUnits OverflowAreaAlign = CharUnits::fromQuantity(4); 4905 4906 CharUnits Size; 4907 if (!isIndirect) { 4908 auto TypeInfo = CGF.getContext().getTypeInfoInChars(Ty); 4909 Size = TypeInfo.Width.alignTo(OverflowAreaAlign); 4910 } else { 4911 Size = CGF.getPointerSize(); 4912 } 4913 4914 Address OverflowAreaAddr = Builder.CreateStructGEP(VAList, 3); 4915 Address OverflowArea = 4916 Address(Builder.CreateLoad(OverflowAreaAddr, "argp.cur"), CGF.Int8Ty, 4917 OverflowAreaAlign); 4918 // Round up address of argument to alignment 4919 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty); 4920 if (Align > OverflowAreaAlign) { 4921 llvm::Value *Ptr = OverflowArea.getPointer(); 4922 OverflowArea = Address(emitRoundPointerUpToAlignment(CGF, Ptr, Align), 4923 OverflowArea.getElementType(), Align); 4924 } 4925 4926 MemAddr = Builder.CreateElementBitCast(OverflowArea, DirectTy); 4927 4928 // Increase the overflow area. 4929 OverflowArea = Builder.CreateConstInBoundsByteGEP(OverflowArea, Size); 4930 Builder.CreateStore(OverflowArea.getPointer(), OverflowAreaAddr); 4931 CGF.EmitBranch(Cont); 4932 } 4933 4934 CGF.EmitBlock(Cont); 4935 4936 // Merge the cases with a phi. 4937 Address Result = emitMergePHI(CGF, RegAddr, UsingRegs, MemAddr, UsingOverflow, 4938 "vaarg.addr"); 4939 4940 // Load the pointer if the argument was passed indirectly. 4941 if (isIndirect) { 4942 Result = Address(Builder.CreateLoad(Result, "aggr"), ElementTy, 4943 getContext().getTypeAlignInChars(Ty)); 4944 } 4945 4946 return Result; 4947 } 4948 4949 bool PPC32TargetCodeGenInfo::isStructReturnInRegABI( 4950 const llvm::Triple &Triple, const CodeGenOptions &Opts) { 4951 assert(Triple.isPPC32()); 4952 4953 switch (Opts.getStructReturnConvention()) { 4954 case CodeGenOptions::SRCK_Default: 4955 break; 4956 case CodeGenOptions::SRCK_OnStack: // -maix-struct-return 4957 return false; 4958 case CodeGenOptions::SRCK_InRegs: // -msvr4-struct-return 4959 return true; 4960 } 4961 4962 if (Triple.isOSBinFormatELF() && !Triple.isOSLinux()) 4963 return true; 4964 4965 return false; 4966 } 4967 4968 bool 4969 PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 4970 llvm::Value *Address) const { 4971 return PPC_initDwarfEHRegSizeTable(CGF, Address, /*Is64Bit*/ false, 4972 /*IsAIX*/ false); 4973 } 4974 4975 // PowerPC-64 4976 4977 namespace { 4978 /// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information. 4979 class PPC64_SVR4_ABIInfo : public SwiftABIInfo { 4980 public: 4981 enum ABIKind { 4982 ELFv1 = 0, 4983 ELFv2 4984 }; 4985 4986 private: 4987 static const unsigned GPRBits = 64; 4988 ABIKind Kind; 4989 bool IsSoftFloatABI; 4990 4991 public: 4992 PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind, 4993 bool SoftFloatABI) 4994 : SwiftABIInfo(CGT), Kind(Kind), IsSoftFloatABI(SoftFloatABI) {} 4995 4996 bool isPromotableTypeForABI(QualType Ty) const; 4997 CharUnits getParamTypeAlignment(QualType Ty) const; 4998 4999 ABIArgInfo classifyReturnType(QualType RetTy) const; 5000 ABIArgInfo classifyArgumentType(QualType Ty) const; 5001 5002 bool isHomogeneousAggregateBaseType(QualType Ty) const override; 5003 bool isHomogeneousAggregateSmallEnough(const Type *Ty, 5004 uint64_t Members) const override; 5005 5006 // TODO: We can add more logic to computeInfo to improve performance. 5007 // Example: For aggregate arguments that fit in a register, we could 5008 // use getDirectInReg (as is done below for structs containing a single 5009 // floating-point value) to avoid pushing them to memory on function 5010 // entry. This would require changing the logic in PPCISelLowering 5011 // when lowering the parameters in the caller and args in the callee. 5012 void computeInfo(CGFunctionInfo &FI) const override { 5013 if (!getCXXABI().classifyReturnType(FI)) 5014 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 5015 for (auto &I : FI.arguments()) { 5016 // We rely on the default argument classification for the most part. 5017 // One exception: An aggregate containing a single floating-point 5018 // or vector item must be passed in a register if one is available. 5019 const Type *T = isSingleElementStruct(I.type, getContext()); 5020 if (T) { 5021 const BuiltinType *BT = T->getAs<BuiltinType>(); 5022 if ((T->isVectorType() && getContext().getTypeSize(T) == 128) || 5023 (BT && BT->isFloatingPoint())) { 5024 QualType QT(T, 0); 5025 I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT)); 5026 continue; 5027 } 5028 } 5029 I.info = classifyArgumentType(I.type); 5030 } 5031 } 5032 5033 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 5034 QualType Ty) const override; 5035 5036 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars, 5037 bool asReturnValue) const override { 5038 return occupiesMoreThan(CGT, scalars, /*total*/ 4); 5039 } 5040 5041 bool isSwiftErrorInRegister() const override { 5042 return false; 5043 } 5044 }; 5045 5046 class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo { 5047 5048 public: 5049 PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT, 5050 PPC64_SVR4_ABIInfo::ABIKind Kind, 5051 bool SoftFloatABI) 5052 : TargetCodeGenInfo( 5053 std::make_unique<PPC64_SVR4_ABIInfo>(CGT, Kind, SoftFloatABI)) {} 5054 5055 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 5056 // This is recovered from gcc output. 5057 return 1; // r1 is the dedicated stack pointer 5058 } 5059 5060 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 5061 llvm::Value *Address) const override; 5062 }; 5063 5064 class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo { 5065 public: 5066 PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {} 5067 5068 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 5069 // This is recovered from gcc output. 5070 return 1; // r1 is the dedicated stack pointer 5071 } 5072 5073 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 5074 llvm::Value *Address) const override; 5075 }; 5076 5077 } 5078 5079 // Return true if the ABI requires Ty to be passed sign- or zero- 5080 // extended to 64 bits. 5081 bool 5082 PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const { 5083 // Treat an enum type as its underlying type. 5084 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 5085 Ty = EnumTy->getDecl()->getIntegerType(); 5086 5087 // Promotable integer types are required to be promoted by the ABI. 5088 if (isPromotableIntegerTypeForABI(Ty)) 5089 return true; 5090 5091 // In addition to the usual promotable integer types, we also need to 5092 // extend all 32-bit types, since the ABI requires promotion to 64 bits. 5093 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) 5094 switch (BT->getKind()) { 5095 case BuiltinType::Int: 5096 case BuiltinType::UInt: 5097 return true; 5098 default: 5099 break; 5100 } 5101 5102 if (const auto *EIT = Ty->getAs<BitIntType>()) 5103 if (EIT->getNumBits() < 64) 5104 return true; 5105 5106 return false; 5107 } 5108 5109 /// isAlignedParamType - Determine whether a type requires 16-byte or 5110 /// higher alignment in the parameter area. Always returns at least 8. 5111 CharUnits PPC64_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const { 5112 // Complex types are passed just like their elements. 5113 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) 5114 Ty = CTy->getElementType(); 5115 5116 auto FloatUsesVector = [this](QualType Ty){ 5117 return Ty->isRealFloatingType() && &getContext().getFloatTypeSemantics( 5118 Ty) == &llvm::APFloat::IEEEquad(); 5119 }; 5120 5121 // Only vector types of size 16 bytes need alignment (larger types are 5122 // passed via reference, smaller types are not aligned). 5123 if (Ty->isVectorType()) { 5124 return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16 : 8); 5125 } else if (FloatUsesVector(Ty)) { 5126 // According to ABI document section 'Optional Save Areas': If extended 5127 // precision floating-point values in IEEE BINARY 128 QUADRUPLE PRECISION 5128 // format are supported, map them to a single quadword, quadword aligned. 5129 return CharUnits::fromQuantity(16); 5130 } 5131 5132 // For single-element float/vector structs, we consider the whole type 5133 // to have the same alignment requirements as its single element. 5134 const Type *AlignAsType = nullptr; 5135 const Type *EltType = isSingleElementStruct(Ty, getContext()); 5136 if (EltType) { 5137 const BuiltinType *BT = EltType->getAs<BuiltinType>(); 5138 if ((EltType->isVectorType() && getContext().getTypeSize(EltType) == 128) || 5139 (BT && BT->isFloatingPoint())) 5140 AlignAsType = EltType; 5141 } 5142 5143 // Likewise for ELFv2 homogeneous aggregates. 5144 const Type *Base = nullptr; 5145 uint64_t Members = 0; 5146 if (!AlignAsType && Kind == ELFv2 && 5147 isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members)) 5148 AlignAsType = Base; 5149 5150 // With special case aggregates, only vector base types need alignment. 5151 if (AlignAsType) { 5152 bool UsesVector = AlignAsType->isVectorType() || 5153 FloatUsesVector(QualType(AlignAsType, 0)); 5154 return CharUnits::fromQuantity(UsesVector ? 16 : 8); 5155 } 5156 5157 // Otherwise, we only need alignment for any aggregate type that 5158 // has an alignment requirement of >= 16 bytes. 5159 if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128) { 5160 return CharUnits::fromQuantity(16); 5161 } 5162 5163 return CharUnits::fromQuantity(8); 5164 } 5165 5166 /// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous 5167 /// aggregate. Base is set to the base element type, and Members is set 5168 /// to the number of base elements. 5169 bool ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base, 5170 uint64_t &Members) const { 5171 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) { 5172 uint64_t NElements = AT->getSize().getZExtValue(); 5173 if (NElements == 0) 5174 return false; 5175 if (!isHomogeneousAggregate(AT->getElementType(), Base, Members)) 5176 return false; 5177 Members *= NElements; 5178 } else if (const RecordType *RT = Ty->getAs<RecordType>()) { 5179 const RecordDecl *RD = RT->getDecl(); 5180 if (RD->hasFlexibleArrayMember()) 5181 return false; 5182 5183 Members = 0; 5184 5185 // If this is a C++ record, check the properties of the record such as 5186 // bases and ABI specific restrictions 5187 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 5188 if (!getCXXABI().isPermittedToBeHomogeneousAggregate(CXXRD)) 5189 return false; 5190 5191 for (const auto &I : CXXRD->bases()) { 5192 // Ignore empty records. 5193 if (isEmptyRecord(getContext(), I.getType(), true)) 5194 continue; 5195 5196 uint64_t FldMembers; 5197 if (!isHomogeneousAggregate(I.getType(), Base, FldMembers)) 5198 return false; 5199 5200 Members += FldMembers; 5201 } 5202 } 5203 5204 for (const auto *FD : RD->fields()) { 5205 // Ignore (non-zero arrays of) empty records. 5206 QualType FT = FD->getType(); 5207 while (const ConstantArrayType *AT = 5208 getContext().getAsConstantArrayType(FT)) { 5209 if (AT->getSize().getZExtValue() == 0) 5210 return false; 5211 FT = AT->getElementType(); 5212 } 5213 if (isEmptyRecord(getContext(), FT, true)) 5214 continue; 5215 5216 // For compatibility with GCC, ignore empty bitfields in C++ mode. 5217 if (getContext().getLangOpts().CPlusPlus && 5218 FD->isZeroLengthBitField(getContext())) 5219 continue; 5220 5221 uint64_t FldMembers; 5222 if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers)) 5223 return false; 5224 5225 Members = (RD->isUnion() ? 5226 std::max(Members, FldMembers) : Members + FldMembers); 5227 } 5228 5229 if (!Base) 5230 return false; 5231 5232 // Ensure there is no padding. 5233 if (getContext().getTypeSize(Base) * Members != 5234 getContext().getTypeSize(Ty)) 5235 return false; 5236 } else { 5237 Members = 1; 5238 if (const ComplexType *CT = Ty->getAs<ComplexType>()) { 5239 Members = 2; 5240 Ty = CT->getElementType(); 5241 } 5242 5243 // Most ABIs only support float, double, and some vector type widths. 5244 if (!isHomogeneousAggregateBaseType(Ty)) 5245 return false; 5246 5247 // The base type must be the same for all members. Types that 5248 // agree in both total size and mode (float vs. vector) are 5249 // treated as being equivalent here. 5250 const Type *TyPtr = Ty.getTypePtr(); 5251 if (!Base) { 5252 Base = TyPtr; 5253 // If it's a non-power-of-2 vector, its size is already a power-of-2, 5254 // so make sure to widen it explicitly. 5255 if (const VectorType *VT = Base->getAs<VectorType>()) { 5256 QualType EltTy = VT->getElementType(); 5257 unsigned NumElements = 5258 getContext().getTypeSize(VT) / getContext().getTypeSize(EltTy); 5259 Base = getContext() 5260 .getVectorType(EltTy, NumElements, VT->getVectorKind()) 5261 .getTypePtr(); 5262 } 5263 } 5264 5265 if (Base->isVectorType() != TyPtr->isVectorType() || 5266 getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr)) 5267 return false; 5268 } 5269 return Members > 0 && isHomogeneousAggregateSmallEnough(Base, Members); 5270 } 5271 5272 bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const { 5273 // Homogeneous aggregates for ELFv2 must have base types of float, 5274 // double, long double, or 128-bit vectors. 5275 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) { 5276 if (BT->getKind() == BuiltinType::Float || 5277 BT->getKind() == BuiltinType::Double || 5278 BT->getKind() == BuiltinType::LongDouble || 5279 BT->getKind() == BuiltinType::Ibm128 || 5280 (getContext().getTargetInfo().hasFloat128Type() && 5281 (BT->getKind() == BuiltinType::Float128))) { 5282 if (IsSoftFloatABI) 5283 return false; 5284 return true; 5285 } 5286 } 5287 if (const VectorType *VT = Ty->getAs<VectorType>()) { 5288 if (getContext().getTypeSize(VT) == 128) 5289 return true; 5290 } 5291 return false; 5292 } 5293 5294 bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateSmallEnough( 5295 const Type *Base, uint64_t Members) const { 5296 // Vector and fp128 types require one register, other floating point types 5297 // require one or two registers depending on their size. 5298 uint32_t NumRegs = 5299 ((getContext().getTargetInfo().hasFloat128Type() && 5300 Base->isFloat128Type()) || 5301 Base->isVectorType()) ? 1 5302 : (getContext().getTypeSize(Base) + 63) / 64; 5303 5304 // Homogeneous Aggregates may occupy at most 8 registers. 5305 return Members * NumRegs <= 8; 5306 } 5307 5308 ABIArgInfo 5309 PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const { 5310 Ty = useFirstFieldIfTransparentUnion(Ty); 5311 5312 if (Ty->isAnyComplexType()) 5313 return ABIArgInfo::getDirect(); 5314 5315 // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes) 5316 // or via reference (larger than 16 bytes). 5317 if (Ty->isVectorType()) { 5318 uint64_t Size = getContext().getTypeSize(Ty); 5319 if (Size > 128) 5320 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 5321 else if (Size < 128) { 5322 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size); 5323 return ABIArgInfo::getDirect(CoerceTy); 5324 } 5325 } 5326 5327 if (const auto *EIT = Ty->getAs<BitIntType>()) 5328 if (EIT->getNumBits() > 128) 5329 return getNaturalAlignIndirect(Ty, /*ByVal=*/true); 5330 5331 if (isAggregateTypeForABI(Ty)) { 5332 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 5333 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 5334 5335 uint64_t ABIAlign = getParamTypeAlignment(Ty).getQuantity(); 5336 uint64_t TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity(); 5337 5338 // ELFv2 homogeneous aggregates are passed as array types. 5339 const Type *Base = nullptr; 5340 uint64_t Members = 0; 5341 if (Kind == ELFv2 && 5342 isHomogeneousAggregate(Ty, Base, Members)) { 5343 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0)); 5344 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members); 5345 return ABIArgInfo::getDirect(CoerceTy); 5346 } 5347 5348 // If an aggregate may end up fully in registers, we do not 5349 // use the ByVal method, but pass the aggregate as array. 5350 // This is usually beneficial since we avoid forcing the 5351 // back-end to store the argument to memory. 5352 uint64_t Bits = getContext().getTypeSize(Ty); 5353 if (Bits > 0 && Bits <= 8 * GPRBits) { 5354 llvm::Type *CoerceTy; 5355 5356 // Types up to 8 bytes are passed as integer type (which will be 5357 // properly aligned in the argument save area doubleword). 5358 if (Bits <= GPRBits) 5359 CoerceTy = 5360 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8)); 5361 // Larger types are passed as arrays, with the base type selected 5362 // according to the required alignment in the save area. 5363 else { 5364 uint64_t RegBits = ABIAlign * 8; 5365 uint64_t NumRegs = llvm::alignTo(Bits, RegBits) / RegBits; 5366 llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits); 5367 CoerceTy = llvm::ArrayType::get(RegTy, NumRegs); 5368 } 5369 5370 return ABIArgInfo::getDirect(CoerceTy); 5371 } 5372 5373 // All other aggregates are passed ByVal. 5374 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign), 5375 /*ByVal=*/true, 5376 /*Realign=*/TyAlign > ABIAlign); 5377 } 5378 5379 return (isPromotableTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty) 5380 : ABIArgInfo::getDirect()); 5381 } 5382 5383 ABIArgInfo 5384 PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const { 5385 if (RetTy->isVoidType()) 5386 return ABIArgInfo::getIgnore(); 5387 5388 if (RetTy->isAnyComplexType()) 5389 return ABIArgInfo::getDirect(); 5390 5391 // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes) 5392 // or via reference (larger than 16 bytes). 5393 if (RetTy->isVectorType()) { 5394 uint64_t Size = getContext().getTypeSize(RetTy); 5395 if (Size > 128) 5396 return getNaturalAlignIndirect(RetTy); 5397 else if (Size < 128) { 5398 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size); 5399 return ABIArgInfo::getDirect(CoerceTy); 5400 } 5401 } 5402 5403 if (const auto *EIT = RetTy->getAs<BitIntType>()) 5404 if (EIT->getNumBits() > 128) 5405 return getNaturalAlignIndirect(RetTy, /*ByVal=*/false); 5406 5407 if (isAggregateTypeForABI(RetTy)) { 5408 // ELFv2 homogeneous aggregates are returned as array types. 5409 const Type *Base = nullptr; 5410 uint64_t Members = 0; 5411 if (Kind == ELFv2 && 5412 isHomogeneousAggregate(RetTy, Base, Members)) { 5413 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0)); 5414 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members); 5415 return ABIArgInfo::getDirect(CoerceTy); 5416 } 5417 5418 // ELFv2 small aggregates are returned in up to two registers. 5419 uint64_t Bits = getContext().getTypeSize(RetTy); 5420 if (Kind == ELFv2 && Bits <= 2 * GPRBits) { 5421 if (Bits == 0) 5422 return ABIArgInfo::getIgnore(); 5423 5424 llvm::Type *CoerceTy; 5425 if (Bits > GPRBits) { 5426 CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits); 5427 CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy); 5428 } else 5429 CoerceTy = 5430 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8)); 5431 return ABIArgInfo::getDirect(CoerceTy); 5432 } 5433 5434 // All other aggregates are returned indirectly. 5435 return getNaturalAlignIndirect(RetTy); 5436 } 5437 5438 return (isPromotableTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy) 5439 : ABIArgInfo::getDirect()); 5440 } 5441 5442 // Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine. 5443 Address PPC64_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 5444 QualType Ty) const { 5445 auto TypeInfo = getContext().getTypeInfoInChars(Ty); 5446 TypeInfo.Align = getParamTypeAlignment(Ty); 5447 5448 CharUnits SlotSize = CharUnits::fromQuantity(8); 5449 5450 // If we have a complex type and the base type is smaller than 8 bytes, 5451 // the ABI calls for the real and imaginary parts to be right-adjusted 5452 // in separate doublewords. However, Clang expects us to produce a 5453 // pointer to a structure with the two parts packed tightly. So generate 5454 // loads of the real and imaginary parts relative to the va_list pointer, 5455 // and store them to a temporary structure. 5456 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) { 5457 CharUnits EltSize = TypeInfo.Width / 2; 5458 if (EltSize < SlotSize) 5459 return complexTempStructure(CGF, VAListAddr, Ty, SlotSize, EltSize, CTy); 5460 } 5461 5462 // Otherwise, just use the general rule. 5463 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false, 5464 TypeInfo, SlotSize, /*AllowHigher*/ true); 5465 } 5466 5467 bool 5468 PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable( 5469 CodeGen::CodeGenFunction &CGF, 5470 llvm::Value *Address) const { 5471 return PPC_initDwarfEHRegSizeTable(CGF, Address, /*Is64Bit*/ true, 5472 /*IsAIX*/ false); 5473 } 5474 5475 bool 5476 PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 5477 llvm::Value *Address) const { 5478 return PPC_initDwarfEHRegSizeTable(CGF, Address, /*Is64Bit*/ true, 5479 /*IsAIX*/ false); 5480 } 5481 5482 //===----------------------------------------------------------------------===// 5483 // AArch64 ABI Implementation 5484 //===----------------------------------------------------------------------===// 5485 5486 namespace { 5487 5488 class AArch64ABIInfo : public SwiftABIInfo { 5489 public: 5490 enum ABIKind { 5491 AAPCS = 0, 5492 DarwinPCS, 5493 Win64 5494 }; 5495 5496 private: 5497 ABIKind Kind; 5498 5499 public: 5500 AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind) 5501 : SwiftABIInfo(CGT), Kind(Kind) {} 5502 5503 private: 5504 ABIKind getABIKind() const { return Kind; } 5505 bool isDarwinPCS() const { return Kind == DarwinPCS; } 5506 5507 ABIArgInfo classifyReturnType(QualType RetTy, bool IsVariadic) const; 5508 ABIArgInfo classifyArgumentType(QualType RetTy, bool IsVariadic, 5509 unsigned CallingConvention) const; 5510 ABIArgInfo coerceIllegalVector(QualType Ty) const; 5511 bool isHomogeneousAggregateBaseType(QualType Ty) const override; 5512 bool isHomogeneousAggregateSmallEnough(const Type *Ty, 5513 uint64_t Members) const override; 5514 5515 bool isIllegalVectorType(QualType Ty) const; 5516 5517 void computeInfo(CGFunctionInfo &FI) const override { 5518 if (!::classifyReturnType(getCXXABI(), FI, *this)) 5519 FI.getReturnInfo() = 5520 classifyReturnType(FI.getReturnType(), FI.isVariadic()); 5521 5522 for (auto &it : FI.arguments()) 5523 it.info = classifyArgumentType(it.type, FI.isVariadic(), 5524 FI.getCallingConvention()); 5525 } 5526 5527 Address EmitDarwinVAArg(Address VAListAddr, QualType Ty, 5528 CodeGenFunction &CGF) const; 5529 5530 Address EmitAAPCSVAArg(Address VAListAddr, QualType Ty, 5531 CodeGenFunction &CGF) const; 5532 5533 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 5534 QualType Ty) const override { 5535 llvm::Type *BaseTy = CGF.ConvertType(Ty); 5536 if (isa<llvm::ScalableVectorType>(BaseTy)) 5537 llvm::report_fatal_error("Passing SVE types to variadic functions is " 5538 "currently not supported"); 5539 5540 return Kind == Win64 ? EmitMSVAArg(CGF, VAListAddr, Ty) 5541 : isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF) 5542 : EmitAAPCSVAArg(VAListAddr, Ty, CGF); 5543 } 5544 5545 Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr, 5546 QualType Ty) const override; 5547 5548 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars, 5549 bool asReturnValue) const override { 5550 return occupiesMoreThan(CGT, scalars, /*total*/ 4); 5551 } 5552 bool isSwiftErrorInRegister() const override { 5553 return true; 5554 } 5555 5556 bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy, 5557 unsigned elts) const override; 5558 5559 bool allowBFloatArgsAndRet() const override { 5560 return getTarget().hasBFloat16Type(); 5561 } 5562 }; 5563 5564 class AArch64TargetCodeGenInfo : public TargetCodeGenInfo { 5565 public: 5566 AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind) 5567 : TargetCodeGenInfo(std::make_unique<AArch64ABIInfo>(CGT, Kind)) {} 5568 5569 StringRef getARCRetainAutoreleasedReturnValueMarker() const override { 5570 return "mov\tfp, fp\t\t// marker for objc_retainAutoreleaseReturnValue"; 5571 } 5572 5573 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 5574 return 31; 5575 } 5576 5577 bool doesReturnSlotInterfereWithArgs() const override { return false; } 5578 5579 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 5580 CodeGen::CodeGenModule &CGM) const override { 5581 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D); 5582 if (!FD) 5583 return; 5584 5585 const auto *TA = FD->getAttr<TargetAttr>(); 5586 if (TA == nullptr) 5587 return; 5588 5589 ParsedTargetAttr Attr = TA->parse(); 5590 if (Attr.BranchProtection.empty()) 5591 return; 5592 5593 TargetInfo::BranchProtectionInfo BPI; 5594 StringRef Error; 5595 (void)CGM.getTarget().validateBranchProtection( 5596 Attr.BranchProtection, Attr.Architecture, BPI, Error); 5597 assert(Error.empty()); 5598 5599 auto *Fn = cast<llvm::Function>(GV); 5600 static const char *SignReturnAddrStr[] = {"none", "non-leaf", "all"}; 5601 Fn->addFnAttr("sign-return-address", SignReturnAddrStr[static_cast<int>(BPI.SignReturnAddr)]); 5602 5603 if (BPI.SignReturnAddr != LangOptions::SignReturnAddressScopeKind::None) { 5604 Fn->addFnAttr("sign-return-address-key", 5605 BPI.SignKey == LangOptions::SignReturnAddressKeyKind::AKey 5606 ? "a_key" 5607 : "b_key"); 5608 } 5609 5610 Fn->addFnAttr("branch-target-enforcement", 5611 BPI.BranchTargetEnforcement ? "true" : "false"); 5612 } 5613 5614 bool isScalarizableAsmOperand(CodeGen::CodeGenFunction &CGF, 5615 llvm::Type *Ty) const override { 5616 if (CGF.getTarget().hasFeature("ls64")) { 5617 auto *ST = dyn_cast<llvm::StructType>(Ty); 5618 if (ST && ST->getNumElements() == 1) { 5619 auto *AT = dyn_cast<llvm::ArrayType>(ST->getElementType(0)); 5620 if (AT && AT->getNumElements() == 8 && 5621 AT->getElementType()->isIntegerTy(64)) 5622 return true; 5623 } 5624 } 5625 return TargetCodeGenInfo::isScalarizableAsmOperand(CGF, Ty); 5626 } 5627 }; 5628 5629 class WindowsAArch64TargetCodeGenInfo : public AArch64TargetCodeGenInfo { 5630 public: 5631 WindowsAArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind K) 5632 : AArch64TargetCodeGenInfo(CGT, K) {} 5633 5634 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 5635 CodeGen::CodeGenModule &CGM) const override; 5636 5637 void getDependentLibraryOption(llvm::StringRef Lib, 5638 llvm::SmallString<24> &Opt) const override { 5639 Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib); 5640 } 5641 5642 void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value, 5643 llvm::SmallString<32> &Opt) const override { 5644 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\""; 5645 } 5646 }; 5647 5648 void WindowsAArch64TargetCodeGenInfo::setTargetAttributes( 5649 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const { 5650 AArch64TargetCodeGenInfo::setTargetAttributes(D, GV, CGM); 5651 if (GV->isDeclaration()) 5652 return; 5653 addStackProbeTargetAttributes(D, GV, CGM); 5654 } 5655 } 5656 5657 ABIArgInfo AArch64ABIInfo::coerceIllegalVector(QualType Ty) const { 5658 assert(Ty->isVectorType() && "expected vector type!"); 5659 5660 const auto *VT = Ty->castAs<VectorType>(); 5661 if (VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector) { 5662 assert(VT->getElementType()->isBuiltinType() && "expected builtin type!"); 5663 assert(VT->getElementType()->castAs<BuiltinType>()->getKind() == 5664 BuiltinType::UChar && 5665 "unexpected builtin type for SVE predicate!"); 5666 return ABIArgInfo::getDirect(llvm::ScalableVectorType::get( 5667 llvm::Type::getInt1Ty(getVMContext()), 16)); 5668 } 5669 5670 if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector) { 5671 assert(VT->getElementType()->isBuiltinType() && "expected builtin type!"); 5672 5673 const auto *BT = VT->getElementType()->castAs<BuiltinType>(); 5674 llvm::ScalableVectorType *ResType = nullptr; 5675 switch (BT->getKind()) { 5676 default: 5677 llvm_unreachable("unexpected builtin type for SVE vector!"); 5678 case BuiltinType::SChar: 5679 case BuiltinType::UChar: 5680 ResType = llvm::ScalableVectorType::get( 5681 llvm::Type::getInt8Ty(getVMContext()), 16); 5682 break; 5683 case BuiltinType::Short: 5684 case BuiltinType::UShort: 5685 ResType = llvm::ScalableVectorType::get( 5686 llvm::Type::getInt16Ty(getVMContext()), 8); 5687 break; 5688 case BuiltinType::Int: 5689 case BuiltinType::UInt: 5690 ResType = llvm::ScalableVectorType::get( 5691 llvm::Type::getInt32Ty(getVMContext()), 4); 5692 break; 5693 case BuiltinType::Long: 5694 case BuiltinType::ULong: 5695 ResType = llvm::ScalableVectorType::get( 5696 llvm::Type::getInt64Ty(getVMContext()), 2); 5697 break; 5698 case BuiltinType::Half: 5699 ResType = llvm::ScalableVectorType::get( 5700 llvm::Type::getHalfTy(getVMContext()), 8); 5701 break; 5702 case BuiltinType::Float: 5703 ResType = llvm::ScalableVectorType::get( 5704 llvm::Type::getFloatTy(getVMContext()), 4); 5705 break; 5706 case BuiltinType::Double: 5707 ResType = llvm::ScalableVectorType::get( 5708 llvm::Type::getDoubleTy(getVMContext()), 2); 5709 break; 5710 case BuiltinType::BFloat16: 5711 ResType = llvm::ScalableVectorType::get( 5712 llvm::Type::getBFloatTy(getVMContext()), 8); 5713 break; 5714 } 5715 return ABIArgInfo::getDirect(ResType); 5716 } 5717 5718 uint64_t Size = getContext().getTypeSize(Ty); 5719 // Android promotes <2 x i8> to i16, not i32 5720 if (isAndroid() && (Size <= 16)) { 5721 llvm::Type *ResType = llvm::Type::getInt16Ty(getVMContext()); 5722 return ABIArgInfo::getDirect(ResType); 5723 } 5724 if (Size <= 32) { 5725 llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext()); 5726 return ABIArgInfo::getDirect(ResType); 5727 } 5728 if (Size == 64) { 5729 auto *ResType = 5730 llvm::FixedVectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2); 5731 return ABIArgInfo::getDirect(ResType); 5732 } 5733 if (Size == 128) { 5734 auto *ResType = 5735 llvm::FixedVectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4); 5736 return ABIArgInfo::getDirect(ResType); 5737 } 5738 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 5739 } 5740 5741 ABIArgInfo 5742 AArch64ABIInfo::classifyArgumentType(QualType Ty, bool IsVariadic, 5743 unsigned CallingConvention) const { 5744 Ty = useFirstFieldIfTransparentUnion(Ty); 5745 5746 // Handle illegal vector types here. 5747 if (isIllegalVectorType(Ty)) 5748 return coerceIllegalVector(Ty); 5749 5750 if (!isAggregateTypeForABI(Ty)) { 5751 // Treat an enum type as its underlying type. 5752 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 5753 Ty = EnumTy->getDecl()->getIntegerType(); 5754 5755 if (const auto *EIT = Ty->getAs<BitIntType>()) 5756 if (EIT->getNumBits() > 128) 5757 return getNaturalAlignIndirect(Ty); 5758 5759 return (isPromotableIntegerTypeForABI(Ty) && isDarwinPCS() 5760 ? ABIArgInfo::getExtend(Ty) 5761 : ABIArgInfo::getDirect()); 5762 } 5763 5764 // Structures with either a non-trivial destructor or a non-trivial 5765 // copy constructor are always indirect. 5766 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) { 5767 return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA == 5768 CGCXXABI::RAA_DirectInMemory); 5769 } 5770 5771 // Empty records are always ignored on Darwin, but actually passed in C++ mode 5772 // elsewhere for GNU compatibility. 5773 uint64_t Size = getContext().getTypeSize(Ty); 5774 bool IsEmpty = isEmptyRecord(getContext(), Ty, true); 5775 if (IsEmpty || Size == 0) { 5776 if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS()) 5777 return ABIArgInfo::getIgnore(); 5778 5779 // GNU C mode. The only argument that gets ignored is an empty one with size 5780 // 0. 5781 if (IsEmpty && Size == 0) 5782 return ABIArgInfo::getIgnore(); 5783 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext())); 5784 } 5785 5786 // Homogeneous Floating-point Aggregates (HFAs) need to be expanded. 5787 const Type *Base = nullptr; 5788 uint64_t Members = 0; 5789 bool IsWin64 = Kind == Win64 || CallingConvention == llvm::CallingConv::Win64; 5790 bool IsWinVariadic = IsWin64 && IsVariadic; 5791 // In variadic functions on Windows, all composite types are treated alike, 5792 // no special handling of HFAs/HVAs. 5793 if (!IsWinVariadic && isHomogeneousAggregate(Ty, Base, Members)) { 5794 if (Kind != AArch64ABIInfo::AAPCS) 5795 return ABIArgInfo::getDirect( 5796 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members)); 5797 5798 // For alignment adjusted HFAs, cap the argument alignment to 16, leave it 5799 // default otherwise. 5800 unsigned Align = 5801 getContext().getTypeUnadjustedAlignInChars(Ty).getQuantity(); 5802 unsigned BaseAlign = getContext().getTypeAlignInChars(Base).getQuantity(); 5803 Align = (Align > BaseAlign && Align >= 16) ? 16 : 0; 5804 return ABIArgInfo::getDirect( 5805 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members), 0, 5806 nullptr, true, Align); 5807 } 5808 5809 // Aggregates <= 16 bytes are passed directly in registers or on the stack. 5810 if (Size <= 128) { 5811 // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of 5812 // same size and alignment. 5813 if (getTarget().isRenderScriptTarget()) { 5814 return coerceToIntArray(Ty, getContext(), getVMContext()); 5815 } 5816 unsigned Alignment; 5817 if (Kind == AArch64ABIInfo::AAPCS) { 5818 Alignment = getContext().getTypeUnadjustedAlign(Ty); 5819 Alignment = Alignment < 128 ? 64 : 128; 5820 } else { 5821 Alignment = std::max(getContext().getTypeAlign(Ty), 5822 (unsigned)getTarget().getPointerWidth(0)); 5823 } 5824 Size = llvm::alignTo(Size, Alignment); 5825 5826 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment. 5827 // For aggregates with 16-byte alignment, we use i128. 5828 llvm::Type *BaseTy = llvm::Type::getIntNTy(getVMContext(), Alignment); 5829 return ABIArgInfo::getDirect( 5830 Size == Alignment ? BaseTy 5831 : llvm::ArrayType::get(BaseTy, Size / Alignment)); 5832 } 5833 5834 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 5835 } 5836 5837 ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy, 5838 bool IsVariadic) const { 5839 if (RetTy->isVoidType()) 5840 return ABIArgInfo::getIgnore(); 5841 5842 if (const auto *VT = RetTy->getAs<VectorType>()) { 5843 if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector || 5844 VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector) 5845 return coerceIllegalVector(RetTy); 5846 } 5847 5848 // Large vector types should be returned via memory. 5849 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128) 5850 return getNaturalAlignIndirect(RetTy); 5851 5852 if (!isAggregateTypeForABI(RetTy)) { 5853 // Treat an enum type as its underlying type. 5854 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 5855 RetTy = EnumTy->getDecl()->getIntegerType(); 5856 5857 if (const auto *EIT = RetTy->getAs<BitIntType>()) 5858 if (EIT->getNumBits() > 128) 5859 return getNaturalAlignIndirect(RetTy); 5860 5861 return (isPromotableIntegerTypeForABI(RetTy) && isDarwinPCS() 5862 ? ABIArgInfo::getExtend(RetTy) 5863 : ABIArgInfo::getDirect()); 5864 } 5865 5866 uint64_t Size = getContext().getTypeSize(RetTy); 5867 if (isEmptyRecord(getContext(), RetTy, true) || Size == 0) 5868 return ABIArgInfo::getIgnore(); 5869 5870 const Type *Base = nullptr; 5871 uint64_t Members = 0; 5872 if (isHomogeneousAggregate(RetTy, Base, Members) && 5873 !(getTarget().getTriple().getArch() == llvm::Triple::aarch64_32 && 5874 IsVariadic)) 5875 // Homogeneous Floating-point Aggregates (HFAs) are returned directly. 5876 return ABIArgInfo::getDirect(); 5877 5878 // Aggregates <= 16 bytes are returned directly in registers or on the stack. 5879 if (Size <= 128) { 5880 // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of 5881 // same size and alignment. 5882 if (getTarget().isRenderScriptTarget()) { 5883 return coerceToIntArray(RetTy, getContext(), getVMContext()); 5884 } 5885 5886 if (Size <= 64 && getDataLayout().isLittleEndian()) { 5887 // Composite types are returned in lower bits of a 64-bit register for LE, 5888 // and in higher bits for BE. However, integer types are always returned 5889 // in lower bits for both LE and BE, and they are not rounded up to 5890 // 64-bits. We can skip rounding up of composite types for LE, but not for 5891 // BE, otherwise composite types will be indistinguishable from integer 5892 // types. 5893 return ABIArgInfo::getDirect( 5894 llvm::IntegerType::get(getVMContext(), Size)); 5895 } 5896 5897 unsigned Alignment = getContext().getTypeAlign(RetTy); 5898 Size = llvm::alignTo(Size, 64); // round up to multiple of 8 bytes 5899 5900 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment. 5901 // For aggregates with 16-byte alignment, we use i128. 5902 if (Alignment < 128 && Size == 128) { 5903 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext()); 5904 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64)); 5905 } 5906 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size)); 5907 } 5908 5909 return getNaturalAlignIndirect(RetTy); 5910 } 5911 5912 /// isIllegalVectorType - check whether the vector type is legal for AArch64. 5913 bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const { 5914 if (const VectorType *VT = Ty->getAs<VectorType>()) { 5915 // Check whether VT is a fixed-length SVE vector. These types are 5916 // represented as scalable vectors in function args/return and must be 5917 // coerced from fixed vectors. 5918 if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector || 5919 VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector) 5920 return true; 5921 5922 // Check whether VT is legal. 5923 unsigned NumElements = VT->getNumElements(); 5924 uint64_t Size = getContext().getTypeSize(VT); 5925 // NumElements should be power of 2. 5926 if (!llvm::isPowerOf2_32(NumElements)) 5927 return true; 5928 5929 // arm64_32 has to be compatible with the ARM logic here, which allows huge 5930 // vectors for some reason. 5931 llvm::Triple Triple = getTarget().getTriple(); 5932 if (Triple.getArch() == llvm::Triple::aarch64_32 && 5933 Triple.isOSBinFormatMachO()) 5934 return Size <= 32; 5935 5936 return Size != 64 && (Size != 128 || NumElements == 1); 5937 } 5938 return false; 5939 } 5940 5941 bool AArch64ABIInfo::isLegalVectorTypeForSwift(CharUnits totalSize, 5942 llvm::Type *eltTy, 5943 unsigned elts) const { 5944 if (!llvm::isPowerOf2_32(elts)) 5945 return false; 5946 if (totalSize.getQuantity() != 8 && 5947 (totalSize.getQuantity() != 16 || elts == 1)) 5948 return false; 5949 return true; 5950 } 5951 5952 bool AArch64ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const { 5953 // Homogeneous aggregates for AAPCS64 must have base types of a floating 5954 // point type or a short-vector type. This is the same as the 32-bit ABI, 5955 // but with the difference that any floating-point type is allowed, 5956 // including __fp16. 5957 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) { 5958 if (BT->isFloatingPoint()) 5959 return true; 5960 } else if (const VectorType *VT = Ty->getAs<VectorType>()) { 5961 unsigned VecSize = getContext().getTypeSize(VT); 5962 if (VecSize == 64 || VecSize == 128) 5963 return true; 5964 } 5965 return false; 5966 } 5967 5968 bool AArch64ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base, 5969 uint64_t Members) const { 5970 return Members <= 4; 5971 } 5972 5973 Address AArch64ABIInfo::EmitAAPCSVAArg(Address VAListAddr, QualType Ty, 5974 CodeGenFunction &CGF) const { 5975 ABIArgInfo AI = classifyArgumentType(Ty, /*IsVariadic=*/true, 5976 CGF.CurFnInfo->getCallingConvention()); 5977 bool IsIndirect = AI.isIndirect(); 5978 5979 llvm::Type *BaseTy = CGF.ConvertType(Ty); 5980 if (IsIndirect) 5981 BaseTy = llvm::PointerType::getUnqual(BaseTy); 5982 else if (AI.getCoerceToType()) 5983 BaseTy = AI.getCoerceToType(); 5984 5985 unsigned NumRegs = 1; 5986 if (llvm::ArrayType *ArrTy = dyn_cast<llvm::ArrayType>(BaseTy)) { 5987 BaseTy = ArrTy->getElementType(); 5988 NumRegs = ArrTy->getNumElements(); 5989 } 5990 bool IsFPR = BaseTy->isFloatingPointTy() || BaseTy->isVectorTy(); 5991 5992 // The AArch64 va_list type and handling is specified in the Procedure Call 5993 // Standard, section B.4: 5994 // 5995 // struct { 5996 // void *__stack; 5997 // void *__gr_top; 5998 // void *__vr_top; 5999 // int __gr_offs; 6000 // int __vr_offs; 6001 // }; 6002 6003 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg"); 6004 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg"); 6005 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack"); 6006 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end"); 6007 6008 CharUnits TySize = getContext().getTypeSizeInChars(Ty); 6009 CharUnits TyAlign = getContext().getTypeUnadjustedAlignInChars(Ty); 6010 6011 Address reg_offs_p = Address::invalid(); 6012 llvm::Value *reg_offs = nullptr; 6013 int reg_top_index; 6014 int RegSize = IsIndirect ? 8 : TySize.getQuantity(); 6015 if (!IsFPR) { 6016 // 3 is the field number of __gr_offs 6017 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 3, "gr_offs_p"); 6018 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs"); 6019 reg_top_index = 1; // field number for __gr_top 6020 RegSize = llvm::alignTo(RegSize, 8); 6021 } else { 6022 // 4 is the field number of __vr_offs. 6023 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 4, "vr_offs_p"); 6024 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs"); 6025 reg_top_index = 2; // field number for __vr_top 6026 RegSize = 16 * NumRegs; 6027 } 6028 6029 //======================================= 6030 // Find out where argument was passed 6031 //======================================= 6032 6033 // If reg_offs >= 0 we're already using the stack for this type of 6034 // argument. We don't want to keep updating reg_offs (in case it overflows, 6035 // though anyone passing 2GB of arguments, each at most 16 bytes, deserves 6036 // whatever they get). 6037 llvm::Value *UsingStack = nullptr; 6038 UsingStack = CGF.Builder.CreateICmpSGE( 6039 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0)); 6040 6041 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock); 6042 6043 // Otherwise, at least some kind of argument could go in these registers, the 6044 // question is whether this particular type is too big. 6045 CGF.EmitBlock(MaybeRegBlock); 6046 6047 // Integer arguments may need to correct register alignment (for example a 6048 // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we 6049 // align __gr_offs to calculate the potential address. 6050 if (!IsFPR && !IsIndirect && TyAlign.getQuantity() > 8) { 6051 int Align = TyAlign.getQuantity(); 6052 6053 reg_offs = CGF.Builder.CreateAdd( 6054 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1), 6055 "align_regoffs"); 6056 reg_offs = CGF.Builder.CreateAnd( 6057 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align), 6058 "aligned_regoffs"); 6059 } 6060 6061 // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list. 6062 // The fact that this is done unconditionally reflects the fact that 6063 // allocating an argument to the stack also uses up all the remaining 6064 // registers of the appropriate kind. 6065 llvm::Value *NewOffset = nullptr; 6066 NewOffset = CGF.Builder.CreateAdd( 6067 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs"); 6068 CGF.Builder.CreateStore(NewOffset, reg_offs_p); 6069 6070 // Now we're in a position to decide whether this argument really was in 6071 // registers or not. 6072 llvm::Value *InRegs = nullptr; 6073 InRegs = CGF.Builder.CreateICmpSLE( 6074 NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg"); 6075 6076 CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock); 6077 6078 //======================================= 6079 // Argument was in registers 6080 //======================================= 6081 6082 // Now we emit the code for if the argument was originally passed in 6083 // registers. First start the appropriate block: 6084 CGF.EmitBlock(InRegBlock); 6085 6086 llvm::Value *reg_top = nullptr; 6087 Address reg_top_p = 6088 CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index, "reg_top_p"); 6089 reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top"); 6090 Address BaseAddr(CGF.Builder.CreateInBoundsGEP(CGF.Int8Ty, reg_top, reg_offs), 6091 CGF.Int8Ty, CharUnits::fromQuantity(IsFPR ? 16 : 8)); 6092 Address RegAddr = Address::invalid(); 6093 llvm::Type *MemTy = CGF.ConvertTypeForMem(Ty), *ElementTy = MemTy; 6094 6095 if (IsIndirect) { 6096 // If it's been passed indirectly (actually a struct), whatever we find from 6097 // stored registers or on the stack will actually be a struct **. 6098 MemTy = llvm::PointerType::getUnqual(MemTy); 6099 } 6100 6101 const Type *Base = nullptr; 6102 uint64_t NumMembers = 0; 6103 bool IsHFA = isHomogeneousAggregate(Ty, Base, NumMembers); 6104 if (IsHFA && NumMembers > 1) { 6105 // Homogeneous aggregates passed in registers will have their elements split 6106 // and stored 16-bytes apart regardless of size (they're notionally in qN, 6107 // qN+1, ...). We reload and store into a temporary local variable 6108 // contiguously. 6109 assert(!IsIndirect && "Homogeneous aggregates should be passed directly"); 6110 auto BaseTyInfo = getContext().getTypeInfoInChars(QualType(Base, 0)); 6111 llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0)); 6112 llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers); 6113 Address Tmp = CGF.CreateTempAlloca(HFATy, 6114 std::max(TyAlign, BaseTyInfo.Align)); 6115 6116 // On big-endian platforms, the value will be right-aligned in its slot. 6117 int Offset = 0; 6118 if (CGF.CGM.getDataLayout().isBigEndian() && 6119 BaseTyInfo.Width.getQuantity() < 16) 6120 Offset = 16 - BaseTyInfo.Width.getQuantity(); 6121 6122 for (unsigned i = 0; i < NumMembers; ++i) { 6123 CharUnits BaseOffset = CharUnits::fromQuantity(16 * i + Offset); 6124 Address LoadAddr = 6125 CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, BaseOffset); 6126 LoadAddr = CGF.Builder.CreateElementBitCast(LoadAddr, BaseTy); 6127 6128 Address StoreAddr = CGF.Builder.CreateConstArrayGEP(Tmp, i); 6129 6130 llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr); 6131 CGF.Builder.CreateStore(Elem, StoreAddr); 6132 } 6133 6134 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, MemTy); 6135 } else { 6136 // Otherwise the object is contiguous in memory. 6137 6138 // It might be right-aligned in its slot. 6139 CharUnits SlotSize = BaseAddr.getAlignment(); 6140 if (CGF.CGM.getDataLayout().isBigEndian() && !IsIndirect && 6141 (IsHFA || !isAggregateTypeForABI(Ty)) && 6142 TySize < SlotSize) { 6143 CharUnits Offset = SlotSize - TySize; 6144 BaseAddr = CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, Offset); 6145 } 6146 6147 RegAddr = CGF.Builder.CreateElementBitCast(BaseAddr, MemTy); 6148 } 6149 6150 CGF.EmitBranch(ContBlock); 6151 6152 //======================================= 6153 // Argument was on the stack 6154 //======================================= 6155 CGF.EmitBlock(OnStackBlock); 6156 6157 Address stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "stack_p"); 6158 llvm::Value *OnStackPtr = CGF.Builder.CreateLoad(stack_p, "stack"); 6159 6160 // Again, stack arguments may need realignment. In this case both integer and 6161 // floating-point ones might be affected. 6162 if (!IsIndirect && TyAlign.getQuantity() > 8) { 6163 int Align = TyAlign.getQuantity(); 6164 6165 OnStackPtr = CGF.Builder.CreatePtrToInt(OnStackPtr, CGF.Int64Ty); 6166 6167 OnStackPtr = CGF.Builder.CreateAdd( 6168 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1), 6169 "align_stack"); 6170 OnStackPtr = CGF.Builder.CreateAnd( 6171 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, -Align), 6172 "align_stack"); 6173 6174 OnStackPtr = CGF.Builder.CreateIntToPtr(OnStackPtr, CGF.Int8PtrTy); 6175 } 6176 Address OnStackAddr = Address(OnStackPtr, CGF.Int8Ty, 6177 std::max(CharUnits::fromQuantity(8), TyAlign)); 6178 6179 // All stack slots are multiples of 8 bytes. 6180 CharUnits StackSlotSize = CharUnits::fromQuantity(8); 6181 CharUnits StackSize; 6182 if (IsIndirect) 6183 StackSize = StackSlotSize; 6184 else 6185 StackSize = TySize.alignTo(StackSlotSize); 6186 6187 llvm::Value *StackSizeC = CGF.Builder.getSize(StackSize); 6188 llvm::Value *NewStack = CGF.Builder.CreateInBoundsGEP( 6189 CGF.Int8Ty, OnStackPtr, StackSizeC, "new_stack"); 6190 6191 // Write the new value of __stack for the next call to va_arg 6192 CGF.Builder.CreateStore(NewStack, stack_p); 6193 6194 if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) && 6195 TySize < StackSlotSize) { 6196 CharUnits Offset = StackSlotSize - TySize; 6197 OnStackAddr = CGF.Builder.CreateConstInBoundsByteGEP(OnStackAddr, Offset); 6198 } 6199 6200 OnStackAddr = CGF.Builder.CreateElementBitCast(OnStackAddr, MemTy); 6201 6202 CGF.EmitBranch(ContBlock); 6203 6204 //======================================= 6205 // Tidy up 6206 //======================================= 6207 CGF.EmitBlock(ContBlock); 6208 6209 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, OnStackAddr, 6210 OnStackBlock, "vaargs.addr"); 6211 6212 if (IsIndirect) 6213 return Address(CGF.Builder.CreateLoad(ResAddr, "vaarg.addr"), ElementTy, 6214 TyAlign); 6215 6216 return ResAddr; 6217 } 6218 6219 Address AArch64ABIInfo::EmitDarwinVAArg(Address VAListAddr, QualType Ty, 6220 CodeGenFunction &CGF) const { 6221 // The backend's lowering doesn't support va_arg for aggregates or 6222 // illegal vector types. Lower VAArg here for these cases and use 6223 // the LLVM va_arg instruction for everything else. 6224 if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty)) 6225 return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect()); 6226 6227 uint64_t PointerSize = getTarget().getPointerWidth(0) / 8; 6228 CharUnits SlotSize = CharUnits::fromQuantity(PointerSize); 6229 6230 // Empty records are ignored for parameter passing purposes. 6231 if (isEmptyRecord(getContext(), Ty, true)) { 6232 Address Addr = Address(CGF.Builder.CreateLoad(VAListAddr, "ap.cur"), 6233 getVAListElementType(CGF), SlotSize); 6234 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty)); 6235 return Addr; 6236 } 6237 6238 // The size of the actual thing passed, which might end up just 6239 // being a pointer for indirect types. 6240 auto TyInfo = getContext().getTypeInfoInChars(Ty); 6241 6242 // Arguments bigger than 16 bytes which aren't homogeneous 6243 // aggregates should be passed indirectly. 6244 bool IsIndirect = false; 6245 if (TyInfo.Width.getQuantity() > 16) { 6246 const Type *Base = nullptr; 6247 uint64_t Members = 0; 6248 IsIndirect = !isHomogeneousAggregate(Ty, Base, Members); 6249 } 6250 6251 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, 6252 TyInfo, SlotSize, /*AllowHigherAlign*/ true); 6253 } 6254 6255 Address AArch64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr, 6256 QualType Ty) const { 6257 bool IsIndirect = false; 6258 6259 // Composites larger than 16 bytes are passed by reference. 6260 if (isAggregateTypeForABI(Ty) && getContext().getTypeSize(Ty) > 128) 6261 IsIndirect = true; 6262 6263 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, 6264 CGF.getContext().getTypeInfoInChars(Ty), 6265 CharUnits::fromQuantity(8), 6266 /*allowHigherAlign*/ false); 6267 } 6268 6269 //===----------------------------------------------------------------------===// 6270 // ARM ABI Implementation 6271 //===----------------------------------------------------------------------===// 6272 6273 namespace { 6274 6275 class ARMABIInfo : public SwiftABIInfo { 6276 public: 6277 enum ABIKind { 6278 APCS = 0, 6279 AAPCS = 1, 6280 AAPCS_VFP = 2, 6281 AAPCS16_VFP = 3, 6282 }; 6283 6284 private: 6285 ABIKind Kind; 6286 bool IsFloatABISoftFP; 6287 6288 public: 6289 ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind) 6290 : SwiftABIInfo(CGT), Kind(_Kind) { 6291 setCCs(); 6292 IsFloatABISoftFP = CGT.getCodeGenOpts().FloatABI == "softfp" || 6293 CGT.getCodeGenOpts().FloatABI == ""; // default 6294 } 6295 6296 bool isEABI() const { 6297 switch (getTarget().getTriple().getEnvironment()) { 6298 case llvm::Triple::Android: 6299 case llvm::Triple::EABI: 6300 case llvm::Triple::EABIHF: 6301 case llvm::Triple::GNUEABI: 6302 case llvm::Triple::GNUEABIHF: 6303 case llvm::Triple::MuslEABI: 6304 case llvm::Triple::MuslEABIHF: 6305 return true; 6306 default: 6307 return false; 6308 } 6309 } 6310 6311 bool isEABIHF() const { 6312 switch (getTarget().getTriple().getEnvironment()) { 6313 case llvm::Triple::EABIHF: 6314 case llvm::Triple::GNUEABIHF: 6315 case llvm::Triple::MuslEABIHF: 6316 return true; 6317 default: 6318 return false; 6319 } 6320 } 6321 6322 ABIKind getABIKind() const { return Kind; } 6323 6324 bool allowBFloatArgsAndRet() const override { 6325 return !IsFloatABISoftFP && getTarget().hasBFloat16Type(); 6326 } 6327 6328 private: 6329 ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic, 6330 unsigned functionCallConv) const; 6331 ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic, 6332 unsigned functionCallConv) const; 6333 ABIArgInfo classifyHomogeneousAggregate(QualType Ty, const Type *Base, 6334 uint64_t Members) const; 6335 ABIArgInfo coerceIllegalVector(QualType Ty) const; 6336 bool isIllegalVectorType(QualType Ty) const; 6337 bool containsAnyFP16Vectors(QualType Ty) const; 6338 6339 bool isHomogeneousAggregateBaseType(QualType Ty) const override; 6340 bool isHomogeneousAggregateSmallEnough(const Type *Ty, 6341 uint64_t Members) const override; 6342 6343 bool isEffectivelyAAPCS_VFP(unsigned callConvention, bool acceptHalf) const; 6344 6345 void computeInfo(CGFunctionInfo &FI) const override; 6346 6347 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 6348 QualType Ty) const override; 6349 6350 llvm::CallingConv::ID getLLVMDefaultCC() const; 6351 llvm::CallingConv::ID getABIDefaultCC() const; 6352 void setCCs(); 6353 6354 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars, 6355 bool asReturnValue) const override { 6356 return occupiesMoreThan(CGT, scalars, /*total*/ 4); 6357 } 6358 bool isSwiftErrorInRegister() const override { 6359 return true; 6360 } 6361 bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy, 6362 unsigned elts) const override; 6363 }; 6364 6365 class ARMTargetCodeGenInfo : public TargetCodeGenInfo { 6366 public: 6367 ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K) 6368 : TargetCodeGenInfo(std::make_unique<ARMABIInfo>(CGT, K)) {} 6369 6370 const ARMABIInfo &getABIInfo() const { 6371 return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo()); 6372 } 6373 6374 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 6375 return 13; 6376 } 6377 6378 StringRef getARCRetainAutoreleasedReturnValueMarker() const override { 6379 return "mov\tr7, r7\t\t// marker for objc_retainAutoreleaseReturnValue"; 6380 } 6381 6382 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 6383 llvm::Value *Address) const override { 6384 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4); 6385 6386 // 0-15 are the 16 integer registers. 6387 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15); 6388 return false; 6389 } 6390 6391 unsigned getSizeOfUnwindException() const override { 6392 if (getABIInfo().isEABI()) return 88; 6393 return TargetCodeGenInfo::getSizeOfUnwindException(); 6394 } 6395 6396 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 6397 CodeGen::CodeGenModule &CGM) const override { 6398 if (GV->isDeclaration()) 6399 return; 6400 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D); 6401 if (!FD) 6402 return; 6403 auto *Fn = cast<llvm::Function>(GV); 6404 6405 if (const auto *TA = FD->getAttr<TargetAttr>()) { 6406 ParsedTargetAttr Attr = TA->parse(); 6407 if (!Attr.BranchProtection.empty()) { 6408 TargetInfo::BranchProtectionInfo BPI; 6409 StringRef DiagMsg; 6410 StringRef Arch = Attr.Architecture.empty() 6411 ? CGM.getTarget().getTargetOpts().CPU 6412 : Attr.Architecture; 6413 if (!CGM.getTarget().validateBranchProtection(Attr.BranchProtection, 6414 Arch, BPI, DiagMsg)) { 6415 CGM.getDiags().Report( 6416 D->getLocation(), 6417 diag::warn_target_unsupported_branch_protection_attribute) 6418 << Arch; 6419 } else { 6420 static const char *SignReturnAddrStr[] = {"none", "non-leaf", "all"}; 6421 assert(static_cast<unsigned>(BPI.SignReturnAddr) <= 2 && 6422 "Unexpected SignReturnAddressScopeKind"); 6423 Fn->addFnAttr( 6424 "sign-return-address", 6425 SignReturnAddrStr[static_cast<int>(BPI.SignReturnAddr)]); 6426 6427 Fn->addFnAttr("branch-target-enforcement", 6428 BPI.BranchTargetEnforcement ? "true" : "false"); 6429 } 6430 } else if (CGM.getLangOpts().BranchTargetEnforcement || 6431 CGM.getLangOpts().hasSignReturnAddress()) { 6432 // If the Branch Protection attribute is missing, validate the target 6433 // Architecture attribute against Branch Protection command line 6434 // settings. 6435 if (!CGM.getTarget().isBranchProtectionSupportedArch(Attr.Architecture)) 6436 CGM.getDiags().Report( 6437 D->getLocation(), 6438 diag::warn_target_unsupported_branch_protection_attribute) 6439 << Attr.Architecture; 6440 } 6441 } 6442 6443 const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>(); 6444 if (!Attr) 6445 return; 6446 6447 const char *Kind; 6448 switch (Attr->getInterrupt()) { 6449 case ARMInterruptAttr::Generic: Kind = ""; break; 6450 case ARMInterruptAttr::IRQ: Kind = "IRQ"; break; 6451 case ARMInterruptAttr::FIQ: Kind = "FIQ"; break; 6452 case ARMInterruptAttr::SWI: Kind = "SWI"; break; 6453 case ARMInterruptAttr::ABORT: Kind = "ABORT"; break; 6454 case ARMInterruptAttr::UNDEF: Kind = "UNDEF"; break; 6455 } 6456 6457 Fn->addFnAttr("interrupt", Kind); 6458 6459 ARMABIInfo::ABIKind ABI = cast<ARMABIInfo>(getABIInfo()).getABIKind(); 6460 if (ABI == ARMABIInfo::APCS) 6461 return; 6462 6463 // AAPCS guarantees that sp will be 8-byte aligned on any public interface, 6464 // however this is not necessarily true on taking any interrupt. Instruct 6465 // the backend to perform a realignment as part of the function prologue. 6466 llvm::AttrBuilder B(Fn->getContext()); 6467 B.addStackAlignmentAttr(8); 6468 Fn->addFnAttrs(B); 6469 } 6470 }; 6471 6472 class WindowsARMTargetCodeGenInfo : public ARMTargetCodeGenInfo { 6473 public: 6474 WindowsARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K) 6475 : ARMTargetCodeGenInfo(CGT, K) {} 6476 6477 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 6478 CodeGen::CodeGenModule &CGM) const override; 6479 6480 void getDependentLibraryOption(llvm::StringRef Lib, 6481 llvm::SmallString<24> &Opt) const override { 6482 Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib); 6483 } 6484 6485 void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value, 6486 llvm::SmallString<32> &Opt) const override { 6487 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\""; 6488 } 6489 }; 6490 6491 void WindowsARMTargetCodeGenInfo::setTargetAttributes( 6492 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const { 6493 ARMTargetCodeGenInfo::setTargetAttributes(D, GV, CGM); 6494 if (GV->isDeclaration()) 6495 return; 6496 addStackProbeTargetAttributes(D, GV, CGM); 6497 } 6498 } 6499 6500 void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const { 6501 if (!::classifyReturnType(getCXXABI(), FI, *this)) 6502 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), FI.isVariadic(), 6503 FI.getCallingConvention()); 6504 6505 for (auto &I : FI.arguments()) 6506 I.info = classifyArgumentType(I.type, FI.isVariadic(), 6507 FI.getCallingConvention()); 6508 6509 6510 // Always honor user-specified calling convention. 6511 if (FI.getCallingConvention() != llvm::CallingConv::C) 6512 return; 6513 6514 llvm::CallingConv::ID cc = getRuntimeCC(); 6515 if (cc != llvm::CallingConv::C) 6516 FI.setEffectiveCallingConvention(cc); 6517 } 6518 6519 /// Return the default calling convention that LLVM will use. 6520 llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const { 6521 // The default calling convention that LLVM will infer. 6522 if (isEABIHF() || getTarget().getTriple().isWatchABI()) 6523 return llvm::CallingConv::ARM_AAPCS_VFP; 6524 else if (isEABI()) 6525 return llvm::CallingConv::ARM_AAPCS; 6526 else 6527 return llvm::CallingConv::ARM_APCS; 6528 } 6529 6530 /// Return the calling convention that our ABI would like us to use 6531 /// as the C calling convention. 6532 llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const { 6533 switch (getABIKind()) { 6534 case APCS: return llvm::CallingConv::ARM_APCS; 6535 case AAPCS: return llvm::CallingConv::ARM_AAPCS; 6536 case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP; 6537 case AAPCS16_VFP: return llvm::CallingConv::ARM_AAPCS_VFP; 6538 } 6539 llvm_unreachable("bad ABI kind"); 6540 } 6541 6542 void ARMABIInfo::setCCs() { 6543 assert(getRuntimeCC() == llvm::CallingConv::C); 6544 6545 // Don't muddy up the IR with a ton of explicit annotations if 6546 // they'd just match what LLVM will infer from the triple. 6547 llvm::CallingConv::ID abiCC = getABIDefaultCC(); 6548 if (abiCC != getLLVMDefaultCC()) 6549 RuntimeCC = abiCC; 6550 } 6551 6552 ABIArgInfo ARMABIInfo::coerceIllegalVector(QualType Ty) const { 6553 uint64_t Size = getContext().getTypeSize(Ty); 6554 if (Size <= 32) { 6555 llvm::Type *ResType = 6556 llvm::Type::getInt32Ty(getVMContext()); 6557 return ABIArgInfo::getDirect(ResType); 6558 } 6559 if (Size == 64 || Size == 128) { 6560 auto *ResType = llvm::FixedVectorType::get( 6561 llvm::Type::getInt32Ty(getVMContext()), Size / 32); 6562 return ABIArgInfo::getDirect(ResType); 6563 } 6564 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 6565 } 6566 6567 ABIArgInfo ARMABIInfo::classifyHomogeneousAggregate(QualType Ty, 6568 const Type *Base, 6569 uint64_t Members) const { 6570 assert(Base && "Base class should be set for homogeneous aggregate"); 6571 // Base can be a floating-point or a vector. 6572 if (const VectorType *VT = Base->getAs<VectorType>()) { 6573 // FP16 vectors should be converted to integer vectors 6574 if (!getTarget().hasLegalHalfType() && containsAnyFP16Vectors(Ty)) { 6575 uint64_t Size = getContext().getTypeSize(VT); 6576 auto *NewVecTy = llvm::FixedVectorType::get( 6577 llvm::Type::getInt32Ty(getVMContext()), Size / 32); 6578 llvm::Type *Ty = llvm::ArrayType::get(NewVecTy, Members); 6579 return ABIArgInfo::getDirect(Ty, 0, nullptr, false); 6580 } 6581 } 6582 unsigned Align = 0; 6583 if (getABIKind() == ARMABIInfo::AAPCS || 6584 getABIKind() == ARMABIInfo::AAPCS_VFP) { 6585 // For alignment adjusted HFAs, cap the argument alignment to 8, leave it 6586 // default otherwise. 6587 Align = getContext().getTypeUnadjustedAlignInChars(Ty).getQuantity(); 6588 unsigned BaseAlign = getContext().getTypeAlignInChars(Base).getQuantity(); 6589 Align = (Align > BaseAlign && Align >= 8) ? 8 : 0; 6590 } 6591 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false, Align); 6592 } 6593 6594 ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty, bool isVariadic, 6595 unsigned functionCallConv) const { 6596 // 6.1.2.1 The following argument types are VFP CPRCs: 6597 // A single-precision floating-point type (including promoted 6598 // half-precision types); A double-precision floating-point type; 6599 // A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate 6600 // with a Base Type of a single- or double-precision floating-point type, 6601 // 64-bit containerized vectors or 128-bit containerized vectors with one 6602 // to four Elements. 6603 // Variadic functions should always marshal to the base standard. 6604 bool IsAAPCS_VFP = 6605 !isVariadic && isEffectivelyAAPCS_VFP(functionCallConv, /* AAPCS16 */ false); 6606 6607 Ty = useFirstFieldIfTransparentUnion(Ty); 6608 6609 // Handle illegal vector types here. 6610 if (isIllegalVectorType(Ty)) 6611 return coerceIllegalVector(Ty); 6612 6613 if (!isAggregateTypeForABI(Ty)) { 6614 // Treat an enum type as its underlying type. 6615 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) { 6616 Ty = EnumTy->getDecl()->getIntegerType(); 6617 } 6618 6619 if (const auto *EIT = Ty->getAs<BitIntType>()) 6620 if (EIT->getNumBits() > 64) 6621 return getNaturalAlignIndirect(Ty, /*ByVal=*/true); 6622 6623 return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty) 6624 : ABIArgInfo::getDirect()); 6625 } 6626 6627 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) { 6628 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 6629 } 6630 6631 // Ignore empty records. 6632 if (isEmptyRecord(getContext(), Ty, true)) 6633 return ABIArgInfo::getIgnore(); 6634 6635 if (IsAAPCS_VFP) { 6636 // Homogeneous Aggregates need to be expanded when we can fit the aggregate 6637 // into VFP registers. 6638 const Type *Base = nullptr; 6639 uint64_t Members = 0; 6640 if (isHomogeneousAggregate(Ty, Base, Members)) 6641 return classifyHomogeneousAggregate(Ty, Base, Members); 6642 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) { 6643 // WatchOS does have homogeneous aggregates. Note that we intentionally use 6644 // this convention even for a variadic function: the backend will use GPRs 6645 // if needed. 6646 const Type *Base = nullptr; 6647 uint64_t Members = 0; 6648 if (isHomogeneousAggregate(Ty, Base, Members)) { 6649 assert(Base && Members <= 4 && "unexpected homogeneous aggregate"); 6650 llvm::Type *Ty = 6651 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members); 6652 return ABIArgInfo::getDirect(Ty, 0, nullptr, false); 6653 } 6654 } 6655 6656 if (getABIKind() == ARMABIInfo::AAPCS16_VFP && 6657 getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(16)) { 6658 // WatchOS is adopting the 64-bit AAPCS rule on composite types: if they're 6659 // bigger than 128-bits, they get placed in space allocated by the caller, 6660 // and a pointer is passed. 6661 return ABIArgInfo::getIndirect( 6662 CharUnits::fromQuantity(getContext().getTypeAlign(Ty) / 8), false); 6663 } 6664 6665 // Support byval for ARM. 6666 // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at 6667 // most 8-byte. We realign the indirect argument if type alignment is bigger 6668 // than ABI alignment. 6669 uint64_t ABIAlign = 4; 6670 uint64_t TyAlign; 6671 if (getABIKind() == ARMABIInfo::AAPCS_VFP || 6672 getABIKind() == ARMABIInfo::AAPCS) { 6673 TyAlign = getContext().getTypeUnadjustedAlignInChars(Ty).getQuantity(); 6674 ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8); 6675 } else { 6676 TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity(); 6677 } 6678 if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) { 6679 assert(getABIKind() != ARMABIInfo::AAPCS16_VFP && "unexpected byval"); 6680 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign), 6681 /*ByVal=*/true, 6682 /*Realign=*/TyAlign > ABIAlign); 6683 } 6684 6685 // On RenderScript, coerce Aggregates <= 64 bytes to an integer array of 6686 // same size and alignment. 6687 if (getTarget().isRenderScriptTarget()) { 6688 return coerceToIntArray(Ty, getContext(), getVMContext()); 6689 } 6690 6691 // Otherwise, pass by coercing to a structure of the appropriate size. 6692 llvm::Type* ElemTy; 6693 unsigned SizeRegs; 6694 // FIXME: Try to match the types of the arguments more accurately where 6695 // we can. 6696 if (TyAlign <= 4) { 6697 ElemTy = llvm::Type::getInt32Ty(getVMContext()); 6698 SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32; 6699 } else { 6700 ElemTy = llvm::Type::getInt64Ty(getVMContext()); 6701 SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64; 6702 } 6703 6704 return ABIArgInfo::getDirect(llvm::ArrayType::get(ElemTy, SizeRegs)); 6705 } 6706 6707 static bool isIntegerLikeType(QualType Ty, ASTContext &Context, 6708 llvm::LLVMContext &VMContext) { 6709 // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure 6710 // is called integer-like if its size is less than or equal to one word, and 6711 // the offset of each of its addressable sub-fields is zero. 6712 6713 uint64_t Size = Context.getTypeSize(Ty); 6714 6715 // Check that the type fits in a word. 6716 if (Size > 32) 6717 return false; 6718 6719 // FIXME: Handle vector types! 6720 if (Ty->isVectorType()) 6721 return false; 6722 6723 // Float types are never treated as "integer like". 6724 if (Ty->isRealFloatingType()) 6725 return false; 6726 6727 // If this is a builtin or pointer type then it is ok. 6728 if (Ty->getAs<BuiltinType>() || Ty->isPointerType()) 6729 return true; 6730 6731 // Small complex integer types are "integer like". 6732 if (const ComplexType *CT = Ty->getAs<ComplexType>()) 6733 return isIntegerLikeType(CT->getElementType(), Context, VMContext); 6734 6735 // Single element and zero sized arrays should be allowed, by the definition 6736 // above, but they are not. 6737 6738 // Otherwise, it must be a record type. 6739 const RecordType *RT = Ty->getAs<RecordType>(); 6740 if (!RT) return false; 6741 6742 // Ignore records with flexible arrays. 6743 const RecordDecl *RD = RT->getDecl(); 6744 if (RD->hasFlexibleArrayMember()) 6745 return false; 6746 6747 // Check that all sub-fields are at offset 0, and are themselves "integer 6748 // like". 6749 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); 6750 6751 bool HadField = false; 6752 unsigned idx = 0; 6753 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 6754 i != e; ++i, ++idx) { 6755 const FieldDecl *FD = *i; 6756 6757 // Bit-fields are not addressable, we only need to verify they are "integer 6758 // like". We still have to disallow a subsequent non-bitfield, for example: 6759 // struct { int : 0; int x } 6760 // is non-integer like according to gcc. 6761 if (FD->isBitField()) { 6762 if (!RD->isUnion()) 6763 HadField = true; 6764 6765 if (!isIntegerLikeType(FD->getType(), Context, VMContext)) 6766 return false; 6767 6768 continue; 6769 } 6770 6771 // Check if this field is at offset 0. 6772 if (Layout.getFieldOffset(idx) != 0) 6773 return false; 6774 6775 if (!isIntegerLikeType(FD->getType(), Context, VMContext)) 6776 return false; 6777 6778 // Only allow at most one field in a structure. This doesn't match the 6779 // wording above, but follows gcc in situations with a field following an 6780 // empty structure. 6781 if (!RD->isUnion()) { 6782 if (HadField) 6783 return false; 6784 6785 HadField = true; 6786 } 6787 } 6788 6789 return true; 6790 } 6791 6792 ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy, bool isVariadic, 6793 unsigned functionCallConv) const { 6794 6795 // Variadic functions should always marshal to the base standard. 6796 bool IsAAPCS_VFP = 6797 !isVariadic && isEffectivelyAAPCS_VFP(functionCallConv, /* AAPCS16 */ true); 6798 6799 if (RetTy->isVoidType()) 6800 return ABIArgInfo::getIgnore(); 6801 6802 if (const VectorType *VT = RetTy->getAs<VectorType>()) { 6803 // Large vector types should be returned via memory. 6804 if (getContext().getTypeSize(RetTy) > 128) 6805 return getNaturalAlignIndirect(RetTy); 6806 // TODO: FP16/BF16 vectors should be converted to integer vectors 6807 // This check is similar to isIllegalVectorType - refactor? 6808 if ((!getTarget().hasLegalHalfType() && 6809 (VT->getElementType()->isFloat16Type() || 6810 VT->getElementType()->isHalfType())) || 6811 (IsFloatABISoftFP && 6812 VT->getElementType()->isBFloat16Type())) 6813 return coerceIllegalVector(RetTy); 6814 } 6815 6816 if (!isAggregateTypeForABI(RetTy)) { 6817 // Treat an enum type as its underlying type. 6818 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 6819 RetTy = EnumTy->getDecl()->getIntegerType(); 6820 6821 if (const auto *EIT = RetTy->getAs<BitIntType>()) 6822 if (EIT->getNumBits() > 64) 6823 return getNaturalAlignIndirect(RetTy, /*ByVal=*/false); 6824 6825 return isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy) 6826 : ABIArgInfo::getDirect(); 6827 } 6828 6829 // Are we following APCS? 6830 if (getABIKind() == APCS) { 6831 if (isEmptyRecord(getContext(), RetTy, false)) 6832 return ABIArgInfo::getIgnore(); 6833 6834 // Complex types are all returned as packed integers. 6835 // 6836 // FIXME: Consider using 2 x vector types if the back end handles them 6837 // correctly. 6838 if (RetTy->isAnyComplexType()) 6839 return ABIArgInfo::getDirect(llvm::IntegerType::get( 6840 getVMContext(), getContext().getTypeSize(RetTy))); 6841 6842 // Integer like structures are returned in r0. 6843 if (isIntegerLikeType(RetTy, getContext(), getVMContext())) { 6844 // Return in the smallest viable integer type. 6845 uint64_t Size = getContext().getTypeSize(RetTy); 6846 if (Size <= 8) 6847 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext())); 6848 if (Size <= 16) 6849 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext())); 6850 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext())); 6851 } 6852 6853 // Otherwise return in memory. 6854 return getNaturalAlignIndirect(RetTy); 6855 } 6856 6857 // Otherwise this is an AAPCS variant. 6858 6859 if (isEmptyRecord(getContext(), RetTy, true)) 6860 return ABIArgInfo::getIgnore(); 6861 6862 // Check for homogeneous aggregates with AAPCS-VFP. 6863 if (IsAAPCS_VFP) { 6864 const Type *Base = nullptr; 6865 uint64_t Members = 0; 6866 if (isHomogeneousAggregate(RetTy, Base, Members)) 6867 return classifyHomogeneousAggregate(RetTy, Base, Members); 6868 } 6869 6870 // Aggregates <= 4 bytes are returned in r0; other aggregates 6871 // are returned indirectly. 6872 uint64_t Size = getContext().getTypeSize(RetTy); 6873 if (Size <= 32) { 6874 // On RenderScript, coerce Aggregates <= 4 bytes to an integer array of 6875 // same size and alignment. 6876 if (getTarget().isRenderScriptTarget()) { 6877 return coerceToIntArray(RetTy, getContext(), getVMContext()); 6878 } 6879 if (getDataLayout().isBigEndian()) 6880 // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4) 6881 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext())); 6882 6883 // Return in the smallest viable integer type. 6884 if (Size <= 8) 6885 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext())); 6886 if (Size <= 16) 6887 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext())); 6888 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext())); 6889 } else if (Size <= 128 && getABIKind() == AAPCS16_VFP) { 6890 llvm::Type *Int32Ty = llvm::Type::getInt32Ty(getVMContext()); 6891 llvm::Type *CoerceTy = 6892 llvm::ArrayType::get(Int32Ty, llvm::alignTo(Size, 32) / 32); 6893 return ABIArgInfo::getDirect(CoerceTy); 6894 } 6895 6896 return getNaturalAlignIndirect(RetTy); 6897 } 6898 6899 /// isIllegalVector - check whether Ty is an illegal vector type. 6900 bool ARMABIInfo::isIllegalVectorType(QualType Ty) const { 6901 if (const VectorType *VT = Ty->getAs<VectorType> ()) { 6902 // On targets that don't support half, fp16 or bfloat, they are expanded 6903 // into float, and we don't want the ABI to depend on whether or not they 6904 // are supported in hardware. Thus return false to coerce vectors of these 6905 // types into integer vectors. 6906 // We do not depend on hasLegalHalfType for bfloat as it is a 6907 // separate IR type. 6908 if ((!getTarget().hasLegalHalfType() && 6909 (VT->getElementType()->isFloat16Type() || 6910 VT->getElementType()->isHalfType())) || 6911 (IsFloatABISoftFP && 6912 VT->getElementType()->isBFloat16Type())) 6913 return true; 6914 if (isAndroid()) { 6915 // Android shipped using Clang 3.1, which supported a slightly different 6916 // vector ABI. The primary differences were that 3-element vector types 6917 // were legal, and so were sub 32-bit vectors (i.e. <2 x i8>). This path 6918 // accepts that legacy behavior for Android only. 6919 // Check whether VT is legal. 6920 unsigned NumElements = VT->getNumElements(); 6921 // NumElements should be power of 2 or equal to 3. 6922 if (!llvm::isPowerOf2_32(NumElements) && NumElements != 3) 6923 return true; 6924 } else { 6925 // Check whether VT is legal. 6926 unsigned NumElements = VT->getNumElements(); 6927 uint64_t Size = getContext().getTypeSize(VT); 6928 // NumElements should be power of 2. 6929 if (!llvm::isPowerOf2_32(NumElements)) 6930 return true; 6931 // Size should be greater than 32 bits. 6932 return Size <= 32; 6933 } 6934 } 6935 return false; 6936 } 6937 6938 /// Return true if a type contains any 16-bit floating point vectors 6939 bool ARMABIInfo::containsAnyFP16Vectors(QualType Ty) const { 6940 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) { 6941 uint64_t NElements = AT->getSize().getZExtValue(); 6942 if (NElements == 0) 6943 return false; 6944 return containsAnyFP16Vectors(AT->getElementType()); 6945 } else if (const RecordType *RT = Ty->getAs<RecordType>()) { 6946 const RecordDecl *RD = RT->getDecl(); 6947 6948 // If this is a C++ record, check the bases first. 6949 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 6950 if (llvm::any_of(CXXRD->bases(), [this](const CXXBaseSpecifier &B) { 6951 return containsAnyFP16Vectors(B.getType()); 6952 })) 6953 return true; 6954 6955 if (llvm::any_of(RD->fields(), [this](FieldDecl *FD) { 6956 return FD && containsAnyFP16Vectors(FD->getType()); 6957 })) 6958 return true; 6959 6960 return false; 6961 } else { 6962 if (const VectorType *VT = Ty->getAs<VectorType>()) 6963 return (VT->getElementType()->isFloat16Type() || 6964 VT->getElementType()->isBFloat16Type() || 6965 VT->getElementType()->isHalfType()); 6966 return false; 6967 } 6968 } 6969 6970 bool ARMABIInfo::isLegalVectorTypeForSwift(CharUnits vectorSize, 6971 llvm::Type *eltTy, 6972 unsigned numElts) const { 6973 if (!llvm::isPowerOf2_32(numElts)) 6974 return false; 6975 unsigned size = getDataLayout().getTypeStoreSizeInBits(eltTy); 6976 if (size > 64) 6977 return false; 6978 if (vectorSize.getQuantity() != 8 && 6979 (vectorSize.getQuantity() != 16 || numElts == 1)) 6980 return false; 6981 return true; 6982 } 6983 6984 bool ARMABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const { 6985 // Homogeneous aggregates for AAPCS-VFP must have base types of float, 6986 // double, or 64-bit or 128-bit vectors. 6987 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) { 6988 if (BT->getKind() == BuiltinType::Float || 6989 BT->getKind() == BuiltinType::Double || 6990 BT->getKind() == BuiltinType::LongDouble) 6991 return true; 6992 } else if (const VectorType *VT = Ty->getAs<VectorType>()) { 6993 unsigned VecSize = getContext().getTypeSize(VT); 6994 if (VecSize == 64 || VecSize == 128) 6995 return true; 6996 } 6997 return false; 6998 } 6999 7000 bool ARMABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base, 7001 uint64_t Members) const { 7002 return Members <= 4; 7003 } 7004 7005 bool ARMABIInfo::isEffectivelyAAPCS_VFP(unsigned callConvention, 7006 bool acceptHalf) const { 7007 // Give precedence to user-specified calling conventions. 7008 if (callConvention != llvm::CallingConv::C) 7009 return (callConvention == llvm::CallingConv::ARM_AAPCS_VFP); 7010 else 7011 return (getABIKind() == AAPCS_VFP) || 7012 (acceptHalf && (getABIKind() == AAPCS16_VFP)); 7013 } 7014 7015 Address ARMABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 7016 QualType Ty) const { 7017 CharUnits SlotSize = CharUnits::fromQuantity(4); 7018 7019 // Empty records are ignored for parameter passing purposes. 7020 if (isEmptyRecord(getContext(), Ty, true)) { 7021 Address Addr = Address(CGF.Builder.CreateLoad(VAListAddr), 7022 getVAListElementType(CGF), SlotSize); 7023 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty)); 7024 return Addr; 7025 } 7026 7027 CharUnits TySize = getContext().getTypeSizeInChars(Ty); 7028 CharUnits TyAlignForABI = getContext().getTypeUnadjustedAlignInChars(Ty); 7029 7030 // Use indirect if size of the illegal vector is bigger than 16 bytes. 7031 bool IsIndirect = false; 7032 const Type *Base = nullptr; 7033 uint64_t Members = 0; 7034 if (TySize > CharUnits::fromQuantity(16) && isIllegalVectorType(Ty)) { 7035 IsIndirect = true; 7036 7037 // ARMv7k passes structs bigger than 16 bytes indirectly, in space 7038 // allocated by the caller. 7039 } else if (TySize > CharUnits::fromQuantity(16) && 7040 getABIKind() == ARMABIInfo::AAPCS16_VFP && 7041 !isHomogeneousAggregate(Ty, Base, Members)) { 7042 IsIndirect = true; 7043 7044 // Otherwise, bound the type's ABI alignment. 7045 // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for 7046 // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte. 7047 // Our callers should be prepared to handle an under-aligned address. 7048 } else if (getABIKind() == ARMABIInfo::AAPCS_VFP || 7049 getABIKind() == ARMABIInfo::AAPCS) { 7050 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4)); 7051 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(8)); 7052 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) { 7053 // ARMv7k allows type alignment up to 16 bytes. 7054 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4)); 7055 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(16)); 7056 } else { 7057 TyAlignForABI = CharUnits::fromQuantity(4); 7058 } 7059 7060 TypeInfoChars TyInfo(TySize, TyAlignForABI, AlignRequirementKind::None); 7061 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TyInfo, 7062 SlotSize, /*AllowHigherAlign*/ true); 7063 } 7064 7065 //===----------------------------------------------------------------------===// 7066 // NVPTX ABI Implementation 7067 //===----------------------------------------------------------------------===// 7068 7069 namespace { 7070 7071 class NVPTXTargetCodeGenInfo; 7072 7073 class NVPTXABIInfo : public ABIInfo { 7074 NVPTXTargetCodeGenInfo &CGInfo; 7075 7076 public: 7077 NVPTXABIInfo(CodeGenTypes &CGT, NVPTXTargetCodeGenInfo &Info) 7078 : ABIInfo(CGT), CGInfo(Info) {} 7079 7080 ABIArgInfo classifyReturnType(QualType RetTy) const; 7081 ABIArgInfo classifyArgumentType(QualType Ty) const; 7082 7083 void computeInfo(CGFunctionInfo &FI) const override; 7084 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 7085 QualType Ty) const override; 7086 bool isUnsupportedType(QualType T) const; 7087 ABIArgInfo coerceToIntArrayWithLimit(QualType Ty, unsigned MaxSize) const; 7088 }; 7089 7090 class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo { 7091 public: 7092 NVPTXTargetCodeGenInfo(CodeGenTypes &CGT) 7093 : TargetCodeGenInfo(std::make_unique<NVPTXABIInfo>(CGT, *this)) {} 7094 7095 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 7096 CodeGen::CodeGenModule &M) const override; 7097 bool shouldEmitStaticExternCAliases() const override; 7098 7099 llvm::Type *getCUDADeviceBuiltinSurfaceDeviceType() const override { 7100 // On the device side, surface reference is represented as an object handle 7101 // in 64-bit integer. 7102 return llvm::Type::getInt64Ty(getABIInfo().getVMContext()); 7103 } 7104 7105 llvm::Type *getCUDADeviceBuiltinTextureDeviceType() const override { 7106 // On the device side, texture reference is represented as an object handle 7107 // in 64-bit integer. 7108 return llvm::Type::getInt64Ty(getABIInfo().getVMContext()); 7109 } 7110 7111 bool emitCUDADeviceBuiltinSurfaceDeviceCopy(CodeGenFunction &CGF, LValue Dst, 7112 LValue Src) const override { 7113 emitBuiltinSurfTexDeviceCopy(CGF, Dst, Src); 7114 return true; 7115 } 7116 7117 bool emitCUDADeviceBuiltinTextureDeviceCopy(CodeGenFunction &CGF, LValue Dst, 7118 LValue Src) const override { 7119 emitBuiltinSurfTexDeviceCopy(CGF, Dst, Src); 7120 return true; 7121 } 7122 7123 private: 7124 // Adds a NamedMDNode with GV, Name, and Operand as operands, and adds the 7125 // resulting MDNode to the nvvm.annotations MDNode. 7126 static void addNVVMMetadata(llvm::GlobalValue *GV, StringRef Name, 7127 int Operand); 7128 7129 static void emitBuiltinSurfTexDeviceCopy(CodeGenFunction &CGF, LValue Dst, 7130 LValue Src) { 7131 llvm::Value *Handle = nullptr; 7132 llvm::Constant *C = 7133 llvm::dyn_cast<llvm::Constant>(Src.getAddress(CGF).getPointer()); 7134 // Lookup `addrspacecast` through the constant pointer if any. 7135 if (auto *ASC = llvm::dyn_cast_or_null<llvm::AddrSpaceCastOperator>(C)) 7136 C = llvm::cast<llvm::Constant>(ASC->getPointerOperand()); 7137 if (auto *GV = llvm::dyn_cast_or_null<llvm::GlobalVariable>(C)) { 7138 // Load the handle from the specific global variable using 7139 // `nvvm.texsurf.handle.internal` intrinsic. 7140 Handle = CGF.EmitRuntimeCall( 7141 CGF.CGM.getIntrinsic(llvm::Intrinsic::nvvm_texsurf_handle_internal, 7142 {GV->getType()}), 7143 {GV}, "texsurf_handle"); 7144 } else 7145 Handle = CGF.EmitLoadOfScalar(Src, SourceLocation()); 7146 CGF.EmitStoreOfScalar(Handle, Dst); 7147 } 7148 }; 7149 7150 /// Checks if the type is unsupported directly by the current target. 7151 bool NVPTXABIInfo::isUnsupportedType(QualType T) const { 7152 ASTContext &Context = getContext(); 7153 if (!Context.getTargetInfo().hasFloat16Type() && T->isFloat16Type()) 7154 return true; 7155 if (!Context.getTargetInfo().hasFloat128Type() && 7156 (T->isFloat128Type() || 7157 (T->isRealFloatingType() && Context.getTypeSize(T) == 128))) 7158 return true; 7159 if (const auto *EIT = T->getAs<BitIntType>()) 7160 return EIT->getNumBits() > 7161 (Context.getTargetInfo().hasInt128Type() ? 128U : 64U); 7162 if (!Context.getTargetInfo().hasInt128Type() && T->isIntegerType() && 7163 Context.getTypeSize(T) > 64U) 7164 return true; 7165 if (const auto *AT = T->getAsArrayTypeUnsafe()) 7166 return isUnsupportedType(AT->getElementType()); 7167 const auto *RT = T->getAs<RecordType>(); 7168 if (!RT) 7169 return false; 7170 const RecordDecl *RD = RT->getDecl(); 7171 7172 // If this is a C++ record, check the bases first. 7173 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 7174 for (const CXXBaseSpecifier &I : CXXRD->bases()) 7175 if (isUnsupportedType(I.getType())) 7176 return true; 7177 7178 for (const FieldDecl *I : RD->fields()) 7179 if (isUnsupportedType(I->getType())) 7180 return true; 7181 return false; 7182 } 7183 7184 /// Coerce the given type into an array with maximum allowed size of elements. 7185 ABIArgInfo NVPTXABIInfo::coerceToIntArrayWithLimit(QualType Ty, 7186 unsigned MaxSize) const { 7187 // Alignment and Size are measured in bits. 7188 const uint64_t Size = getContext().getTypeSize(Ty); 7189 const uint64_t Alignment = getContext().getTypeAlign(Ty); 7190 const unsigned Div = std::min<unsigned>(MaxSize, Alignment); 7191 llvm::Type *IntType = llvm::Type::getIntNTy(getVMContext(), Div); 7192 const uint64_t NumElements = (Size + Div - 1) / Div; 7193 return ABIArgInfo::getDirect(llvm::ArrayType::get(IntType, NumElements)); 7194 } 7195 7196 ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const { 7197 if (RetTy->isVoidType()) 7198 return ABIArgInfo::getIgnore(); 7199 7200 if (getContext().getLangOpts().OpenMP && 7201 getContext().getLangOpts().OpenMPIsDevice && isUnsupportedType(RetTy)) 7202 return coerceToIntArrayWithLimit(RetTy, 64); 7203 7204 // note: this is different from default ABI 7205 if (!RetTy->isScalarType()) 7206 return ABIArgInfo::getDirect(); 7207 7208 // Treat an enum type as its underlying type. 7209 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 7210 RetTy = EnumTy->getDecl()->getIntegerType(); 7211 7212 return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy) 7213 : ABIArgInfo::getDirect()); 7214 } 7215 7216 ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const { 7217 // Treat an enum type as its underlying type. 7218 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 7219 Ty = EnumTy->getDecl()->getIntegerType(); 7220 7221 // Return aggregates type as indirect by value 7222 if (isAggregateTypeForABI(Ty)) { 7223 // Under CUDA device compilation, tex/surf builtin types are replaced with 7224 // object types and passed directly. 7225 if (getContext().getLangOpts().CUDAIsDevice) { 7226 if (Ty->isCUDADeviceBuiltinSurfaceType()) 7227 return ABIArgInfo::getDirect( 7228 CGInfo.getCUDADeviceBuiltinSurfaceDeviceType()); 7229 if (Ty->isCUDADeviceBuiltinTextureType()) 7230 return ABIArgInfo::getDirect( 7231 CGInfo.getCUDADeviceBuiltinTextureDeviceType()); 7232 } 7233 return getNaturalAlignIndirect(Ty, /* byval */ true); 7234 } 7235 7236 if (const auto *EIT = Ty->getAs<BitIntType>()) { 7237 if ((EIT->getNumBits() > 128) || 7238 (!getContext().getTargetInfo().hasInt128Type() && 7239 EIT->getNumBits() > 64)) 7240 return getNaturalAlignIndirect(Ty, /* byval */ true); 7241 } 7242 7243 return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty) 7244 : ABIArgInfo::getDirect()); 7245 } 7246 7247 void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const { 7248 if (!getCXXABI().classifyReturnType(FI)) 7249 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 7250 for (auto &I : FI.arguments()) 7251 I.info = classifyArgumentType(I.type); 7252 7253 // Always honor user-specified calling convention. 7254 if (FI.getCallingConvention() != llvm::CallingConv::C) 7255 return; 7256 7257 FI.setEffectiveCallingConvention(getRuntimeCC()); 7258 } 7259 7260 Address NVPTXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 7261 QualType Ty) const { 7262 llvm_unreachable("NVPTX does not support varargs"); 7263 } 7264 7265 void NVPTXTargetCodeGenInfo::setTargetAttributes( 7266 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const { 7267 if (GV->isDeclaration()) 7268 return; 7269 const VarDecl *VD = dyn_cast_or_null<VarDecl>(D); 7270 if (VD) { 7271 if (M.getLangOpts().CUDA) { 7272 if (VD->getType()->isCUDADeviceBuiltinSurfaceType()) 7273 addNVVMMetadata(GV, "surface", 1); 7274 else if (VD->getType()->isCUDADeviceBuiltinTextureType()) 7275 addNVVMMetadata(GV, "texture", 1); 7276 return; 7277 } 7278 } 7279 7280 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D); 7281 if (!FD) return; 7282 7283 llvm::Function *F = cast<llvm::Function>(GV); 7284 7285 // Perform special handling in OpenCL mode 7286 if (M.getLangOpts().OpenCL) { 7287 // Use OpenCL function attributes to check for kernel functions 7288 // By default, all functions are device functions 7289 if (FD->hasAttr<OpenCLKernelAttr>()) { 7290 // OpenCL __kernel functions get kernel metadata 7291 // Create !{<func-ref>, metadata !"kernel", i32 1} node 7292 addNVVMMetadata(F, "kernel", 1); 7293 // And kernel functions are not subject to inlining 7294 F->addFnAttr(llvm::Attribute::NoInline); 7295 } 7296 } 7297 7298 // Perform special handling in CUDA mode. 7299 if (M.getLangOpts().CUDA) { 7300 // CUDA __global__ functions get a kernel metadata entry. Since 7301 // __global__ functions cannot be called from the device, we do not 7302 // need to set the noinline attribute. 7303 if (FD->hasAttr<CUDAGlobalAttr>()) { 7304 // Create !{<func-ref>, metadata !"kernel", i32 1} node 7305 addNVVMMetadata(F, "kernel", 1); 7306 } 7307 if (CUDALaunchBoundsAttr *Attr = FD->getAttr<CUDALaunchBoundsAttr>()) { 7308 // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node 7309 llvm::APSInt MaxThreads(32); 7310 MaxThreads = Attr->getMaxThreads()->EvaluateKnownConstInt(M.getContext()); 7311 if (MaxThreads > 0) 7312 addNVVMMetadata(F, "maxntidx", MaxThreads.getExtValue()); 7313 7314 // min blocks is an optional argument for CUDALaunchBoundsAttr. If it was 7315 // not specified in __launch_bounds__ or if the user specified a 0 value, 7316 // we don't have to add a PTX directive. 7317 if (Attr->getMinBlocks()) { 7318 llvm::APSInt MinBlocks(32); 7319 MinBlocks = Attr->getMinBlocks()->EvaluateKnownConstInt(M.getContext()); 7320 if (MinBlocks > 0) 7321 // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node 7322 addNVVMMetadata(F, "minctasm", MinBlocks.getExtValue()); 7323 } 7324 } 7325 } 7326 } 7327 7328 void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::GlobalValue *GV, 7329 StringRef Name, int Operand) { 7330 llvm::Module *M = GV->getParent(); 7331 llvm::LLVMContext &Ctx = M->getContext(); 7332 7333 // Get "nvvm.annotations" metadata node 7334 llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations"); 7335 7336 llvm::Metadata *MDVals[] = { 7337 llvm::ConstantAsMetadata::get(GV), llvm::MDString::get(Ctx, Name), 7338 llvm::ConstantAsMetadata::get( 7339 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand))}; 7340 // Append metadata to nvvm.annotations 7341 MD->addOperand(llvm::MDNode::get(Ctx, MDVals)); 7342 } 7343 7344 bool NVPTXTargetCodeGenInfo::shouldEmitStaticExternCAliases() const { 7345 return false; 7346 } 7347 } 7348 7349 //===----------------------------------------------------------------------===// 7350 // SystemZ ABI Implementation 7351 //===----------------------------------------------------------------------===// 7352 7353 namespace { 7354 7355 class SystemZABIInfo : public SwiftABIInfo { 7356 bool HasVector; 7357 bool IsSoftFloatABI; 7358 7359 public: 7360 SystemZABIInfo(CodeGenTypes &CGT, bool HV, bool SF) 7361 : SwiftABIInfo(CGT), HasVector(HV), IsSoftFloatABI(SF) {} 7362 7363 bool isPromotableIntegerTypeForABI(QualType Ty) const; 7364 bool isCompoundType(QualType Ty) const; 7365 bool isVectorArgumentType(QualType Ty) const; 7366 bool isFPArgumentType(QualType Ty) const; 7367 QualType GetSingleElementType(QualType Ty) const; 7368 7369 ABIArgInfo classifyReturnType(QualType RetTy) const; 7370 ABIArgInfo classifyArgumentType(QualType ArgTy) const; 7371 7372 void computeInfo(CGFunctionInfo &FI) const override { 7373 if (!getCXXABI().classifyReturnType(FI)) 7374 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 7375 for (auto &I : FI.arguments()) 7376 I.info = classifyArgumentType(I.type); 7377 } 7378 7379 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 7380 QualType Ty) const override; 7381 7382 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars, 7383 bool asReturnValue) const override { 7384 return occupiesMoreThan(CGT, scalars, /*total*/ 4); 7385 } 7386 bool isSwiftErrorInRegister() const override { 7387 return false; 7388 } 7389 }; 7390 7391 class SystemZTargetCodeGenInfo : public TargetCodeGenInfo { 7392 public: 7393 SystemZTargetCodeGenInfo(CodeGenTypes &CGT, bool HasVector, bool SoftFloatABI) 7394 : TargetCodeGenInfo( 7395 std::make_unique<SystemZABIInfo>(CGT, HasVector, SoftFloatABI)) {} 7396 7397 llvm::Value *testFPKind(llvm::Value *V, unsigned BuiltinID, 7398 CGBuilderTy &Builder, 7399 CodeGenModule &CGM) const override { 7400 assert(V->getType()->isFloatingPointTy() && "V should have an FP type."); 7401 // Only use TDC in constrained FP mode. 7402 if (!Builder.getIsFPConstrained()) 7403 return nullptr; 7404 7405 llvm::Type *Ty = V->getType(); 7406 if (Ty->isFloatTy() || Ty->isDoubleTy() || Ty->isFP128Ty()) { 7407 llvm::Module &M = CGM.getModule(); 7408 auto &Ctx = M.getContext(); 7409 llvm::Function *TDCFunc = 7410 llvm::Intrinsic::getDeclaration(&M, llvm::Intrinsic::s390_tdc, Ty); 7411 unsigned TDCBits = 0; 7412 switch (BuiltinID) { 7413 case Builtin::BI__builtin_isnan: 7414 TDCBits = 0xf; 7415 break; 7416 case Builtin::BIfinite: 7417 case Builtin::BI__finite: 7418 case Builtin::BIfinitef: 7419 case Builtin::BI__finitef: 7420 case Builtin::BIfinitel: 7421 case Builtin::BI__finitel: 7422 case Builtin::BI__builtin_isfinite: 7423 TDCBits = 0xfc0; 7424 break; 7425 case Builtin::BI__builtin_isinf: 7426 TDCBits = 0x30; 7427 break; 7428 default: 7429 break; 7430 } 7431 if (TDCBits) 7432 return Builder.CreateCall( 7433 TDCFunc, 7434 {V, llvm::ConstantInt::get(llvm::Type::getInt64Ty(Ctx), TDCBits)}); 7435 } 7436 return nullptr; 7437 } 7438 }; 7439 } 7440 7441 bool SystemZABIInfo::isPromotableIntegerTypeForABI(QualType Ty) const { 7442 // Treat an enum type as its underlying type. 7443 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 7444 Ty = EnumTy->getDecl()->getIntegerType(); 7445 7446 // Promotable integer types are required to be promoted by the ABI. 7447 if (ABIInfo::isPromotableIntegerTypeForABI(Ty)) 7448 return true; 7449 7450 if (const auto *EIT = Ty->getAs<BitIntType>()) 7451 if (EIT->getNumBits() < 64) 7452 return true; 7453 7454 // 32-bit values must also be promoted. 7455 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) 7456 switch (BT->getKind()) { 7457 case BuiltinType::Int: 7458 case BuiltinType::UInt: 7459 return true; 7460 default: 7461 return false; 7462 } 7463 return false; 7464 } 7465 7466 bool SystemZABIInfo::isCompoundType(QualType Ty) const { 7467 return (Ty->isAnyComplexType() || 7468 Ty->isVectorType() || 7469 isAggregateTypeForABI(Ty)); 7470 } 7471 7472 bool SystemZABIInfo::isVectorArgumentType(QualType Ty) const { 7473 return (HasVector && 7474 Ty->isVectorType() && 7475 getContext().getTypeSize(Ty) <= 128); 7476 } 7477 7478 bool SystemZABIInfo::isFPArgumentType(QualType Ty) const { 7479 if (IsSoftFloatABI) 7480 return false; 7481 7482 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) 7483 switch (BT->getKind()) { 7484 case BuiltinType::Float: 7485 case BuiltinType::Double: 7486 return true; 7487 default: 7488 return false; 7489 } 7490 7491 return false; 7492 } 7493 7494 QualType SystemZABIInfo::GetSingleElementType(QualType Ty) const { 7495 const RecordType *RT = Ty->getAs<RecordType>(); 7496 7497 if (RT && RT->isStructureOrClassType()) { 7498 const RecordDecl *RD = RT->getDecl(); 7499 QualType Found; 7500 7501 // If this is a C++ record, check the bases first. 7502 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 7503 for (const auto &I : CXXRD->bases()) { 7504 QualType Base = I.getType(); 7505 7506 // Empty bases don't affect things either way. 7507 if (isEmptyRecord(getContext(), Base, true)) 7508 continue; 7509 7510 if (!Found.isNull()) 7511 return Ty; 7512 Found = GetSingleElementType(Base); 7513 } 7514 7515 // Check the fields. 7516 for (const auto *FD : RD->fields()) { 7517 // Unlike isSingleElementStruct(), empty structure and array fields 7518 // do count. So do anonymous bitfields that aren't zero-sized. 7519 7520 // Like isSingleElementStruct(), ignore C++20 empty data members. 7521 if (FD->hasAttr<NoUniqueAddressAttr>() && 7522 isEmptyRecord(getContext(), FD->getType(), true)) 7523 continue; 7524 7525 // Unlike isSingleElementStruct(), arrays do not count. 7526 // Nested structures still do though. 7527 if (!Found.isNull()) 7528 return Ty; 7529 Found = GetSingleElementType(FD->getType()); 7530 } 7531 7532 // Unlike isSingleElementStruct(), trailing padding is allowed. 7533 // An 8-byte aligned struct s { float f; } is passed as a double. 7534 if (!Found.isNull()) 7535 return Found; 7536 } 7537 7538 return Ty; 7539 } 7540 7541 Address SystemZABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 7542 QualType Ty) const { 7543 // Assume that va_list type is correct; should be pointer to LLVM type: 7544 // struct { 7545 // i64 __gpr; 7546 // i64 __fpr; 7547 // i8 *__overflow_arg_area; 7548 // i8 *__reg_save_area; 7549 // }; 7550 7551 // Every non-vector argument occupies 8 bytes and is passed by preference 7552 // in either GPRs or FPRs. Vector arguments occupy 8 or 16 bytes and are 7553 // always passed on the stack. 7554 Ty = getContext().getCanonicalType(Ty); 7555 auto TyInfo = getContext().getTypeInfoInChars(Ty); 7556 llvm::Type *ArgTy = CGF.ConvertTypeForMem(Ty); 7557 llvm::Type *DirectTy = ArgTy; 7558 ABIArgInfo AI = classifyArgumentType(Ty); 7559 bool IsIndirect = AI.isIndirect(); 7560 bool InFPRs = false; 7561 bool IsVector = false; 7562 CharUnits UnpaddedSize; 7563 CharUnits DirectAlign; 7564 if (IsIndirect) { 7565 DirectTy = llvm::PointerType::getUnqual(DirectTy); 7566 UnpaddedSize = DirectAlign = CharUnits::fromQuantity(8); 7567 } else { 7568 if (AI.getCoerceToType()) 7569 ArgTy = AI.getCoerceToType(); 7570 InFPRs = (!IsSoftFloatABI && (ArgTy->isFloatTy() || ArgTy->isDoubleTy())); 7571 IsVector = ArgTy->isVectorTy(); 7572 UnpaddedSize = TyInfo.Width; 7573 DirectAlign = TyInfo.Align; 7574 } 7575 CharUnits PaddedSize = CharUnits::fromQuantity(8); 7576 if (IsVector && UnpaddedSize > PaddedSize) 7577 PaddedSize = CharUnits::fromQuantity(16); 7578 assert((UnpaddedSize <= PaddedSize) && "Invalid argument size."); 7579 7580 CharUnits Padding = (PaddedSize - UnpaddedSize); 7581 7582 llvm::Type *IndexTy = CGF.Int64Ty; 7583 llvm::Value *PaddedSizeV = 7584 llvm::ConstantInt::get(IndexTy, PaddedSize.getQuantity()); 7585 7586 if (IsVector) { 7587 // Work out the address of a vector argument on the stack. 7588 // Vector arguments are always passed in the high bits of a 7589 // single (8 byte) or double (16 byte) stack slot. 7590 Address OverflowArgAreaPtr = 7591 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr"); 7592 Address OverflowArgArea = 7593 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"), 7594 CGF.Int8Ty, TyInfo.Align); 7595 Address MemAddr = 7596 CGF.Builder.CreateElementBitCast(OverflowArgArea, DirectTy, "mem_addr"); 7597 7598 // Update overflow_arg_area_ptr pointer 7599 llvm::Value *NewOverflowArgArea = CGF.Builder.CreateGEP( 7600 OverflowArgArea.getElementType(), OverflowArgArea.getPointer(), 7601 PaddedSizeV, "overflow_arg_area"); 7602 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr); 7603 7604 return MemAddr; 7605 } 7606 7607 assert(PaddedSize.getQuantity() == 8); 7608 7609 unsigned MaxRegs, RegCountField, RegSaveIndex; 7610 CharUnits RegPadding; 7611 if (InFPRs) { 7612 MaxRegs = 4; // Maximum of 4 FPR arguments 7613 RegCountField = 1; // __fpr 7614 RegSaveIndex = 16; // save offset for f0 7615 RegPadding = CharUnits(); // floats are passed in the high bits of an FPR 7616 } else { 7617 MaxRegs = 5; // Maximum of 5 GPR arguments 7618 RegCountField = 0; // __gpr 7619 RegSaveIndex = 2; // save offset for r2 7620 RegPadding = Padding; // values are passed in the low bits of a GPR 7621 } 7622 7623 Address RegCountPtr = 7624 CGF.Builder.CreateStructGEP(VAListAddr, RegCountField, "reg_count_ptr"); 7625 llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count"); 7626 llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs); 7627 llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV, 7628 "fits_in_regs"); 7629 7630 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg"); 7631 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem"); 7632 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end"); 7633 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock); 7634 7635 // Emit code to load the value if it was passed in registers. 7636 CGF.EmitBlock(InRegBlock); 7637 7638 // Work out the address of an argument register. 7639 llvm::Value *ScaledRegCount = 7640 CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count"); 7641 llvm::Value *RegBase = 7642 llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize.getQuantity() 7643 + RegPadding.getQuantity()); 7644 llvm::Value *RegOffset = 7645 CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset"); 7646 Address RegSaveAreaPtr = 7647 CGF.Builder.CreateStructGEP(VAListAddr, 3, "reg_save_area_ptr"); 7648 llvm::Value *RegSaveArea = 7649 CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area"); 7650 Address RawRegAddr( 7651 CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, RegOffset, "raw_reg_addr"), 7652 CGF.Int8Ty, PaddedSize); 7653 Address RegAddr = 7654 CGF.Builder.CreateElementBitCast(RawRegAddr, DirectTy, "reg_addr"); 7655 7656 // Update the register count 7657 llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1); 7658 llvm::Value *NewRegCount = 7659 CGF.Builder.CreateAdd(RegCount, One, "reg_count"); 7660 CGF.Builder.CreateStore(NewRegCount, RegCountPtr); 7661 CGF.EmitBranch(ContBlock); 7662 7663 // Emit code to load the value if it was passed in memory. 7664 CGF.EmitBlock(InMemBlock); 7665 7666 // Work out the address of a stack argument. 7667 Address OverflowArgAreaPtr = 7668 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr"); 7669 Address OverflowArgArea = 7670 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"), 7671 CGF.Int8Ty, PaddedSize); 7672 Address RawMemAddr = 7673 CGF.Builder.CreateConstByteGEP(OverflowArgArea, Padding, "raw_mem_addr"); 7674 Address MemAddr = 7675 CGF.Builder.CreateElementBitCast(RawMemAddr, DirectTy, "mem_addr"); 7676 7677 // Update overflow_arg_area_ptr pointer 7678 llvm::Value *NewOverflowArgArea = 7679 CGF.Builder.CreateGEP(OverflowArgArea.getElementType(), 7680 OverflowArgArea.getPointer(), PaddedSizeV, 7681 "overflow_arg_area"); 7682 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr); 7683 CGF.EmitBranch(ContBlock); 7684 7685 // Return the appropriate result. 7686 CGF.EmitBlock(ContBlock); 7687 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, MemAddr, InMemBlock, 7688 "va_arg.addr"); 7689 7690 if (IsIndirect) 7691 ResAddr = Address(CGF.Builder.CreateLoad(ResAddr, "indirect_arg"), ArgTy, 7692 TyInfo.Align); 7693 7694 return ResAddr; 7695 } 7696 7697 ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const { 7698 if (RetTy->isVoidType()) 7699 return ABIArgInfo::getIgnore(); 7700 if (isVectorArgumentType(RetTy)) 7701 return ABIArgInfo::getDirect(); 7702 if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64) 7703 return getNaturalAlignIndirect(RetTy); 7704 return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy) 7705 : ABIArgInfo::getDirect()); 7706 } 7707 7708 ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const { 7709 // Handle the generic C++ ABI. 7710 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 7711 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 7712 7713 // Integers and enums are extended to full register width. 7714 if (isPromotableIntegerTypeForABI(Ty)) 7715 return ABIArgInfo::getExtend(Ty); 7716 7717 // Handle vector types and vector-like structure types. Note that 7718 // as opposed to float-like structure types, we do not allow any 7719 // padding for vector-like structures, so verify the sizes match. 7720 uint64_t Size = getContext().getTypeSize(Ty); 7721 QualType SingleElementTy = GetSingleElementType(Ty); 7722 if (isVectorArgumentType(SingleElementTy) && 7723 getContext().getTypeSize(SingleElementTy) == Size) 7724 return ABIArgInfo::getDirect(CGT.ConvertType(SingleElementTy)); 7725 7726 // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly. 7727 if (Size != 8 && Size != 16 && Size != 32 && Size != 64) 7728 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 7729 7730 // Handle small structures. 7731 if (const RecordType *RT = Ty->getAs<RecordType>()) { 7732 // Structures with flexible arrays have variable length, so really 7733 // fail the size test above. 7734 const RecordDecl *RD = RT->getDecl(); 7735 if (RD->hasFlexibleArrayMember()) 7736 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 7737 7738 // The structure is passed as an unextended integer, a float, or a double. 7739 llvm::Type *PassTy; 7740 if (isFPArgumentType(SingleElementTy)) { 7741 assert(Size == 32 || Size == 64); 7742 if (Size == 32) 7743 PassTy = llvm::Type::getFloatTy(getVMContext()); 7744 else 7745 PassTy = llvm::Type::getDoubleTy(getVMContext()); 7746 } else 7747 PassTy = llvm::IntegerType::get(getVMContext(), Size); 7748 return ABIArgInfo::getDirect(PassTy); 7749 } 7750 7751 // Non-structure compounds are passed indirectly. 7752 if (isCompoundType(Ty)) 7753 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 7754 7755 return ABIArgInfo::getDirect(nullptr); 7756 } 7757 7758 //===----------------------------------------------------------------------===// 7759 // MSP430 ABI Implementation 7760 //===----------------------------------------------------------------------===// 7761 7762 namespace { 7763 7764 class MSP430ABIInfo : public DefaultABIInfo { 7765 static ABIArgInfo complexArgInfo() { 7766 ABIArgInfo Info = ABIArgInfo::getDirect(); 7767 Info.setCanBeFlattened(false); 7768 return Info; 7769 } 7770 7771 public: 7772 MSP430ABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {} 7773 7774 ABIArgInfo classifyReturnType(QualType RetTy) const { 7775 if (RetTy->isAnyComplexType()) 7776 return complexArgInfo(); 7777 7778 return DefaultABIInfo::classifyReturnType(RetTy); 7779 } 7780 7781 ABIArgInfo classifyArgumentType(QualType RetTy) const { 7782 if (RetTy->isAnyComplexType()) 7783 return complexArgInfo(); 7784 7785 return DefaultABIInfo::classifyArgumentType(RetTy); 7786 } 7787 7788 // Just copy the original implementations because 7789 // DefaultABIInfo::classify{Return,Argument}Type() are not virtual 7790 void computeInfo(CGFunctionInfo &FI) const override { 7791 if (!getCXXABI().classifyReturnType(FI)) 7792 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 7793 for (auto &I : FI.arguments()) 7794 I.info = classifyArgumentType(I.type); 7795 } 7796 7797 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 7798 QualType Ty) const override { 7799 return EmitVAArgInstr(CGF, VAListAddr, Ty, classifyArgumentType(Ty)); 7800 } 7801 }; 7802 7803 class MSP430TargetCodeGenInfo : public TargetCodeGenInfo { 7804 public: 7805 MSP430TargetCodeGenInfo(CodeGenTypes &CGT) 7806 : TargetCodeGenInfo(std::make_unique<MSP430ABIInfo>(CGT)) {} 7807 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 7808 CodeGen::CodeGenModule &M) const override; 7809 }; 7810 7811 } 7812 7813 void MSP430TargetCodeGenInfo::setTargetAttributes( 7814 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const { 7815 if (GV->isDeclaration()) 7816 return; 7817 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) { 7818 const auto *InterruptAttr = FD->getAttr<MSP430InterruptAttr>(); 7819 if (!InterruptAttr) 7820 return; 7821 7822 // Handle 'interrupt' attribute: 7823 llvm::Function *F = cast<llvm::Function>(GV); 7824 7825 // Step 1: Set ISR calling convention. 7826 F->setCallingConv(llvm::CallingConv::MSP430_INTR); 7827 7828 // Step 2: Add attributes goodness. 7829 F->addFnAttr(llvm::Attribute::NoInline); 7830 F->addFnAttr("interrupt", llvm::utostr(InterruptAttr->getNumber())); 7831 } 7832 } 7833 7834 //===----------------------------------------------------------------------===// 7835 // MIPS ABI Implementation. This works for both little-endian and 7836 // big-endian variants. 7837 //===----------------------------------------------------------------------===// 7838 7839 namespace { 7840 class MipsABIInfo : public ABIInfo { 7841 bool IsO32; 7842 unsigned MinABIStackAlignInBytes, StackAlignInBytes; 7843 void CoerceToIntArgs(uint64_t TySize, 7844 SmallVectorImpl<llvm::Type *> &ArgList) const; 7845 llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const; 7846 llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const; 7847 llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const; 7848 public: 7849 MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) : 7850 ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8), 7851 StackAlignInBytes(IsO32 ? 8 : 16) {} 7852 7853 ABIArgInfo classifyReturnType(QualType RetTy) const; 7854 ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const; 7855 void computeInfo(CGFunctionInfo &FI) const override; 7856 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 7857 QualType Ty) const override; 7858 ABIArgInfo extendType(QualType Ty) const; 7859 }; 7860 7861 class MIPSTargetCodeGenInfo : public TargetCodeGenInfo { 7862 unsigned SizeOfUnwindException; 7863 public: 7864 MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32) 7865 : TargetCodeGenInfo(std::make_unique<MipsABIInfo>(CGT, IsO32)), 7866 SizeOfUnwindException(IsO32 ? 24 : 32) {} 7867 7868 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override { 7869 return 29; 7870 } 7871 7872 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 7873 CodeGen::CodeGenModule &CGM) const override { 7874 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D); 7875 if (!FD) return; 7876 llvm::Function *Fn = cast<llvm::Function>(GV); 7877 7878 if (FD->hasAttr<MipsLongCallAttr>()) 7879 Fn->addFnAttr("long-call"); 7880 else if (FD->hasAttr<MipsShortCallAttr>()) 7881 Fn->addFnAttr("short-call"); 7882 7883 // Other attributes do not have a meaning for declarations. 7884 if (GV->isDeclaration()) 7885 return; 7886 7887 if (FD->hasAttr<Mips16Attr>()) { 7888 Fn->addFnAttr("mips16"); 7889 } 7890 else if (FD->hasAttr<NoMips16Attr>()) { 7891 Fn->addFnAttr("nomips16"); 7892 } 7893 7894 if (FD->hasAttr<MicroMipsAttr>()) 7895 Fn->addFnAttr("micromips"); 7896 else if (FD->hasAttr<NoMicroMipsAttr>()) 7897 Fn->addFnAttr("nomicromips"); 7898 7899 const MipsInterruptAttr *Attr = FD->getAttr<MipsInterruptAttr>(); 7900 if (!Attr) 7901 return; 7902 7903 const char *Kind; 7904 switch (Attr->getInterrupt()) { 7905 case MipsInterruptAttr::eic: Kind = "eic"; break; 7906 case MipsInterruptAttr::sw0: Kind = "sw0"; break; 7907 case MipsInterruptAttr::sw1: Kind = "sw1"; break; 7908 case MipsInterruptAttr::hw0: Kind = "hw0"; break; 7909 case MipsInterruptAttr::hw1: Kind = "hw1"; break; 7910 case MipsInterruptAttr::hw2: Kind = "hw2"; break; 7911 case MipsInterruptAttr::hw3: Kind = "hw3"; break; 7912 case MipsInterruptAttr::hw4: Kind = "hw4"; break; 7913 case MipsInterruptAttr::hw5: Kind = "hw5"; break; 7914 } 7915 7916 Fn->addFnAttr("interrupt", Kind); 7917 7918 } 7919 7920 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 7921 llvm::Value *Address) const override; 7922 7923 unsigned getSizeOfUnwindException() const override { 7924 return SizeOfUnwindException; 7925 } 7926 }; 7927 } 7928 7929 void MipsABIInfo::CoerceToIntArgs( 7930 uint64_t TySize, SmallVectorImpl<llvm::Type *> &ArgList) const { 7931 llvm::IntegerType *IntTy = 7932 llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8); 7933 7934 // Add (TySize / MinABIStackAlignInBytes) args of IntTy. 7935 for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N) 7936 ArgList.push_back(IntTy); 7937 7938 // If necessary, add one more integer type to ArgList. 7939 unsigned R = TySize % (MinABIStackAlignInBytes * 8); 7940 7941 if (R) 7942 ArgList.push_back(llvm::IntegerType::get(getVMContext(), R)); 7943 } 7944 7945 // In N32/64, an aligned double precision floating point field is passed in 7946 // a register. 7947 llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const { 7948 SmallVector<llvm::Type*, 8> ArgList, IntArgList; 7949 7950 if (IsO32) { 7951 CoerceToIntArgs(TySize, ArgList); 7952 return llvm::StructType::get(getVMContext(), ArgList); 7953 } 7954 7955 if (Ty->isComplexType()) 7956 return CGT.ConvertType(Ty); 7957 7958 const RecordType *RT = Ty->getAs<RecordType>(); 7959 7960 // Unions/vectors are passed in integer registers. 7961 if (!RT || !RT->isStructureOrClassType()) { 7962 CoerceToIntArgs(TySize, ArgList); 7963 return llvm::StructType::get(getVMContext(), ArgList); 7964 } 7965 7966 const RecordDecl *RD = RT->getDecl(); 7967 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD); 7968 assert(!(TySize % 8) && "Size of structure must be multiple of 8."); 7969 7970 uint64_t LastOffset = 0; 7971 unsigned idx = 0; 7972 llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64); 7973 7974 // Iterate over fields in the struct/class and check if there are any aligned 7975 // double fields. 7976 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 7977 i != e; ++i, ++idx) { 7978 const QualType Ty = i->getType(); 7979 const BuiltinType *BT = Ty->getAs<BuiltinType>(); 7980 7981 if (!BT || BT->getKind() != BuiltinType::Double) 7982 continue; 7983 7984 uint64_t Offset = Layout.getFieldOffset(idx); 7985 if (Offset % 64) // Ignore doubles that are not aligned. 7986 continue; 7987 7988 // Add ((Offset - LastOffset) / 64) args of type i64. 7989 for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j) 7990 ArgList.push_back(I64); 7991 7992 // Add double type. 7993 ArgList.push_back(llvm::Type::getDoubleTy(getVMContext())); 7994 LastOffset = Offset + 64; 7995 } 7996 7997 CoerceToIntArgs(TySize - LastOffset, IntArgList); 7998 ArgList.append(IntArgList.begin(), IntArgList.end()); 7999 8000 return llvm::StructType::get(getVMContext(), ArgList); 8001 } 8002 8003 llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset, 8004 uint64_t Offset) const { 8005 if (OrigOffset + MinABIStackAlignInBytes > Offset) 8006 return nullptr; 8007 8008 return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8); 8009 } 8010 8011 ABIArgInfo 8012 MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const { 8013 Ty = useFirstFieldIfTransparentUnion(Ty); 8014 8015 uint64_t OrigOffset = Offset; 8016 uint64_t TySize = getContext().getTypeSize(Ty); 8017 uint64_t Align = getContext().getTypeAlign(Ty) / 8; 8018 8019 Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes), 8020 (uint64_t)StackAlignInBytes); 8021 unsigned CurrOffset = llvm::alignTo(Offset, Align); 8022 Offset = CurrOffset + llvm::alignTo(TySize, Align * 8) / 8; 8023 8024 if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) { 8025 // Ignore empty aggregates. 8026 if (TySize == 0) 8027 return ABIArgInfo::getIgnore(); 8028 8029 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) { 8030 Offset = OrigOffset + MinABIStackAlignInBytes; 8031 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 8032 } 8033 8034 // If we have reached here, aggregates are passed directly by coercing to 8035 // another structure type. Padding is inserted if the offset of the 8036 // aggregate is unaligned. 8037 ABIArgInfo ArgInfo = 8038 ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0, 8039 getPaddingType(OrigOffset, CurrOffset)); 8040 ArgInfo.setInReg(true); 8041 return ArgInfo; 8042 } 8043 8044 // Treat an enum type as its underlying type. 8045 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 8046 Ty = EnumTy->getDecl()->getIntegerType(); 8047 8048 // Make sure we pass indirectly things that are too large. 8049 if (const auto *EIT = Ty->getAs<BitIntType>()) 8050 if (EIT->getNumBits() > 128 || 8051 (EIT->getNumBits() > 64 && 8052 !getContext().getTargetInfo().hasInt128Type())) 8053 return getNaturalAlignIndirect(Ty); 8054 8055 // All integral types are promoted to the GPR width. 8056 if (Ty->isIntegralOrEnumerationType()) 8057 return extendType(Ty); 8058 8059 return ABIArgInfo::getDirect( 8060 nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset)); 8061 } 8062 8063 llvm::Type* 8064 MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const { 8065 const RecordType *RT = RetTy->getAs<RecordType>(); 8066 SmallVector<llvm::Type*, 8> RTList; 8067 8068 if (RT && RT->isStructureOrClassType()) { 8069 const RecordDecl *RD = RT->getDecl(); 8070 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD); 8071 unsigned FieldCnt = Layout.getFieldCount(); 8072 8073 // N32/64 returns struct/classes in floating point registers if the 8074 // following conditions are met: 8075 // 1. The size of the struct/class is no larger than 128-bit. 8076 // 2. The struct/class has one or two fields all of which are floating 8077 // point types. 8078 // 3. The offset of the first field is zero (this follows what gcc does). 8079 // 8080 // Any other composite results are returned in integer registers. 8081 // 8082 if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) { 8083 RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end(); 8084 for (; b != e; ++b) { 8085 const BuiltinType *BT = b->getType()->getAs<BuiltinType>(); 8086 8087 if (!BT || !BT->isFloatingPoint()) 8088 break; 8089 8090 RTList.push_back(CGT.ConvertType(b->getType())); 8091 } 8092 8093 if (b == e) 8094 return llvm::StructType::get(getVMContext(), RTList, 8095 RD->hasAttr<PackedAttr>()); 8096 8097 RTList.clear(); 8098 } 8099 } 8100 8101 CoerceToIntArgs(Size, RTList); 8102 return llvm::StructType::get(getVMContext(), RTList); 8103 } 8104 8105 ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const { 8106 uint64_t Size = getContext().getTypeSize(RetTy); 8107 8108 if (RetTy->isVoidType()) 8109 return ABIArgInfo::getIgnore(); 8110 8111 // O32 doesn't treat zero-sized structs differently from other structs. 8112 // However, N32/N64 ignores zero sized return values. 8113 if (!IsO32 && Size == 0) 8114 return ABIArgInfo::getIgnore(); 8115 8116 if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) { 8117 if (Size <= 128) { 8118 if (RetTy->isAnyComplexType()) 8119 return ABIArgInfo::getDirect(); 8120 8121 // O32 returns integer vectors in registers and N32/N64 returns all small 8122 // aggregates in registers. 8123 if (!IsO32 || 8124 (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) { 8125 ABIArgInfo ArgInfo = 8126 ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size)); 8127 ArgInfo.setInReg(true); 8128 return ArgInfo; 8129 } 8130 } 8131 8132 return getNaturalAlignIndirect(RetTy); 8133 } 8134 8135 // Treat an enum type as its underlying type. 8136 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 8137 RetTy = EnumTy->getDecl()->getIntegerType(); 8138 8139 // Make sure we pass indirectly things that are too large. 8140 if (const auto *EIT = RetTy->getAs<BitIntType>()) 8141 if (EIT->getNumBits() > 128 || 8142 (EIT->getNumBits() > 64 && 8143 !getContext().getTargetInfo().hasInt128Type())) 8144 return getNaturalAlignIndirect(RetTy); 8145 8146 if (isPromotableIntegerTypeForABI(RetTy)) 8147 return ABIArgInfo::getExtend(RetTy); 8148 8149 if ((RetTy->isUnsignedIntegerOrEnumerationType() || 8150 RetTy->isSignedIntegerOrEnumerationType()) && Size == 32 && !IsO32) 8151 return ABIArgInfo::getSignExtend(RetTy); 8152 8153 return ABIArgInfo::getDirect(); 8154 } 8155 8156 void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const { 8157 ABIArgInfo &RetInfo = FI.getReturnInfo(); 8158 if (!getCXXABI().classifyReturnType(FI)) 8159 RetInfo = classifyReturnType(FI.getReturnType()); 8160 8161 // Check if a pointer to an aggregate is passed as a hidden argument. 8162 uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0; 8163 8164 for (auto &I : FI.arguments()) 8165 I.info = classifyArgumentType(I.type, Offset); 8166 } 8167 8168 Address MipsABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 8169 QualType OrigTy) const { 8170 QualType Ty = OrigTy; 8171 8172 // Integer arguments are promoted to 32-bit on O32 and 64-bit on N32/N64. 8173 // Pointers are also promoted in the same way but this only matters for N32. 8174 unsigned SlotSizeInBits = IsO32 ? 32 : 64; 8175 unsigned PtrWidth = getTarget().getPointerWidth(0); 8176 bool DidPromote = false; 8177 if ((Ty->isIntegerType() && 8178 getContext().getIntWidth(Ty) < SlotSizeInBits) || 8179 (Ty->isPointerType() && PtrWidth < SlotSizeInBits)) { 8180 DidPromote = true; 8181 Ty = getContext().getIntTypeForBitwidth(SlotSizeInBits, 8182 Ty->isSignedIntegerType()); 8183 } 8184 8185 auto TyInfo = getContext().getTypeInfoInChars(Ty); 8186 8187 // The alignment of things in the argument area is never larger than 8188 // StackAlignInBytes. 8189 TyInfo.Align = 8190 std::min(TyInfo.Align, CharUnits::fromQuantity(StackAlignInBytes)); 8191 8192 // MinABIStackAlignInBytes is the size of argument slots on the stack. 8193 CharUnits ArgSlotSize = CharUnits::fromQuantity(MinABIStackAlignInBytes); 8194 8195 Address Addr = emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false, 8196 TyInfo, ArgSlotSize, /*AllowHigherAlign*/ true); 8197 8198 8199 // If there was a promotion, "unpromote" into a temporary. 8200 // TODO: can we just use a pointer into a subset of the original slot? 8201 if (DidPromote) { 8202 Address Temp = CGF.CreateMemTemp(OrigTy, "vaarg.promotion-temp"); 8203 llvm::Value *Promoted = CGF.Builder.CreateLoad(Addr); 8204 8205 // Truncate down to the right width. 8206 llvm::Type *IntTy = (OrigTy->isIntegerType() ? Temp.getElementType() 8207 : CGF.IntPtrTy); 8208 llvm::Value *V = CGF.Builder.CreateTrunc(Promoted, IntTy); 8209 if (OrigTy->isPointerType()) 8210 V = CGF.Builder.CreateIntToPtr(V, Temp.getElementType()); 8211 8212 CGF.Builder.CreateStore(V, Temp); 8213 Addr = Temp; 8214 } 8215 8216 return Addr; 8217 } 8218 8219 ABIArgInfo MipsABIInfo::extendType(QualType Ty) const { 8220 int TySize = getContext().getTypeSize(Ty); 8221 8222 // MIPS64 ABI requires unsigned 32 bit integers to be sign extended. 8223 if (Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32) 8224 return ABIArgInfo::getSignExtend(Ty); 8225 8226 return ABIArgInfo::getExtend(Ty); 8227 } 8228 8229 bool 8230 MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 8231 llvm::Value *Address) const { 8232 // This information comes from gcc's implementation, which seems to 8233 // as canonical as it gets. 8234 8235 // Everything on MIPS is 4 bytes. Double-precision FP registers 8236 // are aliased to pairs of single-precision FP registers. 8237 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4); 8238 8239 // 0-31 are the general purpose registers, $0 - $31. 8240 // 32-63 are the floating-point registers, $f0 - $f31. 8241 // 64 and 65 are the multiply/divide registers, $hi and $lo. 8242 // 66 is the (notional, I think) register for signal-handler return. 8243 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65); 8244 8245 // 67-74 are the floating-point status registers, $fcc0 - $fcc7. 8246 // They are one bit wide and ignored here. 8247 8248 // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31. 8249 // (coprocessor 1 is the FP unit) 8250 // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31. 8251 // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31. 8252 // 176-181 are the DSP accumulator registers. 8253 AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181); 8254 return false; 8255 } 8256 8257 //===----------------------------------------------------------------------===// 8258 // M68k ABI Implementation 8259 //===----------------------------------------------------------------------===// 8260 8261 namespace { 8262 8263 class M68kTargetCodeGenInfo : public TargetCodeGenInfo { 8264 public: 8265 M68kTargetCodeGenInfo(CodeGenTypes &CGT) 8266 : TargetCodeGenInfo(std::make_unique<DefaultABIInfo>(CGT)) {} 8267 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 8268 CodeGen::CodeGenModule &M) const override; 8269 }; 8270 8271 } // namespace 8272 8273 void M68kTargetCodeGenInfo::setTargetAttributes( 8274 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const { 8275 if (const auto *FD = dyn_cast_or_null<FunctionDecl>(D)) { 8276 if (const auto *attr = FD->getAttr<M68kInterruptAttr>()) { 8277 // Handle 'interrupt' attribute: 8278 llvm::Function *F = cast<llvm::Function>(GV); 8279 8280 // Step 1: Set ISR calling convention. 8281 F->setCallingConv(llvm::CallingConv::M68k_INTR); 8282 8283 // Step 2: Add attributes goodness. 8284 F->addFnAttr(llvm::Attribute::NoInline); 8285 8286 // Step 3: Emit ISR vector alias. 8287 unsigned Num = attr->getNumber() / 2; 8288 llvm::GlobalAlias::create(llvm::Function::ExternalLinkage, 8289 "__isr_" + Twine(Num), F); 8290 } 8291 } 8292 } 8293 8294 //===----------------------------------------------------------------------===// 8295 // AVR ABI Implementation. Documented at 8296 // https://gcc.gnu.org/wiki/avr-gcc#Calling_Convention 8297 // https://gcc.gnu.org/wiki/avr-gcc#Reduced_Tiny 8298 //===----------------------------------------------------------------------===// 8299 8300 namespace { 8301 class AVRABIInfo : public DefaultABIInfo { 8302 private: 8303 // The total amount of registers can be used to pass parameters. It is 18 on 8304 // AVR, or 6 on AVRTiny. 8305 const unsigned ParamRegs; 8306 // The total amount of registers can be used to pass return value. It is 8 on 8307 // AVR, or 4 on AVRTiny. 8308 const unsigned RetRegs; 8309 8310 public: 8311 AVRABIInfo(CodeGenTypes &CGT, unsigned NPR, unsigned NRR) 8312 : DefaultABIInfo(CGT), ParamRegs(NPR), RetRegs(NRR) {} 8313 8314 ABIArgInfo classifyReturnType(QualType Ty, bool &LargeRet) const { 8315 if (isAggregateTypeForABI(Ty)) { 8316 // On AVR, a return struct with size less than or equals to 8 bytes is 8317 // returned directly via registers R18-R25. On AVRTiny, a return struct 8318 // with size less than or equals to 4 bytes is returned directly via 8319 // registers R22-R25. 8320 if (getContext().getTypeSize(Ty) <= RetRegs * 8) 8321 return ABIArgInfo::getDirect(); 8322 // A return struct with larger size is returned via a stack 8323 // slot, along with a pointer to it as the function's implicit argument. 8324 LargeRet = true; 8325 return getNaturalAlignIndirect(Ty); 8326 } 8327 // Otherwise we follow the default way which is compatible. 8328 return DefaultABIInfo::classifyReturnType(Ty); 8329 } 8330 8331 ABIArgInfo classifyArgumentType(QualType Ty, unsigned &NumRegs) const { 8332 unsigned TySize = getContext().getTypeSize(Ty); 8333 8334 // An int8 type argument always costs two registers like an int16. 8335 if (TySize == 8 && NumRegs >= 2) { 8336 NumRegs -= 2; 8337 return ABIArgInfo::getExtend(Ty); 8338 } 8339 8340 // If the argument size is an odd number of bytes, round up the size 8341 // to the next even number. 8342 TySize = llvm::alignTo(TySize, 16); 8343 8344 // Any type including an array/struct type can be passed in rgisters, 8345 // if there are enough registers left. 8346 if (TySize <= NumRegs * 8) { 8347 NumRegs -= TySize / 8; 8348 return ABIArgInfo::getDirect(); 8349 } 8350 8351 // An argument is passed either completely in registers or completely in 8352 // memory. Since there are not enough registers left, current argument 8353 // and all other unprocessed arguments should be passed in memory. 8354 // However we still need to return `ABIArgInfo::getDirect()` other than 8355 // `ABIInfo::getNaturalAlignIndirect(Ty)`, otherwise an extra stack slot 8356 // will be allocated, so the stack frame layout will be incompatible with 8357 // avr-gcc. 8358 NumRegs = 0; 8359 return ABIArgInfo::getDirect(); 8360 } 8361 8362 void computeInfo(CGFunctionInfo &FI) const override { 8363 // Decide the return type. 8364 bool LargeRet = false; 8365 if (!getCXXABI().classifyReturnType(FI)) 8366 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), LargeRet); 8367 8368 // Decide each argument type. The total number of registers can be used for 8369 // arguments depends on several factors: 8370 // 1. Arguments of varargs functions are passed on the stack. This applies 8371 // even to the named arguments. So no register can be used. 8372 // 2. Total 18 registers can be used on avr and 6 ones on avrtiny. 8373 // 3. If the return type is a struct with too large size, two registers 8374 // (out of 18/6) will be cost as an implicit pointer argument. 8375 unsigned NumRegs = ParamRegs; 8376 if (FI.isVariadic()) 8377 NumRegs = 0; 8378 else if (LargeRet) 8379 NumRegs -= 2; 8380 for (auto &I : FI.arguments()) 8381 I.info = classifyArgumentType(I.type, NumRegs); 8382 } 8383 }; 8384 8385 class AVRTargetCodeGenInfo : public TargetCodeGenInfo { 8386 public: 8387 AVRTargetCodeGenInfo(CodeGenTypes &CGT, unsigned NPR, unsigned NRR) 8388 : TargetCodeGenInfo(std::make_unique<AVRABIInfo>(CGT, NPR, NRR)) {} 8389 8390 LangAS getGlobalVarAddressSpace(CodeGenModule &CGM, 8391 const VarDecl *D) const override { 8392 // Check if global/static variable is defined in address space 8393 // 1~6 (__flash, __flash1, __flash2, __flash3, __flash4, __flash5) 8394 // but not constant. 8395 if (D) { 8396 LangAS AS = D->getType().getAddressSpace(); 8397 if (isTargetAddressSpace(AS) && 1 <= toTargetAddressSpace(AS) && 8398 toTargetAddressSpace(AS) <= 6 && !D->getType().isConstQualified()) 8399 CGM.getDiags().Report(D->getLocation(), 8400 diag::err_verify_nonconst_addrspace) 8401 << "__flash*"; 8402 } 8403 return TargetCodeGenInfo::getGlobalVarAddressSpace(CGM, D); 8404 } 8405 8406 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 8407 CodeGen::CodeGenModule &CGM) const override { 8408 if (GV->isDeclaration()) 8409 return; 8410 const auto *FD = dyn_cast_or_null<FunctionDecl>(D); 8411 if (!FD) return; 8412 auto *Fn = cast<llvm::Function>(GV); 8413 8414 if (FD->getAttr<AVRInterruptAttr>()) 8415 Fn->addFnAttr("interrupt"); 8416 8417 if (FD->getAttr<AVRSignalAttr>()) 8418 Fn->addFnAttr("signal"); 8419 } 8420 }; 8421 } 8422 8423 //===----------------------------------------------------------------------===// 8424 // TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults. 8425 // Currently subclassed only to implement custom OpenCL C function attribute 8426 // handling. 8427 //===----------------------------------------------------------------------===// 8428 8429 namespace { 8430 8431 class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo { 8432 public: 8433 TCETargetCodeGenInfo(CodeGenTypes &CGT) 8434 : DefaultTargetCodeGenInfo(CGT) {} 8435 8436 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 8437 CodeGen::CodeGenModule &M) const override; 8438 }; 8439 8440 void TCETargetCodeGenInfo::setTargetAttributes( 8441 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const { 8442 if (GV->isDeclaration()) 8443 return; 8444 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D); 8445 if (!FD) return; 8446 8447 llvm::Function *F = cast<llvm::Function>(GV); 8448 8449 if (M.getLangOpts().OpenCL) { 8450 if (FD->hasAttr<OpenCLKernelAttr>()) { 8451 // OpenCL C Kernel functions are not subject to inlining 8452 F->addFnAttr(llvm::Attribute::NoInline); 8453 const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>(); 8454 if (Attr) { 8455 // Convert the reqd_work_group_size() attributes to metadata. 8456 llvm::LLVMContext &Context = F->getContext(); 8457 llvm::NamedMDNode *OpenCLMetadata = 8458 M.getModule().getOrInsertNamedMetadata( 8459 "opencl.kernel_wg_size_info"); 8460 8461 SmallVector<llvm::Metadata *, 5> Operands; 8462 Operands.push_back(llvm::ConstantAsMetadata::get(F)); 8463 8464 Operands.push_back( 8465 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue( 8466 M.Int32Ty, llvm::APInt(32, Attr->getXDim())))); 8467 Operands.push_back( 8468 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue( 8469 M.Int32Ty, llvm::APInt(32, Attr->getYDim())))); 8470 Operands.push_back( 8471 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue( 8472 M.Int32Ty, llvm::APInt(32, Attr->getZDim())))); 8473 8474 // Add a boolean constant operand for "required" (true) or "hint" 8475 // (false) for implementing the work_group_size_hint attr later. 8476 // Currently always true as the hint is not yet implemented. 8477 Operands.push_back( 8478 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getTrue(Context))); 8479 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands)); 8480 } 8481 } 8482 } 8483 } 8484 8485 } 8486 8487 //===----------------------------------------------------------------------===// 8488 // Hexagon ABI Implementation 8489 //===----------------------------------------------------------------------===// 8490 8491 namespace { 8492 8493 class HexagonABIInfo : public DefaultABIInfo { 8494 public: 8495 HexagonABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {} 8496 8497 private: 8498 ABIArgInfo classifyReturnType(QualType RetTy) const; 8499 ABIArgInfo classifyArgumentType(QualType RetTy) const; 8500 ABIArgInfo classifyArgumentType(QualType RetTy, unsigned *RegsLeft) const; 8501 8502 void computeInfo(CGFunctionInfo &FI) const override; 8503 8504 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 8505 QualType Ty) const override; 8506 Address EmitVAArgFromMemory(CodeGenFunction &CFG, Address VAListAddr, 8507 QualType Ty) const; 8508 Address EmitVAArgForHexagon(CodeGenFunction &CFG, Address VAListAddr, 8509 QualType Ty) const; 8510 Address EmitVAArgForHexagonLinux(CodeGenFunction &CFG, Address VAListAddr, 8511 QualType Ty) const; 8512 }; 8513 8514 class HexagonTargetCodeGenInfo : public TargetCodeGenInfo { 8515 public: 8516 HexagonTargetCodeGenInfo(CodeGenTypes &CGT) 8517 : TargetCodeGenInfo(std::make_unique<HexagonABIInfo>(CGT)) {} 8518 8519 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 8520 return 29; 8521 } 8522 8523 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 8524 CodeGen::CodeGenModule &GCM) const override { 8525 if (GV->isDeclaration()) 8526 return; 8527 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D); 8528 if (!FD) 8529 return; 8530 } 8531 }; 8532 8533 } // namespace 8534 8535 void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const { 8536 unsigned RegsLeft = 6; 8537 if (!getCXXABI().classifyReturnType(FI)) 8538 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 8539 for (auto &I : FI.arguments()) 8540 I.info = classifyArgumentType(I.type, &RegsLeft); 8541 } 8542 8543 static bool HexagonAdjustRegsLeft(uint64_t Size, unsigned *RegsLeft) { 8544 assert(Size <= 64 && "Not expecting to pass arguments larger than 64 bits" 8545 " through registers"); 8546 8547 if (*RegsLeft == 0) 8548 return false; 8549 8550 if (Size <= 32) { 8551 (*RegsLeft)--; 8552 return true; 8553 } 8554 8555 if (2 <= (*RegsLeft & (~1U))) { 8556 *RegsLeft = (*RegsLeft & (~1U)) - 2; 8557 return true; 8558 } 8559 8560 // Next available register was r5 but candidate was greater than 32-bits so it 8561 // has to go on the stack. However we still consume r5 8562 if (*RegsLeft == 1) 8563 *RegsLeft = 0; 8564 8565 return false; 8566 } 8567 8568 ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty, 8569 unsigned *RegsLeft) const { 8570 if (!isAggregateTypeForABI(Ty)) { 8571 // Treat an enum type as its underlying type. 8572 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 8573 Ty = EnumTy->getDecl()->getIntegerType(); 8574 8575 uint64_t Size = getContext().getTypeSize(Ty); 8576 if (Size <= 64) 8577 HexagonAdjustRegsLeft(Size, RegsLeft); 8578 8579 if (Size > 64 && Ty->isBitIntType()) 8580 return getNaturalAlignIndirect(Ty, /*ByVal=*/true); 8581 8582 return isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty) 8583 : ABIArgInfo::getDirect(); 8584 } 8585 8586 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 8587 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 8588 8589 // Ignore empty records. 8590 if (isEmptyRecord(getContext(), Ty, true)) 8591 return ABIArgInfo::getIgnore(); 8592 8593 uint64_t Size = getContext().getTypeSize(Ty); 8594 unsigned Align = getContext().getTypeAlign(Ty); 8595 8596 if (Size > 64) 8597 return getNaturalAlignIndirect(Ty, /*ByVal=*/true); 8598 8599 if (HexagonAdjustRegsLeft(Size, RegsLeft)) 8600 Align = Size <= 32 ? 32 : 64; 8601 if (Size <= Align) { 8602 // Pass in the smallest viable integer type. 8603 if (!llvm::isPowerOf2_64(Size)) 8604 Size = llvm::NextPowerOf2(Size); 8605 return ABIArgInfo::getDirect(llvm::Type::getIntNTy(getVMContext(), Size)); 8606 } 8607 return DefaultABIInfo::classifyArgumentType(Ty); 8608 } 8609 8610 ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const { 8611 if (RetTy->isVoidType()) 8612 return ABIArgInfo::getIgnore(); 8613 8614 const TargetInfo &T = CGT.getTarget(); 8615 uint64_t Size = getContext().getTypeSize(RetTy); 8616 8617 if (RetTy->getAs<VectorType>()) { 8618 // HVX vectors are returned in vector registers or register pairs. 8619 if (T.hasFeature("hvx")) { 8620 assert(T.hasFeature("hvx-length64b") || T.hasFeature("hvx-length128b")); 8621 uint64_t VecSize = T.hasFeature("hvx-length64b") ? 64*8 : 128*8; 8622 if (Size == VecSize || Size == 2*VecSize) 8623 return ABIArgInfo::getDirectInReg(); 8624 } 8625 // Large vector types should be returned via memory. 8626 if (Size > 64) 8627 return getNaturalAlignIndirect(RetTy); 8628 } 8629 8630 if (!isAggregateTypeForABI(RetTy)) { 8631 // Treat an enum type as its underlying type. 8632 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 8633 RetTy = EnumTy->getDecl()->getIntegerType(); 8634 8635 if (Size > 64 && RetTy->isBitIntType()) 8636 return getNaturalAlignIndirect(RetTy, /*ByVal=*/false); 8637 8638 return isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy) 8639 : ABIArgInfo::getDirect(); 8640 } 8641 8642 if (isEmptyRecord(getContext(), RetTy, true)) 8643 return ABIArgInfo::getIgnore(); 8644 8645 // Aggregates <= 8 bytes are returned in registers, other aggregates 8646 // are returned indirectly. 8647 if (Size <= 64) { 8648 // Return in the smallest viable integer type. 8649 if (!llvm::isPowerOf2_64(Size)) 8650 Size = llvm::NextPowerOf2(Size); 8651 return ABIArgInfo::getDirect(llvm::Type::getIntNTy(getVMContext(), Size)); 8652 } 8653 return getNaturalAlignIndirect(RetTy, /*ByVal=*/true); 8654 } 8655 8656 Address HexagonABIInfo::EmitVAArgFromMemory(CodeGenFunction &CGF, 8657 Address VAListAddr, 8658 QualType Ty) const { 8659 // Load the overflow area pointer. 8660 Address __overflow_area_pointer_p = 8661 CGF.Builder.CreateStructGEP(VAListAddr, 2, "__overflow_area_pointer_p"); 8662 llvm::Value *__overflow_area_pointer = CGF.Builder.CreateLoad( 8663 __overflow_area_pointer_p, "__overflow_area_pointer"); 8664 8665 uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8; 8666 if (Align > 4) { 8667 // Alignment should be a power of 2. 8668 assert((Align & (Align - 1)) == 0 && "Alignment is not power of 2!"); 8669 8670 // overflow_arg_area = (overflow_arg_area + align - 1) & -align; 8671 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int64Ty, Align - 1); 8672 8673 // Add offset to the current pointer to access the argument. 8674 __overflow_area_pointer = 8675 CGF.Builder.CreateGEP(CGF.Int8Ty, __overflow_area_pointer, Offset); 8676 llvm::Value *AsInt = 8677 CGF.Builder.CreatePtrToInt(__overflow_area_pointer, CGF.Int32Ty); 8678 8679 // Create a mask which should be "AND"ed 8680 // with (overflow_arg_area + align - 1) 8681 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int32Ty, -(int)Align); 8682 __overflow_area_pointer = CGF.Builder.CreateIntToPtr( 8683 CGF.Builder.CreateAnd(AsInt, Mask), __overflow_area_pointer->getType(), 8684 "__overflow_area_pointer.align"); 8685 } 8686 8687 // Get the type of the argument from memory and bitcast 8688 // overflow area pointer to the argument type. 8689 llvm::Type *PTy = CGF.ConvertTypeForMem(Ty); 8690 Address AddrTyped = CGF.Builder.CreateElementBitCast( 8691 Address(__overflow_area_pointer, CGF.Int8Ty, 8692 CharUnits::fromQuantity(Align)), 8693 PTy); 8694 8695 // Round up to the minimum stack alignment for varargs which is 4 bytes. 8696 uint64_t Offset = llvm::alignTo(CGF.getContext().getTypeSize(Ty) / 8, 4); 8697 8698 __overflow_area_pointer = CGF.Builder.CreateGEP( 8699 CGF.Int8Ty, __overflow_area_pointer, 8700 llvm::ConstantInt::get(CGF.Int32Ty, Offset), 8701 "__overflow_area_pointer.next"); 8702 CGF.Builder.CreateStore(__overflow_area_pointer, __overflow_area_pointer_p); 8703 8704 return AddrTyped; 8705 } 8706 8707 Address HexagonABIInfo::EmitVAArgForHexagon(CodeGenFunction &CGF, 8708 Address VAListAddr, 8709 QualType Ty) const { 8710 // FIXME: Need to handle alignment 8711 llvm::Type *BP = CGF.Int8PtrTy; 8712 CGBuilderTy &Builder = CGF.Builder; 8713 Address VAListAddrAsBPP = Builder.CreateElementBitCast(VAListAddr, BP, "ap"); 8714 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur"); 8715 // Handle address alignment for type alignment > 32 bits 8716 uint64_t TyAlign = CGF.getContext().getTypeAlign(Ty) / 8; 8717 if (TyAlign > 4) { 8718 assert((TyAlign & (TyAlign - 1)) == 0 && "Alignment is not power of 2!"); 8719 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int32Ty); 8720 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt32(TyAlign - 1)); 8721 AddrAsInt = Builder.CreateAnd(AddrAsInt, Builder.getInt32(~(TyAlign - 1))); 8722 Addr = Builder.CreateIntToPtr(AddrAsInt, BP); 8723 } 8724 Address AddrTyped = Builder.CreateElementBitCast( 8725 Address(Addr, CGF.Int8Ty, CharUnits::fromQuantity(TyAlign)), 8726 CGF.ConvertType(Ty)); 8727 8728 uint64_t Offset = llvm::alignTo(CGF.getContext().getTypeSize(Ty) / 8, 4); 8729 llvm::Value *NextAddr = Builder.CreateGEP( 8730 CGF.Int8Ty, Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset), "ap.next"); 8731 Builder.CreateStore(NextAddr, VAListAddrAsBPP); 8732 8733 return AddrTyped; 8734 } 8735 8736 Address HexagonABIInfo::EmitVAArgForHexagonLinux(CodeGenFunction &CGF, 8737 Address VAListAddr, 8738 QualType Ty) const { 8739 int ArgSize = CGF.getContext().getTypeSize(Ty) / 8; 8740 8741 if (ArgSize > 8) 8742 return EmitVAArgFromMemory(CGF, VAListAddr, Ty); 8743 8744 // Here we have check if the argument is in register area or 8745 // in overflow area. 8746 // If the saved register area pointer + argsize rounded up to alignment > 8747 // saved register area end pointer, argument is in overflow area. 8748 unsigned RegsLeft = 6; 8749 Ty = CGF.getContext().getCanonicalType(Ty); 8750 (void)classifyArgumentType(Ty, &RegsLeft); 8751 8752 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg"); 8753 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg"); 8754 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack"); 8755 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end"); 8756 8757 // Get rounded size of the argument.GCC does not allow vararg of 8758 // size < 4 bytes. We follow the same logic here. 8759 ArgSize = (CGF.getContext().getTypeSize(Ty) <= 32) ? 4 : 8; 8760 int ArgAlign = (CGF.getContext().getTypeSize(Ty) <= 32) ? 4 : 8; 8761 8762 // Argument may be in saved register area 8763 CGF.EmitBlock(MaybeRegBlock); 8764 8765 // Load the current saved register area pointer. 8766 Address __current_saved_reg_area_pointer_p = CGF.Builder.CreateStructGEP( 8767 VAListAddr, 0, "__current_saved_reg_area_pointer_p"); 8768 llvm::Value *__current_saved_reg_area_pointer = CGF.Builder.CreateLoad( 8769 __current_saved_reg_area_pointer_p, "__current_saved_reg_area_pointer"); 8770 8771 // Load the saved register area end pointer. 8772 Address __saved_reg_area_end_pointer_p = CGF.Builder.CreateStructGEP( 8773 VAListAddr, 1, "__saved_reg_area_end_pointer_p"); 8774 llvm::Value *__saved_reg_area_end_pointer = CGF.Builder.CreateLoad( 8775 __saved_reg_area_end_pointer_p, "__saved_reg_area_end_pointer"); 8776 8777 // If the size of argument is > 4 bytes, check if the stack 8778 // location is aligned to 8 bytes 8779 if (ArgAlign > 4) { 8780 8781 llvm::Value *__current_saved_reg_area_pointer_int = 8782 CGF.Builder.CreatePtrToInt(__current_saved_reg_area_pointer, 8783 CGF.Int32Ty); 8784 8785 __current_saved_reg_area_pointer_int = CGF.Builder.CreateAdd( 8786 __current_saved_reg_area_pointer_int, 8787 llvm::ConstantInt::get(CGF.Int32Ty, (ArgAlign - 1)), 8788 "align_current_saved_reg_area_pointer"); 8789 8790 __current_saved_reg_area_pointer_int = 8791 CGF.Builder.CreateAnd(__current_saved_reg_area_pointer_int, 8792 llvm::ConstantInt::get(CGF.Int32Ty, -ArgAlign), 8793 "align_current_saved_reg_area_pointer"); 8794 8795 __current_saved_reg_area_pointer = 8796 CGF.Builder.CreateIntToPtr(__current_saved_reg_area_pointer_int, 8797 __current_saved_reg_area_pointer->getType(), 8798 "align_current_saved_reg_area_pointer"); 8799 } 8800 8801 llvm::Value *__new_saved_reg_area_pointer = 8802 CGF.Builder.CreateGEP(CGF.Int8Ty, __current_saved_reg_area_pointer, 8803 llvm::ConstantInt::get(CGF.Int32Ty, ArgSize), 8804 "__new_saved_reg_area_pointer"); 8805 8806 llvm::Value *UsingStack = nullptr; 8807 UsingStack = CGF.Builder.CreateICmpSGT(__new_saved_reg_area_pointer, 8808 __saved_reg_area_end_pointer); 8809 8810 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, InRegBlock); 8811 8812 // Argument in saved register area 8813 // Implement the block where argument is in register saved area 8814 CGF.EmitBlock(InRegBlock); 8815 8816 llvm::Type *PTy = CGF.ConvertType(Ty); 8817 llvm::Value *__saved_reg_area_p = CGF.Builder.CreateBitCast( 8818 __current_saved_reg_area_pointer, llvm::PointerType::getUnqual(PTy)); 8819 8820 CGF.Builder.CreateStore(__new_saved_reg_area_pointer, 8821 __current_saved_reg_area_pointer_p); 8822 8823 CGF.EmitBranch(ContBlock); 8824 8825 // Argument in overflow area 8826 // Implement the block where the argument is in overflow area. 8827 CGF.EmitBlock(OnStackBlock); 8828 8829 // Load the overflow area pointer 8830 Address __overflow_area_pointer_p = 8831 CGF.Builder.CreateStructGEP(VAListAddr, 2, "__overflow_area_pointer_p"); 8832 llvm::Value *__overflow_area_pointer = CGF.Builder.CreateLoad( 8833 __overflow_area_pointer_p, "__overflow_area_pointer"); 8834 8835 // Align the overflow area pointer according to the alignment of the argument 8836 if (ArgAlign > 4) { 8837 llvm::Value *__overflow_area_pointer_int = 8838 CGF.Builder.CreatePtrToInt(__overflow_area_pointer, CGF.Int32Ty); 8839 8840 __overflow_area_pointer_int = 8841 CGF.Builder.CreateAdd(__overflow_area_pointer_int, 8842 llvm::ConstantInt::get(CGF.Int32Ty, ArgAlign - 1), 8843 "align_overflow_area_pointer"); 8844 8845 __overflow_area_pointer_int = 8846 CGF.Builder.CreateAnd(__overflow_area_pointer_int, 8847 llvm::ConstantInt::get(CGF.Int32Ty, -ArgAlign), 8848 "align_overflow_area_pointer"); 8849 8850 __overflow_area_pointer = CGF.Builder.CreateIntToPtr( 8851 __overflow_area_pointer_int, __overflow_area_pointer->getType(), 8852 "align_overflow_area_pointer"); 8853 } 8854 8855 // Get the pointer for next argument in overflow area and store it 8856 // to overflow area pointer. 8857 llvm::Value *__new_overflow_area_pointer = CGF.Builder.CreateGEP( 8858 CGF.Int8Ty, __overflow_area_pointer, 8859 llvm::ConstantInt::get(CGF.Int32Ty, ArgSize), 8860 "__overflow_area_pointer.next"); 8861 8862 CGF.Builder.CreateStore(__new_overflow_area_pointer, 8863 __overflow_area_pointer_p); 8864 8865 CGF.Builder.CreateStore(__new_overflow_area_pointer, 8866 __current_saved_reg_area_pointer_p); 8867 8868 // Bitcast the overflow area pointer to the type of argument. 8869 llvm::Type *OverflowPTy = CGF.ConvertTypeForMem(Ty); 8870 llvm::Value *__overflow_area_p = CGF.Builder.CreateBitCast( 8871 __overflow_area_pointer, llvm::PointerType::getUnqual(OverflowPTy)); 8872 8873 CGF.EmitBranch(ContBlock); 8874 8875 // Get the correct pointer to load the variable argument 8876 // Implement the ContBlock 8877 CGF.EmitBlock(ContBlock); 8878 8879 llvm::Type *MemTy = CGF.ConvertTypeForMem(Ty); 8880 llvm::Type *MemPTy = llvm::PointerType::getUnqual(MemTy); 8881 llvm::PHINode *ArgAddr = CGF.Builder.CreatePHI(MemPTy, 2, "vaarg.addr"); 8882 ArgAddr->addIncoming(__saved_reg_area_p, InRegBlock); 8883 ArgAddr->addIncoming(__overflow_area_p, OnStackBlock); 8884 8885 return Address(ArgAddr, MemTy, CharUnits::fromQuantity(ArgAlign)); 8886 } 8887 8888 Address HexagonABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 8889 QualType Ty) const { 8890 8891 if (getTarget().getTriple().isMusl()) 8892 return EmitVAArgForHexagonLinux(CGF, VAListAddr, Ty); 8893 8894 return EmitVAArgForHexagon(CGF, VAListAddr, Ty); 8895 } 8896 8897 //===----------------------------------------------------------------------===// 8898 // Lanai ABI Implementation 8899 //===----------------------------------------------------------------------===// 8900 8901 namespace { 8902 class LanaiABIInfo : public DefaultABIInfo { 8903 public: 8904 LanaiABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {} 8905 8906 bool shouldUseInReg(QualType Ty, CCState &State) const; 8907 8908 void computeInfo(CGFunctionInfo &FI) const override { 8909 CCState State(FI); 8910 // Lanai uses 4 registers to pass arguments unless the function has the 8911 // regparm attribute set. 8912 if (FI.getHasRegParm()) { 8913 State.FreeRegs = FI.getRegParm(); 8914 } else { 8915 State.FreeRegs = 4; 8916 } 8917 8918 if (!getCXXABI().classifyReturnType(FI)) 8919 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 8920 for (auto &I : FI.arguments()) 8921 I.info = classifyArgumentType(I.type, State); 8922 } 8923 8924 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const; 8925 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const; 8926 }; 8927 } // end anonymous namespace 8928 8929 bool LanaiABIInfo::shouldUseInReg(QualType Ty, CCState &State) const { 8930 unsigned Size = getContext().getTypeSize(Ty); 8931 unsigned SizeInRegs = llvm::alignTo(Size, 32U) / 32U; 8932 8933 if (SizeInRegs == 0) 8934 return false; 8935 8936 if (SizeInRegs > State.FreeRegs) { 8937 State.FreeRegs = 0; 8938 return false; 8939 } 8940 8941 State.FreeRegs -= SizeInRegs; 8942 8943 return true; 8944 } 8945 8946 ABIArgInfo LanaiABIInfo::getIndirectResult(QualType Ty, bool ByVal, 8947 CCState &State) const { 8948 if (!ByVal) { 8949 if (State.FreeRegs) { 8950 --State.FreeRegs; // Non-byval indirects just use one pointer. 8951 return getNaturalAlignIndirectInReg(Ty); 8952 } 8953 return getNaturalAlignIndirect(Ty, false); 8954 } 8955 8956 // Compute the byval alignment. 8957 const unsigned MinABIStackAlignInBytes = 4; 8958 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8; 8959 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true, 8960 /*Realign=*/TypeAlign > 8961 MinABIStackAlignInBytes); 8962 } 8963 8964 ABIArgInfo LanaiABIInfo::classifyArgumentType(QualType Ty, 8965 CCState &State) const { 8966 // Check with the C++ ABI first. 8967 const RecordType *RT = Ty->getAs<RecordType>(); 8968 if (RT) { 8969 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()); 8970 if (RAA == CGCXXABI::RAA_Indirect) { 8971 return getIndirectResult(Ty, /*ByVal=*/false, State); 8972 } else if (RAA == CGCXXABI::RAA_DirectInMemory) { 8973 return getNaturalAlignIndirect(Ty, /*ByVal=*/true); 8974 } 8975 } 8976 8977 if (isAggregateTypeForABI(Ty)) { 8978 // Structures with flexible arrays are always indirect. 8979 if (RT && RT->getDecl()->hasFlexibleArrayMember()) 8980 return getIndirectResult(Ty, /*ByVal=*/true, State); 8981 8982 // Ignore empty structs/unions. 8983 if (isEmptyRecord(getContext(), Ty, true)) 8984 return ABIArgInfo::getIgnore(); 8985 8986 llvm::LLVMContext &LLVMContext = getVMContext(); 8987 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32; 8988 if (SizeInRegs <= State.FreeRegs) { 8989 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext); 8990 SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32); 8991 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements); 8992 State.FreeRegs -= SizeInRegs; 8993 return ABIArgInfo::getDirectInReg(Result); 8994 } else { 8995 State.FreeRegs = 0; 8996 } 8997 return getIndirectResult(Ty, true, State); 8998 } 8999 9000 // Treat an enum type as its underlying type. 9001 if (const auto *EnumTy = Ty->getAs<EnumType>()) 9002 Ty = EnumTy->getDecl()->getIntegerType(); 9003 9004 bool InReg = shouldUseInReg(Ty, State); 9005 9006 // Don't pass >64 bit integers in registers. 9007 if (const auto *EIT = Ty->getAs<BitIntType>()) 9008 if (EIT->getNumBits() > 64) 9009 return getIndirectResult(Ty, /*ByVal=*/true, State); 9010 9011 if (isPromotableIntegerTypeForABI(Ty)) { 9012 if (InReg) 9013 return ABIArgInfo::getDirectInReg(); 9014 return ABIArgInfo::getExtend(Ty); 9015 } 9016 if (InReg) 9017 return ABIArgInfo::getDirectInReg(); 9018 return ABIArgInfo::getDirect(); 9019 } 9020 9021 namespace { 9022 class LanaiTargetCodeGenInfo : public TargetCodeGenInfo { 9023 public: 9024 LanaiTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT) 9025 : TargetCodeGenInfo(std::make_unique<LanaiABIInfo>(CGT)) {} 9026 }; 9027 } 9028 9029 //===----------------------------------------------------------------------===// 9030 // AMDGPU ABI Implementation 9031 //===----------------------------------------------------------------------===// 9032 9033 namespace { 9034 9035 class AMDGPUABIInfo final : public DefaultABIInfo { 9036 private: 9037 static const unsigned MaxNumRegsForArgsRet = 16; 9038 9039 unsigned numRegsForType(QualType Ty) const; 9040 9041 bool isHomogeneousAggregateBaseType(QualType Ty) const override; 9042 bool isHomogeneousAggregateSmallEnough(const Type *Base, 9043 uint64_t Members) const override; 9044 9045 // Coerce HIP scalar pointer arguments from generic pointers to global ones. 9046 llvm::Type *coerceKernelArgumentType(llvm::Type *Ty, unsigned FromAS, 9047 unsigned ToAS) const { 9048 // Single value types. 9049 auto *PtrTy = llvm::dyn_cast<llvm::PointerType>(Ty); 9050 if (PtrTy && PtrTy->getAddressSpace() == FromAS) 9051 return llvm::PointerType::getWithSamePointeeType(PtrTy, ToAS); 9052 return Ty; 9053 } 9054 9055 public: 9056 explicit AMDGPUABIInfo(CodeGen::CodeGenTypes &CGT) : 9057 DefaultABIInfo(CGT) {} 9058 9059 ABIArgInfo classifyReturnType(QualType RetTy) const; 9060 ABIArgInfo classifyKernelArgumentType(QualType Ty) const; 9061 ABIArgInfo classifyArgumentType(QualType Ty, unsigned &NumRegsLeft) const; 9062 9063 void computeInfo(CGFunctionInfo &FI) const override; 9064 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 9065 QualType Ty) const override; 9066 }; 9067 9068 bool AMDGPUABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const { 9069 return true; 9070 } 9071 9072 bool AMDGPUABIInfo::isHomogeneousAggregateSmallEnough( 9073 const Type *Base, uint64_t Members) const { 9074 uint32_t NumRegs = (getContext().getTypeSize(Base) + 31) / 32; 9075 9076 // Homogeneous Aggregates may occupy at most 16 registers. 9077 return Members * NumRegs <= MaxNumRegsForArgsRet; 9078 } 9079 9080 /// Estimate number of registers the type will use when passed in registers. 9081 unsigned AMDGPUABIInfo::numRegsForType(QualType Ty) const { 9082 unsigned NumRegs = 0; 9083 9084 if (const VectorType *VT = Ty->getAs<VectorType>()) { 9085 // Compute from the number of elements. The reported size is based on the 9086 // in-memory size, which includes the padding 4th element for 3-vectors. 9087 QualType EltTy = VT->getElementType(); 9088 unsigned EltSize = getContext().getTypeSize(EltTy); 9089 9090 // 16-bit element vectors should be passed as packed. 9091 if (EltSize == 16) 9092 return (VT->getNumElements() + 1) / 2; 9093 9094 unsigned EltNumRegs = (EltSize + 31) / 32; 9095 return EltNumRegs * VT->getNumElements(); 9096 } 9097 9098 if (const RecordType *RT = Ty->getAs<RecordType>()) { 9099 const RecordDecl *RD = RT->getDecl(); 9100 assert(!RD->hasFlexibleArrayMember()); 9101 9102 for (const FieldDecl *Field : RD->fields()) { 9103 QualType FieldTy = Field->getType(); 9104 NumRegs += numRegsForType(FieldTy); 9105 } 9106 9107 return NumRegs; 9108 } 9109 9110 return (getContext().getTypeSize(Ty) + 31) / 32; 9111 } 9112 9113 void AMDGPUABIInfo::computeInfo(CGFunctionInfo &FI) const { 9114 llvm::CallingConv::ID CC = FI.getCallingConvention(); 9115 9116 if (!getCXXABI().classifyReturnType(FI)) 9117 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 9118 9119 unsigned NumRegsLeft = MaxNumRegsForArgsRet; 9120 for (auto &Arg : FI.arguments()) { 9121 if (CC == llvm::CallingConv::AMDGPU_KERNEL) { 9122 Arg.info = classifyKernelArgumentType(Arg.type); 9123 } else { 9124 Arg.info = classifyArgumentType(Arg.type, NumRegsLeft); 9125 } 9126 } 9127 } 9128 9129 Address AMDGPUABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 9130 QualType Ty) const { 9131 llvm_unreachable("AMDGPU does not support varargs"); 9132 } 9133 9134 ABIArgInfo AMDGPUABIInfo::classifyReturnType(QualType RetTy) const { 9135 if (isAggregateTypeForABI(RetTy)) { 9136 // Records with non-trivial destructors/copy-constructors should not be 9137 // returned by value. 9138 if (!getRecordArgABI(RetTy, getCXXABI())) { 9139 // Ignore empty structs/unions. 9140 if (isEmptyRecord(getContext(), RetTy, true)) 9141 return ABIArgInfo::getIgnore(); 9142 9143 // Lower single-element structs to just return a regular value. 9144 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext())) 9145 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0))); 9146 9147 if (const RecordType *RT = RetTy->getAs<RecordType>()) { 9148 const RecordDecl *RD = RT->getDecl(); 9149 if (RD->hasFlexibleArrayMember()) 9150 return DefaultABIInfo::classifyReturnType(RetTy); 9151 } 9152 9153 // Pack aggregates <= 4 bytes into single VGPR or pair. 9154 uint64_t Size = getContext().getTypeSize(RetTy); 9155 if (Size <= 16) 9156 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext())); 9157 9158 if (Size <= 32) 9159 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext())); 9160 9161 if (Size <= 64) { 9162 llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext()); 9163 return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2)); 9164 } 9165 9166 if (numRegsForType(RetTy) <= MaxNumRegsForArgsRet) 9167 return ABIArgInfo::getDirect(); 9168 } 9169 } 9170 9171 // Otherwise just do the default thing. 9172 return DefaultABIInfo::classifyReturnType(RetTy); 9173 } 9174 9175 /// For kernels all parameters are really passed in a special buffer. It doesn't 9176 /// make sense to pass anything byval, so everything must be direct. 9177 ABIArgInfo AMDGPUABIInfo::classifyKernelArgumentType(QualType Ty) const { 9178 Ty = useFirstFieldIfTransparentUnion(Ty); 9179 9180 // TODO: Can we omit empty structs? 9181 9182 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext())) 9183 Ty = QualType(SeltTy, 0); 9184 9185 llvm::Type *OrigLTy = CGT.ConvertType(Ty); 9186 llvm::Type *LTy = OrigLTy; 9187 if (getContext().getLangOpts().HIP) { 9188 LTy = coerceKernelArgumentType( 9189 OrigLTy, /*FromAS=*/getContext().getTargetAddressSpace(LangAS::Default), 9190 /*ToAS=*/getContext().getTargetAddressSpace(LangAS::cuda_device)); 9191 } 9192 9193 // FIXME: Should also use this for OpenCL, but it requires addressing the 9194 // problem of kernels being called. 9195 // 9196 // FIXME: This doesn't apply the optimization of coercing pointers in structs 9197 // to global address space when using byref. This would require implementing a 9198 // new kind of coercion of the in-memory type when for indirect arguments. 9199 if (!getContext().getLangOpts().OpenCL && LTy == OrigLTy && 9200 isAggregateTypeForABI(Ty)) { 9201 return ABIArgInfo::getIndirectAliased( 9202 getContext().getTypeAlignInChars(Ty), 9203 getContext().getTargetAddressSpace(LangAS::opencl_constant), 9204 false /*Realign*/, nullptr /*Padding*/); 9205 } 9206 9207 // If we set CanBeFlattened to true, CodeGen will expand the struct to its 9208 // individual elements, which confuses the Clover OpenCL backend; therefore we 9209 // have to set it to false here. Other args of getDirect() are just defaults. 9210 return ABIArgInfo::getDirect(LTy, 0, nullptr, false); 9211 } 9212 9213 ABIArgInfo AMDGPUABIInfo::classifyArgumentType(QualType Ty, 9214 unsigned &NumRegsLeft) const { 9215 assert(NumRegsLeft <= MaxNumRegsForArgsRet && "register estimate underflow"); 9216 9217 Ty = useFirstFieldIfTransparentUnion(Ty); 9218 9219 if (isAggregateTypeForABI(Ty)) { 9220 // Records with non-trivial destructors/copy-constructors should not be 9221 // passed by value. 9222 if (auto RAA = getRecordArgABI(Ty, getCXXABI())) 9223 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 9224 9225 // Ignore empty structs/unions. 9226 if (isEmptyRecord(getContext(), Ty, true)) 9227 return ABIArgInfo::getIgnore(); 9228 9229 // Lower single-element structs to just pass a regular value. TODO: We 9230 // could do reasonable-size multiple-element structs too, using getExpand(), 9231 // though watch out for things like bitfields. 9232 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext())) 9233 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0))); 9234 9235 if (const RecordType *RT = Ty->getAs<RecordType>()) { 9236 const RecordDecl *RD = RT->getDecl(); 9237 if (RD->hasFlexibleArrayMember()) 9238 return DefaultABIInfo::classifyArgumentType(Ty); 9239 } 9240 9241 // Pack aggregates <= 8 bytes into single VGPR or pair. 9242 uint64_t Size = getContext().getTypeSize(Ty); 9243 if (Size <= 64) { 9244 unsigned NumRegs = (Size + 31) / 32; 9245 NumRegsLeft -= std::min(NumRegsLeft, NumRegs); 9246 9247 if (Size <= 16) 9248 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext())); 9249 9250 if (Size <= 32) 9251 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext())); 9252 9253 // XXX: Should this be i64 instead, and should the limit increase? 9254 llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext()); 9255 return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2)); 9256 } 9257 9258 if (NumRegsLeft > 0) { 9259 unsigned NumRegs = numRegsForType(Ty); 9260 if (NumRegsLeft >= NumRegs) { 9261 NumRegsLeft -= NumRegs; 9262 return ABIArgInfo::getDirect(); 9263 } 9264 } 9265 } 9266 9267 // Otherwise just do the default thing. 9268 ABIArgInfo ArgInfo = DefaultABIInfo::classifyArgumentType(Ty); 9269 if (!ArgInfo.isIndirect()) { 9270 unsigned NumRegs = numRegsForType(Ty); 9271 NumRegsLeft -= std::min(NumRegs, NumRegsLeft); 9272 } 9273 9274 return ArgInfo; 9275 } 9276 9277 class AMDGPUTargetCodeGenInfo : public TargetCodeGenInfo { 9278 public: 9279 AMDGPUTargetCodeGenInfo(CodeGenTypes &CGT) 9280 : TargetCodeGenInfo(std::make_unique<AMDGPUABIInfo>(CGT)) {} 9281 9282 void setFunctionDeclAttributes(const FunctionDecl *FD, llvm::Function *F, 9283 CodeGenModule &CGM) const; 9284 9285 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 9286 CodeGen::CodeGenModule &M) const override; 9287 unsigned getOpenCLKernelCallingConv() const override; 9288 9289 llvm::Constant *getNullPointer(const CodeGen::CodeGenModule &CGM, 9290 llvm::PointerType *T, QualType QT) const override; 9291 9292 LangAS getASTAllocaAddressSpace() const override { 9293 return getLangASFromTargetAS( 9294 getABIInfo().getDataLayout().getAllocaAddrSpace()); 9295 } 9296 LangAS getGlobalVarAddressSpace(CodeGenModule &CGM, 9297 const VarDecl *D) const override; 9298 llvm::SyncScope::ID getLLVMSyncScopeID(const LangOptions &LangOpts, 9299 SyncScope Scope, 9300 llvm::AtomicOrdering Ordering, 9301 llvm::LLVMContext &Ctx) const override; 9302 llvm::Function * 9303 createEnqueuedBlockKernel(CodeGenFunction &CGF, 9304 llvm::Function *BlockInvokeFunc, 9305 llvm::Type *BlockTy) const override; 9306 bool shouldEmitStaticExternCAliases() const override; 9307 void setCUDAKernelCallingConvention(const FunctionType *&FT) const override; 9308 }; 9309 } 9310 9311 static bool requiresAMDGPUProtectedVisibility(const Decl *D, 9312 llvm::GlobalValue *GV) { 9313 if (GV->getVisibility() != llvm::GlobalValue::HiddenVisibility) 9314 return false; 9315 9316 return D->hasAttr<OpenCLKernelAttr>() || 9317 (isa<FunctionDecl>(D) && D->hasAttr<CUDAGlobalAttr>()) || 9318 (isa<VarDecl>(D) && 9319 (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>() || 9320 cast<VarDecl>(D)->getType()->isCUDADeviceBuiltinSurfaceType() || 9321 cast<VarDecl>(D)->getType()->isCUDADeviceBuiltinTextureType())); 9322 } 9323 9324 void AMDGPUTargetCodeGenInfo::setFunctionDeclAttributes( 9325 const FunctionDecl *FD, llvm::Function *F, CodeGenModule &M) const { 9326 const auto *ReqdWGS = 9327 M.getLangOpts().OpenCL ? FD->getAttr<ReqdWorkGroupSizeAttr>() : nullptr; 9328 const bool IsOpenCLKernel = 9329 M.getLangOpts().OpenCL && FD->hasAttr<OpenCLKernelAttr>(); 9330 const bool IsHIPKernel = M.getLangOpts().HIP && FD->hasAttr<CUDAGlobalAttr>(); 9331 9332 const auto *FlatWGS = FD->getAttr<AMDGPUFlatWorkGroupSizeAttr>(); 9333 if (ReqdWGS || FlatWGS) { 9334 unsigned Min = 0; 9335 unsigned Max = 0; 9336 if (FlatWGS) { 9337 Min = FlatWGS->getMin() 9338 ->EvaluateKnownConstInt(M.getContext()) 9339 .getExtValue(); 9340 Max = FlatWGS->getMax() 9341 ->EvaluateKnownConstInt(M.getContext()) 9342 .getExtValue(); 9343 } 9344 if (ReqdWGS && Min == 0 && Max == 0) 9345 Min = Max = ReqdWGS->getXDim() * ReqdWGS->getYDim() * ReqdWGS->getZDim(); 9346 9347 if (Min != 0) { 9348 assert(Min <= Max && "Min must be less than or equal Max"); 9349 9350 std::string AttrVal = llvm::utostr(Min) + "," + llvm::utostr(Max); 9351 F->addFnAttr("amdgpu-flat-work-group-size", AttrVal); 9352 } else 9353 assert(Max == 0 && "Max must be zero"); 9354 } else if (IsOpenCLKernel || IsHIPKernel) { 9355 // By default, restrict the maximum size to a value specified by 9356 // --gpu-max-threads-per-block=n or its default value for HIP. 9357 const unsigned OpenCLDefaultMaxWorkGroupSize = 256; 9358 const unsigned DefaultMaxWorkGroupSize = 9359 IsOpenCLKernel ? OpenCLDefaultMaxWorkGroupSize 9360 : M.getLangOpts().GPUMaxThreadsPerBlock; 9361 std::string AttrVal = 9362 std::string("1,") + llvm::utostr(DefaultMaxWorkGroupSize); 9363 F->addFnAttr("amdgpu-flat-work-group-size", AttrVal); 9364 } 9365 9366 if (const auto *Attr = FD->getAttr<AMDGPUWavesPerEUAttr>()) { 9367 unsigned Min = 9368 Attr->getMin()->EvaluateKnownConstInt(M.getContext()).getExtValue(); 9369 unsigned Max = Attr->getMax() ? Attr->getMax() 9370 ->EvaluateKnownConstInt(M.getContext()) 9371 .getExtValue() 9372 : 0; 9373 9374 if (Min != 0) { 9375 assert((Max == 0 || Min <= Max) && "Min must be less than or equal Max"); 9376 9377 std::string AttrVal = llvm::utostr(Min); 9378 if (Max != 0) 9379 AttrVal = AttrVal + "," + llvm::utostr(Max); 9380 F->addFnAttr("amdgpu-waves-per-eu", AttrVal); 9381 } else 9382 assert(Max == 0 && "Max must be zero"); 9383 } 9384 9385 if (const auto *Attr = FD->getAttr<AMDGPUNumSGPRAttr>()) { 9386 unsigned NumSGPR = Attr->getNumSGPR(); 9387 9388 if (NumSGPR != 0) 9389 F->addFnAttr("amdgpu-num-sgpr", llvm::utostr(NumSGPR)); 9390 } 9391 9392 if (const auto *Attr = FD->getAttr<AMDGPUNumVGPRAttr>()) { 9393 uint32_t NumVGPR = Attr->getNumVGPR(); 9394 9395 if (NumVGPR != 0) 9396 F->addFnAttr("amdgpu-num-vgpr", llvm::utostr(NumVGPR)); 9397 } 9398 } 9399 9400 void AMDGPUTargetCodeGenInfo::setTargetAttributes( 9401 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const { 9402 if (requiresAMDGPUProtectedVisibility(D, GV)) { 9403 GV->setVisibility(llvm::GlobalValue::ProtectedVisibility); 9404 GV->setDSOLocal(true); 9405 } 9406 9407 if (GV->isDeclaration()) 9408 return; 9409 9410 llvm::Function *F = dyn_cast<llvm::Function>(GV); 9411 if (!F) 9412 return; 9413 9414 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D); 9415 if (FD) 9416 setFunctionDeclAttributes(FD, F, M); 9417 9418 const bool IsHIPKernel = 9419 M.getLangOpts().HIP && FD && FD->hasAttr<CUDAGlobalAttr>(); 9420 9421 if (IsHIPKernel) 9422 F->addFnAttr("uniform-work-group-size", "true"); 9423 9424 if (M.getContext().getTargetInfo().allowAMDGPUUnsafeFPAtomics()) 9425 F->addFnAttr("amdgpu-unsafe-fp-atomics", "true"); 9426 9427 if (!getABIInfo().getCodeGenOpts().EmitIEEENaNCompliantInsts) 9428 F->addFnAttr("amdgpu-ieee", "false"); 9429 } 9430 9431 unsigned AMDGPUTargetCodeGenInfo::getOpenCLKernelCallingConv() const { 9432 return llvm::CallingConv::AMDGPU_KERNEL; 9433 } 9434 9435 // Currently LLVM assumes null pointers always have value 0, 9436 // which results in incorrectly transformed IR. Therefore, instead of 9437 // emitting null pointers in private and local address spaces, a null 9438 // pointer in generic address space is emitted which is casted to a 9439 // pointer in local or private address space. 9440 llvm::Constant *AMDGPUTargetCodeGenInfo::getNullPointer( 9441 const CodeGen::CodeGenModule &CGM, llvm::PointerType *PT, 9442 QualType QT) const { 9443 if (CGM.getContext().getTargetNullPointerValue(QT) == 0) 9444 return llvm::ConstantPointerNull::get(PT); 9445 9446 auto &Ctx = CGM.getContext(); 9447 auto NPT = llvm::PointerType::getWithSamePointeeType( 9448 PT, Ctx.getTargetAddressSpace(LangAS::opencl_generic)); 9449 return llvm::ConstantExpr::getAddrSpaceCast( 9450 llvm::ConstantPointerNull::get(NPT), PT); 9451 } 9452 9453 LangAS 9454 AMDGPUTargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM, 9455 const VarDecl *D) const { 9456 assert(!CGM.getLangOpts().OpenCL && 9457 !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) && 9458 "Address space agnostic languages only"); 9459 LangAS DefaultGlobalAS = getLangASFromTargetAS( 9460 CGM.getContext().getTargetAddressSpace(LangAS::opencl_global)); 9461 if (!D) 9462 return DefaultGlobalAS; 9463 9464 LangAS AddrSpace = D->getType().getAddressSpace(); 9465 assert(AddrSpace == LangAS::Default || isTargetAddressSpace(AddrSpace)); 9466 if (AddrSpace != LangAS::Default) 9467 return AddrSpace; 9468 9469 // Only promote to address space 4 if VarDecl has constant initialization. 9470 if (CGM.isTypeConstant(D->getType(), false) && 9471 D->hasConstantInitialization()) { 9472 if (auto ConstAS = CGM.getTarget().getConstantAddressSpace()) 9473 return ConstAS.getValue(); 9474 } 9475 return DefaultGlobalAS; 9476 } 9477 9478 llvm::SyncScope::ID 9479 AMDGPUTargetCodeGenInfo::getLLVMSyncScopeID(const LangOptions &LangOpts, 9480 SyncScope Scope, 9481 llvm::AtomicOrdering Ordering, 9482 llvm::LLVMContext &Ctx) const { 9483 std::string Name; 9484 switch (Scope) { 9485 case SyncScope::HIPSingleThread: 9486 Name = "singlethread"; 9487 break; 9488 case SyncScope::HIPWavefront: 9489 case SyncScope::OpenCLSubGroup: 9490 Name = "wavefront"; 9491 break; 9492 case SyncScope::HIPWorkgroup: 9493 case SyncScope::OpenCLWorkGroup: 9494 Name = "workgroup"; 9495 break; 9496 case SyncScope::HIPAgent: 9497 case SyncScope::OpenCLDevice: 9498 Name = "agent"; 9499 break; 9500 case SyncScope::HIPSystem: 9501 case SyncScope::OpenCLAllSVMDevices: 9502 Name = ""; 9503 break; 9504 } 9505 9506 if (Ordering != llvm::AtomicOrdering::SequentiallyConsistent) { 9507 if (!Name.empty()) 9508 Name = Twine(Twine(Name) + Twine("-")).str(); 9509 9510 Name = Twine(Twine(Name) + Twine("one-as")).str(); 9511 } 9512 9513 return Ctx.getOrInsertSyncScopeID(Name); 9514 } 9515 9516 bool AMDGPUTargetCodeGenInfo::shouldEmitStaticExternCAliases() const { 9517 return false; 9518 } 9519 9520 void AMDGPUTargetCodeGenInfo::setCUDAKernelCallingConvention( 9521 const FunctionType *&FT) const { 9522 FT = getABIInfo().getContext().adjustFunctionType( 9523 FT, FT->getExtInfo().withCallingConv(CC_OpenCLKernel)); 9524 } 9525 9526 //===----------------------------------------------------------------------===// 9527 // SPARC v8 ABI Implementation. 9528 // Based on the SPARC Compliance Definition version 2.4.1. 9529 // 9530 // Ensures that complex values are passed in registers. 9531 // 9532 namespace { 9533 class SparcV8ABIInfo : public DefaultABIInfo { 9534 public: 9535 SparcV8ABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {} 9536 9537 private: 9538 ABIArgInfo classifyReturnType(QualType RetTy) const; 9539 void computeInfo(CGFunctionInfo &FI) const override; 9540 }; 9541 } // end anonymous namespace 9542 9543 9544 ABIArgInfo 9545 SparcV8ABIInfo::classifyReturnType(QualType Ty) const { 9546 if (Ty->isAnyComplexType()) { 9547 return ABIArgInfo::getDirect(); 9548 } 9549 else { 9550 return DefaultABIInfo::classifyReturnType(Ty); 9551 } 9552 } 9553 9554 void SparcV8ABIInfo::computeInfo(CGFunctionInfo &FI) const { 9555 9556 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 9557 for (auto &Arg : FI.arguments()) 9558 Arg.info = classifyArgumentType(Arg.type); 9559 } 9560 9561 namespace { 9562 class SparcV8TargetCodeGenInfo : public TargetCodeGenInfo { 9563 public: 9564 SparcV8TargetCodeGenInfo(CodeGenTypes &CGT) 9565 : TargetCodeGenInfo(std::make_unique<SparcV8ABIInfo>(CGT)) {} 9566 9567 llvm::Value *decodeReturnAddress(CodeGen::CodeGenFunction &CGF, 9568 llvm::Value *Address) const override { 9569 int Offset; 9570 if (isAggregateTypeForABI(CGF.CurFnInfo->getReturnType())) 9571 Offset = 12; 9572 else 9573 Offset = 8; 9574 return CGF.Builder.CreateGEP(CGF.Int8Ty, Address, 9575 llvm::ConstantInt::get(CGF.Int32Ty, Offset)); 9576 } 9577 9578 llvm::Value *encodeReturnAddress(CodeGen::CodeGenFunction &CGF, 9579 llvm::Value *Address) const override { 9580 int Offset; 9581 if (isAggregateTypeForABI(CGF.CurFnInfo->getReturnType())) 9582 Offset = -12; 9583 else 9584 Offset = -8; 9585 return CGF.Builder.CreateGEP(CGF.Int8Ty, Address, 9586 llvm::ConstantInt::get(CGF.Int32Ty, Offset)); 9587 } 9588 }; 9589 } // end anonymous namespace 9590 9591 //===----------------------------------------------------------------------===// 9592 // SPARC v9 ABI Implementation. 9593 // Based on the SPARC Compliance Definition version 2.4.1. 9594 // 9595 // Function arguments a mapped to a nominal "parameter array" and promoted to 9596 // registers depending on their type. Each argument occupies 8 or 16 bytes in 9597 // the array, structs larger than 16 bytes are passed indirectly. 9598 // 9599 // One case requires special care: 9600 // 9601 // struct mixed { 9602 // int i; 9603 // float f; 9604 // }; 9605 // 9606 // When a struct mixed is passed by value, it only occupies 8 bytes in the 9607 // parameter array, but the int is passed in an integer register, and the float 9608 // is passed in a floating point register. This is represented as two arguments 9609 // with the LLVM IR inreg attribute: 9610 // 9611 // declare void f(i32 inreg %i, float inreg %f) 9612 // 9613 // The code generator will only allocate 4 bytes from the parameter array for 9614 // the inreg arguments. All other arguments are allocated a multiple of 8 9615 // bytes. 9616 // 9617 namespace { 9618 class SparcV9ABIInfo : public ABIInfo { 9619 public: 9620 SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {} 9621 9622 private: 9623 ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const; 9624 void computeInfo(CGFunctionInfo &FI) const override; 9625 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 9626 QualType Ty) const override; 9627 9628 // Coercion type builder for structs passed in registers. The coercion type 9629 // serves two purposes: 9630 // 9631 // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned' 9632 // in registers. 9633 // 2. Expose aligned floating point elements as first-level elements, so the 9634 // code generator knows to pass them in floating point registers. 9635 // 9636 // We also compute the InReg flag which indicates that the struct contains 9637 // aligned 32-bit floats. 9638 // 9639 struct CoerceBuilder { 9640 llvm::LLVMContext &Context; 9641 const llvm::DataLayout &DL; 9642 SmallVector<llvm::Type*, 8> Elems; 9643 uint64_t Size; 9644 bool InReg; 9645 9646 CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl) 9647 : Context(c), DL(dl), Size(0), InReg(false) {} 9648 9649 // Pad Elems with integers until Size is ToSize. 9650 void pad(uint64_t ToSize) { 9651 assert(ToSize >= Size && "Cannot remove elements"); 9652 if (ToSize == Size) 9653 return; 9654 9655 // Finish the current 64-bit word. 9656 uint64_t Aligned = llvm::alignTo(Size, 64); 9657 if (Aligned > Size && Aligned <= ToSize) { 9658 Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size)); 9659 Size = Aligned; 9660 } 9661 9662 // Add whole 64-bit words. 9663 while (Size + 64 <= ToSize) { 9664 Elems.push_back(llvm::Type::getInt64Ty(Context)); 9665 Size += 64; 9666 } 9667 9668 // Final in-word padding. 9669 if (Size < ToSize) { 9670 Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size)); 9671 Size = ToSize; 9672 } 9673 } 9674 9675 // Add a floating point element at Offset. 9676 void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) { 9677 // Unaligned floats are treated as integers. 9678 if (Offset % Bits) 9679 return; 9680 // The InReg flag is only required if there are any floats < 64 bits. 9681 if (Bits < 64) 9682 InReg = true; 9683 pad(Offset); 9684 Elems.push_back(Ty); 9685 Size = Offset + Bits; 9686 } 9687 9688 // Add a struct type to the coercion type, starting at Offset (in bits). 9689 void addStruct(uint64_t Offset, llvm::StructType *StrTy) { 9690 const llvm::StructLayout *Layout = DL.getStructLayout(StrTy); 9691 for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) { 9692 llvm::Type *ElemTy = StrTy->getElementType(i); 9693 uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i); 9694 switch (ElemTy->getTypeID()) { 9695 case llvm::Type::StructTyID: 9696 addStruct(ElemOffset, cast<llvm::StructType>(ElemTy)); 9697 break; 9698 case llvm::Type::FloatTyID: 9699 addFloat(ElemOffset, ElemTy, 32); 9700 break; 9701 case llvm::Type::DoubleTyID: 9702 addFloat(ElemOffset, ElemTy, 64); 9703 break; 9704 case llvm::Type::FP128TyID: 9705 addFloat(ElemOffset, ElemTy, 128); 9706 break; 9707 case llvm::Type::PointerTyID: 9708 if (ElemOffset % 64 == 0) { 9709 pad(ElemOffset); 9710 Elems.push_back(ElemTy); 9711 Size += 64; 9712 } 9713 break; 9714 default: 9715 break; 9716 } 9717 } 9718 } 9719 9720 // Check if Ty is a usable substitute for the coercion type. 9721 bool isUsableType(llvm::StructType *Ty) const { 9722 return llvm::makeArrayRef(Elems) == Ty->elements(); 9723 } 9724 9725 // Get the coercion type as a literal struct type. 9726 llvm::Type *getType() const { 9727 if (Elems.size() == 1) 9728 return Elems.front(); 9729 else 9730 return llvm::StructType::get(Context, Elems); 9731 } 9732 }; 9733 }; 9734 } // end anonymous namespace 9735 9736 ABIArgInfo 9737 SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const { 9738 if (Ty->isVoidType()) 9739 return ABIArgInfo::getIgnore(); 9740 9741 uint64_t Size = getContext().getTypeSize(Ty); 9742 9743 // Anything too big to fit in registers is passed with an explicit indirect 9744 // pointer / sret pointer. 9745 if (Size > SizeLimit) 9746 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 9747 9748 // Treat an enum type as its underlying type. 9749 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 9750 Ty = EnumTy->getDecl()->getIntegerType(); 9751 9752 // Integer types smaller than a register are extended. 9753 if (Size < 64 && Ty->isIntegerType()) 9754 return ABIArgInfo::getExtend(Ty); 9755 9756 if (const auto *EIT = Ty->getAs<BitIntType>()) 9757 if (EIT->getNumBits() < 64) 9758 return ABIArgInfo::getExtend(Ty); 9759 9760 // Other non-aggregates go in registers. 9761 if (!isAggregateTypeForABI(Ty)) 9762 return ABIArgInfo::getDirect(); 9763 9764 // If a C++ object has either a non-trivial copy constructor or a non-trivial 9765 // destructor, it is passed with an explicit indirect pointer / sret pointer. 9766 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 9767 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 9768 9769 // This is a small aggregate type that should be passed in registers. 9770 // Build a coercion type from the LLVM struct type. 9771 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty)); 9772 if (!StrTy) 9773 return ABIArgInfo::getDirect(); 9774 9775 CoerceBuilder CB(getVMContext(), getDataLayout()); 9776 CB.addStruct(0, StrTy); 9777 CB.pad(llvm::alignTo(CB.DL.getTypeSizeInBits(StrTy), 64)); 9778 9779 // Try to use the original type for coercion. 9780 llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType(); 9781 9782 if (CB.InReg) 9783 return ABIArgInfo::getDirectInReg(CoerceTy); 9784 else 9785 return ABIArgInfo::getDirect(CoerceTy); 9786 } 9787 9788 Address SparcV9ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 9789 QualType Ty) const { 9790 ABIArgInfo AI = classifyType(Ty, 16 * 8); 9791 llvm::Type *ArgTy = CGT.ConvertType(Ty); 9792 if (AI.canHaveCoerceToType() && !AI.getCoerceToType()) 9793 AI.setCoerceToType(ArgTy); 9794 9795 CharUnits SlotSize = CharUnits::fromQuantity(8); 9796 9797 CGBuilderTy &Builder = CGF.Builder; 9798 Address Addr = Address(Builder.CreateLoad(VAListAddr, "ap.cur"), 9799 getVAListElementType(CGF), SlotSize); 9800 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy); 9801 9802 auto TypeInfo = getContext().getTypeInfoInChars(Ty); 9803 9804 Address ArgAddr = Address::invalid(); 9805 CharUnits Stride; 9806 switch (AI.getKind()) { 9807 case ABIArgInfo::Expand: 9808 case ABIArgInfo::CoerceAndExpand: 9809 case ABIArgInfo::InAlloca: 9810 llvm_unreachable("Unsupported ABI kind for va_arg"); 9811 9812 case ABIArgInfo::Extend: { 9813 Stride = SlotSize; 9814 CharUnits Offset = SlotSize - TypeInfo.Width; 9815 ArgAddr = Builder.CreateConstInBoundsByteGEP(Addr, Offset, "extend"); 9816 break; 9817 } 9818 9819 case ABIArgInfo::Direct: { 9820 auto AllocSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType()); 9821 Stride = CharUnits::fromQuantity(AllocSize).alignTo(SlotSize); 9822 ArgAddr = Addr; 9823 break; 9824 } 9825 9826 case ABIArgInfo::Indirect: 9827 case ABIArgInfo::IndirectAliased: 9828 Stride = SlotSize; 9829 ArgAddr = Builder.CreateElementBitCast(Addr, ArgPtrTy, "indirect"); 9830 ArgAddr = Address(Builder.CreateLoad(ArgAddr, "indirect.arg"), ArgTy, 9831 TypeInfo.Align); 9832 break; 9833 9834 case ABIArgInfo::Ignore: 9835 return Address(llvm::UndefValue::get(ArgPtrTy), ArgTy, TypeInfo.Align); 9836 } 9837 9838 // Update VAList. 9839 Address NextPtr = Builder.CreateConstInBoundsByteGEP(Addr, Stride, "ap.next"); 9840 Builder.CreateStore(NextPtr.getPointer(), VAListAddr); 9841 9842 return Builder.CreateElementBitCast(ArgAddr, ArgTy, "arg.addr"); 9843 } 9844 9845 void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const { 9846 FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8); 9847 for (auto &I : FI.arguments()) 9848 I.info = classifyType(I.type, 16 * 8); 9849 } 9850 9851 namespace { 9852 class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo { 9853 public: 9854 SparcV9TargetCodeGenInfo(CodeGenTypes &CGT) 9855 : TargetCodeGenInfo(std::make_unique<SparcV9ABIInfo>(CGT)) {} 9856 9857 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 9858 return 14; 9859 } 9860 9861 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 9862 llvm::Value *Address) const override; 9863 9864 llvm::Value *decodeReturnAddress(CodeGen::CodeGenFunction &CGF, 9865 llvm::Value *Address) const override { 9866 return CGF.Builder.CreateGEP(CGF.Int8Ty, Address, 9867 llvm::ConstantInt::get(CGF.Int32Ty, 8)); 9868 } 9869 9870 llvm::Value *encodeReturnAddress(CodeGen::CodeGenFunction &CGF, 9871 llvm::Value *Address) const override { 9872 return CGF.Builder.CreateGEP(CGF.Int8Ty, Address, 9873 llvm::ConstantInt::get(CGF.Int32Ty, -8)); 9874 } 9875 }; 9876 } // end anonymous namespace 9877 9878 bool 9879 SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 9880 llvm::Value *Address) const { 9881 // This is calculated from the LLVM and GCC tables and verified 9882 // against gcc output. AFAIK all ABIs use the same encoding. 9883 9884 CodeGen::CGBuilderTy &Builder = CGF.Builder; 9885 9886 llvm::IntegerType *i8 = CGF.Int8Ty; 9887 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4); 9888 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8); 9889 9890 // 0-31: the 8-byte general-purpose registers 9891 AssignToArrayRange(Builder, Address, Eight8, 0, 31); 9892 9893 // 32-63: f0-31, the 4-byte floating-point registers 9894 AssignToArrayRange(Builder, Address, Four8, 32, 63); 9895 9896 // Y = 64 9897 // PSR = 65 9898 // WIM = 66 9899 // TBR = 67 9900 // PC = 68 9901 // NPC = 69 9902 // FSR = 70 9903 // CSR = 71 9904 AssignToArrayRange(Builder, Address, Eight8, 64, 71); 9905 9906 // 72-87: d0-15, the 8-byte floating-point registers 9907 AssignToArrayRange(Builder, Address, Eight8, 72, 87); 9908 9909 return false; 9910 } 9911 9912 // ARC ABI implementation. 9913 namespace { 9914 9915 class ARCABIInfo : public DefaultABIInfo { 9916 public: 9917 using DefaultABIInfo::DefaultABIInfo; 9918 9919 private: 9920 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 9921 QualType Ty) const override; 9922 9923 void updateState(const ABIArgInfo &Info, QualType Ty, CCState &State) const { 9924 if (!State.FreeRegs) 9925 return; 9926 if (Info.isIndirect() && Info.getInReg()) 9927 State.FreeRegs--; 9928 else if (Info.isDirect() && Info.getInReg()) { 9929 unsigned sz = (getContext().getTypeSize(Ty) + 31) / 32; 9930 if (sz < State.FreeRegs) 9931 State.FreeRegs -= sz; 9932 else 9933 State.FreeRegs = 0; 9934 } 9935 } 9936 9937 void computeInfo(CGFunctionInfo &FI) const override { 9938 CCState State(FI); 9939 // ARC uses 8 registers to pass arguments. 9940 State.FreeRegs = 8; 9941 9942 if (!getCXXABI().classifyReturnType(FI)) 9943 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 9944 updateState(FI.getReturnInfo(), FI.getReturnType(), State); 9945 for (auto &I : FI.arguments()) { 9946 I.info = classifyArgumentType(I.type, State.FreeRegs); 9947 updateState(I.info, I.type, State); 9948 } 9949 } 9950 9951 ABIArgInfo getIndirectByRef(QualType Ty, bool HasFreeRegs) const; 9952 ABIArgInfo getIndirectByValue(QualType Ty) const; 9953 ABIArgInfo classifyArgumentType(QualType Ty, uint8_t FreeRegs) const; 9954 ABIArgInfo classifyReturnType(QualType RetTy) const; 9955 }; 9956 9957 class ARCTargetCodeGenInfo : public TargetCodeGenInfo { 9958 public: 9959 ARCTargetCodeGenInfo(CodeGenTypes &CGT) 9960 : TargetCodeGenInfo(std::make_unique<ARCABIInfo>(CGT)) {} 9961 }; 9962 9963 9964 ABIArgInfo ARCABIInfo::getIndirectByRef(QualType Ty, bool HasFreeRegs) const { 9965 return HasFreeRegs ? getNaturalAlignIndirectInReg(Ty) : 9966 getNaturalAlignIndirect(Ty, false); 9967 } 9968 9969 ABIArgInfo ARCABIInfo::getIndirectByValue(QualType Ty) const { 9970 // Compute the byval alignment. 9971 const unsigned MinABIStackAlignInBytes = 4; 9972 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8; 9973 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true, 9974 TypeAlign > MinABIStackAlignInBytes); 9975 } 9976 9977 Address ARCABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 9978 QualType Ty) const { 9979 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false, 9980 getContext().getTypeInfoInChars(Ty), 9981 CharUnits::fromQuantity(4), true); 9982 } 9983 9984 ABIArgInfo ARCABIInfo::classifyArgumentType(QualType Ty, 9985 uint8_t FreeRegs) const { 9986 // Handle the generic C++ ABI. 9987 const RecordType *RT = Ty->getAs<RecordType>(); 9988 if (RT) { 9989 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()); 9990 if (RAA == CGCXXABI::RAA_Indirect) 9991 return getIndirectByRef(Ty, FreeRegs > 0); 9992 9993 if (RAA == CGCXXABI::RAA_DirectInMemory) 9994 return getIndirectByValue(Ty); 9995 } 9996 9997 // Treat an enum type as its underlying type. 9998 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 9999 Ty = EnumTy->getDecl()->getIntegerType(); 10000 10001 auto SizeInRegs = llvm::alignTo(getContext().getTypeSize(Ty), 32) / 32; 10002 10003 if (isAggregateTypeForABI(Ty)) { 10004 // Structures with flexible arrays are always indirect. 10005 if (RT && RT->getDecl()->hasFlexibleArrayMember()) 10006 return getIndirectByValue(Ty); 10007 10008 // Ignore empty structs/unions. 10009 if (isEmptyRecord(getContext(), Ty, true)) 10010 return ABIArgInfo::getIgnore(); 10011 10012 llvm::LLVMContext &LLVMContext = getVMContext(); 10013 10014 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext); 10015 SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32); 10016 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements); 10017 10018 return FreeRegs >= SizeInRegs ? 10019 ABIArgInfo::getDirectInReg(Result) : 10020 ABIArgInfo::getDirect(Result, 0, nullptr, false); 10021 } 10022 10023 if (const auto *EIT = Ty->getAs<BitIntType>()) 10024 if (EIT->getNumBits() > 64) 10025 return getIndirectByValue(Ty); 10026 10027 return isPromotableIntegerTypeForABI(Ty) 10028 ? (FreeRegs >= SizeInRegs ? ABIArgInfo::getExtendInReg(Ty) 10029 : ABIArgInfo::getExtend(Ty)) 10030 : (FreeRegs >= SizeInRegs ? ABIArgInfo::getDirectInReg() 10031 : ABIArgInfo::getDirect()); 10032 } 10033 10034 ABIArgInfo ARCABIInfo::classifyReturnType(QualType RetTy) const { 10035 if (RetTy->isAnyComplexType()) 10036 return ABIArgInfo::getDirectInReg(); 10037 10038 // Arguments of size > 4 registers are indirect. 10039 auto RetSize = llvm::alignTo(getContext().getTypeSize(RetTy), 32) / 32; 10040 if (RetSize > 4) 10041 return getIndirectByRef(RetTy, /*HasFreeRegs*/ true); 10042 10043 return DefaultABIInfo::classifyReturnType(RetTy); 10044 } 10045 10046 } // End anonymous namespace. 10047 10048 //===----------------------------------------------------------------------===// 10049 // XCore ABI Implementation 10050 //===----------------------------------------------------------------------===// 10051 10052 namespace { 10053 10054 /// A SmallStringEnc instance is used to build up the TypeString by passing 10055 /// it by reference between functions that append to it. 10056 typedef llvm::SmallString<128> SmallStringEnc; 10057 10058 /// TypeStringCache caches the meta encodings of Types. 10059 /// 10060 /// The reason for caching TypeStrings is two fold: 10061 /// 1. To cache a type's encoding for later uses; 10062 /// 2. As a means to break recursive member type inclusion. 10063 /// 10064 /// A cache Entry can have a Status of: 10065 /// NonRecursive: The type encoding is not recursive; 10066 /// Recursive: The type encoding is recursive; 10067 /// Incomplete: An incomplete TypeString; 10068 /// IncompleteUsed: An incomplete TypeString that has been used in a 10069 /// Recursive type encoding. 10070 /// 10071 /// A NonRecursive entry will have all of its sub-members expanded as fully 10072 /// as possible. Whilst it may contain types which are recursive, the type 10073 /// itself is not recursive and thus its encoding may be safely used whenever 10074 /// the type is encountered. 10075 /// 10076 /// A Recursive entry will have all of its sub-members expanded as fully as 10077 /// possible. The type itself is recursive and it may contain other types which 10078 /// are recursive. The Recursive encoding must not be used during the expansion 10079 /// of a recursive type's recursive branch. For simplicity the code uses 10080 /// IncompleteCount to reject all usage of Recursive encodings for member types. 10081 /// 10082 /// An Incomplete entry is always a RecordType and only encodes its 10083 /// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and 10084 /// are placed into the cache during type expansion as a means to identify and 10085 /// handle recursive inclusion of types as sub-members. If there is recursion 10086 /// the entry becomes IncompleteUsed. 10087 /// 10088 /// During the expansion of a RecordType's members: 10089 /// 10090 /// If the cache contains a NonRecursive encoding for the member type, the 10091 /// cached encoding is used; 10092 /// 10093 /// If the cache contains a Recursive encoding for the member type, the 10094 /// cached encoding is 'Swapped' out, as it may be incorrect, and... 10095 /// 10096 /// If the member is a RecordType, an Incomplete encoding is placed into the 10097 /// cache to break potential recursive inclusion of itself as a sub-member; 10098 /// 10099 /// Once a member RecordType has been expanded, its temporary incomplete 10100 /// entry is removed from the cache. If a Recursive encoding was swapped out 10101 /// it is swapped back in; 10102 /// 10103 /// If an incomplete entry is used to expand a sub-member, the incomplete 10104 /// entry is marked as IncompleteUsed. The cache keeps count of how many 10105 /// IncompleteUsed entries it currently contains in IncompleteUsedCount; 10106 /// 10107 /// If a member's encoding is found to be a NonRecursive or Recursive viz: 10108 /// IncompleteUsedCount==0, the member's encoding is added to the cache. 10109 /// Else the member is part of a recursive type and thus the recursion has 10110 /// been exited too soon for the encoding to be correct for the member. 10111 /// 10112 class TypeStringCache { 10113 enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed}; 10114 struct Entry { 10115 std::string Str; // The encoded TypeString for the type. 10116 enum Status State; // Information about the encoding in 'Str'. 10117 std::string Swapped; // A temporary place holder for a Recursive encoding 10118 // during the expansion of RecordType's members. 10119 }; 10120 std::map<const IdentifierInfo *, struct Entry> Map; 10121 unsigned IncompleteCount; // Number of Incomplete entries in the Map. 10122 unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map. 10123 public: 10124 TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {} 10125 void addIncomplete(const IdentifierInfo *ID, std::string StubEnc); 10126 bool removeIncomplete(const IdentifierInfo *ID); 10127 void addIfComplete(const IdentifierInfo *ID, StringRef Str, 10128 bool IsRecursive); 10129 StringRef lookupStr(const IdentifierInfo *ID); 10130 }; 10131 10132 /// TypeString encodings for enum & union fields must be order. 10133 /// FieldEncoding is a helper for this ordering process. 10134 class FieldEncoding { 10135 bool HasName; 10136 std::string Enc; 10137 public: 10138 FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {} 10139 StringRef str() { return Enc; } 10140 bool operator<(const FieldEncoding &rhs) const { 10141 if (HasName != rhs.HasName) return HasName; 10142 return Enc < rhs.Enc; 10143 } 10144 }; 10145 10146 class XCoreABIInfo : public DefaultABIInfo { 10147 public: 10148 XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {} 10149 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 10150 QualType Ty) const override; 10151 }; 10152 10153 class XCoreTargetCodeGenInfo : public TargetCodeGenInfo { 10154 mutable TypeStringCache TSC; 10155 void emitTargetMD(const Decl *D, llvm::GlobalValue *GV, 10156 const CodeGen::CodeGenModule &M) const; 10157 10158 public: 10159 XCoreTargetCodeGenInfo(CodeGenTypes &CGT) 10160 : TargetCodeGenInfo(std::make_unique<XCoreABIInfo>(CGT)) {} 10161 void emitTargetMetadata(CodeGen::CodeGenModule &CGM, 10162 const llvm::MapVector<GlobalDecl, StringRef> 10163 &MangledDeclNames) const override; 10164 }; 10165 10166 } // End anonymous namespace. 10167 10168 // TODO: this implementation is likely now redundant with the default 10169 // EmitVAArg. 10170 Address XCoreABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 10171 QualType Ty) const { 10172 CGBuilderTy &Builder = CGF.Builder; 10173 10174 // Get the VAList. 10175 CharUnits SlotSize = CharUnits::fromQuantity(4); 10176 Address AP = Address(Builder.CreateLoad(VAListAddr), 10177 getVAListElementType(CGF), SlotSize); 10178 10179 // Handle the argument. 10180 ABIArgInfo AI = classifyArgumentType(Ty); 10181 CharUnits TypeAlign = getContext().getTypeAlignInChars(Ty); 10182 llvm::Type *ArgTy = CGT.ConvertType(Ty); 10183 if (AI.canHaveCoerceToType() && !AI.getCoerceToType()) 10184 AI.setCoerceToType(ArgTy); 10185 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy); 10186 10187 Address Val = Address::invalid(); 10188 CharUnits ArgSize = CharUnits::Zero(); 10189 switch (AI.getKind()) { 10190 case ABIArgInfo::Expand: 10191 case ABIArgInfo::CoerceAndExpand: 10192 case ABIArgInfo::InAlloca: 10193 llvm_unreachable("Unsupported ABI kind for va_arg"); 10194 case ABIArgInfo::Ignore: 10195 Val = Address(llvm::UndefValue::get(ArgPtrTy), ArgTy, TypeAlign); 10196 ArgSize = CharUnits::Zero(); 10197 break; 10198 case ABIArgInfo::Extend: 10199 case ABIArgInfo::Direct: 10200 Val = Builder.CreateElementBitCast(AP, ArgTy); 10201 ArgSize = CharUnits::fromQuantity( 10202 getDataLayout().getTypeAllocSize(AI.getCoerceToType())); 10203 ArgSize = ArgSize.alignTo(SlotSize); 10204 break; 10205 case ABIArgInfo::Indirect: 10206 case ABIArgInfo::IndirectAliased: 10207 Val = Builder.CreateElementBitCast(AP, ArgPtrTy); 10208 Val = Address(Builder.CreateLoad(Val), ArgTy, TypeAlign); 10209 ArgSize = SlotSize; 10210 break; 10211 } 10212 10213 // Increment the VAList. 10214 if (!ArgSize.isZero()) { 10215 Address APN = Builder.CreateConstInBoundsByteGEP(AP, ArgSize); 10216 Builder.CreateStore(APN.getPointer(), VAListAddr); 10217 } 10218 10219 return Val; 10220 } 10221 10222 /// During the expansion of a RecordType, an incomplete TypeString is placed 10223 /// into the cache as a means to identify and break recursion. 10224 /// If there is a Recursive encoding in the cache, it is swapped out and will 10225 /// be reinserted by removeIncomplete(). 10226 /// All other types of encoding should have been used rather than arriving here. 10227 void TypeStringCache::addIncomplete(const IdentifierInfo *ID, 10228 std::string StubEnc) { 10229 if (!ID) 10230 return; 10231 Entry &E = Map[ID]; 10232 assert( (E.Str.empty() || E.State == Recursive) && 10233 "Incorrectly use of addIncomplete"); 10234 assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()"); 10235 E.Swapped.swap(E.Str); // swap out the Recursive 10236 E.Str.swap(StubEnc); 10237 E.State = Incomplete; 10238 ++IncompleteCount; 10239 } 10240 10241 /// Once the RecordType has been expanded, the temporary incomplete TypeString 10242 /// must be removed from the cache. 10243 /// If a Recursive was swapped out by addIncomplete(), it will be replaced. 10244 /// Returns true if the RecordType was defined recursively. 10245 bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) { 10246 if (!ID) 10247 return false; 10248 auto I = Map.find(ID); 10249 assert(I != Map.end() && "Entry not present"); 10250 Entry &E = I->second; 10251 assert( (E.State == Incomplete || 10252 E.State == IncompleteUsed) && 10253 "Entry must be an incomplete type"); 10254 bool IsRecursive = false; 10255 if (E.State == IncompleteUsed) { 10256 // We made use of our Incomplete encoding, thus we are recursive. 10257 IsRecursive = true; 10258 --IncompleteUsedCount; 10259 } 10260 if (E.Swapped.empty()) 10261 Map.erase(I); 10262 else { 10263 // Swap the Recursive back. 10264 E.Swapped.swap(E.Str); 10265 E.Swapped.clear(); 10266 E.State = Recursive; 10267 } 10268 --IncompleteCount; 10269 return IsRecursive; 10270 } 10271 10272 /// Add the encoded TypeString to the cache only if it is NonRecursive or 10273 /// Recursive (viz: all sub-members were expanded as fully as possible). 10274 void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str, 10275 bool IsRecursive) { 10276 if (!ID || IncompleteUsedCount) 10277 return; // No key or it is is an incomplete sub-type so don't add. 10278 Entry &E = Map[ID]; 10279 if (IsRecursive && !E.Str.empty()) { 10280 assert(E.State==Recursive && E.Str.size() == Str.size() && 10281 "This is not the same Recursive entry"); 10282 // The parent container was not recursive after all, so we could have used 10283 // this Recursive sub-member entry after all, but we assumed the worse when 10284 // we started viz: IncompleteCount!=0. 10285 return; 10286 } 10287 assert(E.Str.empty() && "Entry already present"); 10288 E.Str = Str.str(); 10289 E.State = IsRecursive? Recursive : NonRecursive; 10290 } 10291 10292 /// Return a cached TypeString encoding for the ID. If there isn't one, or we 10293 /// are recursively expanding a type (IncompleteCount != 0) and the cached 10294 /// encoding is Recursive, return an empty StringRef. 10295 StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) { 10296 if (!ID) 10297 return StringRef(); // We have no key. 10298 auto I = Map.find(ID); 10299 if (I == Map.end()) 10300 return StringRef(); // We have no encoding. 10301 Entry &E = I->second; 10302 if (E.State == Recursive && IncompleteCount) 10303 return StringRef(); // We don't use Recursive encodings for member types. 10304 10305 if (E.State == Incomplete) { 10306 // The incomplete type is being used to break out of recursion. 10307 E.State = IncompleteUsed; 10308 ++IncompleteUsedCount; 10309 } 10310 return E.Str; 10311 } 10312 10313 /// The XCore ABI includes a type information section that communicates symbol 10314 /// type information to the linker. The linker uses this information to verify 10315 /// safety/correctness of things such as array bound and pointers et al. 10316 /// The ABI only requires C (and XC) language modules to emit TypeStrings. 10317 /// This type information (TypeString) is emitted into meta data for all global 10318 /// symbols: definitions, declarations, functions & variables. 10319 /// 10320 /// The TypeString carries type, qualifier, name, size & value details. 10321 /// Please see 'Tools Development Guide' section 2.16.2 for format details: 10322 /// https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf 10323 /// The output is tested by test/CodeGen/xcore-stringtype.c. 10324 /// 10325 static bool getTypeString(SmallStringEnc &Enc, const Decl *D, 10326 const CodeGen::CodeGenModule &CGM, 10327 TypeStringCache &TSC); 10328 10329 /// XCore uses emitTargetMD to emit TypeString metadata for global symbols. 10330 void XCoreTargetCodeGenInfo::emitTargetMD( 10331 const Decl *D, llvm::GlobalValue *GV, 10332 const CodeGen::CodeGenModule &CGM) const { 10333 SmallStringEnc Enc; 10334 if (getTypeString(Enc, D, CGM, TSC)) { 10335 llvm::LLVMContext &Ctx = CGM.getModule().getContext(); 10336 llvm::Metadata *MDVals[] = {llvm::ConstantAsMetadata::get(GV), 10337 llvm::MDString::get(Ctx, Enc.str())}; 10338 llvm::NamedMDNode *MD = 10339 CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings"); 10340 MD->addOperand(llvm::MDNode::get(Ctx, MDVals)); 10341 } 10342 } 10343 10344 void XCoreTargetCodeGenInfo::emitTargetMetadata( 10345 CodeGen::CodeGenModule &CGM, 10346 const llvm::MapVector<GlobalDecl, StringRef> &MangledDeclNames) const { 10347 // Warning, new MangledDeclNames may be appended within this loop. 10348 // We rely on MapVector insertions adding new elements to the end 10349 // of the container. 10350 for (unsigned I = 0; I != MangledDeclNames.size(); ++I) { 10351 auto Val = *(MangledDeclNames.begin() + I); 10352 llvm::GlobalValue *GV = CGM.GetGlobalValue(Val.second); 10353 if (GV) { 10354 const Decl *D = Val.first.getDecl()->getMostRecentDecl(); 10355 emitTargetMD(D, GV, CGM); 10356 } 10357 } 10358 } 10359 10360 //===----------------------------------------------------------------------===// 10361 // Base ABI and target codegen info implementation common between SPIR and 10362 // SPIR-V. 10363 //===----------------------------------------------------------------------===// 10364 10365 namespace { 10366 class CommonSPIRABIInfo : public DefaultABIInfo { 10367 public: 10368 CommonSPIRABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) { setCCs(); } 10369 10370 private: 10371 void setCCs(); 10372 }; 10373 10374 class SPIRVABIInfo : public CommonSPIRABIInfo { 10375 public: 10376 SPIRVABIInfo(CodeGenTypes &CGT) : CommonSPIRABIInfo(CGT) {} 10377 void computeInfo(CGFunctionInfo &FI) const override; 10378 10379 private: 10380 ABIArgInfo classifyKernelArgumentType(QualType Ty) const; 10381 }; 10382 } // end anonymous namespace 10383 namespace { 10384 class CommonSPIRTargetCodeGenInfo : public TargetCodeGenInfo { 10385 public: 10386 CommonSPIRTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT) 10387 : TargetCodeGenInfo(std::make_unique<CommonSPIRABIInfo>(CGT)) {} 10388 CommonSPIRTargetCodeGenInfo(std::unique_ptr<ABIInfo> ABIInfo) 10389 : TargetCodeGenInfo(std::move(ABIInfo)) {} 10390 10391 LangAS getASTAllocaAddressSpace() const override { 10392 return getLangASFromTargetAS( 10393 getABIInfo().getDataLayout().getAllocaAddrSpace()); 10394 } 10395 10396 unsigned getOpenCLKernelCallingConv() const override; 10397 }; 10398 class SPIRVTargetCodeGenInfo : public CommonSPIRTargetCodeGenInfo { 10399 public: 10400 SPIRVTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT) 10401 : CommonSPIRTargetCodeGenInfo(std::make_unique<SPIRVABIInfo>(CGT)) {} 10402 void setCUDAKernelCallingConvention(const FunctionType *&FT) const override; 10403 }; 10404 } // End anonymous namespace. 10405 10406 void CommonSPIRABIInfo::setCCs() { 10407 assert(getRuntimeCC() == llvm::CallingConv::C); 10408 RuntimeCC = llvm::CallingConv::SPIR_FUNC; 10409 } 10410 10411 ABIArgInfo SPIRVABIInfo::classifyKernelArgumentType(QualType Ty) const { 10412 if (getContext().getLangOpts().CUDAIsDevice) { 10413 // Coerce pointer arguments with default address space to CrossWorkGroup 10414 // pointers for HIPSPV/CUDASPV. When the language mode is HIP/CUDA, the 10415 // SPIRTargetInfo maps cuda_device to SPIR-V's CrossWorkGroup address space. 10416 llvm::Type *LTy = CGT.ConvertType(Ty); 10417 auto DefaultAS = getContext().getTargetAddressSpace(LangAS::Default); 10418 auto GlobalAS = getContext().getTargetAddressSpace(LangAS::cuda_device); 10419 auto *PtrTy = llvm::dyn_cast<llvm::PointerType>(LTy); 10420 if (PtrTy && PtrTy->getAddressSpace() == DefaultAS) { 10421 LTy = llvm::PointerType::getWithSamePointeeType(PtrTy, GlobalAS); 10422 return ABIArgInfo::getDirect(LTy, 0, nullptr, false); 10423 } 10424 } 10425 return classifyArgumentType(Ty); 10426 } 10427 10428 void SPIRVABIInfo::computeInfo(CGFunctionInfo &FI) const { 10429 // The logic is same as in DefaultABIInfo with an exception on the kernel 10430 // arguments handling. 10431 llvm::CallingConv::ID CC = FI.getCallingConvention(); 10432 10433 if (!getCXXABI().classifyReturnType(FI)) 10434 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 10435 10436 for (auto &I : FI.arguments()) { 10437 if (CC == llvm::CallingConv::SPIR_KERNEL) { 10438 I.info = classifyKernelArgumentType(I.type); 10439 } else { 10440 I.info = classifyArgumentType(I.type); 10441 } 10442 } 10443 } 10444 10445 namespace clang { 10446 namespace CodeGen { 10447 void computeSPIRKernelABIInfo(CodeGenModule &CGM, CGFunctionInfo &FI) { 10448 if (CGM.getTarget().getTriple().isSPIRV()) 10449 SPIRVABIInfo(CGM.getTypes()).computeInfo(FI); 10450 else 10451 CommonSPIRABIInfo(CGM.getTypes()).computeInfo(FI); 10452 } 10453 } 10454 } 10455 10456 unsigned CommonSPIRTargetCodeGenInfo::getOpenCLKernelCallingConv() const { 10457 return llvm::CallingConv::SPIR_KERNEL; 10458 } 10459 10460 void SPIRVTargetCodeGenInfo::setCUDAKernelCallingConvention( 10461 const FunctionType *&FT) const { 10462 // Convert HIP kernels to SPIR-V kernels. 10463 if (getABIInfo().getContext().getLangOpts().HIP) { 10464 FT = getABIInfo().getContext().adjustFunctionType( 10465 FT, FT->getExtInfo().withCallingConv(CC_OpenCLKernel)); 10466 return; 10467 } 10468 } 10469 10470 static bool appendType(SmallStringEnc &Enc, QualType QType, 10471 const CodeGen::CodeGenModule &CGM, 10472 TypeStringCache &TSC); 10473 10474 /// Helper function for appendRecordType(). 10475 /// Builds a SmallVector containing the encoded field types in declaration 10476 /// order. 10477 static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE, 10478 const RecordDecl *RD, 10479 const CodeGen::CodeGenModule &CGM, 10480 TypeStringCache &TSC) { 10481 for (const auto *Field : RD->fields()) { 10482 SmallStringEnc Enc; 10483 Enc += "m("; 10484 Enc += Field->getName(); 10485 Enc += "){"; 10486 if (Field->isBitField()) { 10487 Enc += "b("; 10488 llvm::raw_svector_ostream OS(Enc); 10489 OS << Field->getBitWidthValue(CGM.getContext()); 10490 Enc += ':'; 10491 } 10492 if (!appendType(Enc, Field->getType(), CGM, TSC)) 10493 return false; 10494 if (Field->isBitField()) 10495 Enc += ')'; 10496 Enc += '}'; 10497 FE.emplace_back(!Field->getName().empty(), Enc); 10498 } 10499 return true; 10500 } 10501 10502 /// Appends structure and union types to Enc and adds encoding to cache. 10503 /// Recursively calls appendType (via extractFieldType) for each field. 10504 /// Union types have their fields ordered according to the ABI. 10505 static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT, 10506 const CodeGen::CodeGenModule &CGM, 10507 TypeStringCache &TSC, const IdentifierInfo *ID) { 10508 // Append the cached TypeString if we have one. 10509 StringRef TypeString = TSC.lookupStr(ID); 10510 if (!TypeString.empty()) { 10511 Enc += TypeString; 10512 return true; 10513 } 10514 10515 // Start to emit an incomplete TypeString. 10516 size_t Start = Enc.size(); 10517 Enc += (RT->isUnionType()? 'u' : 's'); 10518 Enc += '('; 10519 if (ID) 10520 Enc += ID->getName(); 10521 Enc += "){"; 10522 10523 // We collect all encoded fields and order as necessary. 10524 bool IsRecursive = false; 10525 const RecordDecl *RD = RT->getDecl()->getDefinition(); 10526 if (RD && !RD->field_empty()) { 10527 // An incomplete TypeString stub is placed in the cache for this RecordType 10528 // so that recursive calls to this RecordType will use it whilst building a 10529 // complete TypeString for this RecordType. 10530 SmallVector<FieldEncoding, 16> FE; 10531 std::string StubEnc(Enc.substr(Start).str()); 10532 StubEnc += '}'; // StubEnc now holds a valid incomplete TypeString. 10533 TSC.addIncomplete(ID, std::move(StubEnc)); 10534 if (!extractFieldType(FE, RD, CGM, TSC)) { 10535 (void) TSC.removeIncomplete(ID); 10536 return false; 10537 } 10538 IsRecursive = TSC.removeIncomplete(ID); 10539 // The ABI requires unions to be sorted but not structures. 10540 // See FieldEncoding::operator< for sort algorithm. 10541 if (RT->isUnionType()) 10542 llvm::sort(FE); 10543 // We can now complete the TypeString. 10544 unsigned E = FE.size(); 10545 for (unsigned I = 0; I != E; ++I) { 10546 if (I) 10547 Enc += ','; 10548 Enc += FE[I].str(); 10549 } 10550 } 10551 Enc += '}'; 10552 TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive); 10553 return true; 10554 } 10555 10556 /// Appends enum types to Enc and adds the encoding to the cache. 10557 static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET, 10558 TypeStringCache &TSC, 10559 const IdentifierInfo *ID) { 10560 // Append the cached TypeString if we have one. 10561 StringRef TypeString = TSC.lookupStr(ID); 10562 if (!TypeString.empty()) { 10563 Enc += TypeString; 10564 return true; 10565 } 10566 10567 size_t Start = Enc.size(); 10568 Enc += "e("; 10569 if (ID) 10570 Enc += ID->getName(); 10571 Enc += "){"; 10572 10573 // We collect all encoded enumerations and order them alphanumerically. 10574 if (const EnumDecl *ED = ET->getDecl()->getDefinition()) { 10575 SmallVector<FieldEncoding, 16> FE; 10576 for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E; 10577 ++I) { 10578 SmallStringEnc EnumEnc; 10579 EnumEnc += "m("; 10580 EnumEnc += I->getName(); 10581 EnumEnc += "){"; 10582 I->getInitVal().toString(EnumEnc); 10583 EnumEnc += '}'; 10584 FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc)); 10585 } 10586 llvm::sort(FE); 10587 unsigned E = FE.size(); 10588 for (unsigned I = 0; I != E; ++I) { 10589 if (I) 10590 Enc += ','; 10591 Enc += FE[I].str(); 10592 } 10593 } 10594 Enc += '}'; 10595 TSC.addIfComplete(ID, Enc.substr(Start), false); 10596 return true; 10597 } 10598 10599 /// Appends type's qualifier to Enc. 10600 /// This is done prior to appending the type's encoding. 10601 static void appendQualifier(SmallStringEnc &Enc, QualType QT) { 10602 // Qualifiers are emitted in alphabetical order. 10603 static const char *const Table[]={"","c:","r:","cr:","v:","cv:","rv:","crv:"}; 10604 int Lookup = 0; 10605 if (QT.isConstQualified()) 10606 Lookup += 1<<0; 10607 if (QT.isRestrictQualified()) 10608 Lookup += 1<<1; 10609 if (QT.isVolatileQualified()) 10610 Lookup += 1<<2; 10611 Enc += Table[Lookup]; 10612 } 10613 10614 /// Appends built-in types to Enc. 10615 static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) { 10616 const char *EncType; 10617 switch (BT->getKind()) { 10618 case BuiltinType::Void: 10619 EncType = "0"; 10620 break; 10621 case BuiltinType::Bool: 10622 EncType = "b"; 10623 break; 10624 case BuiltinType::Char_U: 10625 EncType = "uc"; 10626 break; 10627 case BuiltinType::UChar: 10628 EncType = "uc"; 10629 break; 10630 case BuiltinType::SChar: 10631 EncType = "sc"; 10632 break; 10633 case BuiltinType::UShort: 10634 EncType = "us"; 10635 break; 10636 case BuiltinType::Short: 10637 EncType = "ss"; 10638 break; 10639 case BuiltinType::UInt: 10640 EncType = "ui"; 10641 break; 10642 case BuiltinType::Int: 10643 EncType = "si"; 10644 break; 10645 case BuiltinType::ULong: 10646 EncType = "ul"; 10647 break; 10648 case BuiltinType::Long: 10649 EncType = "sl"; 10650 break; 10651 case BuiltinType::ULongLong: 10652 EncType = "ull"; 10653 break; 10654 case BuiltinType::LongLong: 10655 EncType = "sll"; 10656 break; 10657 case BuiltinType::Float: 10658 EncType = "ft"; 10659 break; 10660 case BuiltinType::Double: 10661 EncType = "d"; 10662 break; 10663 case BuiltinType::LongDouble: 10664 EncType = "ld"; 10665 break; 10666 default: 10667 return false; 10668 } 10669 Enc += EncType; 10670 return true; 10671 } 10672 10673 /// Appends a pointer encoding to Enc before calling appendType for the pointee. 10674 static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT, 10675 const CodeGen::CodeGenModule &CGM, 10676 TypeStringCache &TSC) { 10677 Enc += "p("; 10678 if (!appendType(Enc, PT->getPointeeType(), CGM, TSC)) 10679 return false; 10680 Enc += ')'; 10681 return true; 10682 } 10683 10684 /// Appends array encoding to Enc before calling appendType for the element. 10685 static bool appendArrayType(SmallStringEnc &Enc, QualType QT, 10686 const ArrayType *AT, 10687 const CodeGen::CodeGenModule &CGM, 10688 TypeStringCache &TSC, StringRef NoSizeEnc) { 10689 if (AT->getSizeModifier() != ArrayType::Normal) 10690 return false; 10691 Enc += "a("; 10692 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) 10693 CAT->getSize().toStringUnsigned(Enc); 10694 else 10695 Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "". 10696 Enc += ':'; 10697 // The Qualifiers should be attached to the type rather than the array. 10698 appendQualifier(Enc, QT); 10699 if (!appendType(Enc, AT->getElementType(), CGM, TSC)) 10700 return false; 10701 Enc += ')'; 10702 return true; 10703 } 10704 10705 /// Appends a function encoding to Enc, calling appendType for the return type 10706 /// and the arguments. 10707 static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT, 10708 const CodeGen::CodeGenModule &CGM, 10709 TypeStringCache &TSC) { 10710 Enc += "f{"; 10711 if (!appendType(Enc, FT->getReturnType(), CGM, TSC)) 10712 return false; 10713 Enc += "}("; 10714 if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) { 10715 // N.B. we are only interested in the adjusted param types. 10716 auto I = FPT->param_type_begin(); 10717 auto E = FPT->param_type_end(); 10718 if (I != E) { 10719 do { 10720 if (!appendType(Enc, *I, CGM, TSC)) 10721 return false; 10722 ++I; 10723 if (I != E) 10724 Enc += ','; 10725 } while (I != E); 10726 if (FPT->isVariadic()) 10727 Enc += ",va"; 10728 } else { 10729 if (FPT->isVariadic()) 10730 Enc += "va"; 10731 else 10732 Enc += '0'; 10733 } 10734 } 10735 Enc += ')'; 10736 return true; 10737 } 10738 10739 /// Handles the type's qualifier before dispatching a call to handle specific 10740 /// type encodings. 10741 static bool appendType(SmallStringEnc &Enc, QualType QType, 10742 const CodeGen::CodeGenModule &CGM, 10743 TypeStringCache &TSC) { 10744 10745 QualType QT = QType.getCanonicalType(); 10746 10747 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) 10748 // The Qualifiers should be attached to the type rather than the array. 10749 // Thus we don't call appendQualifier() here. 10750 return appendArrayType(Enc, QT, AT, CGM, TSC, ""); 10751 10752 appendQualifier(Enc, QT); 10753 10754 if (const BuiltinType *BT = QT->getAs<BuiltinType>()) 10755 return appendBuiltinType(Enc, BT); 10756 10757 if (const PointerType *PT = QT->getAs<PointerType>()) 10758 return appendPointerType(Enc, PT, CGM, TSC); 10759 10760 if (const EnumType *ET = QT->getAs<EnumType>()) 10761 return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier()); 10762 10763 if (const RecordType *RT = QT->getAsStructureType()) 10764 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier()); 10765 10766 if (const RecordType *RT = QT->getAsUnionType()) 10767 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier()); 10768 10769 if (const FunctionType *FT = QT->getAs<FunctionType>()) 10770 return appendFunctionType(Enc, FT, CGM, TSC); 10771 10772 return false; 10773 } 10774 10775 static bool getTypeString(SmallStringEnc &Enc, const Decl *D, 10776 const CodeGen::CodeGenModule &CGM, 10777 TypeStringCache &TSC) { 10778 if (!D) 10779 return false; 10780 10781 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 10782 if (FD->getLanguageLinkage() != CLanguageLinkage) 10783 return false; 10784 return appendType(Enc, FD->getType(), CGM, TSC); 10785 } 10786 10787 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 10788 if (VD->getLanguageLinkage() != CLanguageLinkage) 10789 return false; 10790 QualType QT = VD->getType().getCanonicalType(); 10791 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) { 10792 // Global ArrayTypes are given a size of '*' if the size is unknown. 10793 // The Qualifiers should be attached to the type rather than the array. 10794 // Thus we don't call appendQualifier() here. 10795 return appendArrayType(Enc, QT, AT, CGM, TSC, "*"); 10796 } 10797 return appendType(Enc, QT, CGM, TSC); 10798 } 10799 return false; 10800 } 10801 10802 //===----------------------------------------------------------------------===// 10803 // RISCV ABI Implementation 10804 //===----------------------------------------------------------------------===// 10805 10806 namespace { 10807 class RISCVABIInfo : public DefaultABIInfo { 10808 private: 10809 // Size of the integer ('x') registers in bits. 10810 unsigned XLen; 10811 // Size of the floating point ('f') registers in bits. Note that the target 10812 // ISA might have a wider FLen than the selected ABI (e.g. an RV32IF target 10813 // with soft float ABI has FLen==0). 10814 unsigned FLen; 10815 static const int NumArgGPRs = 8; 10816 static const int NumArgFPRs = 8; 10817 bool detectFPCCEligibleStructHelper(QualType Ty, CharUnits CurOff, 10818 llvm::Type *&Field1Ty, 10819 CharUnits &Field1Off, 10820 llvm::Type *&Field2Ty, 10821 CharUnits &Field2Off) const; 10822 10823 public: 10824 RISCVABIInfo(CodeGen::CodeGenTypes &CGT, unsigned XLen, unsigned FLen) 10825 : DefaultABIInfo(CGT), XLen(XLen), FLen(FLen) {} 10826 10827 // DefaultABIInfo's classifyReturnType and classifyArgumentType are 10828 // non-virtual, but computeInfo is virtual, so we overload it. 10829 void computeInfo(CGFunctionInfo &FI) const override; 10830 10831 ABIArgInfo classifyArgumentType(QualType Ty, bool IsFixed, int &ArgGPRsLeft, 10832 int &ArgFPRsLeft) const; 10833 ABIArgInfo classifyReturnType(QualType RetTy) const; 10834 10835 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 10836 QualType Ty) const override; 10837 10838 ABIArgInfo extendType(QualType Ty) const; 10839 10840 bool detectFPCCEligibleStruct(QualType Ty, llvm::Type *&Field1Ty, 10841 CharUnits &Field1Off, llvm::Type *&Field2Ty, 10842 CharUnits &Field2Off, int &NeededArgGPRs, 10843 int &NeededArgFPRs) const; 10844 ABIArgInfo coerceAndExpandFPCCEligibleStruct(llvm::Type *Field1Ty, 10845 CharUnits Field1Off, 10846 llvm::Type *Field2Ty, 10847 CharUnits Field2Off) const; 10848 }; 10849 } // end anonymous namespace 10850 10851 void RISCVABIInfo::computeInfo(CGFunctionInfo &FI) const { 10852 QualType RetTy = FI.getReturnType(); 10853 if (!getCXXABI().classifyReturnType(FI)) 10854 FI.getReturnInfo() = classifyReturnType(RetTy); 10855 10856 // IsRetIndirect is true if classifyArgumentType indicated the value should 10857 // be passed indirect, or if the type size is a scalar greater than 2*XLen 10858 // and not a complex type with elements <= FLen. e.g. fp128 is passed direct 10859 // in LLVM IR, relying on the backend lowering code to rewrite the argument 10860 // list and pass indirectly on RV32. 10861 bool IsRetIndirect = FI.getReturnInfo().getKind() == ABIArgInfo::Indirect; 10862 if (!IsRetIndirect && RetTy->isScalarType() && 10863 getContext().getTypeSize(RetTy) > (2 * XLen)) { 10864 if (RetTy->isComplexType() && FLen) { 10865 QualType EltTy = RetTy->castAs<ComplexType>()->getElementType(); 10866 IsRetIndirect = getContext().getTypeSize(EltTy) > FLen; 10867 } else { 10868 // This is a normal scalar > 2*XLen, such as fp128 on RV32. 10869 IsRetIndirect = true; 10870 } 10871 } 10872 10873 // We must track the number of GPRs used in order to conform to the RISC-V 10874 // ABI, as integer scalars passed in registers should have signext/zeroext 10875 // when promoted, but are anyext if passed on the stack. As GPR usage is 10876 // different for variadic arguments, we must also track whether we are 10877 // examining a vararg or not. 10878 int ArgGPRsLeft = IsRetIndirect ? NumArgGPRs - 1 : NumArgGPRs; 10879 int ArgFPRsLeft = FLen ? NumArgFPRs : 0; 10880 int NumFixedArgs = FI.getNumRequiredArgs(); 10881 10882 int ArgNum = 0; 10883 for (auto &ArgInfo : FI.arguments()) { 10884 bool IsFixed = ArgNum < NumFixedArgs; 10885 ArgInfo.info = 10886 classifyArgumentType(ArgInfo.type, IsFixed, ArgGPRsLeft, ArgFPRsLeft); 10887 ArgNum++; 10888 } 10889 } 10890 10891 // Returns true if the struct is a potential candidate for the floating point 10892 // calling convention. If this function returns true, the caller is 10893 // responsible for checking that if there is only a single field then that 10894 // field is a float. 10895 bool RISCVABIInfo::detectFPCCEligibleStructHelper(QualType Ty, CharUnits CurOff, 10896 llvm::Type *&Field1Ty, 10897 CharUnits &Field1Off, 10898 llvm::Type *&Field2Ty, 10899 CharUnits &Field2Off) const { 10900 bool IsInt = Ty->isIntegralOrEnumerationType(); 10901 bool IsFloat = Ty->isRealFloatingType(); 10902 10903 if (IsInt || IsFloat) { 10904 uint64_t Size = getContext().getTypeSize(Ty); 10905 if (IsInt && Size > XLen) 10906 return false; 10907 // Can't be eligible if larger than the FP registers. Half precision isn't 10908 // currently supported on RISC-V and the ABI hasn't been confirmed, so 10909 // default to the integer ABI in that case. 10910 if (IsFloat && (Size > FLen || Size < 32)) 10911 return false; 10912 // Can't be eligible if an integer type was already found (int+int pairs 10913 // are not eligible). 10914 if (IsInt && Field1Ty && Field1Ty->isIntegerTy()) 10915 return false; 10916 if (!Field1Ty) { 10917 Field1Ty = CGT.ConvertType(Ty); 10918 Field1Off = CurOff; 10919 return true; 10920 } 10921 if (!Field2Ty) { 10922 Field2Ty = CGT.ConvertType(Ty); 10923 Field2Off = CurOff; 10924 return true; 10925 } 10926 return false; 10927 } 10928 10929 if (auto CTy = Ty->getAs<ComplexType>()) { 10930 if (Field1Ty) 10931 return false; 10932 QualType EltTy = CTy->getElementType(); 10933 if (getContext().getTypeSize(EltTy) > FLen) 10934 return false; 10935 Field1Ty = CGT.ConvertType(EltTy); 10936 Field1Off = CurOff; 10937 Field2Ty = Field1Ty; 10938 Field2Off = Field1Off + getContext().getTypeSizeInChars(EltTy); 10939 return true; 10940 } 10941 10942 if (const ConstantArrayType *ATy = getContext().getAsConstantArrayType(Ty)) { 10943 uint64_t ArraySize = ATy->getSize().getZExtValue(); 10944 QualType EltTy = ATy->getElementType(); 10945 CharUnits EltSize = getContext().getTypeSizeInChars(EltTy); 10946 for (uint64_t i = 0; i < ArraySize; ++i) { 10947 bool Ret = detectFPCCEligibleStructHelper(EltTy, CurOff, Field1Ty, 10948 Field1Off, Field2Ty, Field2Off); 10949 if (!Ret) 10950 return false; 10951 CurOff += EltSize; 10952 } 10953 return true; 10954 } 10955 10956 if (const auto *RTy = Ty->getAs<RecordType>()) { 10957 // Structures with either a non-trivial destructor or a non-trivial 10958 // copy constructor are not eligible for the FP calling convention. 10959 if (getRecordArgABI(Ty, CGT.getCXXABI())) 10960 return false; 10961 if (isEmptyRecord(getContext(), Ty, true)) 10962 return true; 10963 const RecordDecl *RD = RTy->getDecl(); 10964 // Unions aren't eligible unless they're empty (which is caught above). 10965 if (RD->isUnion()) 10966 return false; 10967 int ZeroWidthBitFieldCount = 0; 10968 for (const FieldDecl *FD : RD->fields()) { 10969 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD); 10970 uint64_t FieldOffInBits = Layout.getFieldOffset(FD->getFieldIndex()); 10971 QualType QTy = FD->getType(); 10972 if (FD->isBitField()) { 10973 unsigned BitWidth = FD->getBitWidthValue(getContext()); 10974 // Allow a bitfield with a type greater than XLen as long as the 10975 // bitwidth is XLen or less. 10976 if (getContext().getTypeSize(QTy) > XLen && BitWidth <= XLen) 10977 QTy = getContext().getIntTypeForBitwidth(XLen, false); 10978 if (BitWidth == 0) { 10979 ZeroWidthBitFieldCount++; 10980 continue; 10981 } 10982 } 10983 10984 bool Ret = detectFPCCEligibleStructHelper( 10985 QTy, CurOff + getContext().toCharUnitsFromBits(FieldOffInBits), 10986 Field1Ty, Field1Off, Field2Ty, Field2Off); 10987 if (!Ret) 10988 return false; 10989 10990 // As a quirk of the ABI, zero-width bitfields aren't ignored for fp+fp 10991 // or int+fp structs, but are ignored for a struct with an fp field and 10992 // any number of zero-width bitfields. 10993 if (Field2Ty && ZeroWidthBitFieldCount > 0) 10994 return false; 10995 } 10996 return Field1Ty != nullptr; 10997 } 10998 10999 return false; 11000 } 11001 11002 // Determine if a struct is eligible for passing according to the floating 11003 // point calling convention (i.e., when flattened it contains a single fp 11004 // value, fp+fp, or int+fp of appropriate size). If so, NeededArgFPRs and 11005 // NeededArgGPRs are incremented appropriately. 11006 bool RISCVABIInfo::detectFPCCEligibleStruct(QualType Ty, llvm::Type *&Field1Ty, 11007 CharUnits &Field1Off, 11008 llvm::Type *&Field2Ty, 11009 CharUnits &Field2Off, 11010 int &NeededArgGPRs, 11011 int &NeededArgFPRs) const { 11012 Field1Ty = nullptr; 11013 Field2Ty = nullptr; 11014 NeededArgGPRs = 0; 11015 NeededArgFPRs = 0; 11016 bool IsCandidate = detectFPCCEligibleStructHelper( 11017 Ty, CharUnits::Zero(), Field1Ty, Field1Off, Field2Ty, Field2Off); 11018 // Not really a candidate if we have a single int but no float. 11019 if (Field1Ty && !Field2Ty && !Field1Ty->isFloatingPointTy()) 11020 return false; 11021 if (!IsCandidate) 11022 return false; 11023 if (Field1Ty && Field1Ty->isFloatingPointTy()) 11024 NeededArgFPRs++; 11025 else if (Field1Ty) 11026 NeededArgGPRs++; 11027 if (Field2Ty && Field2Ty->isFloatingPointTy()) 11028 NeededArgFPRs++; 11029 else if (Field2Ty) 11030 NeededArgGPRs++; 11031 return true; 11032 } 11033 11034 // Call getCoerceAndExpand for the two-element flattened struct described by 11035 // Field1Ty, Field1Off, Field2Ty, Field2Off. This method will create an 11036 // appropriate coerceToType and unpaddedCoerceToType. 11037 ABIArgInfo RISCVABIInfo::coerceAndExpandFPCCEligibleStruct( 11038 llvm::Type *Field1Ty, CharUnits Field1Off, llvm::Type *Field2Ty, 11039 CharUnits Field2Off) const { 11040 SmallVector<llvm::Type *, 3> CoerceElts; 11041 SmallVector<llvm::Type *, 2> UnpaddedCoerceElts; 11042 if (!Field1Off.isZero()) 11043 CoerceElts.push_back(llvm::ArrayType::get( 11044 llvm::Type::getInt8Ty(getVMContext()), Field1Off.getQuantity())); 11045 11046 CoerceElts.push_back(Field1Ty); 11047 UnpaddedCoerceElts.push_back(Field1Ty); 11048 11049 if (!Field2Ty) { 11050 return ABIArgInfo::getCoerceAndExpand( 11051 llvm::StructType::get(getVMContext(), CoerceElts, !Field1Off.isZero()), 11052 UnpaddedCoerceElts[0]); 11053 } 11054 11055 CharUnits Field2Align = 11056 CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(Field2Ty)); 11057 CharUnits Field1End = Field1Off + 11058 CharUnits::fromQuantity(getDataLayout().getTypeStoreSize(Field1Ty)); 11059 CharUnits Field2OffNoPadNoPack = Field1End.alignTo(Field2Align); 11060 11061 CharUnits Padding = CharUnits::Zero(); 11062 if (Field2Off > Field2OffNoPadNoPack) 11063 Padding = Field2Off - Field2OffNoPadNoPack; 11064 else if (Field2Off != Field2Align && Field2Off > Field1End) 11065 Padding = Field2Off - Field1End; 11066 11067 bool IsPacked = !Field2Off.isMultipleOf(Field2Align); 11068 11069 if (!Padding.isZero()) 11070 CoerceElts.push_back(llvm::ArrayType::get( 11071 llvm::Type::getInt8Ty(getVMContext()), Padding.getQuantity())); 11072 11073 CoerceElts.push_back(Field2Ty); 11074 UnpaddedCoerceElts.push_back(Field2Ty); 11075 11076 auto CoerceToType = 11077 llvm::StructType::get(getVMContext(), CoerceElts, IsPacked); 11078 auto UnpaddedCoerceToType = 11079 llvm::StructType::get(getVMContext(), UnpaddedCoerceElts, IsPacked); 11080 11081 return ABIArgInfo::getCoerceAndExpand(CoerceToType, UnpaddedCoerceToType); 11082 } 11083 11084 ABIArgInfo RISCVABIInfo::classifyArgumentType(QualType Ty, bool IsFixed, 11085 int &ArgGPRsLeft, 11086 int &ArgFPRsLeft) const { 11087 assert(ArgGPRsLeft <= NumArgGPRs && "Arg GPR tracking underflow"); 11088 Ty = useFirstFieldIfTransparentUnion(Ty); 11089 11090 // Structures with either a non-trivial destructor or a non-trivial 11091 // copy constructor are always passed indirectly. 11092 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) { 11093 if (ArgGPRsLeft) 11094 ArgGPRsLeft -= 1; 11095 return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA == 11096 CGCXXABI::RAA_DirectInMemory); 11097 } 11098 11099 // Ignore empty structs/unions. 11100 if (isEmptyRecord(getContext(), Ty, true)) 11101 return ABIArgInfo::getIgnore(); 11102 11103 uint64_t Size = getContext().getTypeSize(Ty); 11104 11105 // Pass floating point values via FPRs if possible. 11106 if (IsFixed && Ty->isFloatingType() && !Ty->isComplexType() && 11107 FLen >= Size && ArgFPRsLeft) { 11108 ArgFPRsLeft--; 11109 return ABIArgInfo::getDirect(); 11110 } 11111 11112 // Complex types for the hard float ABI must be passed direct rather than 11113 // using CoerceAndExpand. 11114 if (IsFixed && Ty->isComplexType() && FLen && ArgFPRsLeft >= 2) { 11115 QualType EltTy = Ty->castAs<ComplexType>()->getElementType(); 11116 if (getContext().getTypeSize(EltTy) <= FLen) { 11117 ArgFPRsLeft -= 2; 11118 return ABIArgInfo::getDirect(); 11119 } 11120 } 11121 11122 if (IsFixed && FLen && Ty->isStructureOrClassType()) { 11123 llvm::Type *Field1Ty = nullptr; 11124 llvm::Type *Field2Ty = nullptr; 11125 CharUnits Field1Off = CharUnits::Zero(); 11126 CharUnits Field2Off = CharUnits::Zero(); 11127 int NeededArgGPRs = 0; 11128 int NeededArgFPRs = 0; 11129 bool IsCandidate = 11130 detectFPCCEligibleStruct(Ty, Field1Ty, Field1Off, Field2Ty, Field2Off, 11131 NeededArgGPRs, NeededArgFPRs); 11132 if (IsCandidate && NeededArgGPRs <= ArgGPRsLeft && 11133 NeededArgFPRs <= ArgFPRsLeft) { 11134 ArgGPRsLeft -= NeededArgGPRs; 11135 ArgFPRsLeft -= NeededArgFPRs; 11136 return coerceAndExpandFPCCEligibleStruct(Field1Ty, Field1Off, Field2Ty, 11137 Field2Off); 11138 } 11139 } 11140 11141 uint64_t NeededAlign = getContext().getTypeAlign(Ty); 11142 bool MustUseStack = false; 11143 // Determine the number of GPRs needed to pass the current argument 11144 // according to the ABI. 2*XLen-aligned varargs are passed in "aligned" 11145 // register pairs, so may consume 3 registers. 11146 int NeededArgGPRs = 1; 11147 if (!IsFixed && NeededAlign == 2 * XLen) 11148 NeededArgGPRs = 2 + (ArgGPRsLeft % 2); 11149 else if (Size > XLen && Size <= 2 * XLen) 11150 NeededArgGPRs = 2; 11151 11152 if (NeededArgGPRs > ArgGPRsLeft) { 11153 MustUseStack = true; 11154 NeededArgGPRs = ArgGPRsLeft; 11155 } 11156 11157 ArgGPRsLeft -= NeededArgGPRs; 11158 11159 if (!isAggregateTypeForABI(Ty) && !Ty->isVectorType()) { 11160 // Treat an enum type as its underlying type. 11161 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 11162 Ty = EnumTy->getDecl()->getIntegerType(); 11163 11164 // All integral types are promoted to XLen width, unless passed on the 11165 // stack. 11166 if (Size < XLen && Ty->isIntegralOrEnumerationType() && !MustUseStack) { 11167 return extendType(Ty); 11168 } 11169 11170 if (const auto *EIT = Ty->getAs<BitIntType>()) { 11171 if (EIT->getNumBits() < XLen && !MustUseStack) 11172 return extendType(Ty); 11173 if (EIT->getNumBits() > 128 || 11174 (!getContext().getTargetInfo().hasInt128Type() && 11175 EIT->getNumBits() > 64)) 11176 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 11177 } 11178 11179 return ABIArgInfo::getDirect(); 11180 } 11181 11182 // Aggregates which are <= 2*XLen will be passed in registers if possible, 11183 // so coerce to integers. 11184 if (Size <= 2 * XLen) { 11185 unsigned Alignment = getContext().getTypeAlign(Ty); 11186 11187 // Use a single XLen int if possible, 2*XLen if 2*XLen alignment is 11188 // required, and a 2-element XLen array if only XLen alignment is required. 11189 if (Size <= XLen) { 11190 return ABIArgInfo::getDirect( 11191 llvm::IntegerType::get(getVMContext(), XLen)); 11192 } else if (Alignment == 2 * XLen) { 11193 return ABIArgInfo::getDirect( 11194 llvm::IntegerType::get(getVMContext(), 2 * XLen)); 11195 } else { 11196 return ABIArgInfo::getDirect(llvm::ArrayType::get( 11197 llvm::IntegerType::get(getVMContext(), XLen), 2)); 11198 } 11199 } 11200 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 11201 } 11202 11203 ABIArgInfo RISCVABIInfo::classifyReturnType(QualType RetTy) const { 11204 if (RetTy->isVoidType()) 11205 return ABIArgInfo::getIgnore(); 11206 11207 int ArgGPRsLeft = 2; 11208 int ArgFPRsLeft = FLen ? 2 : 0; 11209 11210 // The rules for return and argument types are the same, so defer to 11211 // classifyArgumentType. 11212 return classifyArgumentType(RetTy, /*IsFixed=*/true, ArgGPRsLeft, 11213 ArgFPRsLeft); 11214 } 11215 11216 Address RISCVABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 11217 QualType Ty) const { 11218 CharUnits SlotSize = CharUnits::fromQuantity(XLen / 8); 11219 11220 // Empty records are ignored for parameter passing purposes. 11221 if (isEmptyRecord(getContext(), Ty, true)) { 11222 Address Addr = Address(CGF.Builder.CreateLoad(VAListAddr), 11223 getVAListElementType(CGF), SlotSize); 11224 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty)); 11225 return Addr; 11226 } 11227 11228 auto TInfo = getContext().getTypeInfoInChars(Ty); 11229 11230 // Arguments bigger than 2*Xlen bytes are passed indirectly. 11231 bool IsIndirect = TInfo.Width > 2 * SlotSize; 11232 11233 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TInfo, 11234 SlotSize, /*AllowHigherAlign=*/true); 11235 } 11236 11237 ABIArgInfo RISCVABIInfo::extendType(QualType Ty) const { 11238 int TySize = getContext().getTypeSize(Ty); 11239 // RV64 ABI requires unsigned 32 bit integers to be sign extended. 11240 if (XLen == 64 && Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32) 11241 return ABIArgInfo::getSignExtend(Ty); 11242 return ABIArgInfo::getExtend(Ty); 11243 } 11244 11245 namespace { 11246 class RISCVTargetCodeGenInfo : public TargetCodeGenInfo { 11247 public: 11248 RISCVTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, unsigned XLen, 11249 unsigned FLen) 11250 : TargetCodeGenInfo(std::make_unique<RISCVABIInfo>(CGT, XLen, FLen)) {} 11251 11252 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 11253 CodeGen::CodeGenModule &CGM) const override { 11254 const auto *FD = dyn_cast_or_null<FunctionDecl>(D); 11255 if (!FD) return; 11256 11257 const auto *Attr = FD->getAttr<RISCVInterruptAttr>(); 11258 if (!Attr) 11259 return; 11260 11261 const char *Kind; 11262 switch (Attr->getInterrupt()) { 11263 case RISCVInterruptAttr::user: Kind = "user"; break; 11264 case RISCVInterruptAttr::supervisor: Kind = "supervisor"; break; 11265 case RISCVInterruptAttr::machine: Kind = "machine"; break; 11266 } 11267 11268 auto *Fn = cast<llvm::Function>(GV); 11269 11270 Fn->addFnAttr("interrupt", Kind); 11271 } 11272 }; 11273 } // namespace 11274 11275 //===----------------------------------------------------------------------===// 11276 // VE ABI Implementation. 11277 // 11278 namespace { 11279 class VEABIInfo : public DefaultABIInfo { 11280 public: 11281 VEABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {} 11282 11283 private: 11284 ABIArgInfo classifyReturnType(QualType RetTy) const; 11285 ABIArgInfo classifyArgumentType(QualType RetTy) const; 11286 void computeInfo(CGFunctionInfo &FI) const override; 11287 }; 11288 } // end anonymous namespace 11289 11290 ABIArgInfo VEABIInfo::classifyReturnType(QualType Ty) const { 11291 if (Ty->isAnyComplexType()) 11292 return ABIArgInfo::getDirect(); 11293 uint64_t Size = getContext().getTypeSize(Ty); 11294 if (Size < 64 && Ty->isIntegerType()) 11295 return ABIArgInfo::getExtend(Ty); 11296 return DefaultABIInfo::classifyReturnType(Ty); 11297 } 11298 11299 ABIArgInfo VEABIInfo::classifyArgumentType(QualType Ty) const { 11300 if (Ty->isAnyComplexType()) 11301 return ABIArgInfo::getDirect(); 11302 uint64_t Size = getContext().getTypeSize(Ty); 11303 if (Size < 64 && Ty->isIntegerType()) 11304 return ABIArgInfo::getExtend(Ty); 11305 return DefaultABIInfo::classifyArgumentType(Ty); 11306 } 11307 11308 void VEABIInfo::computeInfo(CGFunctionInfo &FI) const { 11309 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 11310 for (auto &Arg : FI.arguments()) 11311 Arg.info = classifyArgumentType(Arg.type); 11312 } 11313 11314 namespace { 11315 class VETargetCodeGenInfo : public TargetCodeGenInfo { 11316 public: 11317 VETargetCodeGenInfo(CodeGenTypes &CGT) 11318 : TargetCodeGenInfo(std::make_unique<VEABIInfo>(CGT)) {} 11319 // VE ABI requires the arguments of variadic and prototype-less functions 11320 // are passed in both registers and memory. 11321 bool isNoProtoCallVariadic(const CallArgList &args, 11322 const FunctionNoProtoType *fnType) const override { 11323 return true; 11324 } 11325 }; 11326 } // end anonymous namespace 11327 11328 //===----------------------------------------------------------------------===// 11329 // CSKY ABI Implementation 11330 //===----------------------------------------------------------------------===// 11331 namespace { 11332 class CSKYABIInfo : public DefaultABIInfo { 11333 static const int NumArgGPRs = 4; 11334 static const int NumArgFPRs = 4; 11335 11336 static const unsigned XLen = 32; 11337 unsigned FLen; 11338 11339 public: 11340 CSKYABIInfo(CodeGen::CodeGenTypes &CGT, unsigned FLen) 11341 : DefaultABIInfo(CGT), FLen(FLen) {} 11342 11343 void computeInfo(CGFunctionInfo &FI) const override; 11344 ABIArgInfo classifyArgumentType(QualType Ty, int &ArgGPRsLeft, 11345 int &ArgFPRsLeft, 11346 bool isReturnType = false) const; 11347 ABIArgInfo classifyReturnType(QualType RetTy) const; 11348 11349 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 11350 QualType Ty) const override; 11351 }; 11352 11353 } // end anonymous namespace 11354 11355 void CSKYABIInfo::computeInfo(CGFunctionInfo &FI) const { 11356 QualType RetTy = FI.getReturnType(); 11357 if (!getCXXABI().classifyReturnType(FI)) 11358 FI.getReturnInfo() = classifyReturnType(RetTy); 11359 11360 bool IsRetIndirect = FI.getReturnInfo().getKind() == ABIArgInfo::Indirect; 11361 11362 // We must track the number of GPRs used in order to conform to the CSKY 11363 // ABI, as integer scalars passed in registers should have signext/zeroext 11364 // when promoted. 11365 int ArgGPRsLeft = IsRetIndirect ? NumArgGPRs - 1 : NumArgGPRs; 11366 int ArgFPRsLeft = FLen ? NumArgFPRs : 0; 11367 11368 for (auto &ArgInfo : FI.arguments()) { 11369 ArgInfo.info = classifyArgumentType(ArgInfo.type, ArgGPRsLeft, ArgFPRsLeft); 11370 } 11371 } 11372 11373 Address CSKYABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 11374 QualType Ty) const { 11375 CharUnits SlotSize = CharUnits::fromQuantity(XLen / 8); 11376 11377 // Empty records are ignored for parameter passing purposes. 11378 if (isEmptyRecord(getContext(), Ty, true)) { 11379 Address Addr = Address(CGF.Builder.CreateLoad(VAListAddr), 11380 getVAListElementType(CGF), SlotSize); 11381 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty)); 11382 return Addr; 11383 } 11384 11385 auto TInfo = getContext().getTypeInfoInChars(Ty); 11386 11387 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, false, TInfo, SlotSize, 11388 /*AllowHigherAlign=*/true); 11389 } 11390 11391 ABIArgInfo CSKYABIInfo::classifyArgumentType(QualType Ty, int &ArgGPRsLeft, 11392 int &ArgFPRsLeft, 11393 bool isReturnType) const { 11394 assert(ArgGPRsLeft <= NumArgGPRs && "Arg GPR tracking underflow"); 11395 Ty = useFirstFieldIfTransparentUnion(Ty); 11396 11397 // Structures with either a non-trivial destructor or a non-trivial 11398 // copy constructor are always passed indirectly. 11399 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) { 11400 if (ArgGPRsLeft) 11401 ArgGPRsLeft -= 1; 11402 return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA == 11403 CGCXXABI::RAA_DirectInMemory); 11404 } 11405 11406 // Ignore empty structs/unions. 11407 if (isEmptyRecord(getContext(), Ty, true)) 11408 return ABIArgInfo::getIgnore(); 11409 11410 if (!Ty->getAsUnionType()) 11411 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext())) 11412 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0))); 11413 11414 uint64_t Size = getContext().getTypeSize(Ty); 11415 // Pass floating point values via FPRs if possible. 11416 if (Ty->isFloatingType() && !Ty->isComplexType() && FLen >= Size && 11417 ArgFPRsLeft) { 11418 ArgFPRsLeft--; 11419 return ABIArgInfo::getDirect(); 11420 } 11421 11422 // Complex types for the hard float ABI must be passed direct rather than 11423 // using CoerceAndExpand. 11424 if (Ty->isComplexType() && FLen && !isReturnType) { 11425 QualType EltTy = Ty->castAs<ComplexType>()->getElementType(); 11426 if (getContext().getTypeSize(EltTy) <= FLen) { 11427 ArgFPRsLeft -= 2; 11428 return ABIArgInfo::getDirect(); 11429 } 11430 } 11431 11432 if (!isAggregateTypeForABI(Ty)) { 11433 // Treat an enum type as its underlying type. 11434 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 11435 Ty = EnumTy->getDecl()->getIntegerType(); 11436 11437 // All integral types are promoted to XLen width, unless passed on the 11438 // stack. 11439 if (Size < XLen && Ty->isIntegralOrEnumerationType()) 11440 return ABIArgInfo::getExtend(Ty); 11441 11442 if (const auto *EIT = Ty->getAs<BitIntType>()) { 11443 if (EIT->getNumBits() < XLen) 11444 return ABIArgInfo::getExtend(Ty); 11445 } 11446 11447 return ABIArgInfo::getDirect(); 11448 } 11449 11450 // For argument type, the first 4*XLen parts of aggregate will be passed 11451 // in registers, and the rest will be passed in stack. 11452 // So we can coerce to integers directly and let backend handle it correctly. 11453 // For return type, aggregate which <= 2*XLen will be returned in registers. 11454 // Otherwise, aggregate will be returned indirectly. 11455 if (!isReturnType || (isReturnType && Size <= 2 * XLen)) { 11456 if (Size <= XLen) { 11457 return ABIArgInfo::getDirect( 11458 llvm::IntegerType::get(getVMContext(), XLen)); 11459 } else { 11460 return ABIArgInfo::getDirect(llvm::ArrayType::get( 11461 llvm::IntegerType::get(getVMContext(), XLen), (Size + 31) / XLen)); 11462 } 11463 } 11464 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 11465 } 11466 11467 ABIArgInfo CSKYABIInfo::classifyReturnType(QualType RetTy) const { 11468 if (RetTy->isVoidType()) 11469 return ABIArgInfo::getIgnore(); 11470 11471 int ArgGPRsLeft = 2; 11472 int ArgFPRsLeft = FLen ? 1 : 0; 11473 11474 // The rules for return and argument types are the same, so defer to 11475 // classifyArgumentType. 11476 return classifyArgumentType(RetTy, ArgGPRsLeft, ArgFPRsLeft, true); 11477 } 11478 11479 namespace { 11480 class CSKYTargetCodeGenInfo : public TargetCodeGenInfo { 11481 public: 11482 CSKYTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, unsigned FLen) 11483 : TargetCodeGenInfo(std::make_unique<CSKYABIInfo>(CGT, FLen)) {} 11484 }; 11485 } // end anonymous namespace 11486 11487 //===----------------------------------------------------------------------===// 11488 // Driver code 11489 //===----------------------------------------------------------------------===// 11490 11491 bool CodeGenModule::supportsCOMDAT() const { 11492 return getTriple().supportsCOMDAT(); 11493 } 11494 11495 const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() { 11496 if (TheTargetCodeGenInfo) 11497 return *TheTargetCodeGenInfo; 11498 11499 // Helper to set the unique_ptr while still keeping the return value. 11500 auto SetCGInfo = [&](TargetCodeGenInfo *P) -> const TargetCodeGenInfo & { 11501 this->TheTargetCodeGenInfo.reset(P); 11502 return *P; 11503 }; 11504 11505 const llvm::Triple &Triple = getTarget().getTriple(); 11506 switch (Triple.getArch()) { 11507 default: 11508 return SetCGInfo(new DefaultTargetCodeGenInfo(Types)); 11509 11510 case llvm::Triple::le32: 11511 return SetCGInfo(new PNaClTargetCodeGenInfo(Types)); 11512 case llvm::Triple::m68k: 11513 return SetCGInfo(new M68kTargetCodeGenInfo(Types)); 11514 case llvm::Triple::mips: 11515 case llvm::Triple::mipsel: 11516 if (Triple.getOS() == llvm::Triple::NaCl) 11517 return SetCGInfo(new PNaClTargetCodeGenInfo(Types)); 11518 return SetCGInfo(new MIPSTargetCodeGenInfo(Types, true)); 11519 11520 case llvm::Triple::mips64: 11521 case llvm::Triple::mips64el: 11522 return SetCGInfo(new MIPSTargetCodeGenInfo(Types, false)); 11523 11524 case llvm::Triple::avr: { 11525 // For passing parameters, R8~R25 are used on avr, and R18~R25 are used 11526 // on avrtiny. For passing return value, R18~R25 are used on avr, and 11527 // R22~R25 are used on avrtiny. 11528 unsigned NPR = getTarget().getABI() == "avrtiny" ? 6 : 18; 11529 unsigned NRR = getTarget().getABI() == "avrtiny" ? 4 : 8; 11530 return SetCGInfo(new AVRTargetCodeGenInfo(Types, NPR, NRR)); 11531 } 11532 11533 case llvm::Triple::aarch64: 11534 case llvm::Triple::aarch64_32: 11535 case llvm::Triple::aarch64_be: { 11536 AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS; 11537 if (getTarget().getABI() == "darwinpcs") 11538 Kind = AArch64ABIInfo::DarwinPCS; 11539 else if (Triple.isOSWindows()) 11540 return SetCGInfo( 11541 new WindowsAArch64TargetCodeGenInfo(Types, AArch64ABIInfo::Win64)); 11542 11543 return SetCGInfo(new AArch64TargetCodeGenInfo(Types, Kind)); 11544 } 11545 11546 case llvm::Triple::wasm32: 11547 case llvm::Triple::wasm64: { 11548 WebAssemblyABIInfo::ABIKind Kind = WebAssemblyABIInfo::MVP; 11549 if (getTarget().getABI() == "experimental-mv") 11550 Kind = WebAssemblyABIInfo::ExperimentalMV; 11551 return SetCGInfo(new WebAssemblyTargetCodeGenInfo(Types, Kind)); 11552 } 11553 11554 case llvm::Triple::arm: 11555 case llvm::Triple::armeb: 11556 case llvm::Triple::thumb: 11557 case llvm::Triple::thumbeb: { 11558 if (Triple.getOS() == llvm::Triple::Win32) { 11559 return SetCGInfo( 11560 new WindowsARMTargetCodeGenInfo(Types, ARMABIInfo::AAPCS_VFP)); 11561 } 11562 11563 ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS; 11564 StringRef ABIStr = getTarget().getABI(); 11565 if (ABIStr == "apcs-gnu") 11566 Kind = ARMABIInfo::APCS; 11567 else if (ABIStr == "aapcs16") 11568 Kind = ARMABIInfo::AAPCS16_VFP; 11569 else if (CodeGenOpts.FloatABI == "hard" || 11570 (CodeGenOpts.FloatABI != "soft" && 11571 (Triple.getEnvironment() == llvm::Triple::GNUEABIHF || 11572 Triple.getEnvironment() == llvm::Triple::MuslEABIHF || 11573 Triple.getEnvironment() == llvm::Triple::EABIHF))) 11574 Kind = ARMABIInfo::AAPCS_VFP; 11575 11576 return SetCGInfo(new ARMTargetCodeGenInfo(Types, Kind)); 11577 } 11578 11579 case llvm::Triple::ppc: { 11580 if (Triple.isOSAIX()) 11581 return SetCGInfo(new AIXTargetCodeGenInfo(Types, /*Is64Bit*/ false)); 11582 11583 bool IsSoftFloat = 11584 CodeGenOpts.FloatABI == "soft" || getTarget().hasFeature("spe"); 11585 bool RetSmallStructInRegABI = 11586 PPC32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts); 11587 return SetCGInfo( 11588 new PPC32TargetCodeGenInfo(Types, IsSoftFloat, RetSmallStructInRegABI)); 11589 } 11590 case llvm::Triple::ppcle: { 11591 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft"; 11592 bool RetSmallStructInRegABI = 11593 PPC32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts); 11594 return SetCGInfo( 11595 new PPC32TargetCodeGenInfo(Types, IsSoftFloat, RetSmallStructInRegABI)); 11596 } 11597 case llvm::Triple::ppc64: 11598 if (Triple.isOSAIX()) 11599 return SetCGInfo(new AIXTargetCodeGenInfo(Types, /*Is64Bit*/ true)); 11600 11601 if (Triple.isOSBinFormatELF()) { 11602 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1; 11603 if (getTarget().getABI() == "elfv2") 11604 Kind = PPC64_SVR4_ABIInfo::ELFv2; 11605 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft"; 11606 11607 return SetCGInfo( 11608 new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, IsSoftFloat)); 11609 } 11610 return SetCGInfo(new PPC64TargetCodeGenInfo(Types)); 11611 case llvm::Triple::ppc64le: { 11612 assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!"); 11613 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2; 11614 if (getTarget().getABI() == "elfv1") 11615 Kind = PPC64_SVR4_ABIInfo::ELFv1; 11616 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft"; 11617 11618 return SetCGInfo( 11619 new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, IsSoftFloat)); 11620 } 11621 11622 case llvm::Triple::nvptx: 11623 case llvm::Triple::nvptx64: 11624 return SetCGInfo(new NVPTXTargetCodeGenInfo(Types)); 11625 11626 case llvm::Triple::msp430: 11627 return SetCGInfo(new MSP430TargetCodeGenInfo(Types)); 11628 11629 case llvm::Triple::riscv32: 11630 case llvm::Triple::riscv64: { 11631 StringRef ABIStr = getTarget().getABI(); 11632 unsigned XLen = getTarget().getPointerWidth(0); 11633 unsigned ABIFLen = 0; 11634 if (ABIStr.endswith("f")) 11635 ABIFLen = 32; 11636 else if (ABIStr.endswith("d")) 11637 ABIFLen = 64; 11638 return SetCGInfo(new RISCVTargetCodeGenInfo(Types, XLen, ABIFLen)); 11639 } 11640 11641 case llvm::Triple::systemz: { 11642 bool SoftFloat = CodeGenOpts.FloatABI == "soft"; 11643 bool HasVector = !SoftFloat && getTarget().getABI() == "vector"; 11644 return SetCGInfo(new SystemZTargetCodeGenInfo(Types, HasVector, SoftFloat)); 11645 } 11646 11647 case llvm::Triple::tce: 11648 case llvm::Triple::tcele: 11649 return SetCGInfo(new TCETargetCodeGenInfo(Types)); 11650 11651 case llvm::Triple::x86: { 11652 bool IsDarwinVectorABI = Triple.isOSDarwin(); 11653 bool RetSmallStructInRegABI = 11654 X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts); 11655 bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing(); 11656 11657 if (Triple.getOS() == llvm::Triple::Win32) { 11658 return SetCGInfo(new WinX86_32TargetCodeGenInfo( 11659 Types, IsDarwinVectorABI, RetSmallStructInRegABI, 11660 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters)); 11661 } else { 11662 return SetCGInfo(new X86_32TargetCodeGenInfo( 11663 Types, IsDarwinVectorABI, RetSmallStructInRegABI, 11664 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters, 11665 CodeGenOpts.FloatABI == "soft")); 11666 } 11667 } 11668 11669 case llvm::Triple::x86_64: { 11670 StringRef ABI = getTarget().getABI(); 11671 X86AVXABILevel AVXLevel = 11672 (ABI == "avx512" 11673 ? X86AVXABILevel::AVX512 11674 : ABI == "avx" ? X86AVXABILevel::AVX : X86AVXABILevel::None); 11675 11676 switch (Triple.getOS()) { 11677 case llvm::Triple::Win32: 11678 return SetCGInfo(new WinX86_64TargetCodeGenInfo(Types, AVXLevel)); 11679 default: 11680 return SetCGInfo(new X86_64TargetCodeGenInfo(Types, AVXLevel)); 11681 } 11682 } 11683 case llvm::Triple::hexagon: 11684 return SetCGInfo(new HexagonTargetCodeGenInfo(Types)); 11685 case llvm::Triple::lanai: 11686 return SetCGInfo(new LanaiTargetCodeGenInfo(Types)); 11687 case llvm::Triple::r600: 11688 return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types)); 11689 case llvm::Triple::amdgcn: 11690 return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types)); 11691 case llvm::Triple::sparc: 11692 return SetCGInfo(new SparcV8TargetCodeGenInfo(Types)); 11693 case llvm::Triple::sparcv9: 11694 return SetCGInfo(new SparcV9TargetCodeGenInfo(Types)); 11695 case llvm::Triple::xcore: 11696 return SetCGInfo(new XCoreTargetCodeGenInfo(Types)); 11697 case llvm::Triple::arc: 11698 return SetCGInfo(new ARCTargetCodeGenInfo(Types)); 11699 case llvm::Triple::spir: 11700 case llvm::Triple::spir64: 11701 return SetCGInfo(new CommonSPIRTargetCodeGenInfo(Types)); 11702 case llvm::Triple::spirv32: 11703 case llvm::Triple::spirv64: 11704 return SetCGInfo(new SPIRVTargetCodeGenInfo(Types)); 11705 case llvm::Triple::ve: 11706 return SetCGInfo(new VETargetCodeGenInfo(Types)); 11707 case llvm::Triple::csky: { 11708 bool IsSoftFloat = !getTarget().hasFeature("hard-float-abi"); 11709 bool hasFP64 = getTarget().hasFeature("fpuv2_df") || 11710 getTarget().hasFeature("fpuv3_df"); 11711 return SetCGInfo(new CSKYTargetCodeGenInfo(Types, IsSoftFloat ? 0 11712 : hasFP64 ? 64 11713 : 32)); 11714 } 11715 } 11716 } 11717 11718 /// Create an OpenCL kernel for an enqueued block. 11719 /// 11720 /// The kernel has the same function type as the block invoke function. Its 11721 /// name is the name of the block invoke function postfixed with "_kernel". 11722 /// It simply calls the block invoke function then returns. 11723 llvm::Function * 11724 TargetCodeGenInfo::createEnqueuedBlockKernel(CodeGenFunction &CGF, 11725 llvm::Function *Invoke, 11726 llvm::Type *BlockTy) const { 11727 auto *InvokeFT = Invoke->getFunctionType(); 11728 auto &C = CGF.getLLVMContext(); 11729 std::string Name = Invoke->getName().str() + "_kernel"; 11730 auto *FT = llvm::FunctionType::get(llvm::Type::getVoidTy(C), 11731 InvokeFT->params(), false); 11732 auto *F = llvm::Function::Create(FT, llvm::GlobalValue::ExternalLinkage, Name, 11733 &CGF.CGM.getModule()); 11734 auto IP = CGF.Builder.saveIP(); 11735 auto *BB = llvm::BasicBlock::Create(C, "entry", F); 11736 auto &Builder = CGF.Builder; 11737 Builder.SetInsertPoint(BB); 11738 llvm::SmallVector<llvm::Value *, 2> Args(llvm::make_pointer_range(F->args())); 11739 llvm::CallInst *call = Builder.CreateCall(Invoke, Args); 11740 call->setCallingConv(Invoke->getCallingConv()); 11741 Builder.CreateRetVoid(); 11742 Builder.restoreIP(IP); 11743 return F; 11744 } 11745 11746 /// Create an OpenCL kernel for an enqueued block. 11747 /// 11748 /// The type of the first argument (the block literal) is the struct type 11749 /// of the block literal instead of a pointer type. The first argument 11750 /// (block literal) is passed directly by value to the kernel. The kernel 11751 /// allocates the same type of struct on stack and stores the block literal 11752 /// to it and passes its pointer to the block invoke function. The kernel 11753 /// has "enqueued-block" function attribute and kernel argument metadata. 11754 llvm::Function *AMDGPUTargetCodeGenInfo::createEnqueuedBlockKernel( 11755 CodeGenFunction &CGF, llvm::Function *Invoke, 11756 llvm::Type *BlockTy) const { 11757 auto &Builder = CGF.Builder; 11758 auto &C = CGF.getLLVMContext(); 11759 11760 auto *InvokeFT = Invoke->getFunctionType(); 11761 llvm::SmallVector<llvm::Type *, 2> ArgTys; 11762 llvm::SmallVector<llvm::Metadata *, 8> AddressQuals; 11763 llvm::SmallVector<llvm::Metadata *, 8> AccessQuals; 11764 llvm::SmallVector<llvm::Metadata *, 8> ArgTypeNames; 11765 llvm::SmallVector<llvm::Metadata *, 8> ArgBaseTypeNames; 11766 llvm::SmallVector<llvm::Metadata *, 8> ArgTypeQuals; 11767 llvm::SmallVector<llvm::Metadata *, 8> ArgNames; 11768 11769 ArgTys.push_back(BlockTy); 11770 ArgTypeNames.push_back(llvm::MDString::get(C, "__block_literal")); 11771 AddressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(0))); 11772 ArgBaseTypeNames.push_back(llvm::MDString::get(C, "__block_literal")); 11773 ArgTypeQuals.push_back(llvm::MDString::get(C, "")); 11774 AccessQuals.push_back(llvm::MDString::get(C, "none")); 11775 ArgNames.push_back(llvm::MDString::get(C, "block_literal")); 11776 for (unsigned I = 1, E = InvokeFT->getNumParams(); I < E; ++I) { 11777 ArgTys.push_back(InvokeFT->getParamType(I)); 11778 ArgTypeNames.push_back(llvm::MDString::get(C, "void*")); 11779 AddressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(3))); 11780 AccessQuals.push_back(llvm::MDString::get(C, "none")); 11781 ArgBaseTypeNames.push_back(llvm::MDString::get(C, "void*")); 11782 ArgTypeQuals.push_back(llvm::MDString::get(C, "")); 11783 ArgNames.push_back( 11784 llvm::MDString::get(C, (Twine("local_arg") + Twine(I)).str())); 11785 } 11786 std::string Name = Invoke->getName().str() + "_kernel"; 11787 auto *FT = llvm::FunctionType::get(llvm::Type::getVoidTy(C), ArgTys, false); 11788 auto *F = llvm::Function::Create(FT, llvm::GlobalValue::InternalLinkage, Name, 11789 &CGF.CGM.getModule()); 11790 F->addFnAttr("enqueued-block"); 11791 auto IP = CGF.Builder.saveIP(); 11792 auto *BB = llvm::BasicBlock::Create(C, "entry", F); 11793 Builder.SetInsertPoint(BB); 11794 const auto BlockAlign = CGF.CGM.getDataLayout().getPrefTypeAlign(BlockTy); 11795 auto *BlockPtr = Builder.CreateAlloca(BlockTy, nullptr); 11796 BlockPtr->setAlignment(BlockAlign); 11797 Builder.CreateAlignedStore(F->arg_begin(), BlockPtr, BlockAlign); 11798 auto *Cast = Builder.CreatePointerCast(BlockPtr, InvokeFT->getParamType(0)); 11799 llvm::SmallVector<llvm::Value *, 2> Args; 11800 Args.push_back(Cast); 11801 for (auto I = F->arg_begin() + 1, E = F->arg_end(); I != E; ++I) 11802 Args.push_back(I); 11803 llvm::CallInst *call = Builder.CreateCall(Invoke, Args); 11804 call->setCallingConv(Invoke->getCallingConv()); 11805 Builder.CreateRetVoid(); 11806 Builder.restoreIP(IP); 11807 11808 F->setMetadata("kernel_arg_addr_space", llvm::MDNode::get(C, AddressQuals)); 11809 F->setMetadata("kernel_arg_access_qual", llvm::MDNode::get(C, AccessQuals)); 11810 F->setMetadata("kernel_arg_type", llvm::MDNode::get(C, ArgTypeNames)); 11811 F->setMetadata("kernel_arg_base_type", 11812 llvm::MDNode::get(C, ArgBaseTypeNames)); 11813 F->setMetadata("kernel_arg_type_qual", llvm::MDNode::get(C, ArgTypeQuals)); 11814 if (CGF.CGM.getCodeGenOpts().EmitOpenCLArgMetadata) 11815 F->setMetadata("kernel_arg_name", llvm::MDNode::get(C, ArgNames)); 11816 11817 return F; 11818 } 11819