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