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, bool isVariadic) const; 3103 ABIArgInfo classifyArgumentType(QualType RetTy, int *VFPRegs, 3104 unsigned &AllocatedVFP, 3105 bool &IsHA, bool isVariadic) 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(), FI.isVariadic()); 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, FI.isVariadic()); 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 // Note that IsHA will only be set when using the AAPCS-VFP calling convention, 3214 // and the callee is not variadic. 3215 if (IsHA && AllocatedVFP > NumVFPs && PreAllocation < NumVFPs) { 3216 llvm::Type *PaddingTy = llvm::ArrayType::get( 3217 llvm::Type::getFloatTy(getVMContext()), NumVFPs - PreAllocation); 3218 it->info = ABIArgInfo::getExpandWithPadding(false, PaddingTy); 3219 } 3220 } 3221 3222 // Always honor user-specified calling convention. 3223 if (FI.getCallingConvention() != llvm::CallingConv::C) 3224 return; 3225 3226 llvm::CallingConv::ID cc = getRuntimeCC(); 3227 if (cc != llvm::CallingConv::C) 3228 FI.setEffectiveCallingConvention(cc); 3229 } 3230 3231 /// Return the default calling convention that LLVM will use. 3232 llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const { 3233 // The default calling convention that LLVM will infer. 3234 if (isEABIHF()) 3235 return llvm::CallingConv::ARM_AAPCS_VFP; 3236 else if (isEABI()) 3237 return llvm::CallingConv::ARM_AAPCS; 3238 else 3239 return llvm::CallingConv::ARM_APCS; 3240 } 3241 3242 /// Return the calling convention that our ABI would like us to use 3243 /// as the C calling convention. 3244 llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const { 3245 switch (getABIKind()) { 3246 case APCS: return llvm::CallingConv::ARM_APCS; 3247 case AAPCS: return llvm::CallingConv::ARM_AAPCS; 3248 case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP; 3249 } 3250 llvm_unreachable("bad ABI kind"); 3251 } 3252 3253 void ARMABIInfo::setRuntimeCC() { 3254 assert(getRuntimeCC() == llvm::CallingConv::C); 3255 3256 // Don't muddy up the IR with a ton of explicit annotations if 3257 // they'd just match what LLVM will infer from the triple. 3258 llvm::CallingConv::ID abiCC = getABIDefaultCC(); 3259 if (abiCC != getLLVMDefaultCC()) 3260 RuntimeCC = abiCC; 3261 } 3262 3263 /// isHomogeneousAggregate - Return true if a type is an AAPCS-VFP homogeneous 3264 /// aggregate. If HAMembers is non-null, the number of base elements 3265 /// contained in the type is returned through it; this is used for the 3266 /// recursive calls that check aggregate component types. 3267 static bool isHomogeneousAggregate(QualType Ty, const Type *&Base, 3268 ASTContext &Context, 3269 uint64_t *HAMembers = 0) { 3270 uint64_t Members = 0; 3271 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) { 3272 if (!isHomogeneousAggregate(AT->getElementType(), Base, Context, &Members)) 3273 return false; 3274 Members *= AT->getSize().getZExtValue(); 3275 } else if (const RecordType *RT = Ty->getAs<RecordType>()) { 3276 const RecordDecl *RD = RT->getDecl(); 3277 if (RD->hasFlexibleArrayMember()) 3278 return false; 3279 3280 Members = 0; 3281 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 3282 i != e; ++i) { 3283 const FieldDecl *FD = *i; 3284 uint64_t FldMembers; 3285 if (!isHomogeneousAggregate(FD->getType(), Base, Context, &FldMembers)) 3286 return false; 3287 3288 Members = (RD->isUnion() ? 3289 std::max(Members, FldMembers) : Members + FldMembers); 3290 } 3291 } else { 3292 Members = 1; 3293 if (const ComplexType *CT = Ty->getAs<ComplexType>()) { 3294 Members = 2; 3295 Ty = CT->getElementType(); 3296 } 3297 3298 // Homogeneous aggregates for AAPCS-VFP must have base types of float, 3299 // double, or 64-bit or 128-bit vectors. 3300 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) { 3301 if (BT->getKind() != BuiltinType::Float && 3302 BT->getKind() != BuiltinType::Double && 3303 BT->getKind() != BuiltinType::LongDouble) 3304 return false; 3305 } else if (const VectorType *VT = Ty->getAs<VectorType>()) { 3306 unsigned VecSize = Context.getTypeSize(VT); 3307 if (VecSize != 64 && VecSize != 128) 3308 return false; 3309 } else { 3310 return false; 3311 } 3312 3313 // The base type must be the same for all members. Vector types of the 3314 // same total size are treated as being equivalent here. 3315 const Type *TyPtr = Ty.getTypePtr(); 3316 if (!Base) 3317 Base = TyPtr; 3318 if (Base != TyPtr && 3319 (!Base->isVectorType() || !TyPtr->isVectorType() || 3320 Context.getTypeSize(Base) != Context.getTypeSize(TyPtr))) 3321 return false; 3322 } 3323 3324 // Homogeneous Aggregates can have at most 4 members of the base type. 3325 if (HAMembers) 3326 *HAMembers = Members; 3327 3328 return (Members > 0 && Members <= 4); 3329 } 3330 3331 /// markAllocatedVFPs - update VFPRegs according to the alignment and 3332 /// number of VFP registers (unit is S register) requested. 3333 static void markAllocatedVFPs(int *VFPRegs, unsigned &AllocatedVFP, 3334 unsigned Alignment, 3335 unsigned NumRequired) { 3336 // Early Exit. 3337 if (AllocatedVFP >= 16) 3338 return; 3339 // C.1.vfp If the argument is a VFP CPRC and there are sufficient consecutive 3340 // VFP registers of the appropriate type unallocated then the argument is 3341 // allocated to the lowest-numbered sequence of such registers. 3342 for (unsigned I = 0; I < 16; I += Alignment) { 3343 bool FoundSlot = true; 3344 for (unsigned J = I, JEnd = I + NumRequired; J < JEnd; J++) 3345 if (J >= 16 || VFPRegs[J]) { 3346 FoundSlot = false; 3347 break; 3348 } 3349 if (FoundSlot) { 3350 for (unsigned J = I, JEnd = I + NumRequired; J < JEnd; J++) 3351 VFPRegs[J] = 1; 3352 AllocatedVFP += NumRequired; 3353 return; 3354 } 3355 } 3356 // C.2.vfp If the argument is a VFP CPRC then any VFP registers that are 3357 // unallocated are marked as unavailable. 3358 for (unsigned I = 0; I < 16; I++) 3359 VFPRegs[I] = 1; 3360 AllocatedVFP = 17; // We do not have enough VFP registers. 3361 } 3362 3363 ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty, int *VFPRegs, 3364 unsigned &AllocatedVFP, 3365 bool &IsHA, bool isVariadic) const { 3366 // We update number of allocated VFPs according to 3367 // 6.1.2.1 The following argument types are VFP CPRCs: 3368 // A single-precision floating-point type (including promoted 3369 // half-precision types); A double-precision floating-point type; 3370 // A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate 3371 // with a Base Type of a single- or double-precision floating-point type, 3372 // 64-bit containerized vectors or 128-bit containerized vectors with one 3373 // to four Elements. 3374 3375 // Handle illegal vector types here. 3376 if (isIllegalVectorType(Ty)) { 3377 uint64_t Size = getContext().getTypeSize(Ty); 3378 if (Size <= 32) { 3379 llvm::Type *ResType = 3380 llvm::Type::getInt32Ty(getVMContext()); 3381 return ABIArgInfo::getDirect(ResType); 3382 } 3383 if (Size == 64) { 3384 llvm::Type *ResType = llvm::VectorType::get( 3385 llvm::Type::getInt32Ty(getVMContext()), 2); 3386 markAllocatedVFPs(VFPRegs, AllocatedVFP, 2, 2); 3387 return ABIArgInfo::getDirect(ResType); 3388 } 3389 if (Size == 128) { 3390 llvm::Type *ResType = llvm::VectorType::get( 3391 llvm::Type::getInt32Ty(getVMContext()), 4); 3392 markAllocatedVFPs(VFPRegs, AllocatedVFP, 4, 4); 3393 return ABIArgInfo::getDirect(ResType); 3394 } 3395 return ABIArgInfo::getIndirect(0, /*ByVal=*/false); 3396 } 3397 // Update VFPRegs for legal vector types. 3398 if (const VectorType *VT = Ty->getAs<VectorType>()) { 3399 uint64_t Size = getContext().getTypeSize(VT); 3400 // Size of a legal vector should be power of 2 and above 64. 3401 markAllocatedVFPs(VFPRegs, AllocatedVFP, Size >= 128 ? 4 : 2, Size / 32); 3402 } 3403 // Update VFPRegs for floating point types. 3404 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) { 3405 if (BT->getKind() == BuiltinType::Half || 3406 BT->getKind() == BuiltinType::Float) 3407 markAllocatedVFPs(VFPRegs, AllocatedVFP, 1, 1); 3408 if (BT->getKind() == BuiltinType::Double || 3409 BT->getKind() == BuiltinType::LongDouble) 3410 markAllocatedVFPs(VFPRegs, AllocatedVFP, 2, 2); 3411 } 3412 3413 if (!isAggregateTypeForABI(Ty)) { 3414 // Treat an enum type as its underlying type. 3415 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 3416 Ty = EnumTy->getDecl()->getIntegerType(); 3417 3418 return (Ty->isPromotableIntegerType() ? 3419 ABIArgInfo::getExtend() : ABIArgInfo::getDirect()); 3420 } 3421 3422 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 3423 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory); 3424 3425 // Ignore empty records. 3426 if (isEmptyRecord(getContext(), Ty, true)) 3427 return ABIArgInfo::getIgnore(); 3428 3429 if (getABIKind() == ARMABIInfo::AAPCS_VFP && !isVariadic) { 3430 // Homogeneous Aggregates need to be expanded when we can fit the aggregate 3431 // into VFP registers. 3432 const Type *Base = 0; 3433 uint64_t Members = 0; 3434 if (isHomogeneousAggregate(Ty, Base, getContext(), &Members)) { 3435 assert(Base && "Base class should be set for homogeneous aggregate"); 3436 // Base can be a floating-point or a vector. 3437 if (Base->isVectorType()) { 3438 // ElementSize is in number of floats. 3439 unsigned ElementSize = getContext().getTypeSize(Base) == 64 ? 2 : 4; 3440 markAllocatedVFPs(VFPRegs, AllocatedVFP, ElementSize, 3441 Members * ElementSize); 3442 } else if (Base->isSpecificBuiltinType(BuiltinType::Float)) 3443 markAllocatedVFPs(VFPRegs, AllocatedVFP, 1, Members); 3444 else { 3445 assert(Base->isSpecificBuiltinType(BuiltinType::Double) || 3446 Base->isSpecificBuiltinType(BuiltinType::LongDouble)); 3447 markAllocatedVFPs(VFPRegs, AllocatedVFP, 2, Members * 2); 3448 } 3449 IsHA = true; 3450 return ABIArgInfo::getExpand(); 3451 } 3452 } 3453 3454 // Support byval for ARM. 3455 // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at 3456 // most 8-byte. We realign the indirect argument if type alignment is bigger 3457 // than ABI alignment. 3458 uint64_t ABIAlign = 4; 3459 uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8; 3460 if (getABIKind() == ARMABIInfo::AAPCS_VFP || 3461 getABIKind() == ARMABIInfo::AAPCS) 3462 ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8); 3463 if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) { 3464 return ABIArgInfo::getIndirect(0, /*ByVal=*/true, 3465 /*Realign=*/TyAlign > ABIAlign); 3466 } 3467 3468 // Otherwise, pass by coercing to a structure of the appropriate size. 3469 llvm::Type* ElemTy; 3470 unsigned SizeRegs; 3471 // FIXME: Try to match the types of the arguments more accurately where 3472 // we can. 3473 if (getContext().getTypeAlign(Ty) <= 32) { 3474 ElemTy = llvm::Type::getInt32Ty(getVMContext()); 3475 SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32; 3476 } else { 3477 ElemTy = llvm::Type::getInt64Ty(getVMContext()); 3478 SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64; 3479 } 3480 3481 llvm::Type *STy = 3482 llvm::StructType::get(llvm::ArrayType::get(ElemTy, SizeRegs), NULL); 3483 return ABIArgInfo::getDirect(STy); 3484 } 3485 3486 static bool isIntegerLikeType(QualType Ty, ASTContext &Context, 3487 llvm::LLVMContext &VMContext) { 3488 // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure 3489 // is called integer-like if its size is less than or equal to one word, and 3490 // the offset of each of its addressable sub-fields is zero. 3491 3492 uint64_t Size = Context.getTypeSize(Ty); 3493 3494 // Check that the type fits in a word. 3495 if (Size > 32) 3496 return false; 3497 3498 // FIXME: Handle vector types! 3499 if (Ty->isVectorType()) 3500 return false; 3501 3502 // Float types are never treated as "integer like". 3503 if (Ty->isRealFloatingType()) 3504 return false; 3505 3506 // If this is a builtin or pointer type then it is ok. 3507 if (Ty->getAs<BuiltinType>() || Ty->isPointerType()) 3508 return true; 3509 3510 // Small complex integer types are "integer like". 3511 if (const ComplexType *CT = Ty->getAs<ComplexType>()) 3512 return isIntegerLikeType(CT->getElementType(), Context, VMContext); 3513 3514 // Single element and zero sized arrays should be allowed, by the definition 3515 // above, but they are not. 3516 3517 // Otherwise, it must be a record type. 3518 const RecordType *RT = Ty->getAs<RecordType>(); 3519 if (!RT) return false; 3520 3521 // Ignore records with flexible arrays. 3522 const RecordDecl *RD = RT->getDecl(); 3523 if (RD->hasFlexibleArrayMember()) 3524 return false; 3525 3526 // Check that all sub-fields are at offset 0, and are themselves "integer 3527 // like". 3528 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); 3529 3530 bool HadField = false; 3531 unsigned idx = 0; 3532 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 3533 i != e; ++i, ++idx) { 3534 const FieldDecl *FD = *i; 3535 3536 // Bit-fields are not addressable, we only need to verify they are "integer 3537 // like". We still have to disallow a subsequent non-bitfield, for example: 3538 // struct { int : 0; int x } 3539 // is non-integer like according to gcc. 3540 if (FD->isBitField()) { 3541 if (!RD->isUnion()) 3542 HadField = true; 3543 3544 if (!isIntegerLikeType(FD->getType(), Context, VMContext)) 3545 return false; 3546 3547 continue; 3548 } 3549 3550 // Check if this field is at offset 0. 3551 if (Layout.getFieldOffset(idx) != 0) 3552 return false; 3553 3554 if (!isIntegerLikeType(FD->getType(), Context, VMContext)) 3555 return false; 3556 3557 // Only allow at most one field in a structure. This doesn't match the 3558 // wording above, but follows gcc in situations with a field following an 3559 // empty structure. 3560 if (!RD->isUnion()) { 3561 if (HadField) 3562 return false; 3563 3564 HadField = true; 3565 } 3566 } 3567 3568 return true; 3569 } 3570 3571 ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy, bool isVariadic) const { 3572 if (RetTy->isVoidType()) 3573 return ABIArgInfo::getIgnore(); 3574 3575 // Large vector types should be returned via memory. 3576 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128) 3577 return ABIArgInfo::getIndirect(0); 3578 3579 if (!isAggregateTypeForABI(RetTy)) { 3580 // Treat an enum type as its underlying type. 3581 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 3582 RetTy = EnumTy->getDecl()->getIntegerType(); 3583 3584 return (RetTy->isPromotableIntegerType() ? 3585 ABIArgInfo::getExtend() : ABIArgInfo::getDirect()); 3586 } 3587 3588 // Structures with either a non-trivial destructor or a non-trivial 3589 // copy constructor are always indirect. 3590 if (isRecordReturnIndirect(RetTy, getCXXABI())) 3591 return ABIArgInfo::getIndirect(0, /*ByVal=*/false); 3592 3593 // Are we following APCS? 3594 if (getABIKind() == APCS) { 3595 if (isEmptyRecord(getContext(), RetTy, false)) 3596 return ABIArgInfo::getIgnore(); 3597 3598 // Complex types are all returned as packed integers. 3599 // 3600 // FIXME: Consider using 2 x vector types if the back end handles them 3601 // correctly. 3602 if (RetTy->isAnyComplexType()) 3603 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 3604 getContext().getTypeSize(RetTy))); 3605 3606 // Integer like structures are returned in r0. 3607 if (isIntegerLikeType(RetTy, getContext(), getVMContext())) { 3608 // Return in the smallest viable integer type. 3609 uint64_t Size = getContext().getTypeSize(RetTy); 3610 if (Size <= 8) 3611 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext())); 3612 if (Size <= 16) 3613 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext())); 3614 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext())); 3615 } 3616 3617 // Otherwise return in memory. 3618 return ABIArgInfo::getIndirect(0); 3619 } 3620 3621 // Otherwise this is an AAPCS variant. 3622 3623 if (isEmptyRecord(getContext(), RetTy, true)) 3624 return ABIArgInfo::getIgnore(); 3625 3626 // Check for homogeneous aggregates with AAPCS-VFP. 3627 if (getABIKind() == AAPCS_VFP && !isVariadic) { 3628 const Type *Base = 0; 3629 if (isHomogeneousAggregate(RetTy, Base, getContext())) { 3630 assert(Base && "Base class should be set for homogeneous aggregate"); 3631 // Homogeneous Aggregates are returned directly. 3632 return ABIArgInfo::getDirect(); 3633 } 3634 } 3635 3636 // Aggregates <= 4 bytes are returned in r0; other aggregates 3637 // are returned indirectly. 3638 uint64_t Size = getContext().getTypeSize(RetTy); 3639 if (Size <= 32) { 3640 // Return in the smallest viable integer type. 3641 if (Size <= 8) 3642 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext())); 3643 if (Size <= 16) 3644 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext())); 3645 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext())); 3646 } 3647 3648 return ABIArgInfo::getIndirect(0); 3649 } 3650 3651 /// isIllegalVector - check whether Ty is an illegal vector type. 3652 bool ARMABIInfo::isIllegalVectorType(QualType Ty) const { 3653 if (const VectorType *VT = Ty->getAs<VectorType>()) { 3654 // Check whether VT is legal. 3655 unsigned NumElements = VT->getNumElements(); 3656 uint64_t Size = getContext().getTypeSize(VT); 3657 // NumElements should be power of 2. 3658 if ((NumElements & (NumElements - 1)) != 0) 3659 return true; 3660 // Size should be greater than 32 bits. 3661 return Size <= 32; 3662 } 3663 return false; 3664 } 3665 3666 llvm::Value *ARMABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 3667 CodeGenFunction &CGF) const { 3668 llvm::Type *BP = CGF.Int8PtrTy; 3669 llvm::Type *BPP = CGF.Int8PtrPtrTy; 3670 3671 CGBuilderTy &Builder = CGF.Builder; 3672 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap"); 3673 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur"); 3674 3675 if (isEmptyRecord(getContext(), Ty, true)) { 3676 // These are ignored for parameter passing purposes. 3677 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty)); 3678 return Builder.CreateBitCast(Addr, PTy); 3679 } 3680 3681 uint64_t Size = CGF.getContext().getTypeSize(Ty) / 8; 3682 uint64_t TyAlign = CGF.getContext().getTypeAlign(Ty) / 8; 3683 bool IsIndirect = false; 3684 3685 // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for 3686 // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte. 3687 if (getABIKind() == ARMABIInfo::AAPCS_VFP || 3688 getABIKind() == ARMABIInfo::AAPCS) 3689 TyAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8); 3690 else 3691 TyAlign = 4; 3692 // Use indirect if size of the illegal vector is bigger than 16 bytes. 3693 if (isIllegalVectorType(Ty) && Size > 16) { 3694 IsIndirect = true; 3695 Size = 4; 3696 TyAlign = 4; 3697 } 3698 3699 // Handle address alignment for ABI alignment > 4 bytes. 3700 if (TyAlign > 4) { 3701 assert((TyAlign & (TyAlign - 1)) == 0 && 3702 "Alignment is not power of 2!"); 3703 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int32Ty); 3704 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt32(TyAlign - 1)); 3705 AddrAsInt = Builder.CreateAnd(AddrAsInt, Builder.getInt32(~(TyAlign - 1))); 3706 Addr = Builder.CreateIntToPtr(AddrAsInt, BP, "ap.align"); 3707 } 3708 3709 uint64_t Offset = 3710 llvm::RoundUpToAlignment(Size, 4); 3711 llvm::Value *NextAddr = 3712 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset), 3713 "ap.next"); 3714 Builder.CreateStore(NextAddr, VAListAddrAsBPP); 3715 3716 if (IsIndirect) 3717 Addr = Builder.CreateLoad(Builder.CreateBitCast(Addr, BPP)); 3718 else if (TyAlign < CGF.getContext().getTypeAlign(Ty) / 8) { 3719 // We can't directly cast ap.cur to pointer to a vector type, since ap.cur 3720 // may not be correctly aligned for the vector type. We create an aligned 3721 // temporary space and copy the content over from ap.cur to the temporary 3722 // space. This is necessary if the natural alignment of the type is greater 3723 // than the ABI alignment. 3724 llvm::Type *I8PtrTy = Builder.getInt8PtrTy(); 3725 CharUnits CharSize = getContext().getTypeSizeInChars(Ty); 3726 llvm::Value *AlignedTemp = CGF.CreateTempAlloca(CGF.ConvertType(Ty), 3727 "var.align"); 3728 llvm::Value *Dst = Builder.CreateBitCast(AlignedTemp, I8PtrTy); 3729 llvm::Value *Src = Builder.CreateBitCast(Addr, I8PtrTy); 3730 Builder.CreateMemCpy(Dst, Src, 3731 llvm::ConstantInt::get(CGF.IntPtrTy, CharSize.getQuantity()), 3732 TyAlign, false); 3733 Addr = AlignedTemp; //The content is in aligned location. 3734 } 3735 llvm::Type *PTy = 3736 llvm::PointerType::getUnqual(CGF.ConvertType(Ty)); 3737 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy); 3738 3739 return AddrTyped; 3740 } 3741 3742 namespace { 3743 3744 class NaClARMABIInfo : public ABIInfo { 3745 public: 3746 NaClARMABIInfo(CodeGen::CodeGenTypes &CGT, ARMABIInfo::ABIKind Kind) 3747 : ABIInfo(CGT), PInfo(CGT), NInfo(CGT, Kind) {} 3748 virtual void computeInfo(CGFunctionInfo &FI) const; 3749 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 3750 CodeGenFunction &CGF) const; 3751 private: 3752 PNaClABIInfo PInfo; // Used for generating calls with pnaclcall callingconv. 3753 ARMABIInfo NInfo; // Used for everything else. 3754 }; 3755 3756 class NaClARMTargetCodeGenInfo : public TargetCodeGenInfo { 3757 public: 3758 NaClARMTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, ARMABIInfo::ABIKind Kind) 3759 : TargetCodeGenInfo(new NaClARMABIInfo(CGT, Kind)) {} 3760 }; 3761 3762 } 3763 3764 void NaClARMABIInfo::computeInfo(CGFunctionInfo &FI) const { 3765 if (FI.getASTCallingConvention() == CC_PnaclCall) 3766 PInfo.computeInfo(FI); 3767 else 3768 static_cast<const ABIInfo&>(NInfo).computeInfo(FI); 3769 } 3770 3771 llvm::Value *NaClARMABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 3772 CodeGenFunction &CGF) const { 3773 // Always use the native convention; calling pnacl-style varargs functions 3774 // is unsupported. 3775 return static_cast<const ABIInfo&>(NInfo).EmitVAArg(VAListAddr, Ty, CGF); 3776 } 3777 3778 //===----------------------------------------------------------------------===// 3779 // AArch64 ABI Implementation 3780 //===----------------------------------------------------------------------===// 3781 3782 namespace { 3783 3784 class AArch64ABIInfo : public ABIInfo { 3785 public: 3786 AArch64ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {} 3787 3788 private: 3789 // The AArch64 PCS is explicit about return types and argument types being 3790 // handled identically, so we don't need to draw a distinction between 3791 // Argument and Return classification. 3792 ABIArgInfo classifyGenericType(QualType Ty, int &FreeIntRegs, 3793 int &FreeVFPRegs) const; 3794 3795 ABIArgInfo tryUseRegs(QualType Ty, int &FreeRegs, int RegsNeeded, bool IsInt, 3796 llvm::Type *DirectTy = 0) const; 3797 3798 virtual void computeInfo(CGFunctionInfo &FI) const; 3799 3800 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 3801 CodeGenFunction &CGF) const; 3802 }; 3803 3804 class AArch64TargetCodeGenInfo : public TargetCodeGenInfo { 3805 public: 3806 AArch64TargetCodeGenInfo(CodeGenTypes &CGT) 3807 :TargetCodeGenInfo(new AArch64ABIInfo(CGT)) {} 3808 3809 const AArch64ABIInfo &getABIInfo() const { 3810 return static_cast<const AArch64ABIInfo&>(TargetCodeGenInfo::getABIInfo()); 3811 } 3812 3813 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const { 3814 return 31; 3815 } 3816 3817 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 3818 llvm::Value *Address) const { 3819 // 0-31 are x0-x30 and sp: 8 bytes each 3820 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8); 3821 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 31); 3822 3823 // 64-95 are v0-v31: 16 bytes each 3824 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16); 3825 AssignToArrayRange(CGF.Builder, Address, Sixteen8, 64, 95); 3826 3827 return false; 3828 } 3829 3830 }; 3831 3832 } 3833 3834 void AArch64ABIInfo::computeInfo(CGFunctionInfo &FI) const { 3835 int FreeIntRegs = 8, FreeVFPRegs = 8; 3836 3837 FI.getReturnInfo() = classifyGenericType(FI.getReturnType(), 3838 FreeIntRegs, FreeVFPRegs); 3839 3840 FreeIntRegs = FreeVFPRegs = 8; 3841 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end(); 3842 it != ie; ++it) { 3843 it->info = classifyGenericType(it->type, FreeIntRegs, FreeVFPRegs); 3844 3845 } 3846 } 3847 3848 ABIArgInfo 3849 AArch64ABIInfo::tryUseRegs(QualType Ty, int &FreeRegs, int RegsNeeded, 3850 bool IsInt, llvm::Type *DirectTy) const { 3851 if (FreeRegs >= RegsNeeded) { 3852 FreeRegs -= RegsNeeded; 3853 return ABIArgInfo::getDirect(DirectTy); 3854 } 3855 3856 llvm::Type *Padding = 0; 3857 3858 // We need padding so that later arguments don't get filled in anyway. That 3859 // wouldn't happen if only ByVal arguments followed in the same category, but 3860 // a large structure will simply seem to be a pointer as far as LLVM is 3861 // concerned. 3862 if (FreeRegs > 0) { 3863 if (IsInt) 3864 Padding = llvm::Type::getInt64Ty(getVMContext()); 3865 else 3866 Padding = llvm::Type::getFloatTy(getVMContext()); 3867 3868 // Either [N x i64] or [N x float]. 3869 Padding = llvm::ArrayType::get(Padding, FreeRegs); 3870 FreeRegs = 0; 3871 } 3872 3873 return ABIArgInfo::getIndirect(getContext().getTypeAlign(Ty) / 8, 3874 /*IsByVal=*/ true, /*Realign=*/ false, 3875 Padding); 3876 } 3877 3878 3879 ABIArgInfo AArch64ABIInfo::classifyGenericType(QualType Ty, 3880 int &FreeIntRegs, 3881 int &FreeVFPRegs) const { 3882 // Can only occurs for return, but harmless otherwise. 3883 if (Ty->isVoidType()) 3884 return ABIArgInfo::getIgnore(); 3885 3886 // Large vector types should be returned via memory. There's no such concept 3887 // in the ABI, but they'd be over 16 bytes anyway so no matter how they're 3888 // classified they'd go into memory (see B.3). 3889 if (Ty->isVectorType() && getContext().getTypeSize(Ty) > 128) { 3890 if (FreeIntRegs > 0) 3891 --FreeIntRegs; 3892 return ABIArgInfo::getIndirect(0, /*ByVal=*/false); 3893 } 3894 3895 // All non-aggregate LLVM types have a concrete ABI representation so they can 3896 // be passed directly. After this block we're guaranteed to be in a 3897 // complicated case. 3898 if (!isAggregateTypeForABI(Ty)) { 3899 // Treat an enum type as its underlying type. 3900 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 3901 Ty = EnumTy->getDecl()->getIntegerType(); 3902 3903 if (Ty->isFloatingType() || Ty->isVectorType()) 3904 return tryUseRegs(Ty, FreeVFPRegs, /*RegsNeeded=*/ 1, /*IsInt=*/ false); 3905 3906 assert(getContext().getTypeSize(Ty) <= 128 && 3907 "unexpectedly large scalar type"); 3908 3909 int RegsNeeded = getContext().getTypeSize(Ty) > 64 ? 2 : 1; 3910 3911 // If the type may need padding registers to ensure "alignment", we must be 3912 // careful when this is accounted for. Increasing the effective size covers 3913 // all cases. 3914 if (getContext().getTypeAlign(Ty) == 128) 3915 RegsNeeded += FreeIntRegs % 2 != 0; 3916 3917 return tryUseRegs(Ty, FreeIntRegs, RegsNeeded, /*IsInt=*/ true); 3918 } 3919 3920 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) { 3921 if (FreeIntRegs > 0 && RAA == CGCXXABI::RAA_Indirect) 3922 --FreeIntRegs; 3923 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory); 3924 } 3925 3926 if (isEmptyRecord(getContext(), Ty, true)) { 3927 if (!getContext().getLangOpts().CPlusPlus) { 3928 // Empty structs outside C++ mode are a GNU extension, so no ABI can 3929 // possibly tell us what to do. It turns out (I believe) that GCC ignores 3930 // the object for parameter-passsing purposes. 3931 return ABIArgInfo::getIgnore(); 3932 } 3933 3934 // The combination of C++98 9p5 (sizeof(struct) != 0) and the pseudocode 3935 // description of va_arg in the PCS require that an empty struct does 3936 // actually occupy space for parameter-passing. I'm hoping for a 3937 // clarification giving an explicit paragraph to point to in future. 3938 return tryUseRegs(Ty, FreeIntRegs, /*RegsNeeded=*/ 1, /*IsInt=*/ true, 3939 llvm::Type::getInt8Ty(getVMContext())); 3940 } 3941 3942 // Homogeneous vector aggregates get passed in registers or on the stack. 3943 const Type *Base = 0; 3944 uint64_t NumMembers = 0; 3945 if (isHomogeneousAggregate(Ty, Base, getContext(), &NumMembers)) { 3946 assert(Base && "Base class should be set for homogeneous aggregate"); 3947 // Homogeneous aggregates are passed and returned directly. 3948 return tryUseRegs(Ty, FreeVFPRegs, /*RegsNeeded=*/ NumMembers, 3949 /*IsInt=*/ false); 3950 } 3951 3952 uint64_t Size = getContext().getTypeSize(Ty); 3953 if (Size <= 128) { 3954 // Small structs can use the same direct type whether they're in registers 3955 // or on the stack. 3956 llvm::Type *BaseTy; 3957 unsigned NumBases; 3958 int SizeInRegs = (Size + 63) / 64; 3959 3960 if (getContext().getTypeAlign(Ty) == 128) { 3961 BaseTy = llvm::Type::getIntNTy(getVMContext(), 128); 3962 NumBases = 1; 3963 3964 // If the type may need padding registers to ensure "alignment", we must 3965 // be careful when this is accounted for. Increasing the effective size 3966 // covers all cases. 3967 SizeInRegs += FreeIntRegs % 2 != 0; 3968 } else { 3969 BaseTy = llvm::Type::getInt64Ty(getVMContext()); 3970 NumBases = SizeInRegs; 3971 } 3972 llvm::Type *DirectTy = llvm::ArrayType::get(BaseTy, NumBases); 3973 3974 return tryUseRegs(Ty, FreeIntRegs, /*RegsNeeded=*/ SizeInRegs, 3975 /*IsInt=*/ true, DirectTy); 3976 } 3977 3978 // If the aggregate is > 16 bytes, it's passed and returned indirectly. In 3979 // LLVM terms the return uses an "sret" pointer, but that's handled elsewhere. 3980 --FreeIntRegs; 3981 return ABIArgInfo::getIndirect(0, /* byVal = */ false); 3982 } 3983 3984 llvm::Value *AArch64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 3985 CodeGenFunction &CGF) const { 3986 // The AArch64 va_list type and handling is specified in the Procedure Call 3987 // Standard, section B.4: 3988 // 3989 // struct { 3990 // void *__stack; 3991 // void *__gr_top; 3992 // void *__vr_top; 3993 // int __gr_offs; 3994 // int __vr_offs; 3995 // }; 3996 3997 assert(!CGF.CGM.getDataLayout().isBigEndian() 3998 && "va_arg not implemented for big-endian AArch64"); 3999 4000 int FreeIntRegs = 8, FreeVFPRegs = 8; 4001 Ty = CGF.getContext().getCanonicalType(Ty); 4002 ABIArgInfo AI = classifyGenericType(Ty, FreeIntRegs, FreeVFPRegs); 4003 4004 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg"); 4005 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg"); 4006 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack"); 4007 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end"); 4008 4009 llvm::Value *reg_offs_p = 0, *reg_offs = 0; 4010 int reg_top_index; 4011 int RegSize; 4012 if (FreeIntRegs < 8) { 4013 assert(FreeVFPRegs == 8 && "Arguments never split between int & VFP regs"); 4014 // 3 is the field number of __gr_offs 4015 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 3, "gr_offs_p"); 4016 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs"); 4017 reg_top_index = 1; // field number for __gr_top 4018 RegSize = 8 * (8 - FreeIntRegs); 4019 } else { 4020 assert(FreeVFPRegs < 8 && "Argument must go in VFP or int regs"); 4021 // 4 is the field number of __vr_offs. 4022 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 4, "vr_offs_p"); 4023 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs"); 4024 reg_top_index = 2; // field number for __vr_top 4025 RegSize = 16 * (8 - FreeVFPRegs); 4026 } 4027 4028 //======================================= 4029 // Find out where argument was passed 4030 //======================================= 4031 4032 // If reg_offs >= 0 we're already using the stack for this type of 4033 // argument. We don't want to keep updating reg_offs (in case it overflows, 4034 // though anyone passing 2GB of arguments, each at most 16 bytes, deserves 4035 // whatever they get). 4036 llvm::Value *UsingStack = 0; 4037 UsingStack = CGF.Builder.CreateICmpSGE(reg_offs, 4038 llvm::ConstantInt::get(CGF.Int32Ty, 0)); 4039 4040 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock); 4041 4042 // Otherwise, at least some kind of argument could go in these registers, the 4043 // quesiton is whether this particular type is too big. 4044 CGF.EmitBlock(MaybeRegBlock); 4045 4046 // Integer arguments may need to correct register alignment (for example a 4047 // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we 4048 // align __gr_offs to calculate the potential address. 4049 if (FreeIntRegs < 8 && AI.isDirect() && getContext().getTypeAlign(Ty) > 64) { 4050 int Align = getContext().getTypeAlign(Ty) / 8; 4051 4052 reg_offs = CGF.Builder.CreateAdd(reg_offs, 4053 llvm::ConstantInt::get(CGF.Int32Ty, Align - 1), 4054 "align_regoffs"); 4055 reg_offs = CGF.Builder.CreateAnd(reg_offs, 4056 llvm::ConstantInt::get(CGF.Int32Ty, -Align), 4057 "aligned_regoffs"); 4058 } 4059 4060 // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list. 4061 llvm::Value *NewOffset = 0; 4062 NewOffset = CGF.Builder.CreateAdd(reg_offs, 4063 llvm::ConstantInt::get(CGF.Int32Ty, RegSize), 4064 "new_reg_offs"); 4065 CGF.Builder.CreateStore(NewOffset, reg_offs_p); 4066 4067 // Now we're in a position to decide whether this argument really was in 4068 // registers or not. 4069 llvm::Value *InRegs = 0; 4070 InRegs = CGF.Builder.CreateICmpSLE(NewOffset, 4071 llvm::ConstantInt::get(CGF.Int32Ty, 0), 4072 "inreg"); 4073 4074 CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock); 4075 4076 //======================================= 4077 // Argument was in registers 4078 //======================================= 4079 4080 // Now we emit the code for if the argument was originally passed in 4081 // registers. First start the appropriate block: 4082 CGF.EmitBlock(InRegBlock); 4083 4084 llvm::Value *reg_top_p = 0, *reg_top = 0; 4085 reg_top_p = CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index, "reg_top_p"); 4086 reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top"); 4087 llvm::Value *BaseAddr = CGF.Builder.CreateGEP(reg_top, reg_offs); 4088 llvm::Value *RegAddr = 0; 4089 llvm::Type *MemTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty)); 4090 4091 if (!AI.isDirect()) { 4092 // If it's been passed indirectly (actually a struct), whatever we find from 4093 // stored registers or on the stack will actually be a struct **. 4094 MemTy = llvm::PointerType::getUnqual(MemTy); 4095 } 4096 4097 const Type *Base = 0; 4098 uint64_t NumMembers; 4099 if (isHomogeneousAggregate(Ty, Base, getContext(), &NumMembers) 4100 && NumMembers > 1) { 4101 // Homogeneous aggregates passed in registers will have their elements split 4102 // and stored 16-bytes apart regardless of size (they're notionally in qN, 4103 // qN+1, ...). We reload and store into a temporary local variable 4104 // contiguously. 4105 assert(AI.isDirect() && "Homogeneous aggregates should be passed directly"); 4106 llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0)); 4107 llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers); 4108 llvm::Value *Tmp = CGF.CreateTempAlloca(HFATy); 4109 4110 for (unsigned i = 0; i < NumMembers; ++i) { 4111 llvm::Value *BaseOffset = llvm::ConstantInt::get(CGF.Int32Ty, 16 * i); 4112 llvm::Value *LoadAddr = CGF.Builder.CreateGEP(BaseAddr, BaseOffset); 4113 LoadAddr = CGF.Builder.CreateBitCast(LoadAddr, 4114 llvm::PointerType::getUnqual(BaseTy)); 4115 llvm::Value *StoreAddr = CGF.Builder.CreateStructGEP(Tmp, i); 4116 4117 llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr); 4118 CGF.Builder.CreateStore(Elem, StoreAddr); 4119 } 4120 4121 RegAddr = CGF.Builder.CreateBitCast(Tmp, MemTy); 4122 } else { 4123 // Otherwise the object is contiguous in memory 4124 RegAddr = CGF.Builder.CreateBitCast(BaseAddr, MemTy); 4125 } 4126 4127 CGF.EmitBranch(ContBlock); 4128 4129 //======================================= 4130 // Argument was on the stack 4131 //======================================= 4132 CGF.EmitBlock(OnStackBlock); 4133 4134 llvm::Value *stack_p = 0, *OnStackAddr = 0; 4135 stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "stack_p"); 4136 OnStackAddr = CGF.Builder.CreateLoad(stack_p, "stack"); 4137 4138 // Again, stack arguments may need realigmnent. In this case both integer and 4139 // floating-point ones might be affected. 4140 if (AI.isDirect() && getContext().getTypeAlign(Ty) > 64) { 4141 int Align = getContext().getTypeAlign(Ty) / 8; 4142 4143 OnStackAddr = CGF.Builder.CreatePtrToInt(OnStackAddr, CGF.Int64Ty); 4144 4145 OnStackAddr = CGF.Builder.CreateAdd(OnStackAddr, 4146 llvm::ConstantInt::get(CGF.Int64Ty, Align - 1), 4147 "align_stack"); 4148 OnStackAddr = CGF.Builder.CreateAnd(OnStackAddr, 4149 llvm::ConstantInt::get(CGF.Int64Ty, -Align), 4150 "align_stack"); 4151 4152 OnStackAddr = CGF.Builder.CreateIntToPtr(OnStackAddr, CGF.Int8PtrTy); 4153 } 4154 4155 uint64_t StackSize; 4156 if (AI.isDirect()) 4157 StackSize = getContext().getTypeSize(Ty) / 8; 4158 else 4159 StackSize = 8; 4160 4161 // All stack slots are 8 bytes 4162 StackSize = llvm::RoundUpToAlignment(StackSize, 8); 4163 4164 llvm::Value *StackSizeC = llvm::ConstantInt::get(CGF.Int32Ty, StackSize); 4165 llvm::Value *NewStack = CGF.Builder.CreateGEP(OnStackAddr, StackSizeC, 4166 "new_stack"); 4167 4168 // Write the new value of __stack for the next call to va_arg 4169 CGF.Builder.CreateStore(NewStack, stack_p); 4170 4171 OnStackAddr = CGF.Builder.CreateBitCast(OnStackAddr, MemTy); 4172 4173 CGF.EmitBranch(ContBlock); 4174 4175 //======================================= 4176 // Tidy up 4177 //======================================= 4178 CGF.EmitBlock(ContBlock); 4179 4180 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(MemTy, 2, "vaarg.addr"); 4181 ResAddr->addIncoming(RegAddr, InRegBlock); 4182 ResAddr->addIncoming(OnStackAddr, OnStackBlock); 4183 4184 if (AI.isDirect()) 4185 return ResAddr; 4186 4187 return CGF.Builder.CreateLoad(ResAddr, "vaarg.addr"); 4188 } 4189 4190 //===----------------------------------------------------------------------===// 4191 // NVPTX ABI Implementation 4192 //===----------------------------------------------------------------------===// 4193 4194 namespace { 4195 4196 class NVPTXABIInfo : public ABIInfo { 4197 public: 4198 NVPTXABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {} 4199 4200 ABIArgInfo classifyReturnType(QualType RetTy) const; 4201 ABIArgInfo classifyArgumentType(QualType Ty) const; 4202 4203 virtual void computeInfo(CGFunctionInfo &FI) const; 4204 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 4205 CodeGenFunction &CFG) const; 4206 }; 4207 4208 class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo { 4209 public: 4210 NVPTXTargetCodeGenInfo(CodeGenTypes &CGT) 4211 : TargetCodeGenInfo(new NVPTXABIInfo(CGT)) {} 4212 4213 virtual void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 4214 CodeGen::CodeGenModule &M) const; 4215 private: 4216 static void addKernelMetadata(llvm::Function *F); 4217 }; 4218 4219 ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const { 4220 if (RetTy->isVoidType()) 4221 return ABIArgInfo::getIgnore(); 4222 4223 // note: this is different from default ABI 4224 if (!RetTy->isScalarType()) 4225 return ABIArgInfo::getDirect(); 4226 4227 // Treat an enum type as its underlying type. 4228 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 4229 RetTy = EnumTy->getDecl()->getIntegerType(); 4230 4231 return (RetTy->isPromotableIntegerType() ? 4232 ABIArgInfo::getExtend() : ABIArgInfo::getDirect()); 4233 } 4234 4235 ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const { 4236 // Treat an enum type as its underlying type. 4237 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 4238 Ty = EnumTy->getDecl()->getIntegerType(); 4239 4240 return (Ty->isPromotableIntegerType() ? 4241 ABIArgInfo::getExtend() : ABIArgInfo::getDirect()); 4242 } 4243 4244 void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const { 4245 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 4246 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end(); 4247 it != ie; ++it) 4248 it->info = classifyArgumentType(it->type); 4249 4250 // Always honor user-specified calling convention. 4251 if (FI.getCallingConvention() != llvm::CallingConv::C) 4252 return; 4253 4254 FI.setEffectiveCallingConvention(getRuntimeCC()); 4255 } 4256 4257 llvm::Value *NVPTXABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 4258 CodeGenFunction &CFG) const { 4259 llvm_unreachable("NVPTX does not support varargs"); 4260 } 4261 4262 void NVPTXTargetCodeGenInfo:: 4263 SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 4264 CodeGen::CodeGenModule &M) const{ 4265 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D); 4266 if (!FD) return; 4267 4268 llvm::Function *F = cast<llvm::Function>(GV); 4269 4270 // Perform special handling in OpenCL mode 4271 if (M.getLangOpts().OpenCL) { 4272 // Use OpenCL function attributes to check for kernel functions 4273 // By default, all functions are device functions 4274 if (FD->hasAttr<OpenCLKernelAttr>()) { 4275 // OpenCL __kernel functions get kernel metadata 4276 addKernelMetadata(F); 4277 // And kernel functions are not subject to inlining 4278 F->addFnAttr(llvm::Attribute::NoInline); 4279 } 4280 } 4281 4282 // Perform special handling in CUDA mode. 4283 if (M.getLangOpts().CUDA) { 4284 // CUDA __global__ functions get a kernel metadata entry. Since 4285 // __global__ functions cannot be called from the device, we do not 4286 // need to set the noinline attribute. 4287 if (FD->hasAttr<CUDAGlobalAttr>()) 4288 addKernelMetadata(F); 4289 } 4290 } 4291 4292 void NVPTXTargetCodeGenInfo::addKernelMetadata(llvm::Function *F) { 4293 llvm::Module *M = F->getParent(); 4294 llvm::LLVMContext &Ctx = M->getContext(); 4295 4296 // Get "nvvm.annotations" metadata node 4297 llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations"); 4298 4299 // Create !{<func-ref>, metadata !"kernel", i32 1} node 4300 llvm::SmallVector<llvm::Value *, 3> MDVals; 4301 MDVals.push_back(F); 4302 MDVals.push_back(llvm::MDString::get(Ctx, "kernel")); 4303 MDVals.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), 1)); 4304 4305 // Append metadata to nvvm.annotations 4306 MD->addOperand(llvm::MDNode::get(Ctx, MDVals)); 4307 } 4308 4309 } 4310 4311 //===----------------------------------------------------------------------===// 4312 // SystemZ ABI Implementation 4313 //===----------------------------------------------------------------------===// 4314 4315 namespace { 4316 4317 class SystemZABIInfo : public ABIInfo { 4318 public: 4319 SystemZABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {} 4320 4321 bool isPromotableIntegerType(QualType Ty) const; 4322 bool isCompoundType(QualType Ty) const; 4323 bool isFPArgumentType(QualType Ty) const; 4324 4325 ABIArgInfo classifyReturnType(QualType RetTy) const; 4326 ABIArgInfo classifyArgumentType(QualType ArgTy) const; 4327 4328 virtual void computeInfo(CGFunctionInfo &FI) const { 4329 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 4330 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end(); 4331 it != ie; ++it) 4332 it->info = classifyArgumentType(it->type); 4333 } 4334 4335 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 4336 CodeGenFunction &CGF) const; 4337 }; 4338 4339 class SystemZTargetCodeGenInfo : public TargetCodeGenInfo { 4340 public: 4341 SystemZTargetCodeGenInfo(CodeGenTypes &CGT) 4342 : TargetCodeGenInfo(new SystemZABIInfo(CGT)) {} 4343 }; 4344 4345 } 4346 4347 bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const { 4348 // Treat an enum type as its underlying type. 4349 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 4350 Ty = EnumTy->getDecl()->getIntegerType(); 4351 4352 // Promotable integer types are required to be promoted by the ABI. 4353 if (Ty->isPromotableIntegerType()) 4354 return true; 4355 4356 // 32-bit values must also be promoted. 4357 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) 4358 switch (BT->getKind()) { 4359 case BuiltinType::Int: 4360 case BuiltinType::UInt: 4361 return true; 4362 default: 4363 return false; 4364 } 4365 return false; 4366 } 4367 4368 bool SystemZABIInfo::isCompoundType(QualType Ty) const { 4369 return Ty->isAnyComplexType() || isAggregateTypeForABI(Ty); 4370 } 4371 4372 bool SystemZABIInfo::isFPArgumentType(QualType Ty) const { 4373 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) 4374 switch (BT->getKind()) { 4375 case BuiltinType::Float: 4376 case BuiltinType::Double: 4377 return true; 4378 default: 4379 return false; 4380 } 4381 4382 if (const RecordType *RT = Ty->getAsStructureType()) { 4383 const RecordDecl *RD = RT->getDecl(); 4384 bool Found = false; 4385 4386 // If this is a C++ record, check the bases first. 4387 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 4388 for (CXXRecordDecl::base_class_const_iterator I = CXXRD->bases_begin(), 4389 E = CXXRD->bases_end(); I != E; ++I) { 4390 QualType Base = I->getType(); 4391 4392 // Empty bases don't affect things either way. 4393 if (isEmptyRecord(getContext(), Base, true)) 4394 continue; 4395 4396 if (Found) 4397 return false; 4398 Found = isFPArgumentType(Base); 4399 if (!Found) 4400 return false; 4401 } 4402 4403 // Check the fields. 4404 for (RecordDecl::field_iterator I = RD->field_begin(), 4405 E = RD->field_end(); I != E; ++I) { 4406 const FieldDecl *FD = *I; 4407 4408 // Empty bitfields don't affect things either way. 4409 // Unlike isSingleElementStruct(), empty structure and array fields 4410 // do count. So do anonymous bitfields that aren't zero-sized. 4411 if (FD->isBitField() && FD->getBitWidthValue(getContext()) == 0) 4412 return true; 4413 4414 // Unlike isSingleElementStruct(), arrays do not count. 4415 // Nested isFPArgumentType structures still do though. 4416 if (Found) 4417 return false; 4418 Found = isFPArgumentType(FD->getType()); 4419 if (!Found) 4420 return false; 4421 } 4422 4423 // Unlike isSingleElementStruct(), trailing padding is allowed. 4424 // An 8-byte aligned struct s { float f; } is passed as a double. 4425 return Found; 4426 } 4427 4428 return false; 4429 } 4430 4431 llvm::Value *SystemZABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 4432 CodeGenFunction &CGF) const { 4433 // Assume that va_list type is correct; should be pointer to LLVM type: 4434 // struct { 4435 // i64 __gpr; 4436 // i64 __fpr; 4437 // i8 *__overflow_arg_area; 4438 // i8 *__reg_save_area; 4439 // }; 4440 4441 // Every argument occupies 8 bytes and is passed by preference in either 4442 // GPRs or FPRs. 4443 Ty = CGF.getContext().getCanonicalType(Ty); 4444 ABIArgInfo AI = classifyArgumentType(Ty); 4445 bool InFPRs = isFPArgumentType(Ty); 4446 4447 llvm::Type *APTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty)); 4448 bool IsIndirect = AI.isIndirect(); 4449 unsigned UnpaddedBitSize; 4450 if (IsIndirect) { 4451 APTy = llvm::PointerType::getUnqual(APTy); 4452 UnpaddedBitSize = 64; 4453 } else 4454 UnpaddedBitSize = getContext().getTypeSize(Ty); 4455 unsigned PaddedBitSize = 64; 4456 assert((UnpaddedBitSize <= PaddedBitSize) && "Invalid argument size."); 4457 4458 unsigned PaddedSize = PaddedBitSize / 8; 4459 unsigned Padding = (PaddedBitSize - UnpaddedBitSize) / 8; 4460 4461 unsigned MaxRegs, RegCountField, RegSaveIndex, RegPadding; 4462 if (InFPRs) { 4463 MaxRegs = 4; // Maximum of 4 FPR arguments 4464 RegCountField = 1; // __fpr 4465 RegSaveIndex = 16; // save offset for f0 4466 RegPadding = 0; // floats are passed in the high bits of an FPR 4467 } else { 4468 MaxRegs = 5; // Maximum of 5 GPR arguments 4469 RegCountField = 0; // __gpr 4470 RegSaveIndex = 2; // save offset for r2 4471 RegPadding = Padding; // values are passed in the low bits of a GPR 4472 } 4473 4474 llvm::Value *RegCountPtr = 4475 CGF.Builder.CreateStructGEP(VAListAddr, RegCountField, "reg_count_ptr"); 4476 llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count"); 4477 llvm::Type *IndexTy = RegCount->getType(); 4478 llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs); 4479 llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV, 4480 "fits_in_regs"); 4481 4482 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg"); 4483 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem"); 4484 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end"); 4485 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock); 4486 4487 // Emit code to load the value if it was passed in registers. 4488 CGF.EmitBlock(InRegBlock); 4489 4490 // Work out the address of an argument register. 4491 llvm::Value *PaddedSizeV = llvm::ConstantInt::get(IndexTy, PaddedSize); 4492 llvm::Value *ScaledRegCount = 4493 CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count"); 4494 llvm::Value *RegBase = 4495 llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize + RegPadding); 4496 llvm::Value *RegOffset = 4497 CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset"); 4498 llvm::Value *RegSaveAreaPtr = 4499 CGF.Builder.CreateStructGEP(VAListAddr, 3, "reg_save_area_ptr"); 4500 llvm::Value *RegSaveArea = 4501 CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area"); 4502 llvm::Value *RawRegAddr = 4503 CGF.Builder.CreateGEP(RegSaveArea, RegOffset, "raw_reg_addr"); 4504 llvm::Value *RegAddr = 4505 CGF.Builder.CreateBitCast(RawRegAddr, APTy, "reg_addr"); 4506 4507 // Update the register count 4508 llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1); 4509 llvm::Value *NewRegCount = 4510 CGF.Builder.CreateAdd(RegCount, One, "reg_count"); 4511 CGF.Builder.CreateStore(NewRegCount, RegCountPtr); 4512 CGF.EmitBranch(ContBlock); 4513 4514 // Emit code to load the value if it was passed in memory. 4515 CGF.EmitBlock(InMemBlock); 4516 4517 // Work out the address of a stack argument. 4518 llvm::Value *OverflowArgAreaPtr = 4519 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr"); 4520 llvm::Value *OverflowArgArea = 4521 CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"); 4522 llvm::Value *PaddingV = llvm::ConstantInt::get(IndexTy, Padding); 4523 llvm::Value *RawMemAddr = 4524 CGF.Builder.CreateGEP(OverflowArgArea, PaddingV, "raw_mem_addr"); 4525 llvm::Value *MemAddr = 4526 CGF.Builder.CreateBitCast(RawMemAddr, APTy, "mem_addr"); 4527 4528 // Update overflow_arg_area_ptr pointer 4529 llvm::Value *NewOverflowArgArea = 4530 CGF.Builder.CreateGEP(OverflowArgArea, PaddedSizeV, "overflow_arg_area"); 4531 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr); 4532 CGF.EmitBranch(ContBlock); 4533 4534 // Return the appropriate result. 4535 CGF.EmitBlock(ContBlock); 4536 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(APTy, 2, "va_arg.addr"); 4537 ResAddr->addIncoming(RegAddr, InRegBlock); 4538 ResAddr->addIncoming(MemAddr, InMemBlock); 4539 4540 if (IsIndirect) 4541 return CGF.Builder.CreateLoad(ResAddr, "indirect_arg"); 4542 4543 return ResAddr; 4544 } 4545 4546 bool X86_32TargetCodeGenInfo::isStructReturnInRegABI( 4547 const llvm::Triple &Triple, const CodeGenOptions &Opts) { 4548 assert(Triple.getArch() == llvm::Triple::x86); 4549 4550 switch (Opts.getStructReturnConvention()) { 4551 case CodeGenOptions::SRCK_Default: 4552 break; 4553 case CodeGenOptions::SRCK_OnStack: // -fpcc-struct-return 4554 return false; 4555 case CodeGenOptions::SRCK_InRegs: // -freg-struct-return 4556 return true; 4557 } 4558 4559 if (Triple.isOSDarwin()) 4560 return true; 4561 4562 switch (Triple.getOS()) { 4563 case llvm::Triple::Cygwin: 4564 case llvm::Triple::MinGW32: 4565 case llvm::Triple::AuroraUX: 4566 case llvm::Triple::DragonFly: 4567 case llvm::Triple::FreeBSD: 4568 case llvm::Triple::OpenBSD: 4569 case llvm::Triple::Bitrig: 4570 case llvm::Triple::Win32: 4571 return true; 4572 default: 4573 return false; 4574 } 4575 } 4576 4577 ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const { 4578 if (RetTy->isVoidType()) 4579 return ABIArgInfo::getIgnore(); 4580 if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64) 4581 return ABIArgInfo::getIndirect(0); 4582 return (isPromotableIntegerType(RetTy) ? 4583 ABIArgInfo::getExtend() : ABIArgInfo::getDirect()); 4584 } 4585 4586 ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const { 4587 // Handle the generic C++ ABI. 4588 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 4589 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory); 4590 4591 // Integers and enums are extended to full register width. 4592 if (isPromotableIntegerType(Ty)) 4593 return ABIArgInfo::getExtend(); 4594 4595 // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly. 4596 uint64_t Size = getContext().getTypeSize(Ty); 4597 if (Size != 8 && Size != 16 && Size != 32 && Size != 64) 4598 return ABIArgInfo::getIndirect(0, /*ByVal=*/false); 4599 4600 // Handle small structures. 4601 if (const RecordType *RT = Ty->getAs<RecordType>()) { 4602 // Structures with flexible arrays have variable length, so really 4603 // fail the size test above. 4604 const RecordDecl *RD = RT->getDecl(); 4605 if (RD->hasFlexibleArrayMember()) 4606 return ABIArgInfo::getIndirect(0, /*ByVal=*/false); 4607 4608 // The structure is passed as an unextended integer, a float, or a double. 4609 llvm::Type *PassTy; 4610 if (isFPArgumentType(Ty)) { 4611 assert(Size == 32 || Size == 64); 4612 if (Size == 32) 4613 PassTy = llvm::Type::getFloatTy(getVMContext()); 4614 else 4615 PassTy = llvm::Type::getDoubleTy(getVMContext()); 4616 } else 4617 PassTy = llvm::IntegerType::get(getVMContext(), Size); 4618 return ABIArgInfo::getDirect(PassTy); 4619 } 4620 4621 // Non-structure compounds are passed indirectly. 4622 if (isCompoundType(Ty)) 4623 return ABIArgInfo::getIndirect(0, /*ByVal=*/false); 4624 4625 return ABIArgInfo::getDirect(0); 4626 } 4627 4628 //===----------------------------------------------------------------------===// 4629 // MSP430 ABI Implementation 4630 //===----------------------------------------------------------------------===// 4631 4632 namespace { 4633 4634 class MSP430TargetCodeGenInfo : public TargetCodeGenInfo { 4635 public: 4636 MSP430TargetCodeGenInfo(CodeGenTypes &CGT) 4637 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {} 4638 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 4639 CodeGen::CodeGenModule &M) const; 4640 }; 4641 4642 } 4643 4644 void MSP430TargetCodeGenInfo::SetTargetAttributes(const Decl *D, 4645 llvm::GlobalValue *GV, 4646 CodeGen::CodeGenModule &M) const { 4647 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 4648 if (const MSP430InterruptAttr *attr = FD->getAttr<MSP430InterruptAttr>()) { 4649 // Handle 'interrupt' attribute: 4650 llvm::Function *F = cast<llvm::Function>(GV); 4651 4652 // Step 1: Set ISR calling convention. 4653 F->setCallingConv(llvm::CallingConv::MSP430_INTR); 4654 4655 // Step 2: Add attributes goodness. 4656 F->addFnAttr(llvm::Attribute::NoInline); 4657 4658 // Step 3: Emit ISR vector alias. 4659 unsigned Num = attr->getNumber() / 2; 4660 new llvm::GlobalAlias(GV->getType(), llvm::Function::ExternalLinkage, 4661 "__isr_" + Twine(Num), 4662 GV, &M.getModule()); 4663 } 4664 } 4665 } 4666 4667 //===----------------------------------------------------------------------===// 4668 // MIPS ABI Implementation. This works for both little-endian and 4669 // big-endian variants. 4670 //===----------------------------------------------------------------------===// 4671 4672 namespace { 4673 class MipsABIInfo : public ABIInfo { 4674 bool IsO32; 4675 unsigned MinABIStackAlignInBytes, StackAlignInBytes; 4676 void CoerceToIntArgs(uint64_t TySize, 4677 SmallVectorImpl<llvm::Type *> &ArgList) const; 4678 llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const; 4679 llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const; 4680 llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const; 4681 public: 4682 MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) : 4683 ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8), 4684 StackAlignInBytes(IsO32 ? 8 : 16) {} 4685 4686 ABIArgInfo classifyReturnType(QualType RetTy) const; 4687 ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const; 4688 virtual void computeInfo(CGFunctionInfo &FI) const; 4689 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 4690 CodeGenFunction &CGF) const; 4691 }; 4692 4693 class MIPSTargetCodeGenInfo : public TargetCodeGenInfo { 4694 unsigned SizeOfUnwindException; 4695 public: 4696 MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32) 4697 : TargetCodeGenInfo(new MipsABIInfo(CGT, IsO32)), 4698 SizeOfUnwindException(IsO32 ? 24 : 32) {} 4699 4700 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const { 4701 return 29; 4702 } 4703 4704 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 4705 CodeGen::CodeGenModule &CGM) const { 4706 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D); 4707 if (!FD) return; 4708 llvm::Function *Fn = cast<llvm::Function>(GV); 4709 if (FD->hasAttr<Mips16Attr>()) { 4710 Fn->addFnAttr("mips16"); 4711 } 4712 else if (FD->hasAttr<NoMips16Attr>()) { 4713 Fn->addFnAttr("nomips16"); 4714 } 4715 } 4716 4717 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 4718 llvm::Value *Address) const; 4719 4720 unsigned getSizeOfUnwindException() const { 4721 return SizeOfUnwindException; 4722 } 4723 }; 4724 } 4725 4726 void MipsABIInfo::CoerceToIntArgs(uint64_t TySize, 4727 SmallVectorImpl<llvm::Type *> &ArgList) const { 4728 llvm::IntegerType *IntTy = 4729 llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8); 4730 4731 // Add (TySize / MinABIStackAlignInBytes) args of IntTy. 4732 for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N) 4733 ArgList.push_back(IntTy); 4734 4735 // If necessary, add one more integer type to ArgList. 4736 unsigned R = TySize % (MinABIStackAlignInBytes * 8); 4737 4738 if (R) 4739 ArgList.push_back(llvm::IntegerType::get(getVMContext(), R)); 4740 } 4741 4742 // In N32/64, an aligned double precision floating point field is passed in 4743 // a register. 4744 llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const { 4745 SmallVector<llvm::Type*, 8> ArgList, IntArgList; 4746 4747 if (IsO32) { 4748 CoerceToIntArgs(TySize, ArgList); 4749 return llvm::StructType::get(getVMContext(), ArgList); 4750 } 4751 4752 if (Ty->isComplexType()) 4753 return CGT.ConvertType(Ty); 4754 4755 const RecordType *RT = Ty->getAs<RecordType>(); 4756 4757 // Unions/vectors are passed in integer registers. 4758 if (!RT || !RT->isStructureOrClassType()) { 4759 CoerceToIntArgs(TySize, ArgList); 4760 return llvm::StructType::get(getVMContext(), ArgList); 4761 } 4762 4763 const RecordDecl *RD = RT->getDecl(); 4764 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD); 4765 assert(!(TySize % 8) && "Size of structure must be multiple of 8."); 4766 4767 uint64_t LastOffset = 0; 4768 unsigned idx = 0; 4769 llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64); 4770 4771 // Iterate over fields in the struct/class and check if there are any aligned 4772 // double fields. 4773 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 4774 i != e; ++i, ++idx) { 4775 const QualType Ty = i->getType(); 4776 const BuiltinType *BT = Ty->getAs<BuiltinType>(); 4777 4778 if (!BT || BT->getKind() != BuiltinType::Double) 4779 continue; 4780 4781 uint64_t Offset = Layout.getFieldOffset(idx); 4782 if (Offset % 64) // Ignore doubles that are not aligned. 4783 continue; 4784 4785 // Add ((Offset - LastOffset) / 64) args of type i64. 4786 for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j) 4787 ArgList.push_back(I64); 4788 4789 // Add double type. 4790 ArgList.push_back(llvm::Type::getDoubleTy(getVMContext())); 4791 LastOffset = Offset + 64; 4792 } 4793 4794 CoerceToIntArgs(TySize - LastOffset, IntArgList); 4795 ArgList.append(IntArgList.begin(), IntArgList.end()); 4796 4797 return llvm::StructType::get(getVMContext(), ArgList); 4798 } 4799 4800 llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset, 4801 uint64_t Offset) const { 4802 if (OrigOffset + MinABIStackAlignInBytes > Offset) 4803 return 0; 4804 4805 return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8); 4806 } 4807 4808 ABIArgInfo 4809 MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const { 4810 uint64_t OrigOffset = Offset; 4811 uint64_t TySize = getContext().getTypeSize(Ty); 4812 uint64_t Align = getContext().getTypeAlign(Ty) / 8; 4813 4814 Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes), 4815 (uint64_t)StackAlignInBytes); 4816 unsigned CurrOffset = llvm::RoundUpToAlignment(Offset, Align); 4817 Offset = CurrOffset + llvm::RoundUpToAlignment(TySize, Align * 8) / 8; 4818 4819 if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) { 4820 // Ignore empty aggregates. 4821 if (TySize == 0) 4822 return ABIArgInfo::getIgnore(); 4823 4824 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) { 4825 Offset = OrigOffset + MinABIStackAlignInBytes; 4826 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory); 4827 } 4828 4829 // If we have reached here, aggregates are passed directly by coercing to 4830 // another structure type. Padding is inserted if the offset of the 4831 // aggregate is unaligned. 4832 return ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0, 4833 getPaddingType(OrigOffset, CurrOffset)); 4834 } 4835 4836 // Treat an enum type as its underlying type. 4837 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 4838 Ty = EnumTy->getDecl()->getIntegerType(); 4839 4840 if (Ty->isPromotableIntegerType()) 4841 return ABIArgInfo::getExtend(); 4842 4843 return ABIArgInfo::getDirect( 4844 0, 0, IsO32 ? 0 : getPaddingType(OrigOffset, CurrOffset)); 4845 } 4846 4847 llvm::Type* 4848 MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const { 4849 const RecordType *RT = RetTy->getAs<RecordType>(); 4850 SmallVector<llvm::Type*, 8> RTList; 4851 4852 if (RT && RT->isStructureOrClassType()) { 4853 const RecordDecl *RD = RT->getDecl(); 4854 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD); 4855 unsigned FieldCnt = Layout.getFieldCount(); 4856 4857 // N32/64 returns struct/classes in floating point registers if the 4858 // following conditions are met: 4859 // 1. The size of the struct/class is no larger than 128-bit. 4860 // 2. The struct/class has one or two fields all of which are floating 4861 // point types. 4862 // 3. The offset of the first field is zero (this follows what gcc does). 4863 // 4864 // Any other composite results are returned in integer registers. 4865 // 4866 if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) { 4867 RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end(); 4868 for (; b != e; ++b) { 4869 const BuiltinType *BT = b->getType()->getAs<BuiltinType>(); 4870 4871 if (!BT || !BT->isFloatingPoint()) 4872 break; 4873 4874 RTList.push_back(CGT.ConvertType(b->getType())); 4875 } 4876 4877 if (b == e) 4878 return llvm::StructType::get(getVMContext(), RTList, 4879 RD->hasAttr<PackedAttr>()); 4880 4881 RTList.clear(); 4882 } 4883 } 4884 4885 CoerceToIntArgs(Size, RTList); 4886 return llvm::StructType::get(getVMContext(), RTList); 4887 } 4888 4889 ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const { 4890 uint64_t Size = getContext().getTypeSize(RetTy); 4891 4892 if (RetTy->isVoidType() || Size == 0) 4893 return ABIArgInfo::getIgnore(); 4894 4895 if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) { 4896 if (isRecordReturnIndirect(RetTy, getCXXABI())) 4897 return ABIArgInfo::getIndirect(0); 4898 4899 if (Size <= 128) { 4900 if (RetTy->isAnyComplexType()) 4901 return ABIArgInfo::getDirect(); 4902 4903 // O32 returns integer vectors in registers. 4904 if (IsO32 && RetTy->isVectorType() && !RetTy->hasFloatingRepresentation()) 4905 return ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size)); 4906 4907 if (!IsO32) 4908 return ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size)); 4909 } 4910 4911 return ABIArgInfo::getIndirect(0); 4912 } 4913 4914 // Treat an enum type as its underlying type. 4915 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 4916 RetTy = EnumTy->getDecl()->getIntegerType(); 4917 4918 return (RetTy->isPromotableIntegerType() ? 4919 ABIArgInfo::getExtend() : ABIArgInfo::getDirect()); 4920 } 4921 4922 void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const { 4923 ABIArgInfo &RetInfo = FI.getReturnInfo(); 4924 RetInfo = classifyReturnType(FI.getReturnType()); 4925 4926 // Check if a pointer to an aggregate is passed as a hidden argument. 4927 uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0; 4928 4929 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end(); 4930 it != ie; ++it) 4931 it->info = classifyArgumentType(it->type, Offset); 4932 } 4933 4934 llvm::Value* MipsABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 4935 CodeGenFunction &CGF) const { 4936 llvm::Type *BP = CGF.Int8PtrTy; 4937 llvm::Type *BPP = CGF.Int8PtrPtrTy; 4938 4939 CGBuilderTy &Builder = CGF.Builder; 4940 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap"); 4941 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur"); 4942 int64_t TypeAlign = getContext().getTypeAlign(Ty) / 8; 4943 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty)); 4944 llvm::Value *AddrTyped; 4945 unsigned PtrWidth = getTarget().getPointerWidth(0); 4946 llvm::IntegerType *IntTy = (PtrWidth == 32) ? CGF.Int32Ty : CGF.Int64Ty; 4947 4948 if (TypeAlign > MinABIStackAlignInBytes) { 4949 llvm::Value *AddrAsInt = CGF.Builder.CreatePtrToInt(Addr, IntTy); 4950 llvm::Value *Inc = llvm::ConstantInt::get(IntTy, TypeAlign - 1); 4951 llvm::Value *Mask = llvm::ConstantInt::get(IntTy, -TypeAlign); 4952 llvm::Value *Add = CGF.Builder.CreateAdd(AddrAsInt, Inc); 4953 llvm::Value *And = CGF.Builder.CreateAnd(Add, Mask); 4954 AddrTyped = CGF.Builder.CreateIntToPtr(And, PTy); 4955 } 4956 else 4957 AddrTyped = Builder.CreateBitCast(Addr, PTy); 4958 4959 llvm::Value *AlignedAddr = Builder.CreateBitCast(AddrTyped, BP); 4960 TypeAlign = std::max((unsigned)TypeAlign, MinABIStackAlignInBytes); 4961 uint64_t Offset = 4962 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, TypeAlign); 4963 llvm::Value *NextAddr = 4964 Builder.CreateGEP(AlignedAddr, llvm::ConstantInt::get(IntTy, Offset), 4965 "ap.next"); 4966 Builder.CreateStore(NextAddr, VAListAddrAsBPP); 4967 4968 return AddrTyped; 4969 } 4970 4971 bool 4972 MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 4973 llvm::Value *Address) const { 4974 // This information comes from gcc's implementation, which seems to 4975 // as canonical as it gets. 4976 4977 // Everything on MIPS is 4 bytes. Double-precision FP registers 4978 // are aliased to pairs of single-precision FP registers. 4979 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4); 4980 4981 // 0-31 are the general purpose registers, $0 - $31. 4982 // 32-63 are the floating-point registers, $f0 - $f31. 4983 // 64 and 65 are the multiply/divide registers, $hi and $lo. 4984 // 66 is the (notional, I think) register for signal-handler return. 4985 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65); 4986 4987 // 67-74 are the floating-point status registers, $fcc0 - $fcc7. 4988 // They are one bit wide and ignored here. 4989 4990 // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31. 4991 // (coprocessor 1 is the FP unit) 4992 // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31. 4993 // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31. 4994 // 176-181 are the DSP accumulator registers. 4995 AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181); 4996 return false; 4997 } 4998 4999 //===----------------------------------------------------------------------===// 5000 // TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults. 5001 // Currently subclassed only to implement custom OpenCL C function attribute 5002 // handling. 5003 //===----------------------------------------------------------------------===// 5004 5005 namespace { 5006 5007 class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo { 5008 public: 5009 TCETargetCodeGenInfo(CodeGenTypes &CGT) 5010 : DefaultTargetCodeGenInfo(CGT) {} 5011 5012 virtual void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 5013 CodeGen::CodeGenModule &M) const; 5014 }; 5015 5016 void TCETargetCodeGenInfo::SetTargetAttributes(const Decl *D, 5017 llvm::GlobalValue *GV, 5018 CodeGen::CodeGenModule &M) const { 5019 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D); 5020 if (!FD) return; 5021 5022 llvm::Function *F = cast<llvm::Function>(GV); 5023 5024 if (M.getLangOpts().OpenCL) { 5025 if (FD->hasAttr<OpenCLKernelAttr>()) { 5026 // OpenCL C Kernel functions are not subject to inlining 5027 F->addFnAttr(llvm::Attribute::NoInline); 5028 const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>(); 5029 if (Attr) { 5030 // Convert the reqd_work_group_size() attributes to metadata. 5031 llvm::LLVMContext &Context = F->getContext(); 5032 llvm::NamedMDNode *OpenCLMetadata = 5033 M.getModule().getOrInsertNamedMetadata("opencl.kernel_wg_size_info"); 5034 5035 SmallVector<llvm::Value*, 5> Operands; 5036 Operands.push_back(F); 5037 5038 Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty, 5039 llvm::APInt(32, Attr->getXDim()))); 5040 Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty, 5041 llvm::APInt(32, Attr->getYDim()))); 5042 Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty, 5043 llvm::APInt(32, Attr->getZDim()))); 5044 5045 // Add a boolean constant operand for "required" (true) or "hint" (false) 5046 // for implementing the work_group_size_hint attr later. Currently 5047 // always true as the hint is not yet implemented. 5048 Operands.push_back(llvm::ConstantInt::getTrue(Context)); 5049 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands)); 5050 } 5051 } 5052 } 5053 } 5054 5055 } 5056 5057 //===----------------------------------------------------------------------===// 5058 // Hexagon ABI Implementation 5059 //===----------------------------------------------------------------------===// 5060 5061 namespace { 5062 5063 class HexagonABIInfo : public ABIInfo { 5064 5065 5066 public: 5067 HexagonABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {} 5068 5069 private: 5070 5071 ABIArgInfo classifyReturnType(QualType RetTy) const; 5072 ABIArgInfo classifyArgumentType(QualType RetTy) const; 5073 5074 virtual void computeInfo(CGFunctionInfo &FI) const; 5075 5076 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 5077 CodeGenFunction &CGF) const; 5078 }; 5079 5080 class HexagonTargetCodeGenInfo : public TargetCodeGenInfo { 5081 public: 5082 HexagonTargetCodeGenInfo(CodeGenTypes &CGT) 5083 :TargetCodeGenInfo(new HexagonABIInfo(CGT)) {} 5084 5085 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const { 5086 return 29; 5087 } 5088 }; 5089 5090 } 5091 5092 void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const { 5093 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 5094 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end(); 5095 it != ie; ++it) 5096 it->info = classifyArgumentType(it->type); 5097 } 5098 5099 ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty) const { 5100 if (!isAggregateTypeForABI(Ty)) { 5101 // Treat an enum type as its underlying type. 5102 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 5103 Ty = EnumTy->getDecl()->getIntegerType(); 5104 5105 return (Ty->isPromotableIntegerType() ? 5106 ABIArgInfo::getExtend() : ABIArgInfo::getDirect()); 5107 } 5108 5109 // Ignore empty records. 5110 if (isEmptyRecord(getContext(), Ty, true)) 5111 return ABIArgInfo::getIgnore(); 5112 5113 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 5114 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory); 5115 5116 uint64_t Size = getContext().getTypeSize(Ty); 5117 if (Size > 64) 5118 return ABIArgInfo::getIndirect(0, /*ByVal=*/true); 5119 // Pass in the smallest viable integer type. 5120 else if (Size > 32) 5121 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext())); 5122 else if (Size > 16) 5123 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext())); 5124 else if (Size > 8) 5125 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext())); 5126 else 5127 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext())); 5128 } 5129 5130 ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const { 5131 if (RetTy->isVoidType()) 5132 return ABIArgInfo::getIgnore(); 5133 5134 // Large vector types should be returned via memory. 5135 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 64) 5136 return ABIArgInfo::getIndirect(0); 5137 5138 if (!isAggregateTypeForABI(RetTy)) { 5139 // Treat an enum type as its underlying type. 5140 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 5141 RetTy = EnumTy->getDecl()->getIntegerType(); 5142 5143 return (RetTy->isPromotableIntegerType() ? 5144 ABIArgInfo::getExtend() : ABIArgInfo::getDirect()); 5145 } 5146 5147 // Structures with either a non-trivial destructor or a non-trivial 5148 // copy constructor are always indirect. 5149 if (isRecordReturnIndirect(RetTy, getCXXABI())) 5150 return ABIArgInfo::getIndirect(0, /*ByVal=*/false); 5151 5152 if (isEmptyRecord(getContext(), RetTy, true)) 5153 return ABIArgInfo::getIgnore(); 5154 5155 // Aggregates <= 8 bytes are returned in r0; other aggregates 5156 // are returned indirectly. 5157 uint64_t Size = getContext().getTypeSize(RetTy); 5158 if (Size <= 64) { 5159 // Return in the smallest viable integer type. 5160 if (Size <= 8) 5161 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext())); 5162 if (Size <= 16) 5163 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext())); 5164 if (Size <= 32) 5165 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext())); 5166 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext())); 5167 } 5168 5169 return ABIArgInfo::getIndirect(0, /*ByVal=*/true); 5170 } 5171 5172 llvm::Value *HexagonABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 5173 CodeGenFunction &CGF) const { 5174 // FIXME: Need to handle alignment 5175 llvm::Type *BPP = CGF.Int8PtrPtrTy; 5176 5177 CGBuilderTy &Builder = CGF.Builder; 5178 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, 5179 "ap"); 5180 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur"); 5181 llvm::Type *PTy = 5182 llvm::PointerType::getUnqual(CGF.ConvertType(Ty)); 5183 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy); 5184 5185 uint64_t Offset = 5186 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 4); 5187 llvm::Value *NextAddr = 5188 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset), 5189 "ap.next"); 5190 Builder.CreateStore(NextAddr, VAListAddrAsBPP); 5191 5192 return AddrTyped; 5193 } 5194 5195 5196 //===----------------------------------------------------------------------===// 5197 // SPARC v9 ABI Implementation. 5198 // Based on the SPARC Compliance Definition version 2.4.1. 5199 // 5200 // Function arguments a mapped to a nominal "parameter array" and promoted to 5201 // registers depending on their type. Each argument occupies 8 or 16 bytes in 5202 // the array, structs larger than 16 bytes are passed indirectly. 5203 // 5204 // One case requires special care: 5205 // 5206 // struct mixed { 5207 // int i; 5208 // float f; 5209 // }; 5210 // 5211 // When a struct mixed is passed by value, it only occupies 8 bytes in the 5212 // parameter array, but the int is passed in an integer register, and the float 5213 // is passed in a floating point register. This is represented as two arguments 5214 // with the LLVM IR inreg attribute: 5215 // 5216 // declare void f(i32 inreg %i, float inreg %f) 5217 // 5218 // The code generator will only allocate 4 bytes from the parameter array for 5219 // the inreg arguments. All other arguments are allocated a multiple of 8 5220 // bytes. 5221 // 5222 namespace { 5223 class SparcV9ABIInfo : public ABIInfo { 5224 public: 5225 SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {} 5226 5227 private: 5228 ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const; 5229 virtual void computeInfo(CGFunctionInfo &FI) const; 5230 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 5231 CodeGenFunction &CGF) const; 5232 5233 // Coercion type builder for structs passed in registers. The coercion type 5234 // serves two purposes: 5235 // 5236 // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned' 5237 // in registers. 5238 // 2. Expose aligned floating point elements as first-level elements, so the 5239 // code generator knows to pass them in floating point registers. 5240 // 5241 // We also compute the InReg flag which indicates that the struct contains 5242 // aligned 32-bit floats. 5243 // 5244 struct CoerceBuilder { 5245 llvm::LLVMContext &Context; 5246 const llvm::DataLayout &DL; 5247 SmallVector<llvm::Type*, 8> Elems; 5248 uint64_t Size; 5249 bool InReg; 5250 5251 CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl) 5252 : Context(c), DL(dl), Size(0), InReg(false) {} 5253 5254 // Pad Elems with integers until Size is ToSize. 5255 void pad(uint64_t ToSize) { 5256 assert(ToSize >= Size && "Cannot remove elements"); 5257 if (ToSize == Size) 5258 return; 5259 5260 // Finish the current 64-bit word. 5261 uint64_t Aligned = llvm::RoundUpToAlignment(Size, 64); 5262 if (Aligned > Size && Aligned <= ToSize) { 5263 Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size)); 5264 Size = Aligned; 5265 } 5266 5267 // Add whole 64-bit words. 5268 while (Size + 64 <= ToSize) { 5269 Elems.push_back(llvm::Type::getInt64Ty(Context)); 5270 Size += 64; 5271 } 5272 5273 // Final in-word padding. 5274 if (Size < ToSize) { 5275 Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size)); 5276 Size = ToSize; 5277 } 5278 } 5279 5280 // Add a floating point element at Offset. 5281 void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) { 5282 // Unaligned floats are treated as integers. 5283 if (Offset % Bits) 5284 return; 5285 // The InReg flag is only required if there are any floats < 64 bits. 5286 if (Bits < 64) 5287 InReg = true; 5288 pad(Offset); 5289 Elems.push_back(Ty); 5290 Size = Offset + Bits; 5291 } 5292 5293 // Add a struct type to the coercion type, starting at Offset (in bits). 5294 void addStruct(uint64_t Offset, llvm::StructType *StrTy) { 5295 const llvm::StructLayout *Layout = DL.getStructLayout(StrTy); 5296 for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) { 5297 llvm::Type *ElemTy = StrTy->getElementType(i); 5298 uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i); 5299 switch (ElemTy->getTypeID()) { 5300 case llvm::Type::StructTyID: 5301 addStruct(ElemOffset, cast<llvm::StructType>(ElemTy)); 5302 break; 5303 case llvm::Type::FloatTyID: 5304 addFloat(ElemOffset, ElemTy, 32); 5305 break; 5306 case llvm::Type::DoubleTyID: 5307 addFloat(ElemOffset, ElemTy, 64); 5308 break; 5309 case llvm::Type::FP128TyID: 5310 addFloat(ElemOffset, ElemTy, 128); 5311 break; 5312 case llvm::Type::PointerTyID: 5313 if (ElemOffset % 64 == 0) { 5314 pad(ElemOffset); 5315 Elems.push_back(ElemTy); 5316 Size += 64; 5317 } 5318 break; 5319 default: 5320 break; 5321 } 5322 } 5323 } 5324 5325 // Check if Ty is a usable substitute for the coercion type. 5326 bool isUsableType(llvm::StructType *Ty) const { 5327 if (Ty->getNumElements() != Elems.size()) 5328 return false; 5329 for (unsigned i = 0, e = Elems.size(); i != e; ++i) 5330 if (Elems[i] != Ty->getElementType(i)) 5331 return false; 5332 return true; 5333 } 5334 5335 // Get the coercion type as a literal struct type. 5336 llvm::Type *getType() const { 5337 if (Elems.size() == 1) 5338 return Elems.front(); 5339 else 5340 return llvm::StructType::get(Context, Elems); 5341 } 5342 }; 5343 }; 5344 } // end anonymous namespace 5345 5346 ABIArgInfo 5347 SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const { 5348 if (Ty->isVoidType()) 5349 return ABIArgInfo::getIgnore(); 5350 5351 uint64_t Size = getContext().getTypeSize(Ty); 5352 5353 // Anything too big to fit in registers is passed with an explicit indirect 5354 // pointer / sret pointer. 5355 if (Size > SizeLimit) 5356 return ABIArgInfo::getIndirect(0, /*ByVal=*/false); 5357 5358 // Treat an enum type as its underlying type. 5359 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 5360 Ty = EnumTy->getDecl()->getIntegerType(); 5361 5362 // Integer types smaller than a register are extended. 5363 if (Size < 64 && Ty->isIntegerType()) 5364 return ABIArgInfo::getExtend(); 5365 5366 // Other non-aggregates go in registers. 5367 if (!isAggregateTypeForABI(Ty)) 5368 return ABIArgInfo::getDirect(); 5369 5370 // If a C++ object has either a non-trivial copy constructor or a non-trivial 5371 // destructor, it is passed with an explicit indirect pointer / sret pointer. 5372 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 5373 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory); 5374 5375 // This is a small aggregate type that should be passed in registers. 5376 // Build a coercion type from the LLVM struct type. 5377 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty)); 5378 if (!StrTy) 5379 return ABIArgInfo::getDirect(); 5380 5381 CoerceBuilder CB(getVMContext(), getDataLayout()); 5382 CB.addStruct(0, StrTy); 5383 CB.pad(llvm::RoundUpToAlignment(CB.DL.getTypeSizeInBits(StrTy), 64)); 5384 5385 // Try to use the original type for coercion. 5386 llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType(); 5387 5388 if (CB.InReg) 5389 return ABIArgInfo::getDirectInReg(CoerceTy); 5390 else 5391 return ABIArgInfo::getDirect(CoerceTy); 5392 } 5393 5394 llvm::Value *SparcV9ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 5395 CodeGenFunction &CGF) const { 5396 ABIArgInfo AI = classifyType(Ty, 16 * 8); 5397 llvm::Type *ArgTy = CGT.ConvertType(Ty); 5398 if (AI.canHaveCoerceToType() && !AI.getCoerceToType()) 5399 AI.setCoerceToType(ArgTy); 5400 5401 llvm::Type *BPP = CGF.Int8PtrPtrTy; 5402 CGBuilderTy &Builder = CGF.Builder; 5403 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap"); 5404 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur"); 5405 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy); 5406 llvm::Value *ArgAddr; 5407 unsigned Stride; 5408 5409 switch (AI.getKind()) { 5410 case ABIArgInfo::Expand: 5411 llvm_unreachable("Unsupported ABI kind for va_arg"); 5412 5413 case ABIArgInfo::Extend: 5414 Stride = 8; 5415 ArgAddr = Builder 5416 .CreateConstGEP1_32(Addr, 8 - getDataLayout().getTypeAllocSize(ArgTy), 5417 "extend"); 5418 break; 5419 5420 case ABIArgInfo::Direct: 5421 Stride = getDataLayout().getTypeAllocSize(AI.getCoerceToType()); 5422 ArgAddr = Addr; 5423 break; 5424 5425 case ABIArgInfo::Indirect: 5426 Stride = 8; 5427 ArgAddr = Builder.CreateBitCast(Addr, 5428 llvm::PointerType::getUnqual(ArgPtrTy), 5429 "indirect"); 5430 ArgAddr = Builder.CreateLoad(ArgAddr, "indirect.arg"); 5431 break; 5432 5433 case ABIArgInfo::Ignore: 5434 return llvm::UndefValue::get(ArgPtrTy); 5435 } 5436 5437 // Update VAList. 5438 Addr = Builder.CreateConstGEP1_32(Addr, Stride, "ap.next"); 5439 Builder.CreateStore(Addr, VAListAddrAsBPP); 5440 5441 return Builder.CreatePointerCast(ArgAddr, ArgPtrTy, "arg.addr"); 5442 } 5443 5444 void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const { 5445 FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8); 5446 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end(); 5447 it != ie; ++it) 5448 it->info = classifyType(it->type, 16 * 8); 5449 } 5450 5451 namespace { 5452 class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo { 5453 public: 5454 SparcV9TargetCodeGenInfo(CodeGenTypes &CGT) 5455 : TargetCodeGenInfo(new SparcV9ABIInfo(CGT)) {} 5456 }; 5457 } // end anonymous namespace 5458 5459 5460 //===----------------------------------------------------------------------===// 5461 // Xcore ABI Implementation 5462 //===----------------------------------------------------------------------===// 5463 namespace { 5464 class XCoreABIInfo : public DefaultABIInfo { 5465 public: 5466 XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {} 5467 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 5468 CodeGenFunction &CGF) const; 5469 }; 5470 5471 class XcoreTargetCodeGenInfo : public TargetCodeGenInfo { 5472 public: 5473 XcoreTargetCodeGenInfo(CodeGenTypes &CGT) 5474 :TargetCodeGenInfo(new XCoreABIInfo(CGT)) {} 5475 }; 5476 } // End anonymous namespace. 5477 5478 llvm::Value *XCoreABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty, 5479 CodeGenFunction &CGF) const { 5480 CGBuilderTy &Builder = CGF.Builder; 5481 5482 // Get the VAList. 5483 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, 5484 CGF.Int8PtrPtrTy); 5485 llvm::Value *AP = Builder.CreateLoad(VAListAddrAsBPP); 5486 5487 // Handle the argument. 5488 ABIArgInfo AI = classifyArgumentType(Ty); 5489 llvm::Type *ArgTy = CGT.ConvertType(Ty); 5490 if (AI.canHaveCoerceToType() && !AI.getCoerceToType()) 5491 AI.setCoerceToType(ArgTy); 5492 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy); 5493 llvm::Value *Val; 5494 uint64_t ArgSize = 0; 5495 switch (AI.getKind()) { 5496 case ABIArgInfo::Expand: 5497 llvm_unreachable("Unsupported ABI kind for va_arg"); 5498 case ABIArgInfo::Ignore: 5499 Val = llvm::UndefValue::get(ArgPtrTy); 5500 ArgSize = 0; 5501 break; 5502 case ABIArgInfo::Extend: 5503 case ABIArgInfo::Direct: 5504 Val = Builder.CreatePointerCast(AP, ArgPtrTy); 5505 ArgSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType()); 5506 if (ArgSize < 4) 5507 ArgSize = 4; 5508 break; 5509 case ABIArgInfo::Indirect: 5510 llvm::Value *ArgAddr; 5511 ArgAddr = Builder.CreateBitCast(AP, llvm::PointerType::getUnqual(ArgPtrTy)); 5512 ArgAddr = Builder.CreateLoad(ArgAddr); 5513 Val = Builder.CreatePointerCast(ArgAddr, ArgPtrTy); 5514 ArgSize = 4; 5515 break; 5516 } 5517 5518 // Increment the VAList. 5519 if (ArgSize) { 5520 llvm::Value *APN = Builder.CreateConstGEP1_32(AP, ArgSize); 5521 Builder.CreateStore(APN, VAListAddrAsBPP); 5522 } 5523 return Val; 5524 } 5525 5526 //===----------------------------------------------------------------------===// 5527 // Driver code 5528 //===----------------------------------------------------------------------===// 5529 5530 const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() { 5531 if (TheTargetCodeGenInfo) 5532 return *TheTargetCodeGenInfo; 5533 5534 const llvm::Triple &Triple = getTarget().getTriple(); 5535 switch (Triple.getArch()) { 5536 default: 5537 return *(TheTargetCodeGenInfo = new DefaultTargetCodeGenInfo(Types)); 5538 5539 case llvm::Triple::le32: 5540 return *(TheTargetCodeGenInfo = new PNaClTargetCodeGenInfo(Types)); 5541 case llvm::Triple::mips: 5542 case llvm::Triple::mipsel: 5543 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, true)); 5544 5545 case llvm::Triple::mips64: 5546 case llvm::Triple::mips64el: 5547 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, false)); 5548 5549 case llvm::Triple::aarch64: 5550 return *(TheTargetCodeGenInfo = new AArch64TargetCodeGenInfo(Types)); 5551 5552 case llvm::Triple::arm: 5553 case llvm::Triple::thumb: 5554 { 5555 ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS; 5556 if (strcmp(getTarget().getABI(), "apcs-gnu") == 0) 5557 Kind = ARMABIInfo::APCS; 5558 else if (CodeGenOpts.FloatABI == "hard" || 5559 (CodeGenOpts.FloatABI != "soft" && 5560 Triple.getEnvironment() == llvm::Triple::GNUEABIHF)) 5561 Kind = ARMABIInfo::AAPCS_VFP; 5562 5563 switch (Triple.getOS()) { 5564 case llvm::Triple::NaCl: 5565 return *(TheTargetCodeGenInfo = 5566 new NaClARMTargetCodeGenInfo(Types, Kind)); 5567 default: 5568 return *(TheTargetCodeGenInfo = 5569 new ARMTargetCodeGenInfo(Types, Kind)); 5570 } 5571 } 5572 5573 case llvm::Triple::ppc: 5574 return *(TheTargetCodeGenInfo = new PPC32TargetCodeGenInfo(Types)); 5575 case llvm::Triple::ppc64: 5576 if (Triple.isOSBinFormatELF()) 5577 return *(TheTargetCodeGenInfo = new PPC64_SVR4_TargetCodeGenInfo(Types)); 5578 else 5579 return *(TheTargetCodeGenInfo = new PPC64TargetCodeGenInfo(Types)); 5580 case llvm::Triple::ppc64le: 5581 assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!"); 5582 return *(TheTargetCodeGenInfo = new PPC64_SVR4_TargetCodeGenInfo(Types)); 5583 5584 case llvm::Triple::nvptx: 5585 case llvm::Triple::nvptx64: 5586 return *(TheTargetCodeGenInfo = new NVPTXTargetCodeGenInfo(Types)); 5587 5588 case llvm::Triple::msp430: 5589 return *(TheTargetCodeGenInfo = new MSP430TargetCodeGenInfo(Types)); 5590 5591 case llvm::Triple::systemz: 5592 return *(TheTargetCodeGenInfo = new SystemZTargetCodeGenInfo(Types)); 5593 5594 case llvm::Triple::tce: 5595 return *(TheTargetCodeGenInfo = new TCETargetCodeGenInfo(Types)); 5596 5597 case llvm::Triple::x86: { 5598 bool IsDarwinVectorABI = Triple.isOSDarwin(); 5599 bool IsSmallStructInRegABI = 5600 X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts); 5601 bool IsWin32FloatStructABI = (Triple.getOS() == llvm::Triple::Win32); 5602 5603 if (Triple.getOS() == llvm::Triple::Win32) { 5604 return *(TheTargetCodeGenInfo = 5605 new WinX86_32TargetCodeGenInfo(Types, 5606 IsDarwinVectorABI, IsSmallStructInRegABI, 5607 IsWin32FloatStructABI, 5608 CodeGenOpts.NumRegisterParameters)); 5609 } else { 5610 return *(TheTargetCodeGenInfo = 5611 new X86_32TargetCodeGenInfo(Types, 5612 IsDarwinVectorABI, IsSmallStructInRegABI, 5613 IsWin32FloatStructABI, 5614 CodeGenOpts.NumRegisterParameters)); 5615 } 5616 } 5617 5618 case llvm::Triple::x86_64: { 5619 bool HasAVX = strcmp(getTarget().getABI(), "avx") == 0; 5620 5621 switch (Triple.getOS()) { 5622 case llvm::Triple::Win32: 5623 case llvm::Triple::MinGW32: 5624 case llvm::Triple::Cygwin: 5625 return *(TheTargetCodeGenInfo = new WinX86_64TargetCodeGenInfo(Types)); 5626 case llvm::Triple::NaCl: 5627 return *(TheTargetCodeGenInfo = new NaClX86_64TargetCodeGenInfo(Types, 5628 HasAVX)); 5629 default: 5630 return *(TheTargetCodeGenInfo = new X86_64TargetCodeGenInfo(Types, 5631 HasAVX)); 5632 } 5633 } 5634 case llvm::Triple::hexagon: 5635 return *(TheTargetCodeGenInfo = new HexagonTargetCodeGenInfo(Types)); 5636 case llvm::Triple::sparcv9: 5637 return *(TheTargetCodeGenInfo = new SparcV9TargetCodeGenInfo(Types)); 5638 case llvm::Triple::xcore: 5639 return *(TheTargetCodeGenInfo = new XcoreTargetCodeGenInfo(Types)); 5640 5641 } 5642 } 5643