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