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