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