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