1 //===--- CGDebugInfo.cpp - Emit Debug Information for a Module ------------===// 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 // This coordinates the debug information generation while generating code. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "CGDebugInfo.h" 15 #include "CGBlocks.h" 16 #include "CGCXXABI.h" 17 #include "CGObjCRuntime.h" 18 #include "CodeGenFunction.h" 19 #include "CodeGenModule.h" 20 #include "clang/AST/ASTContext.h" 21 #include "clang/AST/DeclFriend.h" 22 #include "clang/AST/DeclObjC.h" 23 #include "clang/AST/DeclTemplate.h" 24 #include "clang/AST/Expr.h" 25 #include "clang/AST/RecordLayout.h" 26 #include "clang/Basic/FileManager.h" 27 #include "clang/Basic/SourceManager.h" 28 #include "clang/Basic/Version.h" 29 #include "clang/Frontend/CodeGenOptions.h" 30 #include "clang/Lex/HeaderSearchOptions.h" 31 #include "clang/Lex/PreprocessorOptions.h" 32 #include "llvm/ADT/SmallVector.h" 33 #include "llvm/ADT/StringExtras.h" 34 #include "llvm/IR/Constants.h" 35 #include "llvm/IR/DataLayout.h" 36 #include "llvm/IR/DerivedTypes.h" 37 #include "llvm/IR/Instructions.h" 38 #include "llvm/IR/Intrinsics.h" 39 #include "llvm/IR/Module.h" 40 #include "llvm/Support/FileSystem.h" 41 #include "llvm/Support/Path.h" 42 using namespace clang; 43 using namespace clang::CodeGen; 44 45 CGDebugInfo::CGDebugInfo(CodeGenModule &CGM) 46 : CGM(CGM), DebugKind(CGM.getCodeGenOpts().getDebugInfo()), 47 DebugTypeExtRefs(CGM.getCodeGenOpts().DebugTypeExtRefs), 48 DBuilder(CGM.getModule()) { 49 CreateCompileUnit(); 50 } 51 52 CGDebugInfo::~CGDebugInfo() { 53 assert(LexicalBlockStack.empty() && 54 "Region stack mismatch, stack not empty!"); 55 } 56 57 ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF, 58 SourceLocation TemporaryLocation) 59 : CGF(&CGF) { 60 init(TemporaryLocation); 61 } 62 63 ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF, 64 bool DefaultToEmpty, 65 SourceLocation TemporaryLocation) 66 : CGF(&CGF) { 67 init(TemporaryLocation, DefaultToEmpty); 68 } 69 70 void ApplyDebugLocation::init(SourceLocation TemporaryLocation, 71 bool DefaultToEmpty) { 72 auto *DI = CGF->getDebugInfo(); 73 if (!DI) { 74 CGF = nullptr; 75 return; 76 } 77 78 OriginalLocation = CGF->Builder.getCurrentDebugLocation(); 79 if (TemporaryLocation.isValid()) { 80 DI->EmitLocation(CGF->Builder, TemporaryLocation); 81 return; 82 } 83 84 if (DefaultToEmpty) { 85 CGF->Builder.SetCurrentDebugLocation(llvm::DebugLoc()); 86 return; 87 } 88 89 // Construct a location that has a valid scope, but no line info. 90 assert(!DI->LexicalBlockStack.empty()); 91 CGF->Builder.SetCurrentDebugLocation( 92 llvm::DebugLoc::get(0, 0, DI->LexicalBlockStack.back())); 93 } 94 95 ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF, const Expr *E) 96 : CGF(&CGF) { 97 init(E->getExprLoc()); 98 } 99 100 ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF, llvm::DebugLoc Loc) 101 : CGF(&CGF) { 102 if (!CGF.getDebugInfo()) { 103 this->CGF = nullptr; 104 return; 105 } 106 OriginalLocation = CGF.Builder.getCurrentDebugLocation(); 107 if (Loc) 108 CGF.Builder.SetCurrentDebugLocation(std::move(Loc)); 109 } 110 111 ApplyDebugLocation::~ApplyDebugLocation() { 112 // Query CGF so the location isn't overwritten when location updates are 113 // temporarily disabled (for C++ default function arguments) 114 if (CGF) 115 CGF->Builder.SetCurrentDebugLocation(std::move(OriginalLocation)); 116 } 117 118 void CGDebugInfo::setLocation(SourceLocation Loc) { 119 // If the new location isn't valid return. 120 if (Loc.isInvalid()) 121 return; 122 123 CurLoc = CGM.getContext().getSourceManager().getExpansionLoc(Loc); 124 125 // If we've changed files in the middle of a lexical scope go ahead 126 // and create a new lexical scope with file node if it's different 127 // from the one in the scope. 128 if (LexicalBlockStack.empty()) 129 return; 130 131 SourceManager &SM = CGM.getContext().getSourceManager(); 132 auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back()); 133 PresumedLoc PCLoc = SM.getPresumedLoc(CurLoc); 134 135 if (PCLoc.isInvalid() || Scope->getFilename() == PCLoc.getFilename()) 136 return; 137 138 if (auto *LBF = dyn_cast<llvm::DILexicalBlockFile>(Scope)) { 139 LexicalBlockStack.pop_back(); 140 LexicalBlockStack.emplace_back(DBuilder.createLexicalBlockFile( 141 LBF->getScope(), getOrCreateFile(CurLoc))); 142 } else if (isa<llvm::DILexicalBlock>(Scope) || 143 isa<llvm::DISubprogram>(Scope)) { 144 LexicalBlockStack.pop_back(); 145 LexicalBlockStack.emplace_back( 146 DBuilder.createLexicalBlockFile(Scope, getOrCreateFile(CurLoc))); 147 } 148 } 149 150 llvm::DIScope *CGDebugInfo::getDeclContextDescriptor(const Decl *D) { 151 llvm::DIScope *Mod = getParentModuleOrNull(D); 152 return getContextDescriptor(cast<Decl>(D->getDeclContext()), 153 Mod ? Mod : TheCU); 154 } 155 156 llvm::DIScope *CGDebugInfo::getContextDescriptor(const Decl *Context, 157 llvm::DIScope *Default) { 158 if (!Context) 159 return Default; 160 161 auto I = RegionMap.find(Context); 162 if (I != RegionMap.end()) { 163 llvm::Metadata *V = I->second; 164 return dyn_cast_or_null<llvm::DIScope>(V); 165 } 166 167 // Check namespace. 168 if (const NamespaceDecl *NSDecl = dyn_cast<NamespaceDecl>(Context)) 169 return getOrCreateNameSpace(NSDecl); 170 171 if (const RecordDecl *RDecl = dyn_cast<RecordDecl>(Context)) 172 if (!RDecl->isDependentType()) 173 return getOrCreateType(CGM.getContext().getTypeDeclType(RDecl), 174 getOrCreateMainFile()); 175 return Default; 176 } 177 178 StringRef CGDebugInfo::getFunctionName(const FunctionDecl *FD) { 179 assert(FD && "Invalid FunctionDecl!"); 180 IdentifierInfo *FII = FD->getIdentifier(); 181 FunctionTemplateSpecializationInfo *Info = 182 FD->getTemplateSpecializationInfo(); 183 if (!Info && FII) 184 return FII->getName(); 185 186 // Otherwise construct human readable name for debug info. 187 SmallString<128> NS; 188 llvm::raw_svector_ostream OS(NS); 189 FD->printName(OS); 190 191 // Add any template specialization args. 192 if (Info) { 193 const TemplateArgumentList *TArgs = Info->TemplateArguments; 194 const TemplateArgument *Args = TArgs->data(); 195 unsigned NumArgs = TArgs->size(); 196 PrintingPolicy Policy(CGM.getLangOpts()); 197 TemplateSpecializationType::PrintTemplateArgumentList(OS, Args, NumArgs, 198 Policy); 199 } 200 201 // Copy this name on the side and use its reference. 202 return internString(OS.str()); 203 } 204 205 StringRef CGDebugInfo::getObjCMethodName(const ObjCMethodDecl *OMD) { 206 SmallString<256> MethodName; 207 llvm::raw_svector_ostream OS(MethodName); 208 OS << (OMD->isInstanceMethod() ? '-' : '+') << '['; 209 const DeclContext *DC = OMD->getDeclContext(); 210 if (const ObjCImplementationDecl *OID = 211 dyn_cast<const ObjCImplementationDecl>(DC)) { 212 OS << OID->getName(); 213 } else if (const ObjCInterfaceDecl *OID = 214 dyn_cast<const ObjCInterfaceDecl>(DC)) { 215 OS << OID->getName(); 216 } else if (const ObjCCategoryImplDecl *OCD = 217 dyn_cast<const ObjCCategoryImplDecl>(DC)) { 218 OS << ((const NamedDecl *)OCD)->getIdentifier()->getNameStart() << '(' 219 << OCD->getIdentifier()->getNameStart() << ')'; 220 } else if (isa<ObjCProtocolDecl>(DC)) { 221 // We can extract the type of the class from the self pointer. 222 if (ImplicitParamDecl *SelfDecl = OMD->getSelfDecl()) { 223 QualType ClassTy = 224 cast<ObjCObjectPointerType>(SelfDecl->getType())->getPointeeType(); 225 ClassTy.print(OS, PrintingPolicy(LangOptions())); 226 } 227 } 228 OS << ' ' << OMD->getSelector().getAsString() << ']'; 229 230 return internString(OS.str()); 231 } 232 233 StringRef CGDebugInfo::getSelectorName(Selector S) { 234 return internString(S.getAsString()); 235 } 236 237 StringRef CGDebugInfo::getClassName(const RecordDecl *RD) { 238 // quick optimization to avoid having to intern strings that are already 239 // stored reliably elsewhere 240 if (!isa<ClassTemplateSpecializationDecl>(RD)) 241 return RD->getName(); 242 243 SmallString<128> Name; 244 { 245 llvm::raw_svector_ostream OS(Name); 246 RD->getNameForDiagnostic(OS, CGM.getContext().getPrintingPolicy(), 247 /*Qualified*/ false); 248 } 249 250 // Copy this name on the side and use its reference. 251 return internString(Name); 252 } 253 254 llvm::DIFile *CGDebugInfo::getOrCreateFile(SourceLocation Loc) { 255 if (!Loc.isValid()) 256 // If Location is not valid then use main input file. 257 return DBuilder.createFile(TheCU->getFilename(), TheCU->getDirectory()); 258 259 SourceManager &SM = CGM.getContext().getSourceManager(); 260 PresumedLoc PLoc = SM.getPresumedLoc(Loc); 261 262 if (PLoc.isInvalid() || StringRef(PLoc.getFilename()).empty()) 263 // If the location is not valid then use main input file. 264 return DBuilder.createFile(TheCU->getFilename(), TheCU->getDirectory()); 265 266 // Cache the results. 267 const char *fname = PLoc.getFilename(); 268 auto it = DIFileCache.find(fname); 269 270 if (it != DIFileCache.end()) { 271 // Verify that the information still exists. 272 if (llvm::Metadata *V = it->second) 273 return cast<llvm::DIFile>(V); 274 } 275 276 llvm::DIFile *F = 277 DBuilder.createFile(PLoc.getFilename(), getCurrentDirname()); 278 279 DIFileCache[fname].reset(F); 280 return F; 281 } 282 283 llvm::DIFile *CGDebugInfo::getOrCreateMainFile() { 284 return DBuilder.createFile(TheCU->getFilename(), TheCU->getDirectory()); 285 } 286 287 unsigned CGDebugInfo::getLineNumber(SourceLocation Loc) { 288 if (Loc.isInvalid() && CurLoc.isInvalid()) 289 return 0; 290 SourceManager &SM = CGM.getContext().getSourceManager(); 291 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc); 292 return PLoc.isValid() ? PLoc.getLine() : 0; 293 } 294 295 unsigned CGDebugInfo::getColumnNumber(SourceLocation Loc, bool Force) { 296 // We may not want column information at all. 297 if (!Force && !CGM.getCodeGenOpts().DebugColumnInfo) 298 return 0; 299 300 // If the location is invalid then use the current column. 301 if (Loc.isInvalid() && CurLoc.isInvalid()) 302 return 0; 303 SourceManager &SM = CGM.getContext().getSourceManager(); 304 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc); 305 return PLoc.isValid() ? PLoc.getColumn() : 0; 306 } 307 308 StringRef CGDebugInfo::getCurrentDirname() { 309 if (!CGM.getCodeGenOpts().DebugCompilationDir.empty()) 310 return CGM.getCodeGenOpts().DebugCompilationDir; 311 312 if (!CWDName.empty()) 313 return CWDName; 314 SmallString<256> CWD; 315 llvm::sys::fs::current_path(CWD); 316 return CWDName = internString(CWD); 317 } 318 319 void CGDebugInfo::CreateCompileUnit() { 320 321 // Should we be asking the SourceManager for the main file name, instead of 322 // accepting it as an argument? This just causes the main file name to 323 // mismatch with source locations and create extra lexical scopes or 324 // mismatched debug info (a CU with a DW_AT_file of "-", because that's what 325 // the driver passed, but functions/other things have DW_AT_file of "<stdin>" 326 // because that's what the SourceManager says) 327 328 // Get absolute path name. 329 SourceManager &SM = CGM.getContext().getSourceManager(); 330 std::string MainFileName = CGM.getCodeGenOpts().MainFileName; 331 if (MainFileName.empty()) 332 MainFileName = "<stdin>"; 333 334 // The main file name provided via the "-main-file-name" option contains just 335 // the file name itself with no path information. This file name may have had 336 // a relative path, so we look into the actual file entry for the main 337 // file to determine the real absolute path for the file. 338 std::string MainFileDir; 339 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) { 340 MainFileDir = MainFile->getDir()->getName(); 341 if (MainFileDir != ".") { 342 llvm::SmallString<1024> MainFileDirSS(MainFileDir); 343 llvm::sys::path::append(MainFileDirSS, MainFileName); 344 MainFileName = MainFileDirSS.str(); 345 } 346 } 347 348 llvm::dwarf::SourceLanguage LangTag; 349 const LangOptions &LO = CGM.getLangOpts(); 350 if (LO.CPlusPlus) { 351 if (LO.ObjC1) 352 LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus; 353 else 354 LangTag = llvm::dwarf::DW_LANG_C_plus_plus; 355 } else if (LO.ObjC1) { 356 LangTag = llvm::dwarf::DW_LANG_ObjC; 357 } else if (LO.C99) { 358 LangTag = llvm::dwarf::DW_LANG_C99; 359 } else { 360 LangTag = llvm::dwarf::DW_LANG_C89; 361 } 362 363 std::string Producer = getClangFullVersion(); 364 365 // Figure out which version of the ObjC runtime we have. 366 unsigned RuntimeVers = 0; 367 if (LO.ObjC1) 368 RuntimeVers = LO.ObjCRuntime.isNonFragile() ? 2 : 1; 369 370 // Create new compile unit. 371 // FIXME - Eliminate TheCU. 372 TheCU = DBuilder.createCompileUnit( 373 LangTag, MainFileName, getCurrentDirname(), Producer, LO.Optimize, 374 CGM.getCodeGenOpts().DwarfDebugFlags, RuntimeVers, 375 CGM.getCodeGenOpts().SplitDwarfFile, 376 DebugKind <= CodeGenOptions::DebugLineTablesOnly 377 ? llvm::DIBuilder::LineTablesOnly 378 : llvm::DIBuilder::FullDebug, 379 0 /* DWOid */, DebugKind != CodeGenOptions::LocTrackingOnly); 380 } 381 382 llvm::DIType *CGDebugInfo::CreateType(const BuiltinType *BT) { 383 llvm::dwarf::TypeKind Encoding; 384 StringRef BTName; 385 switch (BT->getKind()) { 386 #define BUILTIN_TYPE(Id, SingletonId) 387 #define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id: 388 #include "clang/AST/BuiltinTypes.def" 389 case BuiltinType::Dependent: 390 llvm_unreachable("Unexpected builtin type"); 391 case BuiltinType::NullPtr: 392 return DBuilder.createNullPtrType(); 393 case BuiltinType::Void: 394 return nullptr; 395 case BuiltinType::ObjCClass: 396 if (!ClassTy) 397 ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, 398 "objc_class", TheCU, 399 getOrCreateMainFile(), 0); 400 return ClassTy; 401 case BuiltinType::ObjCId: { 402 // typedef struct objc_class *Class; 403 // typedef struct objc_object { 404 // Class isa; 405 // } *id; 406 407 if (ObjTy) 408 return ObjTy; 409 410 if (!ClassTy) 411 ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, 412 "objc_class", TheCU, 413 getOrCreateMainFile(), 0); 414 415 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy); 416 417 auto *ISATy = DBuilder.createPointerType(ClassTy, Size); 418 419 ObjTy = 420 DBuilder.createStructType(TheCU, "objc_object", getOrCreateMainFile(), 421 0, 0, 0, 0, nullptr, llvm::DINodeArray()); 422 423 DBuilder.replaceArrays( 424 ObjTy, 425 DBuilder.getOrCreateArray(&*DBuilder.createMemberType( 426 ObjTy, "isa", getOrCreateMainFile(), 0, Size, 0, 0, 0, ISATy))); 427 return ObjTy; 428 } 429 case BuiltinType::ObjCSel: { 430 if (!SelTy) 431 SelTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, 432 "objc_selector", TheCU, 433 getOrCreateMainFile(), 0); 434 return SelTy; 435 } 436 437 case BuiltinType::OCLImage1d: 438 return getOrCreateStructPtrType("opencl_image1d_t", OCLImage1dDITy); 439 case BuiltinType::OCLImage1dArray: 440 return getOrCreateStructPtrType("opencl_image1d_array_t", 441 OCLImage1dArrayDITy); 442 case BuiltinType::OCLImage1dBuffer: 443 return getOrCreateStructPtrType("opencl_image1d_buffer_t", 444 OCLImage1dBufferDITy); 445 case BuiltinType::OCLImage2d: 446 return getOrCreateStructPtrType("opencl_image2d_t", OCLImage2dDITy); 447 case BuiltinType::OCLImage2dArray: 448 return getOrCreateStructPtrType("opencl_image2d_array_t", 449 OCLImage2dArrayDITy); 450 case BuiltinType::OCLImage3d: 451 return getOrCreateStructPtrType("opencl_image3d_t", OCLImage3dDITy); 452 case BuiltinType::OCLSampler: 453 return DBuilder.createBasicType( 454 "opencl_sampler_t", CGM.getContext().getTypeSize(BT), 455 CGM.getContext().getTypeAlign(BT), llvm::dwarf::DW_ATE_unsigned); 456 case BuiltinType::OCLEvent: 457 return getOrCreateStructPtrType("opencl_event_t", OCLEventDITy); 458 459 case BuiltinType::UChar: 460 case BuiltinType::Char_U: 461 Encoding = llvm::dwarf::DW_ATE_unsigned_char; 462 break; 463 case BuiltinType::Char_S: 464 case BuiltinType::SChar: 465 Encoding = llvm::dwarf::DW_ATE_signed_char; 466 break; 467 case BuiltinType::Char16: 468 case BuiltinType::Char32: 469 Encoding = llvm::dwarf::DW_ATE_UTF; 470 break; 471 case BuiltinType::UShort: 472 case BuiltinType::UInt: 473 case BuiltinType::UInt128: 474 case BuiltinType::ULong: 475 case BuiltinType::WChar_U: 476 case BuiltinType::ULongLong: 477 Encoding = llvm::dwarf::DW_ATE_unsigned; 478 break; 479 case BuiltinType::Short: 480 case BuiltinType::Int: 481 case BuiltinType::Int128: 482 case BuiltinType::Long: 483 case BuiltinType::WChar_S: 484 case BuiltinType::LongLong: 485 Encoding = llvm::dwarf::DW_ATE_signed; 486 break; 487 case BuiltinType::Bool: 488 Encoding = llvm::dwarf::DW_ATE_boolean; 489 break; 490 case BuiltinType::Half: 491 case BuiltinType::Float: 492 case BuiltinType::LongDouble: 493 case BuiltinType::Double: 494 Encoding = llvm::dwarf::DW_ATE_float; 495 break; 496 } 497 498 switch (BT->getKind()) { 499 case BuiltinType::Long: 500 BTName = "long int"; 501 break; 502 case BuiltinType::LongLong: 503 BTName = "long long int"; 504 break; 505 case BuiltinType::ULong: 506 BTName = "long unsigned int"; 507 break; 508 case BuiltinType::ULongLong: 509 BTName = "long long unsigned int"; 510 break; 511 default: 512 BTName = BT->getName(CGM.getLangOpts()); 513 break; 514 } 515 // Bit size, align and offset of the type. 516 uint64_t Size = CGM.getContext().getTypeSize(BT); 517 uint64_t Align = CGM.getContext().getTypeAlign(BT); 518 return DBuilder.createBasicType(BTName, Size, Align, Encoding); 519 } 520 521 llvm::DIType *CGDebugInfo::CreateType(const ComplexType *Ty) { 522 // Bit size, align and offset of the type. 523 llvm::dwarf::TypeKind Encoding = llvm::dwarf::DW_ATE_complex_float; 524 if (Ty->isComplexIntegerType()) 525 Encoding = llvm::dwarf::DW_ATE_lo_user; 526 527 uint64_t Size = CGM.getContext().getTypeSize(Ty); 528 uint64_t Align = CGM.getContext().getTypeAlign(Ty); 529 return DBuilder.createBasicType("complex", Size, Align, Encoding); 530 } 531 532 llvm::DIType *CGDebugInfo::CreateQualifiedType(QualType Ty, 533 llvm::DIFile *Unit) { 534 QualifierCollector Qc; 535 const Type *T = Qc.strip(Ty); 536 537 // Ignore these qualifiers for now. 538 Qc.removeObjCGCAttr(); 539 Qc.removeAddressSpace(); 540 Qc.removeObjCLifetime(); 541 542 // We will create one Derived type for one qualifier and recurse to handle any 543 // additional ones. 544 llvm::dwarf::Tag Tag; 545 if (Qc.hasConst()) { 546 Tag = llvm::dwarf::DW_TAG_const_type; 547 Qc.removeConst(); 548 } else if (Qc.hasVolatile()) { 549 Tag = llvm::dwarf::DW_TAG_volatile_type; 550 Qc.removeVolatile(); 551 } else if (Qc.hasRestrict()) { 552 Tag = llvm::dwarf::DW_TAG_restrict_type; 553 Qc.removeRestrict(); 554 } else { 555 assert(Qc.empty() && "Unknown type qualifier for debug info"); 556 return getOrCreateType(QualType(T, 0), Unit); 557 } 558 559 auto *FromTy = getOrCreateType(Qc.apply(CGM.getContext(), T), Unit); 560 561 // No need to fill in the Name, Line, Size, Alignment, Offset in case of 562 // CVR derived types. 563 return DBuilder.createQualifiedType(Tag, FromTy); 564 } 565 566 llvm::DIType *CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty, 567 llvm::DIFile *Unit) { 568 569 // The frontend treats 'id' as a typedef to an ObjCObjectType, 570 // whereas 'id<protocol>' is treated as an ObjCPointerType. For the 571 // debug info, we want to emit 'id' in both cases. 572 if (Ty->isObjCQualifiedIdType()) 573 return getOrCreateType(CGM.getContext().getObjCIdType(), Unit); 574 575 return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty, 576 Ty->getPointeeType(), Unit); 577 } 578 579 llvm::DIType *CGDebugInfo::CreateType(const PointerType *Ty, 580 llvm::DIFile *Unit) { 581 return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty, 582 Ty->getPointeeType(), Unit); 583 } 584 585 /// \return whether a C++ mangling exists for the type defined by TD. 586 static bool hasCXXMangling(const TagDecl *TD, llvm::DICompileUnit *TheCU) { 587 switch (TheCU->getSourceLanguage()) { 588 case llvm::dwarf::DW_LANG_C_plus_plus: 589 return true; 590 case llvm::dwarf::DW_LANG_ObjC_plus_plus: 591 return isa<CXXRecordDecl>(TD) || isa<EnumDecl>(TD); 592 default: 593 return false; 594 } 595 } 596 597 /// In C++ mode, types have linkage, so we can rely on the ODR and 598 /// on their mangled names, if they're external. 599 static SmallString<256> getUniqueTagTypeName(const TagType *Ty, 600 CodeGenModule &CGM, 601 llvm::DICompileUnit *TheCU) { 602 SmallString<256> FullName; 603 const TagDecl *TD = Ty->getDecl(); 604 605 if (!hasCXXMangling(TD, TheCU) || !TD->isExternallyVisible()) 606 return FullName; 607 608 // Microsoft Mangler does not have support for mangleCXXRTTIName yet. 609 if (CGM.getTarget().getCXXABI().isMicrosoft()) 610 return FullName; 611 612 // TODO: This is using the RTTI name. Is there a better way to get 613 // a unique string for a type? 614 llvm::raw_svector_ostream Out(FullName); 615 CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(QualType(Ty, 0), Out); 616 return FullName; 617 } 618 619 /// \return the approproate DWARF tag for a composite type. 620 static llvm::dwarf::Tag getTagForRecord(const RecordDecl *RD) { 621 llvm::dwarf::Tag Tag; 622 if (RD->isStruct() || RD->isInterface()) 623 Tag = llvm::dwarf::DW_TAG_structure_type; 624 else if (RD->isUnion()) 625 Tag = llvm::dwarf::DW_TAG_union_type; 626 else { 627 // FIXME: This could be a struct type giving a default visibility different 628 // than C++ class type, but needs llvm metadata changes first. 629 assert(RD->isClass()); 630 Tag = llvm::dwarf::DW_TAG_class_type; 631 } 632 return Tag; 633 } 634 635 llvm::DICompositeType * 636 CGDebugInfo::getOrCreateRecordFwdDecl(const RecordType *Ty, 637 llvm::DIScope *Ctx) { 638 const RecordDecl *RD = Ty->getDecl(); 639 if (llvm::DIType *T = getTypeOrNull(CGM.getContext().getRecordType(RD))) 640 return cast<llvm::DICompositeType>(T); 641 llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation()); 642 unsigned Line = getLineNumber(RD->getLocation()); 643 StringRef RDName = getClassName(RD); 644 645 uint64_t Size = 0; 646 uint64_t Align = 0; 647 648 const RecordDecl *D = RD->getDefinition(); 649 if (D && D->isCompleteDefinition()) { 650 Size = CGM.getContext().getTypeSize(Ty); 651 Align = CGM.getContext().getTypeAlign(Ty); 652 } 653 654 // Create the type. 655 SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU); 656 llvm::DICompositeType *RetTy = DBuilder.createReplaceableCompositeType( 657 getTagForRecord(RD), RDName, Ctx, DefUnit, Line, 0, Size, Align, 658 llvm::DINode::FlagFwdDecl, FullName); 659 ReplaceMap.emplace_back( 660 std::piecewise_construct, std::make_tuple(Ty), 661 std::make_tuple(static_cast<llvm::Metadata *>(RetTy))); 662 return RetTy; 663 } 664 665 llvm::DIType *CGDebugInfo::CreatePointerLikeType(llvm::dwarf::Tag Tag, 666 const Type *Ty, 667 QualType PointeeTy, 668 llvm::DIFile *Unit) { 669 if (Tag == llvm::dwarf::DW_TAG_reference_type || 670 Tag == llvm::dwarf::DW_TAG_rvalue_reference_type) 671 return DBuilder.createReferenceType(Tag, getOrCreateType(PointeeTy, Unit)); 672 673 // Bit size, align and offset of the type. 674 // Size is always the size of a pointer. We can't use getTypeSize here 675 // because that does not return the correct value for references. 676 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy); 677 uint64_t Size = CGM.getTarget().getPointerWidth(AS); 678 uint64_t Align = CGM.getContext().getTypeAlign(Ty); 679 680 return DBuilder.createPointerType(getOrCreateType(PointeeTy, Unit), Size, 681 Align); 682 } 683 684 llvm::DIType *CGDebugInfo::getOrCreateStructPtrType(StringRef Name, 685 llvm::DIType *&Cache) { 686 if (Cache) 687 return Cache; 688 Cache = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, Name, 689 TheCU, getOrCreateMainFile(), 0); 690 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy); 691 Cache = DBuilder.createPointerType(Cache, Size); 692 return Cache; 693 } 694 695 llvm::DIType *CGDebugInfo::CreateType(const BlockPointerType *Ty, 696 llvm::DIFile *Unit) { 697 SmallVector<llvm::Metadata *, 8> EltTys; 698 QualType FType; 699 uint64_t FieldSize, FieldOffset; 700 unsigned FieldAlign; 701 llvm::DINodeArray Elements; 702 703 FieldOffset = 0; 704 FType = CGM.getContext().UnsignedLongTy; 705 EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset)); 706 EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset)); 707 708 Elements = DBuilder.getOrCreateArray(EltTys); 709 EltTys.clear(); 710 711 unsigned Flags = llvm::DINode::FlagAppleBlock; 712 unsigned LineNo = 0; 713 714 auto *EltTy = 715 DBuilder.createStructType(Unit, "__block_descriptor", nullptr, LineNo, 716 FieldOffset, 0, Flags, nullptr, Elements); 717 718 // Bit size, align and offset of the type. 719 uint64_t Size = CGM.getContext().getTypeSize(Ty); 720 721 auto *DescTy = DBuilder.createPointerType(EltTy, Size); 722 723 FieldOffset = 0; 724 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy); 725 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset)); 726 FType = CGM.getContext().IntTy; 727 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset)); 728 EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset)); 729 FType = CGM.getContext().getPointerType(Ty->getPointeeType()); 730 EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset)); 731 732 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy); 733 FieldSize = CGM.getContext().getTypeSize(Ty); 734 FieldAlign = CGM.getContext().getTypeAlign(Ty); 735 EltTys.push_back(DBuilder.createMemberType(Unit, "__descriptor", nullptr, LineNo, 736 FieldSize, FieldAlign, FieldOffset, 737 0, DescTy)); 738 739 FieldOffset += FieldSize; 740 Elements = DBuilder.getOrCreateArray(EltTys); 741 742 // The __block_literal_generic structs are marked with a special 743 // DW_AT_APPLE_BLOCK attribute and are an implementation detail only 744 // the debugger needs to know about. To allow type uniquing, emit 745 // them without a name or a location. 746 EltTy = 747 DBuilder.createStructType(Unit, "", nullptr, LineNo, 748 FieldOffset, 0, Flags, nullptr, Elements); 749 750 return DBuilder.createPointerType(EltTy, Size); 751 } 752 753 llvm::DIType *CGDebugInfo::CreateType(const TemplateSpecializationType *Ty, 754 llvm::DIFile *Unit) { 755 assert(Ty->isTypeAlias()); 756 llvm::DIType *Src = getOrCreateType(Ty->getAliasedType(), Unit); 757 758 SmallString<128> NS; 759 llvm::raw_svector_ostream OS(NS); 760 Ty->getTemplateName().print(OS, CGM.getContext().getPrintingPolicy(), 761 /*qualified*/ false); 762 763 TemplateSpecializationType::PrintTemplateArgumentList( 764 OS, Ty->getArgs(), Ty->getNumArgs(), 765 CGM.getContext().getPrintingPolicy()); 766 767 TypeAliasDecl *AliasDecl = cast<TypeAliasTemplateDecl>( 768 Ty->getTemplateName().getAsTemplateDecl())->getTemplatedDecl(); 769 770 SourceLocation Loc = AliasDecl->getLocation(); 771 return DBuilder.createTypedef(Src, OS.str(), getOrCreateFile(Loc), 772 getLineNumber(Loc), 773 getDeclContextDescriptor(AliasDecl)); 774 } 775 776 llvm::DIType *CGDebugInfo::CreateType(const TypedefType *Ty, 777 llvm::DIFile *Unit) { 778 // We don't set size information, but do specify where the typedef was 779 // declared. 780 SourceLocation Loc = Ty->getDecl()->getLocation(); 781 782 // Typedefs are derived from some other type. 783 return DBuilder.createTypedef( 784 getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit), 785 Ty->getDecl()->getName(), getOrCreateFile(Loc), getLineNumber(Loc), 786 getDeclContextDescriptor(Ty->getDecl())); 787 } 788 789 llvm::DIType *CGDebugInfo::CreateType(const FunctionType *Ty, 790 llvm::DIFile *Unit) { 791 SmallVector<llvm::Metadata *, 16> EltTys; 792 793 // Add the result type at least. 794 EltTys.push_back(getOrCreateType(Ty->getReturnType(), Unit)); 795 796 // Set up remainder of arguments if there is a prototype. 797 // otherwise emit it as a variadic function. 798 if (isa<FunctionNoProtoType>(Ty)) 799 EltTys.push_back(DBuilder.createUnspecifiedParameter()); 800 else if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(Ty)) { 801 for (unsigned i = 0, e = FPT->getNumParams(); i != e; ++i) 802 EltTys.push_back(getOrCreateType(FPT->getParamType(i), Unit)); 803 if (FPT->isVariadic()) 804 EltTys.push_back(DBuilder.createUnspecifiedParameter()); 805 } 806 807 llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(EltTys); 808 return DBuilder.createSubroutineType(Unit, EltTypeArray); 809 } 810 811 /// Convert an AccessSpecifier into the corresponding DINode flag. 812 /// As an optimization, return 0 if the access specifier equals the 813 /// default for the containing type. 814 static unsigned getAccessFlag(AccessSpecifier Access, const RecordDecl *RD) { 815 AccessSpecifier Default = clang::AS_none; 816 if (RD && RD->isClass()) 817 Default = clang::AS_private; 818 else if (RD && (RD->isStruct() || RD->isUnion())) 819 Default = clang::AS_public; 820 821 if (Access == Default) 822 return 0; 823 824 switch (Access) { 825 case clang::AS_private: 826 return llvm::DINode::FlagPrivate; 827 case clang::AS_protected: 828 return llvm::DINode::FlagProtected; 829 case clang::AS_public: 830 return llvm::DINode::FlagPublic; 831 case clang::AS_none: 832 return 0; 833 } 834 llvm_unreachable("unexpected access enumerator"); 835 } 836 837 llvm::DIType *CGDebugInfo::createFieldType( 838 StringRef name, QualType type, uint64_t sizeInBitsOverride, 839 SourceLocation loc, AccessSpecifier AS, uint64_t offsetInBits, 840 llvm::DIFile *tunit, llvm::DIScope *scope, const RecordDecl *RD) { 841 llvm::DIType *debugType = getOrCreateType(type, tunit); 842 843 // Get the location for the field. 844 llvm::DIFile *file = getOrCreateFile(loc); 845 unsigned line = getLineNumber(loc); 846 847 uint64_t SizeInBits = 0; 848 unsigned AlignInBits = 0; 849 if (!type->isIncompleteArrayType()) { 850 TypeInfo TI = CGM.getContext().getTypeInfo(type); 851 SizeInBits = TI.Width; 852 AlignInBits = TI.Align; 853 854 if (sizeInBitsOverride) 855 SizeInBits = sizeInBitsOverride; 856 } 857 858 unsigned flags = getAccessFlag(AS, RD); 859 return DBuilder.createMemberType(scope, name, file, line, SizeInBits, 860 AlignInBits, offsetInBits, flags, debugType); 861 } 862 863 void CGDebugInfo::CollectRecordLambdaFields( 864 const CXXRecordDecl *CXXDecl, SmallVectorImpl<llvm::Metadata *> &elements, 865 llvm::DIType *RecordTy) { 866 // For C++11 Lambdas a Field will be the same as a Capture, but the Capture 867 // has the name and the location of the variable so we should iterate over 868 // both concurrently. 869 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(CXXDecl); 870 RecordDecl::field_iterator Field = CXXDecl->field_begin(); 871 unsigned fieldno = 0; 872 for (CXXRecordDecl::capture_const_iterator I = CXXDecl->captures_begin(), 873 E = CXXDecl->captures_end(); 874 I != E; ++I, ++Field, ++fieldno) { 875 const LambdaCapture &C = *I; 876 if (C.capturesVariable()) { 877 VarDecl *V = C.getCapturedVar(); 878 llvm::DIFile *VUnit = getOrCreateFile(C.getLocation()); 879 StringRef VName = V->getName(); 880 uint64_t SizeInBitsOverride = 0; 881 if (Field->isBitField()) { 882 SizeInBitsOverride = Field->getBitWidthValue(CGM.getContext()); 883 assert(SizeInBitsOverride && "found named 0-width bitfield"); 884 } 885 llvm::DIType *fieldType = createFieldType( 886 VName, Field->getType(), SizeInBitsOverride, C.getLocation(), 887 Field->getAccess(), layout.getFieldOffset(fieldno), VUnit, RecordTy, 888 CXXDecl); 889 elements.push_back(fieldType); 890 } else if (C.capturesThis()) { 891 // TODO: Need to handle 'this' in some way by probably renaming the 892 // this of the lambda class and having a field member of 'this' or 893 // by using AT_object_pointer for the function and having that be 894 // used as 'this' for semantic references. 895 FieldDecl *f = *Field; 896 llvm::DIFile *VUnit = getOrCreateFile(f->getLocation()); 897 QualType type = f->getType(); 898 llvm::DIType *fieldType = createFieldType( 899 "this", type, 0, f->getLocation(), f->getAccess(), 900 layout.getFieldOffset(fieldno), VUnit, RecordTy, CXXDecl); 901 902 elements.push_back(fieldType); 903 } 904 } 905 } 906 907 llvm::DIDerivedType * 908 CGDebugInfo::CreateRecordStaticField(const VarDecl *Var, llvm::DIType *RecordTy, 909 const RecordDecl *RD) { 910 // Create the descriptor for the static variable, with or without 911 // constant initializers. 912 Var = Var->getCanonicalDecl(); 913 llvm::DIFile *VUnit = getOrCreateFile(Var->getLocation()); 914 llvm::DIType *VTy = getOrCreateType(Var->getType(), VUnit); 915 916 unsigned LineNumber = getLineNumber(Var->getLocation()); 917 StringRef VName = Var->getName(); 918 llvm::Constant *C = nullptr; 919 if (Var->getInit()) { 920 const APValue *Value = Var->evaluateValue(); 921 if (Value) { 922 if (Value->isInt()) 923 C = llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt()); 924 if (Value->isFloat()) 925 C = llvm::ConstantFP::get(CGM.getLLVMContext(), Value->getFloat()); 926 } 927 } 928 929 unsigned Flags = getAccessFlag(Var->getAccess(), RD); 930 llvm::DIDerivedType *GV = DBuilder.createStaticMemberType( 931 RecordTy, VName, VUnit, LineNumber, VTy, Flags, C); 932 StaticDataMemberCache[Var->getCanonicalDecl()].reset(GV); 933 return GV; 934 } 935 936 void CGDebugInfo::CollectRecordNormalField( 937 const FieldDecl *field, uint64_t OffsetInBits, llvm::DIFile *tunit, 938 SmallVectorImpl<llvm::Metadata *> &elements, llvm::DIType *RecordTy, 939 const RecordDecl *RD) { 940 StringRef name = field->getName(); 941 QualType type = field->getType(); 942 943 // Ignore unnamed fields unless they're anonymous structs/unions. 944 if (name.empty() && !type->isRecordType()) 945 return; 946 947 uint64_t SizeInBitsOverride = 0; 948 if (field->isBitField()) { 949 SizeInBitsOverride = field->getBitWidthValue(CGM.getContext()); 950 assert(SizeInBitsOverride && "found named 0-width bitfield"); 951 } 952 953 llvm::DIType *fieldType = 954 createFieldType(name, type, SizeInBitsOverride, field->getLocation(), 955 field->getAccess(), OffsetInBits, tunit, RecordTy, RD); 956 957 elements.push_back(fieldType); 958 } 959 960 void CGDebugInfo::CollectRecordFields( 961 const RecordDecl *record, llvm::DIFile *tunit, 962 SmallVectorImpl<llvm::Metadata *> &elements, 963 llvm::DICompositeType *RecordTy) { 964 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(record); 965 966 if (CXXDecl && CXXDecl->isLambda()) 967 CollectRecordLambdaFields(CXXDecl, elements, RecordTy); 968 else { 969 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(record); 970 971 // Field number for non-static fields. 972 unsigned fieldNo = 0; 973 974 // Static and non-static members should appear in the same order as 975 // the corresponding declarations in the source program. 976 for (const auto *I : record->decls()) 977 if (const auto *V = dyn_cast<VarDecl>(I)) { 978 // Reuse the existing static member declaration if one exists 979 auto MI = StaticDataMemberCache.find(V->getCanonicalDecl()); 980 if (MI != StaticDataMemberCache.end()) { 981 assert(MI->second && 982 "Static data member declaration should still exist"); 983 elements.push_back(MI->second); 984 } else { 985 auto Field = CreateRecordStaticField(V, RecordTy, record); 986 elements.push_back(Field); 987 } 988 } else if (const auto *field = dyn_cast<FieldDecl>(I)) { 989 CollectRecordNormalField(field, layout.getFieldOffset(fieldNo), tunit, 990 elements, RecordTy, record); 991 992 // Bump field number for next field. 993 ++fieldNo; 994 } 995 } 996 } 997 998 llvm::DISubroutineType * 999 CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method, 1000 llvm::DIFile *Unit) { 1001 const FunctionProtoType *Func = Method->getType()->getAs<FunctionProtoType>(); 1002 if (Method->isStatic()) 1003 return cast_or_null<llvm::DISubroutineType>( 1004 getOrCreateType(QualType(Func, 0), Unit)); 1005 return getOrCreateInstanceMethodType(Method->getThisType(CGM.getContext()), 1006 Func, Unit); 1007 } 1008 1009 llvm::DISubroutineType *CGDebugInfo::getOrCreateInstanceMethodType( 1010 QualType ThisPtr, const FunctionProtoType *Func, llvm::DIFile *Unit) { 1011 // Add "this" pointer. 1012 llvm::DITypeRefArray Args( 1013 cast<llvm::DISubroutineType>(getOrCreateType(QualType(Func, 0), Unit)) 1014 ->getTypeArray()); 1015 assert(Args.size() && "Invalid number of arguments!"); 1016 1017 SmallVector<llvm::Metadata *, 16> Elts; 1018 1019 // First element is always return type. For 'void' functions it is NULL. 1020 Elts.push_back(Args[0]); 1021 1022 // "this" pointer is always first argument. 1023 const CXXRecordDecl *RD = ThisPtr->getPointeeCXXRecordDecl(); 1024 if (isa<ClassTemplateSpecializationDecl>(RD)) { 1025 // Create pointer type directly in this case. 1026 const PointerType *ThisPtrTy = cast<PointerType>(ThisPtr); 1027 QualType PointeeTy = ThisPtrTy->getPointeeType(); 1028 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy); 1029 uint64_t Size = CGM.getTarget().getPointerWidth(AS); 1030 uint64_t Align = CGM.getContext().getTypeAlign(ThisPtrTy); 1031 llvm::DIType *PointeeType = getOrCreateType(PointeeTy, Unit); 1032 llvm::DIType *ThisPtrType = 1033 DBuilder.createPointerType(PointeeType, Size, Align); 1034 TypeCache[ThisPtr.getAsOpaquePtr()].reset(ThisPtrType); 1035 // TODO: This and the artificial type below are misleading, the 1036 // types aren't artificial the argument is, but the current 1037 // metadata doesn't represent that. 1038 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType); 1039 Elts.push_back(ThisPtrType); 1040 } else { 1041 llvm::DIType *ThisPtrType = getOrCreateType(ThisPtr, Unit); 1042 TypeCache[ThisPtr.getAsOpaquePtr()].reset(ThisPtrType); 1043 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType); 1044 Elts.push_back(ThisPtrType); 1045 } 1046 1047 // Copy rest of the arguments. 1048 for (unsigned i = 1, e = Args.size(); i != e; ++i) 1049 Elts.push_back(Args[i]); 1050 1051 llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(Elts); 1052 1053 unsigned Flags = 0; 1054 if (Func->getExtProtoInfo().RefQualifier == RQ_LValue) 1055 Flags |= llvm::DINode::FlagLValueReference; 1056 if (Func->getExtProtoInfo().RefQualifier == RQ_RValue) 1057 Flags |= llvm::DINode::FlagRValueReference; 1058 1059 return DBuilder.createSubroutineType(Unit, EltTypeArray, Flags); 1060 } 1061 1062 /// isFunctionLocalClass - Return true if CXXRecordDecl is defined 1063 /// inside a function. 1064 static bool isFunctionLocalClass(const CXXRecordDecl *RD) { 1065 if (const CXXRecordDecl *NRD = dyn_cast<CXXRecordDecl>(RD->getDeclContext())) 1066 return isFunctionLocalClass(NRD); 1067 if (isa<FunctionDecl>(RD->getDeclContext())) 1068 return true; 1069 return false; 1070 } 1071 1072 llvm::DISubprogram *CGDebugInfo::CreateCXXMemberFunction( 1073 const CXXMethodDecl *Method, llvm::DIFile *Unit, llvm::DIType *RecordTy) { 1074 bool IsCtorOrDtor = 1075 isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method); 1076 1077 StringRef MethodName = getFunctionName(Method); 1078 llvm::DISubroutineType *MethodTy = getOrCreateMethodType(Method, Unit); 1079 1080 // Since a single ctor/dtor corresponds to multiple functions, it doesn't 1081 // make sense to give a single ctor/dtor a linkage name. 1082 StringRef MethodLinkageName; 1083 if (!IsCtorOrDtor && !isFunctionLocalClass(Method->getParent())) 1084 MethodLinkageName = CGM.getMangledName(Method); 1085 1086 // Get the location for the method. 1087 llvm::DIFile *MethodDefUnit = nullptr; 1088 unsigned MethodLine = 0; 1089 if (!Method->isImplicit()) { 1090 MethodDefUnit = getOrCreateFile(Method->getLocation()); 1091 MethodLine = getLineNumber(Method->getLocation()); 1092 } 1093 1094 // Collect virtual method info. 1095 llvm::DIType *ContainingType = nullptr; 1096 unsigned Virtuality = 0; 1097 unsigned VIndex = 0; 1098 1099 if (Method->isVirtual()) { 1100 if (Method->isPure()) 1101 Virtuality = llvm::dwarf::DW_VIRTUALITY_pure_virtual; 1102 else 1103 Virtuality = llvm::dwarf::DW_VIRTUALITY_virtual; 1104 1105 // It doesn't make sense to give a virtual destructor a vtable index, 1106 // since a single destructor has two entries in the vtable. 1107 // FIXME: Add proper support for debug info for virtual calls in 1108 // the Microsoft ABI, where we may use multiple vptrs to make a vftable 1109 // lookup if we have multiple or virtual inheritance. 1110 if (!isa<CXXDestructorDecl>(Method) && 1111 !CGM.getTarget().getCXXABI().isMicrosoft()) 1112 VIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(Method); 1113 ContainingType = RecordTy; 1114 } 1115 1116 unsigned Flags = 0; 1117 if (Method->isImplicit()) 1118 Flags |= llvm::DINode::FlagArtificial; 1119 Flags |= getAccessFlag(Method->getAccess(), Method->getParent()); 1120 if (const CXXConstructorDecl *CXXC = dyn_cast<CXXConstructorDecl>(Method)) { 1121 if (CXXC->isExplicit()) 1122 Flags |= llvm::DINode::FlagExplicit; 1123 } else if (const CXXConversionDecl *CXXC = 1124 dyn_cast<CXXConversionDecl>(Method)) { 1125 if (CXXC->isExplicit()) 1126 Flags |= llvm::DINode::FlagExplicit; 1127 } 1128 if (Method->hasPrototype()) 1129 Flags |= llvm::DINode::FlagPrototyped; 1130 if (Method->getRefQualifier() == RQ_LValue) 1131 Flags |= llvm::DINode::FlagLValueReference; 1132 if (Method->getRefQualifier() == RQ_RValue) 1133 Flags |= llvm::DINode::FlagRValueReference; 1134 1135 llvm::DINodeArray TParamsArray = CollectFunctionTemplateParams(Method, Unit); 1136 llvm::DISubprogram *SP = DBuilder.createMethod( 1137 RecordTy, MethodName, MethodLinkageName, MethodDefUnit, MethodLine, 1138 MethodTy, /*isLocalToUnit=*/false, 1139 /* isDefinition=*/false, Virtuality, VIndex, ContainingType, Flags, 1140 CGM.getLangOpts().Optimize, nullptr, TParamsArray.get()); 1141 1142 SPCache[Method->getCanonicalDecl()].reset(SP); 1143 1144 return SP; 1145 } 1146 1147 void CGDebugInfo::CollectCXXMemberFunctions( 1148 const CXXRecordDecl *RD, llvm::DIFile *Unit, 1149 SmallVectorImpl<llvm::Metadata *> &EltTys, llvm::DIType *RecordTy) { 1150 1151 // Since we want more than just the individual member decls if we 1152 // have templated functions iterate over every declaration to gather 1153 // the functions. 1154 for (const auto *I : RD->decls()) { 1155 const auto *Method = dyn_cast<CXXMethodDecl>(I); 1156 // If the member is implicit, don't add it to the member list. This avoids 1157 // the member being added to type units by LLVM, while still allowing it 1158 // to be emitted into the type declaration/reference inside the compile 1159 // unit. 1160 // Ditto 'nodebug' methods, for consistency with CodeGenFunction.cpp. 1161 // FIXME: Handle Using(Shadow?)Decls here to create 1162 // DW_TAG_imported_declarations inside the class for base decls brought into 1163 // derived classes. GDB doesn't seem to notice/leverage these when I tried 1164 // it, so I'm not rushing to fix this. (GCC seems to produce them, if 1165 // referenced) 1166 if (!Method || Method->isImplicit() || Method->hasAttr<NoDebugAttr>()) 1167 continue; 1168 1169 if (Method->getType()->getAs<FunctionProtoType>()->getContainedAutoType()) 1170 continue; 1171 1172 // Reuse the existing member function declaration if it exists. 1173 // It may be associated with the declaration of the type & should be 1174 // reused as we're building the definition. 1175 // 1176 // This situation can arise in the vtable-based debug info reduction where 1177 // implicit members are emitted in a non-vtable TU. 1178 auto MI = SPCache.find(Method->getCanonicalDecl()); 1179 EltTys.push_back(MI == SPCache.end() 1180 ? CreateCXXMemberFunction(Method, Unit, RecordTy) 1181 : static_cast<llvm::Metadata *>(MI->second)); 1182 } 1183 } 1184 1185 void CGDebugInfo::CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile *Unit, 1186 SmallVectorImpl<llvm::Metadata *> &EltTys, 1187 llvm::DIType *RecordTy) { 1188 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD); 1189 for (const auto &BI : RD->bases()) { 1190 unsigned BFlags = 0; 1191 uint64_t BaseOffset; 1192 1193 const CXXRecordDecl *Base = 1194 cast<CXXRecordDecl>(BI.getType()->getAs<RecordType>()->getDecl()); 1195 1196 if (BI.isVirtual()) { 1197 if (CGM.getTarget().getCXXABI().isItaniumFamily()) { 1198 // virtual base offset offset is -ve. The code generator emits dwarf 1199 // expression where it expects +ve number. 1200 BaseOffset = 0 - CGM.getItaniumVTableContext() 1201 .getVirtualBaseOffsetOffset(RD, Base) 1202 .getQuantity(); 1203 } else { 1204 // In the MS ABI, store the vbtable offset, which is analogous to the 1205 // vbase offset offset in Itanium. 1206 BaseOffset = 1207 4 * CGM.getMicrosoftVTableContext().getVBTableIndex(RD, Base); 1208 } 1209 BFlags = llvm::DINode::FlagVirtual; 1210 } else 1211 BaseOffset = CGM.getContext().toBits(RL.getBaseClassOffset(Base)); 1212 // FIXME: Inconsistent units for BaseOffset. It is in bytes when 1213 // BI->isVirtual() and bits when not. 1214 1215 BFlags |= getAccessFlag(BI.getAccessSpecifier(), RD); 1216 llvm::DIType *DTy = DBuilder.createInheritance( 1217 RecordTy, getOrCreateType(BI.getType(), Unit), BaseOffset, BFlags); 1218 EltTys.push_back(DTy); 1219 } 1220 } 1221 1222 llvm::DINodeArray 1223 CGDebugInfo::CollectTemplateParams(const TemplateParameterList *TPList, 1224 ArrayRef<TemplateArgument> TAList, 1225 llvm::DIFile *Unit) { 1226 SmallVector<llvm::Metadata *, 16> TemplateParams; 1227 for (unsigned i = 0, e = TAList.size(); i != e; ++i) { 1228 const TemplateArgument &TA = TAList[i]; 1229 StringRef Name; 1230 if (TPList) 1231 Name = TPList->getParam(i)->getName(); 1232 switch (TA.getKind()) { 1233 case TemplateArgument::Type: { 1234 llvm::DIType *TTy = getOrCreateType(TA.getAsType(), Unit); 1235 TemplateParams.push_back( 1236 DBuilder.createTemplateTypeParameter(TheCU, Name, TTy)); 1237 } break; 1238 case TemplateArgument::Integral: { 1239 llvm::DIType *TTy = getOrCreateType(TA.getIntegralType(), Unit); 1240 TemplateParams.push_back(DBuilder.createTemplateValueParameter( 1241 TheCU, Name, TTy, 1242 llvm::ConstantInt::get(CGM.getLLVMContext(), TA.getAsIntegral()))); 1243 } break; 1244 case TemplateArgument::Declaration: { 1245 const ValueDecl *D = TA.getAsDecl(); 1246 QualType T = TA.getParamTypeForDecl().getDesugaredType(CGM.getContext()); 1247 llvm::DIType *TTy = getOrCreateType(T, Unit); 1248 llvm::Constant *V = nullptr; 1249 const CXXMethodDecl *MD; 1250 // Variable pointer template parameters have a value that is the address 1251 // of the variable. 1252 if (const auto *VD = dyn_cast<VarDecl>(D)) 1253 V = CGM.GetAddrOfGlobalVar(VD); 1254 // Member function pointers have special support for building them, though 1255 // this is currently unsupported in LLVM CodeGen. 1256 else if ((MD = dyn_cast<CXXMethodDecl>(D)) && MD->isInstance()) 1257 V = CGM.getCXXABI().EmitMemberFunctionPointer(MD); 1258 else if (const auto *FD = dyn_cast<FunctionDecl>(D)) 1259 V = CGM.GetAddrOfFunction(FD); 1260 // Member data pointers have special handling too to compute the fixed 1261 // offset within the object. 1262 else if (const auto *MPT = dyn_cast<MemberPointerType>(T.getTypePtr())) { 1263 // These five lines (& possibly the above member function pointer 1264 // handling) might be able to be refactored to use similar code in 1265 // CodeGenModule::getMemberPointerConstant 1266 uint64_t fieldOffset = CGM.getContext().getFieldOffset(D); 1267 CharUnits chars = 1268 CGM.getContext().toCharUnitsFromBits((int64_t)fieldOffset); 1269 V = CGM.getCXXABI().EmitMemberDataPointer(MPT, chars); 1270 } 1271 TemplateParams.push_back(DBuilder.createTemplateValueParameter( 1272 TheCU, Name, TTy, 1273 cast_or_null<llvm::Constant>(V->stripPointerCasts()))); 1274 } break; 1275 case TemplateArgument::NullPtr: { 1276 QualType T = TA.getNullPtrType(); 1277 llvm::DIType *TTy = getOrCreateType(T, Unit); 1278 llvm::Constant *V = nullptr; 1279 // Special case member data pointer null values since they're actually -1 1280 // instead of zero. 1281 if (const MemberPointerType *MPT = 1282 dyn_cast<MemberPointerType>(T.getTypePtr())) 1283 // But treat member function pointers as simple zero integers because 1284 // it's easier than having a special case in LLVM's CodeGen. If LLVM 1285 // CodeGen grows handling for values of non-null member function 1286 // pointers then perhaps we could remove this special case and rely on 1287 // EmitNullMemberPointer for member function pointers. 1288 if (MPT->isMemberDataPointer()) 1289 V = CGM.getCXXABI().EmitNullMemberPointer(MPT); 1290 if (!V) 1291 V = llvm::ConstantInt::get(CGM.Int8Ty, 0); 1292 TemplateParams.push_back(DBuilder.createTemplateValueParameter( 1293 TheCU, Name, TTy, cast<llvm::Constant>(V))); 1294 } break; 1295 case TemplateArgument::Template: 1296 TemplateParams.push_back(DBuilder.createTemplateTemplateParameter( 1297 TheCU, Name, nullptr, 1298 TA.getAsTemplate().getAsTemplateDecl()->getQualifiedNameAsString())); 1299 break; 1300 case TemplateArgument::Pack: 1301 TemplateParams.push_back(DBuilder.createTemplateParameterPack( 1302 TheCU, Name, nullptr, 1303 CollectTemplateParams(nullptr, TA.getPackAsArray(), Unit))); 1304 break; 1305 case TemplateArgument::Expression: { 1306 const Expr *E = TA.getAsExpr(); 1307 QualType T = E->getType(); 1308 if (E->isGLValue()) 1309 T = CGM.getContext().getLValueReferenceType(T); 1310 llvm::Constant *V = CGM.EmitConstantExpr(E, T); 1311 assert(V && "Expression in template argument isn't constant"); 1312 llvm::DIType *TTy = getOrCreateType(T, Unit); 1313 TemplateParams.push_back(DBuilder.createTemplateValueParameter( 1314 TheCU, Name, TTy, cast<llvm::Constant>(V->stripPointerCasts()))); 1315 } break; 1316 // And the following should never occur: 1317 case TemplateArgument::TemplateExpansion: 1318 case TemplateArgument::Null: 1319 llvm_unreachable( 1320 "These argument types shouldn't exist in concrete types"); 1321 } 1322 } 1323 return DBuilder.getOrCreateArray(TemplateParams); 1324 } 1325 1326 llvm::DINodeArray 1327 CGDebugInfo::CollectFunctionTemplateParams(const FunctionDecl *FD, 1328 llvm::DIFile *Unit) { 1329 if (FD->getTemplatedKind() == 1330 FunctionDecl::TK_FunctionTemplateSpecialization) { 1331 const TemplateParameterList *TList = FD->getTemplateSpecializationInfo() 1332 ->getTemplate() 1333 ->getTemplateParameters(); 1334 return CollectTemplateParams( 1335 TList, FD->getTemplateSpecializationArgs()->asArray(), Unit); 1336 } 1337 return llvm::DINodeArray(); 1338 } 1339 1340 llvm::DINodeArray CGDebugInfo::CollectCXXTemplateParams( 1341 const ClassTemplateSpecializationDecl *TSpecial, llvm::DIFile *Unit) { 1342 // Always get the full list of parameters, not just the ones from 1343 // the specialization. 1344 TemplateParameterList *TPList = 1345 TSpecial->getSpecializedTemplate()->getTemplateParameters(); 1346 const TemplateArgumentList &TAList = TSpecial->getTemplateArgs(); 1347 return CollectTemplateParams(TPList, TAList.asArray(), Unit); 1348 } 1349 1350 llvm::DIType *CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile *Unit) { 1351 if (VTablePtrType) 1352 return VTablePtrType; 1353 1354 ASTContext &Context = CGM.getContext(); 1355 1356 /* Function type */ 1357 llvm::Metadata *STy = getOrCreateType(Context.IntTy, Unit); 1358 llvm::DITypeRefArray SElements = DBuilder.getOrCreateTypeArray(STy); 1359 llvm::DIType *SubTy = DBuilder.createSubroutineType(Unit, SElements); 1360 unsigned Size = Context.getTypeSize(Context.VoidPtrTy); 1361 llvm::DIType *vtbl_ptr_type = 1362 DBuilder.createPointerType(SubTy, Size, 0, "__vtbl_ptr_type"); 1363 VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size); 1364 return VTablePtrType; 1365 } 1366 1367 StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) { 1368 // Copy the gdb compatible name on the side and use its reference. 1369 return internString("_vptr$", RD->getNameAsString()); 1370 } 1371 1372 void CGDebugInfo::CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile *Unit, 1373 SmallVectorImpl<llvm::Metadata *> &EltTys) { 1374 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD); 1375 1376 // If there is a primary base then it will hold vtable info. 1377 if (RL.getPrimaryBase()) 1378 return; 1379 1380 // If this class is not dynamic then there is not any vtable info to collect. 1381 if (!RD->isDynamicClass()) 1382 return; 1383 1384 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy); 1385 llvm::DIType *VPTR = DBuilder.createMemberType( 1386 Unit, getVTableName(RD), Unit, 0, Size, 0, 0, 1387 llvm::DINode::FlagArtificial, getOrCreateVTablePtrType(Unit)); 1388 EltTys.push_back(VPTR); 1389 } 1390 1391 llvm::DIType *CGDebugInfo::getOrCreateRecordType(QualType RTy, 1392 SourceLocation Loc) { 1393 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo); 1394 llvm::DIType *T = getOrCreateType(RTy, getOrCreateFile(Loc)); 1395 return T; 1396 } 1397 1398 llvm::DIType *CGDebugInfo::getOrCreateInterfaceType(QualType D, 1399 SourceLocation Loc) { 1400 return getOrCreateStandaloneType(D, Loc); 1401 } 1402 1403 llvm::DIType *CGDebugInfo::getOrCreateStandaloneType(QualType D, 1404 SourceLocation Loc) { 1405 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo); 1406 assert(!D.isNull() && "null type"); 1407 llvm::DIType *T = getOrCreateType(D, getOrCreateFile(Loc)); 1408 assert(T && "could not create debug info for type"); 1409 1410 // Composite types with UIDs were already retained by DIBuilder 1411 // because they are only referenced by name in the IR. 1412 if (auto *CTy = dyn_cast<llvm::DICompositeType>(T)) 1413 if (!CTy->getIdentifier().empty()) 1414 return T; 1415 RetainedTypes.push_back(D.getAsOpaquePtr()); 1416 return T; 1417 } 1418 1419 void CGDebugInfo::completeType(const EnumDecl *ED) { 1420 if (DebugKind <= CodeGenOptions::DebugLineTablesOnly) 1421 return; 1422 QualType Ty = CGM.getContext().getEnumType(ED); 1423 void *TyPtr = Ty.getAsOpaquePtr(); 1424 auto I = TypeCache.find(TyPtr); 1425 if (I == TypeCache.end() || !cast<llvm::DIType>(I->second)->isForwardDecl()) 1426 return; 1427 llvm::DIType *Res = CreateTypeDefinition(Ty->castAs<EnumType>()); 1428 assert(!Res->isForwardDecl()); 1429 TypeCache[TyPtr].reset(Res); 1430 } 1431 1432 void CGDebugInfo::completeType(const RecordDecl *RD) { 1433 if (DebugKind > CodeGenOptions::LimitedDebugInfo || 1434 !CGM.getLangOpts().CPlusPlus) 1435 completeRequiredType(RD); 1436 } 1437 1438 void CGDebugInfo::completeRequiredType(const RecordDecl *RD) { 1439 if (DebugKind <= CodeGenOptions::DebugLineTablesOnly) 1440 return; 1441 1442 if (const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD)) 1443 if (CXXDecl->isDynamicClass()) 1444 return; 1445 1446 if (DebugTypeExtRefs && RD->isFromASTFile()) 1447 return; 1448 1449 QualType Ty = CGM.getContext().getRecordType(RD); 1450 llvm::DIType *T = getTypeOrNull(Ty); 1451 if (T && T->isForwardDecl()) 1452 completeClassData(RD); 1453 } 1454 1455 void CGDebugInfo::completeClassData(const RecordDecl *RD) { 1456 if (DebugKind <= CodeGenOptions::DebugLineTablesOnly) 1457 return; 1458 QualType Ty = CGM.getContext().getRecordType(RD); 1459 void *TyPtr = Ty.getAsOpaquePtr(); 1460 auto I = TypeCache.find(TyPtr); 1461 if (I != TypeCache.end() && !cast<llvm::DIType>(I->second)->isForwardDecl()) 1462 return; 1463 llvm::DIType *Res = CreateTypeDefinition(Ty->castAs<RecordType>()); 1464 assert(!Res->isForwardDecl()); 1465 TypeCache[TyPtr].reset(Res); 1466 } 1467 1468 static bool hasExplicitMemberDefinition(CXXRecordDecl::method_iterator I, 1469 CXXRecordDecl::method_iterator End) { 1470 for (; I != End; ++I) 1471 if (FunctionDecl *Tmpl = I->getInstantiatedFromMemberFunction()) 1472 if (!Tmpl->isImplicit() && Tmpl->isThisDeclarationADefinition() && 1473 !I->getMemberSpecializationInfo()->isExplicitSpecialization()) 1474 return true; 1475 return false; 1476 } 1477 1478 static bool shouldOmitDefinition(CodeGenOptions::DebugInfoKind DebugKind, 1479 bool DebugTypeExtRefs, 1480 const RecordDecl *RD, 1481 const LangOptions &LangOpts) { 1482 // Does the type exist in an imported clang module? 1483 if (DebugTypeExtRefs && RD->isFromASTFile() && RD->getDefinition()) 1484 return true; 1485 1486 if (DebugKind > CodeGenOptions::LimitedDebugInfo) 1487 return false; 1488 1489 if (!LangOpts.CPlusPlus) 1490 return false; 1491 1492 if (!RD->isCompleteDefinitionRequired()) 1493 return true; 1494 1495 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD); 1496 1497 if (!CXXDecl) 1498 return false; 1499 1500 if (CXXDecl->hasDefinition() && CXXDecl->isDynamicClass()) 1501 return true; 1502 1503 TemplateSpecializationKind Spec = TSK_Undeclared; 1504 if (const ClassTemplateSpecializationDecl *SD = 1505 dyn_cast<ClassTemplateSpecializationDecl>(RD)) 1506 Spec = SD->getSpecializationKind(); 1507 1508 if (Spec == TSK_ExplicitInstantiationDeclaration && 1509 hasExplicitMemberDefinition(CXXDecl->method_begin(), 1510 CXXDecl->method_end())) 1511 return true; 1512 1513 return false; 1514 } 1515 1516 llvm::DIType *CGDebugInfo::CreateType(const RecordType *Ty) { 1517 RecordDecl *RD = Ty->getDecl(); 1518 llvm::DIType *T = cast_or_null<llvm::DIType>(getTypeOrNull(QualType(Ty, 0))); 1519 if (T || shouldOmitDefinition(DebugKind, DebugTypeExtRefs, RD, 1520 CGM.getLangOpts())) { 1521 if (!T) 1522 T = getOrCreateRecordFwdDecl(Ty, getDeclContextDescriptor(RD)); 1523 return T; 1524 } 1525 1526 return CreateTypeDefinition(Ty); 1527 } 1528 1529 llvm::DIType *CGDebugInfo::CreateTypeDefinition(const RecordType *Ty) { 1530 RecordDecl *RD = Ty->getDecl(); 1531 1532 // Get overall information about the record type for the debug info. 1533 llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation()); 1534 1535 // Records and classes and unions can all be recursive. To handle them, we 1536 // first generate a debug descriptor for the struct as a forward declaration. 1537 // Then (if it is a definition) we go through and get debug info for all of 1538 // its members. Finally, we create a descriptor for the complete type (which 1539 // may refer to the forward decl if the struct is recursive) and replace all 1540 // uses of the forward declaration with the final definition. 1541 llvm::DICompositeType *FwdDecl = getOrCreateLimitedType(Ty, DefUnit); 1542 1543 const RecordDecl *D = RD->getDefinition(); 1544 if (!D || !D->isCompleteDefinition()) 1545 return FwdDecl; 1546 1547 if (const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD)) 1548 CollectContainingType(CXXDecl, FwdDecl); 1549 1550 // Push the struct on region stack. 1551 LexicalBlockStack.emplace_back(&*FwdDecl); 1552 RegionMap[Ty->getDecl()].reset(FwdDecl); 1553 1554 // Convert all the elements. 1555 SmallVector<llvm::Metadata *, 16> EltTys; 1556 // what about nested types? 1557 1558 // Note: The split of CXXDecl information here is intentional, the 1559 // gdb tests will depend on a certain ordering at printout. The debug 1560 // information offsets are still correct if we merge them all together 1561 // though. 1562 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD); 1563 if (CXXDecl) { 1564 CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl); 1565 CollectVTableInfo(CXXDecl, DefUnit, EltTys); 1566 } 1567 1568 // Collect data fields (including static variables and any initializers). 1569 CollectRecordFields(RD, DefUnit, EltTys, FwdDecl); 1570 if (CXXDecl) 1571 CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl); 1572 1573 LexicalBlockStack.pop_back(); 1574 RegionMap.erase(Ty->getDecl()); 1575 1576 llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys); 1577 DBuilder.replaceArrays(FwdDecl, Elements); 1578 1579 if (FwdDecl->isTemporary()) 1580 FwdDecl = 1581 llvm::MDNode::replaceWithPermanent(llvm::TempDICompositeType(FwdDecl)); 1582 1583 RegionMap[Ty->getDecl()].reset(FwdDecl); 1584 return FwdDecl; 1585 } 1586 1587 llvm::DIType *CGDebugInfo::CreateType(const ObjCObjectType *Ty, 1588 llvm::DIFile *Unit) { 1589 // Ignore protocols. 1590 return getOrCreateType(Ty->getBaseType(), Unit); 1591 } 1592 1593 /// \return true if Getter has the default name for the property PD. 1594 static bool hasDefaultGetterName(const ObjCPropertyDecl *PD, 1595 const ObjCMethodDecl *Getter) { 1596 assert(PD); 1597 if (!Getter) 1598 return true; 1599 1600 assert(Getter->getDeclName().isObjCZeroArgSelector()); 1601 return PD->getName() == 1602 Getter->getDeclName().getObjCSelector().getNameForSlot(0); 1603 } 1604 1605 /// \return true if Setter has the default name for the property PD. 1606 static bool hasDefaultSetterName(const ObjCPropertyDecl *PD, 1607 const ObjCMethodDecl *Setter) { 1608 assert(PD); 1609 if (!Setter) 1610 return true; 1611 1612 assert(Setter->getDeclName().isObjCOneArgSelector()); 1613 return SelectorTable::constructSetterName(PD->getName()) == 1614 Setter->getDeclName().getObjCSelector().getNameForSlot(0); 1615 } 1616 1617 llvm::DIType *CGDebugInfo::CreateType(const ObjCInterfaceType *Ty, 1618 llvm::DIFile *Unit) { 1619 ObjCInterfaceDecl *ID = Ty->getDecl(); 1620 if (!ID) 1621 return nullptr; 1622 1623 // Return a forward declaration if this type was imported from a clang module. 1624 if (DebugTypeExtRefs && ID->isFromASTFile() && ID->getDefinition()) 1625 return DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, 1626 ID->getName(), 1627 getDeclContextDescriptor(ID), Unit, 0); 1628 1629 // Get overall information about the record type for the debug info. 1630 llvm::DIFile *DefUnit = getOrCreateFile(ID->getLocation()); 1631 unsigned Line = getLineNumber(ID->getLocation()); 1632 auto RuntimeLang = 1633 static_cast<llvm::dwarf::SourceLanguage>(TheCU->getSourceLanguage()); 1634 1635 // If this is just a forward declaration return a special forward-declaration 1636 // debug type since we won't be able to lay out the entire type. 1637 ObjCInterfaceDecl *Def = ID->getDefinition(); 1638 if (!Def || !Def->getImplementation()) { 1639 llvm::DIType *FwdDecl = DBuilder.createReplaceableCompositeType( 1640 llvm::dwarf::DW_TAG_structure_type, ID->getName(), TheCU, DefUnit, Line, 1641 RuntimeLang); 1642 ObjCInterfaceCache.push_back(ObjCInterfaceCacheEntry(Ty, FwdDecl, Unit)); 1643 return FwdDecl; 1644 } 1645 1646 return CreateTypeDefinition(Ty, Unit); 1647 } 1648 1649 llvm::DIModule * 1650 CGDebugInfo::getOrCreateModuleRef(ExternalASTSource::ASTSourceDescriptor Mod) { 1651 auto &ModRef = ModuleRefCache[Mod.Signature]; 1652 if (ModRef) 1653 return cast<llvm::DIModule>(ModRef); 1654 1655 // Macro definitions that were defined with "-D" on the command line. 1656 SmallString<128> ConfigMacros; 1657 { 1658 llvm::raw_svector_ostream OS(ConfigMacros); 1659 const auto &PPOpts = CGM.getPreprocessorOpts(); 1660 unsigned I = 0; 1661 // Translate the macro definitions back into a commmand line. 1662 for (auto &M : PPOpts.Macros) { 1663 if (++I > 1) 1664 OS << " "; 1665 const std::string &Macro = M.first; 1666 bool Undef = M.second; 1667 OS << "\"-" << (Undef ? 'U' : 'D'); 1668 for (char c : Macro) 1669 switch (c) { 1670 case '\\' : OS << "\\\\"; break; 1671 case '"' : OS << "\\\""; break; 1672 default: OS << c; 1673 } 1674 OS << '\"'; 1675 } 1676 } 1677 llvm::DIBuilder DIB(CGM.getModule()); 1678 auto *CU = DIB.createCompileUnit(TheCU->getSourceLanguage(), Mod.ModuleName, 1679 Mod.Path, TheCU->getProducer(), true, 1680 StringRef(), 0, Mod.ASTFile, 1681 llvm::DIBuilder::FullDebug, Mod.Signature); 1682 llvm::DIModule *M = 1683 DIB.createModule(CU, Mod.ModuleName, ConfigMacros, Mod.Path, 1684 CGM.getHeaderSearchOpts().Sysroot); 1685 DIB.finalize(); 1686 ModRef.reset(M); 1687 return M; 1688 } 1689 1690 llvm::DIType *CGDebugInfo::CreateTypeDefinition(const ObjCInterfaceType *Ty, 1691 llvm::DIFile *Unit) { 1692 ObjCInterfaceDecl *ID = Ty->getDecl(); 1693 llvm::DIFile *DefUnit = getOrCreateFile(ID->getLocation()); 1694 unsigned Line = getLineNumber(ID->getLocation()); 1695 unsigned RuntimeLang = TheCU->getSourceLanguage(); 1696 1697 // Bit size, align and offset of the type. 1698 uint64_t Size = CGM.getContext().getTypeSize(Ty); 1699 uint64_t Align = CGM.getContext().getTypeAlign(Ty); 1700 1701 unsigned Flags = 0; 1702 if (ID->getImplementation()) 1703 Flags |= llvm::DINode::FlagObjcClassComplete; 1704 1705 llvm::DICompositeType *RealDecl = DBuilder.createStructType( 1706 Unit, ID->getName(), DefUnit, Line, Size, Align, Flags, nullptr, 1707 llvm::DINodeArray(), RuntimeLang); 1708 1709 QualType QTy(Ty, 0); 1710 TypeCache[QTy.getAsOpaquePtr()].reset(RealDecl); 1711 1712 // Push the struct on region stack. 1713 LexicalBlockStack.emplace_back(RealDecl); 1714 RegionMap[Ty->getDecl()].reset(RealDecl); 1715 1716 // Convert all the elements. 1717 SmallVector<llvm::Metadata *, 16> EltTys; 1718 1719 ObjCInterfaceDecl *SClass = ID->getSuperClass(); 1720 if (SClass) { 1721 llvm::DIType *SClassTy = 1722 getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit); 1723 if (!SClassTy) 1724 return nullptr; 1725 1726 llvm::DIType *InhTag = DBuilder.createInheritance(RealDecl, SClassTy, 0, 0); 1727 EltTys.push_back(InhTag); 1728 } 1729 1730 // Create entries for all of the properties. 1731 for (const auto *PD : ID->properties()) { 1732 SourceLocation Loc = PD->getLocation(); 1733 llvm::DIFile *PUnit = getOrCreateFile(Loc); 1734 unsigned PLine = getLineNumber(Loc); 1735 ObjCMethodDecl *Getter = PD->getGetterMethodDecl(); 1736 ObjCMethodDecl *Setter = PD->getSetterMethodDecl(); 1737 llvm::MDNode *PropertyNode = DBuilder.createObjCProperty( 1738 PD->getName(), PUnit, PLine, 1739 hasDefaultGetterName(PD, Getter) ? "" 1740 : getSelectorName(PD->getGetterName()), 1741 hasDefaultSetterName(PD, Setter) ? "" 1742 : getSelectorName(PD->getSetterName()), 1743 PD->getPropertyAttributes(), getOrCreateType(PD->getType(), PUnit)); 1744 EltTys.push_back(PropertyNode); 1745 } 1746 1747 const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID); 1748 unsigned FieldNo = 0; 1749 for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field; 1750 Field = Field->getNextIvar(), ++FieldNo) { 1751 llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit); 1752 if (!FieldTy) 1753 return nullptr; 1754 1755 StringRef FieldName = Field->getName(); 1756 1757 // Ignore unnamed fields. 1758 if (FieldName.empty()) 1759 continue; 1760 1761 // Get the location for the field. 1762 llvm::DIFile *FieldDefUnit = getOrCreateFile(Field->getLocation()); 1763 unsigned FieldLine = getLineNumber(Field->getLocation()); 1764 QualType FType = Field->getType(); 1765 uint64_t FieldSize = 0; 1766 unsigned FieldAlign = 0; 1767 1768 if (!FType->isIncompleteArrayType()) { 1769 1770 // Bit size, align and offset of the type. 1771 FieldSize = Field->isBitField() 1772 ? Field->getBitWidthValue(CGM.getContext()) 1773 : CGM.getContext().getTypeSize(FType); 1774 FieldAlign = CGM.getContext().getTypeAlign(FType); 1775 } 1776 1777 uint64_t FieldOffset; 1778 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) { 1779 // We don't know the runtime offset of an ivar if we're using the 1780 // non-fragile ABI. For bitfields, use the bit offset into the first 1781 // byte of storage of the bitfield. For other fields, use zero. 1782 if (Field->isBitField()) { 1783 FieldOffset = 1784 CGM.getObjCRuntime().ComputeBitfieldBitOffset(CGM, ID, Field); 1785 FieldOffset %= CGM.getContext().getCharWidth(); 1786 } else { 1787 FieldOffset = 0; 1788 } 1789 } else { 1790 FieldOffset = RL.getFieldOffset(FieldNo); 1791 } 1792 1793 unsigned Flags = 0; 1794 if (Field->getAccessControl() == ObjCIvarDecl::Protected) 1795 Flags = llvm::DINode::FlagProtected; 1796 else if (Field->getAccessControl() == ObjCIvarDecl::Private) 1797 Flags = llvm::DINode::FlagPrivate; 1798 else if (Field->getAccessControl() == ObjCIvarDecl::Public) 1799 Flags = llvm::DINode::FlagPublic; 1800 1801 llvm::MDNode *PropertyNode = nullptr; 1802 if (ObjCImplementationDecl *ImpD = ID->getImplementation()) { 1803 if (ObjCPropertyImplDecl *PImpD = 1804 ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) { 1805 if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) { 1806 SourceLocation Loc = PD->getLocation(); 1807 llvm::DIFile *PUnit = getOrCreateFile(Loc); 1808 unsigned PLine = getLineNumber(Loc); 1809 ObjCMethodDecl *Getter = PD->getGetterMethodDecl(); 1810 ObjCMethodDecl *Setter = PD->getSetterMethodDecl(); 1811 PropertyNode = DBuilder.createObjCProperty( 1812 PD->getName(), PUnit, PLine, 1813 hasDefaultGetterName(PD, Getter) ? "" : getSelectorName( 1814 PD->getGetterName()), 1815 hasDefaultSetterName(PD, Setter) ? "" : getSelectorName( 1816 PD->getSetterName()), 1817 PD->getPropertyAttributes(), 1818 getOrCreateType(PD->getType(), PUnit)); 1819 } 1820 } 1821 } 1822 FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit, FieldLine, 1823 FieldSize, FieldAlign, FieldOffset, Flags, 1824 FieldTy, PropertyNode); 1825 EltTys.push_back(FieldTy); 1826 } 1827 1828 llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys); 1829 DBuilder.replaceArrays(RealDecl, Elements); 1830 1831 LexicalBlockStack.pop_back(); 1832 return RealDecl; 1833 } 1834 1835 llvm::DIType *CGDebugInfo::CreateType(const VectorType *Ty, 1836 llvm::DIFile *Unit) { 1837 llvm::DIType *ElementTy = getOrCreateType(Ty->getElementType(), Unit); 1838 int64_t Count = Ty->getNumElements(); 1839 if (Count == 0) 1840 // If number of elements are not known then this is an unbounded array. 1841 // Use Count == -1 to express such arrays. 1842 Count = -1; 1843 1844 llvm::Metadata *Subscript = DBuilder.getOrCreateSubrange(0, Count); 1845 llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscript); 1846 1847 uint64_t Size = CGM.getContext().getTypeSize(Ty); 1848 uint64_t Align = CGM.getContext().getTypeAlign(Ty); 1849 1850 return DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray); 1851 } 1852 1853 llvm::DIType *CGDebugInfo::CreateType(const ArrayType *Ty, llvm::DIFile *Unit) { 1854 uint64_t Size; 1855 uint64_t Align; 1856 1857 // FIXME: make getTypeAlign() aware of VLAs and incomplete array types 1858 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) { 1859 Size = 0; 1860 Align = 1861 CGM.getContext().getTypeAlign(CGM.getContext().getBaseElementType(VAT)); 1862 } else if (Ty->isIncompleteArrayType()) { 1863 Size = 0; 1864 if (Ty->getElementType()->isIncompleteType()) 1865 Align = 0; 1866 else 1867 Align = CGM.getContext().getTypeAlign(Ty->getElementType()); 1868 } else if (Ty->isIncompleteType()) { 1869 Size = 0; 1870 Align = 0; 1871 } else { 1872 // Size and align of the whole array, not the element type. 1873 Size = CGM.getContext().getTypeSize(Ty); 1874 Align = CGM.getContext().getTypeAlign(Ty); 1875 } 1876 1877 // Add the dimensions of the array. FIXME: This loses CV qualifiers from 1878 // interior arrays, do we care? Why aren't nested arrays represented the 1879 // obvious/recursive way? 1880 SmallVector<llvm::Metadata *, 8> Subscripts; 1881 QualType EltTy(Ty, 0); 1882 while ((Ty = dyn_cast<ArrayType>(EltTy))) { 1883 // If the number of elements is known, then count is that number. Otherwise, 1884 // it's -1. This allows us to represent a subrange with an array of 0 1885 // elements, like this: 1886 // 1887 // struct foo { 1888 // int x[0]; 1889 // }; 1890 int64_t Count = -1; // Count == -1 is an unbounded array. 1891 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty)) 1892 Count = CAT->getSize().getZExtValue(); 1893 1894 // FIXME: Verify this is right for VLAs. 1895 Subscripts.push_back(DBuilder.getOrCreateSubrange(0, Count)); 1896 EltTy = Ty->getElementType(); 1897 } 1898 1899 llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts); 1900 1901 return DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit), 1902 SubscriptArray); 1903 } 1904 1905 llvm::DIType *CGDebugInfo::CreateType(const LValueReferenceType *Ty, 1906 llvm::DIFile *Unit) { 1907 return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type, Ty, 1908 Ty->getPointeeType(), Unit); 1909 } 1910 1911 llvm::DIType *CGDebugInfo::CreateType(const RValueReferenceType *Ty, 1912 llvm::DIFile *Unit) { 1913 return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type, Ty, 1914 Ty->getPointeeType(), Unit); 1915 } 1916 1917 llvm::DIType *CGDebugInfo::CreateType(const MemberPointerType *Ty, 1918 llvm::DIFile *U) { 1919 uint64_t Size = 1920 !Ty->isIncompleteType() ? CGM.getContext().getTypeSize(Ty) : 0; 1921 llvm::DIType *ClassType = getOrCreateType(QualType(Ty->getClass(), 0), U); 1922 if (Ty->isMemberDataPointerType()) 1923 return DBuilder.createMemberPointerType( 1924 getOrCreateType(Ty->getPointeeType(), U), ClassType, Size); 1925 1926 const FunctionProtoType *FPT = 1927 Ty->getPointeeType()->getAs<FunctionProtoType>(); 1928 return DBuilder.createMemberPointerType( 1929 getOrCreateInstanceMethodType(CGM.getContext().getPointerType(QualType( 1930 Ty->getClass(), FPT->getTypeQuals())), 1931 FPT, U), 1932 ClassType, Size); 1933 } 1934 1935 llvm::DIType *CGDebugInfo::CreateType(const AtomicType *Ty, llvm::DIFile *U) { 1936 // Ignore the atomic wrapping 1937 // FIXME: What is the correct representation? 1938 return getOrCreateType(Ty->getValueType(), U); 1939 } 1940 1941 llvm::DIType *CGDebugInfo::CreateEnumType(const EnumType *Ty) { 1942 const EnumDecl *ED = Ty->getDecl(); 1943 1944 uint64_t Size = 0; 1945 uint64_t Align = 0; 1946 if (!ED->getTypeForDecl()->isIncompleteType()) { 1947 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl()); 1948 Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl()); 1949 } 1950 1951 SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU); 1952 1953 bool isImportedFromModule = 1954 DebugTypeExtRefs && ED->isFromASTFile() && ED->getDefinition(); 1955 1956 // If this is just a forward declaration, construct an appropriately 1957 // marked node and just return it. 1958 if (isImportedFromModule || !ED->getDefinition()) { 1959 llvm::DIScope *EDContext = getDeclContextDescriptor(ED); 1960 llvm::DIFile *DefUnit = getOrCreateFile(ED->getLocation()); 1961 unsigned Line = getLineNumber(ED->getLocation()); 1962 StringRef EDName = ED->getName(); 1963 llvm::DIType *RetTy = DBuilder.createReplaceableCompositeType( 1964 llvm::dwarf::DW_TAG_enumeration_type, EDName, EDContext, DefUnit, Line, 1965 0, Size, Align, llvm::DINode::FlagFwdDecl, FullName); 1966 ReplaceMap.emplace_back( 1967 std::piecewise_construct, std::make_tuple(Ty), 1968 std::make_tuple(static_cast<llvm::Metadata *>(RetTy))); 1969 return RetTy; 1970 } 1971 1972 return CreateTypeDefinition(Ty); 1973 } 1974 1975 llvm::DIType *CGDebugInfo::CreateTypeDefinition(const EnumType *Ty) { 1976 const EnumDecl *ED = Ty->getDecl(); 1977 uint64_t Size = 0; 1978 uint64_t Align = 0; 1979 if (!ED->getTypeForDecl()->isIncompleteType()) { 1980 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl()); 1981 Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl()); 1982 } 1983 1984 SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU); 1985 1986 // Create elements for each enumerator. 1987 SmallVector<llvm::Metadata *, 16> Enumerators; 1988 ED = ED->getDefinition(); 1989 for (const auto *Enum : ED->enumerators()) { 1990 Enumerators.push_back(DBuilder.createEnumerator( 1991 Enum->getName(), Enum->getInitVal().getSExtValue())); 1992 } 1993 1994 // Return a CompositeType for the enum itself. 1995 llvm::DINodeArray EltArray = DBuilder.getOrCreateArray(Enumerators); 1996 1997 llvm::DIFile *DefUnit = getOrCreateFile(ED->getLocation()); 1998 unsigned Line = getLineNumber(ED->getLocation()); 1999 llvm::DIScope *EnumContext = getDeclContextDescriptor(ED); 2000 llvm::DIType *ClassTy = 2001 ED->isFixed() ? getOrCreateType(ED->getIntegerType(), DefUnit) : nullptr; 2002 return DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit, 2003 Line, Size, Align, EltArray, ClassTy, 2004 FullName); 2005 } 2006 2007 static QualType UnwrapTypeForDebugInfo(QualType T, const ASTContext &C) { 2008 Qualifiers Quals; 2009 do { 2010 Qualifiers InnerQuals = T.getLocalQualifiers(); 2011 // Qualifiers::operator+() doesn't like it if you add a Qualifier 2012 // that is already there. 2013 Quals += Qualifiers::removeCommonQualifiers(Quals, InnerQuals); 2014 Quals += InnerQuals; 2015 QualType LastT = T; 2016 switch (T->getTypeClass()) { 2017 default: 2018 return C.getQualifiedType(T.getTypePtr(), Quals); 2019 case Type::TemplateSpecialization: { 2020 const auto *Spec = cast<TemplateSpecializationType>(T); 2021 if (Spec->isTypeAlias()) 2022 return C.getQualifiedType(T.getTypePtr(), Quals); 2023 T = Spec->desugar(); 2024 break; 2025 } 2026 case Type::TypeOfExpr: 2027 T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType(); 2028 break; 2029 case Type::TypeOf: 2030 T = cast<TypeOfType>(T)->getUnderlyingType(); 2031 break; 2032 case Type::Decltype: 2033 T = cast<DecltypeType>(T)->getUnderlyingType(); 2034 break; 2035 case Type::UnaryTransform: 2036 T = cast<UnaryTransformType>(T)->getUnderlyingType(); 2037 break; 2038 case Type::Attributed: 2039 T = cast<AttributedType>(T)->getEquivalentType(); 2040 break; 2041 case Type::Elaborated: 2042 T = cast<ElaboratedType>(T)->getNamedType(); 2043 break; 2044 case Type::Paren: 2045 T = cast<ParenType>(T)->getInnerType(); 2046 break; 2047 case Type::SubstTemplateTypeParm: 2048 T = cast<SubstTemplateTypeParmType>(T)->getReplacementType(); 2049 break; 2050 case Type::Auto: 2051 QualType DT = cast<AutoType>(T)->getDeducedType(); 2052 assert(!DT.isNull() && "Undeduced types shouldn't reach here."); 2053 T = DT; 2054 break; 2055 } 2056 2057 assert(T != LastT && "Type unwrapping failed to unwrap!"); 2058 (void)LastT; 2059 } while (true); 2060 } 2061 2062 llvm::DIType *CGDebugInfo::getTypeOrNull(QualType Ty) { 2063 2064 // Unwrap the type as needed for debug information. 2065 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext()); 2066 2067 auto it = TypeCache.find(Ty.getAsOpaquePtr()); 2068 if (it != TypeCache.end()) { 2069 // Verify that the debug info still exists. 2070 if (llvm::Metadata *V = it->second) 2071 return cast<llvm::DIType>(V); 2072 } 2073 2074 return nullptr; 2075 } 2076 2077 void CGDebugInfo::completeTemplateDefinition( 2078 const ClassTemplateSpecializationDecl &SD) { 2079 if (DebugKind <= CodeGenOptions::DebugLineTablesOnly) 2080 return; 2081 2082 completeClassData(&SD); 2083 // In case this type has no member function definitions being emitted, ensure 2084 // it is retained 2085 RetainedTypes.push_back(CGM.getContext().getRecordType(&SD).getAsOpaquePtr()); 2086 } 2087 2088 llvm::DIType *CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile *Unit) { 2089 if (Ty.isNull()) 2090 return nullptr; 2091 2092 // Unwrap the type as needed for debug information. 2093 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext()); 2094 2095 if (auto *T = getTypeOrNull(Ty)) 2096 return T; 2097 2098 llvm::DIType *Res = CreateTypeNode(Ty, Unit); 2099 void* TyPtr = Ty.getAsOpaquePtr(); 2100 2101 // And update the type cache. 2102 TypeCache[TyPtr].reset(Res); 2103 2104 return Res; 2105 } 2106 2107 unsigned CGDebugInfo::Checksum(const ObjCInterfaceDecl *ID) { 2108 // The assumption is that the number of ivars can only increase 2109 // monotonically, so it is safe to just use their current number as 2110 // a checksum. 2111 unsigned Sum = 0; 2112 for (const ObjCIvarDecl *Ivar = ID->all_declared_ivar_begin(); 2113 Ivar != nullptr; Ivar = Ivar->getNextIvar()) 2114 ++Sum; 2115 2116 return Sum; 2117 } 2118 2119 ObjCInterfaceDecl *CGDebugInfo::getObjCInterfaceDecl(QualType Ty) { 2120 switch (Ty->getTypeClass()) { 2121 case Type::ObjCObjectPointer: 2122 return getObjCInterfaceDecl( 2123 cast<ObjCObjectPointerType>(Ty)->getPointeeType()); 2124 case Type::ObjCInterface: 2125 return cast<ObjCInterfaceType>(Ty)->getDecl(); 2126 default: 2127 return nullptr; 2128 } 2129 } 2130 2131 llvm::DIModule *CGDebugInfo::getParentModuleOrNull(const Decl *D) { 2132 if (!DebugTypeExtRefs || !D->isFromASTFile()) 2133 return nullptr; 2134 2135 llvm::DIModule *ModuleRef = nullptr; 2136 auto *Reader = CGM.getContext().getExternalSource(); 2137 auto Idx = D->getOwningModuleID(); 2138 auto Info = Reader->getSourceDescriptor(Idx); 2139 if (Info) 2140 ModuleRef = getOrCreateModuleRef(*Info); 2141 return ModuleRef; 2142 } 2143 2144 llvm::DIType *CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile *Unit) { 2145 // Handle qualifiers, which recursively handles what they refer to. 2146 if (Ty.hasLocalQualifiers()) 2147 return CreateQualifiedType(Ty, Unit); 2148 2149 // Work out details of type. 2150 switch (Ty->getTypeClass()) { 2151 #define TYPE(Class, Base) 2152 #define ABSTRACT_TYPE(Class, Base) 2153 #define NON_CANONICAL_TYPE(Class, Base) 2154 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 2155 #include "clang/AST/TypeNodes.def" 2156 llvm_unreachable("Dependent types cannot show up in debug information"); 2157 2158 case Type::ExtVector: 2159 case Type::Vector: 2160 return CreateType(cast<VectorType>(Ty), Unit); 2161 case Type::ObjCObjectPointer: 2162 return CreateType(cast<ObjCObjectPointerType>(Ty), Unit); 2163 case Type::ObjCObject: 2164 return CreateType(cast<ObjCObjectType>(Ty), Unit); 2165 case Type::ObjCInterface: 2166 return CreateType(cast<ObjCInterfaceType>(Ty), Unit); 2167 case Type::Builtin: 2168 return CreateType(cast<BuiltinType>(Ty)); 2169 case Type::Complex: 2170 return CreateType(cast<ComplexType>(Ty)); 2171 case Type::Pointer: 2172 return CreateType(cast<PointerType>(Ty), Unit); 2173 case Type::Adjusted: 2174 case Type::Decayed: 2175 // Decayed and adjusted types use the adjusted type in LLVM and DWARF. 2176 return CreateType( 2177 cast<PointerType>(cast<AdjustedType>(Ty)->getAdjustedType()), Unit); 2178 case Type::BlockPointer: 2179 return CreateType(cast<BlockPointerType>(Ty), Unit); 2180 case Type::Typedef: 2181 return CreateType(cast<TypedefType>(Ty), Unit); 2182 case Type::Record: 2183 return CreateType(cast<RecordType>(Ty)); 2184 case Type::Enum: 2185 return CreateEnumType(cast<EnumType>(Ty)); 2186 case Type::FunctionProto: 2187 case Type::FunctionNoProto: 2188 return CreateType(cast<FunctionType>(Ty), Unit); 2189 case Type::ConstantArray: 2190 case Type::VariableArray: 2191 case Type::IncompleteArray: 2192 return CreateType(cast<ArrayType>(Ty), Unit); 2193 2194 case Type::LValueReference: 2195 return CreateType(cast<LValueReferenceType>(Ty), Unit); 2196 case Type::RValueReference: 2197 return CreateType(cast<RValueReferenceType>(Ty), Unit); 2198 2199 case Type::MemberPointer: 2200 return CreateType(cast<MemberPointerType>(Ty), Unit); 2201 2202 case Type::Atomic: 2203 return CreateType(cast<AtomicType>(Ty), Unit); 2204 2205 case Type::TemplateSpecialization: 2206 return CreateType(cast<TemplateSpecializationType>(Ty), Unit); 2207 2208 case Type::Auto: 2209 case Type::Attributed: 2210 case Type::Elaborated: 2211 case Type::Paren: 2212 case Type::SubstTemplateTypeParm: 2213 case Type::TypeOfExpr: 2214 case Type::TypeOf: 2215 case Type::Decltype: 2216 case Type::UnaryTransform: 2217 case Type::PackExpansion: 2218 break; 2219 } 2220 2221 llvm_unreachable("type should have been unwrapped!"); 2222 } 2223 2224 llvm::DICompositeType *CGDebugInfo::getOrCreateLimitedType(const RecordType *Ty, 2225 llvm::DIFile *Unit) { 2226 QualType QTy(Ty, 0); 2227 2228 auto *T = cast_or_null<llvm::DICompositeType>(getTypeOrNull(QTy)); 2229 2230 // We may have cached a forward decl when we could have created 2231 // a non-forward decl. Go ahead and create a non-forward decl 2232 // now. 2233 if (T && !T->isForwardDecl()) 2234 return T; 2235 2236 // Otherwise create the type. 2237 llvm::DICompositeType *Res = CreateLimitedType(Ty); 2238 2239 // Propagate members from the declaration to the definition 2240 // CreateType(const RecordType*) will overwrite this with the members in the 2241 // correct order if the full type is needed. 2242 DBuilder.replaceArrays(Res, T ? T->getElements() : llvm::DINodeArray()); 2243 2244 // And update the type cache. 2245 TypeCache[QTy.getAsOpaquePtr()].reset(Res); 2246 return Res; 2247 } 2248 2249 // TODO: Currently used for context chains when limiting debug info. 2250 llvm::DICompositeType *CGDebugInfo::CreateLimitedType(const RecordType *Ty) { 2251 RecordDecl *RD = Ty->getDecl(); 2252 2253 // Get overall information about the record type for the debug info. 2254 llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation()); 2255 unsigned Line = getLineNumber(RD->getLocation()); 2256 StringRef RDName = getClassName(RD); 2257 2258 llvm::DIScope *RDContext = getDeclContextDescriptor(RD); 2259 2260 // If we ended up creating the type during the context chain construction, 2261 // just return that. 2262 auto *T = cast_or_null<llvm::DICompositeType>( 2263 getTypeOrNull(CGM.getContext().getRecordType(RD))); 2264 if (T && (!T->isForwardDecl() || !RD->getDefinition())) 2265 return T; 2266 2267 // If this is just a forward or incomplete declaration, construct an 2268 // appropriately marked node and just return it. 2269 const RecordDecl *D = RD->getDefinition(); 2270 if (!D || !D->isCompleteDefinition()) 2271 return getOrCreateRecordFwdDecl(Ty, RDContext); 2272 2273 uint64_t Size = CGM.getContext().getTypeSize(Ty); 2274 uint64_t Align = CGM.getContext().getTypeAlign(Ty); 2275 2276 SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU); 2277 2278 llvm::DICompositeType *RealDecl = DBuilder.createReplaceableCompositeType( 2279 getTagForRecord(RD), RDName, RDContext, DefUnit, Line, 0, Size, Align, 0, 2280 FullName); 2281 2282 RegionMap[Ty->getDecl()].reset(RealDecl); 2283 TypeCache[QualType(Ty, 0).getAsOpaquePtr()].reset(RealDecl); 2284 2285 if (const ClassTemplateSpecializationDecl *TSpecial = 2286 dyn_cast<ClassTemplateSpecializationDecl>(RD)) 2287 DBuilder.replaceArrays(RealDecl, llvm::DINodeArray(), 2288 CollectCXXTemplateParams(TSpecial, DefUnit)); 2289 return RealDecl; 2290 } 2291 2292 void CGDebugInfo::CollectContainingType(const CXXRecordDecl *RD, 2293 llvm::DICompositeType *RealDecl) { 2294 // A class's primary base or the class itself contains the vtable. 2295 llvm::DICompositeType *ContainingType = nullptr; 2296 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD); 2297 if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) { 2298 // Seek non-virtual primary base root. 2299 while (1) { 2300 const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase); 2301 const CXXRecordDecl *PBT = BRL.getPrimaryBase(); 2302 if (PBT && !BRL.isPrimaryBaseVirtual()) 2303 PBase = PBT; 2304 else 2305 break; 2306 } 2307 ContainingType = cast<llvm::DICompositeType>( 2308 getOrCreateType(QualType(PBase->getTypeForDecl(), 0), 2309 getOrCreateFile(RD->getLocation()))); 2310 } else if (RD->isDynamicClass()) 2311 ContainingType = RealDecl; 2312 2313 DBuilder.replaceVTableHolder(RealDecl, ContainingType); 2314 } 2315 2316 llvm::DIType *CGDebugInfo::CreateMemberType(llvm::DIFile *Unit, QualType FType, 2317 StringRef Name, uint64_t *Offset) { 2318 llvm::DIType *FieldTy = CGDebugInfo::getOrCreateType(FType, Unit); 2319 uint64_t FieldSize = CGM.getContext().getTypeSize(FType); 2320 unsigned FieldAlign = CGM.getContext().getTypeAlign(FType); 2321 llvm::DIType *Ty = DBuilder.createMemberType(Unit, Name, Unit, 0, FieldSize, 2322 FieldAlign, *Offset, 0, FieldTy); 2323 *Offset += FieldSize; 2324 return Ty; 2325 } 2326 2327 void CGDebugInfo::collectFunctionDeclProps(GlobalDecl GD, llvm::DIFile *Unit, 2328 StringRef &Name, 2329 StringRef &LinkageName, 2330 llvm::DIScope *&FDContext, 2331 llvm::DINodeArray &TParamsArray, 2332 unsigned &Flags) { 2333 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl()); 2334 Name = getFunctionName(FD); 2335 // Use mangled name as linkage name for C/C++ functions. 2336 if (FD->hasPrototype()) { 2337 LinkageName = CGM.getMangledName(GD); 2338 Flags |= llvm::DINode::FlagPrototyped; 2339 } 2340 // No need to replicate the linkage name if it isn't different from the 2341 // subprogram name, no need to have it at all unless coverage is enabled or 2342 // debug is set to more than just line tables. 2343 if (LinkageName == Name || 2344 (!CGM.getCodeGenOpts().EmitGcovArcs && 2345 !CGM.getCodeGenOpts().EmitGcovNotes && 2346 DebugKind <= CodeGenOptions::DebugLineTablesOnly)) 2347 LinkageName = StringRef(); 2348 2349 if (DebugKind >= CodeGenOptions::LimitedDebugInfo) { 2350 if (const NamespaceDecl *NSDecl = 2351 dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext())) 2352 FDContext = getOrCreateNameSpace(NSDecl); 2353 else if (const RecordDecl *RDecl = 2354 dyn_cast_or_null<RecordDecl>(FD->getDeclContext())) { 2355 llvm::DIScope *Mod = getParentModuleOrNull(RDecl); 2356 FDContext = getContextDescriptor(RDecl, Mod ? Mod : TheCU); 2357 } 2358 // Collect template parameters. 2359 TParamsArray = CollectFunctionTemplateParams(FD, Unit); 2360 } 2361 } 2362 2363 void CGDebugInfo::collectVarDeclProps(const VarDecl *VD, llvm::DIFile *&Unit, 2364 unsigned &LineNo, QualType &T, 2365 StringRef &Name, StringRef &LinkageName, 2366 llvm::DIScope *&VDContext) { 2367 Unit = getOrCreateFile(VD->getLocation()); 2368 LineNo = getLineNumber(VD->getLocation()); 2369 2370 setLocation(VD->getLocation()); 2371 2372 T = VD->getType(); 2373 if (T->isIncompleteArrayType()) { 2374 // CodeGen turns int[] into int[1] so we'll do the same here. 2375 llvm::APInt ConstVal(32, 1); 2376 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType(); 2377 2378 T = CGM.getContext().getConstantArrayType(ET, ConstVal, 2379 ArrayType::Normal, 0); 2380 } 2381 2382 Name = VD->getName(); 2383 if (VD->getDeclContext() && !isa<FunctionDecl>(VD->getDeclContext()) && 2384 !isa<ObjCMethodDecl>(VD->getDeclContext())) 2385 LinkageName = CGM.getMangledName(VD); 2386 if (LinkageName == Name) 2387 LinkageName = StringRef(); 2388 2389 // Since we emit declarations (DW_AT_members) for static members, place the 2390 // definition of those static members in the namespace they were declared in 2391 // in the source code (the lexical decl context). 2392 // FIXME: Generalize this for even non-member global variables where the 2393 // declaration and definition may have different lexical decl contexts, once 2394 // we have support for emitting declarations of (non-member) global variables. 2395 const DeclContext *DC = VD->isStaticDataMember() ? VD->getLexicalDeclContext() 2396 : VD->getDeclContext(); 2397 // When a record type contains an in-line initialization of a static data 2398 // member, and the record type is marked as __declspec(dllexport), an implicit 2399 // definition of the member will be created in the record context. DWARF 2400 // doesn't seem to have a nice way to describe this in a form that consumers 2401 // are likely to understand, so fake the "normal" situation of a definition 2402 // outside the class by putting it in the global scope. 2403 if (DC->isRecord()) 2404 DC = CGM.getContext().getTranslationUnitDecl(); 2405 2406 llvm::DIScope *Mod = getParentModuleOrNull(VD); 2407 VDContext = getContextDescriptor(cast<Decl>(DC), Mod ? Mod : TheCU); 2408 } 2409 2410 llvm::DISubprogram * 2411 CGDebugInfo::getFunctionForwardDeclaration(const FunctionDecl *FD) { 2412 llvm::DINodeArray TParamsArray; 2413 StringRef Name, LinkageName; 2414 unsigned Flags = 0; 2415 SourceLocation Loc = FD->getLocation(); 2416 llvm::DIFile *Unit = getOrCreateFile(Loc); 2417 llvm::DIScope *DContext = Unit; 2418 unsigned Line = getLineNumber(Loc); 2419 2420 collectFunctionDeclProps(FD, Unit, Name, LinkageName, DContext, 2421 TParamsArray, Flags); 2422 // Build function type. 2423 SmallVector<QualType, 16> ArgTypes; 2424 for (const ParmVarDecl *Parm: FD->parameters()) 2425 ArgTypes.push_back(Parm->getType()); 2426 QualType FnType = 2427 CGM.getContext().getFunctionType(FD->getReturnType(), ArgTypes, 2428 FunctionProtoType::ExtProtoInfo()); 2429 llvm::DISubprogram *SP = DBuilder.createTempFunctionFwdDecl( 2430 DContext, Name, LinkageName, Unit, Line, 2431 getOrCreateFunctionType(FD, FnType, Unit), !FD->isExternallyVisible(), 2432 /* isDefinition = */ false, 0, Flags, CGM.getLangOpts().Optimize, nullptr, 2433 TParamsArray.get(), getFunctionDeclaration(FD)); 2434 const FunctionDecl *CanonDecl = cast<FunctionDecl>(FD->getCanonicalDecl()); 2435 FwdDeclReplaceMap.emplace_back(std::piecewise_construct, 2436 std::make_tuple(CanonDecl), 2437 std::make_tuple(SP)); 2438 return SP; 2439 } 2440 2441 llvm::DIGlobalVariable * 2442 CGDebugInfo::getGlobalVariableForwardDeclaration(const VarDecl *VD) { 2443 QualType T; 2444 StringRef Name, LinkageName; 2445 SourceLocation Loc = VD->getLocation(); 2446 llvm::DIFile *Unit = getOrCreateFile(Loc); 2447 llvm::DIScope *DContext = Unit; 2448 unsigned Line = getLineNumber(Loc); 2449 2450 collectVarDeclProps(VD, Unit, Line, T, Name, LinkageName, DContext); 2451 auto *GV = DBuilder.createTempGlobalVariableFwdDecl( 2452 DContext, Name, LinkageName, Unit, Line, getOrCreateType(T, Unit), 2453 !VD->isExternallyVisible(), nullptr, nullptr); 2454 FwdDeclReplaceMap.emplace_back( 2455 std::piecewise_construct, 2456 std::make_tuple(cast<VarDecl>(VD->getCanonicalDecl())), 2457 std::make_tuple(static_cast<llvm::Metadata *>(GV))); 2458 return GV; 2459 } 2460 2461 llvm::DINode *CGDebugInfo::getDeclarationOrDefinition(const Decl *D) { 2462 // We only need a declaration (not a definition) of the type - so use whatever 2463 // we would otherwise do to get a type for a pointee. (forward declarations in 2464 // limited debug info, full definitions (if the type definition is available) 2465 // in unlimited debug info) 2466 if (const TypeDecl *TD = dyn_cast<TypeDecl>(D)) 2467 return getOrCreateType(CGM.getContext().getTypeDeclType(TD), 2468 getOrCreateFile(TD->getLocation())); 2469 auto I = DeclCache.find(D->getCanonicalDecl()); 2470 2471 if (I != DeclCache.end()) 2472 return dyn_cast_or_null<llvm::DINode>(I->second); 2473 2474 // No definition for now. Emit a forward definition that might be 2475 // merged with a potential upcoming definition. 2476 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) 2477 return getFunctionForwardDeclaration(FD); 2478 else if (const auto *VD = dyn_cast<VarDecl>(D)) 2479 return getGlobalVariableForwardDeclaration(VD); 2480 2481 return nullptr; 2482 } 2483 2484 llvm::DISubprogram *CGDebugInfo::getFunctionDeclaration(const Decl *D) { 2485 if (!D || DebugKind <= CodeGenOptions::DebugLineTablesOnly) 2486 return nullptr; 2487 2488 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D); 2489 if (!FD) 2490 return nullptr; 2491 2492 // Setup context. 2493 auto *S = getDeclContextDescriptor(D); 2494 2495 auto MI = SPCache.find(FD->getCanonicalDecl()); 2496 if (MI == SPCache.end()) { 2497 if (const CXXMethodDecl *MD = 2498 dyn_cast<CXXMethodDecl>(FD->getCanonicalDecl())) { 2499 return CreateCXXMemberFunction(MD, getOrCreateFile(MD->getLocation()), 2500 cast<llvm::DICompositeType>(S)); 2501 } 2502 } 2503 if (MI != SPCache.end()) { 2504 auto *SP = dyn_cast_or_null<llvm::DISubprogram>(MI->second); 2505 if (SP && !SP->isDefinition()) 2506 return SP; 2507 } 2508 2509 for (auto NextFD : FD->redecls()) { 2510 auto MI = SPCache.find(NextFD->getCanonicalDecl()); 2511 if (MI != SPCache.end()) { 2512 auto *SP = dyn_cast_or_null<llvm::DISubprogram>(MI->second); 2513 if (SP && !SP->isDefinition()) 2514 return SP; 2515 } 2516 } 2517 return nullptr; 2518 } 2519 2520 // getOrCreateFunctionType - Construct type. If it is a c++ method, include 2521 // implicit parameter "this". 2522 llvm::DISubroutineType *CGDebugInfo::getOrCreateFunctionType(const Decl *D, 2523 QualType FnType, 2524 llvm::DIFile *F) { 2525 if (!D || DebugKind <= CodeGenOptions::DebugLineTablesOnly) 2526 // Create fake but valid subroutine type. Otherwise -verify would fail, and 2527 // subprogram DIE will miss DW_AT_decl_file and DW_AT_decl_line fields. 2528 return DBuilder.createSubroutineType(F, 2529 DBuilder.getOrCreateTypeArray(None)); 2530 2531 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 2532 return getOrCreateMethodType(Method, F); 2533 if (const ObjCMethodDecl *OMethod = dyn_cast<ObjCMethodDecl>(D)) { 2534 // Add "self" and "_cmd" 2535 SmallVector<llvm::Metadata *, 16> Elts; 2536 2537 // First element is always return type. For 'void' functions it is NULL. 2538 QualType ResultTy = OMethod->getReturnType(); 2539 2540 // Replace the instancetype keyword with the actual type. 2541 if (ResultTy == CGM.getContext().getObjCInstanceType()) 2542 ResultTy = CGM.getContext().getPointerType( 2543 QualType(OMethod->getClassInterface()->getTypeForDecl(), 0)); 2544 2545 Elts.push_back(getOrCreateType(ResultTy, F)); 2546 // "self" pointer is always first argument. 2547 QualType SelfDeclTy; 2548 if (auto *SelfDecl = OMethod->getSelfDecl()) 2549 SelfDeclTy = SelfDecl->getType(); 2550 else if (auto *FPT = dyn_cast<FunctionProtoType>(FnType)) 2551 if (FPT->getNumParams() > 1) 2552 SelfDeclTy = FPT->getParamType(0); 2553 if (!SelfDeclTy.isNull()) 2554 Elts.push_back(CreateSelfType(SelfDeclTy, getOrCreateType(SelfDeclTy, F))); 2555 // "_cmd" pointer is always second argument. 2556 Elts.push_back(DBuilder.createArtificialType( 2557 getOrCreateType(CGM.getContext().getObjCSelType(), F))); 2558 // Get rest of the arguments. 2559 for (const auto *PI : OMethod->params()) 2560 Elts.push_back(getOrCreateType(PI->getType(), F)); 2561 // Variadic methods need a special marker at the end of the type list. 2562 if (OMethod->isVariadic()) 2563 Elts.push_back(DBuilder.createUnspecifiedParameter()); 2564 2565 llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(Elts); 2566 return DBuilder.createSubroutineType(F, EltTypeArray); 2567 } 2568 2569 // Handle variadic function types; they need an additional 2570 // unspecified parameter. 2571 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) 2572 if (FD->isVariadic()) { 2573 SmallVector<llvm::Metadata *, 16> EltTys; 2574 EltTys.push_back(getOrCreateType(FD->getReturnType(), F)); 2575 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FnType)) 2576 for (unsigned i = 0, e = FPT->getNumParams(); i != e; ++i) 2577 EltTys.push_back(getOrCreateType(FPT->getParamType(i), F)); 2578 EltTys.push_back(DBuilder.createUnspecifiedParameter()); 2579 llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(EltTys); 2580 return DBuilder.createSubroutineType(F, EltTypeArray); 2581 } 2582 2583 return cast<llvm::DISubroutineType>(getOrCreateType(FnType, F)); 2584 } 2585 2586 void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, SourceLocation Loc, 2587 SourceLocation ScopeLoc, QualType FnType, 2588 llvm::Function *Fn, CGBuilderTy &Builder) { 2589 2590 StringRef Name; 2591 StringRef LinkageName; 2592 2593 FnBeginRegionCount.push_back(LexicalBlockStack.size()); 2594 2595 const Decl *D = GD.getDecl(); 2596 bool HasDecl = (D != nullptr); 2597 2598 unsigned Flags = 0; 2599 llvm::DIFile *Unit = getOrCreateFile(Loc); 2600 llvm::DIScope *FDContext = Unit; 2601 llvm::DINodeArray TParamsArray; 2602 if (!HasDecl) { 2603 // Use llvm function name. 2604 LinkageName = Fn->getName(); 2605 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 2606 // If there is a subprogram for this function available then use it. 2607 auto FI = SPCache.find(FD->getCanonicalDecl()); 2608 if (FI != SPCache.end()) { 2609 auto *SP = dyn_cast_or_null<llvm::DISubprogram>(FI->second); 2610 if (SP && SP->isDefinition()) { 2611 LexicalBlockStack.emplace_back(SP); 2612 RegionMap[D].reset(SP); 2613 return; 2614 } 2615 } 2616 collectFunctionDeclProps(GD, Unit, Name, LinkageName, FDContext, 2617 TParamsArray, Flags); 2618 } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) { 2619 Name = getObjCMethodName(OMD); 2620 Flags |= llvm::DINode::FlagPrototyped; 2621 } else { 2622 // Use llvm function name. 2623 Name = Fn->getName(); 2624 Flags |= llvm::DINode::FlagPrototyped; 2625 } 2626 if (!Name.empty() && Name[0] == '\01') 2627 Name = Name.substr(1); 2628 2629 if (!HasDecl || D->isImplicit()) { 2630 Flags |= llvm::DINode::FlagArtificial; 2631 // Artificial functions without a location should not silently reuse CurLoc. 2632 if (Loc.isInvalid()) 2633 CurLoc = SourceLocation(); 2634 } 2635 unsigned LineNo = getLineNumber(Loc); 2636 unsigned ScopeLine = getLineNumber(ScopeLoc); 2637 2638 // FIXME: The function declaration we're constructing here is mostly reusing 2639 // declarations from CXXMethodDecl and not constructing new ones for arbitrary 2640 // FunctionDecls. When/if we fix this we can have FDContext be TheCU/null for 2641 // all subprograms instead of the actual context since subprogram definitions 2642 // are emitted as CU level entities by the backend. 2643 llvm::DISubprogram *SP = DBuilder.createFunction( 2644 FDContext, Name, LinkageName, Unit, LineNo, 2645 getOrCreateFunctionType(D, FnType, Unit), Fn->hasInternalLinkage(), 2646 true /*definition*/, ScopeLine, Flags, CGM.getLangOpts().Optimize, Fn, 2647 TParamsArray.get(), getFunctionDeclaration(D)); 2648 // We might get here with a VarDecl in the case we're generating 2649 // code for the initialization of globals. Do not record these decls 2650 // as they will overwrite the actual VarDecl Decl in the cache. 2651 if (HasDecl && isa<FunctionDecl>(D)) 2652 DeclCache[D->getCanonicalDecl()].reset(static_cast<llvm::Metadata *>(SP)); 2653 2654 // Push the function onto the lexical block stack. 2655 LexicalBlockStack.emplace_back(SP); 2656 2657 if (HasDecl) 2658 RegionMap[D].reset(SP); 2659 } 2660 2661 void CGDebugInfo::EmitFunctionDecl(GlobalDecl GD, SourceLocation Loc, 2662 QualType FnType) { 2663 StringRef Name; 2664 StringRef LinkageName; 2665 2666 const Decl *D = GD.getDecl(); 2667 if (!D) 2668 return; 2669 2670 unsigned Flags = 0; 2671 llvm::DIFile *Unit = getOrCreateFile(Loc); 2672 llvm::DIScope *FDContext = Unit; 2673 llvm::DINodeArray TParamsArray; 2674 if (isa<FunctionDecl>(D)) { 2675 // If there is a DISubprogram for this function available then use it. 2676 collectFunctionDeclProps(GD, Unit, Name, LinkageName, FDContext, 2677 TParamsArray, Flags); 2678 } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) { 2679 Name = getObjCMethodName(OMD); 2680 Flags |= llvm::DINode::FlagPrototyped; 2681 } else { 2682 llvm_unreachable("not a function or ObjC method"); 2683 } 2684 if (!Name.empty() && Name[0] == '\01') 2685 Name = Name.substr(1); 2686 2687 if (D->isImplicit()) { 2688 Flags |= llvm::DINode::FlagArtificial; 2689 // Artificial functions without a location should not silently reuse CurLoc. 2690 if (Loc.isInvalid()) 2691 CurLoc = SourceLocation(); 2692 } 2693 unsigned LineNo = getLineNumber(Loc); 2694 unsigned ScopeLine = 0; 2695 2696 DBuilder.createFunction(FDContext, Name, LinkageName, Unit, LineNo, 2697 getOrCreateFunctionType(D, FnType, Unit), 2698 false /*internalLinkage*/, true /*definition*/, 2699 ScopeLine, Flags, CGM.getLangOpts().Optimize, nullptr, 2700 TParamsArray.get(), 2701 getFunctionDeclaration(D)); 2702 } 2703 2704 void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc) { 2705 // Update our current location 2706 setLocation(Loc); 2707 2708 if (CurLoc.isInvalid() || CurLoc.isMacroID()) 2709 return; 2710 2711 llvm::MDNode *Scope = LexicalBlockStack.back(); 2712 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get( 2713 getLineNumber(CurLoc), getColumnNumber(CurLoc), Scope)); 2714 } 2715 2716 void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) { 2717 llvm::MDNode *Back = nullptr; 2718 if (!LexicalBlockStack.empty()) 2719 Back = LexicalBlockStack.back().get(); 2720 LexicalBlockStack.emplace_back(DBuilder.createLexicalBlock( 2721 cast<llvm::DIScope>(Back), getOrCreateFile(CurLoc), getLineNumber(CurLoc), 2722 getColumnNumber(CurLoc))); 2723 } 2724 2725 void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder, 2726 SourceLocation Loc) { 2727 // Set our current location. 2728 setLocation(Loc); 2729 2730 // Emit a line table change for the current location inside the new scope. 2731 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get( 2732 getLineNumber(Loc), getColumnNumber(Loc), LexicalBlockStack.back())); 2733 2734 if (DebugKind <= CodeGenOptions::DebugLineTablesOnly) 2735 return; 2736 2737 // Create a new lexical block and push it on the stack. 2738 CreateLexicalBlock(Loc); 2739 } 2740 2741 void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder, 2742 SourceLocation Loc) { 2743 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!"); 2744 2745 // Provide an entry in the line table for the end of the block. 2746 EmitLocation(Builder, Loc); 2747 2748 if (DebugKind <= CodeGenOptions::DebugLineTablesOnly) 2749 return; 2750 2751 LexicalBlockStack.pop_back(); 2752 } 2753 2754 void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder) { 2755 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!"); 2756 unsigned RCount = FnBeginRegionCount.back(); 2757 assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch"); 2758 2759 // Pop all regions for this function. 2760 while (LexicalBlockStack.size() != RCount) { 2761 // Provide an entry in the line table for the end of the block. 2762 EmitLocation(Builder, CurLoc); 2763 LexicalBlockStack.pop_back(); 2764 } 2765 FnBeginRegionCount.pop_back(); 2766 } 2767 2768 llvm::DIType *CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD, 2769 uint64_t *XOffset) { 2770 2771 SmallVector<llvm::Metadata *, 5> EltTys; 2772 QualType FType; 2773 uint64_t FieldSize, FieldOffset; 2774 unsigned FieldAlign; 2775 2776 llvm::DIFile *Unit = getOrCreateFile(VD->getLocation()); 2777 QualType Type = VD->getType(); 2778 2779 FieldOffset = 0; 2780 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy); 2781 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset)); 2782 EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset)); 2783 FType = CGM.getContext().IntTy; 2784 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset)); 2785 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset)); 2786 2787 bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD); 2788 if (HasCopyAndDispose) { 2789 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy); 2790 EltTys.push_back( 2791 CreateMemberType(Unit, FType, "__copy_helper", &FieldOffset)); 2792 EltTys.push_back( 2793 CreateMemberType(Unit, FType, "__destroy_helper", &FieldOffset)); 2794 } 2795 bool HasByrefExtendedLayout; 2796 Qualifiers::ObjCLifetime Lifetime; 2797 if (CGM.getContext().getByrefLifetime(Type, Lifetime, 2798 HasByrefExtendedLayout) && 2799 HasByrefExtendedLayout) { 2800 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy); 2801 EltTys.push_back( 2802 CreateMemberType(Unit, FType, "__byref_variable_layout", &FieldOffset)); 2803 } 2804 2805 CharUnits Align = CGM.getContext().getDeclAlign(VD); 2806 if (Align > CGM.getContext().toCharUnitsFromBits( 2807 CGM.getTarget().getPointerAlign(0))) { 2808 CharUnits FieldOffsetInBytes = 2809 CGM.getContext().toCharUnitsFromBits(FieldOffset); 2810 CharUnits AlignedOffsetInBytes = 2811 FieldOffsetInBytes.RoundUpToAlignment(Align); 2812 CharUnits NumPaddingBytes = AlignedOffsetInBytes - FieldOffsetInBytes; 2813 2814 if (NumPaddingBytes.isPositive()) { 2815 llvm::APInt pad(32, NumPaddingBytes.getQuantity()); 2816 FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy, 2817 pad, ArrayType::Normal, 0); 2818 EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset)); 2819 } 2820 } 2821 2822 FType = Type; 2823 llvm::DIType *FieldTy = getOrCreateType(FType, Unit); 2824 FieldSize = CGM.getContext().getTypeSize(FType); 2825 FieldAlign = CGM.getContext().toBits(Align); 2826 2827 *XOffset = FieldOffset; 2828 FieldTy = DBuilder.createMemberType(Unit, VD->getName(), Unit, 0, FieldSize, 2829 FieldAlign, FieldOffset, 0, FieldTy); 2830 EltTys.push_back(FieldTy); 2831 FieldOffset += FieldSize; 2832 2833 llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys); 2834 2835 unsigned Flags = llvm::DINode::FlagBlockByrefStruct; 2836 2837 return DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0, Flags, 2838 nullptr, Elements); 2839 } 2840 2841 void CGDebugInfo::EmitDeclare(const VarDecl *VD, llvm::Value *Storage, 2842 llvm::Optional<unsigned> ArgNo, 2843 CGBuilderTy &Builder) { 2844 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo); 2845 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!"); 2846 2847 bool Unwritten = 2848 VD->isImplicit() || (isa<Decl>(VD->getDeclContext()) && 2849 cast<Decl>(VD->getDeclContext())->isImplicit()); 2850 llvm::DIFile *Unit = nullptr; 2851 if (!Unwritten) 2852 Unit = getOrCreateFile(VD->getLocation()); 2853 llvm::DIType *Ty; 2854 uint64_t XOffset = 0; 2855 if (VD->hasAttr<BlocksAttr>()) 2856 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset); 2857 else 2858 Ty = getOrCreateType(VD->getType(), Unit); 2859 2860 // If there is no debug info for this type then do not emit debug info 2861 // for this variable. 2862 if (!Ty) 2863 return; 2864 2865 // Get location information. 2866 unsigned Line = 0; 2867 unsigned Column = 0; 2868 if (!Unwritten) { 2869 Line = getLineNumber(VD->getLocation()); 2870 Column = getColumnNumber(VD->getLocation()); 2871 } 2872 SmallVector<int64_t, 9> Expr; 2873 unsigned Flags = 0; 2874 if (VD->isImplicit()) 2875 Flags |= llvm::DINode::FlagArtificial; 2876 // If this is the first argument and it is implicit then 2877 // give it an object pointer flag. 2878 // FIXME: There has to be a better way to do this, but for static 2879 // functions there won't be an implicit param at arg1 and 2880 // otherwise it is 'self' or 'this'. 2881 if (isa<ImplicitParamDecl>(VD) && ArgNo && *ArgNo == 1) 2882 Flags |= llvm::DINode::FlagObjectPointer; 2883 if (llvm::Argument *Arg = dyn_cast<llvm::Argument>(Storage)) 2884 if (Arg->getType()->isPointerTy() && !Arg->hasByValAttr() && 2885 !VD->getType()->isPointerType()) 2886 Expr.push_back(llvm::dwarf::DW_OP_deref); 2887 2888 auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back()); 2889 2890 StringRef Name = VD->getName(); 2891 if (!Name.empty()) { 2892 if (VD->hasAttr<BlocksAttr>()) { 2893 CharUnits offset = CharUnits::fromQuantity(32); 2894 Expr.push_back(llvm::dwarf::DW_OP_plus); 2895 // offset of __forwarding field 2896 offset = CGM.getContext().toCharUnitsFromBits( 2897 CGM.getTarget().getPointerWidth(0)); 2898 Expr.push_back(offset.getQuantity()); 2899 Expr.push_back(llvm::dwarf::DW_OP_deref); 2900 Expr.push_back(llvm::dwarf::DW_OP_plus); 2901 // offset of x field 2902 offset = CGM.getContext().toCharUnitsFromBits(XOffset); 2903 Expr.push_back(offset.getQuantity()); 2904 2905 // Create the descriptor for the variable. 2906 auto *D = ArgNo 2907 ? DBuilder.createParameterVariable(Scope, VD->getName(), 2908 *ArgNo, Unit, Line, Ty) 2909 : DBuilder.createAutoVariable(Scope, VD->getName(), Unit, 2910 Line, Ty); 2911 2912 // Insert an llvm.dbg.declare into the current block. 2913 DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr), 2914 llvm::DebugLoc::get(Line, Column, Scope), 2915 Builder.GetInsertBlock()); 2916 return; 2917 } else if (isa<VariableArrayType>(VD->getType())) 2918 Expr.push_back(llvm::dwarf::DW_OP_deref); 2919 } else if (const RecordType *RT = dyn_cast<RecordType>(VD->getType())) { 2920 // If VD is an anonymous union then Storage represents value for 2921 // all union fields. 2922 const RecordDecl *RD = cast<RecordDecl>(RT->getDecl()); 2923 if (RD->isUnion() && RD->isAnonymousStructOrUnion()) { 2924 // GDB has trouble finding local variables in anonymous unions, so we emit 2925 // artifical local variables for each of the members. 2926 // 2927 // FIXME: Remove this code as soon as GDB supports this. 2928 // The debug info verifier in LLVM operates based on the assumption that a 2929 // variable has the same size as its storage and we had to disable the check 2930 // for artificial variables. 2931 for (const auto *Field : RD->fields()) { 2932 llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit); 2933 StringRef FieldName = Field->getName(); 2934 2935 // Ignore unnamed fields. Do not ignore unnamed records. 2936 if (FieldName.empty() && !isa<RecordType>(Field->getType())) 2937 continue; 2938 2939 // Use VarDecl's Tag, Scope and Line number. 2940 auto *D = DBuilder.createAutoVariable( 2941 Scope, FieldName, Unit, Line, FieldTy, CGM.getLangOpts().Optimize, 2942 Flags | llvm::DINode::FlagArtificial); 2943 2944 // Insert an llvm.dbg.declare into the current block. 2945 DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr), 2946 llvm::DebugLoc::get(Line, Column, Scope), 2947 Builder.GetInsertBlock()); 2948 } 2949 } 2950 } 2951 2952 // Create the descriptor for the variable. 2953 auto *D = 2954 ArgNo 2955 ? DBuilder.createParameterVariable(Scope, Name, *ArgNo, Unit, Line, 2956 Ty, CGM.getLangOpts().Optimize, 2957 Flags) 2958 : DBuilder.createAutoVariable(Scope, Name, Unit, Line, Ty, 2959 CGM.getLangOpts().Optimize, Flags); 2960 2961 // Insert an llvm.dbg.declare into the current block. 2962 DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr), 2963 llvm::DebugLoc::get(Line, Column, Scope), 2964 Builder.GetInsertBlock()); 2965 } 2966 2967 void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD, 2968 llvm::Value *Storage, 2969 CGBuilderTy &Builder) { 2970 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo); 2971 EmitDeclare(VD, Storage, llvm::None, Builder); 2972 } 2973 2974 llvm::DIType *CGDebugInfo::CreateSelfType(const QualType &QualTy, 2975 llvm::DIType *Ty) { 2976 llvm::DIType *CachedTy = getTypeOrNull(QualTy); 2977 if (CachedTy) 2978 Ty = CachedTy; 2979 return DBuilder.createObjectPointerType(Ty); 2980 } 2981 2982 void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable( 2983 const VarDecl *VD, llvm::Value *Storage, CGBuilderTy &Builder, 2984 const CGBlockInfo &blockInfo, llvm::Instruction *InsertPoint) { 2985 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo); 2986 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!"); 2987 2988 if (Builder.GetInsertBlock() == nullptr) 2989 return; 2990 2991 bool isByRef = VD->hasAttr<BlocksAttr>(); 2992 2993 uint64_t XOffset = 0; 2994 llvm::DIFile *Unit = getOrCreateFile(VD->getLocation()); 2995 llvm::DIType *Ty; 2996 if (isByRef) 2997 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset); 2998 else 2999 Ty = getOrCreateType(VD->getType(), Unit); 3000 3001 // Self is passed along as an implicit non-arg variable in a 3002 // block. Mark it as the object pointer. 3003 if (isa<ImplicitParamDecl>(VD) && VD->getName() == "self") 3004 Ty = CreateSelfType(VD->getType(), Ty); 3005 3006 // Get location information. 3007 unsigned Line = getLineNumber(VD->getLocation()); 3008 unsigned Column = getColumnNumber(VD->getLocation()); 3009 3010 const llvm::DataLayout &target = CGM.getDataLayout(); 3011 3012 CharUnits offset = CharUnits::fromQuantity( 3013 target.getStructLayout(blockInfo.StructureType) 3014 ->getElementOffset(blockInfo.getCapture(VD).getIndex())); 3015 3016 SmallVector<int64_t, 9> addr; 3017 if (isa<llvm::AllocaInst>(Storage)) 3018 addr.push_back(llvm::dwarf::DW_OP_deref); 3019 addr.push_back(llvm::dwarf::DW_OP_plus); 3020 addr.push_back(offset.getQuantity()); 3021 if (isByRef) { 3022 addr.push_back(llvm::dwarf::DW_OP_deref); 3023 addr.push_back(llvm::dwarf::DW_OP_plus); 3024 // offset of __forwarding field 3025 offset = 3026 CGM.getContext().toCharUnitsFromBits(target.getPointerSizeInBits(0)); 3027 addr.push_back(offset.getQuantity()); 3028 addr.push_back(llvm::dwarf::DW_OP_deref); 3029 addr.push_back(llvm::dwarf::DW_OP_plus); 3030 // offset of x field 3031 offset = CGM.getContext().toCharUnitsFromBits(XOffset); 3032 addr.push_back(offset.getQuantity()); 3033 } 3034 3035 // Create the descriptor for the variable. 3036 auto *D = DBuilder.createAutoVariable( 3037 cast<llvm::DILocalScope>(LexicalBlockStack.back()), VD->getName(), Unit, 3038 Line, Ty); 3039 3040 // Insert an llvm.dbg.declare into the current block. 3041 auto DL = llvm::DebugLoc::get(Line, Column, LexicalBlockStack.back()); 3042 if (InsertPoint) 3043 DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(addr), DL, 3044 InsertPoint); 3045 else 3046 DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(addr), DL, 3047 Builder.GetInsertBlock()); 3048 } 3049 3050 void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI, 3051 unsigned ArgNo, 3052 CGBuilderTy &Builder) { 3053 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo); 3054 EmitDeclare(VD, AI, ArgNo, Builder); 3055 } 3056 3057 namespace { 3058 struct BlockLayoutChunk { 3059 uint64_t OffsetInBits; 3060 const BlockDecl::Capture *Capture; 3061 }; 3062 bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) { 3063 return l.OffsetInBits < r.OffsetInBits; 3064 } 3065 } 3066 3067 void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block, 3068 llvm::Value *Arg, 3069 unsigned ArgNo, 3070 llvm::Value *LocalAddr, 3071 CGBuilderTy &Builder) { 3072 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo); 3073 ASTContext &C = CGM.getContext(); 3074 const BlockDecl *blockDecl = block.getBlockDecl(); 3075 3076 // Collect some general information about the block's location. 3077 SourceLocation loc = blockDecl->getCaretLocation(); 3078 llvm::DIFile *tunit = getOrCreateFile(loc); 3079 unsigned line = getLineNumber(loc); 3080 unsigned column = getColumnNumber(loc); 3081 3082 // Build the debug-info type for the block literal. 3083 getDeclContextDescriptor(blockDecl); 3084 3085 const llvm::StructLayout *blockLayout = 3086 CGM.getDataLayout().getStructLayout(block.StructureType); 3087 3088 SmallVector<llvm::Metadata *, 16> fields; 3089 fields.push_back(createFieldType("__isa", C.VoidPtrTy, 0, loc, AS_public, 3090 blockLayout->getElementOffsetInBits(0), 3091 tunit, tunit)); 3092 fields.push_back(createFieldType("__flags", C.IntTy, 0, loc, AS_public, 3093 blockLayout->getElementOffsetInBits(1), 3094 tunit, tunit)); 3095 fields.push_back(createFieldType("__reserved", C.IntTy, 0, loc, AS_public, 3096 blockLayout->getElementOffsetInBits(2), 3097 tunit, tunit)); 3098 auto *FnTy = block.getBlockExpr()->getFunctionType(); 3099 auto FnPtrType = CGM.getContext().getPointerType(FnTy->desugar()); 3100 fields.push_back(createFieldType("__FuncPtr", FnPtrType, 0, loc, AS_public, 3101 blockLayout->getElementOffsetInBits(3), 3102 tunit, tunit)); 3103 fields.push_back(createFieldType( 3104 "__descriptor", C.getPointerType(block.NeedsCopyDispose 3105 ? C.getBlockDescriptorExtendedType() 3106 : C.getBlockDescriptorType()), 3107 0, loc, AS_public, blockLayout->getElementOffsetInBits(4), tunit, tunit)); 3108 3109 // We want to sort the captures by offset, not because DWARF 3110 // requires this, but because we're paranoid about debuggers. 3111 SmallVector<BlockLayoutChunk, 8> chunks; 3112 3113 // 'this' capture. 3114 if (blockDecl->capturesCXXThis()) { 3115 BlockLayoutChunk chunk; 3116 chunk.OffsetInBits = 3117 blockLayout->getElementOffsetInBits(block.CXXThisIndex); 3118 chunk.Capture = nullptr; 3119 chunks.push_back(chunk); 3120 } 3121 3122 // Variable captures. 3123 for (const auto &capture : blockDecl->captures()) { 3124 const VarDecl *variable = capture.getVariable(); 3125 const CGBlockInfo::Capture &captureInfo = block.getCapture(variable); 3126 3127 // Ignore constant captures. 3128 if (captureInfo.isConstant()) 3129 continue; 3130 3131 BlockLayoutChunk chunk; 3132 chunk.OffsetInBits = 3133 blockLayout->getElementOffsetInBits(captureInfo.getIndex()); 3134 chunk.Capture = &capture; 3135 chunks.push_back(chunk); 3136 } 3137 3138 // Sort by offset. 3139 llvm::array_pod_sort(chunks.begin(), chunks.end()); 3140 3141 for (SmallVectorImpl<BlockLayoutChunk>::iterator i = chunks.begin(), 3142 e = chunks.end(); 3143 i != e; ++i) { 3144 uint64_t offsetInBits = i->OffsetInBits; 3145 const BlockDecl::Capture *capture = i->Capture; 3146 3147 // If we have a null capture, this must be the C++ 'this' capture. 3148 if (!capture) { 3149 const CXXMethodDecl *method = 3150 cast<CXXMethodDecl>(blockDecl->getNonClosureContext()); 3151 QualType type = method->getThisType(C); 3152 3153 fields.push_back(createFieldType("this", type, 0, loc, AS_public, 3154 offsetInBits, tunit, tunit)); 3155 continue; 3156 } 3157 3158 const VarDecl *variable = capture->getVariable(); 3159 StringRef name = variable->getName(); 3160 3161 llvm::DIType *fieldType; 3162 if (capture->isByRef()) { 3163 TypeInfo PtrInfo = C.getTypeInfo(C.VoidPtrTy); 3164 3165 // FIXME: this creates a second copy of this type! 3166 uint64_t xoffset; 3167 fieldType = EmitTypeForVarWithBlocksAttr(variable, &xoffset); 3168 fieldType = DBuilder.createPointerType(fieldType, PtrInfo.Width); 3169 fieldType = 3170 DBuilder.createMemberType(tunit, name, tunit, line, PtrInfo.Width, 3171 PtrInfo.Align, offsetInBits, 0, fieldType); 3172 } else { 3173 fieldType = createFieldType(name, variable->getType(), 0, loc, AS_public, 3174 offsetInBits, tunit, tunit); 3175 } 3176 fields.push_back(fieldType); 3177 } 3178 3179 SmallString<36> typeName; 3180 llvm::raw_svector_ostream(typeName) << "__block_literal_" 3181 << CGM.getUniqueBlockCount(); 3182 3183 llvm::DINodeArray fieldsArray = DBuilder.getOrCreateArray(fields); 3184 3185 llvm::DIType *type = DBuilder.createStructType( 3186 tunit, typeName.str(), tunit, line, 3187 CGM.getContext().toBits(block.BlockSize), 3188 CGM.getContext().toBits(block.BlockAlign), 0, nullptr, fieldsArray); 3189 type = DBuilder.createPointerType(type, CGM.PointerWidthInBits); 3190 3191 // Get overall information about the block. 3192 unsigned flags = llvm::DINode::FlagArtificial; 3193 auto *scope = cast<llvm::DILocalScope>(LexicalBlockStack.back()); 3194 3195 // Create the descriptor for the parameter. 3196 auto *debugVar = DBuilder.createParameterVariable( 3197 scope, Arg->getName(), ArgNo, tunit, line, type, 3198 CGM.getLangOpts().Optimize, flags); 3199 3200 if (LocalAddr) { 3201 // Insert an llvm.dbg.value into the current block. 3202 DBuilder.insertDbgValueIntrinsic( 3203 LocalAddr, 0, debugVar, DBuilder.createExpression(), 3204 llvm::DebugLoc::get(line, column, scope), Builder.GetInsertBlock()); 3205 } 3206 3207 // Insert an llvm.dbg.declare into the current block. 3208 DBuilder.insertDeclare(Arg, debugVar, DBuilder.createExpression(), 3209 llvm::DebugLoc::get(line, column, scope), 3210 Builder.GetInsertBlock()); 3211 } 3212 3213 llvm::DIDerivedType * 3214 CGDebugInfo::getOrCreateStaticDataMemberDeclarationOrNull(const VarDecl *D) { 3215 if (!D->isStaticDataMember()) 3216 return nullptr; 3217 3218 auto MI = StaticDataMemberCache.find(D->getCanonicalDecl()); 3219 if (MI != StaticDataMemberCache.end()) { 3220 assert(MI->second && "Static data member declaration should still exist"); 3221 return MI->second; 3222 } 3223 3224 // If the member wasn't found in the cache, lazily construct and add it to the 3225 // type (used when a limited form of the type is emitted). 3226 auto DC = D->getDeclContext(); 3227 auto *Ctxt = cast<llvm::DICompositeType>(getDeclContextDescriptor(D)); 3228 return CreateRecordStaticField(D, Ctxt, cast<RecordDecl>(DC)); 3229 } 3230 3231 llvm::DIGlobalVariable *CGDebugInfo::CollectAnonRecordDecls( 3232 const RecordDecl *RD, llvm::DIFile *Unit, unsigned LineNo, 3233 StringRef LinkageName, llvm::GlobalVariable *Var, llvm::DIScope *DContext) { 3234 llvm::DIGlobalVariable *GV = nullptr; 3235 3236 for (const auto *Field : RD->fields()) { 3237 llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit); 3238 StringRef FieldName = Field->getName(); 3239 3240 // Ignore unnamed fields, but recurse into anonymous records. 3241 if (FieldName.empty()) { 3242 const RecordType *RT = dyn_cast<RecordType>(Field->getType()); 3243 if (RT) 3244 GV = CollectAnonRecordDecls(RT->getDecl(), Unit, LineNo, LinkageName, 3245 Var, DContext); 3246 continue; 3247 } 3248 // Use VarDecl's Tag, Scope and Line number. 3249 GV = DBuilder.createGlobalVariable(DContext, FieldName, LinkageName, Unit, 3250 LineNo, FieldTy, 3251 Var->hasInternalLinkage(), Var, nullptr); 3252 } 3253 return GV; 3254 } 3255 3256 void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var, 3257 const VarDecl *D) { 3258 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo); 3259 // Create global variable debug descriptor. 3260 llvm::DIFile *Unit = nullptr; 3261 llvm::DIScope *DContext = nullptr; 3262 unsigned LineNo; 3263 StringRef DeclName, LinkageName; 3264 QualType T; 3265 collectVarDeclProps(D, Unit, LineNo, T, DeclName, LinkageName, DContext); 3266 3267 // Attempt to store one global variable for the declaration - even if we 3268 // emit a lot of fields. 3269 llvm::DIGlobalVariable *GV = nullptr; 3270 3271 // If this is an anonymous union then we'll want to emit a global 3272 // variable for each member of the anonymous union so that it's possible 3273 // to find the name of any field in the union. 3274 if (T->isUnionType() && DeclName.empty()) { 3275 const RecordDecl *RD = cast<RecordType>(T)->getDecl(); 3276 assert(RD->isAnonymousStructOrUnion() && 3277 "unnamed non-anonymous struct or union?"); 3278 GV = CollectAnonRecordDecls(RD, Unit, LineNo, LinkageName, Var, DContext); 3279 } else { 3280 GV = DBuilder.createGlobalVariable( 3281 DContext, DeclName, LinkageName, Unit, LineNo, getOrCreateType(T, Unit), 3282 Var->hasInternalLinkage(), Var, 3283 getOrCreateStaticDataMemberDeclarationOrNull(D)); 3284 } 3285 DeclCache[D->getCanonicalDecl()].reset(static_cast<llvm::Metadata *>(GV)); 3286 } 3287 3288 void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD, 3289 llvm::Constant *Init) { 3290 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo); 3291 // Create the descriptor for the variable. 3292 llvm::DIFile *Unit = getOrCreateFile(VD->getLocation()); 3293 StringRef Name = VD->getName(); 3294 llvm::DIType *Ty = getOrCreateType(VD->getType(), Unit); 3295 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(VD)) { 3296 const EnumDecl *ED = cast<EnumDecl>(ECD->getDeclContext()); 3297 assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?"); 3298 Ty = getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit); 3299 } 3300 // Do not use global variables for enums. 3301 // 3302 // FIXME: why not? 3303 if (Ty->getTag() == llvm::dwarf::DW_TAG_enumeration_type) 3304 return; 3305 // Do not emit separate definitions for function local const/statics. 3306 if (isa<FunctionDecl>(VD->getDeclContext())) 3307 return; 3308 VD = cast<ValueDecl>(VD->getCanonicalDecl()); 3309 auto *VarD = cast<VarDecl>(VD); 3310 if (VarD->isStaticDataMember()) { 3311 auto *RD = cast<RecordDecl>(VarD->getDeclContext()); 3312 getDeclContextDescriptor(VarD); 3313 // Ensure that the type is retained even though it's otherwise unreferenced. 3314 RetainedTypes.push_back( 3315 CGM.getContext().getRecordType(RD).getAsOpaquePtr()); 3316 return; 3317 } 3318 3319 llvm::DIScope *DContext = getDeclContextDescriptor(VD); 3320 3321 auto &GV = DeclCache[VD]; 3322 if (GV) 3323 return; 3324 GV.reset(DBuilder.createGlobalVariable( 3325 DContext, Name, StringRef(), Unit, getLineNumber(VD->getLocation()), Ty, 3326 true, Init, getOrCreateStaticDataMemberDeclarationOrNull(VarD))); 3327 } 3328 3329 llvm::DIScope *CGDebugInfo::getCurrentContextDescriptor(const Decl *D) { 3330 if (!LexicalBlockStack.empty()) 3331 return LexicalBlockStack.back(); 3332 llvm::DIScope *Mod = getParentModuleOrNull(D); 3333 return getContextDescriptor(D, Mod ? Mod : TheCU); 3334 } 3335 3336 void CGDebugInfo::EmitUsingDirective(const UsingDirectiveDecl &UD) { 3337 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo) 3338 return; 3339 DBuilder.createImportedModule( 3340 getCurrentContextDescriptor(cast<Decl>(UD.getDeclContext())), 3341 getOrCreateNameSpace(UD.getNominatedNamespace()), 3342 getLineNumber(UD.getLocation())); 3343 } 3344 3345 void CGDebugInfo::EmitUsingDecl(const UsingDecl &UD) { 3346 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo) 3347 return; 3348 assert(UD.shadow_size() && 3349 "We shouldn't be codegening an invalid UsingDecl containing no decls"); 3350 // Emitting one decl is sufficient - debuggers can detect that this is an 3351 // overloaded name & provide lookup for all the overloads. 3352 const UsingShadowDecl &USD = **UD.shadow_begin(); 3353 if (llvm::DINode *Target = 3354 getDeclarationOrDefinition(USD.getUnderlyingDecl())) 3355 DBuilder.createImportedDeclaration( 3356 getCurrentContextDescriptor(cast<Decl>(USD.getDeclContext())), Target, 3357 getLineNumber(USD.getLocation())); 3358 } 3359 3360 void CGDebugInfo::EmitImportDecl(const ImportDecl &ID) { 3361 auto *Reader = CGM.getContext().getExternalSource(); 3362 auto Info = Reader->getSourceDescriptor(*ID.getImportedModule()); 3363 DBuilder.createImportedDeclaration( 3364 getCurrentContextDescriptor(cast<Decl>(ID.getDeclContext())), 3365 getOrCreateModuleRef(Info), 3366 getLineNumber(ID.getLocation())); 3367 } 3368 3369 llvm::DIImportedEntity * 3370 CGDebugInfo::EmitNamespaceAlias(const NamespaceAliasDecl &NA) { 3371 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo) 3372 return nullptr; 3373 auto &VH = NamespaceAliasCache[&NA]; 3374 if (VH) 3375 return cast<llvm::DIImportedEntity>(VH); 3376 llvm::DIImportedEntity *R; 3377 if (const NamespaceAliasDecl *Underlying = 3378 dyn_cast<NamespaceAliasDecl>(NA.getAliasedNamespace())) 3379 // This could cache & dedup here rather than relying on metadata deduping. 3380 R = DBuilder.createImportedDeclaration( 3381 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())), 3382 EmitNamespaceAlias(*Underlying), getLineNumber(NA.getLocation()), 3383 NA.getName()); 3384 else 3385 R = DBuilder.createImportedDeclaration( 3386 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())), 3387 getOrCreateNameSpace(cast<NamespaceDecl>(NA.getAliasedNamespace())), 3388 getLineNumber(NA.getLocation()), NA.getName()); 3389 VH.reset(R); 3390 return R; 3391 } 3392 3393 llvm::DINamespace * 3394 CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl) { 3395 NSDecl = NSDecl->getCanonicalDecl(); 3396 auto I = NameSpaceCache.find(NSDecl); 3397 if (I != NameSpaceCache.end()) 3398 return cast<llvm::DINamespace>(I->second); 3399 3400 unsigned LineNo = getLineNumber(NSDecl->getLocation()); 3401 llvm::DIFile *FileD = getOrCreateFile(NSDecl->getLocation()); 3402 llvm::DIScope *Context = getDeclContextDescriptor(NSDecl); 3403 llvm::DINamespace *NS = 3404 DBuilder.createNameSpace(Context, NSDecl->getName(), FileD, LineNo); 3405 NameSpaceCache[NSDecl].reset(NS); 3406 return NS; 3407 } 3408 3409 void CGDebugInfo::finalize() { 3410 // Creating types might create further types - invalidating the current 3411 // element and the size(), so don't cache/reference them. 3412 for (size_t i = 0; i != ObjCInterfaceCache.size(); ++i) { 3413 ObjCInterfaceCacheEntry E = ObjCInterfaceCache[i]; 3414 llvm::DIType *Ty = E.Type->getDecl()->getDefinition() 3415 ? CreateTypeDefinition(E.Type, E.Unit) 3416 : E.Decl; 3417 DBuilder.replaceTemporary(llvm::TempDIType(E.Decl), Ty); 3418 } 3419 3420 for (auto p : ReplaceMap) { 3421 assert(p.second); 3422 auto *Ty = cast<llvm::DIType>(p.second); 3423 assert(Ty->isForwardDecl()); 3424 3425 auto it = TypeCache.find(p.first); 3426 assert(it != TypeCache.end()); 3427 assert(it->second); 3428 3429 DBuilder.replaceTemporary(llvm::TempDIType(Ty), 3430 cast<llvm::DIType>(it->second)); 3431 } 3432 3433 for (const auto &p : FwdDeclReplaceMap) { 3434 assert(p.second); 3435 llvm::TempMDNode FwdDecl(cast<llvm::MDNode>(p.second)); 3436 llvm::Metadata *Repl; 3437 3438 auto it = DeclCache.find(p.first); 3439 // If there has been no definition for the declaration, call RAUW 3440 // with ourselves, that will destroy the temporary MDNode and 3441 // replace it with a standard one, avoiding leaking memory. 3442 if (it == DeclCache.end()) 3443 Repl = p.second; 3444 else 3445 Repl = it->second; 3446 3447 DBuilder.replaceTemporary(std::move(FwdDecl), cast<llvm::MDNode>(Repl)); 3448 } 3449 3450 // We keep our own list of retained types, because we need to look 3451 // up the final type in the type cache. 3452 for (auto &RT : RetainedTypes) 3453 if (auto MD = TypeCache[RT]) 3454 DBuilder.retainType(cast<llvm::DIType>(MD)); 3455 3456 DBuilder.finalize(); 3457 } 3458 3459 void CGDebugInfo::EmitExplicitCastType(QualType Ty) { 3460 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo) 3461 return; 3462 3463 if (auto *DieTy = getOrCreateType(Ty, getOrCreateMainFile())) 3464 // Don't ignore in case of explicit cast where it is referenced indirectly. 3465 DBuilder.retainType(DieTy); 3466 } 3467