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