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