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