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