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