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 "CodeGenFunction.h" 19 #include "clang/AST/RecordLayout.h" 20 #include "clang/CodeGen/CGFunctionInfo.h" 21 #include "clang/Frontend/CodeGenOptions.h" 22 #include "llvm/ADT/Triple.h" 23 #include "llvm/IR/DataLayout.h" 24 #include "llvm/IR/Type.h" 25 #include "llvm/Support/raw_ostream.h" 26 using namespace clang; 27 using namespace CodeGen; 28 29 static void AssignToArrayRange(CodeGen::CGBuilderTy &Builder, 30 llvm::Value *Array, 31 llvm::Value *Value, 32 unsigned FirstIndex, 33 unsigned LastIndex) { 34 // Alternatively, we could emit this as a loop in the source. 35 for (unsigned I = FirstIndex; I <= LastIndex; ++I) { 36 llvm::Value *Cell = Builder.CreateConstInBoundsGEP1_32(Array, I); 37 Builder.CreateStore(Value, Cell); 38 } 39 } 40 41 static bool isAggregateTypeForABI(QualType T) { 42 return !CodeGenFunction::hasScalarEvaluationKind(T) || 43 T->isMemberFunctionPointerType(); 44 } 45 46 ABIInfo::~ABIInfo() {} 47 48 static bool isRecordReturnIndirect(const RecordType *RT, 49 CGCXXABI &CXXABI) { 50 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 51 if (!RD) 52 return false; 53 return CXXABI.isReturnTypeIndirect(RD); 54 } 55 56 57 static bool isRecordReturnIndirect(QualType T, CGCXXABI &CXXABI) { 58 const RecordType *RT = T->getAs<RecordType>(); 59 if (!RT) 60 return false; 61 return isRecordReturnIndirect(RT, CXXABI); 62 } 63 64 static CGCXXABI::RecordArgABI getRecordArgABI(const RecordType *RT, 65 CGCXXABI &CXXABI) { 66 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 67 if (!RD) 68 return CGCXXABI::RAA_Default; 69 return CXXABI.getRecordArgABI(RD); 70 } 71 72 static CGCXXABI::RecordArgABI getRecordArgABI(QualType T, 73 CGCXXABI &CXXABI) { 74 const RecordType *RT = T->getAs<RecordType>(); 75 if (!RT) 76 return CGCXXABI::RAA_Default; 77 return getRecordArgABI(RT, CXXABI); 78 } 79 80 CGCXXABI &ABIInfo::getCXXABI() const { 81 return CGT.getCXXABI(); 82 } 83 84 ASTContext &ABIInfo::getContext() const { 85 return CGT.getContext(); 86 } 87 88 llvm::LLVMContext &ABIInfo::getVMContext() const { 89 return CGT.getLLVMContext(); 90 } 91 92 const llvm::DataLayout &ABIInfo::getDataLayout() const { 93 return CGT.getDataLayout(); 94 } 95 96 const TargetInfo &ABIInfo::getTarget() const { 97 return CGT.getTarget(); 98 } 99 100 void ABIArgInfo::dump() const { 101 raw_ostream &OS = llvm::errs(); 102 OS << "(ABIArgInfo Kind="; 103 switch (TheKind) { 104 case Direct: 105 OS << "Direct Type="; 106 if (llvm::Type *Ty = getCoerceToType()) 107 Ty->print(OS); 108 else 109 OS << "null"; 110 break; 111 case Extend: 112 OS << "Extend"; 113 break; 114 case Ignore: 115 OS << "Ignore"; 116 break; 117 case Indirect: 118 OS << "Indirect Align=" << getIndirectAlign() 119 << " ByVal=" << getIndirectByVal() 120 << " Realign=" << getIndirectRealign(); 121 break; 122 case Expand: 123 OS << "Expand"; 124 break; 125 } 126 OS << ")\n"; 127 } 128 129 TargetCodeGenInfo::~TargetCodeGenInfo() { delete Info; } 130 131 // If someone can figure out a general rule for this, that would be great. 132 // It's probably just doomed to be platform-dependent, though. 133 unsigned TargetCodeGenInfo::getSizeOfUnwindException() const { 134 // Verified for: 135 // x86-64 FreeBSD, Linux, Darwin 136 // x86-32 FreeBSD, Linux, Darwin 137 // PowerPC Linux, Darwin 138 // ARM Darwin (*not* EABI) 139 // AArch64 Linux 140 return 32; 141 } 142 143 bool TargetCodeGenInfo::isNoProtoCallVariadic(const CallArgList &args, 144 const FunctionNoProtoType *fnType) const { 145 // The following conventions are known to require this to be false: 146 // x86_stdcall 147 // MIPS 148 // For everything else, we just prefer false unless we opt out. 149 return false; 150 } 151 152 void 153 TargetCodeGenInfo::getDependentLibraryOption(llvm::StringRef Lib, 154 llvm::SmallString<24> &Opt) const { 155 // This assumes the user is passing a library name like "rt" instead of a 156 // filename like "librt.a/so", and that they don't care whether it's static or 157 // dynamic. 158 Opt = "-l"; 159 Opt += Lib; 160 } 161 162 static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays); 163 164 /// isEmptyField - Return true iff a the field is "empty", that is it 165 /// is an unnamed bit-field or an (array of) empty record(s). 166 static bool isEmptyField(ASTContext &Context, const FieldDecl *FD, 167 bool AllowArrays) { 168 if (FD->isUnnamedBitfield()) 169 return true; 170 171 QualType FT = FD->getType(); 172 173 // Constant arrays of empty records count as empty, strip them off. 174 // Constant arrays of zero length always count as empty. 175 if (AllowArrays) 176 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) { 177 if (AT->getSize() == 0) 178 return true; 179 FT = AT->getElementType(); 180 } 181 182 const RecordType *RT = FT->getAs<RecordType>(); 183 if (!RT) 184 return false; 185 186 // C++ record fields are never empty, at least in the Itanium ABI. 187 // 188 // FIXME: We should use a predicate for whether this behavior is true in the 189 // current ABI. 190 if (isa<CXXRecordDecl>(RT->getDecl())) 191 return false; 192 193 return isEmptyRecord(Context, FT, AllowArrays); 194 } 195 196 /// isEmptyRecord - Return true iff a structure contains only empty 197 /// fields. Note that a structure with a flexible array member is not 198 /// considered empty. 199 static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) { 200 const RecordType *RT = T->getAs<RecordType>(); 201 if (!RT) 202 return 0; 203 const RecordDecl *RD = RT->getDecl(); 204 if (RD->hasFlexibleArrayMember()) 205 return false; 206 207 // If this is a C++ record, check the bases first. 208 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 209 for (CXXRecordDecl::base_class_const_iterator i = CXXRD->bases_begin(), 210 e = CXXRD->bases_end(); i != e; ++i) 211 if (!isEmptyRecord(Context, i->getType(), true)) 212 return false; 213 214 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 215 i != e; ++i) 216 if (!isEmptyField(Context, *i, AllowArrays)) 217 return false; 218 return true; 219 } 220 221 /// isSingleElementStruct - Determine if a structure is a "single 222 /// element struct", i.e. it has exactly one non-empty field or 223 /// exactly one field which is itself a single element 224 /// struct. Structures with flexible array members are never 225 /// considered single element structs. 226 /// 227 /// \return The field declaration for the single non-empty field, if 228 /// it exists. 229 static const Type *isSingleElementStruct(QualType T, ASTContext &Context) { 230 const RecordType *RT = T->getAsStructureType(); 231 if (!RT) 232 return 0; 233 234 const RecordDecl *RD = RT->getDecl(); 235 if (RD->hasFlexibleArrayMember()) 236 return 0; 237 238 const Type *Found = 0; 239 240 // If this is a C++ record, check the bases first. 241 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 242 for (CXXRecordDecl::base_class_const_iterator i = CXXRD->bases_begin(), 243 e = CXXRD->bases_end(); i != e; ++i) { 244 // Ignore empty records. 245 if (isEmptyRecord(Context, i->getType(), true)) 246 continue; 247 248 // If we already found an element then this isn't a single-element struct. 249 if (Found) 250 return 0; 251 252 // If this is non-empty and not a single element struct, the composite 253 // cannot be a single element struct. 254 Found = isSingleElementStruct(i->getType(), Context); 255 if (!Found) 256 return 0; 257 } 258 } 259 260 // Check for single element. 261 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 262 i != e; ++i) { 263 const FieldDecl *FD = *i; 264 QualType FT = FD->getType(); 265 266 // Ignore empty fields. 267 if (isEmptyField(Context, FD, true)) 268 continue; 269 270 // If we already found an element then this isn't a single-element 271 // struct. 272 if (Found) 273 return 0; 274 275 // Treat single element arrays as the element. 276 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) { 277 if (AT->getSize().getZExtValue() != 1) 278 break; 279 FT = AT->getElementType(); 280 } 281 282 if (!isAggregateTypeForABI(FT)) { 283 Found = FT.getTypePtr(); 284 } else { 285 Found = isSingleElementStruct(FT, Context); 286 if (!Found) 287 return 0; 288 } 289 } 290 291 // We don't consider a struct a single-element struct if it has 292 // padding beyond the element type. 293 if (Found && Context.getTypeSize(Found) != Context.getTypeSize(T)) 294 return 0; 295 296 return Found; 297 } 298 299 static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) { 300 // Treat complex types as the element type. 301 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) 302 Ty = CTy->getElementType(); 303 304 // Check for a type which we know has a simple scalar argument-passing 305 // convention without any padding. (We're specifically looking for 32 306 // and 64-bit integer and integer-equivalents, float, and double.) 307 if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() && 308 !Ty->isEnumeralType() && !Ty->isBlockPointerType()) 309 return false; 310 311 uint64_t Size = Context.getTypeSize(Ty); 312 return Size == 32 || Size == 64; 313 } 314 315 /// canExpandIndirectArgument - Test whether an argument type which is to be 316 /// passed indirectly (on the stack) would have the equivalent layout if it was 317 /// expanded into separate arguments. If so, we prefer to do the latter to avoid 318 /// inhibiting optimizations. 319 /// 320 // FIXME: This predicate is missing many cases, currently it just follows 321 // llvm-gcc (checks that all fields are 32-bit or 64-bit primitive types). We 322 // should probably make this smarter, or better yet make the LLVM backend 323 // capable of handling it. 324 static bool canExpandIndirectArgument(QualType Ty, ASTContext &Context) { 325 // We can only expand structure types. 326 const RecordType *RT = Ty->getAs<RecordType>(); 327 if (!RT) 328 return false; 329 330 // We can only expand (C) structures. 331 // 332 // FIXME: This needs to be generalized to handle classes as well. 333 const RecordDecl *RD = RT->getDecl(); 334 if (!RD->isStruct() || isa<CXXRecordDecl>(RD)) 335 return false; 336 337 uint64_t Size = 0; 338 339 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 340 i != e; ++i) { 341 const FieldDecl *FD = *i; 342 343 if (!is32Or64BitBasicType(FD->getType(), Context)) 344 return false; 345 346 // FIXME: Reject bit-fields wholesale; there are two problems, we don't know 347 // how to expand them yet, and the predicate for telling if a bitfield still 348 // counts as "basic" is more complicated than what we were doing previously. 349 if (FD->isBitField()) 350 return false; 351 352 Size += Context.getTypeSize(FD->getType()); 353 } 354 355 // Make sure there are not any holes in the struct. 356 if (Size != Context.getTypeSize(Ty)) 357 return false; 358 359 return true; 360 } 361 362 namespace { 363 /// DefaultABIInfo - The default implementation for ABI specific 364 /// details. This implementation provides information which results in 365 /// self-consistent and sensible LLVM IR generation, but does not 366 /// conform to any particular ABI. 367 class DefaultABIInfo : public ABIInfo { 368 public: 369 DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {} 370 371 ABIArgInfo classifyReturnType(QualType RetTy) const; 372 ABIArgInfo classifyArgumentType(QualType RetTy) const; 373 374 virtual void computeInfo(CGFunctionInfo &FI) const { 375 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 376 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end(); 377 it != ie; ++it) 378 it->info = classifyArgumentType(it->type); 379 } 380 381 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 382 CodeGenFunction &CGF) const; 383 }; 384 385 class DefaultTargetCodeGenInfo : public TargetCodeGenInfo { 386 public: 387 DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT) 388 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {} 389 }; 390 391 llvm::Value *DefaultABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 392 CodeGenFunction &CGF) const { 393 return 0; 394 } 395 396 ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const { 397 if (isAggregateTypeForABI(Ty)) { 398 // Records with non-trivial destructors/constructors should not be passed 399 // by value. 400 if (isRecordReturnIndirect(Ty, getCXXABI())) 401 return ABIArgInfo::getIndirect(0, /*ByVal=*/false); 402 403 return ABIArgInfo::getIndirect(0); 404 } 405 406 // Treat an enum type as its underlying type. 407 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 408 Ty = EnumTy->getDecl()->getIntegerType(); 409 410 return (Ty->isPromotableIntegerType() ? 411 ABIArgInfo::getExtend() : ABIArgInfo::getDirect()); 412 } 413 414 ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const { 415 if (RetTy->isVoidType()) 416 return ABIArgInfo::getIgnore(); 417 418 if (isAggregateTypeForABI(RetTy)) 419 return ABIArgInfo::getIndirect(0); 420 421 // Treat an enum type as its underlying type. 422 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 423 RetTy = EnumTy->getDecl()->getIntegerType(); 424 425 return (RetTy->isPromotableIntegerType() ? 426 ABIArgInfo::getExtend() : ABIArgInfo::getDirect()); 427 } 428 429 //===----------------------------------------------------------------------===// 430 // le32/PNaCl bitcode ABI Implementation 431 // 432 // This is a simplified version of the x86_32 ABI. Arguments and return values 433 // are always passed on the stack. 434 //===----------------------------------------------------------------------===// 435 436 class PNaClABIInfo : public ABIInfo { 437 public: 438 PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {} 439 440 ABIArgInfo classifyReturnType(QualType RetTy) const; 441 ABIArgInfo classifyArgumentType(QualType RetTy) const; 442 443 virtual void computeInfo(CGFunctionInfo &FI) const; 444 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 445 CodeGenFunction &CGF) const; 446 }; 447 448 class PNaClTargetCodeGenInfo : public TargetCodeGenInfo { 449 public: 450 PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT) 451 : TargetCodeGenInfo(new PNaClABIInfo(CGT)) {} 452 }; 453 454 void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const { 455 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 456 457 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end(); 458 it != ie; ++it) 459 it->info = classifyArgumentType(it->type); 460 } 461 462 llvm::Value *PNaClABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 463 CodeGenFunction &CGF) const { 464 return 0; 465 } 466 467 /// \brief Classify argument of given type \p Ty. 468 ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const { 469 if (isAggregateTypeForABI(Ty)) { 470 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 471 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory); 472 return ABIArgInfo::getIndirect(0); 473 } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) { 474 // Treat an enum type as its underlying type. 475 Ty = EnumTy->getDecl()->getIntegerType(); 476 } else if (Ty->isFloatingType()) { 477 // Floating-point types don't go inreg. 478 return ABIArgInfo::getDirect(); 479 } 480 481 return (Ty->isPromotableIntegerType() ? 482 ABIArgInfo::getExtend() : ABIArgInfo::getDirect()); 483 } 484 485 ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const { 486 if (RetTy->isVoidType()) 487 return ABIArgInfo::getIgnore(); 488 489 // In the PNaCl ABI we always return records/structures on the stack. 490 if (isAggregateTypeForABI(RetTy)) 491 return ABIArgInfo::getIndirect(0); 492 493 // Treat an enum type as its underlying type. 494 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 495 RetTy = EnumTy->getDecl()->getIntegerType(); 496 497 return (RetTy->isPromotableIntegerType() ? 498 ABIArgInfo::getExtend() : ABIArgInfo::getDirect()); 499 } 500 501 /// IsX86_MMXType - Return true if this is an MMX type. 502 bool IsX86_MMXType(llvm::Type *IRType) { 503 // Return true if the type is an MMX type <2 x i32>, <4 x i16>, or <8 x i8>. 504 return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 && 505 cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() && 506 IRType->getScalarSizeInBits() != 64; 507 } 508 509 static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF, 510 StringRef Constraint, 511 llvm::Type* Ty) { 512 if ((Constraint == "y" || Constraint == "&y") && Ty->isVectorTy()) { 513 if (cast<llvm::VectorType>(Ty)->getBitWidth() != 64) { 514 // Invalid MMX constraint 515 return 0; 516 } 517 518 return llvm::Type::getX86_MMXTy(CGF.getLLVMContext()); 519 } 520 521 // No operation needed 522 return Ty; 523 } 524 525 //===----------------------------------------------------------------------===// 526 // X86-32 ABI Implementation 527 //===----------------------------------------------------------------------===// 528 529 /// \brief Similar to llvm::CCState, but for Clang. 530 struct CCState { 531 CCState(unsigned CC) : CC(CC), FreeRegs(0) {} 532 533 unsigned CC; 534 unsigned FreeRegs; 535 }; 536 537 /// X86_32ABIInfo - The X86-32 ABI information. 538 class X86_32ABIInfo : public ABIInfo { 539 enum Class { 540 Integer, 541 Float 542 }; 543 544 static const unsigned MinABIStackAlignInBytes = 4; 545 546 bool IsDarwinVectorABI; 547 bool IsSmallStructInRegABI; 548 bool IsWin32StructABI; 549 unsigned DefaultNumRegisterParameters; 550 551 static bool isRegisterSize(unsigned Size) { 552 return (Size == 8 || Size == 16 || Size == 32 || Size == 64); 553 } 554 555 static bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context, 556 unsigned callingConvention); 557 558 /// getIndirectResult - Give a source type \arg Ty, return a suitable result 559 /// such that the argument will be passed in memory. 560 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const; 561 562 ABIArgInfo getIndirectReturnResult(CCState &State) const; 563 564 /// \brief Return the alignment to use for the given type on the stack. 565 unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const; 566 567 Class classify(QualType Ty) const; 568 ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const; 569 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const; 570 bool shouldUseInReg(QualType Ty, CCState &State, bool &NeedsPadding) const; 571 572 public: 573 574 virtual void computeInfo(CGFunctionInfo &FI) const; 575 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 576 CodeGenFunction &CGF) const; 577 578 X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool d, bool p, bool w, 579 unsigned r) 580 : ABIInfo(CGT), IsDarwinVectorABI(d), IsSmallStructInRegABI(p), 581 IsWin32StructABI(w), DefaultNumRegisterParameters(r) {} 582 }; 583 584 class X86_32TargetCodeGenInfo : public TargetCodeGenInfo { 585 public: 586 X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, 587 bool d, bool p, bool w, unsigned r) 588 :TargetCodeGenInfo(new X86_32ABIInfo(CGT, d, p, w, r)) {} 589 590 static bool isStructReturnInRegABI( 591 const llvm::Triple &Triple, const CodeGenOptions &Opts); 592 593 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 594 CodeGen::CodeGenModule &CGM) const; 595 596 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const { 597 // Darwin uses different dwarf register numbers for EH. 598 if (CGM.getTarget().getTriple().isOSDarwin()) return 5; 599 return 4; 600 } 601 602 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 603 llvm::Value *Address) const; 604 605 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF, 606 StringRef Constraint, 607 llvm::Type* Ty) const { 608 return X86AdjustInlineAsmType(CGF, Constraint, Ty); 609 } 610 611 llvm::Constant *getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const { 612 unsigned Sig = (0xeb << 0) | // jmp rel8 613 (0x06 << 8) | // .+0x08 614 ('F' << 16) | 615 ('T' << 24); 616 return llvm::ConstantInt::get(CGM.Int32Ty, Sig); 617 } 618 619 }; 620 621 } 622 623 /// shouldReturnTypeInRegister - Determine if the given type should be 624 /// passed in a register (for the Darwin ABI). 625 bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty, 626 ASTContext &Context, 627 unsigned callingConvention) { 628 uint64_t Size = Context.getTypeSize(Ty); 629 630 // Type must be register sized. 631 if (!isRegisterSize(Size)) 632 return false; 633 634 if (Ty->isVectorType()) { 635 // 64- and 128- bit vectors inside structures are not returned in 636 // registers. 637 if (Size == 64 || Size == 128) 638 return false; 639 640 return true; 641 } 642 643 // If this is a builtin, pointer, enum, complex type, member pointer, or 644 // member function pointer it is ok. 645 if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() || 646 Ty->isAnyComplexType() || Ty->isEnumeralType() || 647 Ty->isBlockPointerType() || Ty->isMemberPointerType()) 648 return true; 649 650 // Arrays are treated like records. 651 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) 652 return shouldReturnTypeInRegister(AT->getElementType(), Context, 653 callingConvention); 654 655 // Otherwise, it must be a record type. 656 const RecordType *RT = Ty->getAs<RecordType>(); 657 if (!RT) return false; 658 659 // FIXME: Traverse bases here too. 660 661 // For thiscall conventions, structures will never be returned in 662 // a register. This is for compatibility with the MSVC ABI 663 if (callingConvention == llvm::CallingConv::X86_ThisCall && 664 RT->isStructureType()) { 665 return false; 666 } 667 668 // Structure types are passed in register if all fields would be 669 // passed in a register. 670 for (RecordDecl::field_iterator i = RT->getDecl()->field_begin(), 671 e = RT->getDecl()->field_end(); i != e; ++i) { 672 const FieldDecl *FD = *i; 673 674 // Empty fields are ignored. 675 if (isEmptyField(Context, FD, true)) 676 continue; 677 678 // Check fields recursively. 679 if (!shouldReturnTypeInRegister(FD->getType(), Context, 680 callingConvention)) 681 return false; 682 } 683 return true; 684 } 685 686 ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(CCState &State) const { 687 // If the return value is indirect, then the hidden argument is consuming one 688 // integer register. 689 if (State.FreeRegs) { 690 --State.FreeRegs; 691 return ABIArgInfo::getIndirectInReg(/*Align=*/0, /*ByVal=*/false); 692 } 693 return ABIArgInfo::getIndirect(/*Align=*/0, /*ByVal=*/false); 694 } 695 696 ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy, 697 CCState &State) const { 698 if (RetTy->isVoidType()) 699 return ABIArgInfo::getIgnore(); 700 701 if (const VectorType *VT = RetTy->getAs<VectorType>()) { 702 // On Darwin, some vectors are returned in registers. 703 if (IsDarwinVectorABI) { 704 uint64_t Size = getContext().getTypeSize(RetTy); 705 706 // 128-bit vectors are a special case; they are returned in 707 // registers and we need to make sure to pick a type the LLVM 708 // backend will like. 709 if (Size == 128) 710 return ABIArgInfo::getDirect(llvm::VectorType::get( 711 llvm::Type::getInt64Ty(getVMContext()), 2)); 712 713 // Always return in register if it fits in a general purpose 714 // register, or if it is 64 bits and has a single element. 715 if ((Size == 8 || Size == 16 || Size == 32) || 716 (Size == 64 && VT->getNumElements() == 1)) 717 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 718 Size)); 719 720 return getIndirectReturnResult(State); 721 } 722 723 return ABIArgInfo::getDirect(); 724 } 725 726 if (isAggregateTypeForABI(RetTy)) { 727 if (const RecordType *RT = RetTy->getAs<RecordType>()) { 728 if (isRecordReturnIndirect(RT, getCXXABI())) 729 return getIndirectReturnResult(State); 730 731 // Structures with flexible arrays are always indirect. 732 if (RT->getDecl()->hasFlexibleArrayMember()) 733 return getIndirectReturnResult(State); 734 } 735 736 // If specified, structs and unions are always indirect. 737 if (!IsSmallStructInRegABI && !RetTy->isAnyComplexType()) 738 return getIndirectReturnResult(State); 739 740 // Small structures which are register sized are generally returned 741 // in a register. 742 if (X86_32ABIInfo::shouldReturnTypeInRegister(RetTy, getContext(), 743 State.CC)) { 744 uint64_t Size = getContext().getTypeSize(RetTy); 745 746 // As a special-case, if the struct is a "single-element" struct, and 747 // the field is of type "float" or "double", return it in a 748 // floating-point register. (MSVC does not apply this special case.) 749 // We apply a similar transformation for pointer types to improve the 750 // quality of the generated IR. 751 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext())) 752 if ((!IsWin32StructABI && SeltTy->isRealFloatingType()) 753 || SeltTy->hasPointerRepresentation()) 754 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0))); 755 756 // FIXME: We should be able to narrow this integer in cases with dead 757 // padding. 758 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size)); 759 } 760 761 return getIndirectReturnResult(State); 762 } 763 764 // Treat an enum type as its underlying type. 765 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 766 RetTy = EnumTy->getDecl()->getIntegerType(); 767 768 return (RetTy->isPromotableIntegerType() ? 769 ABIArgInfo::getExtend() : ABIArgInfo::getDirect()); 770 } 771 772 static bool isSSEVectorType(ASTContext &Context, QualType Ty) { 773 return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128; 774 } 775 776 static bool isRecordWithSSEVectorType(ASTContext &Context, QualType Ty) { 777 const RecordType *RT = Ty->getAs<RecordType>(); 778 if (!RT) 779 return 0; 780 const RecordDecl *RD = RT->getDecl(); 781 782 // If this is a C++ record, check the bases first. 783 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 784 for (CXXRecordDecl::base_class_const_iterator i = CXXRD->bases_begin(), 785 e = CXXRD->bases_end(); i != e; ++i) 786 if (!isRecordWithSSEVectorType(Context, i->getType())) 787 return false; 788 789 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 790 i != e; ++i) { 791 QualType FT = i->getType(); 792 793 if (isSSEVectorType(Context, FT)) 794 return true; 795 796 if (isRecordWithSSEVectorType(Context, FT)) 797 return true; 798 } 799 800 return false; 801 } 802 803 unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty, 804 unsigned Align) const { 805 // Otherwise, if the alignment is less than or equal to the minimum ABI 806 // alignment, just use the default; the backend will handle this. 807 if (Align <= MinABIStackAlignInBytes) 808 return 0; // Use default alignment. 809 810 // On non-Darwin, the stack type alignment is always 4. 811 if (!IsDarwinVectorABI) { 812 // Set explicit alignment, since we may need to realign the top. 813 return MinABIStackAlignInBytes; 814 } 815 816 // Otherwise, if the type contains an SSE vector type, the alignment is 16. 817 if (Align >= 16 && (isSSEVectorType(getContext(), Ty) || 818 isRecordWithSSEVectorType(getContext(), Ty))) 819 return 16; 820 821 return MinABIStackAlignInBytes; 822 } 823 824 ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal, 825 CCState &State) const { 826 if (!ByVal) { 827 if (State.FreeRegs) { 828 --State.FreeRegs; // Non-byval indirects just use one pointer. 829 return ABIArgInfo::getIndirectInReg(0, false); 830 } 831 return ABIArgInfo::getIndirect(0, false); 832 } 833 834 // Compute the byval alignment. 835 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8; 836 unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign); 837 if (StackAlign == 0) 838 return ABIArgInfo::getIndirect(4); 839 840 // If the stack alignment is less than the type alignment, realign the 841 // argument. 842 if (StackAlign < TypeAlign) 843 return ABIArgInfo::getIndirect(StackAlign, /*ByVal=*/true, 844 /*Realign=*/true); 845 846 return ABIArgInfo::getIndirect(StackAlign); 847 } 848 849 X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const { 850 const Type *T = isSingleElementStruct(Ty, getContext()); 851 if (!T) 852 T = Ty.getTypePtr(); 853 854 if (const BuiltinType *BT = T->getAs<BuiltinType>()) { 855 BuiltinType::Kind K = BT->getKind(); 856 if (K == BuiltinType::Float || K == BuiltinType::Double) 857 return Float; 858 } 859 return Integer; 860 } 861 862 bool X86_32ABIInfo::shouldUseInReg(QualType Ty, CCState &State, 863 bool &NeedsPadding) const { 864 NeedsPadding = false; 865 Class C = classify(Ty); 866 if (C == Float) 867 return false; 868 869 unsigned Size = getContext().getTypeSize(Ty); 870 unsigned SizeInRegs = (Size + 31) / 32; 871 872 if (SizeInRegs == 0) 873 return false; 874 875 if (SizeInRegs > State.FreeRegs) { 876 State.FreeRegs = 0; 877 return false; 878 } 879 880 State.FreeRegs -= SizeInRegs; 881 882 if (State.CC == llvm::CallingConv::X86_FastCall) { 883 if (Size > 32) 884 return false; 885 886 if (Ty->isIntegralOrEnumerationType()) 887 return true; 888 889 if (Ty->isPointerType()) 890 return true; 891 892 if (Ty->isReferenceType()) 893 return true; 894 895 if (State.FreeRegs) 896 NeedsPadding = true; 897 898 return false; 899 } 900 901 return true; 902 } 903 904 ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty, CCState &State) const { 905 // FIXME: Set alignment on indirect arguments. 906 if (isAggregateTypeForABI(Ty)) { 907 if (const RecordType *RT = Ty->getAs<RecordType>()) { 908 if (IsWin32StructABI) 909 return getIndirectResult(Ty, true, State); 910 911 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI())) 912 return getIndirectResult(Ty, RAA == CGCXXABI::RAA_DirectInMemory, 913 State); 914 915 // Structures with flexible arrays are always indirect. 916 if (RT->getDecl()->hasFlexibleArrayMember()) 917 return getIndirectResult(Ty, true, State); 918 } 919 920 // Ignore empty structs/unions. 921 if (isEmptyRecord(getContext(), Ty, true)) 922 return ABIArgInfo::getIgnore(); 923 924 llvm::LLVMContext &LLVMContext = getVMContext(); 925 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext); 926 bool NeedsPadding; 927 if (shouldUseInReg(Ty, State, NeedsPadding)) { 928 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32; 929 SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32); 930 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements); 931 return ABIArgInfo::getDirectInReg(Result); 932 } 933 llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : 0; 934 935 // Expand small (<= 128-bit) record types when we know that the stack layout 936 // of those arguments will match the struct. This is important because the 937 // LLVM backend isn't smart enough to remove byval, which inhibits many 938 // optimizations. 939 if (getContext().getTypeSize(Ty) <= 4*32 && 940 canExpandIndirectArgument(Ty, getContext())) 941 return ABIArgInfo::getExpandWithPadding( 942 State.CC == llvm::CallingConv::X86_FastCall, PaddingType); 943 944 return getIndirectResult(Ty, true, State); 945 } 946 947 if (const VectorType *VT = Ty->getAs<VectorType>()) { 948 // On Darwin, some vectors are passed in memory, we handle this by passing 949 // it as an i8/i16/i32/i64. 950 if (IsDarwinVectorABI) { 951 uint64_t Size = getContext().getTypeSize(Ty); 952 if ((Size == 8 || Size == 16 || Size == 32) || 953 (Size == 64 && VT->getNumElements() == 1)) 954 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 955 Size)); 956 } 957 958 if (IsX86_MMXType(CGT.ConvertType(Ty))) 959 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64)); 960 961 return ABIArgInfo::getDirect(); 962 } 963 964 965 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 966 Ty = EnumTy->getDecl()->getIntegerType(); 967 968 bool NeedsPadding; 969 bool InReg = shouldUseInReg(Ty, State, NeedsPadding); 970 971 if (Ty->isPromotableIntegerType()) { 972 if (InReg) 973 return ABIArgInfo::getExtendInReg(); 974 return ABIArgInfo::getExtend(); 975 } 976 if (InReg) 977 return ABIArgInfo::getDirectInReg(); 978 return ABIArgInfo::getDirect(); 979 } 980 981 void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const { 982 CCState State(FI.getCallingConvention()); 983 if (State.CC == llvm::CallingConv::X86_FastCall) 984 State.FreeRegs = 2; 985 else if (FI.getHasRegParm()) 986 State.FreeRegs = FI.getRegParm(); 987 else 988 State.FreeRegs = DefaultNumRegisterParameters; 989 990 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), State); 991 992 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end(); 993 it != ie; ++it) 994 it->info = classifyArgumentType(it->type, State); 995 } 996 997 llvm::Value *X86_32ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 998 CodeGenFunction &CGF) const { 999 llvm::Type *BPP = CGF.Int8PtrPtrTy; 1000 1001 CGBuilderTy &Builder = CGF.Builder; 1002 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, 1003 "ap"); 1004 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur"); 1005 1006 // Compute if the address needs to be aligned 1007 unsigned Align = CGF.getContext().getTypeAlignInChars(Ty).getQuantity(); 1008 Align = getTypeStackAlignInBytes(Ty, Align); 1009 Align = std::max(Align, 4U); 1010 if (Align > 4) { 1011 // addr = (addr + align - 1) & -align; 1012 llvm::Value *Offset = 1013 llvm::ConstantInt::get(CGF.Int32Ty, Align - 1); 1014 Addr = CGF.Builder.CreateGEP(Addr, Offset); 1015 llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(Addr, 1016 CGF.Int32Ty); 1017 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int32Ty, -Align); 1018 Addr = CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask), 1019 Addr->getType(), 1020 "ap.cur.aligned"); 1021 } 1022 1023 llvm::Type *PTy = 1024 llvm::PointerType::getUnqual(CGF.ConvertType(Ty)); 1025 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy); 1026 1027 uint64_t Offset = 1028 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, Align); 1029 llvm::Value *NextAddr = 1030 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset), 1031 "ap.next"); 1032 Builder.CreateStore(NextAddr, VAListAddrAsBPP); 1033 1034 return AddrTyped; 1035 } 1036 1037 void X86_32TargetCodeGenInfo::SetTargetAttributes(const Decl *D, 1038 llvm::GlobalValue *GV, 1039 CodeGen::CodeGenModule &CGM) const { 1040 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1041 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) { 1042 // Get the LLVM function. 1043 llvm::Function *Fn = cast<llvm::Function>(GV); 1044 1045 // Now add the 'alignstack' attribute with a value of 16. 1046 llvm::AttrBuilder B; 1047 B.addStackAlignmentAttr(16); 1048 Fn->addAttributes(llvm::AttributeSet::FunctionIndex, 1049 llvm::AttributeSet::get(CGM.getLLVMContext(), 1050 llvm::AttributeSet::FunctionIndex, 1051 B)); 1052 } 1053 } 1054 } 1055 1056 bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable( 1057 CodeGen::CodeGenFunction &CGF, 1058 llvm::Value *Address) const { 1059 CodeGen::CGBuilderTy &Builder = CGF.Builder; 1060 1061 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4); 1062 1063 // 0-7 are the eight integer registers; the order is different 1064 // on Darwin (for EH), but the range is the same. 1065 // 8 is %eip. 1066 AssignToArrayRange(Builder, Address, Four8, 0, 8); 1067 1068 if (CGF.CGM.getTarget().getTriple().isOSDarwin()) { 1069 // 12-16 are st(0..4). Not sure why we stop at 4. 1070 // These have size 16, which is sizeof(long double) on 1071 // platforms with 8-byte alignment for that type. 1072 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16); 1073 AssignToArrayRange(Builder, Address, Sixteen8, 12, 16); 1074 1075 } else { 1076 // 9 is %eflags, which doesn't get a size on Darwin for some 1077 // reason. 1078 Builder.CreateStore(Four8, Builder.CreateConstInBoundsGEP1_32(Address, 9)); 1079 1080 // 11-16 are st(0..5). Not sure why we stop at 5. 1081 // These have size 12, which is sizeof(long double) on 1082 // platforms with 4-byte alignment for that type. 1083 llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12); 1084 AssignToArrayRange(Builder, Address, Twelve8, 11, 16); 1085 } 1086 1087 return false; 1088 } 1089 1090 //===----------------------------------------------------------------------===// 1091 // X86-64 ABI Implementation 1092 //===----------------------------------------------------------------------===// 1093 1094 1095 namespace { 1096 /// X86_64ABIInfo - The X86_64 ABI information. 1097 class X86_64ABIInfo : public ABIInfo { 1098 enum Class { 1099 Integer = 0, 1100 SSE, 1101 SSEUp, 1102 X87, 1103 X87Up, 1104 ComplexX87, 1105 NoClass, 1106 Memory 1107 }; 1108 1109 /// merge - Implement the X86_64 ABI merging algorithm. 1110 /// 1111 /// Merge an accumulating classification \arg Accum with a field 1112 /// classification \arg Field. 1113 /// 1114 /// \param Accum - The accumulating classification. This should 1115 /// always be either NoClass or the result of a previous merge 1116 /// call. In addition, this should never be Memory (the caller 1117 /// should just return Memory for the aggregate). 1118 static Class merge(Class Accum, Class Field); 1119 1120 /// postMerge - Implement the X86_64 ABI post merging algorithm. 1121 /// 1122 /// Post merger cleanup, reduces a malformed Hi and Lo pair to 1123 /// final MEMORY or SSE classes when necessary. 1124 /// 1125 /// \param AggregateSize - The size of the current aggregate in 1126 /// the classification process. 1127 /// 1128 /// \param Lo - The classification for the parts of the type 1129 /// residing in the low word of the containing object. 1130 /// 1131 /// \param Hi - The classification for the parts of the type 1132 /// residing in the higher words of the containing object. 1133 /// 1134 void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const; 1135 1136 /// classify - Determine the x86_64 register classes in which the 1137 /// given type T should be passed. 1138 /// 1139 /// \param Lo - The classification for the parts of the type 1140 /// residing in the low word of the containing object. 1141 /// 1142 /// \param Hi - The classification for the parts of the type 1143 /// residing in the high word of the containing object. 1144 /// 1145 /// \param OffsetBase - The bit offset of this type in the 1146 /// containing object. Some parameters are classified different 1147 /// depending on whether they straddle an eightbyte boundary. 1148 /// 1149 /// \param isNamedArg - Whether the argument in question is a "named" 1150 /// argument, as used in AMD64-ABI 3.5.7. 1151 /// 1152 /// If a word is unused its result will be NoClass; if a type should 1153 /// be passed in Memory then at least the classification of \arg Lo 1154 /// will be Memory. 1155 /// 1156 /// The \arg Lo class will be NoClass iff the argument is ignored. 1157 /// 1158 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will 1159 /// also be ComplexX87. 1160 void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi, 1161 bool isNamedArg) const; 1162 1163 llvm::Type *GetByteVectorType(QualType Ty) const; 1164 llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType, 1165 unsigned IROffset, QualType SourceTy, 1166 unsigned SourceOffset) const; 1167 llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType, 1168 unsigned IROffset, QualType SourceTy, 1169 unsigned SourceOffset) const; 1170 1171 /// getIndirectResult - Give a source type \arg Ty, return a suitable result 1172 /// such that the argument will be returned in memory. 1173 ABIArgInfo getIndirectReturnResult(QualType Ty) const; 1174 1175 /// getIndirectResult - Give a source type \arg Ty, return a suitable result 1176 /// such that the argument will be passed in memory. 1177 /// 1178 /// \param freeIntRegs - The number of free integer registers remaining 1179 /// available. 1180 ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const; 1181 1182 ABIArgInfo classifyReturnType(QualType RetTy) const; 1183 1184 ABIArgInfo classifyArgumentType(QualType Ty, 1185 unsigned freeIntRegs, 1186 unsigned &neededInt, 1187 unsigned &neededSSE, 1188 bool isNamedArg) const; 1189 1190 bool IsIllegalVectorType(QualType Ty) const; 1191 1192 /// The 0.98 ABI revision clarified a lot of ambiguities, 1193 /// unfortunately in ways that were not always consistent with 1194 /// certain previous compilers. In particular, platforms which 1195 /// required strict binary compatibility with older versions of GCC 1196 /// may need to exempt themselves. 1197 bool honorsRevision0_98() const { 1198 return !getTarget().getTriple().isOSDarwin(); 1199 } 1200 1201 bool HasAVX; 1202 // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on 1203 // 64-bit hardware. 1204 bool Has64BitPointers; 1205 1206 public: 1207 X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, bool hasavx) : 1208 ABIInfo(CGT), HasAVX(hasavx), 1209 Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) { 1210 } 1211 1212 bool isPassedUsingAVXType(QualType type) const { 1213 unsigned neededInt, neededSSE; 1214 // The freeIntRegs argument doesn't matter here. 1215 ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE, 1216 /*isNamedArg*/true); 1217 if (info.isDirect()) { 1218 llvm::Type *ty = info.getCoerceToType(); 1219 if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty)) 1220 return (vectorTy->getBitWidth() > 128); 1221 } 1222 return false; 1223 } 1224 1225 virtual void computeInfo(CGFunctionInfo &FI) const; 1226 1227 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 1228 CodeGenFunction &CGF) const; 1229 }; 1230 1231 /// WinX86_64ABIInfo - The Windows X86_64 ABI information. 1232 class WinX86_64ABIInfo : public ABIInfo { 1233 1234 ABIArgInfo classify(QualType Ty, bool IsReturnType) const; 1235 1236 public: 1237 WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {} 1238 1239 virtual void computeInfo(CGFunctionInfo &FI) const; 1240 1241 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 1242 CodeGenFunction &CGF) const; 1243 }; 1244 1245 class X86_64TargetCodeGenInfo : public TargetCodeGenInfo { 1246 public: 1247 X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX) 1248 : TargetCodeGenInfo(new X86_64ABIInfo(CGT, HasAVX)) {} 1249 1250 const X86_64ABIInfo &getABIInfo() const { 1251 return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo()); 1252 } 1253 1254 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const { 1255 return 7; 1256 } 1257 1258 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 1259 llvm::Value *Address) const { 1260 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8); 1261 1262 // 0-15 are the 16 integer registers. 1263 // 16 is %rip. 1264 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16); 1265 return false; 1266 } 1267 1268 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF, 1269 StringRef Constraint, 1270 llvm::Type* Ty) const { 1271 return X86AdjustInlineAsmType(CGF, Constraint, Ty); 1272 } 1273 1274 bool isNoProtoCallVariadic(const CallArgList &args, 1275 const FunctionNoProtoType *fnType) const { 1276 // The default CC on x86-64 sets %al to the number of SSA 1277 // registers used, and GCC sets this when calling an unprototyped 1278 // function, so we override the default behavior. However, don't do 1279 // that when AVX types are involved: the ABI explicitly states it is 1280 // undefined, and it doesn't work in practice because of how the ABI 1281 // defines varargs anyway. 1282 if (fnType->getCallConv() == CC_C) { 1283 bool HasAVXType = false; 1284 for (CallArgList::const_iterator 1285 it = args.begin(), ie = args.end(); it != ie; ++it) { 1286 if (getABIInfo().isPassedUsingAVXType(it->Ty)) { 1287 HasAVXType = true; 1288 break; 1289 } 1290 } 1291 1292 if (!HasAVXType) 1293 return true; 1294 } 1295 1296 return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType); 1297 } 1298 1299 llvm::Constant *getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const { 1300 unsigned Sig = (0xeb << 0) | // jmp rel8 1301 (0x0a << 8) | // .+0x0c 1302 ('F' << 16) | 1303 ('T' << 24); 1304 return llvm::ConstantInt::get(CGM.Int32Ty, Sig); 1305 } 1306 1307 }; 1308 1309 static std::string qualifyWindowsLibrary(llvm::StringRef Lib) { 1310 // If the argument does not end in .lib, automatically add the suffix. This 1311 // matches the behavior of MSVC. 1312 std::string ArgStr = Lib; 1313 if (!Lib.endswith_lower(".lib")) 1314 ArgStr += ".lib"; 1315 return ArgStr; 1316 } 1317 1318 class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo { 1319 public: 1320 WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, 1321 bool d, bool p, bool w, unsigned RegParms) 1322 : X86_32TargetCodeGenInfo(CGT, d, p, w, RegParms) {} 1323 1324 void getDependentLibraryOption(llvm::StringRef Lib, 1325 llvm::SmallString<24> &Opt) const { 1326 Opt = "/DEFAULTLIB:"; 1327 Opt += qualifyWindowsLibrary(Lib); 1328 } 1329 1330 void getDetectMismatchOption(llvm::StringRef Name, 1331 llvm::StringRef Value, 1332 llvm::SmallString<32> &Opt) const { 1333 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\""; 1334 } 1335 }; 1336 1337 class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo { 1338 public: 1339 WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT) 1340 : TargetCodeGenInfo(new WinX86_64ABIInfo(CGT)) {} 1341 1342 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const { 1343 return 7; 1344 } 1345 1346 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 1347 llvm::Value *Address) const { 1348 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8); 1349 1350 // 0-15 are the 16 integer registers. 1351 // 16 is %rip. 1352 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16); 1353 return false; 1354 } 1355 1356 void getDependentLibraryOption(llvm::StringRef Lib, 1357 llvm::SmallString<24> &Opt) const { 1358 Opt = "/DEFAULTLIB:"; 1359 Opt += qualifyWindowsLibrary(Lib); 1360 } 1361 1362 void getDetectMismatchOption(llvm::StringRef Name, 1363 llvm::StringRef Value, 1364 llvm::SmallString<32> &Opt) const { 1365 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\""; 1366 } 1367 }; 1368 1369 } 1370 1371 void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo, 1372 Class &Hi) const { 1373 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done: 1374 // 1375 // (a) If one of the classes is Memory, the whole argument is passed in 1376 // memory. 1377 // 1378 // (b) If X87UP is not preceded by X87, the whole argument is passed in 1379 // memory. 1380 // 1381 // (c) If the size of the aggregate exceeds two eightbytes and the first 1382 // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole 1383 // argument is passed in memory. NOTE: This is necessary to keep the 1384 // ABI working for processors that don't support the __m256 type. 1385 // 1386 // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE. 1387 // 1388 // Some of these are enforced by the merging logic. Others can arise 1389 // only with unions; for example: 1390 // union { _Complex double; unsigned; } 1391 // 1392 // Note that clauses (b) and (c) were added in 0.98. 1393 // 1394 if (Hi == Memory) 1395 Lo = Memory; 1396 if (Hi == X87Up && Lo != X87 && honorsRevision0_98()) 1397 Lo = Memory; 1398 if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp)) 1399 Lo = Memory; 1400 if (Hi == SSEUp && Lo != SSE) 1401 Hi = SSE; 1402 } 1403 1404 X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) { 1405 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is 1406 // classified recursively so that always two fields are 1407 // considered. The resulting class is calculated according to 1408 // the classes of the fields in the eightbyte: 1409 // 1410 // (a) If both classes are equal, this is the resulting class. 1411 // 1412 // (b) If one of the classes is NO_CLASS, the resulting class is 1413 // the other class. 1414 // 1415 // (c) If one of the classes is MEMORY, the result is the MEMORY 1416 // class. 1417 // 1418 // (d) If one of the classes is INTEGER, the result is the 1419 // INTEGER. 1420 // 1421 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class, 1422 // MEMORY is used as class. 1423 // 1424 // (f) Otherwise class SSE is used. 1425 1426 // Accum should never be memory (we should have returned) or 1427 // ComplexX87 (because this cannot be passed in a structure). 1428 assert((Accum != Memory && Accum != ComplexX87) && 1429 "Invalid accumulated classification during merge."); 1430 if (Accum == Field || Field == NoClass) 1431 return Accum; 1432 if (Field == Memory) 1433 return Memory; 1434 if (Accum == NoClass) 1435 return Field; 1436 if (Accum == Integer || Field == Integer) 1437 return Integer; 1438 if (Field == X87 || Field == X87Up || Field == ComplexX87 || 1439 Accum == X87 || Accum == X87Up) 1440 return Memory; 1441 return SSE; 1442 } 1443 1444 void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase, 1445 Class &Lo, Class &Hi, bool isNamedArg) const { 1446 // FIXME: This code can be simplified by introducing a simple value class for 1447 // Class pairs with appropriate constructor methods for the various 1448 // situations. 1449 1450 // FIXME: Some of the split computations are wrong; unaligned vectors 1451 // shouldn't be passed in registers for example, so there is no chance they 1452 // can straddle an eightbyte. Verify & simplify. 1453 1454 Lo = Hi = NoClass; 1455 1456 Class &Current = OffsetBase < 64 ? Lo : Hi; 1457 Current = Memory; 1458 1459 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) { 1460 BuiltinType::Kind k = BT->getKind(); 1461 1462 if (k == BuiltinType::Void) { 1463 Current = NoClass; 1464 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) { 1465 Lo = Integer; 1466 Hi = Integer; 1467 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) { 1468 Current = Integer; 1469 } else if ((k == BuiltinType::Float || k == BuiltinType::Double) || 1470 (k == BuiltinType::LongDouble && 1471 getTarget().getTriple().isOSNaCl())) { 1472 Current = SSE; 1473 } else if (k == BuiltinType::LongDouble) { 1474 Lo = X87; 1475 Hi = X87Up; 1476 } 1477 // FIXME: _Decimal32 and _Decimal64 are SSE. 1478 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp). 1479 return; 1480 } 1481 1482 if (const EnumType *ET = Ty->getAs<EnumType>()) { 1483 // Classify the underlying integer type. 1484 classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg); 1485 return; 1486 } 1487 1488 if (Ty->hasPointerRepresentation()) { 1489 Current = Integer; 1490 return; 1491 } 1492 1493 if (Ty->isMemberPointerType()) { 1494 if (Ty->isMemberFunctionPointerType() && Has64BitPointers) 1495 Lo = Hi = Integer; 1496 else 1497 Current = Integer; 1498 return; 1499 } 1500 1501 if (const VectorType *VT = Ty->getAs<VectorType>()) { 1502 uint64_t Size = getContext().getTypeSize(VT); 1503 if (Size == 32) { 1504 // gcc passes all <4 x char>, <2 x short>, <1 x int>, <1 x 1505 // float> as integer. 1506 Current = Integer; 1507 1508 // If this type crosses an eightbyte boundary, it should be 1509 // split. 1510 uint64_t EB_Real = (OffsetBase) / 64; 1511 uint64_t EB_Imag = (OffsetBase + Size - 1) / 64; 1512 if (EB_Real != EB_Imag) 1513 Hi = Lo; 1514 } else if (Size == 64) { 1515 // gcc passes <1 x double> in memory. :( 1516 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double)) 1517 return; 1518 1519 // gcc passes <1 x long long> as INTEGER. 1520 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::LongLong) || 1521 VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULongLong) || 1522 VT->getElementType()->isSpecificBuiltinType(BuiltinType::Long) || 1523 VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULong)) 1524 Current = Integer; 1525 else 1526 Current = SSE; 1527 1528 // If this type crosses an eightbyte boundary, it should be 1529 // split. 1530 if (OffsetBase && OffsetBase != 64) 1531 Hi = Lo; 1532 } else if (Size == 128 || (HasAVX && isNamedArg && Size == 256)) { 1533 // Arguments of 256-bits are split into four eightbyte chunks. The 1534 // least significant one belongs to class SSE and all the others to class 1535 // SSEUP. The original Lo and Hi design considers that types can't be 1536 // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense. 1537 // This design isn't correct for 256-bits, but since there're no cases 1538 // where the upper parts would need to be inspected, avoid adding 1539 // complexity and just consider Hi to match the 64-256 part. 1540 // 1541 // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in 1542 // registers if they are "named", i.e. not part of the "..." of a 1543 // variadic function. 1544 Lo = SSE; 1545 Hi = SSEUp; 1546 } 1547 return; 1548 } 1549 1550 if (const ComplexType *CT = Ty->getAs<ComplexType>()) { 1551 QualType ET = getContext().getCanonicalType(CT->getElementType()); 1552 1553 uint64_t Size = getContext().getTypeSize(Ty); 1554 if (ET->isIntegralOrEnumerationType()) { 1555 if (Size <= 64) 1556 Current = Integer; 1557 else if (Size <= 128) 1558 Lo = Hi = Integer; 1559 } else if (ET == getContext().FloatTy) 1560 Current = SSE; 1561 else if (ET == getContext().DoubleTy || 1562 (ET == getContext().LongDoubleTy && 1563 getTarget().getTriple().isOSNaCl())) 1564 Lo = Hi = SSE; 1565 else if (ET == getContext().LongDoubleTy) 1566 Current = ComplexX87; 1567 1568 // If this complex type crosses an eightbyte boundary then it 1569 // should be split. 1570 uint64_t EB_Real = (OffsetBase) / 64; 1571 uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64; 1572 if (Hi == NoClass && EB_Real != EB_Imag) 1573 Hi = Lo; 1574 1575 return; 1576 } 1577 1578 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) { 1579 // Arrays are treated like structures. 1580 1581 uint64_t Size = getContext().getTypeSize(Ty); 1582 1583 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger 1584 // than four eightbytes, ..., it has class MEMORY. 1585 if (Size > 256) 1586 return; 1587 1588 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned 1589 // fields, it has class MEMORY. 1590 // 1591 // Only need to check alignment of array base. 1592 if (OffsetBase % getContext().getTypeAlign(AT->getElementType())) 1593 return; 1594 1595 // Otherwise implement simplified merge. We could be smarter about 1596 // this, but it isn't worth it and would be harder to verify. 1597 Current = NoClass; 1598 uint64_t EltSize = getContext().getTypeSize(AT->getElementType()); 1599 uint64_t ArraySize = AT->getSize().getZExtValue(); 1600 1601 // The only case a 256-bit wide vector could be used is when the array 1602 // contains a single 256-bit element. Since Lo and Hi logic isn't extended 1603 // to work for sizes wider than 128, early check and fallback to memory. 1604 if (Size > 128 && EltSize != 256) 1605 return; 1606 1607 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) { 1608 Class FieldLo, FieldHi; 1609 classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg); 1610 Lo = merge(Lo, FieldLo); 1611 Hi = merge(Hi, FieldHi); 1612 if (Lo == Memory || Hi == Memory) 1613 break; 1614 } 1615 1616 postMerge(Size, Lo, Hi); 1617 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification."); 1618 return; 1619 } 1620 1621 if (const RecordType *RT = Ty->getAs<RecordType>()) { 1622 uint64_t Size = getContext().getTypeSize(Ty); 1623 1624 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger 1625 // than four eightbytes, ..., it has class MEMORY. 1626 if (Size > 256) 1627 return; 1628 1629 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial 1630 // copy constructor or a non-trivial destructor, it is passed by invisible 1631 // reference. 1632 if (getRecordArgABI(RT, getCXXABI())) 1633 return; 1634 1635 const RecordDecl *RD = RT->getDecl(); 1636 1637 // Assume variable sized types are passed in memory. 1638 if (RD->hasFlexibleArrayMember()) 1639 return; 1640 1641 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD); 1642 1643 // Reset Lo class, this will be recomputed. 1644 Current = NoClass; 1645 1646 // If this is a C++ record, classify the bases first. 1647 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 1648 for (CXXRecordDecl::base_class_const_iterator i = CXXRD->bases_begin(), 1649 e = CXXRD->bases_end(); i != e; ++i) { 1650 assert(!i->isVirtual() && !i->getType()->isDependentType() && 1651 "Unexpected base class!"); 1652 const CXXRecordDecl *Base = 1653 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl()); 1654 1655 // Classify this field. 1656 // 1657 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a 1658 // single eightbyte, each is classified separately. Each eightbyte gets 1659 // initialized to class NO_CLASS. 1660 Class FieldLo, FieldHi; 1661 uint64_t Offset = 1662 OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base)); 1663 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg); 1664 Lo = merge(Lo, FieldLo); 1665 Hi = merge(Hi, FieldHi); 1666 if (Lo == Memory || Hi == Memory) 1667 break; 1668 } 1669 } 1670 1671 // Classify the fields one at a time, merging the results. 1672 unsigned idx = 0; 1673 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 1674 i != e; ++i, ++idx) { 1675 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx); 1676 bool BitField = i->isBitField(); 1677 1678 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than 1679 // four eightbytes, or it contains unaligned fields, it has class MEMORY. 1680 // 1681 // The only case a 256-bit wide vector could be used is when the struct 1682 // contains a single 256-bit element. Since Lo and Hi logic isn't extended 1683 // to work for sizes wider than 128, early check and fallback to memory. 1684 // 1685 if (Size > 128 && getContext().getTypeSize(i->getType()) != 256) { 1686 Lo = Memory; 1687 return; 1688 } 1689 // Note, skip this test for bit-fields, see below. 1690 if (!BitField && Offset % getContext().getTypeAlign(i->getType())) { 1691 Lo = Memory; 1692 return; 1693 } 1694 1695 // Classify this field. 1696 // 1697 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate 1698 // exceeds a single eightbyte, each is classified 1699 // separately. Each eightbyte gets initialized to class 1700 // NO_CLASS. 1701 Class FieldLo, FieldHi; 1702 1703 // Bit-fields require special handling, they do not force the 1704 // structure to be passed in memory even if unaligned, and 1705 // therefore they can straddle an eightbyte. 1706 if (BitField) { 1707 // Ignore padding bit-fields. 1708 if (i->isUnnamedBitfield()) 1709 continue; 1710 1711 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx); 1712 uint64_t Size = i->getBitWidthValue(getContext()); 1713 1714 uint64_t EB_Lo = Offset / 64; 1715 uint64_t EB_Hi = (Offset + Size - 1) / 64; 1716 1717 if (EB_Lo) { 1718 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes."); 1719 FieldLo = NoClass; 1720 FieldHi = Integer; 1721 } else { 1722 FieldLo = Integer; 1723 FieldHi = EB_Hi ? Integer : NoClass; 1724 } 1725 } else 1726 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg); 1727 Lo = merge(Lo, FieldLo); 1728 Hi = merge(Hi, FieldHi); 1729 if (Lo == Memory || Hi == Memory) 1730 break; 1731 } 1732 1733 postMerge(Size, Lo, Hi); 1734 } 1735 } 1736 1737 ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const { 1738 // If this is a scalar LLVM value then assume LLVM will pass it in the right 1739 // place naturally. 1740 if (!isAggregateTypeForABI(Ty)) { 1741 // Treat an enum type as its underlying type. 1742 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 1743 Ty = EnumTy->getDecl()->getIntegerType(); 1744 1745 return (Ty->isPromotableIntegerType() ? 1746 ABIArgInfo::getExtend() : ABIArgInfo::getDirect()); 1747 } 1748 1749 return ABIArgInfo::getIndirect(0); 1750 } 1751 1752 bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const { 1753 if (const VectorType *VecTy = Ty->getAs<VectorType>()) { 1754 uint64_t Size = getContext().getTypeSize(VecTy); 1755 unsigned LargestVector = HasAVX ? 256 : 128; 1756 if (Size <= 64 || Size > LargestVector) 1757 return true; 1758 } 1759 1760 return false; 1761 } 1762 1763 ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty, 1764 unsigned freeIntRegs) const { 1765 // If this is a scalar LLVM value then assume LLVM will pass it in the right 1766 // place naturally. 1767 // 1768 // This assumption is optimistic, as there could be free registers available 1769 // when we need to pass this argument in memory, and LLVM could try to pass 1770 // the argument in the free register. This does not seem to happen currently, 1771 // but this code would be much safer if we could mark the argument with 1772 // 'onstack'. See PR12193. 1773 if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty)) { 1774 // Treat an enum type as its underlying type. 1775 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 1776 Ty = EnumTy->getDecl()->getIntegerType(); 1777 1778 return (Ty->isPromotableIntegerType() ? 1779 ABIArgInfo::getExtend() : ABIArgInfo::getDirect()); 1780 } 1781 1782 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 1783 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory); 1784 1785 // Compute the byval alignment. We specify the alignment of the byval in all 1786 // cases so that the mid-level optimizer knows the alignment of the byval. 1787 unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U); 1788 1789 // Attempt to avoid passing indirect results using byval when possible. This 1790 // is important for good codegen. 1791 // 1792 // We do this by coercing the value into a scalar type which the backend can 1793 // handle naturally (i.e., without using byval). 1794 // 1795 // For simplicity, we currently only do this when we have exhausted all of the 1796 // free integer registers. Doing this when there are free integer registers 1797 // would require more care, as we would have to ensure that the coerced value 1798 // did not claim the unused register. That would require either reording the 1799 // arguments to the function (so that any subsequent inreg values came first), 1800 // or only doing this optimization when there were no following arguments that 1801 // might be inreg. 1802 // 1803 // We currently expect it to be rare (particularly in well written code) for 1804 // arguments to be passed on the stack when there are still free integer 1805 // registers available (this would typically imply large structs being passed 1806 // by value), so this seems like a fair tradeoff for now. 1807 // 1808 // We can revisit this if the backend grows support for 'onstack' parameter 1809 // attributes. See PR12193. 1810 if (freeIntRegs == 0) { 1811 uint64_t Size = getContext().getTypeSize(Ty); 1812 1813 // If this type fits in an eightbyte, coerce it into the matching integral 1814 // type, which will end up on the stack (with alignment 8). 1815 if (Align == 8 && Size <= 64) 1816 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 1817 Size)); 1818 } 1819 1820 return ABIArgInfo::getIndirect(Align); 1821 } 1822 1823 /// GetByteVectorType - The ABI specifies that a value should be passed in an 1824 /// full vector XMM/YMM register. Pick an LLVM IR type that will be passed as a 1825 /// vector register. 1826 llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const { 1827 llvm::Type *IRType = CGT.ConvertType(Ty); 1828 1829 // Wrapper structs that just contain vectors are passed just like vectors, 1830 // strip them off if present. 1831 llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType); 1832 while (STy && STy->getNumElements() == 1) { 1833 IRType = STy->getElementType(0); 1834 STy = dyn_cast<llvm::StructType>(IRType); 1835 } 1836 1837 // If the preferred type is a 16-byte vector, prefer to pass it. 1838 if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(IRType)){ 1839 llvm::Type *EltTy = VT->getElementType(); 1840 unsigned BitWidth = VT->getBitWidth(); 1841 if ((BitWidth >= 128 && BitWidth <= 256) && 1842 (EltTy->isFloatTy() || EltTy->isDoubleTy() || 1843 EltTy->isIntegerTy(8) || EltTy->isIntegerTy(16) || 1844 EltTy->isIntegerTy(32) || EltTy->isIntegerTy(64) || 1845 EltTy->isIntegerTy(128))) 1846 return VT; 1847 } 1848 1849 return llvm::VectorType::get(llvm::Type::getDoubleTy(getVMContext()), 2); 1850 } 1851 1852 /// BitsContainNoUserData - Return true if the specified [start,end) bit range 1853 /// is known to either be off the end of the specified type or being in 1854 /// alignment padding. The user type specified is known to be at most 128 bits 1855 /// in size, and have passed through X86_64ABIInfo::classify with a successful 1856 /// classification that put one of the two halves in the INTEGER class. 1857 /// 1858 /// It is conservatively correct to return false. 1859 static bool BitsContainNoUserData(QualType Ty, unsigned StartBit, 1860 unsigned EndBit, ASTContext &Context) { 1861 // If the bytes being queried are off the end of the type, there is no user 1862 // data hiding here. This handles analysis of builtins, vectors and other 1863 // types that don't contain interesting padding. 1864 unsigned TySize = (unsigned)Context.getTypeSize(Ty); 1865 if (TySize <= StartBit) 1866 return true; 1867 1868 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) { 1869 unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType()); 1870 unsigned NumElts = (unsigned)AT->getSize().getZExtValue(); 1871 1872 // Check each element to see if the element overlaps with the queried range. 1873 for (unsigned i = 0; i != NumElts; ++i) { 1874 // If the element is after the span we care about, then we're done.. 1875 unsigned EltOffset = i*EltSize; 1876 if (EltOffset >= EndBit) break; 1877 1878 unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0; 1879 if (!BitsContainNoUserData(AT->getElementType(), EltStart, 1880 EndBit-EltOffset, Context)) 1881 return false; 1882 } 1883 // If it overlaps no elements, then it is safe to process as padding. 1884 return true; 1885 } 1886 1887 if (const RecordType *RT = Ty->getAs<RecordType>()) { 1888 const RecordDecl *RD = RT->getDecl(); 1889 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); 1890 1891 // If this is a C++ record, check the bases first. 1892 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 1893 for (CXXRecordDecl::base_class_const_iterator i = CXXRD->bases_begin(), 1894 e = CXXRD->bases_end(); i != e; ++i) { 1895 assert(!i->isVirtual() && !i->getType()->isDependentType() && 1896 "Unexpected base class!"); 1897 const CXXRecordDecl *Base = 1898 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl()); 1899 1900 // If the base is after the span we care about, ignore it. 1901 unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base)); 1902 if (BaseOffset >= EndBit) continue; 1903 1904 unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0; 1905 if (!BitsContainNoUserData(i->getType(), BaseStart, 1906 EndBit-BaseOffset, Context)) 1907 return false; 1908 } 1909 } 1910 1911 // Verify that no field has data that overlaps the region of interest. Yes 1912 // this could be sped up a lot by being smarter about queried fields, 1913 // however we're only looking at structs up to 16 bytes, so we don't care 1914 // much. 1915 unsigned idx = 0; 1916 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 1917 i != e; ++i, ++idx) { 1918 unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx); 1919 1920 // If we found a field after the region we care about, then we're done. 1921 if (FieldOffset >= EndBit) break; 1922 1923 unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0; 1924 if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset, 1925 Context)) 1926 return false; 1927 } 1928 1929 // If nothing in this record overlapped the area of interest, then we're 1930 // clean. 1931 return true; 1932 } 1933 1934 return false; 1935 } 1936 1937 /// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a 1938 /// float member at the specified offset. For example, {int,{float}} has a 1939 /// float at offset 4. It is conservatively correct for this routine to return 1940 /// false. 1941 static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset, 1942 const llvm::DataLayout &TD) { 1943 // Base case if we find a float. 1944 if (IROffset == 0 && IRType->isFloatTy()) 1945 return true; 1946 1947 // If this is a struct, recurse into the field at the specified offset. 1948 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) { 1949 const llvm::StructLayout *SL = TD.getStructLayout(STy); 1950 unsigned Elt = SL->getElementContainingOffset(IROffset); 1951 IROffset -= SL->getElementOffset(Elt); 1952 return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD); 1953 } 1954 1955 // If this is an array, recurse into the field at the specified offset. 1956 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) { 1957 llvm::Type *EltTy = ATy->getElementType(); 1958 unsigned EltSize = TD.getTypeAllocSize(EltTy); 1959 IROffset -= IROffset/EltSize*EltSize; 1960 return ContainsFloatAtOffset(EltTy, IROffset, TD); 1961 } 1962 1963 return false; 1964 } 1965 1966 1967 /// GetSSETypeAtOffset - Return a type that will be passed by the backend in the 1968 /// low 8 bytes of an XMM register, corresponding to the SSE class. 1969 llvm::Type *X86_64ABIInfo:: 1970 GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset, 1971 QualType SourceTy, unsigned SourceOffset) const { 1972 // The only three choices we have are either double, <2 x float>, or float. We 1973 // pass as float if the last 4 bytes is just padding. This happens for 1974 // structs that contain 3 floats. 1975 if (BitsContainNoUserData(SourceTy, SourceOffset*8+32, 1976 SourceOffset*8+64, getContext())) 1977 return llvm::Type::getFloatTy(getVMContext()); 1978 1979 // We want to pass as <2 x float> if the LLVM IR type contains a float at 1980 // offset+0 and offset+4. Walk the LLVM IR type to find out if this is the 1981 // case. 1982 if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) && 1983 ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout())) 1984 return llvm::VectorType::get(llvm::Type::getFloatTy(getVMContext()), 2); 1985 1986 return llvm::Type::getDoubleTy(getVMContext()); 1987 } 1988 1989 1990 /// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in 1991 /// an 8-byte GPR. This means that we either have a scalar or we are talking 1992 /// about the high or low part of an up-to-16-byte struct. This routine picks 1993 /// the best LLVM IR type to represent this, which may be i64 or may be anything 1994 /// else that the backend will pass in a GPR that works better (e.g. i8, %foo*, 1995 /// etc). 1996 /// 1997 /// PrefType is an LLVM IR type that corresponds to (part of) the IR type for 1998 /// the source type. IROffset is an offset in bytes into the LLVM IR type that 1999 /// the 8-byte value references. PrefType may be null. 2000 /// 2001 /// SourceTy is the source level type for the entire argument. SourceOffset is 2002 /// an offset into this that we're processing (which is always either 0 or 8). 2003 /// 2004 llvm::Type *X86_64ABIInfo:: 2005 GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset, 2006 QualType SourceTy, unsigned SourceOffset) const { 2007 // If we're dealing with an un-offset LLVM IR type, then it means that we're 2008 // returning an 8-byte unit starting with it. See if we can safely use it. 2009 if (IROffset == 0) { 2010 // Pointers and int64's always fill the 8-byte unit. 2011 if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) || 2012 IRType->isIntegerTy(64)) 2013 return IRType; 2014 2015 // If we have a 1/2/4-byte integer, we can use it only if the rest of the 2016 // goodness in the source type is just tail padding. This is allowed to 2017 // kick in for struct {double,int} on the int, but not on 2018 // struct{double,int,int} because we wouldn't return the second int. We 2019 // have to do this analysis on the source type because we can't depend on 2020 // unions being lowered a specific way etc. 2021 if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) || 2022 IRType->isIntegerTy(32) || 2023 (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) { 2024 unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 : 2025 cast<llvm::IntegerType>(IRType)->getBitWidth(); 2026 2027 if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth, 2028 SourceOffset*8+64, getContext())) 2029 return IRType; 2030 } 2031 } 2032 2033 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) { 2034 // If this is a struct, recurse into the field at the specified offset. 2035 const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy); 2036 if (IROffset < SL->getSizeInBytes()) { 2037 unsigned FieldIdx = SL->getElementContainingOffset(IROffset); 2038 IROffset -= SL->getElementOffset(FieldIdx); 2039 2040 return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset, 2041 SourceTy, SourceOffset); 2042 } 2043 } 2044 2045 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) { 2046 llvm::Type *EltTy = ATy->getElementType(); 2047 unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy); 2048 unsigned EltOffset = IROffset/EltSize*EltSize; 2049 return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy, 2050 SourceOffset); 2051 } 2052 2053 // Okay, we don't have any better idea of what to pass, so we pass this in an 2054 // integer register that isn't too big to fit the rest of the struct. 2055 unsigned TySizeInBytes = 2056 (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity(); 2057 2058 assert(TySizeInBytes != SourceOffset && "Empty field?"); 2059 2060 // It is always safe to classify this as an integer type up to i64 that 2061 // isn't larger than the structure. 2062 return llvm::IntegerType::get(getVMContext(), 2063 std::min(TySizeInBytes-SourceOffset, 8U)*8); 2064 } 2065 2066 2067 /// GetX86_64ByValArgumentPair - Given a high and low type that can ideally 2068 /// be used as elements of a two register pair to pass or return, return a 2069 /// first class aggregate to represent them. For example, if the low part of 2070 /// a by-value argument should be passed as i32* and the high part as float, 2071 /// return {i32*, float}. 2072 static llvm::Type * 2073 GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi, 2074 const llvm::DataLayout &TD) { 2075 // In order to correctly satisfy the ABI, we need to the high part to start 2076 // at offset 8. If the high and low parts we inferred are both 4-byte types 2077 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have 2078 // the second element at offset 8. Check for this: 2079 unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo); 2080 unsigned HiAlign = TD.getABITypeAlignment(Hi); 2081 unsigned HiStart = llvm::DataLayout::RoundUpAlignment(LoSize, HiAlign); 2082 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!"); 2083 2084 // To handle this, we have to increase the size of the low part so that the 2085 // second element will start at an 8 byte offset. We can't increase the size 2086 // of the second element because it might make us access off the end of the 2087 // struct. 2088 if (HiStart != 8) { 2089 // There are only two sorts of types the ABI generation code can produce for 2090 // the low part of a pair that aren't 8 bytes in size: float or i8/i16/i32. 2091 // Promote these to a larger type. 2092 if (Lo->isFloatTy()) 2093 Lo = llvm::Type::getDoubleTy(Lo->getContext()); 2094 else { 2095 assert(Lo->isIntegerTy() && "Invalid/unknown lo type"); 2096 Lo = llvm::Type::getInt64Ty(Lo->getContext()); 2097 } 2098 } 2099 2100 llvm::StructType *Result = llvm::StructType::get(Lo, Hi, NULL); 2101 2102 2103 // Verify that the second element is at an 8-byte offset. 2104 assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 && 2105 "Invalid x86-64 argument pair!"); 2106 return Result; 2107 } 2108 2109 ABIArgInfo X86_64ABIInfo:: 2110 classifyReturnType(QualType RetTy) const { 2111 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the 2112 // classification algorithm. 2113 X86_64ABIInfo::Class Lo, Hi; 2114 classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true); 2115 2116 // Check some invariants. 2117 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification."); 2118 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification."); 2119 2120 llvm::Type *ResType = 0; 2121 switch (Lo) { 2122 case NoClass: 2123 if (Hi == NoClass) 2124 return ABIArgInfo::getIgnore(); 2125 // If the low part is just padding, it takes no register, leave ResType 2126 // null. 2127 assert((Hi == SSE || Hi == Integer || Hi == X87Up) && 2128 "Unknown missing lo part"); 2129 break; 2130 2131 case SSEUp: 2132 case X87Up: 2133 llvm_unreachable("Invalid classification for lo word."); 2134 2135 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via 2136 // hidden argument. 2137 case Memory: 2138 return getIndirectReturnResult(RetTy); 2139 2140 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next 2141 // available register of the sequence %rax, %rdx is used. 2142 case Integer: 2143 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0); 2144 2145 // If we have a sign or zero extended integer, make sure to return Extend 2146 // so that the parameter gets the right LLVM IR attributes. 2147 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) { 2148 // Treat an enum type as its underlying type. 2149 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 2150 RetTy = EnumTy->getDecl()->getIntegerType(); 2151 2152 if (RetTy->isIntegralOrEnumerationType() && 2153 RetTy->isPromotableIntegerType()) 2154 return ABIArgInfo::getExtend(); 2155 } 2156 break; 2157 2158 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next 2159 // available SSE register of the sequence %xmm0, %xmm1 is used. 2160 case SSE: 2161 ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0); 2162 break; 2163 2164 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is 2165 // returned on the X87 stack in %st0 as 80-bit x87 number. 2166 case X87: 2167 ResType = llvm::Type::getX86_FP80Ty(getVMContext()); 2168 break; 2169 2170 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real 2171 // part of the value is returned in %st0 and the imaginary part in 2172 // %st1. 2173 case ComplexX87: 2174 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification."); 2175 ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()), 2176 llvm::Type::getX86_FP80Ty(getVMContext()), 2177 NULL); 2178 break; 2179 } 2180 2181 llvm::Type *HighPart = 0; 2182 switch (Hi) { 2183 // Memory was handled previously and X87 should 2184 // never occur as a hi class. 2185 case Memory: 2186 case X87: 2187 llvm_unreachable("Invalid classification for hi word."); 2188 2189 case ComplexX87: // Previously handled. 2190 case NoClass: 2191 break; 2192 2193 case Integer: 2194 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8); 2195 if (Lo == NoClass) // Return HighPart at offset 8 in memory. 2196 return ABIArgInfo::getDirect(HighPart, 8); 2197 break; 2198 case SSE: 2199 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8); 2200 if (Lo == NoClass) // Return HighPart at offset 8 in memory. 2201 return ABIArgInfo::getDirect(HighPart, 8); 2202 break; 2203 2204 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte 2205 // is passed in the next available eightbyte chunk if the last used 2206 // vector register. 2207 // 2208 // SSEUP should always be preceded by SSE, just widen. 2209 case SSEUp: 2210 assert(Lo == SSE && "Unexpected SSEUp classification."); 2211 ResType = GetByteVectorType(RetTy); 2212 break; 2213 2214 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is 2215 // returned together with the previous X87 value in %st0. 2216 case X87Up: 2217 // If X87Up is preceded by X87, we don't need to do 2218 // anything. However, in some cases with unions it may not be 2219 // preceded by X87. In such situations we follow gcc and pass the 2220 // extra bits in an SSE reg. 2221 if (Lo != X87) { 2222 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8); 2223 if (Lo == NoClass) // Return HighPart at offset 8 in memory. 2224 return ABIArgInfo::getDirect(HighPart, 8); 2225 } 2226 break; 2227 } 2228 2229 // If a high part was specified, merge it together with the low part. It is 2230 // known to pass in the high eightbyte of the result. We do this by forming a 2231 // first class struct aggregate with the high and low part: {low, high} 2232 if (HighPart) 2233 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout()); 2234 2235 return ABIArgInfo::getDirect(ResType); 2236 } 2237 2238 ABIArgInfo X86_64ABIInfo::classifyArgumentType( 2239 QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE, 2240 bool isNamedArg) 2241 const 2242 { 2243 X86_64ABIInfo::Class Lo, Hi; 2244 classify(Ty, 0, Lo, Hi, isNamedArg); 2245 2246 // Check some invariants. 2247 // FIXME: Enforce these by construction. 2248 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification."); 2249 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification."); 2250 2251 neededInt = 0; 2252 neededSSE = 0; 2253 llvm::Type *ResType = 0; 2254 switch (Lo) { 2255 case NoClass: 2256 if (Hi == NoClass) 2257 return ABIArgInfo::getIgnore(); 2258 // If the low part is just padding, it takes no register, leave ResType 2259 // null. 2260 assert((Hi == SSE || Hi == Integer || Hi == X87Up) && 2261 "Unknown missing lo part"); 2262 break; 2263 2264 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument 2265 // on the stack. 2266 case Memory: 2267 2268 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or 2269 // COMPLEX_X87, it is passed in memory. 2270 case X87: 2271 case ComplexX87: 2272 if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect) 2273 ++neededInt; 2274 return getIndirectResult(Ty, freeIntRegs); 2275 2276 case SSEUp: 2277 case X87Up: 2278 llvm_unreachable("Invalid classification for lo word."); 2279 2280 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next 2281 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8 2282 // and %r9 is used. 2283 case Integer: 2284 ++neededInt; 2285 2286 // Pick an 8-byte type based on the preferred type. 2287 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0); 2288 2289 // If we have a sign or zero extended integer, make sure to return Extend 2290 // so that the parameter gets the right LLVM IR attributes. 2291 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) { 2292 // Treat an enum type as its underlying type. 2293 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 2294 Ty = EnumTy->getDecl()->getIntegerType(); 2295 2296 if (Ty->isIntegralOrEnumerationType() && 2297 Ty->isPromotableIntegerType()) 2298 return ABIArgInfo::getExtend(); 2299 } 2300 2301 break; 2302 2303 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next 2304 // available SSE register is used, the registers are taken in the 2305 // order from %xmm0 to %xmm7. 2306 case SSE: { 2307 llvm::Type *IRType = CGT.ConvertType(Ty); 2308 ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0); 2309 ++neededSSE; 2310 break; 2311 } 2312 } 2313 2314 llvm::Type *HighPart = 0; 2315 switch (Hi) { 2316 // Memory was handled previously, ComplexX87 and X87 should 2317 // never occur as hi classes, and X87Up must be preceded by X87, 2318 // which is passed in memory. 2319 case Memory: 2320 case X87: 2321 case ComplexX87: 2322 llvm_unreachable("Invalid classification for hi word."); 2323 2324 case NoClass: break; 2325 2326 case Integer: 2327 ++neededInt; 2328 // Pick an 8-byte type based on the preferred type. 2329 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8); 2330 2331 if (Lo == NoClass) // Pass HighPart at offset 8 in memory. 2332 return ABIArgInfo::getDirect(HighPart, 8); 2333 break; 2334 2335 // X87Up generally doesn't occur here (long double is passed in 2336 // memory), except in situations involving unions. 2337 case X87Up: 2338 case SSE: 2339 HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8); 2340 2341 if (Lo == NoClass) // Pass HighPart at offset 8 in memory. 2342 return ABIArgInfo::getDirect(HighPart, 8); 2343 2344 ++neededSSE; 2345 break; 2346 2347 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the 2348 // eightbyte is passed in the upper half of the last used SSE 2349 // register. This only happens when 128-bit vectors are passed. 2350 case SSEUp: 2351 assert(Lo == SSE && "Unexpected SSEUp classification"); 2352 ResType = GetByteVectorType(Ty); 2353 break; 2354 } 2355 2356 // If a high part was specified, merge it together with the low part. It is 2357 // known to pass in the high eightbyte of the result. We do this by forming a 2358 // first class struct aggregate with the high and low part: {low, high} 2359 if (HighPart) 2360 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout()); 2361 2362 return ABIArgInfo::getDirect(ResType); 2363 } 2364 2365 void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const { 2366 2367 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 2368 2369 // Keep track of the number of assigned registers. 2370 unsigned freeIntRegs = 6, freeSSERegs = 8; 2371 2372 // If the return value is indirect, then the hidden argument is consuming one 2373 // integer register. 2374 if (FI.getReturnInfo().isIndirect()) 2375 --freeIntRegs; 2376 2377 bool isVariadic = FI.isVariadic(); 2378 unsigned numRequiredArgs = 0; 2379 if (isVariadic) 2380 numRequiredArgs = FI.getRequiredArgs().getNumRequiredArgs(); 2381 2382 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers 2383 // get assigned (in left-to-right order) for passing as follows... 2384 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end(); 2385 it != ie; ++it) { 2386 bool isNamedArg = true; 2387 if (isVariadic) 2388 isNamedArg = (it - FI.arg_begin()) < 2389 static_cast<signed>(numRequiredArgs); 2390 2391 unsigned neededInt, neededSSE; 2392 it->info = classifyArgumentType(it->type, freeIntRegs, neededInt, 2393 neededSSE, isNamedArg); 2394 2395 // AMD64-ABI 3.2.3p3: If there are no registers available for any 2396 // eightbyte of an argument, the whole argument is passed on the 2397 // stack. If registers have already been assigned for some 2398 // eightbytes of such an argument, the assignments get reverted. 2399 if (freeIntRegs >= neededInt && freeSSERegs >= neededSSE) { 2400 freeIntRegs -= neededInt; 2401 freeSSERegs -= neededSSE; 2402 } else { 2403 it->info = getIndirectResult(it->type, freeIntRegs); 2404 } 2405 } 2406 } 2407 2408 static llvm::Value *EmitVAArgFromMemory(llvm::Value *VAListAddr, 2409 QualType Ty, 2410 CodeGenFunction &CGF) { 2411 llvm::Value *overflow_arg_area_p = 2412 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_p"); 2413 llvm::Value *overflow_arg_area = 2414 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area"); 2415 2416 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16 2417 // byte boundary if alignment needed by type exceeds 8 byte boundary. 2418 // It isn't stated explicitly in the standard, but in practice we use 2419 // alignment greater than 16 where necessary. 2420 uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8; 2421 if (Align > 8) { 2422 // overflow_arg_area = (overflow_arg_area + align - 1) & -align; 2423 llvm::Value *Offset = 2424 llvm::ConstantInt::get(CGF.Int64Ty, Align - 1); 2425 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset); 2426 llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(overflow_arg_area, 2427 CGF.Int64Ty); 2428 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int64Ty, -(uint64_t)Align); 2429 overflow_arg_area = 2430 CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask), 2431 overflow_arg_area->getType(), 2432 "overflow_arg_area.align"); 2433 } 2434 2435 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area. 2436 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty); 2437 llvm::Value *Res = 2438 CGF.Builder.CreateBitCast(overflow_arg_area, 2439 llvm::PointerType::getUnqual(LTy)); 2440 2441 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to: 2442 // l->overflow_arg_area + sizeof(type). 2443 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to 2444 // an 8 byte boundary. 2445 2446 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8; 2447 llvm::Value *Offset = 2448 llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7); 2449 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset, 2450 "overflow_arg_area.next"); 2451 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p); 2452 2453 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type. 2454 return Res; 2455 } 2456 2457 llvm::Value *X86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 2458 CodeGenFunction &CGF) const { 2459 // Assume that va_list type is correct; should be pointer to LLVM type: 2460 // struct { 2461 // i32 gp_offset; 2462 // i32 fp_offset; 2463 // i8* overflow_arg_area; 2464 // i8* reg_save_area; 2465 // }; 2466 unsigned neededInt, neededSSE; 2467 2468 Ty = CGF.getContext().getCanonicalType(Ty); 2469 ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE, 2470 /*isNamedArg*/false); 2471 2472 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed 2473 // in the registers. If not go to step 7. 2474 if (!neededInt && !neededSSE) 2475 return EmitVAArgFromMemory(VAListAddr, Ty, CGF); 2476 2477 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of 2478 // general purpose registers needed to pass type and num_fp to hold 2479 // the number of floating point registers needed. 2480 2481 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into 2482 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or 2483 // l->fp_offset > 304 - num_fp * 16 go to step 7. 2484 // 2485 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of 2486 // register save space). 2487 2488 llvm::Value *InRegs = 0; 2489 llvm::Value *gp_offset_p = 0, *gp_offset = 0; 2490 llvm::Value *fp_offset_p = 0, *fp_offset = 0; 2491 if (neededInt) { 2492 gp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "gp_offset_p"); 2493 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset"); 2494 InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8); 2495 InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp"); 2496 } 2497 2498 if (neededSSE) { 2499 fp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 1, "fp_offset_p"); 2500 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset"); 2501 llvm::Value *FitsInFP = 2502 llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16); 2503 FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp"); 2504 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP; 2505 } 2506 2507 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg"); 2508 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem"); 2509 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end"); 2510 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock); 2511 2512 // Emit code to load the value if it was passed in registers. 2513 2514 CGF.EmitBlock(InRegBlock); 2515 2516 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with 2517 // an offset of l->gp_offset and/or l->fp_offset. This may require 2518 // copying to a temporary location in case the parameter is passed 2519 // in different register classes or requires an alignment greater 2520 // than 8 for general purpose registers and 16 for XMM registers. 2521 // 2522 // FIXME: This really results in shameful code when we end up needing to 2523 // collect arguments from different places; often what should result in a 2524 // simple assembling of a structure from scattered addresses has many more 2525 // loads than necessary. Can we clean this up? 2526 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty); 2527 llvm::Value *RegAddr = 2528 CGF.Builder.CreateLoad(CGF.Builder.CreateStructGEP(VAListAddr, 3), 2529 "reg_save_area"); 2530 if (neededInt && neededSSE) { 2531 // FIXME: Cleanup. 2532 assert(AI.isDirect() && "Unexpected ABI info for mixed regs"); 2533 llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType()); 2534 llvm::Value *Tmp = CGF.CreateMemTemp(Ty); 2535 Tmp = CGF.Builder.CreateBitCast(Tmp, ST->getPointerTo()); 2536 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs"); 2537 llvm::Type *TyLo = ST->getElementType(0); 2538 llvm::Type *TyHi = ST->getElementType(1); 2539 assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) && 2540 "Unexpected ABI info for mixed regs"); 2541 llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo); 2542 llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi); 2543 llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset); 2544 llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset); 2545 llvm::Value *RegLoAddr = TyLo->isFloatingPointTy() ? FPAddr : GPAddr; 2546 llvm::Value *RegHiAddr = TyLo->isFloatingPointTy() ? GPAddr : FPAddr; 2547 llvm::Value *V = 2548 CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegLoAddr, PTyLo)); 2549 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0)); 2550 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegHiAddr, PTyHi)); 2551 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1)); 2552 2553 RegAddr = CGF.Builder.CreateBitCast(Tmp, 2554 llvm::PointerType::getUnqual(LTy)); 2555 } else if (neededInt) { 2556 RegAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset); 2557 RegAddr = CGF.Builder.CreateBitCast(RegAddr, 2558 llvm::PointerType::getUnqual(LTy)); 2559 2560 // Copy to a temporary if necessary to ensure the appropriate alignment. 2561 std::pair<CharUnits, CharUnits> SizeAlign = 2562 CGF.getContext().getTypeInfoInChars(Ty); 2563 uint64_t TySize = SizeAlign.first.getQuantity(); 2564 unsigned TyAlign = SizeAlign.second.getQuantity(); 2565 if (TyAlign > 8) { 2566 llvm::Value *Tmp = CGF.CreateMemTemp(Ty); 2567 CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, 8, false); 2568 RegAddr = Tmp; 2569 } 2570 } else if (neededSSE == 1) { 2571 RegAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset); 2572 RegAddr = CGF.Builder.CreateBitCast(RegAddr, 2573 llvm::PointerType::getUnqual(LTy)); 2574 } else { 2575 assert(neededSSE == 2 && "Invalid number of needed registers!"); 2576 // SSE registers are spaced 16 bytes apart in the register save 2577 // area, we need to collect the two eightbytes together. 2578 llvm::Value *RegAddrLo = CGF.Builder.CreateGEP(RegAddr, fp_offset); 2579 llvm::Value *RegAddrHi = CGF.Builder.CreateConstGEP1_32(RegAddrLo, 16); 2580 llvm::Type *DoubleTy = CGF.DoubleTy; 2581 llvm::Type *DblPtrTy = 2582 llvm::PointerType::getUnqual(DoubleTy); 2583 llvm::StructType *ST = llvm::StructType::get(DoubleTy, DoubleTy, NULL); 2584 llvm::Value *V, *Tmp = CGF.CreateMemTemp(Ty); 2585 Tmp = CGF.Builder.CreateBitCast(Tmp, ST->getPointerTo()); 2586 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrLo, 2587 DblPtrTy)); 2588 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0)); 2589 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrHi, 2590 DblPtrTy)); 2591 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1)); 2592 RegAddr = CGF.Builder.CreateBitCast(Tmp, 2593 llvm::PointerType::getUnqual(LTy)); 2594 } 2595 2596 // AMD64-ABI 3.5.7p5: Step 5. Set: 2597 // l->gp_offset = l->gp_offset + num_gp * 8 2598 // l->fp_offset = l->fp_offset + num_fp * 16. 2599 if (neededInt) { 2600 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8); 2601 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset), 2602 gp_offset_p); 2603 } 2604 if (neededSSE) { 2605 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16); 2606 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset), 2607 fp_offset_p); 2608 } 2609 CGF.EmitBranch(ContBlock); 2610 2611 // Emit code to load the value if it was passed in memory. 2612 2613 CGF.EmitBlock(InMemBlock); 2614 llvm::Value *MemAddr = EmitVAArgFromMemory(VAListAddr, Ty, CGF); 2615 2616 // Return the appropriate result. 2617 2618 CGF.EmitBlock(ContBlock); 2619 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(RegAddr->getType(), 2, 2620 "vaarg.addr"); 2621 ResAddr->addIncoming(RegAddr, InRegBlock); 2622 ResAddr->addIncoming(MemAddr, InMemBlock); 2623 return ResAddr; 2624 } 2625 2626 ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, bool IsReturnType) const { 2627 2628 if (Ty->isVoidType()) 2629 return ABIArgInfo::getIgnore(); 2630 2631 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 2632 Ty = EnumTy->getDecl()->getIntegerType(); 2633 2634 uint64_t Size = getContext().getTypeSize(Ty); 2635 2636 if (const RecordType *RT = Ty->getAs<RecordType>()) { 2637 if (IsReturnType) { 2638 if (isRecordReturnIndirect(RT, getCXXABI())) 2639 return ABIArgInfo::getIndirect(0, false); 2640 } else { 2641 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI())) 2642 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory); 2643 } 2644 2645 if (RT->getDecl()->hasFlexibleArrayMember()) 2646 return ABIArgInfo::getIndirect(0, /*ByVal=*/false); 2647 2648 // FIXME: mingw-w64-gcc emits 128-bit struct as i128 2649 if (Size == 128 && getTarget().getTriple().getOS() == llvm::Triple::MinGW32) 2650 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 2651 Size)); 2652 2653 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is 2654 // not 1, 2, 4, or 8 bytes, must be passed by reference." 2655 if (Size <= 64 && 2656 (Size & (Size - 1)) == 0) 2657 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 2658 Size)); 2659 2660 return ABIArgInfo::getIndirect(0, /*ByVal=*/false); 2661 } 2662 2663 if (Ty->isPromotableIntegerType()) 2664 return ABIArgInfo::getExtend(); 2665 2666 return ABIArgInfo::getDirect(); 2667 } 2668 2669 void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const { 2670 2671 QualType RetTy = FI.getReturnType(); 2672 FI.getReturnInfo() = classify(RetTy, true); 2673 2674 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end(); 2675 it != ie; ++it) 2676 it->info = classify(it->type, false); 2677 } 2678 2679 llvm::Value *WinX86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 2680 CodeGenFunction &CGF) const { 2681 llvm::Type *BPP = CGF.Int8PtrPtrTy; 2682 2683 CGBuilderTy &Builder = CGF.Builder; 2684 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, 2685 "ap"); 2686 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur"); 2687 llvm::Type *PTy = 2688 llvm::PointerType::getUnqual(CGF.ConvertType(Ty)); 2689 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy); 2690 2691 uint64_t Offset = 2692 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 8); 2693 llvm::Value *NextAddr = 2694 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset), 2695 "ap.next"); 2696 Builder.CreateStore(NextAddr, VAListAddrAsBPP); 2697 2698 return AddrTyped; 2699 } 2700 2701 namespace { 2702 2703 class NaClX86_64ABIInfo : public ABIInfo { 2704 public: 2705 NaClX86_64ABIInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX) 2706 : ABIInfo(CGT), PInfo(CGT), NInfo(CGT, HasAVX) {} 2707 virtual void computeInfo(CGFunctionInfo &FI) const; 2708 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 2709 CodeGenFunction &CGF) const; 2710 private: 2711 PNaClABIInfo PInfo; // Used for generating calls with pnaclcall callingconv. 2712 X86_64ABIInfo NInfo; // Used for everything else. 2713 }; 2714 2715 class NaClX86_64TargetCodeGenInfo : public TargetCodeGenInfo { 2716 public: 2717 NaClX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX) 2718 : TargetCodeGenInfo(new NaClX86_64ABIInfo(CGT, HasAVX)) {} 2719 }; 2720 2721 } 2722 2723 void NaClX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const { 2724 if (FI.getASTCallingConvention() == CC_PnaclCall) 2725 PInfo.computeInfo(FI); 2726 else 2727 NInfo.computeInfo(FI); 2728 } 2729 2730 llvm::Value *NaClX86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 2731 CodeGenFunction &CGF) const { 2732 // Always use the native convention; calling pnacl-style varargs functions 2733 // is unuspported. 2734 return NInfo.EmitVAArg(VAListAddr, Ty, CGF); 2735 } 2736 2737 2738 // PowerPC-32 2739 2740 namespace { 2741 class PPC32TargetCodeGenInfo : public DefaultTargetCodeGenInfo { 2742 public: 2743 PPC32TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {} 2744 2745 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const { 2746 // This is recovered from gcc output. 2747 return 1; // r1 is the dedicated stack pointer 2748 } 2749 2750 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 2751 llvm::Value *Address) const; 2752 }; 2753 2754 } 2755 2756 bool 2757 PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 2758 llvm::Value *Address) const { 2759 // This is calculated from the LLVM and GCC tables and verified 2760 // against gcc output. AFAIK all ABIs use the same encoding. 2761 2762 CodeGen::CGBuilderTy &Builder = CGF.Builder; 2763 2764 llvm::IntegerType *i8 = CGF.Int8Ty; 2765 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4); 2766 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8); 2767 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16); 2768 2769 // 0-31: r0-31, the 4-byte general-purpose registers 2770 AssignToArrayRange(Builder, Address, Four8, 0, 31); 2771 2772 // 32-63: fp0-31, the 8-byte floating-point registers 2773 AssignToArrayRange(Builder, Address, Eight8, 32, 63); 2774 2775 // 64-76 are various 4-byte special-purpose registers: 2776 // 64: mq 2777 // 65: lr 2778 // 66: ctr 2779 // 67: ap 2780 // 68-75 cr0-7 2781 // 76: xer 2782 AssignToArrayRange(Builder, Address, Four8, 64, 76); 2783 2784 // 77-108: v0-31, the 16-byte vector registers 2785 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108); 2786 2787 // 109: vrsave 2788 // 110: vscr 2789 // 111: spe_acc 2790 // 112: spefscr 2791 // 113: sfp 2792 AssignToArrayRange(Builder, Address, Four8, 109, 113); 2793 2794 return false; 2795 } 2796 2797 // PowerPC-64 2798 2799 namespace { 2800 /// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information. 2801 class PPC64_SVR4_ABIInfo : public DefaultABIInfo { 2802 2803 public: 2804 PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {} 2805 2806 bool isPromotableTypeForABI(QualType Ty) const; 2807 2808 ABIArgInfo classifyReturnType(QualType RetTy) const; 2809 ABIArgInfo classifyArgumentType(QualType Ty) const; 2810 2811 // TODO: We can add more logic to computeInfo to improve performance. 2812 // Example: For aggregate arguments that fit in a register, we could 2813 // use getDirectInReg (as is done below for structs containing a single 2814 // floating-point value) to avoid pushing them to memory on function 2815 // entry. This would require changing the logic in PPCISelLowering 2816 // when lowering the parameters in the caller and args in the callee. 2817 virtual void computeInfo(CGFunctionInfo &FI) const { 2818 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 2819 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end(); 2820 it != ie; ++it) { 2821 // We rely on the default argument classification for the most part. 2822 // One exception: An aggregate containing a single floating-point 2823 // or vector item must be passed in a register if one is available. 2824 const Type *T = isSingleElementStruct(it->type, getContext()); 2825 if (T) { 2826 const BuiltinType *BT = T->getAs<BuiltinType>(); 2827 if (T->isVectorType() || (BT && BT->isFloatingPoint())) { 2828 QualType QT(T, 0); 2829 it->info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT)); 2830 continue; 2831 } 2832 } 2833 it->info = classifyArgumentType(it->type); 2834 } 2835 } 2836 2837 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, 2838 QualType Ty, 2839 CodeGenFunction &CGF) const; 2840 }; 2841 2842 class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo { 2843 public: 2844 PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT) 2845 : TargetCodeGenInfo(new PPC64_SVR4_ABIInfo(CGT)) {} 2846 2847 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const { 2848 // This is recovered from gcc output. 2849 return 1; // r1 is the dedicated stack pointer 2850 } 2851 2852 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 2853 llvm::Value *Address) const; 2854 }; 2855 2856 class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo { 2857 public: 2858 PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {} 2859 2860 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const { 2861 // This is recovered from gcc output. 2862 return 1; // r1 is the dedicated stack pointer 2863 } 2864 2865 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 2866 llvm::Value *Address) const; 2867 }; 2868 2869 } 2870 2871 // Return true if the ABI requires Ty to be passed sign- or zero- 2872 // extended to 64 bits. 2873 bool 2874 PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const { 2875 // Treat an enum type as its underlying type. 2876 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 2877 Ty = EnumTy->getDecl()->getIntegerType(); 2878 2879 // Promotable integer types are required to be promoted by the ABI. 2880 if (Ty->isPromotableIntegerType()) 2881 return true; 2882 2883 // In addition to the usual promotable integer types, we also need to 2884 // extend all 32-bit types, since the ABI requires promotion to 64 bits. 2885 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) 2886 switch (BT->getKind()) { 2887 case BuiltinType::Int: 2888 case BuiltinType::UInt: 2889 return true; 2890 default: 2891 break; 2892 } 2893 2894 return false; 2895 } 2896 2897 ABIArgInfo 2898 PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const { 2899 if (Ty->isAnyComplexType()) 2900 return ABIArgInfo::getDirect(); 2901 2902 if (isAggregateTypeForABI(Ty)) { 2903 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 2904 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory); 2905 2906 return ABIArgInfo::getIndirect(0); 2907 } 2908 2909 return (isPromotableTypeForABI(Ty) ? 2910 ABIArgInfo::getExtend() : ABIArgInfo::getDirect()); 2911 } 2912 2913 ABIArgInfo 2914 PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const { 2915 if (RetTy->isVoidType()) 2916 return ABIArgInfo::getIgnore(); 2917 2918 if (RetTy->isAnyComplexType()) 2919 return ABIArgInfo::getDirect(); 2920 2921 if (isAggregateTypeForABI(RetTy)) 2922 return ABIArgInfo::getIndirect(0); 2923 2924 return (isPromotableTypeForABI(RetTy) ? 2925 ABIArgInfo::getExtend() : ABIArgInfo::getDirect()); 2926 } 2927 2928 // Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine. 2929 llvm::Value *PPC64_SVR4_ABIInfo::EmitVAArg(llvm::Value *VAListAddr, 2930 QualType Ty, 2931 CodeGenFunction &CGF) const { 2932 llvm::Type *BP = CGF.Int8PtrTy; 2933 llvm::Type *BPP = CGF.Int8PtrPtrTy; 2934 2935 CGBuilderTy &Builder = CGF.Builder; 2936 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap"); 2937 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur"); 2938 2939 // Update the va_list pointer. The pointer should be bumped by the 2940 // size of the object. We can trust getTypeSize() except for a complex 2941 // type whose base type is smaller than a doubleword. For these, the 2942 // size of the object is 16 bytes; see below for further explanation. 2943 unsigned SizeInBytes = CGF.getContext().getTypeSize(Ty) / 8; 2944 QualType BaseTy; 2945 unsigned CplxBaseSize = 0; 2946 2947 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) { 2948 BaseTy = CTy->getElementType(); 2949 CplxBaseSize = CGF.getContext().getTypeSize(BaseTy) / 8; 2950 if (CplxBaseSize < 8) 2951 SizeInBytes = 16; 2952 } 2953 2954 unsigned Offset = llvm::RoundUpToAlignment(SizeInBytes, 8); 2955 llvm::Value *NextAddr = 2956 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int64Ty, Offset), 2957 "ap.next"); 2958 Builder.CreateStore(NextAddr, VAListAddrAsBPP); 2959 2960 // If we have a complex type and the base type is smaller than 8 bytes, 2961 // the ABI calls for the real and imaginary parts to be right-adjusted 2962 // in separate doublewords. However, Clang expects us to produce a 2963 // pointer to a structure with the two parts packed tightly. So generate 2964 // loads of the real and imaginary parts relative to the va_list pointer, 2965 // and store them to a temporary structure. 2966 if (CplxBaseSize && CplxBaseSize < 8) { 2967 llvm::Value *RealAddr = Builder.CreatePtrToInt(Addr, CGF.Int64Ty); 2968 llvm::Value *ImagAddr = RealAddr; 2969 RealAddr = Builder.CreateAdd(RealAddr, Builder.getInt64(8 - CplxBaseSize)); 2970 ImagAddr = Builder.CreateAdd(ImagAddr, Builder.getInt64(16 - CplxBaseSize)); 2971 llvm::Type *PBaseTy = llvm::PointerType::getUnqual(CGF.ConvertType(BaseTy)); 2972 RealAddr = Builder.CreateIntToPtr(RealAddr, PBaseTy); 2973 ImagAddr = Builder.CreateIntToPtr(ImagAddr, PBaseTy); 2974 llvm::Value *Real = Builder.CreateLoad(RealAddr, false, ".vareal"); 2975 llvm::Value *Imag = Builder.CreateLoad(ImagAddr, false, ".vaimag"); 2976 llvm::Value *Ptr = CGF.CreateTempAlloca(CGT.ConvertTypeForMem(Ty), 2977 "vacplx"); 2978 llvm::Value *RealPtr = Builder.CreateStructGEP(Ptr, 0, ".real"); 2979 llvm::Value *ImagPtr = Builder.CreateStructGEP(Ptr, 1, ".imag"); 2980 Builder.CreateStore(Real, RealPtr, false); 2981 Builder.CreateStore(Imag, ImagPtr, false); 2982 return Ptr; 2983 } 2984 2985 // If the argument is smaller than 8 bytes, it is right-adjusted in 2986 // its doubleword slot. Adjust the pointer to pick it up from the 2987 // correct offset. 2988 if (SizeInBytes < 8) { 2989 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int64Ty); 2990 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt64(8 - SizeInBytes)); 2991 Addr = Builder.CreateIntToPtr(AddrAsInt, BP); 2992 } 2993 2994 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty)); 2995 return Builder.CreateBitCast(Addr, PTy); 2996 } 2997 2998 static bool 2999 PPC64_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 3000 llvm::Value *Address) { 3001 // This is calculated from the LLVM and GCC tables and verified 3002 // against gcc output. AFAIK all ABIs use the same encoding. 3003 3004 CodeGen::CGBuilderTy &Builder = CGF.Builder; 3005 3006 llvm::IntegerType *i8 = CGF.Int8Ty; 3007 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4); 3008 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8); 3009 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16); 3010 3011 // 0-31: r0-31, the 8-byte general-purpose registers 3012 AssignToArrayRange(Builder, Address, Eight8, 0, 31); 3013 3014 // 32-63: fp0-31, the 8-byte floating-point registers 3015 AssignToArrayRange(Builder, Address, Eight8, 32, 63); 3016 3017 // 64-76 are various 4-byte special-purpose registers: 3018 // 64: mq 3019 // 65: lr 3020 // 66: ctr 3021 // 67: ap 3022 // 68-75 cr0-7 3023 // 76: xer 3024 AssignToArrayRange(Builder, Address, Four8, 64, 76); 3025 3026 // 77-108: v0-31, the 16-byte vector registers 3027 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108); 3028 3029 // 109: vrsave 3030 // 110: vscr 3031 // 111: spe_acc 3032 // 112: spefscr 3033 // 113: sfp 3034 AssignToArrayRange(Builder, Address, Four8, 109, 113); 3035 3036 return false; 3037 } 3038 3039 bool 3040 PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable( 3041 CodeGen::CodeGenFunction &CGF, 3042 llvm::Value *Address) const { 3043 3044 return PPC64_initDwarfEHRegSizeTable(CGF, Address); 3045 } 3046 3047 bool 3048 PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 3049 llvm::Value *Address) const { 3050 3051 return PPC64_initDwarfEHRegSizeTable(CGF, Address); 3052 } 3053 3054 //===----------------------------------------------------------------------===// 3055 // ARM ABI Implementation 3056 //===----------------------------------------------------------------------===// 3057 3058 namespace { 3059 3060 class ARMABIInfo : public ABIInfo { 3061 public: 3062 enum ABIKind { 3063 APCS = 0, 3064 AAPCS = 1, 3065 AAPCS_VFP 3066 }; 3067 3068 private: 3069 ABIKind Kind; 3070 3071 public: 3072 ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind) : ABIInfo(CGT), Kind(_Kind) { 3073 setRuntimeCC(); 3074 } 3075 3076 bool isEABI() const { 3077 switch (getTarget().getTriple().getEnvironment()) { 3078 case llvm::Triple::Android: 3079 case llvm::Triple::EABI: 3080 case llvm::Triple::EABIHF: 3081 case llvm::Triple::GNUEABI: 3082 case llvm::Triple::GNUEABIHF: 3083 return true; 3084 default: 3085 return false; 3086 } 3087 } 3088 3089 bool isEABIHF() const { 3090 switch (getTarget().getTriple().getEnvironment()) { 3091 case llvm::Triple::EABIHF: 3092 case llvm::Triple::GNUEABIHF: 3093 return true; 3094 default: 3095 return false; 3096 } 3097 } 3098 3099 ABIKind getABIKind() const { return Kind; } 3100 3101 private: 3102 ABIArgInfo classifyReturnType(QualType RetTy) const; 3103 ABIArgInfo classifyArgumentType(QualType RetTy, int *VFPRegs, 3104 unsigned &AllocatedVFP, 3105 bool &IsHA) const; 3106 bool isIllegalVectorType(QualType Ty) const; 3107 3108 virtual void computeInfo(CGFunctionInfo &FI) const; 3109 3110 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 3111 CodeGenFunction &CGF) const; 3112 3113 llvm::CallingConv::ID getLLVMDefaultCC() const; 3114 llvm::CallingConv::ID getABIDefaultCC() const; 3115 void setRuntimeCC(); 3116 }; 3117 3118 class ARMTargetCodeGenInfo : public TargetCodeGenInfo { 3119 public: 3120 ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K) 3121 :TargetCodeGenInfo(new ARMABIInfo(CGT, K)) {} 3122 3123 const ARMABIInfo &getABIInfo() const { 3124 return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo()); 3125 } 3126 3127 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const { 3128 return 13; 3129 } 3130 3131 StringRef getARCRetainAutoreleasedReturnValueMarker() const { 3132 return "mov\tr7, r7\t\t@ marker for objc_retainAutoreleaseReturnValue"; 3133 } 3134 3135 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 3136 llvm::Value *Address) const { 3137 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4); 3138 3139 // 0-15 are the 16 integer registers. 3140 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15); 3141 return false; 3142 } 3143 3144 unsigned getSizeOfUnwindException() const { 3145 if (getABIInfo().isEABI()) return 88; 3146 return TargetCodeGenInfo::getSizeOfUnwindException(); 3147 } 3148 3149 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 3150 CodeGen::CodeGenModule &CGM) const { 3151 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D); 3152 if (!FD) 3153 return; 3154 3155 const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>(); 3156 if (!Attr) 3157 return; 3158 3159 const char *Kind; 3160 switch (Attr->getInterrupt()) { 3161 case ARMInterruptAttr::Generic: Kind = ""; break; 3162 case ARMInterruptAttr::IRQ: Kind = "IRQ"; break; 3163 case ARMInterruptAttr::FIQ: Kind = "FIQ"; break; 3164 case ARMInterruptAttr::SWI: Kind = "SWI"; break; 3165 case ARMInterruptAttr::ABORT: Kind = "ABORT"; break; 3166 case ARMInterruptAttr::UNDEF: Kind = "UNDEF"; break; 3167 } 3168 3169 llvm::Function *Fn = cast<llvm::Function>(GV); 3170 3171 Fn->addFnAttr("interrupt", Kind); 3172 3173 if (cast<ARMABIInfo>(getABIInfo()).getABIKind() == ARMABIInfo::APCS) 3174 return; 3175 3176 // AAPCS guarantees that sp will be 8-byte aligned on any public interface, 3177 // however this is not necessarily true on taking any interrupt. Instruct 3178 // the backend to perform a realignment as part of the function prologue. 3179 llvm::AttrBuilder B; 3180 B.addStackAlignmentAttr(8); 3181 Fn->addAttributes(llvm::AttributeSet::FunctionIndex, 3182 llvm::AttributeSet::get(CGM.getLLVMContext(), 3183 llvm::AttributeSet::FunctionIndex, 3184 B)); 3185 } 3186 3187 }; 3188 3189 } 3190 3191 void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const { 3192 // To correctly handle Homogeneous Aggregate, we need to keep track of the 3193 // VFP registers allocated so far. 3194 // C.1.vfp If the argument is a VFP CPRC and there are sufficient consecutive 3195 // VFP registers of the appropriate type unallocated then the argument is 3196 // allocated to the lowest-numbered sequence of such registers. 3197 // C.2.vfp If the argument is a VFP CPRC then any VFP registers that are 3198 // unallocated are marked as unavailable. 3199 unsigned AllocatedVFP = 0; 3200 int VFPRegs[16] = { 0 }; 3201 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 3202 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end(); 3203 it != ie; ++it) { 3204 unsigned PreAllocation = AllocatedVFP; 3205 bool IsHA = false; 3206 // 6.1.2.3 There is one VFP co-processor register class using registers 3207 // s0-s15 (d0-d7) for passing arguments. 3208 const unsigned NumVFPs = 16; 3209 it->info = classifyArgumentType(it->type, VFPRegs, AllocatedVFP, IsHA); 3210 // If we do not have enough VFP registers for the HA, any VFP registers 3211 // that are unallocated are marked as unavailable. To achieve this, we add 3212 // padding of (NumVFPs - PreAllocation) floats. 3213 if (IsHA && AllocatedVFP > NumVFPs && PreAllocation < NumVFPs) { 3214 llvm::Type *PaddingTy = llvm::ArrayType::get( 3215 llvm::Type::getFloatTy(getVMContext()), NumVFPs - PreAllocation); 3216 it->info = ABIArgInfo::getExpandWithPadding(false, PaddingTy); 3217 } 3218 } 3219 3220 // Always honor user-specified calling convention. 3221 if (FI.getCallingConvention() != llvm::CallingConv::C) 3222 return; 3223 3224 llvm::CallingConv::ID cc = getRuntimeCC(); 3225 if (cc != llvm::CallingConv::C) 3226 FI.setEffectiveCallingConvention(cc); 3227 } 3228 3229 /// Return the default calling convention that LLVM will use. 3230 llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const { 3231 // The default calling convention that LLVM will infer. 3232 if (isEABIHF()) 3233 return llvm::CallingConv::ARM_AAPCS_VFP; 3234 else if (isEABI()) 3235 return llvm::CallingConv::ARM_AAPCS; 3236 else 3237 return llvm::CallingConv::ARM_APCS; 3238 } 3239 3240 /// Return the calling convention that our ABI would like us to use 3241 /// as the C calling convention. 3242 llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const { 3243 switch (getABIKind()) { 3244 case APCS: return llvm::CallingConv::ARM_APCS; 3245 case AAPCS: return llvm::CallingConv::ARM_AAPCS; 3246 case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP; 3247 } 3248 llvm_unreachable("bad ABI kind"); 3249 } 3250 3251 void ARMABIInfo::setRuntimeCC() { 3252 assert(getRuntimeCC() == llvm::CallingConv::C); 3253 3254 // Don't muddy up the IR with a ton of explicit annotations if 3255 // they'd just match what LLVM will infer from the triple. 3256 llvm::CallingConv::ID abiCC = getABIDefaultCC(); 3257 if (abiCC != getLLVMDefaultCC()) 3258 RuntimeCC = abiCC; 3259 } 3260 3261 /// isHomogeneousAggregate - Return true if a type is an AAPCS-VFP homogeneous 3262 /// aggregate. If HAMembers is non-null, the number of base elements 3263 /// contained in the type is returned through it; this is used for the 3264 /// recursive calls that check aggregate component types. 3265 static bool isHomogeneousAggregate(QualType Ty, const Type *&Base, 3266 ASTContext &Context, 3267 uint64_t *HAMembers = 0) { 3268 uint64_t Members = 0; 3269 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) { 3270 if (!isHomogeneousAggregate(AT->getElementType(), Base, Context, &Members)) 3271 return false; 3272 Members *= AT->getSize().getZExtValue(); 3273 } else if (const RecordType *RT = Ty->getAs<RecordType>()) { 3274 const RecordDecl *RD = RT->getDecl(); 3275 if (RD->hasFlexibleArrayMember()) 3276 return false; 3277 3278 Members = 0; 3279 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 3280 i != e; ++i) { 3281 const FieldDecl *FD = *i; 3282 uint64_t FldMembers; 3283 if (!isHomogeneousAggregate(FD->getType(), Base, Context, &FldMembers)) 3284 return false; 3285 3286 Members = (RD->isUnion() ? 3287 std::max(Members, FldMembers) : Members + FldMembers); 3288 } 3289 } else { 3290 Members = 1; 3291 if (const ComplexType *CT = Ty->getAs<ComplexType>()) { 3292 Members = 2; 3293 Ty = CT->getElementType(); 3294 } 3295 3296 // Homogeneous aggregates for AAPCS-VFP must have base types of float, 3297 // double, or 64-bit or 128-bit vectors. 3298 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) { 3299 if (BT->getKind() != BuiltinType::Float && 3300 BT->getKind() != BuiltinType::Double && 3301 BT->getKind() != BuiltinType::LongDouble) 3302 return false; 3303 } else if (const VectorType *VT = Ty->getAs<VectorType>()) { 3304 unsigned VecSize = Context.getTypeSize(VT); 3305 if (VecSize != 64 && VecSize != 128) 3306 return false; 3307 } else { 3308 return false; 3309 } 3310 3311 // The base type must be the same for all members. Vector types of the 3312 // same total size are treated as being equivalent here. 3313 const Type *TyPtr = Ty.getTypePtr(); 3314 if (!Base) 3315 Base = TyPtr; 3316 if (Base != TyPtr && 3317 (!Base->isVectorType() || !TyPtr->isVectorType() || 3318 Context.getTypeSize(Base) != Context.getTypeSize(TyPtr))) 3319 return false; 3320 } 3321 3322 // Homogeneous Aggregates can have at most 4 members of the base type. 3323 if (HAMembers) 3324 *HAMembers = Members; 3325 3326 return (Members > 0 && Members <= 4); 3327 } 3328 3329 /// markAllocatedVFPs - update VFPRegs according to the alignment and 3330 /// number of VFP registers (unit is S register) requested. 3331 static void markAllocatedVFPs(int *VFPRegs, unsigned &AllocatedVFP, 3332 unsigned Alignment, 3333 unsigned NumRequired) { 3334 // Early Exit. 3335 if (AllocatedVFP >= 16) 3336 return; 3337 // C.1.vfp If the argument is a VFP CPRC and there are sufficient consecutive 3338 // VFP registers of the appropriate type unallocated then the argument is 3339 // allocated to the lowest-numbered sequence of such registers. 3340 for (unsigned I = 0; I < 16; I += Alignment) { 3341 bool FoundSlot = true; 3342 for (unsigned J = I, JEnd = I + NumRequired; J < JEnd; J++) 3343 if (J >= 16 || VFPRegs[J]) { 3344 FoundSlot = false; 3345 break; 3346 } 3347 if (FoundSlot) { 3348 for (unsigned J = I, JEnd = I + NumRequired; J < JEnd; J++) 3349 VFPRegs[J] = 1; 3350 AllocatedVFP += NumRequired; 3351 return; 3352 } 3353 } 3354 // C.2.vfp If the argument is a VFP CPRC then any VFP registers that are 3355 // unallocated are marked as unavailable. 3356 for (unsigned I = 0; I < 16; I++) 3357 VFPRegs[I] = 1; 3358 AllocatedVFP = 17; // We do not have enough VFP registers. 3359 } 3360 3361 ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty, int *VFPRegs, 3362 unsigned &AllocatedVFP, 3363 bool &IsHA) const { 3364 // We update number of allocated VFPs according to 3365 // 6.1.2.1 The following argument types are VFP CPRCs: 3366 // A single-precision floating-point type (including promoted 3367 // half-precision types); A double-precision floating-point type; 3368 // A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate 3369 // with a Base Type of a single- or double-precision floating-point type, 3370 // 64-bit containerized vectors or 128-bit containerized vectors with one 3371 // to four Elements. 3372 3373 // Handle illegal vector types here. 3374 if (isIllegalVectorType(Ty)) { 3375 uint64_t Size = getContext().getTypeSize(Ty); 3376 if (Size <= 32) { 3377 llvm::Type *ResType = 3378 llvm::Type::getInt32Ty(getVMContext()); 3379 return ABIArgInfo::getDirect(ResType); 3380 } 3381 if (Size == 64) { 3382 llvm::Type *ResType = llvm::VectorType::get( 3383 llvm::Type::getInt32Ty(getVMContext()), 2); 3384 markAllocatedVFPs(VFPRegs, AllocatedVFP, 2, 2); 3385 return ABIArgInfo::getDirect(ResType); 3386 } 3387 if (Size == 128) { 3388 llvm::Type *ResType = llvm::VectorType::get( 3389 llvm::Type::getInt32Ty(getVMContext()), 4); 3390 markAllocatedVFPs(VFPRegs, AllocatedVFP, 4, 4); 3391 return ABIArgInfo::getDirect(ResType); 3392 } 3393 return ABIArgInfo::getIndirect(0, /*ByVal=*/false); 3394 } 3395 // Update VFPRegs for legal vector types. 3396 if (const VectorType *VT = Ty->getAs<VectorType>()) { 3397 uint64_t Size = getContext().getTypeSize(VT); 3398 // Size of a legal vector should be power of 2 and above 64. 3399 markAllocatedVFPs(VFPRegs, AllocatedVFP, Size >= 128 ? 4 : 2, Size / 32); 3400 } 3401 // Update VFPRegs for floating point types. 3402 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) { 3403 if (BT->getKind() == BuiltinType::Half || 3404 BT->getKind() == BuiltinType::Float) 3405 markAllocatedVFPs(VFPRegs, AllocatedVFP, 1, 1); 3406 if (BT->getKind() == BuiltinType::Double || 3407 BT->getKind() == BuiltinType::LongDouble) 3408 markAllocatedVFPs(VFPRegs, AllocatedVFP, 2, 2); 3409 } 3410 3411 if (!isAggregateTypeForABI(Ty)) { 3412 // Treat an enum type as its underlying type. 3413 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 3414 Ty = EnumTy->getDecl()->getIntegerType(); 3415 3416 return (Ty->isPromotableIntegerType() ? 3417 ABIArgInfo::getExtend() : ABIArgInfo::getDirect()); 3418 } 3419 3420 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 3421 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory); 3422 3423 // Ignore empty records. 3424 if (isEmptyRecord(getContext(), Ty, true)) 3425 return ABIArgInfo::getIgnore(); 3426 3427 if (getABIKind() == ARMABIInfo::AAPCS_VFP) { 3428 // Homogeneous Aggregates need to be expanded when we can fit the aggregate 3429 // into VFP registers. 3430 const Type *Base = 0; 3431 uint64_t Members = 0; 3432 if (isHomogeneousAggregate(Ty, Base, getContext(), &Members)) { 3433 assert(Base && "Base class should be set for homogeneous aggregate"); 3434 // Base can be a floating-point or a vector. 3435 if (Base->isVectorType()) { 3436 // ElementSize is in number of floats. 3437 unsigned ElementSize = getContext().getTypeSize(Base) == 64 ? 2 : 4; 3438 markAllocatedVFPs(VFPRegs, AllocatedVFP, ElementSize, 3439 Members * ElementSize); 3440 } else if (Base->isSpecificBuiltinType(BuiltinType::Float)) 3441 markAllocatedVFPs(VFPRegs, AllocatedVFP, 1, Members); 3442 else { 3443 assert(Base->isSpecificBuiltinType(BuiltinType::Double) || 3444 Base->isSpecificBuiltinType(BuiltinType::LongDouble)); 3445 markAllocatedVFPs(VFPRegs, AllocatedVFP, 2, Members * 2); 3446 } 3447 IsHA = true; 3448 return ABIArgInfo::getExpand(); 3449 } 3450 } 3451 3452 // Support byval for ARM. 3453 // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at 3454 // most 8-byte. We realign the indirect argument if type alignment is bigger 3455 // than ABI alignment. 3456 uint64_t ABIAlign = 4; 3457 uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8; 3458 if (getABIKind() == ARMABIInfo::AAPCS_VFP || 3459 getABIKind() == ARMABIInfo::AAPCS) 3460 ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8); 3461 if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) { 3462 return ABIArgInfo::getIndirect(0, /*ByVal=*/true, 3463 /*Realign=*/TyAlign > ABIAlign); 3464 } 3465 3466 // Otherwise, pass by coercing to a structure of the appropriate size. 3467 llvm::Type* ElemTy; 3468 unsigned SizeRegs; 3469 // FIXME: Try to match the types of the arguments more accurately where 3470 // we can. 3471 if (getContext().getTypeAlign(Ty) <= 32) { 3472 ElemTy = llvm::Type::getInt32Ty(getVMContext()); 3473 SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32; 3474 } else { 3475 ElemTy = llvm::Type::getInt64Ty(getVMContext()); 3476 SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64; 3477 } 3478 3479 llvm::Type *STy = 3480 llvm::StructType::get(llvm::ArrayType::get(ElemTy, SizeRegs), NULL); 3481 return ABIArgInfo::getDirect(STy); 3482 } 3483 3484 static bool isIntegerLikeType(QualType Ty, ASTContext &Context, 3485 llvm::LLVMContext &VMContext) { 3486 // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure 3487 // is called integer-like if its size is less than or equal to one word, and 3488 // the offset of each of its addressable sub-fields is zero. 3489 3490 uint64_t Size = Context.getTypeSize(Ty); 3491 3492 // Check that the type fits in a word. 3493 if (Size > 32) 3494 return false; 3495 3496 // FIXME: Handle vector types! 3497 if (Ty->isVectorType()) 3498 return false; 3499 3500 // Float types are never treated as "integer like". 3501 if (Ty->isRealFloatingType()) 3502 return false; 3503 3504 // If this is a builtin or pointer type then it is ok. 3505 if (Ty->getAs<BuiltinType>() || Ty->isPointerType()) 3506 return true; 3507 3508 // Small complex integer types are "integer like". 3509 if (const ComplexType *CT = Ty->getAs<ComplexType>()) 3510 return isIntegerLikeType(CT->getElementType(), Context, VMContext); 3511 3512 // Single element and zero sized arrays should be allowed, by the definition 3513 // above, but they are not. 3514 3515 // Otherwise, it must be a record type. 3516 const RecordType *RT = Ty->getAs<RecordType>(); 3517 if (!RT) return false; 3518 3519 // Ignore records with flexible arrays. 3520 const RecordDecl *RD = RT->getDecl(); 3521 if (RD->hasFlexibleArrayMember()) 3522 return false; 3523 3524 // Check that all sub-fields are at offset 0, and are themselves "integer 3525 // like". 3526 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); 3527 3528 bool HadField = false; 3529 unsigned idx = 0; 3530 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 3531 i != e; ++i, ++idx) { 3532 const FieldDecl *FD = *i; 3533 3534 // Bit-fields are not addressable, we only need to verify they are "integer 3535 // like". We still have to disallow a subsequent non-bitfield, for example: 3536 // struct { int : 0; int x } 3537 // is non-integer like according to gcc. 3538 if (FD->isBitField()) { 3539 if (!RD->isUnion()) 3540 HadField = true; 3541 3542 if (!isIntegerLikeType(FD->getType(), Context, VMContext)) 3543 return false; 3544 3545 continue; 3546 } 3547 3548 // Check if this field is at offset 0. 3549 if (Layout.getFieldOffset(idx) != 0) 3550 return false; 3551 3552 if (!isIntegerLikeType(FD->getType(), Context, VMContext)) 3553 return false; 3554 3555 // Only allow at most one field in a structure. This doesn't match the 3556 // wording above, but follows gcc in situations with a field following an 3557 // empty structure. 3558 if (!RD->isUnion()) { 3559 if (HadField) 3560 return false; 3561 3562 HadField = true; 3563 } 3564 } 3565 3566 return true; 3567 } 3568 3569 ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy) const { 3570 if (RetTy->isVoidType()) 3571 return ABIArgInfo::getIgnore(); 3572 3573 // Large vector types should be returned via memory. 3574 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128) 3575 return ABIArgInfo::getIndirect(0); 3576 3577 if (!isAggregateTypeForABI(RetTy)) { 3578 // Treat an enum type as its underlying type. 3579 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 3580 RetTy = EnumTy->getDecl()->getIntegerType(); 3581 3582 return (RetTy->isPromotableIntegerType() ? 3583 ABIArgInfo::getExtend() : ABIArgInfo::getDirect()); 3584 } 3585 3586 // Structures with either a non-trivial destructor or a non-trivial 3587 // copy constructor are always indirect. 3588 if (isRecordReturnIndirect(RetTy, getCXXABI())) 3589 return ABIArgInfo::getIndirect(0, /*ByVal=*/false); 3590 3591 // Are we following APCS? 3592 if (getABIKind() == APCS) { 3593 if (isEmptyRecord(getContext(), RetTy, false)) 3594 return ABIArgInfo::getIgnore(); 3595 3596 // Complex types are all returned as packed integers. 3597 // 3598 // FIXME: Consider using 2 x vector types if the back end handles them 3599 // correctly. 3600 if (RetTy->isAnyComplexType()) 3601 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 3602 getContext().getTypeSize(RetTy))); 3603 3604 // Integer like structures are returned in r0. 3605 if (isIntegerLikeType(RetTy, getContext(), getVMContext())) { 3606 // Return in the smallest viable integer type. 3607 uint64_t Size = getContext().getTypeSize(RetTy); 3608 if (Size <= 8) 3609 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext())); 3610 if (Size <= 16) 3611 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext())); 3612 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext())); 3613 } 3614 3615 // Otherwise return in memory. 3616 return ABIArgInfo::getIndirect(0); 3617 } 3618 3619 // Otherwise this is an AAPCS variant. 3620 3621 if (isEmptyRecord(getContext(), RetTy, true)) 3622 return ABIArgInfo::getIgnore(); 3623 3624 // Check for homogeneous aggregates with AAPCS-VFP. 3625 if (getABIKind() == AAPCS_VFP) { 3626 const Type *Base = 0; 3627 if (isHomogeneousAggregate(RetTy, Base, getContext())) { 3628 assert(Base && "Base class should be set for homogeneous aggregate"); 3629 // Homogeneous Aggregates are returned directly. 3630 return ABIArgInfo::getDirect(); 3631 } 3632 } 3633 3634 // Aggregates <= 4 bytes are returned in r0; other aggregates 3635 // are returned indirectly. 3636 uint64_t Size = getContext().getTypeSize(RetTy); 3637 if (Size <= 32) { 3638 // Return in the smallest viable integer type. 3639 if (Size <= 8) 3640 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext())); 3641 if (Size <= 16) 3642 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext())); 3643 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext())); 3644 } 3645 3646 return ABIArgInfo::getIndirect(0); 3647 } 3648 3649 /// isIllegalVector - check whether Ty is an illegal vector type. 3650 bool ARMABIInfo::isIllegalVectorType(QualType Ty) const { 3651 if (const VectorType *VT = Ty->getAs<VectorType>()) { 3652 // Check whether VT is legal. 3653 unsigned NumElements = VT->getNumElements(); 3654 uint64_t Size = getContext().getTypeSize(VT); 3655 // NumElements should be power of 2. 3656 if ((NumElements & (NumElements - 1)) != 0) 3657 return true; 3658 // Size should be greater than 32 bits. 3659 return Size <= 32; 3660 } 3661 return false; 3662 } 3663 3664 llvm::Value *ARMABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 3665 CodeGenFunction &CGF) const { 3666 llvm::Type *BP = CGF.Int8PtrTy; 3667 llvm::Type *BPP = CGF.Int8PtrPtrTy; 3668 3669 CGBuilderTy &Builder = CGF.Builder; 3670 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap"); 3671 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur"); 3672 3673 if (isEmptyRecord(getContext(), Ty, true)) { 3674 // These are ignored for parameter passing purposes. 3675 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty)); 3676 return Builder.CreateBitCast(Addr, PTy); 3677 } 3678 3679 uint64_t Size = CGF.getContext().getTypeSize(Ty) / 8; 3680 uint64_t TyAlign = CGF.getContext().getTypeAlign(Ty) / 8; 3681 bool IsIndirect = false; 3682 3683 // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for 3684 // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte. 3685 if (getABIKind() == ARMABIInfo::AAPCS_VFP || 3686 getABIKind() == ARMABIInfo::AAPCS) 3687 TyAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8); 3688 else 3689 TyAlign = 4; 3690 // Use indirect if size of the illegal vector is bigger than 16 bytes. 3691 if (isIllegalVectorType(Ty) && Size > 16) { 3692 IsIndirect = true; 3693 Size = 4; 3694 TyAlign = 4; 3695 } 3696 3697 // Handle address alignment for ABI alignment > 4 bytes. 3698 if (TyAlign > 4) { 3699 assert((TyAlign & (TyAlign - 1)) == 0 && 3700 "Alignment is not power of 2!"); 3701 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int32Ty); 3702 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt32(TyAlign - 1)); 3703 AddrAsInt = Builder.CreateAnd(AddrAsInt, Builder.getInt32(~(TyAlign - 1))); 3704 Addr = Builder.CreateIntToPtr(AddrAsInt, BP, "ap.align"); 3705 } 3706 3707 uint64_t Offset = 3708 llvm::RoundUpToAlignment(Size, 4); 3709 llvm::Value *NextAddr = 3710 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset), 3711 "ap.next"); 3712 Builder.CreateStore(NextAddr, VAListAddrAsBPP); 3713 3714 if (IsIndirect) 3715 Addr = Builder.CreateLoad(Builder.CreateBitCast(Addr, BPP)); 3716 else if (TyAlign < CGF.getContext().getTypeAlign(Ty) / 8) { 3717 // We can't directly cast ap.cur to pointer to a vector type, since ap.cur 3718 // may not be correctly aligned for the vector type. We create an aligned 3719 // temporary space and copy the content over from ap.cur to the temporary 3720 // space. This is necessary if the natural alignment of the type is greater 3721 // than the ABI alignment. 3722 llvm::Type *I8PtrTy = Builder.getInt8PtrTy(); 3723 CharUnits CharSize = getContext().getTypeSizeInChars(Ty); 3724 llvm::Value *AlignedTemp = CGF.CreateTempAlloca(CGF.ConvertType(Ty), 3725 "var.align"); 3726 llvm::Value *Dst = Builder.CreateBitCast(AlignedTemp, I8PtrTy); 3727 llvm::Value *Src = Builder.CreateBitCast(Addr, I8PtrTy); 3728 Builder.CreateMemCpy(Dst, Src, 3729 llvm::ConstantInt::get(CGF.IntPtrTy, CharSize.getQuantity()), 3730 TyAlign, false); 3731 Addr = AlignedTemp; //The content is in aligned location. 3732 } 3733 llvm::Type *PTy = 3734 llvm::PointerType::getUnqual(CGF.ConvertType(Ty)); 3735 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy); 3736 3737 return AddrTyped; 3738 } 3739 3740 namespace { 3741 3742 class NaClARMABIInfo : public ABIInfo { 3743 public: 3744 NaClARMABIInfo(CodeGen::CodeGenTypes &CGT, ARMABIInfo::ABIKind Kind) 3745 : ABIInfo(CGT), PInfo(CGT), NInfo(CGT, Kind) {} 3746 virtual void computeInfo(CGFunctionInfo &FI) const; 3747 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 3748 CodeGenFunction &CGF) const; 3749 private: 3750 PNaClABIInfo PInfo; // Used for generating calls with pnaclcall callingconv. 3751 ARMABIInfo NInfo; // Used for everything else. 3752 }; 3753 3754 class NaClARMTargetCodeGenInfo : public TargetCodeGenInfo { 3755 public: 3756 NaClARMTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, ARMABIInfo::ABIKind Kind) 3757 : TargetCodeGenInfo(new NaClARMABIInfo(CGT, Kind)) {} 3758 }; 3759 3760 } 3761 3762 void NaClARMABIInfo::computeInfo(CGFunctionInfo &FI) const { 3763 if (FI.getASTCallingConvention() == CC_PnaclCall) 3764 PInfo.computeInfo(FI); 3765 else 3766 static_cast<const ABIInfo&>(NInfo).computeInfo(FI); 3767 } 3768 3769 llvm::Value *NaClARMABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 3770 CodeGenFunction &CGF) const { 3771 // Always use the native convention; calling pnacl-style varargs functions 3772 // is unsupported. 3773 return static_cast<const ABIInfo&>(NInfo).EmitVAArg(VAListAddr, Ty, CGF); 3774 } 3775 3776 //===----------------------------------------------------------------------===// 3777 // AArch64 ABI Implementation 3778 //===----------------------------------------------------------------------===// 3779 3780 namespace { 3781 3782 class AArch64ABIInfo : public ABIInfo { 3783 public: 3784 AArch64ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {} 3785 3786 private: 3787 // The AArch64 PCS is explicit about return types and argument types being 3788 // handled identically, so we don't need to draw a distinction between 3789 // Argument and Return classification. 3790 ABIArgInfo classifyGenericType(QualType Ty, int &FreeIntRegs, 3791 int &FreeVFPRegs) const; 3792 3793 ABIArgInfo tryUseRegs(QualType Ty, int &FreeRegs, int RegsNeeded, bool IsInt, 3794 llvm::Type *DirectTy = 0) const; 3795 3796 virtual void computeInfo(CGFunctionInfo &FI) const; 3797 3798 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 3799 CodeGenFunction &CGF) const; 3800 }; 3801 3802 class AArch64TargetCodeGenInfo : public TargetCodeGenInfo { 3803 public: 3804 AArch64TargetCodeGenInfo(CodeGenTypes &CGT) 3805 :TargetCodeGenInfo(new AArch64ABIInfo(CGT)) {} 3806 3807 const AArch64ABIInfo &getABIInfo() const { 3808 return static_cast<const AArch64ABIInfo&>(TargetCodeGenInfo::getABIInfo()); 3809 } 3810 3811 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const { 3812 return 31; 3813 } 3814 3815 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 3816 llvm::Value *Address) const { 3817 // 0-31 are x0-x30 and sp: 8 bytes each 3818 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8); 3819 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 31); 3820 3821 // 64-95 are v0-v31: 16 bytes each 3822 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16); 3823 AssignToArrayRange(CGF.Builder, Address, Sixteen8, 64, 95); 3824 3825 return false; 3826 } 3827 3828 }; 3829 3830 } 3831 3832 void AArch64ABIInfo::computeInfo(CGFunctionInfo &FI) const { 3833 int FreeIntRegs = 8, FreeVFPRegs = 8; 3834 3835 FI.getReturnInfo() = classifyGenericType(FI.getReturnType(), 3836 FreeIntRegs, FreeVFPRegs); 3837 3838 FreeIntRegs = FreeVFPRegs = 8; 3839 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end(); 3840 it != ie; ++it) { 3841 it->info = classifyGenericType(it->type, FreeIntRegs, FreeVFPRegs); 3842 3843 } 3844 } 3845 3846 ABIArgInfo 3847 AArch64ABIInfo::tryUseRegs(QualType Ty, int &FreeRegs, int RegsNeeded, 3848 bool IsInt, llvm::Type *DirectTy) const { 3849 if (FreeRegs >= RegsNeeded) { 3850 FreeRegs -= RegsNeeded; 3851 return ABIArgInfo::getDirect(DirectTy); 3852 } 3853 3854 llvm::Type *Padding = 0; 3855 3856 // We need padding so that later arguments don't get filled in anyway. That 3857 // wouldn't happen if only ByVal arguments followed in the same category, but 3858 // a large structure will simply seem to be a pointer as far as LLVM is 3859 // concerned. 3860 if (FreeRegs > 0) { 3861 if (IsInt) 3862 Padding = llvm::Type::getInt64Ty(getVMContext()); 3863 else 3864 Padding = llvm::Type::getFloatTy(getVMContext()); 3865 3866 // Either [N x i64] or [N x float]. 3867 Padding = llvm::ArrayType::get(Padding, FreeRegs); 3868 FreeRegs = 0; 3869 } 3870 3871 return ABIArgInfo::getIndirect(getContext().getTypeAlign(Ty) / 8, 3872 /*IsByVal=*/ true, /*Realign=*/ false, 3873 Padding); 3874 } 3875 3876 3877 ABIArgInfo AArch64ABIInfo::classifyGenericType(QualType Ty, 3878 int &FreeIntRegs, 3879 int &FreeVFPRegs) const { 3880 // Can only occurs for return, but harmless otherwise. 3881 if (Ty->isVoidType()) 3882 return ABIArgInfo::getIgnore(); 3883 3884 // Large vector types should be returned via memory. There's no such concept 3885 // in the ABI, but they'd be over 16 bytes anyway so no matter how they're 3886 // classified they'd go into memory (see B.3). 3887 if (Ty->isVectorType() && getContext().getTypeSize(Ty) > 128) { 3888 if (FreeIntRegs > 0) 3889 --FreeIntRegs; 3890 return ABIArgInfo::getIndirect(0, /*ByVal=*/false); 3891 } 3892 3893 // All non-aggregate LLVM types have a concrete ABI representation so they can 3894 // be passed directly. After this block we're guaranteed to be in a 3895 // complicated case. 3896 if (!isAggregateTypeForABI(Ty)) { 3897 // Treat an enum type as its underlying type. 3898 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 3899 Ty = EnumTy->getDecl()->getIntegerType(); 3900 3901 if (Ty->isFloatingType() || Ty->isVectorType()) 3902 return tryUseRegs(Ty, FreeVFPRegs, /*RegsNeeded=*/ 1, /*IsInt=*/ false); 3903 3904 assert(getContext().getTypeSize(Ty) <= 128 && 3905 "unexpectedly large scalar type"); 3906 3907 int RegsNeeded = getContext().getTypeSize(Ty) > 64 ? 2 : 1; 3908 3909 // If the type may need padding registers to ensure "alignment", we must be 3910 // careful when this is accounted for. Increasing the effective size covers 3911 // all cases. 3912 if (getContext().getTypeAlign(Ty) == 128) 3913 RegsNeeded += FreeIntRegs % 2 != 0; 3914 3915 return tryUseRegs(Ty, FreeIntRegs, RegsNeeded, /*IsInt=*/ true); 3916 } 3917 3918 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) { 3919 if (FreeIntRegs > 0 && RAA == CGCXXABI::RAA_Indirect) 3920 --FreeIntRegs; 3921 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory); 3922 } 3923 3924 if (isEmptyRecord(getContext(), Ty, true)) { 3925 if (!getContext().getLangOpts().CPlusPlus) { 3926 // Empty structs outside C++ mode are a GNU extension, so no ABI can 3927 // possibly tell us what to do. It turns out (I believe) that GCC ignores 3928 // the object for parameter-passsing purposes. 3929 return ABIArgInfo::getIgnore(); 3930 } 3931 3932 // The combination of C++98 9p5 (sizeof(struct) != 0) and the pseudocode 3933 // description of va_arg in the PCS require that an empty struct does 3934 // actually occupy space for parameter-passing. I'm hoping for a 3935 // clarification giving an explicit paragraph to point to in future. 3936 return tryUseRegs(Ty, FreeIntRegs, /*RegsNeeded=*/ 1, /*IsInt=*/ true, 3937 llvm::Type::getInt8Ty(getVMContext())); 3938 } 3939 3940 // Homogeneous vector aggregates get passed in registers or on the stack. 3941 const Type *Base = 0; 3942 uint64_t NumMembers = 0; 3943 if (isHomogeneousAggregate(Ty, Base, getContext(), &NumMembers)) { 3944 assert(Base && "Base class should be set for homogeneous aggregate"); 3945 // Homogeneous aggregates are passed and returned directly. 3946 return tryUseRegs(Ty, FreeVFPRegs, /*RegsNeeded=*/ NumMembers, 3947 /*IsInt=*/ false); 3948 } 3949 3950 uint64_t Size = getContext().getTypeSize(Ty); 3951 if (Size <= 128) { 3952 // Small structs can use the same direct type whether they're in registers 3953 // or on the stack. 3954 llvm::Type *BaseTy; 3955 unsigned NumBases; 3956 int SizeInRegs = (Size + 63) / 64; 3957 3958 if (getContext().getTypeAlign(Ty) == 128) { 3959 BaseTy = llvm::Type::getIntNTy(getVMContext(), 128); 3960 NumBases = 1; 3961 3962 // If the type may need padding registers to ensure "alignment", we must 3963 // be careful when this is accounted for. Increasing the effective size 3964 // covers all cases. 3965 SizeInRegs += FreeIntRegs % 2 != 0; 3966 } else { 3967 BaseTy = llvm::Type::getInt64Ty(getVMContext()); 3968 NumBases = SizeInRegs; 3969 } 3970 llvm::Type *DirectTy = llvm::ArrayType::get(BaseTy, NumBases); 3971 3972 return tryUseRegs(Ty, FreeIntRegs, /*RegsNeeded=*/ SizeInRegs, 3973 /*IsInt=*/ true, DirectTy); 3974 } 3975 3976 // If the aggregate is > 16 bytes, it's passed and returned indirectly. In 3977 // LLVM terms the return uses an "sret" pointer, but that's handled elsewhere. 3978 --FreeIntRegs; 3979 return ABIArgInfo::getIndirect(0, /* byVal = */ false); 3980 } 3981 3982 llvm::Value *AArch64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 3983 CodeGenFunction &CGF) const { 3984 // The AArch64 va_list type and handling is specified in the Procedure Call 3985 // Standard, section B.4: 3986 // 3987 // struct { 3988 // void *__stack; 3989 // void *__gr_top; 3990 // void *__vr_top; 3991 // int __gr_offs; 3992 // int __vr_offs; 3993 // }; 3994 3995 assert(!CGF.CGM.getDataLayout().isBigEndian() 3996 && "va_arg not implemented for big-endian AArch64"); 3997 3998 int FreeIntRegs = 8, FreeVFPRegs = 8; 3999 Ty = CGF.getContext().getCanonicalType(Ty); 4000 ABIArgInfo AI = classifyGenericType(Ty, FreeIntRegs, FreeVFPRegs); 4001 4002 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg"); 4003 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg"); 4004 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack"); 4005 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end"); 4006 4007 llvm::Value *reg_offs_p = 0, *reg_offs = 0; 4008 int reg_top_index; 4009 int RegSize; 4010 if (FreeIntRegs < 8) { 4011 assert(FreeVFPRegs == 8 && "Arguments never split between int & VFP regs"); 4012 // 3 is the field number of __gr_offs 4013 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 3, "gr_offs_p"); 4014 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs"); 4015 reg_top_index = 1; // field number for __gr_top 4016 RegSize = 8 * (8 - FreeIntRegs); 4017 } else { 4018 assert(FreeVFPRegs < 8 && "Argument must go in VFP or int regs"); 4019 // 4 is the field number of __vr_offs. 4020 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 4, "vr_offs_p"); 4021 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs"); 4022 reg_top_index = 2; // field number for __vr_top 4023 RegSize = 16 * (8 - FreeVFPRegs); 4024 } 4025 4026 //======================================= 4027 // Find out where argument was passed 4028 //======================================= 4029 4030 // If reg_offs >= 0 we're already using the stack for this type of 4031 // argument. We don't want to keep updating reg_offs (in case it overflows, 4032 // though anyone passing 2GB of arguments, each at most 16 bytes, deserves 4033 // whatever they get). 4034 llvm::Value *UsingStack = 0; 4035 UsingStack = CGF.Builder.CreateICmpSGE(reg_offs, 4036 llvm::ConstantInt::get(CGF.Int32Ty, 0)); 4037 4038 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock); 4039 4040 // Otherwise, at least some kind of argument could go in these registers, the 4041 // quesiton is whether this particular type is too big. 4042 CGF.EmitBlock(MaybeRegBlock); 4043 4044 // Integer arguments may need to correct register alignment (for example a 4045 // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we 4046 // align __gr_offs to calculate the potential address. 4047 if (FreeIntRegs < 8 && AI.isDirect() && getContext().getTypeAlign(Ty) > 64) { 4048 int Align = getContext().getTypeAlign(Ty) / 8; 4049 4050 reg_offs = CGF.Builder.CreateAdd(reg_offs, 4051 llvm::ConstantInt::get(CGF.Int32Ty, Align - 1), 4052 "align_regoffs"); 4053 reg_offs = CGF.Builder.CreateAnd(reg_offs, 4054 llvm::ConstantInt::get(CGF.Int32Ty, -Align), 4055 "aligned_regoffs"); 4056 } 4057 4058 // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list. 4059 llvm::Value *NewOffset = 0; 4060 NewOffset = CGF.Builder.CreateAdd(reg_offs, 4061 llvm::ConstantInt::get(CGF.Int32Ty, RegSize), 4062 "new_reg_offs"); 4063 CGF.Builder.CreateStore(NewOffset, reg_offs_p); 4064 4065 // Now we're in a position to decide whether this argument really was in 4066 // registers or not. 4067 llvm::Value *InRegs = 0; 4068 InRegs = CGF.Builder.CreateICmpSLE(NewOffset, 4069 llvm::ConstantInt::get(CGF.Int32Ty, 0), 4070 "inreg"); 4071 4072 CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock); 4073 4074 //======================================= 4075 // Argument was in registers 4076 //======================================= 4077 4078 // Now we emit the code for if the argument was originally passed in 4079 // registers. First start the appropriate block: 4080 CGF.EmitBlock(InRegBlock); 4081 4082 llvm::Value *reg_top_p = 0, *reg_top = 0; 4083 reg_top_p = CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index, "reg_top_p"); 4084 reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top"); 4085 llvm::Value *BaseAddr = CGF.Builder.CreateGEP(reg_top, reg_offs); 4086 llvm::Value *RegAddr = 0; 4087 llvm::Type *MemTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty)); 4088 4089 if (!AI.isDirect()) { 4090 // If it's been passed indirectly (actually a struct), whatever we find from 4091 // stored registers or on the stack will actually be a struct **. 4092 MemTy = llvm::PointerType::getUnqual(MemTy); 4093 } 4094 4095 const Type *Base = 0; 4096 uint64_t NumMembers; 4097 if (isHomogeneousAggregate(Ty, Base, getContext(), &NumMembers) 4098 && NumMembers > 1) { 4099 // Homogeneous aggregates passed in registers will have their elements split 4100 // and stored 16-bytes apart regardless of size (they're notionally in qN, 4101 // qN+1, ...). We reload and store into a temporary local variable 4102 // contiguously. 4103 assert(AI.isDirect() && "Homogeneous aggregates should be passed directly"); 4104 llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0)); 4105 llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers); 4106 llvm::Value *Tmp = CGF.CreateTempAlloca(HFATy); 4107 4108 for (unsigned i = 0; i < NumMembers; ++i) { 4109 llvm::Value *BaseOffset = llvm::ConstantInt::get(CGF.Int32Ty, 16 * i); 4110 llvm::Value *LoadAddr = CGF.Builder.CreateGEP(BaseAddr, BaseOffset); 4111 LoadAddr = CGF.Builder.CreateBitCast(LoadAddr, 4112 llvm::PointerType::getUnqual(BaseTy)); 4113 llvm::Value *StoreAddr = CGF.Builder.CreateStructGEP(Tmp, i); 4114 4115 llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr); 4116 CGF.Builder.CreateStore(Elem, StoreAddr); 4117 } 4118 4119 RegAddr = CGF.Builder.CreateBitCast(Tmp, MemTy); 4120 } else { 4121 // Otherwise the object is contiguous in memory 4122 RegAddr = CGF.Builder.CreateBitCast(BaseAddr, MemTy); 4123 } 4124 4125 CGF.EmitBranch(ContBlock); 4126 4127 //======================================= 4128 // Argument was on the stack 4129 //======================================= 4130 CGF.EmitBlock(OnStackBlock); 4131 4132 llvm::Value *stack_p = 0, *OnStackAddr = 0; 4133 stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "stack_p"); 4134 OnStackAddr = CGF.Builder.CreateLoad(stack_p, "stack"); 4135 4136 // Again, stack arguments may need realigmnent. In this case both integer and 4137 // floating-point ones might be affected. 4138 if (AI.isDirect() && getContext().getTypeAlign(Ty) > 64) { 4139 int Align = getContext().getTypeAlign(Ty) / 8; 4140 4141 OnStackAddr = CGF.Builder.CreatePtrToInt(OnStackAddr, CGF.Int64Ty); 4142 4143 OnStackAddr = CGF.Builder.CreateAdd(OnStackAddr, 4144 llvm::ConstantInt::get(CGF.Int64Ty, Align - 1), 4145 "align_stack"); 4146 OnStackAddr = CGF.Builder.CreateAnd(OnStackAddr, 4147 llvm::ConstantInt::get(CGF.Int64Ty, -Align), 4148 "align_stack"); 4149 4150 OnStackAddr = CGF.Builder.CreateIntToPtr(OnStackAddr, CGF.Int8PtrTy); 4151 } 4152 4153 uint64_t StackSize; 4154 if (AI.isDirect()) 4155 StackSize = getContext().getTypeSize(Ty) / 8; 4156 else 4157 StackSize = 8; 4158 4159 // All stack slots are 8 bytes 4160 StackSize = llvm::RoundUpToAlignment(StackSize, 8); 4161 4162 llvm::Value *StackSizeC = llvm::ConstantInt::get(CGF.Int32Ty, StackSize); 4163 llvm::Value *NewStack = CGF.Builder.CreateGEP(OnStackAddr, StackSizeC, 4164 "new_stack"); 4165 4166 // Write the new value of __stack for the next call to va_arg 4167 CGF.Builder.CreateStore(NewStack, stack_p); 4168 4169 OnStackAddr = CGF.Builder.CreateBitCast(OnStackAddr, MemTy); 4170 4171 CGF.EmitBranch(ContBlock); 4172 4173 //======================================= 4174 // Tidy up 4175 //======================================= 4176 CGF.EmitBlock(ContBlock); 4177 4178 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(MemTy, 2, "vaarg.addr"); 4179 ResAddr->addIncoming(RegAddr, InRegBlock); 4180 ResAddr->addIncoming(OnStackAddr, OnStackBlock); 4181 4182 if (AI.isDirect()) 4183 return ResAddr; 4184 4185 return CGF.Builder.CreateLoad(ResAddr, "vaarg.addr"); 4186 } 4187 4188 //===----------------------------------------------------------------------===// 4189 // NVPTX ABI Implementation 4190 //===----------------------------------------------------------------------===// 4191 4192 namespace { 4193 4194 class NVPTXABIInfo : public ABIInfo { 4195 public: 4196 NVPTXABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {} 4197 4198 ABIArgInfo classifyReturnType(QualType RetTy) const; 4199 ABIArgInfo classifyArgumentType(QualType Ty) const; 4200 4201 virtual void computeInfo(CGFunctionInfo &FI) const; 4202 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 4203 CodeGenFunction &CFG) const; 4204 }; 4205 4206 class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo { 4207 public: 4208 NVPTXTargetCodeGenInfo(CodeGenTypes &CGT) 4209 : TargetCodeGenInfo(new NVPTXABIInfo(CGT)) {} 4210 4211 virtual void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 4212 CodeGen::CodeGenModule &M) const; 4213 private: 4214 static void addKernelMetadata(llvm::Function *F); 4215 }; 4216 4217 ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const { 4218 if (RetTy->isVoidType()) 4219 return ABIArgInfo::getIgnore(); 4220 4221 // note: this is different from default ABI 4222 if (!RetTy->isScalarType()) 4223 return ABIArgInfo::getDirect(); 4224 4225 // Treat an enum type as its underlying type. 4226 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 4227 RetTy = EnumTy->getDecl()->getIntegerType(); 4228 4229 return (RetTy->isPromotableIntegerType() ? 4230 ABIArgInfo::getExtend() : ABIArgInfo::getDirect()); 4231 } 4232 4233 ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const { 4234 // Treat an enum type as its underlying type. 4235 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 4236 Ty = EnumTy->getDecl()->getIntegerType(); 4237 4238 return (Ty->isPromotableIntegerType() ? 4239 ABIArgInfo::getExtend() : ABIArgInfo::getDirect()); 4240 } 4241 4242 void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const { 4243 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 4244 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end(); 4245 it != ie; ++it) 4246 it->info = classifyArgumentType(it->type); 4247 4248 // Always honor user-specified calling convention. 4249 if (FI.getCallingConvention() != llvm::CallingConv::C) 4250 return; 4251 4252 FI.setEffectiveCallingConvention(getRuntimeCC()); 4253 } 4254 4255 llvm::Value *NVPTXABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 4256 CodeGenFunction &CFG) const { 4257 llvm_unreachable("NVPTX does not support varargs"); 4258 } 4259 4260 void NVPTXTargetCodeGenInfo:: 4261 SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 4262 CodeGen::CodeGenModule &M) const{ 4263 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D); 4264 if (!FD) return; 4265 4266 llvm::Function *F = cast<llvm::Function>(GV); 4267 4268 // Perform special handling in OpenCL mode 4269 if (M.getLangOpts().OpenCL) { 4270 // Use OpenCL function attributes to check for kernel functions 4271 // By default, all functions are device functions 4272 if (FD->hasAttr<OpenCLKernelAttr>()) { 4273 // OpenCL __kernel functions get kernel metadata 4274 addKernelMetadata(F); 4275 // And kernel functions are not subject to inlining 4276 F->addFnAttr(llvm::Attribute::NoInline); 4277 } 4278 } 4279 4280 // Perform special handling in CUDA mode. 4281 if (M.getLangOpts().CUDA) { 4282 // CUDA __global__ functions get a kernel metadata entry. Since 4283 // __global__ functions cannot be called from the device, we do not 4284 // need to set the noinline attribute. 4285 if (FD->hasAttr<CUDAGlobalAttr>()) 4286 addKernelMetadata(F); 4287 } 4288 } 4289 4290 void NVPTXTargetCodeGenInfo::addKernelMetadata(llvm::Function *F) { 4291 llvm::Module *M = F->getParent(); 4292 llvm::LLVMContext &Ctx = M->getContext(); 4293 4294 // Get "nvvm.annotations" metadata node 4295 llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations"); 4296 4297 // Create !{<func-ref>, metadata !"kernel", i32 1} node 4298 llvm::SmallVector<llvm::Value *, 3> MDVals; 4299 MDVals.push_back(F); 4300 MDVals.push_back(llvm::MDString::get(Ctx, "kernel")); 4301 MDVals.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), 1)); 4302 4303 // Append metadata to nvvm.annotations 4304 MD->addOperand(llvm::MDNode::get(Ctx, MDVals)); 4305 } 4306 4307 } 4308 4309 //===----------------------------------------------------------------------===// 4310 // SystemZ ABI Implementation 4311 //===----------------------------------------------------------------------===// 4312 4313 namespace { 4314 4315 class SystemZABIInfo : public ABIInfo { 4316 public: 4317 SystemZABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {} 4318 4319 bool isPromotableIntegerType(QualType Ty) const; 4320 bool isCompoundType(QualType Ty) const; 4321 bool isFPArgumentType(QualType Ty) const; 4322 4323 ABIArgInfo classifyReturnType(QualType RetTy) const; 4324 ABIArgInfo classifyArgumentType(QualType ArgTy) const; 4325 4326 virtual void computeInfo(CGFunctionInfo &FI) const { 4327 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 4328 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end(); 4329 it != ie; ++it) 4330 it->info = classifyArgumentType(it->type); 4331 } 4332 4333 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 4334 CodeGenFunction &CGF) const; 4335 }; 4336 4337 class SystemZTargetCodeGenInfo : public TargetCodeGenInfo { 4338 public: 4339 SystemZTargetCodeGenInfo(CodeGenTypes &CGT) 4340 : TargetCodeGenInfo(new SystemZABIInfo(CGT)) {} 4341 }; 4342 4343 } 4344 4345 bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const { 4346 // Treat an enum type as its underlying type. 4347 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 4348 Ty = EnumTy->getDecl()->getIntegerType(); 4349 4350 // Promotable integer types are required to be promoted by the ABI. 4351 if (Ty->isPromotableIntegerType()) 4352 return true; 4353 4354 // 32-bit values must also be promoted. 4355 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) 4356 switch (BT->getKind()) { 4357 case BuiltinType::Int: 4358 case BuiltinType::UInt: 4359 return true; 4360 default: 4361 return false; 4362 } 4363 return false; 4364 } 4365 4366 bool SystemZABIInfo::isCompoundType(QualType Ty) const { 4367 return Ty->isAnyComplexType() || isAggregateTypeForABI(Ty); 4368 } 4369 4370 bool SystemZABIInfo::isFPArgumentType(QualType Ty) const { 4371 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) 4372 switch (BT->getKind()) { 4373 case BuiltinType::Float: 4374 case BuiltinType::Double: 4375 return true; 4376 default: 4377 return false; 4378 } 4379 4380 if (const RecordType *RT = Ty->getAsStructureType()) { 4381 const RecordDecl *RD = RT->getDecl(); 4382 bool Found = false; 4383 4384 // If this is a C++ record, check the bases first. 4385 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 4386 for (CXXRecordDecl::base_class_const_iterator I = CXXRD->bases_begin(), 4387 E = CXXRD->bases_end(); I != E; ++I) { 4388 QualType Base = I->getType(); 4389 4390 // Empty bases don't affect things either way. 4391 if (isEmptyRecord(getContext(), Base, true)) 4392 continue; 4393 4394 if (Found) 4395 return false; 4396 Found = isFPArgumentType(Base); 4397 if (!Found) 4398 return false; 4399 } 4400 4401 // Check the fields. 4402 for (RecordDecl::field_iterator I = RD->field_begin(), 4403 E = RD->field_end(); I != E; ++I) { 4404 const FieldDecl *FD = *I; 4405 4406 // Empty bitfields don't affect things either way. 4407 // Unlike isSingleElementStruct(), empty structure and array fields 4408 // do count. So do anonymous bitfields that aren't zero-sized. 4409 if (FD->isBitField() && FD->getBitWidthValue(getContext()) == 0) 4410 return true; 4411 4412 // Unlike isSingleElementStruct(), arrays do not count. 4413 // Nested isFPArgumentType structures still do though. 4414 if (Found) 4415 return false; 4416 Found = isFPArgumentType(FD->getType()); 4417 if (!Found) 4418 return false; 4419 } 4420 4421 // Unlike isSingleElementStruct(), trailing padding is allowed. 4422 // An 8-byte aligned struct s { float f; } is passed as a double. 4423 return Found; 4424 } 4425 4426 return false; 4427 } 4428 4429 llvm::Value *SystemZABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 4430 CodeGenFunction &CGF) const { 4431 // Assume that va_list type is correct; should be pointer to LLVM type: 4432 // struct { 4433 // i64 __gpr; 4434 // i64 __fpr; 4435 // i8 *__overflow_arg_area; 4436 // i8 *__reg_save_area; 4437 // }; 4438 4439 // Every argument occupies 8 bytes and is passed by preference in either 4440 // GPRs or FPRs. 4441 Ty = CGF.getContext().getCanonicalType(Ty); 4442 ABIArgInfo AI = classifyArgumentType(Ty); 4443 bool InFPRs = isFPArgumentType(Ty); 4444 4445 llvm::Type *APTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty)); 4446 bool IsIndirect = AI.isIndirect(); 4447 unsigned UnpaddedBitSize; 4448 if (IsIndirect) { 4449 APTy = llvm::PointerType::getUnqual(APTy); 4450 UnpaddedBitSize = 64; 4451 } else 4452 UnpaddedBitSize = getContext().getTypeSize(Ty); 4453 unsigned PaddedBitSize = 64; 4454 assert((UnpaddedBitSize <= PaddedBitSize) && "Invalid argument size."); 4455 4456 unsigned PaddedSize = PaddedBitSize / 8; 4457 unsigned Padding = (PaddedBitSize - UnpaddedBitSize) / 8; 4458 4459 unsigned MaxRegs, RegCountField, RegSaveIndex, RegPadding; 4460 if (InFPRs) { 4461 MaxRegs = 4; // Maximum of 4 FPR arguments 4462 RegCountField = 1; // __fpr 4463 RegSaveIndex = 16; // save offset for f0 4464 RegPadding = 0; // floats are passed in the high bits of an FPR 4465 } else { 4466 MaxRegs = 5; // Maximum of 5 GPR arguments 4467 RegCountField = 0; // __gpr 4468 RegSaveIndex = 2; // save offset for r2 4469 RegPadding = Padding; // values are passed in the low bits of a GPR 4470 } 4471 4472 llvm::Value *RegCountPtr = 4473 CGF.Builder.CreateStructGEP(VAListAddr, RegCountField, "reg_count_ptr"); 4474 llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count"); 4475 llvm::Type *IndexTy = RegCount->getType(); 4476 llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs); 4477 llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV, 4478 "fits_in_regs"); 4479 4480 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg"); 4481 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem"); 4482 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end"); 4483 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock); 4484 4485 // Emit code to load the value if it was passed in registers. 4486 CGF.EmitBlock(InRegBlock); 4487 4488 // Work out the address of an argument register. 4489 llvm::Value *PaddedSizeV = llvm::ConstantInt::get(IndexTy, PaddedSize); 4490 llvm::Value *ScaledRegCount = 4491 CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count"); 4492 llvm::Value *RegBase = 4493 llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize + RegPadding); 4494 llvm::Value *RegOffset = 4495 CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset"); 4496 llvm::Value *RegSaveAreaPtr = 4497 CGF.Builder.CreateStructGEP(VAListAddr, 3, "reg_save_area_ptr"); 4498 llvm::Value *RegSaveArea = 4499 CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area"); 4500 llvm::Value *RawRegAddr = 4501 CGF.Builder.CreateGEP(RegSaveArea, RegOffset, "raw_reg_addr"); 4502 llvm::Value *RegAddr = 4503 CGF.Builder.CreateBitCast(RawRegAddr, APTy, "reg_addr"); 4504 4505 // Update the register count 4506 llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1); 4507 llvm::Value *NewRegCount = 4508 CGF.Builder.CreateAdd(RegCount, One, "reg_count"); 4509 CGF.Builder.CreateStore(NewRegCount, RegCountPtr); 4510 CGF.EmitBranch(ContBlock); 4511 4512 // Emit code to load the value if it was passed in memory. 4513 CGF.EmitBlock(InMemBlock); 4514 4515 // Work out the address of a stack argument. 4516 llvm::Value *OverflowArgAreaPtr = 4517 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr"); 4518 llvm::Value *OverflowArgArea = 4519 CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"); 4520 llvm::Value *PaddingV = llvm::ConstantInt::get(IndexTy, Padding); 4521 llvm::Value *RawMemAddr = 4522 CGF.Builder.CreateGEP(OverflowArgArea, PaddingV, "raw_mem_addr"); 4523 llvm::Value *MemAddr = 4524 CGF.Builder.CreateBitCast(RawMemAddr, APTy, "mem_addr"); 4525 4526 // Update overflow_arg_area_ptr pointer 4527 llvm::Value *NewOverflowArgArea = 4528 CGF.Builder.CreateGEP(OverflowArgArea, PaddedSizeV, "overflow_arg_area"); 4529 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr); 4530 CGF.EmitBranch(ContBlock); 4531 4532 // Return the appropriate result. 4533 CGF.EmitBlock(ContBlock); 4534 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(APTy, 2, "va_arg.addr"); 4535 ResAddr->addIncoming(RegAddr, InRegBlock); 4536 ResAddr->addIncoming(MemAddr, InMemBlock); 4537 4538 if (IsIndirect) 4539 return CGF.Builder.CreateLoad(ResAddr, "indirect_arg"); 4540 4541 return ResAddr; 4542 } 4543 4544 bool X86_32TargetCodeGenInfo::isStructReturnInRegABI( 4545 const llvm::Triple &Triple, const CodeGenOptions &Opts) { 4546 assert(Triple.getArch() == llvm::Triple::x86); 4547 4548 switch (Opts.getStructReturnConvention()) { 4549 case CodeGenOptions::SRCK_Default: 4550 break; 4551 case CodeGenOptions::SRCK_OnStack: // -fpcc-struct-return 4552 return false; 4553 case CodeGenOptions::SRCK_InRegs: // -freg-struct-return 4554 return true; 4555 } 4556 4557 if (Triple.isOSDarwin()) 4558 return true; 4559 4560 switch (Triple.getOS()) { 4561 case llvm::Triple::Cygwin: 4562 case llvm::Triple::MinGW32: 4563 case llvm::Triple::AuroraUX: 4564 case llvm::Triple::DragonFly: 4565 case llvm::Triple::FreeBSD: 4566 case llvm::Triple::OpenBSD: 4567 case llvm::Triple::Bitrig: 4568 case llvm::Triple::Win32: 4569 return true; 4570 default: 4571 return false; 4572 } 4573 } 4574 4575 ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const { 4576 if (RetTy->isVoidType()) 4577 return ABIArgInfo::getIgnore(); 4578 if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64) 4579 return ABIArgInfo::getIndirect(0); 4580 return (isPromotableIntegerType(RetTy) ? 4581 ABIArgInfo::getExtend() : ABIArgInfo::getDirect()); 4582 } 4583 4584 ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const { 4585 // Handle the generic C++ ABI. 4586 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 4587 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory); 4588 4589 // Integers and enums are extended to full register width. 4590 if (isPromotableIntegerType(Ty)) 4591 return ABIArgInfo::getExtend(); 4592 4593 // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly. 4594 uint64_t Size = getContext().getTypeSize(Ty); 4595 if (Size != 8 && Size != 16 && Size != 32 && Size != 64) 4596 return ABIArgInfo::getIndirect(0, /*ByVal=*/false); 4597 4598 // Handle small structures. 4599 if (const RecordType *RT = Ty->getAs<RecordType>()) { 4600 // Structures with flexible arrays have variable length, so really 4601 // fail the size test above. 4602 const RecordDecl *RD = RT->getDecl(); 4603 if (RD->hasFlexibleArrayMember()) 4604 return ABIArgInfo::getIndirect(0, /*ByVal=*/false); 4605 4606 // The structure is passed as an unextended integer, a float, or a double. 4607 llvm::Type *PassTy; 4608 if (isFPArgumentType(Ty)) { 4609 assert(Size == 32 || Size == 64); 4610 if (Size == 32) 4611 PassTy = llvm::Type::getFloatTy(getVMContext()); 4612 else 4613 PassTy = llvm::Type::getDoubleTy(getVMContext()); 4614 } else 4615 PassTy = llvm::IntegerType::get(getVMContext(), Size); 4616 return ABIArgInfo::getDirect(PassTy); 4617 } 4618 4619 // Non-structure compounds are passed indirectly. 4620 if (isCompoundType(Ty)) 4621 return ABIArgInfo::getIndirect(0, /*ByVal=*/false); 4622 4623 return ABIArgInfo::getDirect(0); 4624 } 4625 4626 //===----------------------------------------------------------------------===// 4627 // MSP430 ABI Implementation 4628 //===----------------------------------------------------------------------===// 4629 4630 namespace { 4631 4632 class MSP430TargetCodeGenInfo : public TargetCodeGenInfo { 4633 public: 4634 MSP430TargetCodeGenInfo(CodeGenTypes &CGT) 4635 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {} 4636 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 4637 CodeGen::CodeGenModule &M) const; 4638 }; 4639 4640 } 4641 4642 void MSP430TargetCodeGenInfo::SetTargetAttributes(const Decl *D, 4643 llvm::GlobalValue *GV, 4644 CodeGen::CodeGenModule &M) const { 4645 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 4646 if (const MSP430InterruptAttr *attr = FD->getAttr<MSP430InterruptAttr>()) { 4647 // Handle 'interrupt' attribute: 4648 llvm::Function *F = cast<llvm::Function>(GV); 4649 4650 // Step 1: Set ISR calling convention. 4651 F->setCallingConv(llvm::CallingConv::MSP430_INTR); 4652 4653 // Step 2: Add attributes goodness. 4654 F->addFnAttr(llvm::Attribute::NoInline); 4655 4656 // Step 3: Emit ISR vector alias. 4657 unsigned Num = attr->getNumber() / 2; 4658 new llvm::GlobalAlias(GV->getType(), llvm::Function::ExternalLinkage, 4659 "__isr_" + Twine(Num), 4660 GV, &M.getModule()); 4661 } 4662 } 4663 } 4664 4665 //===----------------------------------------------------------------------===// 4666 // MIPS ABI Implementation. This works for both little-endian and 4667 // big-endian variants. 4668 //===----------------------------------------------------------------------===// 4669 4670 namespace { 4671 class MipsABIInfo : public ABIInfo { 4672 bool IsO32; 4673 unsigned MinABIStackAlignInBytes, StackAlignInBytes; 4674 void CoerceToIntArgs(uint64_t TySize, 4675 SmallVectorImpl<llvm::Type *> &ArgList) const; 4676 llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const; 4677 llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const; 4678 llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const; 4679 public: 4680 MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) : 4681 ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8), 4682 StackAlignInBytes(IsO32 ? 8 : 16) {} 4683 4684 ABIArgInfo classifyReturnType(QualType RetTy) const; 4685 ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const; 4686 virtual void computeInfo(CGFunctionInfo &FI) const; 4687 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 4688 CodeGenFunction &CGF) const; 4689 }; 4690 4691 class MIPSTargetCodeGenInfo : public TargetCodeGenInfo { 4692 unsigned SizeOfUnwindException; 4693 public: 4694 MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32) 4695 : TargetCodeGenInfo(new MipsABIInfo(CGT, IsO32)), 4696 SizeOfUnwindException(IsO32 ? 24 : 32) {} 4697 4698 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const { 4699 return 29; 4700 } 4701 4702 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 4703 CodeGen::CodeGenModule &CGM) const { 4704 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D); 4705 if (!FD) return; 4706 llvm::Function *Fn = cast<llvm::Function>(GV); 4707 if (FD->hasAttr<Mips16Attr>()) { 4708 Fn->addFnAttr("mips16"); 4709 } 4710 else if (FD->hasAttr<NoMips16Attr>()) { 4711 Fn->addFnAttr("nomips16"); 4712 } 4713 } 4714 4715 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 4716 llvm::Value *Address) const; 4717 4718 unsigned getSizeOfUnwindException() const { 4719 return SizeOfUnwindException; 4720 } 4721 }; 4722 } 4723 4724 void MipsABIInfo::CoerceToIntArgs(uint64_t TySize, 4725 SmallVectorImpl<llvm::Type *> &ArgList) const { 4726 llvm::IntegerType *IntTy = 4727 llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8); 4728 4729 // Add (TySize / MinABIStackAlignInBytes) args of IntTy. 4730 for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N) 4731 ArgList.push_back(IntTy); 4732 4733 // If necessary, add one more integer type to ArgList. 4734 unsigned R = TySize % (MinABIStackAlignInBytes * 8); 4735 4736 if (R) 4737 ArgList.push_back(llvm::IntegerType::get(getVMContext(), R)); 4738 } 4739 4740 // In N32/64, an aligned double precision floating point field is passed in 4741 // a register. 4742 llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const { 4743 SmallVector<llvm::Type*, 8> ArgList, IntArgList; 4744 4745 if (IsO32) { 4746 CoerceToIntArgs(TySize, ArgList); 4747 return llvm::StructType::get(getVMContext(), ArgList); 4748 } 4749 4750 if (Ty->isComplexType()) 4751 return CGT.ConvertType(Ty); 4752 4753 const RecordType *RT = Ty->getAs<RecordType>(); 4754 4755 // Unions/vectors are passed in integer registers. 4756 if (!RT || !RT->isStructureOrClassType()) { 4757 CoerceToIntArgs(TySize, ArgList); 4758 return llvm::StructType::get(getVMContext(), ArgList); 4759 } 4760 4761 const RecordDecl *RD = RT->getDecl(); 4762 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD); 4763 assert(!(TySize % 8) && "Size of structure must be multiple of 8."); 4764 4765 uint64_t LastOffset = 0; 4766 unsigned idx = 0; 4767 llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64); 4768 4769 // Iterate over fields in the struct/class and check if there are any aligned 4770 // double fields. 4771 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 4772 i != e; ++i, ++idx) { 4773 const QualType Ty = i->getType(); 4774 const BuiltinType *BT = Ty->getAs<BuiltinType>(); 4775 4776 if (!BT || BT->getKind() != BuiltinType::Double) 4777 continue; 4778 4779 uint64_t Offset = Layout.getFieldOffset(idx); 4780 if (Offset % 64) // Ignore doubles that are not aligned. 4781 continue; 4782 4783 // Add ((Offset - LastOffset) / 64) args of type i64. 4784 for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j) 4785 ArgList.push_back(I64); 4786 4787 // Add double type. 4788 ArgList.push_back(llvm::Type::getDoubleTy(getVMContext())); 4789 LastOffset = Offset + 64; 4790 } 4791 4792 CoerceToIntArgs(TySize - LastOffset, IntArgList); 4793 ArgList.append(IntArgList.begin(), IntArgList.end()); 4794 4795 return llvm::StructType::get(getVMContext(), ArgList); 4796 } 4797 4798 llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset, 4799 uint64_t Offset) const { 4800 if (OrigOffset + MinABIStackAlignInBytes > Offset) 4801 return 0; 4802 4803 return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8); 4804 } 4805 4806 ABIArgInfo 4807 MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const { 4808 uint64_t OrigOffset = Offset; 4809 uint64_t TySize = getContext().getTypeSize(Ty); 4810 uint64_t Align = getContext().getTypeAlign(Ty) / 8; 4811 4812 Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes), 4813 (uint64_t)StackAlignInBytes); 4814 unsigned CurrOffset = llvm::RoundUpToAlignment(Offset, Align); 4815 Offset = CurrOffset + llvm::RoundUpToAlignment(TySize, Align * 8) / 8; 4816 4817 if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) { 4818 // Ignore empty aggregates. 4819 if (TySize == 0) 4820 return ABIArgInfo::getIgnore(); 4821 4822 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) { 4823 Offset = OrigOffset + MinABIStackAlignInBytes; 4824 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory); 4825 } 4826 4827 // If we have reached here, aggregates are passed directly by coercing to 4828 // another structure type. Padding is inserted if the offset of the 4829 // aggregate is unaligned. 4830 return ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0, 4831 getPaddingType(OrigOffset, CurrOffset)); 4832 } 4833 4834 // Treat an enum type as its underlying type. 4835 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 4836 Ty = EnumTy->getDecl()->getIntegerType(); 4837 4838 if (Ty->isPromotableIntegerType()) 4839 return ABIArgInfo::getExtend(); 4840 4841 return ABIArgInfo::getDirect( 4842 0, 0, IsO32 ? 0 : getPaddingType(OrigOffset, CurrOffset)); 4843 } 4844 4845 llvm::Type* 4846 MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const { 4847 const RecordType *RT = RetTy->getAs<RecordType>(); 4848 SmallVector<llvm::Type*, 8> RTList; 4849 4850 if (RT && RT->isStructureOrClassType()) { 4851 const RecordDecl *RD = RT->getDecl(); 4852 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD); 4853 unsigned FieldCnt = Layout.getFieldCount(); 4854 4855 // N32/64 returns struct/classes in floating point registers if the 4856 // following conditions are met: 4857 // 1. The size of the struct/class is no larger than 128-bit. 4858 // 2. The struct/class has one or two fields all of which are floating 4859 // point types. 4860 // 3. The offset of the first field is zero (this follows what gcc does). 4861 // 4862 // Any other composite results are returned in integer registers. 4863 // 4864 if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) { 4865 RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end(); 4866 for (; b != e; ++b) { 4867 const BuiltinType *BT = b->getType()->getAs<BuiltinType>(); 4868 4869 if (!BT || !BT->isFloatingPoint()) 4870 break; 4871 4872 RTList.push_back(CGT.ConvertType(b->getType())); 4873 } 4874 4875 if (b == e) 4876 return llvm::StructType::get(getVMContext(), RTList, 4877 RD->hasAttr<PackedAttr>()); 4878 4879 RTList.clear(); 4880 } 4881 } 4882 4883 CoerceToIntArgs(Size, RTList); 4884 return llvm::StructType::get(getVMContext(), RTList); 4885 } 4886 4887 ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const { 4888 uint64_t Size = getContext().getTypeSize(RetTy); 4889 4890 if (RetTy->isVoidType() || Size == 0) 4891 return ABIArgInfo::getIgnore(); 4892 4893 if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) { 4894 if (isRecordReturnIndirect(RetTy, getCXXABI())) 4895 return ABIArgInfo::getIndirect(0); 4896 4897 if (Size <= 128) { 4898 if (RetTy->isAnyComplexType()) 4899 return ABIArgInfo::getDirect(); 4900 4901 // O32 returns integer vectors in registers. 4902 if (IsO32 && RetTy->isVectorType() && !RetTy->hasFloatingRepresentation()) 4903 return ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size)); 4904 4905 if (!IsO32) 4906 return ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size)); 4907 } 4908 4909 return ABIArgInfo::getIndirect(0); 4910 } 4911 4912 // Treat an enum type as its underlying type. 4913 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 4914 RetTy = EnumTy->getDecl()->getIntegerType(); 4915 4916 return (RetTy->isPromotableIntegerType() ? 4917 ABIArgInfo::getExtend() : ABIArgInfo::getDirect()); 4918 } 4919 4920 void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const { 4921 ABIArgInfo &RetInfo = FI.getReturnInfo(); 4922 RetInfo = classifyReturnType(FI.getReturnType()); 4923 4924 // Check if a pointer to an aggregate is passed as a hidden argument. 4925 uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0; 4926 4927 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end(); 4928 it != ie; ++it) 4929 it->info = classifyArgumentType(it->type, Offset); 4930 } 4931 4932 llvm::Value* MipsABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 4933 CodeGenFunction &CGF) const { 4934 llvm::Type *BP = CGF.Int8PtrTy; 4935 llvm::Type *BPP = CGF.Int8PtrPtrTy; 4936 4937 CGBuilderTy &Builder = CGF.Builder; 4938 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap"); 4939 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur"); 4940 int64_t TypeAlign = getContext().getTypeAlign(Ty) / 8; 4941 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty)); 4942 llvm::Value *AddrTyped; 4943 unsigned PtrWidth = getTarget().getPointerWidth(0); 4944 llvm::IntegerType *IntTy = (PtrWidth == 32) ? CGF.Int32Ty : CGF.Int64Ty; 4945 4946 if (TypeAlign > MinABIStackAlignInBytes) { 4947 llvm::Value *AddrAsInt = CGF.Builder.CreatePtrToInt(Addr, IntTy); 4948 llvm::Value *Inc = llvm::ConstantInt::get(IntTy, TypeAlign - 1); 4949 llvm::Value *Mask = llvm::ConstantInt::get(IntTy, -TypeAlign); 4950 llvm::Value *Add = CGF.Builder.CreateAdd(AddrAsInt, Inc); 4951 llvm::Value *And = CGF.Builder.CreateAnd(Add, Mask); 4952 AddrTyped = CGF.Builder.CreateIntToPtr(And, PTy); 4953 } 4954 else 4955 AddrTyped = Builder.CreateBitCast(Addr, PTy); 4956 4957 llvm::Value *AlignedAddr = Builder.CreateBitCast(AddrTyped, BP); 4958 TypeAlign = std::max((unsigned)TypeAlign, MinABIStackAlignInBytes); 4959 uint64_t Offset = 4960 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, TypeAlign); 4961 llvm::Value *NextAddr = 4962 Builder.CreateGEP(AlignedAddr, llvm::ConstantInt::get(IntTy, Offset), 4963 "ap.next"); 4964 Builder.CreateStore(NextAddr, VAListAddrAsBPP); 4965 4966 return AddrTyped; 4967 } 4968 4969 bool 4970 MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 4971 llvm::Value *Address) const { 4972 // This information comes from gcc's implementation, which seems to 4973 // as canonical as it gets. 4974 4975 // Everything on MIPS is 4 bytes. Double-precision FP registers 4976 // are aliased to pairs of single-precision FP registers. 4977 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4); 4978 4979 // 0-31 are the general purpose registers, $0 - $31. 4980 // 32-63 are the floating-point registers, $f0 - $f31. 4981 // 64 and 65 are the multiply/divide registers, $hi and $lo. 4982 // 66 is the (notional, I think) register for signal-handler return. 4983 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65); 4984 4985 // 67-74 are the floating-point status registers, $fcc0 - $fcc7. 4986 // They are one bit wide and ignored here. 4987 4988 // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31. 4989 // (coprocessor 1 is the FP unit) 4990 // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31. 4991 // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31. 4992 // 176-181 are the DSP accumulator registers. 4993 AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181); 4994 return false; 4995 } 4996 4997 //===----------------------------------------------------------------------===// 4998 // TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults. 4999 // Currently subclassed only to implement custom OpenCL C function attribute 5000 // handling. 5001 //===----------------------------------------------------------------------===// 5002 5003 namespace { 5004 5005 class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo { 5006 public: 5007 TCETargetCodeGenInfo(CodeGenTypes &CGT) 5008 : DefaultTargetCodeGenInfo(CGT) {} 5009 5010 virtual void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 5011 CodeGen::CodeGenModule &M) const; 5012 }; 5013 5014 void TCETargetCodeGenInfo::SetTargetAttributes(const Decl *D, 5015 llvm::GlobalValue *GV, 5016 CodeGen::CodeGenModule &M) const { 5017 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D); 5018 if (!FD) return; 5019 5020 llvm::Function *F = cast<llvm::Function>(GV); 5021 5022 if (M.getLangOpts().OpenCL) { 5023 if (FD->hasAttr<OpenCLKernelAttr>()) { 5024 // OpenCL C Kernel functions are not subject to inlining 5025 F->addFnAttr(llvm::Attribute::NoInline); 5026 const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>(); 5027 if (Attr) { 5028 // Convert the reqd_work_group_size() attributes to metadata. 5029 llvm::LLVMContext &Context = F->getContext(); 5030 llvm::NamedMDNode *OpenCLMetadata = 5031 M.getModule().getOrInsertNamedMetadata("opencl.kernel_wg_size_info"); 5032 5033 SmallVector<llvm::Value*, 5> Operands; 5034 Operands.push_back(F); 5035 5036 Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty, 5037 llvm::APInt(32, Attr->getXDim()))); 5038 Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty, 5039 llvm::APInt(32, Attr->getYDim()))); 5040 Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty, 5041 llvm::APInt(32, Attr->getZDim()))); 5042 5043 // Add a boolean constant operand for "required" (true) or "hint" (false) 5044 // for implementing the work_group_size_hint attr later. Currently 5045 // always true as the hint is not yet implemented. 5046 Operands.push_back(llvm::ConstantInt::getTrue(Context)); 5047 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands)); 5048 } 5049 } 5050 } 5051 } 5052 5053 } 5054 5055 //===----------------------------------------------------------------------===// 5056 // Hexagon ABI Implementation 5057 //===----------------------------------------------------------------------===// 5058 5059 namespace { 5060 5061 class HexagonABIInfo : public ABIInfo { 5062 5063 5064 public: 5065 HexagonABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {} 5066 5067 private: 5068 5069 ABIArgInfo classifyReturnType(QualType RetTy) const; 5070 ABIArgInfo classifyArgumentType(QualType RetTy) const; 5071 5072 virtual void computeInfo(CGFunctionInfo &FI) const; 5073 5074 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 5075 CodeGenFunction &CGF) const; 5076 }; 5077 5078 class HexagonTargetCodeGenInfo : public TargetCodeGenInfo { 5079 public: 5080 HexagonTargetCodeGenInfo(CodeGenTypes &CGT) 5081 :TargetCodeGenInfo(new HexagonABIInfo(CGT)) {} 5082 5083 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const { 5084 return 29; 5085 } 5086 }; 5087 5088 } 5089 5090 void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const { 5091 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 5092 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end(); 5093 it != ie; ++it) 5094 it->info = classifyArgumentType(it->type); 5095 } 5096 5097 ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty) const { 5098 if (!isAggregateTypeForABI(Ty)) { 5099 // Treat an enum type as its underlying type. 5100 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 5101 Ty = EnumTy->getDecl()->getIntegerType(); 5102 5103 return (Ty->isPromotableIntegerType() ? 5104 ABIArgInfo::getExtend() : ABIArgInfo::getDirect()); 5105 } 5106 5107 // Ignore empty records. 5108 if (isEmptyRecord(getContext(), Ty, true)) 5109 return ABIArgInfo::getIgnore(); 5110 5111 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 5112 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory); 5113 5114 uint64_t Size = getContext().getTypeSize(Ty); 5115 if (Size > 64) 5116 return ABIArgInfo::getIndirect(0, /*ByVal=*/true); 5117 // Pass in the smallest viable integer type. 5118 else if (Size > 32) 5119 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext())); 5120 else if (Size > 16) 5121 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext())); 5122 else if (Size > 8) 5123 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext())); 5124 else 5125 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext())); 5126 } 5127 5128 ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const { 5129 if (RetTy->isVoidType()) 5130 return ABIArgInfo::getIgnore(); 5131 5132 // Large vector types should be returned via memory. 5133 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 64) 5134 return ABIArgInfo::getIndirect(0); 5135 5136 if (!isAggregateTypeForABI(RetTy)) { 5137 // Treat an enum type as its underlying type. 5138 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 5139 RetTy = EnumTy->getDecl()->getIntegerType(); 5140 5141 return (RetTy->isPromotableIntegerType() ? 5142 ABIArgInfo::getExtend() : ABIArgInfo::getDirect()); 5143 } 5144 5145 // Structures with either a non-trivial destructor or a non-trivial 5146 // copy constructor are always indirect. 5147 if (isRecordReturnIndirect(RetTy, getCXXABI())) 5148 return ABIArgInfo::getIndirect(0, /*ByVal=*/false); 5149 5150 if (isEmptyRecord(getContext(), RetTy, true)) 5151 return ABIArgInfo::getIgnore(); 5152 5153 // Aggregates <= 8 bytes are returned in r0; other aggregates 5154 // are returned indirectly. 5155 uint64_t Size = getContext().getTypeSize(RetTy); 5156 if (Size <= 64) { 5157 // Return in the smallest viable integer type. 5158 if (Size <= 8) 5159 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext())); 5160 if (Size <= 16) 5161 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext())); 5162 if (Size <= 32) 5163 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext())); 5164 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext())); 5165 } 5166 5167 return ABIArgInfo::getIndirect(0, /*ByVal=*/true); 5168 } 5169 5170 llvm::Value *HexagonABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 5171 CodeGenFunction &CGF) const { 5172 // FIXME: Need to handle alignment 5173 llvm::Type *BPP = CGF.Int8PtrPtrTy; 5174 5175 CGBuilderTy &Builder = CGF.Builder; 5176 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, 5177 "ap"); 5178 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur"); 5179 llvm::Type *PTy = 5180 llvm::PointerType::getUnqual(CGF.ConvertType(Ty)); 5181 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy); 5182 5183 uint64_t Offset = 5184 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 4); 5185 llvm::Value *NextAddr = 5186 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset), 5187 "ap.next"); 5188 Builder.CreateStore(NextAddr, VAListAddrAsBPP); 5189 5190 return AddrTyped; 5191 } 5192 5193 5194 //===----------------------------------------------------------------------===// 5195 // SPARC v9 ABI Implementation. 5196 // Based on the SPARC Compliance Definition version 2.4.1. 5197 // 5198 // Function arguments a mapped to a nominal "parameter array" and promoted to 5199 // registers depending on their type. Each argument occupies 8 or 16 bytes in 5200 // the array, structs larger than 16 bytes are passed indirectly. 5201 // 5202 // One case requires special care: 5203 // 5204 // struct mixed { 5205 // int i; 5206 // float f; 5207 // }; 5208 // 5209 // When a struct mixed is passed by value, it only occupies 8 bytes in the 5210 // parameter array, but the int is passed in an integer register, and the float 5211 // is passed in a floating point register. This is represented as two arguments 5212 // with the LLVM IR inreg attribute: 5213 // 5214 // declare void f(i32 inreg %i, float inreg %f) 5215 // 5216 // The code generator will only allocate 4 bytes from the parameter array for 5217 // the inreg arguments. All other arguments are allocated a multiple of 8 5218 // bytes. 5219 // 5220 namespace { 5221 class SparcV9ABIInfo : public ABIInfo { 5222 public: 5223 SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {} 5224 5225 private: 5226 ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const; 5227 virtual void computeInfo(CGFunctionInfo &FI) const; 5228 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 5229 CodeGenFunction &CGF) const; 5230 5231 // Coercion type builder for structs passed in registers. The coercion type 5232 // serves two purposes: 5233 // 5234 // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned' 5235 // in registers. 5236 // 2. Expose aligned floating point elements as first-level elements, so the 5237 // code generator knows to pass them in floating point registers. 5238 // 5239 // We also compute the InReg flag which indicates that the struct contains 5240 // aligned 32-bit floats. 5241 // 5242 struct CoerceBuilder { 5243 llvm::LLVMContext &Context; 5244 const llvm::DataLayout &DL; 5245 SmallVector<llvm::Type*, 8> Elems; 5246 uint64_t Size; 5247 bool InReg; 5248 5249 CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl) 5250 : Context(c), DL(dl), Size(0), InReg(false) {} 5251 5252 // Pad Elems with integers until Size is ToSize. 5253 void pad(uint64_t ToSize) { 5254 assert(ToSize >= Size && "Cannot remove elements"); 5255 if (ToSize == Size) 5256 return; 5257 5258 // Finish the current 64-bit word. 5259 uint64_t Aligned = llvm::RoundUpToAlignment(Size, 64); 5260 if (Aligned > Size && Aligned <= ToSize) { 5261 Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size)); 5262 Size = Aligned; 5263 } 5264 5265 // Add whole 64-bit words. 5266 while (Size + 64 <= ToSize) { 5267 Elems.push_back(llvm::Type::getInt64Ty(Context)); 5268 Size += 64; 5269 } 5270 5271 // Final in-word padding. 5272 if (Size < ToSize) { 5273 Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size)); 5274 Size = ToSize; 5275 } 5276 } 5277 5278 // Add a floating point element at Offset. 5279 void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) { 5280 // Unaligned floats are treated as integers. 5281 if (Offset % Bits) 5282 return; 5283 // The InReg flag is only required if there are any floats < 64 bits. 5284 if (Bits < 64) 5285 InReg = true; 5286 pad(Offset); 5287 Elems.push_back(Ty); 5288 Size = Offset + Bits; 5289 } 5290 5291 // Add a struct type to the coercion type, starting at Offset (in bits). 5292 void addStruct(uint64_t Offset, llvm::StructType *StrTy) { 5293 const llvm::StructLayout *Layout = DL.getStructLayout(StrTy); 5294 for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) { 5295 llvm::Type *ElemTy = StrTy->getElementType(i); 5296 uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i); 5297 switch (ElemTy->getTypeID()) { 5298 case llvm::Type::StructTyID: 5299 addStruct(ElemOffset, cast<llvm::StructType>(ElemTy)); 5300 break; 5301 case llvm::Type::FloatTyID: 5302 addFloat(ElemOffset, ElemTy, 32); 5303 break; 5304 case llvm::Type::DoubleTyID: 5305 addFloat(ElemOffset, ElemTy, 64); 5306 break; 5307 case llvm::Type::FP128TyID: 5308 addFloat(ElemOffset, ElemTy, 128); 5309 break; 5310 case llvm::Type::PointerTyID: 5311 if (ElemOffset % 64 == 0) { 5312 pad(ElemOffset); 5313 Elems.push_back(ElemTy); 5314 Size += 64; 5315 } 5316 break; 5317 default: 5318 break; 5319 } 5320 } 5321 } 5322 5323 // Check if Ty is a usable substitute for the coercion type. 5324 bool isUsableType(llvm::StructType *Ty) const { 5325 if (Ty->getNumElements() != Elems.size()) 5326 return false; 5327 for (unsigned i = 0, e = Elems.size(); i != e; ++i) 5328 if (Elems[i] != Ty->getElementType(i)) 5329 return false; 5330 return true; 5331 } 5332 5333 // Get the coercion type as a literal struct type. 5334 llvm::Type *getType() const { 5335 if (Elems.size() == 1) 5336 return Elems.front(); 5337 else 5338 return llvm::StructType::get(Context, Elems); 5339 } 5340 }; 5341 }; 5342 } // end anonymous namespace 5343 5344 ABIArgInfo 5345 SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const { 5346 if (Ty->isVoidType()) 5347 return ABIArgInfo::getIgnore(); 5348 5349 uint64_t Size = getContext().getTypeSize(Ty); 5350 5351 // Anything too big to fit in registers is passed with an explicit indirect 5352 // pointer / sret pointer. 5353 if (Size > SizeLimit) 5354 return ABIArgInfo::getIndirect(0, /*ByVal=*/false); 5355 5356 // Treat an enum type as its underlying type. 5357 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 5358 Ty = EnumTy->getDecl()->getIntegerType(); 5359 5360 // Integer types smaller than a register are extended. 5361 if (Size < 64 && Ty->isIntegerType()) 5362 return ABIArgInfo::getExtend(); 5363 5364 // Other non-aggregates go in registers. 5365 if (!isAggregateTypeForABI(Ty)) 5366 return ABIArgInfo::getDirect(); 5367 5368 // If a C++ object has either a non-trivial copy constructor or a non-trivial 5369 // destructor, it is passed with an explicit indirect pointer / sret pointer. 5370 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 5371 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory); 5372 5373 // This is a small aggregate type that should be passed in registers. 5374 // Build a coercion type from the LLVM struct type. 5375 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty)); 5376 if (!StrTy) 5377 return ABIArgInfo::getDirect(); 5378 5379 CoerceBuilder CB(getVMContext(), getDataLayout()); 5380 CB.addStruct(0, StrTy); 5381 CB.pad(llvm::RoundUpToAlignment(CB.DL.getTypeSizeInBits(StrTy), 64)); 5382 5383 // Try to use the original type for coercion. 5384 llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType(); 5385 5386 if (CB.InReg) 5387 return ABIArgInfo::getDirectInReg(CoerceTy); 5388 else 5389 return ABIArgInfo::getDirect(CoerceTy); 5390 } 5391 5392 llvm::Value *SparcV9ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 5393 CodeGenFunction &CGF) const { 5394 ABIArgInfo AI = classifyType(Ty, 16 * 8); 5395 llvm::Type *ArgTy = CGT.ConvertType(Ty); 5396 if (AI.canHaveCoerceToType() && !AI.getCoerceToType()) 5397 AI.setCoerceToType(ArgTy); 5398 5399 llvm::Type *BPP = CGF.Int8PtrPtrTy; 5400 CGBuilderTy &Builder = CGF.Builder; 5401 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap"); 5402 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur"); 5403 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy); 5404 llvm::Value *ArgAddr; 5405 unsigned Stride; 5406 5407 switch (AI.getKind()) { 5408 case ABIArgInfo::Expand: 5409 llvm_unreachable("Unsupported ABI kind for va_arg"); 5410 5411 case ABIArgInfo::Extend: 5412 Stride = 8; 5413 ArgAddr = Builder 5414 .CreateConstGEP1_32(Addr, 8 - getDataLayout().getTypeAllocSize(ArgTy), 5415 "extend"); 5416 break; 5417 5418 case ABIArgInfo::Direct: 5419 Stride = getDataLayout().getTypeAllocSize(AI.getCoerceToType()); 5420 ArgAddr = Addr; 5421 break; 5422 5423 case ABIArgInfo::Indirect: 5424 Stride = 8; 5425 ArgAddr = Builder.CreateBitCast(Addr, 5426 llvm::PointerType::getUnqual(ArgPtrTy), 5427 "indirect"); 5428 ArgAddr = Builder.CreateLoad(ArgAddr, "indirect.arg"); 5429 break; 5430 5431 case ABIArgInfo::Ignore: 5432 return llvm::UndefValue::get(ArgPtrTy); 5433 } 5434 5435 // Update VAList. 5436 Addr = Builder.CreateConstGEP1_32(Addr, Stride, "ap.next"); 5437 Builder.CreateStore(Addr, VAListAddrAsBPP); 5438 5439 return Builder.CreatePointerCast(ArgAddr, ArgPtrTy, "arg.addr"); 5440 } 5441 5442 void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const { 5443 FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8); 5444 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end(); 5445 it != ie; ++it) 5446 it->info = classifyType(it->type, 16 * 8); 5447 } 5448 5449 namespace { 5450 class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo { 5451 public: 5452 SparcV9TargetCodeGenInfo(CodeGenTypes &CGT) 5453 : TargetCodeGenInfo(new SparcV9ABIInfo(CGT)) {} 5454 }; 5455 } // end anonymous namespace 5456 5457 5458 //===----------------------------------------------------------------------===// 5459 // Xcore ABI Implementation 5460 //===----------------------------------------------------------------------===// 5461 namespace { 5462 class XCoreABIInfo : public DefaultABIInfo { 5463 public: 5464 XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {} 5465 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 5466 CodeGenFunction &CGF) const; 5467 }; 5468 5469 class XcoreTargetCodeGenInfo : public TargetCodeGenInfo { 5470 public: 5471 XcoreTargetCodeGenInfo(CodeGenTypes &CGT) 5472 :TargetCodeGenInfo(new XCoreABIInfo(CGT)) {} 5473 }; 5474 } // End anonymous namespace. 5475 5476 llvm::Value *XCoreABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 5477 CodeGenFunction &CGF) const { 5478 CGBuilderTy &Builder = CGF.Builder; 5479 5480 // Get the VAList. 5481 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, 5482 CGF.Int8PtrPtrTy); 5483 llvm::Value *AP = Builder.CreateLoad(VAListAddrAsBPP); 5484 5485 // Handle the argument. 5486 ABIArgInfo AI = classifyArgumentType(Ty); 5487 llvm::Type *ArgTy = CGT.ConvertType(Ty); 5488 if (AI.canHaveCoerceToType() && !AI.getCoerceToType()) 5489 AI.setCoerceToType(ArgTy); 5490 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy); 5491 llvm::Value *Val; 5492 uint64_t ArgSize = 0; 5493 switch (AI.getKind()) { 5494 case ABIArgInfo::Expand: 5495 llvm_unreachable("Unsupported ABI kind for va_arg"); 5496 case ABIArgInfo::Ignore: 5497 Val = llvm::UndefValue::get(ArgPtrTy); 5498 ArgSize = 0; 5499 break; 5500 case ABIArgInfo::Extend: 5501 case ABIArgInfo::Direct: 5502 Val = Builder.CreatePointerCast(AP, ArgPtrTy); 5503 ArgSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType()); 5504 if (ArgSize < 4) 5505 ArgSize = 4; 5506 break; 5507 case ABIArgInfo::Indirect: 5508 llvm::Value *ArgAddr; 5509 ArgAddr = Builder.CreateBitCast(AP, llvm::PointerType::getUnqual(ArgPtrTy)); 5510 ArgAddr = Builder.CreateLoad(ArgAddr); 5511 Val = Builder.CreatePointerCast(ArgAddr, ArgPtrTy); 5512 ArgSize = 4; 5513 break; 5514 } 5515 5516 // Increment the VAList. 5517 if (ArgSize) { 5518 llvm::Value *APN = Builder.CreateConstGEP1_32(AP, ArgSize); 5519 Builder.CreateStore(APN, VAListAddrAsBPP); 5520 } 5521 return Val; 5522 } 5523 5524 //===----------------------------------------------------------------------===// 5525 // Driver code 5526 //===----------------------------------------------------------------------===// 5527 5528 const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() { 5529 if (TheTargetCodeGenInfo) 5530 return *TheTargetCodeGenInfo; 5531 5532 const llvm::Triple &Triple = getTarget().getTriple(); 5533 switch (Triple.getArch()) { 5534 default: 5535 return *(TheTargetCodeGenInfo = new DefaultTargetCodeGenInfo(Types)); 5536 5537 case llvm::Triple::le32: 5538 return *(TheTargetCodeGenInfo = new PNaClTargetCodeGenInfo(Types)); 5539 case llvm::Triple::mips: 5540 case llvm::Triple::mipsel: 5541 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, true)); 5542 5543 case llvm::Triple::mips64: 5544 case llvm::Triple::mips64el: 5545 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, false)); 5546 5547 case llvm::Triple::aarch64: 5548 return *(TheTargetCodeGenInfo = new AArch64TargetCodeGenInfo(Types)); 5549 5550 case llvm::Triple::arm: 5551 case llvm::Triple::thumb: 5552 { 5553 ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS; 5554 if (strcmp(getTarget().getABI(), "apcs-gnu") == 0) 5555 Kind = ARMABIInfo::APCS; 5556 else if (CodeGenOpts.FloatABI == "hard" || 5557 (CodeGenOpts.FloatABI != "soft" && 5558 Triple.getEnvironment() == llvm::Triple::GNUEABIHF)) 5559 Kind = ARMABIInfo::AAPCS_VFP; 5560 5561 switch (Triple.getOS()) { 5562 case llvm::Triple::NaCl: 5563 return *(TheTargetCodeGenInfo = 5564 new NaClARMTargetCodeGenInfo(Types, Kind)); 5565 default: 5566 return *(TheTargetCodeGenInfo = 5567 new ARMTargetCodeGenInfo(Types, Kind)); 5568 } 5569 } 5570 5571 case llvm::Triple::ppc: 5572 return *(TheTargetCodeGenInfo = new PPC32TargetCodeGenInfo(Types)); 5573 case llvm::Triple::ppc64: 5574 if (Triple.isOSBinFormatELF()) 5575 return *(TheTargetCodeGenInfo = new PPC64_SVR4_TargetCodeGenInfo(Types)); 5576 else 5577 return *(TheTargetCodeGenInfo = new PPC64TargetCodeGenInfo(Types)); 5578 case llvm::Triple::ppc64le: 5579 assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!"); 5580 return *(TheTargetCodeGenInfo = new PPC64_SVR4_TargetCodeGenInfo(Types)); 5581 5582 case llvm::Triple::nvptx: 5583 case llvm::Triple::nvptx64: 5584 return *(TheTargetCodeGenInfo = new NVPTXTargetCodeGenInfo(Types)); 5585 5586 case llvm::Triple::msp430: 5587 return *(TheTargetCodeGenInfo = new MSP430TargetCodeGenInfo(Types)); 5588 5589 case llvm::Triple::systemz: 5590 return *(TheTargetCodeGenInfo = new SystemZTargetCodeGenInfo(Types)); 5591 5592 case llvm::Triple::tce: 5593 return *(TheTargetCodeGenInfo = new TCETargetCodeGenInfo(Types)); 5594 5595 case llvm::Triple::x86: { 5596 bool IsDarwinVectorABI = Triple.isOSDarwin(); 5597 bool IsSmallStructInRegABI = 5598 X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts); 5599 bool IsWin32FloatStructABI = (Triple.getOS() == llvm::Triple::Win32); 5600 5601 if (Triple.getOS() == llvm::Triple::Win32) { 5602 return *(TheTargetCodeGenInfo = 5603 new WinX86_32TargetCodeGenInfo(Types, 5604 IsDarwinVectorABI, IsSmallStructInRegABI, 5605 IsWin32FloatStructABI, 5606 CodeGenOpts.NumRegisterParameters)); 5607 } else { 5608 return *(TheTargetCodeGenInfo = 5609 new X86_32TargetCodeGenInfo(Types, 5610 IsDarwinVectorABI, IsSmallStructInRegABI, 5611 IsWin32FloatStructABI, 5612 CodeGenOpts.NumRegisterParameters)); 5613 } 5614 } 5615 5616 case llvm::Triple::x86_64: { 5617 bool HasAVX = strcmp(getTarget().getABI(), "avx") == 0; 5618 5619 switch (Triple.getOS()) { 5620 case llvm::Triple::Win32: 5621 case llvm::Triple::MinGW32: 5622 case llvm::Triple::Cygwin: 5623 return *(TheTargetCodeGenInfo = new WinX86_64TargetCodeGenInfo(Types)); 5624 case llvm::Triple::NaCl: 5625 return *(TheTargetCodeGenInfo = new NaClX86_64TargetCodeGenInfo(Types, 5626 HasAVX)); 5627 default: 5628 return *(TheTargetCodeGenInfo = new X86_64TargetCodeGenInfo(Types, 5629 HasAVX)); 5630 } 5631 } 5632 case llvm::Triple::hexagon: 5633 return *(TheTargetCodeGenInfo = new HexagonTargetCodeGenInfo(Types)); 5634 case llvm::Triple::sparcv9: 5635 return *(TheTargetCodeGenInfo = new SparcV9TargetCodeGenInfo(Types)); 5636 case llvm::Triple::xcore: 5637 return *(TheTargetCodeGenInfo = new XcoreTargetCodeGenInfo(Types)); 5638 5639 } 5640 } 5641