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