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