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